3lips/event/event.py

169 lines
4.5 KiB
Python
Raw Normal View History

2024-02-11 02:27:20 +00:00
"""
@file event.py
@brief Event loop for 3lips.
@author 30hours
"""
2024-02-09 00:41:51 +00:00
import asyncio
import requests
import threading
2024-02-09 14:47:13 +00:00
import asyncio
import time
2024-02-10 04:19:08 +00:00
import copy
import json
2024-02-11 02:27:20 +00:00
import hashlib
2024-02-09 00:41:51 +00:00
from algorithm.associator.AdsbAssociator import AdsbAssociator
2024-02-19 09:27:05 +00:00
from algorithm.coordreg.EllipsoidParametric import EllipsoidParametric
2024-02-09 14:47:13 +00:00
from common.Message import Message
# init event loop
api = []
2024-02-10 04:19:08 +00:00
# init config
tDelete = 60
2024-02-11 02:27:20 +00:00
adsbAssociator = AdsbAssociator()
2024-02-19 09:27:05 +00:00
ellipsoidParametric = EllipsoidParametric()
2024-02-09 00:41:51 +00:00
async def event():
2024-02-09 14:47:13 +00:00
2024-02-10 04:19:08 +00:00
global api
2024-02-09 14:47:13 +00:00
timestamp = int(time.time()*1000)
2024-02-10 04:19:08 +00:00
api_event = copy.copy(api)
2024-02-11 02:27:20 +00:00
# list all blah2 radars
radar_names = []
for item in api_event:
for radar in item["server"]:
radar_names.append(radar)
radar_names = list(set(radar_names))
# get detections all radar
radar_detections_url = [
"http://" + radar_name + "/api/detection" for radar_name in radar_names]
radar_detections = []
for url in radar_detections_url:
try:
response = requests.get(url, timeout=1)
response.raise_for_status()
data = response.json()
radar_detections.append(data)
except requests.exceptions.RequestException as e:
print(f"Error fetching data from {url}: {e}")
radar_detections.append(None)
# get config all radar
radar_config_url = [
"http://" + radar_name + "/api/config" for radar_name in radar_names]
radar_config = []
for url in radar_config_url:
try:
response = requests.get(url, timeout=1)
response.raise_for_status()
data = response.json()
radar_config.append(data)
except requests.exceptions.RequestException as e:
print(f"Error fetching data from {url}: {e}")
radar_config.append(None)
# store detections in dict
radar_dict = {}
for i in range(len(radar_names)):
radar_dict[radar_names[i]] = {
"detection": radar_detections[i],
"config": radar_config[i]
}
# main processing
2024-02-10 04:19:08 +00:00
for item in api_event:
2024-02-11 07:23:30 +00:00
# extract dict for item
radar_dict_item = {
key: radar_dict[key]
for key in item["server"]
if key in radar_dict
}
# associator selection
if item["associator"] == "adsb-associator":
associator = adsbAssociator
else:
print("Error: Associator invalid.")
return
# coord reg selection
2024-02-19 09:27:05 +00:00
if item["coordreg"] == "ellipsoid-parametric":
coordreg = ellipsoidParametric
else:
print("Error: Coord reg invalid.")
return
2024-02-19 05:19:23 +00:00
# processing
2024-02-11 07:23:30 +00:00
associated_dets = associator.process(item["server"], radar_dict_item)
2024-02-19 05:19:23 +00:00
localised_dets = coordreg.process(associated_dets, radar_dict_item)
# output data to API
item["detections_associated"] = associated_dets
item["detections_localised"] = localised_dets
2024-02-10 04:19:08 +00:00
# delete old API requests
api_event = [
item for item in api_event if timestamp - item["timestamp"] <= tDelete*1000]
2024-02-10 04:19:08 +00:00
# update API
api = api_event
# event loop
2024-02-09 00:41:51 +00:00
async def main():
2024-02-09 00:41:51 +00:00
while True:
await event()
await asyncio.sleep(1)
2024-02-11 02:27:20 +00:00
def short_hash(input_string, length=10):
hash_object = hashlib.sha256(input_string.encode())
short_hash = hash_object.hexdigest()[:length]
return short_hash
2024-02-09 14:47:13 +00:00
# message received callback
2024-02-10 02:18:08 +00:00
async def callback_message_received(msg):
2024-02-10 04:19:08 +00:00
2024-02-10 02:18:08 +00:00
print(f"Callback: Received message in event.py: {msg}", flush=True)
2024-02-10 04:19:08 +00:00
2024-02-10 02:18:08 +00:00
timestamp = int(time.time()*1000)
2024-02-10 04:19:08 +00:00
2024-02-11 02:27:20 +00:00
# update timestamp if API entry exists
2024-02-10 04:19:08 +00:00
for x in api:
2024-02-11 02:27:20 +00:00
if x["hash"] == short_hash(msg):
2024-02-10 04:19:08 +00:00
x["timestamp"] = timestamp
break
2024-02-11 02:27:20 +00:00
# add API entry if does not exist, split URL
if not any(x.get("hash") == short_hash(msg) for x in api):
2024-02-10 04:19:08 +00:00
api.append({})
2024-02-11 02:27:20 +00:00
api[-1]["hash"] = short_hash(msg)
url_parts = msg.split("&")
for part in url_parts:
key, value = part.split("=")
if key in api[-1]:
if not isinstance(api[-1][key], list):
api[-1][key] = [api[-1][key]]
api[-1][key].append(value)
else:
api[-1][key] = value
2024-02-10 04:19:08 +00:00
api[-1]["timestamp"] = timestamp
# json dump
output = json.dumps(api)
return output
2024-02-09 14:47:13 +00:00
# init messaging
2024-02-10 02:18:08 +00:00
message_api_request = Message('event', 6969)
message_api_request.set_callback_message_received(callback_message_received)
2024-02-09 00:41:51 +00:00
if __name__ == "__main__":
2024-02-10 02:18:08 +00:00
threading.Thread(target=message_api_request.start_listener).start()
2024-02-09 00:41:51 +00:00
asyncio.run(main())