bluetooth_service.dart 50 KB

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