from serial import Serial from math import inf import sys #import binascii def crap_to_number(num, unit, acdc, include_unit): number_str = "" if(num[0]&0x10): number_str+="-" num[0] &= 0xEF for elem in num: if(elem & 0x10 != 0): number_str+="." switch={ 0xcf:"9", 0xef:"8", 0x8a:"7", 0xe7:"6", 0xc7:"5", 0x4e:"4", 0x8f:"3", 0xad:"2", 0x0a:"1", 0xeb:"0", 0x61:"L", 0x00:" " } number_str+=switch.get(elem&0xEF, "-") if(include_unit): if (unit[0] & 0x1): number_str+="µ" if (unit[0] & 0x2): number_str+="n" if (unit[0] & 0x4): number_str+="k" if (unit[1] & 0x1): number_str+="m" if (unit[1] & 0x2): number_str+="%" if (unit[1] & 0x4): number_str+="M" if (unit[2] & 0x1): number_str+="F" if (unit[2] & 0x2): number_str+="Ω" if (unit[3] & 0x1): number_str+="A" if (unit[3] & 0x2): number_str+="V" if (unit[3] & 0x4): number_str+="Hz" if (unit[4] & 0x2): number_str+="°C" if (unit[4] & 0x1): number_str+="°F" if(acdc&0xb == 0x0a): number_str+=" DC" if(acdc&0xb == 0x09): number_str+=" AC" return number_str def read_peaktech(ser, include_unit=True): line = ser.read_until( b'\xf1' ) #print(binascii.hexlify(line)) good=1 if(len(line) == 15): for i in range(0, 0xf): if i+1 != ((line[i]&0xF0)>>4): good=0 else: line = ser.read_until( b'\xf1' ) bytearr = bytearray(line) if(good==1): for i in range(0, 0xf): bytearr[i] = (bytearr[i] & 0x0F) #print(binascii.hexlify(bytearr)) acdc = bytearr[0] num = [] num.append((bytearr[1]<<4) | bytearr[2]) num.append((bytearr[3]<<4) | bytearr[4]) num.append((bytearr[5]<<4) | bytearr[6]) num.append((bytearr[7]<<4) | bytearr[8]) unit = [] unit.append(bytearr[9] ) unit.append(bytearr[10]) unit.append(bytearr[11]) unit.append(bytearr[12]) unit.append(bytearr[13]) #print(unit[0]) #print(unit[1]) #print(unit[2]) #print(unit[3]) #print(unit[4]) return crap_to_number(num, unit, acdc, include_unit) def read(): ser = Serial("/dev/ttyUSB0", 2400) res = read_peaktech(ser, False) try: res = int(res) except: res = 0 return res if __name__ == "__main__": port = "/dev/ttyUSB0" if len(sys.argv) > 1: port = sys.argv[1] try: with Serial( port , 2400) as ser: print(ser.name) while True: print(read_peaktech(ser)) except KeyboardInterrupt: pass except Exception as ex: print( "Exception:", ex )