From 26d200e282a4b790ee05d1fcd8cd0dc92c8a7f46 Mon Sep 17 00:00:00 2001 From: iGoX Date: Fri, 16 Oct 2026 19:24:00 +0200 Subject: [PATCH] Add websocket support (#13) Reviewed-on: https://code.igox.org/busylight/busylight-buddy/pulls/13 --- .vscode/settings.json | 3 + README.md | 36 +- .../reports/problems/problems-report.html | 666 ++++++++++++++++++ .../gradle/wrapper/gradle-wrapper.properties | 3 +- lib/providers/busylight_provider.dart | 124 ++-- lib/screens/home_screen.dart | 5 +- lib/screens/settings_screen.dart | 58 -- lib/services/busylight_service.dart | 41 ++ macos/Podfile | 8 +- macos/Podfile.lock | 2 +- macos/Runner.xcodeproj/project.pbxproj | 10 +- macos/toolchain/lipo | 12 + pubspec.lock | 2 +- pubspec.yaml | 1 + test/busylight_live_status_test.dart | 183 +++++ test/widget_test.dart | 56 +- 16 files changed, 1042 insertions(+), 168 deletions(-) create mode 100644 .vscode/settings.json create mode 100644 android/build/reports/problems/problems-report.html create mode 100755 macos/toolchain/lipo create mode 100644 test/busylight_live_status_test.dart diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..85c892f --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "cmake.sourceDirectory": "/Users/mbocquet/PRIVATE Documents/git/code-igox/busylight-buddy/windows" +} \ No newline at end of file diff --git a/README.md b/README.md index 051f887..26cb78a 100644 --- a/README.md +++ b/README.md @@ -38,14 +38,15 @@ Supports **Android**, **macOS**, and **Windows**. ### Brightness - Brightness slider (0–100%) -### Background polling -- Automatically pulls status + color from device at a configurable interval +### Live updates +- Subscribes to `/ws/status` for live status, color, and brightness updates +- Automatically reconnects after a disconnect or device address change - Silent updates — no loading screen interruption -- Configurable in Settings (default: every second, can be disabled) +- Initial state comes from the WebSocket; no REST polling is used +- Keeps the last received state visible while reconnecting ### Settings - Device address (hostname or IP, e.g. `http://igox-busylight.local`) -- Polling interval slider (Off → 1 min) - Start with session (macOS and Windows only) — launch automatically at login ### UX & feedback @@ -86,10 +87,10 @@ busylight_app/ │ │ ├── busylight_color.dart # Color model (r/g/b/brightness) │ │ └── color_preset.dart # Named color preset model │ ├── services/ -│ │ ├── busylight_service.dart # All REST API calls +│ │ ├── busylight_service.dart # REST API calls and WebSocket status stream │ │ └── autostart_service.dart # Start with session (macOS + Windows) │ ├── providers/ -│ │ ├── busylight_provider.dart # Status, color, brightness, polling, config +│ │ ├── busylight_provider.dart # Live status, color, brightness, config │ │ └── presets_provider.dart # Custom color presets (CRUD + persistence) │ ├── screens/ │ │ ├── home_screen.dart # Main screen @@ -106,19 +107,28 @@ busylight_app/ | Endpoint | Method | Description | |---|---|---| -| `/api/status` | GET | Get current status | -| `/api/status/available` | POST/GET | Set available (green) | -| `/api/status/away` | POST/GET | Set away (yellow) | -| `/api/status/busy` | POST/GET | Set busy (red) | -| `/api/status/on` | POST/GET | Turn on (white) | -| `/api/status/off` | POST/GET | Turn off | -| `/api/color` | GET | Get current color + brightness | +| `/ws/status` | WebSocket | Initial state and live status, color, brightness updates | +| `/api/status/available` | POST | Set available (green) | +| `/api/status/away` | POST | Set away (yellow) | +| `/api/status/busy` | POST | Set busy (red) | +| `/api/status/on` | POST | Turn on (white) | +| `/api/status/off` | POST | Turn off | | `/api/color` | POST | Set custom color (r, g, b, brightness) | --- ## Platform setup +### macOS — build release + +Requires macOS 12.0 or newer. + +```bash +flutter build macos +``` + +The Flutter Xcode build phases use `macos/toolchain/lipo` to work around Xcode 27.1 rejecting Flutter's multi-architecture `-verify_arch` call. It verifies each requested architecture separately and delegates all other operations to the system tool. The app remains universal (Intel and Apple Silicon); no Flutter SDK modifications are needed. + ### Android — build APK Two helper scripts are available in the `android/` folder to build and rename the APK in one step — one for macOS/Linux, one for Windows. diff --git a/android/build/reports/problems/problems-report.html b/android/build/reports/problems/problems-report.html new file mode 100644 index 0000000..d9f760f --- /dev/null +++ b/android/build/reports/problems/problems-report.html @@ -0,0 +1,666 @@ + + + + + + + + + + + + + Gradle Configuration Cache + + + +
+ +
+ Loading... +
+ + + + + + diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties index e4ef43f..605da55 100644 --- a/android/gradle/wrapper/gradle-wrapper.properties +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,6 @@ +#Fri Oct 16 18:40:11 CEST 2026 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.7.1-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.14-all.zip diff --git a/lib/providers/busylight_provider.dart b/lib/providers/busylight_provider.dart index f1ab931..54a953e 100644 --- a/lib/providers/busylight_provider.dart +++ b/lib/providers/busylight_provider.dart @@ -9,8 +9,6 @@ import '../services/busylight_service.dart'; const _kHostKey = 'busylight_host'; const _kDefaultHost = 'http://igox-busylight.local'; -const _kPollIntervalKey = 'busylight_poll_interval'; -const _kDefaultPollInterval = 1.0; // seconds final sharedPreferencesProvider = FutureProvider( (_) => SharedPreferences.getInstance(), @@ -21,11 +19,6 @@ final deviceHostProvider = StateProvider((ref) { return prefs?.getString(_kHostKey) ?? _kDefaultHost; }); -final pollIntervalProvider = StateProvider((ref) { - final prefs = ref.watch(sharedPreferencesProvider).valueOrNull; - return prefs?.getDouble(_kPollIntervalKey) ?? _kDefaultPollInterval.toDouble(); -}); - // ── Service ────────────────────────────────────────────────────────────────── final busylightServiceProvider = Provider((ref) { @@ -33,33 +26,10 @@ final busylightServiceProvider = Provider((ref) { return BusylightService(baseUrl: host); }); -// ── Startup snapshot ───────────────────────────────────────────────────────── -// Loads status + color (which includes brightness) in 2 parallel calls. -// No separate GET /api/brightness needed — the color response already has it. - -class BusylightSnapshot { - final BusylightStatus status; - final BusylightColor color; - - const BusylightSnapshot({ - required this.status, - required this.color, - }); - - double get brightness => color.brightness; -} - -final busylightSnapshotProvider = FutureProvider((ref) async { - final service = ref.watch(busylightServiceProvider); - final results = await Future.wait([ - service.getStatus(), - service.getColor(), - ]); - return BusylightSnapshot( - status: results[0] as BusylightStatus, - color: results[1] as BusylightColor, - ); -}); +final busylightSnapshotProvider = + StateNotifierProvider>( + (ref) => LiveStatusNotifier(ref.watch(busylightServiceProvider)), +); // ── State notifiers ────────────────────────────────────────────────────────── @@ -67,25 +37,21 @@ class BusylightStateNotifier extends StateNotifier> BusylightStateNotifier(this._service, BusylightStatus? initial) : super(initial != null ? AsyncValue.data(initial) - : const AsyncValue.loading()) { - if (initial == null) refresh(); - } + : const AsyncValue.loading()); final BusylightService _service; - - Future refresh() async { - state = const AsyncValue.loading(); - state = await AsyncValue.guard(_service.getStatus); - } + int _revision = 0; Future setStatus(BusylightStatus status) async { // Keep current value visible during the API call — no loading state + final revision = ++_revision; final result = await AsyncValue.guard(() => _service.setStatus(status)); - state = result; + if (mounted && revision == _revision) state = result; } /// Update state locally without making an API call (e.g. for `colored`) void setLocalStatus(BusylightStatus status) { + _revision++; state = AsyncValue.data(status); } } @@ -120,7 +86,7 @@ final brightnessProvider = StateNotifierProvider( final snapshot = ref.watch(busylightSnapshotProvider).valueOrNull; return BrightnessNotifier( ref.watch(busylightServiceProvider), - snapshot?.brightness ?? 0.3, + snapshot?.color.brightness ?? 0.3, ); }, ); @@ -149,51 +115,47 @@ final colorProvider = StateNotifierProvider( }, ); -// ── Background polling ──────────────────────────────────────────────────────── -// Periodically pulls status + color from the device and silently updates state. - -class PollingNotifier extends StateNotifier { - PollingNotifier(this._ref) : super(null) { - _start(); +class LiveStatusNotifier extends StateNotifier> { + LiveStatusNotifier( + this._service, { + this.reconnectDelay = const Duration(seconds: 2), + }) : super(const AsyncValue.loading()) { + _connect(); } - final Ref _ref; - Timer? _timer; + final BusylightService _service; + final Duration reconnectDelay; + Timer? _reconnectTimer; + StreamSubscription? _subscription; - void _start() { - final intervalSeconds = _ref.read(pollIntervalProvider); - final intervalMillis = (intervalSeconds * 1000).toInt(); - _timer?.cancel(); - if (intervalMillis <= 0) return; - _timer = Timer.periodic(Duration(milliseconds: intervalMillis), (_) => _poll()); + void _connect() { + if (!mounted) return; + _subscription = _service.watchStatus().listen( + (update) { + if (!mounted) return; + state = AsyncValue.data(update); + }, + onError: _disconnected, + onDone: () => _disconnected( + const BusylightException('Live status connection closed'), + StackTrace.current, + ), + cancelOnError: true, + ); } - void restart() => _start(); - - Future _poll() async { - try { - final service = _ref.read(busylightServiceProvider); - final results = await Future.wait([ - service.getStatus(), - service.getColor(), - ]); - final status = results[0] as BusylightStatus; - final color = results[1] as BusylightColor; - _ref.read(busylightStatusProvider.notifier).setLocalStatus(status); - _ref.read(colorProvider.notifier).silentSet(color); - _ref.read(brightnessProvider.notifier).silentSet(color.brightness); - } catch (_) { - // Silently ignore poll errors — connection issues are shown on manual refresh - } + void _disconnected(Object error, StackTrace stackTrace) { + if (!mounted) return; + state = AsyncValue.error(error, stackTrace) + .copyWithPrevious(state); + _reconnectTimer?.cancel(); + _reconnectTimer = Timer(reconnectDelay, _connect); } @override void dispose() { - _timer?.cancel(); + _reconnectTimer?.cancel(); + _subscription?.cancel(); super.dispose(); } -} - -final pollingProvider = StateNotifierProvider( - (ref) => PollingNotifier(ref), -); \ No newline at end of file +} \ No newline at end of file diff --git a/lib/screens/home_screen.dart b/lib/screens/home_screen.dart index 3235863..1015db4 100644 --- a/lib/screens/home_screen.dart +++ b/lib/screens/home_screen.dart @@ -36,9 +36,6 @@ class HomeScreen extends ConsumerWidget { final snapshot = ref.watch(busylightSnapshotProvider); final statusAsync = ref.watch(busylightStatusProvider); - // Start background polling (no-op if already running) - ref.watch(pollingProvider); - if (!snapshot.hasValue && !snapshot.hasError) { return Scaffold( backgroundColor: Colors.black, @@ -65,7 +62,7 @@ class HomeScreen extends ConsumerWidget { loading: () => const Center(child: CircularProgressIndicator(color: Colors.amber)), error: (e, _) => _ErrorView( message: e.toString(), - onRetry: () => ref.read(busylightStatusProvider.notifier).refresh(), + onRetry: () => ref.invalidate(busylightSnapshotProvider), ), data: (_) => const _Body(), ), diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart index 1924c10..0793493 100644 --- a/lib/screens/settings_screen.dart +++ b/lib/screens/settings_screen.dart @@ -1,4 +1,3 @@ -import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:shared_preferences/shared_preferences.dart'; @@ -14,14 +13,12 @@ class SettingsScreen extends ConsumerStatefulWidget { class _SettingsScreenState extends ConsumerState { late TextEditingController _hostController; - late double _pollInterval; bool _startWithSession = false; @override void initState() { super.initState(); _hostController = TextEditingController(text: ref.read(deviceHostProvider)); - _pollInterval = ref.read(pollIntervalProvider); _loadAutostart(); } @@ -41,14 +38,11 @@ class _SettingsScreenState extends ConsumerState { if (host.isEmpty) return; ref.read(deviceHostProvider.notifier).state = host; - ref.read(pollIntervalProvider.notifier).state = _pollInterval; - ref.read(pollingProvider.notifier).restart(); await AutostartService.setEnabled(_startWithSession); final prefs = await SharedPreferences.getInstance(); await prefs.setString('busylight_host', host); - await prefs.setDouble('busylight_poll_interval', _pollInterval); if (mounted) { ScaffoldMessenger.of(context).showSnackBar( @@ -58,12 +52,6 @@ class _SettingsScreenState extends ConsumerState { } } - String _intervalLabel(double seconds) { - if (seconds == 0.0) return 'Off'; - if (seconds < 2.0) return '${seconds}s'; - return '${ (seconds)}s'; - } - @override Widget build(BuildContext context) { return Scaffold( @@ -103,52 +91,6 @@ class _SettingsScreenState extends ConsumerState { ), const SizedBox(height: 32), - // ── Polling interval ──────────────────────────────────────────── - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Text('Status polling', - style: TextStyle(color: Colors.grey.shade300, fontSize: 13, fontWeight: FontWeight.w600)), - Text( - _intervalLabel(_pollInterval), - style: const TextStyle(color: Colors.amber, fontSize: 13, fontWeight: FontWeight.w600), - ), - ], - ), - const SizedBox(height: 8), - SliderTheme( - data: SliderTheme.of(context).copyWith( - activeTrackColor: Colors.amber, - thumbColor: Colors.amber, - inactiveTrackColor: Colors.grey.shade800, - overlayColor: Colors.amber.withOpacity(0.2), - ), - child: Slider( - value: _pollInterval, - min: 0.0, - max: 2.0, - divisions: 4, - onChanged: (v) => setState(() => _pollInterval = v), - ), - ), - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Text('Off', style: TextStyle(color: Colors.grey.shade600, fontSize: 11)), - Text('0.5s', style: TextStyle(color: Colors.grey.shade600, fontSize: 11)), - Text('1s', style: TextStyle(color: Colors.grey.shade600, fontSize: 11)), - Text('1.5s', style: TextStyle(color: Colors.grey.shade600, fontSize: 11)), - Text('2s', style: TextStyle(color: Colors.grey.shade600, fontSize: 11)), - ], - ), - const SizedBox(height: 6), - Text( - _pollInterval == 0 - ? 'Polling is disabled. Status will only refresh manually.' - : 'Status is pulled from the device every $_pollInterval seconds.', - style: TextStyle(color: Colors.grey.shade600, fontSize: 12), - ), - // ── Start with session (macOS + Windows only) ─────────────────── if (AutostartService.isSupported) ...[ const SizedBox(height: 32), diff --git a/lib/services/busylight_service.dart b/lib/services/busylight_service.dart index ce31fcb..c5636d9 100644 --- a/lib/services/busylight_service.dart +++ b/lib/services/busylight_service.dart @@ -1,8 +1,29 @@ import 'dart:convert'; import 'package:http/http.dart' as http; +import 'package:web_socket_channel/web_socket_channel.dart'; import '../models/busylight_color.dart'; import '../models/busylight_status.dart'; +class BusylightUpdate { + final BusylightStatus status; + final BusylightColor color; + + const BusylightUpdate({required this.status, required this.color}); + + factory BusylightUpdate.fromJson(Map json) { + final color = json['color'] as List; + return BusylightUpdate( + status: BusylightStatus.fromString(json['status'] as String), + color: BusylightColor( + r: (color[0] as num).toInt(), + g: (color[1] as num).toInt(), + b: (color[2] as num).toInt(), + brightness: (json['brightness'] as num).toDouble(), + ), + ); + } +} + class BusylightException implements Exception { final String message; const BusylightException(this.message); @@ -21,6 +42,26 @@ class BusylightService { Uri _uri(String path) => Uri.parse('$baseUrl$path'); + Stream watchStatus() async* { + final uri = _uri('/ws/status'); + final channel = WebSocketChannel.connect( + uri.replace(scheme: uri.scheme == 'https' ? 'wss' : 'ws'), + ); + try { + await channel.ready.timeout(timeout); + await for (final message in channel.stream) { + final text = message is String + ? message + : utf8.decode(message as List); + yield BusylightUpdate.fromJson( + jsonDecode(text) as Map, + ); + } + } finally { + await channel.sink.close(); + } + } + Future> _get(String path) async { try { final res = await http.get(_uri(path)).timeout(timeout); diff --git a/macos/Podfile b/macos/Podfile index ff5ddb3..613c5a4 100644 --- a/macos/Podfile +++ b/macos/Podfile @@ -1,4 +1,4 @@ -platform :osx, '10.15' +platform :osx, '12.0' # CocoaPods analytics sends network stats synchronously affecting flutter build latency. ENV['COCOAPODS_DISABLE_STATS'] = 'true' @@ -38,5 +38,11 @@ end post_install do |installer| installer.pods_project.targets.each do |target| flutter_additional_macos_build_settings(target) + target.build_configurations.each do |config| + deployment_target = config.build_settings['MACOSX_DEPLOYMENT_TARGET'] || '0' + if Gem::Version.new(deployment_target) < Gem::Version.new('12.0') + config.build_settings['MACOSX_DEPLOYMENT_TARGET'] = '12.0' + end + end end end diff --git a/macos/Podfile.lock b/macos/Podfile.lock index 1385d0f..85cf657 100644 --- a/macos/Podfile.lock +++ b/macos/Podfile.lock @@ -18,6 +18,6 @@ SPEC CHECKSUMS: FlutterMacOS: d0db08ddef1a9af05a5ec4b724367152bb0500b1 shared_preferences_foundation: 7036424c3d8ec98dfe75ff1667cb0cd531ec82bb -PODFILE CHECKSUM: 54d867c82ac51cbd61b565781b9fada492027009 +PODFILE CHECKSUM: f24c7d0ecaa1b6ecc83f74a8e53fc646a281a2d5 COCOAPODS: 1.16.2 diff --git a/macos/Runner.xcodeproj/project.pbxproj b/macos/Runner.xcodeproj/project.pbxproj index bcf2adc..5efb7d3 100644 --- a/macos/Runner.xcodeproj/project.pbxproj +++ b/macos/Runner.xcodeproj/project.pbxproj @@ -355,7 +355,7 @@ ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "echo \"$PRODUCT_NAME.app\" > \"$PROJECT_DIR\"/Flutter/ephemeral/.app_filename && \"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh embed\n"; + shellScript = "export PATH=\"$PROJECT_DIR/toolchain:$PATH\"\necho \"$PRODUCT_NAME.app\" > \"$PROJECT_DIR\"/Flutter/ephemeral/.app_filename && \"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh embed\n"; }; 33CC111E2044C6BF0003C045 /* ShellScript */ = { isa = PBXShellScriptBuildPhase; @@ -375,7 +375,7 @@ ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh && touch Flutter/ephemeral/tripwire"; + shellScript = "export PATH=\"$PROJECT_DIR/toolchain:$PATH\"\n\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh && touch Flutter/ephemeral/tripwire"; }; 7ED5BCFD33FB57073491EF91 /* [CP] Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; @@ -556,7 +556,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.15; + MACOSX_DEPLOYMENT_TARGET = 12.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = macosx; SWIFT_COMPILATION_MODE = wholemodule; @@ -642,7 +642,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.15; + MACOSX_DEPLOYMENT_TARGET = 12.0; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = macosx; @@ -692,7 +692,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.15; + MACOSX_DEPLOYMENT_TARGET = 12.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = macosx; SWIFT_COMPILATION_MODE = wholemodule; diff --git a/macos/toolchain/lipo b/macos/toolchain/lipo new file mode 100755 index 0000000..af0e58b --- /dev/null +++ b/macos/toolchain/lipo @@ -0,0 +1,12 @@ +#!/bin/sh + +if [ "$#" -gt 3 ] && [ "$2" = "-verify_arch" ]; then + binary="$1" + shift 2 + for architecture do + /usr/bin/lipo "$binary" -verify_arch "$architecture" || exit "$?" + done + exit 0 +fi + +exec /usr/bin/lipo "$@" \ No newline at end of file diff --git a/pubspec.lock b/pubspec.lock index b21dace..07ed797 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -798,7 +798,7 @@ packages: source: hosted version: "1.0.1" web_socket_channel: - dependency: transitive + dependency: "direct main" description: name: web_socket_channel sha256: d645757fb0f4773d602444000a8131ff5d48c9e47adfe9772652dd1a4f2d45c8 diff --git a/pubspec.yaml b/pubspec.yaml index aba8f78..05dc402 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -10,6 +10,7 @@ dependencies: flutter: sdk: flutter http: ^1.2.0 + web_socket_channel: ^3.0.3 flutter_riverpod: ^2.5.1 riverpod_annotation: ^2.3.5 shared_preferences: ^2.2.3 diff --git a/test/busylight_live_status_test.dart b/test/busylight_live_status_test.dart new file mode 100644 index 0000000..d6e250a --- /dev/null +++ b/test/busylight_live_status_test.dart @@ -0,0 +1,183 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:busylight_buddy/models/busylight_color.dart'; +import 'package:busylight_buddy/models/busylight_status.dart'; +import 'package:busylight_buddy/providers/busylight_provider.dart'; +import 'package:busylight_buddy/services/busylight_service.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +class FakeBusylightService extends BusylightService { + FakeBusylightService() : super(baseUrl: 'http://localhost'); + + final updates = StreamController.broadcast(); + int connections = 0; + int statusRequests = 0; + int colorRequests = 0; + + @override + Stream watchStatus() { + connections++; + return updates.stream; + } + + @override + Future getStatus() async { + statusRequests++; + return BusylightStatus.off; + } + + @override + Future getColor() async { + colorRequests++; + return BusylightColor.white; + } + + @override + Future setStatus(BusylightStatus status) async => status; +} + +Future waitUntil(bool Function() condition) async { + final deadline = DateTime.now().add(const Duration(seconds: 3)); + while (!condition()) { + if (DateTime.now().isAfter(deadline)) fail('Condition was not reached'); + await Future.delayed(const Duration(milliseconds: 5)); + } +} + +const update = BusylightUpdate( + status: BusylightStatus.colored, + color: BusylightColor(r: 12, g: 34, b: 56, brightness: 0.7), +); + +void main() { + test('decodes initial and subsequent messages from /ws/status', () async { + final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); + final sockets = []; + addTearDown(() async { + for (final socket in sockets) { + await socket.close(); + } + await server.close(force: true); + }); + server.listen((request) async { + expect(request.uri.path, '/ws/status'); + final socket = await WebSocketTransformer.upgrade(request); + sockets.add(socket); + socket.add(jsonEncode({ + 'status': 'available', + 'color': [0, 255, 0], + 'brightness': 0.3, + })); + socket.add(utf8.encode(jsonEncode({ + 'status': 'colored', + 'color': [12, 34, 56], + 'brightness': 0.7, + }))); + await socket.close(); + }); + + final service = BusylightService( + baseUrl: 'http://127.0.0.1:${server.port}', + ); + final messages = await service.watchStatus().toList(); + expect(messages.map((message) => message.status), + [BusylightStatus.available, BusylightStatus.colored]); + expect(messages.last.color.r, 12); + expect(messages.last.color.g, 34); + expect(messages.last.color.b, 56); + expect(messages.last.color.brightness, 0.7); + }); + + test('live updates initialize without REST and reconnect after errors', + () async { + final service = FakeBusylightService(); + final container = ProviderContainer(overrides: [ + busylightServiceProvider.overrideWithValue(service), + busylightSnapshotProvider.overrideWith((ref) => LiveStatusNotifier( + ref.watch(busylightServiceProvider), + reconnectDelay: const Duration(milliseconds: 5), + )), + ]); + addTearDown(() async { + container.dispose(); + await service.updates.close(); + }); + expect(container.read(busylightStatusProvider).isLoading, isTrue); + await waitUntil(() => service.updates.hasListener); + service.updates.add(update); + await waitUntil(() => container.read(brightnessProvider) == 0.7); + expect(container.read(busylightStatusProvider).value, update.status); + expect(container.read(colorProvider).r, 12); + expect(container.read(colorProvider).g, 34); + expect(container.read(colorProvider).b, 56); + + service.updates.addError(StateError('Disconnected')); + await waitUntil(() => service.connections == 2); + service.updates.add(const BusylightUpdate( + status: BusylightStatus.busy, + color: BusylightColor.red, + )); + await waitUntil(() => + container.read(busylightStatusProvider).value == BusylightStatus.busy); + expect(service.statusRequests, 0); + expect(service.colorRequests, 0); + }); + + test('socket closure retains the last state without REST polling', () async { + final service = FakeBusylightService(); + final container = ProviderContainer(overrides: [ + busylightServiceProvider.overrideWithValue(service), + ]); + addTearDown(container.dispose); + container.read(busylightSnapshotProvider); + await waitUntil(() => service.updates.hasListener); + service.updates.add(update); + await waitUntil(() => container.read(brightnessProvider) == 0.7); + await service.updates.close(); + await waitUntil(() => container.read(busylightSnapshotProvider).hasError); + expect(container.read(busylightStatusProvider).value, update.status); + expect(container.read(brightnessProvider), 0.7); + expect(service.statusRequests, 0); + expect(service.colorRequests, 0); + }); + + test('changing the device cancels the old subscription', () async { + final first = FakeBusylightService(); + final second = FakeBusylightService(); + final container = ProviderContainer(overrides: [ + deviceHostProvider.overrideWith((ref) => 'first'), + busylightServiceProvider.overrideWith((ref) => + ref.watch(deviceHostProvider) == 'first' ? first : second), + ]); + addTearDown(() async { + container.dispose(); + await first.updates.close(); + await second.updates.close(); + }); + final subscription = container.listen(busylightSnapshotProvider, (_, next) {}); + addTearDown(subscription.close); + await waitUntil(() => first.updates.hasListener); + container.read(deviceHostProvider.notifier).state = 'second'; + await waitUntil(() => second.updates.hasListener); + expect(first.updates.hasListener, isFalse); + second.updates.add(update); + await waitUntil(() => container.read(brightnessProvider) == 0.7); + container.dispose(); + expect(second.updates.hasListener, isFalse); + }); + + test('a stale command response cannot overwrite a pushed status', () async { + final notifier = BusylightStateNotifier( + FakeBusylightService(), + BusylightStatus.off, + ); + addTearDown(notifier.dispose); + final command = notifier.setStatus(BusylightStatus.available); + notifier.setLocalStatus(BusylightStatus.busy); + await command; + expect(notifier.state.value, BusylightStatus.busy); + }); +} \ No newline at end of file diff --git a/test/widget_test.dart b/test/widget_test.dart index b773878..425436c 100644 --- a/test/widget_test.dart +++ b/test/widget_test.dart @@ -1,14 +1,64 @@ +import 'dart:async'; + +import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:busylight_buddy/main.dart'; +import 'package:busylight_buddy/models/busylight_color.dart'; +import 'package:busylight_buddy/models/busylight_status.dart'; +import 'package:busylight_buddy/providers/busylight_provider.dart'; +import 'package:busylight_buddy/services/busylight_service.dart'; +import 'package:busylight_buddy/widgets/brightness_slider.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +class _WidgetBusylightService extends BusylightService { + _WidgetBusylightService() : super(baseUrl: 'http://localhost'); + + final updates = StreamController(); + + @override + Future getStatus() async => BusylightStatus.off; + + @override + Future getColor() async => BusylightColor.white; + + @override + Stream watchStatus() => updates.stream; +} void main() { - testWidgets('App smoke test — renders without crashing', (WidgetTester tester) async { + testWidgets('App renders pushed status and brightness', (WidgetTester tester) async { + SharedPreferences.setMockInitialValues({}); + final service = _WidgetBusylightService(); + addTearDown(service.updates.close); await tester.pumpWidget( - const ProviderScope( - child: BusylightApp(), + ProviderScope( + overrides: [ + busylightServiceProvider.overrideWithValue(service), + ], + child: const BusylightApp(), ), ); expect(find.text('BusyLight'), findsOneWidget); + service.updates.add(const BusylightUpdate( + status: BusylightStatus.off, + color: BusylightColor.white, + )); + await tester.pumpAndSettle(); + expect(find.text('OFF'), findsOneWidget); + + service.updates.add(const BusylightUpdate( + status: BusylightStatus.busy, + color: BusylightColor(r: 255, g: 0, b: 0, brightness: 0.7), + )); + await tester.pumpAndSettle(); + expect(find.text('BUSY'), findsOneWidget); + await tester.scrollUntilVisible( + find.byType(BrightnessSlider), + 300, + scrollable: find.byType(Scrollable).first, + ); + expect(tester.widget(find.byType(BrightnessSlider)).value, + 0.7); }); } \ No newline at end of file