time_correlation.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import logging
  2. from datetime import timedelta
  3. from structures.correlated import CorrelatedMeasurements
  4. logger = logging.getLogger(__name__)
  5. class TimeCorrelation:
  6. def __init__(self, parent):
  7. self.state = {}
  8. self.timestamp = None
  9. self.old_values = []
  10. def execute(self, values: list):
  11. # combine new values with old values and sort them by timestamp and series
  12. values = sorted(self.old_values + values, key=lambda x: (x.timestamp, x.series))
  13. results = []
  14. # iterate over old values
  15. for i, measurement in enumerate(values[:len(self.old_values)]):
  16. self.state[type(measurement).__name__] = measurement
  17. if self.timestamp and self.timestamp > measurement.timestamp:
  18. logger.error(f"Timestamps are not in order: {measurement.series} is {self.timestamp - measurement.timestamp} to late")
  19. if len(values) > i+1 and values[i+1].timestamp == measurement.timestamp:
  20. continue
  21. self.timestamp = measurement.timestamp
  22. results.append(CorrelatedMeasurements(
  23. timestamp = measurement.timestamp,
  24. source = ','.join([x.source for x in self.state.values()]),
  25. measurement_24v = self.state.get("Measurement24v", None),
  26. measurement_480v = self.state.get("Measurement480v", None),
  27. measurement_plant = self.state.get("CompactLogixState", None) or self.state.get("S7State", None)
  28. ))
  29. # store new values for next iteration
  30. self.old_values = values[len(self.old_values):]
  31. return results