支持通过WIFI完成ota升级
authorkyz <kongyuzhong@google.com>
Fri, 26 Apr 2024 08:19:47 +0000 (16:19 +0800)
committerkyz <kongyuzhong@google.com>
Fri, 26 Apr 2024 08:19:47 +0000 (16:19 +0800)
16 files changed:
Core/Inc/FreeRTOSConfig.h
Core/Inc/iwdg.h [new file with mode: 0644]
Core/Src/iwdg.c [new file with mode: 0644]
MDK-ARM/welding_controller_v2.sct [new file with mode: 0644]
MDK-ARM/welding_controller_v2.uvprojx
tools_v2/mk_ota_image.py [new file with mode: 0644]
tools_v2/test.py
tools_v2/test.ui
user/bootloader.c
user/ht1622.c
user/mbmCRC16.c
user/user.h
user/user_adc.c
user/user_ospi_flash.c
user/user_ota.c [new file with mode: 0644]
user/user_wifi.c

index 89015ab7bd11d90b69fd4510ed07301b4f96a4c8..bba88dbb5b132a3dcdb36ae254fc083eb1694b07 100644 (file)
@@ -68,7 +68,7 @@
 #define configTICK_RATE_HZ                       ((TickType_t)1000)
 #define configMAX_PRIORITIES                     ( 56 )
 #define configMINIMAL_STACK_SIZE                 ((uint16_t)128)
-#define configTOTAL_HEAP_SIZE                    ((size_t)15360)
+#define configTOTAL_HEAP_SIZE                    ((size_t)15360+20000)
 #define configMAX_TASK_NAME_LEN                  ( 16 )
 #define configUSE_TRACE_FACILITY                 1
 #define configUSE_16_BIT_TICKS                   0
diff --git a/Core/Inc/iwdg.h b/Core/Inc/iwdg.h
new file mode 100644 (file)
index 0000000..343c90e
--- /dev/null
@@ -0,0 +1,52 @@
+/* USER CODE BEGIN Header */
+/**
+  ******************************************************************************
+  * @file    iwdg.h
+  * @brief   This file contains all the function prototypes for
+  *          the iwdg.c file
+  ******************************************************************************
+  * @attention
+  *
+  * Copyright (c) 2024 STMicroelectronics.
+  * All rights reserved.
+  *
+  * This software is licensed under terms that can be found in the LICENSE file
+  * in the root directory of this software component.
+  * If no LICENSE file comes with this software, it is provided AS-IS.
+  *
+  ******************************************************************************
+  */
+/* USER CODE END Header */
+/* Define to prevent recursive inclusion -------------------------------------*/
+#ifndef __IWDG_H__
+#define __IWDG_H__
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Includes ------------------------------------------------------------------*/
+#include "main.h"
+
+/* USER CODE BEGIN Includes */
+
+/* USER CODE END Includes */
+
+extern IWDG_HandleTypeDef hiwdg1;
+
+/* USER CODE BEGIN Private defines */
+
+/* USER CODE END Private defines */
+
+void MX_IWDG1_Init(void);
+
+/* USER CODE BEGIN Prototypes */
+
+/* USER CODE END Prototypes */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __IWDG_H__ */
+
diff --git a/Core/Src/iwdg.c b/Core/Src/iwdg.c
new file mode 100644 (file)
index 0000000..26efa36
--- /dev/null
@@ -0,0 +1,56 @@
+/* USER CODE BEGIN Header */
+/**
+  ******************************************************************************
+  * @file    iwdg.c
+  * @brief   This file provides code for the configuration
+  *          of the IWDG instances.
+  ******************************************************************************
+  * @attention
+  *
+  * Copyright (c) 2024 STMicroelectronics.
+  * All rights reserved.
+  *
+  * This software is licensed under terms that can be found in the LICENSE file
+  * in the root directory of this software component.
+  * If no LICENSE file comes with this software, it is provided AS-IS.
+  *
+  ******************************************************************************
+  */
+/* USER CODE END Header */
+/* Includes ------------------------------------------------------------------*/
+#include "iwdg.h"
+
+/* USER CODE BEGIN 0 */
+
+/* USER CODE END 0 */
+
+IWDG_HandleTypeDef hiwdg1;
+
+/* IWDG1 init function */
+void MX_IWDG1_Init(void)
+{
+
+  /* USER CODE BEGIN IWDG1_Init 0 */
+
+  /* USER CODE END IWDG1_Init 0 */
+
+  /* USER CODE BEGIN IWDG1_Init 1 */
+
+  /* USER CODE END IWDG1_Init 1 */
+  hiwdg1.Instance = IWDG1;
+  hiwdg1.Init.Prescaler = IWDG_PRESCALER_32;
+  hiwdg1.Init.Window = 4000;
+  hiwdg1.Init.Reload = 4000;
+  if (HAL_IWDG_Init(&hiwdg1) != HAL_OK)
+  {
+    Error_Handler();
+  }
+  /* USER CODE BEGIN IWDG1_Init 2 */
+
+  /* USER CODE END IWDG1_Init 2 */
+
+}
+
+/* USER CODE BEGIN 1 */
+
+/* USER CODE END 1 */
diff --git a/MDK-ARM/welding_controller_v2.sct b/MDK-ARM/welding_controller_v2.sct
new file mode 100644 (file)
index 0000000..0f54b9a
--- /dev/null
@@ -0,0 +1,19 @@
+; *************************************************************
+; *** Scatter-Loading Description File generated by uVision ***
+; *************************************************************
+
+LR_IROM1 0x00001000 0x0003F000  {    ; load region size_region
+  ER_IROM1 0x00001000 0x0003F000  {  ; load address = execution address
+   *.o (RESET, +First)
+   *(InRoot$$Sections)
+   .ANY (+RO)
+   .ANY (+XO)
+  }
+  RW_IRAM2 0x24000000 0x00020000  {  ; RW data
+   .ANY (+RW +ZI)
+  }
+  RW_DTCM 0x20000000 0x00020000  {  ; RW data
+       *(.DTCM)
+  }
+}
+
index 7c12b8bdb59bdaba838b91275464e2a78d907056..886a6c1f48aca7defefd2442bf308fd957f8e4db 100644 (file)
             <TextAddressRange></TextAddressRange>
             <DataAddressRange></DataAddressRange>
             <pXoBase></pXoBase>
-            <ScatterFile>welding_controller_v2\welding_controller_v2.sct</ScatterFile>
+            <ScatterFile>welding_controller_v2.sct</ScatterFile>
             <IncludeLibs></IncludeLibs>
             <IncludeLibsPath></IncludeLibsPath>
             <Misc></Misc>
               <FileType>1</FileType>
               <FilePath>..\user\cJSON.c</FilePath>
             </File>
+            <File>
+              <FileName>user_ota.c</FileName>
+              <FileType>1</FileType>
+              <FilePath>..\user\user_ota.c</FilePath>
+            </File>
           </Files>
         </Group>
         <Group>
