arduino-sketches – Blame information for rev 14
?pathlinks?
Rev | Author | Line No. | Line |
---|---|---|---|
5 | office | 1 | /*************************************************************************/ |
2 | /* Copyright (C) 2020 Wizardry and Steamworks - License: GNU GPLv3 */ |
||
3 | /*************************************************************************/ |
||
4 | |||
5 | // The AP to connect to via Wifi. |
||
6 | #define STA_SSID "" |
||
7 | // The AP Wifi password. |
||
8 | #define STA_PSK "" |
||
9 | // The MQTT broker to connect to. |
||
10 | #define MQTT_HOST "" |
||
11 | // The MQTT broker username. |
||
12 | #define MQTT_USERNAME "" |
||
13 | // The MQTT broker password. |
||
14 | #define MQTT_PASSWORD "" |
||
15 | // The MQTT broker port. |
||
16 | #define MQTT_PORT 1883 |
||
17 | // The default MQTT client ID is "esp-CHIPID" where CHIPID is the ESP8266 |
||
18 | // or ESP32 chip identifier. |
||
19 | #define MQTT_CLIENT_ID() String("esp-" + String(GET_CHIP_ID(), HEX)) |
||
20 | // The authentication password to use for OTA updates. |
||
21 | #define OTA_PASSWORD "" |
||
22 | // The OTA port on which updates take place. |
||
23 | #define OTA_PORT 8266 |
||
24 | // The default topic that the sketch subscribes to is "esp/CHIPID" where |
||
25 | // CHIPID is the ESP8266 or ESP32 chip identifier. |
||
26 | #define MQTT_TOPIC() String("esp/" + String(GET_CHIP_ID(), HEX)) |
||
27 | |||
28 | // Platform specific defines. |
||
29 | #if defined(ARDUINO_ARCH_ESP8266) |
||
30 | #define GET_CHIP_ID() (ESP.getChipId()) |
||
31 | #elif defined(ARDUINO_ARCH_ESP32) |
||
32 | #define GET_CHIP_ID() ((uint16_t)(ESP.getEfuseMac()>>32)) |
||
33 | #endif |
||
34 | |||
35 | // Miscellaneous defines. |
||
36 | //#define CHIP_ID_HEX (String(GET_CHIP_ID()).c_str()) |
||
37 | #define HOSTNAME() String("esp-" + String(GET_CHIP_ID(), HEX)) |
||
38 | |||
39 | // Platform specific libraries. |
||
40 | #if defined(ARDUINO_ARCH_ESP8266) |
||
41 | #include <ESP8266WiFi.h> |
||
42 | #include <ESP8266mDNS.h> |
||
43 | #elif defined(ARDUINO_ARCH_ESP32) |
||
44 | #include <WiFi.h> |
||
45 | #include <ESPmDNS.h> |
||
46 | #endif |
||
47 | // General libraries. |
||
48 | #include <WiFiUdp.h> |
||
49 | #include <ArduinoOTA.h> |
||
50 | #include <PubSubClient.h> |
||
51 | #include <ArduinoJson.h> |
||
52 | #if defined(ARDUINO_ARCH_ESP32) |
||
53 | #include <FS.h> |
||
54 | #include <SPIFFS.h> |
||
55 | #endif |
||
56 | // DHT11 |
||
57 | #include <Adafruit_Sensor.h> |
||
58 | #include <DHT.h> |
||
59 | #include <DHT_U.h> |
||
60 | |||
61 | const char *sta_ssid = STA_SSID; |
||
62 | const char *sta_psk = STA_PSK; |
||
63 | const char *mqtt_host = MQTT_HOST; |
||
64 | const char *mqtt_username = MQTT_USERNAME; |
||
65 | const char *mqtt_password = MQTT_PASSWORD; |
||
66 | const int mqtt_port = MQTT_PORT; |
||
67 | const char *ota_password = OTA_PASSWORD; |
||
68 | const int ota_port = OTA_PORT; |
||
69 | |||
70 | WiFiClient espClient; |
||
71 | PubSubClient mqttClient(espClient); |
||
72 | |||
73 | // Uncomment the type of sensor in use: |
||
74 | #define DHTTYPE DHT11 // DHT 11 |
||
75 | //#define DHTTYPE DHT22 // DHT 22 (AM2302) |
||
76 | //#define DHTTYPE DHT21 // DHT 21 (AM2301) |
||
77 | |||
78 | // Define GPIO pins for supported architectures. |
||
79 | #if defined(ARDUINO_ARCH_ESP8266) |
||
80 | int PINS[] = { D0, D1, D2, D3, D4, D5, D6, D7, D8 }; |
||
81 | #elif defined(ARDUINO_ARCH_ESP32) |
||
82 | int PINS[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, |
||
83 | 12, 13, 14, 15, 16, 17, 18, 19, 21, 22, |
||
84 | 23, 25, 26, 27, 32, 33, 34, 35, 36, 37, |
||
85 | 38, 39 |
||
86 | }; |
||
87 | #endif |
||
88 | |||
89 | const char* mqttSerialize(StaticJsonDocument<256> msg) { |
||
90 | char message[256]; |
||
91 | serializeJson(msg, message); |
||
92 | return (const char*) message; |
||
93 | } |
||
94 | |||
95 | void mqttCallback(char *topic, byte *payload, unsigned int length) { |
||
96 | String msgTopic = String(topic); |
||
97 | // payload is not null terminated and casting will not work |
||
98 | char msgPayload[length + 1]; |
||
99 | snprintf(msgPayload, length + 1, "%s", payload); |
||
100 | Serial.println("Message received on topic: " + String(topic) + " with payload: " + String(msgPayload)); |
||
101 | |||
102 | // Parse the payload sent to the MQTT topic as a JSON document. |
||
103 | StaticJsonDocument<256> doc; |
||
104 | Serial.println("Deserializing message...."); |
||
105 | DeserializationError error = deserializeJson(doc, msgPayload); |
||
106 | if (error) { |
||
107 | Serial.println("Failed to parse MQTT payload as JSON: " + String(error.c_str())); |
||
108 | return; |
||
109 | } |
||
110 | |||
111 | // Ignore message with no identifier in the payload. |
||
112 | if (!doc.containsKey("id")) { |
||
113 | return; |
||
114 | } |
||
115 | |||
116 | // Do not listen to self. |
||
117 | String id = (const char *)doc["id"]; |
||
118 | if (id == String(MQTT_CLIENT_ID().c_str())) { |
||
119 | return; |
||
120 | } |
||
121 | |||
122 | // Reject messages that do not provide a reading pin. |
||
123 | if (!doc.containsKey("pin")) { |
||
124 | Serial.println("MQTT message received but no pin supplied..."); |
||
125 | return; |
||
126 | } |
||
127 | |||
128 | const int pin = (const int)doc["pin"]; |
||
129 | |||
130 | StaticJsonDocument<256> msg; |
||
6 | office | 131 | msg["id"] = String(MQTT_CLIENT_ID().c_str()); |
5 | office | 132 | DHT_Unified dht(PINS[pin], DHTTYPE); |
133 | dht.begin(); |
||
134 | // Print temperature sensor details. |
||
135 | sensors_event_t event; |
||
136 | dht.temperature().getEvent(&event); |
||
137 | switch (!isnan(event.temperature)) { |
||
138 | case true: |
||
139 | msg["temperature"] = event.temperature; |
||
140 | break; |
||
141 | default: |
||
142 | Serial.println("Error reading temperature..."); |
||
143 | break; |
||
144 | } |
||
145 | |||
146 | dht.humidity().getEvent(&event); |
||
147 | switch (!isnan(event.relative_humidity)) { |
||
148 | case true: |
||
149 | msg["humidity"] = event.relative_humidity; |
||
150 | break; |
||
151 | default: |
||
152 | Serial.println("Error reading humidity..."); |
||
153 | break; |
||
154 | } |
||
155 | // Eeek? |
||
156 | //dht.end(); |
||
157 | |||
158 | // Publish the sensor data. |
||
159 | mqttClient.publish(MQTT_TOPIC().c_str(), mqttSerialize(msg)); |
||
160 | } |
||
161 | |||
162 | bool mqttConnect() { |
||
163 | Serial.println("Attempting to connect to MQTT broker: " + String(mqtt_host)); |
||
164 | mqttClient.setServer(mqtt_host, mqtt_port); |
||
165 | |||
166 | StaticJsonDocument<255> msg; |
||
167 | if (mqttClient.connect(MQTT_CLIENT_ID().c_str(), mqtt_username, mqtt_password)) { |
||
168 | Serial.println("Established connection with MQTT broker using client ID: " + MQTT_CLIENT_ID()); |
||
169 | mqttClient.setCallback(mqttCallback); |
||
170 | msg["action"] = "connected"; |
||
171 | mqttClient.publish(MQTT_TOPIC().c_str(), mqttSerialize(msg)); |
||
172 | Serial.println("Attempting to subscribe to MQTT topic: " + MQTT_TOPIC()); |
||
173 | if (!mqttClient.subscribe(MQTT_TOPIC().c_str())) { |
||
174 | Serial.println("Failed to subscribe to MQTT topic: " + MQTT_TOPIC()); |
||
175 | return false; |
||
176 | } |
||
177 | Serial.println("Subscribed to MQTT topic: " + MQTT_TOPIC()); |
||
178 | msg.clear(); |
||
179 | msg["action"] = "subscribed"; |
||
180 | mqttClient.publish(MQTT_TOPIC().c_str(), mqttSerialize(msg)); |
||
181 | return true; |
||
182 | } |
||
183 | else { |
||
184 | Serial.println("Connection to MQTT broker failed with MQTT client state: " + String(mqttClient.state())); |
||
185 | } |
||
186 | |||
187 | return false; |
||
188 | } |
||
189 | |||
190 | bool loopWifiConnected() { |
||
191 | // Process OTA loop first since emergency OTA updates might be needed. |
||
192 | ArduinoOTA.handle(); |
||
193 | |||
194 | // Process MQTT client loop. |
||
195 | if (!mqttClient.connected()) { |
||
196 | // If the connection to the MQTT broker has failed then sleep before carrying on. |
||
197 | if (!mqttConnect()) { |
||
198 | return false; |
||
199 | } |
||
200 | } |
||
201 | mqttClient.loop(); |
||
202 | |||
203 | return true; |
||
204 | } |
||
205 | |||
206 | void setup() { |
||
207 | Serial.begin(115200); |
||
208 | Serial.println("Booted, setting up Wifi in 10s..."); |
||
209 | delay(10000); |
||
210 | |||
211 | WiFi.mode(WIFI_STA); |
||
212 | #if defined(ARDUINO_ARCH_ESP8266) |
||
213 | WiFi.hostname(HOSTNAME().c_str()); |
||
214 | #elif defined(ARDUINO_ARCH_ESP32) |
||
215 | WiFi.setHostname(HOSTNAME().c_str()); |
||
216 | #endif |
||
217 | WiFi.begin(sta_ssid, sta_psk); |
||
14 | office | 218 | uint8_t result = WiFi.waitForConnectResult(); |
219 | while (result != WL_CONNECTED) { |
||
220 | Serial.print("Failed to connect to Wifi: "); |
||
221 | Serial.println(result); |
||
222 | Serial.println("Rebooting in 5s..."); |
||
5 | office | 223 | delay(5000); |
224 | ESP.restart(); |
||
225 | } |
||
226 | |||
227 | Serial.print("Connected to Wifi: "); |
||
228 | Serial.println(WiFi.localIP()); |
||
229 | |||
230 | Serial.println("Setting up OTA in 10s..."); |
||
231 | delay(10000); |
||
232 | |||
233 | // Port defaults to 8266 |
||
234 | ArduinoOTA.setPort(ota_port); |
||
235 | |||
236 | // Hostname defaults to esp-[ChipID] |
||
237 | ArduinoOTA.setHostname(HOSTNAME().c_str()); |
||
238 | |||
239 | // Set the OTA password |
||
240 | ArduinoOTA.setPassword(ota_password); |
||
241 | |||
242 | ArduinoOTA.onStart([]() { |
||
243 | switch (ArduinoOTA.getCommand()) { |
||
244 | case U_FLASH: // Sketch |
||
245 | Serial.println("OTA start updating sketch."); |
||
246 | break; |
||
247 | #if defined(ARDUINO_ARCH_ESP8266) |
||
248 | case U_FS: |
||
249 | #elif defined(ARDUINO_ARCH_ESP32) |
||
250 | case U_SPIFFS: |
||
251 | #endif |
||
252 | Serial.println("OTA start updating filesystem."); |
||
253 | SPIFFS.end(); |
||
254 | break; |
||
255 | default: |
||
256 | Serial.println("Unknown OTA update type."); |
||
257 | break; |
||
258 | } |
||
259 | }); |
||
260 | ArduinoOTA.onEnd([]() { |
||
261 | Serial.println("OTA update complete."); |
||
262 | SPIFFS.begin(); |
||
263 | #if defined(ARDUINO_ARCH_ESP8266) |
||
264 | // For what it's worth, check the filesystem on ESP8266. |
||
265 | SPIFFS.check(); |
||
266 | #endif |
||
267 | ESP.restart(); |
||
268 | }); |
||
269 | ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { |
||
270 | Serial.printf("OTA update progress: %u%%\r", (progress / (total / 100))); |
||
271 | }); |
||
272 | ArduinoOTA.onError([](ota_error_t error) { |
||
273 | Serial.printf("OTA update error [%u]: ", error); |
||
274 | switch (error) { |
||
275 | case OTA_AUTH_ERROR: |
||
276 | Serial.println("OTA authentication failed"); |
||
277 | break; |
||
278 | case OTA_BEGIN_ERROR: |
||
279 | Serial.println("OTA begin failed"); |
||
280 | break; |
||
281 | case OTA_CONNECT_ERROR: |
||
282 | Serial.println("OTA connect failed"); |
||
283 | break; |
||
284 | case OTA_RECEIVE_ERROR: |
||
285 | Serial.println("OTA receive failed"); |
||
286 | break; |
||
287 | case OTA_END_ERROR: |
||
288 | Serial.println("OTA end failed"); |
||
289 | break; |
||
290 | default: |
||
291 | Serial.println("Unknown OTA failure"); |
||
292 | break; |
||
293 | } |
||
294 | ESP.restart(); |
||
295 | }); |
||
296 | ArduinoOTA.begin(); |
||
297 | |||
298 | // Set up MQTT client. |
||
299 | mqttClient.setServer(mqtt_host, mqtt_port); |
||
300 | mqttClient.setCallback(mqttCallback); |
||
301 | |||
302 | // Touchdown. |
||
303 | Serial.println("Setup complete."); |
||
304 | } |
||
305 | |||
306 | void loop() { |
||
307 | // Check the Wifi connection status. |
||
308 | int wifiStatus = WiFi.status(); |
||
309 | switch (wifiStatus) { |
||
310 | case WL_CONNECTED: |
||
311 | if (!loopWifiConnected()) { |
||
312 | delay(1000); |
||
313 | break; |
||
314 | } |
||
315 | delay(1); |
||
316 | break; |
||
317 | case WL_NO_SHIELD: |
||
318 | Serial.println("No Wifi shield present."); |
||
319 | goto DEFAULT_CASE; |
||
320 | break; |
||
321 | case WL_NO_SSID_AVAIL: |
||
322 | Serial.println("Configured SSID not found."); |
||
323 | goto DEFAULT_CASE; |
||
324 | break; |
||
325 | // Temporary statuses indicating transitional states. |
||
326 | case WL_IDLE_STATUS: |
||
327 | case WL_SCAN_COMPLETED: |
||
328 | delay(1000); |
||
329 | break; |
||
330 | // Fatal Wifi statuses trigger a delayed ESP restart. |
||
331 | case WL_CONNECT_FAILED: |
||
332 | case WL_CONNECTION_LOST: |
||
333 | case WL_DISCONNECTED: |
||
334 | default: |
||
335 | Serial.println("Wifi connection failed with status: " + String(wifiStatus)); |
||
336 | DEFAULT_CASE: |
||
337 | delay(10000); |
||
338 | ESP.restart(); |
||
339 | break; |
||
340 | } |
||
341 | } |