import re from serial import Serial parameters = { 'acvoltsin': (1, '01 V In +([0-9]+[.]?[0-9]*)'), 'acvoltsout': (2, '02 V Out +([0-9]+[.]?[0-9]*)'), 'vaout': (5, '05 VA Out +([0-9]+[.]?[0-9]*)'), 'vbattery': (7, '07 V Batt +([0-9]+[.]?[0-9]*)'), 'frequency': (8, '08 Freq ([0-9]+[.]?[0-9]*) Hz'), 'fullload': (16, '16 FullLoad% ([0-9]+[.]?[0-9]*)'), 'watts': (17, '17 Watts +([0-9]+[.]?[0-9]*)'), 'powerfactor': (18, '18 PF +([0-9]+[.]?[0-9]*) ----'), 'crestfactor': (19, '19 CrestF +([0-9]+[.]?[0-9]*)'), 'powerout': (20, '20 #PwrOut +([0-9]+[.]?[0-9]*)'), 'inverterminutes': (23, '23 InvMin +([0-9]+[.]?[0-9]*)') } class UsvSerialHandler(object): def __init__(self, device_path): """ Handles the serial connection to the usv """ self._serial_port = Serial(device_path, baudrate=600, timeout=0.8) # force clean prompt self._serial_port.write('\r') self._serial_port.read(100) def request(self, index): """ Write and read until prompt """ self._serial_port.write('d {}\r'.format(index)) return self._serial_port.read(21) class Usv(UsvSerialHandler): def __init__(self, device_path): super().__init__(device_path) def read(self): fields = {} for name, (index, regex) in parameters.items(): result = self.request(index) match = re.search(regex, result, re.MULTILINE) if match: value = float(match.group(1)) fields[name] = value return fields