|
| 1 | +import asyncio |
| 2 | +import functools |
| 3 | +import json |
| 4 | +import os |
| 5 | +import socket |
| 6 | +from datetime import datetime |
| 7 | + |
| 8 | +import enapter |
| 9 | + |
| 10 | + |
| 11 | +def parse_json(data_bytes): |
| 12 | + """Decode bytes to JSON dict.""" |
| 13 | + return json.loads(data_bytes.decode()) |
| 14 | + |
| 15 | + |
| 16 | +class NIDAQ(enapter.vucm.Device): |
| 17 | + def __init__(self, socket, tcp_port, **kwargs): |
| 18 | + super().__init__(**kwargs) |
| 19 | + self.socket = socket |
| 20 | + self.tcp_port = int(tcp_port) |
| 21 | + |
| 22 | + async def task_properties_sender(self): |
| 23 | + """Periodically send device properties.""" |
| 24 | + while True: |
| 25 | + await self.send_properties( |
| 26 | + {"vendor": "National Instruments", "model": "cDAQ 9178"} |
| 27 | + ) |
| 28 | + await asyncio.sleep(10) |
| 29 | + |
| 30 | + async def task_telemetry_sender(self): |
| 31 | + """Accept connections and process telemetry data.""" |
| 32 | + self._setup_socket() |
| 33 | + while True: |
| 34 | + try: |
| 35 | + connection, addr = await asyncio.get_event_loop().sock_accept( |
| 36 | + self.socket |
| 37 | + ) |
| 38 | + await self._handle_connection(connection) |
| 39 | + except Exception as e: |
| 40 | + await self.log.error(f"Connection error: {e}") |
| 41 | + await asyncio.sleep(1) |
| 42 | + |
| 43 | + def _setup_socket(self): |
| 44 | + """Bind and configure the server socket.""" |
| 45 | + server_address = ("localhost", self.tcp_port) |
| 46 | + self.socket.bind(server_address) |
| 47 | + self.socket.setblocking(False) |
| 48 | + self.socket.listen(1) |
| 49 | + |
| 50 | + async def _handle_connection(self, connection): |
| 51 | + """Receive data from a single connection and process telemetry.""" |
| 52 | + data = await self._receive_data(connection) |
| 53 | + await self._process_and_send_telemetry(data) |
| 54 | + connection.close() |
| 55 | + |
| 56 | + async def _receive_data(self, connection): |
| 57 | + """Receive all data from the connection.""" |
| 58 | + data = bytearray() |
| 59 | + try: |
| 60 | + while True: |
| 61 | + received = await asyncio.get_event_loop().sock_recv(connection, 1024) |
| 62 | + if not received: |
| 63 | + break |
| 64 | + data.extend(received) |
| 65 | + except Exception as e: |
| 66 | + await self.log.error(f"Error receiving data: {e}") |
| 67 | + return data |
| 68 | + |
| 69 | + async def _process_and_send_telemetry(self, data): |
| 70 | + """Parse, enrich, and send telemetry data.""" |
| 71 | + telemetry = {} |
| 72 | + status = "no_data" |
| 73 | + try: |
| 74 | + if data: |
| 75 | + status = "ok" |
| 76 | + telemetry = parse_json(data) |
| 77 | + self._add_timestamp_if_present(telemetry) |
| 78 | + telemetry["status"] = status |
| 79 | + await self.send_telemetry(telemetry) |
| 80 | + self.alerts.clear() |
| 81 | + except Exception as e: |
| 82 | + self.alerts.add("parse_error") |
| 83 | + await self.log.error(f"Failed to process data: {e}") |
| 84 | + |
| 85 | + def _add_timestamp_if_present(self, telemetry): |
| 86 | + """If 'Date' and 'Time' are present, combine and convert to timestamp.""" |
| 87 | + date_str = telemetry.get("Date") |
| 88 | + time_str = telemetry.get("Time") |
| 89 | + if date_str and time_str: |
| 90 | + dt_str = f"{date_str} {time_str}" |
| 91 | + date = datetime.strptime(dt_str, "%d/%m/%Y %H:%M:%S") |
| 92 | + telemetry.pop("Date") |
| 93 | + telemetry.pop("Time") |
| 94 | + telemetry["timestamp"] = int(date.timestamp()) |
| 95 | + |
| 96 | + |
| 97 | +async def main(): |
| 98 | + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: |
| 99 | + device_factory = functools.partial( |
| 100 | + NIDAQ, |
| 101 | + socket=sock, |
| 102 | + tcp_port=os.environ["LISTEN_TCP_PORT"], |
| 103 | + ) |
| 104 | + await enapter.vucm.run(device_factory) |
| 105 | + |
| 106 | + |
| 107 | +if __name__ == "__main__": |
| 108 | + asyncio.run(main()) |
0 commit comments