机智云智能浇花器实战(3)-基础Demo实现

链接:机智云智能浇花器实战(2)-基础Demo实现

BH1750光照传感器原理图

BH1750传感器代码

#include "bh1750.h"
#include "delay.h"uint8_t    BUF[8];               //接收数据缓存区
int         mcy;     //进位标志/***开始信号***/
void BH1750_Start()
{BH1750_SDA_H;                                               //拉高数据线BH1750_SCL_H;                                               //拉高时钟线Delay_nus(5);                                         //延时GPIO_ResetBits(BH1750_PORT, BH1750_SDA_PIN);                    //产生下降沿Delay_nus(5);                                         //延时GPIO_ResetBits(BH1750_PORT, BH1750_SCL_PIN);                    //拉低时钟线
}/*****停止信号******/
void BH1750_Stop()
{BH1750_SDA_L;                                             //拉低数据线BH1750_SCL_H;                                             //拉高时钟线Delay_nus(5);                                       //延时GPIO_SetBits(BH1750_PORT, BH1750_SDA_PIN);                    //产生上升沿Delay_nus(5);                 //延时
}/**************************************
发送应答信号
入口参数:ack (0:ACK 1:NAK)
**************************************/
void BH1750_SendACK(int ack)
{GPIO_InitTypeDef GPIO_InitStruct;GPIO_InitStruct.GPIO_Mode = GPIO_Mode_Out_PP;  GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;GPIO_InitStruct.GPIO_Pin = BH1750_SDA_PIN;GPIO_Init(BH1750_PORT, &GPIO_InitStruct);  if(ack == 1)   //写应答信号BH1750_SDA_H; else if(ack == 0)BH1750_SDA_L; elsereturn;           BH1750_SCL_H;     //拉高时钟线Delay_nus(5);                 //延时BH1750_SCL_L;      //拉低时钟线Delay_nus(5);                //延时
}/**************************************
接收应答信号
**************************************/
int BH1750_RecvACK()
{GPIO_InitTypeDef GPIO_InitStruct;GPIO_InitStruct.GPIO_Mode=GPIO_Mode_IPU;  /*这里一定要设成输入上拉,否则不能读出数据*/GPIO_InitStruct.GPIO_Speed=GPIO_Speed_50MHz;GPIO_InitStruct.GPIO_Pin=BH1750_SDA_PIN;GPIO_Init(BH1750_PORT,&GPIO_InitStruct);BH1750_SCL_H;            //拉高时钟线Delay_nus(5);                 //延时    if(GPIO_ReadInputDataBit(BH1750_PORT,BH1750_SDA_PIN)==1)//读应答信号mcy = 1 ;  elsemcy = 0 ;             BH1750_SCL_L;                    //拉低时钟线Delay_nus(5);                 //延时GPIO_InitStruct.GPIO_Mode=GPIO_Mode_Out_PP;GPIO_Init(BH1750_PORT,&GPIO_InitStruct);return mcy;
}/**************************************
向IIC总线发送一个字节数据
**************************************/
void BH1750_SendByte(uint8_t dat)
{uint8_t i;for (i=0; i<8; i++)         //8位计数器{if( 0X80 & dat )GPIO_SetBits(BH1750_PORT,BH1750_SDA_PIN);elseGPIO_ResetBits(BH1750_PORT,BH1750_SDA_PIN);dat <<= 1;BH1750_SCL_H;               //拉高时钟线Delay_nus(5);             //延时BH1750_SCL_L;                //拉低时钟线Delay_nus(5);            //延时}BH1750_RecvACK();
}uint8_t BH1750_RecvByte()
{uint8_t i;uint8_t dat = 0;uint8_t bit;GPIO_InitTypeDef GPIO_InitStruct;GPIO_InitStruct.GPIO_Mode  = GPIO_Mode_IPU;   /*这里一定要设成输入上拉,否则不能读出数据*/GPIO_InitStruct.GPIO_Pin   = BH1750_SDA_PIN;GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;GPIO_Init(BH1750_PORT,&GPIO_InitStruct );GPIO_SetBits(BH1750_PORT,BH1750_SDA_PIN);          //使能内部上拉,准备读取数据,for (i=0; i<8; i++)         //8位计数器{dat <<= 1;BH1750_SCL_H;               //拉高时钟线Delay_nus(5);             //延时if( SET == GPIO_ReadInputDataBit(BH1750_PORT,BH1750_SDA_PIN))bit = 0X01;elsebit = 0x00;  dat |= bit;             //读数据    BH1750_SCL_L;                //拉低时钟线Delay_nus(5);            //延时}        GPIO_InitStruct.GPIO_Mode = GPIO_Mode_Out_PP;GPIO_Init(BH1750_PORT, &GPIO_InitStruct );return dat;
}void Single_Write_BH1750(uint8_t REG_Address)
{BH1750_Start();                  //起始信号BH1750_SendByte(SlaveAddress);   //发送设备地址+写信号BH1750_SendByte(REG_Address);    //内部寄存器地址,请参考中文pdf22页
//  BH1750_SendByte(REG_data);       //内部寄存器数据,请参考中文pdf22页 BH1750_Stop();                   //发送停止信号
}//初始化BH1750,根据需要请参考pdf进行修改****
void BH1750_Init()
{GPIO_InitTypeDef GPIO_InitStruct;/*开启GPIOB的外设时钟*/ RCC_APB2PeriphClockCmd( RCC_APB2Periph_GPIOB, ENABLE); GPIO_InitStruct.GPIO_Mode = GPIO_Mode_Out_PP;  GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;GPIO_InitStruct.GPIO_Pin = BH1750_SDA_PIN | BH1750_SCL_PIN ;GPIO_Init(BH1750_PORT,&GPIO_InitStruct); Single_Write_BH1750(0x01);  Delay_nms(180);            //延时180ms
}//连续读出BH1750内部数据
void mread(void)
{   uint8_t i;  BH1750_Start();                          //起始信号BH1750_SendByte(SlaveAddress+1);         //发送设备地址+读信号for (i=0; i<3; i++)                      //连续读取6个地址数据,存储中BUF{BUF[i] = BH1750_RecvByte();          //BUF[0]存储0x32地址中的数据if (i == 3){BH1750_SendACK(1);                //最后一个数据需要回NOACK}else{        BH1750_SendACK(0);                //回应ACK}}BH1750_Stop();                          //停止信号Delay_nms(5);
}float Read_BH1750(void)
{int dis_data;                       //变量   float temp1;float temp2;Single_Write_BH1750(0x01);   // power onSingle_Write_BH1750(0x10);   // H- resolution modeDelay_nms(180);              //延时180msmread();                     //连续读出数据,存储在BUF中dis_data=BUF[0];dis_data=(dis_data<<8)+BUF[1]; //合成数据 temp1=dis_data/1.2;temp2=10*dis_data/1.2;  temp2=(int)temp2%10;return temp1;
}
#ifndef __BH1750_H__
#define __BH1750_H__#include "stm32f10x.h"/*定义器件在IIC总线中的从地址,根据ALT  ADDRESS地址引脚不同修改 ALT  ADDRESS引脚接地时地址为0x46,   接电源时地址为0xB8
*/
#define SlaveAddress     0x46
#define BH1750_PORT      GPIOB
#define BH1750_SCL_PIN   GPIO_Pin_1
#define BH1750_SDA_PIN   GPIO_Pin_0#define BH1750_SCL_H     GPIO_SetBits(BH1750_PORT,BH1750_SCL_PIN)
#define BH1750_SCL_L     GPIO_ResetBits(BH1750_PORT,BH1750_SCL_PIN) #define BH1750_SDA_H     GPIO_SetBits(BH1750_PORT,BH1750_SDA_PIN)
#define BH1750_SDA_L     GPIO_ResetBits(BH1750_PORT,BH1750_SDA_PIN)  extern uint8_t    BUF[8];                         //接收数据缓存区
extern int        dis_data;                       //变量
extern int        mcy;                            //表示进位标志位void BH1750_Init(void);
void conversion(uint32_t temp_data);
void  Single_Write_BH1750(uint8_t REG_Address);    //单个写入数据
uint8_t Single_Read_BH1750(uint8_t REG_Address);   //单个读取内部寄存器数据
void  mread(void);                                 //连续的读取内部寄存器数据
float Read_BH1750(void);#endif

BH1750传感器代码说明

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

理论上SCL SDA这两个GPIO管脚是任意的就可以实现这是第二个bug了,手动捂脸

显示数据不准,原因:硬件数据线接口是PB2,代码是PB0(下次修改)

机智云数据点创建

机智云官方网站

https://www.gizwits.com/
创建自己的产品

创建好后就会有基本信息

Product Key

Product Secret


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


Product Key :9c8a5a8e38344fb4af14b6db0f5b1df7Product Secret :45c86d8c6a2a4b1dac7d68df54f6e4f0

定义自己的数据点


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

MCU开发

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

生成代码包

下载自动生成的代码包

机智云 Gizwits协议移植



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

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

修改gizwits_product.c