diff --git a/tools_v2/mk_ota_image.py b/tools_v2/mk_ota_image.py
new file mode 100644 (file)
index 0000000..70e9d00
--- /dev/null
@@ -0,0 +1,104 @@
+import re
+import struct
+s = '''
+ota固件, 编译生产bing文件 增加1K文件头
+文件头格式定义:
+长度一共1024字节,最后两个字节为文件头前面1022个字节的crc16校验
+所有多字节字段,按低字节在前
+2B  flag AA01
+2B  版本号, 主版本1B + 副版本1B
+2B  固件块长度最大507,每个块1024B
+2B  固件内容CRC16
+2B*507 数据块CRC16校验值, 
+2B 文件头校验CRC16
+'''
+import tkinter
+from tkinter import filedialog
+import crcmod
+import os
+import intelhex
+
+crc16 = crcmod.mkCrcFun(0x18005, rev=True, initCrc=0xFFFF, xorOut=0x0000)
+
+def mk_ota_img( fw_paths ):
+       print( "fw_paths:[%s]"%fw_paths)
+       fw_path, fw_name = os.path.split( fw_paths)
+
+       print( "--", os.path.splitext( fw_name ), "--" )
+       print( "file path{}, name{}".format( fw_path, fw_name  ) )
+       #file , check = QFileDialog.getOpenFileNames(None, u"选择固件", "", "All Files (202*)")
+       ota_img = b''
+       fw_raw = b''
+
+       ext = os.path.splitext( fw_name)[1]
+       print( "---------ext:", ext)
+       if ext and ext=='.hex':
+               #Hex file
+               print( "+++IntelHex ....")
+               ih = intelhex.IntelHex( fw_paths )
+               print( "---IntelHex ....")
+               image_addr = ih.minaddr()
+               print( "---IntelHex ....", image_addr)
+               fw_raw  = ih.tobinarray().tobytes()
+               print( "---IntelHex ....", len(fw_raw) )
+               #self.image_type = 'hex'
+       else:
+               with open( fw_paths, "rb" ) as fd:
+                       fw_raw = fd.read()
+
+       if len( fw_raw )> 1024:
+               flag, ver_addr, table_start, table_end, vectors = struct.unpack( "<LLLLL", fw_raw[0x400:0x400+20] )
+               ver_major, ver_minor = struct.unpack( ">BB", fw_raw[ ver_addr-vectors:ver_addr-vectors+2])
+               if flag != 0x00505041:
+                       print( "invalid ota image!")
+                       return ( '', b'' )
+               print( "flag: %08X, ver_addr:%08X-V%d.%d, vect:%08X"%( flag, ver_addr, ver_major, ver_minor, vectors ))
+
+               fw_len = len( fw_raw )
+               if fw_len %1024:
+                       fw_raw += b'\xff'*( 1024-fw_len%1024)
+               fw_blks = re.findall( b'[\s\S]{1024}', fw_raw )
+               #ota 文件头信息定义 1024字节
+               ota_head_info = '''
+                       typedef struct{
+                               uint16_t flag; //AA01
+                               uint8_t ver[2]; //major, minor
+                               uint16_t blks;  //1024
+                               uint16_t blk_sz;
+                               uint16_t fw_crc; //后面固件填充FF到按1024对齐, 然后计算得到的crc16
+                               uint16_t reserved; //填充
+                               uint32_t load_addr;  
+                               uint16_t blks_crc[256];
+                               uint16_t reserved[256-9]; //填充到1024大小
+                               uint16_t head_crc;
+                       }fw_header_t;
+               '''
+               ota_img += struct.pack( '<HBBHHHHL',
+                                                0xAA01,
+                                                ver_major,ver_minor,
+                                                len(fw_blks),
+                                                1024, #blk size
+                                                crc16( fw_raw),
+                                                0, #reserved
+                                                vectors #load addr
+                                                )
+               for b in fw_blks:
+                       ota_img += struct.pack( '<H', crc16( b ) )
+               ota_img += b'\xFF'*(1024-len(ota_img) - 2)
+               ota_img += struct.pack( '<H', crc16( ota_img ) )
+               print( "ota head[%d]:"%len( ota_img), ota_img[:16].hex())
+               ota_img += fw_raw
+               ota_img_name = os.path.splitext( fw_name )[0] + '_V%d.%d_otaimg.bin'%( ver_major, ver_minor)
+               return  ( ota_img_name, ota_img )
+
+
+if __name__ == "__main__":
+       #d.download()
+       fw_paths = filedialog.askopenfilename(title="选择固件文件", filetypes=[("bin", ".bin"), ("hex", ".hex")], defaultextension=".hex", multiple=False )
+       img_name, img_data = mk_ota_img( fw_paths )
+       img_path = filedialog.asksaveasfilename( title="保存文件", initialfile=img_name, filetypes=[("bin", ".bin")], defaultextension=".bin" )
+       print( "mk ota img, save as {}, len:{}".format( img_name, len(img_data)))
+       with open( img_path, "wb" ) as ota_fd:
+               print( "save ota img len:%d/%08X Bytes"%( len(img_data), len( img_data)))
+               ota_fd.write( img_data )
+       exit(0)
\ No newline at end of file
index 39aa76cf3d6271ab94ce86a1a565f4d2e58cb37a..2a5683c6eed8dafc49100f66420076853d60b5d2 100644 (file)
@@ -27,6 +27,7 @@ import crcmod
 import struct
 import intelhex
 import yn_download
+import mk_ota_image
 
 #生成CRC16-MODBUS校验码
 #crc16 = crcmod.mkCrcFun(0x18005, rev=True, initCrc=0xFFFF, xorOut=0x0000)
@@ -39,7 +40,7 @@ class App( QDialog, ui_welding.Ui_Dialog ):
     def __init__( self ):
         super().__init__()
         self.setupUi(self)
-        self.setWindowTitle( u"焊接控制器调试工具 V0.2")
+        self.setWindowTitle( u"焊接控制器调试工具 V0.3")
 
         self.trigger_rx_pkt.connect( self.on_rx_pkt )
 
@@ -93,6 +94,19 @@ class App( QDialog, ui_welding.Ui_Dialog ):
         self.btn_iot_cfg_read.released.connect( lambda: self.on_btn_cfg_read( 4 ) )
         self.btn_iot_cfg_write.released.connect( lambda: self.on_btn_cfg_write( 4 ) )
 
+        self.btn_mk_ota_img.released.connect( self.on_btn_mk_ota_img )
+
+    def on_btn_mk_ota_img(self):
+        file , check = QFileDialog.getOpenFileName(None, u"选择固件", "", "image (*hex *bin)")
+        print("select fw file:{}, check:{}".format( file, check) )
+        img_name, img_data = mk_ota_image.mk_ota_img( file )
+        if len( img_name) and len(img_data):
+            save_name, check = QFileDialog.getSaveFileName(None, u"保存OTA文件", img_name, "ota image ( *bin)")
+            print( "save as {}, check:{}".format( save_name, check))
+            with open( save_name, "wb" ) as ota_fd:
+                print( "save file:%s len:%d/%08X Bytes"%( save_name, len(img_data), len( img_data)))
+                ota_fd.write( img_data )
+
     def on_btn_cfg_read( self, cfg ):
         if self.connected != 0 or self.ser_opened:
             return
