修改bootloader
authorkyz <kyz@kyz.pub>
Wed, 13 Mar 2024 03:31:04 +0000 (11:31 +0800)
committerkyz <kyz@kyz.pub>
Wed, 13 Mar 2024 03:31:04 +0000 (11:31 +0800)
Core/Src/main.c
MDK-ARM/bootloader.uvprojx
tools/test2.py [new file with mode: 0644]
tools/test2.ui [new file with mode: 0644]
tools/yn_download.py [new file with mode: 0644]
user/bootloader.c
user/user_cdc_rx_2.c
user/user_ospi_flash.c

index 7e7b918133674a54a75a213a577f7662a78b86ea..e7735a99d658e52cc937e06ce23da7dd0b10feca 100644 (file)
@@ -78,11 +78,11 @@ void MX_FREERTOS_Init(void);
 int main(void)
 {
   /* USER CODE BEGIN 1 */
-    //BOOT中把itcm配置256K 地址空间0
+    //BOOT中把itcm配置256K 地址空间0--256K
     //主程序从flash加载到ITCM中运行,加载地址1000 
-    //程序0x00001000不放å\9c?0地址,否则许多内存读写函数会判为NULL?
+    //程序0x00001000不放0地址,否则许多内存读写函数会判为NULL?
     //在这里手动修改VTOR
-    //SCB->VTOR = 0x1000; 
+//    SCB->VTOR = 0x1000; 
   /* USER CODE END 1 */
 /* Enable the CPU Cache */
 
index 206bb1b88a5a42191d99e43ed40bd55ba45554a4..51a966677a00239d70a09f0a06e6cd93d676255a 100644 (file)
               <FileType>1</FileType>
               <FilePath>..\Core\Src\adc.c</FilePath>
             </File>
+            <File>
+              <FileName>octospi.c</FileName>
+              <FileType>1</FileType>
+              <FilePath>..\Core\Src\octospi.c</FilePath>
+            </File>
           </Files>
         </Group>
         <Group>
               <FileType>1</FileType>
               <FilePath>../Drivers/STM32H7xx_HAL_Driver/Src/stm32h7xx_hal_uart_ex.c</FilePath>
             </File>
+            <File>
+              <FileName>stm32h7xx_hal_ospi.c</FileName>
+              <FileType>1</FileType>
+              <FilePath>..\Drivers\STM32H7xx_HAL_Driver\Src\stm32h7xx_hal_ospi.c</FilePath>
+            </File>
           </Files>
         </Group>
         <Group>
               <FileType>1</FileType>
               <FilePath>..\user\user_nv.c</FilePath>
             </File>
-            <File>
-              <FileName>user_sflash.c</FileName>
-              <FileType>1</FileType>
-              <FilePath>..\user\user_sflash.c</FilePath>
-            </File>
             <File>
               <FileName>mbmCRC16.c</FileName>
               <FileType>1</FileType>
               <FilePath>..\user\mbmCRC16.c</FilePath>
             </File>
             <File>
-              <FileName>user_cdc_rx.c</FileName>
+              <FileName>user_cdc_rx_2.c</FileName>
               <FileType>1</FileType>
-              <FilePath>..\user\user_cdc_rx.c</FilePath>
-              <FileOption>
-                <CommonProperty>
-                  <UseCPPCompiler>2</UseCPPCompiler>
-                  <RVCTCodeConst>0</RVCTCodeConst>
-                  <RVCTZI>0</RVCTZI>
-                  <RVCTOtherData>0</RVCTOtherData>
-                  <ModuleSelection>0</ModuleSelection>
-                  <IncludeInBuild>0</IncludeInBuild>
-                  <AlwaysBuild>2</AlwaysBuild>
-                  <GenerateAssemblyFile>2</GenerateAssemblyFile>
-                  <AssembleAssemblyFile>2</AssembleAssemblyFile>
-                  <PublicsOnly>2</PublicsOnly>
-                  <StopOnExitCode>11</StopOnExitCode>
-                  <CustomArgument></CustomArgument>
-                  <IncludeLibraryModules></IncludeLibraryModules>
-                  <ComprImg>1</ComprImg>
-                </CommonProperty>
-                <FileArmAds>
-                  <Cads>
-                    <interw>2</interw>
-                    <Optim>0</Optim>
-                    <oTime>2</oTime>
-                    <SplitLS>2</SplitLS>
-                    <OneElfS>2</OneElfS>
-                    <Strict>2</Strict>
-                    <EnumInt>2</EnumInt>
-                    <PlainCh>2</PlainCh>
-                    <Ropi>2</Ropi>
-                    <Rwpi>2</Rwpi>
-                    <wLevel>0</wLevel>
-                    <uThumb>2</uThumb>
-                    <uSurpInc>2</uSurpInc>
-                    <uC99>2</uC99>
-                    <uGnu>2</uGnu>
-                    <useXO>2</useXO>
-                    <v6Lang>0</v6Lang>
-                    <v6LangP>0</v6LangP>
-                    <vShortEn>2</vShortEn>
-                    <vShortWch>2</vShortWch>
-                    <v6Lto>2</v6Lto>
-                    <v6WtE>2</v6WtE>
-                    <v6Rtti>2</v6Rtti>
-                    <VariousControls>
-                      <MiscControls></MiscControls>
-                      <Define></Define>
-                      <Undefine></Undefine>
-                      <IncludePath></IncludePath>
-                    </VariousControls>
-                  </Cads>
-                </FileArmAds>
-              </FileOption>
+              <FilePath>..\user\user_cdc_rx_2.c</FilePath>
             </File>
             <File>
-              <FileName>user_cdc_rx_2.c</FileName>
+              <FileName>user_ospi_flash.c</FileName>
               <FileType>1</FileType>
-              <FilePath>..\user\user_cdc_rx_2.c</FilePath>
+              <FilePath>..\user\user_ospi_flash.c</FilePath>
             </File>
           </Files>
         </Group>
diff --git a/tools/test2.py b/tools/test2.py
new file mode 100644 (file)
index 0000000..00374db
--- /dev/null
@@ -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_test2 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 = '<font color="#FF0000">' + str + '</font>'
+        elif tag == 'warning':
+            log_str = '<font color="orange">' + str + '</font>'
+        elif tag == 'green':
+            log_str = '<font color="green">' + str + '</font>'
+        elif tag == 'info':
+            log_str = '<font color="#000000">' + str + '</font>'
+        else:
+            log_str = '<font color="#000000">' + str + '</font>'
+        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("<HHHHHBBBBH", data[:16])
+            self.tableWidget_devinfo.item(0,0).setText( "%0.0f"%(idx/10.0) )
+            self.tableWidget_devinfo.item(0,1).setText( "%0.1f"%(curr_x10/10.0))
+            self.tableWidget_devinfo.item(0,2).setText( "%0.1f"%(target_fs_x10/10.0))
+            self.tableWidget_devinfo.item(0,3).setText( "%0.1f"%(fs_x10/10.0))
+            self.tableWidget_devinfo.item(0,4).setText( "%0.1f"%(pr_x10/10.0))
+            self.tableWidget_devinfo.item(0,5).setText( "%0.0f"%(valve_curr_ma))
+            self.tableWidget_devinfo.item(0,6).setText( "%d"%(method))
+            self.tableWidget_devinfo.item(0,7).setText( "%d"%(factor))
+            self.tableWidget_devinfo.item(0,8).setText( "%0.1f"%(tem_x10/10.0))
+            if idx == 0:
+                    self.flow_x=[]
+                    self.flow_y=[]
+                    self.flow_target_y=[]
+                    self.valve_curr_y=[]
+                    return
+            elif idx == 1:
+                    self.flow_x=[]
+                    self.flow_y=[]
+                    self.flow_target_y=[]
+                    self.valve_curr_y=[]
+            if len( self.flow_x)<1000:
+                self.flow_x.append( idx/10.0)
+                self.valve_curr_y.append( valve_curr_ma*1.0 )
+                self.flow_target_y.append( target_fs_x10/10.0)
+                self.flow_y.append( fs_x10/10.0)
+            else:
+                self.flow_x = self.flow_x[1:]+[ idx/2.0 ]
+                self.valve_curr_y = self.valve_curr_y[1:]+[ curr_x10/10.0]
+                self.flow_target_y = self.flow_target_y[1:]+[ target_fs_x10/10.0]
+                self.flow_y = self.flow_y[1:]+[ fs_x10/10.0]
+            print( '23 pkt', len( self.flow_x), len( self.flow_target_y), len( self.flow_y), len( self.valve_curr_y) )
+            self.curve_valve_curr.setData( np.array( self.flow_x), np.array( self.valve_curr_y))
+            self.curve_flow.setData( np.array( self.flow_x), np.array( self.flow_y))
+            self.curve_flow_target.setData( np.array( self.flow_x), np.array( self.flow_target_y))
+
+        if cmd == self.wait_resp[0]:
+            self.wait_resp = ( cmd, True, data[0] )
+            print( "recv resp", self.wait_resp )
+
+    def on_serial_rx_cb( self, data ):
+        self.rx_buf += data
+        while len(self.rx_buf)>=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 = '<font color="#FF0000">' + str + '</font>'
+        elif tag == 'warning':
+            log_str = '<font color="orange">' + str + '</font>'
+        elif tag == 'green':
+            log_str = '<font color="green">' + str + '</font>'
+        elif tag == 'info':
+            log_str = '<font color="#000000">' + str + '</font>'
+        else:
+            log_str = '<font color="#000000">' + str + '</font>'
+        #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/test2.ui b/tools/test2.ui
new file mode 100644 (file)
index 0000000..df3b4e7
--- /dev/null
@@ -0,0 +1,782 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>Dialog</class>
+ <widget class="QDialog" name="Dialog">
+  <property name="geometry">
+   <rect>
+    <x>0</x>
+    <y>0</y>
+    <width>1324</width>
+    <height>845</height>
+   </rect>
+  </property>
+  <property name="windowTitle">
+   <string>Dialog</string>
+  </property>
+  <widget class="QFrame" name="frame_left">
+   <property name="geometry">
+    <rect>
+     <x>10</x>
+     <y>150</y>
+     <width>141</width>
+     <height>691</height>
+    </rect>
+   </property>
+   <property name="frameShape">
+    <enum>QFrame::Box</enum>
+   </property>
+   <property name="frameShadow">
+    <enum>QFrame::Raised</enum>
+   </property>
+   <widget class="QPushButton" name="btn_devinfo">
+    <property name="geometry">
+     <rect>
+      <x>10</x>
+      <y>20</y>
+      <width>121</width>
+      <height>81</height>
+     </rect>
+    </property>
+    <property name="text">
+     <string>设备状态</string>
+    </property>
+    <property name="autoDefault">
+     <bool>false</bool>
+    </property>
+   </widget>
+   <widget class="QPushButton" name="btn_curr">
+    <property name="geometry">
+     <rect>
+      <x>10</x>
+      <y>110</y>
+      <width>121</width>
+      <height>81</height>
+     </rect>
+    </property>
+    <property name="text">
+     <string>焊接电流</string>
+    </property>
+    <property name="autoDefault">
+     <bool>false</bool>
+    </property>
+   </widget>
+   <widget class="QPushButton" name="btn_cfg">
+    <property name="geometry">
+     <rect>
+      <x>10</x>
+      <y>300</y>
+      <width>121</width>
+      <height>81</height>
+     </rect>
+    </property>
+    <property name="text">
+     <string>参数配置</string>
+    </property>
+    <property name="autoDefault">
+     <bool>false</bool>
+    </property>
+   </widget>
+   <widget class="QPushButton" name="btn_update">
+    <property name="geometry">
+     <rect>
+      <x>10</x>
+      <y>210</y>
+      <width>121</width>
+      <height>81</height>
+     </rect>
+    </property>
+    <property name="text">
+     <string>固件更新</string>
+    </property>
+    <property name="autoDefault">
+     <bool>false</bool>
+    </property>
+   </widget>
+  </widget>
+  <widget class="QGroupBox" name="groupBox_2">
+   <property name="geometry">
+    <rect>
+     <x>10</x>
+     <y>10</y>
+     <width>141</width>
+     <height>141</height>
+    </rect>
+   </property>
+   <property name="title">
+    <string/>
+   </property>
+   <property name="flat">
+    <bool>true</bool>
+   </property>
+   <widget class="QComboBox" name="cb_serial">
+    <property name="geometry">
+     <rect>
+      <x>10</x>
+      <y>40</y>
+      <width>121</width>
+      <height>31</height>
+     </rect>
+    </property>
+    <property name="editable">
+     <bool>true</bool>
+    </property>
+    <property name="duplicatesEnabled">
+     <bool>false</bool>
+    </property>
+    <property name="frame">
+     <bool>true</bool>
+    </property>
+   </widget>
+   <widget class="QLabel" name="label">
+    <property name="geometry">
+     <rect>
+      <x>20</x>
+      <y>10</y>
+      <width>31</width>
+      <height>31</height>
+     </rect>
+    </property>
+    <property name="text">
+     <string>串口</string>
+    </property>
+   </widget>
+   <widget class="QLineEdit" name="lineEdit_baud">
+    <property name="geometry">
+     <rect>
+      <x>10</x>
+      <y>100</y>
+      <width>121</width>
+      <height>31</height>
+     </rect>
+    </property>
+   </widget>
+   <widget class="QLabel" name="label_2">
+    <property name="geometry">
+     <rect>
+      <x>10</x>
+      <y>70</y>
+      <width>41</width>
+      <height>31</height>
+     </rect>
+    </property>
+    <property name="text">
+     <string>波特率</string>
+    </property>
+   </widget>
+  </widget>
+  <widget class="QFrame" name="frame_right">
+   <property name="geometry">
+    <rect>
+     <x>160</x>
+     <y>10</y>
+     <width>1201</width>
+     <height>831</height>
+    </rect>
+   </property>
+   <property name="frameShape">
+    <enum>QFrame::Panel</enum>
+   </property>
+   <property name="frameShadow">
+    <enum>QFrame::Raised</enum>
+   </property>
+   <widget class="QTabWidget" name="tabWidget">
+    <property name="geometry">
+     <rect>
+      <x>0</x>
+      <y>0</y>
+      <width>1161</width>
+      <height>831</height>
+     </rect>
+    </property>
+    <property name="currentIndex">
+     <number>0</number>
+    </property>
+    <widget class="QWidget" name="tab">
+     <attribute name="title">
+      <string>Tab 1</string>
+     </attribute>
+     <widget class="QFrame" name="frame_curr">
+      <property name="geometry">
+       <rect>
+        <x>0</x>
+        <y>130</y>
+        <width>1141</width>
+        <height>201</height>
+       </rect>
+      </property>
+      <property name="frameShape">
+       <enum>QFrame::StyledPanel</enum>
+      </property>
+      <property name="frameShadow">
+       <enum>QFrame::Raised</enum>
+      </property>
+     </widget>
+     <widget class="QFrame" name="frame_flow">
+      <property name="geometry">
+       <rect>
+        <x>0</x>
+        <y>340</y>
+        <width>1141</width>
+        <height>461</height>
+       </rect>
+      </property>
+      <property name="frameShape">
+       <enum>QFrame::StyledPanel</enum>
+      </property>
+      <property name="frameShadow">
+       <enum>QFrame::Raised</enum>
+      </property>
+     </widget>
+     <widget class="QTableWidget" name="tableWidget_devinfo">
+      <property name="geometry">
+       <rect>
+        <x>10</x>
+        <y>70</y>
+        <width>1141</width>
+        <height>51</height>
+       </rect>
+      </property>
+      <row>
+       <property name="text">
+        <string/>
+       </property>
+      </row>
+      <column>
+       <property name="text">
+        <string>焊接时间</string>
+       </property>
+      </column>
+      <column>
+       <property name="text">
+        <string>焊接电流</string>
+       </property>
+      </column>
+      <column>
+       <property name="text">
+        <string>目标流量</string>
+       </property>
+      </column>
+      <column>
+       <property name="text">
+        <string>实时流量</string>
+       </property>
+      </column>
+      <column>
+       <property name="text">
+        <string>气体压力</string>
+       </property>
+      </column>
+      <column>
+       <property name="text">
+        <string>控制电流</string>
+       </property>
+      </column>
+      <column>
+       <property name="text">
+        <string>焊接工艺</string>
+       </property>
+      </column>
+      <column>
+       <property name="text">
+        <string>节气因子</string>
+       </property>
+      </column>
+      <column>
+       <property name="text">
+        <string>默认开度</string>
+       </property>
+      </column>
+      <column>
+       <property name="text">
+        <string>电流校准</string>
+       </property>
+      </column>
+      <column>
+       <property name="text">
+        <string>流量校准</string>
+       </property>
+      </column>
+      <item row="0" column="0">
+       <property name="text">
+        <string>0</string>
+       </property>
+      </item>
+      <item row="0" column="1">
+       <property name="text">
+        <string>0</string>
+       </property>
+      </item>
+      <item row="0" column="2">
+       <property name="text">
+        <string>0</string>
+       </property>
+      </item>
+      <item row="0" column="3">
+       <property name="text">
+        <string>0</string>
+       </property>
+      </item>
+      <item row="0" column="4">
+       <property name="text">
+        <string>0</string>
+       </property>
+      </item>
+      <item row="0" column="5">
+       <property name="text">
+        <string>0</string>
+       </property>
+      </item>
+      <item row="0" column="6">
+       <property name="text">
+        <string>0</string>
+       </property>
+      </item>
+      <item row="0" column="7">
+       <property name="text">
+        <string>0</string>
+       </property>
+      </item>
+      <item row="0" column="8">
+       <property name="text">
+        <string>0</string>
+       </property>
+      </item>
+      <item row="0" column="9">
+       <property name="text">
+        <string>0</string>
+       </property>
+      </item>
+      <item row="0" column="10">
+       <property name="text">
+        <string>0</string>
+       </property>
+      </item>
+     </widget>
+     <widget class="QPushButton" name="btn_connect_devinfo">
+      <property name="geometry">
+       <rect>
+        <x>10</x>
+        <y>0</y>
+        <width>71</width>
+        <height>61</height>
+       </rect>
+      </property>
+      <property name="text">
+       <string>连接</string>
+      </property>
+      <property name="autoDefault">
+       <bool>false</bool>
+      </property>
+     </widget>
+     <widget class="QGroupBox" name="groupBox">
+      <property name="geometry">
+       <rect>
+        <x>540</x>
+        <y>0</y>
+        <width>611</width>
+        <height>61</height>
+       </rect>
+      </property>
+      <property name="title">
+       <string>GroupBox</string>
+      </property>
+      <widget class="QPushButton" name="btn_debug_write">
+       <property name="geometry">
+        <rect>
+         <x>510</x>
+         <y>10</y>
+         <width>91</width>
+         <height>51</height>
+        </rect>
+       </property>
+       <property name="text">
+        <string>写入</string>
+       </property>
+      </widget>
+      <widget class="QLineEdit" name="lineEdit_debug_value">
+       <property name="geometry">
+        <rect>
+         <x>150</x>
+         <y>20</y>
+         <width>41</width>
+         <height>31</height>
+        </rect>
+       </property>
+       <property name="text">
+        <string>80</string>
+       </property>
+      </widget>
+      <widget class="QSlider" name="horizontalSlider">
+       <property name="geometry">
+        <rect>
+         <x>230</x>
+         <y>20</y>
+         <width>271</width>
+         <height>31</height>
+        </rect>
+       </property>
+       <property name="orientation">
+        <enum>Qt::Horizontal</enum>
+       </property>
+      </widget>
+      <widget class="QComboBox" name="cb_debug_mode">
+       <property name="geometry">
+        <rect>
+         <x>10</x>
+         <y>20</y>
+         <width>121</width>
+         <height>31</height>
+        </rect>
+       </property>
+       <property name="editable">
+        <bool>true</bool>
+       </property>
+       <property name="duplicatesEnabled">
+        <bool>false</bool>
+       </property>
+       <property name="frame">
+        <bool>true</bool>
+       </property>
+       <item>
+        <property name="text">
+         <string>关闭模拟调试</string>
+        </property>
+       </item>
+       <item>
+        <property name="text">
+         <string>模拟焊接电流</string>
+        </property>
+       </item>
+       <item>
+        <property name="text">
+         <string>比例阀控制电流</string>
+        </property>
+       </item>
+      </widget>
+      <widget class="QLabel" name="label_debug_curr_unit">
+       <property name="geometry">
+        <rect>
+         <x>200</x>
+         <y>20</y>
+         <width>21</width>
+         <height>31</height>
+        </rect>
+       </property>
+       <property name="text">
+        <string>A</string>
+       </property>
+      </widget>
+     </widget>
+     <widget class="QGroupBox" name="groupBox_4">
+      <property name="geometry">
+       <rect>
+        <x>90</x>
+        <y>0</y>
+        <width>441</width>
+        <height>61</height>
+       </rect>
+      </property>
+      <property name="title">
+       <string>GroupBox</string>
+      </property>
+      <widget class="QLabel" name="label_4">
+       <property name="geometry">
+        <rect>
+         <x>20</x>
+         <y>21</y>
+         <width>41</width>
+         <height>31</height>
+        </rect>
+       </property>
+       <property name="text">
+        <string>版本:</string>
+       </property>
+      </widget>
+      <widget class="QLabel" name="label_fw_ver">
+       <property name="geometry">
+        <rect>
+         <x>70</x>
+         <y>20</y>
+         <width>81</width>
+         <height>31</height>
+        </rect>
+       </property>
+       <property name="text">
+        <string>V1.0</string>
+       </property>
+      </widget>
+      <widget class="QLabel" name="label_5">
+       <property name="geometry">
+        <rect>
+         <x>190</x>
+         <y>20</y>
+         <width>41</width>
+         <height>31</height>
+        </rect>
+       </property>
+       <property name="text">
+        <string>UUID:</string>
+       </property>
+      </widget>
+      <widget class="QLineEdit" name="lineEdit_uuid">
+       <property name="geometry">
+        <rect>
+         <x>230</x>
+         <y>20</y>
+         <width>201</width>
+         <height>31</height>
+        </rect>
+       </property>
+       <property name="text">
+        <string>00000000-00000000-00000000</string>
+       </property>
+       <property name="readOnly">
+        <bool>true</bool>
+       </property>
+      </widget>
+     </widget>
+    </widget>
+    <widget class="QWidget" name="tab_2">
+     <attribute name="title">
+      <string>Tab 2</string>
+     </attribute>
+     <widget class="QFrame" name="frame_curr_raw">
+      <property name="geometry">
+       <rect>
+        <x>0</x>
+        <y>480</y>
+        <width>1151</width>
+        <height>321</height>
+       </rect>
+      </property>
+      <property name="frameShape">
+       <enum>QFrame::StyledPanel</enum>
+      </property>
+      <property name="frameShadow">
+       <enum>QFrame::Raised</enum>
+      </property>
+     </widget>
+     <widget class="QPushButton" name="btn_files_select">
+      <property name="geometry">
+       <rect>
+        <x>10</x>
+        <y>60</y>
+        <width>111</width>
+        <height>51</height>
+       </rect>
+      </property>
+      <property name="text">
+       <string>日志选择</string>
+      </property>
+     </widget>
+     <widget class="QListWidget" name="listWidget_log_files">
+      <property name="geometry">
+       <rect>
+        <x>130</x>
+        <y>0</y>
+        <width>931</width>
+        <height>471</height>
+       </rect>
+      </property>
+     </widget>
+     <widget class="QPushButton" name="btn_connect_curr">
+      <property name="geometry">
+       <rect>
+        <x>10</x>
+        <y>0</y>
+        <width>111</width>
+        <height>51</height>
+       </rect>
+      </property>
+      <property name="text">
+       <string>连接</string>
+      </property>
+     </widget>
+     <widget class="QPushButton" name="btn_files_clear">
+      <property name="geometry">
+       <rect>
+        <x>10</x>
+        <y>120</y>
+        <width>111</width>
+        <height>51</height>
+       </rect>
+      </property>
+      <property name="text">
+       <string>日志清除</string>
+      </property>
+     </widget>
+    </widget>
+    <widget class="QWidget" name="tab_3">
+     <attribute name="title">
+      <string>页</string>
+     </attribute>
+     <widget class="QGroupBox" name="groupBox_3">
+      <property name="geometry">
+       <rect>
+        <x>10</x>
+        <y>10</y>
+        <width>591</width>
+        <height>591</height>
+       </rect>
+      </property>
+      <property name="title">
+       <string>GroupBox</string>
+      </property>
+      <widget class="QLineEdit" name="lineEdit_image_addr">
+       <property name="geometry">
+        <rect>
+         <x>80</x>
+         <y>70</y>
+         <width>111</width>
+         <height>31</height>
+        </rect>
+       </property>
+      </widget>
+      <widget class="Line" name="line_3">
+       <property name="geometry">
+        <rect>
+         <x>10</x>
+         <y>140</y>
+         <width>571</width>
+         <height>20</height>
+        </rect>
+       </property>
+       <property name="orientation">
+        <enum>Qt::Horizontal</enum>
+       </property>
+      </widget>
+      <widget class="QLineEdit" name="lineEdit_fw_path">
+       <property name="geometry">
+        <rect>
+         <x>80</x>
+         <y>30</y>
+         <width>331</width>
+         <height>31</height>
+        </rect>
+       </property>
+      </widget>
+      <widget class="QPushButton" name="btn_select_fw">
+       <property name="geometry">
+        <rect>
+         <x>10</x>
+         <y>30</y>
+         <width>61</width>
+         <height>31</height>
+        </rect>
+       </property>
+       <property name="text">
+        <string>固件..</string>
+       </property>
+       <property name="autoDefault">
+        <bool>false</bool>
+       </property>
+      </widget>
+      <widget class="QLabel" name="label_3">
+       <property name="geometry">
+        <rect>
+         <x>210</x>
+         <y>70</y>
+         <width>91</width>
+         <height>31</height>
+        </rect>
+       </property>
+       <property name="text">
+        <string>数据包最大长度</string>
+       </property>
+      </widget>
+      <widget class="QPushButton" name="btn_download">
+       <property name="geometry">
+        <rect>
+         <x>420</x>
+         <y>30</y>
+         <width>161</width>
+         <height>101</height>
+        </rect>
+       </property>
+       <property name="text">
+        <string>下载</string>
+       </property>
+      </widget>
+      <widget class="QLineEdit" name="lineEdit_pkt_max_sz">
+       <property name="geometry">
+        <rect>
+         <x>310</x>
+         <y>70</y>
+         <width>101</width>
+         <height>31</height>
+        </rect>
+       </property>
+       <property name="text">
+        <string>1024</string>
+       </property>
+       <property name="dragEnabled">
+        <bool>false</bool>
+       </property>
+       <property name="readOnly">
+        <bool>false</bool>
+       </property>
+       <property name="clearButtonEnabled">
+        <bool>false</bool>
+       </property>
+      </widget>
+      <widget class="QTextEdit" name="update_log">
+       <property name="geometry">
+        <rect>
+         <x>10</x>
+         <y>160</y>
+         <width>571</width>
+         <height>421</height>
+        </rect>
+       </property>
+       <property name="inputMethodHints">
+        <set>Qt::ImhDigitsOnly</set>
+       </property>
+      </widget>
+      <widget class="QLabel" name="label_6">
+       <property name="geometry">
+        <rect>
+         <x>10</x>
+         <y>70</y>
+         <width>51</width>
+         <height>31</height>
+        </rect>
+       </property>
+       <property name="text">
+        <string>起始地址</string>
+       </property>
+      </widget>
+      <widget class="QProgressBar" name="progressBar">
+       <property name="geometry">
+        <rect>
+         <x>10</x>
+         <y>110</y>
+         <width>401</width>
+         <height>20</height>
+        </rect>
+       </property>
+       <property name="autoFillBackground">
+        <bool>false</bool>
+       </property>
+       <property name="value">
+        <number>0</number>
+       </property>
+       <property name="textVisible">
+        <bool>true</bool>
+       </property>
+       <property name="orientation">
+        <enum>Qt::Horizontal</enum>
+       </property>
+      </widget>
+     </widget>
+    </widget>
+    <widget class="QWidget" name="tab_4">
+     <attribute name="title">
+      <string>页</string>
+     </attribute>
+    </widget>
+   </widget>
+  </widget>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>
diff --git a/tools/yn_download.py b/tools/yn_download.py
new file mode 100644 (file)
index 0000000..9e5860e
--- /dev/null
@@ -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<img_sz:
+                       sz = img_sz-count
+                       if sz > 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)
+
index 0469e137fdc83dd4ab7b127431dfadb5bb40b0c9..d1708532a151d27fee90c205021420c1d0b3e9e2 100644 (file)
@@ -118,30 +118,42 @@ int main(void)
   /* USER CODE END SysInit */
 
   /* Initialize all configured peripherals */
