me_coffee_protocol.dart 13 KB

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