This repository has been archived by the owner on Sep 17, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http_api.py
87 lines (73 loc) · 2.43 KB
/
http_api.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
79
80
81
82
83
84
85
86
'''
HTTP API for providing ruuvitag sensor readings
Endpoint: http://0.0.0.0:5000/ruuvitag
Requires:
bottle
ruuvitag_sensor
'''
import sys, json, time, threading, datetime
from bottle import get, response, request, run
from ruuvitag_sensor.ruuvitag import RuuviTag
from tag.tag import load_tag_configuration, format_tags_data
# borrowed from https://ongspxm.github.io/blog/2017/02/bottlepy-cors/
def enable_cors(func):
def wrapper(*args, **kwargs):
response.set_header("Access-Control-Allow-Origin", "*")
response.set_header("Content-Type", "application/json")
response.set_header("Access-Control-Allow-Methods", "GET, OPTIONS")
response.set_header("Access-Control-Allow-Headers", "Access-Control-Allow-Origin, Content-Type")
# skip the function if it is not needed
if request.method == 'OPTIONS':
return
return func(*args, **kwargs)
return wrapper
configuredTags = dict()
cachedData = []
nextRun = time.time()
def read_data():
global cachedData
allData = []
try:
for mac in configuredTags.keys():
sensor = RuuviTag(mac)
sensor.update()
tagData = sensor.state
tagData['name'] = configuredTags[mac]
allData.append(tagData)
except:
sys.exit(1)
cachedData.clear()
return allData
def cache_data():
print('[{}] Refreshing cache'.format(datetime.datetime.now()))
global cachedData
global cacheTimer
global nextRun
cachePeriodSeconds = 30
cachedData = read_data()
nextRun = nextRun + cachePeriodSeconds
intervalInSeconds = nextRun - time.time()
cacheTimer = threading.Timer(intervalInSeconds, cache_data)
cacheTimer.start()
cacheTimer = threading.Timer(0, cache_data)
@get('/ruuvitag')
@enable_cors
def ruuvitag_data():
response.content_type = 'application/json; charset=UTF-8'
return format_tags_data(cachedData)
if __name__ == '__main__':
# First argument is this python file itself
if (len(sys.argv) < 2):
print('Program needs a tag configuration file as parameter, e.g.: python http_api.py tags.json')
sys.exit(0)
global configuredTags
configurationFile = sys.argv[1]
configuredTags = load_tag_configuration(configurationFile)
cacheTimer.start()
try:
run(host='0.0.0.0', port=5000, debug=True)
except:
sys.exit(1)
finally:
print('Exiting...')
cacheTimer.cancel()