-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
248 lines (204 loc) · 6.45 KB
/
api.py
File metadata and controls
248 lines (204 loc) · 6.45 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
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
238
239
240
241
242
243
244
245
246
247
248
"""
API methods implementation
This file contains every method called by the API defined in v2.yml
"""
import os
import subprocess
import json
import connexion
from tinydb import TinyDB, Query
from tinydb.operations import delete
from tinydb_appengine.storages import EphemeralJSONStorage
from cachetools import cached, TTLCache
from coderbot import CoderBot
from program import ProgramEngine, Program
from config import Config
BUTTON_PIN = 16
bot_config = Config.get()
bot = CoderBot.get_instance(
motor_trim_factor=float(bot_config.get("move_motor_trim", 1.0)),
encoder=bool(bot_config.get("encoder"))
)
query = Query()
def get_serial():
"""
Extract serial from cpuinfo file
"""
cpuserial = "0000000000000000"
try:
f = open('/proc/cpuinfo', 'r')
for line in f:
if line[0:6] == 'Serial':
cpuserial = line[10:26]
f.close()
except Exception:
cpuserial = "ERROR000000000"
return cpuserial
@cached(cache=TTLCache(maxsize=1, ttl=10))
def get_status():
"""
Expose CoderBot status:
temperature, uptime, and internet connectivity status.
(Cached method)
"""
try:
temp = "20.0°"
except Exception:
temp = "undefined"
uptime = "0 days"
internet_status = "online"
return {'internet_status': internet_status,
'temp': temp,
'uptime': uptime}
@cached(cache=TTLCache(maxsize=1, ttl=60))
def get_info():
"""
Expose informations about the CoderBot system.
(Cached method)
"""
try:
# manifest.json is generated while building/copying the backend
with open('manifest.json', 'r') as f:
metadata = json.load(f)
backend_commit = metadata["backendCommit"][0:7]
except Exception:
backend_commit = "undefined"
try:
coderbot_version = subprocess.check_output(["cat", "/etc/coderbot/version"]).decode('utf-8').replace('\n', '')
except Exception:
coderbot_version = 'undefined'
try:
kernel = subprocess.check_output(["uname", "-r"]).decode('utf-8').replace('\n', '')
except Exception:
kernel = 'undefined'
try:
update_status = subprocess.check_output(["cat", "/etc/coderbot/update_status"]).decode('utf-8').replace('\n', '')
except Exception:
update_status = 'undefined'
try:
encoder = bool(Config.read().get('encoder'))
if(encoder):
motors = 'DC encoder motors'
else:
motors = 'DC motors'
except Exception:
motors = 'undefined'
serial = get_serial()
return {'backend_commit': backend_commit,
'coderbot_version': coderbot_version,
'update_status': update_status,
'kernel': kernel,
'serial': serial,
'motors': motors}
prog = None
prog_engine = ProgramEngine.get_instance()
# Programs and Activities databases
activities = TinyDB("data/activities.json", storage=EphemeralJSONStorage)
## Robot control
def stop():
bot.stop()
return 200
def move(data):
bot.move(speed=data["speed"], elapse=data["elapse"], distance=data["distance"])
return 200
def turn(data):
bot.turn(speed=data["speed"], time_elapse=data["elapse"])
return 200
def exec(data):
program = prog_engine.create(data["name"], data["code"])
return json.dumps(program.execute())
## System
def status():
sts = get_status()
# getting reset log file
try:
with open('/home/pi/coderbot/logs/reset_trigger_service.log', 'r') as log_file:
data = [x for x in log_file.read().split('\n') if x]
except Exception:
data = [] # if file doesn't exist, no restore as ever been performed. return empty data
return {
"status": "ok",
"internetConnectivity": sts["internet_status"],
"temp": sts["temp"],
"uptime": sts["uptime"],
"log": data
}
def info():
inf = get_info()
return {
"model": 1,
"version": inf["coderbot_version"],
"backend commit build": inf["backend_commit"],
"kernel" : inf["kernel"],
"update status": inf["update_status"],
"serial": inf["serial"],
"motors": inf["motors"]
}
def restoreSettings():
with open("data/defaults/config.json") as f:
Config.write(json.loads(f.read()))
Config.get()
return "ok"
def updateFromPackage():
os.system('sudo bash /home/pi/clean-update.sh')
file_to_upload = connexion.request.files['file_to_upload']
file_to_upload.save(os.path.join('/home/pi/', 'update.tar'))
os.system('sudo reboot')
return 200
## Programs
def saveProgram(data, overwrite):
existing_program = prog_engine.load(data["name"])
if existing_program and not overwrite:
return "askOverwrite"
elif existing_program and existing_program.is_default() == True:
return "defaultOverwrite"
program = Program(name=data["name"], code=data["code"], dom_code=data["dom_code"])
prog_engine.save(program)
return 200
def loadProgram(name):
existing_program = prog_engine.load(name)
return existing_program.as_dict(), 200
def deleteProgram(data):
prog_engine.delete(data["name"])
def listPrograms():
return prog_engine.prog_list()
## Activities
def saveActivity(data):
data = data["activity"]
if activities.search(query.name == data["name"]) == []:
activities.insert(data)
return 200
else:
activities.update(data, query.name == data["name"])
return 200
def loadActivity(name):
return activities.search(query.name == name)[0], 200
def deleteActivity(data):
activities.remove(query.name == data["name"])
def listActivities():
return activities.all()
def resetDefaultPrograms():
"""
Delete everything but the default programs
"""
programs.purge()
for filename in os.listdir("data/defaults/programs/"):
if filename.endswith(".json"):
with open("data/defaults/programs/" + filename) as p:
q = p.read()
programs.insert(json.loads(q))
## Reset
def reset():
pi = pigpio.pi('localhost')
#simulating FALLING EDGE
# it triggers the reset by using the service altready running on the system that detects a button press (3 sec).
pi.write(BUTTON_PIN, 1)
pi.write(BUTTON_PIN, 0)
return {
"status": "ok"
}
## Test
def testCoderbot(data):
# taking first JSON key value (varargin)
tests_state = runCoderbotTestUnit(data[list(data.keys())[0]])
return tests_state