-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
94 lines (71 loc) · 1.82 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
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
#include <WiFi.h>
#include <MQTT.h>
#include <Adafruit_Sensor.h>
#include "DHT.h"
#include "temperature_sensor.h"
#include "rgb_led_routine.h"
// #define DEBUG // uncomment to see debug output
const char ssid[] = "YOUR_WIFI_SSID";
const char pass[] = "YOUR_WIFI_PASS";
#define BROKER_URI "broker.emqx.io"
WiFiClient net;
MQTTClient client;
extern DHT dht;
void connect() {
Serial.print("checking wifi...");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(1000);
}
#ifdef DEBUG
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
#endif // DEBUG
Serial.println("connecting...");
while (!client.connect("esp32", "", "")) {
Serial.print(".");
client.disconnect();
delay(2000);
}
Serial.println("connected!");
client.subscribe("esp32");
client.subscribe("esp32/color");
}
void actionOnMessage(String topic_, String payload_) {
#ifdef DEBUG
Serial.print("TOPIC: ");
Serial.println(topic_);
Serial.print("PAYLOAD: ");
Serial.println(payload_);
#endif // DEBUG
// string payload from "(..., ..., ...)"
uint8_t red; // Red value for RGB
uint8_t green; // Green value for RBG
uint8_t blue; // Blue value for RGB
TrimPayloadToRGB(payload_, &red, &green, &blue);
setColorRGB(red, green, blue);
}
// callback on incoming message
void messageReceived(String &topic, String &payload) {
#ifdef DEBUG
Serial.println("incoming: " + topic + " - " + payload);
#endif // DEBUG
actionOnMessage(topic, payload);
}
void setup() {
Serial.begin(115200);
dht.begin();
initPWM();
WiFi.begin(ssid, pass);
client.begin(BROKER_URI, net);
client.onMessage(messageReceived);
connect();
}
void loop() {
client.loop();
delay(10); // <- fixes some issues with WiFi stability
if (!client.connected()) {
connect();
}
DHTReadAndPublish();
}