def hexShow(argv):
try:
result = ''
hLen = len(argv)
for i in range(hLen):
hvol = argv[i]
hhex = '%02x' % hvol
result += hhex+' '
logging.info('Led Read:%s', result)
return result
except Exception as e:
print("---异常---:", e)
def crc_sum(data, data_len):
crc = 0
i = 0
while(i < data_len):
crc += data[i]
i += 1
return crc & 0x00FF
def crc_sum_u32(data, data_len):
crc = 0
i = 0
while(i < data_len):
crc += data[i]
i += 1
return crc
# 打开串⼝
def DOpenPort(portx, bps, timeout):
try:
# 打开串⼝,并得到串⼝对象
ser = serial.Serial(portx, bps, timeout=timeout)
# 判断是否打开成功
if(False == ser.is_open):
ser = -1
except Exception as e:
print("---异常---:", e)
return ser
# 关闭串⼝
def DColsePort(ser):
uart.fdstate = -1
ser.close()
# 写数据
def DWritePort(ser, data):
result = ser.write(data) # 写数据
logging.info(ser)
logging.info("Led Write %s(%d)" % (data.hex(), result)) return result
# 读数据
def ReadData_Thread(ser):
# 循环接收数据,此为死循环,可⽤线程实现
readstr = ""
while(-1 != ser):python怎么读取串口数据
if ser.in_waiting:
try: # 如果读取的不是⼗六进制数据--
readbuf = ad(ser.in_waiting)
if readbuf[0] == 0x55 and readbuf[1] == 0xaa: readstr = readbuf
else:
readstr = readstr + readbuf
hexShow(readstr)
hexShow(readstr)
if (readstr[3] == 0x01) and (len(readstr) > 10):
uart.version = readstr[16]
uart.write_event.set()
elif (readstr[3] == 0x21) and (readstr[4] == 0x00) and (readstr[5] == 0x00): sponse = True
uart.write_event.set()
elif (readstr[3] == 0x22) and (len(readstr) > 10):
uart.image_addr = (readstr[6] << 24 & 0xFF000000)
uart.image_addr += (readstr[7] << 16 & 0x00FF0000)
uart.image_addr += (readstr[8] << 8 & 0x0000FF00)
uart.image_addr += (readstr[9] << 0 & 0x000000FF)
uart.write_event.set()
elif (readstr[3] == 0x23) and (len(readstr) > 25):
uart.write_event.set()
except: # --则将其作为字符串读取
readbuf = ad(ser.in_waiting)
hexShow(readbuf)
def GetVersion(ser):
print("GetVersion")
writebuf = bytearray([0x55, 0xaa, 0x00, 0x01, 0x00, 0x00])
# crc
writebuf.append(crc_sum(writebuf, len(writebuf)))
DWritePort(ser, writebuf)
logging.info("take")
uart.write_event.clear()
uart.write_event.wait(timeout=3)
uart.write_event.clear()
logging.info("give")
sponse == False:
logging.info("fail")
return False
else:
return True
# 测试任务
def Test_Thread(ser):
while (-1 != ser):
uart.image_addr = 0x00
uart.image_crc = 0x00
uart.version = 0
logging.info("count:%d", unt)
logging.info("fail:%d", uart.fail)
print("count", unt)
print("fail", uart.fail)
if GetVersion(ser):
logging.info(uart.version)
if uart.version == 0x37:
otafile = "./UartV108.bin"
else:
otafile = "./UartV107.bin"
else:
uart.fail += 1
continue
print("ota:", otafile)
logging.info("ota:%s", otafile)
time.sleep(2)
time.sleep(5)
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论