支持MCU和RN固件OTA更新
authorkyz <kongyuzhong@google.com>
Fri, 3 Jan 2025 08:25:50 +0000 (16:25 +0800)
committerkyz <kongyuzhong@google.com>
Tue, 7 Jan 2025 02:26:33 +0000 (10:26 +0800)
19 files changed:
STM32/IAR_project/F407_TCM.ewp
STM32/IAR_project/F407_TCM.ewt
STM32/code/app/App_RS485_1.c
STM32/code/app/main_task.c
STM32/code/app/rn2026.c
STM32/code/app/rn2026_upgrade.c
STM32/code/flat/Port.h
STM32/code/mcu_com/mcu_com.c
STM32/code/mcu_com/mcu_com_hard.c
STM32/code/mcu_com/mcu_com_hard.h
STM32/code/new_sensor/fun.h
STM32/code/protocol/protocol_modbus/protocol_modbus_rtu.c
STM32/code/protocol/protocol_modbus/protocol_modbus_rtu.h
STM32/win32/ZD_Download/demo.py [new file with mode: 0644]
STM32/win32/ZD_Download/demo.ui [new file with mode: 0644]
STM32/win32/ZD_Download/ser.py [new file with mode: 0644]
STM32/win32/ZD_Download/yn_download.py [new file with mode: 0644]
STM32/win32/zd_mk_img.exe
STM32/win32/zd_mk_img.py

index 3eccc054dc59cb522a2657de0a39eff5be9ad471..5e7a08d30ff23f2db81b60b19f74ce000b5d3aec 100644 (file)
         <file>
             <name>$PROJ_DIR$\..\code\mcu_com\mcu_com_hard.c</name>
         </file>
+        <file>
+            <name>$PROJ_DIR$\..\code\mcu_com\mcu_com_ota.c</name>
+        </file>
         <file>
             <name>$PROJ_DIR$\..\code\mcu_com\mcu_com_second_machine_sensor.c</name>
         </file>
index e48071fce8c1297fae45b9a603a6ade0abadaefe..4278c806c6972ae96509f6dd763bebe039fb4e0c 100644 (file)
         <file>
             <name>$PROJ_DIR$\..\code\mcu_com\mcu_com_hard.c</name>
         </file>
+        <file>
+            <name>$PROJ_DIR$\..\code\mcu_com\mcu_com_ota.c</name>
+        </file>
         <file>
             <name>$PROJ_DIR$\..\code\mcu_com\mcu_com_second_machine_sensor.c</name>
         </file>
index e6ffeff5e0298dede56004818f94199169edb0ec..86cd094a4b499ada20e8339ee1865df9cbfb431c 100644 (file)
@@ -59,6 +59,24 @@ void Task_RS485_2_sProtocol()
         }
                else
                {
+          ///ÁÙʱÔö¼Ó²âÊÔ´úÂ룬ͨ¹ý485½Ó¿Úµ÷ÊÔota´úÂ빦ÄÜ
+            static uint8_t tmp[1024];
+            uint8_t pos;
+            memcpy( tmp, frame, len );
+            if( true == ComHard_Uart_Get_Frame_Head(tmp, len, &pos)) // Ñ°ÕÒ°üÍ·
+            {
+                uint8_t*p = tmp + pos; //°üͷλÖÃ
+                uint16_t data_len = (p[4]<<8)|p[5];
+                uint16_t crc16 = p[data_len+6] |(p[data_len+7]<<8);
+                uint16_t cal_crc = ModBusCRC16(p, data_len+6);
+                if (cal_crc == crc16 && p[2] == MCUCOM_OTA )
+                {
+                    extern int32_t ota_data_handle( int32_t port, uint8_t cmd, uint8_t *data, uint16_t len );
+                    ota_data_handle( PORT_UART_IFACE_RS4852, p[3], &p[6], data_len );
+                }
+                return;
+            }
+          ///
                        printf("Protocl Not Recognized\n");
                }
         
