import serial #Using pyserial Library from serial import SerialException import serial.tools.list_ports import time #for loop timeout import serial.tools.list_ports import sys #for sys.exit in while True loop import logging as log log.basicConfig(level=log.INFO, format='%(asctime)s - %(levelname)s - %(message)s') def list_ports_matching_descr(dev_descr): ports_found = [] ports = serial.tools.list_ports.comports() for p in ports: log.info('Found device: %s, %s, %s', p.device, p.description, p.manufacturer) if dev_descr in str(p.manufacturer): ports_found.append(p.device) log.debug('Devices containing %s: %s', dev_descr, ports_found) return ports_found def initialize_port(port_name): try: ser = serial.Serial(port_name, 19200, timeout=10) log.debug('Port: %s', ser.name) except SerialException: print port_name sys.exit('Error: cannot open port, quitting...') return ser def Victron_HEX_call(ser, write_hex, expected_read): log.info('Sending %s to %s', write_hex, ser.name) timeout = time.time() + 3 #s of timeout while True: ser.write(write_hex) read_hex=ser.read_until('\n') #Reading until "\n" symbol if read_hex[0:len(expected_read)] == expected_read: #Exiting after receiving a correct answer log.info('Received HEX string: %s \n', read_hex) break elif time.time() > timeout: log.warning('Timeout reached, received HEX string: %s \n', read_hex) break return read_hex #Find Victron devices port_list = list_ports_matching_descr('Victron') #Identyfying Victron devices MPPT_port = [] BMV_port = [] for port in port_list: ser = initialize_port(port) read_hex = Victron_HEX_call(ser, ':451\n', ':1') ser.close() if read_hex[4:6] in ['A0', 'A1', '03']: #MPPT Product ID first byte MPPT_port.append(port) log.info('Found MPPT ID %s at port %s', read_hex[2:6], MPPT_port) if read_hex[4:6] in ['02', 'A3']: #BMV Product ID first byte BMV_port.append(port) log.info('Found BMV ID %s at port %s', read_hex[2:6], BMV_port) if not MPPT_port: log.critical('No MPPT port found, is the device connected and powered?') if not BMV_port: log.critical('No BMV port found, is the device connected and powered?') if (not MPPT_port) or (not BMV_port): sys.exit(log.critical('Quitting...'))