me_coffee_protocol.dart 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. import '../models/machine_state.dart';
  2. class MeCoffeeProtocol {
  3. /// Two-byte settings above this raw value are replaced by defaults when the
  4. /// controller restores them at startup (V9/V10 firmware).
  5. static const maxPersistentRaw = 32000;
  6. /// Highest wind-down percentage whose raw value stays within
  7. /// [maxPersistentRaw].
  8. static const maxPidLimitPercent = 48;
  9. /// The firmware compares against the low 16 bits of `shtmx * 1000`, so
  10. /// 66 s and above wrap to a sub-second limit.
  11. static const maxShotSeconds = 65;
  12. static MachineState parse(
  13. String msg,
  14. MachineState currentState, {
  15. bool isLegacyV4 = false,
  16. }) {
  17. msg = msg.trim();
  18. if (msg.isEmpty) return currentState;
  19. final parts = msg.split(RegExp(r'\s+'));
  20. if (parts.last == 'OK') parts.removeLast();
  21. if (parts.isEmpty) return currentState;
  22. final command = parts[0];
  23. // Temperature update: tmp <timestamp> <setpoint> <boiler> <sensor2>
  24. if (command == 'tmp' || command == 'T') {
  25. if (parts.length < 4) return currentState;
  26. try {
  27. final timestamp = double.parse(parts[1]);
  28. double setpoint = double.parse(parts[2]) / 100.0;
  29. double boiler = double.parse(parts[3]) / 100.0;
  30. if (!timestamp.isFinite || !setpoint.isFinite || !boiler.isFinite) {
  31. return currentState;
  32. }
  33. // sensor2: validate range (same guard as Android: 0.05 – 200 °C raw)
  34. double? sensor2;
  35. if (parts.length >= 5) {
  36. final raw = double.parse(parts[4]);
  37. if (!raw.isFinite) return currentState;
  38. if (raw > 5.0 && raw < 20000) sensor2 = raw / 100.0;
  39. }
  40. // While steam is active the firmware reports tmpstm as the setpoint,
  41. // including phases where the boiler is above it and no marker is sent.
  42. var isSteaming = currentState.isSteaming;
  43. final steamRaw = (currentState.steamTemperature * 100).round();
  44. final brewRaw = (currentState.brewTemperature * 100).round();
  45. if (steamRaw != brewRaw) {
  46. final setpointRaw = double.parse(parts[2]).round();
  47. if (setpointRaw == steamRaw) isSteaming = true;
  48. if (setpointRaw == brewRaw) isSteaming = false;
  49. }
  50. return currentState.copyWith(
  51. targetTemperature: setpoint,
  52. temperature: boiler,
  53. sensor2Temperature: sensor2 ?? currentState.sensor2Temperature,
  54. isSteaming: isSteaming,
  55. );
  56. } catch (_) {}
  57. }
  58. // PID Power update: pid <p> <i> <d> <f>
  59. if (command == 'pid') {
  60. if (parts.length < 4) return currentState;
  61. try {
  62. int p = int.parse(parts[1]);
  63. int i = int.parse(parts[2]);
  64. int d = int.parse(parts[3]);
  65. int f = parts.length >= 5 ? int.parse(parts[4]) : 0;
  66. // V9/V10 steam markers. While the steam input is active no PID frames
  67. // are sent and the boiler is switched fully on below tmpstm and off at
  68. // or above it: `pid 65535 0 0 0` (steam start, heater on),
  69. // `pid 65536 0 0 0` (heater on again) and `pid 0 0 0 0` (heater off;
  70. // also sent on steam release and power-off). Steam itself is tracked
  71. // from the `tmp` setpoint and from the next regular PID frame.
  72. if (parts.length == 5 && i == 0 && d == 0 && f == 0) {
  73. if (p == 65535 || p == 65536) {
  74. return currentState.copyWith(
  75. isSteaming: true,
  76. isHeating: true,
  77. heatingPower: 1.0,
  78. );
  79. }
  80. if (p == 0 && currentState.isSteaming) {
  81. return currentState.copyWith(isHeating: false, heatingPower: 0);
  82. }
  83. }
  84. double totalPower = (p + i + d + f) / 65535.0;
  85. return currentState.copyWith(
  86. heatingPower: totalPower.clamp(0.0, 1.0),
  87. isHeating: totalPower > 0,
  88. isSteaming: false,
  89. );
  90. } catch (_) {}
  91. }
  92. // Shot timer update: sht <val1> <time_ms>
  93. if (command == 'sht') {
  94. if (parts.length < 3) return currentState;
  95. try {
  96. int shottimeMs = int.parse(parts[2]);
  97. if (shottimeMs == 0) {
  98. return currentState.copyWith(isBrewing: true, shotTimer: 0);
  99. } else if (!currentState.isBrewing) {
  100. // V9/V10 send a second end line when the input is released after a
  101. // `shtmx` cutoff, and can send a stray `sht <s> <uptime-ms>` before
  102. // the first start line. Keep the duration of the shot that ended.
  103. return currentState.copyWith();
  104. } else {
  105. return currentState.copyWith(
  106. isBrewing: false,
  107. shotTimer: (shottimeMs / 1000).round(),
  108. );
  109. }
  110. } catch (_) {}
  111. }
  112. // The bundled V4 image identifies itself as "meCoffee V4 ".
  113. final identityStart = command == 'uname'
  114. ? 1
  115. : command == 'cmd' && parts.length >= 2 && parts[1] == 'uname'
  116. ? 2
  117. : null;
  118. if (identityStart != null) {
  119. if (parts.length <= identityStart) return currentState;
  120. final version = parts.sublist(identityStart).join(' ');
  121. final isV4 = RegExp(
  122. r'(^|[^a-z0-9])v4($|[^a-z0-9])',
  123. caseSensitive: false,
  124. ).hasMatch(version);
  125. return currentState.copyWith(
  126. isLegacyV4Firmware: isV4,
  127. firmwareVersion: version,
  128. );
  129. }
  130. // Command responses: cmd <set/get> <key> <value>
  131. if (command == 'cmd') {
  132. if (parts.length >= 4 && (parts[1] == 'set' || parts[1] == 'get')) {
  133. // Firmware echoes accepted writes as `cmd set s_<key> <value> OK`.
  134. final key = parts[1] == 'set' && parts[2].startsWith('s_')
  135. ? parts[2].substring(2)
  136. : parts[2];
  137. final valStr = parts[3];
  138. return _updateFromKeyVal(
  139. currentState,
  140. key,
  141. valStr,
  142. isLegacyV4: isLegacyV4 || currentState.isLegacyV4Firmware,
  143. );
  144. }
  145. }
  146. // Legacy compatibility: get <key> <value>
  147. if (command == 'get' && parts.length >= 3) {
  148. return _updateFromKeyVal(
  149. currentState,
  150. parts[1],
  151. parts[2],
  152. isLegacyV4: isLegacyV4 || currentState.isLegacyV4Firmware,
  153. );
  154. }
  155. return currentState;
  156. }
  157. static MachineState _updateFromKeyVal(
  158. MachineState state,
  159. String key,
  160. String valStr, {
  161. required bool isLegacyV4,
  162. }) {
  163. try {
  164. final val = double.parse(valStr);
  165. if (!val.isFinite) return state;
  166. // V4 legacy firmware uses raw seconds (scale=1) for pistrt/piprd;
  167. // newer firmware uses milliseconds (scale=1000).
  168. final preinfusionScale = isLegacyV4 ? 1.0 : 1000.0;
  169. switch (key) {
  170. case 'tmpsp':
  171. return state.copyWith(
  172. brewTemperature: val / 100.0,
  173. targetTemperature: val / 100.0,
  174. );
  175. case 'tmpstm':
  176. return state.copyWith(steamTemperature: val / 100.0);
  177. case 'pd1p':
  178. return state.copyWith(pidP: val);
  179. case 'pd1i':
  180. return state.copyWith(pidI: isLegacyV4 ? val : val / 100.0);
  181. case 'pd1d':
  182. return state.copyWith(pidD: val);
  183. case 'pd1imm':
  184. case 'pd1imn':
  185. if (isLegacyV4) return state;
  186. return state.copyWith(pidIWindDownMin: (val / 655.36).clamp(0, 100));
  187. case 'pd1imx':
  188. return state.copyWith(
  189. pidIWindDownMax: isLegacyV4 ? val : (val / 655.36).clamp(0, 100),
  190. );
  191. case 'pd1sz':
  192. return state.copyWith(pidPollingInterval: val.toInt());
  193. case 'pistrt':
  194. return state.copyWith(preinfusionTime: val / preinfusionScale);
  195. case 'piprd':
  196. return state.copyWith(preinfusionPauseTime: val / preinfusionScale);
  197. case 'pinbl':
  198. return state.copyWith(preinfusionEnabled: val != 0);
  199. case 'pivlv':
  200. return state.copyWith(valveClosedWhilePaused: val != 0);
  201. case 'tmppap':
  202. return state.copyWith(proActivePercentage: val.toInt());
  203. case 'tmrosd':
  204. return state.copyWith(autoShutoffMinutes: val.toInt());
  205. case 'tmrosdnbl':
  206. return state.copyWith(autoShutoffEnabled: val != 0);
  207. case 'o0':
  208. return state.copyWith(output0: val.toInt());
  209. case 'o1':
  210. return state.copyWith(output1: val.toInt());
  211. case 'o2':
  212. return state.copyWith(output2: val.toInt());
  213. case 'tmrpwr':
  214. return state.copyWith(installedAsTimer: val != 0);
  215. case 'pwrflp':
  216. return state.copyWith(powerButtonFlipsBack: val != 0);
  217. case 'tmrwnbl':
  218. return state.copyWith(wakeupEnabled: val != 0);
  219. case 'tmron':
  220. return state.copyWith(wakeupTime: _secondsToTimeString(val.toInt()));
  221. case 'tmrsnbl':
  222. return state.copyWith(shutdownEnabled: val != 0);
  223. case 'tmroff':
  224. return state.copyWith(
  225. shutdownTime: _secondsToTimeString(val.toInt()),
  226. );
  227. case 'pp1':
  228. return state.copyWith(pressureStart: val.toInt());
  229. case 'pp2':
  230. return state.copyWith(pressureEnd: val.toInt());
  231. case 'ppt':
  232. return state.copyWith(pressurePeriod: val.toInt());
  233. case 'cntgrndr':
  234. case 'grndr_cnt':
  235. return state.copyWith(grinderCounter: val.toInt());
  236. case 'shtmx':
  237. return state.copyWith(maxShotTime: val.toInt());
  238. case 'tmpcntns':
  239. return state.copyWith(continuousMode: val != 0);
  240. }
  241. } catch (_) {}
  242. return state;
  243. }
  244. static String encodeSet(
  245. String key,
  246. dynamic value, {
  247. bool isLegacyV4 = false,
  248. }) {
  249. String valStr;
  250. if (value is bool) {
  251. valStr = value ? '1' : '0';
  252. } else if (value is String && (key == 'tmron' || key == 'tmroff')) {
  253. valStr = _timeStringToSeconds(value).toString();
  254. } else if (value is double) {
  255. if (key == 'tmpsp' || key == 'tmpstm') {
  256. valStr = (value * 100).round().toString();
  257. } else if (key == 'pistrt' || key == 'piprd') {
  258. valStr = (value * (isLegacyV4 ? 1 : 1000)).round().toString();
  259. } else if (key == 'pd1i') {
  260. valStr = (value * (isLegacyV4 ? 1 : 100)).round().toString();
  261. } else if (key == 'pd1imm' || key == 'pd1imn' || key == 'pd1imx') {
  262. valStr = isLegacyV4
  263. ? value.round().toString()
  264. : (value * 655.36).round().clamp(0, maxPersistentRaw).toString();
  265. } else {
  266. valStr = value.round().toString();
  267. }
  268. } else {
  269. valStr = value.toString();
  270. }
  271. return "cmd set $key $valStr\n";
  272. }
  273. static List<int> encodeTemperature(double temp) {
  274. return _toBytes(encodeSet('tmpsp', temp));
  275. }
  276. static List<int> encodeSteamTemperature(double temp) {
  277. return _toBytes(encodeSet('tmpstm', temp));
  278. }
  279. static List<int> encodePreinfusion(
  280. bool enabled,
  281. double time,
  282. double pause,
  283. bool closeValve, {
  284. bool isLegacyV4 = false,
  285. }) {
  286. // V4 firmware uses raw seconds (scale=1); newer firmware uses milliseconds (scale=1000).
  287. final scale = isLegacyV4 ? 1 : 1000;
  288. return _toBytes(
  289. encodeSet('pinbl', enabled ? 1 : 0) +
  290. encodeSet('pistrt', (time * scale).round()) +
  291. encodeSet('piprd', (pause * scale).round()) +
  292. encodeSet('pivlv', closeValve ? 1 : 0),
  293. );
  294. }
  295. static List<int> encodeHardware(
  296. int o0,
  297. int o1,
  298. int o2,
  299. bool timer,
  300. bool flips,
  301. ) {
  302. return _toBytes(
  303. encodeSet('o0', o0) +
  304. encodeSet('o1', o1) +
  305. encodeSet('o2', o2) +
  306. encodeSet('tmrpwr', timer ? 1 : 0) +
  307. encodeSet('pwrflp', flips ? 1 : 0),
  308. );
  309. }
  310. static List<int> encodePID(
  311. double p,
  312. double i,
  313. double d, {
  314. bool isLegacyV4 = false,
  315. }) {
  316. return _toBytes(
  317. encodeSet('pd1p', p) +
  318. encodeSet('pd1i', (i * (isLegacyV4 ? 1 : 100)).round()) +
  319. encodeSet('pd1d', d),
  320. );
  321. }
  322. static List<int> encodePIDLimits(
  323. double min,
  324. double max,
  325. int interval, {
  326. bool isLegacyV4 = false,
  327. }) {
  328. return _toBytes(
  329. // V10's key table uses pd1imn; Android's modern XML also has pd1imm.
  330. // V4 exposes only the maximum, in direct units rather than percent.
  331. (isLegacyV4 ? '' : encodeSet('pd1imn', min)) +
  332. encodeSet('pd1imx', isLegacyV4 ? max.round() : max) +
  333. encodeSet('pd1sz', interval),
  334. );
  335. }
  336. static List<int> encodePressure(int start, int end, int period) {
  337. return _toBytes(
  338. encodeSet('pp1', start) +
  339. encodeSet('pp2', end) +
  340. encodeSet('ppt', period),
  341. );
  342. }
  343. static List<int> encodeProActive(int percentage) {
  344. return _toBytes(encodeSet('tmppap', percentage));
  345. }
  346. static List<int> encodeAutoShutoff(int minutes) {
  347. return _toBytes(encodeSet('tmrosd', minutes));
  348. }
  349. static List<int> encodeMaxShotTime(int seconds) {
  350. return _toBytes(encodeSet('shtmx', seconds));
  351. }
  352. static List<int> encodeContinuousMode(bool enabled) {
  353. return _toBytes(encodeSet('tmpcntns', enabled ? 1 : 0));
  354. }
  355. static List<int> encodeSchedule(
  356. bool wEnabled,
  357. String wTime,
  358. bool sEnabled,
  359. String sTime,
  360. ) {
  361. return _toBytes(
  362. encodeSet('tmrwnbl', wEnabled ? 1 : 0) +
  363. encodeSet('tmron', _timeStringToSeconds(wTime)) +
  364. encodeSet('tmrsnbl', sEnabled ? 1 : 0) +
  365. encodeSet('tmroff', _timeStringToSeconds(sTime)),
  366. );
  367. }
  368. static int _timeStringToSeconds(String time) {
  369. final parts = time.split(':');
  370. if (parts.length != 2) return 0;
  371. final hours = int.tryParse(parts[0]) ?? 0;
  372. final minutes = int.tryParse(parts[1]) ?? 0;
  373. final clampedHours = hours.clamp(0, 23);
  374. final clampedMinutes = minutes.clamp(0, 59);
  375. return clampedHours * 3600 + clampedMinutes * 60;
  376. }
  377. static String _secondsToTimeString(int totalSeconds) {
  378. final normalized = ((totalSeconds % 86400) + 86400) % 86400;
  379. final hours = (normalized ~/ 3600).toString().padLeft(2, '0');
  380. final minutes = ((normalized % 3600) ~/ 60).toString().padLeft(2, '0');
  381. return '$hours:$minutes';
  382. }
  383. static List<int> _toBytes(String s) => s.codeUnits;
  384. }