snap7_connect.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. from snap7.client import Client
  2. import time
  3. from datetime import datetime
  4. import struct
  5. from structures.measurement import Measurement24v
  6. from inputs.common import Input
  7. localtz = datetime.now().astimezone().tzinfo
  8. class SiemensCPU(Input):
  9. cpu_start_time = None
  10. cpu_last_time = None
  11. local_start_time = time.time()
  12. db = 1
  13. interval = 0.05
  14. cpu_db_value_count = 50
  15. def __init__(self) -> None:
  16. super().__init__(self.read_handler)
  17. self.cpu = Client()
  18. def start(self):
  19. self.cpu.connect("192.168.10.6", 0, 0)
  20. super().start()
  21. def read_handler(self):
  22. raw = self.cpu.db_read(self.db, 0, (self.cpu_db_value_count + 1)*4)
  23. data = struct.unpack(">" + "i" * (self.cpu_db_value_count + 1), raw)
  24. cpu_time = data[0] / 1000
  25. if not self.cpu_last_time:
  26. self.cpu_last_time = cpu_time - self.interval
  27. if cpu_time == self.cpu_last_time:
  28. return
  29. inc_time = (cpu_time - self.cpu_last_time) / self.cpu_db_value_count
  30. for i, val in enumerate(data[1:]):
  31. timestamp = self.get_timestamp(self.cpu_last_time + inc_time * (i+1))
  32. self._q.put(Measurement(timestamp, "S7", "24v_current", 0, val / 10))
  33. self.cpu_last_time = cpu_time
  34. def get_timestamp(self, cpu_time):
  35. if not self.cpu_start_time:
  36. self.synchronize()
  37. cpu_diff = cpu_time - self.cpu_start_time
  38. date = datetime.fromtimestamp(self.local_start_time + cpu_diff, localtz)
  39. return date
  40. def synchronize(self, duration = 3):
  41. start = time.monotonic()
  42. self.cpu_last_time = None
  43. intervals = []
  44. while time.monotonic() - start < duration:
  45. cpu_time = self.get_ints(0, 1)[0] / 1000
  46. if cpu_time != self.cpu_last_time:
  47. self.cpu_start_time = cpu_time
  48. self.local_start_time = time.time()
  49. if self.cpu_last_time:
  50. intervals.append(cpu_time - self.cpu_last_time)
  51. self.cpu_last_time = cpu_time
  52. time.sleep(0.05)
  53. if len(intervals) > 0:
  54. self.interval = sum(intervals) / len(intervals)
  55. return self.interval