index 62fcbe0746bb432e11841c50cfdf9ace1ef717fc..0ea53bf40032072b46123bbe7ee3fce21bacaeca 100644 (file)
      </rect>
     </property>
     <property name="currentIndex">
-     <number>3</number>
+     <number>2</number>
     </property>
     <widget class="QWidget" name="tab">
      <attribute name="title">
        </property>
       </widget>
      </widget>
+     <widget class="QPushButton" name="btn_mk_ota_img">
+      <property name="geometry">
+       <rect>
+        <x>10</x>
+        <y>700</y>
+        <width>121</width>
+        <height>41</height>
+       </rect>
+      </property>
+      <property name="text">
+       <string>创建ota升级文件</string>
+      </property>
+      <property name="autoDefault">
+       <bool>false</bool>
+      </property>
+     </widget>
     </widget>
     <widget class="QWidget" name="tab_4">
      <attribute name="title">
index 31dceab576f888d1378ab95b58571f0f73d50e41..4de025bf76cc7f9d9f08b3d6a098cff9b33134ce 100644 (file)
@@ -345,4 +345,6 @@ uint16_t user_crc16( uint8_t *data, uint32_t length )
 }
 
 ETH_HandleTypeDef heth;
-void HAL_ETH_IRQHandler( ETH_HandleTypeDef * unused){ return;}
\ No newline at end of file
+SD_HandleTypeDef hsd1;
+void HAL_ETH_IRQHandler( ETH_HandleTypeDef * unused){ return;}
+void HAL_SD_IRQHandler( SD_HandleTypeDef *handle ){ return; }
\ No newline at end of file
index 3931ae3c2f175be57cf5d024916ad5c7d3f15cda..b365aadeed48aa40bf812b3c90c694d869837ed7 100644 (file)
@@ -81,14 +81,14 @@ COMMAND  100
 #define CMD_VALUE_12B( cmd_8b )  ( (0x04<<9)|((cmd_8b)<<1) )
 
 
-#define ht1622_cs_l() 
-#define ht1622_cs_h() 
-#define ht1622_rd_clk_l() 
-#define ht1622_rd_clk_h() 
-#define ht1622_wr_clk_l() 
-#define ht1622_wr_clk_h() 
-#define ht1622_data_out_l() 
-#define ht1622_data_out_h() 
+#define ht1622_cs_l()
+#define ht1622_cs_h()
+#define ht1622_rd_clk_l()
+#define ht1622_rd_clk_h()
+#define ht1622_wr_clk_l()
+#define ht1622_wr_clk_h()
+#define ht1622_data_out_l()
+#define ht1622_data_out_h()
 
 #define ht1622_data_read()  0
 
index 278019257165a0436a55aa475059911fac5c8534..a2fa2bea571bd3008dec0cb60cd3df4d9de35931 100644 (file)
@@ -115,4 +115,19 @@ uint16_t mbm_CRC16Calc(uint8_t *data, uint32_t length)
   return (uint16_t) (crcHI << 8 | crcLO);
 }
 
+uint16_t mbm_crc16( uint16_t init, uint8_t *data, uint32_t length)
+{
+  uint8_t crcHI = (init>>8)&0xFF;
+  uint8_t crcLO = init&0xFF;
+  int32_t index;
+  
+  while (length--) {
+    index = crcLO ^ *(data++);
+    crcLO = (uint8_t) (crcHI ^ CRC16_HI[index]);
+    crcHI = CRC16_LO[index];
+  }
+  
+  return (uint16_t) (crcHI << 8 | crcLO);
+}
+
 /*@}*/
index 6ae904347e8636824db5c6412ef58c4596be0515..51436f8f9cc0199be97f50a9132db3469eaeba45 100644 (file)
@@ -65,8 +65,10 @@ void  debug_printf(char* str , ...);
 #define SYS_INFO_PART_SIZE   0x00010000  //+64K
 //用户数据
 #define USER_DATA_PART_ADDR  0x00100000  //1M
-#define USER_DATA_PART_SIZE  0x00300000  //+3M
-
+#define USER_DATA_PART_SIZE  0x00280000  //+2.5M
+//OTA存储区
+#define OTA_PART_ADDR        0x00380000  //3.5M
+#define OTA_PART_SIZE        0x00080000  //+512K
 
 
 typedef struct{
index 014041a813ccc3a27929910731851a0546ef18df..5930c21f843c72fdf988346c95a395a6a623d15f 100644 (file)
@@ -21,9 +21,10 @@ ALIGN_32BYTES (static uint16_t adc3_raw[(ADC3_RAW_NRS+15)&~15] ); //采集100次
 static uint16_t adc1_raw_copy[ADC1_RAW_NRS];
 static uint16_t adc3_raw_copy[ADC3_RAW_NRS];
 
-__attribute__((at(0x20005000))) static uint16_t        adc2_raw_copy[ADC2_RAW_NRS];
-__attribute__((at(0x20000000))) static float adc2_curr[ADC2_RAW_NRS];
-
+//__attribute__((at(0x20005000))) static uint16_t      adc2_raw_copy[ADC2_RAW_NRS];
+//__attribute__((at(0x20000000))) static float adc2_curr[ADC2_RAW_NRS];
+__attribute__((section(".DTCM")))  static uint16_t     adc2_raw_copy[ADC2_RAW_NRS];
+__attribute__((section(".DTCM"))) static float adc2_curr[ADC2_RAW_NRS];
 extern dev_info_t g_dev;
 
 void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc)
index 6ed2ee0d877b5b768621a4434feab2a51c147e90..62313a550fad31350946f31dba87516d88cb5fc6 100644 (file)
@@ -580,3 +580,32 @@ int32_t user_sflash_read( uint32_t addr, uint8_t *data, uint32_t sz )
     return ret;
 }
 
