我正在尝试使用代码中的回调函数的输出来触发操作。基本上,我将在“ reedTopic”上安装一个门传感器,该传感器需要报告“ OFF”,然后才能发送“主题”的有效负载。 “主题”有效载荷是车库门开启器的拨动开关,因此来自“主题”的数据将始终保持不变。
目标是当插入我的汽车的esp8266-01连接到无线网络时,它将检测“ reedTopic”的状态,如果不等于“ OFF”,则不会触发“主题”有效负载。
我想完全用代码来设置这种自动化,而不必依靠Node-Red或HomeAssistant等其他软件来完成这项工作。
我也很确定我不完全了解回调函数以及应如何使用它,尤其是在这种情况下。我还是Arduino新手,所以这确实是我的第一个项目。我还很确定其中有一些垃圾代码,因为大多数代码是从Arduino IDE中的pubsubclient处理程序的示例中拼接而成的。
#include <PubSubClient.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPUpdateServer.h>
const char* ssid = "******";
const char* password = "******";
const char* host = "CarPresence";
const char* update_path = "/";
const char* update_username = "*****";
const char* update_password = "*****";
char* topic = "cmnd/GarageDoor/POWER";
const char* willTopic = "cmnd/GarageDoor/POWER";
char* reedTopic = "cmnd/GarageDoor/POWER2";
char* server = "192.168.1.138";
byte willQoS = 1;
const char* willMessage = "1";
boolean willRetain = false;
boolean retained = true;
ESP8266WebServer httpServer(80);
ESP8266HTTPUpdateServer httpUpdater;
WiFiClient wifiClient;
PubSubClient client(server, 1883, wifiClient);
void callback(char* reedTopic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(reedTopic);
Serial.print("] ");
for (int i=0;i<length;i++) {
Serial.print((char)payload[i]);
}
if (strcmp((char* )reedTopic, "OFF") == 0) {
client.connect("CarPresence", willTopic, willQoS, willRetain, willMessage);
client.publish(topic, "The Garage door is CLOSED... Opening...");
client.publish(topic, "1");
while (WiFi.status() == WL_CONNECTED) {
delay(5000);
client.println(reedTopic);
client.publish(topic, "Ah ah ah ah staying alive staying alive...");
}
}
if (strcmp((char* )reedTopic, "ON") == 0) {
client.publish(topic, "The Garage door is OPEN... Aborting...");
while (WiFi.status() == WL_CONNECTED) {
delay(5000);
client.println(reedTopic);
client.publish(topic, "Dying... I'm dying...");
}
}
Serial.println();
}
String macToStr(const uint8_t* mac)
{
String result;
for (int i = 0; i < 6; ++i) {
result += String(mac[i], 16);
if (i < 5)
result += ':';
}
return result;
}
void setup() {
Serial.begin(115200);
delay(10);
client.setCallback(callback);
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
client.connect("CarPresence");
client.subscribe(topic);
client.subscribe(reedTopic, retained);
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
httpUpdater.setup(&httpServer, update_path, update_username, update_password);
httpServer.begin();
Serial.printf("HTTPUpdateServer ready! Open http://%s%s in your browser and login with username '%s' and password '%s'\n", host, update_path, update_username, update_password);
// Generate client name based on MAC address and last 8 bits of microsecond counter
String clientName = "CarPresence";
Serial.print("Connecting to ");
Serial.print(server);
Serial.print(" as ");
Serial.println(clientName);
if (client.connect((char*) clientName.c_str())) {
Serial.println("Connected to MQTT broker");
Serial.print("Topics are: ");
Serial.println(topic);
Serial.println(reedTopic);
if (client.publish(topic, "Hello from ESP8266")) {
Serial.println("Publish ok");
}
else {
Serial.println("Publish failed");
}
}
else {
Serial.println("MQTT connect failed");
Serial.println("Will reset and try again...");
abort();
}
}
void loop() {
httpServer.handleClient();
client.setCallback(callback);
while (WiFi.status() != WL_CONNECTED) {
delay(5000);
Serial.print(".");
}
}
在大多数情况下,该代码有效。最大的问题是围绕reedTopic反馈的IF语句。该代码直接吹过去,无需再次浏览即可执行主题有效负载。
答案 0 :(得分:0)
我设法从GitHub上PubSubClient的作者那里得到了一些帮助。后来我在Arduino论坛上找到了我需要的其余内容。这是我下面的完整代码。
// Setup your sonoff //
// Flash your sonoff switch with tasmota //
// Associate the tasmotized sonoff with your WiFi network //
// Load the webpage for the sonoff and setup your mqtt topics //
// Go into module setup and set GPIO14 to Switch2 //
// Go into the console and type "SwitchMode2 1" (without quotes) //
// Lastly, in the console type "PulseTime 1" (without quotes) //
// Setup credentials in the code //
// Replace asterisks next to ssid & password with WiFi credentials //
// Replace asterisks next to update_username & update_password with creds //
#include <PubSubClient.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPUpdateServer.h>
const char* ssid = "******";
const char* password = "******";
const char* host = "CarPresence";
const char* update_path = "/";
const char* update_username = "******";
const char* update_password = "******";
char* topic = "cmnd/GarageDoor/POWER";
const char* willTopic = "cmnd/GarageDoor/POWER";
char* reedTopic = "cmnd/GarageDoor/POWER2";
char* server = "192.168.1.138";
byte willQoS = 1;
const char* willMessage = "1";
boolean willRetain = false;
boolean retained = true;
ESP8266WebServer httpServer(80);
ESP8266HTTPUpdateServer httpUpdater;
WiFiClient wifiClient;
PubSubClient client(wifiClient);
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("CarPresence")) {
Serial.println("connected");
// set callback and subscribe to topics
client.setCallback(callback);
client.subscribe("cmnd/GarageDoor/POWER");
client.subscribe("cmnd/GarageDoor/POWER2");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void callback(char* reedTopic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(reedTopic);
Serial.print("] ");
for (int i=0;i<length;i++) {
Serial.print((char)payload[i]);
}
Serial.println();
payload[length] = '\0';
String message = (char*)payload;
if(message == "ON"){
client.publish(topic, "Garage Door is CLOSED");
client.publish(topic, "1");
delay(10000);
while(message != "ON"){
break;
}
}
if(message == "OFF"){
client.publish(topic, "Garage Door is OPEN");
delay(10000);
while(message != "OFF"){
break;
}
}
}
String macToStr(const uint8_t* mac)
{
String result;
for (int i = 0; i < 6; ++i) {
result += String(mac[i], 16);
if (i < 5)
result += ':';
}
return result;
}
void setup() {
Serial.begin(115200);
delay(10);
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());
httpUpdater.setup(&httpServer, update_path, update_username, update_password);
httpServer.begin();
Serial.println("HTTPUpdateServer ready!");
// Generate client name based on MAC address and last 8 bits of microsecond counter
String clientName = "CarPresence";
client.setServer(server, 1883);
client.setCallback(callback);
client.connect("CarPresence", willTopic, willQoS, willRetain, willMessage);
client.subscribe(topic);
client.subscribe(reedTopic, retained);
Serial.print("Connecting to ");
Serial.print(server);
Serial.print(" as ");
Serial.println(clientName);
if (client.connect((char*) clientName.c_str())) {
Serial.println("Connected to MQTT broker");
Serial.print("Topics are: ");
Serial.println(topic);
Serial.println(reedTopic);
if (client.publish(topic, "Hello from ESP8266")) {
Serial.println("Publish ok");
}
else {
Serial.println("Publish failed");
}
}
else {
Serial.println("MQTT connect failed");
Serial.println("Will reset and try again...");
reconnect();
}
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
httpServer.handleClient();
client.publish(topic, "Keeping Alive");
delay(2000);
while (WiFi.status() != WL_CONNECTED) {
delay(5000);
Serial.print(".");
}
}
该代码也将发布在GitHub的摘要中。 https://gist.github.com/hyukishi