bluetooth_service.dart 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641
  1. import 'dart:async';
  2. import 'package:flutter/foundation.dart';
  3. import 'package:flutter_blue_plus/flutter_blue_plus.dart';
  4. import 'package:flutter_riverpod/flutter_riverpod.dart';
  5. import 'package:flutter/services.dart';
  6. import 'package:shared_preferences/shared_preferences.dart';
  7. import '../models/diagnostic_entry.dart';
  8. import '../models/machine_state.dart';
  9. import '../models/temperature_sample.dart';
  10. import 'classic_bluetooth_transport.dart';
  11. import 'firmware_updater.dart';
  12. import 'me_coffee_protocol.dart';
  13. final bluetoothServiceProvider =
  14. StateNotifierProvider<MeCoffeeService, MachineState>((ref) {
  15. return MeCoffeeService();
  16. });
  17. class MeCoffeeService extends StateNotifier<MachineState> {
  18. static const String _meCoffeeServiceUuidPrefix = '0000ffe0';
  19. static const String _meCoffeeCharacteristicUuidPrefix = '0000ffe1';
  20. MeCoffeeService({
  21. ClassicBluetoothTransport? classicTransport,
  22. Future<void> Function(Duration)? firmwareDelay,
  23. this.savePreference,
  24. this.freshnessTimeout = const Duration(seconds: 3),
  25. this.settingsReplyTimeout = const Duration(seconds: 3),
  26. this.clockSyncInterval = const Duration(hours: 1),
  27. }) : _classicTransport = classicTransport ?? ClassicBluetoothTransport(),
  28. _firmwareDelay = firmwareDelay ?? Future<void>.delayed,
  29. super(MachineState()) {
  30. _settingsLoaded = _loadSettings();
  31. }
  32. final Duration freshnessTimeout;
  33. /// How long a `cmd set` may wait for its `cmd set s_<key> …` confirmation.
  34. final Duration settingsReplyTimeout;
  35. /// Periodic `cmd clock set` while connected (drift, DST, controller resets).
  36. final Duration clockSyncInterval;
  37. final ClassicBluetoothTransport _classicTransport;
  38. final Future<void> Function(Duration) _firmwareDelay;
  39. final Future<bool> Function(String, Object)? savePreference;
  40. StreamSubscription<List<int>>? _classicDataSubscription;
  41. StreamSubscription<ClassicBluetoothEvent>? _classicEventSubscription;
  42. ClassicBluetoothDevice? _classicDevice;
  43. bool _classicConnected = false;
  44. Timer? _freshnessTimer;
  45. StreamController<List<int>>? _firmwareBytes;
  46. bool _firmwareMode = false;
  47. bool _settingsLocked = false;
  48. // True after a heater-off frame (`pid 0 0 0 0`) on live telemetry and until
  49. // the next non-zero PID frame: the controller is switched off or asleep.
  50. bool _heaterOffConfirmed = false;
  51. ({String key, Completer<String?> reply})? _pendingSetEcho;
  52. Timer? _clockTimer;
  53. bool _reinitializing = false;
  54. final _reportedSettings = <String>{};
  55. final _pendingFirmwareSettings = <String, String>{};
  56. static const _firmwareScaledKeys = {
  57. 'pd1i',
  58. 'pd1imn',
  59. 'pd1imm',
  60. 'pd1imx',
  61. 'pistrt',
  62. 'piprd',
  63. };
  64. static const int historyLimit = 5000;
  65. static const int diagnosticLimit = 1000;
  66. @visibleForTesting
  67. static bool matchesMeCoffeeAdvertisement({
  68. required String name,
  69. required String advertisedName,
  70. required Iterable<Guid> serviceUuids,
  71. }) =>
  72. serviceUuids.any(
  73. (uuid) =>
  74. uuid.str128.toLowerCase().startsWith(_meCoffeeServiceUuidPrefix),
  75. ) ||
  76. name.toLowerCase().contains('mecoffee') ||
  77. advertisedName.toLowerCase().contains('mecoffee') ||
  78. name.toLowerCase() == 'misssilvia';
  79. bool get supportsClassic => _classicTransport.isSupported;
  80. bool get _machineSafeForFirmware =>
  81. _classicConnected &&
  82. _commandReady &&
  83. !state.isBrewing &&
  84. !state.isHeating &&
  85. !state.isSteaming &&
  86. _heaterOffConfirmed &&
  87. !state.telemetryStale &&
  88. state.temperature <= 50 &&
  89. supportsBundledFirmware(
  90. state.firmwareVersion,
  91. isLegacyV4: state.isLegacyV4Firmware,
  92. );
  93. /// The bundled V10 image targets the `pcb V9` board. V4 controllers report
  94. /// `pcb V3`, keep a different sensor scale and EEPROM layout, and were never
  95. /// offered V10 by the vendor app, so they must not be flashed with it.
  96. @visibleForTesting
  97. static bool supportsBundledFirmware(
  98. String firmwareVersion, {
  99. required bool isLegacyV4,
  100. }) =>
  101. !isLegacyV4 &&
  102. RegExp(r'\bmeCoffee\b', caseSensitive: false).hasMatch(firmwareVersion) &&
  103. RegExp(r'\bpcb\s+V9\b', caseSensitive: false).hasMatch(firmwareVersion);
  104. bool get canUpdateFirmware =>
  105. mounted && !_settingsLocked && _machineSafeForFirmware;
  106. late final Future<void> _settingsLoaded;
  107. StreamSubscription<List<ScanResult>>? _scanSubscription;
  108. StreamSubscription<bool>? _scanStateSubscription;
  109. bool _scanActive = false;
  110. bool _scanStarted = false;
  111. int _scanGeneration = 0;
  112. StreamSubscription<BluetoothConnectionState>? _connectionStateSubscription;
  113. final _notificationSubscriptions = <StreamSubscription<List<int>>>[];
  114. BluetoothDevice? _connectedDevice;
  115. BluetoothCharacteristic? _commandCharacteristic;
  116. bool _commandReady = false;
  117. int _connectionGeneration = 0;
  118. Future<void> _commandQueue = Future<void>.value();
  119. Future<void> _settingsQueue = Future<void>.value();
  120. Future<void> _setpointQueue = Future<void>.value();
  121. // Auto-reconnect: scheduled after an unexpected disconnection.
  122. Timer? _reconnectTimer;
  123. bool _userDisconnected = false;
  124. void _log(DiagnosticDirection direction, String message) {
  125. if (!mounted) return;
  126. final entries = [
  127. ...state.diagnosticLog,
  128. DiagnosticEntry(
  129. timestamp: DateTime.now(),
  130. direction: direction,
  131. message: message.length > 2048
  132. ? '${message.substring(0, 2048)}...'
  133. : message,
  134. ),
  135. ];
  136. if (entries.length > diagnosticLimit) entries.removeAt(0);
  137. state = state.copyWith(diagnosticLog: List.unmodifiable(entries));
  138. }
  139. String exportDiagnosticLog() =>
  140. 'meBarista diagnostics\n'
  141. 'Connection: ${state.connectionStatus}\n'
  142. 'Transport: ${state.transportName}\n'
  143. 'Firmware: ${state.firmwareVersion}\n'
  144. 'Temperature telemetry: ${state.telemetryStale ? 'stale' : 'live'}\n'
  145. '${state.diagnosticLog.map((entry) => entry.text).join('\n')}';
  146. void clearDiagnosticLog() {
  147. state = state.copyWith(diagnosticLog: const []);
  148. }
  149. void _watchFreshness() {
  150. _freshnessTimer?.cancel();
  151. final generation = _connectionGeneration;
  152. _freshnessTimer = Timer(freshnessTimeout, () {
  153. if (!mounted || generation != _connectionGeneration) return;
  154. _stopShotTimer();
  155. _heaterOffConfirmed = false;
  156. state = state.copyWith(
  157. telemetryStale: true,
  158. isHeating: false,
  159. heatingPower: 0,
  160. isSteaming: false,
  161. isBrewing: false,
  162. );
  163. _log(DiagnosticDirection.event, 'Temperature telemetry timed out');
  164. });
  165. }
  166. void _scheduleReconnect({ClassicBluetoothDevice? classicDevice}) {
  167. if (_userDisconnected || _settingsLocked || !mounted) return;
  168. state = state.copyWith(connectionStatus: 'Reconnecting...');
  169. _reconnectTimer?.cancel();
  170. _reconnectTimer = Timer(const Duration(seconds: 30), () {
  171. _reconnectTimer = null;
  172. if (!mounted || _userDisconnected) return;
  173. if (classicDevice != null) {
  174. unawaited(connectToClassicDevice(classicDevice));
  175. } else {
  176. unawaited(startScan());
  177. }
  178. });
  179. }
  180. Future<List<ClassicBluetoothDevice>> listClassicDevices() async {
  181. try {
  182. return await _classicTransport.listBondedDevices();
  183. } catch (error) {
  184. _reportCommandError('Unable to list paired Bluetooth devices: $error');
  185. rethrow;
  186. }
  187. }
  188. void _listenClassic(int generation) {
  189. _classicDataSubscription = _classicTransport.received.listen(
  190. (data) {
  191. if (mounted && generation == _connectionGeneration) _handleData(data);
  192. },
  193. onError: (Object error) {
  194. if (!mounted || generation != _connectionGeneration) return;
  195. _firmwareBytes?.addError(error);
  196. if (!_firmwareMode) unawaited(_failConnection(null, error));
  197. },
  198. );
  199. _classicEventSubscription = _classicTransport.connectionEvents.listen(
  200. (event) {
  201. if (!mounted || generation != _connectionGeneration) return;
  202. if (event.type == ClassicBluetoothEventType.connected) {
  203. _classicConnected = true;
  204. return;
  205. }
  206. final error = StateError(
  207. event.message ?? 'Bluetooth Classic disconnected',
  208. );
  209. if (_firmwareMode) {
  210. _classicConnected = false;
  211. _firmwareBytes?.addError(error);
  212. return;
  213. }
  214. final classic = _classicDevice;
  215. _log(DiagnosticDirection.event, error.toString());
  216. _clearConnection();
  217. state = state.copyWith(
  218. connectionStatus: 'Disconnected',
  219. isBrewing: false,
  220. );
  221. if (!event.explicitDisconnect) {
  222. _scheduleReconnect(classicDevice: classic);
  223. }
  224. },
  225. onError: (Object error) {
  226. if (!mounted || generation != _connectionGeneration) return;
  227. _firmwareBytes?.addError(error);
  228. if (!_firmwareMode) unawaited(_failConnection(null, error));
  229. },
  230. );
  231. }
  232. Future<void> connectToClassicDevice(ClassicBluetoothDevice device) async {
  233. if (_commandReady ||
  234. state.connectionStatus == 'Connecting...' ||
  235. _settingsLocked) {
  236. return;
  237. }
  238. _reconnectTimer?.cancel();
  239. _reconnectTimer = null;
  240. _userDisconnected = false;
  241. _clearConnection();
  242. _classicDevice = device;
  243. final generation = _connectionGeneration;
  244. state = state.copyWith(
  245. connectionStatus: 'Connecting...',
  246. transportName: 'Bluetooth Classic',
  247. firmwareVersion: '',
  248. isLegacyV4Firmware: false,
  249. clearCommandError: true,
  250. );
  251. try {
  252. if (!await stopScan()) return;
  253. await _settingsLoaded;
  254. if (!mounted || generation != _connectionGeneration) return;
  255. _listenClassic(generation);
  256. await _classicTransport.connect(device.address);
  257. if (!mounted || generation != _connectionGeneration) return;
  258. _classicConnected = true;
  259. if (!await _sendInitializationSequence()) {
  260. throw StateError(state.commandError ?? 'Initialization failed');
  261. }
  262. if (!mounted || generation != _connectionGeneration) return;
  263. _commandReady = true;
  264. state = state.copyWith(connectionStatus: 'Connected');
  265. _watchFreshness();
  266. _startClockSync();
  267. _log(DiagnosticDirection.event, 'Connected via Bluetooth Classic');
  268. } catch (error) {
  269. if (mounted && generation == _connectionGeneration) {
  270. await _failConnection(null, error);
  271. }
  272. }
  273. }
  274. Future<void> updateFirmware() async {
  275. if (!canUpdateFirmware) {
  276. _reportCommandError(
  277. state.firmwareVersion.isNotEmpty &&
  278. !supportsBundledFirmware(
  279. state.firmwareVersion,
  280. isLegacyV4: state.isLegacyV4Firmware,
  281. )
  282. ? 'The bundled V10 firmware only supports "pcb V9" controllers; '
  283. 'this controller reports "${state.firmwareVersion}".'
  284. : 'Firmware updates require a live Bluetooth Classic connection, '
  285. 'the machine switched off at its power switch (heating off), '
  286. 'and a boiler at or below 50 C.',
  287. );
  288. return;
  289. }
  290. final classic = _classicDevice!;
  291. final generation = _connectionGeneration;
  292. // Validate the bundled image before touching the controller.
  293. late final IntelHexFirmware image;
  294. try {
  295. image = IntelHexFirmware.parse(
  296. await rootBundle.loadString(
  297. 'meBarista_for_Android/assets/meCoffee-V10.hex',
  298. ),
  299. );
  300. } catch (error) {
  301. _reportCommandError('Cannot load firmware: $error');
  302. return;
  303. }
  304. if (!mounted ||
  305. generation != _connectionGeneration ||
  306. !canUpdateFirmware ||
  307. classic != _classicDevice) {
  308. _reportCommandError(
  309. 'Connection or machine state changed before updating.',
  310. );
  311. return;
  312. }
  313. _settingsLocked = true;
  314. _reconnectTimer?.cancel();
  315. state = state.copyWith(
  316. firmwareUpdating: true,
  317. firmwareProgress: 0,
  318. firmwareUpdateStatus: 'Waiting for settings to finish...',
  319. clearCommandError: true,
  320. );
  321. _log(DiagnosticDirection.event, 'Starting confirmed V10 firmware update');
  322. var resetStarted = false;
  323. try {
  324. await _settingsQueue.timeout(const Duration(seconds: 15));
  325. await _commandQueue.timeout(const Duration(seconds: 15));
  326. if (!mounted ||
  327. generation != _connectionGeneration ||
  328. !_machineSafeForFirmware ||
  329. classic != _classicDevice) {
  330. if (mounted) {
  331. state = state.copyWith(
  332. firmwareUpdating: false,
  333. firmwareUpdateStatus: 'Update cancelled before controller reset.',
  334. );
  335. _reportCommandError(
  336. 'Connection or machine state changed before updating.',
  337. );
  338. }
  339. return;
  340. }
  341. _firmwareMode = true;
  342. _commandReady = false;
  343. _freshnessTimer?.cancel();
  344. state = state.copyWith(firmwareUpdateStatus: 'Entering bootloader...');
  345. resetStarted = true;
  346. await _classicTransport
  347. .write('\ncmd reset en\n'.codeUnits)
  348. .timeout(const Duration(seconds: 5));
  349. await _firmwareDelay(const Duration(seconds: 5));
  350. if (!_classicConnected) {
  351. _clearConnection();
  352. await _classicTransport.disconnect();
  353. _listenClassic(_connectionGeneration);
  354. await _classicTransport.connect(classic.address);
  355. _classicConnected = true;
  356. }
  357. await _classicTransport
  358. .write('\ncmd reset en\n'.codeUnits)
  359. .timeout(const Duration(seconds: 5));
  360. await _firmwareDelay(const Duration(seconds: 1));
  361. _clearConnection();
  362. await _classicTransport.disconnect();
  363. await _firmwareDelay(const Duration(seconds: 1));
  364. if (!mounted) throw StateError('Firmware update interrupted');
  365. _firmwareBytes = StreamController<List<int>>.broadcast();
  366. _listenClassic(_connectionGeneration);
  367. await _classicTransport.connect(classic.address);
  368. _classicConnected = true;
  369. state = state.copyWith(
  370. firmwareUpdateStatus: 'Programming and verifying...',
  371. );
  372. // The reconnect resets the controller into its bootloader; give it time
  373. // to start before syncing (the vendor app waits 750 ms here).
  374. await _firmwareDelay(const Duration(milliseconds: 750));
  375. final updater = FirmwareUpdater(
  376. write: (bytes) async {
  377. if (!_classicConnected) throw StateError('Bootloader disconnected');
  378. await _classicTransport.write(bytes);
  379. },
  380. received: _firmwareBytes!.stream,
  381. );
  382. try {
  383. await updater.flash(
  384. image,
  385. onProgress: (progress) {
  386. if (mounted) state = state.copyWith(firmwareProgress: progress);
  387. },
  388. );
  389. } finally {
  390. await updater.dispose();
  391. }
  392. if (!mounted) throw StateError('Firmware update interrupted');
  393. state = state.copyWith(
  394. firmwareUpdateStatus: 'Firmware verified. Reconnecting...',
  395. firmwareProgress: 1,
  396. );
  397. _log(DiagnosticDirection.event, 'Firmware programmed and verified');
  398. _clearConnection();
  399. await _classicTransport.disconnect();
  400. _firmwareMode = false;
  401. await _firmwareDelay(const Duration(seconds: 2));
  402. if (mounted) {
  403. _settingsLocked = false;
  404. state = state.copyWith(
  405. firmwareUpdating: false,
  406. connectionStatus: 'Disconnected',
  407. );
  408. await connectToClassicDevice(classic);
  409. if (!mounted) return;
  410. state = state.copyWith(
  411. firmwareUpdateStatus: state.connectionStatus == 'Connected'
  412. ? 'V10 firmware programmed and verified.'
  413. : 'Firmware verified; reconnect to read controller settings.',
  414. );
  415. }
  416. } catch (error) {
  417. if (!resetStarted) {
  418. if (mounted) {
  419. state = state.copyWith(
  420. firmwareUpdating: false,
  421. firmwareUpdateStatus: 'Update cancelled before controller reset.',
  422. );
  423. _reportCommandError('Cannot prepare firmware update: $error');
  424. }
  425. return;
  426. }
  427. _clearConnection();
  428. try {
  429. await _classicTransport.disconnect();
  430. } catch (disconnectError) {
  431. _log(
  432. DiagnosticDirection.event,
  433. 'Bootloader disconnect failed: $disconnectError',
  434. );
  435. }
  436. if (mounted) {
  437. final nothingWritten =
  438. error is FirmwareUpdateException &&
  439. (error.code == FirmwareUpdateError.noBootloader ||
  440. error.code == FirmwareUpdateError.signatureMismatch);
  441. state = state.copyWith(
  442. firmwareUpdating: false,
  443. connectionStatus: 'Error: Firmware update failed',
  444. firmwareUpdateStatus: 'Update failed: $error',
  445. );
  446. _reportCommandError(
  447. nothingWritten
  448. ? 'Firmware update failed before programming: $error. No flash '
  449. 'was written; power-cycle the machine and reconnect.'
  450. : 'Firmware update failed: $error. Do not brew; the controller may '
  451. 'require bootloader recovery before it can be used.',
  452. );
  453. }
  454. } finally {
  455. _firmwareMode = false;
  456. _settingsLocked = false;
  457. await _firmwareBytes?.close();
  458. _firmwareBytes = null;
  459. }
  460. }
  461. Future<void> _loadSettings() async {
  462. final prefs = await SharedPreferences.getInstance();
  463. if (!mounted) return;
  464. final brewTemp = prefs.getDouble('brewTemperature') ?? 101.0;
  465. state = state.copyWith(
  466. brewTemperature: brewTemp,
  467. steamTemperature: prefs.getDouble('steamTemperature') ?? 125.0,
  468. preinfusionEnabled: prefs.getBool('preinfusionEnabled') ?? true,
  469. preinfusionTime: prefs.getDouble('preinfusionTime') ?? 3.0,
  470. preinfusionPauseTime: prefs.getDouble('preinfusionPauseTime') ?? 3.0,
  471. // preinfusionPower has no corresponding protocol key; retained only for local display
  472. preinfusionPower: prefs.getInt('preinfusionPower') ?? 100,
  473. targetTemperature: brewTemp,
  474. pidP: prefs.getDouble('pidP') ?? 20.0,
  475. pidI: prefs.getDouble('pidI') ?? 0.3,
  476. pidD: prefs.getDouble('pidD') ?? 128.0,
  477. pidIWindDownMin: prefs.getDouble('pidIWindDownMin') ?? 0.0,
  478. pidIWindDownMax: prefs.getDouble('pidIWindDownMax') ?? 20.0,
  479. pidPollingInterval: prefs.getInt('pidPollingInterval') ?? 1000,
  480. shotCounter: prefs.getInt('shotCounter') ?? 0,
  481. grinderCounter: prefs.getInt('grinderCounter') ?? 0,
  482. pressureStart: prefs.getInt('pressureStart') ?? 100,
  483. pressureEnd: prefs.getInt('pressureEnd') ?? 100,
  484. pressurePeriod: prefs.getInt('pressurePeriod') ?? 25,
  485. valveClosedWhilePaused: prefs.getBool('valveClosedWhilePaused') ?? false,
  486. proActivePercentage: prefs.getInt('proActivePercentage') ?? 33,
  487. autoShutoffMinutes: prefs.getInt('autoShutoffMinutes') ?? 60,
  488. autoShutoffEnabled: prefs.getBool('autoShutoffEnabled') ?? false,
  489. wakeupEnabled: prefs.getBool('wakeupEnabled') ?? false,
  490. wakeupTime: prefs.getString('wakeupTime') ?? "07:00",
  491. shutdownEnabled: prefs.getBool('shutdownEnabled') ?? false,
  492. shutdownTime: prefs.getString('shutdownTime') ?? "22:00",
  493. output0: prefs.getInt('output0') ?? 112,
  494. output1: prefs.getInt('output1') ?? 98,
  495. output2: prefs.getInt('output2') ?? 118,
  496. installedAsTimer: prefs.getBool('installedAsTimer') ?? false,
  497. powerButtonFlipsBack: prefs.getBool('powerButtonFlipsBack') ?? false,
  498. maxShotTime: prefs.getInt('maxShotTime') ?? 60,
  499. continuousMode: prefs.getBool('continuousMode') ?? false,
  500. );
  501. }
  502. Future<void> updatePreinfusion(
  503. bool enabled,
  504. double time,
  505. double pause,
  506. bool closeValve,
  507. ) => updatePreinfusionSettings(
  508. enabled: enabled,
  509. time: time,
  510. pause: pause,
  511. closeValve: closeValve,
  512. );
  513. Future<void> updatePreinfusionSettings({
  514. bool? enabled,
  515. double? time,
  516. double? pause,
  517. bool? closeValve,
  518. }) => _updateSettings({
  519. 'pinbl': ?enabled,
  520. 'pistrt': ?time,
  521. 'piprd': ?pause,
  522. 'pivlv': ?closeValve,
  523. });
  524. Future<void> updateHardware(int o0, int o1, int o2, bool timer, bool flips) =>
  525. updateHardwareSettings(
  526. output0: o0,
  527. output1: o1,
  528. output2: o2,
  529. timer: timer,
  530. flips: flips,
  531. );
  532. Future<void> updateHardwareSettings({
  533. int? output0,
  534. int? output1,
  535. int? output2,
  536. bool? timer,
  537. bool? flips,
  538. }) => _updateSettings({
  539. 'o0': ?output0,
  540. 'o1': ?output1,
  541. 'o2': ?output2,
  542. 'tmrpwr': ?timer,
  543. 'pwrflp': ?flips,
  544. });
  545. Future<void> updateInstalledAsTimer(bool enabled) =>
  546. _updateSettings({'tmrpwr': enabled});
  547. Future<void> updateProActive(int percentage) =>
  548. _updateSettings({'tmppap': percentage});
  549. /// Minutes of inactivity before the controller switches off; 0 disables it.
  550. /// The firmware only acts on `tmrosd` while `tmrosdnbl` is set.
  551. Future<void> updateAutoShutoff(int minutes) => _updateSettings(
  552. minutes > 0 ? {'tmrosd': minutes, 'tmrosdnbl': true} : {'tmrosdnbl': false},
  553. );
  554. Future<void> updateMaxShotTime(int seconds) async {
  555. if (seconds < 0 || seconds > MeCoffeeProtocol.maxShotSeconds) {
  556. _reportCommandError(
  557. 'Max shot time must be between 0 and '
  558. '${MeCoffeeProtocol.maxShotSeconds} s.',
  559. );
  560. return;
  561. }
  562. await _updateSettings({'shtmx': seconds});
  563. }
  564. Future<void> updateContinuousMode(bool enabled) =>
  565. _updateSettings({'tmpcntns': enabled});
  566. Future<void> updateSchedule({
  567. bool? wEnabled,
  568. String? wTime,
  569. bool? sEnabled,
  570. String? sTime,
  571. }) => _updateSettings({
  572. 'tmrwnbl': ?wEnabled,
  573. 'tmron': ?wTime,
  574. 'tmrsnbl': ?sEnabled,
  575. 'tmroff': ?sTime,
  576. });
  577. Future<void> updatePressure(int start, int end, int period) =>
  578. updatePressureSettings(start: start, end: end, period: period);
  579. Future<void> updatePressureSettings({int? start, int? end, int? period}) =>
  580. _updateSettings({'pp1': ?start, 'pp2': ?end, 'ppt': ?period});
  581. Future<void> updatePID(double p, double i, double d) =>
  582. updatePIDSettings(p: p, i: i, d: d);
  583. Future<void> updatePIDSettings({double? p, double? i, double? d}) =>
  584. _updateSettings({'pd1p': ?p, 'pd1i': ?i, 'pd1d': ?d});
  585. bool _pidLimitsOutOfRange(Iterable<double?> percentages) {
  586. if (state.isLegacyV4Firmware) return false;
  587. final outOfRange = percentages.any(
  588. (value) =>
  589. value != null &&
  590. (value < 0 || value > MeCoffeeProtocol.maxPidLimitPercent),
  591. );
  592. if (outOfRange) {
  593. _reportCommandError(
  594. 'I-wind-down limits must be between 0 and '
  595. '${MeCoffeeProtocol.maxPidLimitPercent}%.',
  596. );
  597. }
  598. return outOfRange;
  599. }
  600. Future<void> updatePIDLimits(double min, double max, int interval) async {
  601. if (_pidLimitsOutOfRange([min, max])) return;
  602. await _updateSettings({
  603. 'pd1imn': min,
  604. 'pd1imx': max,
  605. 'pd1sz': interval,
  606. }, omitV4Minimum: true);
  607. }
  608. Future<void> updatePIDLimitSettings({
  609. double? min,
  610. double? max,
  611. int? interval,
  612. }) async {
  613. if (_pidLimitsOutOfRange([min, max])) return;
  614. await _updateSettings({'pd1imn': ?min, 'pd1imx': ?max, 'pd1sz': ?interval});
  615. }
  616. Future<void> _incrementShotCount() async {
  617. final prefs = await SharedPreferences.getInstance();
  618. if (!mounted) return;
  619. final newCount = state.shotCounter + 1;
  620. await prefs.setInt('shotCounter', newCount);
  621. if (!mounted) return;
  622. state = state.copyWith(shotCounter: newCount);
  623. }
  624. Future<void> updateBrewTemperature(double temp) async {
  625. if (!temp.isFinite || temp < 50 || temp > 125) {
  626. _reportCommandError('Brew temperature must be between 50 and 125 C.');
  627. return;
  628. }
  629. await _updateSettings({'tmpsp': temp});
  630. }
  631. Future<void> incrementSetpoint() => _adjustSetpoint(0.5);
  632. Future<void> decrementSetpoint() => _adjustSetpoint(-0.5);
  633. Future<void> _adjustSetpoint(double change) {
  634. final generation = _connectionGeneration;
  635. final operation = _setpointQueue.then((_) async {
  636. await _settingsLoaded;
  637. if (!mounted || generation != _connectionGeneration) return;
  638. if (!_reportedSettings.contains('tmpsp')) {
  639. _reportCommandError(
  640. 'Wait for the controller brew setting before adjusting it.',
  641. );
  642. return;
  643. }
  644. if (!state.brewTemperature.isFinite) {
  645. _reportCommandError('Brew temperature must be a finite number.');
  646. return;
  647. }
  648. final newTemp = (state.brewTemperature + change).clamp(50.0, 125.0);
  649. if (newTemp != state.brewTemperature) {
  650. await updateBrewTemperature(newTemp);
  651. }
  652. });
  653. _setpointQueue = operation;
  654. return operation;
  655. }
  656. Future<void> updateSteamTemperature(double temp) async {
  657. if (!temp.isFinite || temp < 110 || temp > 150) {
  658. _reportCommandError('Steam temperature must be between 110 and 150 C.');
  659. return;
  660. }
  661. await _updateSettings({'tmpstm': temp});
  662. }
  663. static const _preferenceKeys = {
  664. 'tmpsp': 'brewTemperature',
  665. 'tmpstm': 'steamTemperature',
  666. 'pinbl': 'preinfusionEnabled',
  667. 'pistrt': 'preinfusionTime',
  668. 'piprd': 'preinfusionPauseTime',
  669. 'pivlv': 'valveClosedWhilePaused',
  670. 'o0': 'output0',
  671. 'o1': 'output1',
  672. 'o2': 'output2',
  673. 'tmrpwr': 'installedAsTimer',
  674. 'pwrflp': 'powerButtonFlipsBack',
  675. 'tmppap': 'proActivePercentage',
  676. 'tmrosd': 'autoShutoffMinutes',
  677. 'tmrosdnbl': 'autoShutoffEnabled',
  678. 'shtmx': 'maxShotTime',
  679. 'tmpcntns': 'continuousMode',
  680. 'tmrwnbl': 'wakeupEnabled',
  681. 'tmron': 'wakeupTime',
  682. 'tmrsnbl': 'shutdownEnabled',
  683. 'tmroff': 'shutdownTime',
  684. 'pp1': 'pressureStart',
  685. 'pp2': 'pressureEnd',
  686. 'ppt': 'pressurePeriod',
  687. 'pd1p': 'pidP',
  688. 'pd1i': 'pidI',
  689. 'pd1d': 'pidD',
  690. 'pd1imn': 'pidIWindDownMin',
  691. 'pd1imx': 'pidIWindDownMax',
  692. 'pd1sz': 'pidPollingInterval',
  693. };
  694. Map<String, Object> _preferenceValues(MachineState value) => {
  695. 'brewTemperature': value.brewTemperature,
  696. 'steamTemperature': value.steamTemperature,
  697. 'preinfusionEnabled': value.preinfusionEnabled,
  698. 'preinfusionTime': value.preinfusionTime,
  699. 'preinfusionPauseTime': value.preinfusionPauseTime,
  700. 'valveClosedWhilePaused': value.valveClosedWhilePaused,
  701. 'output0': value.output0,
  702. 'output1': value.output1,
  703. 'output2': value.output2,
  704. 'installedAsTimer': value.installedAsTimer,
  705. 'powerButtonFlipsBack': value.powerButtonFlipsBack,
  706. 'proActivePercentage': value.proActivePercentage,
  707. 'autoShutoffMinutes': value.autoShutoffMinutes,
  708. 'autoShutoffEnabled': value.autoShutoffEnabled,
  709. 'maxShotTime': value.maxShotTime,
  710. 'continuousMode': value.continuousMode,
  711. 'wakeupEnabled': value.wakeupEnabled,
  712. 'wakeupTime': value.wakeupTime,
  713. 'shutdownEnabled': value.shutdownEnabled,
  714. 'shutdownTime': value.shutdownTime,
  715. 'pressureStart': value.pressureStart,
  716. 'pressureEnd': value.pressureEnd,
  717. 'pressurePeriod': value.pressurePeriod,
  718. 'pidP': value.pidP,
  719. 'pidI': value.pidI,
  720. 'pidD': value.pidD,
  721. 'pidIWindDownMin': value.pidIWindDownMin,
  722. 'pidIWindDownMax': value.pidIWindDownMax,
  723. 'pidPollingInterval': value.pidPollingInterval,
  724. };
  725. Future<bool> _persistPreference(String key, Object value) async {
  726. if (savePreference case final save?) return save(key, value);
  727. final prefs = await SharedPreferences.getInstance();
  728. return switch (value) {
  729. bool value => prefs.setBool(key, value),
  730. double value => prefs.setDouble(key, value),
  731. int value => prefs.setInt(key, value),
  732. String value => prefs.setString(key, value),
  733. _ => throw ArgumentError.value(value, key, 'Unsupported setting type'),
  734. };
  735. }
  736. Future<void> _updateSettings(
  737. Map<String, Object> requested, {
  738. bool omitV4Minimum = false,
  739. }) {
  740. if (!mounted) return Future<void>.value();
  741. if (_settingsLocked) {
  742. _reportCommandError(
  743. 'Settings are blocked while firmware is being updated.',
  744. );
  745. return Future<void>.value();
  746. }
  747. if (!_commandReady) {
  748. _reportCommandError('Settings not sent: connect to meCoffee first.');
  749. return Future<void>.value();
  750. }
  751. if (state.firmwareVersion.isEmpty) {
  752. _reportCommandError(
  753. 'Settings not sent: waiting for controller firmware identity.',
  754. );
  755. return Future<void>.value();
  756. }
  757. if (requested.values.any((value) => value is double && !value.isFinite)) {
  758. _reportCommandError('Settings must contain finite numbers.');
  759. return Future<void>.value();
  760. }
  761. final generation = _connectionGeneration;
  762. final operation = _settingsQueue.then((_) async {
  763. if (!mounted || generation != _connectionGeneration) {
  764. const message = 'Settings cancelled: Bluetooth connection changed.';
  765. if (mounted && state.commandError == null) {
  766. _reportCommandError(message);
  767. } else {
  768. _log(DiagnosticDirection.event, message);
  769. }
  770. return;
  771. }
  772. final values = Map<String, Object>.from(requested);
  773. if (state.isLegacyV4Firmware) {
  774. if (omitV4Minimum) values.remove('pd1imn');
  775. if (values.keys.any(
  776. const {
  777. 'o0',
  778. 'o1',
  779. 'o2',
  780. 'pwrflp',
  781. 'tmrosd',
  782. 'tmrosdnbl',
  783. 'shtmx',
  784. 'pd1imn',
  785. }.contains,
  786. )) {
  787. _reportCommandError(
  788. 'These settings are not supported by V4 firmware.',
  789. );
  790. return;
  791. }
  792. }
  793. // One command per write: each `set` blocks the controller while it
  794. // rewrites EEPROM and its receive buffer holds only 64 bytes. The
  795. // `cmd set s_<key> <stored value> OK` echo confirms delivery and carries
  796. // the value actually stored, which is what gets persisted locally.
  797. for (final entry in values.entries) {
  798. if (!mounted || generation != _connectionGeneration) return;
  799. final command = MeCoffeeProtocol.encodeSet(
  800. entry.key,
  801. entry.value,
  802. isLegacyV4: state.isLegacyV4Firmware,
  803. );
  804. final reply = Completer<String?>();
  805. // A disconnect can fail the reply before it is awaited below.
  806. reply.future.ignore();
  807. _pendingSetEcho = (key: entry.key, reply: reply);
  808. String? confirmation;
  809. try {
  810. if (!await _sendCommand(command.codeUnits)) return;
  811. confirmation = await reply.future.timeout(settingsReplyTimeout);
  812. } on TimeoutException {
  813. _reportCommandError(
  814. 'The controller did not confirm ${entry.key}; it may not be stored.',
  815. );
  816. return;
  817. } catch (error) {
  818. _reportCommandError('Setting ${entry.key} not confirmed: $error');
  819. return;
  820. } finally {
  821. if (identical(_pendingSetEcho?.reply, reply)) _pendingSetEcho = null;
  822. }
  823. if (confirmation == null) {
  824. _reportCommandError('The controller rejected ${entry.key} (NOT OK).');
  825. return;
  826. }
  827. if (!mounted || generation != _connectionGeneration) return;
  828. final preferenceKey = _preferenceKeys[entry.key]!;
  829. try {
  830. if (!await _persistPreference(
  831. preferenceKey,
  832. _preferenceValues(state)[preferenceKey]!,
  833. )) {
  834. _reportCommandError(
  835. 'Settings delivered but could not be saved locally.',
  836. );
  837. return;
  838. }
  839. } on Exception catch (error) {
  840. _reportCommandError(
  841. 'Settings delivered but could not be saved locally: $error',
  842. );
  843. return;
  844. }
  845. }
  846. });
  847. _settingsQueue = operation;
  848. return operation;
  849. }
  850. void _reportCommandError(String message) {
  851. if (!mounted) return;
  852. _log(DiagnosticDirection.event, message);
  853. state = state.copyWith(clearCommandError: true);
  854. state = state.copyWith(commandError: message);
  855. }
  856. Future<bool> _sendCommand(List<int> bytes, {bool initializing = false}) {
  857. final characteristic = _commandCharacteristic;
  858. final classic = _classicConnected;
  859. final generation = _connectionGeneration;
  860. if (_firmwareMode) {
  861. _reportCommandError(
  862. 'Settings are blocked while firmware is being updated.',
  863. );
  864. return Future<bool>.value(false);
  865. }
  866. if ((characteristic == null && !classic) ||
  867. (!initializing && !_commandReady)) {
  868. _reportCommandError('Settings not sent: connect to meCoffee first.');
  869. return Future<bool>.value(false);
  870. }
  871. final operation = _commandQueue.then((_) async {
  872. try {
  873. await _settingsLoaded;
  874. _log(DiagnosticDirection.sent, String.fromCharCodes(bytes).trim());
  875. for (var offset = 0; offset < bytes.length;) {
  876. if (!mounted ||
  877. generation != _connectionGeneration ||
  878. (classic
  879. ? !_classicConnected
  880. : characteristic != _commandCharacteristic ||
  881. characteristic!.device.isDisconnected)) {
  882. throw StateError(
  883. 'Bluetooth disconnected before settings were sent',
  884. );
  885. }
  886. final payloadSize = classic
  887. ? bytes.length
  888. : (characteristic!.device.mtuNow - 3).clamp(1, 512);
  889. final end = (offset + payloadSize).clamp(0, bytes.length);
  890. if (classic) {
  891. await _classicTransport
  892. .write(bytes.sublist(offset, end))
  893. .timeout(const Duration(seconds: 15));
  894. } else {
  895. await characteristic!.write(
  896. bytes.sublist(offset, end),
  897. withoutResponse: !characteristic.properties.write,
  898. );
  899. if (!characteristic.properties.write) {
  900. await Future<void>.delayed(const Duration(milliseconds: 20));
  901. }
  902. }
  903. offset = end;
  904. }
  905. if (!mounted || generation != _connectionGeneration) {
  906. throw StateError('Bluetooth disconnected while sending settings');
  907. }
  908. state = state.copyWith(clearCommandError: true);
  909. return true;
  910. } catch (e) {
  911. if (!initializing && mounted && generation == _connectionGeneration) {
  912. await _failConnection(characteristic?.device, e);
  913. }
  914. _reportCommandError(
  915. 'Settings not saved: $e. The machine may be partially updated.',
  916. );
  917. return false;
  918. }
  919. });
  920. // Queue the whole payload, not individual chunks, so commands cannot interleave.
  921. _commandQueue = operation.then((_) {});
  922. return operation;
  923. }
  924. Future<void> startScan() async {
  925. if (!mounted ||
  926. _scanActive ||
  927. _commandReady ||
  928. _settingsLocked ||
  929. _classicConnected ||
  930. state.connectionStatus == 'Connecting...') {
  931. return;
  932. }
  933. _scanActive = true;
  934. final generation = ++_scanGeneration;
  935. _reconnectTimer?.cancel();
  936. _reconnectTimer = null;
  937. _userDisconnected = false;
  938. try {
  939. final adapterState = await FlutterBluePlus.adapterState.first;
  940. if (!mounted || generation != _scanGeneration) return;
  941. if (adapterState != BluetoothAdapterState.on) {
  942. _cancelScanSubscriptions();
  943. state = state.copyWith(connectionStatus: 'Error: Bluetooth is off');
  944. return;
  945. }
  946. state = state.copyWith(connectionStatus: 'Scanning...');
  947. _scanStarted = true;
  948. await FlutterBluePlus.startScan(timeout: const Duration(seconds: 15));
  949. if (!mounted || generation != _scanGeneration) {
  950. return;
  951. }
  952. var foundDevice = false;
  953. _scanSubscription = FlutterBluePlus.onScanResults.listen(
  954. (results) {
  955. if (!mounted || generation != _scanGeneration || foundDevice) return;
  956. for (final result in results) {
  957. if (matchesMeCoffeeAdvertisement(
  958. name: result.device.platformName,
  959. advertisedName: result.advertisementData.advName,
  960. serviceUuids: result.advertisementData.serviceUuids,
  961. )) {
  962. foundDevice = true;
  963. unawaited(_connectScanResult(result.device));
  964. break;
  965. }
  966. }
  967. },
  968. onError: (Object error) {
  969. if (!mounted || generation != _scanGeneration) return;
  970. state = state.copyWith(
  971. connectionStatus: 'Error: ${_friendlyBtError(error)}',
  972. );
  973. unawaited(stopScan());
  974. },
  975. );
  976. _scanStateSubscription = FlutterBluePlus.isScanning.listen((scanning) {
  977. if (!mounted || generation != _scanGeneration) return;
  978. if (!scanning && !foundDevice) {
  979. _cancelScanSubscriptions();
  980. if (state.connectionStatus == 'Scanning...') {
  981. state = state.copyWith(connectionStatus: 'Not found');
  982. }
  983. }
  984. });
  985. } catch (e) {
  986. if (mounted && generation == _scanGeneration) {
  987. _cancelScanSubscriptions();
  988. state = state.copyWith(
  989. connectionStatus: 'Error: ${_friendlyBtError(e)}',
  990. );
  991. } else {
  992. FlutterError.reportError(
  993. FlutterErrorDetails(
  994. exception: e,
  995. library: 'meBarista Bluetooth',
  996. context: ErrorDescription('while stopping a cancelled scan'),
  997. ),
  998. );
  999. }
  1000. }
  1001. }
  1002. Future<void> _connectScanResult(BluetoothDevice device) async {
  1003. final stoppedGeneration = _scanGeneration + 1;
  1004. if (await stopScan() &&
  1005. mounted &&
  1006. !_userDisconnected &&
  1007. stoppedGeneration == _scanGeneration) {
  1008. await connectToDevice(device);
  1009. }
  1010. }
  1011. static String _friendlyBtError(Object e) {
  1012. final msg = e.toString().toLowerCase();
  1013. if (msg.contains('off') ||
  1014. msg.contains('unknown') ||
  1015. msg.contains('cbmanagerstate')) {
  1016. return 'Bluetooth is off';
  1017. }
  1018. if (msg.contains('unauthorized') || msg.contains('permission')) {
  1019. return 'Bluetooth permission denied';
  1020. }
  1021. return e.toString();
  1022. }
  1023. void _cancelScanSubscriptions() {
  1024. _scanGeneration++;
  1025. _scanActive = false;
  1026. _scanStarted = false;
  1027. _scanSubscription?.cancel();
  1028. _scanSubscription = null;
  1029. _scanStateSubscription?.cancel();
  1030. _scanStateSubscription = null;
  1031. }
  1032. Future<bool> stopScan() async {
  1033. final wasStarted = _scanStarted;
  1034. _cancelScanSubscriptions();
  1035. final generation = _scanGeneration;
  1036. if (!wasStarted) return true;
  1037. try {
  1038. await FlutterBluePlus.stopScan();
  1039. if (mounted &&
  1040. generation == _scanGeneration &&
  1041. state.connectionStatus == 'Scanning...') {
  1042. state = state.copyWith(connectionStatus: 'Not found');
  1043. }
  1044. return true;
  1045. } catch (e, stack) {
  1046. if (mounted) {
  1047. state = state.copyWith(
  1048. connectionStatus: 'Error: ${_friendlyBtError(e)}',
  1049. );
  1050. } else {
  1051. FlutterError.reportError(
  1052. FlutterErrorDetails(
  1053. exception: e,
  1054. stack: stack,
  1055. library: 'meBarista Bluetooth',
  1056. context: ErrorDescription('while stopping a scan'),
  1057. ),
  1058. );
  1059. }
  1060. return false;
  1061. }
  1062. }
  1063. Future<void> connectToDevice(BluetoothDevice device) async {
  1064. if (state.connectionStatus == 'Connecting...' ||
  1065. _commandReady ||
  1066. _settingsLocked) {
  1067. return;
  1068. }
  1069. _reconnectTimer?.cancel();
  1070. _reconnectTimer = null;
  1071. _userDisconnected = false;
  1072. _clearConnection();
  1073. final generation = _connectionGeneration;
  1074. _connectedDevice = device;
  1075. state = state.copyWith(
  1076. connectionStatus: 'Connecting...',
  1077. transportName: 'BLE',
  1078. firmwareVersion: '',
  1079. isLegacyV4Firmware: false,
  1080. clearCommandError: true,
  1081. );
  1082. try {
  1083. if (!await stopScan()) {
  1084. _clearConnection();
  1085. return;
  1086. }
  1087. await _settingsLoaded;
  1088. if (!mounted || generation != _connectionGeneration) return;
  1089. await device.connect();
  1090. if (!mounted || generation != _connectionGeneration) return;
  1091. _connectionStateSubscription = device.connectionState.listen((
  1092. connectionState,
  1093. ) {
  1094. if (!mounted || generation != _connectionGeneration) return;
  1095. if (connectionState == BluetoothConnectionState.disconnected) {
  1096. _clearConnection();
  1097. state = state.copyWith(
  1098. connectionStatus: 'Disconnected',
  1099. isBrewing: false,
  1100. );
  1101. _scheduleReconnect();
  1102. }
  1103. });
  1104. await _discoverServices(device);
  1105. if (!mounted || generation != _connectionGeneration) return;
  1106. await Future<void>.delayed(const Duration(milliseconds: 500));
  1107. if (!mounted || generation != _connectionGeneration) return;
  1108. if (!await _sendInitializationSequence()) {
  1109. throw StateError(state.commandError ?? 'Initialization failed');
  1110. }
  1111. if (!mounted || generation != _connectionGeneration) return;
  1112. _commandReady = true;
  1113. state = state.copyWith(connectionStatus: 'Connected');
  1114. _watchFreshness();
  1115. _startClockSync();
  1116. _log(DiagnosticDirection.event, 'Connected via BLE');
  1117. } catch (e) {
  1118. if (mounted && generation == _connectionGeneration) {
  1119. await _failConnection(device, e);
  1120. }
  1121. }
  1122. }
  1123. /// The firmware ignores a pending clock value of 0, so midnight is sent as 1.
  1124. List<int> _clockCommand() {
  1125. final now = DateTime.now();
  1126. final seconds = now.hour * 3600 + now.minute * 60 + now.second;
  1127. return '\ncmd clock set ${seconds < 1 ? 1 : seconds}\n'.codeUnits;
  1128. }
  1129. /// Resend the clock periodically: the controller's mains-derived clock
  1130. /// drifts, does not follow DST and restarts at 0 after every reset.
  1131. void _startClockSync() {
  1132. _clockTimer?.cancel();
  1133. final generation = _connectionGeneration;
  1134. _clockTimer = Timer.periodic(clockSyncInterval, (_) {
  1135. if (!mounted || generation != _connectionGeneration || !_commandReady) {
  1136. return;
  1137. }
  1138. unawaited(_sendCommand(_clockCommand()));
  1139. });
  1140. }
  1141. /// A boot frame (`tmp 0 …`) or watchdog report while connected means the
  1142. /// controller restarted underneath an open link: its clock is reset and
  1143. /// settings may have been restored, so repeat the start-up sequence.
  1144. void _reinitializeAfterReset(String line) {
  1145. if (_reinitializing || !_commandReady || _settingsLocked) return;
  1146. _reinitializing = true;
  1147. final generation = _connectionGeneration;
  1148. _log(
  1149. DiagnosticDirection.event,
  1150. 'Controller restarted ("$line"); re-sending clock and reading settings',
  1151. );
  1152. unawaited(
  1153. _sendInitializationSequence().whenComplete(() {
  1154. if (generation == _connectionGeneration) _reinitializing = false;
  1155. }),
  1156. );
  1157. }
  1158. Future<bool> _sendInitializationSequence() async {
  1159. if (!await _sendCommand(_clockCommand(), initializing: true)) {
  1160. return false;
  1161. }
  1162. if (!await _sendCommand("\ncmd uname OK\n".codeUnits, initializing: true)) {
  1163. return false;
  1164. }
  1165. return _sendCommand("\ncmd dump\n".codeUnits, initializing: true);
  1166. }
  1167. Future<void> _discoverServices(BluetoothDevice device) async {
  1168. final services = await device.discoverServices();
  1169. if (_connectedDevice != device || device.isDisconnected) {
  1170. throw StateError('Bluetooth disconnected during service discovery');
  1171. }
  1172. BluetoothCharacteristic? preferred;
  1173. for (final service in services) {
  1174. final serviceId = service.uuid.str128.toLowerCase();
  1175. if (!serviceId.startsWith(_meCoffeeServiceUuidPrefix)) continue;
  1176. for (final characteristic in service.characteristics) {
  1177. final charId = characteristic.uuid.str128.toLowerCase();
  1178. if (charId.startsWith(_meCoffeeCharacteristicUuidPrefix) &&
  1179. (characteristic.properties.write ||
  1180. characteristic.properties.writeWithoutResponse) &&
  1181. (characteristic.properties.notify ||
  1182. characteristic.properties.indicate)) {
  1183. preferred = characteristic;
  1184. break;
  1185. }
  1186. }
  1187. if (preferred != null) break;
  1188. }
  1189. if (preferred != null) {
  1190. await _attachCharacteristic(preferred);
  1191. if (_connectedDevice != device || device.isDisconnected) {
  1192. throw StateError('Bluetooth disconnected during service discovery');
  1193. }
  1194. _commandCharacteristic = preferred;
  1195. return;
  1196. }
  1197. // Fallback still requires both a write path and a telemetry path.
  1198. BluetoothCharacteristic? writable;
  1199. var hasNotifications = false;
  1200. for (final service in services) {
  1201. for (final characteristic in service.characteristics) {
  1202. if (writable == null &&
  1203. (characteristic.properties.write ||
  1204. characteristic.properties.writeWithoutResponse)) {
  1205. writable = characteristic;
  1206. }
  1207. if (characteristic.properties.notify ||
  1208. characteristic.properties.indicate) {
  1209. await _attachCharacteristic(characteristic);
  1210. hasNotifications = true;
  1211. }
  1212. }
  1213. }
  1214. if (writable == null || !hasNotifications) {
  1215. throw StateError(
  1216. 'No usable meCoffee write/notification characteristics found',
  1217. );
  1218. }
  1219. if (_connectedDevice != device || device.isDisconnected) {
  1220. throw StateError('Bluetooth disconnected during service discovery');
  1221. }
  1222. _commandCharacteristic = writable;
  1223. }
  1224. Future<void> _attachCharacteristic(
  1225. BluetoothCharacteristic characteristic,
  1226. ) async {
  1227. final generation = _connectionGeneration;
  1228. if (characteristic.properties.notify ||
  1229. characteristic.properties.indicate) {
  1230. final subscription = characteristic.onValueReceived.listen(
  1231. (data) {
  1232. if (mounted && generation == _connectionGeneration) _handleData(data);
  1233. },
  1234. onError: (Object error) {
  1235. if (mounted && generation == _connectionGeneration) {
  1236. unawaited(_failConnection(characteristic.device, error));
  1237. }
  1238. },
  1239. );
  1240. _notificationSubscriptions.add(subscription);
  1241. await characteristic.setNotifyValue(true);
  1242. if (generation != _connectionGeneration) {
  1243. throw StateError('Bluetooth disconnected during notification setup');
  1244. }
  1245. }
  1246. }
  1247. void _clearConnection() {
  1248. _connectionGeneration++;
  1249. _heaterOffConfirmed = false;
  1250. _clockTimer?.cancel();
  1251. _clockTimer = null;
  1252. _reinitializing = false;
  1253. final pendingEcho = _pendingSetEcho;
  1254. _pendingSetEcho = null;
  1255. if (pendingEcho != null && !pendingEcho.reply.isCompleted) {
  1256. pendingEcho.reply.completeError(
  1257. StateError('Bluetooth disconnected before the controller confirmed'),
  1258. );
  1259. }
  1260. _reportedSettings.clear();
  1261. _pendingFirmwareSettings.clear();
  1262. _commandReady = false;
  1263. _connectedDevice = null;
  1264. _commandCharacteristic = null;
  1265. _classicConnected = false;
  1266. _classicDataSubscription?.cancel();
  1267. _classicDataSubscription = null;
  1268. _classicEventSubscription?.cancel();
  1269. _classicEventSubscription = null;
  1270. _freshnessTimer?.cancel();
  1271. _freshnessTimer = null;
  1272. _connectionStateSubscription?.cancel();
  1273. _connectionStateSubscription = null;
  1274. for (final subscription in _notificationSubscriptions) {
  1275. subscription.cancel();
  1276. }
  1277. _notificationSubscriptions.clear();
  1278. _stopShotTimer();
  1279. _inputBuffer = '';
  1280. if (mounted) {
  1281. state = state.copyWith(
  1282. telemetryStale: true,
  1283. clearLastTelemetry: true,
  1284. isHeating: false,
  1285. heatingPower: 0,
  1286. isSteaming: false,
  1287. );
  1288. }
  1289. }
  1290. Future<void> _failConnection(BluetoothDevice? device, Object error) async {
  1291. final classic = _classicConnected || _classicDataSubscription != null;
  1292. _clearConnection();
  1293. final generation = _connectionGeneration;
  1294. var message = error.toString();
  1295. if (mounted) {
  1296. state = state.copyWith(
  1297. connectionStatus: 'Error: $message',
  1298. isBrewing: false,
  1299. );
  1300. }
  1301. try {
  1302. if (classic) await _classicTransport.disconnect();
  1303. if (device != null) await device.disconnect();
  1304. } catch (disconnectError) {
  1305. message = '$message; disconnect failed: $disconnectError';
  1306. }
  1307. if (mounted && generation == _connectionGeneration) {
  1308. state = state.copyWith(
  1309. connectionStatus: 'Error: $message',
  1310. isBrewing: false,
  1311. );
  1312. _log(DiagnosticDirection.event, 'Connection failed: $message');
  1313. }
  1314. }
  1315. Timer? _shotTimer;
  1316. String _inputBuffer = "";
  1317. void _handleData(List<int> data) {
  1318. if (!mounted) return;
  1319. if (_firmwareMode) {
  1320. _firmwareBytes?.add(List<int>.from(data));
  1321. return;
  1322. }
  1323. _inputBuffer += String.fromCharCodes(data);
  1324. if (_inputBuffer.length > 8192 && !_inputBuffer.contains('\n')) {
  1325. _inputBuffer = '';
  1326. _log(DiagnosticDirection.event, 'Discarded oversized unterminated frame');
  1327. return;
  1328. }
  1329. while (_inputBuffer.contains('\n')) {
  1330. int index = _inputBuffer.indexOf('\n');
  1331. String line = _inputBuffer.substring(0, index).trim();
  1332. _inputBuffer = _inputBuffer.substring(index + 1);
  1333. if (line.isNotEmpty) {
  1334. _log(DiagnosticDirection.received, line);
  1335. final fields = line.split(RegExp(r'\s+'));
  1336. final settingKey = fields.first == 'get' && fields.length >= 3
  1337. ? fields[1]
  1338. : fields.first == 'cmd' &&
  1339. fields.length >= 4 &&
  1340. (fields[1] == 'get' || fields[1] == 'set')
  1341. ? fields[2]
  1342. : null;
  1343. // A dump can arrive before uname; do not guess V4 units.
  1344. if (state.firmwareVersion.isEmpty &&
  1345. _firmwareScaledKeys.contains(settingKey)) {
  1346. _pendingFirmwareSettings[settingKey == 'pd1imm'
  1347. ? 'pd1imn'
  1348. : settingKey!] =
  1349. line;
  1350. continue;
  1351. }
  1352. final oldBrewing = state.isBrewing;
  1353. var parsed = MeCoffeeProtocol.parse(line, state);
  1354. final valid = !identical(parsed, state);
  1355. if (valid &&
  1356. parsed.firmwareVersion.isNotEmpty &&
  1357. state.firmwareVersion.isEmpty) {
  1358. for (final entry in _pendingFirmwareSettings.entries) {
  1359. final replayed = MeCoffeeProtocol.parse(entry.value, parsed);
  1360. if (!identical(replayed, parsed)) {
  1361. _reportedSettings.add(entry.key);
  1362. }
  1363. parsed = replayed;
  1364. }
  1365. _pendingFirmwareSettings.clear();
  1366. }
  1367. if (valid && fields.first == 'pid') {
  1368. _heaterOffConfirmed =
  1369. !state.telemetryStale &&
  1370. fields.skip(1).where((f) => f != 'OK').every((f) => f == '0');
  1371. }
  1372. if (state.telemetryStale &&
  1373. (fields.first == 'pid' || fields.first == 'sht')) {
  1374. parsed = parsed.copyWith(
  1375. isHeating: false,
  1376. heatingPower: 0,
  1377. isSteaming: false,
  1378. isBrewing: false,
  1379. );
  1380. }
  1381. if (valid && fields.first == 'get' && fields.length >= 3) {
  1382. _reportedSettings.add(fields[1]);
  1383. } else if (valid &&
  1384. fields.first == 'cmd' &&
  1385. fields.length >= 4 &&
  1386. fields[1] == 'get') {
  1387. _reportedSettings.add(fields[2]);
  1388. }
  1389. state = parsed;
  1390. if (fields.length >= 3 && fields[0] == 'cmd' && fields[1] == 'set') {
  1391. final pending = _pendingSetEcho;
  1392. if (pending != null && !pending.reply.isCompleted) {
  1393. if (fields[2] == 'NOT') {
  1394. pending.reply.complete(null);
  1395. } else if (fields[2] == 's_${pending.key}') {
  1396. pending.reply.complete(line);
  1397. }
  1398. }
  1399. }
  1400. if (fields.length >= 2 && fields[0] == 'tmp' && fields[1] == '0' ||
  1401. line.contains('WDT fired')) {
  1402. _reinitializeAfterReset(line);
  1403. }
  1404. if (valid && (line.startsWith('tmp ') || line.startsWith('T '))) {
  1405. final now = DateTime.now();
  1406. final fields = line.split(RegExp(r'\s+'));
  1407. final rawSensor2 = fields.length >= 5
  1408. ? double.tryParse(fields[4])
  1409. : null;
  1410. final sensor2 =
  1411. rawSensor2 != null && rawSensor2 > 5 && rawSensor2 < 20000
  1412. ? rawSensor2 / 100
  1413. : null;
  1414. final history = List<double>.from(state.temperatureHistory);
  1415. history.add(state.temperature);
  1416. if (history.length > historyLimit) history.removeAt(0);
  1417. final history2 = List<double>.from(state.sensor2TemperatureHistory);
  1418. // Only record sensor2 if we have a valid (non-zero) reading.
  1419. if (sensor2 != null) {
  1420. history2.add(sensor2);
  1421. if (history2.length > historyLimit) history2.removeAt(0);
  1422. }
  1423. final samples = [
  1424. ...state.temperatureSamples,
  1425. TemperatureSample(
  1426. timestamp: now,
  1427. boiler: state.temperature,
  1428. target: state.targetTemperature,
  1429. sensor2: sensor2,
  1430. ),
  1431. ];
  1432. if (samples.length > historyLimit) samples.removeAt(0);
  1433. state = state.copyWith(
  1434. temperatureHistory: history,
  1435. sensor2TemperatureHistory: history2,
  1436. sensor2Temperature: sensor2 ?? 0,
  1437. temperatureSamples: List.unmodifiable(samples),
  1438. lastTelemetryAt: now,
  1439. telemetryStale: false,
  1440. );
  1441. _watchFreshness();
  1442. } else if (!valid &&
  1443. (line.startsWith('tmp ') ||
  1444. line.startsWith('T ') ||
  1445. line.startsWith('pid ') ||
  1446. line.startsWith('sht '))) {
  1447. _log(DiagnosticDirection.event, 'Ignored malformed telemetry: $line');
  1448. }
  1449. // Shot Timer Logic
  1450. if (state.isBrewing && !oldBrewing) {
  1451. // Started brewing (triggered by 'sht 0')
  1452. _startShotTimer();
  1453. } else if (!state.isBrewing && oldBrewing) {
  1454. // Stopped brewing (triggered by 'sht <final_time>')
  1455. _stopShotTimer();
  1456. _incrementShotCount();
  1457. }
  1458. }
  1459. }
  1460. }
  1461. void _startShotTimer() {
  1462. if (state.telemetryStale) return;
  1463. _shotTimer?.cancel();
  1464. state = state.copyWith(shotTimer: 0);
  1465. _shotTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
  1466. if (!mounted || state.telemetryStale) {
  1467. timer.cancel();
  1468. return;
  1469. }
  1470. state = state.copyWith(shotTimer: state.shotTimer + 1);
  1471. });
  1472. }
  1473. void _stopShotTimer() {
  1474. _shotTimer?.cancel();
  1475. _shotTimer = null;
  1476. }
  1477. Future<void> disconnect() async {
  1478. if (state.firmwareUpdating) {
  1479. _reportCommandError('Cannot disconnect while firmware is being updated.');
  1480. return;
  1481. }
  1482. _userDisconnected = true;
  1483. _log(DiagnosticDirection.event, 'Disconnect requested by user');
  1484. _reconnectTimer?.cancel();
  1485. _reconnectTimer = null;
  1486. final device = _connectedDevice;
  1487. final classic = _classicConnected || _classicDataSubscription != null;
  1488. _clearConnection();
  1489. state = state.copyWith(connectionStatus: 'Disconnected', isBrewing: false);
  1490. await stopScan();
  1491. if (classic) {
  1492. try {
  1493. await _classicTransport.disconnect();
  1494. } catch (e) {
  1495. if (mounted) state = state.copyWith(connectionStatus: 'Error: $e');
  1496. _log(DiagnosticDirection.event, 'Classic disconnect failed: $e');
  1497. }
  1498. }
  1499. if (device != null) {
  1500. try {
  1501. await device.disconnect(queue: false);
  1502. } catch (e) {
  1503. if (mounted) {
  1504. state = state.copyWith(connectionStatus: 'Error: $e');
  1505. }
  1506. _log(DiagnosticDirection.event, 'BLE disconnect failed: $e');
  1507. }
  1508. }
  1509. if (mounted && state.connectionStatus == 'Disconnected') {
  1510. _log(DiagnosticDirection.event, 'Disconnected by user');
  1511. }
  1512. }
  1513. @override
  1514. void dispose() {
  1515. _userDisconnected = true;
  1516. _reconnectTimer?.cancel();
  1517. final device = _connectedDevice;
  1518. unawaited(stopScan());
  1519. _clearConnection();
  1520. unawaited(
  1521. _classicTransport.dispose().catchError((Object error, StackTrace stack) {
  1522. FlutterError.reportError(
  1523. FlutterErrorDetails(
  1524. exception: error,
  1525. stack: stack,
  1526. library: 'meBarista Bluetooth',
  1527. context: ErrorDescription('while disposing the Classic connection'),
  1528. ),
  1529. );
  1530. }),
  1531. );
  1532. if (device != null) {
  1533. unawaited(
  1534. device.disconnect(queue: false).catchError((
  1535. Object error,
  1536. StackTrace stack,
  1537. ) {
  1538. FlutterError.reportError(
  1539. FlutterErrorDetails(
  1540. exception: error,
  1541. stack: stack,
  1542. library: 'meBarista Bluetooth',
  1543. context: ErrorDescription(
  1544. 'while disposing the Bluetooth connection',
  1545. ),
  1546. ),
  1547. );
  1548. }),
  1549. );
  1550. }
  1551. super.dispose();
  1552. }
  1553. }