-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
65 lines (53 loc) · 1.53 KB
/
main.cpp
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
54
55
56
57
58
59
60
61
62
63
64
65
#include <Arduino.h>
#include <ControlDigitalOutput.h>
#include "WiFiSupportESP8266.h"
#include <PubSubClient.h>
#include "Configuration.h"
#define debug_port Serial
WiFiSupportESP8266 wifiSupport(&debug_port, LED_STATUS_WIFI, LED_STATE_WIFI);
WiFiClient espClient;
PubSubClient client(espClient);
ControlDigitalOutput led(LED_BUILTIN, LOW);
void callback(char* topic, byte* payload, unsigned int length);
void reconnect();
void subscribe();
void setup() {
debug_port.begin(115200);
wifiSupport.isSmartConfig();
client.setServer(MQTT_SERVER, MQTT_PORT);
client.setCallback(callback);
subscribe();
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}
void callback(char* topic, byte* payload, unsigned int length) {
String topicStr = topic;
if (topicStr.equals(TOPIC_SUB_LOAD)) {
if ((char) payload[0] == ON_LOAD) {
Serial.println("ON");
led.on();
} else {
Serial.println("OFF");
led.off();
}
}
}
void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
if (client.connect(DEVICE_ID, MQTT_USER, MQTT_PASSWORD)) {
Serial.println("connected");
subscribe();
} else {
Serial.printf("failed, rc= %d try again in 5 seconds", client.state());
delay(5000);
}
}
}
void subscribe() {
client.subscribe(TOPIC_SUB_LOAD);
}