network state is saved across app reboots
This commit is contained in:
parent
952d725639
commit
0b17c76fae
22
juice.py
22
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
|
||||
|
||||
|
||||
|
|
Loading…
Reference in New Issue
Block a user