写法应该跟CONNECE差不多,大概就是下边这样
void OneNet_Publish(const char *topic, const char *msg) { MQTT_PACKET_STRUCTURE mqttPacket = {NULL, 0, 0, 0}; UsartPrintf("Publish Topic: %s, Msg: %s\r\n", topic, msg); if(MQTT_PacketPublish(MQTT_PUBLISH_ID, topic, msg, strlen(msg), MQTT_QOS_LEVEL0, 0, 1, &mqttPacket) == 0) { ESP8266_SendData(mqttPacket._data, mqttPacket._len); MQTT_DeleteBuffer(&mqttPacket); } }
其中 topic就是发送的主题,msg就是所要上传的信息
主题可以直接定义好,类似下边
const char devPubTopic[] = "$sys/407529/G0701/dp/post/json";
msg跟之前的POST一样,是json数据,这里依然使用字符串拼接的方法。
void OneNet_FillBuf(char *buf) { char buf1[64]; memset(buf1, 0, sizeof(buf1)); sprintf(buf1, "{\"id\":123,\"dp\":{\"tem\":[{\"v\":%.1f,}],",pv.tem); strcat(buf, buf1); memset(buf1, 0, sizeof(buf1)); sprintf(buf1, "\"hum\":[{\"v\":%d,}],",pv.hum); strcat(buf, buf1); memset(buf1, 0, sizeof(buf1)); sprintf(buf1, "\"lux\":[{\"v\":%d,}]}}",pv.lux_16); strcat(buf, buf1); }
下边就是把程序整合起来
while (1) { if(time6_count1>10) { time6_count1 = 0; 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); BH1750_Send_Cmd(ONCE_H_MODE);//单次模式 sprintf(buf,"tem:%.1f",pv.tem); OLED_P8x16Str(0u,4u,(uint8_t *)buf); sprintf(buf,"hum:%d%%",pv.hum); OLED_P8x16Str(64u,4u,(uint8_t *)buf); sprintf(buf,"lux:%d ",pv.lux_16); OLED_P8x16Str(0u,6u,(uint8_t *)buf); } if(time6_count>120) { time6_count = 0; memset(PUB_BUF, 0, sizeof(PUB_BUF)); OneNet_FillBuf(PUB_BUF); printf("PUB_BUF:%s\r\n",PUB_BUF); OneNet_Publish(devPubTopic, PUB_BUF); } }
5s中采集一次并刷新一次OLED屏幕,然后一分钟上传一次