import 'dart:async'; import 'package:flutter_blue_plus/flutter_blue_plus.dart'; import 'package:flutter_blue_plus_platform_interface/flutter_blue_plus_platform_interface.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:mebarista/services/bluetooth_service.dart'; import 'package:mebarista/services/me_coffee_protocol.dart'; import '../support/fake_bluetooth_platform.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); final platform = FakeBluetoothPlatform(); late MeCoffeeService service; late BluetoothDevice device; setUpAll(() { FlutterBluePlusPlatform.instance = platform; }); setUp(() async { platform.reset(); SharedPreferences.setMockInitialValues({}); service = MeCoffeeService(); device = platform.newDevice(); await Future.delayed(Duration.zero); }); tearDown(() async { platform.discoveryGate?.complete(); platform.writeGate?.complete(); if (service.mounted) { await service.disconnect(); service.dispose(); } await FlutterBluePlus.stopScan(); }); Future connect() async { await service.connectToDevice(device); expect(service.state.connectionStatus, 'Connected'); platform.notify(device, 'cmd get tmpsp 10100\n'); await Future.delayed(Duration.zero); platform.writes.clear(); } test( 'reconnecting resets partial input and processes notifications once', () async { await connect(); platform.notify(device, 'tmp 1 10100'); await Future.delayed(Duration.zero); await service.disconnect(); await connect(); platform.notify(device, 'tmp 2 10100 9850 OK\n'); await Future.delayed(Duration.zero); expect(service.state.temperature, 98.5); expect(service.state.temperatureHistory, [98.5]); }, ); test( 'disconnect stops the shot timer and ignores old notifications', () async { await connect(); platform.notify(device, 'tmp 1 10100 9850\n'); platform.notify(device, 'sht 0 0 OK\n'); await Future.delayed(Duration.zero); expect(service.state.isBrewing, isTrue); await service.disconnect(); final stoppedTime = service.state.shotTimer; platform.notify(device, 'tmp 1 10100 9850 OK\n'); await Future.delayed(const Duration(milliseconds: 1100)); expect(service.state.isBrewing, isFalse); expect(service.state.shotTimer, stoppedTime); expect(service.state.temperatureHistory, [98.5]); }, ); test('stopped scans can be restarted without stale listeners', () async { for (var attempt = 0; attempt < 3; attempt++) { await service.startScan(); expect(service.state.connectionStatus, 'Scanning...'); expect(await service.stopScan(), isTrue); expect(service.state.connectionStatus, 'Not found'); } expect(platform.scanStarts, 3); expect(platform.scanStops, 3); await service.startScan(); await FlutterBluePlus.stopScan(); await Future.delayed(Duration.zero); expect(service.state.connectionStatus, 'Not found'); await service.startScan(); expect(platform.scanStarts, 5); expect(service.state.connectionStatus, 'Scanning...'); }); test( 'disposing an idle service leaves an independently started scan running', () async { await FlutterBluePlus.startScan(); service.dispose(); await Future.delayed(Duration.zero); expect(FlutterBluePlus.isScanningNow, isTrue); expect(platform.scanStops, 0); }, ); test( 'configuration payloads are delivered in MTU-sized ordered chunks', () async { await connect(); await service.updatePreinfusion(true, 3, 3, false); await service.updatePID(20, 0.3, 128); await service.updateHardware(112, 98, 118, false, false); await service.updateSchedule(wEnabled: true, wTime: '07:00'); await Future.delayed(Duration.zero); final expected = [ ...MeCoffeeProtocol.encodePreinfusion(true, 3, 3, false), ...MeCoffeeProtocol.encodePID(20, 0.3, 128), ...MeCoffeeProtocol.encodeHardware(112, 98, 118, false, false), ...'cmd set tmrwnbl 1\ncmd set tmron 25200\n'.codeUnits, ]; expect(platform.writes.expand((chunk) => chunk).toList(), expected); expect(platform.writes.every((chunk) => chunk.length <= 20), isTrue); }, ); test('failed writes do not save or display a changed temperature', () async { await connect(); platform.failWrites = true; await service.updateBrewTemperature(95); await Future.delayed(Duration.zero); final prefs = await SharedPreferences.getInstance(); expect(service.state.brewTemperature, 101); expect(prefs.getDouble('brewTemperature'), isNull); expect(service.state.commandError, contains('Write failed')); expect(service.state.connectionStatus, startsWith('Error:')); expect(platform.connected, isEmpty); }); test('disconnected edits do not save a setting', () async { await service.updateBrewTemperature(95); final prefs = await SharedPreferences.getInstance(); expect(service.state.brewTemperature, 101); expect(prefs.getDouble('brewTemperature'), isNull); expect(service.state.commandError, contains('connect to meCoffee first')); }); test( 'home controls adjust brew configuration rather than active target', () async { await connect(); platform.notify(device, 'tmp 1 12500 9850 0\n'); await Future.delayed(Duration.zero); await service.decrementSetpoint(); expect(service.state.brewTemperature, 100.5); }, ); test( 'home increment recovers a low setpoint without writing below 50', () async { await connect(); platform.notify(device, 'cmd get tmpsp 3942\n'); await Future.delayed(Duration.zero); await service.incrementSetpoint(); expect(service.state.brewTemperature, 50); }, ); test('Connected is not exposed during discovery', () async { platform.discoveryGate = Completer(); final connecting = service.connectToDevice(device); await Future.delayed(const Duration(milliseconds: 10)); expect(service.state.connectionStatus, 'Connecting...'); platform.discoveryGate!.complete(); platform.discoveryGate = null; await connecting; expect(service.state.connectionStatus, 'Connected'); }); test('initialization writes clock, uname, and dump in order', () async { await service.connectToDevice(device); final payload = String.fromCharCodes(platform.writes.expand((v) => v)); expect( payload, matches(r'^\ncmd clock set \d+\n\ncmd uname OK\n\ncmd dump\n$'), ); expect(service.state.connectionStatus, 'Connected'); }); for (final stage in [ 'discovery', 'notifications', 'missing characteristic', 'not writable', 'no notifications', 'initialization', ]) { test( '$stage failure is caught and closes the unusable connection', () async { platform.failDiscovery = stage == 'discovery'; platform.failNotifications = stage == 'notifications'; platform.hasCharacteristic = stage != 'missing characteristic'; platform.writable = stage != 'not writable'; platform.notifiable = stage != 'no notifications'; platform.failWrites = stage == 'initialization'; await service.connectToDevice(device); expect(service.state.connectionStatus, startsWith('Error:')); expect(platform.connected, isEmpty); await service.updateBrewTemperature(95); expect(service.state.brewTemperature, 101); expect( service.state.commandError, contains('connect to meCoffee first'), ); }, ); } test('settings cannot be sent while initialization is incomplete', () async { platform.writeGate = Completer(); final connecting = service.connectToDevice(device); await Future.delayed(const Duration(milliseconds: 550)); expect(service.state.connectionStatus, 'Connecting...'); await service.updateBrewTemperature(95); expect(service.state.brewTemperature, 101); expect(service.state.commandError, contains('connect to meCoffee first')); platform.writeGate!.complete(); platform.writeGate = null; await connecting; expect(service.state.connectionStatus, 'Connected'); }); test('concurrent command groups do not interleave their chunks', () async { await connect(); await Future.wait([ service.updatePreinfusion(true, 4, 2, true), service.updatePID(21, 0.4, 129), ]); expect(platform.writes.expand((v) => v).toList(), [ ...MeCoffeeProtocol.encodePreinfusion(true, 4, 2, true), ...MeCoffeeProtocol.encodePID(21, 0.4, 129), ]); }); test( 'mid-payload failure aborts queued commands and preserves local settings', () async { await connect(); platform.failWriteAt = 1; await Future.wait([ service.updatePreinfusion(true, 4, 2, true), service.updatePID(21, 0.4, 129), ]); final prefs = await SharedPreferences.getInstance(); expect(platform.writes.length, 1); expect(service.state.preinfusionTime, 3); expect(service.state.pidP, 20); expect(prefs.getDouble('preinfusionTime'), isNull); expect(prefs.getDouble('pidP'), isNull); expect(service.state.commandError, contains('partially updated')); }, ); test('successful retry after reconnect clears a write error', () async { await connect(); platform.failWrites = true; await service.updateBrewTemperature(95); platform.failWrites = false; await service.connectToDevice(device); await service.updateBrewTemperature(95); expect(service.state.commandError, isNull); expect(service.state.brewTemperature, 95); final prefs = await SharedPreferences.getInstance(); expect(prefs.getDouble('brewTemperature'), 95); }); test( 'cancelled discovery cannot later initialize an old connection', () async { platform.discoveryGate = Completer(); final connecting = service.connectToDevice(device); await Future.delayed(const Duration(milliseconds: 10)); await service.disconnect(); platform.discoveryGate!.complete(); platform.discoveryGate = null; await connecting; expect(service.state.connectionStatus, 'Disconnected'); expect(platform.writes, isEmpty); }, ); for (final temperature in [49.9, 125.1, double.nan, double.infinity]) { test( 'invalid brew temperature $temperature is rejected before writing', () async { await connect(); await service.updateBrewTemperature(temperature); expect(platform.writes, isEmpty); expect(service.state.brewTemperature, 101); expect(service.state.commandError, contains('between 50 and 125')); }, ); } for (final temperature in [109.9, 150.1, double.nan, double.infinity]) { test( 'invalid steam temperature $temperature is rejected before writing', () async { await connect(); await service.updateSteamTemperature(temperature); expect(platform.writes, isEmpty); expect(service.state.steamTemperature, 125); expect(service.state.commandError, contains('between 110 and 150')); }, ); } test( 'home decrement recovers an excessive setpoint within the upper bound', () async { await connect(); platform.notify(device, 'cmd get tmpsp 13000\n'); await Future.delayed(Duration.zero); await service.decrementSetpoint(); expect(service.state.brewTemperature, 125); }, ); test('home controls do not send beyond either boundary', () async { await connect(); platform.notify(device, 'cmd get tmpsp 12500\n'); await Future.delayed(Duration.zero); await service.incrementSetpoint(); expect(platform.writes, isEmpty); platform.notify(device, 'cmd get tmpsp 5000\n'); await Future.delayed(Duration.zero); await service.decrementSetpoint(); expect(platform.writes, isEmpty); }); test('rapid home button presses each adjust the brew setpoint', () async { await connect(); await Future.wait([ service.incrementSetpoint(), service.incrementSetpoint(), service.incrementSetpoint(), service.decrementSetpoint(), ]); expect(service.state.brewTemperature, 102); final prefs = await SharedPreferences.getInstance(); expect(prefs.getDouble('brewTemperature'), 102); }); test('disposing the service stops its active scan', () async { await service.startScan(); expect(FlutterBluePlus.isScanningNow, isTrue); service.dispose(); await Future.delayed(const Duration(milliseconds: 10)); expect(FlutterBluePlus.isScanningNow, isFalse); expect(platform.scanStops, 1); }); test( 'disposing the service closes its physical Bluetooth connection', () async { await connect(); service.dispose(); await Future.delayed(const Duration(milliseconds: 10)); expect(platform.connected, isEmpty); }, ); test('repeated scan requests start only one scan', () async { await Future.wait([service.startScan(), service.startScan()]); expect(platform.scanStarts, 1); }); test('BLE supports characteristics with only no-response writes', () async { platform.writable = false; platform.writableWithoutResponse = true; await connect(); await service.updateBrewTemperature(98.1); expect(service.state.brewTemperature, 98.1); expect(service.state.commandError, isNull); }); test('discovery recognizes renamed, legacy and name-only controllers', () { expect( MeCoffeeService.matchesMeCoffeeAdvertisement( name: 'Renamed machine', advertisedName: '', serviceUuids: [Guid('ffe0')], ), isTrue, ); for (final name in ['meCoffee', 'MissSilvia']) { expect( MeCoffeeService.matchesMeCoffeeAdvertisement( name: name, advertisedName: '', serviceUuids: const [], ), isTrue, ); } expect( MeCoffeeService.matchesMeCoffeeAdvertisement( name: '', advertisedName: 'meCoffee controller', serviceUuids: const [], ), isTrue, ); expect( MeCoffeeService.matchesMeCoffeeAdvertisement( name: 'Unrelated device', advertisedName: '', serviceUuids: [Guid('180d')], ), isFalse, ); }); test('steam settings preserve the Ionic upper range', () async { await connect(); await service.updateSteamTemperature(150); expect(service.state.steamTemperature, 150); }); test( 'temperature telemetry expires and resumes without losing history', () async { service.dispose(); service = MeCoffeeService( freshnessTimeout: const Duration(milliseconds: 40), ); await connect(); platform.notify(device, 'tmp 1 10100 9850 9100 OK\n'); await Future.delayed(Duration.zero); expect(service.state.telemetryStale, isFalse); expect(service.state.lastTelemetryAt, isNotNull); expect(service.state.temperatureSamples.single.sensor2, 91); await Future.delayed(const Duration(milliseconds: 60)); expect(service.state.telemetryStale, isTrue); expect(service.state.isHeating, isFalse); expect(service.state.temperature, 98.5); platform.notify(device, 'tmp 2 10200 9860 OK\n'); await Future.delayed(Duration.zero); expect(service.state.telemetryStale, isFalse); expect(service.state.temperatureSamples.length, 2); expect(service.state.temperatureSamples.last.target, 102); expect(service.state.temperatureSamples.last.sensor2, isNull); expect(service.state.sensor2Temperature, 0); }, ); test( 'malformed temperature and command replies do not refresh telemetry', () async { service.dispose(); service = MeCoffeeService( freshnessTimeout: const Duration(milliseconds: 40), ); await connect(); platform.notify(device, 'tmp 1 10100 9850 OK\n'); await Future.delayed(Duration.zero); final lastSample = service.state.lastTelemetryAt; platform.notify(device, 'tmp nonsense\ncmd get tmpsp 10200\n'); await Future.delayed(const Duration(milliseconds: 60)); expect(service.state.telemetryStale, isTrue); expect(service.state.lastTelemetryAt, lastSample); expect(service.state.temperatureSamples.length, 1); expect( service.exportDiagnosticLog(), contains('Ignored malformed telemetry'), ); }, ); test( 'history and diagnostic logs are bounded and independently clearable', () async { await connect(); final frames = List.generate( MeCoffeeService.historyLimit + 2, (index) => 'tmp $index 10100 ${9800 + index % 100} OK\n', ).join(); platform.notify(device, frames); await Future.delayed(Duration.zero); expect( service.state.temperatureHistory.length, MeCoffeeService.historyLimit, ); expect( service.state.temperatureSamples.length, MeCoffeeService.historyLimit, ); expect( service.state.diagnosticLog.length, MeCoffeeService.diagnosticLimit, ); expect(service.state.temperatureSamples.first.boiler, 98.02); service.clearDiagnosticLog(); expect(service.state.diagnosticLog, isEmpty); expect( service.state.temperatureSamples.length, MeCoffeeService.historyLimit, ); }, ); test('legacy PID writes use firmware-specific wire units', () async { await connect(); platform.notify(device, 'cmd uname meCoffee V4 OK\n'); await Future.delayed(Duration.zero); await service.updatePID(25, 3, 128); final payload = String.fromCharCodes( platform.writes.expand((bytes) => bytes), ); expect(payload, contains('cmd set pd1i 3\n')); expect(payload, isNot(contains('cmd set pd1i 300\n'))); }); test('firmware update refuses BLE and disconnected controllers', () async { await service.updateFirmware(); expect(service.state.firmwareUpdating, isFalse); expect(service.state.commandError, contains('Bluetooth Classic')); await connect(); platform.notify(device, 'cmd uname meCoffee V10 OK\ntmp 1 10100 2000\n'); await Future.delayed(Duration.zero); expect(service.canUpdateFirmware, isFalse); await service.updateFirmware(); expect(platform.writes, isEmpty); }); test('settings wait for identity and use delayed V4 wire units', () async { platform.respondToIdentity = false; await service.connectToDevice(device); platform.writes.clear(); await service.updatePreinfusionSettings(time: 3); await service.updatePIDSettings(i: 3); expect(platform.writes, isEmpty); expect(service.state.commandError, contains('firmware identity')); platform.notify( device, 'cmd get pistrt 4\nget pd1i 3\ncmd get pd1imx 3750\n', ); await Future.delayed(Duration.zero); expect(service.state.preinfusionTime, 3); expect(service.state.pidI, 0.3); platform.notify(device, 'cmd uname meCoffee V4 OK\n'); await Future.delayed(Duration.zero); expect(service.state.preinfusionTime, 4); expect(service.state.pidI, 3); expect(service.state.pidIWindDownMax, 3750); await service.updatePreinfusionSettings(time: 3); await service.updatePIDSettings(i: 3); expect( String.fromCharCodes(platform.writes.expand((bytes) => bytes)), 'cmd set pistrt 3\ncmd set pd1i 3\n', ); }); test('individual edits do not resend unread companion settings', () async { await service.connectToDevice(device); platform.writes.clear(); await service.incrementSetpoint(); expect(platform.writes, isEmpty); expect(service.state.commandError, contains('controller brew setting')); await service.updatePIDSettings(p: 25); await service.updatePressureSettings(start: 80); await service.updateHardwareSettings(flips: true); expect( String.fromCharCodes(platform.writes.expand((bytes) => bytes)), 'cmd set pd1p 25\ncmd set pp1 80\ncmd set pwrflp 1\n', ); }); test('concurrent partial schedule edits preserve both timers', () async { await connect(); platform.writeGate = Completer(); final wakeup = service.updateSchedule(wEnabled: true); final shutdown = service.updateSchedule(sEnabled: true); await Future.delayed(Duration.zero); platform.writeGate!.complete(); platform.writeGate = null; await Future.wait([wakeup, shutdown]); expect( String.fromCharCodes(platform.writes.expand((bytes) => bytes)), 'cmd set tmrwnbl 1\ncmd set tmrsnbl 1\n', ); expect(service.state.wakeupEnabled, isTrue); expect(service.state.shutdownEnabled, isTrue); final prefs = await SharedPreferences.getInstance(); expect(prefs.getBool('wakeupEnabled'), isTrue); expect(prefs.getBool('shutdownEnabled'), isTrue); }); test('V4 rounded settings persist the delivered units', () async { await connect(); platform.notify(device, 'cmd uname meCoffee V4 OK\n'); await Future.delayed(Duration.zero); await service.updatePreinfusionSettings(time: 3.4); await service.updatePIDSettings(i: 2.6); final prefs = await SharedPreferences.getInstance(); expect(service.state.preinfusionTime, 3); expect(prefs.getDouble('preinfusionTime'), 3); expect(service.state.pidI, 3); expect(prefs.getDouble('pidI'), 3); }); test('nonfinite settings do not poison subsequent writes', () async { await connect(); await service.updatePIDSettings(p: double.nan); expect(platform.writes, isEmpty); expect(service.state.commandError, contains('finite')); await service.updatePIDSettings(p: 25); expect(service.state.pidP, 25); expect(service.state.commandError, isNull); }); for (final dispose in [false, true]) { test( 'late persistence cannot update ${dispose ? 'disposed' : 'replacement'} state', () async { service.dispose(); final saving = Completer(); final release = Completer(); service = MeCoffeeService( savePreference: (key, value) async { saving.complete(); await release.future; final prefs = await SharedPreferences.getInstance(); if (value is! double) { throw StateError('Expected temperature value'); } return prefs.setDouble(key, value); }, ); await connect(); final updating = service.updateBrewTemperature(95); await saving.future; if (dispose) { service.dispose(); } else { await service.disconnect(); await service.connectToDevice(device); platform.notify(device, 'cmd get tmpsp 9900\n'); await Future.delayed(Duration.zero); } release.complete(); await updating; if (!dispose) expect(service.state.brewTemperature, 99); expect( (await SharedPreferences.getInstance()).getDouble('brewTemperature'), 95, ); }, ); } test('late PID and shot frames cannot revive stale activity', () async { service.dispose(); service = MeCoffeeService( freshnessTimeout: const Duration(milliseconds: 40), ); await connect(); platform.notify(device, 'tmp 1 10100 9850\n'); await Future.delayed(const Duration(milliseconds: 60)); platform.notify(device, 'pid 65535 0 0\nsht 0 0\n'); await Future.delayed(const Duration(milliseconds: 1100)); expect(service.state.telemetryStale, isTrue); expect(service.state.isHeating, isFalse); expect(service.state.heatingPower, 0); expect(service.state.isBrewing, isFalse); expect(service.state.shotTimer, 0); }); }