#1 BLE fix

Merge realizado
thomashondema mesclou 2 commits de thomashondema/ble_fix em thomashondema/main 1 mês atrás

+ 0 - 4
lib/models/machine_state.dart

@@ -52,7 +52,6 @@ class MachineState {
   // Advanced Logic
   final bool valveClosedWhilePaused;
   final int proActivePercentage;
-  final double temperatureOffset;
   final int autoShutoffMinutes;
 
   // Scheduling
@@ -117,7 +116,6 @@ class MachineState {
     this.heatingPower = 0.0,
     this.valveClosedWhilePaused = false,
     this.proActivePercentage = 33,
-    this.temperatureOffset = 0.0,
     this.autoShutoffMinutes = 60,
     this.wakeupEnabled = false,
     this.wakeupTime = "07:00",
@@ -175,7 +173,6 @@ class MachineState {
     double? heatingPower,
     bool? valveClosedWhilePaused,
     int? proActivePercentage,
-    double? temperatureOffset,
     int? autoShutoffMinutes,
     bool? wakeupEnabled,
     String? wakeupTime,
@@ -236,7 +233,6 @@ class MachineState {
       valveClosedWhilePaused:
           valveClosedWhilePaused ?? this.valveClosedWhilePaused,
       proActivePercentage: proActivePercentage ?? this.proActivePercentage,
-      temperatureOffset: temperatureOffset ?? this.temperatureOffset,
       autoShutoffMinutes: autoShutoffMinutes ?? this.autoShutoffMinutes,
       wakeupEnabled: wakeupEnabled ?? this.wakeupEnabled,
       wakeupTime: wakeupTime ?? this.wakeupTime,

+ 5 - 12
lib/screens/pid_settings_screen.dart

@@ -1,6 +1,7 @@
 import 'package:flutter/material.dart';
 import 'package:flutter_riverpod/flutter_riverpod.dart';
 import '../services/bluetooth_service.dart';
+import '../services/me_coffee_protocol.dart';
 
 class PIDSettingsScreen extends ConsumerWidget {
   const PIDSettingsScreen({super.key});
@@ -52,30 +53,22 @@ class PIDSettingsScreen extends ConsumerWidget {
             max: 100,
             onChanged: (v) => bluetoothService.updateProActive(v.toInt()),
           ),
-          if (!isLegacyV4)
-            _PIDSlider(
-              label: 'Temperature Offset (°C)',
-              value: machineState.temperatureOffset,
-              min: -10,
-              max: 10,
-              step: 0.1,
-              decimalPlaces: 1,
-              onChanged: (v) => bluetoothService.updateOffset(v),
-            ),
           const Divider(),
           if (!isLegacyV4)
             _PIDSlider(
               label: 'I-Wind-down Min (%)',
               value: machineState.pidIWindDownMin,
               min: 0,
-              max: 100,
+              max: MeCoffeeProtocol.maxPidLimitPercent.toDouble(),
               onChanged: (v) => bluetoothService.updatePIDLimitSettings(min: v),
             ),
           _PIDSlider(
             label: isLegacyV4 ? 'I-Wind-down Max (raw)' : 'I-Wind-down Max (%)',
             value: machineState.pidIWindDownMax,
             min: 0,
-            max: isLegacyV4 ? 6000 : 100,
+            max: isLegacyV4
+                ? 6000
+                : MeCoffeeProtocol.maxPidLimitPercent.toDouble(),
             step: isLegacyV4 ? 250 : 1,
             onChanged: (v) => bluetoothService.updatePIDLimitSettings(max: v),
           ),

+ 3 - 2
lib/screens/settings_screen.dart

@@ -1,6 +1,7 @@
 import 'package:flutter/material.dart';
 import 'package:flutter_riverpod/flutter_riverpod.dart';
 import '../services/bluetooth_service.dart';
+import '../services/me_coffee_protocol.dart';
 import 'pid_settings_screen.dart';
 import 'statistics_screen.dart';
 import 'pressure_settings_screen.dart';
@@ -169,8 +170,8 @@ class SettingsScreen extends ConsumerWidget {
                 child: _DraftSlider(
                   value: machineState.maxShotTime.toDouble(),
                   min: 0,
-                  max: 120,
-                  divisions: 120,
+                  max: MeCoffeeProtocol.maxShotSeconds.toDouble(),
+                  divisions: MeCoffeeProtocol.maxShotSeconds,
                   format: (val) => val == 0 ? 'Off' : '${val.round()} s',
                   onSubmitted: (val) =>
                       bluetoothService.updateMaxShotTime(val.round()),

+ 1 - 4
lib/screens/statistics_screen.dart

@@ -57,10 +57,7 @@ class _StatTile extends StatelessWidget {
       title: Text(label),
       trailing: Text(
         value,
-        style: const TextStyle(
-          fontSize: 20,
-          fontWeight: FontWeight.bold,
-        ),
+        style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
       ),
     );
   }

+ 38 - 16
lib/services/bluetooth_service.dart

@@ -460,7 +460,6 @@ class MeCoffeeService extends StateNotifier<MachineState> {
       pressurePeriod: prefs.getInt('pressurePeriod') ?? 25,
       valveClosedWhilePaused: prefs.getBool('valveClosedWhilePaused') ?? false,
       proActivePercentage: prefs.getInt('proActivePercentage') ?? 33,
-      temperatureOffset: prefs.getDouble('temperatureOffset') ?? 0.0,
       autoShutoffMinutes: prefs.getInt('autoShutoffMinutes') ?? 60,
       wakeupEnabled: prefs.getBool('wakeupEnabled') ?? false,
       wakeupTime: prefs.getString('wakeupTime') ?? "07:00",
@@ -529,14 +528,19 @@ class MeCoffeeService extends StateNotifier<MachineState> {
   Future<void> updateProActive(int percentage) =>
       _updateSettings({'tmppap': percentage});
 
-  Future<void> updateOffset(double offset) =>
-      _updateSettings({'tmpoff': offset});
-
   Future<void> updateAutoShutoff(int minutes) =>
       _updateSettings({'tmrosd': minutes});
 
-  Future<void> updateMaxShotTime(int seconds) =>
-      _updateSettings({'shtmx': seconds});
+  Future<void> updateMaxShotTime(int seconds) async {
+    if (seconds < 0 || seconds > MeCoffeeProtocol.maxShotSeconds) {
+      _reportCommandError(
+        'Max shot time must be between 0 and '
+        '${MeCoffeeProtocol.maxShotSeconds} s.',
+      );
+      return;
+    }
+    await _updateSettings({'shtmx': seconds});
+  }
 
   Future<void> updateContinuousMode(bool enabled) =>
       _updateSettings({'tmpcntns': enabled});
@@ -565,18 +569,39 @@ class MeCoffeeService extends StateNotifier<MachineState> {
   Future<void> updatePIDSettings({double? p, double? i, double? d}) =>
       _updateSettings({'pd1p': ?p, 'pd1i': ?i, 'pd1d': ?d});
 
-  Future<void> updatePIDLimits(double min, double max, int interval) =>
-      _updateSettings({
-        'pd1imn': min,
-        'pd1imx': max,
-        'pd1sz': interval,
-      }, omitV4Minimum: true);
+  bool _pidLimitsOutOfRange(Iterable<double?> percentages) {
+    if (state.isLegacyV4Firmware) return false;
+    final outOfRange = percentages.any(
+      (value) =>
+          value != null &&
+          (value < 0 || value > MeCoffeeProtocol.maxPidLimitPercent),
+    );
+    if (outOfRange) {
+      _reportCommandError(
+        'I-wind-down limits must be between 0 and '
+        '${MeCoffeeProtocol.maxPidLimitPercent}%.',
+      );
+    }
+    return outOfRange;
+  }
+
+  Future<void> updatePIDLimits(double min, double max, int interval) async {
+    if (_pidLimitsOutOfRange([min, max])) return;
+    await _updateSettings({
+      'pd1imn': min,
+      'pd1imx': max,
+      'pd1sz': interval,
+    }, omitV4Minimum: true);
+  }
 
   Future<void> updatePIDLimitSettings({
     double? min,
     double? max,
     int? interval,
-  }) => _updateSettings({'pd1imn': ?min, 'pd1imx': ?max, 'pd1sz': ?interval});
+  }) async {
+    if (_pidLimitsOutOfRange([min, max])) return;
+    await _updateSettings({'pd1imn': ?min, 'pd1imx': ?max, 'pd1sz': ?interval});
+  }
 
   Future<void> _incrementShotCount() async {
     final prefs = await SharedPreferences.getInstance();
@@ -644,7 +669,6 @@ class MeCoffeeService extends StateNotifier<MachineState> {
     'tmrpwr': 'installedAsTimer',
     'pwrflp': 'powerButtonFlipsBack',
     'tmppap': 'proActivePercentage',
-    'tmpoff': 'temperatureOffset',
     'tmrosd': 'autoShutoffMinutes',
     'shtmx': 'maxShotTime',
     'tmpcntns': 'continuousMode',
@@ -676,7 +700,6 @@ class MeCoffeeService extends StateNotifier<MachineState> {
     'installedAsTimer': value.installedAsTimer,
     'powerButtonFlipsBack': value.powerButtonFlipsBack,
     'proActivePercentage': value.proActivePercentage,
-    'temperatureOffset': value.temperatureOffset,
     'autoShutoffMinutes': value.autoShutoffMinutes,
     'maxShotTime': value.maxShotTime,
     'continuousMode': value.continuousMode,
@@ -752,7 +775,6 @@ class MeCoffeeService extends StateNotifier<MachineState> {
             'o1',
             'o2',
             'pwrflp',
-            'tmpoff',
             'tmrosd',
             'shtmx',
             'pd1imn',

+ 21 - 9
lib/services/me_coffee_protocol.dart

@@ -1,6 +1,18 @@
 import '../models/machine_state.dart';
 
 class MeCoffeeProtocol {
+  /// Two-byte settings above this raw value are replaced by defaults when the
+  /// controller restores them at startup (V9/V10 firmware).
+  static const maxPersistentRaw = 32000;
+
+  /// Highest wind-down percentage whose raw value stays within
+  /// [maxPersistentRaw].
+  static const maxPidLimitPercent = 48;
+
+  /// The firmware compares against the low 16 bits of `shtmx * 1000`, so
+  /// 66 s and above wrap to a sub-second limit.
+  static const maxShotSeconds = 65;
+
   static MachineState parse(
     String msg,
     MachineState currentState, {
@@ -95,7 +107,10 @@ class MeCoffeeProtocol {
     // Command responses: cmd <set/get> <key> <value>
     if (command == 'cmd') {
       if (parts.length >= 4 && (parts[1] == 'set' || parts[1] == 'get')) {
-        final key = parts[2];
+        // Firmware echoes accepted writes as `cmd set s_<key> <value> OK`.
+        final key = parts[1] == 'set' && parts[2].startsWith('s_')
+            ? parts[2].substring(2)
+            : parts[2];
         final valStr = parts[3];
         return _updateFromKeyVal(
           currentState,
@@ -165,8 +180,6 @@ class MeCoffeeProtocol {
           return state.copyWith(valveClosedWhilePaused: val != 0);
         case 'tmppap':
           return state.copyWith(proActivePercentage: val.toInt());
-        case 'tmpoff':
-          return state.copyWith(temperatureOffset: val / 100.0);
         case 'tmrosd':
           return state.copyWith(autoShutoffMinutes: val.toInt());
         case 'o0':
@@ -195,6 +208,7 @@ class MeCoffeeProtocol {
           return state.copyWith(pressureEnd: val.toInt());
         case 'ppt':
           return state.copyWith(pressurePeriod: val.toInt());
+        case 'cntgrndr':
         case 'grndr_cnt':
           return state.copyWith(grinderCounter: val.toInt());
         case 'shtmx':
@@ -217,14 +231,16 @@ class MeCoffeeProtocol {
     } else if (value is String && (key == 'tmron' || key == 'tmroff')) {
       valStr = _timeStringToSeconds(value).toString();
     } else if (value is double) {
-      if (key == 'tmpsp' || key == 'tmpstm' || key == 'tmpoff') {
+      if (key == 'tmpsp' || key == 'tmpstm') {
         valStr = (value * 100).round().toString();
       } else if (key == 'pistrt' || key == 'piprd') {
         valStr = (value * (isLegacyV4 ? 1 : 1000)).round().toString();
       } else if (key == 'pd1i') {
         valStr = (value * (isLegacyV4 ? 1 : 100)).round().toString();
       } else if (key == 'pd1imm' || key == 'pd1imn' || key == 'pd1imx') {
-        valStr = (value * (isLegacyV4 ? 1 : 655.36)).round().toString();
+        valStr = isLegacyV4
+            ? value.round().toString()
+            : (value * 655.36).round().clamp(0, maxPersistentRaw).toString();
       } else {
         valStr = value.round().toString();
       }
@@ -315,10 +331,6 @@ class MeCoffeeProtocol {
     return _toBytes(encodeSet('tmppap', percentage));
   }
 
-  static List<int> encodeOffset(double offset) {
-    return _toBytes(encodeSet('tmpoff', offset));
-  }
-
   static List<int> encodeAutoShutoff(int minutes) {
     return _toBytes(encodeSet('tmrosd', minutes));
   }

+ 1 - 1
test/screens/settings_ranges_test.dart

@@ -92,7 +92,7 @@ void main() {
       } else {
         expect(
           (sliders[4].min, sliders[4].max, sliders[4].divisions),
-          (0, 120, 120),
+          (0, 65, 65),
         );
       }
 

+ 5 - 20
test/screens/v4_pid_settings_screen_test.dart

@@ -10,7 +10,6 @@ import 'package:mebarista/services/bluetooth_service.dart';
 class _RecordingPIDService extends MeCoffeeService {
   List<double>? pid;
   List<num>? limits;
-  double? offset;
   int? proactive;
   MachineState get machineState => state;
 
@@ -34,11 +33,6 @@ class _RecordingPIDService extends MeCoffeeService {
     ];
   }
 
-  @override
-  Future<void> updateOffset(double value) async {
-    offset = value;
-  }
-
   @override
   Future<void> updateProActive(int value) async {
     proactive = value;
@@ -124,28 +118,19 @@ void main() {
   testWidgets('modern PID preserves fine steps and firmware control ranges', (
     tester,
   ) async {
-    final service = await _pumpPID(
-      tester,
-      MachineState(pidP: 100, pidI: 0.35, temperatureOffset: 0.1),
-    );
+    final service = await _pumpPID(tester, MachineState(pidP: 100, pidI: 0.35));
     final sliders = tester.widgetList<Slider>(find.byType(Slider)).toList();
-    expect(sliders, hasLength(8));
+    expect(sliders, hasLength(7));
     expect((sliders[0].max, sliders[0].divisions), (100, 100));
     expect((sliders[1].max, sliders[1].divisions), (1, 100));
     expect(sliders[2].divisions, 256);
     expect(sliders[3].divisions, 100);
-    expect(
-      (sliders[4].min, sliders[4].max, sliders[4].divisions),
-      (-10, 10, 200),
-    );
-    expect(sliders[5].divisions, 100);
-    expect(sliders[6].divisions, 100);
+    expect((sliders[4].max, sliders[4].divisions), (48, 48));
+    expect((sliders[5].max, sliders[5].divisions), (48, 48));
     expect(find.text('Integral (I): 0.35'), findsOneWidget);
-    expect(find.text('Temperature Offset (°C): 0.1'), findsOneWidget);
+    expect(find.textContaining('Temperature Offset'), findsNothing);
     sliders[1].onChanged!(0.35000000000000003);
     expect(service.pid, [100, 0.35, 128]);
-    sliders[4].onChanged!(0.10000000000000009);
-    expect(service.offset, 0.1);
     sliders[3].onChanged!(34);
     expect(service.proactive, 34);
     expect(tester.takeException(), isNull);

+ 13 - 1
test/services/classic_service_test.dart

@@ -235,7 +235,6 @@ void main() {
     await connect();
     transport.data.add('cmd uname meCoffee V4 OK\n'.codeUnits);
     transport.writes.clear();
-    await service.updateOffset(1);
     await service.updateAutoShutoff(30);
     await service.updateMaxShotTime(25);
     await service.updateHardware(112, 98, 118, false, false);
@@ -244,6 +243,19 @@ void main() {
     expect(String.fromCharCodes(transport.writes.single), 'cmd set tmrpwr 1\n');
   });
 
+  test('settings outside firmware storage limits are not sent', () async {
+    await connect();
+    transport.data.add('cmd uname meCoffee  pcb V9 30 149 15 OK\n'.codeUnits);
+    transport.writes.clear();
+    await service.updateMaxShotTime(66);
+    expect(service.state.commandError, contains('65 s'));
+    await service.updatePIDLimitSettings(max: 49);
+    expect(service.state.commandError, contains('48%'));
+    expect(transport.writes, isEmpty);
+    await service.updateMaxShotTime(65);
+    expect(String.fromCharCodes(transport.writes.single), 'cmd set shtmx 65\n');
+  });
+
   test('cold temperature alone does not establish heater-off status', () async {
     await connect();
     transport.data.add('tmp 1 10100 2000\n'.codeUnits);

+ 31 - 25
test/services/me_coffee_protocol_test.dart

@@ -137,6 +137,19 @@ void main() {
       expect(state.valveClosedWhilePaused, isTrue);
     });
 
+    test('parses firmware grinder counter key and set echoes', () {
+      var state = MachineState();
+
+      state = MeCoffeeProtocol.parse('cmd get cntgrndr 42 OK', state);
+      expect(state.grinderCounter, 42);
+
+      state = MeCoffeeProtocol.parse('cmd set s_tmpsp 9350 OK', state);
+      expect(state.brewTemperature, 93.5);
+
+      final rejected = MeCoffeeProtocol.parse('cmd set  NOT OK', state);
+      expect(rejected.brewTemperature, 93.5);
+    });
+
     test('normalizes parsed schedule seconds to HH:mm', () {
       var state = MachineState();
 
@@ -382,38 +395,31 @@ void main() {
             50,
           );
         }
+        expect(
+          String.fromCharCodes(MeCoffeeProtocol.encodePIDLimits(25, 48, 1000)),
+          'cmd set pd1imn 16384\ncmd set pd1imx 31457\ncmd set pd1sz 1000\n',
+        );
+        // Raw values above 32000 are reset to defaults at controller startup,
+        // and 65536 would store 0 in the 16-bit field.
         expect(
           String.fromCharCodes(MeCoffeeProtocol.encodePIDLimits(50, 100, 1000)),
-          'cmd set pd1imn 32768\ncmd set pd1imx 65536\ncmd set pd1sz 1000\n',
+          'cmd set pd1imn 32000\ncmd set pd1imx 32000\ncmd set pd1sz 1000\n',
         );
       },
     );
 
-    test(
-      'settings ranges preserve direct P, D, percentage and offset units',
-      () {
-        var state = MachineState();
-        for (final entry in {
-          'pd1p': 100,
-          'pd1d': 256,
-          'tmppap': 100,
-          'tmpoff': -1000,
-        }.entries) {
-          state = MeCoffeeProtocol.parse(
-            'cmd get ${entry.key} ${entry.value}',
-            state,
-          );
-        }
-        expect(state.pidP, 100);
-        expect(state.pidD, 256);
-        expect(state.proActivePercentage, 100);
-        expect(state.temperatureOffset, -10);
-        expect(
-          String.fromCharCodes(MeCoffeeProtocol.encodeOffset(0.1)),
-          'cmd set tmpoff 10\n',
+    test('settings ranges preserve direct P, D and percentage units', () {
+      var state = MachineState();
+      for (final entry in {'pd1p': 100, 'pd1d': 256, 'tmppap': 100}.entries) {
+        state = MeCoffeeProtocol.parse(
+          'cmd get ${entry.key} ${entry.value}',
+          state,
         );
-      },
-    );
+      }
+      expect(state.pidP, 100);
+      expect(state.pidD, 256);
+      expect(state.proActivePercentage, 100);
+    });
 
     test(
       'unknown and nonfinite settings do not alter state or guess scaling',