收藏官网首页
查看: 1292|回复: 0

[分享] 【Io开发笔记】机智云智能浇花器实战(3)-自动生成代码移植

610

主题

660

帖子

3万

积分

版主

Rank: 7Rank: 7Rank: 7

积分
33430
跳转到指定楼层
楼主
 楼主| 发表于 2022-7-25 15:54:55 | 只看该作者 |只看大图 回帖奖励 |倒序浏览 |阅读模式
汉枫LPB120模块
【Io开发笔记】机智云智能浇花器实战(3)-自动生成代码移植



第一篇内容:总体设计/系统功能介绍/机智云自助开发平台-开发利器GAgent等等
点击下载:【Io开发笔记】机智云智能浇花器实战(1)-基础Demo实现

第二篇内容:
继电器实现/功能测试/DHT11驱动代码实现/OLED屏幕显示传感器数据/中文字模制作等等
点击下载:机智云智能浇花器实战(2)-基础Demo实现


一,BH1750光照传感器原理图




二,BH1750传感器代码
  1. #include "bh1750.h"
  2. #include "delay.h"

  3. uint8_t    BUF[8];               //接收数据缓存区  
  4. int         mcy;     //进位标志

  5. /**开始信号**/
  6. void BH1750_Start()
  7. {
  8.   BH1750_SDA_H;                                               //拉高数据线
  9.   BH1750_SCL_H;                                               //拉高时钟线
  10.   Delay_nus(5);                                         //延时
  11.   GPIO_ResetBits(BH1750_PORT, BH1750_SDA_PIN);                    //产生下降沿
  12.   Delay_nus(5);                                         //延时
  13.   GPIO_ResetBits(BH1750_PORT, BH1750_SCL_PIN);                    //拉低时钟线
  14. }

  15. /**停止信号**/
  16. void BH1750_Stop()
  17. {
  18.     BH1750_SDA_L;                                             //拉低数据线
  19.     BH1750_SCL_H;                                             //拉高时钟线
  20.     Delay_nus(5);                                       //延时
  21.     GPIO_SetBits(BH1750_PORT, BH1750_SDA_PIN);                    //产生上升沿
  22.     Delay_nus(5);                 //延时
  23. }

  24. /***
  25. 发送应答信号
  26. 入口参数:ack (0:ACK 1:NAK)
  27. ***/
  28. void BH1750_SendACK(int ack)
  29. {
  30.         GPIO_InitTypeDef GPIO_InitStruct;
  31.         
  32.   GPIO_InitStruct.GPIO_Mode = GPIO_Mode_Out_PP;  
  33.   GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
  34.   GPIO_InitStruct.GPIO_Pin = BH1750_SDA_PIN;
  35.   GPIO_Init(BH1750_PORT, &GPIO_InitStruct);  
  36.         
  37.         if(ack == 1)   //写应答信号
  38.                 BH1750_SDA_H;
  39.         else if(ack == 0)
  40.                 BH1750_SDA_L;
  41.         else
  42.                 return;                        
  43.   BH1750_SCL_H;     //拉高时钟线
  44.   Delay_nus(5);                 //延时
  45.   BH1750_SCL_L;      //拉低时钟线
  46.   Delay_nus(5);                //延时
  47. }

  48. /***
  49. 接收应答信号
  50. ***/
  51. int BH1750_RecvACK()
  52. {
  53.   GPIO_InitTypeDef GPIO_InitStruct;
  54.         
  55.   GPIO_InitStruct.GPIO_Mode=GPIO_Mode_IPU;  /*这里一定要设成输入上拉,否则不能读出数据*/
  56.   GPIO_InitStruct.GPIO_Speed=GPIO_Speed_50MHz;
  57.   GPIO_InitStruct.GPIO_Pin=BH1750_SDA_PIN;
  58.   GPIO_Init(BH1750_PORT,&GPIO_InitStruct);
  59.         
  60.   BH1750_SCL_H;            //拉高时钟线
  61.   Delay_nus(5);                 //延时        
  62.         if(GPIO_ReadInputDataBit(BH1750_PORT,BH1750_SDA_PIN)==1)//读应答信号
  63.     mcy = 1 ;  
  64.   else
  65.     mcy = 0 ;                                
  66.   BH1750_SCL_L;                    //拉低时钟线
  67.   Delay_nus(5);                 //延时
  68.   GPIO_InitStruct.GPIO_Mode=GPIO_Mode_Out_PP;
  69.   GPIO_Init(BH1750_PORT,&GPIO_InitStruct);
  70.         return mcy;
  71. }

  72. /***
  73. 向IIC总线发送一个字节数据
  74. ***/
  75. void BH1750_SendByte(uint8_t dat)
  76. {
  77.   uint8_t i;
  78.   for (i=0; i<8; i++)         //8位计数器
  79.   {
  80.                 if( 0X80 & dat )
  81.       GPIO_SetBits(BH1750_PORT,BH1750_SDA_PIN);
  82.     else
  83.       GPIO_ResetBits(BH1750_PORT,BH1750_SDA_PIN);
  84.                 dat <<= 1;
  85.     BH1750_SCL_H;               //拉高时钟线
  86.     Delay_nus(5);             //延时
  87.     BH1750_SCL_L;                //拉低时钟线
  88.     Delay_nus(5);            //延时
  89.   }
  90.   BH1750_RecvACK();
  91. }

  92. uint8_t BH1750_RecvByte()
  93. {
  94.   uint8_t i;
  95.   uint8_t dat = 0;
  96.   uint8_t bit;
  97.         
  98.   GPIO_InitTypeDef GPIO_InitStruct;
  99.         
  100.   GPIO_InitStruct.GPIO_Mode  = GPIO_Mode_IPU;   /*这里一定要设成输入上拉,否则不能读出数据*/
  101.   GPIO_InitStruct.GPIO_Pin   = BH1750_SDA_PIN;
  102.   GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
  103.   GPIO_Init(BH1750_PORT,&GPIO_InitStruct );
  104.         
  105.   GPIO_SetBits(BH1750_PORT,BH1750_SDA_PIN);          //使能内部上拉,准备读取数据,
  106.   for (i=0; i<8; i++)         //8位计数器
  107.   {
  108.     dat <<= 1;
  109.     BH1750_SCL_H;               //拉高时钟线
  110.     Delay_nus(5);             //延时
  111.                         
  112.                 if( SET == GPIO_ReadInputDataBit(BH1750_PORT,BH1750_SDA_PIN))
  113.       bit = 0X01;
  114.     else
  115.       bit = 0x00;  
  116.                 dat |= bit;             //读数据   
  117.                 BH1750_SCL_L;                //拉低时钟线
  118.     Delay_nus(5);            //延时
  119.   }               
  120.         GPIO_InitStruct.GPIO_Mode = GPIO_Mode_Out_PP;
  121.   GPIO_Init(BH1750_PORT, &GPIO_InitStruct );
  122.   return dat;
  123. }

  124. void Single_Write_BH1750(uint8_t REG_Address)
  125. {
  126.   BH1750_Start();                  //起始信号
  127.   BH1750_SendByte(SlaveAddress);   //发送设备地址+写信号
  128.   BH1750_SendByte(REG_Address);    //内部寄存器地址,请参考中文pdf22页
  129. //  BH1750_SendByte(REG_data);       //内部寄存器数据,请参考中文pdf22页
  130.   BH1750_Stop();                   //发送停止信号
  131. }

  132. //初始化BH1750,根据需要请参考pdf进行修改**
  133. void BH1750_Init()
  134. {
  135.   GPIO_InitTypeDef GPIO_InitStruct;
  136.          /*开启GPIOB的外设时钟*/
  137.   RCC_APB2PeriphClockCmd( RCC_APB2Periph_GPIOB, ENABLE);
  138.   GPIO_InitStruct.GPIO_Mode = GPIO_Mode_Out_PP;  
  139.   GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
  140.   GPIO_InitStruct.GPIO_Pin = BH1750_SDA_PIN | BH1750_SCL_PIN ;
  141.   GPIO_Init(BH1750_PORT,&GPIO_InitStruct);
  142.         
  143.   Single_Write_BH1750(0x01);  
  144.   Delay_nms(180);            //延时180ms
  145. }

  146. //连续读出BH1750内部数据
  147. void mread(void)
  148. {   
  149.   uint8_t i;        
  150.   BH1750_Start();                          //起始信号
  151.   BH1750_SendByte(SlaveAddress+1);         //发送设备地址+读信号
  152.         
  153.         for (i=0; i<3; i++)                      //连续读取6个地址数据,存储中BUF
  154.   {
  155.     BUF[i] = BH1750_RecvByte();          //BUF[0]存储0x32地址中的数据
  156.     if (i == 3)
  157.     {
  158.       BH1750_SendACK(1);                //最后一个数据需要回NOACK
  159.     }
  160.     else
  161.     {               
  162.       BH1750_SendACK(0);                //回应ACK
  163.     }
  164.   }
  165.   BH1750_Stop();                          //停止信号
  166.   Delay_nms(5);
  167. }

  168. float Read_BH1750(void)
  169. {
  170.   int dis_data;                       //变量        
  171.         float temp1;
  172.         float temp2;
  173.         Single_Write_BH1750(0x01);   // power on
  174.         Single_Write_BH1750(0x10);   // H- resolution mode
  175.         Delay_nms(180);              //延时180ms
  176.         mread();                     //连续读出数据,存储在BUF中
  177.         dis_data=BUF[0];
  178.         dis_data=(dis_data<<8)+BUF[1]; //合成数据
  179.         temp1=dis_data/1.2;
  180.         temp2=10*dis_data/1.2;        
  181.         temp2=(int)temp2%10;
  182.         return temp1;
  183. }

复制代码

  1. #ifndef __BH1750_H__
  2. #define __BH1750_H__

  3. #include "STM32f10x.h"

  4. /*
  5.         定义器件在IIC总线中的从地址,根据ALT  ADDRESS地址引脚不同修改
  6.         ALT  ADDRESS引脚接地时地址为0x46,   接电源时地址为0xB8
  7. */
  8. #define        SlaveAddress     0x46                     
  9. #define BH1750_PORT      GPIOB
  10. #define BH1750_SCL_PIN   GPIO_Pin_1
  11. #define BH1750_SDA_PIN   GPIO_Pin_0

  12. #define BH1750_SCL_H     GPIO_SetBits(BH1750_PORT,BH1750_SCL_PIN)
  13. #define BH1750_SCL_L     GPIO_ResetBits(BH1750_PORT,BH1750_SCL_PIN)

  14. #define BH1750_SDA_H     GPIO_SetBits(BH1750_PORT,BH1750_SDA_PIN)
  15. #define BH1750_SDA_L     GPIO_ResetBits(BH1750_PORT,BH1750_SDA_PIN)  

  16.                                              
  17.                                                                                                                         
  18. extern uint8_t    BUF[8];                         //接收数据缓存区              
  19. extern int        dis_data;                       //变量               
  20. extern int        mcy;                            //表示进位标志位

  21. void BH1750_Init(void);
  22. void conversion(uint32_t temp_data);
  23. void  Single_Write_BH1750(uint8_t REG_Address);    //单个写入数据
  24. uint8_t Single_Read_BH1750(uint8_t REG_Address);   //单个读取内部寄存器数据
  25. void  mread(void);                                 //连续的读取内部寄存器数据
  26. float Read_BH1750(void);


  27. #endif


复制代码

BH1750传感器代码说明


核心板单独测试程序在PB0PB1管脚是完全正常,不知道是不是核心板的PB2上接了什么暂时还未排查出来问题,如果你是用开发板或者是自己设计的项目板的话,那么程序是直接可以使用的程序依然按照PB0PB1保留。


三,机智云自助开发平台数据点创建
机智云官方网站:https://www.gizwits.com/
步骤1,创建产品



创建好后就会有基本信息




步骤2,填写机智云产品ProductKey


这两个信息比较重要最好是保存下来

  1. Product Key :9c8a5a8e38344fb4af14b6db0f5b1df7

  2. Product Secret :45c86d8c6a2a4b1dac7d68df54f6e4f0

复制代码


步骤3,定义自己的数据点


只读:就是只允许赋值数据传感器赋值给平台平台只能读取
可写:就是数据可以被修改继电器的开关状态平台可以修改

四,MCU开发


mcu开发注意事项平台选Common其实就是STM32F103x平台



1,生成代码包


2,下载自动生成的代码包

3,机智云Gizwits协议移植




这两个文件夹要添加到自己的工程

这是添加的文件夹以及文件的目录

