Fun Things HTTP service ① OneNET the platform - Analog Upload temperature (TcpClient)

1. Theoretical basis

    Bo Bowen on the main line of reference:

  • About Fun Things platform of OneNET
  • ESP8266 network development trip to articles ⑨ HttpClient - use ESP8266HTTPClient library

2.OneNet HTTP

    Http protocol as a common network protocol, which is a short connection protocol (HTTP protocol here does not explain, the reader access to their own data), also supports on OneNet platform.

Features side apparatus applies :

  • Only reporting sensor data to the internet
  • Device to control the downlink quality without

Side platform provides functionality :

  • Data points reported by the storage device;
  • Provide API interface for device management;
  • Providing data to the application to push;

Typical application scenarios

  • Simple data reporting scenarios, such as temperature and humidity control system, a sensor detects projects;

3. Upload temperature simulation

3.1 Experimental Materials

  • ESP8266 NodeMcu
  • OneNet platform

3.2 Experimental Procedure

3.2.1 Create a system of temperature and humidity -HTTP product (HTTP protocol)

image

Notes :

  • Be sure to select the HTTP protocol

    Once created, we click to view specific product information:

image

Notes :

  • You need to record product ID, which is a unique identifier used to distinguish products
  • Master-APIkey, network requests authentication information into the interface calls needed

3.2.2 API debugging create deviceA

API interface definition :

Procedure :

  • DeviceA created through the API debug tool

image

http body

{
    "title": "http_device_A",
    "desc": "http_device_A",
    "tags": ["china", "mobile"],
    "location": {
        "lon": 109,
        "lat": 23.54
    },
    "auth_info": "http_device_A",
    "other": {
        "version": "1.0.0",
        "manufacturer": "china mobile"
    }
}
  • View the list of devices

image

3.2.3 API debugging analog upload Temperature - deviceA

API interface definition :

Procedure :

  • Send a request through the API debug tool

image

  • View the operation result
    image

image

3.2.4 NodeMcu programming code - deviceA

    In order to clearly distinguish the code function, Boge named project called P_OneNet_Exam02:

  • P_OneNet_Exam02.ino file:
/**
 *  功能:ESP8266 HTTP 远程上传温度值 V1.0
 *  作者:单片机菜鸟
 *  时间:2019-06-27
 *  描述:
 *      1.OneNet平台端:创建Http协议的产品,创建DeviceA设备点
 *      2.每个20s上传一个随机值给到OneNet平台
*/

#include <ESP8266WiFi.h>
#include <ArduinoJson.h>
#include <stdlib.h>
#include <Ticker.h>
#include "H_project.h"

void initSystem();
void wifiTick();
void postTempToOneNet();

/**
 * 初始化
 */
void setup() {
  initSystem();
}

void loop() {
  ESP.wdtFeed();
  wifiTick();
  doTCPClientTick();
  postTempToOneNet();
}

/**
 * 初始化系统
 */
void initSystem(){
    int cnt = 0;
    Serial.begin (115200);
    Serial.println("\r\n\r\nStart ESP8266 HTTP");
    Serial.print("Firmware Version:");
    Serial.println(VER);
    Serial.print("SDK Version:");
    Serial.println(ESP.getSdkVersion());
    wifi_station_set_auto_connect(0);//关闭自动连接
    ESP.wdtEnable(5000);
    WiFi.disconnect();
    delay(100);
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
          delay(500);
          cnt++;
          Serial.print(".");
          if(cnt>=40){
            cnt = 0;
            //重启系统
            delayRestart(1);
          }
    }
    pinMode(LED_BUILTIN, OUTPUT);
}

/*
*  WiFiTick
*  检查是否需要初始化WiFi
*  检查WiFi是否连接上,若连接成功启动TCP Client
*  控制指示灯
*/
void wifiTick(){
  static bool taskStarted = false;
  static bool ledTurnon = false;
   if ( WiFi.status() != WL_CONNECTED ) {
       if (millis() - lastWiFiCheckTick > 1000) {
         lastWiFiCheckTick = millis();
         ledState = !ledState; digitalWrite(LED_BUILTIN, ledState);
         ledTurnon = false;
       }
    }else{
       if (ledTurnon == false) {
             ledTurnon = true;
             digitalWrite(LED_BUILTIN, 0);
        }

        if (taskStarted == false) {
             taskStarted = true;
             startTCPClient();
        }
    }
}

/**
 * 检查client连接
 */
