-
Notifications
You must be signed in to change notification settings - Fork 0
/
qdotweb_rpi.py
78 lines (68 loc) · 2.26 KB
/
qdotweb_rpi.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
from flask import Flask, render_template, request
from datetime import datetime
import device
from device import Device
import socket
import json
from collections import OrderedDict
if socket.gethostname().find('.')>=0:
hostname=socket.gethostname()
else:
hostname=socket.gethostbyaddr(socket.gethostname())[0]
hostname = hostname.split('.')[0]
app = Flask(__name__)
devices = []
def format_devices_table(devlist):
""" put devices list into HTML table """
table = '<table border="1" cellpadding="5" cellspacing="5">'
table += '<caption>List of available resources:</caption>'
table += '<tr> <th>Device(s)</th> </tr>'
for i in devlist:
table += '<tr> <td>{}</td> </tr>'.format(i)
table += '</table>'
return table
@app.route('/')
def index():
resource_table = format_devices_table(device.DEVICE_NAMES)
current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
return render_template('index.html', resource_table = resource_table, hostname = hostname, current_time = current_time)
@app.route("/read", methods=['POST', 'GET'])
def query():
data = ''
errors = ''
device = ''
command = ''
try:
if request.method == 'POST':
post = request.form
if post['device']:
device = post['device']
else:
raise ValueError('You did not send a device')
if post['command']:
command=request.form['command']
else:
raise ValueError('You did not send a command')
else:
raise ValueError('Please POST a device and command')
data = device_read(device, command)
except Exception as e:
errors = str(e)
output = OrderedDict([('device', device), ('command', command), ('data', data), ('errors', errors)])
return json.dumps(output)
def device_read(device_name, cmd):
global devices
count=0
for i in devices:
if devices[count].getName() == device_name:
data = devices[count].getData(cmd)
count+=1
return data
def init_devices():
global devices
device_names = device.DEVICE_NAMES
for i in device_names:
devices.append(Device(i))
if __name__ == "__main__":
init_devices()
app.run(host= ('0.0.0.0'), threaded=True)