4,修改gizwits_product.c

  1. #include <stdio.h>
  2. #include <string.h>
  3. #include "gizwits_product.h"
  4. #include "usart3.h"

  5. static uint32_t timerMsCount;
  6. uint8_t aRxBuffer;
  7. dataPoint_t currentDataPoint;
  8. uint8_t wifi_flag;

  9. //存放事件处理API接口函数
  10. int8_t gizwitsEventProcess(eventInfo_t *info, uint8_t *gizdata, uint32_t len)
  11. {
  12.   uint8_t i = 0;
  13.   dataPoint_t *dataPointPtr = (dataPoint_t *)gizdata;
  14.   moduleStatusInfo_t *wifiData = (moduleStatusInfo_t *)gizdata;
  15.   protocolTime_t *ptime = (protocolTime_t *)gizdata;
  16.   
  17. #if MODULE_TYPE
  18.   gprsInfo_t *gprsInfoData = (gprsInfo_t *)gizdata;
  19. #else
  20.   moduleInfo_t *ptModuleInfo = (moduleInfo_t *)gizdata;
  21. #endif

  22.   if((NULL == info) || (NULL == gizdata))
  23.   {
  24.     return -1;
  25.   }

  26.   for(i=0; i<info->num; i++)
  27.   {
  28.     switch(info->event[i])
  29.     {
  30.       case EVENT_Relay_1:
  31.         currentDataPoint.valueRelay_1 = dataPointPtr->valueRelay_1;
  32.         GIZWITS_LOG("Evt: EVENT_Relay_1 %d \n", currentDataPoint.valueRelay_1);
  33.         if(0x01 == currentDataPoint.valueRelay_1)
  34.         {
  35.             currentDataPoint.valueRelay_1 = 1;

  36.         }
  37.         else
  38.         {
  39.             currentDataPoint.valueRelay_1 = 0;

  40.         }
  41.         break;
  42.       case WIFI_SOFTAP:
  43.         break;
  44.       case WIFI_AIRLINK:
  45.         break;
  46.       case WIFI_STATION:
  47.         break;
  48.       case WIFI_CON_ROUTER:

  49.         break;
  50.       case WIFI_DISCON_ROUTER:

  51.         break;
  52.       case WIFI_CON_M2M:
  53.                wifi_flag = 1; //WiFi连接标志
  54.         break;
  55.       case WIFI_DISCON_M2M:
  56.                wifi_flag = 0; //WiFi断开标志
  57.         break;
  58.       case WIFI_RSSI:
  59.         GIZWITS_LOG("RSSI %d\n", wifiData->rssi);
  60.         break;
  61.       case TRANSPARENT_DATA:
  62.         GIZWITS_LOG("TRANSPARENT_DATA \n");
  63.         //user handle , Fetch data from [data] , size is [len]
  64.         break;
  65.       case WIFI_NTP:
  66.         GIZWITS_LOG("WIFI_NTP : [%d-%d-%d %02d:%02d:%02d][%d] \n",ptime->year,ptime->month,ptime->day,ptime->hour,ptime->minute,ptime->second,ptime->ntp);
  67.         break;
  68.       case MODULE_INFO:
  69.             GIZWITS_LOG("MODULE INFO ...\n");
  70.       #if MODULE_TYPE
  71.             GIZWITS_LOG("GPRS MODULE ...\n");
  72.             //Format By gprsInfo_t
  73.       #else
  74.             GIZWITS_LOG("WIF MODULE ...\n");
  75.             //Format By moduleInfo_t
  76.             GIZWITS_LOG("moduleType : [%d] \n",ptModuleInfo->moduleType);
  77.       #endif
  78.     break;
  79.       default:
  80.         break;
  81.     }
  82.   }

  83.   return 0;
  84. }


  85. void userHandle(void)
  86. {
  87. /*
  88.     currentDataPoint.valueTemp = ;//Add Sensor Data Collection
  89.     currentDataPoint.valueHumi = ;//Add Sensor Data Collection
  90.     currentDataPoint.valueLight_Intensity = ;//Add Sensor Data Collection
  91. */
  92. }
  93. void userInit(void)
  94. {
  95.     memset((uint8_t*)¤tDataPoint, 0, sizeof(dataPoint_t));
  96.                 currentDataPoint.valueRelay_1         = 0;
  97.                 currentDataPoint.valueTemp            = 0;
  98.                 currentDataPoint.valueHumi            = 0;
  99.                 currentDataPoint.valueLight_Intensity = 0;
  100. }

  101. void gizTimerMs(void)
  102. {
  103.     timerMsCount++;
  104. }

  105. uint32_t gizGetTimerCount(void)
  106. {
  107.     return timerMsCount;
  108. }

  109. void mcuRestart(void)
  110. {
  111.         __set_FAULTMASK(1);
  112.         NVIC_SystemReset();
  113. }

  114. void TIMER_IRQ_FUN(void)
  115. {
  116.   gizTimerMs();
  117. }

  118. void UART_IRQ_FUN(void)
  119. {
  120.   uint8_t value = 0;
  121.   gizPutData(&value, 1);
  122. }

  123. int32_t uartWrite(uint8_t *buf, uint32_t len)
  124. {
  125.     uint32_t i = 0;
  126.         
  127.     if(NULL == buf)
  128.     {
  129.         return -1;
  130.     }
  131.    
  132.     for(i=0; i<len; i++)
  133.     {
  134.         USART_SendData(USART3,buf[i]);
  135.         while(USART_GetFlagStatus(USART3, USART_FLAG_TC) == RESET); //循环发送,直到发送完毕
  136.         if(i >=2 && buf[i] == 0xFF)
  137.         {
  138.             USART_SendData(USART3, 0x55);
  139.             while (USART_GetFlagStatus(USART3, USART_FLAG_TC) == RESET); //循环发送,直到发送完毕
  140.         }
  141.     }
  142.     return len;
  143. }

复制代码
5,修改
  1. #ifndef _GIZWITS_PRODUCT_H
  2. #define _GIZWITS_PRODUCT_H

  3. #ifdef __cplusplus
  4. extern "C" {
  5. #endif

  6. #include <stdint.h>
  7. //#include "stm32f1xx.h"
  8. #include "gizwits_protocol.h"

  9. /**
  10. * MCU software version
  11. */
  12. #define SOFTWARE_VERSION "03030000"
  13. /**
  14. * MCU hardware version
  15. */
  16. #define HARDWARE_VERSION "03010100"


  17. /**
  18. * Communication module model
  19. */
  20. #define MODULE_TYPE 0 //0,WIFI ;1,GPRS


  21. /**@name TIM3 related macro definition
  22. * @{
  23. */
  24. #define TIMER                                             TIM3
  25. #define TIMER_IRQ                                   TIM3_IRQn
  26. #define TIMER_RCC                                   RCC_APB1Periph_TIM3
  27. #define TIMER_IRQ_FUN                         TIM3_IRQHandler
  28. /**@} */

  29. /**@name USART related macro definition
  30. * @{
  31. */
  32. #define UART_BAUDRATE                         9600
  33. #define UART_PORT                             2
  34. #define UART                                  USART2
  35. #define UART_IRQ                              USART2_IRQn
  36. #define UART_IRQ_FUN                          USART2_IRQHandler

  37. #if (UART_PORT == 1)
  38. #define UART_GPIO_Cmd          RCC_APB2PeriphClockCmd
  39. #define UART_GPIO_CLK          RCC_APB2Periph_GPIOA

  40. #define UART_AFIO_Cmd          RCC_APB2PeriphClockCmd
  41. #define UART_AFIO_CLK          RCC_APB2Periph_AFIO

  42. #define UART_CLK_Cmd           RCC_APB2PeriphClockCmd
  43. #define UART_CLK               RCC_APB2Periph_USART1

  44. #define UART_GPIO_PORT         GPIOA
  45. #define UART_RxPin             GPIO_Pin_10
  46. #define UART_TxPin             GPIO_Pin_9
  47. #endif

  48. #if (UART_PORT == 2)
  49. #define UART_GPIO_Cmd          RCC_APB2PeriphClockCmd
  50. #define UART_GPIO_CLK          RCC_APB2Periph_GPIOA

  51. #define UART_AFIO_Cmd          RCC_APB2PeriphClockCmd
  52. #define UART_AFIO_CLK          RCC_APB2Periph_AFIO

  53. #define UART_CLK_Cmd           RCC_APB1PeriphClockCmd
  54. #define UART_CLK               RCC_APB1Periph_USART2

  55. #define UART_GPIO_PORT         GPIOA
  56. #define UART_RxPin             GPIO_Pin_3
  57. #define UART_TxPin             GPIO_Pin_2
  58. #endif


  59. #if (UART_PORT == 3)

  60. #define UART_GPIO_Cmd          RCC_APB2PeriphClockCmd
  61. #define UART_GPIO_CLK          RCC_APB2Periph_GPIOC

  62. #define UART_AFIO_Cmd          RCC_APB2PeriphClockCmd
  63. #define UART_AFIO_CLK          RCC_APB2Periph_AFIO

  64. #define UART_CLK_Cmd           RCC_APB1PeriphClockCmd
  65. #define UART_CLK               RCC_APB1Periph_USART3

  66. #define UART_GPIO_PORT         GPIOC
  67. #define UART_RxPin             GPIO_Pin_11
  68. #define UART_TxPin             GPIO_Pin_10

  69. #endif
  70. /**@} */

  71. /** User area the current device state structure*/
  72. extern dataPoint_t currentDataPoint;

  73. void gizTimerMs(void);
  74. uint32_t gizGetTimerCount(void);
  75. void timerInit(void);
  76. void uartInit(void);

  77. void userInit(void);
  78. void userHandle(void);
  79. void mcuRestart(void);

  80. int32_t uartWrite(uint8_t *buf, uint32_t len);
  81. int8_t gizwitsEventProcess(eventInfo_t *info, uint8_t *data, uint32_t len);

  82. #ifdef __cplusplus
  83. }
  84. #endif

  85. #endif

复制代码

