added new_devices()

This commit is contained in:
iou1name 2019-06-20 07:49:29 -04:00
parent 1f0078446d
commit ded3593a2f
3 changed files with 58 additions and 0 deletions

View File

@ -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.

View File

@ -30,6 +30,7 @@ nav span:hover {
#devices {
padding: 5%;
display: flex;
flex-wrap: wrap;
justify-content: center;
}

View File

@ -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);
});
}