#include <stdio.h>
#include <string.h>
#include "gizwits_product.h"
#include "usart3.h"static uint32_t timerMsCount;
uint8_t aRxBuffer;
dataPoint_t currentDataPoint;
uint8_t wifi_flag;//存放事件处理API接口函数
int8_t gizwitsEventProcess(eventInfo_t *info, uint8_t *gizdata, uint32_t len)
{uint8_t i = 0;dataPoint_t *dataPointPtr = (dataPoint_t *)gizdata;moduleStatusInfo_t *wifiData = (moduleStatusInfo_t *)gizdata;protocolTime_t *ptime = (protocolTime_t *)gizdata;#if MODULE_TYPEgprsInfo_t *gprsInfoData = (gprsInfo_t *)gizdata;
#elsemoduleInfo_t *ptModuleInfo = (moduleInfo_t *)gizdata;
#endifif((NULL == info) || (NULL == gizdata)){return -1;}for(i=0; i<info->num; i++){switch(info->event[i]){case EVENT_Relay_1:currentDataPoint.valueRelay_1 = dataPointPtr->valueRelay_1;GIZWITS_LOG("Evt: EVENT_Relay_1 %d \n", currentDataPoint.valueRelay_1);if(0x01 == currentDataPoint.valueRelay_1){currentDataPoint.valueRelay_1 = 1;}else{currentDataPoint.valueRelay_1 = 0;}break;case WIFI_SOFTAP:break;case WIFI_AIRLINK:break;case WIFI_STATION:break;case WIFI_CON_ROUTER:break;case WIFI_DISCON_ROUTER:break;case WIFI_CON_M2M:wifi_flag = 1; //WiFi连接标志break;case WIFI_DISCON_M2M:wifi_flag = 0; //WiFi断开标志break;case WIFI_RSSI:GIZWITS_LOG("RSSI %d\n", wifiData->rssi);break;case TRANSPARENT_DATA:GIZWITS_LOG("TRANSPARENT_DATA \n");//user handle , Fetch data from [data] , size is [len]break;case WIFI_NTP: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);break;case MODULE_INFO:GIZWITS_LOG("MODULE INFO ...\n");#if MODULE_TYPEGIZWITS_LOG("GPRS MODULE ...\n");//Format By gprsInfo_t#elseGIZWITS_LOG("WIF MODULE ...\n");//Format By moduleInfo_tGIZWITS_LOG("moduleType : [%d] \n",ptModuleInfo->moduleType);#endifbreak;default:break;}}return 0;
}void userHandle(void)
{/*currentDataPoint.valueTemp = ;//Add Sensor Data CollectioncurrentDataPoint.valueHumi = ;//Add Sensor Data CollectioncurrentDataPoint.valueLight_Intensity = ;//Add Sensor Data Collection*/
}
void userInit(void)
{memset((uint8_t*)&currentDataPoint, 0, sizeof(dataPoint_t));currentDataPoint.valueRelay_1         = 0;currentDataPoint.valueTemp            = 0;currentDataPoint.valueHumi            = 0;currentDataPoint.valueLight_Intensity = 0;
}void gizTimerMs(void)
{timerMsCount++;
}uint32_t gizGetTimerCount(void)
{return timerMsCount;
}void mcuRestart(void)
{__set_FAULTMASK(1);NVIC_SystemReset();
}void TIMER_IRQ_FUN(void)
{gizTimerMs();
}void UART_IRQ_FUN(void)
{uint8_t value = 0;gizPutData(&value, 1);
}int32_t uartWrite(uint8_t *buf, uint32_t len)
{uint32_t i = 0;if(NULL == buf){return -1;}for(i=0; i<len; i++){USART_SendData(USART3,buf[i]);while(USART_GetFlagStatus(USART3, USART_FLAG_TC) == RESET); //循环发送,直到发送完毕if(i >=2 && buf[i] == 0xFF){USART_SendData(USART3, 0x55);while (USART_GetFlagStatus(USART3, USART_FLAG_TC) == RESET); //循环发送,直到发送完毕 }}return len;
}

修改

#ifndef _GIZWITS_PRODUCT_H
#define _GIZWITS_PRODUCT_H#ifdef __cplusplus
extern "C" {#endif#include <stdint.h>
//#include "stm32f1xx.h"
#include "gizwits_protocol.h"/**
* MCU software version
*/
#define SOFTWARE_VERSION "03030000"
/**
* MCU hardware version
*/
#define HARDWARE_VERSION "03010100"/**
* Communication module model
*/
#define MODULE_TYPE 0 //0,WIFI ;1,GPRS/**@name TIM3 related macro definition
* @{
*/
#define TIMER                       TIM3
#define TIMER_IRQ                 TIM3_IRQn
#define TIMER_RCC                 RCC_APB1Periph_TIM3
#define TIMER_IRQ_FUN           TIM3_IRQHandler
/**@} *//**@name USART related macro definition
* @{
*/
#define UART_BAUDRATE           9600
#define UART_PORT               2
#define UART                    USART2
#define UART_IRQ                USART2_IRQn
#define UART_IRQ_FUN            USART2_IRQHandler#if (UART_PORT == 1)
#define UART_GPIO_Cmd          RCC_APB2PeriphClockCmd
#define UART_GPIO_CLK          RCC_APB2Periph_GPIOA#define UART_AFIO_Cmd          RCC_APB2PeriphClockCmd
#define UART_AFIO_CLK          RCC_APB2Periph_AFIO#define UART_CLK_Cmd           RCC_APB2PeriphClockCmd
#define UART_CLK               RCC_APB2Periph_USART1 #define UART_GPIO_PORT         GPIOA
#define UART_RxPin             GPIO_Pin_10
#define UART_TxPin             GPIO_Pin_9
#endif#if (UART_PORT == 2)
#define UART_GPIO_Cmd          RCC_APB2PeriphClockCmd
#define UART_GPIO_CLK          RCC_APB2Periph_GPIOA#define UART_AFIO_Cmd          RCC_APB2PeriphClockCmd
#define UART_AFIO_CLK          RCC_APB2Periph_AFIO#define UART_CLK_Cmd           RCC_APB1PeriphClockCmd
#define UART_CLK               RCC_APB1Periph_USART2 #define UART_GPIO_PORT         GPIOA
#define UART_RxPin             GPIO_Pin_3
#define UART_TxPin             GPIO_Pin_2
#endif#if (UART_PORT == 3)#define UART_GPIO_Cmd          RCC_APB2PeriphClockCmd
#define UART_GPIO_CLK          RCC_APB2Periph_GPIOC#define UART_AFIO_Cmd          RCC_APB2PeriphClockCmd
#define UART_AFIO_CLK          RCC_APB2Periph_AFIO#define UART_CLK_Cmd           RCC_APB1PeriphClockCmd
#define UART_CLK               RCC_APB1Periph_USART3 #define UART_GPIO_PORT         GPIOC
#define UART_RxPin             GPIO_Pin_11
#define UART_TxPin             GPIO_Pin_10#endif
/**@} *//** User area the current device state structure*/
extern dataPoint_t currentDataPoint;void gizTimerMs(void);
uint32_t gizGetTimerCount(void);
void timerInit(void);
void uartInit(void);void userInit(void);
void userHandle(void);
void mcuRestart(void);int32_t uartWrite(uint8_t *buf, uint32_t len);
int8_t gizwitsEventProcess(eventInfo_t *info, uint8_t *data, uint32_t len);#ifdef __cplusplus
}
#endif#endif

修改gizwits_product.h

  • List item
  • List item
  • List item
  • List item
  • List item
/**
************************************************************
* @file         gizwits_protocol.c
* @brief        Corresponding gizwits_product.c header file (including product hardware and software version definition)
* @author       Gizwits
* @date         2017-07-19
* @version      V03030000
* @copyright    Gizwits
*
* @note         机智云.只为智能硬件而生
*               Gizwits Smart Cloud  for Smart Products
*               链接|增值ֵ|开放|中立|安全|自有|自由|生态
*               www.gizwits.com
*
***********************************************************/
//#include "ringBuffer.h"
//#include "gizwits_product.h"
//#include "dataPointTools.h"
#include "delay.h"
/** Protocol global variables **/
//gizwitsProtocol_t gizwitsProtocol;
//extern dataPoint_t currentDataPoint;
//extern uint8_t wifi_flag;/**@name The serial port receives the ring buffer implementation
* @{
*/
rb_t pRb;                                               ///< Ring buffer structure variable
static uint8_t rbBuf[RB_MAX_LEN];                       ///< Ring buffer data cache buffer/**@} *//**
* @brief Write data to the ring buffer
* @param [in] buf        : buf adress
* @param [in] len        : byte length
* @return   correct : Returns the length of the written datafailure : -1
*/
int32_t gizPutData(uint8_t *buf, uint32_t len)
{int32_t count = 0;if(NULL == buf){GIZWITS_LOG("ERR: gizPutData buf is empty \n");return -1;}count = rbWrite(&pRb, buf, len);if(count != len){GIZWITS_LOG("ERR: Failed to rbWrite \n");return -1;}return count;
}/**
* @brief Protocol header initialization
*
* @param [out] head         : Protocol header pointer
*
* @return 0, success; other, failure
*/
static int8_t gizProtocolHeadInit(protocolHead_t *head)
{if(NULL == head){GIZWITS_LOG("ERR: gizProtocolHeadInit head is empty \n");return -1;}memset((uint8_t *)head, 0, sizeof(protocolHead_t));head->head[0] = 0xFF;head->head[1] = 0xFF;return 0;
}/**
* @brief Protocol ACK check processing function
*
* @param [in] data            : data adress
* @param [in] len             : data length
*
* @return 0, suceess; other, failure
*/
static int8_t gizProtocolWaitAck(uint8_t *gizdata, uint32_t len)
{if(NULL == gizdata){GIZWITS_LOG("ERR: data is empty \n");return -1;}memset((uint8_t *)&gizwitsProtocol.waitAck, 0, sizeof(protocolWaitAck_t));memcpy((uint8_t *)gizwitsProtocol.waitAck.buf, gizdata, len);gizwitsProtocol.waitAck.dataLen = (uint16_t)len;gizwitsProtocol.waitAck.flag = 1;gizwitsProtocol.waitAck.sendTime = gizGetTimerCount();return 0;
}
/**
* @brief generates "controlled events" according to protocol* @param [in] issuedData: Controlled data
* @param [out] info: event queue
* @param [out] dataPoints: data point data
* @return 0, the implementation of success, non-0, failed
*/
static int8_t ICACHE_FLASH_ATTR gizDataPoint2Event(gizwitsIssued_t *issuedData, eventInfo_t *info, dataPoint_t *dataPoints)
{if((NULL == issuedData) || (NULL == info) ||(NULL == dataPoints)){GIZWITS_LOG("gizDataPoint2Event Error , Illegal Param\n");return -1;}/** Greater than 1 byte to do bit conversion **/if(sizeof(issuedData->attrFlags) > 1){if(-1 == gizByteOrderExchange((uint8_t *)&issuedData->attrFlags,sizeof(attrFlags_t))){GIZWITS_LOG("gizByteOrderExchange Error\n");return -1;}}if(0x01 == issuedData->attrFlags.flagRelay_1){info->event[info->num] = EVENT_Relay_1;info->num++;dataPoints->valueRelay_1 = gizStandardDecompressionValue(Relay_1_BYTEOFFSET,Relay_1_BITOFFSET,Relay_1_LEN,(uint8_t *)&issuedData->attrVals.wBitBuf,sizeof(issuedData->attrVals.wBitBuf));}return 0;
}/**
* @brief contrasts the current data with the last data
*
* @param [in] cur: current data point data
* @param [in] last: last data point data
*
* @return: 0, no change in data; 1, data changes
*/
static int8_t ICACHE_FLASH_ATTR gizCheckReport(dataPoint_t *cur, dataPoint_t *last)
{int8_t ret = 0;static uint32_t lastReportTime = 0;uint32_t currentTime = 0;if((NULL == cur) || (NULL == last)){GIZWITS_LOG("gizCheckReport Error , Illegal Param\n");return -1;}currentTime = gizGetTimerCount();if(last->valueRelay_1 != cur->valueRelay_1){GIZWITS_LOG("valueRelay_1 Changed\n");ret = 1;}if(last->valueTemp != cur->valueTemp){if(currentTime - lastReportTime >= REPORT_TIME_MAX){GIZWITS_LOG("valueTemp Changed\n");ret = 1;}}if(last->valueHumi != cur->valueHumi){if(currentTime - lastReportTime >= REPORT_TIME_MAX){GIZWITS_LOG("valueHumi Changed\n");ret = 1;}}if(last->valueLight_Intensity != cur->valueLight_Intensity){if(currentTime - lastReportTime >= REPORT_TIME_MAX){GIZWITS_LOG("valueLight_Intensity Changed\n");ret = 1;}}if(1 == ret){lastReportTime = gizGetTimerCount();}return ret;
}/**
* @brief User data point data is converted to wit the cloud to report data point data
*
* @param [in] dataPoints: user data point data address
* @param [out] devStatusPtr: wit the cloud data point data address
*
* @return 0, the correct return; -1, the error returned
*/
static int8_t ICACHE_FLASH_ATTR gizDataPoints2ReportData(dataPoint_t *dataPoints , devStatus_t *devStatusPtr)
{if((NULL == dataPoints) || (NULL == devStatusPtr)){GIZWITS_LOG("gizDataPoints2ReportData Error , Illegal Param\n");return -1;}gizMemset((uint8_t *)devStatusPtr->wBitBuf,0,sizeof(devStatusPtr->wBitBuf));gizStandardCompressValue(Relay_1_BYTEOFFSET,Relay_1_BITOFFSET,Relay_1_LEN,(uint8_t *)devStatusPtr,dataPoints->valueRelay_1);gizByteOrderExchange((uint8_t *)devStatusPtr->wBitBuf,sizeof(devStatusPtr->wBitBuf));devStatusPtr->valueTemp = gizY2X(Temp_RATIO,  Temp_ADDITION, dataPoints->valueTemp); devStatusPtr->valueHumi = gizY2X(Humi_RATIO,  Humi_ADDITION, dataPoints->valueHumi); devStatusPtr->valueLight_Intensity = gizY2X(Light_Intensity_RATIO,  Light_Intensity_ADDITION, dataPoints->valueLight_Intensity); return 0;
}/**
* @brief This function is called by the Gagent module to receive the relevant protocol data from the cloud or APP
* @param [in] inData The protocol data entered
* @param [in] inLen Enter the length of the data
* @param [out] outData The output of the protocol data
* @param [out] outLen The length of the output data
* @return 0, the implementation of success, non-0, failed
*/
static int8_t gizProtocolIssuedProcess(char *did, uint8_t *inData, uint32_t inLen, uint8_t *outData, uint32_t *outLen)
{uint8_t issuedAction = inData[0];if((NULL == inData)||(NULL == outData)||(NULL == outLen)){GIZWITS_LOG("gizProtocolIssuedProcess Error , Illegal Param\n");return -1;}if(NULL == did){memset((uint8_t *)&gizwitsProtocol.issuedProcessEvent, 0, sizeof(eventInfo_t));switch(issuedAction){case ACTION_CONTROL_DEVICE:gizDataPoint2Event((gizwitsIssued_t *)&inData[1], &gizwitsProtocol.issuedProcessEvent,&gizwitsProtocol.gizCurrentDataPoint);gizwitsProtocol.issuedFlag = ACTION_CONTROL_TYPE;outData = NULL;*outLen = 0;break;case ACTION_READ_DEV_STATUS:if(0 == gizDataPoints2ReportData(&gizwitsProtocol.gizLastDataPoint,&gizwitsProtocol.reportData.devStatus)){memcpy(outData+1, (uint8_t *)&gizwitsProtocol.reportData.devStatus, sizeof(gizwitsReport_t));outData[0] = ACTION_READ_DEV_STATUS_ACK;*outLen = sizeof(gizwitsReport_t)+1;}else{return -1;}break;case ACTION_W2D_TRANSPARENT_DATA:memcpy(gizwitsProtocol.transparentBuff, &inData[1], inLen-1);gizwitsProtocol.transparentLen = inLen - 1;gizwitsProtocol.issuedProcessEvent.event[gizwitsProtocol.issuedProcessEvent.num] = TRANSPARENT_DATA;gizwitsProtocol.issuedProcessEvent.num++;gizwitsProtocol.issuedFlag = ACTION_W2D_TRANSPARENT_TYPE;outData = NULL;*outLen = 0;break;default:break;}}return 0;
}
/**
* @brief The protocol sends data back , P0 ACK
*
* @param [in] head                  : Protocol head pointer
* @param [in] data                  : Payload data
* @param [in] len                   : Payload data length
* @param [in] proFlag               : DID flag ,1 for Virtual sub device did ,0 for single product or gateway
*
* @return : 0,Ack success;
*           -1,Input Param Illegal
*           -2,Serial send faild
*/
static int32_t gizProtocolIssuedDataAck(protocolHead_t *head, uint8_t *gizdata, uint32_t len, uint8_t proFlag)
{int32_t ret = 0;uint8_t tx_buf[RB_MAX_LEN];uint32_t offset = 0;uint8_t sDidLen = 0;uint16_t data_len = 0;uint8_t *pTxBuf = tx_buf;if(NULL == gizdata){GIZWITS_LOG("[ERR]  data Is Null \n");return -1;}if(0x1 == proFlag){sDidLen = *((uint8_t *)head + sizeof(protocolHead_t));data_len = 5 + 1 + sDidLen + len;   }else{data_len = 5 + len;}GIZWITS_LOG("len = %d , sDidLen = %d ,data_len = %d\n", len,sDidLen,data_len);*pTxBuf ++= 0xFF;*pTxBuf ++= 0xFF;*pTxBuf ++= (uint8_t)(data_len>>8);*pTxBuf ++= (uint8_t)(data_len);*pTxBuf ++= head->cmd + 1;*pTxBuf ++= head->sn;*pTxBuf ++= 0x00;*pTxBuf ++= proFlag;offset = 8;if(0x1 == proFlag){*pTxBuf ++= sDidLen;offset += 1;memcpy(&tx_buf[offset],(uint8_t *)head+sizeof(protocolHead_t)+1,sDidLen);offset += sDidLen;pTxBuf += sDidLen;}if(0 != len){memcpy(&tx_buf[offset],gizdata,len);}tx_buf[data_len + 4 - 1 ] = gizProtocolSum( tx_buf , (data_len+4));ret = uartWrite(tx_buf, data_len+4);if(ret < 0){GIZWITS_LOG("uart write error %d \n", ret);return -2;}return 0;
}/**
* @brief Report data interface
*
* @param [in] action            : PO action
* @param [in] data              : Payload data
* @param [in] len               : Payload data length
*
* @return : 0,Ack success;
*           -1,Input Param Illegal
*           -2,Serial send faild
*/
static int32_t gizReportData(uint8_t action, uint8_t *gizdata, uint32_t len)
{int32_t ret = 0;protocolReport_t protocolReport;if(NULL == gizdata){GIZWITS_LOG("gizReportData Error , Illegal Param\n");return -1;}gizProtocolHeadInit((protocolHead_t *)&protocolReport);protocolReport.head.cmd = CMD_REPORT_P0;protocolReport.head.sn = gizwitsProtocol.sn++;protocolReport.action = action;protocolReport.head.len = exchangeBytes(sizeof(protocolReport_t)-4);memcpy((gizwitsReport_t *)&protocolReport.reportData, (gizwitsReport_t *)gizdata,len);protocolReport.sum = gizProtocolSum((uint8_t *)&protocolReport, sizeof(protocolReport_t));ret = uartWrite((uint8_t *)&protocolReport, sizeof(protocolReport_t));if(ret < 0){GIZWITS_LOG("ERR: uart write error %d \n", ret);return -2;}gizProtocolWaitAck((uint8_t *)&protocolReport, sizeof(protocolReport_t));return ret;
}/**
* @brief Datapoints reporting mechanism
*
* 1. Changes are reported immediately* 2. Data timing report , 600000 Millisecond
*
*@param [in] currentData       : Current datapoints value
* @return : NULL
*/
static void gizDevReportPolicy(dataPoint_t *currentData)
{static uint32_t lastRepTime = 0;uint32_t timeNow = gizGetTimerCount();if((1 == gizCheckReport(currentData, (dataPoint_t *)&gizwitsProtocol.gizLastDataPoint))){GIZWITS_LOG("changed, report data\n");if(0 == gizDataPoints2ReportData(currentData,&gizwitsProtocol.reportData.devStatus)){gizReportData(ACTION_REPORT_DEV_STATUS, (uint8_t *)&gizwitsProtocol.reportData.devStatus, sizeof(devStatus_t));        }       memcpy((uint8_t *)&gizwitsProtocol.gizLastDataPoint, (uint8_t *)currentData, sizeof(dataPoint_t));}if((0 == (timeNow % (600000))) && (lastRepTime != timeNow)){GIZWITS_LOG("Info: 600S report data\n");if(0 == gizDataPoints2ReportData(currentData,&gizwitsProtocol.reportData.devStatus)){gizReportData(ACTION_REPORT_DEV_STATUS, (uint8_t *)&gizwitsProtocol.reportData.devStatus, sizeof(devStatus_t));}       memcpy((uint8_t *)&gizwitsProtocol.gizLastDataPoint, (uint8_t *)currentData, sizeof(dataPoint_t));lastRepTime = timeNow;}
}/**
* @brief Get a packet of data from the ring buffer
*
* @param [in]  rb                  : Input data address
* @param [out] data                : Output data address
* @param [out] len                 : Output data length
*
* @return : 0,Return correct ;-1,Return failure;-2,Data check failure
*/
static int8_t gizProtocolGetOnePacket(rb_t *rb, uint8_t *gizdata, uint16_t *len)
{int32_t ret = 0;uint8_t sum = 0;int32_t i = 0;uint8_t tmpData;uint8_t tmpLen = 0;uint16_t tmpCount = 0;static uint8_t protocolFlag = 0;static uint16_t protocolCount = 0;static uint8_t lastData = 0;static uint8_t debugCount = 0;uint8_t *protocolBuff = gizdata;protocolHead_t *head = NULL;if((NULL == rb) || (NULL == gizdata) ||(NULL == len)){GIZWITS_LOG("gizProtocolGetOnePacket Error , Illegal Param\n");return -1;}tmpLen = rbCanRead(rb);if(0 == tmpLen){return -1;}for(i=0; i<tmpLen; i++){ret = rbRead(rb, &tmpData, 1);if(0 != ret){if((0xFF == lastData) && (0xFF == tmpData)){if(0 == protocolFlag){protocolBuff[0] = 0xFF;protocolBuff[1] = 0xFF;protocolCount = 2;protocolFlag = 1;}else{if((protocolCount > 4) && (protocolCount != tmpCount)){protocolBuff[0] = 0xFF;protocolBuff[1] = 0xFF;protocolCount = 2;}}}else if((0xFF == lastData) && (0x55 == tmpData)){}else{if(1 == protocolFlag){protocolBuff[protocolCount] = tmpData;protocolCount++;if(protocolCount > 4){head = (protocolHead_t *)protocolBuff;tmpCount = exchangeBytes(head->len)+4;if(protocolCount == tmpCount){break;}}}}lastData = tmpData;debugCount++;}}if((protocolCount > 4) && (protocolCount == tmpCount)){sum = gizProtocolSum(protocolBuff, protocolCount);if(protocolBuff[protocolCount-1] == sum){memcpy(gizdata, protocolBuff, tmpCount);*len = tmpCount;protocolFlag = 0;protocolCount = 0;debugCount = 0;lastData = 0;return 0;}else{return -2;}}return 1;
}/**
* @brief Protocol data resend* The protocol data resend when check timeout and meet the resend limiting* @param none
*
* @return none
*/
static void gizProtocolResendData(void)
{int32_t ret = 0;if(0 == gizwitsProtocol.waitAck.flag){return;}GIZWITS_LOG("Warning: timeout, resend data \n");ret = uartWrite(gizwitsProtocol.waitAck.buf, gizwitsProtocol.waitAck.dataLen);if(ret != gizwitsProtocol.waitAck.dataLen){GIZWITS_LOG("ERR: resend data error\n");}gizwitsProtocol.waitAck.sendTime = gizGetTimerCount();
}/**
* @brief Clear the ACK protocol message
*
* @param [in] head : Protocol header address
*
* @return 0, success; other, failure
*/
static int8_t gizProtocolWaitAckCheck(protocolHead_t *head)
{protocolHead_t *waitAckHead = (protocolHead_t *)gizwitsProtocol.waitAck.buf;if(NULL == head){GIZWITS_LOG("ERR: data is empty \n");return -1;}if(waitAckHead->cmd+1 == head->cmd){memset((uint8_t *)&gizwitsProtocol.waitAck, 0, sizeof(protocolWaitAck_t));}return 0;
}/**
* @brief Send general protocol message data
*
* @param [in] head              : Protocol header address
*
* @return : Return effective data length;-1,return failure
*/
static int32_t gizProtocolCommonAck(protocolHead_t *head)
{int32_t ret = 0;protocolCommon_t ack;if(NULL == head){GIZWITS_LOG("ERR: gizProtocolCommonAck data is empty \n");return -1;}memcpy((uint8_t *)&ack, (uint8_t *)head, sizeof(protocolHead_t));ack.head.cmd = ack.head.cmd+1;ack.head.len = exchangeBytes(sizeof(protocolCommon_t)-4);ack.sum = gizProtocolSum((uint8_t *)&ack, sizeof(protocolCommon_t));ret = uartWrite((uint8_t *)&ack, sizeof(protocolCommon_t));if(ret < 0){GIZWITS_LOG("ERR: uart write error %d \n", ret);}return ret;
}/**
* @brief ACK processing function* Time-out 200ms no ACK resend,resend two times at most* @param none
*
* @return none
*/
static void gizProtocolAckHandle(void)
{if(1 == gizwitsProtocol.waitAck.flag){if(SEND_MAX_NUM > gizwitsProtocol.waitAck.num){// Time-out no ACK resendif(SEND_MAX_TIME < (gizGetTimerCount() - gizwitsProtocol.waitAck.sendTime)){GIZWITS_LOG("Warning:gizProtocolResendData %d %d %d\n", gizGetTimerCount(), gizwitsProtocol.waitAck.sendTime, gizwitsProtocol.waitAck.num);gizProtocolResendData();gizwitsProtocol.waitAck.num++;}}else{memset((uint8_t *)&gizwitsProtocol.waitAck, 0, sizeof(protocolWaitAck_t));}}
}/**
* @brief Protocol 4.1 WiFi module requests device information
*
* @param[in] head : Protocol header address
*
* @return Return effective data length;-1,return failure
*/
static int32_t gizProtocolGetDeviceInfo(protocolHead_t * head)
{int32_t ret = 0;protocolDeviceInfo_t deviceInfo;if(NULL == head){GIZWITS_LOG("gizProtocolGetDeviceInfo Error , Illegal Param\n");return -1;}gizProtocolHeadInit((protocolHead_t *)&deviceInfo);deviceInfo.head.cmd = ACK_GET_DEVICE_INFO;deviceInfo.head.sn = head->sn;memcpy((uint8_t *)deviceInfo.protocolVer, protocol_VERSION, 8);memcpy((uint8_t *)deviceInfo.p0Ver, P0_VERSION, 8);memcpy((uint8_t *)deviceInfo.softVer, SOFTWARE_VERSION, 8);memcpy((uint8_t *)deviceInfo.hardVer, HARDWARE_VERSION, 8);memcpy((uint8_t *)deviceInfo.productKey, PRODUCT_KEY, strlen(PRODUCT_KEY));memcpy((uint8_t *)deviceInfo.productSecret, PRODUCT_SECRET, strlen(PRODUCT_SECRET));memset((uint8_t *)deviceInfo.devAttr, 0, 8);deviceInfo.devAttr[7] |= DEV_IS_GATEWAY<<0;deviceInfo.devAttr[7] |= (0x01<<1);deviceInfo.ninableTime = exchangeBytes(NINABLETIME);deviceInfo.head.len = exchangeBytes(sizeof(protocolDeviceInfo_t)-4);deviceInfo.sum = gizProtocolSum((uint8_t *)&deviceInfo, sizeof(protocolDeviceInfo_t));ret = uartWrite((uint8_t *)&deviceInfo, sizeof(protocolDeviceInfo_t));if(ret < 0){GIZWITS_LOG("ERR: uart write error %d \n", ret);}return ret;
}/**
* @brief Protocol 4.7 Handling of illegal message notification* @param[in] head  : Protocol header address
* @param[in] errno : Illegal message notification type
* @return 0, success; other, failure
*/
static int32_t gizProtocolErrorCmd(protocolHead_t *head,errorPacketsType_t errno)
{int32_t ret = 0;protocolErrorType_t errorType;if(NULL == head){GIZWITS_LOG("gizProtocolErrorCmd Error , Illegal Param\n");return -1;}gizProtocolHeadInit((protocolHead_t *)&errorType);errorType.head.cmd = ACK_ERROR_PACKAGE;errorType.head.sn = head->sn;errorType.head.len = exchangeBytes(sizeof(protocolErrorType_t)-4);errorType.error = errno;errorType.sum = gizProtocolSum((uint8_t *)&errorType, sizeof(protocolErrorType_t));ret = uartWrite((uint8_t *)&errorType, sizeof(protocolErrorType_t));if(ret < 0){GIZWITS_LOG("ERR: uart write error %d \n", ret);}return ret;
}/**
* @brief Protocol 4.13 Get and process network time
*
* @param [in] head : Protocol header address
*
* @return 0, success; other, failure
*/
static int8_t gizProtocolNTP(protocolHead_t *head)
{  protocolUTT_t *UTTInfo = (protocolUTT_t *)head;if(NULL == head){GIZWITS_LOG("ERR: NTP is empty \n");return -1;}memcpy((uint8_t *)&gizwitsProtocol.TimeNTP,(uint8_t *)UTTInfo->time, (7 + 4));gizwitsProtocol.TimeNTP.year = exchangeBytes(gizwitsProtocol.TimeNTP.year);gizwitsProtocol.TimeNTP.ntp =exchangeWord(gizwitsProtocol.TimeNTP.ntp);gizwitsProtocol.NTPEvent.event[gizwitsProtocol.NTPEvent.num] = WIFI_NTP;gizwitsProtocol.NTPEvent.num++;gizwitsProtocol.issuedFlag = GET_NTP_TYPE;return 0;
}/**
* @brief Protocol 4.4 Device MCU restarts function* @param none
* @return none
*/
static void gizProtocolReboot(void)
{uint32_t timeDelay = gizGetTimerCount();/*Wait 600ms*/while((gizGetTimerCount() - timeDelay) <= 600);mcuRestart();
}/**
* @brief Protocol 4.5 :The WiFi module informs the device MCU of working status about the WiFi module* @param[in] status WiFi module working status
* @return none
*/
static int8_t gizProtocolModuleStatus(protocolWifiStatus_t *status)
{static wifiStatus_t lastStatus;if(NULL == status){GIZWITS_LOG("gizProtocolModuleStatus Error , Illegal Param\n");return -1;}status->ststus.value = exchangeBytes(status->ststus.value);//OnBoarding mode statusif(lastStatus.types.onboarding != status->ststus.types.onboarding){if(1 == status->ststus.types.onboarding){if(1 == status->ststus.types.softap){gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_SOFTAP;gizwitsProtocol.wifiStatusEvent.num++;GIZWITS_LOG("OnBoarding: SoftAP or Web mode\n");}if(1 == status->ststus.types.station){gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_AIRLINK;gizwitsProtocol.wifiStatusEvent.num++;GIZWITS_LOG("OnBoarding: AirLink mode\n");}}else{if(1 == status->ststus.types.softap){gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_SOFTAP;gizwitsProtocol.wifiStatusEvent.num++;GIZWITS_LOG("OnBoarding: SoftAP or Web mode\n");}if(1 == status->ststus.types.station){gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_STATION;gizwitsProtocol.wifiStatusEvent.num++;GIZWITS_LOG("OnBoarding: Station mode\n");}}}//binding mode statusif(lastStatus.types.binding != status->ststus.types.binding){lastStatus.types.binding = status->ststus.types.binding;if(1 == status->ststus.types.binding){gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_OPEN_BINDING;gizwitsProtocol.wifiStatusEvent.num++;GIZWITS_LOG("WiFi status: in binding mode\n");}else{gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_CLOSE_BINDING;gizwitsProtocol.wifiStatusEvent.num++;GIZWITS_LOG("WiFi status: out binding mode\n");}}//router statusif(lastStatus.types.con_route != status->ststus.types.con_route){lastStatus.types.con_route = status->ststus.types.con_route;if(1 == status->ststus.types.con_route){gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_CON_ROUTER;gizwitsProtocol.wifiStatusEvent.num++;GIZWITS_LOG("WiFi status: connected router\n");}else{gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_DISCON_ROUTER;gizwitsProtocol.wifiStatusEvent.num++;GIZWITS_LOG("WiFi status: disconnected router\n");}}//M2M server statusif(lastStatus.types.con_m2m != status->ststus.types.con_m2m){lastStatus.types.con_m2m = status->ststus.types.con_m2m;if(1 == status->ststus.types.con_m2m){gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_CON_M2M;gizwitsProtocol.wifiStatusEvent.num++;GIZWITS_LOG("WiFi status: connected m2m\n");}else{gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_DISCON_M2M;gizwitsProtocol.wifiStatusEvent.num++;GIZWITS_LOG("WiFi status: disconnected m2m\n");}}//APP statusif(lastStatus.types.app != status->ststus.types.app){lastStatus.types.app = status->ststus.types.app;if(1 == status->ststus.types.app){gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_CON_APP;gizwitsProtocol.wifiStatusEvent.num++;GIZWITS_LOG("WiFi status: app connect\n");}else{gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_DISCON_APP;gizwitsProtocol.wifiStatusEvent.num++;GIZWITS_LOG("WiFi status: no app connect\n");}}//test mode statusif(lastStatus.types.test != status->ststus.types.test){lastStatus.types.test = status->ststus.types.test;if(1 == status->ststus.types.test){gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_OPEN_TESTMODE;gizwitsProtocol.wifiStatusEvent.num++;GIZWITS_LOG("WiFi status: in test mode\n");}else{gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_CLOSE_TESTMODE;gizwitsProtocol.wifiStatusEvent.num++;GIZWITS_LOG("WiFi status: out test mode\n");}}gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_RSSI;gizwitsProtocol.wifiStatusEvent.num++;gizwitsProtocol.wifiStatusData.rssi = status->ststus.types.rssi;GIZWITS_LOG("RSSI is %d \n", gizwitsProtocol.wifiStatusData.rssi);gizwitsProtocol.issuedFlag = WIFI_STATUS_TYPE;return 0;
}/**@name Gizwits User API interface
* @{
*//**
* @brief gizwits Protocol initialization interface* Protocol-related timer, serial port initialization* Datapoint initialization* @param none
* @return none
*/
void gizwitsInit(void)
{    pRb.rbCapacity = RB_MAX_LEN;pRb.rbBuff = rbBuf;if(0 == rbCreate(&pRb)){GIZWITS_LOG("rbCreate Success \n");}else{GIZWITS_LOG("rbCreate Faild \n");}memset((uint8_t *)&gizwitsProtocol, 0, sizeof(gizwitsProtocol_t));
}/**
* @brief WiFi configure interface* Set the WiFi module into the corresponding configuration mode or reset the module* @param[in] mode :0x0, reset the module ;0x01, SoftAp mode ;0x02, AirLink mode ;0x03, Production test mode; 0x04:allow users to bind devices* @return Error command code
*/
int32_t gizwitsSetMode(uint8_t mode)
{int32_t ret = 0;protocolCfgMode_t cfgMode;protocolCommon_t setDefault;switch(mode){case WIFI_RESET_MODE:gizProtocolHeadInit((protocolHead_t *)&setDefault);setDefault.head.cmd = CMD_SET_DEFAULT;setDefault.head.sn = gizwitsProtocol.sn++;setDefault.head.len = exchangeBytes(sizeof(protocolCommon_t)-4);setDefault.sum = gizProtocolSum((uint8_t *)&setDefault, sizeof(protocolCommon_t));ret = uartWrite((uint8_t *)&setDefault, sizeof(protocolCommon_t));if(ret < 0){GIZWITS_LOG("ERR: uart write error %d \n", ret);}gizProtocolWaitAck((uint8_t *)&setDefault, sizeof(protocolCommon_t));   break;case WIFI_SOFTAP_MODE:gizProtocolHeadInit((protocolHead_t *)&cfgMode);cfgMode.head.cmd = CMD_WIFI_CONFIG;cfgMode.head.sn = gizwitsProtocol.sn++;cfgMode.cfgMode = mode;cfgMode.head.len = exchangeBytes(sizeof(protocolCfgMode_t)-4);cfgMode.sum = gizProtocolSum((uint8_t *)&cfgMode, sizeof(protocolCfgMode_t));ret = uartWrite((uint8_t *)&cfgMode, sizeof(protocolCfgMode_t));if(ret < 0){GIZWITS_LOG("ERR: uart write error %d \n", ret);}gizProtocolWaitAck((uint8_t *)&cfgMode, sizeof(protocolCfgMode_t)); break;case WIFI_AIRLINK_MODE:gizProtocolHeadInit((protocolHead_t *)&cfgMode);cfgMode.head.cmd = CMD_WIFI_CONFIG;cfgMode.head.sn = gizwitsProtocol.sn++;cfgMode.cfgMode = mode;cfgMode.head.len = exchangeBytes(sizeof(protocolCfgMode_t)-4);cfgMode.sum = gizProtocolSum((uint8_t *)&cfgMode, sizeof(protocolCfgMode_t));ret = uartWrite((uint8_t *)&cfgMode, sizeof(protocolCfgMode_t));if(ret < 0){GIZWITS_LOG("ERR: uart write error %d \n", ret);}gizProtocolWaitAck((uint8_t *)&cfgMode, sizeof(protocolCfgMode_t)); break;case WIFI_PRODUCTION_TEST:gizProtocolHeadInit((protocolHead_t *)&setDefault);setDefault.head.cmd = CMD_PRODUCTION_TEST;setDefault.head.sn = gizwitsProtocol.sn++;setDefault.head.len = exchangeBytes(sizeof(protocolCommon_t)-4);setDefault.sum = gizProtocolSum((uint8_t *)&setDefault, sizeof(protocolCommon_t));ret = uartWrite((uint8_t *)&setDefault, sizeof(protocolCommon_t));if(ret < 0){GIZWITS_LOG("ERR: uart write error %d \n", ret);}gizProtocolWaitAck((uint8_t *)&setDefault, sizeof(protocolCommon_t));break;case WIFI_NINABLE_MODE:gizProtocolHeadInit((protocolHead_t *)&setDefault);setDefault.head.cmd = CMD_NINABLE_MODE;setDefault.head.sn = gizwitsProtocol.sn++;setDefault.head.len = exchangeBytes(sizeof(protocolCommon_t)-4);setDefault.sum = gizProtocolSum((uint8_t *)&setDefault, sizeof(protocolCommon_t));ret = uartWrite((uint8_t *)&setDefault, sizeof(protocolCommon_t));if(ret < 0){GIZWITS_LOG("ERR: uart write error %d \n", ret);}gizProtocolWaitAck((uint8_t *)&setDefault, sizeof(protocolCommon_t)); break;case WIFI_REBOOT_MODE:gizProtocolHeadInit((protocolHead_t *)&setDefault);setDefault.head.cmd = CMD_REBOOT_MODULE;setDefault.head.sn = gizwitsProtocol.sn++;setDefault.head.len = exchangeBytes(sizeof(protocolCommon_t)-4);setDefault.sum = gizProtocolSum((uint8_t *)&setDefault, sizeof(protocolCommon_t));ret = uartWrite((uint8_t *)&setDefault, sizeof(protocolCommon_t));if(ret < 0){GIZWITS_LOG("ERR: uart write error %d \n", ret);}gizProtocolWaitAck((uint8_t *)&setDefault, sizeof(protocolCommon_t)); break;default:GIZWITS_LOG("ERR: CfgMode error!\n");break;}return ret;
}/**
* @brief Get the the network time* Protocol 4.13:"Device MCU send" of "the MCU requests access to the network time"* @param[in] none
* @return none
*/
void gizwitsGetNTP(void)
{int32_t ret = 0;protocolCommon_t getNTP;gizProtocolHeadInit((protocolHead_t *)&getNTP);getNTP.head.cmd = CMD_GET_NTP;getNTP.head.sn = gizwitsProtocol.sn++;getNTP.head.len = exchangeBytes(sizeof(protocolCommon_t)-4);getNTP.sum = gizProtocolSum((uint8_t *)&getNTP, sizeof(protocolCommon_t));ret = uartWrite((uint8_t *)&getNTP, sizeof(protocolCommon_t));if(ret < 0){GIZWITS_LOG("ERR[NTP]: uart write error %d \n", ret);}gizProtocolWaitAck((uint8_t *)&getNTP, sizeof(protocolCommon_t));
}/**
* @brief Get Module Info* * @param[in] none
* @return none
*/
void gizwitsGetModuleInfo(void)
{int32_t ret = 0;protocolGetModuleInfo_t getModuleInfo;gizProtocolHeadInit((protocolHead_t *)&getModuleInfo);getModuleInfo.head.cmd = CMD_ASK_MODULE_INFO;getModuleInfo.head.sn = gizwitsProtocol.sn++;getModuleInfo.type = 0x0;getModuleInfo.head.len = exchangeBytes(sizeof(protocolGetModuleInfo_t)-4);getModuleInfo.sum = gizProtocolSum((uint8_t *)&getModuleInfo, sizeof(protocolGetModuleInfo_t));ret = uartWrite((uint8_t *)&getModuleInfo, sizeof(protocolGetModuleInfo_t));if(ret < 0){GIZWITS_LOG("ERR[NTP]: uart write error %d \n", ret);}gizProtocolWaitAck((uint8_t *)&getModuleInfo, sizeof(protocolGetModuleInfo_t));
}/**
* @brief Module Info Analyse
*
* @param [in] head :
*
* @return 0, Success, , other,Faild
*/
static int8_t gizProtocolModuleInfoHandle(protocolHead_t *head)
{protocolModuleInfo_t *moduleInfo = (protocolModuleInfo_t *)head;if(NULL == head){GIZWITS_LOG("NTP is empty \n");return -1;}memcpy((uint8_t *)&gizwitsProtocol.wifiModuleNews,(uint8_t *)&moduleInfo->wifiModuleInfo, sizeof(moduleInfo_t));gizwitsProtocol.moduleInfoEvent.event[gizwitsProtocol.moduleInfoEvent.num] = MODULE_INFO;gizwitsProtocol.moduleInfoEvent.num++;gizwitsProtocol.issuedFlag = GET_MODULEINFO_TYPE;return 0;
}/**
* @brief Protocol handling function* * @param [in] currentData :The protocol data pointer
* @return none
*/
int32_t gizwitsHandle(dataPoint_t *currentData)
{int8_t ret = 0;
#ifdef PROTOCOL_DEBUGuint16_t i = 0;
#endifuint8_t ackData[RB_MAX_LEN];uint16_t protocolLen = 0;uint32_t ackLen = 0;protocolHead_t *recvHead = NULL;char *didPtr = NULL;uint16_t offset = 0;if(NULL == currentData){GIZWITS_LOG("GizwitsHandle Error , Illegal Param\n");return -1;}/*resend strategy*/gizProtocolAckHandle();ret = gizProtocolGetOnePacket(&pRb, gizwitsProtocol.protocolBuf, &protocolLen);if(0 == ret){GIZWITS_LOG("Get One Packet!\n");#ifdef PROTOCOL_DEBUGGIZWITS_LOG("WiFi2MCU[%4d:%4d]: ", gizGetTimerCount(), protocolLen);for(i=0; i<protocolLen;i++){GIZWITS_LOG("%02x ", gizwitsProtocol.protocolBuf[i]);}GIZWITS_LOG("\n");
#endifrecvHead = (protocolHead_t *)gizwitsProtocol.protocolBuf;switch (recvHead->cmd){case CMD_GET_DEVICE_INTO:gizProtocolGetDeviceInfo(recvHead);break;case CMD_ISSUED_P0:GIZWITS_LOG("flag %x %x \n", recvHead->flags[0], recvHead->flags[1]);//offset = 1;if(0 == gizProtocolIssuedProcess(didPtr, gizwitsProtocol.protocolBuf+sizeof(protocolHead_t)+offset, protocolLen-(sizeof(protocolHead_t)+offset+1), ackData, &ackLen)){gizProtocolIssuedDataAck(recvHead, ackData, ackLen,recvHead->flags[1]);GIZWITS_LOG("AckData : \n");}break;case CMD_HEARTBEAT:gizProtocolCommonAck(recvHead);break;case CMD_WIFISTATUS:gizProtocolCommonAck(recvHead);gizProtocolModuleStatus((protocolWifiStatus_t *)recvHead);break;case ACK_REPORT_P0:case ACK_WIFI_CONFIG:case ACK_SET_DEFAULT:case ACK_NINABLE_MODE:case ACK_REBOOT_MODULE:gizProtocolWaitAckCheck(recvHead);break;case CMD_MCU_REBOOT:gizProtocolCommonAck(recvHead);GIZWITS_LOG("report:MCU reboot!\n");gizProtocolReboot();break;case CMD_ERROR_PACKAGE:break;case ACK_PRODUCTION_TEST:gizProtocolWaitAckCheck(recvHead);GIZWITS_LOG("Ack PRODUCTION_MODE success \n");break;           case ACK_GET_NTP:gizProtocolWaitAckCheck(recvHead);gizProtocolNTP(recvHead);GIZWITS_LOG("Ack GET_UTT success \n");break; case ACK_ASK_MODULE_INFO:gizProtocolWaitAckCheck(recvHead);gizProtocolModuleInfoHandle(recvHead);GIZWITS_LOG("Ack GET_Module success \n");break;default:gizProtocolErrorCmd(recvHead,ERROR_CMD);GIZWITS_LOG("ERR: cmd code error!\n");break;}}else if(-2 == ret){//Check failed, report exceptionrecvHead = (protocolHead_t *)gizwitsProtocol.protocolBuf;gizProtocolErrorCmd(recvHead,ERROR_ACK_SUM);GIZWITS_LOG("ERR: check sum error!\n");return -2;}switch(gizwitsProtocol.issuedFlag){case ACTION_CONTROL_TYPE:gizwitsProtocol.issuedFlag = STATELESS_TYPE;gizwitsEventProcess(&gizwitsProtocol.issuedProcessEvent, (uint8_t *)&gizwitsProtocol.gizCurrentDataPoint, sizeof(dataPoint_t));memset((uint8_t *)&gizwitsProtocol.issuedProcessEvent,0x0,sizeof(gizwitsProtocol.issuedProcessEvent));  break;case WIFI_STATUS_TYPE:gizwitsProtocol.issuedFlag = STATELESS_TYPE;gizwitsEventProcess(&gizwitsProtocol.wifiStatusEvent, (uint8_t *)&gizwitsProtocol.wifiStatusData, sizeof(moduleStatusInfo_t));memset((uint8_t *)&gizwitsProtocol.wifiStatusEvent,0x0,sizeof(gizwitsProtocol.wifiStatusEvent));break;case ACTION_W2D_TRANSPARENT_TYPE:gizwitsProtocol.issuedFlag = STATELESS_TYPE;gizwitsEventProcess(&gizwitsProtocol.issuedProcessEvent, (uint8_t *)gizwitsProtocol.transparentBuff, gizwitsProtocol.transparentLen);break;case GET_NTP_TYPE:gizwitsProtocol.issuedFlag = STATELESS_TYPE;gizwitsEventProcess(&gizwitsProtocol.NTPEvent, (uint8_t *)&gizwitsProtocol.TimeNTP, sizeof(protocolTime_t));memset((uint8_t *)&gizwitsProtocol.NTPEvent,0x0,sizeof(gizwitsProtocol.NTPEvent));break;case GET_MODULEINFO_TYPE:gizwitsProtocol.issuedFlag = STATELESS_TYPE;gizwitsEventProcess(&gizwitsProtocol.moduleInfoEvent, (uint8_t *)&gizwitsProtocol.wifiModuleNews, sizeof(moduleInfo_t));memset((uint8_t *)&gizwitsProtocol.moduleInfoEvent,0x0,sizeof(moduleInfo_t));break;default:break;      }gizDevReportPolicy(currentData);return 0;
}/**
* @brief gizwits report transparent data interface* The user can call the interface to complete the reporting of private protocol data* @param [in] data :Private protocol data
* @param [in] len  :Private protocol data length
* @return 0,success ;other,failure
*/
int32_t gizwitsPassthroughData(uint8_t * gizdata, uint32_t len)
{int32_t ret = 0;uint8_t tx_buf[MAX_PACKAGE_LEN];uint8_t *pTxBuf = tx_buf;uint16_t data_len = 6+len;if(NULL == gizdata){GIZWITS_LOG("[ERR] gizwitsPassthroughData Error \n");return (-1);}*pTxBuf ++= 0xFF;*pTxBuf ++= 0xFF;*pTxBuf ++= (uint8_t)(data_len>>8);//len*pTxBuf ++= (uint8_t)(data_len);*pTxBuf ++= CMD_REPORT_P0;//0x1b cmd*pTxBuf ++= gizwitsProtocol.sn++;//sn*pTxBuf ++= 0x00;//flag*pTxBuf ++= 0x00;//flag*pTxBuf ++= ACTION_D2W_TRANSPARENT_DATA;//P0_Cmdmemcpy(&tx_buf[9],gizdata,len);tx_buf[data_len + 4 - 1 ] = gizProtocolSum( tx_buf , (data_len+4));ret = uartWrite(tx_buf, data_len+4);if(ret < 0){GIZWITS_LOG("ERR: uart write error %d \n", ret);}gizProtocolWaitAck(tx_buf, data_len+4);return 0;
}void gziwits_Task(dataPoint_t * currentDataPoint)
{static uint32_t Timer=0;if(SoftTimer(Timer,5000)){gizwitsHandle(currentDataPoint); Timer=GetSoftTimer();}
}/**@} */

修改gizwits_protocol.h

#ifndef _GIZWITS_PROTOCOL_H
#define _GIZWITS_PROTOCOL_H#ifdef __cplusplus
extern "C" {#endif#include <stdint.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "common.h"#define SEND_MAX_TIME       200                     ///< 200ms resend
#define SEND_MAX_NUM        2                       ///< resend times#define protocol_VERSION    "00000004"              ///< protocol version
#define P0_VERSION          "00000002"              ///< P0 protocol version/**@name Product Key
* @{
*/
#define PRODUCT_KEY "9c8a5a8e38344fb4af14b6db0f5b1df7"
/**@} */
/**@name Product Secret
* @{
*/
#define PRODUCT_SECRET "45c86d8c6a2a4b1dac7d68df54f6e4f0"/**@name Device status data reporting interval
* @{
*/
#define REPORT_TIME_MAX 6000 //6S
/**@} */    #define CELLNUMMAX 7    /**@name Whether the device is in the control class, 0 means no, 1 means yes
* @{
*/
#define DEV_IS_GATEWAY   0
/**@} *//**@name Binding time
* @{
*/
#define NINABLETIME  0
/**@} */#define MAX_PACKAGE_LEN    (sizeof(devStatus_t)+sizeof(attrFlags_t)+20)                 ///< Data buffer maximum length
#define RB_MAX_LEN          (MAX_PACKAGE_LEN*2)     ///< Maximum length of ring buffer/**@name Data point related definition
* @{
*/
#define Relay_1_BYTEOFFSET                    0
#define Relay_1_BITOFFSET                     0
#define Relay_1_LEN                           1#define Temp_RATIO                         1
#define Temp_ADDITION                      0
#define Temp_MIN                           0
#define Temp_MAX                           100
#define Humi_RATIO                         1
#define Humi_ADDITION                      0
#define Humi_MIN                           0
#define Humi_MAX                           100
#define Light_Intensity_RATIO                         1
#define Light_Intensity_ADDITION                      0
#define Light_Intensity_MIN                           0
#define Light_Intensity_MAX                           100
/**@} *//** Writable data points Boolean and enumerated variables occupy byte size */
#define COUNT_W_BIT 1/** Event enumeration */
typedef enum
{WIFI_SOFTAP = 0x00,                               ///< WiFi SOFTAP configuration eventWIFI_AIRLINK,                                     ///< WiFi module AIRLINK configuration eventWIFI_STATION,                                     ///< WiFi module STATION configuration eventWIFI_OPEN_BINDING,                                ///< The WiFi module opens the binding eventWIFI_CLOSE_BINDING,                               ///< The WiFi module closes the binding eventWIFI_CON_ROUTER,                                  ///< The WiFi module is connected to a routing eventWIFI_DISCON_ROUTER,                               ///< The WiFi module has been disconnected from the routing eventWIFI_CON_M2M,                                     ///< The WiFi module has a server M2M eventWIFI_DISCON_M2M,                                  ///< The WiFi module has been disconnected from the server M2M eventWIFI_OPEN_TESTMODE,                               ///< The WiFi module turns on the test mode eventWIFI_CLOSE_TESTMODE,                              ///< The WiFi module turns off the test mode eventWIFI_CON_APP,                                     ///< The WiFi module connects to the APP eventWIFI_DISCON_APP,                                  ///< The WiFi module disconnects the APP eventWIFI_RSSI,                                        ///< WiFi module RSSI eventWIFI_NTP,                                         ///< Network time eventMODULE_INFO,                                      ///< Module information eventTRANSPARENT_DATA,                                 ///< Transparency eventsEVENT_Relay_1,EVENT_TYPE_MAX                                    ///< Enumerate the number of members to calculate (user accidentally deleted)
} EVENT_TYPE_T;/** P0 Command code */
typedef enum
{ACTION_CONTROL_DEVICE       = 0x01,             ///< Protocol 4.10 WiFi Module Control Device WiFi Module SendACTION_READ_DEV_STATUS      = 0x02,             ///< Protocol 4.8 WiFi Module Reads the current status of the device WiFi module sentACTION_READ_DEV_STATUS_ACK  = 0x03,             ///< Protocol 4.8 WiFi Module Read Device Current Status Device MCU ReplyACTION_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 MCUACTION_W2D_TRANSPARENT_DATA = 0x05,             ///< WiFi to device MCU transparentACTION_D2W_TRANSPARENT_DATA = 0x06,             ///< Device MCU to WiFi
} actionType_t;   /** Protocol network time structure */
typedef struct
{uint16_t year;uint8_t month;uint8_t day;uint8_t hour;uint8_t minute;uint8_t second;uint32_t ntp;
}protocolTime_t;/** WiFi Module configuration parameters*/
typedef enum
{WIFI_RESET_MODE = 0x00,                           ///< WIFI module resetWIFI_SOFTAP_MODE,                                 ///< WIFI module softAP modeFWIFI_AIRLINK_MODE,                                ///< WIFI module AirLink modeWIFI_PRODUCTION_TEST,                             ///< MCU request WiFi module into production test modeWIFI_NINABLE_MODE,                                ///< MCU request module to enter binding modeWIFI_REBOOT_MODE,                                 ///< MCU request module reboot
}WIFI_MODE_TYPE_T;                                /** The protocol event type*/
typedef enum
{STATELESS_TYPE = 0x00,                            ///< Stateless typeACTION_CONTROL_TYPE,                              ///< Protocol 4.10 :WiFi module control device eventWIFI_STATUS_TYPE,                                 ///< Protocol 4.5 :WiFi module inform the device MCU of the change event of the WiFi module statusACTION_W2D_TRANSPARENT_TYPE,                      ///< Protocol WiFi to device MCU transparent eventGET_NTP_TYPE,                                     ///< Protocol 4.13 :The MCU requests access to the network time eventGET_MODULEINFO_TYPE,                              ///< Protocol 4.9 :The MCU get module information eventPROTOCOL_EVENT_TYPE_MAX                           ///< Count enumerated member (User donot delete)
} PROTOCOL_EVENT_TYPE_T;/** Protocol command code */
typedef enum
{                                                   CMD_GET_DEVICE_INTO             = 0x01,         ///< Protocol:3.1 ACK_GET_DEVICE_INFO             = 0x02,         ///< Protocol:3.1 CMD_ISSUED_P0                   = 0x03,         ///< Protocol:3.2 3.3 ACK_ISSUED_P0                   = 0x04,         ///< Protocol:3.2 3.3 CMD_REPORT_P0                   = 0x05,         ///< Protocol:3.4 ACK_REPORT_P0                   = 0x06,         ///< Protocol:3.4 CMD_HEARTBEAT                   = 0x07,         ///< Protocol:3.5 ACK_HEARTBEAT                   = 0x08,         ///< Protocol:3.5 CMD_WIFI_CONFIG                 = 0x09,         ///< Protocol:3.6 ACK_WIFI_CONFIG                 = 0x0A,         ///< Protocol:3.6 CMD_SET_DEFAULT                 = 0x0B,         ///< Protocol:3.7 ACK_SET_DEFAULT                 = 0x0C,         ///< Protocol:3.7 CMD_WIFISTATUS                  = 0x0D,         ///< Protocol:3.8 ACK_WIFISTATUS                  = 0x0E,         ///< Protocol:3.8 CMD_MCU_REBOOT                  = 0x0F,         ///< Protocol:4.1 ACK_MCU_REBOOT                  = 0x10,         ///< Protocol:4.1 CMD_ERROR_PACKAGE               = 0x11,         ///< Protocol:3.9 ACK_ERROR_PACKAGE               = 0x12,         ///< Protocol:3.9 CMD_PRODUCTION_TEST             = 0x13,         ///< Protocol:ACK_PRODUCTION_TEST             = 0x14,         ///< Protocol:CMD_NINABLE_MODE                = 0x15,         ///< Protocol:3.10ACK_NINABLE_MODE                = 0x16,         ///< Protocol:3.10CMD_GET_NTP                     = 0x17,         ///< Protocol:4.3 ACK_GET_NTP                     = 0x18,         ///< Protocol:4.3 CMD_ASK_BIGDATA                 = 0x19,         ///< Protocol:4.4ACK_ASK_BIGDATA                 = 0x1A,         ///< Protocol:4.4CMD_BIGDATA_READY               = 0x1B,         ///< Protocol:4.5ACK_BIGDATA_READY               = 0x1C,         ///< Protocol:4.5CMD_BIGDATA_SEND                = 0x1D,         ///< Protocol:4.6ACK_BIGDATA_SEND                = 0x1E,         ///< Protocol:4.6CMD_S_STOP_BIGDATA_SEND         = 0x1F,         ///< Protocol:4.7ACK_S_STOP_BIGDATA_SEND         = 0x20,         ///< Protocol:4.7CMD_D_STOP_BIGDATA_SEND         = 0x27,         ///< Protocol:4.8ACK_D_STOP_BIGDATA_SEND         = 0x28,         ///< Protocol:4.8CMD_ASK_MODULE_INFO             = 0x21,         ///< Protocol:4.9ACK_ASK_MODULE_INFO             = 0x22,         ///< Protocol:4.9CMD_ASK_AFFAIR_HANDLE           = 0x23,         ///< Protocol:4.10ACK_ASK_AFFAIR_HANDLE           = 0x24,         ///< Protocol:4.10CMD_AFFAIR_RESULT               = 0x25,         ///< Protocol:4.10ACK_AFFAIR_RESULT               = 0x26,         ///< Protocol:4.10CMD_REBOOT_MODULE               = 0x29,         ///< Protocol:3.11ACK_REBOOT_MODULE               = 0x2A,         ///< Protocol:3.11CMD_CONNECT_M2M                 = 0x2D,         ///< Protocol:for VirtualizationACK_CONNECT_M2M                 = 0x2E,         ///< Protocol:for VirtualizationCMD_CONNECT_M2M_BACK            = 0x2F,         ///< Protocol:for VirtualizationACK_CONNECT_M2M_BACK            = 0x30,         ///< Protocol:for VirtualizationCMD_UPLOAD_DATA                 = 0x31,         ///< Protocol:for VirtualizationACK_UPLOAD_DATA                 = 0x32,         ///< Protocol:for VirtualizationCMD_UPLOAD_DATA_BACK            = 0x33,         ///< Protocol:for VirtualizationACK_UPLOAD_DATA_BACK            = 0x34,         ///< Protocol:for VirtualizationCMD_DISCONNECT_M2M              = 0x35,         ///< Protocol:for VirtualizationACK_DISCONNECT_M2M              = 0x36,         ///< Protocol:for VirtualizationCMD_DISCONNECT_M2M_BACK         = 0x37,         ///< Protocol:for VirtualizationACK_DISCONNECT_M2M_BACK         = 0x38,         ///< Protocol:for VirtualizationCMD_RESET_SIMULATOR             = 0x39,         ///< Protocol:for VirtualizationACK_RESET_SIMULATOR             = 0x3A,         ///< Protocol:for VirtualizationCMD_RESET_SIMULATOR_BACK        = 0x3B,         ///< Protocol:for VirtualizationACK_RESET_SIMULATOR_BACK        = 0x3C,         ///< Protocol:for Virtualization
} PROTOCOL_CMDTYPE;                                                                                  /** Illegal message type*/
typedef enum
{ERROR_ACK_SUM = 0x01,                           ///< check errorERROR_CMD     = 0x02,                           ///< Command code errorERROR_OTHER   = 0x03,                           ///< other
} errorPacketsType_t;typedef enum
{EXE_SUCESS                      = 0x00,EXE_FAILE                       = 0x01,
} execute_result;  #pragma pack(1)/** User Area Device State Structure */
typedef struct {bool valueRelay_1;uint32_t valueTemp;uint32_t valueHumi;uint32_t valueLight_Intensity;
} dataPoint_t;/** Corresponding to the protocol "4.10 WiFi module control device" in the flag " attr_flags" */
typedef struct {uint8_t flagRelay_1:1;
} attrFlags_t;/** Corresponding protocol "4.10 WiFi module control device" in the data value "attr_vals" */typedef struct {uint8_t wBitBuf[COUNT_W_BIT];
} attrVals_t;/** The flag "attr_flags (1B)" + data value "P0 protocol area" in the corresponding protocol "4.10 WiFi module control device"attr_vals(6B)" */
typedef struct {attrFlags_t attrFlags;attrVals_t  attrVals;
}gizwitsIssued_t;/** Corresponding protocol "4.9 Device MCU to the WiFi module to actively report the current state" in the device status "dev_status(11B)" */ typedef struct {uint8_t wBitBuf[COUNT_W_BIT];uint8_t valueTemp;uint8_t valueHumi;uint8_t valueLight_Intensity;
} devStatus_t; /** Event queue structure */
typedef struct {                           uint8_t num;                                    ///< Number of queue memberuint8_t event[EVENT_TYPE_MAX];                  ///< Queue member event content
}eventInfo_t;/** wifiSignal strength structure */
typedef struct {                           uint8_t rssi;                                   ///< WIFI signal strength
}moduleStatusInfo_t;                                /** Protocol standard header structure */
typedef struct
{uint8_t                 head[2];                ///< The head is 0xFFFFuint16_t                len;                    ///< From cmd to the end of the entire packet occupied by the number of bytesuint8_t                 cmd;                    ///< commanduint8_t                 sn;                     ///< uint8_t                 flags[2];               ///< flag,default is 0
} protocolHead_t;/** 4.1 WiFi module requests the device information protocol structure */
typedef struct
{protocolHead_t          head;                   ///< Protocol standard header structureuint8_t                 protocolVer[8];         ///< Protocol versionuint8_t                 p0Ver[8];               ///< p0 Protocol versionuint8_t                 hardVer[8];             ///< Hardware versionuint8_t                 softVer[8];             ///< Software versionuint8_t                 productKey[32];         ///< Product keyuint16_t                ninableTime;            ///< Binding time(second)uint8_t                 devAttr[8];             ///< Device attributeuint8_t                 productSecret[32];      ///< Product secretuint8_t                 sum;                    ///< checksum
} protocolDeviceInfo_t;/** Protocol common data frame(4.2、4.4、4.6、4.9、4.10) protocol structure */
typedef struct
{protocolHead_t          head;                   ///< Protocol standard header structureuint8_t                 sum;                    ///< checksum
} protocolCommon_t;/** 4.3 The device MCU informs the WiFi module of the configuration mode  protocol structure */
typedef struct
{protocolHead_t          head;                   ///< Protocol standard header structureuint8_t                 cfgMode;                ///< Configuration parametersuint8_t                 sum;                    ///< checksum
} protocolCfgMode_t;/** 4.13 The MCU requests the network time  protocol structure */
typedef struct
{protocolHead_t          head;                   ///< Protocol standard header structureuint8_t                 time[7];                ///< Hardware versionuint8_t                 ntp_time[4];            ///< Software versionuint8_t                 sum;                    ///< checksum
} protocolUTT_t;/** WiFi module working status*/
typedef union
{uint16_t                value;struct{uint16_t            softap:1;     uint16_t            station:1;    uint16_t            onboarding:1; uint16_t            binding:1;    uint16_t            con_route:1;  uint16_t            con_m2m:1;    uint16_t            reserve1:2;   uint16_t            rssi:3;       uint16_t            app:1;        uint16_t            test:1;       uint16_t            reserve2:3;   }types; } wifiStatus_t;/** WiFi status type :protocol structure */
typedef struct
{protocolHead_t          head;                   ///< Protocol standard header structurewifiStatus_t            ststus;                 ///< WIFI statusuint8_t                 sum;                    ///< checksum
} protocolWifiStatus_t;/** Protocol common data frame(4.9) :protocol structure */
typedef struct
{protocolHead_t          head;                   ///< Protocol standard header structureuint8_t                 type;                   ///< Information Typeuint8_t                 sum;                    ///< checksum
} protocolGetModuleInfo_t;typedef struct
{uint8_t                 moduleType;             ///< Information Typeuint8_t                 serialVer[8];           ///< Serial port protocol versionuint8_t                 hardVer[8];             ///< Hardware versionuint8_t                 softVer[8];             ///< Software versionuint8_t                 mac[16];                ///< mac uint8_t                 ip[16];                 ///< ipuint8_t                 devAttr[8];             ///< Device attribute
} moduleInfo_t;/** Protocol common data frame(4.9) :protocol structure */
typedef struct
{protocolHead_t          head;                   ///< Protocol standard header structuremoduleInfo_t            wifiModuleInfo;         ///< WIFI module informationuint8_t                 sum;                    ///< checksum
} protocolModuleInfo_t;/** GPRS information of base station */
typedef struct
{uint16_t                    LAC_ID;             ///<LAC area IDuint16_t                    CellID;             ///<Base station IDuint8_t                     RSSI;               ///<Signal strength of base station
} gprsCellInfo_t;/** 3.19 The basic information of the GPRS communication module  */
typedef struct
{uint8_t                 Type;//2G/3g/4guint8_t                 Pro_ver[8];//Universal serial port protocol versionuint8_t                 Hard_ver[8];//Hardware versionuint8_t                 Soft_ver[8];//Software versionuint8_t                 Device_attribute[8];//Device attributeuint8_t                 IMEI[16];//stringuint8_t                 IMSI[16];//stringuint8_t                 MCC[8];//Mobile country codeuint8_t                 MNC[8];//Mobile network codeuint8_t                 CellNum;//Number of base stationuint8_t                 CellInfoLen;//Information length of base station gprsCellInfo_t          GPRS_CellINFO[CELLNUMMAX];
}gprsInfo_t;/** 4.7 Illegal message notification :protocol structure*/
typedef struct
{protocolHead_t          head;                   ///< Protocol standard header structureuint8_t                 error;                  ///< error valueuint8_t                 sum;                    ///< checksum
} protocolErrorType_t;/** P0 message header */
typedef struct
{protocolHead_t          head;                   ///< Protocol standard header structureuint8_t                 action;                 ///< p0 command
} protocolP0Head_t;/** protocol “4.9 The device MCU reports the current status to the WiFi module” device status "dev_status(11B)"  */
typedef struct {devStatus_t devStatus;                          ///< Stores the device status data
}gizwitsReport_t;/** resend strategy structure */
typedef struct {uint8_t                 num;                    ///< resend timesuint8_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 ACKuint8_t                 buf[MAX_PACKAGE_LEN];   ///< resend data bufferuint16_t                dataLen;                ///< resend data lengthuint32_t                sendTime;               ///< resend time
} protocolWaitAck_t;/** 4.8 WiFi read device datapoint value , device ack use this struct */
typedef struct
{protocolHead_t          head;                   ///< Protocol headuint8_t                 action;                 ///< p0 actiongizwitsReport_t         reportData;             ///< p0 datauint8_t                 sum;                    ///< Checksum
} protocolReport_t;/** Protocol main and very important struct */
typedef struct
{uint8_t issuedFlag;                             ///< P0 action typeuint8_t protocolBuf[MAX_PACKAGE_LEN];           ///< Protocol data handle bufferuint8_t transparentBuff[MAX_PACKAGE_LEN];       ///< Transparent data storage areauint32_t transparentLen;                        ///< Transmission data lengthuint32_t sn;                                    ///< Message SNuint32_t timerMsCount;                          ///< Timer Count protocolWaitAck_t waitAck;                      ///< Protocol wait ACK data structureeventInfo_t issuedProcessEvent;                 ///< Control eventseventInfo_t wifiStatusEvent;                    ///< WIFI Status eventseventInfo_t NTPEvent;                           ///< NTP eventseventInfo_t moduleInfoEvent;                    ///< Module Info eventsgizwitsReport_t reportData;                     ///< The protocol reports data for standard productdataPoint_t gizCurrentDataPoint;                ///< Current device datapoints statusdataPoint_t gizLastDataPoint;                   ///< Last device datapoints statusmoduleStatusInfo_t wifiStatusData;              ///< WIFI signal intensityprotocolTime_t TimeNTP;                         ///< Network time information
#if MODULE_TYPEgprsInfo_t   gprsInfoNews;
#else  moduleInfo_t  wifiModuleNews;                   ///< WIFI module Info
#endif}gizwitsProtocol_t; #pragma pack()/**@name Gizwits user API interface
* @{
*/extern uint32_t gizGetTimerCount(void);void gizwitsInit(void);
int32_t gizwitsSetMode(uint8_t mode);
void gizwitsGetNTP(void);
int32_t gizwitsHandle(dataPoint_t *currentData);
int32_t gizwitsPassthroughData(uint8_t * gizdata, uint32_t len);
void gizwitsGetModuleInfo(void);
int32_t gizPutData(uint8_t *buf, uint32_t len);/*添加用户自定义的函数声明*/
void gziwits_Task(dataPoint_t * currentDataPoint);/**@} */
#ifdef __cplusplus
}
#endif #endif

Utils直接移植无需修改

添加TIM3定时器代码驱动

#include "tim3.h"
#include "gizwits_product.h"void TIM3_Config(uint16_t psc,uint16_t arr)
{RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE); TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;TIM_TimeBaseStructure.TIM_Period                     = arr; TIM_TimeBaseStructure.TIM_Prescaler                  = psc;TIM_TimeBaseStructure.TIM_ClockDivision              = TIM_CKD_DIV1; TIM_TimeBaseStructure.TIM_CounterMode                = TIM_CounterMode_Up;TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);TIM_ITConfig(TIM3,TIM_IT_Update,ENABLE ); NVIC_InitTypeDef NVIC_InitStructure;NVIC_InitStructure.NVIC_IRQChannel                   = TIM3_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;  NVIC_InitStructure.NVIC_IRQChannelSubPriority        = 3;  NVIC_InitStructure.NVIC_IRQChannelCmd                = ENABLE; NVIC_Init(&NVIC_InitStructure);                             TIM_Cmd(TIM3, ENABLE);
}
/*用户实现的定时器接口*/
void TIM3_IRQHandler(void)
{if(TIM_GetITStatus(TIM3, TIM_IT_Update) != RESET)  {TIM_ClearITPendingBit(TIM3, TIM_IT_Update  );  gizTimerMs();}
}
/******************************************/
//void TIMER_IRQ_FUN(void)
//{//  gizTimerMs();
//}
/******************************************/## 添加UART3串口通信代码驱动```c
#include "usart3.h"
#include "gizwits_product.h"void USART3_Init(uint32_t BaudRate)
{  RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);                           //GPIOB时钟RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART3,ENABLE);                          //串口3时钟使能USART_DeInit(USART3);  //复位串口3GPIO_InitTypeDef GPIO_InitStructure;GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;                                     //PB10GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;                              //USART3_TX   PB10GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;                                 //复用推挽输出GPIO_Init(GPIOB, &GPIO_InitStructure);                                         //初始化PB10GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11;                                          //USART3_RX   PB11GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;                          //浮空输入GPIO_Init(GPIOB, &GPIO_InitStructure);  USART_InitTypeDef                  USART_InitStructure;USART_InitStructure.USART_BaudRate            = BaudRate;                                    //波特率一般设置为9600;USART_InitStructure.USART_WordLength          = USART_WordLength_8b;                    //字长为8位数据格式USART_InitStructure.USART_StopBits            = USART_StopBits_1;                         //一个停止位USART_InitStructure.USART_Parity              = USART_Parity_No;                            //无奇偶校验位USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;//无硬件数据流控制USART_InitStructure.USART_Mode                = USART_Mode_Rx | USART_Mode_Tx;                   //收发模式USART_Init(USART3, &USART_InitStructure);       //初始化串口3USART_Cmd(USART3, ENABLE);                      //使能串口 USART_ITConfig(USART3, USART_IT_RXNE, ENABLE);       //开启中断 NVIC_InitTypeDef NVIC_InitStructure;NVIC_InitStructure.NVIC_IRQChannel                   = USART3_IRQn;NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2; NVIC_InitStructure.NVIC_IRQChannelSubPriority        = 3; NVIC_InitStructure.NVIC_IRQChannelCmd                = ENABLE;           NVIC_Init(&NVIC_InitStructure); }
/*用户实现的中断服务函数接口*/
void USART3_IRQHandler(void)
{uint8_t Recv_Data;       if(USART_GetITStatus(USART3, USART_IT_RXNE) != RESET)//接收到数据{     Recv_Data = USART_ReceiveData(USART3);         gizPutData(&Recv_Data, 1);}
}
/**********************************************/
//void UART_IRQ_FUN(void)
//{//  uint8_t value = 0;
//  gizPutData(&value, 1);
//}
/**********************************************/

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

机智云初始化函数封装

配网成功

设备上线

好像正常的结果

意料之中也是意料之外的bug

总结以及细节

明天再写,睡觉

初出茅庐的小李第114篇博客项目笔记之机智云智能浇花器实战(3)-基础Demo实现相关推荐

  1. 初出茅庐的小李第113篇博客项目笔记之机智云智能浇花器实战(2)-基础Demo实现

    初出茅庐的小李第112篇博客项目笔记之机智云智能浇花器实战(1)-基础Demo实现 接(1) 继电器实现 继电器原理图 继电器采用的是5V继电器,控制端是RELAY-1 继电器代码实现 #includ ...

  2. 初出茅庐的小李第112篇博客项目笔记之机智云智能浇花器实战(1)-基础Demo实现

    项目文件夹框架 API文件夹---------------------------------------放置各种传感器驱动代码文件夹 CMSIS文件夹------------------------ ...

  3. 初出茅庐的小李第3篇博客《5G物联网及NB-IoT技术详解》读书笔记1

    初出茅庐的小李第3篇博客 <5G物联网及NB-IoT技术详解>读书笔记1 在Mculover666那里白嫖了一本书,不要问我咋白嫖的,我也不知道- 为什么要写这样的笔记? 因为我白嫖的时候 ...

  4. 初出茅庐的小李第39篇博客之转载一篇有关unistd.h的介绍文章

    转载一篇文章 mask一下好找 unistd.h在unix中类似于window中的windows.h! #ifdef WIN32 #include <windows.h> #else #i ...

  5. 初出茅庐的小李第19篇博客之广和通G510模块接入机智云平台

    2020年5月1日劳动节 为什么要说一下这个日期,因为我上一次玩(学)G510模组是去年2019年5月1日,由于种种原因吧,一直也没有机会再次操作,而且不幸的一件事情就是,我还把上次搞的代码搞丢了,也 ...

  6. 初出茅庐的小李第73篇博客之offsetof(type, member-designator)使用

    offsetof(type, member-designator) 这是一个宏定义包含在<stddef.h>里,它的作用是用来计算一个结构成员相对于结构开头的字节偏移量. 说到这里我先来补 ...

  7. 初出茅庐的小李第86篇博客之Modbus协议总结

    Modbus协议来源 Modbus协议的由来 Mod,取自英文单词" Modicon",Modicon 中文翻译为莫迪康,是美国一家自动化公司的名字,现在这家公司被法国的施耐德电气 ...

  8. 初出茅庐的小李第59篇博客之测试Modbus协议的继电器

    1, Modbus RTU指令详解 发送: FF 05 00 00 FF 00 99 E4 字段 含义 注释 FF 设备地址 范围1-255,默认255 05 功能码 写单个线圈 00 00 继电器地 ...

  9. 初出茅庐的小李第36篇博客之读取旋转编码器正反转状态(arduino uno 测试)

    旋转编码器的引脚 CLK(A相) DATA(B相) SWITCH VCC GND 工作原理 旋转编码器的工作原理以及如何在Arduino中使用 https://www.yiboard.com/thre ...

最新文章

  1. com/opensymphony/xwork2/spring/SpringObjectFactory.java:220:-1问题出现的原因及解决办法
  2. enq: tt - contention_要签TT或伊巴卡?湖人要走一步大棋,大肆招揽老将,为老詹真拼...
  3. fiddler及postman讲解
  4. 计算未来轻沙龙 | 对抗攻击、强化学习,你关心的都在这里!
  5. 什么比日期和时区更难? SQL / JDBC中的日期和时区!
  6. Google GSON入门
  7. 优酷视频如何分享个人主页
  8. centos6.5 升级python2.6到python2.7
  9. C语言程序设计 基础入门(认识、描述与计算)
  10. 前端页面截图,指定区域截图
  11. ps动作储存覆盖原文件的原因
  12. 无奇不有,20款国外便携式智能手机充电器
  13. 008_生成设备节点
  14. 用计算机打一闪一闪亮晶晶,一闪一闪亮晶晶 我去!RGB轴机械键盘灯光玩法亮瞎人...
  15. 骨传导耳机是什么,骨传导耳机对耳朵有什么好处吗
  16. sense8影评摘抄
  17. 预测《权游》角色生死,AI算法魔力何在?
  18. mysql navicate查询_Mysql Navicate 基础操作与SQL语句 版本5.7.29
  19. EVE 设备开机时的更改连线
  20. vue3.0为什么要用Proxy替代defineProperty

热门文章

  1. apt-get update出现无法连接上 archive.ubuntukylin.com:10006
  2. 俞军跟我聊了三个小时产品(1):用户不是人,是需求的集合
  3. python第三方库文件传输_慢步学习,python库文件概述,再来点第三方库文件安装的干货...
  4. 学上位机迎来最好的时代
  5. 迭代重建算法中投影矩阵的计算
  6. php 购买车票,jQuery实现买火车票城市选择切换功能
  7. java单根结构_Java语言程序设计中的单根结构
  8. Mac电脑使用:下载安装SourceTree的步骤以及使用方法
  9. c++ 原子操作 赋值_请问c++如何实现原子性操作?
  10. 跨国企业在中国 | 麦德龙中国正式引进高品质法国牛肉;雀巢加码在华宠物护理业务...