Add websocket support

This commit is contained in:
iGoX committed 2026-10-16 19:12:16 +02:00
1 parent ce0579b672
commit 88f41081be
16 files changed
+1042 -168

No files matched your search

+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);