bluetooth_service.dart 50 KB

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