| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519 |
- 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 &&
- !state.isSteaming &&
- _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,
- isSteaming: false,
- 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,
- 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> updateAutoShutoff(int minutes) =>
- _updateSettings({'tmrosd': minutes});
- Future<void> updateMaxShotTime(int seconds) async {
- if (seconds < 0 || seconds > MeCoffeeProtocol.maxShotSeconds) {
- _reportCommandError(
- 'Max shot time must be between 0 and '
- '${MeCoffeeProtocol.maxShotSeconds} s.',
- );
- return;
- }
- await _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});
- bool _pidLimitsOutOfRange(Iterable<double?> percentages) {
- if (state.isLegacyV4Firmware) return false;
- final outOfRange = percentages.any(
- (value) =>
- value != null &&
- (value < 0 || value > MeCoffeeProtocol.maxPidLimitPercent),
- );
- if (outOfRange) {
- _reportCommandError(
- 'I-wind-down limits must be between 0 and '
- '${MeCoffeeProtocol.maxPidLimitPercent}%.',
- );
- }
- return outOfRange;
- }
- Future<void> updatePIDLimits(double min, double max, int interval) async {
- if (_pidLimitsOutOfRange([min, max])) return;
- await _updateSettings({
- 'pd1imn': min,
- 'pd1imx': max,
- 'pd1sz': interval,
- }, omitV4Minimum: true);
- }
- Future<void> updatePIDLimitSettings({
- double? min,
- double? max,
- int? interval,
- }) async {
- if (_pidLimitsOutOfRange([min, max])) return;
- await _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',
- '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,
- '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',
- '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,
- isSteaming: false,
- );
- }
- }
- 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,
- isSteaming: false,
- 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();
- }
- }
|