通過 ESP8266 搭建簡單的物聯網項目

關於本篇文章的背景知識如 ESP8266 介紹、開發環境搭建等可以參考之前寫的 Arduino IDE 搭建 ESP8266 開發環境及項目演示,或者瀏覽網絡上的其他文章,不做贅述。
這裏使用的開發板爲基於 ESP8266 芯片設計的 NodeMcu,開發環境爲配置後的 Arduino IDE

一、雲端數據監控(DHT11 + NodeMcu +Dweet.io)

1. 前期準備
2. Dweet.io

Dweet.io 是一個可以通過非常簡易的方式爲物聯網設備提供通信服務(包括報警等)的雲端平臺。它不需要任何的設置或註冊步驟,只要終端設備連接上互聯網,即可直接發佈或訂閱數據。
通過 Dweet.io 提供的雲端服務,可以很方便的將傳感器數據發佈到在線平臺並實時地進行遠程監控。

Dweeting

Dweeting發送數據到雲端,可以通過調用如下格式的 URL https://dweet.io/dweet/for/my-thing-name?hello=world&foo=bar

$ http -b "https://dweet.io/dweet/for/rollingstarky?hello=world&foo=bar"
{
    "by": "dweeting",
    "the": "dweet",
    "this": "succeeded",
    "with": {
        "content": {
            "foo": "bar",
            "hello": "world"
        },
        "created": "2019-01-14T19:15:34.524Z",
        "thing": "rollingstarky",
        "transaction": "6af2b067-229f-4b40-9af9-23d22e438ecd"
    }
}

注:上述代碼示例中的 http 命令(類似於 curl,但更加友好)來自於 HTTPie 軟件包

也可以在發送請求時通過 POST 方法提交合法的 JSON 數據。

Get Dweets

獲取最新發布的 dweet 可以訪問如下格式的 URL:
https://dweet.io/get/latest/dweet/for/my-thing-name

而獲取某個名字下所有的 dweets,則可以訪問如下 URL:
https://dweet.io/get/dweets/for/my-thing-name

$ http -b "https://dweet.io/get/dweets/for/rollingstarky"
{
    "by": "getting",
    "the": "dweets",
    "this": "succeeded",
    "with": [
        {
            "content": {
                "foo": "bar",
                "hello": "world"
            },
            "created": "2019-01-14T19:15:34.524Z",
            "thing": "rollingstarky"
        },
        {
            "content": {
                "foo": "bar",
                "hello": "world"
            },
            "created": "2019-01-14T19:10:46.694Z",
            "thing": "rollingstarky"
        }
    ]
}

好吧,發了兩遍一樣的內容。。。

3. 項目代碼

主要是通過 DHT11 傳感器獲取室內的溫溼度數據,再通過 ESP8266 將這些數據源源不斷地發送至 Dweet.io 的雲端平臺。

代碼如下:

#include <ESP8266WiFi.h>
#include "DHT.h"

// WiFi parameters
const char* ssid = "wifi-name";
const char* password = "wifi-password";

#define DHTPIN 5

#define DHTTYPE DHT11

// Initialize DHT sensor
DHT dht(DHTPIN, DHTTYPE, 15);

const char* host = "dweet.io";

void setup() {
  
  Serial.begin(115200);
  delay(10);
  
  dht.begin();

  // Connecting to a WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");  
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void loop() {

  Serial.print("Connecting to ");
  Serial.println(host);
  
  // Use WiFiClient class to create TCP connections
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(host, httpPort)) {
    Serial.println("connection failed");
    return;
  }
    
  // Reading temperature and humidity
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  
  while (isnan(h) || isnan(t)) {
    Serial.println("Failed to read from DHT sensor!");
    delay(2000);
    
    // Get the measurements once more
    h = dht.readHumidity(); 
    t = dht.readTemperature();
  }
  
    Serial.println();
    Serial.println("The temperature and humidity are:");
    Serial.println(t);
    Serial.println(h);
  
    // Send the request to the server
    client.print(String("GET /dweet/for/rollingstarkyesp8266?temperature=") + String(t) + "&humidity=" + String(h) + " HTTP/1.1\r\n" +
                 "Host: " + host + "\r\n" + 
                 "Connection: close\r\n\r\n");
    unsigned long timeout = millis();
    while (client.available() == 0) {
      if (millis() - timeout > 5000) {
        Serial.println(">>> Client Timeout !");
        client.stop();
        return;
    }
  }
  
    // Read all the lines of the reply from server and print them to Serial
    while(client.available()){
      String line = client.readStringUntil('\r');
      Serial.print(line);
    }
    Serial.println();
    Serial.println("closing connection");
    Serial.println();
  
  // Repeat every 10 seconds
  delay(10000);
}

