Use correct fetch for plugs

This commit is contained in:
hodasemi 2023-10-06 09:15:17 +02:00
parent 5dbc860cc3
commit 34702024b0
2 changed files with 42 additions and 27 deletions

View file

@ -13,33 +13,47 @@ class Category {
static Future<List<Category>> fetch(String base_url) async {
final response = await http.get(Uri.parse("$base_url/devices"));
if (response.statusCode == 200) {
List<Category> categories = [];
Map<String, List<Map<String, dynamic>>> json = jsonDecode(response.body);
for (MapEntry<String, List<Map<String, dynamic>>> category_entry
in json.entries) {
Category category = Category(category_entry.key);
for (Map<String, dynamic> device_map in category_entry.value) {
Device device = Device(
device_map["device_id"],
device_map["device_descriptor"],
device_map["led"],
device_map["power"],
device_map["power_draw"]);
category.devices.add(device);
}
categories.add(category);
}
return categories;
} else {
if (response.statusCode != 200) {
throw Exception("Failed to fetch devices");
}
List<Category> categories = [];
Map<String, List<List<dynamic>>> json = jsonDecode(response.body);
for (MapEntry<String, List<List<dynamic>>> category_entry in json.entries) {
Category category = Category(category_entry.key);
for (List<dynamic> device_info in category_entry.value) {
String device_id = device_info[0];
String? device_descriptor = device_info[1];
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");
}
Map<String, dynamic> device_state = jsonDecode(response.body);
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;
}
}
@ -79,7 +93,8 @@ class Device {
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_state, this.power_draw, this.power_control);
}

View file

@ -63,7 +63,7 @@ class _MyHomePageState extends State<MyHomePage> {
future: Category.fetch("smart.gavania.de"),
builder: (context, AsyncSnapshot<List<Category>> categories) {
if (!categories.hasData) {
return const Scaffold();
throw Exception("categories not ready");
}
return Scaffold(