work on data dispatcher

This commit is contained in:
DJ2LS 2024-01-20 13:52:35 +01:00
parent cd1a37ddbe
commit a31fce3301
3 changed files with 88 additions and 1 deletions

View file

@ -5,6 +5,8 @@ from modem_frametypes import FRAME_TYPE
from codec2 import FREEDV_MODE from codec2 import FREEDV_MODE
from enum import Enum from enum import Enum
import time import time
from data_dispatcher import DataDispatcher
class IRS_State(Enum): class IRS_State(Enum):
NEW = 0 NEW = 0
OPEN_ACK_SENT = 1 OPEN_ACK_SENT = 1
@ -191,7 +193,7 @@ class ARQSessionIRS(arq_session.ARQSession):
self.set_state(IRS_State.ENDED) self.set_state(IRS_State.ENDED)
self.event_manager.send_arq_session_finished( self.event_manager.send_arq_session_finished(
False, self.id, self.dxcall, True, self.state.name, data=self.received_data, statistics=self.calculate_session_statistics()) False, self.id, self.dxcall, True, self.state.name, data=self.received_data, statistics=self.calculate_session_statistics())
DataDispatcher().dispatch(self.received_data)
else: else:
ack = self.frame_factory.build_arq_burst_ack(self.id, ack = self.frame_factory.build_arq_burst_ack(self.id,

52
modem/data_dispatcher.py Normal file
View file

@ -0,0 +1,52 @@
import json
import structlog
class DataDispatcher:
def __init__(self):
self.logger = structlog.get_logger(type(self).__name__)
# Hardcoded endpoints
self.endpoints = {
"p2pmsg": self.handle_p2pmsg,
"test": self.handle_test,
}
self.default_handler = self.handle_raw # Default handler for unrecognized types
def log(self, message, isWarning = False):
msg = f"[{type(self).__name__}]: {message}"
logger = self.logger.warn if isWarning else self.logger.info
logger(msg)
def encapsulate(self, data, type_key="p2pmsg"):
"""Encapsulate data into the specified format with the given type key."""
formatted_data = {type_key: data}
return json.dumps(formatted_data)
def decapsulate(self, byte_data):
"""Decapsulate data from the specified format, returning both the data and the type."""
try:
json_data = byte_data.decode('utf-8') # Decode byte array to string
parsed_data = json.loads(json_data)
if parsed_data and isinstance(parsed_data, dict):
for key, value in parsed_data.items():
return key, value # Return type and data
return "raw", byte_data # Treat as raw data if no matching type is found
except (json.JSONDecodeError, UnicodeDecodeError):
return "raw", byte_data # Return original data as raw if there's an error
def dispatch(self, byte_data):
"""Decapsulate and dispatch data to the appropriate endpoint based on its type."""
type_key, data = self.decapsulate(byte_data)
if type_key in self.endpoints:
self.endpoints[type_key](data)
else:
# Use the default handler for unrecognized types
self.default_handler(data)
def handle_p2pmsg(self, data):
self.log(f"Handling p2pmsg: {data}")
def handle_raw(self, data):
self.log(f"Handling raw data: {data}")
def handle_test(self, data):
self.log(f"Handling test data: {data}")

View file

@ -0,0 +1,33 @@
import sys
sys.path.append('modem')
import unittest
from data_dispatcher import DataDispatcher
class TestDispatcher(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.data_dispatcher = DataDispatcher()
def testEncapsulator(self):
message_type = "p2pmsg"
message_data = {"message": "Hello, P2P World!"}
encapsulated = self.data_dispatcher.encapsulate(message_data, message_type)
type, decapsulated = self.data_dispatcher.decapsulate(encapsulated.encode('utf-8'))
self.assertEqual(type, message_type)
self.assertEqual(decapsulated, message_data)
def testDispatcher(self):
message_type = "test"
message_data = {"message": "Hello, P2P World!"}
encapsulated = self.data_dispatcher.encapsulate(message_data, message_type)
self.data_dispatcher.dispatch(encapsulated.encode('utf-8'))
if __name__ == '__main__':
unittest.main()