me_coffee_protocol.dart 11 KB

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