Skip to content

Commit f378bd4

Browse files
previRoberto Previtera
andauthored
Refactor api v3 (#167)
* wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * merge remove_old_ui * merge remove_old_ui * fix merge * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * WIP #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wop #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #184 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 * wip #164 Co-authored-by: Roberto Previtera <roberto@MacBook-Air.station>
1 parent cc4792a commit f378bd4

File tree

12 files changed

+119
-57
lines changed

12 files changed

+119
-57
lines changed

.github/workflows/build_backend.yml

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,19 +20,24 @@ jobs:
2020
#python3 -m unittest test/cnn_test.py 2>&1 | tee test-reports/test_report.txt
2121
echo "test complete"
2222
- run: |
23-
export PYTHONPATH=./coderbot:./stub:./test
23+
export PYTHONPATH=./stub:./coderbot:./test
2424
python3 coderbot/main.py > coderbot.log &
2525
sleep 30
2626
apt-get install -y python3-venv
2727
mkdir -p schemathesis
2828
python3 -m venv schemathesis
2929
. schemathesis/bin/activate
3030
pip install schemathesis
31-
st run --endpoint '^(?!(\/api\/v1\/video\/stream|\/api\/v1\/control\/move|\/api\/v1\/video\/rec|\/api\/v1\/video\/stop)$).*$' --hypothesis-max-examples=10 --request-timeout=20 http://localhost:5000/api/v1/openapi.json
31+
st run --endpoint 'activities' --hypothesis-max-examples=10 --request-timeout=20 http://localhost:5000/api/v1/openapi.json
32+
st run --endpoint 'media' --hypothesis-max-examples=10 --request-timeout=20 http://localhost:5000/api/v1/openapi.json
33+
st run --endpoint 'control/speak' --hypothesis-max-examples=10 --request-timeout=20 http://localhost:5000/api/v1/openapi.json
34+
st run --endpoint 'control/stop' --hypothesis-max-examples=10 --request-timeout=20 http://localhost:5000/api/v1/openapi.json
35+
st run --endpoint 'music' --hypothesis-max-examples=10 --request-timeout=20 http://localhost:5000/api/v1/openapi.json
36+
st run --endpoint 'programs' --hypothesis-max-examples=10 --request-timeout=20 http://localhost:5000/api/v1/openapi.json
3237
echo "openapi test complete"
3338
3439
release-backend:
35-
#needs: [test]
40+
needs: [test]
3641
runs-on: ubuntu-latest
3742
steps:
3843
- name: Docker meta

coderbot/activity.py

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,12 @@
11
from tinydb import TinyDB, Query
2-
from tinydb.operations import delete
3-
import json
42

53
# Programs and Activities databases
64
class Activities():
75
_instance = None
8-
6+
97
@classmethod
108
def get_instance(cls):
11-
if cls._instance == None:
9+
if cls._instance is None:
1210
cls._instance = Activities()
1311
return cls._instance
1412

@@ -22,15 +20,14 @@ def load(self, name, default):
2220
if len(activities) > 0:
2321
return activities[0]
2422
elif default is not None:
25-
default_Activities = self.activities.search(self.query.default == True)
2623
if len(self.activities.search(self.query.default == True)) > 0:
2724
return self.activities.search(self.query.default == True)[0]
28-
else:
29-
return None
25+
return None
26+
return None
3027

3128
def save(self, name, activity):
3229
# if saved activity is "default", reset existing default activity to "non-default"
33-
if activity.get("default", False) == True:
30+
if activity.get("default", False) is True:
3431
self.activities.update({'default': False})
3532
if self.activities.search(self.query.name == name) == []:
3633
self.activities.insert(activity)
@@ -41,10 +38,9 @@ def delete(self, name):
4138
activities = self.activities.search(self.query.name == name)
4239
if len(activities) > 0:
4340
activity = activities[0]
44-
if activity.get("default", False) == True:
41+
if activity.get("default", False) is True:
4542
self.activities.update({'default': True}, self.query.stock == True)
4643
self.activities.remove(self.query.name == activity["name"])
4744

4845
def list(self):
4946
return self.activities.all()
50-

coderbot/api.py

Lines changed: 27 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
from audio import Audio
2929
from event import EventManager
3030
from coderbotTestUnit import run_test as runCoderbotTestUnit
31+
from balena import Balena
3132

3233
BUTTON_PIN = 16
3334

@@ -95,7 +96,7 @@ def get_info():
9596
backend_commit = "undefined"
9697
coderbot_version = "undefined"
9798
update_status = "ok"
98-
kernel = 'undefined'
99+
device = {}
99100
motors = 'undefined'
100101

101102
try:
@@ -107,11 +108,6 @@ def get_info():
107108
except Exception:
108109
pass
109110

110-
try:
111-
kernel = subprocess.check_output(["uname", "-r"]).decode('utf-8').replace('\n', '')
112-
except Exception:
113-
pass
114-
115111
try:
116112
encoder = bool(Config.read().get('encoder'))
117113
if(encoder):
@@ -123,12 +119,16 @@ def get_info():
123119

124120
serial = get_serial()
125121

126-
return {'backend_commit': backend_commit,
127-
'coderbot_version': coderbot_version,
128-
'update_status': update_status,
129-
'kernel': kernel,
130-
'serial': serial,
131-
'motors': motors}
122+
try:
123+
device = Baleba.get_instance().device()
124+
except Exception:
125+
pass
126+
return { 'backend_commit': device.get("commit"),
127+
'coderbot_version': coderbot_version,
128+
'update_status': device.get("status"),
129+
'kernel': device.get("os_version"),
130+
'serial': serial,
131+
'motors': motors }
132132

133133
prog = None
134134
prog_engine = ProgramEngine.get_instance()
@@ -161,21 +161,24 @@ def turn(body):
161161
def takePhoto():
162162
try:
163163
cam.photo_take()
164-
Audio.say(config.get("sound_shutter"))
164+
audio_device.say(config.get("sound_shutter"))
165+
return 200
165166
except Exception as e:
166167
logging.warning("Error: %s", e)
167168

168169
def recVideo():
169170
try:
170171
cam.video_rec()
171172
audio_device.say(config.get("sound_shutter"))
173+
return 200
172174
except Exception as e:
173175
logging.warning("Error: %s", e)
174176

175177
def stopVideo():
176178
try:
177179
cam.video_stop()
178180
audio_device.say(config.get("sound_shutter"))
181+
return 200
179182
except Exception as e:
180183
logging.warning("Error: %s", e)
181184

@@ -184,24 +187,24 @@ def speak(body):
184187
locale = body.get("locale", "")
185188
logging.debug("say: " + text + " in: " + locale)
186189
audio_device.say(text, locale)
190+
return 200
187191

188192
def reset():
189-
logging.debug("reset bot")
190-
shutil.rmtree("data/*")
191-
bot.restart()
193+
Balena.get_instance().purge()
194+
return 200
192195

193196
def halt():
194-
logging.debug("shutting down")
195197
audio_device.say(what=config.get("sound_stop"))
196-
bot.halt()
198+
Balena.get_instance().shutdown()
199+
return 200
197200

198201
def restart():
199-
logging.debug("restarting bot")
200-
bot.restart()
202+
Balena.get_instance().restart()
201203

202204
def reboot():
203-
logging.debug("rebooting")
204-
bot.reboot()
205+
audio_device.say(what=config.get("sound_stop"))
206+
Balena.get_instance().reboot()
207+
return 200
205208

206209
def video_stream(a_cam):
207210
while True:
@@ -287,13 +290,14 @@ def info():
287290

288291
def restoreSettings():
289292
Config.restore()
290-
restart()
293+
return restart()
291294

292295
def loadSettings():
293296
return Config.get()
294297

295298
def saveSettings(body):
296299
Config.write(body)
300+
return 200
297301

298302
def updateFromPackage():
299303
os.system('sudo bash /home/pi/clean-update.sh')

coderbot/balena/__init__.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import os
2+
from urllib.request import urlopen, Request
3+
import json
4+
import logging
5+
6+
class Balena():
7+
_instance = None
8+
9+
@classmethod
10+
def get_instance(cls):
11+
if cls._instance is None:
12+
cls._instance = Balena()
13+
return cls._instance
14+
15+
def __init__(self):
16+
self.supervisor_address = os.environ["BALENA_SUPERVISOR_ADDRESS"]
17+
self.supervisor_key = os.environ["BALENA_SUPERVISOR_API_KEY"]
18+
self.app_id_data = json.dumps({ "appId": os.environ["BALENA_APP_ID"] }).encode("utf-8")
19+
self.headers = { 'Content-Type': 'application/json' }
20+
21+
def purge(self):
22+
logging.debug("reset bot")
23+
req = Request(f'{self.supervisor_address}/v1/purge?apikey={self.supervisor_key}', data=self.app_id_data, headers=self.headers, method='POST')
24+
return urlopen(req).read()
25+
26+
def shutdown(self):
27+
logging.debug("shutdown bot")
28+
req = Request(f'{self.supervisor_address}/v1/shutdown?apikey={self.supervisor_key}', headers=self.headers, method='POST')
29+
return urlopen(req).read()
30+
31+
def restart(self):
32+
logging.debug("restarting bot")
33+
req = Request(f'{self.supervisor_address}/v1/restart?apikey={self.supervisor_key}', data=self.app_id_data, headers=self.headers, method='POST')
34+
return urlopen(req).read()
35+
36+
def reboot(self):
37+
logging.debug("reboot bot")
38+
req = Request(f'{self.supervisor_address}/v1/reboot?apikey={self.supervisor_key}', headers=self.headers, method='POST')
39+
return urlopen(req).read()
40+
41+
def device(self):
42+
logging.debug("reboot bot", f'{self.supervisor_address}get?apikey={self.supervisor_key}')
43+
req = Request(f'{self.supervisor_address}/device?apikey={self.supervisor_key}', headers=self.headers, method='GET')
44+
return json.load(urlopen(req))

coderbot/coderbot.py

Lines changed: 1 addition & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
import logging
2424
import pigpio
2525
import sonar
26-
import hw.mpu
26+
from hw import mpu
2727
from rotary_encoder.wheelsaxel import WheelsAxel
2828

2929
# GPIO
@@ -268,13 +268,3 @@ def _cb_button(self, gpio, level, tick):
268268
logging.info("pushed: %d, %d", level, tick)
269269
cb()
270270

271-
def halt(self):
272-
logging.info("halt requested")
273-
pass
274-
275-
def restart(self):
276-
sys.exit()
277-
278-
def reboot(self):
279-
logging.info("reboot requested")
280-

coderbot/hw/__init__.py

Whitespace-only changes.

coderbot/hw/mpu.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from hw import lsm9ds1
1+
from . import lsm9ds1
22
import time
33

44
class AccelGyroMag:

coderbot/main.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,22 +5,19 @@
55
import os
66
import logging
77
import logging.handlers
8-
import subprocess
98
import picamera
109
import connexion
1110

12-
from flask import (send_from_directory, redirect)
13-
1411
from flask_cors import CORS
1512

16-
from coderbot import CoderBot
1713
from camera import Camera
1814
from motion import Motion
1915
from audio import Audio
20-
from program import ProgramEngine, Program
16+
from program import ProgramEngine
2117
from config import Config
2218
from cnn.cnn_manager import CNNManager
2319
from event import EventManager
20+
from coderbot import CoderBot
2421

2522
# Logging configuration
2623
logger = logging.getLogger()

coderbot/program.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@
3434
import event
3535
import music
3636
import musicPackages
37-
import hw.atmega328p
37+
from hw.atmega328p import ATMega328
3838

3939
PROGRAM_PATH = "./data/"
4040
PROGRAM_PREFIX = "program_"
@@ -66,7 +66,7 @@ def get_music():
6666
return music.Music.get_instance(musicPackageManager)
6767

6868
def get_atmega():
69-
return atmega328p.ATMega328.get_instance()
69+
return ATMega328.get_instance()
7070

7171
class ProgramEngine:
7272

defaults/config.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@
3838
"hw_version":"5",
3939
"audio_volume_level":"100",
4040
"wifi_mode":"ap",
41-
"wifi_ssid":"coderbot_CHANGEMEATFIRSTRUN",
41+
"wifi_ssid":"coderbot",
4242
"wifi_psk":"coderbot",
4343
"packages_installed":"",
4444
"admin_password":"",

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy