| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493 |
- import 'dart:async';
- import 'package:flutter/foundation.dart';
- import 'package:flutter_blue_plus/flutter_blue_plus.dart';
- import 'package:flutter_riverpod/flutter_riverpod.dart';
- import 'package:flutter/services.dart';
- import 'package:shared_preferences/shared_preferences.dart';
- import '../models/diagnostic_entry.dart';
- import '../models/machine_state.dart';
- import '../models/temperature_sample.dart';
- import 'classic_bluetooth_transport.dart';
- import 'firmware_updater.dart';
- import 'me_coffee_protocol.dart';
- final bluetoothServiceProvider =
- StateNotifierProvider<MeCoffeeService, MachineState>((ref) {
- return MeCoffeeService();
- });
- class MeCoffeeService extends StateNotifier<MachineState> {
- static const String _meCoffeeServiceUuidPrefix = '0000ffe0';
- static const String _meCoffeeCharacteristicUuidPrefix = '0000ffe1';
- MeCoffeeService({
- ClassicBluetoothTransport? classicTransport,
- Future<void> Function(Duration)? firmwareDelay,
- this.savePreference,
- this.freshnessTimeout = const Duration(seconds: 3),
- }) : _classicTransport = classicTransport ?? ClassicBluetoothTransport(),
- _firmwareDelay = firmwareDelay ?? Future<void>.delayed,
- super(MachineState()) {
- _settingsLoaded = _loadSettings();
- }
- final Duration freshnessTimeout;
- final ClassicBluetoothTransport _classicTransport;
- final Future<void> Function(Duration) _firmwareDelay;
- final Future<bool> Function(String, Object)? savePreference;
- StreamSubscription<List<int>>? _classicDataSubscription;
- StreamSubscription<ClassicBluetoothEvent>? _classicEventSubscription;
- ClassicBluetoothDevice? _classicDevice;
- bool _classicConnected = false;
- Timer? _freshnessTimer;
- StreamController<List<int>>? _firmwareBytes;
- bool _firmwareMode = false;
- bool _settingsLocked = false;
- DateTime? _lastPidAt;
- final _reportedSettings = <String>{};
- final _pendingFirmwareSettings = <String, String>{};
- static const _firmwareScaledKeys = {
- 'pd1i',
- 'pd1imn',
- 'pd1imm',
- 'pd1imx',
- 'pistrt',
- 'piprd',
- };
- static const int historyLimit = 5000;
- static const int diagnosticLimit = 1000;
- @visibleForTesting
- static bool matchesMeCoffeeAdvertisement({
- required String name,
- required String advertisedName,
- required Iterable<Guid> serviceUuids,
- }) =>
- serviceUuids.any(
- (uuid) =>
- uuid.str128.toLowerCase().startsWith(_meCoffeeServiceUuidPrefix),
- ) ||
- name.toLowerCase().contains('mecoffee') ||
- advertisedName.toLowerCase().contains('mecoffee') ||
- name.toLowerCase() == 'misssilvia';
- bool get supportsClassic => _classicTransport.isSupported;
- bool get _machineSafeForFirmware =>
- _classicConnected &&
- _commandReady &&
- !state.isBrewing &&
- !state.isHeating &&
- _lastPidAt != null &&
- DateTime.now().difference(_lastPidAt!) < freshnessTimeout &&
- !state.telemetryStale &&
- state.temperature <= 50 &&
- RegExp(
- r'\bmeCoffee\b',
- caseSensitive: false,
- ).hasMatch(state.firmwareVersion);
- bool get canUpdateFirmware =>
- mounted && !_settingsLocked && _machineSafeForFirmware;
- late final Future<void> _settingsLoaded;
- StreamSubscription<List<ScanResult>>? _scanSubscription;
- StreamSubscription<bool>? _scanStateSubscription;
- bool _scanActive = false;
- bool _scanStarted = false;
- int _scanGeneration = 0;
- StreamSubscription<BluetoothConnectionState>? _connectionStateSubscription;
- final _notificationSubscriptions = <StreamSubscription<List<int>>>[];
- BluetoothDevice? _connectedDevice;
- BluetoothCharacteristic? _commandCharacteristic;
- bool _commandReady = false;
- int _connectionGeneration = 0;
- Future<void> _commandQueue = Future<void>.value();
- Future<void> _settingsQueue = Future<void>.value();
- Future<void> _setpointQueue = Future<void>.value();
- // Auto-reconnect: scheduled after an unexpected disconnection.
- Timer? _reconnectTimer;
- bool _userDisconnected = false;
- void _log(DiagnosticDirection direction, String message) {
- if (!mounted) return;
- final entries = [
- ...state.diagnosticLog,
- DiagnosticEntry(
- timestamp: DateTime.now(),
- direction: direction,
- message: message.length > 2048
- ? '${message.substring(0, 2048)}...'
- : message,
- ),
- ];
- if (entries.length > diagnosticLimit) entries.removeAt(0);
- state = state.copyWith(diagnosticLog: List.unmodifiable(entries));
- }
- String exportDiagnosticLog() =>
- 'meBarista diagnostics\n'
- 'Connection: ${state.connectionStatus}\n'
- 'Transport: ${state.transportName}\n'
- 'Firmware: ${state.firmwareVersion}\n'
- 'Temperature telemetry: ${state.telemetryStale ? 'stale' : 'live'}\n'
- '${state.diagnosticLog.map((entry) => entry.text).join('\n')}';
- void clearDiagnosticLog() {
- state = state.copyWith(diagnosticLog: const []);
- }
- void _watchFreshness() {
- _freshnessTimer?.cancel();
- final generation = _connectionGeneration;
- _freshnessTimer = Timer(freshnessTimeout, () {
- if (!mounted || generation != _connectionGeneration) return;
- _stopShotTimer();
- _lastPidAt = null;
- state = state.copyWith(
- telemetryStale: true,
- isHeating: false,
- heatingPower: 0,
- isBrewing: false,
- );
- _log(DiagnosticDirection.event, 'Temperature telemetry timed out');
- });
- }
- void _scheduleReconnect({ClassicBluetoothDevice? classicDevice}) {
- if (_userDisconnected || _settingsLocked || !mounted) return;
- state = state.copyWith(connectionStatus: 'Reconnecting...');
- _reconnectTimer?.cancel();
- _reconnectTimer = Timer(const Duration(seconds: 30), () {
- _reconnectTimer = null;
- if (!mounted || _userDisconnected) return;
- if (classicDevice != null) {
- unawaited(connectToClassicDevice(classicDevice));
- } else {
- unawaited(startScan());
- }
- });
- }
- Future<List<ClassicBluetoothDevice>> listClassicDevices() async {
- try {
- return await _classicTransport.listBondedDevices();
- } catch (error) {
- _reportCommandError('Unable to list paired Bluetooth devices: $error');
- rethrow;
- }
- }
- void _listenClassic(int generation) {
- _classicDataSubscription = _classicTransport.received.listen(
- (data) {
- if (mounted && generation == _connectionGeneration) _handleData(data);
- },
- onError: (Object error) {
- if (!mounted || generation != _connectionGeneration) return;
- _firmwareBytes?.addError(error);
- if (!_firmwareMode) unawaited(_failConnection(null, error));
- },
- );
- _classicEventSubscription = _classicTransport.connectionEvents.listen(
- (event) {
- if (!mounted || generation != _connectionGeneration) return;
- if (event.type == ClassicBluetoothEventType.connected) {
- _classicConnected = true;
- return;
- }
- final error = StateError(
- event.message ?? 'Bluetooth Classic disconnected',
- );
- if (_firmwareMode) {
- _classicConnected = false;
- _firmwareBytes?.addError(error);
- return;
- }
- final classic = _classicDevice;
- _log(DiagnosticDirection.event, error.toString());
- _clearConnection();
- state = state.copyWith(
- connectionStatus: 'Disconnected',
- isBrewing: false,
- );
- if (!event.explicitDisconnect) {
- _scheduleReconnect(classicDevice: classic);
- }
- },
- onError: (Object error) {
- if (!mounted || generation != _connectionGeneration) return;
- _firmwareBytes?.addError(error);
- if (!_firmwareMode) unawaited(_failConnection(null, error));
- },
- );
- }
- Future<void> connectToClassicDevice(ClassicBluetoothDevice device) async {
- if (_commandReady ||
- state.connectionStatus == 'Connecting...' ||
- _settingsLocked) {
- return;
- }
- _reconnectTimer?.cancel();
- _reconnectTimer = null;
- _userDisconnected = false;
- _clearConnection();
- _classicDevice = device;
- final generation = _connectionGeneration;
- state = state.copyWith(
- connectionStatus: 'Connecting...',
- transportName: 'Bluetooth Classic',
- firmwareVersion: '',
- isLegacyV4Firmware: false,
- clearCommandError: true,
- );
- try {
- if (!await stopScan()) return;
- await _settingsLoaded;
- if (!mounted || generation != _connectionGeneration) return;
- _listenClassic(generation);
- await _classicTransport.connect(device.address);
- if (!mounted || generation != _connectionGeneration) return;
- _classicConnected = true;
- if (!await _sendInitializationSequence()) {
- throw StateError(state.commandError ?? 'Initialization failed');
- }
- if (!mounted || generation != _connectionGeneration) return;
- _commandReady = true;
- state = state.copyWith(connectionStatus: 'Connected');
- _watchFreshness();
- _log(DiagnosticDirection.event, 'Connected via Bluetooth Classic');
- } catch (error) {
- if (mounted && generation == _connectionGeneration) {
- await _failConnection(null, error);
- }
- }
- }
- Future<void> updateFirmware() async {
- if (!canUpdateFirmware) {
- _reportCommandError(
- 'Firmware updates require a live Bluetooth Classic connection to '
- 'meCoffee, an idle machine with heating off, and a boiler at or below 50 C.',
- );
- return;
- }
- final classic = _classicDevice!;
- final generation = _connectionGeneration;
- // Validate the bundled image before touching the controller.
- late final IntelHexFirmware image;
- try {
- image = IntelHexFirmware.parse(
- await rootBundle.loadString(
- 'meBarista_for_Android/assets/meCoffee-V10.hex',
- ),
- );
- } catch (error) {
- _reportCommandError('Cannot load firmware: $error');
- return;
- }
- if (!mounted ||
- generation != _connectionGeneration ||
- !canUpdateFirmware ||
- classic != _classicDevice) {
- _reportCommandError(
- 'Connection or machine state changed before updating.',
- );
- return;
- }
- _settingsLocked = true;
- _reconnectTimer?.cancel();
- state = state.copyWith(
- firmwareUpdating: true,
- firmwareProgress: 0,
- firmwareUpdateStatus: 'Waiting for settings to finish...',
- clearCommandError: true,
- );
- _log(DiagnosticDirection.event, 'Starting confirmed V10 firmware update');
- var resetStarted = false;
- try {
- await _settingsQueue.timeout(const Duration(seconds: 15));
- await _commandQueue.timeout(const Duration(seconds: 15));
- if (!mounted ||
- generation != _connectionGeneration ||
- !_machineSafeForFirmware ||
- classic != _classicDevice) {
- if (mounted) {
- state = state.copyWith(
- firmwareUpdating: false,
- firmwareUpdateStatus: 'Update cancelled before controller reset.',
- );
- _reportCommandError(
- 'Connection or machine state changed before updating.',
- );
- }
- return;
- }
- _firmwareMode = true;
- _commandReady = false;
- _freshnessTimer?.cancel();
- state = state.copyWith(firmwareUpdateStatus: 'Entering bootloader...');
- resetStarted = true;
- await _classicTransport
- .write('\ncmd reset en\n'.codeUnits)
- .timeout(const Duration(seconds: 5));
- await _firmwareDelay(const Duration(seconds: 5));
- if (!_classicConnected) {
- _clearConnection();
- await _classicTransport.disconnect();
- _listenClassic(_connectionGeneration);
- await _classicTransport.connect(classic.address);
- _classicConnected = true;
- }
- await _classicTransport
- .write('\ncmd reset en\n'.codeUnits)
- .timeout(const Duration(seconds: 5));
- await _firmwareDelay(const Duration(seconds: 1));
- _clearConnection();
- await _classicTransport.disconnect();
- await _firmwareDelay(const Duration(seconds: 1));
- if (!mounted) throw StateError('Firmware update interrupted');
- _firmwareBytes = StreamController<List<int>>.broadcast();
- _listenClassic(_connectionGeneration);
- await _classicTransport.connect(classic.address);
- _classicConnected = true;
- state = state.copyWith(
- firmwareUpdateStatus: 'Programming and verifying...',
- );
- final updater = FirmwareUpdater(
- write: (bytes) async {
- if (!_classicConnected) throw StateError('Bootloader disconnected');
- await _classicTransport.write(bytes);
- },
- received: _firmwareBytes!.stream,
- );
- try {
- await updater.flash(
- image,
- onProgress: (progress) {
- if (mounted) state = state.copyWith(firmwareProgress: progress);
- },
- );
- } finally {
- await updater.dispose();
- }
- if (!mounted) throw StateError('Firmware update interrupted');
- state = state.copyWith(
- firmwareUpdateStatus: 'Firmware verified. Reconnecting...',
- firmwareProgress: 1,
- );
- _log(DiagnosticDirection.event, 'Firmware programmed and verified');
- _clearConnection();
- await _classicTransport.disconnect();
- _firmwareMode = false;
- await _firmwareDelay(const Duration(seconds: 2));
- if (mounted) {
- _settingsLocked = false;
- state = state.copyWith(
- firmwareUpdating: false,
- connectionStatus: 'Disconnected',
- );
- await connectToClassicDevice(classic);
- if (!mounted) return;
- state = state.copyWith(
- firmwareUpdateStatus: state.connectionStatus == 'Connected'
- ? 'V10 firmware programmed and verified.'
- : 'Firmware verified; reconnect to read controller settings.',
- );
- }
- } catch (error) {
- if (!resetStarted) {
- if (mounted) {
- state = state.copyWith(
- firmwareUpdating: false,
- firmwareUpdateStatus: 'Update cancelled before controller reset.',
- );
- _reportCommandError('Cannot prepare firmware update: $error');
- }
- return;
- }
- _clearConnection();
- try {
- await _classicTransport.disconnect();
- } catch (disconnectError) {
- _log(
- DiagnosticDirection.event,
- 'Bootloader disconnect failed: $disconnectError',
- );
- }
- if (mounted) {
- state = state.copyWith(
- firmwareUpdating: false,
- connectionStatus: 'Error: Firmware update failed',
- firmwareUpdateStatus: 'Update failed: $error',
- );
- _reportCommandError(
- 'Firmware update failed: $error. Do not brew; the controller may '
- 'require bootloader recovery before it can be used.',
- );
- }
- } finally {
- _firmwareMode = false;
- _settingsLocked = false;
- await _firmwareBytes?.close();
- _firmwareBytes = null;
- }
- }
- Future<void> _loadSettings() async {
- final prefs = await SharedPreferences.getInstance();
- if (!mounted) return;
- final brewTemp = prefs.getDouble('brewTemperature') ?? 101.0;
- state = state.copyWith(
- brewTemperature: brewTemp,
- steamTemperature: prefs.getDouble('steamTemperature') ?? 125.0,
- preinfusionEnabled: prefs.getBool('preinfusionEnabled') ?? true,
- preinfusionTime: prefs.getDouble('preinfusionTime') ?? 3.0,
- preinfusionPauseTime: prefs.getDouble('preinfusionPauseTime') ?? 3.0,
- // preinfusionPower has no corresponding protocol key; retained only for local display
- preinfusionPower: prefs.getInt('preinfusionPower') ?? 100,
- targetTemperature: brewTemp,
- pidP: prefs.getDouble('pidP') ?? 20.0,
- pidI: prefs.getDouble('pidI') ?? 0.3,
- pidD: prefs.getDouble('pidD') ?? 128.0,
- pidIWindDownMin: prefs.getDouble('pidIWindDownMin') ?? 0.0,
- pidIWindDownMax: prefs.getDouble('pidIWindDownMax') ?? 20.0,
- pidPollingInterval: prefs.getInt('pidPollingInterval') ?? 1000,
- shotCounter: prefs.getInt('shotCounter') ?? 0,
- grinderCounter: prefs.getInt('grinderCounter') ?? 0,
- pressureStart: prefs.getInt('pressureStart') ?? 100,
- pressureEnd: prefs.getInt('pressureEnd') ?? 100,
- pressurePeriod: prefs.getInt('pressurePeriod') ?? 25,
- valveClosedWhilePaused: prefs.getBool('valveClosedWhilePaused') ?? false,
- proActivePercentage: prefs.getInt('proActivePercentage') ?? 33,
- temperatureOffset: prefs.getDouble('temperatureOffset') ?? 0.0,
- autoShutoffMinutes: prefs.getInt('autoShutoffMinutes') ?? 60,
- wakeupEnabled: prefs.getBool('wakeupEnabled') ?? false,
- wakeupTime: prefs.getString('wakeupTime') ?? "07:00",
- shutdownEnabled: prefs.getBool('shutdownEnabled') ?? false,
- shutdownTime: prefs.getString('shutdownTime') ?? "22:00",
- output0: prefs.getInt('output0') ?? 112,
- output1: prefs.getInt('output1') ?? 98,
- output2: prefs.getInt('output2') ?? 118,
- installedAsTimer: prefs.getBool('installedAsTimer') ?? false,
- powerButtonFlipsBack: prefs.getBool('powerButtonFlipsBack') ?? false,
- maxShotTime: prefs.getInt('maxShotTime') ?? 60,
- continuousMode: prefs.getBool('continuousMode') ?? false,
- );
- }
- Future<void> updatePreinfusion(
- bool enabled,
- double time,
- double pause,
- bool closeValve,
- ) => updatePreinfusionSettings(
- enabled: enabled,
- time: time,
- pause: pause,
- closeValve: closeValve,
- );
- Future<void> updatePreinfusionSettings({
- bool? enabled,
- double? time,
- double? pause,
- bool? closeValve,
- }) => _updateSettings({
- 'pinbl': ?enabled,
- 'pistrt': ?time,
- 'piprd': ?pause,
- 'pivlv': ?closeValve,
- });
- Future<void> updateHardware(int o0, int o1, int o2, bool timer, bool flips) =>
- updateHardwareSettings(
- output0: o0,
- output1: o1,
- output2: o2,
- timer: timer,
- flips: flips,
- );
- Future<void> updateHardwareSettings({
- int? output0,
- int? output1,
- int? output2,
- bool? timer,
- bool? flips,
- }) => _updateSettings({
- 'o0': ?output0,
- 'o1': ?output1,
- 'o2': ?output2,
- 'tmrpwr': ?timer,
- 'pwrflp': ?flips,
- });
- Future<void> updateInstalledAsTimer(bool enabled) =>
- _updateSettings({'tmrpwr': enabled});
- Future<void> updateProActive(int percentage) =>
- _updateSettings({'tmppap': percentage});
- Future<void> updateOffset(double offset) =>
- _updateSettings({'tmpoff': offset});
- Future<void> updateAutoShutoff(int minutes) =>
- _updateSettings({'tmrosd': minutes});
- Future<void> updateMaxShotTime(int seconds) =>
- _updateSettings({'shtmx': seconds});
- Future<void> updateContinuousMode(bool enabled) =>
- _updateSettings({'tmpcntns': enabled});
- Future<void> updateSchedule({
- bool? wEnabled,
- String? wTime,
- bool? sEnabled,
- String? sTime,
- }) => _updateSettings({
- 'tmrwnbl': ?wEnabled,
- 'tmron': ?wTime,
- 'tmrsnbl': ?sEnabled,
- 'tmroff': ?sTime,
- });
- Future<void> updatePressure(int start, int end, int period) =>
- updatePressureSettings(start: start, end: end, period: period);
- Future<void> updatePressureSettings({int? start, int? end, int? period}) =>
- _updateSettings({'pp1': ?start, 'pp2': ?end, 'ppt': ?period});
- Future<void> updatePID(double p, double i, double d) =>
- updatePIDSettings(p: p, i: i, d: d);
- Future<void> updatePIDSettings({double? p, double? i, double? d}) =>
- _updateSettings({'pd1p': ?p, 'pd1i': ?i, 'pd1d': ?d});
- Future<void> updatePIDLimits(double min, double max, int interval) =>
- _updateSettings({
- 'pd1imn': min,
- 'pd1imx': max,
- 'pd1sz': interval,
- }, omitV4Minimum: true);
- Future<void> updatePIDLimitSettings({
- double? min,
- double? max,
- int? interval,
- }) => _updateSettings({'pd1imn': ?min, 'pd1imx': ?max, 'pd1sz': ?interval});
- Future<void> _incrementShotCount() async {
- final prefs = await SharedPreferences.getInstance();
- if (!mounted) return;
- final newCount = state.shotCounter + 1;
- await prefs.setInt('shotCounter', newCount);
- if (!mounted) return;
- state = state.copyWith(shotCounter: newCount);
- }
- Future<void> updateBrewTemperature(double temp) async {
- if (!temp.isFinite || temp < 50 || temp > 125) {
- _reportCommandError('Brew temperature must be between 50 and 125 C.');
- return;
- }
- await _updateSettings({'tmpsp': temp});
- }
- Future<void> incrementSetpoint() => _adjustSetpoint(0.5);
- Future<void> decrementSetpoint() => _adjustSetpoint(-0.5);
- Future<void> _adjustSetpoint(double change) {
- final generation = _connectionGeneration;
- final operation = _setpointQueue.then((_) async {
- await _settingsLoaded;
- if (!mounted || generation != _connectionGeneration) return;
- if (!_reportedSettings.contains('tmpsp')) {
- _reportCommandError(
- 'Wait for the controller brew setting before adjusting it.',
- );
- return;
- }
- if (!state.brewTemperature.isFinite) {
- _reportCommandError('Brew temperature must be a finite number.');
- return;
- }
- final newTemp = (state.brewTemperature + change).clamp(50.0, 125.0);
- if (newTemp != state.brewTemperature) {
- await updateBrewTemperature(newTemp);
- }
- });
- _setpointQueue = operation;
- return operation;
- }
- Future<void> updateSteamTemperature(double temp) async {
- if (!temp.isFinite || temp < 110 || temp > 150) {
- _reportCommandError('Steam temperature must be between 110 and 150 C.');
- return;
- }
- await _updateSettings({'tmpstm': temp});
- }
- static const _preferenceKeys = {
- 'tmpsp': 'brewTemperature',
- 'tmpstm': 'steamTemperature',
- 'pinbl': 'preinfusionEnabled',
- 'pistrt': 'preinfusionTime',
- 'piprd': 'preinfusionPauseTime',
- 'pivlv': 'valveClosedWhilePaused',
- 'o0': 'output0',
- 'o1': 'output1',
- 'o2': 'output2',
- 'tmrpwr': 'installedAsTimer',
- 'pwrflp': 'powerButtonFlipsBack',
- 'tmppap': 'proActivePercentage',
- 'tmpoff': 'temperatureOffset',
- 'tmrosd': 'autoShutoffMinutes',
- 'shtmx': 'maxShotTime',
- 'tmpcntns': 'continuousMode',
- 'tmrwnbl': 'wakeupEnabled',
- 'tmron': 'wakeupTime',
- 'tmrsnbl': 'shutdownEnabled',
- 'tmroff': 'shutdownTime',
- 'pp1': 'pressureStart',
- 'pp2': 'pressureEnd',
- 'ppt': 'pressurePeriod',
- 'pd1p': 'pidP',
- 'pd1i': 'pidI',
- 'pd1d': 'pidD',
- 'pd1imn': 'pidIWindDownMin',
- 'pd1imx': 'pidIWindDownMax',
- 'pd1sz': 'pidPollingInterval',
- };
- Map<String, Object> _preferenceValues(MachineState value) => {
- 'brewTemperature': value.brewTemperature,
- 'steamTemperature': value.steamTemperature,
- 'preinfusionEnabled': value.preinfusionEnabled,
- 'preinfusionTime': value.preinfusionTime,
- 'preinfusionPauseTime': value.preinfusionPauseTime,
- 'valveClosedWhilePaused': value.valveClosedWhilePaused,
- 'output0': value.output0,
- 'output1': value.output1,
- 'output2': value.output2,
- 'installedAsTimer': value.installedAsTimer,
- 'powerButtonFlipsBack': value.powerButtonFlipsBack,
- 'proActivePercentage': value.proActivePercentage,
- 'temperatureOffset': value.temperatureOffset,
- 'autoShutoffMinutes': value.autoShutoffMinutes,
- 'maxShotTime': value.maxShotTime,
- 'continuousMode': value.continuousMode,
- 'wakeupEnabled': value.wakeupEnabled,
- 'wakeupTime': value.wakeupTime,
- 'shutdownEnabled': value.shutdownEnabled,
- 'shutdownTime': value.shutdownTime,
- 'pressureStart': value.pressureStart,
- 'pressureEnd': value.pressureEnd,
- 'pressurePeriod': value.pressurePeriod,
- 'pidP': value.pidP,
- 'pidI': value.pidI,
- 'pidD': value.pidD,
- 'pidIWindDownMin': value.pidIWindDownMin,
- 'pidIWindDownMax': value.pidIWindDownMax,
- 'pidPollingInterval': value.pidPollingInterval,
- };
- Future<bool> _persistPreference(String key, Object value) async {
- if (savePreference case final save?) return save(key, value);
- final prefs = await SharedPreferences.getInstance();
- return switch (value) {
- bool value => prefs.setBool(key, value),
- double value => prefs.setDouble(key, value),
- int value => prefs.setInt(key, value),
- String value => prefs.setString(key, value),
- _ => throw ArgumentError.value(value, key, 'Unsupported setting type'),
- };
- }
- Future<void> _updateSettings(
- Map<String, Object> requested, {
- bool omitV4Minimum = false,
- }) {
- if (!mounted) return Future<void>.value();
- if (_settingsLocked) {
- _reportCommandError(
- 'Settings are blocked while firmware is being updated.',
- );
- return Future<void>.value();
- }
- if (!_commandReady) {
- _reportCommandError('Settings not sent: connect to meCoffee first.');
- return Future<void>.value();
- }
- if (state.firmwareVersion.isEmpty) {
- _reportCommandError(
- 'Settings not sent: waiting for controller firmware identity.',
- );
- return Future<void>.value();
- }
- if (requested.values.any((value) => value is double && !value.isFinite)) {
- _reportCommandError('Settings must contain finite numbers.');
- return Future<void>.value();
- }
- final generation = _connectionGeneration;
- final operation = _settingsQueue.then((_) async {
- if (!mounted || generation != _connectionGeneration) {
- const message = 'Settings cancelled: Bluetooth connection changed.';
- if (mounted && state.commandError == null) {
- _reportCommandError(message);
- } else {
- _log(DiagnosticDirection.event, message);
- }
- return;
- }
- final values = Map<String, Object>.from(requested);
- if (state.isLegacyV4Firmware) {
- if (omitV4Minimum) values.remove('pd1imn');
- if (values.keys.any(
- const {
- 'o0',
- 'o1',
- 'o2',
- 'pwrflp',
- 'tmpoff',
- 'tmrosd',
- 'shtmx',
- 'pd1imn',
- }.contains,
- )) {
- _reportCommandError(
- 'These settings are not supported by V4 firmware.',
- );
- return;
- }
- }
- if (values.isEmpty) return;
- final commands = values.entries
- .map(
- (entry) => MeCoffeeProtocol.encodeSet(
- entry.key,
- entry.value,
- isLegacyV4: state.isLegacyV4Firmware,
- ),
- )
- .toList();
- if (!await _sendCommand(commands.join().codeUnits)) return;
- if (!mounted || generation != _connectionGeneration) return;
- var delivered = state;
- for (final command in commands) {
- delivered = MeCoffeeProtocol.parse(command, delivered);
- }
- final preferences = _preferenceValues(delivered);
- try {
- for (final key in values.keys) {
- final preferenceKey = _preferenceKeys[key]!;
- if (!await _persistPreference(
- preferenceKey,
- preferences[preferenceKey]!,
- )) {
- _reportCommandError(
- 'Settings delivered but could not be saved locally.',
- );
- return;
- }
- }
- } on Exception catch (error) {
- _reportCommandError(
- 'Settings delivered but could not be saved locally: $error',
- );
- return;
- }
- if (!mounted || generation != _connectionGeneration) return;
- var updated = state;
- for (final command in commands) {
- updated = MeCoffeeProtocol.parse(command, updated);
- }
- state = updated;
- });
- _settingsQueue = operation;
- return operation;
- }
- void _reportCommandError(String message) {
- if (!mounted) return;
- _log(DiagnosticDirection.event, message);
- state = state.copyWith(clearCommandError: true);
- state = state.copyWith(commandError: message);
- }
- Future<bool> _sendCommand(List<int> bytes, {bool initializing = false}) {
- final characteristic = _commandCharacteristic;
- final classic = _classicConnected;
- final generation = _connectionGeneration;
- if (_firmwareMode) {
- _reportCommandError(
- 'Settings are blocked while firmware is being updated.',
- );
- return Future<bool>.value(false);
- }
- if ((characteristic == null && !classic) ||
- (!initializing && !_commandReady)) {
- _reportCommandError('Settings not sent: connect to meCoffee first.');
- return Future<bool>.value(false);
- }
- final operation = _commandQueue.then((_) async {
- try {
- await _settingsLoaded;
- _log(DiagnosticDirection.sent, String.fromCharCodes(bytes).trim());
- for (var offset = 0; offset < bytes.length;) {
- if (!mounted ||
- generation != _connectionGeneration ||
- (classic
- ? !_classicConnected
- : characteristic != _commandCharacteristic ||
- characteristic!.device.isDisconnected)) {
- throw StateError(
- 'Bluetooth disconnected before settings were sent',
- );
- }
- final payloadSize = classic
- ? bytes.length
- : (characteristic!.device.mtuNow - 3).clamp(1, 512);
- final end = (offset + payloadSize).clamp(0, bytes.length);
- if (classic) {
- await _classicTransport
- .write(bytes.sublist(offset, end))
- .timeout(const Duration(seconds: 15));
- } else {
- await characteristic!.write(
- bytes.sublist(offset, end),
- withoutResponse: !characteristic.properties.write,
- );
- if (!characteristic.properties.write) {
- await Future<void>.delayed(const Duration(milliseconds: 20));
- }
- }
- offset = end;
- }
- if (!mounted || generation != _connectionGeneration) {
- throw StateError('Bluetooth disconnected while sending settings');
- }
- state = state.copyWith(clearCommandError: true);
- return true;
- } catch (e) {
- if (!initializing && mounted && generation == _connectionGeneration) {
- await _failConnection(characteristic?.device, e);
- }
- _reportCommandError(
- 'Settings not saved: $e. The machine may be partially updated.',
- );
- return false;
- }
- });
- // Queue the whole payload, not individual chunks, so commands cannot interleave.
- _commandQueue = operation.then((_) {});
- return operation;
- }
- Future<void> startScan() async {
- if (!mounted ||
- _scanActive ||
- _commandReady ||
- _settingsLocked ||
- _classicConnected ||
- state.connectionStatus == 'Connecting...') {
- return;
- }
- _scanActive = true;
- final generation = ++_scanGeneration;
- _reconnectTimer?.cancel();
- _reconnectTimer = null;
- _userDisconnected = false;
- try {
- final adapterState = await FlutterBluePlus.adapterState.first;
- if (!mounted || generation != _scanGeneration) return;
- if (adapterState != BluetoothAdapterState.on) {
- _cancelScanSubscriptions();
- state = state.copyWith(connectionStatus: 'Error: Bluetooth is off');
- return;
- }
- state = state.copyWith(connectionStatus: 'Scanning...');
- _scanStarted = true;
- await FlutterBluePlus.startScan(timeout: const Duration(seconds: 15));
- if (!mounted || generation != _scanGeneration) {
- return;
- }
- var foundDevice = false;
- _scanSubscription = FlutterBluePlus.onScanResults.listen(
- (results) {
- if (!mounted || generation != _scanGeneration || foundDevice) return;
- for (final result in results) {
- if (matchesMeCoffeeAdvertisement(
- name: result.device.platformName,
- advertisedName: result.advertisementData.advName,
- serviceUuids: result.advertisementData.serviceUuids,
- )) {
- foundDevice = true;
- unawaited(_connectScanResult(result.device));
- break;
- }
- }
- },
- onError: (Object error) {
- if (!mounted || generation != _scanGeneration) return;
- state = state.copyWith(
- connectionStatus: 'Error: ${_friendlyBtError(error)}',
- );
- unawaited(stopScan());
- },
- );
- _scanStateSubscription = FlutterBluePlus.isScanning.listen((scanning) {
- if (!mounted || generation != _scanGeneration) return;
- if (!scanning && !foundDevice) {
- _cancelScanSubscriptions();
- if (state.connectionStatus == 'Scanning...') {
- state = state.copyWith(connectionStatus: 'Not found');
- }
- }
- });
- } catch (e) {
- if (mounted && generation == _scanGeneration) {
- _cancelScanSubscriptions();
- state = state.copyWith(
- connectionStatus: 'Error: ${_friendlyBtError(e)}',
- );
- } else {
- FlutterError.reportError(
- FlutterErrorDetails(
- exception: e,
- library: 'meBarista Bluetooth',
- context: ErrorDescription('while stopping a cancelled scan'),
- ),
- );
- }
- }
- }
- Future<void> _connectScanResult(BluetoothDevice device) async {
- final stoppedGeneration = _scanGeneration + 1;
- if (await stopScan() &&
- mounted &&
- !_userDisconnected &&
- stoppedGeneration == _scanGeneration) {
- await connectToDevice(device);
- }
- }
- static String _friendlyBtError(Object e) {
- final msg = e.toString().toLowerCase();
- if (msg.contains('off') ||
- msg.contains('unknown') ||
- msg.contains('cbmanagerstate')) {
- return 'Bluetooth is off';
- }
- if (msg.contains('unauthorized') || msg.contains('permission')) {
- return 'Bluetooth permission denied';
- }
- return e.toString();
- }
- void _cancelScanSubscriptions() {
- _scanGeneration++;
- _scanActive = false;
- _scanStarted = false;
- _scanSubscription?.cancel();
- _scanSubscription = null;
- _scanStateSubscription?.cancel();
- _scanStateSubscription = null;
- }
- Future<bool> stopScan() async {
- final wasStarted = _scanStarted;
- _cancelScanSubscriptions();
- final generation = _scanGeneration;
- if (!wasStarted) return true;
- try {
- await FlutterBluePlus.stopScan();
- if (mounted &&
- generation == _scanGeneration &&
- state.connectionStatus == 'Scanning...') {
- state = state.copyWith(connectionStatus: 'Not found');
- }
- return true;
- } catch (e, stack) {
- if (mounted) {
- state = state.copyWith(
- connectionStatus: 'Error: ${_friendlyBtError(e)}',
- );
- } else {
- FlutterError.reportError(
- FlutterErrorDetails(
- exception: e,
- stack: stack,
- library: 'meBarista Bluetooth',
- context: ErrorDescription('while stopping a scan'),
- ),
- );
- }
- return false;
- }
- }
- Future<void> connectToDevice(BluetoothDevice device) async {
- if (state.connectionStatus == 'Connecting...' ||
- _commandReady ||
- _settingsLocked) {
- return;
- }
- _reconnectTimer?.cancel();
- _reconnectTimer = null;
- _userDisconnected = false;
- _clearConnection();
- final generation = _connectionGeneration;
- _connectedDevice = device;
- state = state.copyWith(
- connectionStatus: 'Connecting...',
- transportName: 'BLE',
- firmwareVersion: '',
- isLegacyV4Firmware: false,
- clearCommandError: true,
- );
- try {
- if (!await stopScan()) {
- _clearConnection();
- return;
- }
- await _settingsLoaded;
- if (!mounted || generation != _connectionGeneration) return;
- await device.connect();
- if (!mounted || generation != _connectionGeneration) return;
- _connectionStateSubscription = device.connectionState.listen((
- connectionState,
- ) {
- if (!mounted || generation != _connectionGeneration) return;
- if (connectionState == BluetoothConnectionState.disconnected) {
- _clearConnection();
- state = state.copyWith(
- connectionStatus: 'Disconnected',
- isBrewing: false,
- );
- _scheduleReconnect();
- }
- });
- await _discoverServices(device);
- if (!mounted || generation != _connectionGeneration) return;
- await Future<void>.delayed(const Duration(milliseconds: 500));
- if (!mounted || generation != _connectionGeneration) return;
- if (!await _sendInitializationSequence()) {
- throw StateError(state.commandError ?? 'Initialization failed');
- }
- if (!mounted || generation != _connectionGeneration) return;
- _commandReady = true;
- state = state.copyWith(connectionStatus: 'Connected');
- _watchFreshness();
- _log(DiagnosticDirection.event, 'Connected via BLE');
- } catch (e) {
- if (mounted && generation == _connectionGeneration) {
- await _failConnection(device, e);
- }
- }
- }
- Future<bool> _sendInitializationSequence() async {
- final now = DateTime.now();
- final secondsPassed = now.hour * 3600 + now.minute * 60 + now.second;
- if (!await _sendCommand(
- "\ncmd clock set $secondsPassed\n".codeUnits,
- initializing: true,
- )) {
- return false;
- }
- if (!await _sendCommand("\ncmd uname OK\n".codeUnits, initializing: true)) {
- return false;
- }
- return _sendCommand("\ncmd dump\n".codeUnits, initializing: true);
- }
- Future<void> _discoverServices(BluetoothDevice device) async {
- final services = await device.discoverServices();
- if (_connectedDevice != device || device.isDisconnected) {
- throw StateError('Bluetooth disconnected during service discovery');
- }
- BluetoothCharacteristic? preferred;
- for (final service in services) {
- final serviceId = service.uuid.str128.toLowerCase();
- if (!serviceId.startsWith(_meCoffeeServiceUuidPrefix)) continue;
- for (final characteristic in service.characteristics) {
- final charId = characteristic.uuid.str128.toLowerCase();
- if (charId.startsWith(_meCoffeeCharacteristicUuidPrefix) &&
- (characteristic.properties.write ||
- characteristic.properties.writeWithoutResponse) &&
- (characteristic.properties.notify ||
- characteristic.properties.indicate)) {
- preferred = characteristic;
- break;
- }
- }
- if (preferred != null) break;
- }
- if (preferred != null) {
- await _attachCharacteristic(preferred);
- if (_connectedDevice != device || device.isDisconnected) {
- throw StateError('Bluetooth disconnected during service discovery');
- }
- _commandCharacteristic = preferred;
- return;
- }
- // Fallback still requires both a write path and a telemetry path.
- BluetoothCharacteristic? writable;
- var hasNotifications = false;
- for (final service in services) {
- for (final characteristic in service.characteristics) {
- if (writable == null &&
- (characteristic.properties.write ||
- characteristic.properties.writeWithoutResponse)) {
- writable = characteristic;
- }
- if (characteristic.properties.notify ||
- characteristic.properties.indicate) {
- await _attachCharacteristic(characteristic);
- hasNotifications = true;
- }
- }
- }
- if (writable == null || !hasNotifications) {
- throw StateError(
- 'No usable meCoffee write/notification characteristics found',
- );
- }
- if (_connectedDevice != device || device.isDisconnected) {
- throw StateError('Bluetooth disconnected during service discovery');
- }
- _commandCharacteristic = writable;
- }
- Future<void> _attachCharacteristic(
- BluetoothCharacteristic characteristic,
- ) async {
- final generation = _connectionGeneration;
- if (characteristic.properties.notify ||
- characteristic.properties.indicate) {
- final subscription = characteristic.onValueReceived.listen(
- (data) {
- if (mounted && generation == _connectionGeneration) _handleData(data);
- },
- onError: (Object error) {
- if (mounted && generation == _connectionGeneration) {
- unawaited(_failConnection(characteristic.device, error));
- }
- },
- );
- _notificationSubscriptions.add(subscription);
- await characteristic.setNotifyValue(true);
- if (generation != _connectionGeneration) {
- throw StateError('Bluetooth disconnected during notification setup');
- }
- }
- }
- void _clearConnection() {
- _connectionGeneration++;
- _lastPidAt = null;
- _reportedSettings.clear();
- _pendingFirmwareSettings.clear();
- _commandReady = false;
- _connectedDevice = null;
- _commandCharacteristic = null;
- _classicConnected = false;
- _classicDataSubscription?.cancel();
- _classicDataSubscription = null;
- _classicEventSubscription?.cancel();
- _classicEventSubscription = null;
- _freshnessTimer?.cancel();
- _freshnessTimer = null;
- _connectionStateSubscription?.cancel();
- _connectionStateSubscription = null;
- for (final subscription in _notificationSubscriptions) {
- subscription.cancel();
- }
- _notificationSubscriptions.clear();
- _stopShotTimer();
- _inputBuffer = '';
- if (mounted) {
- state = state.copyWith(
- telemetryStale: true,
- clearLastTelemetry: true,
- isHeating: false,
- heatingPower: 0,
- );
- }
- }
- Future<void> _failConnection(BluetoothDevice? device, Object error) async {
- final classic = _classicConnected || _classicDataSubscription != null;
- _clearConnection();
- final generation = _connectionGeneration;
- var message = error.toString();
- if (mounted) {
- state = state.copyWith(
- connectionStatus: 'Error: $message',
- isBrewing: false,
- );
- }
- try {
- if (classic) await _classicTransport.disconnect();
- if (device != null) await device.disconnect();
- } catch (disconnectError) {
- message = '$message; disconnect failed: $disconnectError';
- }
- if (mounted && generation == _connectionGeneration) {
- state = state.copyWith(
- connectionStatus: 'Error: $message',
- isBrewing: false,
- );
- _log(DiagnosticDirection.event, 'Connection failed: $message');
- }
- }
- Timer? _shotTimer;
- String _inputBuffer = "";
- void _handleData(List<int> data) {
- if (!mounted) return;
- if (_firmwareMode) {
- _firmwareBytes?.add(List<int>.from(data));
- return;
- }
- _inputBuffer += String.fromCharCodes(data);
- if (_inputBuffer.length > 8192 && !_inputBuffer.contains('\n')) {
- _inputBuffer = '';
- _log(DiagnosticDirection.event, 'Discarded oversized unterminated frame');
- return;
- }
- while (_inputBuffer.contains('\n')) {
- int index = _inputBuffer.indexOf('\n');
- String line = _inputBuffer.substring(0, index).trim();
- _inputBuffer = _inputBuffer.substring(index + 1);
- if (line.isNotEmpty) {
- _log(DiagnosticDirection.received, line);
- final fields = line.split(RegExp(r'\s+'));
- final settingKey = fields.first == 'get' && fields.length >= 3
- ? fields[1]
- : fields.first == 'cmd' &&
- fields.length >= 4 &&
- (fields[1] == 'get' || fields[1] == 'set')
- ? fields[2]
- : null;
- // A dump can arrive before uname; do not guess V4 units.
- if (state.firmwareVersion.isEmpty &&
- _firmwareScaledKeys.contains(settingKey)) {
- _pendingFirmwareSettings[settingKey == 'pd1imm'
- ? 'pd1imn'
- : settingKey!] =
- line;
- continue;
- }
- final oldBrewing = state.isBrewing;
- var parsed = MeCoffeeProtocol.parse(line, state);
- final valid = !identical(parsed, state);
- if (valid &&
- parsed.firmwareVersion.isNotEmpty &&
- state.firmwareVersion.isEmpty) {
- for (final entry in _pendingFirmwareSettings.entries) {
- final replayed = MeCoffeeProtocol.parse(entry.value, parsed);
- if (!identical(replayed, parsed)) {
- _reportedSettings.add(entry.key);
- }
- parsed = replayed;
- }
- _pendingFirmwareSettings.clear();
- }
- if (valid && fields.first == 'pid') {
- if (!state.telemetryStale) _lastPidAt = DateTime.now();
- }
- if (state.telemetryStale &&
- (fields.first == 'pid' || fields.first == 'sht')) {
- parsed = parsed.copyWith(
- isHeating: false,
- heatingPower: 0,
- isBrewing: false,
- );
- }
- if (valid && fields.first == 'get' && fields.length >= 3) {
- _reportedSettings.add(fields[1]);
- } else if (valid &&
- fields.first == 'cmd' &&
- fields.length >= 4 &&
- fields[1] == 'get') {
- _reportedSettings.add(fields[2]);
- }
- state = parsed;
- if (valid && (line.startsWith('tmp ') || line.startsWith('T '))) {
- final now = DateTime.now();
- final fields = line.split(RegExp(r'\s+'));
- final rawSensor2 = fields.length >= 5
- ? double.tryParse(fields[4])
- : null;
- final sensor2 =
- rawSensor2 != null && rawSensor2 > 5 && rawSensor2 < 20000
- ? rawSensor2 / 100
- : null;
- final history = List<double>.from(state.temperatureHistory);
- history.add(state.temperature);
- if (history.length > historyLimit) history.removeAt(0);
- final history2 = List<double>.from(state.sensor2TemperatureHistory);
- // Only record sensor2 if we have a valid (non-zero) reading.
- if (sensor2 != null) {
- history2.add(sensor2);
- if (history2.length > historyLimit) history2.removeAt(0);
- }
- final samples = [
- ...state.temperatureSamples,
- TemperatureSample(
- timestamp: now,
- boiler: state.temperature,
- target: state.targetTemperature,
- sensor2: sensor2,
- ),
- ];
- if (samples.length > historyLimit) samples.removeAt(0);
- state = state.copyWith(
- temperatureHistory: history,
- sensor2TemperatureHistory: history2,
- sensor2Temperature: sensor2 ?? 0,
- temperatureSamples: List.unmodifiable(samples),
- lastTelemetryAt: now,
- telemetryStale: false,
- );
- _watchFreshness();
- } else if (!valid &&
- (line.startsWith('tmp ') ||
- line.startsWith('T ') ||
- line.startsWith('pid ') ||
- line.startsWith('sht '))) {
- _log(DiagnosticDirection.event, 'Ignored malformed telemetry: $line');
- }
- // Shot Timer Logic
- if (state.isBrewing && !oldBrewing) {
- // Started brewing (triggered by 'sht 0')
- _startShotTimer();
- } else if (!state.isBrewing && oldBrewing) {
- // Stopped brewing (triggered by 'sht <final_time>')
- _stopShotTimer();
- _incrementShotCount();
- }
- }
- }
- }
- void _startShotTimer() {
- if (state.telemetryStale) return;
- _shotTimer?.cancel();
- state = state.copyWith(shotTimer: 0);
- _shotTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
- if (!mounted || state.telemetryStale) {
- timer.cancel();
- return;
- }
- state = state.copyWith(shotTimer: state.shotTimer + 1);
- });
- }
- void _stopShotTimer() {
- _shotTimer?.cancel();
- _shotTimer = null;
- }
- Future<void> disconnect() async {
- if (state.firmwareUpdating) {
- _reportCommandError('Cannot disconnect while firmware is being updated.');
- return;
- }
- _userDisconnected = true;
- _log(DiagnosticDirection.event, 'Disconnect requested by user');
- _reconnectTimer?.cancel();
- _reconnectTimer = null;
- final device = _connectedDevice;
- final classic = _classicConnected || _classicDataSubscription != null;
- _clearConnection();
- state = state.copyWith(connectionStatus: 'Disconnected', isBrewing: false);
- await stopScan();
- if (classic) {
- try {
- await _classicTransport.disconnect();
- } catch (e) {
- if (mounted) state = state.copyWith(connectionStatus: 'Error: $e');
- _log(DiagnosticDirection.event, 'Classic disconnect failed: $e');
- }
- }
- if (device != null) {
- try {
- await device.disconnect(queue: false);
- } catch (e) {
- if (mounted) {
- state = state.copyWith(connectionStatus: 'Error: $e');
- }
- _log(DiagnosticDirection.event, 'BLE disconnect failed: $e');
- }
- }
- if (mounted && state.connectionStatus == 'Disconnected') {
- _log(DiagnosticDirection.event, 'Disconnected by user');
- }
- }
- @override
- void dispose() {
- _userDisconnected = true;
- _reconnectTimer?.cancel();
- final device = _connectedDevice;
- unawaited(stopScan());
- _clearConnection();
- unawaited(
- _classicTransport.dispose().catchError((Object error, StackTrace stack) {
- FlutterError.reportError(
- FlutterErrorDetails(
- exception: error,
- stack: stack,
- library: 'meBarista Bluetooth',
- context: ErrorDescription('while disposing the Classic connection'),
- ),
- );
- }),
- );
- if (device != null) {
- unawaited(
- device.disconnect(queue: false).catchError((
- Object error,
- StackTrace stack,
- ) {
- FlutterError.reportError(
- FlutterErrorDetails(
- exception: error,
- stack: stack,
- library: 'meBarista Bluetooth',
- context: ErrorDescription(
- 'while disposing the Bluetooth connection',
- ),
- ),
- );
- }),
- );
- }
- super.dispose();
- }
- }
|