首页 > 代码库 > ESP8266上报数据到中国移动物联网平台HTTP

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 =http://www.mamicode.com/ 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