wip: separate clock and rest into separate apps.

This commit is contained in:
Remy Moll
2021-06-18 16:57:20 +02:00
parent 93fb257d2d
commit ffc903b8f2
25 changed files with 580 additions and 257 deletions

1
broadcast/__init__.py Normal file
View File

@@ -0,0 +1 @@
# Placeholder

65
broadcast/b_in.py Normal file
View File

@@ -0,0 +1,65 @@
import requests
import logging
logger = logging.getLogger(__name__)
class FetchUpdates:
"""Fetches updates from the main server and relays them to the clock"""
def __init__(self, server_ip, port):
"""Both methods return a list as python-object. This should be then converted to a numpy array."""
# self.server_ip = server_ip
self.base_url = server_ip + ":" + port
# self.modules gets added through the caller
self.update_calls = 0
self.last_fetch = {}
def get_updates(self):
update_url = "http://" + self.base_url + "/getupdates"
result = self.call_api(update_url)
return result
def get_last(self):
update_url = "http://" + self.base_url + "/getlast"
result = self.call_api(update_url)
return result
def fetch_data(self):
if self.update_calls == 0:
fetch = self.get_last()
else:
fetch = self.get_updates()
if not fetch["is_new"]:
fetch = self.last_fetch
else:
self.last_fetch = fetch
try:
data = fetch["data"]
has_queue = fetch["has_queue"]
except:
data = {}
has_queue = False
self.update_calls += 1
return has_queue, data
def call_api(self, url):
ret = {}
try:
result = requests.get(url)
result = result.json()
if result.pop("status") == "ok":
ret = result
except:
logger.error("Bad api call for method {}.".format(url[:url.rfind("/")]))
return ret

78
broadcast/b_out.py Normal file
View File

@@ -0,0 +1,78 @@
import flask
from flask import request, jsonify
import numpy as np
from threading import Thread
class BroadcastUpdates:
"""Broadcasts (out) updates for the hw-handler to be fetched periodically"""
def __init__(self, port):
""""""
self.last_show = ""
self.queue = [] #[{"matrices" : [np.full((16,16,3), 10).tolist(), np.full((16,16,3), 100).tolist(), np.full((16,16,3), 200).tolist()]} for _ in range(4)]
self.port = port
def start(self):
t = Thread(target=self.run)
t.start()
def run(self):
app = flask.Flask(__name__)
@app.route('/getupdates', methods=['GET'])
def get_updates():
return self.get_updates()
@app.route('/getlast', methods=['GET'])
def get_last():
return self.get_last()
app.run('0.0.0.0', port=self.port)
def get_updates(self):
try:
data = self.queue.pop(0)
self.last_show = data
is_new = True
has_queue = len(self.queue) > 0
except:
data = ""
is_new = False
has_queue = False
return self.generate_response(
is_new = is_new,
data = data,
has_queue = has_queue
)
def get_last(self):
try:
try:
data = self.queue[-1]
self.queue = []
except: # list empty
data = self.last_show,
except:
data = ""
return self.generate_response(
data = data,
has_queue = False,
)
def generate_response(self, **kwargs):
ret = {
"status" : "ok",
**kwargs
}
print(ret)
return jsonify(ret)