+extern uint16_t mbm_crc16( uint16_t init, uint8_t *data, uint32_t length);
+uint16_t user_sflash_crc( uint32_t addr, uint32_t sz )
+{
+               uint8_t data[256];
+               uint16_t crc = 0xffff;
+
+    if( sflash_init ){
+                       user_sflash_lock();
+                       for( int i=0; i<sz; i+= sizeof(data) ){
+                               OSPI_ReadBuffer( data, addr+i, sizeof( data ) );
+                               crc = mbm_crc16( crc, data, sz-i>=sizeof(data)?sizeof(data):sz-i );
+                       }
+                       user_sflash_unlock();
+               }
+    return crc;
+}
+
+int32_t user_sflash_copy( uint32_t dst, uint32_t src, uint32_t sz )
+{
+               uint8_t data[256];
+
+    if( sflash_init ){
+                       for( int i=0; i<sz; i+= sizeof(data) ){
+                               user_sflash_read( src+i, data, sizeof(data) );
+                               user_sflash_write( dst+i, data, sizeof(data) );
+                       }
+               }
+         return 0;
+}
diff --git a/user/user_ota.c b/user/user_ota.c
new file mode 100644 (file)
index 0000000..290ad69
--- /dev/null
@@ -0,0 +1,378 @@
+#include "user.h"
+//-----------------------------------------------------------------------------------------------------------------------//
+
+#define OTA_LINK_WIFI 0
+#define OTA_LINK_ETH  1
+
+#define OTA_FW_HEAD_FLAG  0xAA01
+       
+#define get_fmt "\
+GET %s HTTP/1.0\r\n\
+Host:%s:%d\r\n\
+Range:bytes=%d-%d\r\n\
+Connection:keep-alive\r\n\r\n"
+
+extern int32_t wifi_ota_requst( char *host, uint16_t port, char *req );
+extern void wifi_ota_close( void );
+extern uint16_t user_sflash_crc( uint32_t addr, uint32_t sz );
+extern int32_t user_sflash_copy( uint32_t dst, uint32_t src, uint32_t sz );
+
+static int32_t ota_url_parse( char* ota_url );
+static void ota_task( void * unused );
+
+typedef struct{
+    uint16_t flag;
+    uint8_t ver[2];
+    uint16_t blks;
+               uint16_t blk_sz;
+    uint16_t fw_crc;
+               uint16_t reserved; //填充
+               uint32_t load_addr;  
+
+    uint16_t blks_crc[256];
+    uint16_t reserved_2[256-9]; //填充到1024大小
+    uint16_t head_crc;
+}fw_header_t;
+
+typedef struct{
+    uint32_t keepalive;   //Connection:keep-alive/close
+    uint32_t range_start; //Content-Range: bytes %d-%d/%d
+    uint32_t range_end;
+    uint32_t range_total;
+
+    uint32_t data_len;
+    uint8_t data[1024];
+}fw_blk_t;
+
+typedef struct{
+    char url[256];
+    osThreadId_t task;
+
+    char host[100];
+    char path[200];
+    uint16_t port;
+
+    uint32_t fw_size;
+    uint32_t fw_received;
+    uint32_t link; //0-wifi, 1-eth
+    uint32_t tcp_connected;
+
+    uint32_t start_time; //ms
+
+    fw_header_t fw_head;
+    fw_blk_t blk_info;
+         int32_t resp;
+}ota_t;
+
+static const osThreadAttr_t otaTask_attributes = {
+  .name = "otaTask",
+  .stack_size = 2048,
+  .priority = (osPriority_t) osPriorityNormal,
+};
+
+__attribute__((section(".DTCM"))) static ota_t g_ota;
+
+
+int32_t ota_start( uint32_t link, char * url, char *ver )
+{
+    if( link != OTA_LINK_WIFI && link != OTA_LINK_ETH ){
+        return -1;
+    } 
+
+    if( g_ota.task ){
+        //busy
+        return -1;
+    }
+
+    memset( &g_ota, 0, sizeof( g_ota ) );
+
+    if( ota_url_parse( url ) < 0 ){
+        return -1;
+    }
+
+    //create task
+    g_ota.link = link;
+    g_ota.task = osThreadNew(ota_task, NULL, &otaTask_attributes);
+    if( !g_ota.task ){
+        return -1;
+    }
+    return 0;
+}
+
+int32_t wifi_ota_start( char * url, char *ver )
+{
+       return ota_start( OTA_LINK_WIFI, url, ver );
+}
+
+int32_t eth_ota_start( char * url, char *ver )
+{
+       return ota_start( OTA_LINK_ETH, url, ver );
+}
+
+int32_t ota_handle_http_resp( uint8_t *rx_data, uint32_t rx_sz )
+{
+       //http_resp_flag = 1;
+       char *s;
+       uint8_t *content_data;
+       uint32_t content_sz;
+       uint32_t range_start;
+       uint32_t range_end;
+       uint32_t range_total;
+       uint32_t keepalive;
+       int32_t ret = -1;
+
+       if( strstr( (char*)rx_data, "404 Not Found" ) ){
+               g_ota.resp = -1;
+               return -1;
+       }
+               
+       s=strstr( (char*)rx_data, "Content-Range:" );
+       if( s && sscanf( s, "Content-Range: bytes %d-%d/%d", &range_start, &range_end, &range_total ) == 3 ){
+
+               debug_printf( "recv range:%d-%d/%d\n", range_start, range_end, range_total );
+               if( strstr( (char*)rx_data, "Connection: Close" ) ){
+                       keepalive = 0;
+               }else{
+                       keepalive = 1;
+               }
+
+               s = strstr( (char*)rx_data, "\r\n\r\n" );
+               if( s ){
+
+                       content_data = (uint8_t*)(s+4);
+                       uint32_t head_sz = (uint32_t)content_data-(uint32_t)rx_data;
+                       content_sz = rx_sz - head_sz;
+                       debug_printf( "rx content size: %d\n", content_sz );
+                       if(content_sz == range_end-range_start+1 ){
+                                       g_ota.blk_info.range_start  = range_start;
+                                       g_ota.blk_info.range_end = range_end;
+                                       g_ota.blk_info.range_total = range_total;
+                                       g_ota.blk_info.keepalive = keepalive;
+                                       memcpy( g_ota.blk_info.data, content_data, content_sz );
+                                       g_ota.blk_info.data_len = content_sz;
+                                       g_ota.resp = content_sz;
+                                       ret = 0;
+                       }
+               }
+       }
+       return ret;
+}
+
+int32_t http_close( void )
+{
+       if(g_ota.link == OTA_LINK_WIFI ){
+               wifi_ota_close();
+       }else if(g_ota.link == OTA_LINK_ETH ){
+               //eth_ota_close();
+       }
+       return 0;
+}
+
+int32_t http_get_blk( void )
+{
+    char http_req[200];
+    uint32_t tick;
+
+               uint32_t range_start;
+               int32_t ret=0;
+
+               range_start = g_ota.fw_received;
+
+               sprintf( http_req, get_fmt, g_ota.path, g_ota.host, g_ota.port, range_start, range_start+1024-1 );
+               g_ota.blk_info.data_len = 0;
+       
+               g_ota.resp = 0;
+    if( g_ota.link == OTA_LINK_WIFI ){
+                        ret = wifi_ota_requst( g_ota.host, g_ota.port, http_req );
+                        if(ret < 0){
+                                 //tcp connect fail, ota fail
+                                 return ret;
+                        }
+    }else if( g_ota.link == OTA_LINK_ETH ){
+                         //ret = eth_ota_requst( g_ota.host, g_ota.port, http_req );
+                         //if(ret < 0){
+                                 //tcp connect fail, ota fail
+                                 //return ret;
+                         //}
+                         return -1;
+    }else{
+                         return -1;
+               }
+
+    tick = xTaskGetTickCount();
+    while( xTaskGetTickCount() - tick < 10*1000 && !g_ota.resp ){
+    }
+
+    if( g_ota.resp ){
+        return 0;
+    }
+    return -1;
+}
+
+static int32_t is_valid_fw( fw_header_t *head )
+{
+               uint16_t crc;
+
+               if( !head )
+                       return 0;
+
+               if( head->flag != OTA_FW_HEAD_FLAG ){
+                       debug_printf( "invalid fw,  head flag:%04X\n", head->flag );
+                       return 0;
+               }
+
+               crc = user_crc16( g_ota.blk_info.data, sizeof(fw_header_t)-2 );
+               if(crc != head->head_crc ){
+                               debug_printf( "head crc fail: calc:%04X/ head:%04X!\n", crc, head->head_crc ); 
+                               return 0;
+               }
+
+               if( head->blk_sz* head->blks > 256*1024 ){
+                       //itcm最大256K, 固件加载在itcm运行, 最大只能支持256K
+                       debug_printf( "invalid fw, blks:%d x blk_sz:%d fwsize:%dK\n", head->blks, head->blk_sz, head->blks * head->blk_sz );
+                       return 0;
+               }
+               return 1;
+}
+
+static int32_t ota_url_parse( char* ota_url )
+{
+    //http://www.test.com:80/path/file.bin
+    //http://www.test.com/path/file.bin
+    char * url;
+    char *path;
+    char host[100];
+    uint16_t port;
+
+    if( strstr( ota_url, "https://" ) )
+        return -1;
+
+    url = strstr( ota_url, "http://" );
+    if( url )
+        url+=7;
+
+    port = 80;
+    if( sscanf( url, "%[^/:]:%hd", host, &port ) < 1 ){
+        return -1;
+    }
+
+    path = strstr( url, "/");
+    if( !path ){
+        return -1;
+    }
+
+    strcpy( g_ota.url,  ota_url );
+    strcpy( g_ota.host, host );
+    strcpy( g_ota.path, path );
+    g_ota.port = port;
+
+    return 0;
+}
+
+static void ota_task( void * unused )
+{
+    uint32_t blk;
+               uint32_t blk_sz;
+         int32_t ret;
+               int32_t err_cnt = 0;
+
+               g_ota.start_time = xTaskGetTickCount();
+    while( xTaskGetTickCount()-g_ota.start_time < 5*60*1000 ){ //总共5分钟超时
+
+        if( http_get_blk() == 0 ){
+                                               if( g_ota.resp<0){
+                                                               if( err_cnt++ < 3 ){
+                                                                                       debug_printf( "ota task: 404 Not Found-%d, retry!\n", err_cnt );
+                                                                                       continue;
+                                                                       }
+                                                                       debug_printf( "ota task: get head fail-%d, exit!\n", err_cnt );
+                                                                       break;
+                                               }
+            if( g_ota.fw_received == 0 ){
+                //blk_head
+                if( g_ota.blk_info.range_start == 0 ){
+                    memcpy( (uint8_t*)&g_ota.fw_head, g_ota.blk_info.data, 1024 );
+
+                                                                               //获取第一块数据是固件头信息,检查是否有效
+                                                                         if( !is_valid_fw( &g_ota.fw_head ) ){
+                                                                                               if( err_cnt++ < 10 ){
+                                                                                                       //重试
+                                                                                                       debug_printf( "ota task: get head fail-%d, retry:%d!\n", err_cnt);
+                                                                                                       continue;
+                                                                                               }else{
+                                                                                                       //多次尝试试失败,退出ota任务
+                                                                                                       debug_printf( "ota task: get head fail-%d, exit!\n", err_cnt );
+                                                                                                       break;
+                                                                                               }
+                                                                               }
+
+                                                                               err_cnt = 0;
+                                                                               if(g_ota.fw_head.ver[0] == APP_VER_MAJOR && g_ota.fw_head.ver[1] == APP_VER_MINOR ){
+                                                                                               //固件版本和当前一样,退出ota任务
+                                                                                               debug_printf( "ota task: fw ver V%d.%d, exit\n", g_ota.fw_head.ver[0], g_ota.fw_head.ver[1] );
+                                                                                               break;
+                                                                               }
+
+                    g_ota.fw_size = g_ota.blk_info.range_total;
+                                                                               //eraes flash ota part 
+                                                                               debug_printf( "erase ota spiflash %08X, -size:%08X\n", OTA_PART_ADDR, g_ota.fw_size );
+                                                                               ret = user_sflash_erase( OTA_PART_ADDR, g_ota.fw_size );
+                                                                               debug_printf( "erase flash ret:%d\n", ret );
+
+                                                                               debug_printf( "write ota spiflash blk[i], addr:%08X, -size:%08X\n", blk-1, OTA_PART_ADDR+g_ota.fw_received, g_ota.blk_info.data_len );
+                                                                               ret = user_sflash_write( OTA_PART_ADDR+g_ota.fw_received, g_ota.blk_info.data, g_ota.blk_info.data_len );
+                                                                               debug_printf( "write flash ret:%d\n", ret );
+
+                                                                               g_ota.fw_received += g_ota.blk_info.data_len;
+                }
+            }else{
+                                                               blk_sz = g_ota.fw_head.blk_sz;
+                                                               blk = g_ota.fw_received/blk_sz;
+                if( g_ota.fw_received == g_ota.blk_info.range_start){
+                                                                       uint16_t crc1 = user_crc16( g_ota.blk_info.data, blk_sz );
+                                                                       uint16_t crc2 = g_ota.fw_head.blks_crc[blk-1];
+                                                                       if(crc1 == crc2 ){
+
+                                                                                 debug_printf( "write ota spiflash blk[%d], addr:%08X, -size:%08X\n", blk-1, OTA_PART_ADDR+g_ota.fw_received, g_ota.blk_info.data_len );
+                                                                                       ret = user_sflash_write( OTA_PART_ADDR+g_ota.fw_received, g_ota.blk_info.data, g_ota.blk_info.data_len );
+                                                                                 debug_printf( "write flash ret:%d\n", ret );
+
+                                                                                       g_ota.fw_received += g_ota.blk_info.data_len;
+                                                                                 debug_printf( "ota received blk[%d], sz:%d\n", blk, g_ota.fw_received );
+                                                                                 //TODO: write flash
+                                                                                 if( g_ota.fw_received == g_ota.fw_size ){//下载完成
+
+                                                                                               uint16_t crc = user_sflash_crc( OTA_PART_ADDR+blk_sz, g_ota.fw_size-blk_sz ); //skip fw_head_info
+                                                                                               debug_printf( "ota:success, flash_crc:%04X, fw_crc:%04X\n", crc, g_ota.fw_head.fw_crc );
+                                                                                               //TODO copy data from ota part to app part
+                                                                                               if( crc == g_ota.fw_head.fw_crc ){
+                                                                                                       uint32_t fwinfo[4];
+                                                                                                       fwinfo[0] = 0x31505041; //flag
+                                                                                                       fwinfo[1] = g_ota.fw_size-blk_sz;//size - head;
+                                                                                                       fwinfo[2] = 0x1000; //addr;
+                                                                                                       fwinfo[3] = crc; //crc16;
+                                                                                                       //app part erase
+                                                                                                       user_sflash_erase( APP_PART_ADDR, APP_PART_SIZE );
+                                                                                                       //app part copy
+                                                                                                       user_sflash_copy( APP_PART_ADDR, OTA_PART_ADDR+1024, g_ota.fw_size - 1024 );
+                                                                                                       crc = user_sflash_crc( APP_PART_ADDR, g_ota.fw_size-1024 );
+                                                                                                       debug_printf( "app part crc:%04X\n", crc );
+                                                                                                       user_sflash_erase( APP_INFO_PART_ADDR, APP_INFO_PART_SIZE );
+                                                                                                       user_sflash_write( APP_INFO_PART_ADDR, (uint8_t*)fwinfo, sizeof(fwinfo));
+                                                                                                       osDelay(1000);
+                                                                                                       HAL_NVIC_SystemReset();
+                                                                                               }
+                                                                                               break;
+                                                                                       }
+                                                                       }else{
+                                                                               debug_printf( "bkl crc faile :%08X/%08X\n", crc1, crc2 );
+                                                                       }
+                                                               }
+            }
+        }
+    }
+
+               http_close();
+    g_ota.task = NULL;
+    vTaskDelete( NULL );
+}
index ee52d68f3c0345d5d203dfc2907383e09dd3c32d..346f9646bddaa060e9b334b23c33992b916a71a0 100644 (file)
@@ -2,6 +2,8 @@
 #include "at_parser.h"
 #include "cJSON.h"
 
