me_coffee_protocol.dart 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  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 'o0':
  206. return state.copyWith(output0: val.toInt());
  207. case 'o1':
  208. return state.copyWith(output1: val.toInt());
  209. case 'o2':
  210. return state.copyWith(output2: val.toInt());
  211. case 'tmrpwr':
  212. return state.copyWith(installedAsTimer: val != 0);
  213. case 'pwrflp':
  214. return state.copyWith(powerButtonFlipsBack: val != 0);
  215. case 'tmrwnbl':
  216. return state.copyWith(wakeupEnabled: val != 0);
  217. case 'tmron':
  218. return state.copyWith(wakeupTime: _secondsToTimeString(val.toInt()));
  219. case 'tmrsnbl':
  220. return state.copyWith(shutdownEnabled: val != 0);
  221. case 'tmroff':
  222. return state.copyWith(
  223. shutdownTime: _secondsToTimeString(val.toInt()),
  224. );
  225. case 'pp1':
  226. return state.copyWith(pressureStart: val.toInt());
  227. case 'pp2':
  228. return state.copyWith(pressureEnd: val.toInt());
  229. case 'ppt':
  230. return state.copyWith(pressurePeriod: val.toInt());
  231. case 'cntgrndr':
  232. case 'grndr_cnt':
  233. return state.copyWith(grinderCounter: val.toInt());
  234. case 'shtmx':
  235. return state.copyWith(maxShotTime: val.toInt());
  236. case 'tmpcntns':
  237. return state.copyWith(continuousMode: val != 0);
  238. }
  239. } catch (_) {}
  240. return state;
  241. }
  242. static String encodeSet(
  243. String key,
  244. dynamic value, {
  245. bool isLegacyV4 = false,
  246. }) {
  247. String valStr;
  248. if (value is bool) {
  249. valStr = value ? '1' : '0';
  250. } else if (value is String && (key == 'tmron' || key == 'tmroff')) {
  251. valStr = _timeStringToSeconds(value).toString();
  252. } else if (value is double) {
  253. if (key == 'tmpsp' || key == 'tmpstm') {
  254. valStr = (value * 100).round().toString();
  255. } else if (key == 'pistrt' || key == 'piprd') {
  256. valStr = (value * (isLegacyV4 ? 1 : 1000)).round().toString();
  257. } else if (key == 'pd1i') {
  258. valStr = (value * (isLegacyV4 ? 1 : 100)).round().toString();
  259. } else if (key == 'pd1imm' || key == 'pd1imn' || key == 'pd1imx') {
  260. valStr = isLegacyV4
  261. ? value.round().toString()
  262. : (value * 655.36).round().clamp(0, maxPersistentRaw).toString();
  263. } else {
  264. valStr = value.round().toString();
  265. }
  266. } else {
  267. valStr = value.toString();
  268. }
  269. return "cmd set $key $valStr\n";
  270. }
  271. static List<int> encodeTemperature(double temp) {
  272. return _toBytes(encodeSet('tmpsp', temp));
  273. }
  274. static List<int> encodeSteamTemperature(double temp) {
  275. return _toBytes(encodeSet('tmpstm', temp));
  276. }
  277. static List<int> encodePreinfusion(
  278. bool enabled,
  279. double time,
  280. double pause,
  281. bool closeValve, {
  282. bool isLegacyV4 = false,
  283. }) {
  284. // V4 firmware uses raw seconds (scale=1); newer firmware uses milliseconds (scale=1000).
  285. final scale = isLegacyV4 ? 1 : 1000;
  286. return _toBytes(
  287. encodeSet('pinbl', enabled ? 1 : 0) +
  288. encodeSet('pistrt', (time * scale).round()) +
  289. encodeSet('piprd', (pause * scale).round()) +
  290. encodeSet('pivlv', closeValve ? 1 : 0),
  291. );
  292. }
  293. static List<int> encodeHardware(
  294. int o0,
  295. int o1,
  296. int o2,
  297. bool timer,
  298. bool flips,
  299. ) {
  300. return _toBytes(
  301. encodeSet('o0', o0) +
  302. encodeSet('o1', o1) +
  303. encodeSet('o2', o2) +
  304. encodeSet('tmrpwr', timer ? 1 : 0) +
  305. encodeSet('pwrflp', flips ? 1 : 0),
  306. );
  307. }
  308. static List<int> encodePID(
  309. double p,
  310. double i,
  311. double d, {
  312. bool isLegacyV4 = false,
  313. }) {
  314. return _toBytes(
  315. encodeSet('pd1p', p) +
  316. encodeSet('pd1i', (i * (isLegacyV4 ? 1 : 100)).round()) +
  317. encodeSet('pd1d', d),
  318. );
  319. }
  320. static List<int> encodePIDLimits(
  321. double min,
  322. double max,
  323. int interval, {
  324. bool isLegacyV4 = false,
  325. }) {
  326. return _toBytes(
  327. // V10's key table uses pd1imn; Android's modern XML also has pd1imm.
  328. // V4 exposes only the maximum, in direct units rather than percent.
  329. (isLegacyV4 ? '' : encodeSet('pd1imn', min)) +
  330. encodeSet('pd1imx', isLegacyV4 ? max.round() : max) +
  331. encodeSet('pd1sz', interval),
  332. );
  333. }
  334. static List<int> encodePressure(int start, int end, int period) {
  335. return _toBytes(
  336. encodeSet('pp1', start) +
  337. encodeSet('pp2', end) +
  338. encodeSet('ppt', period),
  339. );
  340. }
  341. static List<int> encodeProActive(int percentage) {
  342. return _toBytes(encodeSet('tmppap', percentage));
  343. }
  344. static List<int> encodeAutoShutoff(int minutes) {
  345. return _toBytes(encodeSet('tmrosd', minutes));
  346. }
  347. static List<int> encodeMaxShotTime(int seconds) {
  348. return _toBytes(encodeSet('shtmx', seconds));
  349. }
  350. static List<int> encodeContinuousMode(bool enabled) {
  351. return _toBytes(encodeSet('tmpcntns', enabled ? 1 : 0));
  352. }
  353. static List<int> encodeSchedule(
  354. bool wEnabled,
  355. String wTime,
  356. bool sEnabled,
  357. String sTime,
  358. ) {
  359. return _toBytes(
  360. encodeSet('tmrwnbl', wEnabled ? 1 : 0) +
  361. encodeSet('tmron', _timeStringToSeconds(wTime)) +
  362. encodeSet('tmrsnbl', sEnabled ? 1 : 0) +
  363. encodeSet('tmroff', _timeStringToSeconds(sTime)),
  364. );
  365. }
  366. static int _timeStringToSeconds(String time) {
  367. final parts = time.split(':');
  368. if (parts.length != 2) return 0;
  369. final hours = int.tryParse(parts[0]) ?? 0;
  370. final minutes = int.tryParse(parts[1]) ?? 0;
  371. final clampedHours = hours.clamp(0, 23);
  372. final clampedMinutes = minutes.clamp(0, 59);
  373. return clampedHours * 3600 + clampedMinutes * 60;
  374. }
  375. static String _secondsToTimeString(int totalSeconds) {
  376. final normalized = ((totalSeconds % 86400) + 86400) % 86400;
  377. final hours = (normalized ~/ 3600).toString().padLeft(2, '0');
  378. final minutes = ((normalized % 3600) ~/ 60).toString().padLeft(2, '0');
  379. return '$hours:$minutes';
  380. }
  381. static List<int> _toBytes(String s) => s.codeUnits;
  382. }