From 1492144e8562b11c638105e53c6f025767d8f821 Mon Sep 17 00:00:00 2001 From: Alfredo Dal'Ava Junior Date: Tue, 18 May 2021 03:00:04 -0300 Subject: [PATCH] add generic TelemetryServer class --- RMS/TelemetryServer.py | 50 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 RMS/TelemetryServer.py diff --git a/RMS/TelemetryServer.py b/RMS/TelemetryServer.py new file mode 100644 index 000000000..d538daffd --- /dev/null +++ b/RMS/TelemetryServer.py @@ -0,0 +1,50 @@ +""" Generic Telemetry web service """ + +from http.server import BaseHTTPRequestHandler, HTTPServer, ThreadingHTTPServer +import json +from socketserver import BaseRequestHandler +import time +import threading +from typing import Callable, Tuple + +class TelemetryServer(ThreadingHTTPServer): + data = {} + + def __init__(self, ip, port): + super().__init__((ip, port), TelemetryHandler) + + + def set_data(self, data_obj): + self.data = data_obj + + def run(self): + server_thread = threading.Thread(target=self.serve_forever) + server_thread.daemon_threads = True + server_thread.start() + +class TelemetryHandler(BaseHTTPRequestHandler): + + def do_GET(self): + self.send_response(200) + self.send_header('Content-type', 'application/json') + self.end_headers() + + self.wfile.write(bytes(json.dumps(self.server.data), "utf-8")) + self.wfile.flush() + + +if __name__ == "__main__": + server = TelemetryServer('127.0.0.1', 5000) + server.run() + + print("server started") + server.set_data({'hello': 'world', 'received': 'ok'}) + + + input("Press any key to terminate the program") + server.set_data({'hello': 'world', 'received': 'err'}) + input("Press any key to terminate the program") + + server.shutdown() + print("Server stopped.") +