+//----------
+  /* Initialize all configured peripherals */
   MX_GPIO_Init();
   MX_DMA_Init();
 
-  MX_SPI2_Init();
-  MX_USART1_UART_Init();
-  MX_USART2_UART_Init();
-  MX_USART6_UART_Init();
+//  MX_USART2_UART_Init();
+//  MX_SPI2_Init();
+//  MX_USART1_UART_Init();
+//  MX_ADC1_Init();
+//  MX_ADC2_Init();
+//  MX_ADC3_Init();
+//  MX_I2C2_Init();
+//  MX_USART6_UART_Init();
   MX_TIM13_Init();
-  MX_UART5_Init();
+//  MX_UART5_Init();
   MX_TIM2_Init();
-  MX_UART4_Init();
+//  MX_UART4_Init();
+  MX_OCTOSPI1_Init();
+///  MX_SDMMC1_SD_Init();
+  MX_TIM1_Init();
+//----------
+  if( user_sflash_init() ){
+      
+  }
 
-  sFLASH_Init();
     uint32_t download_flag = 0;
   if( *(uint32_t *)BOOT_MODE_LOAD_ADDR == 0x00505041 ){
       *(uint32_t *)BOOT_MODE_LOAD_ADDR = 0; //清除下载标志    download = 1;
       SCB_CleanDCache();
       download_flag = 1;
   }else{
-      *(uint32_t *)BOOT_MODE_LOAD_ADDR = *(uint32_t *)BOOT_MODE_LOAD_ADDR + 1;
+      *(uint32_t *)BOOT_MODE_LOAD_ADDR = *(uint32_t *)BOOT_MODE_LOAD_ADDR + 1; //for debug
   }
 
   if( !download_flag ){
-//      load_app();
+      load_app();
   }
 
   /* init code for USB_DEVICE */
