Add websocket support (#13)

Reviewed-on: #13
This commit was merged in pull request #13.
This commit is contained in:
iGoX committed 2026-10-16 19:24:00 +02:00
1 parent ce0579b672
commit 26d200e282
16 files changed
+1042 -168

No files matched your search

+43 -81
View File
@@ -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>(
(_) => SharedPreferences.getInstance(),
@@ -21,11 +19,6 @@ final deviceHostProvider = StateProvider<String>((ref) {
return prefs?.getString(_kHostKey) ?? _kDefaultHost;
});
final pollIntervalProvider = StateProvider<double>((ref) {
final prefs = ref.watch(sharedPreferencesProvider).valueOrNull;
return prefs?.getDouble(_kPollIntervalKey) ?? _kDefaultPollInterval.toDouble();
});
// ── Service ──────────────────────────────────────────────────────────────────
final busylightServiceProvider = Provider<BusylightService>((ref) {
@@ -33,33 +26,10 @@ final busylightServiceProvider = Provider<BusylightService>((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<BusylightSnapshot>((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<LiveStatusNotifier, AsyncValue<BusylightUpdate>>(
(ref) => LiveStatusNotifier(ref.watch(busylightServiceProvider)),
);
// ── State notifiers ──────────────────────────────────────────────────────────
@@ -67,25 +37,21 @@ class BusylightStateNotifier extends StateNotifier<AsyncValue<BusylightStatus>>
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<void> refresh() async {
state = const AsyncValue.loading();
state = await AsyncValue.guard(_service.getStatus);
}
int _revision = 0;
Future<void> 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<BrightnessNotifier, double>(
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<ColorNotifier, BusylightColor>(
},
);
// ── Background polling ────────────────────────────────────────────────────────
// Periodically pulls status + color from the device and silently updates state.
class PollingNotifier extends StateNotifier<void> {
PollingNotifier(this._ref) : super(null) {
_start();
class LiveStatusNotifier extends StateNotifier<AsyncValue<BusylightUpdate>> {
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<BusylightUpdate>? _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<void> _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<BusylightUpdate>.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<PollingNotifier, void>(
(ref) => PollingNotifier(ref),
);
}
+1 -4
View File
@@ -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(),
),
-58
View File
@@ -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<SettingsScreen> {
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<SettingsScreen> {
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<SettingsScreen> {
}
}
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<SettingsScreen> {
),
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),
+41
View File
@@ -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<String, dynamic> json) {
final color = json['color'] as List<dynamic>;
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<BusylightUpdate> 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<int>);
yield BusylightUpdate.fromJson(
jsonDecode(text) as Map<String, dynamic>,
);
}
} finally {
await channel.sink.close();
}
}
Future<Map<String, dynamic>> _get(String path) async {
try {
final res = await http.get(_uri(path)).timeout(timeout);