| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379 |
- 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 <timestamp> <setpoint> <boiler> <sensor2>
- 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 <p> <i> <d> <f>
- 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 <val1> <time_ms>
- 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 <set/get> <key> <value>
- if (command == 'cmd') {
- if (parts.length >= 4 && (parts[1] == 'set' || parts[1] == 'get')) {
- // Firmware echoes accepted writes as `cmd set s_<key> <value> 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 <key> <value>
- 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<int> encodeTemperature(double temp) {
- return _toBytes(encodeSet('tmpsp', temp));
- }
- static List<int> encodeSteamTemperature(double temp) {
- return _toBytes(encodeSet('tmpstm', temp));
- }
- static List<int> 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<int> 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<int> 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<int> 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<int> encodePressure(int start, int end, int period) {
- return _toBytes(
- encodeSet('pp1', start) +
- encodeSet('pp2', end) +
- encodeSet('ppt', period),
- );
- }
- static List<int> encodeProActive(int percentage) {
- return _toBytes(encodeSet('tmppap', percentage));
- }
- static List<int> encodeAutoShutoff(int minutes) {
- return _toBytes(encodeSet('tmrosd', minutes));
- }
- static List<int> encodeMaxShotTime(int seconds) {
- return _toBytes(encodeSet('shtmx', seconds));
- }
- static List<int> encodeContinuousMode(bool enabled) {
- return _toBytes(encodeSet('tmpcntns', enabled ? 1 : 0));
- }
- static List<int> 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<int> _toBytes(String s) => s.codeUnits;
- }
|