Para enviar a mensagem para o Home Assistent mostrando o estado do botão (Se pressionado ou não), baseando-se na aula do sonoff, o que vai mudar seria a inserção do botão?
Por exemplono código abaixo, aonde devo adicionar o digitalRead do botão?
no callback?
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#define RELAY 12
#define BOTAO 4
const char* ssid = "........";
const char* password = "........";
const char* mqtt_server = "broker.mqtt-dashboard.com";
const int mqtt_port = 1883;
const char* mqtt_topic = "ha/escritorio/iluminacao";
const char* mqtt_clientID = "sonoff01";
const char* mqtt_user = "alvarenga";
const char* mqtt_pass = "wiloliver";
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
// -----Setup------
void setup() {
pinMode (BOTAO, INPUNT);
pinMode(RELAY, OUTPUT);
setup_wifi();
client.setServer(mqtt_server , mqtt_port );
client.setCallback (callback);
}
// -----setup_wifi--------
void setup_wifi() {
delay(10);
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
randomSeed(micros());
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
// ---------callback------
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
if ((char)payload[0] == '1') {
digitalWrite(RELAY, HIGH);
}
if ((char)payload[0] == '0') {
digitalWrite(RELAY_ HIGH);
}
}
void reconnect() {
while (!client.connected()) {
client.connect(mqtt_clientID, mqtt_user, mqtt_pass);
client.subscribe(mqtt_topic);
delay(1000);
}
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
long now = millis();
if (now - lastMsg > 2000) {
lastMsg = now;
++value;
snprintf (msg, 50, "hello world #%ld", value);
Serial.print("Publish message: ");
Serial.println(msg);
client.publish("outTopic", msg);
}
}