优化下以下代码:def irpoweron(ser_mcu, cmd_list='6E 51 00 2C 04 02 FD 14 EB ed 02', frame_id=0): cmd_switch = uart_tx_cmd(cmd_list, frame_id) datahex = bytes.fromhex(cmd_switch) star_sendcmd_flag = False # print(cmd_switch) time.sleep(0.1) try: ser_mcu.write(datahex) star_sendcmd_flag = True except: sys.exit(0) time_uart_start = time.perf_counter() while True: time_now = time.perf_counter() # print(time_now - time_uart_start) if time_now - time_uart_start > 0.1: # print('测试超时!') return -1 try: com_input = ser_mcu.read(8192) # 设置一次循环接收数据的个数 except: sys.exit(0) if com_input and star_sendcmd_flag == True: # 如果读取结果非空,则输出 rxdata = uartrx_pro(com_input, ser_mcu) # print('接收到指令:', rxdata) if rxdata[0] == 1: if rxdata[1] == int('0', 16) and int(rxdata[4], 16) == frame_id % 256: # ACK 指令 # print('遥控器Power发送成功') return 1 if rxdata[0] == 2: if rxdata[1] == int('0', 16) and int(rxdata[4], 16) == frame_id % 256: # ACK 指令 # print('遥控器Power发送成功') star_flag = True return 1 if rxdata[5] == int('0', 16) and int(rxdata[8], 16) == frame_id % 256: # ACK 指令 # print('遥控器Power发送成功') star_flag = True return 1
时间: 2023-12-10 08:41:22 浏览: 79
usb.c51.rar_USB C51_d12_ser c51 U_usb c51_usb 编程
以下是对该代码的优化建议:
1. 使用参数注解来增加代码可读性;
2. 使用异常机制来处理串口通信时可能出现的异常;
3. 在 while 循环中添加 time.sleep() 来降低 CPU 占用率;
4. 使用 bytearray.fromhex() 代替 bytes.fromhex();
5. 将常量提取为变量,以提高代码可维护性;
6. 在代码中添加注释,以增加代码可读性。
下面是优化后的代码:
```python
import sys
import time
import serial
def irpoweron(ser_mcu: serial.Serial, cmd_list: str = '6E 51 00 2C 04 02 FD 14 EB ed 02', frame_id: int = 0) -> int:
# 将命令字符串转换为字节数组
cmd_switch = uart_tx_cmd(cmd_list, frame_id)
datahex = bytearray.fromhex(cmd_switch)
# 发送命令
star_sendcmd_flag = False
time_uart_start = time.perf_counter()
try:
ser_mcu.write(datahex)
star_sendcmd_flag = True
except Exception as e:
print(f"Exception: {e}")
sys.exit(0)
# 接收响应
while True:
time_now = time.perf_counter()
if time_now - time_uart_start > 0.1:
# 超时未收到响应
return -1
time.sleep(0.01) # 降低 CPU 占用率
try:
com_input = ser_mcu.read(8192)
except Exception as e:
print(f"Exception: {e}")
sys.exit(0)
if com_input and star_sendcmd_flag:
# 解析响应
rxdata = uartrx_pro(com_input, ser_mcu)
# print('接收到指令:', rxdata)
if rxdata[0] == 1:
if rxdata[1] == 0 and int(rxdata[4], 16) == frame_id % 256:
# 收到 ACK 响应
# print('遥控器Power发送成功')
return 1
elif rxdata[0] == 2:
if rxdata[1] == 0 and int(rxdata[4], 16) == frame_id % 256:
# 收到 ACK 响应
# print('遥控器Power发送成功')
star_flag = True
return 1
elif rxdata[5] == 0 and int(rxdata[8], 16) == frame_id % 256:
# 收到 ACK 响应
# print('遥控器Power发送成功')
star_flag = True
return 1
# 将常量提取为变量
CMD_LIST = '6E 51 00 2C 04 02 FD 14 EB ed 02'
FRAME_ID = 0
```
阅读全文