import '../models/machine_state.dart'; class MeCoffeeProtocol { /// Two-byte settings above this raw value are replaced by defaults when the /// controller restores them at startup (V9/V10 firmware). static const maxPersistentRaw = 32000; /// Highest wind-down percentage whose raw value stays within /// [maxPersistentRaw]. static const maxPidLimitPercent = 48; /// The firmware compares against the low 16 bits of `shtmx * 1000`, so /// 66 s and above wrap to a sub-second limit. static const maxShotSeconds = 65; static MachineState parse( String msg, MachineState currentState, { bool isLegacyV4 = false, }) { msg = msg.trim(); if (msg.isEmpty) return currentState; final parts = msg.split(RegExp(r'\s+')); if (parts.last == 'OK') parts.removeLast(); if (parts.isEmpty) return currentState; final command = parts[0]; // Temperature update: tmp if (command == 'tmp' || command == 'T') { if (parts.length < 4) return currentState; try { final timestamp = double.parse(parts[1]); double setpoint = double.parse(parts[2]) / 100.0; double boiler = double.parse(parts[3]) / 100.0; if (!timestamp.isFinite || !setpoint.isFinite || !boiler.isFinite) { return currentState; } // sensor2: validate range (same guard as Android: 0.05 – 200 °C raw) double? sensor2; if (parts.length >= 5) { final raw = double.parse(parts[4]); if (!raw.isFinite) return currentState; if (raw > 5.0 && raw < 20000) sensor2 = raw / 100.0; } // While steam is active the firmware reports tmpstm as the setpoint, // including phases where the boiler is above it and no marker is sent. var isSteaming = currentState.isSteaming; final steamRaw = (currentState.steamTemperature * 100).round(); final brewRaw = (currentState.brewTemperature * 100).round(); if (steamRaw != brewRaw) { final setpointRaw = double.parse(parts[2]).round(); if (setpointRaw == steamRaw) isSteaming = true; if (setpointRaw == brewRaw) isSteaming = false; } return currentState.copyWith( targetTemperature: setpoint, temperature: boiler, sensor2Temperature: sensor2 ?? currentState.sensor2Temperature, isSteaming: isSteaming, ); } catch (_) {} } // PID Power update: pid

if (command == 'pid') { if (parts.length < 4) return currentState; try { int p = int.parse(parts[1]); int i = int.parse(parts[2]); int d = int.parse(parts[3]); int f = parts.length >= 5 ? int.parse(parts[4]) : 0; // V9/V10 steam markers. While the steam input is active no PID frames // are sent and the boiler is switched fully on below tmpstm and off at // or above it: `pid 65535 0 0 0` (steam start, heater on), // `pid 65536 0 0 0` (heater on again) and `pid 0 0 0 0` (heater off; // also sent on steam release and power-off). Steam itself is tracked // from the `tmp` setpoint and from the next regular PID frame. if (parts.length == 5 && i == 0 && d == 0 && f == 0) { if (p == 65535 || p == 65536) { return currentState.copyWith( isSteaming: true, isHeating: true, heatingPower: 1.0, ); } if (p == 0 && currentState.isSteaming) { return currentState.copyWith(isHeating: false, heatingPower: 0); } } double totalPower = (p + i + d + f) / 65535.0; return currentState.copyWith( heatingPower: totalPower.clamp(0.0, 1.0), isHeating: totalPower > 0, isSteaming: false, ); } catch (_) {} } // Shot timer update: sht if (command == 'sht') { if (parts.length < 3) return currentState; try { int shottimeMs = int.parse(parts[2]); if (shottimeMs == 0) { return currentState.copyWith(isBrewing: true, shotTimer: 0); } else if (!currentState.isBrewing) { // V9/V10 send a second end line when the input is released after a // `shtmx` cutoff, and can send a stray `sht ` before // the first start line. Keep the duration of the shot that ended. return currentState.copyWith(); } else { return currentState.copyWith( isBrewing: false, shotTimer: (shottimeMs / 1000).round(), ); } } catch (_) {} } // The bundled V4 image identifies itself as "meCoffee V4 ". final identityStart = command == 'uname' ? 1 : command == 'cmd' && parts.length >= 2 && parts[1] == 'uname' ? 2 : null; if (identityStart != null) { if (parts.length <= identityStart) return currentState; final version = parts.sublist(identityStart).join(' '); final isV4 = RegExp( r'(^|[^a-z0-9])v4($|[^a-z0-9])', caseSensitive: false, ).hasMatch(version); return currentState.copyWith( isLegacyV4Firmware: isV4, firmwareVersion: version, ); } // Command responses: cmd if (command == 'cmd') { if (parts.length >= 4 && (parts[1] == 'set' || parts[1] == 'get')) { // Firmware echoes accepted writes as `cmd set s_ OK`. final key = parts[1] == 'set' && parts[2].startsWith('s_') ? parts[2].substring(2) : parts[2]; final valStr = parts[3]; return _updateFromKeyVal( currentState, key, valStr, isLegacyV4: isLegacyV4 || currentState.isLegacyV4Firmware, ); } } // Legacy compatibility: get if (command == 'get' && parts.length >= 3) { return _updateFromKeyVal( currentState, parts[1], parts[2], isLegacyV4: isLegacyV4 || currentState.isLegacyV4Firmware, ); } return currentState; } static MachineState _updateFromKeyVal( MachineState state, String key, String valStr, { required bool isLegacyV4, }) { try { final val = double.parse(valStr); if (!val.isFinite) return state; // V4 legacy firmware uses raw seconds (scale=1) for pistrt/piprd; // newer firmware uses milliseconds (scale=1000). final preinfusionScale = isLegacyV4 ? 1.0 : 1000.0; switch (key) { case 'tmpsp': return state.copyWith( brewTemperature: val / 100.0, targetTemperature: val / 100.0, ); case 'tmpstm': return state.copyWith(steamTemperature: val / 100.0); case 'pd1p': return state.copyWith(pidP: val); case 'pd1i': return state.copyWith(pidI: isLegacyV4 ? val : val / 100.0); case 'pd1d': return state.copyWith(pidD: val); case 'pd1imm': case 'pd1imn': if (isLegacyV4) return state; return state.copyWith(pidIWindDownMin: (val / 655.36).clamp(0, 100)); case 'pd1imx': return state.copyWith( pidIWindDownMax: isLegacyV4 ? val : (val / 655.36).clamp(0, 100), ); case 'pd1sz': return state.copyWith(pidPollingInterval: val.toInt()); case 'pistrt': return state.copyWith(preinfusionTime: val / preinfusionScale); case 'piprd': return state.copyWith(preinfusionPauseTime: val / preinfusionScale); case 'pinbl': return state.copyWith(preinfusionEnabled: val != 0); case 'pivlv': return state.copyWith(valveClosedWhilePaused: val != 0); case 'tmppap': return state.copyWith(proActivePercentage: val.toInt()); case 'tmrosd': return state.copyWith(autoShutoffMinutes: val.toInt()); case 'o0': return state.copyWith(output0: val.toInt()); case 'o1': return state.copyWith(output1: val.toInt()); case 'o2': return state.copyWith(output2: val.toInt()); case 'tmrpwr': return state.copyWith(installedAsTimer: val != 0); case 'pwrflp': return state.copyWith(powerButtonFlipsBack: val != 0); case 'tmrwnbl': return state.copyWith(wakeupEnabled: val != 0); case 'tmron': return state.copyWith(wakeupTime: _secondsToTimeString(val.toInt())); case 'tmrsnbl': return state.copyWith(shutdownEnabled: val != 0); case 'tmroff': return state.copyWith( shutdownTime: _secondsToTimeString(val.toInt()), ); case 'pp1': return state.copyWith(pressureStart: val.toInt()); case 'pp2': return state.copyWith(pressureEnd: val.toInt()); case 'ppt': return state.copyWith(pressurePeriod: val.toInt()); case 'cntgrndr': case 'grndr_cnt': return state.copyWith(grinderCounter: val.toInt()); case 'shtmx': return state.copyWith(maxShotTime: val.toInt()); case 'tmpcntns': return state.copyWith(continuousMode: val != 0); } } catch (_) {} return state; } static String encodeSet( String key, dynamic value, { bool isLegacyV4 = false, }) { String valStr; if (value is bool) { valStr = value ? '1' : '0'; } else if (value is String && (key == 'tmron' || key == 'tmroff')) { valStr = _timeStringToSeconds(value).toString(); } else if (value is double) { if (key == 'tmpsp' || key == 'tmpstm') { valStr = (value * 100).round().toString(); } else if (key == 'pistrt' || key == 'piprd') { valStr = (value * (isLegacyV4 ? 1 : 1000)).round().toString(); } else if (key == 'pd1i') { valStr = (value * (isLegacyV4 ? 1 : 100)).round().toString(); } else if (key == 'pd1imm' || key == 'pd1imn' || key == 'pd1imx') { valStr = isLegacyV4 ? value.round().toString() : (value * 655.36).round().clamp(0, maxPersistentRaw).toString(); } else { valStr = value.round().toString(); } } else { valStr = value.toString(); } return "cmd set $key $valStr\n"; } static List encodeTemperature(double temp) { return _toBytes(encodeSet('tmpsp', temp)); } static List encodeSteamTemperature(double temp) { return _toBytes(encodeSet('tmpstm', temp)); } static List encodePreinfusion( bool enabled, double time, double pause, bool closeValve, { bool isLegacyV4 = false, }) { // V4 firmware uses raw seconds (scale=1); newer firmware uses milliseconds (scale=1000). final scale = isLegacyV4 ? 1 : 1000; return _toBytes( encodeSet('pinbl', enabled ? 1 : 0) + encodeSet('pistrt', (time * scale).round()) + encodeSet('piprd', (pause * scale).round()) + encodeSet('pivlv', closeValve ? 1 : 0), ); } static List encodeHardware( int o0, int o1, int o2, bool timer, bool flips, ) { return _toBytes( encodeSet('o0', o0) + encodeSet('o1', o1) + encodeSet('o2', o2) + encodeSet('tmrpwr', timer ? 1 : 0) + encodeSet('pwrflp', flips ? 1 : 0), ); } static List encodePID( double p, double i, double d, { bool isLegacyV4 = false, }) { return _toBytes( encodeSet('pd1p', p) + encodeSet('pd1i', (i * (isLegacyV4 ? 1 : 100)).round()) + encodeSet('pd1d', d), ); } static List encodePIDLimits( double min, double max, int interval, { bool isLegacyV4 = false, }) { return _toBytes( // V10's key table uses pd1imn; Android's modern XML also has pd1imm. // V4 exposes only the maximum, in direct units rather than percent. (isLegacyV4 ? '' : encodeSet('pd1imn', min)) + encodeSet('pd1imx', isLegacyV4 ? max.round() : max) + encodeSet('pd1sz', interval), ); } static List encodePressure(int start, int end, int period) { return _toBytes( encodeSet('pp1', start) + encodeSet('pp2', end) + encodeSet('ppt', period), ); } static List encodeProActive(int percentage) { return _toBytes(encodeSet('tmppap', percentage)); } static List encodeAutoShutoff(int minutes) { return _toBytes(encodeSet('tmrosd', minutes)); } static List encodeMaxShotTime(int seconds) { return _toBytes(encodeSet('shtmx', seconds)); } static List encodeContinuousMode(bool enabled) { return _toBytes(encodeSet('tmpcntns', enabled ? 1 : 0)); } static List encodeSchedule( bool wEnabled, String wTime, bool sEnabled, String sTime, ) { return _toBytes( encodeSet('tmrwnbl', wEnabled ? 1 : 0) + encodeSet('tmron', _timeStringToSeconds(wTime)) + encodeSet('tmrsnbl', sEnabled ? 1 : 0) + encodeSet('tmroff', _timeStringToSeconds(sTime)), ); } static int _timeStringToSeconds(String time) { final parts = time.split(':'); if (parts.length != 2) return 0; final hours = int.tryParse(parts[0]) ?? 0; final minutes = int.tryParse(parts[1]) ?? 0; final clampedHours = hours.clamp(0, 23); final clampedMinutes = minutes.clamp(0, 59); return clampedHours * 3600 + clampedMinutes * 60; } static String _secondsToTimeString(int totalSeconds) { final normalized = ((totalSeconds % 86400) + 86400) % 86400; final hours = (normalized ~/ 3600).toString().padLeft(2, '0'); final minutes = ((normalized % 3600) ~/ 60).toString().padLeft(2, '0'); return '$hours:$minutes'; } static List _toBytes(String s) => s.codeUnits; }