bluetooth_service.dart 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486
  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) =>
  509. _updateSettings({'shtmx': seconds});
  510. Future<void> updateContinuousMode(bool enabled) =>
  511. _updateSettings({'tmpcntns': enabled});
  512. Future<void> updateSchedule({
  513. bool? wEnabled,
  514. String? wTime,
  515. bool? sEnabled,
  516. String? sTime,
  517. }) => _updateSettings({
  518. 'tmrwnbl': ?wEnabled,
  519. 'tmron': ?wTime,
  520. 'tmrsnbl': ?sEnabled,
  521. 'tmroff': ?sTime,
  522. });
  523. Future<void> updatePressure(int start, int end, int period) =>
  524. updatePressureSettings(start: start, end: end, period: period);
  525. Future<void> updatePressureSettings({int? start, int? end, int? period}) =>
  526. _updateSettings({'pp1': ?start, 'pp2': ?end, 'ppt': ?period});
  527. Future<void> updatePID(double p, double i, double d) =>
  528. updatePIDSettings(p: p, i: i, d: d);
  529. Future<void> updatePIDSettings({double? p, double? i, double? d}) =>
  530. _updateSettings({'pd1p': ?p, 'pd1i': ?i, 'pd1d': ?d});
  531. Future<void> updatePIDLimits(double min, double max, int interval) =>
  532. _updateSettings({
  533. 'pd1imn': min,
  534. 'pd1imx': max,
  535. 'pd1sz': interval,
  536. }, omitV4Minimum: true);
  537. Future<void> updatePIDLimitSettings({
  538. double? min,
  539. double? max,
  540. int? interval,
  541. }) => _updateSettings({'pd1imn': ?min, 'pd1imx': ?max, 'pd1sz': ?interval});
  542. Future<void> _incrementShotCount() async {
  543. final prefs = await SharedPreferences.getInstance();
  544. if (!mounted) return;
  545. final newCount = state.shotCounter + 1;
  546. await prefs.setInt('shotCounter', newCount);
  547. if (!mounted) return;
  548. state = state.copyWith(shotCounter: newCount);
  549. }
  550. Future<void> updateBrewTemperature(double temp) async {
  551. if (!temp.isFinite || temp < 50 || temp > 125) {
  552. _reportCommandError('Brew temperature must be between 50 and 125 C.');
  553. return;
  554. }
  555. await _updateSettings({'tmpsp': temp});
  556. }
  557. Future<void> incrementSetpoint() => _adjustSetpoint(0.5);
  558. Future<void> decrementSetpoint() => _adjustSetpoint(-0.5);
  559. Future<void> _adjustSetpoint(double change) {
  560. final generation = _connectionGeneration;
  561. final operation = _setpointQueue.then((_) async {
  562. await _settingsLoaded;
  563. if (!mounted || generation != _connectionGeneration) return;
  564. if (!_reportedSettings.contains('tmpsp')) {
  565. _reportCommandError(
  566. 'Wait for the controller brew setting before adjusting it.',
  567. );
  568. return;
  569. }
  570. if (!state.brewTemperature.isFinite) {
  571. _reportCommandError('Brew temperature must be a finite number.');
  572. return;
  573. }
  574. final newTemp = (state.brewTemperature + change).clamp(50.0, 125.0);
  575. if (newTemp != state.brewTemperature) {
  576. await updateBrewTemperature(newTemp);
  577. }
  578. });
  579. _setpointQueue = operation;
  580. return operation;
  581. }
  582. Future<void> updateSteamTemperature(double temp) async {
  583. if (!temp.isFinite || temp < 110 || temp > 150) {
  584. _reportCommandError('Steam temperature must be between 110 and 150 C.');
  585. return;
  586. }
  587. await _updateSettings({'tmpstm': temp});
  588. }
  589. static const _preferenceKeys = {
  590. 'tmpsp': 'brewTemperature',
  591. 'tmpstm': 'steamTemperature',
  592. 'pinbl': 'preinfusionEnabled',
  593. 'pistrt': 'preinfusionTime',
  594. 'piprd': 'preinfusionPauseTime',
  595. 'pivlv': 'valveClosedWhilePaused',
  596. 'o0': 'output0',
  597. 'o1': 'output1',
  598. 'o2': 'output2',
  599. 'tmrpwr': 'installedAsTimer',
  600. 'pwrflp': 'powerButtonFlipsBack',
  601. 'tmppap': 'proActivePercentage',
  602. 'tmrosd': 'autoShutoffMinutes',
  603. 'shtmx': 'maxShotTime',
  604. 'tmpcntns': 'continuousMode',
  605. 'tmrwnbl': 'wakeupEnabled',
  606. 'tmron': 'wakeupTime',
  607. 'tmrsnbl': 'shutdownEnabled',
  608. 'tmroff': 'shutdownTime',
  609. 'pp1': 'pressureStart',
  610. 'pp2': 'pressureEnd',
  611. 'ppt': 'pressurePeriod',
  612. 'pd1p': 'pidP',
  613. 'pd1i': 'pidI',
  614. 'pd1d': 'pidD',
  615. 'pd1imn': 'pidIWindDownMin',
  616. 'pd1imx': 'pidIWindDownMax',
  617. 'pd1sz': 'pidPollingInterval',
  618. };
  619. Map<String, Object> _preferenceValues(MachineState value) => {
  620. 'brewTemperature': value.brewTemperature,
  621. 'steamTemperature': value.steamTemperature,
  622. 'preinfusionEnabled': value.preinfusionEnabled,
  623. 'preinfusionTime': value.preinfusionTime,
  624. 'preinfusionPauseTime': value.preinfusionPauseTime,
  625. 'valveClosedWhilePaused': value.valveClosedWhilePaused,
  626. 'output0': value.output0,
  627. 'output1': value.output1,
  628. 'output2': value.output2,
  629. 'installedAsTimer': value.installedAsTimer,
  630. 'powerButtonFlipsBack': value.powerButtonFlipsBack,
  631. 'proActivePercentage': value.proActivePercentage,
  632. 'autoShutoffMinutes': value.autoShutoffMinutes,
  633. 'maxShotTime': value.maxShotTime,
  634. 'continuousMode': value.continuousMode,
  635. 'wakeupEnabled': value.wakeupEnabled,
  636. 'wakeupTime': value.wakeupTime,
  637. 'shutdownEnabled': value.shutdownEnabled,
  638. 'shutdownTime': value.shutdownTime,
  639. 'pressureStart': value.pressureStart,
  640. 'pressureEnd': value.pressureEnd,
  641. 'pressurePeriod': value.pressurePeriod,
  642. 'pidP': value.pidP,
  643. 'pidI': value.pidI,
  644. 'pidD': value.pidD,
  645. 'pidIWindDownMin': value.pidIWindDownMin,
  646. 'pidIWindDownMax': value.pidIWindDownMax,
  647. 'pidPollingInterval': value.pidPollingInterval,
  648. };
  649. Future<bool> _persistPreference(String key, Object value) async {
  650. if (savePreference case final save?) return save(key, value);
  651. final prefs = await SharedPreferences.getInstance();
  652. return switch (value) {
  653. bool value => prefs.setBool(key, value),
  654. double value => prefs.setDouble(key, value),
  655. int value => prefs.setInt(key, value),
  656. String value => prefs.setString(key, value),
  657. _ => throw ArgumentError.value(value, key, 'Unsupported setting type'),
  658. };
  659. }
  660. Future<void> _updateSettings(
  661. Map<String, Object> requested, {
  662. bool omitV4Minimum = false,
  663. }) {
  664. if (!mounted) return Future<void>.value();
  665. if (_settingsLocked) {
  666. _reportCommandError(
  667. 'Settings are blocked while firmware is being updated.',
  668. );
  669. return Future<void>.value();
  670. }
  671. if (!_commandReady) {
  672. _reportCommandError('Settings not sent: connect to meCoffee first.');
  673. return Future<void>.value();
  674. }
  675. if (state.firmwareVersion.isEmpty) {
  676. _reportCommandError(
  677. 'Settings not sent: waiting for controller firmware identity.',
  678. );
  679. return Future<void>.value();
  680. }
  681. if (requested.values.any((value) => value is double && !value.isFinite)) {
  682. _reportCommandError('Settings must contain finite numbers.');
  683. return Future<void>.value();
  684. }
  685. final generation = _connectionGeneration;
  686. final operation = _settingsQueue.then((_) async {
  687. if (!mounted || generation != _connectionGeneration) {
  688. const message = 'Settings cancelled: Bluetooth connection changed.';
  689. if (mounted && state.commandError == null) {
  690. _reportCommandError(message);
  691. } else {
  692. _log(DiagnosticDirection.event, message);
  693. }
  694. return;
  695. }
  696. final values = Map<String, Object>.from(requested);
  697. if (state.isLegacyV4Firmware) {
  698. if (omitV4Minimum) values.remove('pd1imn');
  699. if (values.keys.any(
  700. const {
  701. 'o0',
  702. 'o1',
  703. 'o2',
  704. 'pwrflp',
  705. 'tmrosd',
  706. 'shtmx',
  707. 'pd1imn',
  708. }.contains,
  709. )) {
  710. _reportCommandError(
  711. 'These settings are not supported by V4 firmware.',
  712. );
  713. return;
  714. }
  715. }
  716. if (values.isEmpty) return;
  717. final commands = values.entries
  718. .map(
  719. (entry) => MeCoffeeProtocol.encodeSet(
  720. entry.key,
  721. entry.value,
  722. isLegacyV4: state.isLegacyV4Firmware,
  723. ),
  724. )
  725. .toList();
  726. if (!await _sendCommand(commands.join().codeUnits)) return;
  727. if (!mounted || generation != _connectionGeneration) return;
  728. var delivered = state;
  729. for (final command in commands) {
  730. delivered = MeCoffeeProtocol.parse(command, delivered);
  731. }
  732. final preferences = _preferenceValues(delivered);
  733. try {
  734. for (final key in values.keys) {
  735. final preferenceKey = _preferenceKeys[key]!;
  736. if (!await _persistPreference(
  737. preferenceKey,
  738. preferences[preferenceKey]!,
  739. )) {
  740. _reportCommandError(
  741. 'Settings delivered but could not be saved locally.',
  742. );
  743. return;
  744. }
  745. }
  746. } on Exception catch (error) {
  747. _reportCommandError(
  748. 'Settings delivered but could not be saved locally: $error',
  749. );
  750. return;
  751. }
  752. if (!mounted || generation != _connectionGeneration) return;
  753. var updated = state;
  754. for (final command in commands) {
  755. updated = MeCoffeeProtocol.parse(command, updated);
  756. }
  757. state = updated;
  758. });
  759. _settingsQueue = operation;
  760. return operation;
  761. }
  762. void _reportCommandError(String message) {
  763. if (!mounted) return;
  764. _log(DiagnosticDirection.event, message);
  765. state = state.copyWith(clearCommandError: true);
  766. state = state.copyWith(commandError: message);
  767. }
  768. Future<bool> _sendCommand(List<int> bytes, {bool initializing = false}) {
  769. final characteristic = _commandCharacteristic;
  770. final classic = _classicConnected;
  771. final generation = _connectionGeneration;
  772. if (_firmwareMode) {
  773. _reportCommandError(
  774. 'Settings are blocked while firmware is being updated.',
  775. );
  776. return Future<bool>.value(false);
  777. }
  778. if ((characteristic == null && !classic) ||
  779. (!initializing && !_commandReady)) {
  780. _reportCommandError('Settings not sent: connect to meCoffee first.');
  781. return Future<bool>.value(false);
  782. }
  783. final operation = _commandQueue.then((_) async {
  784. try {
  785. await _settingsLoaded;
  786. _log(DiagnosticDirection.sent, String.fromCharCodes(bytes).trim());
  787. for (var offset = 0; offset < bytes.length;) {
  788. if (!mounted ||
  789. generation != _connectionGeneration ||
  790. (classic
  791. ? !_classicConnected
  792. : characteristic != _commandCharacteristic ||
  793. characteristic!.device.isDisconnected)) {
  794. throw StateError(
  795. 'Bluetooth disconnected before settings were sent',
  796. );
  797. }
  798. final payloadSize = classic
  799. ? bytes.length
  800. : (characteristic!.device.mtuNow - 3).clamp(1, 512);
  801. final end = (offset + payloadSize).clamp(0, bytes.length);
  802. if (classic) {
  803. await _classicTransport
  804. .write(bytes.sublist(offset, end))
  805. .timeout(const Duration(seconds: 15));
  806. } else {
  807. await characteristic!.write(
  808. bytes.sublist(offset, end),
  809. withoutResponse: !characteristic.properties.write,
  810. );
  811. if (!characteristic.properties.write) {
  812. await Future<void>.delayed(const Duration(milliseconds: 20));
  813. }
  814. }
  815. offset = end;
  816. }
  817. if (!mounted || generation != _connectionGeneration) {
  818. throw StateError('Bluetooth disconnected while sending settings');
  819. }
  820. state = state.copyWith(clearCommandError: true);
  821. return true;
  822. } catch (e) {
  823. if (!initializing && mounted && generation == _connectionGeneration) {
  824. await _failConnection(characteristic?.device, e);
  825. }
  826. _reportCommandError(
  827. 'Settings not saved: $e. The machine may be partially updated.',
  828. );
  829. return false;
  830. }
  831. });
  832. // Queue the whole payload, not individual chunks, so commands cannot interleave.
  833. _commandQueue = operation.then((_) {});
  834. return operation;
  835. }
  836. Future<void> startScan() async {
  837. if (!mounted ||
  838. _scanActive ||
  839. _commandReady ||
  840. _settingsLocked ||
  841. _classicConnected ||
  842. state.connectionStatus == 'Connecting...') {
  843. return;
  844. }
  845. _scanActive = true;
  846. final generation = ++_scanGeneration;
  847. _reconnectTimer?.cancel();
  848. _reconnectTimer = null;
  849. _userDisconnected = false;
  850. try {
  851. final adapterState = await FlutterBluePlus.adapterState.first;
  852. if (!mounted || generation != _scanGeneration) return;
  853. if (adapterState != BluetoothAdapterState.on) {
  854. _cancelScanSubscriptions();
  855. state = state.copyWith(connectionStatus: 'Error: Bluetooth is off');
  856. return;
  857. }
  858. state = state.copyWith(connectionStatus: 'Scanning...');
  859. _scanStarted = true;
  860. await FlutterBluePlus.startScan(timeout: const Duration(seconds: 15));
  861. if (!mounted || generation != _scanGeneration) {
  862. return;
  863. }
  864. var foundDevice = false;
  865. _scanSubscription = FlutterBluePlus.onScanResults.listen(
  866. (results) {
  867. if (!mounted || generation != _scanGeneration || foundDevice) return;
  868. for (final result in results) {
  869. if (matchesMeCoffeeAdvertisement(
  870. name: result.device.platformName,
  871. advertisedName: result.advertisementData.advName,
  872. serviceUuids: result.advertisementData.serviceUuids,
  873. )) {
  874. foundDevice = true;
  875. unawaited(_connectScanResult(result.device));
  876. break;
  877. }
  878. }
  879. },
  880. onError: (Object error) {
  881. if (!mounted || generation != _scanGeneration) return;
  882. state = state.copyWith(
  883. connectionStatus: 'Error: ${_friendlyBtError(error)}',
  884. );
  885. unawaited(stopScan());
  886. },
  887. );
  888. _scanStateSubscription = FlutterBluePlus.isScanning.listen((scanning) {
  889. if (!mounted || generation != _scanGeneration) return;
  890. if (!scanning && !foundDevice) {
  891. _cancelScanSubscriptions();
  892. if (state.connectionStatus == 'Scanning...') {
  893. state = state.copyWith(connectionStatus: 'Not found');
  894. }
  895. }
  896. });
  897. } catch (e) {
  898. if (mounted && generation == _scanGeneration) {
  899. _cancelScanSubscriptions();
  900. state = state.copyWith(
  901. connectionStatus: 'Error: ${_friendlyBtError(e)}',
  902. );
  903. } else {
  904. FlutterError.reportError(
  905. FlutterErrorDetails(
  906. exception: e,
  907. library: 'meBarista Bluetooth',
  908. context: ErrorDescription('while stopping a cancelled scan'),
  909. ),
  910. );
  911. }
  912. }
  913. }
  914. Future<void> _connectScanResult(BluetoothDevice device) async {
  915. final stoppedGeneration = _scanGeneration + 1;
  916. if (await stopScan() &&
  917. mounted &&
  918. !_userDisconnected &&
  919. stoppedGeneration == _scanGeneration) {
  920. await connectToDevice(device);
  921. }
  922. }
  923. static String _friendlyBtError(Object e) {
  924. final msg = e.toString().toLowerCase();
  925. if (msg.contains('off') ||
  926. msg.contains('unknown') ||
  927. msg.contains('cbmanagerstate')) {
  928. return 'Bluetooth is off';
  929. }
  930. if (msg.contains('unauthorized') || msg.contains('permission')) {
  931. return 'Bluetooth permission denied';
  932. }
  933. return e.toString();
  934. }
  935. void _cancelScanSubscriptions() {
  936. _scanGeneration++;
  937. _scanActive = false;
  938. _scanStarted = false;
  939. _scanSubscription?.cancel();
  940. _scanSubscription = null;
  941. _scanStateSubscription?.cancel();
  942. _scanStateSubscription = null;
  943. }
  944. Future<bool> stopScan() async {
  945. final wasStarted = _scanStarted;
  946. _cancelScanSubscriptions();
  947. final generation = _scanGeneration;
  948. if (!wasStarted) return true;
  949. try {
  950. await FlutterBluePlus.stopScan();
  951. if (mounted &&
  952. generation == _scanGeneration &&
  953. state.connectionStatus == 'Scanning...') {
  954. state = state.copyWith(connectionStatus: 'Not found');
  955. }
  956. return true;
  957. } catch (e, stack) {
  958. if (mounted) {
  959. state = state.copyWith(
  960. connectionStatus: 'Error: ${_friendlyBtError(e)}',
  961. );
  962. } else {
  963. FlutterError.reportError(
  964. FlutterErrorDetails(
  965. exception: e,
  966. stack: stack,
  967. library: 'meBarista Bluetooth',
  968. context: ErrorDescription('while stopping a scan'),
  969. ),
  970. );
  971. }
  972. return false;
  973. }
  974. }
  975. Future<void> connectToDevice(BluetoothDevice device) async {
  976. if (state.connectionStatus == 'Connecting...' ||
  977. _commandReady ||
  978. _settingsLocked) {
  979. return;
  980. }
  981. _reconnectTimer?.cancel();
  982. _reconnectTimer = null;
  983. _userDisconnected = false;
  984. _clearConnection();
  985. final generation = _connectionGeneration;
  986. _connectedDevice = device;
  987. state = state.copyWith(
  988. connectionStatus: 'Connecting...',
  989. transportName: 'BLE',
  990. firmwareVersion: '',
  991. isLegacyV4Firmware: false,
  992. clearCommandError: true,
  993. );
  994. try {
  995. if (!await stopScan()) {
  996. _clearConnection();
  997. return;
  998. }
  999. await _settingsLoaded;
  1000. if (!mounted || generation != _connectionGeneration) return;
  1001. await device.connect();
  1002. if (!mounted || generation != _connectionGeneration) return;
  1003. _connectionStateSubscription = device.connectionState.listen((
  1004. connectionState,
  1005. ) {
  1006. if (!mounted || generation != _connectionGeneration) return;
  1007. if (connectionState == BluetoothConnectionState.disconnected) {
  1008. _clearConnection();
  1009. state = state.copyWith(
  1010. connectionStatus: 'Disconnected',
  1011. isBrewing: false,
  1012. );
  1013. _scheduleReconnect();
  1014. }
  1015. });
  1016. await _discoverServices(device);
  1017. if (!mounted || generation != _connectionGeneration) return;
  1018. await Future<void>.delayed(const Duration(milliseconds: 500));
  1019. if (!mounted || generation != _connectionGeneration) return;
  1020. if (!await _sendInitializationSequence()) {
  1021. throw StateError(state.commandError ?? 'Initialization failed');
  1022. }
  1023. if (!mounted || generation != _connectionGeneration) return;
  1024. _commandReady = true;
  1025. state = state.copyWith(connectionStatus: 'Connected');
  1026. _watchFreshness();
  1027. _log(DiagnosticDirection.event, 'Connected via BLE');
  1028. } catch (e) {
  1029. if (mounted && generation == _connectionGeneration) {
  1030. await _failConnection(device, e);
  1031. }
  1032. }
  1033. }
  1034. Future<bool> _sendInitializationSequence() async {
  1035. final now = DateTime.now();
  1036. final secondsPassed = now.hour * 3600 + now.minute * 60 + now.second;
  1037. if (!await _sendCommand(
  1038. "\ncmd clock set $secondsPassed\n".codeUnits,
  1039. initializing: true,
  1040. )) {
  1041. return false;
  1042. }
  1043. if (!await _sendCommand("\ncmd uname OK\n".codeUnits, initializing: true)) {
  1044. return false;
  1045. }
  1046. return _sendCommand("\ncmd dump\n".codeUnits, initializing: true);
  1047. }
  1048. Future<void> _discoverServices(BluetoothDevice device) async {
  1049. final services = await device.discoverServices();
  1050. if (_connectedDevice != device || device.isDisconnected) {
  1051. throw StateError('Bluetooth disconnected during service discovery');
  1052. }
  1053. BluetoothCharacteristic? preferred;
  1054. for (final service in services) {
  1055. final serviceId = service.uuid.str128.toLowerCase();
  1056. if (!serviceId.startsWith(_meCoffeeServiceUuidPrefix)) continue;
  1057. for (final characteristic in service.characteristics) {
  1058. final charId = characteristic.uuid.str128.toLowerCase();
  1059. if (charId.startsWith(_meCoffeeCharacteristicUuidPrefix) &&
  1060. (characteristic.properties.write ||
  1061. characteristic.properties.writeWithoutResponse) &&
  1062. (characteristic.properties.notify ||
  1063. characteristic.properties.indicate)) {
  1064. preferred = characteristic;
  1065. break;
  1066. }
  1067. }
  1068. if (preferred != null) break;
  1069. }
  1070. if (preferred != null) {
  1071. await _attachCharacteristic(preferred);
  1072. if (_connectedDevice != device || device.isDisconnected) {
  1073. throw StateError('Bluetooth disconnected during service discovery');
  1074. }
  1075. _commandCharacteristic = preferred;
  1076. return;
  1077. }
  1078. // Fallback still requires both a write path and a telemetry path.
  1079. BluetoothCharacteristic? writable;
  1080. var hasNotifications = false;
  1081. for (final service in services) {
  1082. for (final characteristic in service.characteristics) {
  1083. if (writable == null &&
  1084. (characteristic.properties.write ||
  1085. characteristic.properties.writeWithoutResponse)) {
  1086. writable = characteristic;
  1087. }
  1088. if (characteristic.properties.notify ||
  1089. characteristic.properties.indicate) {
  1090. await _attachCharacteristic(characteristic);
  1091. hasNotifications = true;
  1092. }
  1093. }
  1094. }
  1095. if (writable == null || !hasNotifications) {
  1096. throw StateError(
  1097. 'No usable meCoffee write/notification characteristics found',
  1098. );
  1099. }
  1100. if (_connectedDevice != device || device.isDisconnected) {
  1101. throw StateError('Bluetooth disconnected during service discovery');
  1102. }
  1103. _commandCharacteristic = writable;
  1104. }
  1105. Future<void> _attachCharacteristic(
  1106. BluetoothCharacteristic characteristic,
  1107. ) async {
  1108. final generation = _connectionGeneration;
  1109. if (characteristic.properties.notify ||
  1110. characteristic.properties.indicate) {
  1111. final subscription = characteristic.onValueReceived.listen(
  1112. (data) {
  1113. if (mounted && generation == _connectionGeneration) _handleData(data);
  1114. },
  1115. onError: (Object error) {
  1116. if (mounted && generation == _connectionGeneration) {
  1117. unawaited(_failConnection(characteristic.device, error));
  1118. }
  1119. },
  1120. );
  1121. _notificationSubscriptions.add(subscription);
  1122. await characteristic.setNotifyValue(true);
  1123. if (generation != _connectionGeneration) {
  1124. throw StateError('Bluetooth disconnected during notification setup');
  1125. }
  1126. }
  1127. }
  1128. void _clearConnection() {
  1129. _connectionGeneration++;
  1130. _lastPidAt = null;
  1131. _reportedSettings.clear();
  1132. _pendingFirmwareSettings.clear();
  1133. _commandReady = false;
  1134. _connectedDevice = null;
  1135. _commandCharacteristic = null;
  1136. _classicConnected = false;
  1137. _classicDataSubscription?.cancel();
  1138. _classicDataSubscription = null;
  1139. _classicEventSubscription?.cancel();
  1140. _classicEventSubscription = null;
  1141. _freshnessTimer?.cancel();
  1142. _freshnessTimer = null;
  1143. _connectionStateSubscription?.cancel();
  1144. _connectionStateSubscription = null;
  1145. for (final subscription in _notificationSubscriptions) {
  1146. subscription.cancel();
  1147. }
  1148. _notificationSubscriptions.clear();
  1149. _stopShotTimer();
  1150. _inputBuffer = '';
  1151. if (mounted) {
  1152. state = state.copyWith(
  1153. telemetryStale: true,
  1154. clearLastTelemetry: true,
  1155. isHeating: false,
  1156. heatingPower: 0,
  1157. );
  1158. }
  1159. }
  1160. Future<void> _failConnection(BluetoothDevice? device, Object error) async {
  1161. final classic = _classicConnected || _classicDataSubscription != null;
  1162. _clearConnection();
  1163. final generation = _connectionGeneration;
  1164. var message = error.toString();
  1165. if (mounted) {
  1166. state = state.copyWith(
  1167. connectionStatus: 'Error: $message',
  1168. isBrewing: false,
  1169. );
  1170. }
  1171. try {
  1172. if (classic) await _classicTransport.disconnect();
  1173. if (device != null) await device.disconnect();
  1174. } catch (disconnectError) {
  1175. message = '$message; disconnect failed: $disconnectError';
  1176. }
  1177. if (mounted && generation == _connectionGeneration) {
  1178. state = state.copyWith(
  1179. connectionStatus: 'Error: $message',
  1180. isBrewing: false,
  1181. );
  1182. _log(DiagnosticDirection.event, 'Connection failed: $message');
  1183. }
  1184. }
  1185. Timer? _shotTimer;
  1186. String _inputBuffer = "";
  1187. void _handleData(List<int> data) {
  1188. if (!mounted) return;
  1189. if (_firmwareMode) {
  1190. _firmwareBytes?.add(List<int>.from(data));
  1191. return;
  1192. }
  1193. _inputBuffer += String.fromCharCodes(data);
  1194. if (_inputBuffer.length > 8192 && !_inputBuffer.contains('\n')) {
  1195. _inputBuffer = '';
  1196. _log(DiagnosticDirection.event, 'Discarded oversized unterminated frame');
  1197. return;
  1198. }
  1199. while (_inputBuffer.contains('\n')) {
  1200. int index = _inputBuffer.indexOf('\n');
  1201. String line = _inputBuffer.substring(0, index).trim();
  1202. _inputBuffer = _inputBuffer.substring(index + 1);
  1203. if (line.isNotEmpty) {
  1204. _log(DiagnosticDirection.received, line);
  1205. final fields = line.split(RegExp(r'\s+'));
  1206. final settingKey = fields.first == 'get' && fields.length >= 3
  1207. ? fields[1]
  1208. : fields.first == 'cmd' &&
  1209. fields.length >= 4 &&
  1210. (fields[1] == 'get' || fields[1] == 'set')
  1211. ? fields[2]
  1212. : null;
  1213. // A dump can arrive before uname; do not guess V4 units.
  1214. if (state.firmwareVersion.isEmpty &&
  1215. _firmwareScaledKeys.contains(settingKey)) {
  1216. _pendingFirmwareSettings[settingKey == 'pd1imm'
  1217. ? 'pd1imn'
  1218. : settingKey!] =
  1219. line;
  1220. continue;
  1221. }
  1222. final oldBrewing = state.isBrewing;
  1223. var parsed = MeCoffeeProtocol.parse(line, state);
  1224. final valid = !identical(parsed, state);
  1225. if (valid &&
  1226. parsed.firmwareVersion.isNotEmpty &&
  1227. state.firmwareVersion.isEmpty) {
  1228. for (final entry in _pendingFirmwareSettings.entries) {
  1229. final replayed = MeCoffeeProtocol.parse(entry.value, parsed);
  1230. if (!identical(replayed, parsed)) {
  1231. _reportedSettings.add(entry.key);
  1232. }
  1233. parsed = replayed;
  1234. }
  1235. _pendingFirmwareSettings.clear();
  1236. }
  1237. if (valid && fields.first == 'pid') {
  1238. if (!state.telemetryStale) _lastPidAt = DateTime.now();
  1239. }
  1240. if (state.telemetryStale &&
  1241. (fields.first == 'pid' || fields.first == 'sht')) {
  1242. parsed = parsed.copyWith(
  1243. isHeating: false,
  1244. heatingPower: 0,
  1245. isBrewing: false,
  1246. );
  1247. }
  1248. if (valid && fields.first == 'get' && fields.length >= 3) {
  1249. _reportedSettings.add(fields[1]);
  1250. } else if (valid &&
  1251. fields.first == 'cmd' &&
  1252. fields.length >= 4 &&
  1253. fields[1] == 'get') {
  1254. _reportedSettings.add(fields[2]);
  1255. }
  1256. state = parsed;
  1257. if (valid && (line.startsWith('tmp ') || line.startsWith('T '))) {
  1258. final now = DateTime.now();
  1259. final fields = line.split(RegExp(r'\s+'));
  1260. final rawSensor2 = fields.length >= 5
  1261. ? double.tryParse(fields[4])
  1262. : null;
  1263. final sensor2 =
  1264. rawSensor2 != null && rawSensor2 > 5 && rawSensor2 < 20000
  1265. ? rawSensor2 / 100
  1266. : null;
  1267. final history = List<double>.from(state.temperatureHistory);
  1268. history.add(state.temperature);
  1269. if (history.length > historyLimit) history.removeAt(0);
  1270. final history2 = List<double>.from(state.sensor2TemperatureHistory);
  1271. // Only record sensor2 if we have a valid (non-zero) reading.
  1272. if (sensor2 != null) {
  1273. history2.add(sensor2);
  1274. if (history2.length > historyLimit) history2.removeAt(0);
  1275. }
  1276. final samples = [
  1277. ...state.temperatureSamples,
  1278. TemperatureSample(
  1279. timestamp: now,
  1280. boiler: state.temperature,
  1281. target: state.targetTemperature,
  1282. sensor2: sensor2,
  1283. ),
  1284. ];
  1285. if (samples.length > historyLimit) samples.removeAt(0);
  1286. state = state.copyWith(
  1287. temperatureHistory: history,
  1288. sensor2TemperatureHistory: history2,
  1289. sensor2Temperature: sensor2 ?? 0,
  1290. temperatureSamples: List.unmodifiable(samples),
  1291. lastTelemetryAt: now,
  1292. telemetryStale: false,
  1293. );
  1294. _watchFreshness();
  1295. } else if (!valid &&
  1296. (line.startsWith('tmp ') ||
  1297. line.startsWith('T ') ||
  1298. line.startsWith('pid ') ||
  1299. line.startsWith('sht '))) {
  1300. _log(DiagnosticDirection.event, 'Ignored malformed telemetry: $line');
  1301. }
  1302. // Shot Timer Logic
  1303. if (state.isBrewing && !oldBrewing) {
  1304. // Started brewing (triggered by 'sht 0')
  1305. _startShotTimer();
  1306. } else if (!state.isBrewing && oldBrewing) {
  1307. // Stopped brewing (triggered by 'sht <final_time>')
  1308. _stopShotTimer();
  1309. _incrementShotCount();
  1310. }
  1311. }
  1312. }
  1313. }
  1314. void _startShotTimer() {
  1315. if (state.telemetryStale) return;
  1316. _shotTimer?.cancel();
  1317. state = state.copyWith(shotTimer: 0);
  1318. _shotTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
  1319. if (!mounted || state.telemetryStale) {
  1320. timer.cancel();
  1321. return;
  1322. }
  1323. state = state.copyWith(shotTimer: state.shotTimer + 1);
  1324. });
  1325. }
  1326. void _stopShotTimer() {
  1327. _shotTimer?.cancel();
  1328. _shotTimer = null;
  1329. }
  1330. Future<void> disconnect() async {
  1331. if (state.firmwareUpdating) {
  1332. _reportCommandError('Cannot disconnect while firmware is being updated.');
  1333. return;
  1334. }
  1335. _userDisconnected = true;
  1336. _log(DiagnosticDirection.event, 'Disconnect requested by user');
  1337. _reconnectTimer?.cancel();
  1338. _reconnectTimer = null;
  1339. final device = _connectedDevice;
  1340. final classic = _classicConnected || _classicDataSubscription != null;
  1341. _clearConnection();
  1342. state = state.copyWith(connectionStatus: 'Disconnected', isBrewing: false);
  1343. await stopScan();
  1344. if (classic) {
  1345. try {
  1346. await _classicTransport.disconnect();
  1347. } catch (e) {
  1348. if (mounted) state = state.copyWith(connectionStatus: 'Error: $e');
  1349. _log(DiagnosticDirection.event, 'Classic disconnect failed: $e');
  1350. }
  1351. }
  1352. if (device != null) {
  1353. try {
  1354. await device.disconnect(queue: false);
  1355. } catch (e) {
  1356. if (mounted) {
  1357. state = state.copyWith(connectionStatus: 'Error: $e');
  1358. }
  1359. _log(DiagnosticDirection.event, 'BLE disconnect failed: $e');
  1360. }
  1361. }
  1362. if (mounted && state.connectionStatus == 'Disconnected') {
  1363. _log(DiagnosticDirection.event, 'Disconnected by user');
  1364. }
  1365. }
  1366. @override
  1367. void dispose() {
  1368. _userDisconnected = true;
  1369. _reconnectTimer?.cancel();
  1370. final device = _connectedDevice;
  1371. unawaited(stopScan());
  1372. _clearConnection();
  1373. unawaited(
  1374. _classicTransport.dispose().catchError((Object error, StackTrace stack) {
  1375. FlutterError.reportError(
  1376. FlutterErrorDetails(
  1377. exception: error,
  1378. stack: stack,
  1379. library: 'meBarista Bluetooth',
  1380. context: ErrorDescription('while disposing the Classic connection'),
  1381. ),
  1382. );
  1383. }),
  1384. );
  1385. if (device != null) {
  1386. unawaited(
  1387. device.disconnect(queue: false).catchError((
  1388. Object error,
  1389. StackTrace stack,
  1390. ) {
  1391. FlutterError.reportError(
  1392. FlutterErrorDetails(
  1393. exception: error,
  1394. stack: stack,
  1395. library: 'meBarista Bluetooth',
  1396. context: ErrorDescription(
  1397. 'while disposing the Bluetooth connection',
  1398. ),
  1399. ),
  1400. );
  1401. }),
  1402. );
  1403. }
  1404. super.dispose();
  1405. }
  1406. }