Thomas Hondema 1 месяц назад
Родитель
Сommit
d84e091715

+ 2 - 2
README.md

@@ -63,8 +63,8 @@ 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.
 
 Only controllers reporting `pcb V9` (V9/V10 hardware) are offered the update;

+ 4 - 0
lib/models/machine_state.dart

@@ -58,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;
@@ -123,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,
@@ -181,6 +183,7 @@ class MachineState {
     bool? valveClosedWhilePaused,
     int? proActivePercentage,
     int? autoShutoffMinutes,
+    bool? autoShutoffEnabled,
     bool? wakeupEnabled,
     String? wakeupTime,
     bool? shutdownEnabled,
@@ -242,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,

+ 2 - 2
lib/screens/hardware_settings_screen.dart

@@ -78,8 +78,8 @@ class HardwareSettingsScreen extends ConsumerWidget {
             subtitle: const Text(
               '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 '
-              'at or below 50 C. BLE flashing is not available.',
+              '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,

+ 141 - 48
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 = {
@@ -78,8 +91,7 @@ class MeCoffeeService extends StateNotifier<MachineState> {
       !state.isBrewing &&
       !state.isHeating &&
       !state.isSteaming &&
-      _lastPidAt != null &&
-      DateTime.now().difference(_lastPidAt!) < freshnessTimeout &&
+      _heaterOffConfirmed &&
       !state.telemetryStale &&
       state.temperature <= 50 &&
       supportsBundledFirmware(
@@ -155,7 +167,7 @@ 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,
@@ -270,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) {
@@ -288,8 +301,9 @@ class MeCoffeeService extends StateNotifier<MachineState> {
                 )
             ? '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.',
+            : '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;
     }
@@ -492,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,
@@ -559,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) {
@@ -701,6 +719,7 @@ class MeCoffeeService extends StateNotifier<MachineState> {
     'pwrflp': 'powerButtonFlipsBack',
     'tmppap': 'proActivePercentage',
     'tmrosd': 'autoShutoffMinutes',
+    'tmrosdnbl': 'autoShutoffEnabled',
     'shtmx': 'maxShotTime',
     'tmpcntns': 'continuousMode',
     'tmrwnbl': 'wakeupEnabled',
@@ -732,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,
@@ -807,6 +827,7 @@ class MeCoffeeService extends StateNotifier<MachineState> {
             'o2',
             'pwrflp',
             'tmrosd',
+            'tmrosdnbl',
             'shtmx',
             'pd1imn',
           }.contains,
@@ -817,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;
@@ -1142,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) {
@@ -1150,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)) {
@@ -1253,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;
@@ -1367,7 +1443,9 @@ 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')) {
@@ -1388,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+'));

+ 2 - 0
lib/services/me_coffee_protocol.dart

@@ -218,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':

+ 1 - 0
test/firmware/v10_firmware_conformance_test.dart

@@ -33,6 +33,7 @@ Object? field(MachineState s, String name) => switch (name) {
   'valveClosedWhilePaused' => s.valveClosedWhilePaused,
   'proActivePercentage' => s.proActivePercentage,
   'autoShutoffMinutes' => s.autoShutoffMinutes,
+  'autoShutoffEnabled' => s.autoShutoffEnabled,
   'maxShotTime' => s.maxShotTime,
   'continuousMode' => s.continuousMode,
   'installedAsTimer' => s.installedAsTimer,

+ 15 - 1
test/fixtures/v10_golden_transcripts.json

@@ -268,6 +268,20 @@
    "field": "autoShutoffMinutes",
    "expect": 45
   },
+  {
+   "key": "tmrosdnbl",
+   "kind": "bool",
+   "value": true,
+   "send": "cmd set tmrosdnbl 1\n",
+   "reply": [
+    "cmd set s_tmrosdnbl 1 OK"
+   ],
+   "readback": [
+    "cmd get tmrosdnbl 1 OK"
+   ],
+   "field": "autoShutoffEnabled",
+   "expect": true
+  },
   {
    "key": "shtmx",
    "kind": "int",
@@ -496,7 +510,7 @@
   "cmd get ppt 20 OK",
   "cmd get s2cr 0 OK",
   "cmd get pd1sz 500 OK",
-  "cmd get tmrosdnbl 0 OK",
+  "cmd get tmrosdnbl 1 OK",
   "cmd get tmrosd 45 OK",
   "cmd get o0 112 OK",
   "cmd get o1 98 OK",

+ 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);
   });

+ 147 - 0
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 [];
@@ -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:
@@ -323,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);
+    });
+  });
 }

+ 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,