void doTCPClientTick(){
   //检查是否断开,断开后重连
   if(WiFi.status() != WL_CONNECTED) return;
   if (!client.connected()) {//断开重连
      if(preTCPConnected == true){
            preTCPConnected = false;
            preTCPStartTick = millis();
            Serial.println();
            Serial.println("TCP Client disconnected.");
            client.stop();
       }else if(millis() - preTCPStartTick > 10*1000){
            startTCPClient();
       }
   }
}

/**
 * 启动Tcp client
 */
void startTCPClient(){
   Serial.println("\r\nstartTCPClient");
  if(client.connect(host, 80)){
      preTCPConnected = true;
      client.setNoDelay(true);
  }else{
      Serial.print("Failed connected to server:");
      Serial.println(host);
      client.stop();
      preTCPConnected = false;
  }
  preTCPStartTick = millis();
}

/**
 * 提交数据到OneNet
 */
void postTempToOneNet(){
   if(WiFi.status() != WL_CONNECTED || !client.connected()) return;
   if(millis() - lastOneNetPostTick > 15*1000){
       lastOneNetPostTick = millis();
       Serial.println("TCP Client postTempToOneNet.");

       StaticJsonBuffer<230> jsonBuffer;
       //创建根,也就是顶节点
       JsonObject& root = jsonBuffer.createObject();
       //在root对象中加入data数组
       JsonArray& datastreams = root.createNestedArray("datastreams");
       JsonObject& stream = datastreams.createNestedObject(); 
       stream["id"] = "temperature";
       JsonArray& datapoints = stream.createNestedArray("datapoints");
       JsonObject& value1 = datapoints.createNestedObject();
       value1["value"] =  random(20, 50);
       JsonObject& value2 = datapoints.createNestedObject();
       value2["value"] =  random(20, 50);
       
       int len = root.measureLength();
       char buffer[100];
       root.printTo(buffer, 100);
       String data;
       for(int index = 0;index<len;index++){
           data += buffer[index];
       }
       postToDeviceDataPoint(data);
   }
}
  • H_project.h Code:
#ifndef _MAIN_H__
#define _MAIN_H__


extern "C" {
#include "user_interface.h"
#include "smartconfig.h"
}

/************** ESP8266相关操作 **************************/
void delayRestart(float t);
void delayNs(uint8_t m);
/*********************************************************/

/******************** Http 相关操作 **********************/
const unsigned long HTTP_TIMEOUT = 5000;// max respone time from server
const size_t MAX_CONTENT_SIZE = 500;// max size of the HTTP response

WiFiClient client;
char response[MAX_CONTENT_SIZE];
char endOfHeaders[] = "\r\n\r\n";

bool sendGetRequest(const char* host,String url,String header,char* response);
bool sendPostRequest(const char* host,String url,String header,String postData,char* response);
bool skipResponseHeaders();
void readReponseContent(char* content, size_t maxSize);
void clearResponseBuffer(char* response);
/*********************************************************/

/*************** OneNet HTTP相关操作 *********************/
const char* host = "api.heclouds.com";
bool postToDeviceDataPoint(String data);
/*********************************************************/

/*********************** 项目相关操作 ********************/
#define VER             "HTTP_TEMP_V1.0"
const char* ssid = "TP-LINK_5344";//wifi账号
const char* password = "xxxxxx";//wifi秘密
const unsigned long BAUD_RATE = 115200;// serial connection speed
unsigned long lastWiFiCheckTick = 0;
bool ledState = 0;
unsigned long lastOneNetPostTick=0;
unsigned long preTCPStartTick=0;
bool preTCPConnected=false;
/*********************************************************/

#endif

    All project code, Boge on personal QQ group.

Notes :

  • Here used JSON, please refer to the online Boge Bowen Fun ArduinoJson library V5 version ;
  • We used here to ESP8266 WiFiClient to encapsulate Http requests (also can be used directly HttpClient library), in order to deepen understanding, the reader is referred Boge on-line blog ESP8266 network development trip to articles ⑦ TCP Server & TCP Client on client section;

    The project burned into NodeMcu, then you can see the serial print content, as follows:

image

    Meanwhile, the data stream can also be seen in the case of OneNet platform, as follows:

image

4. Summary

On the basis of the understanding of the HTTP protocol herein, this is very easy to operate. But readers need to focus on several points:

  • OneNet create your own product, do not use Boge created (please modify your product information Boge source basis);
  • May try to join optimize code, such as temperature change, whether to consider not upload, upload or increase the interval, and join or sleep mode

Next, Boge will explain HTTP service ② OneNET Fun Things platform - The simulation upload temperature (HttpClient).

Guess you like

Origin www.cnblogs.com/danpianjicainiao/p/11100742.html