+#define CONN_ID_IOT  0
+#define CONN_ID_OTA  1
 //wifi task
 //uart5 
 //
 
 #define huart_wifi  huart5
 
+extern int32_t ota_handle_http_resp( uint8_t *rx_data, uint32_t rx_sz );
+extern int32_t wifi_ota_start( char * url, char *ver );
+extern char * devinfo_report_str( void );
+
 extern UART_HandleTypeDef huart5;
 
 #define WIFI_RX_BUF_SIZE  (512*4)
 #define WIFI_RX_BUF_SIZE_MASK  (WIFI_RX_BUF_SIZE-1)
-static char wifi_rx_buf[WIFI_RX_BUF_SIZE];
+__attribute__((section(".DTCM")))  static char wifi_rx_buf[WIFI_RX_BUF_SIZE];
+
+
+
+static uint32_t ota_link_connected = 0;
+
 static uint32_t rx_buf_rd = 0;
 static uint32_t rx_buf_wr = 0;
 
@@ -23,6 +34,11 @@ static uint8_t wifi_rx_byte = 0;
 
 static char g_wifi_ver[50];
 
+__attribute__((section(".DTCM"))) static uint8_t tcp_rx_buf[ 512 ];
+static uint16_t tcp_rx_n;
+
+__attribute__((section(".DTCM"))) static uint8_t ota_rx_buf[2048];
+static uint16_t ota_rx_n;
 
 static int32_t wifi_tcp_tx( uint8_t link, uint8_t *data, uint32_t sz );
 
