me_coffee_protocol.dart 11 KB

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