index f6e7978e6f1551cca36b6bf37bf34fd1f664f7eb..0b4f8f4fb3a1af7678f8ae770142b1563da214a3 100644 (file)
@@ -40,6 +40,7 @@ extern tEngRamDbase s_Ram_eng;
 BOOL IF_UPADTING = FALSE;
 
 const uint8_t SW_VER[4] = { SW_VER_MAJOR, SW_VER_MINOR, 0, 0 };
+uint8_t RN_VER[4] = { 0, 0, 0, 0 };
 /*
        ¸´Î»»òÕßµôµçÒª´æ´¢µ±Ç°µôµçÊý¾Ý
 */
index e95f1b88772d6c22f831b5b9f6d4a7f24a90f9a6..a695a50e2384f973556aaaa36c49b67943d806d6 100644 (file)
@@ -409,6 +409,11 @@ int32_t Run_RN2026_Task( void )
     if( rn_info.id[0] == 0x20 && rn_info.id[1] == 0x26 ){\r
 \r
       if( (rn_info.csr & (1<<5) )==0 ){\r
+        \r
+            extern uint8_t RN_VER[4];\r
+            RN_VER[0] = rn_info.ver[0];\r
+            RN_VER[1] = rn_info.ver[1];\r
+\r
             regs_verify_para_t para_rd;\r
             printf( "--- RN SW VER: V%d.%d ---\n", rn_info.ver[0], rn_info.ver[1] );\r
             printf( "CSR:%02X, tx cal data to RN ...\n", rn_info.csr );\r
index e6a2b9f4fd870b328599be8d44b946f54944146b..bbd607b39300b87bab8b3c8472c8fe68eee01bf9 100644 (file)
@@ -11,7 +11,7 @@
 
 extern int32_t rn2026_read(  uint16_t reg_addr, uint8_t * rd_data, uint16_t rd_size );
 extern int32_t rn2026_write( uint16_t reg_addr, uint8_t * wr_data, uint16_t wr_size );
-extern uint16_t ModBusCRC16(uint8_t *buf, uint16_t len);
+extern uint16_t ModBusCRC16(uint8_t *buf, uint32_t len);
 
 static uint8_t cmd_sn = 0;
 static uint16_t wr_page = 0;
index f4106e0522e6693101821c135290162a2c804d4f..62aa5a7408ac08c907919ac4be79dbe6684ae0ab 100644 (file)
@@ -28,7 +28,7 @@ enum
     PORT_UART_IFACE_HOST = PORT_UART_IFACE_WIFI,
 };
 
-#define ONE_RX_FRAME_SIZE_MAX 300
+#define ONE_RX_FRAME_SIZE_MAX (300*2)
 #define PORT_FIFO_FRAME_NUM_MAX (2)
 
 /* ÕæÊµ¶Ë¿Ú½ÓÊÕFIFO */
index 2f56a4b543a69cd9f00959ebec04003f75aa21ba..a195dc05cd84c93d60bbf3b7975b30626058493f 100644 (file)
@@ -2104,3 +2104,11 @@ void McuCom_Send_disp_data_request( void )
     len = McuCom_Sensor_Packet( MCUCOM_SYNC_DISP_DATA, 0x01, &data, 1 );
     UART_Tx_One_Frame(PORT_UART_IFACE_WIFI, com_temp, len);
 }
+
+int32_t mcucom_ota_ack( int32_t port, uint8_t ota_cmd,  uint8_t *data, uint16_t data_sz )
+{
+    uint16_t len;
+
+    len = McuCom_Sensor_Packet( MCUCOM_OTA, ota_cmd, data, data_sz );
+    UART_Tx_One_Frame(port, com_temp, len);
+}
index 74a0a61495f55b6b0ea47da2298b7cbbe84e3322..a85d9cdc54a7d8805e43ed7d598743a53d06442e 100644 (file)
@@ -12,7 +12,7 @@
 // #include "wireless_temp.h"
 // mcuÏòarm·¢Ë͵Ĵ®¿Ú½ÓÊÕ½âÎö
 
