From 0b17c76faefc224b96c0bce85777a706af9ae1e6 Mon Sep 17 00:00:00 2001 From: iou1name Date: Sat, 8 Jun 2019 03:56:30 -0400 Subject: [PATCH] network state is saved across app reboots --- juice.py | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/juice.py b/juice.py index 30980ed..0852125 100644 --- a/juice.py +++ b/juice.py @@ -3,6 +3,7 @@ A hub for controlling IOT devices. """ import re +import copy import json import requests @@ -92,11 +93,19 @@ class RelayOutlet: return self -def init_network(): +class DeviceEncoder(json.JSONEncoder): + """ + A custom json encoder for dumping devices to file. + """ + def default(self, o): + return vars(o) + + +def init_network(filepath="devices.json"): """ Initializes the network of IOT devices. """ - with open("devices.json", 'r') as file: + with open(filepath, 'r') as file: data = file.read() data = json.loads(data) network = {} @@ -111,6 +120,14 @@ def init_network(): return network +def save_network(filepath="devices.json"): + """ + Dumps the network to file. + """ + with open(filepath, 'w') as file: + file.write(json.dumps(network, cls=DeviceEncoder, indent='\t')) + + app = Flask(__name__) network = init_network() @@ -138,6 +155,7 @@ def toggle(): res = device.toggle(sub_dev_id) if not res: abort(404) + save_network() return res