common.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. from threading import Thread
  2. from queue import Queue
  3. import time
  4. import struct
  5. from structures.measurement import *
  6. class Input:
  7. _t = None
  8. _stop = False
  9. _q = Queue()
  10. interval = 1
  11. _read_cb = None
  12. def __init__(self, read_cb) -> None:
  13. self._read_cb = read_cb
  14. def start(self):
  15. if not self._t:
  16. self._stop = False
  17. self._t = Thread(target = self._main)
  18. self._t.setDaemon(True)
  19. self._t.start()
  20. def stop(self):
  21. if self._t:
  22. self._stop = True
  23. self._t.join()
  24. self._t = None
  25. def read(self):
  26. while not self._q.empty():
  27. yield self._q.get()
  28. def _main(self):
  29. start_time = time.monotonic()
  30. while not self._stop:
  31. self._read_cb()
  32. end_time = time.monotonic()
  33. remaining = self.interval + start_time - end_time
  34. start_time = end_time
  35. if remaining > 0:
  36. time.sleep(remaining)
  37. def queue_ifm_from_bytes(self, source, timestamp, raw, channels = 16):
  38. data = struct.unpack(">" + "B" * 16 + "HHHHHBxH", raw)
  39. current = tuple([x / 10 for x in data[0:channels]])
  40. status = tuple([data[16] & (1 << i) > 0 for i in range(channels)])
  41. overload = tuple([data[17] & (1 << i) > 0 for i in range(channels)])
  42. short_circuit = tuple([data[18] & (1 << i) > 0 for i in range(channels)])
  43. limit = tuple([data[19] & (1 << i) > 0 for i in range(channels)])
  44. pushbutton = tuple([data[20] & (1 << i) > 0 for i in range(channels)])
  45. voltage = data[22] / 100
  46. self._q.put(Measurement24v(timestamp, source, current, status, overload, short_circuit, limit, pushbutton, voltage))
  47. def queue_energy_meter_from_bytes(self, source, timestamp, raw):
  48. data = struct.unpack(">" + "f" * 9, raw)
  49. voltage = tuple(data[0:3])
  50. current = tuple(data[3:6])
  51. phase = tuple(data[6:9])
  52. self._q.put(Measurement480v(timestamp, source, voltage, current, phase))