基于ESP8266對接機智云介紹
單片機源程序如下:
- /*
- HTTP協(xié)議實現(xiàn)post和get發(fā)往onenet平臺。
- post為溫濕度上傳。
- get為開關(guān)消息獲取并執(zhí)行。
- 阿正修改,資源源于網(wǎng)絡(luò)。
- */
- #include <ESP8266WiFi.h>
- #include <ESP8266HTTPClient.h>
- #include <ArduinoJson.h>
- #include <DHT.h>
- #define LED 14 //配網(wǎng)指示燈D5/GPIO14
- #define DEBUG 0
- #define ledPin 14 // 定義ledPin連接到D5/GPIO14
- #define DHTPIN 12 // 溫濕度模塊 D6 GPIO12
- #define DHTTYPE DHT11
- int ds;
- const char* host = "api.heclouds.com";
- const char* APIKEY = "dDu2j8l23dNMJSWv5XVqfc6hXoM="; // API KEY 改成你自己的
- int32_t deviceId = 28315875; // Device ID 改成你自己的
- const char* DataStreams = "led"; //四個數(shù)據(jù)流 改成你自己的
- const char* DS_Temp = "wendu";
- const char* DS_Baojing = "w_baojing";
- const char* DS_Hum = "shidu";
- const size_t MAX_CONTENT_SIZE = 1024;
- const unsigned long HTTP_TIMEOUT = 2100; // max respone time from server
- WiFiClient client;
- const int tcpPort = 80; //80端口
- DHT dht(DHTPIN, DHTTYPE);
- struct UserData {
- int errno_val; // 錯誤返回值
- char error[32]; // 錯誤返回信息
- int test_led_Val; // TEST LED 狀態(tài)值
- char udate_at[32]; // 最后更新時間及日期
- };
- // Skip HTTP headers so that we are at the beginning of the response's body
- // -- 跳過 HTTP 頭,使我們在響應(yīng)正文的開頭
- bool skipResponseHeaders() {
- // HTTP headers end with an empty line
- char endOfHeaders[] = "\r\n\r\n";
- client.setTimeout(HTTP_TIMEOUT);
- bool ok = client.find(endOfHeaders);
- if (!ok) {
- Serial.println("No response or invalid response!");
- }
- return ok;
- }
- // Read the body of the response from the HTTP server -- 從HTTP服務(wù)器響應(yīng)中讀取正文
- void readReponseContent(char* content, size_t maxSize) {
- // size_t length = client.peekBytes(content, maxSize);
- size_t length = client.readBytes(content, maxSize);
- delay(20);
- Serial.println(length);
- Serial.println("Get the data from Internet!");
- content[length] = 0;
- Serial.println(content);
- Serial.println("Read Over!");
- }
- bool parseUserData_test(char* content, struct UserData* userData) {
- // Compute optimal size of the JSON buffer according to what we need to parse.
- // -- 根據(jù)我們需要解析的數(shù)據(jù)來計算JSON緩沖區(qū)最佳大小
- // This is only required if you use StaticJsonBuffer. -- 如果你使用StaticJsonBuffer時才需要
- const size_t BUFFER_SIZE = 1024;
- // Allocate a temporary memory pool on the stack -- 在堆棧上分配一個臨時內(nèi)存池
- StaticJsonBuffer<BUFFER_SIZE> jsonBuffer;
- // -- 如果堆棧的內(nèi)存池太大,使用 DynamicJsonBuffer jsonBuffer 代替
- // If the memory pool is too big for the stack, use this instead:
- // DynamicJsonBuffer jsonBuffer;
- JsonObject& root = jsonBuffer.parseObject(content);
- if (!root.success()) {
- Serial.println("JSON parsing failed!");
- return false;
- }
- // Here were copy the strings we're interested in
- userData->errno_val = root["errno"];
- strcpy(userData->error, root["error"]);
- if ( userData->errno_val == 0 ) {
- userData->test_led_Val = root["data"]["current_value"];
- strcpy(userData->udate_at, root["data"]["update_at"]);
- Serial.print("YF-Test_LED Value : ");
- Serial.print(userData->test_led_Val);
- Serial.print("\t The last update time : ");
- Serial.println(userData->udate_at);
- }
- Serial.print("errno : ");
- Serial.print(userData->errno_val);
- Serial.print("\t error : ");
- Serial.println(userData->error);
- return true;
- }
- void colLED(int sta) {
- digitalWrite(ledPin, sta);
- }
- void smartConfig()//智能配網(wǎng),可以微信掃一掃進行配網(wǎng),或者用app進行配網(wǎng)。
- {
- WiFi.mode(WIFI_STA);
- Serial.println("\r\nWait for Smartconfig");
- WiFi.beginSmartConfig();
- while (1)
- {
- Serial.print(".");
- digitalWrite(LED, 0);
- delay(500);
- digitalWrite(LED, 1);
- delay(500);
- if (WiFi.smartConfigDone())
- {
- Serial.println("SmartConfig Success");
- Serial.printf("SSID:%s\r\n", WiFi.SSID().c_str());
- Serial.printf("PSW:%s\r\n", WiFi.psk().c_str());
- break;
- }
- }
- }
- void tcp_test () {
- if (!client.connect(host, tcpPort)) {//鏈接tcp服務(wù)器測試
- Serial.println("connection failed");
- return;
- }
- }
- void setup() {
- WiFi.mode(WIFI_AP_STA); //set work mode: WIFI_AP /WIFI_STA /WIFI_AP_STA
- Serial.begin(115200); //傳輸波特率
- pinMode(ledPin, OUTPUT);
- dht.begin(); //初始化溫濕度模塊
- smartConfig(); //開啟自動配網(wǎng)。
- }
- void loop() {
- float h = dht.readHumidity();
- float t = dht.readTemperature();
- if (isnan(h) || isnan(t)) { //檢測dht溫濕度故障
- Serial.println("Failed to read from DHT sensor!");
- return;
- }
- tcp_test (); //tcp鏈接校驗
- getdata(); //獲取下發(fā)的數(shù)據(jù)流
- tcp_test (); //tcp鏈接校驗
- postData(deviceId, t, h); //發(fā)送上報的數(shù)據(jù)流
- }
- void postData(int dId, float val_t, float val_h) { //采用post方式發(fā)包,進行http協(xié)議溫濕度上傳
- String url = "/devices/";
- url += String(dId);
- url += "/datapoints?type=3"; //http://open.iot.10086.cn/doc/art190.html#43
- String data = "{\"" + String(DS_Temp) + "\":" + String(val_t) + ",\"" + String(DS_Hum) + "\":" + String(val_h) + ",\"" + String(DS_Baojing) + "\":" + String(val_t) + "}";
- Serial.println(data);
- Serial.print("data length:");
- Serial.println(String(data.length()));
- String post_data = "POST " + url + " HTTP/1.1\r\n" +
- "api-key:" + APIKEY + "\r\n" +
- "Host:" + host + "\r\n" +
- "Content-Length: " + String(data.length()) + "\r\n" +
- "Connection: close\r\n\r\n" +
- data;
- client.print(post_data);
- }
- void getdata() { //采用get方式獲取服務(wù)器數(shù)據(jù)反饋進行開關(guān)繼電器操作
- // We now create a URI for the request
- String url2 = "/devices/";
- url2 += String(deviceId);
- url2 += "/datastreams/";
- url2 += DataStreams;
- String send_data = String("GET ") + url2 + " HTTP/1.1\r\n" +
- "api-key:" + APIKEY + "\r\n" +
- "Host:" + host + "\r\n" +
- "Connection: close\r\n\r\n";
- client.print(send_data);
- if (DEBUG) {
- Serial.println(send_data);
- }
- if (skipResponseHeaders()) { // 發(fā)送請求json解析
- char response[MAX_CONTENT_SIZE];
- readReponseContent(response, sizeof(response));
- UserData userData_testLED;
- if (parseUserData_test(response, &userData_testLED)) {
- Serial.println("daily data parse OK!");
- colLED(userData_testLED.test_led_Val);
- }
- }
- }
復(fù)制代碼
所有資料51hei提供下載:
esp用arduinoide對接onenet.zip
(3.56 KB, 下載次數(shù): 30)
2019-3-26 21:42 上傳
點擊文件名下載附件
下載積分: 黑幣 -5
|