bluetooth_service.dart 52 KB

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