Quellcode durchsuchen

Fix high findings

Thomas Hondema vor 1 Monat
Ursprung
Commit
c94ced1ce4

+ 7 - 3
README.md

@@ -67,9 +67,13 @@ an idle machine with a fresh PID frame confirming heating off, a boiler at or
 below 50 C, and explicit confirmation. Pending settings finish while telemetry
 below 50 C, and explicit confirmation. Pending settings finish while telemetry
 continues to be parsed; the safety conditions are rechecked before controller reset.
 continues to be parsed; the safety conditions are rechecked before controller reset.
 
 
-The Intel HEX image is validated before resetting the controller. The programmer
-checks the ATmega328P signature before writing and verifies programmed pages by
-reading them back. Unsupported bootloaders, timeouts, checksum errors, and
+Only controllers reporting `pcb V9` (V9/V10 hardware) are offered the update;
+V4 controllers (`pcb V3`) use a different sensor scale and EEPROM layout and are
+refused. The Intel HEX image is validated before resetting the controller. After
+reconnecting, the app waits 750 ms for the bootloader and retries STK500
+`GET_SYNC` (ignoring application output) before programming; if no bootloader
+answers, nothing is written. The programmer checks the ATmega328P signature
+before writing and verifies programmed pages by reading them back. Unsupported bootloaders, timeouts, checksum errors, and
 verification failures stop the operation and surface an error.
 verification failures stop the operation and surface an error.
 
 
 Do not brew, close the app, or interrupt controller power/Bluetooth during an
 Do not brew, close the app, or interrupt controller power/Bluetooth during an

+ 1 - 0
lib/screens/hardware_settings_screen.dart