5,修改gizwits_product.h
Listitem
Listitem
Listitem
Listitem
Listitem
  1. /**
  2. ****
  3. * @file         gizwits_protocol.c
  4. * @brief        Corresponding gizwits_product.c header file (including product hardware and software version definition)
  5. * @author       Gizwits
  6. * @date         2017-07-19
  7. * @version      V03030000
  8. * @copyright    Gizwits
  9. *
  10. * @note         机智云.只为智能硬件而生
  11. *               Gizwits Smart Cloud  for Smart Products
  12. *               链接|增值ֵ|开放|中立|安全|自有|自由|生态
  13. *               www.gizwits.com
  14. *
  15. ****/
  16. //#include "ringBuffer.h"
  17. //#include "gizwits_product.h"
  18. //#include "dataPointTools.h"
  19. #include "delay.h"
  20. /** Protocol global variables **/
  21. //gizwitsProtocol_t gizwitsProtocol;
  22. //extern dataPoint_t currentDataPoint;
  23. //extern uint8_t wifi_flag;

  24. /**@name The serial port receives the ring buffer implementation
  25. * @{
  26. */
  27. rb_t pRb;                                               ///< Ring buffer structure variable
  28. static uint8_t rbBuf[RB_MAX_LEN];                       ///< Ring buffer data cache buffer


  29. /**@} */

  30. /**
  31. * @brief Write data to the ring buffer
  32. * @param [in] buf        : buf adress
  33. * @param [in] len        : byte length
  34. * @return   correct : Returns the length of the written data
  35.             failure : -1
  36. */
  37. int32_t gizPutData(uint8_t *buf, uint32_t len)
  38. {
  39.     int32_t count = 0;

  40.     if(NULL == buf)
  41.     {
  42.         GIZWITS_LOG("ERR: gizPutData buf is empty \n");
  43.         return -1;
  44.     }

  45.     count = rbWrite(&pRb, buf, len);
  46.     if(count != len)
  47.     {
  48.         GIZWITS_LOG("ERR: Failed to rbWrite \n");
  49.         return -1;
  50.     }

  51.     return count;
  52. }



  53. /**
  54. * @brief Protocol header initialization
  55. *
  56. * @param [out] head         : Protocol header pointer
  57. *
  58. * @return 0, success; other, failure   
  59. */
  60. static int8_t gizProtocolHeadInit(protocolHead_t *head)
  61. {
  62.     if(NULL == head)
  63.     {
  64.         GIZWITS_LOG("ERR: gizProtocolHeadInit head is empty \n");
  65.         return -1;
  66.     }

  67.     memset((uint8_t *)head, 0, sizeof(protocolHead_t));
  68.     head->head[0] = 0xFF;
  69.     head->head[1] = 0xFF;

  70.     return 0;
  71. }

  72. /**
  73. * @brief Protocol ACK check processing function
  74. *
  75. * @param [in] data            : data adress
  76. * @param [in] len             : data length
  77. *
  78. * @return 0, suceess; other, failure
  79. */
  80. static int8_t gizProtocolWaitAck(uint8_t *gizdata, uint32_t len)
  81. {
  82.     if(NULL == gizdata)
  83.     {
  84.         GIZWITS_LOG("ERR: data is empty \n");
  85.         return -1;
  86.     }

  87.     memset((uint8_t *)&gizwitsProtocol.waitAck, 0, sizeof(protocolWaitAck_t));
  88.     memcpy((uint8_t *)gizwitsProtocol.waitAck.buf, gizdata, len);
  89.     gizwitsProtocol.waitAck.dataLen = (uint16_t)len;
  90.    
  91.     gizwitsProtocol.waitAck.flag = 1;
  92.     gizwitsProtocol.waitAck.sendTime = gizGetTimerCount();

  93.     return 0;
  94. }
  95. /**
  96. * @brief generates "controlled events" according to protocol

  97. * @param [in] issuedData: Controlled data
  98. * @param [out] info: event queue
  99. * @param [out] dataPoints: data point data
  100. * @return 0, the implementation of success, non-0, failed
  101. */
  102. static int8_t ICACHE_FLASH_ATTR gizDataPoint2Event(gizwitsIssued_t *issuedData, eventInfo_t *info, dataPoint_t *dataPoints)
  103. {
  104.     if((NULL == issuedData) || (NULL == info) ||(NULL == dataPoints))
  105.     {
  106.         GIZWITS_LOG("gizDataPoint2Event Error , Illegal Param\n");
  107.         return -1;
  108.     }
  109.    
  110.     /** Greater than 1 byte to do bit conversion **/
  111.     if(sizeof(issuedData->attrFlags) > 1)
  112.     {
  113.         if(-1 == gizByteOrderExchange((uint8_t *)&issuedData->attrFlags,sizeof(attrFlags_t)))
  114.         {
  115.             GIZWITS_LOG("gizByteOrderExchange Error\n");
  116.             return -1;
  117.         }
  118.     }
  119.    
  120.     if(0x01 == issuedData->attrFlags.flagRelay_1)
  121.     {
  122.         info->event[info->num] = EVENT_Relay_1;
  123.         info->num++;
  124.         dataPoints->valueRelay_1 = gizStandardDecompressionValue(Relay_1_BYTEOFFSET,Relay_1_BITOFFSET,Relay_1_LEN,(uint8_t *)&issuedData->attrVals.wBitBuf,sizeof(issuedData->attrVals.wBitBuf));
  125.     }
  126.         
  127.    
  128.     return 0;
  129. }

  130. /**
  131. * @brief contrasts the current data with the last data
  132. *
  133. * @param [in] cur: current data point data
  134. * @param [in] last: last data point data
  135. *
  136. * @return: 0, no change in data; 1, data changes
  137. */
  138. static int8_t ICACHE_FLASH_ATTR gizCheckReport(dataPoint_t *cur, dataPoint_t *last)
  139. {
  140.     int8_t ret = 0;
  141.     static uint32_t lastReportTime = 0;
  142.     uint32_t currentTime = 0;

  143.     if((NULL == cur) || (NULL == last))
  144.     {
  145.         GIZWITS_LOG("gizCheckReport Error , Illegal Param\n");
  146.         return -1;
  147.     }
  148.     currentTime = gizGetTimerCount();
  149.     if(last->valueRelay_1 != cur->valueRelay_1)
  150.     {
  151.         GIZWITS_LOG("valueRelay_1 Changed\n");
  152.         ret = 1;
  153.     }

  154.     if(last->valueTemp != cur->valueTemp)
  155.     {
  156.         if(currentTime - lastReportTime >= REPORT_TIME_MAX)
  157.         {
  158.             GIZWITS_LOG("valueTemp Changed\n");
  159.             ret = 1;
  160.         }
  161.     }
  162.     if(last->valueHumi != cur->valueHumi)
  163.     {
  164.         if(currentTime - lastReportTime >= REPORT_TIME_MAX)
  165.         {
  166.             GIZWITS_LOG("valueHumi Changed\n");
  167.             ret = 1;
  168.         }
  169.     }
  170.     if(last->valueLight_Intensity != cur->valueLight_Intensity)
  171.     {
  172.         if(currentTime - lastReportTime >= REPORT_TIME_MAX)
  173.         {
  174.             GIZWITS_LOG("valueLight_Intensity Changed\n");
  175.             ret = 1;
  176.         }
  177.     }

  178.     if(1 == ret)
  179.     {
  180.         lastReportTime = gizGetTimerCount();
  181.     }
  182.     return ret;
  183. }

  184. /**
  185. * @brief User data point data is converted to wit the cloud to report data point data
  186. *
  187. * @param [in] dataPoints: user data point data address
  188. * @param [out] devStatusPtr: wit the cloud data point data address
  189. *
  190. * @return 0, the correct return; -1, the error returned
  191. */
  192. static int8_t ICACHE_FLASH_ATTR gizDataPoints2ReportData(dataPoint_t *dataPoints , devStatus_t *devStatusPtr)
  193. {
  194.     if((NULL == dataPoints) || (NULL == devStatusPtr))
  195.     {
  196.         GIZWITS_LOG("gizDataPoints2ReportData Error , Illegal Param\n");
  197.         return -1;
  198.     }

  199.     gizMemset((uint8_t *)devStatusPtr->wBitBuf,0,sizeof(devStatusPtr->wBitBuf));

  200.     gizStandardCompressValue(Relay_1_BYTEOFFSET,Relay_1_BITOFFSET,Relay_1_LEN,(uint8_t *)devStatusPtr,dataPoints->valueRelay_1);
  201.     gizByteOrderExchange((uint8_t *)devStatusPtr->wBitBuf,sizeof(devStatusPtr->wBitBuf));

  202.     devStatusPtr->valueTemp = gizY2X(Temp_RATIO,  Temp_ADDITION, dataPoints->valueTemp);
  203.     devStatusPtr->valueHumi = gizY2X(Humi_RATIO,  Humi_ADDITION, dataPoints->valueHumi);
  204.     devStatusPtr->valueLight_Intensity = gizY2X(Light_Intensity_RATIO,  Light_Intensity_ADDITION, dataPoints->valueLight_Intensity);




  205.     return 0;
  206. }


  207. /**
  208. * @brief This function is called by the GAgent module to receive the relevant protocol data from the cloud or APP
  209. * @param [in] inData The protocol data entered
  210. * @param [in] inLen Enter the length of the data
  211. * @param [out] outData The output of the protocol data
  212. * @param [out] outLen The length of the output data
  213. * @return 0, the implementation of success, non-0, failed
  214. */
  215. static int8_t gizProtocolIssuedProcess(char *did, uint8_t *inData, uint32_t inLen, uint8_t *outData, uint32_t *outLen)
  216. {
  217.     uint8_t issuedAction = inData[0];

  218.     if((NULL == inData)||(NULL == outData)||(NULL == outLen))
  219.     {
  220.         GIZWITS_LOG("gizProtocolIssuedProcess Error , Illegal Param\n");
  221.         return -1;
  222.     }
  223.    
  224.     if(NULL == did)
  225.     {
  226.         memset((uint8_t *)&gizwitsProtocol.issuedProcessEvent, 0, sizeof(eventInfo_t));
  227.         switch(issuedAction)
  228.         {
  229.             case ACTION_CONTROL_DEVICE:
  230.                 gizDataPoint2Event((gizwitsIssued_t *)&inData[1], &gizwitsProtocol.issuedProcessEvent,&gizwitsProtocol.gizCurrentDataPoint);
  231.                 gizwitsProtocol.issuedFlag = ACTION_CONTROL_TYPE;
  232.                 outData = NULL;
  233.                 *outLen = 0;
  234.                 break;
  235.             
  236.             case ACTION_READ_DEV_STATUS:
  237.                 if(0 == gizDataPoints2ReportData(&gizwitsProtocol.gizLastDataPoint,&gizwitsProtocol.reportData.devStatus))
  238.                 {
  239.                     memcpy(outData+1, (uint8_t *)&gizwitsProtocol.reportData.devStatus, sizeof(gizwitsReport_t));
  240.                     outData[0] = ACTION_READ_DEV_STATUS_ACK;
  241.                     *outLen = sizeof(gizwitsReport_t)+1;
  242.                 }
  243.                 else
  244.                 {
  245.                     return -1;
  246.                 }
  247.                 break;
  248.             case ACTION_W2D_TRANSPARENT_DATA:
  249.                 memcpy(gizwitsProtocol.transparentBuff, &inData[1], inLen-1);
  250.                 gizwitsProtocol.transparentLen = inLen - 1;
  251.                
  252.                 gizwitsProtocol.issuedProcessEvent.event[gizwitsProtocol.issuedProcessEvent.num] = TRANSPARENT_DATA;
  253.                 gizwitsProtocol.issuedProcessEvent.num++;
  254.                 gizwitsProtocol.issuedFlag = ACTION_W2D_TRANSPARENT_TYPE;
  255.                 outData = NULL;
  256.                 *outLen = 0;
  257.                 break;
  258.             
  259.                 default:
  260.                     break;
  261.         }
  262.     }

  263.     return 0;
  264. }
  265. /**
  266. * @brief The protocol sends data back , P0 ACK
  267. *
  268. * @param [in] head                  : Protocol head pointer
  269. * @param [in] data                  : Payload data
  270. * @param [in] len                   : Payload data length
  271. * @param [in] proFlag               : DID flag ,1 for Virtual sub device did ,0 for single product or gateway
  272. *
  273. * @return : 0,Ack success;
  274. *           -1,Input Param Illegal
  275. *           -2,Serial send faild
  276. */
  277. static int32_t gizProtocolIssuedDataAck(protocolHead_t *head, uint8_t *gizdata, uint32_t len, uint8_t proFlag)
  278. {
  279.     int32_t ret = 0;
  280.     uint8_t tx_buf[RB_MAX_LEN];
  281.     uint32_t offset = 0;
  282.     uint8_t sDidLen = 0;
  283.     uint16_t data_len = 0;
  284.         uint8_t *pTxBuf = tx_buf;
  285.     if(NULL == gizdata)
  286.     {
  287.         GIZWITS_LOG("[ERR]  data Is Null \n");
  288.         return -1;
  289.     }
  290.    

  291.     if(0x1 == proFlag)
  292.     {
  293.         sDidLen = *((uint8_t *)head + sizeof(protocolHead_t));
  294.         data_len = 5 + 1 + sDidLen + len;   
  295.     }
  296.     else
  297.     {
  298.         data_len = 5 + len;
  299.     }
  300.     GIZWITS_LOG("len = %d , sDidLen = %d ,data_len = %d\n", len,sDidLen,data_len);
  301.     *pTxBuf ++= 0xFF;
  302.     *pTxBuf ++= 0xFF;
  303.     *pTxBuf ++= (uint8_t)(data_len>>8);
  304.     *pTxBuf ++= (uint8_t)(data_len);
  305.     *pTxBuf ++= head->cmd + 1;
  306.     *pTxBuf ++= head->sn;
  307.     *pTxBuf ++= 0x00;
  308.     *pTxBuf ++= proFlag;
  309.     offset = 8;
  310.     if(0x1 == proFlag)
  311.     {
  312.         *pTxBuf ++= sDidLen;
  313.         offset += 1;
  314.         memcpy(&tx_buf[offset],(uint8_t *)head+sizeof(protocolHead_t)+1,sDidLen);
  315.         offset += sDidLen;
  316.         pTxBuf += sDidLen;

  317.     }
  318.     if(0 != len)
  319.     {
  320.         memcpy(&tx_buf[offset],gizdata,len);
  321.     }
  322.     tx_buf[data_len + 4 - 1 ] = gizProtocolSum( tx_buf , (data_len+4));

  323.     ret = uartWrite(tx_buf, data_len+4);
  324.     if(ret < 0)
  325.     {
  326.         GIZWITS_LOG("uart write error %d \n", ret);
  327.         return -2;
  328.     }

  329.     return 0;
  330. }

  331. /**
  332. * @brief Report data interface
  333. *
  334. * @param [in] action            : PO action
  335. * @param [in] data              : Payload data
  336. * @param [in] len               : Payload data length
  337. *
  338. * @return : 0,Ack success;
  339. *           -1,Input Param Illegal
  340. *           -2,Serial send faild
  341. */
  342. static int32_t gizReportData(uint8_t action, uint8_t *gizdata, uint32_t len)
  343. {
  344.     int32_t ret = 0;
  345.     protocolReport_t protocolReport;

  346.     if(NULL == gizdata)
  347.     {
  348.         GIZWITS_LOG("gizReportData Error , Illegal Param\n");
  349.         return -1;
  350.     }
  351.     gizProtocolHeadInit((protocolHead_t *)&protocolReport);
  352.     protocolReport.head.cmd = CMD_REPORT_P0;
  353.     protocolReport.head.sn = gizwitsProtocol.sn++;
  354.     protocolReport.action = action;
  355.     protocolReport.head.len = exchangeBytes(sizeof(protocolReport_t)-4);
  356.     memcpy((gizwitsReport_t *)&protocolReport.reportData, (gizwitsReport_t *)gizdata,len);
  357.     protocolReport.sum = gizProtocolSum((uint8_t *)&protocolReport, sizeof(protocolReport_t));
  358.    
  359.     ret = uartWrite((uint8_t *)&protocolReport, sizeof(protocolReport_t));
  360.     if(ret < 0)
  361.     {
  362.         GIZWITS_LOG("ERR: uart write error %d \n", ret);
  363.         return -2;
  364.     }

  365.     gizProtocolWaitAck((uint8_t *)&protocolReport, sizeof(protocolReport_t));

  366.     return ret;
  367. }/**
  368. * @brief Datapoints reporting mechanism
  369. *
  370. * 1. Changes are reported immediately

  371. * 2. Data timing report , 600000 Millisecond
  372. *
  373. *@param [in] currentData       : Current datapoints value
  374. * @return : NULL
  375. */
  376. static void gizDevReportPolicy(dataPoint_t *currentData)
  377. {
  378.     static uint32_t lastRepTime = 0;
  379.     uint32_t timeNow = gizGetTimerCount();

  380.     if((1 == gizCheckReport(currentData, (dataPoint_t *)&gizwitsProtocol.gizLastDataPoint)))
  381.     {
  382.         GIZWITS_LOG("changed, report data\n");
  383.         if(0 == gizDataPoints2ReportData(currentData,&gizwitsProtocol.reportData.devStatus))
  384.         {
  385.             gizReportData(ACTION_REPORT_DEV_STATUS, (uint8_t *)&gizwitsProtocol.reportData.devStatus, sizeof(devStatus_t));        }      
  386.         memcpy((uint8_t *)&gizwitsProtocol.gizLastDataPoint, (uint8_t *)currentData, sizeof(dataPoint_t));
  387.     }

  388.     if((0 == (timeNow % (600000))) && (lastRepTime != timeNow))
  389.     {
  390.         GIZWITS_LOG("Info: 600S report data\n");
  391.         if(0 == gizDataPoints2ReportData(currentData,&gizwitsProtocol.reportData.devStatus))
  392.         {
  393.             gizReportData(ACTION_REPORT_DEV_STATUS, (uint8_t *)&gizwitsProtocol.reportData.devStatus, sizeof(devStatus_t));
  394.         }      
  395.         memcpy((uint8_t *)&gizwitsProtocol.gizLastDataPoint, (uint8_t *)currentData, sizeof(dataPoint_t));

  396.         lastRepTime = timeNow;
  397.     }
  398. }

  399. /**
  400. * @brief Get a packet of data from the ring buffer
  401. *
  402. * @param [in]  rb                  : Input data address
  403. * @param [out] data                : Output data address
  404. * @param [out] len                 : Output data length
  405. *
  406. * @return : 0,Return correct ;-1,Return failure;-2,Data check failure
  407. */
  408. static int8_t gizProtocolGetOnePacket(rb_t *rb, uint8_t *gizdata, uint16_t *len)
  409. {
  410.     int32_t ret = 0;
  411.     uint8_t sum = 0;
  412.     int32_t i = 0;
  413.     uint8_t tmpData;
  414.     uint8_t tmpLen = 0;
  415.     uint16_t tmpCount = 0;
  416.     static uint8_t protocolFlag = 0;
  417.     static uint16_t protocolCount = 0;
  418.     static uint8_t lastData = 0;
  419.     static uint8_t debugCount = 0;
  420.     uint8_t *protocolBuff = gizdata;
  421.     protocolHead_t *head = NULL;

  422.     if((NULL == rb) || (NULL == gizdata) ||(NULL == len))
  423.     {
  424.         GIZWITS_LOG("gizProtocolGetOnePacket Error , Illegal Param\n");
  425.         return -1;
  426.     }

  427.     tmpLen = rbCanRead(rb);
  428.     if(0 == tmpLen)
  429.     {
  430.         return -1;
  431.     }

  432.     for(i=0; i<tmpLen; i++)
  433.     {
  434.         ret = rbRead(rb, &tmpData, 1);
  435.         if(0 != ret)
  436.         {
  437.             if((0xFF == lastData) && (0xFF == tmpData))
  438.             {
  439.                 if(0 == protocolFlag)
  440.                 {
  441.                     protocolBuff[0] = 0xFF;
  442.                     protocolBuff[1] = 0xFF;
  443.                     protocolCount = 2;
  444.                     protocolFlag = 1;
  445.                 }
  446.                 else
  447.                 {
  448.                     if((protocolCount > 4) && (protocolCount != tmpCount))
  449.                     {
  450.                         protocolBuff[0] = 0xFF;
  451.                         protocolBuff[1] = 0xFF;
  452.                         protocolCount = 2;
  453.                     }
  454.                 }
  455.             }
  456.             else if((0xFF == lastData) && (0x55 == tmpData))
  457.             {
  458.             }
  459.             else
  460.             {
  461.                 if(1 == protocolFlag)
  462.                 {
  463.                     protocolBuff[protocolCount] = tmpData;
  464.                     protocolCount++;

  465.                     if(protocolCount > 4)
  466.                     {
  467.                         head = (protocolHead_t *)protocolBuff;
  468.                         tmpCount = exchangeBytes(head->len)+4;
  469.                         if(protocolCount == tmpCount)
  470.                         {
  471.                             break;
  472.                         }
  473.                     }
  474.                 }
  475.             }

  476.             lastData = tmpData;
  477.             debugCount++;
  478.         }
  479.     }

  480.     if((protocolCount > 4) && (protocolCount == tmpCount))
  481.     {
  482.         sum = gizProtocolSum(protocolBuff, protocolCount);

  483.         if(protocolBuff[protocolCount-1] == sum)
  484.         {
  485.             memcpy(gizdata, protocolBuff, tmpCount);
  486.             *len = tmpCount;
  487.             protocolFlag = 0;

  488.             protocolCount = 0;
  489.             debugCount = 0;
  490.             lastData = 0;

  491.             return 0;
  492.         }
  493.         else
  494.         {
  495.             return -2;
  496.         }
  497.     }

  498.     return 1;
  499. }



  500. /**
  501. * @brief Protocol data resend

  502. * The protocol data resend when check timeout and meet the resend limiting

  503. * @param none   
  504. *
  505. * @return none
  506. */
  507. static void gizProtocolResendData(void)
  508. {
  509.     int32_t ret = 0;

  510.     if(0 == gizwitsProtocol.waitAck.flag)
  511.     {
  512.         return;
  513.     }

  514.     GIZWITS_LOG("Warning: timeout, resend data \n");
  515.    
  516.     ret = uartWrite(gizwitsProtocol.waitAck.buf, gizwitsProtocol.waitAck.dataLen);
  517.     if(ret != gizwitsProtocol.waitAck.dataLen)
  518.     {
  519.         GIZWITS_LOG("ERR: resend data error\n");
  520.     }

  521.     gizwitsProtocol.waitAck.sendTime = gizGetTimerCount();
  522. }

  523. /**
  524. * @brief Clear the ACK protocol message
  525. *
  526. * @param [in] head : Protocol header address
  527. *
  528. * @return 0, success; other, failure
  529. */
  530. static int8_t gizProtocolWaitAckCheck(protocolHead_t *head)
  531. {
  532.     protocolHead_t *waitAckHead = (protocolHead_t *)gizwitsProtocol.waitAck.buf;

  533.     if(NULL == head)
  534.     {
  535.         GIZWITS_LOG("ERR: data is empty \n");
  536.         return -1;
  537.     }

  538.     if(waitAckHead->cmd+1 == head->cmd)
  539.     {
  540.         memset((uint8_t *)&gizwitsProtocol.waitAck, 0, sizeof(protocolWaitAck_t));
  541.     }

  542.     return 0;
  543. }

  544. /**
  545. * @brief Send general protocol message data
  546. *
  547. * @param [in] head              : Protocol header address
  548. *
  549. * @return : Return effective data length;-1,return failure
  550. */
  551. static int32_t gizProtocolCommonAck(protocolHead_t *head)
  552. {
  553.     int32_t ret = 0;
  554.     protocolCommon_t ack;

  555.     if(NULL == head)
  556.     {
  557.         GIZWITS_LOG("ERR: gizProtocolCommonAck data is empty \n");
  558.         return -1;
  559.     }
  560.     memcpy((uint8_t *)&ack, (uint8_t *)head, sizeof(protocolHead_t));
  561.     ack.head.cmd = ack.head.cmd+1;
  562.     ack.head.len = exchangeBytes(sizeof(protocolCommon_t)-4);
  563.     ack.sum = gizProtocolSum((uint8_t *)&ack, sizeof(protocolCommon_t));

  564.     ret = uartWrite((uint8_t *)&ack, sizeof(protocolCommon_t));
  565.     if(ret < 0)
  566.     {
  567.         GIZWITS_LOG("ERR: uart write error %d \n", ret);
  568.     }

  569.     return ret;
  570. }

  571. /**
  572. * @brief ACK processing function

  573. * Time-out 200ms no ACK resend,resend two times at most

  574. * @param none
  575. *
  576. * @return none
  577. */
  578. static void gizProtocolAckHandle(void)
  579. {
  580.     if(1 == gizwitsProtocol.waitAck.flag)
  581.     {
  582.         if(SEND_MAX_NUM > gizwitsProtocol.waitAck.num)
  583.         {
  584.             // Time-out no ACK resend
  585.             if(SEND_MAX_TIME < (gizGetTimerCount() - gizwitsProtocol.waitAck.sendTime))
  586.             {
  587.                 GIZWITS_LOG("Warning:gizProtocolResendData %d %d %d\n", gizGetTimerCount(), gizwitsProtocol.waitAck.sendTime, gizwitsProtocol.waitAck.num);
  588.                 gizProtocolResendData();
  589.                 gizwitsProtocol.waitAck.num++;
  590.             }
  591.         }
  592.         else
  593.         {
  594.             memset((uint8_t *)&gizwitsProtocol.waitAck, 0, sizeof(protocolWaitAck_t));
  595.         }
  596.     }
  597. }

  598. /**
  599. * @brief Protocol 4.1 WiFi module requests device information
  600. *
  601. * @param[in] head : Protocol header address
  602. *
  603. * @return Return effective data length;-1,return failure
  604. */
  605. static int32_t gizProtocolGetDeviceInfo(protocolHead_t * head)
  606. {
  607.     int32_t ret = 0;
  608.     protocolDeviceInfo_t deviceInfo;

  609.     if(NULL == head)
  610.     {
  611.         GIZWITS_LOG("gizProtocolGetDeviceInfo Error , Illegal Param\n");
  612.         return -1;
  613.     }

  614.     gizProtocolHeadInit((protocolHead_t *)&deviceInfo);
  615.     deviceInfo.head.cmd = ACK_GET_DEVICE_INFO;
  616.     deviceInfo.head.sn = head->sn;
  617.     memcpy((uint8_t *)deviceInfo.protocolVer, protocol_VERSION, 8);
  618.     memcpy((uint8_t *)deviceInfo.p0Ver, P0_VERSION, 8);
  619.     memcpy((uint8_t *)deviceInfo.softVer, SOFTWARE_VERSION, 8);
  620.     memcpy((uint8_t *)deviceInfo.hardVer, HARDWARE_VERSION, 8);
  621.     memcpy((uint8_t *)deviceInfo.productKey, PRODUCT_KEY, strlen(PRODUCT_KEY));
  622.     memcpy((uint8_t *)deviceInfo.productSecret, PRODUCT_SECRET, strlen(PRODUCT_SECRET));
  623.     memset((uint8_t *)deviceInfo.devAttr, 0, 8);
  624.     deviceInfo.devAttr[7] |= DEV_IS_GATEWAY<<0;
  625.     deviceInfo.devAttr[7] |= (0x01<<1);
  626.     deviceInfo.ninableTime = exchangeBytes(NINABLETIME);
  627.     deviceInfo.head.len = exchangeBytes(sizeof(protocolDeviceInfo_t)-4);
  628.     deviceInfo.sum = gizProtocolSum((uint8_t *)&deviceInfo, sizeof(protocolDeviceInfo_t));

  629.     ret = uartWrite((uint8_t *)&deviceInfo, sizeof(protocolDeviceInfo_t));
  630.     if(ret < 0)
  631.     {
  632.         GIZWITS_LOG("ERR: uart write error %d \n", ret);
  633.     }
  634.    
  635.     return ret;
  636. }

  637. /**
  638. * @brief Protocol 4.7 Handling of illegal message notification

  639. * @param[in] head  : Protocol header address
  640. * @param[in] errno : Illegal message notification type
  641. * @return 0, success; other, failure
  642. */
  643. static int32_t gizProtocolErrorCmd(protocolHead_t *head,errorPacketsType_t errno)
  644. {
  645.     int32_t ret = 0;
  646.     protocolErrorType_t errorType;

  647.     if(NULL == head)
  648.     {
  649.         GIZWITS_LOG("gizProtocolErrorCmd Error , Illegal Param\n");
  650.         return -1;
  651.     }
  652.     gizProtocolHeadInit((protocolHead_t *)&errorType);
  653.     errorType.head.cmd = ACK_ERROR_PACKAGE;
  654.     errorType.head.sn = head->sn;
  655.    
  656.     errorType.head.len = exchangeBytes(sizeof(protocolErrorType_t)-4);
  657.     errorType.error = errno;
  658.     errorType.sum = gizProtocolSum((uint8_t *)&errorType, sizeof(protocolErrorType_t));
  659.    
  660.     ret = uartWrite((uint8_t *)&errorType, sizeof(protocolErrorType_t));
  661.     if(ret < 0)
  662.     {
  663.         GIZWITS_LOG("ERR: uart write error %d \n", ret);
  664.     }

  665.     return ret;
  666. }

  667. /**
  668. * @brief Protocol 4.13 Get and process network time
  669. *
  670. * @param [in] head : Protocol header address
  671. *
  672. * @return 0, success; other, failure
  673. */
  674. static int8_t gizProtocolNTP(protocolHead_t *head)
  675. {  
  676.     protocolUTT_t *UTTInfo = (protocolUTT_t *)head;
  677.    
  678.     if(NULL == head)
  679.     {
  680.         GIZWITS_LOG("ERR: NTP is empty \n");
  681.         return -1;
  682.     }
  683.    
  684.     memcpy((uint8_t *)&gizwitsProtocol.TimeNTP,(uint8_t *)UTTInfo->time, (7 + 4));
  685.     gizwitsProtocol.TimeNTP.year = exchangeBytes(gizwitsProtocol.TimeNTP.year);
  686.     gizwitsProtocol.TimeNTP.ntp =exchangeWord(gizwitsProtocol.TimeNTP.ntp);

  687.     gizwitsProtocol.NTPEvent.event[gizwitsProtocol.NTPEvent.num] = WIFI_NTP;
  688.     gizwitsProtocol.NTPEvent.num++;
  689.    
  690.     gizwitsProtocol.issuedFlag = GET_NTP_TYPE;
  691.    
  692.    
  693.     return 0;
  694. }

  695. /**
  696. * @brief Protocol 4.4 Device MCU restarts function

  697. * @param none
  698. * @return none
  699. */
  700. static void gizProtocolReboot(void)
  701. {
  702.     uint32_t timeDelay = gizGetTimerCount();
  703.    
  704.     /*Wait 600ms*/
  705.     while((gizGetTimerCount() - timeDelay) <= 600);
  706.     mcuRestart();
  707. }

  708. /**
  709. * @brief Protocol 4.5 :The WiFi module informs the device MCU of working status about the WiFi module

  710. * @param[in] status WiFi module working status
  711. * @return none
  712. */
  713. static int8_t gizProtocolModuleStatus(protocolWifiStatus_t *status)
  714. {
  715.     static wifiStatus_t lastStatus;

  716.     if(NULL == status)
  717.     {
  718.         GIZWITS_LOG("gizProtocolModuleStatus Error , Illegal Param\n");
  719.         return -1;
  720.     }

  721.     status->ststus.value = exchangeBytes(status->ststus.value);
  722.    
  723.     //OnBoarding mode status
  724.     if(lastStatus.types.onboarding != status->ststus.types.onboarding)
  725.     {
  726.         if(1 == status->ststus.types.onboarding)
  727.         {
  728.             if(1 == status->ststus.types.softap)
  729.             {
  730.                 gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_SOFTAP;
  731.                 gizwitsProtocol.wifiStatusEvent.num++;
  732.                 GIZWITS_LOG("OnBoarding: SoftAP or Web mode\n");
  733.             }

  734.             if(1 == status->ststus.types.station)
  735.             {
  736.                 gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_AIRLINK;
  737.                 gizwitsProtocol.wifiStatusEvent.num++;
  738.                 GIZWITS_LOG("OnBoarding: AirLink mode\n");
  739.             }
  740.         }
  741.         else
  742.         {
  743.             if(1 == status->ststus.types.softap)
  744.             {
  745.                 gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_SOFTAP;
  746.                 gizwitsProtocol.wifiStatusEvent.num++;
  747.                 GIZWITS_LOG("OnBoarding: SoftAP or Web mode\n");
  748.             }

  749.             if(1 == status->ststus.types.station)
  750.             {
  751.                 gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_STATION;
  752.                 gizwitsProtocol.wifiStatusEvent.num++;
  753.                 GIZWITS_LOG("OnBoarding: Station mode\n");
  754.             }
  755.         }
  756.     }

  757.     //binding mode status
  758.     if(lastStatus.types.binding != status->ststus.types.binding)
  759.     {
  760.         lastStatus.types.binding = status->ststus.types.binding;
  761.         if(1 == status->ststus.types.binding)
  762.         {
  763.             gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_OPEN_BINDING;
  764.             gizwitsProtocol.wifiStatusEvent.num++;
  765.             GIZWITS_LOG("WiFi status: in binding mode\n");
  766.         }
  767.         else
  768.         {
  769.             gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_CLOSE_BINDING;
  770.             gizwitsProtocol.wifiStatusEvent.num++;
  771.             GIZWITS_LOG("WiFi status: out binding mode\n");
  772.         }
  773.     }

  774.     //router status
  775.     if(lastStatus.types.con_route != status->ststus.types.con_route)
  776.     {
  777.         lastStatus.types.con_route = status->ststus.types.con_route;
  778.         if(1 == status->ststus.types.con_route)
  779.         {
  780.             gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_CON_ROUTER;
  781.             gizwitsProtocol.wifiStatusEvent.num++;
  782.             GIZWITS_LOG("WiFi status: connected router\n");
  783.         }
  784.         else
  785.         {
  786.             gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_DISCON_ROUTER;
  787.             gizwitsProtocol.wifiStatusEvent.num++;
  788.             GIZWITS_LOG("WiFi status: disconnected router\n");
  789.         }
  790.     }

  791.     //M2M server status
  792.     if(lastStatus.types.con_m2m != status->ststus.types.con_m2m)
  793.     {
  794.         lastStatus.types.con_m2m = status->ststus.types.con_m2m;
  795.         if(1 == status->ststus.types.con_m2m)
  796.         {
  797.             gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_CON_M2M;
  798.             gizwitsProtocol.wifiStatusEvent.num++;
  799.             GIZWITS_LOG("WiFi status: connected m2m\n");
  800.         }
  801.         else
  802.         {
  803.             gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_DISCON_M2M;
  804.             gizwitsProtocol.wifiStatusEvent.num++;
  805.             GIZWITS_LOG("WiFi status: disconnected m2m\n");
  806.         }
  807.     }

  808.     //APP status
  809.     if(lastStatus.types.app != status->ststus.types.app)
  810.     {
  811.         lastStatus.types.app = status->ststus.types.app;
  812.         if(1 == status->ststus.types.app)
  813.         {
  814.             gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_CON_APP;
  815.             gizwitsProtocol.wifiStatusEvent.num++;
  816.             GIZWITS_LOG("WiFi status: app connect\n");
  817.         }
  818.         else
  819.         {
  820.             gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_DISCON_APP;
  821.             gizwitsProtocol.wifiStatusEvent.num++;
  822.             GIZWITS_LOG("WiFi status: no app connect\n");
  823.         }
  824.     }

  825.     //test mode status
  826.     if(lastStatus.types.test != status->ststus.types.test)
  827.     {
  828.         lastStatus.types.test = status->ststus.types.test;
  829.         if(1 == status->ststus.types.test)
  830.         {
  831.             gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_OPEN_TESTMODE;
  832.             gizwitsProtocol.wifiStatusEvent.num++;
  833.             GIZWITS_LOG("WiFi status: in test mode\n");
  834.         }
  835.         else
  836.         {
  837.             gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_CLOSE_TESTMODE;
  838.             gizwitsProtocol.wifiStatusEvent.num++;
  839.             GIZWITS_LOG("WiFi status: out test mode\n");
  840.         }
  841.     }

  842.     gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_RSSI;
  843.     gizwitsProtocol.wifiStatusEvent.num++;
  844.     gizwitsProtocol.wifiStatusData.rssi = status->ststus.types.rssi;
  845.     GIZWITS_LOG("RSSI is %d \n", gizwitsProtocol.wifiStatusData.rssi);

  846.     gizwitsProtocol.issuedFlag = WIFI_STATUS_TYPE;

  847.     return 0;
  848. }


  849. /**@name Gizwits User API interface
  850. * @{
  851. */

  852. /**
  853. * @brief gizwits Protocol initialization interface

  854. * Protocol-related timer, serial port initialization

  855. * Datapoint initialization

  856. * @param none
  857. * @return none
  858. */
  859. void gizwitsInit(void)
  860. {   
  861.     pRb.rbCapacity = RB_MAX_LEN;
  862.     pRb.rbBuff = rbBuf;
  863.     if(0 == rbCreate(&pRb))
  864.         {
  865.                 GIZWITS_LOG("rbCreate Success \n");
  866.         }
  867.         else
  868.         {
  869.                 GIZWITS_LOG("rbCreate Faild \n");
  870.         }
  871.    
  872.     memset((uint8_t *)&gizwitsProtocol, 0, sizeof(gizwitsProtocol_t));
  873. }

  874. /**
  875. * @brief WiFi configure interface

  876. * Set the WiFi module into the corresponding configuration mode or reset the module

  877. * @param[in] mode :0x0, reset the module ;0x01, SoftAp mode ;0x02, AirLink mode ;0x03, Production test mode; 0x04:allow users to bind devices

  878. * @return Error command code
  879. */
  880. int32_t gizwitsSetMode(uint8_t mode)
  881. {
  882.     int32_t ret = 0;
  883.     protocolCfgMode_t cfgMode;
  884.     protocolCommon_t setDefault;

  885.     switch(mode)
  886.     {
  887.         case WIFI_RESET_MODE:
  888.             gizProtocolHeadInit((protocolHead_t *)&setDefault);
  889.             setDefault.head.cmd = CMD_SET_DEFAULT;
  890.             setDefault.head.sn = gizwitsProtocol.sn++;
  891.             setDefault.head.len = exchangeBytes(sizeof(protocolCommon_t)-4);
  892.             setDefault.sum = gizProtocolSum((uint8_t *)&setDefault, sizeof(protocolCommon_t));
  893.             ret = uartWrite((uint8_t *)&setDefault, sizeof(protocolCommon_t));
  894.             if(ret < 0)
  895.             {
  896.                 GIZWITS_LOG("ERR: uart write error %d \n", ret);
  897.             }

  898.             gizProtocolWaitAck((uint8_t *)&setDefault, sizeof(protocolCommon_t));   
  899.             break;
  900.         case WIFI_SOFTAP_MODE:
  901.             gizProtocolHeadInit((protocolHead_t *)&cfgMode);
  902.             cfgMode.head.cmd = CMD_WIFI_CONFIG;
  903.             cfgMode.head.sn = gizwitsProtocol.sn++;
  904.             cfgMode.cfgMode = mode;
  905.             cfgMode.head.len = exchangeBytes(sizeof(protocolCfgMode_t)-4);
  906.             cfgMode.sum = gizProtocolSum((uint8_t *)&cfgMode, sizeof(protocolCfgMode_t));
  907.             ret = uartWrite((uint8_t *)&cfgMode, sizeof(protocolCfgMode_t));
  908.             if(ret < 0)
  909.             {
  910.                 GIZWITS_LOG("ERR: uart write error %d \n", ret);
  911.             }
  912.             gizProtocolWaitAck((uint8_t *)&cfgMode, sizeof(protocolCfgMode_t));
  913.             break;
  914.         case WIFI_AIRLINK_MODE:
  915.             gizProtocolHeadInit((protocolHead_t *)&cfgMode);
  916.             cfgMode.head.cmd = CMD_WIFI_CONFIG;
  917.             cfgMode.head.sn = gizwitsProtocol.sn++;
  918.             cfgMode.cfgMode = mode;
  919.             cfgMode.head.len = exchangeBytes(sizeof(protocolCfgMode_t)-4);
  920.             cfgMode.sum = gizProtocolSum((uint8_t *)&cfgMode, sizeof(protocolCfgMode_t));
  921.             ret = uartWrite((uint8_t *)&cfgMode, sizeof(protocolCfgMode_t));
  922.             if(ret < 0)
  923.             {
  924.                 GIZWITS_LOG("ERR: uart write error %d \n", ret);
  925.             }
  926.             gizProtocolWaitAck((uint8_t *)&cfgMode, sizeof(protocolCfgMode_t));
  927.             break;
  928.         case WIFI_PRODUCTION_TEST:
  929.             gizProtocolHeadInit((protocolHead_t *)&setDefault);
  930.             setDefault.head.cmd = CMD_PRODUCTION_TEST;
  931.             setDefault.head.sn = gizwitsProtocol.sn++;
  932.             setDefault.head.len = exchangeBytes(sizeof(protocolCommon_t)-4);
  933.             setDefault.sum = gizProtocolSum((uint8_t *)&setDefault, sizeof(protocolCommon_t));
  934.             ret = uartWrite((uint8_t *)&setDefault, sizeof(protocolCommon_t));
  935.             if(ret < 0)
  936.             {
  937.                 GIZWITS_LOG("ERR: uart write error %d \n", ret);
  938.             }

  939.             gizProtocolWaitAck((uint8_t *)&setDefault, sizeof(protocolCommon_t));
  940.             break;
  941.         case WIFI_NINABLE_MODE:
  942.             gizProtocolHeadInit((protocolHead_t *)&setDefault);
  943.             setDefault.head.cmd = CMD_NINABLE_MODE;
  944.             setDefault.head.sn = gizwitsProtocol.sn++;
  945.             setDefault.head.len = exchangeBytes(sizeof(protocolCommon_t)-4);
  946.             setDefault.sum = gizProtocolSum((uint8_t *)&setDefault, sizeof(protocolCommon_t));
  947.             ret = uartWrite((uint8_t *)&setDefault, sizeof(protocolCommon_t));
  948.             if(ret < 0)
  949.             {
  950.                 GIZWITS_LOG("ERR: uart write error %d \n", ret);
  951.             }

  952.             gizProtocolWaitAck((uint8_t *)&setDefault, sizeof(protocolCommon_t));
  953.             break;
  954.         case WIFI_REBOOT_MODE:
  955.             gizProtocolHeadInit((protocolHead_t *)&setDefault);
  956.             setDefault.head.cmd = CMD_REBOOT_MODULE;
  957.             setDefault.head.sn = gizwitsProtocol.sn++;
  958.             setDefault.head.len = exchangeBytes(sizeof(protocolCommon_t)-4);
  959.             setDefault.sum = gizProtocolSum((uint8_t *)&setDefault, sizeof(protocolCommon_t));
  960.             ret = uartWrite((uint8_t *)&setDefault, sizeof(protocolCommon_t));
  961.             if(ret < 0)
  962.             {
  963.                 GIZWITS_LOG("ERR: uart write error %d \n", ret);
  964.             }

  965.             gizProtocolWaitAck((uint8_t *)&setDefault, sizeof(protocolCommon_t));
  966.             break;
  967.         default:
  968.             GIZWITS_LOG("ERR: CfgMode error!\n");
  969.             break;
  970.     }

  971.     return ret;
  972. }

  973. /**
  974. * @brief Get the the network time

  975. * Protocol 4.13:"Device MCU send" of "the MCU requests access to the network time"

  976. * @param[in] none
  977. * @return none
  978. */
  979. void gizwitsGetNTP(void)
  980. {
  981.     int32_t ret = 0;
  982.     protocolCommon_t getNTP;

  983.     gizProtocolHeadInit((protocolHead_t *)&getNTP);
  984.     getNTP.head.cmd = CMD_GET_NTP;
  985.     getNTP.head.sn = gizwitsProtocol.sn++;
  986.     getNTP.head.len = exchangeBytes(sizeof(protocolCommon_t)-4);
  987.     getNTP.sum = gizProtocolSum((uint8_t *)&getNTP, sizeof(protocolCommon_t));
  988.     ret = uartWrite((uint8_t *)&getNTP, sizeof(protocolCommon_t));
  989.     if(ret < 0)
  990.     {
  991.         GIZWITS_LOG("ERR[NTP]: uart write error %d \n", ret);
  992.     }

  993.     gizProtocolWaitAck((uint8_t *)&getNTP, sizeof(protocolCommon_t));
  994. }


  995. /**
  996. * @brief Get Module Info

  997. *

  998. * @param[in] none
  999. * @return none
  1000. */
  1001. void gizwitsGetModuleInfo(void)
  1002. {
  1003.     int32_t ret = 0;
  1004.     protocolGetModuleInfo_t getModuleInfo;

  1005.     gizProtocolHeadInit((protocolHead_t *)&getModuleInfo);
  1006.     getModuleInfo.head.cmd = CMD_ASK_MODULE_INFO;
  1007.     getModuleInfo.head.sn = gizwitsProtocol.sn++;
  1008.     getModuleInfo.type = 0x0;
  1009.     getModuleInfo.head.len = exchangeBytes(sizeof(protocolGetModuleInfo_t)-4);
  1010.     getModuleInfo.sum = gizProtocolSum((uint8_t *)&getModuleInfo, sizeof(protocolGetModuleInfo_t));
  1011.     ret = uartWrite((uint8_t *)&getModuleInfo, sizeof(protocolGetModuleInfo_t));
  1012.     if(ret < 0)
  1013.     {
  1014.         GIZWITS_LOG("ERR[NTP]: uart write error %d \n", ret);
  1015.     }

  1016.     gizProtocolWaitAck((uint8_t *)&getModuleInfo, sizeof(protocolGetModuleInfo_t));
  1017. }


  1018. /**
  1019. * @brief Module Info Analyse
  1020. *
  1021. * @param [in] head :
  1022. *
  1023. * @return 0, Success, , other,Faild
  1024. */
  1025. static int8_t gizProtocolModuleInfoHandle(protocolHead_t *head)
  1026. {
  1027.     protocolModuleInfo_t *moduleInfo = (protocolModuleInfo_t *)head;

  1028.     if(NULL == head)
  1029.     {
  1030.         GIZWITS_LOG("NTP is empty \n");
  1031.         return -1;
  1032.     }

  1033.     memcpy((uint8_t *)&gizwitsProtocol.wifiModuleNews,(uint8_t *)&moduleInfo->wifiModuleInfo, sizeof(moduleInfo_t));

  1034.     gizwitsProtocol.moduleInfoEvent.event[gizwitsProtocol.moduleInfoEvent.num] = MODULE_INFO;
  1035.     gizwitsProtocol.moduleInfoEvent.num++;

  1036.     gizwitsProtocol.issuedFlag = GET_MODULEINFO_TYPE;


  1037.     return 0;
  1038. }

  1039. /**
  1040. * @brief Protocol handling function

  1041. *

  1042. * @param [in] currentData :The protocol data pointer
  1043. * @return none
  1044. */
  1045. int32_t gizwitsHandle(dataPoint_t *currentData)
  1046. {
  1047.     int8_t ret = 0;
  1048. #ifdef PROTOCOL_DEBUG
  1049.     uint16_t i = 0;
  1050. #endif
  1051.     uint8_t ackData[RB_MAX_LEN];
  1052.     uint16_t protocolLen = 0;
  1053.     uint32_t ackLen = 0;
  1054.     protocolHead_t *recvHead = NULL;
  1055.     char *didPtr = NULL;
  1056.     uint16_t offset = 0;


  1057.     if(NULL == currentData)
  1058.     {
  1059.         GIZWITS_LOG("GizwitsHandle Error , Illegal Param\n");
  1060.         return -1;
  1061.     }

  1062.     /*resend strategy*/
  1063.     gizProtocolAckHandle();
  1064.     ret = gizProtocolGetOnePacket(&pRb, gizwitsProtocol.protocolBuf, &protocolLen);

  1065.     if(0 == ret)
  1066.     {
  1067.         GIZWITS_LOG("Get One Packet!\n");
  1068.         
  1069. #ifdef PROTOCOL_DEBUG
  1070.         GIZWITS_LOG("WiFi2MCU[%4d:%4d]: ", gizGetTimerCount(), protocolLen);
  1071.         for(i=0; i<protocolLen;i++)
  1072.         {
  1073.             GIZWITS_LOG("%02x ", gizwitsProtocol.protocolBuf[i]);
  1074.         }
  1075.         GIZWITS_LOG("\n");
  1076. #endif

  1077.         recvHead = (protocolHead_t *)gizwitsProtocol.protocolBuf;
  1078.         switch (recvHead->cmd)
  1079.         {
  1080.             case CMD_GET_DEVICE_INTO:
  1081.                 gizProtocolGetDeviceInfo(recvHead);
  1082.                 break;
  1083.             case CMD_ISSUED_P0:
  1084.                 GIZWITS_LOG("flag %x %x \n", recvHead->flags[0], recvHead->flags[1]);
  1085.                 //offset = 1;
  1086.                
  1087.                 if(0 == gizProtocolIssuedProcess(didPtr, gizwitsProtocol.protocolBuf+sizeof(protocolHead_t)+offset, protocolLen-(sizeof(protocolHead_t)+offset+1), ackData, &ackLen))
  1088.                 {
  1089.                     gizProtocolIssuedDataAck(recvHead, ackData, ackLen,recvHead->flags[1]);
  1090.                     GIZWITS_LOG("AckData : \n");
  1091.                 }
  1092.                 break;
  1093.             case CMD_HEARTBEAT:
  1094.                 gizProtocolCommonAck(recvHead);
  1095.                 break;
  1096.             case CMD_WIFISTATUS:
  1097.                 gizProtocolCommonAck(recvHead);
  1098.                 gizProtocolModuleStatus((protocolWifiStatus_t *)recvHead);
  1099.                 break;
  1100.             case ACK_REPORT_P0:
  1101.             case ACK_WIFI_CONFIG:
  1102.             case ACK_SET_DEFAULT:
  1103.             case ACK_NINABLE_MODE:
  1104.             case ACK_REBOOT_MODULE:
  1105.                 gizProtocolWaitAckCheck(recvHead);
  1106.                 break;
  1107.             case CMD_MCU_REBOOT:
  1108.                 gizProtocolCommonAck(recvHead);
  1109.                 GIZWITS_LOG("report:MCU reboot!\n");
  1110.                
  1111.                 gizProtocolReboot();
  1112.                 break;
  1113.             case CMD_ERROR_PACKAGE:
  1114.                 break;
  1115.             case ACK_PRODUCTION_TEST:
  1116.                 gizProtocolWaitAckCheck(recvHead);
  1117.                 GIZWITS_LOG("Ack PRODUCTION_MODE success \n");
  1118.                 break;           
  1119.             case ACK_GET_NTP:
  1120.                 gizProtocolWaitAckCheck(recvHead);
  1121.                 gizProtocolNTP(recvHead);
  1122.                 GIZWITS_LOG("Ack GET_UTT success \n");
  1123.                 break;
  1124.             case ACK_ASK_MODULE_INFO:
  1125.                 gizProtocolWaitAckCheck(recvHead);
  1126.                 gizProtocolModuleInfoHandle(recvHead);
  1127.                 GIZWITS_LOG("Ack GET_Module success \n");
  1128.             break;

  1129.             default:
  1130.                 gizProtocolErrorCmd(recvHead,ERROR_CMD);
  1131.                 GIZWITS_LOG("ERR: cmd code error!\n");
  1132.                 break;
  1133.         }
  1134.     }
  1135.     else if(-2 == ret)
  1136.     {
  1137.         //Check failed, report exception
  1138.         recvHead = (protocolHead_t *)gizwitsProtocol.protocolBuf;
  1139.         gizProtocolErrorCmd(recvHead,ERROR_ACK_SUM);
  1140.         GIZWITS_LOG("ERR: check sum error!\n");
  1141.         return -2;
  1142.     }
  1143.    
  1144.     switch(gizwitsProtocol.issuedFlag)
  1145.     {
  1146.         case ACTION_CONTROL_TYPE:
  1147.             gizwitsProtocol.issuedFlag = STATELESS_TYPE;
  1148.             gizwitsEventProcess(&gizwitsProtocol.issuedProcessEvent, (uint8_t *)&gizwitsProtocol.gizCurrentDataPoint, sizeof(dataPoint_t));
  1149.             memset((uint8_t *)&gizwitsProtocol.issuedProcessEvent,0x0,sizeof(gizwitsProtocol.issuedProcessEvent));  
  1150.             break;
  1151.         case WIFI_STATUS_TYPE:
  1152.             gizwitsProtocol.issuedFlag = STATELESS_TYPE;
  1153.             gizwitsEventProcess(&gizwitsProtocol.wifiStatusEvent, (uint8_t *)&gizwitsProtocol.wifiStatusData, sizeof(moduleStatusInfo_t));
  1154.             memset((uint8_t *)&gizwitsProtocol.wifiStatusEvent,0x0,sizeof(gizwitsProtocol.wifiStatusEvent));
  1155.             break;
  1156.         case ACTION_W2D_TRANSPARENT_TYPE:
  1157.             gizwitsProtocol.issuedFlag = STATELESS_TYPE;
  1158.             gizwitsEventProcess(&gizwitsProtocol.issuedProcessEvent, (uint8_t *)gizwitsProtocol.transparentBuff, gizwitsProtocol.transparentLen);
  1159.             break;
  1160.         case GET_NTP_TYPE:
  1161.             gizwitsProtocol.issuedFlag = STATELESS_TYPE;
  1162.             gizwitsEventProcess(&gizwitsProtocol.NTPEvent, (uint8_t *)&gizwitsProtocol.TimeNTP, sizeof(protocolTime_t));
  1163.             memset((uint8_t *)&gizwitsProtocol.NTPEvent,0x0,sizeof(gizwitsProtocol.NTPEvent));
  1164.             break;
  1165.         case GET_MODULEINFO_TYPE:
  1166.             gizwitsProtocol.issuedFlag = STATELESS_TYPE;
  1167.             gizwitsEventProcess(&gizwitsProtocol.moduleInfoEvent, (uint8_t *)&gizwitsProtocol.wifiModuleNews, sizeof(moduleInfo_t));
  1168.             memset((uint8_t *)&gizwitsProtocol.moduleInfoEvent,0x0,sizeof(moduleInfo_t));
  1169.             break;
  1170.         default:
  1171.             break;      
  1172.     }

  1173.     gizDevReportPolicy(currentData);

  1174.     return 0;
  1175. }

  1176. /**
  1177. * @brief gizwits report transparent data interface

  1178. * The user can call the interface to complete the reporting of private protocol data

  1179. * @param [in] data :Private protocol data
  1180. * @param [in] len  :Private protocol data length
  1181. * @return 0,success ;other,failure
  1182. */
  1183. int32_t gizwitsPassthroughData(uint8_t * gizdata, uint32_t len)
  1184. {
  1185.         int32_t ret = 0;
  1186.         uint8_t tx_buf[MAX_PACKAGE_LEN];
  1187.         uint8_t *pTxBuf = tx_buf;
  1188.         uint16_t data_len = 6+len;
  1189.     if(NULL == gizdata)
  1190.     {
  1191.         GIZWITS_LOG("[ERR] gizwitsPassthroughData Error \n");
  1192.         return (-1);
  1193.     }

  1194.         *pTxBuf ++= 0xFF;
  1195.         *pTxBuf ++= 0xFF;
  1196.         *pTxBuf ++= (uint8_t)(data_len>>8);//len
  1197.         *pTxBuf ++= (uint8_t)(data_len);
  1198.         *pTxBuf ++= CMD_REPORT_P0;//0x1b cmd
  1199.         *pTxBuf ++= gizwitsProtocol.sn++;//sn
  1200.         *pTxBuf ++= 0x00;//flag
  1201.         *pTxBuf ++= 0x00;//flag
  1202.         *pTxBuf ++= ACTION_D2W_TRANSPARENT_DATA;//P0_Cmd

  1203.     memcpy(&tx_buf[9],gizdata,len);
  1204.     tx_buf[data_len + 4 - 1 ] = gizProtocolSum( tx_buf , (data_len+4));
  1205.    
  1206.         ret = uartWrite(tx_buf, data_len+4);
  1207.     if(ret < 0)
  1208.     {
  1209.         GIZWITS_LOG("ERR: uart write error %d \n", ret);
  1210.     }

  1211.     gizProtocolWaitAck(tx_buf, data_len+4);

  1212.     return 0;
  1213. }


  1214. void gziwits_Task(dataPoint_t * currentDataPoint)
  1215. {
  1216.         static uint32_t Timer=0;
  1217.         if(SoftTimer(Timer,5000))
  1218.         {
  1219.                 gizwitsHandle(currentDataPoint);
  1220.                 Timer=GetSoftTimer();
  1221.         }
  1222. }


  1223. /**@} */

