diff --git a/juice.py b/juice.py index f175db6..ee0dc92 100644 --- a/juice.py +++ b/juice.py @@ -28,6 +28,14 @@ class RelayDevice: self.location = "" self.ip_address = "" self.sub_devices = [] + self.sub_devices.append(RelayOutlet()) + self.sub_devices.append(RelayOutlet()) + self.sub_devices[0].id = 'GPIO0' + self.sub_devices[0].type = 'RelayOutlet' + self.sub_devices[0].gpio = '0' + self.sub_devices[1].id = 'GPIO2' + self.sub_devices[1].type = 'RelayOutlet' + self.sub_devices[1].gpio = '2' self.update() @@ -36,6 +44,8 @@ class RelayDevice: Queries the physical device and updates the internal model as appropriate. """ + if not self.ip_address: + return for sub_dev in self.sub_devices: res = requests.get(self.ip_address) gpio0 = re.search(r"GPIO0: (\bLow|\bHigh)", res.text).groups()[0] @@ -211,6 +221,36 @@ def edit(): return json.dumps(data) +@app_views.route('/new_device') +def new_device(): + """ + Allows adding a new device. Accepts device_type parameter, returns + the device_id. + """ + device_type = request.args.get('device_type') + + if device_type == 'RelayDevice': + device = RelayDevice() + else: + return make_error(400, "Unknown device type") + + devices = [dev for dev in network if dev.type == device_type] + devices.sort(key=lambda dev: dev.type) + if not devices: + device.id = device_type + '01' + else: + num = re.search(r'(\d*)$', devices[-1].id).groups() + if not num: + device.id = device_type + '01' + else: + num = str(int(num[0]) + 1).zfill(2) + device.id = device_type + num + network.append(device) + save_network() + data = {'device_id': device.id} + return json.dumps(data) + + def make_error(code, message): """ Returns a JSON error. diff --git a/static/juice.css b/static/juice.css index 9fdb417..3904420 100644 --- a/static/juice.css +++ b/static/juice.css @@ -30,6 +30,7 @@ nav span:hover { #devices { padding: 5%; display: flex; + flex-wrap: wrap; justify-content: center; } diff --git a/static/juice.js b/static/juice.js index a89f260..c07fc32 100644 --- a/static/juice.js +++ b/static/juice.js @@ -98,3 +98,20 @@ function save_field(field) { field.children[1].replaceWith(edit); }); } + +function new_device() { + let params = { + device_type: 'RelayDevice', + }; + let query = Object.keys(params) + .map(k => encodeURIComponent(k) + '=' + encodeURIComponent(params[k])) + .join('&'); + + fetch(window.location.href + 'new_device?' + query) + .then(function(response) { + return response.json(); + }) + .then(function(json) { + console.log(json); + }); +}