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 devices; static Future> 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 categories = []; print("debug print"); print(response.body); final Map>> json = jsonDecode(response.body); for (MapEntry>> category_entry in json.entries) { final Category category = Category(category_entry.key); for (List 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 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: [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); }