Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 31 additions & 5 deletions lib/integrations/hue.dart
Original file line number Diff line number Diff line change
Expand Up @@ -215,13 +215,18 @@ class HueBridge {
}
}

@visibleForTesting
static http.Client? testClient;

static Future<HueBridge?> 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<void> forget() async {
await _store.delete(key: _kBridge, iOptions: _apple);
await _store.delete(key: _kSched, iOptions: _apple);
Expand Down Expand Up @@ -364,24 +369,40 @@ Future<void> _hueSerial(Future<void> 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<void> 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<void> 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;
Comment thread
abdulsaheel marked this conversation as resolved.
Resolved
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();
}
});

Expand All @@ -390,11 +411,16 @@ Future<void> hueWindDownAt(DateTime? at) => _hueSerial(() async {
Future<bool> 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;
Expand Down
4 changes: 3 additions & 1 deletion lib/notify/notification_center.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
36 changes: 36 additions & 0 deletions test/integrations/hue_test.dart
Original file line number Diff line number Diff line change
@@ -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', () {
Expand Down Expand Up @@ -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 = <String>[];
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);
});
}
Loading