根據自己的實際情況修改上述代碼中的 Wi-Fi 連接信息,之後上傳至 NodeMcu 並運行。

通過瀏覽器訪問以下鏈接 http://dweet.io/follow/my-thing-name (代碼中的 my-thing-namerollingstarkyesp8266,可以自行修改),效果如下:

4. freeboard

freeboard 是一個開源的儀表盤應用,可以通過非常簡單的操作,爲物聯網系統提供實時的、交互式的儀表盤和可視化效果。
freeboard 可以直接讀取上傳到 Dweet.io 上的傳感器數據,並將這些數據通過“漂亮”的圖表展示出來。

首先進入 freeboard 官網 創建賬戶並登錄,新建一個儀表板。
參考下圖添加位於 Dweet.io 上的數據源

添加面板和插件:


這裏可以選擇多種類型的插件,如 GaugeSparkline 等。實際操作並不複雜,自行摸索一下即可。最終效果如下:


呃,我又對着傳感器哈氣了,爲了曲線好看一點。。。實際溫溼度變化沒有這麼明顯(溫度一直保持在11℃。沒錯,這就是我的冬日臥室)。

二、遠程控制物聯網設備(NodeMcu + PubSubClient + aREST)

本項目源代碼如下:

// Import required libraries
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <aREST.h>

// Clients
WiFiClient espClient;
PubSubClient client(espClient);

// Create aREST instance
aREST rest = aREST(client);

// Unique ID to identify the device for cloud.arest.io
char* device_id = "wuwu380";

// WiFi parameters
const char* ssid = "wifi-name";
const char* password = "wifi-password";

// Callback functions
void callback(char* topic, byte* payload, unsigned int length);

void setup(void)
{
  // Start Serial
  Serial.begin(115200);

  // Set callback
  client.setCallback(callback);

  // Give name and ID to device
  rest.set_id(device_id);
  rest.set_name("devices_control");

  // Connect to WiFi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  // Set output topic
  char* out_topic = rest.get_topic();
}

void loop() {

  // Connect to the cloud
  rest.handle(client);
}

// Handles message arrived on subscribed topic(s)
void callback(char* topic, byte* payload, unsigned int length) {
  rest.handle_callback(client, topic, payload, length);
}

代碼編譯執行前,Arduino IDE 需要先安裝 aRESTPubSubClient 庫。

aREST 框架可以爲一些常見的嵌入式開發板提供 RESTful 接口,支持通過串口、Wi-Fi、以太網、藍牙等硬件發送命令至開發板,激發特定的操作,並將數據以 JSON 的格式返回給控制端用戶(可以參考 Arduino IDE 搭建 ESP8266 開發環境及項目演示)。

cloud.arest.io 上部署着雲端版本的 aREST 框架,可以綁定用戶聯網設備,並通過 MQTT 協議以消息訂閱和發佈的模式在客戶端設備和服務器之間傳輸數據,最終完成對遠程設備的控制。

運行效果如下:

$ http -b https://cloud.arest.io/wuwu380/name
{
    "connected": true,
    "hardware": "esp8266",
    "id": "wuwu380",
    "name": "devices_control",
    "variables": {}
}

$ http -b https://cloud.arest.io/wuwu380/mode/5/o
{
    "connected": true,
    "hardware": "esp8266",
    "id": "wuwu380",
    "message": "Pin D5 set to output",
    "name": "devices_control"
}

$ http -b https://cloud.arest.io/wuwu380/digital/5/1
{
    "connected": true,
    "hardware": "esp8266",
    "id": "wuwu380",
    "message": "Pin D5 set to 1",
    "name": "devices_control"
}
儀表盤

cloud.arest.io 還提供了一個很簡易的儀表板 Dashboard (雖然在交互設計上感覺有點不友好。。),可以自己嘗試下。我這裏只把實際效果貼一下:

內容有點多感覺,,先告一段落了

參考資源

Internet of Things with ESP8266 (English Edition)
ESP8266 Internet of Things Cookbook

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章