/
mock.py
66 lines (47 loc) · 1.77 KB
/
mock.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
import requests
import re
from Reading import Reading
import json
BASE_URL = "https://vitruvian.jakeryan.co.uk/api/"
# BASE_URL = "http://localhost:3000/api/"
# ----------------------------
# Fetch single reading
# ----------------------------
def fetchTestMpuReading(time, mpu_path):
return fetchRemoteServerReading(mpu_path + "?time=" + str(time))
def fetchLiveMpuReading(mpu_path):
return fetchRemoteServerReading(mpu_path)
def fetchRemoteServerReading(path):
r = requests.get(BASE_URL + path)
matches = re.findall(INPUT_REGEX, r.text)
if r.status_code == 200 and matches is not None and len(matches) == 1 and len(matches[0]) == 4:
[(timestamp, x, y, z)] = matches
return Reading({'x': float(x), 'y': float(y), 'z': float(z)}, fix=False)
else:
return Reading({'x': 0, 'y': 0, 'z': 0}, fix=False)
# ----------------------------
# Fetch single reading
# ----------------------------
def fetchLiveMpuReadings(path):
r = requests.get(BASE_URL + path)
if r.status_code == 200 and len(r.text) > 0:
data = json.loads(r.text)
data = list(map(lambda o: Reading(o['timestamp'], o['x'], o['y'], o['z']), data))
data.sort(key=lambda x: x.timestamp, reverse=True)
return data
else:
return []
# ----------------------------
# Post buffer file
# ----------------------------
def postToRemoteDatabase(key, buffer_file):
data = buffer_file
url = BASE_URL + "pi/" + key
try:
r = requests.post(url, data=data)
print('Received ' + str(r.status_code) + ' status code from remote database for POST')
print(r.text)
return r.text == data
except requests.exceptions.RequestException as e:
print("Error posting to remote database: " + str(e))
return False