前言
如果对于 MQTT 协议有一点了解的话,应该知道设备既可以推送消息给 MQTT 代理,也可以从 MQTT 代理那里订阅消息,而在之前的教程中,因为我们连接的设备都是传感器,仅需要将数据发送给 MQTT 代理即可,这时 HomeAssistant 相当于运行着一个 MQTT 订阅服务。既然我们有了 Arduino ,通过 Arduino 我们可以读取很多设备,也可以控制很多设备,如灯,电动机,而通过继电器还能控制高压电路,可以实现更多的功能,因此我们肯定不会仅限于从 Arduino 收集数据发送给 HomeAssistant ,我们肯定还希望能从 HomeAssistant 控制 Arduino 设备。本文便来源于此,建议正在阅读的你将之前我写的那两篇关于传感器的教程阅读完,因为今天的教程,是接着上面写的。
链接
使用 Arduino 通过 MQTT 协议连接 HomeAssistant -- 树莓派端
使用 Arduino 通过 MQTT 协议连接 HomeAssistant -- Arduino端
1. 树莓派端
树莓派端仅仅需要添加相应的配置即可,如果是灯就添加在 light 标签中,如果是风扇就添加在 fan 标签中,这里是一个小的激光灯和一个散热风扇。配置如下:
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 服务。当然如果想把这两个设备加入到分组中,也可以先将他们加入到分组之后再重启 HomeAssistant 服务也行。
ESP12 端
如果你在之前已经将传感器按照之前的教程配置完成,并且可以使用,那么之前的 Arduino 中的程序不需要更改,只需要修改部分 ESP12 中的程序即可,在修改 ESP12 的程序中一定要注意,本教程是将受控设备连接到 ESP12 ,而非 Arduino,虽然也可以将它连接到 Arduino ,连接 Arduino 还要添加 Arduino 与 ESP12 的通信程序,因为 ESP12 本身就有 IO 所以可以将受控设备直接连接到 ESP12 上。
在使用 ESP12 的时候一定要注意,如果你是直接用一个 ESP8266 ,那么直接按照引脚图上的引脚用即可,如果你使用的是像我使用的 ESP12 一样的话,建议你找到 引脚与IO对应的图在进行使用。程序中使用 GPIO 号作为引脚号使用。上面没标的GPIO号,谨慎使用。
#include
#include
#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;
}
}
}
在这个程序中你可以看到之前教程的影子,包括之前传感器的主题,串口接收的程序都还依旧保留。所以如果你是想在上面直接加上受控设备直接用的话,可以参考本文的代码。