使用 Arduino 通過 MQTT 協(xié)議連接 HomeAssistant -- 受控設(shè)備

前言

如果對(duì)于 MQTT 協(xié)議有一點(diǎn)了解的話,應(yīng)該知道設(shè)備既可以推送消息給 MQTT 代理,也可以從 MQTT 代理那里訂閱消息,而在之前的教程中,因?yàn)槲覀冞B接的設(shè)備都是傳感器,僅需要將數(shù)據(jù)發(fā)送給 MQTT 代理即可,這時(shí) HomeAssistant 相當(dāng)于運(yùn)行著一個(gè) MQTT 訂閱服務(wù)。既然我們有了 Arduino ,通過 Arduino 我們可以讀取很多設(shè)備,也可以控制很多設(shè)備,如燈,電動(dòng)機(jī),而通過繼電器還能控制高壓電路,可以實(shí)現(xiàn)更多的功能,因此我們肯定不會(huì)僅限于從 Arduino 收集數(shù)據(jù)發(fā)送給 HomeAssistant ,我們肯定還希望能從 HomeAssistant 控制 Arduino 設(shè)備。本文便來源于此,建議正在閱讀的你將之前我寫的那兩篇關(guān)于傳感器的教程閱讀完,因?yàn)榻裉斓慕坛蹋墙又厦鎸懙摹?/p>

鏈接
使用 Arduino 通過 MQTT 協(xié)議連接 HomeAssistant -- 樹莓派端
使用 Arduino 通過 MQTT 協(xié)議連接 HomeAssistant -- Arduino端

1. 樹莓派端

樹莓派端僅僅需要添加相應(yīng)的配置即可,如果是燈就添加在 light 標(biāo)簽中,如果是風(fēng)扇就添加在 fan 標(biāo)簽中,這里是一個(gè)小的激光燈和一個(gè)散熱風(fēng)扇。配置如下:

light: 
  - platform: mqtt
    name: laserLight
    command_topic: "home-assistant/arduino1/laserLight"
    state_topic: "home-assistant/arduino1/laserLightState"
    optimistic: false
fan:
  - platform: mqtt
    name: coolFan
    command_topic: "home-assistant/arduino1/fan"
    state_topic: "home-assistant/arduino1/fanState"
    optimistic: false

配置完成后使用 sudo systemctl restart home-assistant.service 重啟 HomeAssistant 服務(wù)。當(dāng)然如果想把這兩個(gè)設(shè)備加入到分組中,也可以先將他們加入到分組之后再重啟 HomeAssistant 服務(wù)也行。

ESP12 端

如果你在之前已經(jīng)將傳感器按照之前的教程配置完成,并且可以使用,那么之前的 Arduino 中的程序不需要更改,只需要修改部分 ESP12 中的程序即可,在修改 ESP12 的程序中一定要注意,本教程是將受控設(shè)備連接到 ESP12 ,而非 Arduino,雖然也可以將它連接到 Arduino ,連接 Arduino 還要添加 Arduino 與 ESP12 的通信程序,因?yàn)?ESP12 本身就有 IO 所以可以將受控設(shè)備直接連接到 ESP12 上。
在使用 ESP12 的時(shí)候一定要注意,如果你是直接用一個(gè) ESP8266 ,那么直接按照引腳圖上的引腳用即可,如果你使用的是像我使用的 ESP12 一樣的話,建議你找到 引腳與IO對(duì)應(yīng)的圖在進(jìn)行使用。程序中使用 GPIO 號(hào)作為引腳號(hào)使用。上面沒標(biāo)的GPIO號(hào),謹(jǐn)慎使用。

我的ESP12 引腳與GPIO對(duì)應(yīng)圖
#include <ESP8266WiFi.h>
#include <PubSubClient.h>

#define MQTT_VERSION MQTT_VERSION_3_1_1

// Wifi: SSID and password
const char* WIFI_SSID = "YourWiFiSSID";
const char* WIFI_PASSWORD = "YourWiFiPassword";

// MQTT: ID, server IP, port, username and password
const PROGMEM char* MQTT_CLIENT_ID = "DeviceID";
const PROGMEM char* MQTT_SERVER_IP = "YourRaspberryPi_IPAddress";
const PROGMEM uint16_t MQTT_SERVER_PORT = 1883;
const PROGMEM char* MQTT_USER = "YourMQTTUserName";
const PROGMEM char* MQTT_PASSWORD = "YouMQTTPassword";

// MQTT: topics 這里的主題要與樹莓派中的配置文件中的主題保持一致
const char* MQTT_LASOR_COMMAND_TOPIC = "home-assistant/arduino1/laserLight";
const char* MQTT_FAN_COMMAND_TOPIC = "home-assistant/arduino1/fan";
const char* MQTT_LASOR_STATE_TOPIC = "home-assistant/arduino1/laserLightState";
const char* MQTT_FAN_STATE_TOPIC = "home-assistant/arduino1/fanState";

