DeaD_EyE

sockets test

Oct 7th, 2020
930
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import socket
  2. import struct
  3. from datetime import datetime
  4.  
  5. TOPICS = (
  6.     "id",
  7.     "row",
  8.     "cycle",
  9.     "capacity",
  10.     "error",
  11.     "voltage",
  12.     "current",
  13.     "charge",
  14.     "temperature",
  15.     "timestamp",
  16. )
  17. ST = struct.Struct("<5i9f")
  18. BROADCAST = "255.255.255.255"
  19. PORT = 2020
  20. ADDR = (BROADCAST, PORT)
  21.  
  22.  
  23. print("Size:", ST.size)
  24.  
  25. with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
  26.     sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
  27.     sock.bind(ADDR)
  28.     while data := sock.recvfrom(ST.size):
  29.         msg, (ip, port) = data
  30.         size = len(msg)
  31.         if size != ST.size:
  32.             continue
  33.         result = dict(zip(TOPICS, (ST.unpack(msg))))
  34.         try:
  35.             result["timestamp"] = datetime.fromtimestamp(result["timestamp"])
  36.         except ArithmeticError:
  37.             pass
  38.         print(result)
  39.  
RAW Paste Data