复制代码



修改gizwits_protocol.h


  1. #ifndef _GIZWITS_PROTOCOL_H
  2. #define _GIZWITS_PROTOCOL_H

  3. #ifdef __cplusplus
  4. extern "C" {
  5. #endif

  6. #include <stdint.h>
  7. #include <stdbool.h>
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include <string.h>
  11. #include "common.h"

  12.                                                                                                                   
  13. #define SEND_MAX_TIME       200                     ///< 200ms resend
  14. #define SEND_MAX_NUM        2                       ///< resend times
  15.                                                    
  16. #define protocol_VERSION    "00000004"              ///< protocol version
  17. #define P0_VERSION          "00000002"              ///< P0 protocol version

  18. /**@name Product Key  
  19. * @{
  20. */
  21. #define PRODUCT_KEY "9c8a5a8e38344fb4af14b6db0f5b1df7"
  22. /**@} */
  23. /**@name Product Secret  
  24. * @{
  25. */
  26. #define PRODUCT_SECRET "45c86d8c6a2a4b1dac7d68df54f6e4f0"
  27.                
  28. /**@name Device status data reporting interval
  29. * @{
  30. */
  31. #define REPORT_TIME_MAX 6000 //6S
  32. /**@} */   

  33. #define CELLNUMMAX 7   


  34. /**@name Whether the device is in the control class, 0 means no, 1 means yes
  35. * @{
  36. */
  37. #define DEV_IS_GATEWAY   0                    
  38. /**@} */

  39. /**@name Binding time
  40. * @{
  41. */
  42. #define NINABLETIME  0
  43. /**@} */



  44. #define MAX_PACKAGE_LEN    (sizeof(devStatus_t)+sizeof(attrFlags_t)+20)                 ///< Data buffer maximum length
  45. #define RB_MAX_LEN          (MAX_PACKAGE_LEN*2)     ///< Maximum length of ring buffer

  46. /**@name Data point related definition
  47. * @{
  48. */
  49. #define Relay_1_BYTEOFFSET                    0
  50. #define Relay_1_BITOFFSET                     0
  51. #define Relay_1_LEN                           1

  52. #define Temp_RATIO                         1
  53. #define Temp_ADDITION                      0
  54. #define Temp_MIN                           0
  55. #define Temp_MAX                           100
  56. #define Humi_RATIO                         1
  57. #define Humi_ADDITION                      0
  58. #define Humi_MIN                           0
  59. #define Humi_MAX                           100
  60. #define Light_Intensity_RATIO                         1
  61. #define Light_Intensity_ADDITION                      0
  62. #define Light_Intensity_MIN                           0
  63. #define Light_Intensity_MAX                           100
  64. /**@} */

  65. /** Writable data points Boolean and enumerated variables occupy byte size */
  66. #define COUNT_W_BIT 1







  67. /** Event enumeration */
  68. typedef enum
  69. {
  70.   WIFI_SOFTAP = 0x00,                               ///< WiFi SOFTAP configuration event
  71.   WIFI_AIRLINK,                                     ///< WiFi module AIRLINK configuration event
  72.   WIFI_STATION,                                     ///< WiFi module STATION configuration event
  73.   WIFI_OPEN_BINDING,                                ///< The WiFi module opens the binding event
  74.   WIFI_CLOSE_BINDING,                               ///< The WiFi module closes the binding event
  75.   WIFI_CON_ROUTER,                                  ///< The WiFi module is connected to a routing event
  76.   WIFI_DISCON_ROUTER,                               ///< The WiFi module has been disconnected from the routing event
  77.   WIFI_CON_M2M,                                     ///< The WiFi module has a server M2M event
  78.   WIFI_DISCON_M2M,                                  ///< The WiFi module has been disconnected from the server M2M event
  79.   WIFI_OPEN_TESTMODE,                               ///< The WiFi module turns on the test mode event
  80.   WIFI_CLOSE_TESTMODE,                              ///< The WiFi module turns off the test mode event
  81.   WIFI_CON_APP,                                     ///< The WiFi module connects to the APP event
  82.   WIFI_DISCON_APP,                                  ///< The WiFi module disconnects the APP event
  83.   WIFI_RSSI,                                        ///< WiFi module RSSI event
  84.   WIFI_NTP,                                         ///< Network time event
  85.   MODULE_INFO,                                      ///< Module information event
  86.   TRANSPARENT_DATA,                                 ///< Transparency events
  87.   EVENT_Relay_1,
  88.   EVENT_TYPE_MAX                                    ///< Enumerate the number of members to calculate (user accidentally deleted)
  89. } EVENT_TYPE_T;

  90. /** P0 Command code */
  91. typedef enum
  92. {
  93.     ACTION_CONTROL_DEVICE       = 0x01,             ///< Protocol 4.10 WiFi Module Control Device WiFi Module Send
  94.     ACTION_READ_DEV_STATUS      = 0x02,             ///< Protocol 4.8 WiFi Module Reads the current status of the device WiFi module sent
  95.     ACTION_READ_DEV_STATUS_ACK  = 0x03,             ///< Protocol 4.8 WiFi Module Read Device Current Status Device MCU Reply
  96.     ACTION_REPORT_DEV_STATUS    = 0x04,             ///< Protocol 4.9 device MCU to the WiFi module to actively report the current status of the device to send the MCU
  97.     ACTION_W2D_TRANSPARENT_DATA = 0x05,             ///< WiFi to device MCU transparent
  98.     ACTION_D2W_TRANSPARENT_DATA = 0x06,             ///< Device MCU to WiFi
  99. } actionType_t;   

  100. /** Protocol network time structure */
  101. typedef struct
  102. {
  103.     uint16_t year;
  104.     uint8_t month;
  105.     uint8_t day;
  106.     uint8_t hour;
  107.     uint8_t minute;
  108.     uint8_t second;
  109.     uint32_t ntp;
  110. }protocolTime_t;
  111.            

  112. /** WiFi Module configuration parameters*/
  113. typedef enum
  114. {
  115.   WIFI_RESET_MODE = 0x00,                           ///< WIFI module reset
  116.   WIFI_SOFTAP_MODE,                                 ///< WIFI module softAP modeF
  117.   WIFI_AIRLINK_MODE,                                ///< WIFI module AirLink mode
  118.   WIFI_PRODUCTION_TEST,                             ///< MCU request WiFi module into production test mode
  119.   WIFI_NINABLE_MODE,                                ///< MCU request module to enter binding mode
  120.   WIFI_REBOOT_MODE,                                 ///< MCU request module reboot  
  121. }WIFI_MODE_TYPE_T;                                

  122. /** The protocol event type*/
  123. typedef enum
  124. {
  125.   STATELESS_TYPE = 0x00,                            ///< Stateless type
  126.   ACTION_CONTROL_TYPE,                              ///< Protocol 4.10 :WiFi module control device event
  127.   WIFI_STATUS_TYPE,                                 ///< Protocol 4.5 :WiFi module inform the device MCU of the change event of the WiFi module status
  128.   ACTION_W2D_TRANSPARENT_TYPE,                      ///< Protocol WiFi to device MCU transparent event
  129.   GET_NTP_TYPE,                                     ///< Protocol 4.13 :The MCU requests access to the network time event
  130.   GET_MODULEINFO_TYPE,                              ///< Protocol 4.9 :The MCU get module information event
  131.   PROTOCOL_EVENT_TYPE_MAX                           ///< Count enumerated member (User donot delete)
  132. } PROTOCOL_EVENT_TYPE_T;
  133.      
  134. /** Protocol command code */                                   
  135. typedef enum                              
  136. {                                                   
  137.     CMD_GET_DEVICE_INTO             = 0x01,         ///< Protocol:3.1
  138.     ACK_GET_DEVICE_INFO             = 0x02,         ///< Protocol:3.1
  139.             
  140.     CMD_ISSUED_P0                   = 0x03,         ///< Protocol:3.2 3.3
  141.     ACK_ISSUED_P0                   = 0x04,         ///< Protocol:3.2 3.3
  142.             
  143.     CMD_REPORT_P0                   = 0x05,         ///< Protocol:3.4
  144.     ACK_REPORT_P0                   = 0x06,         ///< Protocol:3.4
  145.             
  146.     CMD_HEARTBEAT                   = 0x07,         ///< Protocol:3.5
  147.     ACK_HEARTBEAT                   = 0x08,         ///< Protocol:3.5
  148.             
  149.     CMD_WIFI_CONFIG                 = 0x09,         ///< Protocol:3.6
  150.     ACK_WIFI_CONFIG                 = 0x0A,         ///< Protocol:3.6
  151.             
  152.     CMD_SET_DEFAULT                 = 0x0B,         ///< Protocol:3.7
  153.     ACK_SET_DEFAULT                 = 0x0C,         ///< Protocol:3.7
  154.             
  155.     CMD_WIFISTATUS                  = 0x0D,         ///< Protocol:3.8
  156.     ACK_WIFISTATUS                  = 0x0E,         ///< Protocol:3.8
  157.         
  158.     CMD_MCU_REBOOT                  = 0x0F,         ///< Protocol:4.1
  159.     ACK_MCU_REBOOT                  = 0x10,         ///< Protocol:4.1
  160.             
  161.     CMD_ERROR_PACKAGE               = 0x11,         ///< Protocol:3.9
  162.     ACK_ERROR_PACKAGE               = 0x12,         ///< Protocol:3.9

  163.     CMD_PRODUCTION_TEST             = 0x13,         ///< Protocol:
  164.     ACK_PRODUCTION_TEST             = 0x14,         ///< Protocol:

  165.     CMD_NINABLE_MODE                = 0x15,         ///< Protocol:3.10
  166.     ACK_NINABLE_MODE                = 0x16,         ///< Protocol:3.10

  167.     CMD_GET_NTP                     = 0x17,         ///< Protocol:4.3
  168.     ACK_GET_NTP                     = 0x18,         ///< Protocol:4.3


  169.     CMD_ASK_BIGDATA                 = 0x19,         ///< Protocol:4.4
  170.     ACK_ASK_BIGDATA                 = 0x1A,         ///< Protocol:4.4

  171.     CMD_BIGDATA_READY               = 0x1B,         ///< Protocol:4.5
  172.     ACK_BIGDATA_READY               = 0x1C,         ///< Protocol:4.5

  173.     CMD_BIGDATA_SEND                = 0x1D,         ///< Protocol:4.6
  174.     ACK_BIGDATA_SEND                = 0x1E,         ///< Protocol:4.6

  175.     CMD_S_STOP_BIGDATA_SEND         = 0x1F,         ///< Protocol:4.7
  176.     ACK_S_STOP_BIGDATA_SEND         = 0x20,         ///< Protocol:4.7

  177.     CMD_D_STOP_BIGDATA_SEND         = 0x27,         ///< Protocol:4.8
  178.     ACK_D_STOP_BIGDATA_SEND         = 0x28,         ///< Protocol:4.8

  179.     CMD_ASK_MODULE_INFO             = 0x21,         ///< Protocol:4.9
  180.     ACK_ASK_MODULE_INFO             = 0x22,         ///< Protocol:4.9

  181.     CMD_ASK_AFFAIR_HANDLE           = 0x23,         ///< Protocol:4.10
  182.     ACK_ASK_AFFAIR_HANDLE           = 0x24,         ///< Protocol:4.10

  183.     CMD_AFFAIR_RESULT               = 0x25,         ///< Protocol:4.10
  184.     ACK_AFFAIR_RESULT               = 0x26,         ///< Protocol:4.10

  185.     CMD_REBOOT_MODULE               = 0x29,         ///< Protocol:3.11
  186.     ACK_REBOOT_MODULE               = 0x2A,         ///< Protocol:3.11

  187.     CMD_CONNECT_M2M                 = 0x2D,         ///< Protocol:for Virtualization
  188.     ACK_CONNECT_M2M                 = 0x2E,         ///< Protocol:for Virtualization

  189.     CMD_CONNECT_M2M_BACK            = 0x2F,         ///< Protocol:for Virtualization
  190.     ACK_CONNECT_M2M_BACK            = 0x30,         ///< Protocol:for Virtualization

  191.     CMD_UPLOAD_DATA                 = 0x31,         ///< Protocol:for Virtualization
  192.     ACK_UPLOAD_DATA                 = 0x32,         ///< Protocol:for Virtualization

  193.     CMD_UPLOAD_DATA_BACK            = 0x33,         ///< Protocol:for Virtualization
  194.     ACK_UPLOAD_DATA_BACK            = 0x34,         ///< Protocol:for Virtualization

  195.     CMD_DISCONNECT_M2M              = 0x35,         ///< Protocol:for Virtualization
  196.     ACK_DISCONNECT_M2M              = 0x36,         ///< Protocol:for Virtualization

  197.     CMD_DISCONNECT_M2M_BACK         = 0x37,         ///< Protocol:for Virtualization
  198.     ACK_DISCONNECT_M2M_BACK         = 0x38,         ///< Protocol:for Virtualization

  199.     CMD_RESET_SIMULATOR             = 0x39,         ///< Protocol:for Virtualization
  200.     ACK_RESET_SIMULATOR             = 0x3A,         ///< Protocol:for Virtualization

  201.     CMD_RESET_SIMULATOR_BACK        = 0x3B,         ///< Protocol:for Virtualization
  202.     ACK_RESET_SIMULATOR_BACK        = 0x3C,         ///< Protocol:for Virtualization
  203. } PROTOCOL_CMDTYPE;                                                                                 
  204.                         
  205. /** Illegal message type*/  
  206. typedef enum
  207. {
  208.     ERROR_ACK_SUM = 0x01,                           ///< check error
  209.     ERROR_CMD     = 0x02,                           ///< Command code error
  210.     ERROR_OTHER   = 0x03,                           ///< other
  211. } errorPacketsType_t;

  212. typedef enum
  213. {
  214.     EXE_SUCESS                      = 0x00,
  215.     EXE_FAILE                       = 0x01,
  216. } execute_result;  

  217. #pragma pack(1)

  218. /** User Area Device State Structure */
  219. typedef struct {
  220.   bool valueRelay_1;
  221.   uint32_t valueTemp;
  222.   uint32_t valueHumi;
  223.   uint32_t valueLight_Intensity;
  224. } dataPoint_t;


  225. /** Corresponding to the protocol "4.10 WiFi module control device" in the flag " attr_flags" */
  226. typedef struct {
  227.   uint8_t flagRelay_1:1;
  228. } attrFlags_t;


  229. /** Corresponding protocol "4.10 WiFi module control device" in the data value "attr_vals" */

  230. typedef struct {
  231.   uint8_t wBitBuf[COUNT_W_BIT];
  232. } attrVals_t;

  233. /** The flag "attr_flags (1B)" + data value "P0 protocol area" in the corresponding protocol "4.10 WiFi module control device"attr_vals(6B)" */
  234. typedef struct {
  235.     attrFlags_t attrFlags;
  236.     attrVals_t  attrVals;
  237. }gizwitsIssued_t;

  238. /** Corresponding protocol "4.9 Device MCU to the WiFi module to actively report the current state" in the device status "dev_status(11B)" */

  239. typedef struct {
  240.   uint8_t wBitBuf[COUNT_W_BIT];
  241.   uint8_t valueTemp;
  242.   uint8_t valueHumi;
  243.   uint8_t valueLight_Intensity;
  244. } devStatus_t;


  245.                
  246. /** Event queue structure */                              
  247. typedef struct {                           
  248.     uint8_t num;                                    ///< Number of queue member
  249.     uint8_t event[EVENT_TYPE_MAX];                  ///< Queue member event content
  250. }eventInfo_t;


  251.                            
  252. /** wifiSignal strength structure */                       
  253. typedef struct {                           
  254.     uint8_t rssi;                                   ///< WIFI signal strength
  255. }moduleStatusInfo_t;                                

  256. /** Protocol standard header structure */
  257. typedef struct
  258. {
  259.     uint8_t                 head[2];                ///< The head is 0xFFFF
  260.     uint16_t                len;                    ///< From cmd to the end of the entire packet occupied by the number of bytes
  261.     uint8_t                 cmd;                    ///< command
  262.     uint8_t                 sn;                     ///<
  263.     uint8_t                 flags[2];               ///< flag,default is 0
  264. } protocolHead_t;

  265. /** 4.1 WiFi module requests the device information protocol structure */
  266. typedef struct
  267. {
  268.     protocolHead_t          head;                   ///< Protocol standard header structure
  269.     uint8_t                 protocolVer[8];         ///< Protocol version
  270.     uint8_t                 p0Ver[8];               ///< p0 Protocol version
  271.     uint8_t                 hardVer[8];             ///< Hardware version
  272.     uint8_t                 softVer[8];             ///< Software version
  273.     uint8_t                 productKey[32];         ///< Product key
  274.     uint16_t                ninableTime;            ///< Binding time(second)
  275.     uint8_t                 devAttr[8];             ///< Device attribute
  276.     uint8_t                 productSecret[32];      ///< Product secret
  277.     uint8_t                 sum;                    ///< checksum
  278. } protocolDeviceInfo_t;

  279. /** Protocol common data frame(4.2、4.4、4.6、4.9、4.10) protocol structure */
  280. typedef struct
  281. {
  282.     protocolHead_t          head;                   ///< Protocol standard header structure
  283.     uint8_t                 sum;                    ///< checksum
  284. } protocolCommon_t;

  285. /** 4.3 The device MCU informs the WiFi module of the configuration mode  protocol structure */
  286. typedef struct
  287. {
  288.     protocolHead_t          head;                   ///< Protocol standard header structure
  289.     uint8_t                 cfgMode;                ///< Configuration parameters
  290.     uint8_t                 sum;                    ///< checksum
  291. } protocolCfgMode_t;

  292. /** 4.13 The MCU requests the network time  protocol structure */
  293. typedef struct
  294. {
  295.     protocolHead_t          head;                   ///< Protocol standard header structure
  296.     uint8_t                 time[7];                ///< Hardware version
  297.     uint8_t                 ntp_time[4];            ///< Software version
  298.     uint8_t                 sum;                    ///< checksum
  299. } protocolUTT_t;

  300. /** WiFi module working status*/
  301. typedef union
  302. {
  303.     uint16_t                value;
  304.     struct
  305.     {
  306.         uint16_t            softap:1;     
  307.         uint16_t            station:1;   
  308.         uint16_t            onboarding:1;
  309.         uint16_t            binding:1;   
  310.         uint16_t            con_route:1;  
  311.         uint16_t            con_m2m:1;   
  312.         uint16_t            reserve1:2;   
  313.         uint16_t            rssi:3;      
  314.         uint16_t            app:1;        
  315.         uint16_t            test:1;      
  316.         uint16_t            reserve2:3;   
  317.     }types;
  318.    
  319. } wifiStatus_t;

  320. /** WiFi status type :protocol structure */
  321. typedef struct
  322. {
  323.     protocolHead_t          head;                   ///< Protocol standard header structure
  324.     wifiStatus_t            ststus;                 ///< WIFI status
  325.     uint8_t                 sum;                    ///< checksum
  326. } protocolWifiStatus_t;

  327. /** Protocol common data frame(4.9) :protocol structure */
  328. typedef struct
  329. {
  330.     protocolHead_t          head;                   ///< Protocol standard header structure
  331.     uint8_t                 type;                   ///< Information Type
  332.     uint8_t                 sum;                    ///< checksum
  333. } protocolGetModuleInfo_t;

  334. typedef struct
  335. {
  336.     uint8_t                 moduleType;             ///< Information Type
  337.     uint8_t                 serialVer[8];           ///< Serial port protocol version
  338.     uint8_t                 hardVer[8];             ///< Hardware version
  339.     uint8_t                 softVer[8];             ///< Software version
  340.     uint8_t                 mac[16];                ///< mac
  341.     uint8_t                 ip[16];                 ///< ip
  342.     uint8_t                 devAttr[8];             ///< Device attribute
  343. } moduleInfo_t;

  344. /** Protocol common data frame(4.9) :protocol structure */
  345. typedef struct
  346. {
  347.     protocolHead_t          head;                   ///< Protocol standard header structure
  348.     moduleInfo_t            wifiModuleInfo;         ///< WIFI module information
  349.     uint8_t                 sum;                    ///< checksum
  350. } protocolModuleInfo_t;


  351. /** GPRS information of base station */
  352. typedef struct
  353. {
  354.     uint16_t                    LAC_ID;             ///<LAC area ID
  355.     uint16_t                    CellID;             ///<Base station ID
  356.     uint8_t                     RSSI;               ///<Signal strength of base station
  357. } gprsCellInfo_t;


  358. /** 3.19 The basic information of the GPRS communication module  */
  359. typedef struct
  360. {
  361.     uint8_t                 Type;//2G/3g/4g
  362.     uint8_t                 Pro_ver[8];//Universal serial port protocol version
  363.     uint8_t                 Hard_ver[8];//Hardware version
  364.     uint8_t                 Soft_ver[8];//Software version
  365.     uint8_t                 Device_attribute[8];//Device attribute
  366.     uint8_t                 IMEI[16];//string
  367.     uint8_t                 IMSI[16];//string
  368.     uint8_t                 MCC[8];//Mobile country code
  369.     uint8_t                 MNC[8];//Mobile network code
  370.     uint8_t                 CellNum;//Number of base station
  371.     uint8_t                 CellInfoLen;//Information length of base station
  372.     gprsCellInfo_t          GPRS_CellINFO[CELLNUMMAX];
  373. }gprsInfo_t;

  374. /** 4.7 Illegal message notification :protocol structure*/
  375. typedef struct
  376. {
  377.     protocolHead_t          head;                   ///< Protocol standard header structure
  378.     uint8_t                 error;                  ///< error value
  379.     uint8_t                 sum;                    ///< checksum
  380. } protocolErrorType_t;


  381. /** P0 message header */
  382. typedef struct
  383. {
  384.     protocolHead_t          head;                   ///< Protocol standard header structure
  385.     uint8_t                 action;                 ///< p0 command
  386. } protocolP0Head_t;


  387. /** protocol “4.9 The device MCU reports the current status to the WiFi module” device status "dev_status(11B)"  */
  388. typedef struct {
  389.                      
  390.     devStatus_t devStatus;                          ///< Stores the device status data
  391. }gizwitsReport_t;

  392. /** resend strategy structure */
  393. typedef struct {
  394.     uint8_t                 num;                    ///< resend times
  395.     uint8_t                 flag;                   ///< 1,Indicates that there is a need to wait for the ACK;0,Indicates that there is no need to wait for the ACK
  396.     uint8_t                 buf[MAX_PACKAGE_LEN];   ///< resend data buffer
  397.     uint16_t                dataLen;                ///< resend data length
  398.     uint32_t                sendTime;               ///< resend time
  399. } protocolWaitAck_t;
  400.                                                                                 
  401. /** 4.8 WiFi read device datapoint value , device ack use this struct */
  402. typedef struct
  403. {
  404.     protocolHead_t          head;                   ///< Protocol head
  405.     uint8_t                 action;                 ///< p0 action
  406.     gizwitsReport_t         reportData;             ///< p0 data
  407.     uint8_t                 sum;                    ///< Checksum
  408. } protocolReport_t;


  409. /** Protocol main and very important struct */
  410. typedef struct
  411. {
  412.     uint8_t issuedFlag;                             ///< P0 action type
  413.     uint8_t protocolBuf[MAX_PACKAGE_LEN];           ///< Protocol data handle buffer
  414.     uint8_t transparentBuff[MAX_PACKAGE_LEN];       ///< Transparent data storage area
  415.     uint32_t transparentLen;                        ///< Transmission data length
  416.    
  417.     uint32_t sn;                                    ///< Message SN
  418.     uint32_t timerMsCount;                          ///< Timer Count
  419.     protocolWaitAck_t waitAck;                      ///< Protocol wait ACK data structure
  420.    
  421.     eventInfo_t issuedProcessEvent;                 ///< Control events
  422.     eventInfo_t wifiStatusEvent;                    ///< WIFI Status events
  423.     eventInfo_t NTPEvent;                           ///< NTP events
  424.     eventInfo_t moduleInfoEvent;                    ///< Module Info events

  425.         gizwitsReport_t reportData;                     ///< The protocol reports data for standard product
  426.     dataPoint_t gizCurrentDataPoint;                ///< Current device datapoints status
  427.     dataPoint_t gizLastDataPoint;                   ///< Last device datapoints status
  428.     moduleStatusInfo_t wifiStatusData;              ///< WIFI signal intensity
  429.     protocolTime_t TimeNTP;                         ///< Network time information
  430. #if MODULE_TYPE
  431.     gprsInfo_t   gprsInfoNews;
  432. #else  
  433.     moduleInfo_t  wifiModuleNews;                   ///< WIFI module Info
  434. #endif
  435.         
  436.         
  437. }gizwitsProtocol_t;

  438. #pragma pack()

  439. /**@name Gizwits user API interface
  440. * @{
  441. */

  442. extern uint32_t gizGetTimerCount(void);

  443. void gizwitsInit(void);
  444. int32_t gizwitsSetMode(uint8_t mode);
  445. void gizwitsGetNTP(void);
  446. int32_t gizwitsHandle(dataPoint_t *currentData);
  447. int32_t gizwitsPassthroughData(uint8_t * gizdata, uint32_t len);
  448. void gizwitsGetModuleInfo(void);
  449. int32_t gizPutData(uint8_t *buf, uint32_t len);


  450. /*添加用户自定义的函数**/
  451. void gziwits_Task(dataPoint_t * currentDataPoint);

  452. /**@} */
  453. #ifdef __cplusplus
  454. }
  455. #endif

  456. #endif

