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((ref) { return MeCoffeeService(); }); class MeCoffeeService extends StateNotifier { static const String _meCoffeeServiceUuidPrefix = '0000ffe0'; static const String _meCoffeeCharacteristicUuidPrefix = '0000ffe1'; MeCoffeeService({ ClassicBluetoothTransport? classicTransport, Future Function(Duration)? firmwareDelay, this.savePreference, this.freshnessTimeout = const Duration(seconds: 3), }) : _classicTransport = classicTransport ?? ClassicBluetoothTransport(), _firmwareDelay = firmwareDelay ?? Future.delayed, super(MachineState()) { _settingsLoaded = _loadSettings(); } final Duration freshnessTimeout; final ClassicBluetoothTransport _classicTransport; final Future Function(Duration) _firmwareDelay; final Future Function(String, Object)? savePreference; StreamSubscription>? _classicDataSubscription; StreamSubscription? _classicEventSubscription; ClassicBluetoothDevice? _classicDevice; bool _classicConnected = false; Timer? _freshnessTimer; StreamController>? _firmwareBytes; bool _firmwareMode = false; bool _settingsLocked = false; DateTime? _lastPidAt; final _reportedSettings = {}; final _pendingFirmwareSettings = {}; 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 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 _settingsLoaded; StreamSubscription>? _scanSubscription; StreamSubscription? _scanStateSubscription; bool _scanActive = false; bool _scanStarted = false; int _scanGeneration = 0; StreamSubscription? _connectionStateSubscription; final _notificationSubscriptions = >>[]; BluetoothDevice? _connectedDevice; BluetoothCharacteristic? _commandCharacteristic; bool _commandReady = false; int _connectionGeneration = 0; Future _commandQueue = Future.value(); Future _settingsQueue = Future.value(); Future _setpointQueue = Future.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> 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 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 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>.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 _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, 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 updatePreinfusion( bool enabled, double time, double pause, bool closeValve, ) => updatePreinfusionSettings( enabled: enabled, time: time, pause: pause, closeValve: closeValve, ); Future updatePreinfusionSettings({ bool? enabled, double? time, double? pause, bool? closeValve, }) => _updateSettings({ 'pinbl': ?enabled, 'pistrt': ?time, 'piprd': ?pause, 'pivlv': ?closeValve, }); Future updateHardware(int o0, int o1, int o2, bool timer, bool flips) => updateHardwareSettings( output0: o0, output1: o1, output2: o2, timer: timer, flips: flips, ); Future updateHardwareSettings({ int? output0, int? output1, int? output2, bool? timer, bool? flips, }) => _updateSettings({ 'o0': ?output0, 'o1': ?output1, 'o2': ?output2, 'tmrpwr': ?timer, 'pwrflp': ?flips, }); Future updateInstalledAsTimer(bool enabled) => _updateSettings({'tmrpwr': enabled}); Future updateProActive(int percentage) => _updateSettings({'tmppap': percentage}); Future updateAutoShutoff(int minutes) => _updateSettings({'tmrosd': minutes}); Future updateMaxShotTime(int seconds) => _updateSettings({'shtmx': seconds}); Future updateContinuousMode(bool enabled) => _updateSettings({'tmpcntns': enabled}); Future updateSchedule({ bool? wEnabled, String? wTime, bool? sEnabled, String? sTime, }) => _updateSettings({ 'tmrwnbl': ?wEnabled, 'tmron': ?wTime, 'tmrsnbl': ?sEnabled, 'tmroff': ?sTime, }); Future updatePressure(int start, int end, int period) => updatePressureSettings(start: start, end: end, period: period); Future updatePressureSettings({int? start, int? end, int? period}) => _updateSettings({'pp1': ?start, 'pp2': ?end, 'ppt': ?period}); Future updatePID(double p, double i, double d) => updatePIDSettings(p: p, i: i, d: d); Future updatePIDSettings({double? p, double? i, double? d}) => _updateSettings({'pd1p': ?p, 'pd1i': ?i, 'pd1d': ?d}); Future updatePIDLimits(double min, double max, int interval) => _updateSettings({ 'pd1imn': min, 'pd1imx': max, 'pd1sz': interval, }, omitV4Minimum: true); Future updatePIDLimitSettings({ double? min, double? max, int? interval, }) => _updateSettings({'pd1imn': ?min, 'pd1imx': ?max, 'pd1sz': ?interval}); Future _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 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 incrementSetpoint() => _adjustSetpoint(0.5); Future decrementSetpoint() => _adjustSetpoint(-0.5); Future _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 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', '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 _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, '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 _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 _updateSettings( Map requested, { bool omitV4Minimum = false, }) { if (!mounted) return Future.value(); if (_settingsLocked) { _reportCommandError( 'Settings are blocked while firmware is being updated.', ); return Future.value(); } if (!_commandReady) { _reportCommandError('Settings not sent: connect to meCoffee first.'); return Future.value(); } if (state.firmwareVersion.isEmpty) { _reportCommandError( 'Settings not sent: waiting for controller firmware identity.', ); return Future.value(); } if (requested.values.any((value) => value is double && !value.isFinite)) { _reportCommandError('Settings must contain finite numbers.'); return Future.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.from(requested); if (state.isLegacyV4Firmware) { if (omitV4Minimum) values.remove('pd1imn'); if (values.keys.any( const { 'o0', 'o1', 'o2', 'pwrflp', '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 _sendCommand(List 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.value(false); } if ((characteristic == null && !classic) || (!initializing && !_commandReady)) { _reportCommandError('Settings not sent: connect to meCoffee first.'); return Future.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.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 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 _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 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 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.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 _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 _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 _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 _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 data) { if (!mounted) return; if (_firmwareMode) { _firmwareBytes?.add(List.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.from(state.temperatureHistory); history.add(state.temperature); if (history.length > historyLimit) history.removeAt(0); final history2 = List.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 ') _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 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(); } }