diff --git a/lib/integrations/hue.dart b/lib/integrations/hue.dart index 11f2d223d..d68d63349 100644 --- a/lib/integrations/hue.dart +++ b/lib/integrations/hue.dart @@ -215,13 +215,18 @@ class HueBridge { } } + @visibleForTesting + static http.Client? testClient; + static Future load() async { final s = await _store.read(key: _kBridge, iOptions: _apple); if (s == null) return null; final m = jsonDecode(s) as Map; - return HueBridge(m['ip'] as String, m['user'] as String, fingerprint: m['fp'] as String?); + return HueBridge(m['ip'] as String, m['user'] as String, fingerprint: m['fp'] as String?, client: testClient); } + void close() => _c.close(); + Future forget() async { await _store.delete(key: _kBridge, iOptions: _apple); await _store.delete(key: _kSched, iOptions: _apple); @@ -364,24 +369,40 @@ Future _hueSerial(Future Function() f) { /// Best effort, all of these: a bridge that is off, moved or unpaired must /// never get in the way of the alarm or the reminder that called it. Future hueSunriseFor(DateTime? wake) => _hueSerial(() async { + HueBridge? b; try { - final b = await HueBridge.load(); + b = await HueBridge.load(); final room = await hueRoom(); if (b == null || room == null) return; wake == null ? await b.clearSunrise() : await b.scheduleSunrise(wake: wake, groupId: room); } catch (e) { debugPrint('[hue] sunrise: $e'); + } finally { + b?.close(); } }); +// What the bridge last got for wind-down (room + time). Reminder passes run on +// every sync batch and resume with the same time; only a change, or a retry +// after a failure, needs to reach the bridge. +String? _hueWindDownLast; + Future hueWindDownAt(DateTime? at) => _hueSerial(() async { + HueBridge? b; try { - final b = await HueBridge.load(); final room = await hueRoom(); - if (b == null || room == null) return; + if (room == null) return; + final key = '$room|${at?.toUtc().toIso8601String()}'; + if (key == _hueWindDownLast) return; + b = await HueBridge.load(); + if (b == null) return; + _hueWindDownLast = null; // a half-done replace must be retried at == null ? await b.clearWindDown() : await b.scheduleWindDown(at: at, groupId: room); + _hueWindDownLast = key; } catch (e) { debugPrint('[hue] wind-down: $e'); + } finally { + b?.close(); } }); @@ -390,11 +411,16 @@ Future hueWindDownAt(DateTime? at) => _hueSerial(() async { Future hueClearAll() async { var ok = true; await _hueSerial(() async { + _hueWindDownLast = null; + HueBridge? b; try { - await (await HueBridge.load())?.clearSchedules(); + b = await HueBridge.load(); + await b?.clearSchedules(); } catch (e) { debugPrint('[hue] clear: $e'); ok = false; + } finally { + b?.close(); } }); return ok; diff --git a/lib/notify/notification_center.dart b/lib/notify/notification_center.dart index 4bf6d89a9..5c28f146b 100644 --- a/lib/notify/notification_center.dart +++ b/lib/notify/notification_center.dart @@ -519,7 +519,9 @@ class NotificationCenter { final now = DateTime.now(); var at = DateTime(now.year, now.month, now.day, minuteOfDay ~/ 60, minuteOfDay % 60); if (!at.isAfter(now)) at = at.add(const Duration(days: 1)); - await hueWindDownAt(at); + // Not awaited: a bridge that is off the network sits on its timeouts, and + // the arms after this one must not wait for it. + unawaited(hueWindDownAt(at)); } /// The wind-down copy. Names the LEARNED bedtime, not the slot plus the diff --git a/test/integrations/hue_test.dart b/test/integrations/hue_test.dart index 5defc8907..30d92f9a9 100644 --- a/test/integrations/hue_test.dart +++ b/test/integrations/hue_test.dart @@ -1,9 +1,11 @@ import 'dart:convert'; +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:http/http.dart' as http; import 'package:http/testing.dart'; import 'package:openstrap_edge/integrations/hue.dart'; +import 'package:shared_preferences/shared_preferences.dart'; void main() { test('localtime format', () { @@ -63,4 +65,38 @@ void main() { expect(hueBridgeOffset(const Duration(seconds: 50)), Duration.zero); expect(hueBridgeOffset(const Duration(minutes: -300, seconds: -20)), const Duration(minutes: -300)); }); + + test('wind-down only reaches the bridge when the time changes or the last try failed', () async { + FlutterSecureStorage.setMockInitialValues({'hue.bridge': '{"ip":"192.0.2.1","user":"u","fp":"x"}'}); + SharedPreferences.setMockInitialValues({'hue_room': '1'}); + final calls = []; + var failPost = true; + HueBridge.testClient = MockClient((r) async { + calls.add(r.method); + if (r.method == 'GET') return http.Response('{"localtime":"2000-01-01T00:00:00"}', 200); + if (r.method == 'POST' && failPost) return http.Response('[{"error":{"type":7,"description":"x"}}]', 200); + if (r.method == 'POST') return http.Response('[{"success":{"id":"9"}}]', 200); + return http.Response('[{"success":"gone"}]', 200); + }); + addTearDown(() => HueBridge.testClient = null); + final at = DateTime.now().add(const Duration(hours: 2)); + + await hueWindDownAt(at); + expect(calls, contains('POST')); + failPost = false; + calls.clear(); + await hueWindDownAt(at); // retried after the failed POST + expect(calls, contains('POST')); + calls.clear(); + await hueWindDownAt(at); // same time again: nothing sent + expect(calls, isEmpty); + await hueWindDownAt(at.add(const Duration(days: 1))); + expect(calls, ['DELETE', 'GET', 'POST']); + calls.clear(); + await hueWindDownAt(null); + expect(calls, ['DELETE']); + calls.clear(); + await hueWindDownAt(null); + expect(calls, isEmpty); + }); }