// payloads by default (on/off)
const char* DEVICE_ON = "ON";
const char* DEVICE_OFF = "OFF";

const PROGMEM uint8_t lasorPin = 14;
const PROGMEM uint8_t fanPin = 12;

boolean lightSstate = false;
boolean fanState = false;

String strRecv = "";
long now = 0;
long lastRecv = 0;
bool newDataComing = false;

WiFiClient wifiClient;
PubSubClient client(wifiClient);

void publishLasorState() {
    if (lightSstate) {
        client.publish(MQTT_LASOR_STATE_TOPIC, DEVICE_ON, true);
    } else {
        client.publish(MQTT_LASOR_STATE_TOPIC, DEVICE_OFF, true);
    }
}

// function called to turn on/off the light
void setLasorState() {
    if (lightSstate) {
       digitalWrite(lasorPin, HIGH);
       //Serial.println("INFO: Turn light on...");
    } else {
       digitalWrite(lasorPin, LOW);
       //Serial.println("INFO: Turn light off...");
    }
  }

void publishFanState() {
    if (fanState) {
        client.publish(MQTT_FAN_STATE_TOPIC, DEVICE_ON, true);
    } else {
         client.publish(MQTT_FAN_STATE_TOPIC, DEVICE_OFF, true);
    }
}

void setFanState() {
    if (fanState) {
        digitalWrite(fanPin, HIGH);
        //Serial.println("INFO: Turn Fan on...");
      } else {
        digitalWrite(fanPin, LOW);
        //Serial.println("INFO: Turn Fan off...");
      }
 }

// function called when a MQTT message arrived
void callback(char* p_topic, byte* p_payload, unsigned int p_length) {
    // concat the payload into a string
    String payload;
    Serial.println("INFO:callback...");
    for (uint8_t i = 0; i < p_length; i++) {
    payload.concat((char)p_payload[i]);
    }

    // handle message topic
  if (String(MQTT_LASOR_COMMAND_TOPIC).equals(p_topic)) {
    if (payload.equals(String(DEVICE_ON))) {
        lightSstate = true;
    } else if (payload.equals(String(DEVICE_OFF))) {
        lightSstate = false;
    }
    setLasorState();
    publishLasorState();
  }
  else if (String(MQTT_FAN_COMMAND_TOPIC).equals(p_topic)) {
    if (payload.equals(String(DEVICE_ON))) {
         fanState = true;
    } else if (payload.equals(String(DEVICE_OFF))) {
         fanState = false;
    }
    setFanState();
    publishFanState();
  }
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("INFO: Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect(MQTT_CLIENT_ID, MQTT_USER, MQTT_PASSWORD)) {
      Serial.println("INFO: connected");
      // Once connected, publish an announcement...
      publishLasorState();
      publishFanState();
      // ... and resubscribe
      client.subscribe(MQTT_LASOR_COMMAND_TOPIC);
      client.subscribe(MQTT_FAN_COMMAND_TOPIC);
    } else {
      Serial.print("ERROR: failed, rc=");
      Serial.print(client.state());
      Serial.println("DEBUG: try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void setup() {
  // init the serial
  Serial.begin(9600);

  // init the led
  pinMode(lasorPin, OUTPUT);
  pinMode(fanPin, OUTPUT);
  analogWriteRange(255);
  setLasorState();
  setFanState();

  // init the WiFi connection
  Serial.println();
  Serial.println();
  Serial.print("INFO: Connecting to ");
  WiFi.mode(WIFI_STA);
  Serial.println(WIFI_SSID);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);

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

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

  // init the MQTT connection
  client.setServer(MQTT_SERVER_IP, MQTT_SERVER_PORT);
  client.setCallback(callback);
}

void loop() {
  //Serial.println("INFO: LOOP: ");
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
  if (Serial.available() > 0) {
    char str = char(Serial.read());
    strRecv = strRecv + str;
    lastRecv = millis();
    newDataComing = true;
    delay(2);
  }
  else {
    now = millis();
    if ((now - lastRecv > 100) && (newDataComing == true)) {
      //Serial.print("recv Data ");
      //Serial.print(strRecv);

      boolean isOK = client.publish(ARDUINO_SENSOR, String(strRecv).c_str(), true);
      //Serial.print(" send state ");
      //Serial.println(isOK);

      strRecv = "";
      newDataComing = false;
    }
  }
}

在這個(gè)程序中你可以看到之前教程的影子,包括之前傳感器的主題,串口接收的程序都還依舊保留。所以如果你是想在上面直接加上受控設(shè)備直接用的話,可以參考本文的代碼。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容