复制代码



6,Utils直接移植无需修改


7,添加TIM3定时器代码驱动
  1. #include "tim3.h"
  2. #include "gizwits_product.h"

  3. void TIM3_Config(uint16_t psc,uint16_t arr)
  4. {
  5.         RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
  6.         
  7.         TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
  8.         TIM_TimeBaseStructure.TIM_Period                     = arr;
  9.         TIM_TimeBaseStructure.TIM_Prescaler                  = psc;
  10.         TIM_TimeBaseStructure.TIM_ClockDivision              = TIM_CKD_DIV1;
  11.         TIM_TimeBaseStructure.TIM_CounterMode                = TIM_CounterMode_Up;
  12.         TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);
  13.         
  14.         TIM_ITConfig(TIM3,TIM_IT_Update,ENABLE );
  15.         
  16.   NVIC_InitTypeDef NVIC_InitStructure;
  17.         NVIC_InitStructure.NVIC_IRQChannel                   = TIM3_IRQn;
  18.         NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;  
  19.         NVIC_InitStructure.NVIC_IRQChannelSubPriority        = 3;  
  20.         NVIC_InitStructure.NVIC_IRQChannelCmd                = ENABLE;
  21.         NVIC_Init(&NVIC_InitStructure);                             
  22.         TIM_Cmd(TIM3, ENABLE);                  
  23. }
  24. /*用户实现的定时器接口*/
  25. void TIM3_IRQHandler(void)  
  26. {
  27.         if(TIM_GetITStatus(TIM3, TIM_IT_Update) != RESET)  
  28.         {
  29.                 TIM_ClearITPendingBit(TIM3, TIM_IT_Update  );  
  30.                 gizTimerMs();
  31.         }
  32. }
  33. /***/
  34. //void TIMER_IRQ_FUN(void)
  35. //{
  36. //  gizTimerMs();
  37. //}
  38. /***/


  39. ## 添加UART3串口通信代码驱动

  40. ```c
  41. #include "usart3.h"
  42. #include "gizwits_product.h"

  43. void USART3_Init(uint32_t BaudRate)
  44. {  
  45.         RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);                               //GPIOB时钟
  46.         RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART3,ENABLE);                          //串口3时钟使能

  47.          USART_DeInit(USART3);  //复位串口3
  48.         GPIO_InitTypeDef GPIO_InitStructure;
  49.         
  50.         
  51.   GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;                                     //PB10
  52.         GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;                              //USART3_TX   PB10
  53.         GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;                                       //复用推挽输出
  54.         GPIO_Init(GPIOB, &GPIO_InitStructure);                                         //初始化PB10


  55.         GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11;                                              //USART3_RX          PB11
  56.         GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;                          //浮空输入
  57.         GPIO_Init(GPIOB, &GPIO_InitStructure);  

  58.         USART_InitTypeDef                  USART_InitStructure;
  59.         USART_InitStructure.USART_BaudRate            = BaudRate;                                    //波特率一般设置为9600;
  60.         USART_InitStructure.USART_WordLength          = USART_WordLength_8b;                    //字长为8位数据格式
  61.         USART_InitStructure.USART_StopBits            = USART_StopBits_1;                         //一个停止位
  62.         USART_InitStructure.USART_Parity              = USART_Parity_No;                            //无奇偶校验位
  63.         USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;//无硬件数据流控制
  64.         USART_InitStructure.USART_Mode                = USART_Mode_Rx | USART_Mode_Tx;                       //收发模式
  65.   
  66.         USART_Init(USART3, &USART_InitStructure);       //初始化串口3
  67.   

  68.         USART_Cmd(USART3, ENABLE);                      //使能串口
  69.         
  70.   
  71.   USART_ITConfig(USART3, USART_IT_RXNE, ENABLE);       //开启中断

  72.   NVIC_InitTypeDef NVIC_InitStructure;
  73.         NVIC_InitStructure.NVIC_IRQChannel                   = USART3_IRQn;
  74.         NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2;
  75.         NVIC_InitStructure.NVIC_IRQChannelSubPriority        = 3;
  76.         NVIC_InitStructure.NVIC_IRQChannelCmd                = ENABLE;                        
  77.         NVIC_Init(&NVIC_InitStructure);        
  78.         
  79. }
  80. /*用户实现的中断服务函数接口*/
  81. void USART3_IRQHandler(void)
  82. {
  83.         uint8_t Recv_Data;              
  84.         if(USART_GetITStatus(USART3, USART_IT_RXNE) != RESET)//接收到数据
  85.         {         
  86.                   Recv_Data = USART_ReceiveData(USART3);                 
  87.                   gizPutData(&Recv_Data, 1);
  88.         }                                                                                                                           
  89. }   
  90. /****/
  91. //void UART_IRQ_FUN(void)
  92. //{
  93. //  uint8_t value = 0;
  94. //  gizPutData(&value, 1);
  95. //}
  96. /****/
复制代码


8,修改关键函数的函数体,封装各模块的初始化


五,机智云初始化函数封装
成功联网


设备上线显示


效果展示



☟▼▼开源代码/原理图/笔记下载:

链接:https://pan.baidu.com/s/1Mm4dl6x48awWffYE1zrsvw?pwd=d4my
提取码:d4my

点击观看视频上集https://www.bilibili.com/video/BV1rr4y1L7Xx?spm_id_from=333.337.search-card.all.click&vd_source=fa2f39377822bdaec0cecc96fd2a3a72

点击观看视频下集:

https://www.bilibili.com/video/BV1Ar4y1j7CP?spm_id_from=333.337.search-card.all.click&vd_source=fa2f39377822bdaec0cecc96fd2a3a72




本帖被以下淘专辑推荐:

  • · .i|主题: 2, 订阅: 0
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

加入Q群 返回顶部

版权与免责声明 © 2006-2024 Gizwits IoT Technology Co., Ltd. ( 粤ICP备11090211号 )

快速回复 返回顶部 返回列表