import '../models/machine_state.dart'; class MeCoffeeProtocol { 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; } return currentState.copyWith( targetTemperature: setpoint, temperature: boiler, sensor2Temperature: sensor2 ?? currentState.sensor2Temperature, ); } 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; double totalPower = (p + i + d + f) / 65535.0; return currentState.copyWith( heatingPower: totalPower.clamp(0.0, 1.0), isHeating: totalPower > 0, ); } 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 { 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')) { final key = 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 'tmpoff': return state.copyWith(temperatureOffset: val / 100.0); 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 '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' || key == 'tmpoff') { 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 = (value * (isLegacyV4 ? 1 : 655.36)).round().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 encodeOffset(double offset) { return _toBytes(encodeSet('tmpoff', offset)); } 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; }