-
Notifications
You must be signed in to change notification settings - Fork 18
/
ESP8266_MqttSubClientAlert.ino
53 lines (45 loc) · 1.22 KB
/
ESP8266_MqttSubClientAlert.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <ESP8266WiFi.h> // v2.4.2
#include <ESP8266MQTTClient.h> // v1.0.4
const char *ssid = "MY_SSID"; // TODO
const char *password = "MY_PASSWORD"; // TODO
const char *host = "mqtt://LOCAL_IP"; // TODO
const int buzzerPin = 5;
MQTTClient client;
void handleConnected() {
Serial.println("Connected to broker");
client.subscribe("alert");
}
void handleSubscribed(int topicId) {
Serial.println("Subscribed");
}
void handleDataReceived(String topic, String data, bool b) {
Serial.print("Received topic: ");
Serial.print(topic);
Serial.print(", data: ");
Serial.println(data);
if (data == "on") {
digitalWrite(buzzerPin, HIGH);
} else {
digitalWrite(buzzerPin, LOW);
}
}
void setup() {
Serial.begin(115200);
pinMode(buzzerPin, OUTPUT);
Serial.print("\nConnecting to network ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(100); // keeps watchdog happy
}
Serial.print("Connected to network, local IP = ");
Serial.println(WiFi.localIP());
client.onConnect(handleConnected);
client.onSubscribe(handleSubscribed);
client.onData(handleDataReceived);
client.begin(host);
}
void loop() {
client.handle();
}