-static uint8_t temp[512] = {0};
+static uint8_t temp[512*2] = {0};
 static BYTE mcu_com2_ota[1024];
 // Machine_Type_t Machine_Type;
 Mcu_Config_Enable_t Mcu_Config_Enable;
@@ -545,6 +545,12 @@ void ComHard_Uart2_Analy(void)
             p += 2;
             disp_data_sync( p, head_len );
             break;
+        case MCUCOM_OTA: //0x47 OTA ²Ù×÷
+            {
+                p += 2;
+                ota_data_handle( PORT_UART_IFACE_WIFI, McuCom_Head->sub_type,  p, head_len );
+            }
+            break;
         default:
             break;          
         }
index 8622010ffadc3b114e871cca148062552acb6536..df913428ef000be58de4bc6518d73a0af051b5ab 100644 (file)
@@ -175,6 +175,7 @@ typedef enum
     RN2026_ADJUST  = 0x44,  //У±íÖ¸Áî
     MCUCOM_24H_EVENT = 0x45, //ÉÏλ»úÐèÒªµÄ24Сʱ·¢ËÍÒ»¸ö֪ͨÊý¾Ý°ü¡£
     MCUCOM_SYNC_DISP_DATA = 0x46,
+    MCUCOM_OTA = 0x47,
 
 } ComHard_CmdType_E;
 
index 43bcd9390d1d31fd9cc60bfe85d33f0c07c53ee4..5f78fa6471a84b0df81dda8ddc0f91a6ca790a1b 100644 (file)
@@ -14,6 +14,6 @@ void buf_big_to_littles_int(uint32_t *data, uint8_t len);
 uint16_t little_tobig_uint16(uint16_t num);
 uint16_t big_to_littles_uint16(uint16_t be);
 void buf_big_to_littles_uint16(uint16_t *data, uint8_t len);
-uint16_t ModBusCRC16(uint8_t *buf, uint16_t len);
+uint16_t ModBusCRC16(uint8_t *buf, uint32_t len);
 
 #endif
