-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
62 lines (50 loc) · 1.66 KB
/
api.py
File metadata and controls
62 lines (50 loc) · 1.66 KB
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
#!/usr/bin/env python3
from flask import Flask, request, g, jsonify
import time
import sqlite3
import json
import re
RF_QUEUE_FOLDER = '/data/queue'
DATABASE = '/data/biactrl.db'
app = Flask(__name__)
def row_to_dict(cursor: sqlite3.Cursor, row: sqlite3.Row) -> dict:
data = {}
for idx, col in enumerate(cursor.description):
data[col[0]] = row[idx]
return data
def get_db():
db = getattr(g, '_database', None)
if db is None:
db = g._database = sqlite3.connect(DATABASE, isolation_level=None)
db.row_factory = row_to_dict
return db
def paramcheck(param):
if param is not None and re.match(r'[\w\-_]+', param):
return True
return False
@app.route('/api/devices', methods = ['GET'])
def get_devices():
result = get_db().execute('SELECT * FROM devices')
devices = { 'devices' : result.fetchall() }
return jsonify(devices)
@app.route('/api/biactrl', methods = ['POST'])
def hass_device_control():
xtype = request.form.get('type')
device = request.form.get('device')
cmd = request.form.get('cmd')
tstamp = int(time.time())
if not all([paramcheck(x) for x in [xtype, device, cmd]]):
return '', 400
data = { 'type': xtype, 'device': device, 'cmd': cmd, 'time': tstamp }
json_object = json.dumps(data)
filename = "{}/{}_{}_{}.json".format(RF_QUEUE_FOLDER, tstamp, xtype, device)
with open(filename, "w") as outfile:
outfile.write(json_object)
return '', 200
@app.teardown_appcontext
def close_connection(exception):
db = getattr(g, '_database', None)
if db is not None:
db.close()
if __name__ == '__main__':
app.run(host="0.0.0.0", debug=True)