measuringLoop.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import time
  2. import csv
  3. from threading import Thread
  4. class MeasuringLoop(Thread):
  5. def __init__(self, ser, event_voltage, event_current, filename):
  6. super().__init__()
  7. self.ser = ser
  8. self.event_voltage = event_voltage
  9. self.event_current = event_current
  10. self.do = True
  11. self.filename_log = filename.replace('log_', 'logParam_')
  12. self.filename_log = self.filename_log.replace('txt', 'csv')
  13. self.log_parameters = open(self.filename_log, 'w', encoding='UTF8', newline='')
  14. fieldnames = ['time [s]', 'measured voltage [V]', 'measured current [A]']
  15. self.writer = csv.writer(self.log_parameters)
  16. self.writer.writerow(fieldnames)
  17. def run(self):
  18. self.setDo(True)
  19. start_time = time.time()
  20. while self.do:
  21. volts = bytearray(self.ser.measureVoltage()).decode()
  22. volts = volts.replace('\n', '')
  23. ampers = bytearray(self.ser.measureCurrent()).decode()
  24. ampers = ampers.replace('\n', '')
  25. self.event_voltage.on_change(volts)
  26. self.event_current.on_change(ampers)
  27. self.writer.writerow([time.time() - start_time, volts, ampers])
  28. self.event_voltage.on_change("0000")
  29. self.event_current.on_change("0000")
  30. self.log_parameters.close()
  31. def setDo(self, flag):
  32. self.do = flag