index aac0ea6825ff36c26a6cfc8d40ac040aa585170a..d85f3290a34584115ab42ced02981fb15e20dd81 100644 (file)
@@ -32,10 +32,10 @@ static tMBFunctionList MB_FunCode_list[]={
 /*
        MODBUSУÑéËã·¨
 */
-WORD ModBusCRC16(BYTE * buf,WORD len)
+WORD ModBusCRC16(BYTE * buf, uint32_t len)
 {
        WORD rc=0xffff;
-       WORD i, j;
+       uint32_t i, j;
 
        for(i=0; i<len; i++)
        {
index 9c40837111633ce097a8895d3e14fab953ea5b34..e0e2ae707621166a1d2c913d3472578eea799ed2 100644 (file)
@@ -5,7 +5,7 @@
 
 #ifndef protocol_modbus_rtu_h
 #define protocol_modbus_rtu_h
-
+#include <stdint.h>
 /*
        ¹ØÓÚMODBUSµÄCRC Óеĵط½ÊDz»°üº¬Í·²¿2¸ö×Ö½ÚµÄ,ÓеÄÊǰüº¬µÄ.񻂿·Ö
 */
@@ -88,7 +88,7 @@ typedef struct
 /*
        MODBUSУÑéËã·¨
 */
-WORD ModBusCRC16(BYTE * buf,WORD len);
+WORD ModBusCRC16(BYTE * buf, uint32_t len);
 
 /*
        MODBUS¹æÔ¼´¦Àí
diff --git a/STM32/win32/ZD_Download/demo.py b/STM32/win32/ZD_Download/demo.py
new file mode 100644 (file)
index 0000000..6dc8868
--- /dev/null
@@ -0,0 +1,110 @@
+from collections import deque
+from re import L
+import socket
+import sys
+import os
+
+from PyQt5.QtCore import *
+from PyQt5.QtGui import *
+from PyQt5.QtWidgets import *
+
+import json
+import demo_ui as ui_demo
+import time
+import ser
+import yn_download
+
+import crcmod
+import struct
+import intelhex
+
+#生成CRC16-MODBUS校验码
+#crc16 = crcmod.mkCrcFun(0x18005, rev=True, initCrc=0xFFFF, xorOut=0x0000)
+from collections import deque
+
+class demoApp( QDialog, ui_demo.Ui_Dialog ):
+    def __init__( self ):
+        super().__init__()
+        self.setupUi(self)
+        self.setWindowTitle( u"中电智能终端固件下载 V1.0")
+        self.btn_select_file.released.connect( lambda :self.on_btn_sel_fw())
+        self.btn_download.released.connect( lambda :self.on_btn_download() )
+        self.io_timer = QTimer()
+        self.io_timer.timeout.connect(self.on_io_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( "115200" )
+
+    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_btn_sel_fw( self ):
+        file , _ = QFileDialog.getOpenFileName(None, u"选择固件", "", "bin files(*.bin);;All Files (*)")
+        if file:
+            self.lineEdit_path.setText( file )
+            #todo show img info
+ 
+    def on_btn_download( self ):
+        img_path =  self.lineEdit_path.text() 
+        port = self.cb_serial.currentText()
+        try:
+            baud = int( self.lineEdit_baud.text() )
+        except:
+            baud = None
+        try:
+            pkt_max_sz = int( self.lineEdit_pkt_max_sz.text() )
+        except:
+            pkt_max_sz = 512
+
+        if not img_path or not port or not baud :
+            print( 'get img path fail!' )
+            return
+        elif not os.path.exists( img_path ) or  not os.path.isfile( img_path ):
+            print( "valid img path")
+            return
+
+        self.yn_download = yn_download.yn_download( parent = self, image_path=img_path,  port=port, baudrate = baud, pkt_max_sz = pkt_max_sz )
+        if self.yn_download:
+            self.txt_log.clear()
+            self.btn_download.setEnabled(False)
+            self.yn_download.start()
+
+    def on_set_progress( self, v ):
+        self.progressBar.setValue( v ) 
+    def on_download_end(self):
+        self.btn_download.setEnabled(True)
+    def on_io_timer( self ):
+        self.scan_port()
+    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.txt_log.append( log_str )
+
+if __name__ == "__main__":
+    app = QApplication(sys.argv)  # 创建一个QApplication,也就是你要开发的软件app
+    ##x = telegraph()
+    #x.show()            # 执行QMainWindow的show()方法,显示这个QMainWindow
+    demo = demoApp()
+    demo.show()
+    sys.exit(app.exec_())          # 使用exit()或者点击关闭按钮退出QApplication
diff --git a/STM32/win32/ZD_Download/demo.ui b/STM32/win32/ZD_Download/demo.ui
new file mode 100644 (file)
index 0000000..ee12078
--- /dev/null
@@ -0,0 +1,226 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>Dialog</class>
+ <widget class="QDialog" name="Dialog">
+  <property name="windowModality">
+   <enum>Qt::NonModal</enum>
+  </property>
+  <property name="enabled">
+   <bool>true</bool>
+  </property>
+  <property name="geometry">
+   <rect>
+    <x>0</x>
+    <y>0</y>
+    <width>600</width>
+    <height>600</height>
+   </rect>
+  </property>
+  <property name="sizePolicy">
+   <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
+    <horstretch>0</horstretch>
+    <verstretch>0</verstretch>
+   </sizepolicy>
+  </property>
+  <property name="minimumSize">
+   <size>
+    <width>600</width>
+    <height>600</height>
+   </size>
+  </property>
+  <property name="maximumSize">
+   <size>
+    <width>600</width>
+    <height>600</height>
+   </size>
+  </property>
+  <property name="windowTitle">
+   <string>Dialog</string>
+  </property>
+  <property name="inputMethodHints">
+   <set>Qt::ImhPreferNumbers</set>
+  </property>
+  <property name="sizeGripEnabled">
+   <bool>false</bool>
+  </property>
+  <property name="modal">
+   <bool>false</bool>
+  </property>
+  <widget class="QLabel" name="label">
+   <property name="geometry">
+    <rect>
+     <x>20</x>
+     <y>10</y>
+     <width>51</width>
+     <height>31</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>串口号</string>
+   </property>
+  </widget>
+  <widget class="QTextEdit" name="txt_log">
+   <property name="geometry">
+    <rect>
+     <x>10</x>
+     <y>170</y>
+     <width>581</width>
+     <height>421</height>
+    </rect>
+   </property>
+   <property name="inputMethodHints">
+    <set>Qt::ImhDigitsOnly</set>
+   </property>
+  </widget>
+  <widget class="Line" name="line_3">
+   <property name="geometry">
+    <rect>
+     <x>0</x>
+     <y>150</y>
+     <width>601</width>
+     <height>20</height>
+    </rect>
+   </property>
+   <property name="orientation">
+    <enum>Qt::Horizontal</enum>
+   </property>
+  </widget>
+  <widget class="QPushButton" name="btn_download">
+   <property name="geometry">
+    <rect>
+     <x>430</x>
+     <y>10</y>
+     <width>161</width>
+     <height>131</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>下载</string>
+   </property>
+  </widget>
+  <widget class="QComboBox" name="cb_serial">
+   <property name="geometry">
+    <rect>
+     <x>80</x>
+     <y>10</y>
+     <width>161</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_2">
+   <property name="geometry">
+    <rect>
+     <x>260</x>
+     <y>10</y>
+     <width>41</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>130</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 class="QLineEdit" name="lineEdit_baud">
+   <property name="geometry">
+    <rect>
+     <x>312</x>
+     <y>10</y>
+     <width>101</width>
+     <height>31</height>
+    </rect>
+   </property>
+  </widget>
+  <widget class="QLineEdit" name="lineEdit_path">
+   <property name="geometry">
+    <rect>
+     <x>80</x>
+     <y>50</y>
+     <width>331</width>
+     <height>31</height>
+    </rect>
+   </property>
+  </widget>
+  <widget class="QPushButton" name="btn_select_file">
+   <property name="geometry">
+    <rect>
+     <x>10</x>
+     <y>50</y>
+     <width>61</width>
+     <height>31</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>固件..</string>
+   </property>
+  </widget>
+  <widget class="QLabel" name="label_3">
+   <property name="geometry">
+    <rect>
+     <x>210</x>
+     <y>90</y>
+     <width>91</width>
+     <height>31</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>数据包最大长度</string>
+   </property>
+  </widget>
+  <widget class="QLineEdit" name="lineEdit_pkt_max_sz">
+   <property name="geometry">
+    <rect>
+     <x>312</x>
+     <y>90</y>
+     <width>101</width>
+     <height>31</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>512</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>
+ <resources/>
+ <connections/>
+</ui>
diff --git a/STM32/win32/ZD_Download/ser.py b/STM32/win32/ZD_Download/ser.py
new file mode 100644 (file)
index 0000000..943286b
--- /dev/null
@@ -0,0 +1,101 @@
+#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 ):
+        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):
+        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/STM32/win32/ZD_Download/yn_download.py b/STM32/win32/ZD_Download/yn_download.py
new file mode 100644 (file)
index 0000000..f281a2f
--- /dev/null
@@ -0,0 +1,329 @@
+#! /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 *
+
+RN_IMG_FLAG   = 0x26204E52   # 'R' 'N' 0x20 0x26
+MCU_IMG_FLAG  = 0x0055434D   # 'MCU\0'
+
+APP_IMG_FLAG  = 0x00505041  # 'APP\0'
+BOOT_IMG_FLAG = 0x544F4F42 # 'BOOT'
+
+class yn_download(QThread):
+       trigger_end = pyqtSignal()
+       trigger_log = pyqtSignal( tuple )
+       trigger_pbar = pyqtSignal( int )
+       def  __init__( self,  parent,  image_path,  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.img_path = image_path
+               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.trigger_pbar.emit(0)
+               self.crc16 = crcmod.mkCrcFun(0x18005, rev=True, initCrc=0xFFFF, xorOut=0x0000)
+               self.img = ZD_Image( self.img_path)
+
+       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'' ):
+               #AA 55 47 01 00 01 01
+               pkt_data = bytes(  [0xAA, 0x55, 0x47, cmd ] )
+               pkt_data += struct.pack( ">H", len(data) )
+               pkt_data += data
+               crc_v = self.crc16( pkt_data ) 
+               pkt_data += struct.pack( "<H", crc_v )
+               return pkt_data
+
+       def wrap_ota_query_pkt( self ):
+               pkt_data = struct.pack( ">B", 1 )
+               return self.wrap_pkt( 1, pkt_data )
+
+       def wrap_ota_start_pkt( self  ):
+               pkt_data = struct.pack( ">BBBHLH", self.img.img_type,
+                                               self.img.img_ver[0],self.img.img_ver[1], 0,
+                                               self.img.img_raw_sz, self.img.img_raw_crc )
+               return self.wrap_pkt( 2, pkt_data )
+       
+       def wrap_ota_write_pkt( self, off, data ):
+               pkt_data = struct.pack( ">L", off )
+               pkt_data += data
+               return self.wrap_pkt( 3, pkt_data )
+       
+       def parse_image( self ):
+               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):
+               # AA 55 47 cmd(1B) LEN(2B) DATA(xB) CRC(2B)
+               d = self.rx_data
+               n=0
+               if len(d)>=6 and d[0]==0xAA and d[1] == 0x55:
+                       n = struct.unpack( ">H",d[4:6])[0]
+               else:
+                       return []
+               if len(d) >= n+8:
+                       pkt_crc = struct.unpack( "<H",d[n+6:n+8])[0]
+                       if pkt_crc == self.crc16( d[:n+6] ):
+                               return d[:n+6]
+                       else:
+                               print( 'rxpkt crc err!:', n, hex(pkt_crc), hex( self.crc16( d[:n+6] ) ) )
+               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, verbose=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
+                               elif verbose:
+                                       self.log_add( '数据传输超时!',  'error')
+                       except:
+                               if verbose:
+                                   self.log_add( '数据发送失败!',  'error')
+               return False
+
+       def read_mcu_ver( self, timeout=2 ):
+               resp = self.transmit(  tx=self.wrap_ota_query_pkt(),  timeout=2, retry=2, verbose=1 )
+               print( "tx resp:", resp )
+               if resp and len( self.rx_pkt)>=14  and self.rx_pkt[3] == 1:
+                       return  ( True, self.rx_pkt[6:8], self.rx_pkt[10:12] )
+               else:
+                       return( False, (0,0), (0,0)  )
+
+       def mcu_update_start( self, ):
+               resp = self.transmit(  tx=self.wrap_ota_start_pkt(),  timeout=5, retry=2, verbose=1 )
+               if resp and len( self.rx_pkt)>=7  and self.rx_pkt[6] == 1:
+                       return (True, 1 )
+               else:
+                       return (False, 0 )
+
+       def mcu_update_write( self, address, data ):
+               resp = self.transmit(  tx=self.wrap_ota_write_pkt( address,  data),  timeout=2, retry=2, verbose=1 )
+               if resp and len( self.rx_pkt)>=7  and self.rx_pkt[6] == 1:
+                       return (True, 1)
+               else:
+                       return (False, 1)
+
+       def update_stop( self ):
+               self.s.close()
+               self.trigger_end.emit()
+       def run(self ):
+               self.log_clear()
+               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
+
+               #1. read version
+               resp, ver_mcu, ver_rn = self.read_mcu_ver()
+               if resp:
+                       self.log_add( u"读取MCU版本 成功: MCU_V{}.{} RN_V{}.{}".format(ver_mcu[0], ver_mcu[1], ver_rn[0], ver_rn[1]), 'info' )
+                       if self.img.img_type == 1 and ver_mcu[0] == self.img.img_ver[0] and ver_mcu[0] == self.img.img_ver[0]:
+                               self.update_stop()
+                               self.log_add( u"MCU已是最新版本",'info' )
+                               return
+                       elif self.img.img_type == 2 and ver_rn[0] == self.img.img_ver[0] and ver_rn[0] == self.img.img_ver[0]:
+                               self.update_stop()
+                               self.log_add( u"RN已是最新版本",'info' )
+                               return
+                       else:
+                               pass
+               else:
+                       self.log_add( u"读取MCU版本 失败", 'error' )
+                       self.update_stop()
+                       return
+
+               #2. update request
+               resp, code = self.mcu_update_start()
+               self.log_add( u"固件更新请求 ,返回{},{}".format(resp, code), 'info' )
+               if not resp:
+                       self.s.close()
+                       self.trigger_end.emit()
+                       return
+               else:
+                       pass
+                       #return
+
+               #3. write img
+               writen = 0
+               self.log_add( u"开始下载", 'info' )
+               while writen < self.img.img_raw_sz:
+                       to_write = self.img.img_raw[writen:writen+512]
+                       resp,_ =  self.mcu_update_write(  writen, to_write )
+                       print( u"MCU update write {},".format( resp ))
+                       self.log_add( u"MCU update write {} - {},".format( writen,resp ), 'info' )
+                       if resp:
+                               writen += len(  to_write )
+                       else:
+                               print( "write img fail!" )
+                               break
+
+               #wait update finish
+               if writen < self.img.img_raw_sz:
+                       print( "write img ok, wait update ..." )
+               else:
+                       print( "write img fail!" )
+                       self.update_stop()
+                       return
+
+               time.sleep(5)
+               update = False
+               for i in range(5):
+                       time.sleep(2)
+                       update, ver_1, ver_2 = self.read_mcu_ver()
+                       if update and ver_1 ==  self.img.img_ver[0] and ver_2 == self.img.img_ver[2]:
+                               break
+               if update:
+                       print( "update image success!")
+               else:
+                       print( "mcu  update fail!")
+               self.update_stop()
+               return
+
+               self.log_add( '下载开始 ... %s'%(time.strftime('%H:%M:%S')), 'info' )
+               t0 = time.time()
+               self.log_add( "响应超时",  "error")
+               self.trigger_pbar.emit( cmd_n*100//len(pkgs))
+               self.log_add( "校验...", 'info' )
+               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( "校验错误, 固件CRC:%04X, 读取CRC:%04X"%( img_crc, flash_crc),  "error"  )
+               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
+
+
+class ZD_Image:
+    def __init__( self, img_path ):
+        self.img_type = 0
+        self.img_path = img_path
+        self.crc16 = crcmod.mkCrcFun(0x18005, rev=True, initCrc=0xFFFF, xorOut=0x0000)
+        with open( img_path, "rb" ) as fd:
+            self.img_raw = fd.read()
+            print( "image path:",  img_path,  "imgraw sz", len(self.img_raw) )
+            self.img_raw_sz = len( self.img_raw )
+            self.img_type, v_major, v_minor = self.get_ver( self.img_raw )
+            self.img_ver = ( v_major, v_minor )
+            self.img_raw_crc = self.crc16( self.img_raw)
+            print( "--calc img raw crc", hex(self.img_raw_crc))
+        if self.img_type == 1:
+            #MCU img
+            #img_sz = struct.unpack( "<L", self.img_raw[0x0218:0x021C])[0]
+            #img_flag, img_sz, img_crc = struct.unpack( "<LLL", self.img_raw[img_sz:img_sz+12])
+                       #print( "img info:", hex( ximg_flag), hex(ximg_sz), hex(ximg_crc) )
+            #check crc
+            #if self.crc16( self.img_raw ) == ximg_crc:
+            #    self.img_sz = ximg_sz
+            #    self.img_crc = ximg_crc
+            #    self.img_flag = ximg_flag
+            pass
+        elif self.img_type == 2:
+            #RN img
+            pass
+        else:
+            #error
+            pass
+        print( "ZD_Image init, img type:%d"%(self.img_type ) )
+    
+    def get_ver( self, img_raw ):
+        rn_flag, app_flag, ver_addr, table_start, table_end, vectors = struct.unpack( "<LLLLLL", img_raw[0x200:0x200+24] )
+        if rn_flag == MCU_IMG_FLAG and app_flag == APP_IMG_FLAG:
+            img_type = 1
+            ver_major,ver_minor = struct.unpack( "BB", img_raw[ ver_addr-vectors:ver_addr-vectors+2] )
+            return (img_type, ver_major, ver_minor )
+
+        img_raw = img_raw[0x200:]
+        rn_flag, app_flag, ver_addr, table_start, table_end, vectors = struct.unpack( "<LLLLLL", img_raw[0x200:0x200+24] )
+        if rn_flag == RN_IMG_FLAG and app_flag == APP_IMG_FLAG:
+            img_type = 2
+            print( "ver_addr, vectors:", hex(ver_addr), hex(vectors) )
+            print( "ver bytes:", img_raw[ ver_addr-vectors:ver_addr-vectors+2].hex())
+            ver_major,ver_minor = struct.unpack( "BB", img_raw[ ver_addr-vectors:ver_addr-vectors+2] )
+            return (img_type, ver_major, ver_minor )
+
+if __name__ == "__main__":
+       #d.download()
+       exit(0)
index 2aa4a5ddc285f0ed8e646bc53423dc8ba0e8c159..11526d73efbb61449aa02812a9e3597885bebacc 100644 (file)
Binary files a/STM32/win32/zd_mk_img.exe and b/STM32/win32/zd_mk_img.exe differ
index 0966f3fe4ca5c4663411b7bc0ac48bf3994547d2..efcd689c8aec05e7ff507098ef1a62fda440c953 100644 (file)
@@ -70,7 +70,10 @@ def mk_ota_img( fw_paths ):
                ver_major, ver_minor = struct.unpack( "BB", fw_raw[ ver_addr-vectors:ver_addr-vectors+2] )
                #ota文件在固件[0x218]填上img size,用来识别当前flash中固件是否烧入的是ota image。这个字段为0表示烧入的是原始编译生成的文件
                #在最后面追加3个字段:flag/size/crc, 用于固件有效校验
-               ota_img = fw_raw[:0x0218] +struct.pack( "L", len(fw_raw) ) +fw_raw[0x021c:] + struct.pack( "LLL",  MCU_IMG_FLAG, len(fw_raw), crc16( fw_raw ) )
+               ota_img = fw_raw[:0x0218] +struct.pack( "L", len(fw_raw) ) +fw_raw[0x021c:]
+               ota_data_crc = crc16( ota_img )
+               print( "ota_img, size:", hex( len(ota_img) ), "crc", hex( ota_data_crc ) )
+               ota_img += struct.pack( "<LLL",  MCU_IMG_FLAG, len(fw_raw), ota_data_crc )
                ota_img_name = os.path.splitext( fw_paths )[0] + '_V%d.%d_otaimg.bin'%( ver_major, ver_minor)
                return  ( ota_img_name, ota_img )
 
@@ -115,7 +118,7 @@ if __name__ == "__main__":
                fw_paths = sys.argv[1]
        else:
                fw_paths = filedialog.askopenfilename( initialdir=".", title="选择固件文件", filetypes=[("hex", ".hex"), ("bin","bin")], defaultextension=".hex", multiple=False )
-       print( "ZD 生成ota镜像文件工具 V1.0")
+       print( "ZD生成ota镜像工具 V1.0")
        print( "输入文件:", fw_paths)
        img_name, img_data = mk_ota_img( fw_paths )
        if not len(img_data):