-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathrestserver.py
237 lines (183 loc) · 6.37 KB
/
restserver.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
from flask import Flask, request
from ph4_walkingpad import pad
from ph4_walkingpad.pad import WalkingPad, Controller
from ph4_walkingpad.utils import setup_logging
import asyncio
import yaml
import psycopg2
from datetime import date
app = Flask(__name__)
# minimal_cmd_space does not exist in the version we use from pip, thus we define it here.
# This should be removed once we can take it from the controller
minimal_cmd_space = 0.69
log = setup_logging()
pad.logger = log
ctler = Controller()
last_status = {
"steps": None,
"distance": None,
"time": None
}
def on_new_status(sender, record):
distance_in_km = record.dist / 100
print("Received Record:")
print('Distance: {0}km'.format(distance_in_km))
print('Time: {0} seconds'.format(record.time))
print('Steps: {0}'.format(record.steps))
last_status['steps'] = record.steps
last_status['distance'] = distance_in_km
last_status['time'] = record.time
def store_in_db(steps, distance_in_km, duration_in_seconds):
db_config = load_config()['database']
if not db_config['host']:
return
try:
conn = psycopg2.connect(host=db_config['host'], port=db_config['port'],
dbname=db_config['dbname'], user=db_config['user'], password=db_config['password'])
cur = conn.cursor()
date_today = date.today().strftime("%Y-%m-%d")
duration = int(duration_in_seconds / 60)
cur.execute("INSERT INTO exercise VALUES ('{0}', {1}, {2}, {3})".format(
date_today, steps, duration, distance_in_km))
conn.commit()
finally:
cur.close()
conn.close()
def load_config():
with open("config.yaml", 'r') as stream:
try:
return yaml.safe_load(stream)
except yaml.YAMLError as exc:
print(exc)
def save_config(config):
with open('config.yaml', 'w') as outfile:
yaml.dump(config, outfile, default_flow_style=False)
async def connect():
address = load_config()['address']
print("Connecting to {0}".format(address))
await ctler.run(address)
await asyncio.sleep(minimal_cmd_space)
async def disconnect():
await ctler.disconnect()
await asyncio.sleep(minimal_cmd_space)
@app.route("/config/address", methods=['GET'])
def get_config_address():
config = load_config()
return str(config['address']), 200
@app.route("/config/address", methods=['POST'])
def set_config_address():
address = request.args.get('address')
config = load_config()
config['address'] = address
save_config(config)
return get_config_address()
@app.route("/mode", methods=['GET'])
async def get_pad_mode():
try:
await connect()
await ctler.ask_stats()
await asyncio.sleep(minimal_cmd_space)
stats = ctler.last_status
mode = stats.manual_mode
if (mode == WalkingPad.MODE_STANDBY):
return "standby"
elif (mode == WalkingPad.MODE_MANUAL):
return "manual"
elif (mode == WalkingPad.MODE_AUTOMAT):
return "auto"
else:
return "Mode {0} not supported".format(mode), 400
finally:
await disconnect()
return "Error", 500
@app.route("/mode", methods=['POST'])
async def change_pad_mode():
new_mode = request.args.get('new_mode')
print("Got mode {0}".format(new_mode))
if (new_mode.lower() == "standby"):
pad_mode = WalkingPad.MODE_STANDBY
elif (new_mode.lower() == "manual"):
pad_mode = WalkingPad.MODE_MANUAL
elif (new_mode.lower() == "auto"):
pad_mode = WalkingPad.MODE_AUTOMAT
else:
return "Mode {0} not supported".format(new_mode), 400
try:
await connect()
await ctler.switch_mode(pad_mode)
await asyncio.sleep(minimal_cmd_space)
finally:
await disconnect()
return new_mode
@app.route("/status", methods=['GET'])
async def get_status():
try:
await connect()
await ctler.ask_stats()
await asyncio.sleep(minimal_cmd_space)
stats = ctler.last_status
mode = stats.manual_mode
belt_state = stats.belt_state
if (mode == WalkingPad.MODE_STANDBY):
mode = "standby"
elif (mode == WalkingPad.MODE_MANUAL):
mode = "manual"
elif (mode == WalkingPad.MODE_AUTOMAT):
mode = "auto"
if (belt_state == 5):
belt_state = "standby"
elif (belt_state == 0):
belt_state = "idle"
elif (belt_state == 1):
belt_state = "running"
elif (belt_state >=7):
belt_state = "starting"
dist = stats.dist / 100
time = stats.time
steps = stats.steps
speed = stats.speed / 10
return { "dist": dist, "time": time, "steps": steps, "speed": speed, "belt_state": belt_state }
finally:
await disconnect()
@app.route("/history", methods=['GET'])
async def get_history():
try:
await connect()
await ctler.ask_hist(0)
await asyncio.sleep(minimal_cmd_space)
finally:
await disconnect()
return last_status
@app.route("/save", methods=['POST'])
def save():
store_in_db(last_status['steps'], last_status['distance'], last_status['time'])
@app.route("/startwalk", methods=['POST'])
async def start_walk():
try:
await connect()
await ctler.switch_mode(WalkingPad.MODE_STANDBY) # Ensure we start from a known state, since start_belt is actually toggle_belt
await asyncio.sleep(minimal_cmd_space)
await ctler.switch_mode(WalkingPad.MODE_MANUAL)
await asyncio.sleep(minimal_cmd_space)
await ctler.start_belt()
await asyncio.sleep(minimal_cmd_space)
await ctler.ask_hist(0)
await asyncio.sleep(minimal_cmd_space)
finally:
await disconnect()
return last_status
@app.route("/finishwalk", methods=['POST'])
async def finish_walk():
try:
await connect()
await ctler.switch_mode(WalkingPad.MODE_STANDBY)
await asyncio.sleep(minimal_cmd_space)
await ctler.ask_hist(0)
await asyncio.sleep(minimal_cmd_space)
store_in_db(last_status['steps'], last_status['distance'], last_status['time'])
finally:
await disconnect()
return last_status
ctler.handler_last_status = on_new_status
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=5678, processes=1, threaded=False)