feat: split camera worker and tick worker

This commit is contained in:
2020-08-28 13:39:21 +02:00
parent 955ceb9977
commit 44cb97b44e
2 changed files with 29 additions and 10 deletions

71
tickworker.py Normal file
View File

@@ -0,0 +1,71 @@
import sched
import time
from threading import Thread
import json
from redis import Redis
from control.walle import WallE
INTERVAL_TICK = 0.0125 # 20/s
class EventListener(Thread):
def __init__(self):
super(EventListener, self).__init__()
self.keep_running = True
self.dbcon = Redis()
self.pubsub = self.dbcon.pubsub()
self.pubsub.subscribe(['move', 'look'])
def run(self) -> None:
while self.keep_running:
item = self.pubsub.get_message()
if not item:
time.sleep(0.01)
continue
channel = item['channel'].decode()
data = item['data']
if not isinstance(data, bytes):
print(f"Channel {channel} got message that is not bytes {data}")
continue
try:
self.handle_message(channel, data)
except ValueError:
pass # todo
self.pubsub.close()
def stop(self):
self.keep_running = False
def handle_message(self, channel: str, data: bytes):
data_dict = json.loads(data.decode())
if channel == 'move':
walle.set_movement(data_dict['angle'], data_dict['force'])
elif channel == 'look':
walle.set_eye_velocity(data_dict['angle'], data_dict['force'])
else:
print(f'Unknown channel {channel}')
scheduler = sched.scheduler()
walle = WallE()
walle.setup()
def walle_tick():
scheduler.enter(INTERVAL_TICK, 1, walle_tick)
walle.tick()
scheduler.enter(INTERVAL_TICK, 1, walle_tick)
if __name__ == '__main__':
redisdb = Redis()
event_listener = EventListener()
event_listener.start()
try:
scheduler.run()
except KeyboardInterrupt:
event_listener.stop()
raise