baseimage-tutorial-framework/lib/tfw/message_sender.py
2018-02-02 16:51:06 +01:00

25 lines
773 B
Python

import json
from datetime import datetime
from .networking.server_connector import ServerUplinkConnector
class MessageSender:
def __init__(self, custom_anchor=None):
self.server_connector = ServerUplinkConnector()
if isinstance(custom_anchor, bytes):
custom_anchor = custom_anchor.decode('utf-8')
self.anchor = custom_anchor or 'message'
def send(self, originator, message):
data = {
'originator': originator,
'timestamp': datetime.now().isoformat(),
'message': message
}
response = {
'anchor': self.anchor,
'data': data
}
self.server_connector.send(*[frame.encode('utf-8') for frame in (self.anchor, json.dumps(response))])