@@ -59,10 +75,6 @@ int32_t wifi_read_byte( uint8_t *rd_byte )
     }
 }
 
-int32_t wifi_received_bytes( void )
-{
-       return rx_buf_wr-rx_buf_rd;
-}
 
 char * wifi_tx_cmd( char * cmd, uint32_t timeout_ms )
 {
@@ -90,6 +102,7 @@ int32_t wifi_init( void )
 
         if( at_send_wait_reply( cmd, strlen(cmd), true, NULL, 0, resp_buf, sizeof( resp_buf)-1, &at_cfg ) ){
             DBG_PRINTF( "at send wait reply timeout!\n" );
+                                        //TODO: err++>10 reset wifi module
         }else{
             if( strstr( resp_buf, "OK" ) ){
                 char *ver_str  = strtok( resp_buf, "\r\n" );
@@ -119,13 +132,6 @@ int32_t wifi_init( void )
     return ret;
 }
 
-int32_t wifi_get_cfg( char * ssid, char * passwd )
-{
-    strcpy( ssid, "yino305" );
-    strcpy( passwd, "cc123456789" );
-    return 0;
-}
-
 int32_t wifi_connect( const char * ssid, const char * passwd )
 {
     char cmd[100];
@@ -184,16 +190,17 @@ int32_t wifi_connect( const char * ssid, const char * passwd )
 
 int32_t tcp_server_connect( uint8_t conn_id, const char * tcp_server, uint16_t port )
 {
-    char cmd[200];
+    char cmd[128];
     atcmd_config_t at_cfg;
-    char resp_buf[200];
+    char resp_buf[128];
 
-    //4. 连接TCP服务器
+    //连接TCP服务器
     //AT+CIPSTART="TCP","192.168.3.116",8080                    //protocol,    server  IP      and     port
     at_cfg.reply_prefix = NULL;
     at_cfg.reply_success_postfix="OK"; //"CONNECT  OK";
     at_cfg.reply_fail_postfix = "ERROR"; //"ERROR  CLOSED";
     sprintf( cmd, "AT+CIPSTART=%d,\"TCP\",\"%s\",%d", conn_id, tcp_server, port  );
+               memset( resp_buf, 0, sizeof(resp_buf) );
     if( at_send_wait_reply( cmd, strlen(cmd), true, NULL, 0, resp_buf, sizeof( resp_buf )-1, &at_cfg ) ){
         return -1;
     }
@@ -225,42 +232,17 @@ int32_t tcp_server_close( uint8_t conn_id )
     return 0;
 }
 
-extern char * devinfo_report_str( void );
-extern int32_t get_ota_state( void );
 
 int32_t wifi_devinfo_report( void )
 {
     char * rpt_data;
 
-               if( get_ota_state() ){
-                       //ota http 下载中, 暂停上报数据
-                       return 0;
-               }
-
     rpt_data = devinfo_report_str();
-    wifi_tcp_tx( 0, (uint8_t *)rpt_data, strlen((char *)rpt_data) );
+    wifi_tcp_tx( CONN_ID_IOT, (uint8_t *)rpt_data, strlen((char *)rpt_data) );
 
     return 0;
 }
 
-static uint8_t tcp_rx_buf[ 512 ];
-static uint16_t tcp_rx_n;
-
-static uint8_t ota_rx_buf[2048];
-static uint16_t ota_rx_n;
-
-void ota_start( char* ver, char* url );
-void ota_handle_http_data( uint8_t *data, uint32_t sz );
-
-static void wifi_rpt_link_down( void )
-{
-    if( g_dev.wifi_connected == 2 )
-            g_dev.wifi_connected = 1 ;
-}
-
-
-extern int32_t wifi_received_bytes( void );
-
 static void tcp_rx_data_handle(void *arg, char *rspinfo, int rsplen)
 {
     unsigned char unusesymbol = 0;
@@ -305,7 +287,7 @@ static void tcp_rx_data_handle(void *arg, char *rspinfo, int rsplen)
         len = len * 10 + datalen[j] - '0';
     }
                HAL_Printf( "--R:%d, wifi buf: %d[%d..%d]\n",len, rx_buf_wr-rx_buf_rd, rx_buf_rd, rx_buf_wr );
-               if( link_id == '0' ){
+               if( link_id == '0'+CONN_ID_IOT ){
                        if( tcp_rx_n + len >= sizeof(tcp_rx_buf ) ){
                                tcp_rx_n = 0;
                        }
@@ -341,7 +323,7 @@ static void tcp_rx_data_handle(void *arg, char *rspinfo, int rsplen)
                                                        if( ver ) debug_printf( "--version:[%s]", ver->valuestring );
                                                        if( url ) debug_printf( "--url:[%s]", url->valuestring );
                                                        if(  ver &&url ){
-                                                                       ///ota_start( ver->valuestring, url->valuestring );
+                                                                       wifi_ota_start( url->valuestring, ver->valuestring );
                                                        }
                                                }
                                                debug_printf( "\n" );
@@ -350,62 +332,56 @@ static void tcp_rx_data_handle(void *arg, char *rspinfo, int rsplen)
                                tcp_rx_n = 0;
                                cJSON_Delete( root );
                        }
-               }else if( link_id == '1' ){
+               }else if( link_id == '0'+CONN_ID_OTA ){
                        if( len <= sizeof(ota_rx_buf ) ){
                                 int n =at_read( (char*)(ota_rx_buf), len );
                                ota_rx_n = len;
                                debug_printf( " ota recv data %d bytes, rd:%d, wifi buf:%d[%d..%d]\n", len, n, rx_buf_wr-rx_buf_rd, rx_buf_rd, rx_buf_wr );
-                               ///ota_handle_http_data(  ota_rx_buf, ota_rx_n );
+                               ota_handle_http_resp( ota_rx_buf, ota_rx_n );
                        }       
                }
     return;
 }
 
-int32_t wifi_tcp_tx( uint8_t link, uint8_t *data, uint32_t sz )
+int32_t wifi_tcp_tx( uint8_t conn_id, uint8_t *data, uint32_t sz )
 {
     //AT+CIPSEND=4
-    //> xxx
+    //> xxxx
     static char cmd[500];
     char resp_buf[500];                                         
     atcmd_config_t at_cfg;
-#if 1
+               int32_t ret = 0;
+
     at_cfg.reply_prefix = "SEND";
     at_cfg.reply_success_postfix="OK";
     at_cfg.reply_fail_postfix = "ERROR";
-    sprintf( cmd, "AT+CIPSEND=%d,%d", link, sz );
+    sprintf( cmd, "AT+CIPSEND=%d,%d", conn_id, sz );
                resp_buf[0] = 0;
     if( at_send_wait_reply( cmd, strlen(cmd), true, (char *)data, sz, resp_buf, sizeof( resp_buf )-1, &at_cfg ) ){
-        return -1;
+                         ret = -1;
+        return ret;
     }
                if( strstr( resp_buf, "link is not valid" ) ){
-                               if( link == 0 ){
-                                       wifi_rpt_link_down();
-                               }else if(link==1){
-                                       //wifi_ota_link_down();
+                               if( conn_id == CONN_ID_IOT ){
+                                               if( g_dev.wifi_connected == 2 )
+                                                               g_dev.wifi_connected = 1 ;
+                                       ret = -2;
+                               }else if(conn_id==CONN_ID_OTA){
+                                       ret = -2;
                                }
                }
-                       
-#endif
-    return 0;
-}
-
-#define TCP_CONN_ID 0
-#define OTA_CONN_ID 1
 
-void wifi_ota_init( void );
+    return ret;
+}
 
 void user_wifi_task( void* unused )
 {
-
     char *ssid;
     char *passwd;
 
     TickType_t last_ticks;
 
     g_dev.wifi_connected = 0;
-               g_dev.eth_connected = 0;
-
-               wifi_ota_init();
 
     MX_UART5_Init();
     wifi_uart_rx_start();
@@ -416,7 +392,6 @@ void user_wifi_task( void* unused )
         //wifi init fail
         g_dev.state |= (WIFI_ERR);
         osDelay( 10*1000 );
-        //vTaskDelete( NULL );
     }
 
     at_register_callback("+IPD", NULL, NULL, 0, tcp_rx_data_handle, NULL);
@@ -441,7 +416,7 @@ void user_wifi_task( void* unused )
 
         while( g_dev.wifi_connected == 1 ){
             //tcp connect
-            if( tcp_server_connect( TCP_CONN_ID, g_dev.cfg.net.tcp_server, g_dev.cfg.net.tcp_port ) == 0 ){
+            if( tcp_server_connect( CONN_ID_IOT, g_dev.cfg.net.tcp_server, g_dev.cfg.net.tcp_port ) == 0 ){
                 g_dev.wifi_connected = 2;
             }else{
                 osDelay( 1000 );
@@ -459,6 +434,10 @@ void user_wifi_task( void* unused )
                 continue;
             }
 
+                                               if( ota_link_connected ){
+                                                               continue;
+                                               }
+                                               
             //定时上报
             if( wifi_devinfo_report() < 0 ){
                 //reconnect
@@ -469,262 +448,51 @@ void user_wifi_task( void* unused )
     }
 }
 
-//static osThreadId_t wifiTaskHandle;
-
 const osThreadAttr_t wifiTask_attributes = {
   .name = "wifiTask",
   .stack_size = 1024,
   .priority = (osPriority_t) osPriorityNormal,
 };
 
-const osThreadAttr_t otaTask_attributes = {
-  .name = "otaTask",
-  .stack_size = 2048,
-  .priority = (osPriority_t) osPriorityNormal,
-};
-
 void wifi_task_start( void )
 {
     // wifiTaskHandle = osThreadNew(user_wifi_task, NULL, &wifiTask_attributes);
     osThreadNew(user_wifi_task, NULL, &wifiTask_attributes);
 }
 
-
-
-
-typedef struct{
-    char url[300];
-    char tcp_srv[100];
-    char path[200];
-    uint16_t tcp_port;
-    void * lock;
-    osThreadId_t task;
-    uint8_t state; //0:idle, 1:start
-               uint32_t start_time;
-       
-               char fw_ver[20];
-               uint32_t fw_received;
-         uint32_t fw_size;
-               uint32_t connected;
-}ota_t;
-
-static ota_t g_ota;
-
-void wifi_ota_init( void )
+void wifi_ota_close( void )
 {
-       memset( &g_ota, 0, sizeof( g_ota ) );
+       tcp_server_close( CONN_ID_OTA );
+       ota_link_connected = 0;
 }
 
-int32_t get_ota_state( void )
+int32_t wifi_ota_requst( char *host, uint16_t port, char *req )
 {
-       return g_ota.state;  //0:idle, //1.busy
-}
-       
-#if WIFI_OTA
-
-static uint32_t http_wait_data = 0;
-
-void ota_task( void * unused );
-int32_t ota_url_parse( char* ota_url );
-
-void wifi_ota_link_down( void )
-{
-       g_ota.connected = 0;
-}
-
-int32_t ota_url_parse( char* ota_url )
-{
-    //http://www.test.com:80/path/file.bin
-    //http://www.test.com/path/file.bin
-    char * url;
-    char *path;
-    char host[100];
-    uint16_t port;
-
-    strcpy( g_ota.url, ota_url );
-
-    url = strstr( ota_url, "http://" );
-    if( !url )
-        return -1;
-
-    //get host
-    url+=7;
-
-    port = 80;
-    if( sscanf( url, "%[^/:]:%hd", host, &port ) < 1 ){
-        return -1;
-    }
-
-    path = strstr( url, "/");
-    if( !path ){
-        return -1;
-    }
-
-    strcpy( g_ota.tcp_srv, host );
-    strcpy( g_ota.path, path );
-    g_ota.tcp_port = port;
-
-    return 0;
-}
-
-#define get_fmt "\
-GET %s HTTP/1.0\r\n\
-Host:%s:%d\r\n\
-Range:bytes=%d-%d\r\n\
-Connection:keep-alive\r\n\r\n"
-
-void ota_handle_http_data( uint8_t *data, uint32_t sz )
-{
-       char *s;
-       uint8_t *content_data;
-       uint32_t content_sz;
-       uint32_t range_start;
-       uint32_t range_end;
-       uint32_t file_sz;
-
-       s=strstr( (char*)data, "Content-Range:" );
-       if( s && sscanf( s, "Content-Range: bytes %d-%d/%d", &range_start, &range_end, &file_sz ) == 3 ){
-                               g_ota.fw_size = file_sz;
-                               debug_printf( "recv range:%d-%d/%d\n", range_start, range_end, file_sz );
-                               if( range_start == g_ota.fw_received ){
-                                       g_ota.fw_received = range_end+1;
-                                       debug_printf( "fw_received -> %d\n", g_ota.fw_received );
-                                       http_wait_data = 0;
-                               }
-                               s = strstr( (char*)data, "\r\n\r\n" );
-                               if( s ){
-                                       content_data = (uint8_t*)(s+4);
-                                       uint32_t head_sz = (uint32_t)content_data-(uint32_t)data;
-                                       content_sz = sz - head_sz;
-                                       debug_printf( "rx content size: %d\n", content_sz );
-                               }
-       }
-       
-}
-
-int32_t http_dowload( void )
-{
-       uint32_t blk_start;
-       uint32_t blk_sz;
-       uint32_t tick;
-       uint32_t download_start_time;
-
-       char cmd[200];
-
-       download_start_time = xTaskGetTickCount();
-       while( (g_ota.fw_size == 0 ||  g_ota.fw_received < g_ota.fw_size) && xTaskGetTickCount()-download_start_time < 30*60*1000 ){
-
-               if( !g_ota.connected  ){
-                       if( tcp_server_connect( OTA_CONN_ID, g_ota.tcp_srv, g_ota.tcp_port ) < 0 ){
+               int32_t ret = -1;
+               uint32_t tick = xTaskGetTickCount();
+               while( xTaskGetTickCount()-tick < 1*60*1000 ){
                        
-                               osDelay( 2000 );
-                               continue;
+                       if( !ota_link_connected ){
+                               if( tcp_server_connect( CONN_ID_OTA, host, port ) == 0 ){
+                                ota_link_connected = 1;
+                               }else{
+                                       osDelay(1000);
+                                       tcp_server_close( CONN_ID_OTA );
+                                       continue;
+                               }
                        }
-                       g_ota.connected = 1;
-               }
-
-               blk_start = g_ota.fw_received;
-               if( g_ota.fw_size && g_ota.fw_size < blk_start+1000 )
-                       blk_sz = g_ota.fw_size-blk_start;
-               else
-                       blk_sz = 1000;
-
-               sprintf( cmd, get_fmt, g_ota.path, g_ota.tcp_srv, g_ota.tcp_port, blk_start, blk_start+blk_sz-1 );
-               debug_printf( "http get block, cmd[%s]\n", cmd );
-               http_wait_data = blk_sz;
-               tick = xTaskGetTickCount();
-
-               wifi_tcp_tx(1,  (uint8_t *)cmd, strlen(cmd) );
-               while( http_wait_data && xTaskGetTickCount()-tick < 20*1000 ){
-                       osDelay(10);
-               }
-       }
-
-       if( g_ota.fw_received == g_ota.fw_size ){
-               return 0;
-       }else{
-               return -1;
-       }
-}
-
 
-void ota_task( void * unused )
-{
-       int32_t ret;
-       debug_printf( "ota_task ...\n" );
-       debug_printf( "url [%s], host[%s], port[%d], path[%s]\n", g_ota.url, g_ota.tcp_srv, g_ota.tcp_port, g_ota.path );
-
-  g_ota.start_time = xTaskGetTickCount();
-       g_ota.fw_size = 0;
-       g_ota.fw_ver[0] = 0;
-       g_ota.fw_received = 0;
-
-  //十分钟超时
-       while( xTaskGetTickCount() - g_ota.start_time < 10*60*1000 ){
-
-                       //1. tcp connect
-                debug_printf( "tcp connect: %s %d ...\n", g_ota.tcp_srv, g_ota.tcp_port );
-                       if( tcp_server_connect( OTA_CONN_ID, g_ota.tcp_srv, g_ota.tcp_port ) < 0 ){
-                               
-          osDelay( 1000 );
-          continue;
-      }
-                       g_ota.connected = 1;
-                       debug_printf( "tcp connected\n" );
-                       ret = http_dowload();
-                       if( ret== 0 ){
-                               //dowload success
-                               //reboot
+                       ret = wifi_tcp_tx(CONN_ID_OTA,  (uint8_t *)req, strlen(req) );
+                       if( ret == 0 ){
                                break;
-
-                       }else if( ret == -1 ){
-                               //fail
-                               goto err_exit;
-
-                       }else if( ret == -2 ){
-                               //reconnect
-                               tcp_server_close( OTA_CONN_ID );
-                               osDelay( 5000 );
-                               continue;
                        }
-                       if( g_ota.connected == 0 ){
+                       if( ret == -2 ){
+                                ota_link_connected = 0;
                        }
-    }
-
-err_exit:
-               tcp_server_close( OTA_CONN_ID );
-               g_ota.state = 0;
-               vTaskDelete( NULL );
-}
-
-
-void ota_start( char* ver, char* url )
-{
-               debug_printf("ota_start, ver:%s, url:%s\n" );
-    if( g_ota.state ){
-        //busy
-                               debug_printf("device busy\n" );
-        return;
-    }
-
-    //1. parser_url
-    if( ota_url_parse( url ) < 0 ){
-                               debug_printf("url parse fail!\n" );
-        return;
-    }
-
-               strcpy( g_ota.fw_ver, ver );
-    g_ota.task = osThreadNew(ota_task, NULL, &otaTask_attributes);
-    if( g_ota.task ){
-                               debug_printf("create ota task success!\n" );
-        g_ota.state = 1;
-               }else{
-                       debug_printf("create ota task fail!\n" );
                }
-    return;
-}
 
-#endif //WIFI_OTA
+               return ret;
+}
 
 extern void *HAL_Malloc(uint32_t size);
 extern void HAL_Free(void *ptr);