1. 程式人生 > 其它 >ESP8266 + MQTT (platformio 開發環境)

ESP8266 + MQTT (platformio 開發環境)

ESP8266 + MQTT

引用庫

  • include <ESP8266WiFi.h>

  • include <PubSubClient.h>

#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>

// led 引腳
#define led_one 2

// wifi info 
const char *SSID = "wifi-name"; // 你家的wifi名
const char *PASSWORD = "123456a"; // wifi 密碼

// MQTT info https://www.emqx.com/zh/mqtt/public-mqtt5-broker 
const char *MQTT_SERVER = "broker-cn.emqx.io"; // MQTT 伺服器地址
const int MQTT_PROT = 1883; // MQTT 埠

// mqtt 主題
const char *MQTT_TOPIC_LED = "my/home/led";
const char *MQTT_TOPIC_ONLINE = "my/home/online";
const char *CLIENT_ID = "esp8266-457065e5-f063-474e-2saf-cacf5cb52af5";

WiFiClient espClient;
PubSubClient client(espClient);

void init_wifi();                                                        // 初始化wifi
void mqtt_reconnect();                                                   // 重新連線wifi
void mqtt_msg_callback(char *topic, byte *payload, unsigned int length); // mqtt 訊息回撥

void setup()
{
  Serial.begin(115200);
  pinMode(led_one, OUTPUT);
  init_wifi();
  client.setServer(MQTT_SERVER, MQTT_PROT); // 設定mqtt 服務和埠
  client.setCallback(mqtt_msg_callback);    // 設定mqtt 回撥函式
}

void loop()
{
  if (!client.connected())
  {
    mqtt_reconnect();
  }
  client.loop();
}

void init_wifi()
{
  Serial.println("Connecting to");
  Serial.println(SSID);

  WiFi.begin(SSID, PASSWORD);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
}

void mqtt_reconnect()
{
  while (!client.connected())
  {
    Serial.print("Attempting MQTT connection...");

    // 第一步: 建立連線
    if (client.connect(CLIENT_ID))
    {
      Serial.println("connected");
      client.publish(MQTT_TOPIC_ONLINE, "online"); // 釋出
      client.subscribe(MQTT_TOPIC_LED);            // 監聽 led 主題
    }
    else
    {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}

void mqtt_msg_callback(char *topic, byte *payload, unsigned int length)
{
  Serial.print("Message arrived [");
  Serial.print(topic); // 列印主題資訊
  Serial.print("] ");
  for (unsigned int i = 0; i < length; i++)
  {
    Serial.print((char)payload[i]); // 列印主題內容
  }

  String topic_data = String(topic);
  // String() 非同步
  if (topic_data == MQTT_TOPIC_LED)
  {
    // (char) byte 轉 char 型別
    if ((char)payload[0] == '1')
    {
      digitalWrite(led_one, HIGH);
      Serial.println("open_led");
    }
    else
    {
      digitalWrite(led_one, LOW);
      Serial.println("close_led");
    }
  }

  Serial.println();
}