From 1123715297897670bc2dbbfa61feedacfd723ffc Mon Sep 17 00:00:00 2001 From: kyz Date: Sun, 17 Mar 2024 13:42:59 +0800 Subject: [PATCH] add test tool --- tools_v2/ser.py | 103 ++++++ tools_v2/test.py | 467 ++++++++++++++++++++++++ tools_v2/test.ui | 782 ++++++++++++++++++++++++++++++++++++++++ tools_v2/yn_download.py | 260 +++++++++++++ 4 files changed, 1612 insertions(+) create mode 100644 tools_v2/ser.py create mode 100644 tools_v2/test.py create mode 100644 tools_v2/test.ui create mode 100644 tools_v2/yn_download.py diff --git a/tools_v2/ser.py b/tools_v2/ser.py new file mode 100644 index 0000000..a771f89 --- /dev/null +++ b/tools_v2/ser.py @@ -0,0 +1,103 @@ +#ser.py + +import sys +import serial +import serial.tools +import serial.tools.list_ports +import serial.threaded +import time +import threading + +def scan( ): + device=[] + ports = serial.tools.list_ports.comports() + for p in ports: + device .append( p.device ) + return device + +class ser_rx(serial.threaded.Protocol): + def __init__( self , parent): + self.master = parent +# print( "ser_rx __init__ ") + + def __del__( self ): + pass +# print( "ser_rx __del__ ") + + def __call__(self): + return self + + def data_received(self, data): + if self.master.rx_handler: + with self.master.rx_lock: + self.master.rx_handler( data ) + else: + with self.master.rx_lock: + self.master.rx_data+=data + + +class ser: + def __init__( self): + self.port = None + self.rx_handler = None + self.ser = serial.Serial() + self.rx_data=[] + self.rx_lock = threading.Lock() + self.rx_worker = None +# print( "ser __init__ ") + + def __del__(self): + pass +# print( "ser __del__ ") + + + def __call__(self): + return self + + def open(self, port='COM7', baudrate=3000000, rx_handler=None ): + self.port = port + self.ser.baudrate=baudrate + self.rx_handler = rx_handler + self.ser.port = port + self.ser.timeout = None + self.ser.open() + self.rx_instance = ser_rx( self ) + self.rx_worker = serial.threaded.ReaderThread(self.ser, self.rx_instance ) + self.rx_worker.start() + + def close(self ): + self.rx_worker.close() + self.rx_worker.join() + + def write(self, data): + self.rx_worker.write( data ) + pass + + def read( self ): + with self.rx_lock: + data = self.rx_data + self.rx_data = [] + return data + +if __name__ == "__main__": + s = ser( ) + s=None + s=ser() + s.open( 'COM7', None) + print( 'open') + time.sleep(2) + + s.write( [0xf0, 0x04, 0x00, 0x00] ) + print("write") + time.sleep(2) + d = s.read() + print("read") + time.sleep(2) + s.close() + print("close") + time.sleep(2) + s=None + print( "rx:", bytes(d).hex()) + time.sleep(10) + exit(0) + diff --git a/tools_v2/test.py b/tools_v2/test.py new file mode 100644 index 0000000..d1d836d --- /dev/null +++ b/tools_v2/test.py @@ -0,0 +1,467 @@ +from collections import deque +from re import L +import socket +import sys +import os +import ser +import math + +import numpy as np +import pyqtgraph as pg + +from PyQt5.QtCore import * +from PyQt5.QtGui import * +from PyQt5.QtWidgets import * + +import json +#import serial +#import serial.tools +#import serial.tools.list_ports +#import serial.serialutil +#import modbus_tk + +import ui_test as ui_welding +import time + +import crcmod +import struct +import intelhex +import yn_download + +#生成CRC16-MODBUS校验码 +#crc16 = crcmod.mkCrcFun(0x18005, rev=True, initCrc=0xFFFF, xorOut=0x0000) +from collections import deque + +class App( QDialog, ui_welding.Ui_Dialog ): + trigger_rx_pkt = pyqtSignal( tuple ) + def __init__( self ): + super().__init__() + self.setupUi(self) + self.setWindowTitle( u"焊接控制器调试工具 V0.1") + + self.trigger_rx_pkt.connect( self.on_rx_pkt ) + + self.ser_opened = False + self.connected = 0 #0-disconnect 1-devinfo 2-curr 3-update + + self.btn_devinfo.released.connect( lambda:self.on_table_select(1) ) + self.btn_curr.released.connect( lambda:self.on_table_select(2) ) + self.btn_update.released.connect( lambda:self.on_table_select(3) ) + self.btn_cfg.released.connect( lambda:self.on_table_select(4) ) + self.tabWidget.findChild( QTabBar).hide() + + self.btn_connect_devinfo.released.connect( lambda:self.on_btn_connect(1)) + self.btn_connect_curr.released.connect( lambda:self.on_btn_connect(2)) + #self.btn_download.released.connect( lambda:self.on_btn_connect(3)) + + ###self.cbx_debug.release + #self.cbx_debug.stateChanged.connect( lambda:self.on_cbx_debug() ) + self.cb_debug_mode.currentIndexChanged.connect( self.on_cb_debug_mode ) + self.btn_debug_write.released.connect( self.on_btn_debug_write ) + self.debug_mode = 0 + self.on_cb_debug_mode(0) + + self.io_timer = QTimer() + self.io_timer.timeout.connect(self.on_scan_timer) + self.io_timer.start(2000) + self.crc16 = crcmod.mkCrcFun(0x18005, rev=True, initCrc=0xFFFF, xorOut=0x0000) + self.comports = [] + self.scan_port() + self.lineEdit_baud.setText( "9600" ) + self.ser = ser.ser() + self.rx_buf = b'' + self.generate_image() + self.raw_curr_idx = 0 +# self.btn_current.released.connect( self.on_btn_current ) + #fw update + self.btn_select_fw.released.connect( self.on_btn_select_file ) + self.btn_download.released.connect( self.on_btn_fw_download ) + + def parse_hex( self, path ): + try: + self.lineEdit_fw_path.setText( path ) + ih = intelhex.IntelHex( path ) + self.lineEdit_image_addr.setText( '%08X'%( ih.minaddr() ) ) + except: + #self.on_log( ( u"读取hex文件错误", "error") ) + self.lineEdit_image_addr.setText( "" ) + print( "select file error!" ) + return False + return True + def on_set_progress( self, v ): + self.progressBar.setValue( v ) + def on_download_end(self): + self.btn_download.setEnabled(True) + def on_log( self, log_evt ): + str, tag = log_evt + print( "LOG:", str ) + if tag == 'error': + log_str = '' + str + '' + elif tag == 'warning': + log_str = '' + str + '' + elif tag == 'green': + log_str = '' + str + '' + elif tag == 'info': + log_str = '' + str + '' + else: + log_str = '' + str + '' + self.update_log.append( log_str ) + def on_btn_select_file( self ): + file , check = QFileDialog.getOpenFileName(None, u"选择固件", "", "Hex files(*.hex);;All Files (*)") + print( "file,check", file, check ) + self.parse_hex( file ) + + def on_btn_fw_download( self ): + img_path = self.lineEdit_fw_path.text() + try: + pkt_max_sz = int( self.lineEdit_pkt_max_sz.text() ) + print( "pkt data max size", pkt_max_sz ) + except: + pkt_max_sz = 1024 + print( "pase hex ...", img_path) + if not self.parse_hex( img_path ): + print( "get hex img fail!" ) + return + + if not img_path: + print( 'get img path fail!' ) + return + if not os.path.exists( img_path ) or not os.path.isfile( img_path ): + print( "valid img path") + return + + print( "ser open ...") + if not self.ser_open(): + print( "open serial fail!") + return + + print( "ser close ...") + self.ser_close() + self.connected = 3 + #download + print( "fw:", self.lineEdit_fw_path.text() ) + self.yn_download = yn_download.yn_download( parent = self, image=img_path, port=self.port, baudrate = self.baud, pkt_max_sz = pkt_max_sz ) + #self.yn_download.download() + #self.yn_download.close() + self.update_log.clear() + self.btn_download.setEnabled(False) + print( "download start ...") + self.yn_download.start() + def wrap_pkt( self, cmd, data=b'' ): + pkt = struct.pack( '>HHH', 0x5AA5, len(data)+8, cmd )+data + crc = self.crc16( pkt ) + pkt += struct.pack( '>H', crc ) + return pkt + def wrap_close_debug_mode_pkt( self ): + return self.wrap_pkt( 0xF0 ) + def wrap_welding_curr_pkt( self, curr_a ): + return self.wrap_pkt( 0xF1, struct.pack( '>L', int(curr_a*1000+.5) ) ) + def wrap_valve_curr_pkt( self, curr_ma ): + return self.wrap_pkt( 0xF2, struct.pack( '>L', int(curr_ma) ) ) + def close_debug_mode( self): + if self.ser_opened: + print( "write cmd close debug_mode ") + self.ser.write( self.wrap_close_debug_mode_pkt() ) + def on_cb_debug_mode( self, idx ): + if idx == 0: + self.label_debug_curr_unit.setText( "A") + self.close_debug_mode() + self.btn_debug_write.setEnabled(0) + elif idx == 1: + self.label_debug_curr_unit.setText( "A") + self.btn_debug_write.setEnabled(1) + elif idx == 2: + self.label_debug_curr_unit.setText( "mA") + self.btn_debug_write.setEnabled(1) + self.debug_mode = idx + def on_btn_debug_write( self ): + if self.ser_opened: + curr = int( self.lineEdit_debug_value.text() ) + print( 'curr', curr, 'debug_mode', self.debug_mode ) + if self.debug_mode == 1: + cmd = self.wrap_welding_curr_pkt( curr ) + self.ser.write( cmd ) + elif self.debug_mode == 2: + cmd = self.wrap_valve_curr_pkt( curr ) + self.ser.write( cmd ) + def on_table_select( self, index ): + print( "on table select ", index ) + self.tabWidget.setCurrentIndex( index-1 ) + self.btn_devinfo.setStyleSheet( "background-color: green" if index==1 else "background-color: lightgray" ) + self.btn_curr.setStyleSheet( "background-color: green" if index==2 else "background-color: lightgray" ) + self.btn_update.setStyleSheet( "background-color: green" if index==3 else "background-color: lightgray" ) + self.btn_cfg.setStyleSheet( "background-color: green" if index==4 else "background-color: lightgray" ) + + def tx_cmd( self, cmd, data=b'', resp_cb=None ): + pkt = self.wrap_pkt( cmd, data ) + #print( "tx pkt[%04X]:"%cmd, pkt.hex() ) + self.ser.write( pkt ) + + self.wait_resp = ( cmd, False, resp_cb ) # wait resp cmd, rx cmd, rx result + retry = 10 + while not self.wait_resp[1] and retry>0 : + time.sleep( 0.1) + QApplication.processEvents() + retry -=1 + return self.wait_resp[2] + + def read_device_version( self ): + pass + def on_btn_connect( self, id ): + print( 'on btn connect', self.connected, id ) + if self.connected == 0: + if self.ser_open(): + if self.tx_cmd( 0x0022, struct.pack( '>L', id )): + self.connected = id + elif self.connected == id: + self.tx_cmd( 0x0022, struct.pack( '>L', 0 )) + self.connected = 0 + self.ser_close() + self.btn_connect_devinfo.setStyleSheet( "background-color: green" if self.connected==1 else "background-color: lightgray" ) + self.btn_connect_curr.setStyleSheet( "background-color: green" if self.connected==2 else "background-color: lightgray" ) + if self.connected: + self.tx_cmd( 0x0000 ) #读取版本 + + def generate_image(self): + verticalLayout_curr = QVBoxLayout(self.frame_curr) + win_curr = pg.GraphicsLayoutWidget(self.frame_curr) + verticalLayout_curr.addWidget(win_curr) + p_curr = win_curr.addPlot(title="动态波形图") + p_curr.showGrid(x=True,y=True) + p_curr.setLabel(axis="left",text="电流 mA") + p_curr.setLabel(axis="bottom",text="时间 s") + p_curr.setTitle(u"比例阀控制") + p_curr.addLegend() + #self.curve1 = p.plot(pen="r",name="焊接电流") + self.curve_valve_curr = p_curr.plot(pen="r",name="比例阀控制电流") + verticalLayout_flow = QVBoxLayout(self.frame_flow) + win_flow = pg.GraphicsLayoutWidget(self.frame_flow) + verticalLayout_flow.addWidget(win_flow) + p_flow = win_flow.addPlot(title="动态波形图") + p_flow.showGrid(x=True,y=True) + p_flow.setLabel(axis="left",text="气体流量 L/min") + p_flow.setLabel(axis="bottom",text="时间 (s)") + p_flow.setTitle("1.目标流量 2.实际流量") + p_flow.addLegend() + self.curve_flow_target = p_flow.plot(pen="r",name="1.目标流量") + self.curve_flow = p_flow.plot(pen="g",name="2.实际流量") + + #curr raw disp + verticalLayout_curr_raw = QVBoxLayout(self.frame_curr_raw) + win_curr_raw = pg.GraphicsLayoutWidget(self.frame_curr_raw) + verticalLayout_curr_raw.addWidget(win_curr_raw) + p_curr_raw = win_curr_raw.addPlot(title="动态波形图") + p_curr_raw.showGrid(x=True,y=True) + p_curr_raw.setLabel(axis="left",text="电流 A") + p_curr_raw.setLabel(axis="bottom",text="时间 (0.1ms/10KHz)") + p_curr_raw.setTitle("1.焊接电流") + p_curr_raw.addLegend() + self.curve_curr_raw = p_curr_raw.plot(pen="yellow",name="焊接电流") + + self.valve_curr_y = [] + self.flow_target_y = [] + self.flow_x = [] + self.flow_y = [] + self.curr_raw_x = [] + self.curr_raw_y = [] + + def on_rx_pkt( self, pkt ): + comments=''' + item.id = index; //焊接开始第一条记录id为0, 后面每条记录id加1 + item.curr_x10 = g_dev.welding_current*10; + item.flow_speed_x10 = g_dev.flowmeter.flow_speed*10; + item.pressure_x10 = g_dev.pressure * 10; + item.save_factor = g_dev.cfg.save_gas_factor; + item.target_flowspeed_x10 = g_dev.target_flowspeed; + item.valve_curr_ma = g_dev.valve_curr_out*1000; + item.valve_temp_x10 = g_dev.valve_temperature*10; + item.whelding_method = g_dev.cfg.welding_method; + typedef struct{ + uint16_t id; + uint16_t curr_x10; + uint16_t target_flowspeed_x10; + uint16_t flow_speed_x10; + uint16_t pressure_x10; + uint8_t valve_curr_ma; + uint8_t valve_temp_x10; + uint8_t whelding_method; + uint8_t save_factor; + uint16_t reserved; + }record_item_t; + ''' + + #print( "parse pkt , data:", data.hex(), len(data) ) + cmd,data = pkt + print( "rx_pkt: cmd:%04X, data len", len( data), data.hex() ) + if cmd == 0x0000 and len( data )>=24: + _,flag, v_major, v_minor, _, _, id0, id1, id2 = struct.unpack( '>BBBBLLLLL', data[:24] ) + print( 'flag', flag ) + self.label_fw_ver.setText( "%s V%d.%d"%( "APP"if flag == 0x41 else "BOOT", v_major, v_minor) ) + self.lineEdit_uuid.setText( "%08X-%08X-%08X"%( id0, id1, id2 )) + elif cmd == 0x0024 and len(data)>=10000: #焊接电流原始信息实时上报 + self.curr_raw_x = [] + self.curr_raw_y = [] + curr_sum = 0 + for i in range( 5000 ): + raw = struct.unpack( '>h', data[i*2:i*2+2])[0] + self.curr_raw_x.append( i/10.0 ) + self.curr_raw_y.append( raw ) + curr_sum += abs( raw ) + #save raw log + if not os.path.exists( 'raw_data/' ): + os.mkdir( 'raw_data' ) + file_name = time.strftime( "raw_data/%Y%m%d_%H%M%S" )+'-%d'%self.raw_curr_idx + self.raw_curr_idx += 1 + with open( file_name, 'wb' ) as fd: + fd.write( data ) + self.curve_curr_raw.setData( np.array( self.curr_raw_x), np.array( self.curr_raw_y)) + elif cmd == 0x0023 and len(data)>=16: #设备控制信息实时上报 + idx,curr_x10,target_fs_x10, fs_x10, pr_x10, valve_curr_ma, tem_x10, method,factor, res =struct.unpack("=2 and self.rx_buf[0] != 0x5A and self.rx_buf[1] != 0xA5: + self.rx_buf = self.rx_buf[1:] + if len( self.rx_buf )>=8: + print( "rx ", self.rx_buf[:8].hex()) + flag, pkt_sz, cmd = struct.unpack( '>HHH', self.rx_buf[:6] ) + if flag==0x5AA5: + if len(self.rx_buf)>= pkt_sz: + crc = self.crc16( self.rx_buf[0:pkt_sz-2]) + crc2 = struct.unpack( '>H', self.rx_buf[pkt_sz-2:pkt_sz] )[0] + print( 'crc--', crc ) + print( 'crc2-', crc2 ) + if crc == crc2: + pkt_data = self.rx_buf[6:pkt_sz-2] + self.trigger_rx_pkt.emit( (cmd, self.rx_buf[6:pkt_sz-2])) + self.rx_buf = self.rx_buf[pkt_sz:] + else: + pass #wait + else: + self.rx_buf = b'' + + def ser_close( self ): + self.port = self.cb_serial.currentText() + self.baud = self.lineEdit_baud.text() + #self.on_disconnect() + if self.ser_opened: + self.ser.close() + self.ser_opened = False + + def ser_open( self ): + self.port = self.cb_serial.currentText() + self.baud = self.lineEdit_baud.text() + self.ser.open( port=self.port, baudrate=self.baud, rx_handler=self.on_serial_rx_cb ) + if( self.ser.ser.is_open): + self.ser_opened = True + else: + print( "open serial fail" ) + return self.ser_opened + + def log_add( self, log_data ): + self.update_log.append( log_data ) + + def scan_port( self ): + comports=ser.scan() + if not self.comports == comports: + s = self.cb_serial.currentText() + self.cb_serial.clear() + + for com in comports: + self.cb_serial.addItem( com ) + if s in comports: + self.cb_serial.setEditText(s) + self.comports = comports + + def on_scan_timer( self ): + if not self.ser_opened: + self.scan_port() + + def __tx_sensor_cmd( self, sensor, cmd, span=0 ): + span_decimal, span_int = math.modf( span ) + span_int = int( span_int ) + span_decimal = round( span_decimal*100) + print( "span %d.%02d"%(span_int, span_decimal ) ) + tx_pkt =[0]*9 + tx_pkt[0] = 0xff + tx_pkt[1] = sensor + tx_pkt[2] = cmd + tx_pkt[3] = (span_int>>8)&0xff + tx_pkt[4] = span_int&0xff + tx_pkt[7] = span_decimal&0xff + sum = tx_pkt[1]+tx_pkt[2]+tx_pkt[3]+tx_pkt[4]+tx_pkt[5]+tx_pkt[6]+tx_pkt[7] + tx_pkt[8] = (0x100-sum)&0xff + tx_data = bytes( tx_pkt ) + + s = ser.ser() + s.open( port = self.port, baudrate = self.baud ) + print( "-------tx data:", tx_data.hex() ) + s.write( tx_data ) + time.sleep(0.5) + rd_data = s.read() + if len( rd_data )==9 and rd_data[0] == 0xff and rd_data[1]==0x86: + print( "ser read:", bytes(rd_data).hex() ) + self.lineEdit_concentration[sensor].setText( "%d"%((rd_data[2]<<8)|rd_data[3])) + elif len( rd_data )==9 and rd_data[0] == 0xff and rd_data[1]==0x87: + print( "ser read 87:", bytes(rd_data).hex() ) + elif len( rd_data )==9 and rd_data[0] == 0xff and rd_data[1]==0x88: + print( "ser read 88:", bytes(rd_data).hex() ) + s.close() + + def on_log( self, log_evt ): + str, tag = log_evt + print( "LOG:", str ) + if tag == 'error': + log_str = '' + str + '' + elif tag == 'warning': + log_str = '' + str + '' + elif tag == 'green': + log_str = '' + str + '' + elif tag == 'info': + log_str = '' + str + '' + else: + log_str = '' + str + '' + #self.update_log.append( log_str ) + +if __name__ == "__main__": + app = QApplication(sys.argv) # 创建一个QApplication,也就是你要开发的软件app + App().show() + sys.exit(app.exec_()) # 使用exit()或者点击关闭按钮退出QApplication diff --git a/tools_v2/test.ui b/tools_v2/test.ui new file mode 100644 index 0000000..df3b4e7 --- /dev/null +++ b/tools_v2/test.ui @@ -0,0 +1,782 @@ + + + Dialog + + + + 0 + 0 + 1324 + 845 + + + + Dialog + + + + + 10 + 150 + 141 + 691 + + + + QFrame::Box + + + QFrame::Raised + + + + + 10 + 20 + 121 + 81 + + + + 设备状态 + + + false + + + + + + 10 + 110 + 121 + 81 + + + + 焊接电流 + + + false + + + + + + 10 + 300 + 121 + 81 + + + + 参数配置 + + + false + + + + + + 10 + 210 + 121 + 81 + + + + 固件更新 + + + false + + + + + + + 10 + 10 + 141 + 141 + + + + + + + true + + + + + 10 + 40 + 121 + 31 + + + + true + + + false + + + true + + + + + + 20 + 10 + 31 + 31 + + + + 串口 + + + + + + 10 + 100 + 121 + 31 + + + + + + + 10 + 70 + 41 + 31 + + + + 波特率 + + + + + + + 160 + 10 + 1201 + 831 + + + + QFrame::Panel + + + QFrame::Raised + + + + + 0 + 0 + 1161 + 831 + + + + 0 + + + + Tab 1 + + + + + 0 + 130 + 1141 + 201 + + + + QFrame::StyledPanel + + + QFrame::Raised + + + + + + 0 + 340 + 1141 + 461 + + + + QFrame::StyledPanel + + + QFrame::Raised + + + + + + 10 + 70 + 1141 + 51 + + + + + + + + + + 焊接时间 + + + + + 焊接电流 + + + + + 目标流量 + + + + + 实时流量 + + + + + 气体压力 + + + + + 控制电流 + + + + + 焊接工艺 + + + + + 节气因子 + + + + + 默认开度 + + + + + 电流校准 + + + + + 流量校准 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + + + 10 + 0 + 71 + 61 + + + + 连接 + + + false + + + + + + 540 + 0 + 611 + 61 + + + + GroupBox + + + + + 510 + 10 + 91 + 51 + + + + 写入 + + + + + + 150 + 20 + 41 + 31 + + + + 80 + + + + + + 230 + 20 + 271 + 31 + + + + Qt::Horizontal + + + + + + 10 + 20 + 121 + 31 + + + + true + + + false + + + true + + + + 关闭模拟调试 + + + + + 模拟焊接电流 + + + + + 比例阀控制电流 + + + + + + + 200 + 20 + 21 + 31 + + + + A + + + + + + + 90 + 0 + 441 + 61 + + + + GroupBox + + + + + 20 + 21 + 41 + 31 + + + + 版本: + + + + + + 70 + 20 + 81 + 31 + + + + V1.0 + + + + + + 190 + 20 + 41 + 31 + + + + UUID: + + + + + + 230 + 20 + 201 + 31 + + + + 00000000-00000000-00000000 + + + true + + + + + + + Tab 2 + + + + + 0 + 480 + 1151 + 321 + + + + QFrame::StyledPanel + + + QFrame::Raised + + + + + + 10 + 60 + 111 + 51 + + + + 日志选择 + + + + + + 130 + 0 + 931 + 471 + + + + + + + 10 + 0 + 111 + 51 + + + + 连接 + + + + + + 10 + 120 + 111 + 51 + + + + 日志清除 + + + + + + 页 + + + + + 10 + 10 + 591 + 591 + + + + GroupBox + + + + + 80 + 70 + 111 + 31 + + + + + + + 10 + 140 + 571 + 20 + + + + Qt::Horizontal + + + + + + 80 + 30 + 331 + 31 + + + + + + + 10 + 30 + 61 + 31 + + + + 固件.. + + + false + + + + + + 210 + 70 + 91 + 31 + + + + 数据包最大长度 + + + + + + 420 + 30 + 161 + 101 + + + + 下载 + + + + + + 310 + 70 + 101 + 31 + + + + 1024 + + + false + + + false + + + false + + + + + + 10 + 160 + 571 + 421 + + + + Qt::ImhDigitsOnly + + + + + + 10 + 70 + 51 + 31 + + + + 起始地址 + + + + + + 10 + 110 + 401 + 20 + + + + false + + + 0 + + + true + + + Qt::Horizontal + + + + + + + 页 + + + + + + + + diff --git a/tools_v2/yn_download.py b/tools_v2/yn_download.py new file mode 100644 index 0000000..9e5860e --- /dev/null +++ b/tools_v2/yn_download.py @@ -0,0 +1,260 @@ +#! /usr/bin/python +import os +import ser +import threading +import time +import intelhex +import crcmod +import struct + +from PyQt5.QtCore import * +from PyQt5.QtGui import * +from PyQt5.QtWidgets import * + +class yn_download(QThread): + trigger_end = pyqtSignal() + trigger_log = pyqtSignal( tuple ) + trigger_pbar = pyqtSignal( int ) + def __init__( self, parent, image, port='COM4', baudrate=3000000, pkt_max_sz=512 ): + super(yn_download, self).__init__() + self.parent = parent + self.s = None #ser.ser() + self.port = port + self.baudrate = baudrate + self.rx_event = threading.Event() + self.wait_cmd = 0 + self.rx_data=b'' + self.ser = None + self.image_path = image + self.image_bin = None + self.image_addr = 0x08000000 + self.pkt_max_sz = pkt_max_sz + self.trigger_end.connect( self.parent.on_download_end ) + self.trigger_log.connect( self.parent.on_log ) + self.trigger_pbar.connect( self.parent.on_set_progress ) + #self.image_type = None + ext = os.path.splitext( self.image_path ) + if ext and ext[1]=='.hex': + #Hex file + print( "+++IntelHex ....") + ih = intelhex.IntelHex( self.image_path ) + print( "---IntelHex ....") + self.image_addr = ih.minaddr() + print( "---IntelHex ....", self.image_addr) + self.image_bin = ih.tobinarray().tobytes() + print( "---IntelHex ....", len(self.image_bin) ) + #self.image_type = 'hex' + else: + #Bin file + with open( self.image_path, 'rb' ) as fd: + self.image_bin = fd.read() + self.image_addr = 0x08000000 + #self.image_type = 'bin' + #self.trigger_pbar.emit(0) + self.crc16 = crcmod.mkCrcFun(0x18005, rev=True, initCrc=0xFFFF, xorOut=0x0000) + print( "--------download init ---------------" ) + + def __del__( self ): + if self.ser: + self.ser.close() + def close(self ): + if self.ser: + self.ser.close() + self.ser = None + def wrap_pkt( self, cmd, data=b'' ): + pkt_len = len(data)+8 + p = struct.pack( '>HHH', 0x5aa5, pkt_len, cmd ) + p += data + crc_v = self.crc16( p ) + p += struct.pack( '>H', crc_v ) + print( "wrap a pkt:", p.hex()) + return p + def wrap_erase_pkt( self, off, sz ): + print( 'wrap pkt', off, sz ) + d = struct.pack( '>LL', off, sz ) + return self.wrap_pkt( 0x0001, d ) + def wrap_write_pkt( self, off, data ): + d = struct.pack( '>L', off )+data + return self.wrap_pkt( 0x0002, d ) + def wrap_query_pkt( self ): + return self.wrap_pkt( 0x0000 ) + def wrap_readcrc_pkt( self ): + d = struct.pack( '>LL', self.image_addr, len( self.image_bin)) + return self.wrap_pkt( 0x0003, d ) + def wrap_reboot_pkt( self, mode = 0 ): + return self.wrap_pkt( 0x0004, mode.to_bytes(4, 'big') ) + def parse_image( self ): + print( "parse_image .................") + img_path, img_name = os.path.split( self.image_path ) + self.log_add( '='*50 , 'info' ) + self.log_add( 'image: %s'%(img_name), 'info' ) + self.log_add( 'addr: %08X size: %d Bytes, CRC:%04X\n'%( self.image_addr, len(self.image_bin), self.crc16( self.image_bin ) ), 'info' ) + self.log_add( '-'*50, 'info') + + data = self.image_bin + img_sz = len(data) + + pkgs=[] + count = 0 + off = self.image_addr + erase_sz = (img_sz+self.pkt_max_sz-1)//self.pkt_max_sz*self.pkt_max_sz + p = self.wrap_erase_pkt( off, erase_sz ) + pkgs.append( p ) + while count self.pkt_max_sz: + sz = self.pkt_max_sz + d = data[count:count+sz] + p = self.wrap_write_pkt( off + count, d ) + pkgs.append(p) + count +=sz + #verify todo ... + + #reboot todo ... + return pkgs + + def get_pkt(self): + d = self.rx_data + if( len(d) >=8 ): + print( "get_pkt", len(d), d.hex() ) + n=0 + + if len(d)>=8 and d[0]==0x5A and d[1]==0xA5: + n = struct.unpack( '>H', d[2:4])[0] + else: + return [] + if len(d) >= n: + pkt_crc = struct.unpack( '>H', d[n-2:n] )[0] + if pkt_crc == self.crc16( d[:n-2] ): + return d[:n] + else: + print( 'rxpkt crc err!:') + return [] + + def wait(self, cmd, to): + self.wait_cmd = cmd + self.rx_event.wait( timeout=to) + + def wait_resp(self): + if self.rx_event.wait( timeout= 5): + return self.resp + return None + + def rx_handler(self, data): + self.rx_data += data + #print( "rx data :", self.rx_data.hex() ) + pkt = self.get_pkt() + if len(pkt): + self.rx_data = b'' + #print( "event set") + self.rx_pkt = pkt + self.rx_event.set() + + def transmit(self, tx, timeout = 5, retry=1 ): + while retry>0: + retry -= 1 + self.rx_event.clear() + try: + print( "发送[%d]: %s ..."%( len(tx), tx[:64].hex())) + self.s.write( tx ) + if self.rx_event.wait( timeout= timeout ): + print( "接收[%d]: %s ..."%( len(self.rx_pkt), self.rx_pkt[:64].hex() ) ) + return True + else: + self.log_add( '数据传输超时!', 'error') + except: + self.log_add( '数据发送失败!', 'error') + #TODO : raise excpection + return False + + def connect(self): + self.log_add( u"连接设备 ... ") + #read uuid + print( "++++++++++++++++++++++++++++++++++") + resp = self.transmit( self.wrap_query_pkt(), timeout = 2, retry = 5 ) + if resp: + if len(self.rx_pkt)>=32 and self.rx_pkt[7]==0x42: + self.log_add( u'连接成功', 'info') + self.log_add( '-'*50 + '\n' ) + return True + else: + self.log_add( u'连接错误', 'error' ) + else: + self.log_add( '连接超时', 'error') + return False + + def run(self ): + self.log_clear() + pkgs = self.parse_image() + #if self.pbar: + # self.pbar['maximum'] = len(pkgs) + self.s = ser.ser() + try: + self.s.open( self.port, self.baudrate, self.rx_handler) + except: + self.log_add( '打开串口失败!', 'error') + self.trigger_end.emit() + return + if not self.connect(): + self.s.close() + self.trigger_end.emit() + return + + self.log_add( '下载开始 ... %s'%(time.strftime('%H:%M:%S')), 'info' ) + t0 = time.time() + + cmd_n = 0 + for cmd in pkgs: + #if self.pbar: + # self.pbar.step(1) + # self.pbar.update() + if cmd_n == 0: + wait_time = 20 + else: + wait_time = 5*2 + + resp = self.transmit( cmd, timeout=wait_time ) + if resp and len( self.rx_pkt)>6 and self.rx_pkt[6]: + time.sleep( 0.01 ) + else: + self.log_add( "响应超时", "error") + self.s.close() + self.trigger_end.emit() + return + + cmd_n += 1 + self.trigger_pbar.emit( cmd_n*100//len(pkgs)) + + #verify, read crc16 vaule of image + self.log_add( "校验...", 'info' ) + resp = self.transmit( self.wrap_readcrc_pkt()) + if resp and len( self.rx_pkt)>=8: + flash_crc = int.from_bytes(self.rx_pkt[6:8], 'little') + img_crc = self.crc16( self.image_bin ) + if flash_crc == img_crc: + self.log_add( "校验成功 CRC:%04X"%(flash_crc), 'info' ) + self.log_add( '下载完成 ... %s'%(time.strftime('%H:%M:%S')), 'info' ) + self.log_add( "下载时间: \t%d 秒"%( time.time()-t0 ), 'info' ) + self.transmit( self.wrap_readcrc_pkt(), timeout = 2 ) + self.log_add( "重启系统 ... ", 'info' ) + if self.transmit( self.wrap_reboot_pkt(), timeout=2 ): + pass + else: + pass + else: + self.log_add( "校验错误, 固件CRC:%04X, 读取CRC:%04X"%( img_crc, flash_crc), "error" ) + else: + self.log_add( "校验响应超时", "error" ) + self.s.close() + self.trigger_end.emit() + + def log_add( self, text, tag='info' ): + self.trigger_log.emit( (text, tag) ) + + def log_clear(self ): + pass + +if __name__ == "__main__": + #d.download() + exit(0) + -- 2.34.1