ESP8266上报数据到中国移动物联网平台HTTP

Posted dozeoo

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ESP8266上报数据到中国移动物联网平台HTTP相关的知识,希望对你有一定的参考价值。

#include <HttpPacket.h>
#include <ArduinoJson.h>
#include <ESP8266WiFi.h>
HttpPacketHead packet;
#define myPeriodic 5
int L = 0; //LED指示灯引脚
int sent = 0;
char OneNetServer[] = "api.heclouds.com";       //不需要修改
const char ssid[] = "plus";     //修改为自己的路由器用户名
const char password[] = "45623467981"; //修改为自己的路由器密码
char device_id[] = "4983230";    //修改为自己的设备ID
char API_KEY[] = "ZnbTv5Qpbrv";    //修改为自己的API_KEY
char sensor_id1[] = "PM1.0";
char sensor_id2[] = "PM2.5";

void connectWifi()
{  Serial.print("Connecting to " + *ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print(".");  }
  Serial.println("");
  Serial.println("Connected");
  Serial.println("");
  digitalWrite(0, HIGH);
  delay(1000);
  digitalWrite(0, LOW);
  delay(1000);
  digitalWrite(0, HIGH);
}
void postDataToOneNet(char* API_VALUE_temp, char* device_id_temp, char* sensor_id_temp, float thisData)
{  
  WiFiClient client;
  StaticJsonBuffer<250> jsonBuffer;
  JsonObject& myJson = jsonBuffer.createObject();
  JsonArray& datastreams= myJson.createNestedArray("datastreams");
  JsonObject& id_datapoints = datastreams.createNestedObject();
  id_datapoints["id"] = sensor_id_temp;
    JsonArray& datapoints = id_datapoints.createNestedArray("datapoints");
  JsonObject& value = datapoints.createNestedObject();
    value["value"] =thisData;
  char p[180];
  myJson.printTo(p, sizeof(p));
  packet.setHostAddress(OneNetServer);
  packet.setDevId(device_id_temp);   //device_id
  packet.setAccessKey(API_VALUE_temp);  //API_KEY
  /*create the http message about add datapoint */
  packet.createCmdPacket(POST, TYPE_DATAPOINT, p);
  if (strlen(packet.content))
    Serial.print(packet.content);
  Serial.println(p);
  char cmd[400];
  memset(cmd, 0, 400);  
  strcpy(cmd, packet.content);
  strcat(cmd, p);
  if (client.connect(OneNetServer, 80)) {
    Serial.println("WiFi Client connected ");
    client.print(cmd);
    delay(1000);
  }//end if
  //  Serial.println(cmd);
  client.stop();
}
void setup() {
  Serial.begin(115200);
  pinMode(0, OUTPUT);
  connectWifi();
  Serial.println("setup end!");
}
void loop() {
  int temp = random(10, 38); int hum = random(50, 70);
  //发送数据到Onenet
  postDataToOneNet(API_KEY, device_id, sensor_id1, temp);
  delay(100);
  postDataToOneNet(API_KEY, device_id, sensor_id2, hum);
  Serial.println("N0 " + String(sent) + " Stream: was send");
  sent++;
  int count = myPeriodic;
  while (count--)
    delay(1000);
}

以上是关于ESP8266上报数据到中国移动物联网平台HTTP的主要内容,如果未能解决你的问题,请参考以下文章

ESP8266实战贴:使用HTTP POST请求上传数据到公有云OneNet

STM32+ESP8266+MQTT协议连接腾讯物联网开发平台

STM32+ESP8266+MQTT协议连接腾讯物联网开发平台

ESP32 + MQTT 连接到中移动物联网云平台 OneNET

ESP32 + MQTT 连接到中移动物联网云平台 OneNET

智慧农业: STM32F103ZE+ESP8266+腾讯云物联网平台+微信小程序设计