me_coffee_protocol.dart 12 KB

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