bluetooth_service.dart 49 KB

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