|
| 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 | +async def main(): |
| 12 | + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: |
| 13 | + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True) |
| 14 | + sock.bind(("127.0.0.1", int(os.environ["LISTEN_TCP_PORT"]))) |
| 15 | + sock.listen() |
| 16 | + sock.setblocking(False) |
| 17 | + device_factory = functools.partial(NIDAQ, socket=sock) |
| 18 | + await enapter.vucm.run(device_factory) |
| 19 | + |
| 20 | + |
| 21 | +class NIDAQ(enapter.vucm.Device): |
| 22 | + def __init__(self, socket, **kwargs): |
| 23 | + super().__init__(**kwargs) |
| 24 | + self.socket = socket |
| 25 | + |
| 26 | + async def task_accept_conns(self): |
| 27 | + sock = self.socket |
| 28 | + while True: |
| 29 | + (conn, addr) = await asyncio.get_event_loop().sock_accept(sock) |
| 30 | + asyncio.create_task(self.handle_conn(conn, addr)) |
| 31 | + |
| 32 | + async def handle_conn(self, conn, addr): |
| 33 | + print(addr, "accept") |
| 34 | + data = bytearray() |
| 35 | + try: |
| 36 | + while True: |
| 37 | + try: |
| 38 | + async with asyncio.timeout(5): |
| 39 | + chunk = await asyncio.get_event_loop().sock_recv(conn, 1024) |
| 40 | + except TimeoutError: |
| 41 | + print(addr, "timeout") |
| 42 | + return |
| 43 | + if chunk: |
| 44 | + print(addr, "read chunk: ", chunk) |
| 45 | + data.extend(chunk) |
| 46 | + continue |
| 47 | + print(addr, "read data: ", data) |
| 48 | + await self._process_and_send_telemetry(data) |
| 49 | + return |
| 50 | + finally: |
| 51 | + print(addr, "close") |
| 52 | + conn.close() |
| 53 | + |
| 54 | + async def task_properties_sender(self): |
| 55 | + """Periodically send device properties.""" |
| 56 | + while True: |
| 57 | + await self.send_properties( |
| 58 | + {"vendor": "National Instruments", "model": "cDAQ 9178"} |
| 59 | + ) |
| 60 | + await asyncio.sleep(10) |
| 61 | + |
| 62 | + async def _process_and_send_telemetry(self, data): |
| 63 | + """Parse, enrich, and send telemetry data.""" |
| 64 | + telemetry = {} |
| 65 | + status = "no_data" |
| 66 | + try: |
| 67 | + if data: |
| 68 | + status = "ok" |
| 69 | + telemetry = json.loads(data.decode()) |
| 70 | + self._add_timestamp_if_present(telemetry) |
| 71 | + telemetry["status"] = status |
| 72 | + await self.send_telemetry(telemetry) |
| 73 | + self.alerts.clear() |
| 74 | + except Exception as e: |
| 75 | + self.alerts.add("parse_error") |
| 76 | + await self.log.error(f"Failed to process data: {e}") |
| 77 | + |
| 78 | + def _add_timestamp_if_present(self, telemetry): |
| 79 | + """If 'Date' and 'Time' are present, combine and convert to timestamp.""" |
| 80 | + date_str = telemetry.get("Date") |
| 81 | + time_str = telemetry.get("Time") |
| 82 | + if date_str and time_str: |
| 83 | + dt_str = f"{date_str} {time_str}" |
| 84 | + date = datetime.strptime(dt_str, "%d/%m/%Y %H:%M:%S") |
| 85 | + telemetry.pop("Date") |
| 86 | + telemetry.pop("Time") |
| 87 | + telemetry["timestamp"] = int(date.timestamp()) |
| 88 | + |
| 89 | + |
| 90 | +if __name__ == "__main__": |
| 91 | + asyncio.run(main()) |
0 commit comments