index a8b5e42da8b8c40509c5eec40ef03d6e6b9bbe6a..aae2faa836a4c32f14232ef239c72db14821b9b3 100644 (file)
@@ -239,7 +239,7 @@ int32_t load_app( void )
       //暂忽略,待后续研究原因
   }
 
-  if( sFLASH_Init() < 0 )
+  if( user_sflash_init() < 0 )
       return -1;
 
   user_sflash_read( APP_INFO_PART_ADDR, (uint8_t*)&fw_info, sizeof( fw_info ) );
@@ -331,7 +331,7 @@ int32_t handle_cdc_pkt( cdc_pkt_t *pkt )
             tx_n = wrap_resp_pkt( tx_pkt, pkt->cmd, resp, 1 );
             fw.size = fw.addr = fw.crc16=0;
             break;
-        case 0xA1: //erase
+        case 0x0001: //erase
         {
             off = get_u32_big( pkt->pdata );
             sz = get_u32_big( pkt->pdata+4 );
@@ -345,7 +345,7 @@ int32_t handle_cdc_pkt( cdc_pkt_t *pkt )
             tx_n = wrap_resp_pkt( tx_pkt, pkt->cmd, resp, 1 );
             break;
         }
-        case 0xA2: //write
+        case 0x0002: //write
             off = get_u32_big( pkt->pdata );
             sz = pkt->data_len -4;
             if( user_sflash_write(APP_PART_ADDR+off-fw.addr, pkt->pdata+4, sz ) == 0)
