HomeServer/frontend/lib/devices.dart
2023-10-09 20:12:34 +02:00

107 lines
2.8 KiB
Dart

import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class Category {
Category(this.name) : devices = [];
final String name;
List<Device> devices;
static Future<List<Category>> fetch(String base_url) async {
print("fetch: http://$base_url/devices");
final response = await http.get(Uri.parse("http://$base_url/devices"));
if (response.statusCode != 200) {
throw Exception("Failed to fetch devices");
}
final List<Category> categories = [];
print("debug print");
print(response.body);
final Map<String, List<List<dynamic>>> json = jsonDecode(response.body);
for (MapEntry<String, List<List<dynamic>>> category_entry in json.entries) {
final Category category = Category(category_entry.key);
for (List<dynamic> device_info in category_entry.value) {
final String device_id = device_info[0];
final String? device_descriptor = device_info[1];
final bool power_control = device_info[2];
final response =
await http.get(Uri.parse("$base_url/plug_state/$device_id"));
if (response.statusCode != 200) {
throw Exception("Failed to fetch plug_state for $device_id");
}
print(response.body);
final Map<String, dynamic> device_state = jsonDecode(response.body);
final Device device = Device(
device_id,
device_descriptor,
device_state["led"],
device_state["power"],
device_state["power_draw"],
power_control && device_state["power_draw"] < 15,
);
category.devices.add(device);
}
categories.add(category);
}
return categories;
}
}
class CategoryWidget extends StatelessWidget {
Category category;
CategoryWidget({super.key, required this.category});
@override
Widget build(BuildContext context) {
var list = category.devices
.map((device) => TableRow(children: [
Text(device.device_descriptor ?? device.device_id),
Text(device.led_state.toString()),
Text(device.power_state.toString()),
Text("${device.power_draw} W")
]))
.toList();
list.insert(
0,
const TableRow(children: [
Text("Name"),
Text("LED"),
Text("Power"),
Text("Power Draw"),
]));
return Column(
children: <Widget>[Text(category.name), Table(children: list)]);
}
}
class Device {
final String device_id;
String? device_descriptor;
bool led_state;
bool power_state;
double power_draw;
bool power_control;
Device(this.device_id, this.device_descriptor, this.led_state,
this.power_state, this.power_draw, this.power_control);
}