-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathadafruit.ino
127 lines (103 loc) · 2.63 KB
/
adafruit.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#include <ESP8266WiFi.h>
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"
#define WIFI_SSID ""
#define WIFI_PASS ""
#define MQTT_SERV "io.adafruit.com"
#define MQTT_PORT 1883
#define MQTT_NAME ""
#define MQTT_PASS ""
int led = D7;
WiFiClient client;
Adafruit_MQTT_Client mqtt(&client, MQTT_SERV, MQTT_PORT, MQTT_NAME, MQTT_PASS);
Adafruit_MQTT_Subscribe onoff = Adafruit_MQTT_Subscribe(&mqtt, MQTT_NAME "/f/ONOF");
Adafruit_MQTT_Publish LightsStatus = Adafruit_MQTT_Publish(&mqtt, MQTT_NAME "/f/LightsStatus");
void setup()
{
Serial.begin(9600);
pinMode(LED_BUILTIN, OUTPUT);
//Connect to WiFi
Serial.print("\n\nConnecting Wifi>");
WiFi.begin(WIFI_SSID, WIFI_PASS);
digitalWrite(LED_BUILTIN, LOW);
while (WiFi.status() != WL_CONNECTED)
{
Serial.print(">");
delay(50);
}
Serial.println("OK!");
//Subscribe to the onoff topic
mqtt.subscribe(&onoff);
pinMode(led, OUTPUT);
digitalWrite(LED_BUILTIN, HIGH);
digitalWrite(led, LOW);
}
void loop()
{
//Connect/Reconnect to MQTT
MQTT_connect();
//Read from our subscription queue until we run out, or
//wait up to 5 seconds for subscription to update
Adafruit_MQTT_Subscribe * subscription;
while ((subscription = mqtt.readSubscription(5000)))
{
//If we're in here, a subscription updated...
if (subscription == &onoff)
{
//Print the new value to the serial monitor
Serial.print("onoff: ");
Serial.println((char*) onoff.lastread);
//If the new value is "ON", turn the light on.
//Otherwise, turn it off.
if (!strcmp((char*) onoff.lastread, "ON"))
{
//active low logic
digitalWrite(led, HIGH);
LightsStatus.publish("ON");
}
else if (!strcmp((char*) onoff.lastread, "OFF"))
{
digitalWrite(led, LOW);
LightsStatus.publish("OFF");
}
else
{
LightsStatus.publish("ERROR");
}
}
else
{
//LightsStatus.publish("ERROR");
}
}
// if (!mqtt.ping())
// {
// mqtt.disconnect();
// }
}
void MQTT_connect()
{
// // Stop if already connected
if (mqtt.connected() && mqtt.ping())
{
// mqtt.disconnect();
return;
}
int8_t ret;
mqtt.disconnect();
Serial.print("Connecting to MQTT... ");
uint8_t retries = 3;
while ((ret = mqtt.connect()) != 0) // connect will return 0 for connected
{
Serial.println(mqtt.connectErrorString(ret));
Serial.println("Retrying MQTT connection in 5 seconds...");
mqtt.disconnect();
delay(5000); // wait 5 seconds
retries--;
if (retries == 0)
{
ESP.reset();
}
}
Serial.println("MQTT Connected!");
}