@@ -354,7 +354,7 @@ int32_t handle_cdc_pkt( cdc_pkt_t *pkt )
                 resp[0] = 0; //fail
             tx_n = wrap_resp_pkt( tx_pkt, pkt->cmd, resp, 1 );
             break;
-        case 0xA4: //read crc
+        case 0x0003: //read crc
             off = get_u32_big( pkt->pdata );
             sz = get_u32_big( pkt->pdata+4 );
             user_sflash_read( APP_PART_ADDR, (uint8_t*)0x10, sz );
@@ -365,7 +365,7 @@ int32_t handle_cdc_pkt( cdc_pkt_t *pkt )
             fw.size = sz;
             fw.crc16 = crc;
             break;
-        case 0xA5: //reboot
+        case 0x0004: //reboot
         {
             fw.flag = APP_FLAG;
             user_sflash_erase( APP_INFO_PART_ADDR, APP_INFO_PART_SIZE );
index f22500fb39029cd9d92ab9dea33723968ba1e099..6ed2ee0d877b5b768621a4434feab2a51c147e90 100644 (file)
@@ -506,7 +506,7 @@ int32_t user_sflash_erase( uint32_t addr, uint32_t sz )
     user_sflash_lock();
 
     if( addr & (4*1024-1) ){
-        //æ\9a\82å\8fªæ\9c\80å°\8fæ\94¯æ\8c\81æ\8c\894Kå\9d\97æ\93¦é\99¤
+        //最小支持按4K块擦除
         ret = -1;
     }else{
         erase_sz = 0;