1.连接wifi 2.连接TCP服务器 3.发送POST数据
前两条之前已经操作过了(第14篇),添加一个透传模式设置以及发送代码即可
编写代码添加透传模式
直接在之前的初始化命令数组里边添加即可
//前边是发送的指令,后边是要确定的回令 char *const esp_inti_cmd[][2] = { {"AT\r\n", "OK"}, {"ATE0\r\n", "OK"}, {"AT+CWMODE=3\r\n", "OK"}, {"AT+CWJAP=\"******\",\"********\"\r\n", "GOT IP"}, {"AT+CIFSR\r\n", "OK"}, {"AT+CIPSTART=\"TCP\",\"183.230.40.33\",80\r\n", "CONNECT"}, {"AT+CIPMODE=1\r\n", "OK"}, {"AT+CIPSEND\r\n", ">"}, {0, 0} };
重要的是如何封装数据
POST /devices/device_id/datapoints?type=3 HTTP/1.1 api-key:*********************** Host:api.heclouds.com Content-Length:10 {"tem":42}
类似于这样,来进行字符串操作,主要用到了sprintf和strcat strcat就是将两个字符串拼接起来
添加两个宏定义
#define DEVID #define APIKEY
就是device_id和api-key
我的代码也是参考onenet的官方例程写的 展示一下
void OneNet_FillBuf(char *buf) { char text[24]; char buf1[128]; memset(text, 0, sizeof(text)); memset(buf1, 0, sizeof(buf1)); strcpy(buf1, "{"); memset(text, 0, sizeof(text)); sprintf(text,"\"tem\":%.1f,",pv.tem); strcat(buf1, text); memset(text, 0, sizeof(text)); sprintf(text,"\"hum\":%d,",pv.hum); strcat(buf1, text); memset(text, 0, sizeof(text)); sprintf(text,"\"lux\":%d",pv.lux_16); strcat(buf1, text); strcat(buf1, "}"); sprintf(buf, "POST /devices/%s/datapoints?type=3 HTTP/1.1\r\napi-key:%s\r\nHost:api.heclouds.com\r\n" "Content-Length:%d\r\n\r\n", DEVID, APIKEY, strlen(buf1)); strcat(buf, buf1); }
先测试一下这个函数的封装效果对不对
可以,是这个效果
然后直接发送就行了
void OneNet_SendData(void) { char buf[256]; memset(buf, 0, sizeof(buf)); OneNet_FillBuf(buf); //封装数据流 ESP_SendString((unsigned char *)buf, strlen(buf)); //上传数据 }
主函数里添加
while (1) { static uint8_t num; num++; BH1750_Send_Cmd(ONCE_H_MODE);//单次模式 sprintf(buf,"tem:%.1f ",pv.tem); OLED_P8x16Str(0u,2u,(uint8_t *)buf); sprintf(buf,"hum:%d%% ",pv.hum); OLED_P8x16Str(0u,4u,(uint8_t *)buf); sprintf(buf,"lux:%d ",pv.lux_16); OLED_P8x16Str(0u,6u,(uint8_t *)buf); HAL_Delay(500); AHT10ReadData(&pv.tem,&pv.hum); BH1750_Read_Dat(pv.lux);//读取数据 pv.lux_16 = BH1750_Dat_To_Lux(pv.lux);//转换数据 printf("lux:%d\r\n",pv.lux_16); printf("tem:%.1f\r\nhum:%d%%\r\n",pv.tem,pv.hum); if(num>10) { num = 0; OneNet_SendData(); } if(usart1_rx.flag)//接收到数据 { printf("%s",usart1_rx.rx_buff); Clear_Usart(&usart1_rx);//清空缓存 } /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ }
5s发送一次
出来咯