ソースを参照

Merge branch 'ble_fix' of thomashondema/meBarista_in_Flutter into main

thomashondema 1 ヶ月 前
親
コミット
2a13b1fdf1

+ 9 - 5
README.md

@@ -63,13 +63,17 @@ For more information on the original project and its opening to the community, v
 Hardware Configuration can install the existing bundled V10 firmware through an
 Android Classic/SPP connection. This is an experimental STK500v1 operation, not a
 network download or a BLE OTA implementation. It requires live temperature data,
-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
+the machine switched off at its power switch (confirmed by a `pid 0 0 0 0` frame
+on live telemetry), a boiler at or below 50 C, and explicit confirmation. Pending settings finish while telemetry
 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.
 
 Do not brew, close the app, or interrupt controller power/Bluetooth during an

+ 4 - 0
lib/main.dart

@@ -211,6 +211,8 @@ class MyHomePage extends ConsumerWidget {
                               child: LinearProgressIndicator(
                                 value: machineState.telemetryStale
                                     ? 0
+                                    : machineState.isSteaming
+                                    ? null
                                     : machineState.heatingPower,
                                 backgroundColor: Colors.grey.withValues(
                                   alpha: 0.2,
@@ -224,6 +226,8 @@ class MyHomePage extends ConsumerWidget {
                           Text(
                             machineState.telemetryStale
                                 ? 'Unavailable'
+                                : machineState.isSteaming
+                                ? 'Steam'
                                 : '${(machineState.heatingPower * 100).toStringAsFixed(0)}%',
                             style: const TextStyle(
                               fontSize: 12,

+ 12 - 0
lib/models/machine_state.dart

@@ -6,6 +6,11 @@ class MachineState {
   final double targetTemperature;
   final bool isHeating;
   final bool isBrewing;
+
+  /// Steam input active (V9/V10 `pid 65535 0 0 0` marker). The firmware
+  /// switches the boiler on/off around the steam setpoint and sends no PID
+  /// output, so [heatingPower] is unknown while this is set.
+  final bool isSteaming;
   final int shotTimer;
   final String connectionStatus;
   final String? commandError;
@@ -53,6 +58,7 @@ class MachineState {
   final bool valveClosedWhilePaused;
   final int proActivePercentage;
   final int autoShutoffMinutes;
+  final bool autoShutoffEnabled; // tmrosdnbl – inactivity shut-off gate
 
   // Scheduling
   final bool wakeupEnabled;
@@ -84,6 +90,7 @@ class MachineState {
     this.targetTemperature = 101.0,
     this.isHeating = false,
     this.isBrewing = false,
+    this.isSteaming = false,
     this.shotTimer = 0,
     this.connectionStatus = 'Disconnected',
     this.commandError,
@@ -117,6 +124,7 @@ class MachineState {
     this.valveClosedWhilePaused = false,
     this.proActivePercentage = 33,
     this.autoShutoffMinutes = 60,
+    this.autoShutoffEnabled = false,
     this.wakeupEnabled = false,
     this.wakeupTime = "07:00",
     this.shutdownEnabled = false,
@@ -139,6 +147,7 @@ class MachineState {
     double? targetTemperature,
     bool? isHeating,
     bool? isBrewing,
+    bool? isSteaming,
     int? shotTimer,
     String? connectionStatus,
     String? commandError,
@@ -174,6 +183,7 @@ class MachineState {
     bool? valveClosedWhilePaused,
     int? proActivePercentage,
     int? autoShutoffMinutes,
+    bool? autoShutoffEnabled,
     bool? wakeupEnabled,
     String? wakeupTime,
     bool? shutdownEnabled,
@@ -195,6 +205,7 @@ class MachineState {
       targetTemperature: targetTemperature ?? this.targetTemperature,
       isHeating: isHeating ?? this.isHeating,
       isBrewing: isBrewing ?? this.isBrewing,
+      isSteaming: isSteaming ?? this.isSteaming,
       shotTimer: shotTimer ?? this.shotTimer,
       connectionStatus: connectionStatus ?? this.connectionStatus,
       commandError: clearCommandError
@@ -234,6 +245,7 @@ class MachineState {
           valveClosedWhilePaused ?? this.valveClosedWhilePaused,
       proActivePercentage: proActivePercentage ?? this.proActivePercentage,
       autoShutoffMinutes: autoShutoffMinutes ?? this.autoShutoffMinutes,
+      autoShutoffEnabled: autoShutoffEnabled ?? this.autoShutoffEnabled,
       wakeupEnabled: wakeupEnabled ?? this.wakeupEnabled,
       wakeupTime: wakeupTime ?? this.wakeupTime,
       shutdownEnabled: shutdownEnabled ?? this.shutdownEnabled,

+ 3 - 2
lib/screens/hardware_settings_screen.dart

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

+ 41 - 33
lib/screens/pid_settings_screen.dart

@@ -72,25 +72,14 @@ class PIDSettingsScreen extends ConsumerWidget {
             step: isLegacyV4 ? 250 : 1,
             onChanged: (v) => bluetoothService.updatePIDLimitSettings(max: v),
           ),
-          ListTile(
-            title: const Text('Polling Interval (ms)'),
-            subtitle: Text('${machineState.pidPollingInterval} ms'),
-            trailing: SizedBox(
-              width: 200,
-              child: Slider(
-                value: machineState.pidPollingInterval.toDouble().clamp(
-                  1000.0,
-                  10000.0,
-                ),
-                min: 1000,
-                max: 10000,
-                divisions: 18, // 500 ms steps
-                label: '${machineState.pidPollingInterval} ms',
-                onChanged: (v) {
-                  bluetoothService.updatePIDLimitSettings(interval: v.round());
-                },
-              ),
-            ),
+          _PIDSlider(
+            label: 'Polling Interval (ms)',
+            value: machineState.pidPollingInterval.toDouble(),
+            min: 1000,
+            max: 10000,
+            step: 500,
+            onChanged: (v) =>
+                bluetoothService.updatePIDLimitSettings(interval: v.round()),
           ),
         ],
       ),
@@ -98,7 +87,9 @@ class PIDSettingsScreen extends ConsumerWidget {
   }
 }
 
-class _PIDSlider extends StatelessWidget {
+/// Shows the dragged value immediately but sends it only on release: every
+/// `cmd set` rewrites controller EEPROM, so per-tick writes wear it out.
+class _PIDSlider extends StatefulWidget {
   final String label;
   final double value;
   final double min;
@@ -117,9 +108,28 @@ class _PIDSlider extends StatelessWidget {
     required this.onChanged,
   });
 
+  @override
+  State<_PIDSlider> createState() => _PIDSliderState();
+}
+
+class _PIDSliderState extends State<_PIDSlider> {
+  double? _draft;
+
+  double _snap(double v) => double.parse(
+    (widget.min + ((v - widget.min) / widget.step).round() * widget.step)
+        .toStringAsFixed(widget.decimalPlaces),
+  );
+
+  @override
+  void didUpdateWidget(covariant _PIDSlider oldWidget) {
+    super.didUpdateWidget(oldWidget);
+    if (oldWidget.value != widget.value) _draft = null;
+  }
+
   @override
   Widget build(BuildContext context) {
-    final rounded = value.toStringAsFixed(decimalPlaces);
+    final value = _draft ?? widget.value;
+    final rounded = value.toStringAsFixed(widget.decimalPlaces);
     final reading = double.tryParse(rounded) == value
         ? rounded
         : value.toString();
@@ -128,21 +138,19 @@ class _PIDSlider extends StatelessWidget {
       children: [
         Padding(
           padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
-          child: Text('$label: $reading'),
+          child: Text('${widget.label}: $reading'),
         ),
         Slider(
-          value: value.clamp(min, max),
-          min: min,
-          max: max,
-          divisions: ((max - min) / step).round(),
+          value: value.clamp(widget.min, widget.max),
+          min: widget.min,
+          max: widget.max,
+          divisions: ((widget.max - widget.min) / widget.step).round(),
           label: reading,
-          onChanged: (v) => onChanged(
-            double.parse(
-              (min + ((v - min) / step).round() * step).toStringAsFixed(
-                decimalPlaces,
-              ),
-            ),
-          ),
+          onChanged: (v) => setState(() => _draft = _snap(v)),
+          onChangeEnd: (v) {
+            setState(() => _draft = null);
+            widget.onChanged(_snap(v));
+          },
         ),
       ],
     );

+ 26 - 7
lib/screens/pressure_settings_screen.dart

@@ -54,7 +54,8 @@ class PressureSettingsScreen extends ConsumerWidget {
   }
 }
 
-class _PressureSlider extends StatelessWidget {
+/// Sends only on release; every `cmd set` rewrites controller EEPROM.
+class _PressureSlider extends StatefulWidget {
   final String label;
   final double value;
   final double min;
@@ -69,23 +70,41 @@ class _PressureSlider extends StatelessWidget {
     required this.onChanged,
   });
 
+  @override
+  State<_PressureSlider> createState() => _PressureSliderState();
+}
+
+class _PressureSliderState extends State<_PressureSlider> {
+  double? _draft;
+
+  @override
+  void didUpdateWidget(covariant _PressureSlider oldWidget) {
+    super.didUpdateWidget(oldWidget);
+    if (oldWidget.value != widget.value) _draft = null;
+  }
+
   @override
   Widget build(BuildContext context) {
+    final value = _draft ?? widget.value;
     return Column(
       crossAxisAlignment: CrossAxisAlignment.start,
       children: [
         Padding(
           padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
           child: Text(
-            '$label: ${value.toInt()}${label.contains('%') ? '%' : 's'}',
+            '${widget.label}: ${value.round()}${widget.label.contains('%') ? '%' : 's'}',
           ),
         ),
         Slider(
-          value: value.clamp(min, max),
-          min: min,
-          max: max,
-          divisions: (max - min).toInt(),
-          onChanged: onChanged,
+          value: value.clamp(widget.min, widget.max),
+          min: widget.min,
+          max: widget.max,
+          divisions: (widget.max - widget.min).toInt(),
+          onChanged: (v) => setState(() => _draft = v.roundToDouble()),
+          onChangeEnd: (v) {
+            setState(() => _draft = null);
+            widget.onChanged(v.roundToDouble());
+          },
         ),
       ],
     );

+ 29 - 5
lib/screens/timer_settings_screen.dart

@@ -13,12 +13,17 @@ class TimerSettingsScreen extends ConsumerStatefulWidget {
 class _TimerSettingsScreenState extends ConsumerState<TimerSettingsScreen> {
   double? _autoShutoffDraft;
 
+  static String _autoShutoffLabel(int minutes) =>
+      minutes == 0 ? 'Off' : '$minutes minutes';
+
   @override
   Widget build(BuildContext context) {
     final machineState = ref.watch(bluetoothServiceProvider);
     final bluetoothService = ref.read(bluetoothServiceProvider.notifier);
     ref.listen(
-      bluetoothServiceProvider.select((state) => state.autoShutoffMinutes),
+      bluetoothServiceProvider.select(
+        (state) => (state.autoShutoffMinutes, state.autoShutoffEnabled),
+      ),
       (_, _) => setState(() => _autoShutoffDraft = null),
     );
 
@@ -31,19 +36,30 @@ class _TimerSettingsScreenState extends ConsumerState<TimerSettingsScreen> {
             _SectionHeader(title: 'Auto-Shutoff'),
             ListTile(
               title: const Text('Inactivity Timer'),
-              subtitle: Text('${machineState.autoShutoffMinutes} minutes'),
+              subtitle: Text(
+                machineState.autoShutoffEnabled
+                    ? '${machineState.autoShutoffMinutes} minutes'
+                    : 'Off',
+              ),
               trailing: SizedBox(
                 width: 150,
                 child: Slider(
                   value:
                       (_autoShutoffDraft ??
-                              machineState.autoShutoffMinutes.toDouble())
+                              (machineState.autoShutoffEnabled
+                                  ? machineState.autoShutoffMinutes.toDouble()
+                                  : 0.0))
                           .clamp(0.0, 120.0),
                   min: 0,
                   max: 120,
                   divisions: 120,
-                  label:
-                      '${(_autoShutoffDraft ?? machineState.autoShutoffMinutes).round()} minutes',
+                  label: _autoShutoffLabel(
+                    (_autoShutoffDraft ??
+                            (machineState.autoShutoffEnabled
+                                ? machineState.autoShutoffMinutes
+                                : 0))
+                        .round(),
+                  ),
                   onChanged: (v) => setState(() => _autoShutoffDraft = v),
                   onChangeEnd: (v) {
                     setState(() => _autoShutoffDraft = null);
@@ -55,6 +71,14 @@ class _TimerSettingsScreenState extends ConsumerState<TimerSettingsScreen> {
             const Divider(),
           ],
           _SectionHeader(title: 'Daily Schedule'),
+          const Padding(
+            padding: EdgeInsets.only(bottom: 8),
+            child: Text(
+              'The controller clock restarts when the machine loses power. '
+              'Wake-up and shutdown times only run after this app has '
+              'connected once since then.',
+            ),
+          ),
           SwitchListTile(
             title: const Text('Enable Wakeup Timer'),
             value: machineState.wakeupEnabled,

+ 180 - 54
lib/services/bluetooth_service.dart

@@ -25,6 +25,8 @@ class MeCoffeeService extends StateNotifier<MachineState> {
     Future<void> Function(Duration)? firmwareDelay,
     this.savePreference,
     this.freshnessTimeout = const Duration(seconds: 3),
+    this.settingsReplyTimeout = const Duration(seconds: 3),
+    this.clockSyncInterval = const Duration(hours: 1),
   }) : _classicTransport = classicTransport ?? ClassicBluetoothTransport(),
        _firmwareDelay = firmwareDelay ?? Future<void>.delayed,
        super(MachineState()) {
@@ -32,6 +34,12 @@ class MeCoffeeService extends StateNotifier<MachineState> {
   }
 
   final Duration freshnessTimeout;
+
+  /// How long a `cmd set` may wait for its `cmd set s_<key> …` confirmation.
+  final Duration settingsReplyTimeout;
+
+  /// Periodic `cmd clock set` while connected (drift, DST, controller resets).
+  final Duration clockSyncInterval;
   final ClassicBluetoothTransport _classicTransport;
   final Future<void> Function(Duration) _firmwareDelay;
   final Future<bool> Function(String, Object)? savePreference;
@@ -43,7 +51,12 @@ class MeCoffeeService extends StateNotifier<MachineState> {
   StreamController<List<int>>? _firmwareBytes;
   bool _firmwareMode = false;
   bool _settingsLocked = false;
-  DateTime? _lastPidAt;
+  // True after a heater-off frame (`pid 0 0 0 0`) on live telemetry and until
+  // the next non-zero PID frame: the controller is switched off or asleep.
+  bool _heaterOffConfirmed = false;
+  ({String key, Completer<String?> reply})? _pendingSetEcho;
+  Timer? _clockTimer;
+  bool _reinitializing = false;
   final _reportedSettings = <String>{};
   final _pendingFirmwareSettings = <String, String>{};
   static const _firmwareScaledKeys = {
@@ -77,14 +90,26 @@ class MeCoffeeService extends StateNotifier<MachineState> {
       _commandReady &&
       !state.isBrewing &&
       !state.isHeating &&
-      _lastPidAt != null &&
-      DateTime.now().difference(_lastPidAt!) < freshnessTimeout &&
+      !state.isSteaming &&
+      _heaterOffConfirmed &&
       !state.telemetryStale &&
       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 =>
       mounted && !_settingsLocked && _machineSafeForFirmware;
 
@@ -142,11 +167,12 @@ class MeCoffeeService extends StateNotifier<MachineState> {
     _freshnessTimer = Timer(freshnessTimeout, () {
       if (!mounted || generation != _connectionGeneration) return;
       _stopShotTimer();
-      _lastPidAt = null;
+      _heaterOffConfirmed = false;
       state = state.copyWith(
         telemetryStale: true,
         isHeating: false,
         heatingPower: 0,
+        isSteaming: false,
         isBrewing: false,
       );
       _log(DiagnosticDirection.event, 'Temperature telemetry timed out');
@@ -256,6 +282,7 @@ class MeCoffeeService extends StateNotifier<MachineState> {
       _commandReady = true;
       state = state.copyWith(connectionStatus: 'Connected');
       _watchFreshness();
+      _startClockSync();
       _log(DiagnosticDirection.event, 'Connected via Bluetooth Classic');
     } catch (error) {
       if (mounted && generation == _connectionGeneration) {
@@ -267,8 +294,16 @@ class MeCoffeeService extends StateNotifier<MachineState> {
   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.',
+        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, '
+                  'the machine switched off at its power switch (heating off), '
+                  'and a boiler at or below 50 C.',
       );
       return;
     }
@@ -354,6 +389,9 @@ class MeCoffeeService extends StateNotifier<MachineState> {
       state = state.copyWith(
         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(
         write: (bytes) async {
           if (!_classicConnected) throw StateError('Bootloader disconnected');
@@ -416,14 +454,21 @@ class MeCoffeeService extends StateNotifier<MachineState> {
         );
       }
       if (mounted) {
+        final nothingWritten =
+            error is FirmwareUpdateException &&
+            (error.code == FirmwareUpdateError.noBootloader ||
+                error.code == FirmwareUpdateError.signatureMismatch);
         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.',
+          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 {
@@ -461,6 +506,7 @@ class MeCoffeeService extends StateNotifier<MachineState> {
       valveClosedWhilePaused: prefs.getBool('valveClosedWhilePaused') ?? false,
       proActivePercentage: prefs.getInt('proActivePercentage') ?? 33,
       autoShutoffMinutes: prefs.getInt('autoShutoffMinutes') ?? 60,
+      autoShutoffEnabled: prefs.getBool('autoShutoffEnabled') ?? false,
       wakeupEnabled: prefs.getBool('wakeupEnabled') ?? false,
       wakeupTime: prefs.getString('wakeupTime') ?? "07:00",
       shutdownEnabled: prefs.getBool('shutdownEnabled') ?? false,
@@ -528,8 +574,11 @@ class MeCoffeeService extends StateNotifier<MachineState> {
   Future<void> updateProActive(int percentage) =>
       _updateSettings({'tmppap': percentage});
 
-  Future<void> updateAutoShutoff(int minutes) =>
-      _updateSettings({'tmrosd': minutes});
+  /// Minutes of inactivity before the controller switches off; 0 disables it.
+  /// The firmware only acts on `tmrosd` while `tmrosdnbl` is set.
+  Future<void> updateAutoShutoff(int minutes) => _updateSettings(
+    minutes > 0 ? {'tmrosd': minutes, 'tmrosdnbl': true} : {'tmrosdnbl': false},
+  );
 
   Future<void> updateMaxShotTime(int seconds) async {
     if (seconds < 0 || seconds > MeCoffeeProtocol.maxShotSeconds) {
@@ -670,6 +719,7 @@ class MeCoffeeService extends StateNotifier<MachineState> {
     'pwrflp': 'powerButtonFlipsBack',
     'tmppap': 'proActivePercentage',
     'tmrosd': 'autoShutoffMinutes',
+    'tmrosdnbl': 'autoShutoffEnabled',
     'shtmx': 'maxShotTime',
     'tmpcntns': 'continuousMode',
     'tmrwnbl': 'wakeupEnabled',
@@ -701,6 +751,7 @@ class MeCoffeeService extends StateNotifier<MachineState> {
     'powerButtonFlipsBack': value.powerButtonFlipsBack,
     'proActivePercentage': value.proActivePercentage,
     'autoShutoffMinutes': value.autoShutoffMinutes,
+    'autoShutoffEnabled': value.autoShutoffEnabled,
     'maxShotTime': value.maxShotTime,
     'continuousMode': value.continuousMode,
     'wakeupEnabled': value.wakeupEnabled,
@@ -776,6 +827,7 @@ class MeCoffeeService extends StateNotifier<MachineState> {
             'o2',
             'pwrflp',
             'tmrosd',
+            'tmrosdnbl',
             'shtmx',
             'pd1imn',
           }.contains,
@@ -786,48 +838,59 @@ class MeCoffeeService extends StateNotifier<MachineState> {
           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]!;
+      // One command per write: each `set` blocks the controller while it
+      // rewrites EEPROM and its receive buffer holds only 64 bytes. The
+      // `cmd set s_<key> <stored value> OK` echo confirms delivery and carries
+      // the value actually stored, which is what gets persisted locally.
+      for (final entry in values.entries) {
+        if (!mounted || generation != _connectionGeneration) return;
+        final command = MeCoffeeProtocol.encodeSet(
+          entry.key,
+          entry.value,
+          isLegacyV4: state.isLegacyV4Firmware,
+        );
+        final reply = Completer<String?>();
+        // A disconnect can fail the reply before it is awaited below.
+        reply.future.ignore();
+        _pendingSetEcho = (key: entry.key, reply: reply);
+        String? confirmation;
+        try {
+          if (!await _sendCommand(command.codeUnits)) return;
+          confirmation = await reply.future.timeout(settingsReplyTimeout);
+        } on TimeoutException {
+          _reportCommandError(
+            'The controller did not confirm ${entry.key}; it may not be stored.',
+          );
+          return;
+        } catch (error) {
+          _reportCommandError('Setting ${entry.key} not confirmed: $error');
+          return;
+        } finally {
+          if (identical(_pendingSetEcho?.reply, reply)) _pendingSetEcho = null;
+        }
+        if (confirmation == null) {
+          _reportCommandError('The controller rejected ${entry.key} (NOT OK).');
+          return;
+        }
+        if (!mounted || generation != _connectionGeneration) return;
+        final preferenceKey = _preferenceKeys[entry.key]!;
+        try {
           if (!await _persistPreference(
             preferenceKey,
-            preferences[preferenceKey]!,
+            _preferenceValues(state)[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;
         }
-      } 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;
@@ -1111,6 +1174,7 @@ class MeCoffeeService extends StateNotifier<MachineState> {
       _commandReady = true;
       state = state.copyWith(connectionStatus: 'Connected');
       _watchFreshness();
+      _startClockSync();
       _log(DiagnosticDirection.event, 'Connected via BLE');
     } catch (e) {
       if (mounted && generation == _connectionGeneration) {
@@ -1119,13 +1183,46 @@ class MeCoffeeService extends StateNotifier<MachineState> {
     }
   }
 
-  Future<bool> _sendInitializationSequence() async {
+  /// The firmware ignores a pending clock value of 0, so midnight is sent as 1.
+  List<int> _clockCommand() {
     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,
-    )) {
+    final seconds = now.hour * 3600 + now.minute * 60 + now.second;
+    return '\ncmd clock set ${seconds < 1 ? 1 : seconds}\n'.codeUnits;
+  }
+
+  /// Resend the clock periodically: the controller's mains-derived clock
+  /// drifts, does not follow DST and restarts at 0 after every reset.
+  void _startClockSync() {
+    _clockTimer?.cancel();
+    final generation = _connectionGeneration;
+    _clockTimer = Timer.periodic(clockSyncInterval, (_) {
+      if (!mounted || generation != _connectionGeneration || !_commandReady) {
+        return;
+      }
+      unawaited(_sendCommand(_clockCommand()));
+    });
+  }
+
+  /// A boot frame (`tmp 0 …`) or watchdog report while connected means the
+  /// controller restarted underneath an open link: its clock is reset and
+  /// settings may have been restored, so repeat the start-up sequence.
+  void _reinitializeAfterReset(String line) {
+    if (_reinitializing || !_commandReady || _settingsLocked) return;
+    _reinitializing = true;
+    final generation = _connectionGeneration;
+    _log(
+      DiagnosticDirection.event,
+      'Controller restarted ("$line"); re-sending clock and reading settings',
+    );
+    unawaited(
+      _sendInitializationSequence().whenComplete(() {
+        if (generation == _connectionGeneration) _reinitializing = false;
+      }),
+    );
+  }
+
+  Future<bool> _sendInitializationSequence() async {
+    if (!await _sendCommand(_clockCommand(), initializing: true)) {
       return false;
     }
     if (!await _sendCommand("\ncmd uname OK\n".codeUnits, initializing: true)) {
@@ -1222,7 +1319,17 @@ class MeCoffeeService extends StateNotifier<MachineState> {
 
   void _clearConnection() {
     _connectionGeneration++;
-    _lastPidAt = null;
+    _heaterOffConfirmed = false;
+    _clockTimer?.cancel();
+    _clockTimer = null;
+    _reinitializing = false;
+    final pendingEcho = _pendingSetEcho;
+    _pendingSetEcho = null;
+    if (pendingEcho != null && !pendingEcho.reply.isCompleted) {
+      pendingEcho.reply.completeError(
+        StateError('Bluetooth disconnected before the controller confirmed'),
+      );
+    }
     _reportedSettings.clear();
     _pendingFirmwareSettings.clear();
     _commandReady = false;
@@ -1249,6 +1356,7 @@ class MeCoffeeService extends StateNotifier<MachineState> {
         clearLastTelemetry: true,
         isHeating: false,
         heatingPower: 0,
+        isSteaming: false,
       );
     }
   }
@@ -1335,13 +1443,16 @@ class MeCoffeeService extends StateNotifier<MachineState> {
           _pendingFirmwareSettings.clear();
         }
         if (valid && fields.first == 'pid') {
-          if (!state.telemetryStale) _lastPidAt = DateTime.now();
+          _heaterOffConfirmed =
+              !state.telemetryStale &&
+              fields.skip(1).where((f) => f != 'OK').every((f) => f == '0');
         }
         if (state.telemetryStale &&
             (fields.first == 'pid' || fields.first == 'sht')) {
           parsed = parsed.copyWith(
             isHeating: false,
             heatingPower: 0,
+            isSteaming: false,
             isBrewing: false,
           );
         }
@@ -1355,6 +1466,21 @@ class MeCoffeeService extends StateNotifier<MachineState> {
         }
         state = parsed;
 
+        if (fields.length >= 3 && fields[0] == 'cmd' && fields[1] == 'set') {
+          final pending = _pendingSetEcho;
+          if (pending != null && !pending.reply.isCompleted) {
+            if (fields[2] == 'NOT') {
+              pending.reply.complete(null);
+            } else if (fields[2] == 's_${pending.key}') {
+              pending.reply.complete(line);
+            }
+          }
+        }
+        if (fields.length >= 2 && fields[0] == 'tmp' && fields[1] == '0' ||
+            line.contains('WDT fired')) {
+          _reinitializeAfterReset(line);
+        }
+
         if (valid && (line.startsWith('tmp ') || line.startsWith('T '))) {
           final now = DateTime.now();
           final fields = line.split(RegExp(r'\s+'));

+ 95 - 1
lib/services/firmware_updater.dart

@@ -85,6 +85,9 @@ enum FirmwareUpdateError {
   bufferOverflow,
   signatureMismatch,
   verificationFailed,
+
+  /// No STK500 bootloader answered GET_SYNC; nothing was written.
+  noBootloader,
 }
 
 class FirmwareUpdateException implements Exception {
@@ -110,6 +113,14 @@ class FirmwareUpdater {
 
   final Future<void> Function(List<int>) write;
   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>();
   late final StreamSubscription<List<int>> _subscription;
   Completer<List<int>>? _reply;
@@ -118,15 +129,22 @@ class FirmwareUpdater {
   bool _flashing = false;
   bool _disposed = false;
   bool _finished = false;
+  bool _syncing = false;
 
   FirmwareUpdater({
     required this.write,
     required Stream<List<int>> received,
     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) {
       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.
     _subscription = received.listen(
       _receive,
@@ -180,6 +198,24 @@ class FirmwareUpdater {
   void _drain() {
     final reply = _reply;
     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) {
       _fail(
         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 {
     final wordAddress = byteAddress ~/ 2;
     await _exchange([0x55, wordAddress & 0xff, wordAddress >> 8, 0x20]);
@@ -269,7 +363,7 @@ class FirmwareUpdater {
     _flashing = true;
     try {
       onProgress?.call(0);
-      await _exchange([0x30, 0x20]);
+      await _synchronize();
       await _exchange([0x50, 0x20]);
       final signature = await _exchange([0x75, 0x20], responseLength: 3);
       final actual = (signature[0] << 16) | (signature[1] << 8) | signature[2];

+ 38 - 0
lib/services/me_coffee_protocol.dart

@@ -44,10 +44,21 @@ class MeCoffeeProtocol {
           if (!raw.isFinite) return currentState;
           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(
           targetTemperature: setpoint,
           temperature: boiler,
           sensor2Temperature: sensor2 ?? currentState.sensor2Temperature,
+          isSteaming: isSteaming,
         );
       } catch (_) {}
     }
@@ -61,10 +72,30 @@ class MeCoffeeProtocol {
         int d = int.parse(parts[3]);
         int f = parts.length >= 5 ? int.parse(parts[4]) : 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;
         return currentState.copyWith(
           heatingPower: totalPower.clamp(0.0, 1.0),
           isHeating: totalPower > 0,
+          isSteaming: false,
         );
       } catch (_) {}
     }
@@ -76,6 +107,11 @@ class MeCoffeeProtocol {
         int shottimeMs = int.parse(parts[2]);
         if (shottimeMs == 0) {
           return currentState.copyWith(isBrewing: true, shotTimer: 0);
+        } else if (!currentState.isBrewing) {
+          // V9/V10 send a second end line when the input is released after a
+          // `shtmx` cutoff, and can send a stray `sht <s> <uptime-ms>` before
+          // the first start line. Keep the duration of the shot that ended.
+          return currentState.copyWith();
         } else {
           return currentState.copyWith(
             isBrewing: false,
@@ -182,6 +218,8 @@ class MeCoffeeProtocol {
           return state.copyWith(proActivePercentage: val.toInt());
         case 'tmrosd':
           return state.copyWith(autoShutoffMinutes: val.toInt());
+        case 'tmrosdnbl':
+          return state.copyWith(autoShutoffEnabled: val != 0);
         case 'o0':
           return state.copyWith(output0: val.toInt());
         case 'o1':

+ 311 - 0
test/firmware/v10_firmware_conformance_test.dart

@@ -0,0 +1,311 @@
+// 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,
+  'autoShutoffEnabled' => s.autoShutoffEnabled,
+  '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));
+    });
+  });
+}

ファイルの差分が大きいため隠しています
+ 1321 - 0
test/fixtures/v10_golden_transcripts.json


+ 3 - 1
test/screens/settings_ranges_test.dart

@@ -144,7 +144,9 @@ void main() {
       expect(tester.widget<Slider>(find.byType(Slider)).value, 61);
       slider.onChangeEnd!(61);
       expect(service.writes, {'shutoff': 61});
-      service.setMachineState(MachineState(autoShutoffMinutes: 62));
+      service.setMachineState(
+        MachineState(autoShutoffMinutes: 62, autoShutoffEnabled: true),
+      );
       await tester.pump();
       expect(tester.widget<Slider>(find.byType(Slider)).value, 62);
     },

+ 10 - 5
test/screens/v4_pid_settings_screen_test.dart

@@ -106,11 +106,11 @@ void main() {
       findsOneWidget,
     );
 
-    sliders[1].onChanged!(4);
+    sliders[1].onChangeEnd!(4);
     expect(service.pid, [25, 4, 128]);
-    sliders[4].onChanged!(4000);
+    sliders[4].onChangeEnd!(4000);
     expect(service.limits, [0, 4000, 1000]);
-    sliders[5].onChanged!(1500);
+    sliders[5].onChangeEnd!(1500);
     expect(service.limits, [0, 3750, 1500]);
     expect(tester.takeException(), isNull);
   });
@@ -129,9 +129,14 @@ void main() {
     expect((sliders[5].max, sliders[5].divisions), (48, 48));
     expect(find.text('Integral (I): 0.35'), findsOneWidget);
     expect(find.textContaining('Temperature Offset'), findsNothing);
-    sliders[1].onChanged!(0.35000000000000003);
+    // Dragging only previews; nothing is sent until release (EEPROM wear).
+    sliders[0].onChanged!(60);
+    await tester.pump();
+    expect(service.pid, isNull);
+    expect(find.text('Proportional (P): 60'), findsOneWidget);
+    sliders[1].onChangeEnd!(0.35000000000000003);
     expect(service.pid, [100, 0.35, 128]);
-    sliders[3].onChanged!(34);
+    sliders[3].onChangeEnd!(34);
     expect(service.proactive, 34);
     expect(tester.takeException(), isNull);
   });

+ 165 - 2
test/services/classic_service_test.dart

@@ -17,6 +17,8 @@ class FakeClassicTransport extends ClassicBluetoothTransport {
   bool resetDisconnects = false;
   bool wrongSignature = false;
   bool respondToIdentity = true;
+  bool echoSettings = true;
+  final settingReplies = <String, String>{};
   Completer<void>? writeGate;
   int resets = 0;
   List<int> page = const [];
@@ -51,7 +53,7 @@ class FakeClassicTransport extends ClassicBluetoothTransport {
     writes.add(List.of(bytes));
     if (respondToIdentity &&
         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')) {
       resets++;
@@ -66,6 +68,17 @@ class FakeClassicTransport extends ClassicBluetoothTransport {
       }
       return;
     }
+    if (echoSettings) {
+      for (final match in RegExp(
+        r'^cmd set (\S+) (\S+)$',
+        multiLine: true,
+      ).allMatches(String.fromCharCodes(bytes))) {
+        data.add(
+          '${settingReplies[match[1]] ?? 'cmd set s_${match[1]} ${match[2]} OK'}\n'
+              .codeUnits,
+        );
+      }
+    }
     if (bytes.first == 0x0a || bytes.first == 0x63) return;
     switch (bytes.first) {
       case 0x75:
@@ -142,7 +155,7 @@ void main() {
 
   void reportIdleMachine() {
     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,
     );
   }
@@ -231,6 +244,22 @@ void main() {
     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 {
     await connect();
     transport.data.add('cmd uname meCoffee V4 OK\n'.codeUnits);
@@ -307,4 +336,138 @@ void main() {
       expect(transport.connected, isTrue);
     },
   );
+
+  group('medium compatibility fixes', () {
+    List<String> sentLines() => String.fromCharCodes(
+      transport.writes.expand((bytes) => bytes),
+    ).split('\n').where((line) => line.isNotEmpty).toList();
+
+    test('auto shut-off also sets and clears the tmrosdnbl gate', () async {
+      await connect();
+      reportIdleMachine();
+      transport.writes.clear();
+      await service.updateAutoShutoff(30);
+      expect(transport.writes.map(String.fromCharCodes), [
+        'cmd set tmrosd 30\n',
+        'cmd set tmrosdnbl 1\n',
+      ]);
+      expect(service.state.autoShutoffMinutes, 30);
+      expect(service.state.autoShutoffEnabled, isTrue);
+      final prefs = await SharedPreferences.getInstance();
+      expect(prefs.getBool('autoShutoffEnabled'), isTrue);
+      transport.writes.clear();
+      await service.updateAutoShutoff(0);
+      expect(sentLines(), ['cmd set tmrosdnbl 0']);
+      expect(service.state.autoShutoffEnabled, isFalse);
+      expect(service.state.autoShutoffMinutes, 30);
+    });
+
+    test('settings go one command per write and persist the echo', () async {
+      await connect();
+      reportIdleMachine();
+      transport.writes.clear();
+      transport.settingReplies['pistrt'] = 'cmd set s_pistrt 2000 OK';
+      await service.updatePreinfusion(true, 2.5, 1.5, false);
+      expect(transport.writes.map(String.fromCharCodes), [
+        'cmd set pinbl 1\n',
+        'cmd set pistrt 2500\n',
+        'cmd set piprd 1500\n',
+        'cmd set pivlv 0\n',
+      ]);
+      // The controller stored 2000, so the app shows and keeps 2000.
+      expect(service.state.preinfusionTime, 2.0);
+      final prefs = await SharedPreferences.getInstance();
+      expect(prefs.getDouble('preinfusionTime'), 2.0);
+      expect(service.state.commandError, isNull);
+    });
+
+    test('NOT OK stops the batch and is not persisted', () async {
+      await connect();
+      reportIdleMachine();
+      transport.writes.clear();
+      transport.settingReplies['pistrt'] = 'cmd set  NOT OK';
+      await service.updatePreinfusion(true, 2.5, 1.5, false);
+      expect(sentLines(), ['cmd set pinbl 1', 'cmd set pistrt 2500']);
+      expect(service.state.commandError, contains('rejected pistrt'));
+      final prefs = await SharedPreferences.getInstance();
+      expect(prefs.getBool('preinfusionEnabled'), isTrue);
+      expect(prefs.getDouble('preinfusionTime'), isNull);
+    });
+
+    test('missing confirmation is reported and not persisted', () async {
+      service.dispose();
+      await Future<void>.delayed(Duration.zero);
+      transport = FakeClassicTransport();
+      service = MeCoffeeService(
+        classicTransport: transport,
+        settingsReplyTimeout: const Duration(milliseconds: 30),
+      );
+      await connect();
+      reportIdleMachine();
+      transport.echoSettings = false;
+      await service.updateBrewTemperature(95);
+      expect(service.state.commandError, contains('did not confirm tmpsp'));
+      final prefs = await SharedPreferences.getInstance();
+      expect(prefs.getDouble('brewTemperature'), isNull);
+    });
+
+    test('firmware update gate is the powered-off state', () async {
+      service.dispose();
+      await Future<void>.delayed(Duration.zero);
+      transport = FakeClassicTransport();
+      service = MeCoffeeService(
+        classicTransport: transport,
+        freshnessTimeout: const Duration(milliseconds: 40),
+      );
+      await connect();
+      reportIdleMachine();
+      expect(service.canUpdateFirmware, isTrue);
+      // Switched off: only tmp frames follow, well past the freshness window.
+      for (var i = 0; i < 3; i++) {
+        await Future<void>.delayed(const Duration(milliseconds: 25));
+        transport.data.add('tmp ${i + 2} 10100 2000 0 OK\n'.codeUnits);
+      }
+      expect(service.canUpdateFirmware, isTrue);
+      transport.data.add('pid 0 999 0 0 OK\n'.codeUnits);
+      expect(service.canUpdateFirmware, isFalse);
+    });
+
+    test('controller restart re-sends clock, identity and dump', () async {
+      await connect();
+      reportIdleMachine();
+      for (final line in ['tmp 0 10100 2000 0 OK', 'WDT fired']) {
+        transport.writes.clear();
+        transport.data.add('$line\n'.codeUnits);
+        await Future<void>.delayed(const Duration(milliseconds: 10));
+        expect(
+          String.fromCharCodes(transport.writes.expand((bytes) => bytes)),
+          matches(r'^\ncmd clock set [1-9]\d*\n\ncmd uname OK\n\ncmd dump\n$'),
+          reason: line,
+        );
+      }
+    });
+
+    test('clock is resynchronised periodically while connected', () async {
+      service.dispose();
+      await Future<void>.delayed(Duration.zero);
+      transport = FakeClassicTransport();
+      service = MeCoffeeService(
+        classicTransport: transport,
+        clockSyncInterval: const Duration(milliseconds: 20),
+      );
+      await connect();
+      transport.writes.clear();
+      await Future<void>.delayed(const Duration(milliseconds: 70));
+      final syncs = transport.writes
+          .map(String.fromCharCodes)
+          .where(
+            (text) => RegExp(r'^\ncmd clock set [1-9]\d*\n$').hasMatch(text),
+          );
+      expect(syncs.length, greaterThanOrEqualTo(2));
+      await service.disconnect();
+      transport.writes.clear();
+      await Future<void>.delayed(const Duration(milliseconds: 50));
+      expect(transport.writes, isEmpty);
+    });
+  });
 }

+ 58 - 6
test/services/firmware_updater_test.dart

@@ -23,6 +23,8 @@ class FakeBootloader {
   List<int> signature = [0x1e, 0x95, 0x0f];
   int address = 0;
   int? silentCommand;
+  int ignoredSyncs = 0;
+  bool duplicateSync = false;
   int? failedCommand;
   bool corruptRead = false;
   bool fragment = false;
@@ -30,6 +32,17 @@ class FakeBootloader {
   Future<void> write(List<int> command) async {
     commands.add(List.of(command));
     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) {
       controller.add([0x14, 0x11]);
       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() {
@@ -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', () {
     for (final fragmented in [false, true]) {
       test('writes and verifies pages (fragmented=$fragmented)', () async {

+ 74 - 0
test/services/me_coffee_protocol_test.dart

@@ -118,6 +118,80 @@ void main() {
       expect(stopped.shotTimer, 25);
     });
 
+    test('keeps the shtmx cutoff duration when the release line follows', () {
+      // V10 simulation, shtmx 2 with a 4 s shot signal.
+      var state = MachineState();
+      for (final line in [
+        'sht 4 4823 OK', // stray line before the start
+        'sht 4 0 OK',
+        'sht 6 2001 OK', // cutoff
+        'sht 8 3971 OK', // signal released
+      ]) {
+        state = MeCoffeeProtocol.parse(line, state);
+        if (line == 'sht 4 4823 OK') {
+          expect(state.isBrewing, isFalse);
+          expect(state.shotTimer, 0);
+        }
+      }
+
+      expect(state.isBrewing, isFalse);
+      expect(state.shotTimer, 2);
+    });
+
+    test('steam markers switch the heater without ending steam', () {
+      final heating = MachineState(heatingPower: 0.3, isHeating: true);
+      final steaming = MeCoffeeProtocol.parse('pid 65535 0 0 0 OK', heating);
+
+      expect(steaming.isSteaming, isTrue);
+      expect(steaming.isHeating, isTrue);
+      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);
+
+      final resumed = MeCoffeeProtocol.parse('pid 2200 1258 0 0 OK', steaming);
+      expect(resumed.isSteaming, isFalse);
+      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', () {
+      final state = MeCoffeeProtocol.parse('pid 65535 0 0', MachineState());
+
+      expect(state.isSteaming, isFalse);
+      expect(state.heatingPower, 1.0);
+    });
+
     test('parses scaled cmd get values for key-value settings', () {
       var state = MachineState();
 

+ 23 - 0
test/support/fake_bluetooth_platform.dart

@@ -25,6 +25,13 @@ final class FakeBluetoothPlatform extends FlutterBluePlusPlatform {
   bool writableWithoutResponse = false;
   bool notifiable = true;
   bool respondToIdentity = true;
+
+  /// Answer each `cmd set <key> <value>` like the V10 firmware does.
+  bool echoSettings = true;
+
+  /// Reply for a key instead of the normal echo, e.g. `cmd set  NOT OK`.
+  final settingReplies = <String, String>{};
+  String _writtenText = '';
   Completer<void>? discoveryGate;
   Completer<void>? writeGate;
   int mtu = 23;
@@ -46,6 +53,9 @@ final class FakeBluetoothPlatform extends FlutterBluePlusPlatform {
     writableWithoutResponse = false;
     notifiable = true;
     respondToIdentity = true;
+    echoSettings = true;
+    settingReplies.clear();
+    _writtenText = '';
     discoveryGate = null;
     writeGate = null;
     mtu = 23;
@@ -206,6 +216,19 @@ final class FakeBluetoothPlatform extends FlutterBluePlusPlatform {
         'cmd uname meCoffee V10 OK\n',
       );
     }
+    _writtenText += String.fromCharCodes(request.value);
+    while (_writtenText.contains('\n')) {
+      final index = _writtenText.indexOf('\n');
+      final line = _writtenText.substring(0, index).trim();
+      _writtenText = _writtenText.substring(index + 1);
+      final match = RegExp(r'^cmd set (\S+) (\S+)$').firstMatch(line);
+      if (echoSettings && match != null) {
+        notify(
+          BluetoothDevice.fromId(request.remoteId.str),
+          '${settingReplies[match[1]] ?? 'cmd set s_${match[1]} ${match[2]} OK'}\n',
+        );
+      }
+    }
     _written.add(
       BmCharacteristicData(
         remoteId: request.remoteId,

+ 33 - 0
test/widget_test.dart

@@ -87,6 +87,39 @@ void main() {
     await tester.pumpWidget(const SizedBox());
   });
 
+  testWidgets('dashboard shows Steam instead of a PID percentage', (
+    tester,
+  ) async {
+    final service = DashboardService();
+    await tester.pump();
+    service.showState(
+      MachineState(
+        connectionStatus: 'Connected',
+        temperature: 120,
+        lastTelemetryAt: DateTime(2026, 10, 6),
+        telemetryStale: false,
+        isHeating: true,
+        isSteaming: true,
+      ),
+    );
+    await tester.pumpWidget(
+      ProviderScope(
+        overrides: [bluetoothServiceProvider.overrideWith((ref) => service)],
+        child: const MyApp(),
+      ),
+    );
+    await tester.pump(const Duration(milliseconds: 100));
+    expect(find.text('Steam'), findsOneWidget);
+    expect(find.text('0%'), findsNothing);
+    expect(
+      tester
+          .widget<LinearProgressIndicator>(find.byType(LinearProgressIndicator))
+          .value,
+      isNull,
+    );
+    await tester.pumpWidget(const SizedBox());
+  });
+
   testWidgets('dashboard diagnostics button opens local logs', (tester) async {
     await tester.pumpWidget(const ProviderScope(child: MyApp()));
     await tester.pumpAndSettle();