@@ -77,6 +77,7 @@ class HardwareSettingsScreen extends ConsumerWidget {
             title: const Text('Install bundled V10 firmware'),
             title: const Text('Install bundled V10 firmware'),
             subtitle: const Text(
             subtitle: const Text(
               'Experimental STK500 update with read-back verification. '
               'Experimental STK500 update with read-back verification. '
+              'Only for "pcb V9" controllers (not V4 / pcb V3). '
               'Requires Bluetooth Classic, live telemetry, heating off, no shot, and a boiler '
               'Requires Bluetooth Classic, live telemetry, heating off, no shot, and a boiler '
               'at or below 50 C. BLE flashing is not available.',
               'at or below 50 C. BLE flashing is not available.',
             ),
             ),

+ 37 - 8
lib/services/bluetooth_service.dart

@@ -82,10 +82,22 @@ class MeCoffeeService extends StateNotifier<MachineState> {
       DateTime.now().difference(_lastPidAt!) < freshnessTimeout &&
       DateTime.now().difference(_lastPidAt!) < freshnessTimeout &&
       !state.telemetryStale &&
       !state.telemetryStale &&
       state.temperature <= 50 &&
       state.temperature <= 50 &&
-      RegExp(
-        r'\bmeCoffee\b',
-        caseSensitive: false,
-      ).hasMatch(state.firmwareVersion);
+      supportsBundledFirmware(
+        state.firmwareVersion,
+        isLegacyV4: state.isLegacyV4Firmware,
+      );
+
+  /// The bundled V10 image targets the `pcb V9` board. V4 controllers report
+  /// `pcb V3`, keep a different sensor scale and EEPROM layout, and were never
+  /// offered V10 by the vendor app, so they must not be flashed with it.
+  @visibleForTesting
+  static bool supportsBundledFirmware(
+    String firmwareVersion, {
+    required bool isLegacyV4,
+  }) =>
+      !isLegacyV4 &&
+      RegExp(r'\bmeCoffee\b', caseSensitive: false).hasMatch(firmwareVersion) &&
+      RegExp(r'\bpcb\s+V9\b', caseSensitive: false).hasMatch(firmwareVersion);
   bool get canUpdateFirmware =>
   bool get canUpdateFirmware =>
       mounted && !_settingsLocked && _machineSafeForFirmware;
       mounted && !_settingsLocked && _machineSafeForFirmware;
 
 
@@ -269,8 +281,15 @@ class MeCoffeeService extends StateNotifier<MachineState> {
   Future<void> updateFirmware() async {
   Future<void> updateFirmware() async {
     if (!canUpdateFirmware) {
     if (!canUpdateFirmware) {
       _reportCommandError(
       _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.',
+        state.firmwareVersion.isNotEmpty &&
+                !supportsBundledFirmware(
+                  state.firmwareVersion,
+                  isLegacyV4: state.isLegacyV4Firmware,
+                )
+            ? 'The bundled V10 firmware only supports "pcb V9" controllers; '
+                  'this controller reports "${state.firmwareVersion}".'
+            : '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;
       return;
     }
     }
@@ -356,6 +375,9 @@ class MeCoffeeService extends StateNotifier<MachineState> {
       state = state.copyWith(
       state = state.copyWith(
         firmwareUpdateStatus: 'Programming and verifying...',
         firmwareUpdateStatus: 'Programming and verifying...',
       );
       );
+      // The reconnect resets the controller into its bootloader; give it time
+      // to start before syncing (the vendor app waits 750 ms here).
+      await _firmwareDelay(const Duration(milliseconds: 750));
       final updater = FirmwareUpdater(
       final updater = FirmwareUpdater(
         write: (bytes) async {
         write: (bytes) async {
           if (!_classicConnected) throw StateError('Bootloader disconnected');
           if (!_classicConnected) throw StateError('Bootloader disconnected');
@@ -418,14 +440,21 @@ class MeCoffeeService extends StateNotifier<MachineState> {
         );
         );
       }
       }
       if (mounted) {
       if (mounted) {
+        final nothingWritten =
+            error is FirmwareUpdateException &&
+            (error.code == FirmwareUpdateError.noBootloader ||
+                error.code == FirmwareUpdateError.signatureMismatch);
         state = state.copyWith(
         state = state.copyWith(
           firmwareUpdating: false,
           firmwareUpdating: false,
           connectionStatus: 'Error: Firmware update failed',
           connectionStatus: 'Error: Firmware update failed',
           firmwareUpdateStatus: 'Update failed: $error',
           firmwareUpdateStatus: 'Update failed: $error',
         );
         );
         _reportCommandError(
         _reportCommandError(
-          'Firmware update failed: $error. Do not brew; the controller may '
-          'require bootloader recovery before it can be used.',
+          nothingWritten
+              ? 'Firmware update failed before programming: $error. No flash '
+                    'was written; power-cycle the machine and reconnect.'
+              : 'Firmware update failed: $error. Do not brew; the controller may '
+                    'require bootloader recovery before it can be used.',
         );
         );
       }
       }
     } finally {
     } finally {

+ 95 - 1
lib/services/firmware_updater.dart

@@ -85,6 +85,9 @@ enum FirmwareUpdateError {
   bufferOverflow,
   bufferOverflow,
   signatureMismatch,
   signatureMismatch,
   verificationFailed,
   verificationFailed,
+
+  /// No STK500 bootloader answered GET_SYNC; nothing was written.
+  noBootloader,
 }
 }
 
 
 class FirmwareUpdateException implements Exception {
 class FirmwareUpdateException implements Exception {
@@ -110,6 +113,14 @@ class FirmwareUpdater {
 
 
   final Future<void> Function(List<int>) write;
   final Future<void> Function(List<int>) write;
   final Duration timeout;
   final Duration timeout;
+
+  /// GET_SYNC is retried this many times, each waiting [syncInterval], because
+  /// the bootloader only starts after the reconnect resets the controller.
+  final int syncAttempts;
+  final Duration syncInterval;
+
+  /// After sync, late answers to earlier GET_SYNC attempts are discarded.
+  final Duration syncSettle;
   final Queue<int> _buffer = Queue<int>();
   final Queue<int> _buffer = Queue<int>();
   late final StreamSubscription<List<int>> _subscription;
   late final StreamSubscription<List<int>> _subscription;
   Completer<List<int>>? _reply;
   Completer<List<int>>? _reply;
@@ -118,15 +129,22 @@ class FirmwareUpdater {
   bool _flashing = false;
   bool _flashing = false;
   bool _disposed = false;
   bool _disposed = false;
   bool _finished = false;
   bool _finished = false;
+  bool _syncing = false;
 
 
   FirmwareUpdater({
   FirmwareUpdater({
     required this.write,
     required this.write,
     required Stream<List<int>> received,
     required Stream<List<int>> received,
     this.timeout = const Duration(seconds: 3),
     this.timeout = const Duration(seconds: 3),
+    this.syncAttempts = 12,
+    this.syncInterval = const Duration(milliseconds: 250),
+    this.syncSettle = const Duration(milliseconds: 100),
   }) {
   }) {
     if (timeout <= Duration.zero) {
     if (timeout <= Duration.zero) {
       throw ArgumentError.value(timeout, 'timeout', 'Must be positive');
       throw ArgumentError.value(timeout, 'timeout', 'Must be positive');
     }
     }
+    if (syncAttempts < 1 || syncInterval <= Duration.zero) {
+      throw ArgumentError('GET_SYNC needs at least one positive attempt');
+    }
     // Install before the first write, including synchronous transport replies.
     // Install before the first write, including synchronous transport replies.
     _subscription = received.listen(
     _subscription = received.listen(
       _receive,
       _receive,
@@ -180,6 +198,24 @@ class FirmwareUpdater {
   void _drain() {
   void _drain() {
     final reply = _reply;
     final reply = _reply;
     if (reply == null || reply.isCompleted || _buffer.isEmpty) return;
     if (reply == null || reply.isCompleted || _buffer.isEmpty) return;
+    if (_syncing) {
+      // Before sync, skip application output and partial replies until an
+      // STK_INSYNC/STK_OK pair arrives.
+      while (_buffer.isNotEmpty) {
+        if (_buffer.first != 0x14) {
+          _buffer.removeFirst();
+          continue;
+        }
+        if (_buffer.length < 2) return;
+        _buffer.removeFirst();
+        if (_buffer.first == 0x10) {
+          _buffer.removeFirst();
+          reply.complete(const []);
+          return;
+        }
+      }
+      return;
+    }
     if (_buffer.first != 0x14) {
     if (_buffer.first != 0x14) {
       _fail(
       _fail(
         const FirmwareUpdateException(
         const FirmwareUpdateException(
@@ -244,6 +280,64 @@ class FirmwareUpdater {
     }
     }
   }
   }
 
 
+  Future<void> _synchronize() async {
+    for (var attempt = 0; attempt < syncAttempts; attempt++) {
+      if (_failure case final failure?) throw failure;
+      final reply = Completer<List<int>>();
+      _reply = reply;
+      _replyLength = 0;
+      _syncing = true;
+      try {
+        final exchange = Future.wait<Object?>([
+          reply.future,
+          Future<void>.sync(() => write(const [0x30, 0x20])),
+        ], eagerError: true);
+        // A write still pending when this attempt times out must not surface
+        // later as an unhandled error.
+        exchange.ignore();
+        await exchange.timeout(syncInterval);
+        _reply = null;
+        _syncing = false;
+        await Future<void>.delayed(syncSettle);
+        if (_failure case final failure?) throw failure;
+        _buffer.clear();
+        return;
+      } on TimeoutException {
+        if (reply.isCompleted) {
+          // The bootloader answered but the transport never finished the
+          // write: a stalled link, not a missing bootloader.
+          const failure = FirmwareUpdateException(
+            FirmwareUpdateError.timeout,
+            'Timed out waiting for bootloader command delivery/response',
+          );
+          _fail(failure);
+          throw failure;
+        }
+        continue;
+      } on FirmwareUpdateException catch (error) {
+        _fail(error);
+        rethrow;
+      } catch (error) {
+        final failure = FirmwareUpdateException(
+          FirmwareUpdateError.transport,
+          'Bootloader command delivery failed',
+          cause: error,
+        );
+        _fail(failure);
+        throw failure;
+      } finally {
+        _reply = null;
+        _syncing = false;
+      }
+    }
+    final failure = FirmwareUpdateException(
+      FirmwareUpdateError.noBootloader,
+      'No STK500 bootloader answered GET_SYNC after $syncAttempts attempts',
+    );
+    _fail(failure);
+    throw failure;
+  }
+
   Future<void> _loadAddress(int byteAddress) async {
   Future<void> _loadAddress(int byteAddress) async {
     final wordAddress = byteAddress ~/ 2;
     final wordAddress = byteAddress ~/ 2;
     await _exchange([0x55, wordAddress & 0xff, wordAddress >> 8, 0x20]);
     await _exchange([0x55, wordAddress & 0xff, wordAddress >> 8, 0x20]);
@@ -269,7 +363,7 @@ class FirmwareUpdater {
     _flashing = true;
     _flashing = true;
     try {
     try {
       onProgress?.call(0);
       onProgress?.call(0);
-      await _exchange([0x30, 0x20]);
+      await _synchronize();
       await _exchange([0x50, 0x20]);
       await _exchange([0x50, 0x20]);
       final signature = await _exchange([0x75, 0x20], responseLength: 3);
       final signature = await _exchange([0x75, 0x20], responseLength: 3);
       final actual = (signature[0] << 16) | (signature[1] << 8) | signature[2];
       final actual = (signature[0] << 16) | (signature[1] << 8) | signature[2];

+ 28 - 10
lib/services/me_coffee_protocol.dart

@@ -44,10 +44,21 @@ class MeCoffeeProtocol {
           if (!raw.isFinite) return currentState;
           if (!raw.isFinite) return currentState;
           if (raw > 5.0 && raw < 20000) sensor2 = raw / 100.0;
           if (raw > 5.0 && raw < 20000) sensor2 = raw / 100.0;
         }
         }
+        // While steam is active the firmware reports tmpstm as the setpoint,
+        // including phases where the boiler is above it and no marker is sent.
+        var isSteaming = currentState.isSteaming;
+        final steamRaw = (currentState.steamTemperature * 100).round();
+        final brewRaw = (currentState.brewTemperature * 100).round();
+        if (steamRaw != brewRaw) {
+          final setpointRaw = double.parse(parts[2]).round();
+          if (setpointRaw == steamRaw) isSteaming = true;
+          if (setpointRaw == brewRaw) isSteaming = false;
+        }
         return currentState.copyWith(
         return currentState.copyWith(
           targetTemperature: setpoint,
           targetTemperature: setpoint,
           temperature: boiler,
           temperature: boiler,
           sensor2Temperature: sensor2 ?? currentState.sensor2Temperature,
           sensor2Temperature: sensor2 ?? currentState.sensor2Temperature,
+          isSteaming: isSteaming,
         );
         );
       } catch (_) {}
       } catch (_) {}
     }
     }
@@ -61,16 +72,23 @@ class MeCoffeeProtocol {
         int d = int.parse(parts[3]);
         int d = int.parse(parts[3]);
         int f = parts.length >= 5 ? int.parse(parts[4]) : 0;
         int f = parts.length >= 5 ? int.parse(parts[4]) : 0;
 
 
-        // V9/V10 send the fixed line `pid 65535 0 0 0` when the steam input
-        // becomes active. It is an event marker, not controller output: the
-        // boiler is then switched fully on or off around the steam setpoint
-        // and no further `pid` lines arrive until steam ends.
-        if (parts.length == 5 && p == 65535 && i == 0 && d == 0 && f == 0) {
-          return currentState.copyWith(
-            isSteaming: true,
-            isHeating: true,
-            heatingPower: 0,
-          );
+        // V9/V10 steam markers. While the steam input is active no PID frames
+        // are sent and the boiler is switched fully on below tmpstm and off at
+        // or above it: `pid 65535 0 0 0` (steam start, heater on),
+        // `pid 65536 0 0 0` (heater on again) and `pid 0 0 0 0` (heater off;
+        // also sent on steam release and power-off). Steam itself is tracked
+        // from the `tmp` setpoint and from the next regular PID frame.
+        if (parts.length == 5 && i == 0 && d == 0 && f == 0) {
+          if (p == 65535 || p == 65536) {
+            return currentState.copyWith(
+              isSteaming: true,
+              isHeating: true,
+              heatingPower: 1.0,
+            );
+          }
+          if (p == 0 && currentState.isSteaming) {
+            return currentState.copyWith(isHeating: false, heatingPower: 0);
+          }
         }
         }
 
 
         double totalPower = (p + i + d + f) / 65535.0;
         double totalPower = (p + i + d + f) / 65535.0;

+ 310 - 0
test/firmware/v10_firmware_conformance_test.dart

@@ -0,0 +1,310 @@
+// Conformance of the protocol layer against transcripts recorded from the
+// original meCoffee V10 firmware image running in simavr.
+//
+// Regenerate the fixture with `python3 sim/generate_transcripts.py` in the
+// meCoffee firmware workspace and copy it to test/fixtures/. Every received
+// line was produced by the unmodified firmware; the `send` strings are what
+// this client must emit for the listed settings.
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:mebarista/models/machine_state.dart';
+import 'package:mebarista/services/me_coffee_protocol.dart';
+
+final Map<String, dynamic> fixture =
+    jsonDecode(
+          File('test/fixtures/v10_golden_transcripts.json').readAsStringSync(),
+        )
+        as Map<String, dynamic>;
+
+Object? field(MachineState s, String name) => switch (name) {
+  'brewTemperature' => s.brewTemperature,
+  'steamTemperature' => s.steamTemperature,
+  'pidP' => s.pidP,
+  'pidI' => s.pidI,
+  'pidD' => s.pidD,
+  'pidIWindDownMin' => s.pidIWindDownMin,
+  'pidIWindDownMax' => s.pidIWindDownMax,
+  'pidPollingInterval' => s.pidPollingInterval,
+  'preinfusionEnabled' => s.preinfusionEnabled,
+  'preinfusionTime' => s.preinfusionTime,
+  'preinfusionPauseTime' => s.preinfusionPauseTime,
+  'valveClosedWhilePaused' => s.valveClosedWhilePaused,
+  'proActivePercentage' => s.proActivePercentage,
+  'autoShutoffMinutes' => s.autoShutoffMinutes,
+  'maxShotTime' => s.maxShotTime,
+  'continuousMode' => s.continuousMode,
+  'installedAsTimer' => s.installedAsTimer,
+  'powerButtonFlipsBack' => s.powerButtonFlipsBack,
+  'output0' => s.output0,
+  'output1' => s.output1,
+  'output2' => s.output2,
+  'wakeupEnabled' => s.wakeupEnabled,
+  'wakeupTime' => s.wakeupTime,
+  'shutdownEnabled' => s.shutdownEnabled,
+  'shutdownTime' => s.shutdownTime,
+  'pressureStart' => s.pressureStart,
+  'pressureEnd' => s.pressureEnd,
+  'pressurePeriod' => s.pressurePeriod,
+  _ => throw ArgumentError('unmapped MachineState field $name'),
+};
+
+Object clientValue(Map<String, dynamic> w) => switch (w['kind']) {
+  'double' => (w['value'] as num).toDouble(),
+  'int' => w['value'] as int,
+  'bool' => w['value'] as bool,
+  'time' => w['value'] as String,
+  _ => throw ArgumentError('unknown kind ${w['kind']}'),
+};
+
+Matcher expectation(Object? expected) =>
+    expected is double ? closeTo(expected, 1e-6) : equals(expected);
+
+MachineState parseAll(Iterable<String> lines, [MachineState? start]) =>
+    lines.fold(
+      start ?? MachineState(),
+      (state, line) => MeCoffeeProtocol.parse(line, state),
+    );
+
+List<String> scenarioLines(String name) {
+  final scenario = (fixture['scenarios'] as List)
+      .cast<Map<String, dynamic>>()
+      .firstWhere((s) => s['name'] == name);
+  return [
+    for (final e in (scenario['receive'] as List).cast<Map<String, dynamic>>())
+      e['line'] as String,
+  ];
+}
+
+void main() {
+  final writes = (fixture['setting_writes'] as List)
+      .cast<Map<String, dynamic>>();
+
+  test('fixture comes from the bundled V10 image', () {
+    final hex = File('meBarista_for_Android/assets/meCoffee-V10.hex');
+    if (!hex.existsSync()) return;
+    expect(
+      fixture['firmware_hex_sha256'],
+      'ba8a21559881bac6a624b5cccb372fc31cafeee70c76babcb41e57f5e476c4ac',
+    );
+  });
+
+  group('V10 firmware conformance: settings writes', () {
+    for (final w in writes) {
+      final key = w['key'] as String;
+
+      test('$key: encoder emits the command the firmware accepted', () {
+        expect(MeCoffeeProtocol.encodeSet(key, clientValue(w)), w['send']);
+        final reply = (w['reply'] as List).cast<String>();
+        expect(reply, hasLength(1));
+        expect(reply.single, startsWith('cmd set s_$key '));
+        expect(reply.single, endsWith(' OK'));
+        expect(reply.single, isNot(contains('NOT OK')));
+        final stored = reply.single.split(' ')[3];
+        expect((w['readback'] as List).single, 'cmd get $key $stored OK');
+      });
+
+      test('$key: firmware echo and readback parse to the intended value', () {
+        final expected = expectation(w['expect']);
+        final echoed = parseAll((w['reply'] as List).cast<String>());
+        expect(field(echoed, w['field'] as String), expected);
+        final readBack = parseAll((w['readback'] as List).cast<String>());
+        expect(field(readBack, w['field'] as String), expected);
+      });
+    }
+
+    test('every written setting survives a controller reboot', () {
+      final dump = (fixture['dump_after_reboot'] as List).cast<String>();
+      expect(dump.first, 'cmd dump  OK');
+      expect(dump.last, 'cmd dump 35 OK');
+      final state = parseAll(dump);
+      for (final w in writes) {
+        expect(
+          field(state, w['field'] as String),
+          expectation(w['expect']),
+          reason: w['key'] as String,
+        );
+      }
+    });
+
+    test('a batched settings write is acknowledged command by command', () {
+      final batch = fixture['batched_write'] as Map<String, dynamic>;
+      final byKey = {for (final w in writes) w['key'] as String: w};
+      final payload = ['pinbl', 'pistrt', 'piprd', 'pivlv']
+          .map((k) => MeCoffeeProtocol.encodeSet(k, clientValue(byKey[k]!)))
+          .join();
+      expect(payload, batch['send']);
+      final replies = (batch['reply'] as List).cast<String>();
+      expect(replies, hasLength(4));
+      expect(
+        replies.every((r) => r.endsWith(' OK') && !r.contains('NOT')),
+        isTrue,
+      );
+    });
+  });
+
+  group('V10 firmware conformance: connection start-up', () {
+    final init = fixture['init'] as Map<String, dynamic>;
+    final received = (init['receive'] as List).cast<String>();
+    final state = parseAll([
+      ...(init['boot'] as List).cast<String>(),
+      ...received,
+    ]);
+
+    test('controller identity is recognised as modern (not V4) firmware', () {
+      expect(received, contains('cmd uname meCoffee  pcb V9 30 149 15 OK'));
+      expect(state.firmwareVersion, contains('pcb V9'));
+      expect(state.isLegacyV4Firmware, isFalse);
+    });
+
+    test('dump delivers all 35 settings between start and end markers', () {
+      final gets = received.where((l) => l.startsWith('cmd get '));
+      expect(gets, hasLength(35));
+      expect(received, contains('cmd dump  OK'));
+      expect(received, contains('cmd dump 35 OK'));
+    });
+
+    test('factory defaults decode with the client scaling', () {
+      expect(state.brewTemperature, 101.0);
+      expect(state.steamTemperature, 125.0);
+      expect(state.pidP, 20);
+      expect(state.pidI, closeTo(0.30, 1e-9));
+      expect(state.pidD, 128);
+      expect(state.pidIWindDownMin, closeTo(1000 / 655.36, 1e-9));
+      expect(state.pidIWindDownMax, closeTo(13107 / 655.36, 1e-9));
+      expect(state.pidPollingInterval, 1000);
+      expect(state.preinfusionEnabled, isFalse);
+      expect(state.preinfusionTime, 3.0);
+      expect(state.preinfusionPauseTime, 3.0);
+      expect(state.continuousMode, isTrue);
+      expect(state.proActivePercentage, 33);
+      expect(state.autoShutoffMinutes, 60);
+      expect([state.output0, state.output1, state.output2], [112, 98, 118]);
+      expect(
+        [state.pressureStart, state.pressureEnd, state.pressurePeriod],
+        [100, 100, 25],
+      );
+      expect(state.maxShotTime, 0);
+      expect(state.grinderCounter, 0);
+    });
+
+    test('telemetry decodes the boiler sensor', () {
+      expect(state.temperature, closeTo(92.83, 1e-9));
+      expect(state.targetTemperature, 101.0);
+    });
+  });
+
+  group('V10 firmware conformance: replies the client must ignore', () {
+    final rejections = (fixture['rejections'] as List)
+        .cast<Map<String, dynamic>>();
+
+    test('unknown keys, CR-terminated lines and diagnostics leave state', () {
+      final base = parseAll(['cmd get tmpsp 9350 OK']);
+      for (final r in rejections) {
+        final send = r['send'] as String;
+        if (send.startsWith('cmd set tmpsp 9350 OK')) continue;
+        for (final line in (r['reply'] as List).cast<String>()) {
+          final next = MeCoffeeProtocol.parse(line, base);
+          expect(identical(next, base), isTrue, reason: '$send -> "$line"');
+        }
+      }
+    });
+
+    test('firmware rejects keys only some clients use', () {
+      String replyTo(String send) =>
+          (rejections.firstWhere((r) => r['send'] == send)['reply'] as List)
+                  .single
+              as String;
+      expect(replyTo('cmd get grndr_cnt\n'), 'cmd get  NOT OK');
+      expect(replyTo('cmd set tmpoff 5\n'), 'cmd set  NOT OK');
+      expect(replyTo('cmd get pd1imm\n'), 'cmd get  NOT OK');
+      expect(replyTo('cmd get tmpsp\r\n'), 'cmd get  NOT OK');
+    });
+  });
+
+  group('V10 firmware conformance: machine events', () {
+    test('a 6 s shot is timed from the firmware sht frames', () {
+      final lines = scenarioLines('shot_6s');
+      var state = MachineState();
+      var sawBrewing = false;
+      for (final line in lines) {
+        state = MeCoffeeProtocol.parse(line, state);
+        sawBrewing |= state.isBrewing;
+      }
+      expect(sawBrewing, isTrue);
+      expect(state.isBrewing, isFalse);
+      expect(state.shotTimer, 6);
+    });
+
+    test('a shtmx cutoff keeps the cutoff duration, not the release', () {
+      final state = parseAll(scenarioLines('shot_cutoff_shtmx_2'));
+      expect(state.isBrewing, isFalse);
+      expect(state.shotTimer, 2);
+    });
+
+    test('preinfusion gap is included in the shot duration', () {
+      final state = parseAll(scenarioLines('shot_preinfusion_1s_gap_1s'));
+      expect(state.shotTimer, 5);
+    });
+
+    test('steam marker, steam setpoint and return to brew', () {
+      final lines = scenarioLines('steam_3s');
+      var state = MachineState();
+      var sawSteam = false;
+      for (final line in lines) {
+        state = MeCoffeeProtocol.parse(line, state);
+        if (state.isSteaming) {
+          sawSteam = true;
+          if (line.startsWith('tmp ')) expect(state.targetTemperature, 125.0);
+        }
+      }
+      expect(sawSteam, isTrue);
+      expect(state.isSteaming, isFalse);
+      expect(state.targetTemperature, 101.0);
+    });
+
+    for (final name in ['steam_reaching_tmpstm', 'steam_start_above_tmpstm']) {
+      test('$name: steam persists while the heater cycles', () {
+        final lines = scenarioLines(name);
+        final start = lines.indexOf('pid 65535 0 0 0 OK');
+        final end = lines.lastIndexWhere(
+          (l) => l.startsWith('tmp ') && l.split(' ')[2] == '12500',
+        );
+        expect(start, greaterThanOrEqualTo(0));
+        var state = MachineState();
+        for (var i = 0; i < lines.length; i++) {
+          state = MeCoffeeProtocol.parse(lines[i], state);
+          if (i >= start && i <= end) {
+            expect(state.isSteaming, isTrue, reason: lines[i]);
+          }
+          if (lines[i].startsWith('pid ') && state.isSteaming) {
+            final heaterOn = lines[i] != 'pid 0 0 0 0 OK';
+            expect(state.isHeating, heaterOn, reason: lines[i]);
+            expect(state.heatingPower, heaterOn ? 1.0 : 0.0, reason: lines[i]);
+          }
+        }
+        expect(state.isSteaming, isFalse);
+        expect(state.targetTemperature, 101.0);
+      });
+    }
+
+    test('power switch off reports zero heating', () {
+      final state = parseAll(scenarioLines('power_switch_off'));
+      expect(state.heatingPower, 0);
+      expect(state.isHeating, isFalse);
+    });
+
+    test('sensor range switch above 110 C is transparent to the client', () {
+      final lines = scenarioLines('sensor_saturated_range_switch');
+      final temps = <double>[];
+      var state = MachineState();
+      for (final line in lines) {
+        state = MeCoffeeProtocol.parse(line, state);
+        if (line.startsWith('tmp ')) temps.add(state.temperature);
+      }
+      expect(temps.reduce((a, b) => a > b ? a : b), closeTo(129.79, 1e-9));
+      expect(temps.last, closeTo(79.94, 1e-9));
+    });
+  });
+}

Datei-Diff unterdrückt, da er zu groß ist
+ 1307 - 0
test/fixtures/v10_golden_transcripts.json


+ 18 - 2
test/services/classic_service_test.dart

@@ -51,7 +51,7 @@ class FakeClassicTransport extends ClassicBluetoothTransport {
     writes.add(List.of(bytes));
     writes.add(List.of(bytes));
     if (respondToIdentity &&
     if (respondToIdentity &&
         String.fromCharCodes(bytes).contains('cmd uname')) {
         String.fromCharCodes(bytes).contains('cmd uname')) {
-      data.add('cmd uname meCoffee V10 OK\n'.codeUnits);
+      data.add('cmd uname meCoffee  pcb V9 30 149 15 OK\n'.codeUnits);
     }
     }
     if (String.fromCharCodes(bytes).contains('cmd reset en')) {
     if (String.fromCharCodes(bytes).contains('cmd reset en')) {
       resets++;
       resets++;
@@ -142,7 +142,7 @@ void main() {
 
 
   void reportIdleMachine() {
   void reportIdleMachine() {
     transport.data.add(
     transport.data.add(
-      'cmd uname meCoffee V10 OK\ntmp 1 10100 2000 OK\npid 0 0 0 OK\n'
+      'cmd uname meCoffee  pcb V9 30 149 15 OK\ntmp 1 10100 2000 OK\npid 0 0 0 OK\n'
           .codeUnits,
           .codeUnits,
     );
     );
   }
   }
@@ -231,6 +231,22 @@ void main() {
     expect(transport.resets, 0);
     expect(transport.resets, 0);
   });
   });
 
 
+  test('bundled V10 is only offered to pcb V9 controllers', () async {
+    await connect();
+    reportIdleMachine();
+    expect(service.canUpdateFirmware, isTrue);
+    for (final identity in [
+      'cmd uname meCoffee V4 pcb V3 OK',
+      'cmd uname meCoffee V10 OK',
+    ]) {
+      transport.data.add('$identity\npid 0 0 0\n'.codeUnits);
+      expect(service.canUpdateFirmware, isFalse, reason: identity);
+      await service.updateFirmware();
+      expect(transport.resets, 0);
+      expect(service.state.commandError, contains('pcb V9'));
+    }
+  });
+
   test('V4 cannot send unsupported modern settings', () async {
   test('V4 cannot send unsupported modern settings', () async {
     await connect();
     await connect();
     transport.data.add('cmd uname meCoffee V4 OK\n'.codeUnits);
     transport.data.add('cmd uname meCoffee V4 OK\n'.codeUnits);

+ 58 - 6
test/services/firmware_updater_test.dart

@@ -23,6 +23,8 @@ class FakeBootloader {
   List<int> signature = [0x1e, 0x95, 0x0f];
   List<int> signature = [0x1e, 0x95, 0x0f];
   int address = 0;
   int address = 0;
   int? silentCommand;
   int? silentCommand;
+  int ignoredSyncs = 0;
+  bool duplicateSync = false;
   int? failedCommand;
   int? failedCommand;
   bool corruptRead = false;
   bool corruptRead = false;
   bool fragment = false;
   bool fragment = false;
@@ -30,6 +32,17 @@ class FakeBootloader {
   Future<void> write(List<int> command) async {
   Future<void> write(List<int> command) async {
     commands.add(List.of(command));
     commands.add(List.of(command));
     if (command.first == silentCommand) return;
     if (command.first == silentCommand) return;
+    if (command.first == 0x30 && ignoredSyncs > 0) {
+      ignoredSyncs--;
+      // The application is still running: its telemetry is noise here.
+      controller.add('tmp 3 10100 2000 0 OK\r\n'.codeUnits);
+      return;
+    }
+    if (command.first == 0x30 && duplicateSync) {
+      controller.add([0x14, 0x10, 0x14]);
+      controller.add([0x10]);
+      return;
+    }
     if (command.first == failedCommand) {
     if (command.first == failedCommand) {
       controller.add([0x14, 0x11]);
       controller.add([0x14, 0x11]);
       return;
       return;
@@ -69,12 +82,17 @@ class FakeBootloader {
     }
     }
   }
   }
 
 
-  FirmwareUpdater updater({Duration timeout = const Duration(seconds: 1)}) =>
-      FirmwareUpdater(
-        write: write,
-        received: controller.stream,
-        timeout: timeout,
-      );
+  FirmwareUpdater updater({
+    Duration timeout = const Duration(seconds: 1),
+    int syncAttempts = 12,
+  }) => FirmwareUpdater(
+    write: write,
+    received: controller.stream,
+    timeout: timeout,
+    syncAttempts: syncAttempts,
+    syncInterval: const Duration(milliseconds: 20),
+    syncSettle: const Duration(milliseconds: 5),
+  );
 }
 }
 
 
 void main() {
 void main() {
@@ -163,6 +181,40 @@ void main() {
     }
     }
   });
   });
 
 
+  group('STK500v1 bootloader sync', () {
+    final firmware = IntelHexFirmware.parse(image([1, 2, 3, 4]));
+
+    test('retries GET_SYNC past application output until in sync', () async {
+      final bootloader = FakeBootloader()..ignoredSyncs = 4;
+      final updater = bootloader.updater();
+      await updater.flash(firmware);
+      final syncs = bootloader.commands.where((c) => c.first == 0x30);
+      expect(syncs, hasLength(5));
+      expect(bootloader.flash.sublist(0, 4), [1, 2, 3, 4]);
+      await updater.dispose();
+    });
+
+    test('discards a late duplicate sync reply before programming', () async {
+      final bootloader = FakeBootloader()..duplicateSync = true;
+      final updater = bootloader.updater();
+      await updater.flash(firmware);
+      expect(bootloader.flash.sublist(0, 4), [1, 2, 3, 4]);
+      await updater.dispose();
+    });
+
+    test('no bootloader: bounded attempts and nothing written', () async {
+      final bootloader = FakeBootloader()..ignoredSyncs = 1 << 30;
+      final updater = bootloader.updater(syncAttempts: 5);
+      await expectLater(
+        updater.flash(firmware),
+        throwsA(failure(FirmwareUpdateError.noBootloader)),
+      );
+      expect(bootloader.commands.map((c) => c.first).toSet(), {0x30});
+      expect(bootloader.commands, hasLength(5));
+      await updater.dispose();
+    });
+  });
+
   group('STK500v1 programming', () {
   group('STK500v1 programming', () {
     for (final fragmented in [false, true]) {
     for (final fragmented in [false, true]) {
       test('writes and verifies pages (fragmented=$fragmented)', () async {
       test('writes and verifies pages (fragmented=$fragmented)', () async {

+ 35 - 6
test/services/me_coffee_protocol_test.dart

@@ -138,24 +138,53 @@ void main() {
       expect(state.shotTimer, 2);
       expect(state.shotTimer, 2);
     });
     });
 
 
-    test('treats pid 65535 0 0 0 as the steam marker, not full power', () {
+    test('steam markers switch the heater without ending steam', () {
       final heating = MachineState(heatingPower: 0.3, isHeating: true);
       final heating = MachineState(heatingPower: 0.3, isHeating: true);
       final steaming = MeCoffeeProtocol.parse('pid 65535 0 0 0 OK', heating);
       final steaming = MeCoffeeProtocol.parse('pid 65535 0 0 0 OK', heating);
 
 
       expect(steaming.isSteaming, isTrue);
       expect(steaming.isSteaming, isTrue);
       expect(steaming.isHeating, isTrue);
       expect(steaming.isHeating, isTrue);
-      expect(steaming.heatingPower, 0);
-
-      final released = MeCoffeeProtocol.parse('pid 0 0 0 0 OK', steaming);
+      expect(steaming.heatingPower, 1.0);
+
+      // Boiler reached tmpstm: heater off, steam switch still on.
+      final atSteamTemp = MeCoffeeProtocol.parse('pid 0 0 0 0 OK', steaming);
+      expect(atSteamTemp.isSteaming, isTrue);
+      expect(atSteamTemp.isHeating, isFalse);
+      expect(atSteamTemp.heatingPower, 0);
+
+      // Below tmpstm again: V10 reports 65536, not 65535.
+      final reheating = MeCoffeeProtocol.parse(
+        'pid 65536 0 0 0 OK',
+        atSteamTemp,
+      );
+      expect(reheating.isSteaming, isTrue);
+      expect(reheating.isHeating, isTrue);
+      expect(reheating.heatingPower, 1.0);
+
+      // Release: the setpoint in tmp returns to tmpsp.
+      final released = MeCoffeeProtocol.parse(
+        'tmp 9 10100 11990 0 - 619 100 128 128 OK',
+        MeCoffeeProtocol.parse('pid 0 0 0 0 OK', reheating),
+      );
       expect(released.isSteaming, isFalse);
       expect(released.isSteaming, isFalse);
-      expect(released.isHeating, isFalse);
-      expect(released.heatingPower, 0);
 
 
       final resumed = MeCoffeeProtocol.parse('pid 2200 1258 0 0 OK', steaming);
       final resumed = MeCoffeeProtocol.parse('pid 2200 1258 0 0 OK', steaming);
       expect(resumed.isSteaming, isFalse);
       expect(resumed.isSteaming, isFalse);
       expect(resumed.heatingPower, closeTo(3458 / 65535, 1e-9));
       expect(resumed.heatingPower, closeTo(3458 / 65535, 1e-9));
     });
     });
 
 
+    test('tmp setpoint equal to tmpstm marks steam without a marker', () {
+      final state = MeCoffeeProtocol.parse(
+        'tmp 7 12500 12785 0 - 619 100 128 128 OK',
+        MachineState(),
+      );
+      expect(state.isSteaming, isTrue);
+      expect(
+        MeCoffeeProtocol.parse('pid 0 0 0 0 OK', MachineState()).isSteaming,
+        isFalse,
+      );
+    });
+
     test('V4 three-field pid 65535 0 0 is still full power', () {
     test('V4 three-field pid 65535 0 0 is still full power', () {
       final state = MeCoffeeProtocol.parse('pid 65535 0 0', MachineState());
       final state = MeCoffeeProtocol.parse('pid 65535 0 0', MachineState());