|
| 1 | +import asyncio |
| 2 | +import csv |
| 3 | +import enapter |
| 4 | +import functools |
| 5 | +import glob |
| 6 | +from datetime import datetime |
| 7 | + |
| 8 | + |
| 9 | +def parse_timestamp(date_str, time_str): |
| 10 | + """ |
| 11 | + Combine date and time strings into a UNIX timestamp (int), or return None if parsing fails. |
| 12 | + """ |
| 13 | + if date_str and time_str: |
| 14 | + try: |
| 15 | + dt_str = f"{date_str} {time_str}" |
| 16 | + date = datetime.strptime(dt_str, "%d/%m/%Y %H:%M:%S") |
| 17 | + return int(date.timestamp()) |
| 18 | + except Exception as e: |
| 19 | + print(f"Failed to parse timestamp: {e}") |
| 20 | + return None |
| 21 | + return None |
| 22 | + |
| 23 | + |
| 24 | +async def main(): |
| 25 | + csv_files = sorted(glob.glob("*.csv")) |
| 26 | + device_factory = functools.partial(CSVBackup, csv_files=csv_files) |
| 27 | + await enapter.vucm.run(device_factory) |
| 28 | + |
| 29 | + |
| 30 | +class CSVBackup(enapter.vucm.Device): |
| 31 | + def __init__(self, csv_files, **kwargs): |
| 32 | + super().__init__(**kwargs) |
| 33 | + self.csv_files = csv_files |
| 34 | + |
| 35 | + async def task_send_csv_telemetry(self): |
| 36 | + """ |
| 37 | + Read CSV file line by line, send each row as telemetry every second. |
| 38 | + """ |
| 39 | + while True: |
| 40 | + for f in self.csv_files: |
| 41 | + try: |
| 42 | + with open(f, newline="") as csv_file: |
| 43 | + reader = csv.DictReader(csv_file) |
| 44 | + headers = reader.fieldnames or [] |
| 45 | + for row in reader: |
| 46 | + telemetry = {} |
| 47 | + telemetry["status"] = "ok" |
| 48 | + for key in headers: |
| 49 | + if key in ("Date", "Time"): |
| 50 | + continue |
| 51 | + value = row.get(key) |
| 52 | + telemetry[key] = value if value != "" else None |
| 53 | + await self.log.info(f" {key}: {telemetry[key]}") |
| 54 | + telemetry["timestamp"] = parse_timestamp( |
| 55 | + row.get("Date"), row.get("Time") |
| 56 | + ) |
| 57 | + await self.send_telemetry(telemetry) |
| 58 | + await asyncio.sleep(1) |
| 59 | + except Exception as e: |
| 60 | + await self.log.error(f"Failed to read CSV: {e}") |
| 61 | + await asyncio.sleep(5) |
| 62 | + |
| 63 | + |
| 64 | +if __name__ == "__main__": |
| 65 | + asyncio.run(main()) |
0 commit comments