arduino-sketches – Diff between revs 8 and 17

Subversion Repositories:
Rev:
Show entire fileIgnore whitespace
Rev 8 Rev 17
Line 1... Line 1...
1 /*************************************************************************/ 1 /*************************************************************************/
2 /* Copyright (C) 2022 Wizardry and Steamworks - License: GNU GPLv3 */ 2 /* Copyright (C) 2023 Wizardry and Steamworks - License: GNU GPLv3 */
3 /*************************************************************************/ 3 /*************************************************************************/
Line -... Line 4...
-   4  
-   5 // Removing comment for debugging over the first serial port.
4   6 // #define DEBUG 1
5 // The AP to connect to via Wifi. 7 // The AP to connect to via Wifi.
6 #define STA_SSID "" 8 #define STA_SSID ""
7 // The AP Wifi password. 9 // The AP Wifi password.
8 #define STA_PSK "" 10 #define STA_PSK ""
Line 27... Line 29...
27   29  
28 // Platform specific defines. 30 // Platform specific defines.
29 #if defined(ARDUINO_ARCH_ESP8266) 31 #if defined(ARDUINO_ARCH_ESP8266)
30 #define GET_CHIP_ID() (ESP.getChipId()) 32 #define GET_CHIP_ID() (ESP.getChipId())
31 #elif defined(ARDUINO_ARCH_ESP32) 33 #elif defined(ARDUINO_ARCH_ESP32)
32 #define GET_CHIP_ID() ((uint16_t)(ESP.getEfuseMac()>>32)) 34 #define GET_CHIP_ID() ((uint16_t)(ESP.getEfuseMac() >> 32))
Line 33... Line 35...
33 #endif 35 #endif
34   36  
35 // Miscellaneous defines. 37 // Miscellaneous defines.
Line 52... Line 54...
52 #if defined(ARDUINO_ARCH_ESP32) 54 #if defined(ARDUINO_ARCH_ESP32)
53 #include <FS.h> 55 #include <FS.h>
54 #include <SPIFFS.h> 56 #include <SPIFFS.h>
55 #endif 57 #endif
Line 56... Line -...
56   -  
57 const char *sta_ssid = STA_SSID; -  
58 const char *sta_psk = STA_PSK; -  
59 const char *mqtt_host = MQTT_HOST; -  
60 const char *mqtt_username = MQTT_USERNAME; -  
61 const char *mqtt_password = MQTT_PASSWORD; -  
62 const int mqtt_port = MQTT_PORT; -  
63 const char *ota_password = OTA_PASSWORD; -  
64 const int ota_port = OTA_PORT; -  
65   58  
66 WiFiClient espClient; 59 WiFiClient espClient;
Line 67... Line 60...
67 PubSubClient mqttClient(espClient); 60 PubSubClient mqttClient(espClient);
68   61  
69 // Define GPIO pins for supported architectures. 62 // Define GPIO pins for supported architectures.
70 #if defined(ARDUINO_ARCH_ESP8266) 63 #if defined(ARDUINO_ARCH_ESP8266)
71 int PINS[] = { D0, D1, D2, D3, D4, D5, D6, D7, D8 }; 64 int PINS[] = { D0, D1, D2, D3, D4, D5, D6, D7, D8 };
72 #elif defined(ARDUINO_ARCH_ESP32) 65 #elif defined(ARDUINO_ARCH_ESP32)
73 int PINS[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 66 int PINS[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
74 12, 13, 14, 15, 16, 17, 18, 19, 21, 22, 67 12, 13, 14, 15, 16, 17, 18, 19, 21, 22,
75 23, 25, 26, 27, 32, 33, 34, 35, 36, 37, -  
76 38, 39 68 23, 25, 26, 27, 32, 33, 34, 35, 36, 37,
Line 77... Line 69...
77 }; 69 38, 39 };
78 #endif 70 #endif
79   71  
Line 86... Line 78...
86 void mqttCallback(char *topic, byte *payload, unsigned int length) { 78 void mqttCallback(char *topic, byte *payload, unsigned int length) {
87 String msgTopic = String(topic); 79 String msgTopic = String(topic);
88 // payload is not null terminated and casting will not work 80 // payload is not null terminated and casting will not work
89 char msgPayload[length + 1]; 81 char msgPayload[length + 1];
90 snprintf(msgPayload, length + 1, "%s", payload); 82 snprintf(msgPayload, length + 1, "%s", payload);
-   83 #ifdef DEBUG
91 Serial.println("Message received on topic: " + String(topic) + " with payload: " + String(msgPayload)); 84 Serial.println("Message received on topic: " + String(topic) + " with payload: " + String(msgPayload));
-   85 #endif
Line 92... Line 86...
92   86  
93 // Parse the payload sent to the MQTT topic as a JSON document. 87 // Parse the payload sent to the MQTT topic as a JSON document.
-   88 StaticJsonDocument<256> doc;
94 StaticJsonDocument<256> doc; 89 #ifdef DEBUG
-   90 Serial.println("Deserializing message....");
95 Serial.println("Deserializing message...."); 91 #endif
96 DeserializationError error = deserializeJson(doc, msgPayload); 92 DeserializationError error = deserializeJson(doc, msgPayload);
-   93 if (error) {
97 if (error) { 94 #ifdef DEBUG
-   95 Serial.println("Failed to parse MQTT payload as JSON: " + String(error.c_str()));
98 Serial.println("Failed to parse MQTT payload as JSON: " + String(error.c_str())); 96 #endif
99 return; 97 return;
Line 100... Line 98...
100 } 98 }
101   99  
102 // Do not process messages without an action key. 100 // Do not process messages without an action key.
103 if (!doc.containsKey("action")) { 101 if (!doc.containsKey("action")) {
Line 104... Line 102...
104 return; 102 return;
105 } 103 }
106   104  
107 String action = (const char *)doc["action"]; 105 String action = (const char *)doc["action"];
108 if(action == "set") { 106 if (action == "set") {
109 String state = (const char *)doc["state"]; 107 String state = (const char *)doc["state"];
110 const int pin = (const int)doc["pin"]; 108 const int pin = (const int)doc["pin"];
111   109 #ifdef DEBUG
112 Serial.println("Setting pin: " + String(pin) + " to state: " + String(state)); -  
113   -  
114 pinMode(PINS[pin], OUTPUT); -  
115   -  
116 if (state == "on") { -  
117 digitalWrite(PINS[pin], HIGH); -  
118 int status = digitalRead(PINS[pin]); -  
Line -... Line 110...
-   110 Serial.println("Setting pin: " + String(pin) + " to state: " + String(state));
119 Serial.println("Pin " + String(pin) + " state is now: " + String(status)); 111 #endif
120 return; 112 pinMode(PINS[pin], OUTPUT);
-   113  
121 } 114 if (state == "on") {
-   115 digitalWrite(PINS[pin], HIGH);
122   116 int status = digitalRead(PINS[pin]);
123 digitalWrite(PINS[pin], LOW); 117 #ifdef DEBUG
124 int status = digitalRead(PINS[pin]); -  
125 Serial.println("Pin " + String(pin) + " state is now: " + String(status)); -  
126 return; -  
127 } -  
128   -  
Line -... Line 118...
-   118 Serial.println("Pin " + String(pin) + " state is now: " + String(status));
129 if(action == "get") { 119 #endif
-   120 return;
130 const int pin = (const int)doc["pin"]; 121 }
-   122  
-   123 digitalWrite(PINS[pin], LOW);
-   124 int status = digitalRead(PINS[pin]);
Line -... Line 125...
-   125 #ifdef DEBUG
-   126 Serial.println("Pin " + String(pin) + " state is now: " + String(status));
-   127 #endif
-   128 return;
-   129 }
-   130  
-   131 if (action == "get") {
-   132 const int pin = (const int)doc["pin"];
-   133 #ifdef DEBUG
131   134 Serial.println("Getting pin: " + String(pin) + " state.");
132 Serial.println("Getting pin: " + String(pin) + " state."); 135 #endif
133   136 int status = digitalRead(PINS[pin]);
134 int status = digitalRead(PINS[pin]); 137 #ifdef DEBUG
135 Serial.println("Pin " + String(pin) + " state is now: " + String(status)); 138 Serial.println("Pin " + String(pin) + " state is now: " + String(status));
136   139 #endif
137 // Announce the action. 140 // Announce the action.
138 StaticJsonDocument<256> msg; 141 StaticJsonDocument<256> msg;
139 msg["pin"] = pin; 142 msg["pin"] = pin;
140 switch(status) { 143 switch (status) {
141 case 1: 144 case 1:
142 msg["state"] = "on"; 145 msg["state"] = "on";
143 break; 146 break;
144 case 0: 147 case 0:
Line 145... Line 148...
145 msg["state"] = "off"; 148 msg["state"] = "off";
146 break; 149 break;
147 default: 150 default:
148 msg["state"] = "unknown"; 151 msg["state"] = "unknown";
Line 149... Line 152...
149 break; 152 break;
-   153 }
150 } 154  
-   155 mqttClient.publish(MQTT_TOPIC().c_str(), mqttSerialize(msg).c_str());
151   156 return;
Line 152... Line 157...
152 mqttClient.publish(MQTT_TOPIC().c_str(), mqttSerialize(msg).c_str()); 157 }
153 return; 158 }
-   159  
154 } 160 bool mqttConnect() {
-   161 #ifdef DEBUG
155 } 162 Serial.println("Attempting to connect to MQTT broker: " + String(MQTT_HOST));
156   163 #endif
157 bool mqttConnect() { 164 mqttClient.setServer(MQTT_HOST, MQTT_PORT);
-   165  
158 Serial.println("Attempting to connect to MQTT broker: " + String(mqtt_host)); 166 StaticJsonDocument<256> msg;
-   167 if (mqttClient.connect(MQTT_CLIENT_ID().c_str(), MQTT_USERNAME, MQTT_PASSWORD)) {
159 mqttClient.setServer(mqtt_host, mqtt_port); 168 #ifdef DEBUG
-   169 Serial.println("Established connection with MQTT broker using client ID: " + MQTT_CLIENT_ID());
160   170 #endif
-   171 mqttClient.setCallback(mqttCallback);
161 StaticJsonDocument<256> msg; 172 msg["action"] = "connected";
162 if (mqttClient.connect(MQTT_CLIENT_ID().c_str(), mqtt_username, mqtt_password)) { 173 mqttClient.publish(MQTT_TOPIC().c_str(), mqttSerialize(msg).c_str());
-   174 #ifdef DEBUG
163 Serial.println("Established connection with MQTT broker using client ID: " + MQTT_CLIENT_ID()); 175 Serial.println("Attempting to subscribe to MQTT topic: " + MQTT_TOPIC());
-   176 #endif
164 mqttClient.setCallback(mqttCallback); 177 if (!mqttClient.subscribe(MQTT_TOPIC().c_str())) {
165 msg["action"] = "connected"; 178 #ifdef DEBUG
166 mqttClient.publish(MQTT_TOPIC().c_str(), mqttSerialize(msg).c_str()); 179 Serial.println("Failed to subscribe to MQTT topic: " + MQTT_TOPIC());
167 Serial.println("Attempting to subscribe to MQTT topic: " + MQTT_TOPIC()); 180 #endif
168 if (!mqttClient.subscribe(MQTT_TOPIC().c_str())) { 181 return false;
169 Serial.println("Failed to subscribe to MQTT topic: " + MQTT_TOPIC()); 182 }
170 return false; 183 #ifdef DEBUG
171 } 184 Serial.println("Subscribed to MQTT topic: " + MQTT_TOPIC());
172 Serial.println("Subscribed to MQTT topic: " + MQTT_TOPIC()); 185 #endif
173 msg.clear(); 186 msg.clear();
Line 174... Line 187...
174 msg["action"] = "subscribed"; 187 msg["action"] = "subscribed";
175 mqttClient.publish(MQTT_TOPIC().c_str(), mqttSerialize(msg).c_str()); 188 mqttClient.publish(MQTT_TOPIC().c_str(), mqttSerialize(msg).c_str());
Line 197... Line 210...
197 return true; 210 return true;
198 } 211 }
Line 199... Line 212...
199   212  
200 void setup() { 213 void setup() {
-   214 Serial.begin(115200);
201 Serial.begin(115200); 215 #ifdef DEBUG
-   216 Serial.println("Booted, setting up Wifi in 10s...");
202 Serial.println("Booted, setting up Wifi in 10s..."); 217 #endif
Line 203... Line 218...
203 delay(10000); 218 delay(10000);
204   219  
205 WiFi.mode(WIFI_STA); 220 WiFi.mode(WIFI_STA);
206 #if defined(ARDUINO_ARCH_ESP8266) 221 #if defined(ARDUINO_ARCH_ESP8266)
207 WiFi.hostname(HOSTNAME().c_str()); 222 WiFi.hostname(HOSTNAME().c_str());
208 #elif defined(ARDUINO_ARCH_ESP32) 223 #elif defined(ARDUINO_ARCH_ESP32)
209 WiFi.setHostname(HOSTNAME().c_str()); 224 WiFi.setHostname(HOSTNAME().c_str());
210 #endif 225 #endif
-   226 WiFi.begin(STA_SSID, STA_PSK);
211 WiFi.begin(sta_ssid, sta_psk); 227 while (WiFi.waitForConnectResult() != WL_CONNECTED) {
-   228 #ifdef DEBUG
212 while (WiFi.waitForConnectResult() != WL_CONNECTED) { 229 Serial.println("Failed to connect to Wifi, rebooting in 5s...");
213 Serial.println("Failed to connect to Wifi, rebooting in 5s..."); 230 #endif
214 delay(5000); 231 delay(5000);
215 ESP.restart(); 232 ESP.restart();
216 } 233 }
-   234 #ifdef DEBUG
217   235 Serial.print("Connected to Wifi: ");
218 Serial.print("Connected to Wifi: "); 236 #endif
219 Serial.println(WiFi.localIP()); 237 Serial.println(WiFi.localIP());
-   238 #ifdef DEBUG
220   239 Serial.println("Setting up OTA in 10s...");
Line 221... Line 240...
221 Serial.println("Setting up OTA in 10s..."); 240 #endif
222 delay(10000); 241 delay(10000);
Line 223... Line 242...
223   242  
224 // Port defaults to 8266 243 // Port defaults to 8266
Line 225... Line 244...
225 ArduinoOTA.setPort(ota_port); 244 ArduinoOTA.setPort(OTA_PORT);
226   245  
Line 227... Line 246...
227 // Hostname defaults to esp-[ChipID] 246 // Hostname defaults to esp-[ChipID]
228 ArduinoOTA.setHostname(HOSTNAME().c_str()); 247 ArduinoOTA.setHostname(HOSTNAME().c_str());
229   248  
-   249 // Set the OTA password
230 // Set the OTA password 250 ArduinoOTA.setPassword(OTA_PASSWORD);
-   251  
231 ArduinoOTA.setPassword(ota_password); 252 ArduinoOTA.onStart([]() {
232   253 switch (ArduinoOTA.getCommand()) {
233 ArduinoOTA.onStart([]() { 254 case U_FLASH: // Sketch
234 switch (ArduinoOTA.getCommand()) { 255 #ifdef DEBUG
235 case U_FLASH: // Sketch 256 Serial.println("OTA start updating sketch.");
236 Serial.println("OTA start updating sketch."); 257 #endif
-   258 break;
237 break; 259 #if defined(ARDUINO_ARCH_ESP8266)
-   260 case U_FS:
238 #if defined(ARDUINO_ARCH_ESP8266) 261 #elif defined(ARDUINO_ARCH_ESP32)
239 case U_FS: 262 case U_SPIFFS:
240 #elif defined(ARDUINO_ARCH_ESP32) 263 #endif
-   264 #ifdef DEBUG
241 case U_SPIFFS: 265 Serial.println("OTA start updating filesystem.");
-   266 #endif
242 #endif 267 SPIFFS.end();
243 Serial.println("OTA start updating filesystem."); 268 break;
244 SPIFFS.end(); 269 default:
245 break; 270 #ifdef DEBUG
-   271 Serial.println("Unknown OTA update type.");
246 default: 272 #endif
-   273 break;
247 Serial.println("Unknown OTA update type."); 274 }
248 break; 275 });
249 } 276 ArduinoOTA.onEnd([]() {
250 }); 277 #ifdef DEBUG
251 ArduinoOTA.onEnd([]() { 278 Serial.println("OTA update complete.");
252 Serial.println("OTA update complete."); 279 #endif
253 SPIFFS.begin(); 280 SPIFFS.begin();
254 #if defined(ARDUINO_ARCH_ESP8266) 281 #if defined(ARDUINO_ARCH_ESP8266)
-   282 // For what it's worth, check the filesystem on ESP8266.
255 // For what it's worth, check the filesystem on ESP8266. 283 SPIFFS.check();
-   284 #endif
256 SPIFFS.check(); 285 ESP.restart();
257 #endif 286 });
-   287 ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
258 ESP.restart(); 288 #ifdef DEBUG
-   289 Serial.printf("OTA update progress: %u%%\r", (progress / (total / 100)));
259 }); 290 #endif
260 ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { 291 });
-   292 ArduinoOTA.onError([](ota_error_t error) {
261 Serial.printf("OTA update progress: %u%%\r", (progress / (total / 100))); 293 #ifdef DEBUG
-   294 Serial.printf("OTA update error [%u]: ", error);
262 }); 295 #endif
263 ArduinoOTA.onError([](ota_error_t error) { 296 switch (error) {
-   297 case OTA_AUTH_ERROR:
264 Serial.printf("OTA update error [%u]: ", error); 298 #ifdef DEBUG
-   299 Serial.println("OTA authentication failed");
265 switch (error) { 300 #endif
266 case OTA_AUTH_ERROR: 301 break;
-   302 case OTA_BEGIN_ERROR:
267 Serial.println("OTA authentication failed"); 303 #ifdef DEBUG
-   304 Serial.println("OTA begin failed");
268 break; 305 #endif
269 case OTA_BEGIN_ERROR: 306 break;
-   307 case OTA_CONNECT_ERROR:
270 Serial.println("OTA begin failed"); 308 #ifdef DEBUG
-   309 Serial.println("OTA connect failed");
271 break; 310 #endif
272 case OTA_CONNECT_ERROR: 311 break;
-   312 case OTA_RECEIVE_ERROR:
273 Serial.println("OTA connect failed"); 313 #ifdef DEBUG
-   314 Serial.println("OTA receive failed");
274 break; 315 #endif
275 case OTA_RECEIVE_ERROR: 316 break;
-   317 case OTA_END_ERROR:
276 Serial.println("OTA receive failed"); 318 #ifdef DEBUG
-   319 Serial.println("OTA end failed");
277 break; 320 #endif
278 case OTA_END_ERROR: 321 break;
279 Serial.println("OTA end failed"); 322 default:
280 break; 323 #ifdef DEBUG
281 default: 324 Serial.println("Unknown OTA failure");
Line 282... Line 325...
282 Serial.println("Unknown OTA failure"); 325 #endif
283 break; 326 break;
284 } 327 }
Line 285... Line 328...
285 ESP.restart(); 328 ESP.restart();
-   329 });
286 }); 330 ArduinoOTA.begin();
-   331  
287 ArduinoOTA.begin(); 332 // Set up MQTT client.
Line 288... Line 333...
288   333 mqttClient.setServer(MQTT_HOST, MQTT_PORT);
289 // Set up MQTT client. 334 mqttClient.setCallback(mqttCallback);
290 mqttClient.setServer(mqtt_host, mqtt_port); 335  
Line 304... Line 349...
304 break; 349 break;
305 } 350 }
306 delay(1); 351 delay(1);
307 break; 352 break;
308 case WL_NO_SHIELD: 353 case WL_NO_SHIELD:
-   354 #ifdef DEBUG
309 Serial.println("No Wifi shield present."); 355 Serial.println("No Wifi shield present.");
-   356 #endif
310 goto DEFAULT_CASE; 357 goto DEFAULT_CASE;
311 break; 358 break;
312 case WL_NO_SSID_AVAIL: 359 case WL_NO_SSID_AVAIL:
-   360 #ifdef DEBUG
313 Serial.println("Configured SSID not found."); 361 Serial.println("Configured SSID not found.");
-   362 #endif
314 goto DEFAULT_CASE; 363 goto DEFAULT_CASE;
315 break; 364 break;
316 // Temporary statuses indicating transitional states. 365 // Temporary statuses indicating transitional states.
317 case WL_IDLE_STATUS: 366 case WL_IDLE_STATUS:
318 case WL_SCAN_COMPLETED: 367 case WL_SCAN_COMPLETED:
Line 321... Line 370...
321 // Fatal Wifi statuses trigger a delayed ESP restart. 370 // Fatal Wifi statuses trigger a delayed ESP restart.
322 case WL_CONNECT_FAILED: 371 case WL_CONNECT_FAILED:
323 case WL_CONNECTION_LOST: 372 case WL_CONNECTION_LOST:
324 case WL_DISCONNECTED: 373 case WL_DISCONNECTED:
325 default: 374 default:
-   375 #ifdef DEBUG
326 Serial.println("Wifi connection failed with status: " + String(wifiStatus)); 376 Serial.println("Wifi connection failed with status: " + String(wifiStatus));
-   377 #endif
327 DEFAULT_CASE: 378 DEFAULT_CASE:
328 delay(10000); 379 delay(10000);
329 ESP.restart(); 380 ESP.restart();
330 break; 381 break;
331 } 382 }