-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsensory.ino
618 lines (527 loc) · 16.5 KB
/
sensory.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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
#include "user_config.h"
#include <ArduinoMqttClient.h>
#include <WiFi101.h>
#include <ArduinoJson.h>
#define VERSION "1.0"
//#define USE_RTC
#ifdef USE_RTC
#include <RTCZero.h>
#endif
#define USE_WDT
#ifdef USE_WDT
#include <Adafruit_SleepyDog.h>
#define WDT_INTERVAL_MS 180000 //3 minutes
#endif
#define REPORT_INTERVAL_MS REPORT_INTERVAL_S * 1000
#ifdef USE_BMP280
#include <Adafruit_BMP280.h>
#undef REPORT_HUMIDITY
#elif defined( USE_SHT31 )
#include <Adafruit_SHT31.h>
#undef REPORT_PRESSURE
#endif
#ifdef REPORT_VOLTAGE
#ifndef VOLTAGE_PIN
#define VOLTAGE_PIN A7
#endif
#endif
#define LED_STATUS_PIN 13
#define MAX_CONN_ATTEMPTS 5
#ifdef REPORT_TEMPERATURE
#define MQTT_TOPIC_CONFIG_TEMPERATURE "homeassistant/sensor/" SENSOR_NAME "_T/config"
#endif
#ifdef REPORT_VOLTAGE
#define MQTT_TOPIC_CONFIG_VOLTAGE "homeassistant/sensor/" SENSOR_NAME "_V/config"
#endif
#ifdef REPORT_HUMIDITY
#define MQTT_TOPIC_CONFIG_HUMIDITY "homeassistant/sensor/" SENSOR_NAME "_H/config"
#endif
#ifdef REPORT_PRESSURE
#define MQTT_TOPIC_CONFIG_PRESSURE "homeassistant/sensor/" SENSOR_NAME "_P/config"
#endif
#ifdef REPORT_MEMORY
extern "C" char* sbrk(int incr);
#define MQTT_TOPIC_CONFIG_MEMORY "homeassistant/sensor/" SENSOR_NAME "_M/config"
#endif
#define MQTT_TOPIC_STATE "homeassistant/sensor/" SENSOR_NAME "/state"
//=============================================================================
//Globals
//=============================================================================
#ifdef USE_RTC
RTCZero rtc;
#endif
//Wifi globals
char ssid[] = SECRET_SSID;
char pass[] = SECRET_PASS;
int wifi_status = WL_IDLE_STATUS;
//Sensor globals
#ifdef USE_BMP280
Adafruit_BMP280 sensor;
#elif defined( USE_SHT31 )
Adafruit_SHT31 sensor;
#endif
bool alt_address = false;
#ifdef USE_ALT_ADDRESS
alt_address = true;
#endif
bool use_metric = true;
//MQTT globals
char mqtt_server[] = MQTT_SERVER;
int mqtt_port = MQTT_PORT;
char mqtt_username[] = MQTT_USERNAME;
char mqtt_password[] = MQTT_PASSWORD;
#ifdef REPORT_TEMPERATURE
char mqtt_topic_config_temperature[] = MQTT_TOPIC_CONFIG_TEMPERATURE;
#endif
#ifdef REPORT_VOLTAGE
char mqtt_topic_config_voltage[] = MQTT_TOPIC_CONFIG_VOLTAGE;
#endif
#ifdef REPORT_HUMIDITY
char mqtt_topic_config_humidity[] = MQTT_TOPIC_CONFIG_HUMIDITY;
#endif
#ifdef REPORT_PRESSURE
char mqtt_topic_config_pressure[] = MQTT_TOPIC_CONFIG_PRESSURE;
#endif
#ifdef REPORT_MEMORY
char mqtt_topic_config_memory[] = MQTT_TOPIC_CONFIG_MEMORY;
#endif
char mqtt_topic_state[] = MQTT_TOPIC_STATE;
char sensor_name[] = SENSOR_NAME;
char sensor_name_nice[] = SENSOR_NAME_NICE;
WiFiClient wifi_client;
MqttClient mqtt_client( wifi_client );
//=============================================================================
//Main block
//=============================================================================
void setup() {
delay( 3000 );
setup_serial( false );
Serial.println( "Booting" );
#ifdef USE_METRIC
use_metric = true;
#else
use_metric = false;
#endif
#ifdef USE_BMP280
if ( !sensor.begin( alt_address ? BMP280_ADDRESS_ALT : BMP280_ADDRESS ) ) {
Serial.println( "Could not find a valid BMP280 sensor" );
delay( 1000 );
}
Serial.println( "Set up BMP280 sensor" );
sensor.setSampling( Adafruit_BMP280::MODE_FORCED, Adafruit_BMP280::SAMPLING_X2, Adafruit_BMP280::SAMPLING_X16, Adafruit_BMP280::FILTER_X16, Adafruit_BMP280::STANDBY_MS_500 );
#elif defined( USE_SHT31 )
if ( !sensor.begin( alt_address ? 0x45 : SHT31_DEFAULT_ADDR ) ) {
Serial.println( "Could not find a valid SHT31 sensor" );
delay( 1000 );
}
Serial.println( "Set up SHT31 sensor" );
sensor.heater( false );
#endif
//For Adafruit ATWINC1500
WiFi.setPins( 8, 7, 4, 2 );
if ( WiFi.status() == WL_NO_SHIELD ) {
while ( true ) {
delay( 30000 );
Serial.println( "No wifi detected" );
}
}
byte mac_addr[6];
WiFi.macAddress( mac_addr );
char mac_addr_str[18];
snprintf( mac_addr_str, sizeof( mac_addr_str ), "%x:%x:%x:%x:%x:%x", mac_addr[5], mac_addr[4], mac_addr[3], mac_addr[2], mac_addr[1], mac_addr[0] );
mac_addr_str[sizeof( mac_addr_str ) - 1] = '\0';
Serial.print( "Wifi MAC: " );
Serial.println( mac_addr_str );
//Set LED pin to indicate activity
pinMode( LED_STATUS_PIN, OUTPUT );
#ifdef USE_RTC
rtc.begin();
rtc.setEpoch( 0 );
#endif
#ifdef USE_WDT
Watchdog.enable( WDT_INTERVAL_MS );
if ( setup_wifi() ) {
if ( setup_mqtt() ) {
send_config();
}
}
Watchdog.disable();
#endif
Serial.println( "Boot done" );
}
void loop() {
#ifdef USE_WDT
Watchdog.enable( WDT_INTERVAL_MS );
#endif
#ifdef REPORT_TEMPERATURE
double temperature = NAN;
#endif
#ifdef REPORT_VOLTAGE
double voltage = NAN;
#endif
#ifdef REPORT_HUMIDITY
double humidity = NAN;
#endif
#ifdef REPORT_PRESSURE
double pressure = NAN;
#endif
#ifdef REPORT_MEMORY
double memory = NAN;
#endif
StaticJsonDocument<512> json_doc;
digitalWrite( LED_STATUS_PIN, HIGH );
delay( 1000 );
#ifdef USE_RTC
rtc.disableAlarm();
#endif
if ( !Serial ) {
setup_serial( false );
}
wifi_status = WiFi.status();
if ( wifi_status != WL_CONNECTED ) {
Serial.println( "Connection lost" );
mqtt_client.stop();
WiFi.end();
wifi_status = WL_IDLE_STATUS;
setup_wifi();
}
if ( wifi_status == WL_CONNECTED && !mqtt_client.connected() ) {
if ( setup_mqtt() ) {
send_config();
}
}
if ( mqtt_client.connected() ) {
#ifdef REPORT_TEMPERATURE
read_temperature( &temperature );
if ( !isnan( temperature ) ) {
temperature = round_double( temperature, 2 );
json_doc["temperature"] = temperature;
}
#endif
#ifdef REPORT_VOLTAGE
read_voltage( &voltage );
if ( !isnan( voltage ) ) {
voltage = round_double( voltage, 1 );
json_doc["voltage"] = voltage;
}
#endif
#ifdef REPORT_HUMIDITY
read_humidity( &humidity );
if ( !isnan( humidity ) ) {
humidity = round_double( humidity, 2 );
json_doc["humidity"] = humidity;
}
#endif
#ifdef REPORT_PRESSURE
read_pressure( &pressure );
if ( !isnan( pressure ) ) {
pressure = round_double( pressure, 2 );
json_doc["pressure"] = pressure;
}
#endif
#ifdef REPORT_MEMORY
read_memory( &memory );
if ( !isnan( memory ) ) {
memory = round_double( memory, 2 );
json_doc["memory"] = memory;
}
#endif
if ( !json_doc.isNull() ) {
send_json( mqtt_topic_state, &json_doc, false );
}
}
digitalWrite( LED_STATUS_PIN, LOW );
#ifdef USE_RTC
rtc.setAlarmEpoch( rtc.getEpoch() + REPORT_INTERVAL_S );
rtc.enableAlarm( rtc.MATCH_YYMMDDHHMMSS );
rtc.standbyMode();
#else
#ifdef USE_WDT
Watchdog.disable();
#endif
delay( REPORT_INTERVAL_MS );
#endif
}
//=============================================================================
//Setup functions
//=============================================================================
bool setup_wifi() {
int tries = 0;
while ( wifi_status != WL_CONNECTED && tries < MAX_CONN_ATTEMPTS ) {
tries++;
WiFi.end();
Serial.print( "Connecting to SSID: " );
Serial.println( ssid );
wifi_status = WiFi.begin( ssid, pass );
delay( 10000 );
}
if ( wifi_status != WL_CONNECTED ) {
Serial.println( "Failed to connect to SSID" );
return false;
}
Serial.println( "Connected to SSID" );
WiFi.maxLowPowerMode();
IPAddress addr = WiFi.localIP();
char buf[16];
IPAddress_to_cstr( addr, buf, sizeof( buf ) );
Serial.print( "Wifi IP: " );
Serial.println( buf );
return true;
}
bool setup_mqtt() {
int tries = 0;
Serial.print( "Connecting to broker: " );
Serial.println( mqtt_server );
mqtt_client.setId( sensor_name );
mqtt_client.setUsernamePassword( mqtt_username, mqtt_password );
mqtt_client.setKeepAliveInterval( 600 ); //Default to 10 minutes or double the default report interval
while ( !mqtt_client.connect( mqtt_server, mqtt_port ) && tries < MAX_CONN_ATTEMPTS ) {
tries++;
Serial.print( "Error: " );
Serial.println( mqtt_client.connectError() );
delay( 10000 );
}
if ( tries >= MAX_CONN_ATTEMPTS ) {
Serial.println( "Failed to connect to broker" );
return false;
}
return true;
}
void setup_serial( bool blocking ) {
Serial.begin( 115200 );
if ( blocking ) {
while ( !Serial ) {
;
}
}
}
//=============================================================================
//MQTT functions
//=============================================================================
bool mqtt_publish( MqttClient *client, char *topic, char *buf, bool retain = false, uint8_t qos = 0, bool dup = false ) {
int ret = 0;
ret = client->beginMessage( topic, strlen( buf ), retain, qos, dup );
if ( ret == 1 ) {
client->print( buf );
ret = client->endMessage();
}
return ( ret == 1 );
}
void mqtt_publish_config( MqttClient *client, char *topic, char *buf ) {
bool ret = mqtt_publish( client, topic, buf, true, 0, false );
if ( !ret ) {
Serial.print( "Failed to publish config: " );
Serial.println( buf );
}
else {
Serial.print( "Published config: " );
Serial.println( buf );
}
}
void send_config() {
StaticJsonDocument<512> json_doc;
#ifdef REPORT_TEMPERATURE
build_config_temperature( &json_doc );
send_json( mqtt_topic_config_temperature, &json_doc, true );
json_doc.clear();
#endif
#ifdef REPORT_VOLTAGE
build_config_voltage( &json_doc );
send_json( mqtt_topic_config_voltage, &json_doc, true );
json_doc.clear();
#endif
#ifdef REPORT_HUMIDITY
build_config_humidity( &json_doc );
send_json( mqtt_topic_config_humidity, &json_doc, true );
json_doc.clear();
#endif
#ifdef REPORT_PRESSURE
build_config_pressure( &json_doc );
send_json( mqtt_topic_config_pressure, &json_doc, true );
json_doc.clear();
#endif
#ifdef REPORT_MEMORY
build_config_memory( &json_doc );
send_json( mqtt_topic_config_memory, &json_doc, true );
json_doc.clear();
#endif
}
void send_json( char *topic, JsonDocument *document, bool config ) {
int buf_size = 512;
char buf[buf_size];
if ( topic == NULL || strlen( topic ) == 0 || document == NULL ) {
Serial.println( "Failed to publish: null" );
return;
}
serializeJson( *document, buf, buf_size );
if ( config ) {
mqtt_publish_config( &mqtt_client, topic, buf );
}
else {
if ( !mqtt_publish( &mqtt_client, topic, buf, false, 0, false ) ) {
Serial.print( "Failed to publish state: " );
Serial.println( buf );
}
else {
Serial.print( "Published: " );
Serial.println( buf );
}
}
}
//=============================================================================
//Utility functions
//=============================================================================
double round_double( double number, int decimals ) {
double factor = pow( 10, decimals );
return round( number * factor ) / factor;
}
bool IPAddress_to_cstr( IPAddress addr, char* buf, int buf_size ) {
if ( buf_size < 16 ) {
return false;
}
uint8_t octet[4];
for ( int i = 0; i < 4; i++ ) {
octet[i] = addr >> ( i * 8 );
}
snprintf( buf, buf_size, "%d.%d.%d.%d", octet[0], octet[1], octet[2], octet[3] );
return true;
}
void build_config_device( JsonDocument *document ) {
(*document)["device"]["name"] = sensor_name_nice;
(*document)["device"]["identifiers"] = sensor_name;
(*document)["device"]["manufacturer"] = "fullburnen";
(*document)["device"]["model"] = "Sensory";
(*document)["device"]["sw_version"] = VERSION;
}
//=============================================================================
//Sensor functions
//=============================================================================
#ifdef REPORT_TEMPERATURE
void build_config_temperature( JsonDocument *document ) {
(*document)["unique_id"] = String( sensor_name ) + "_temp";
(*document)["state_topic"] = "homeassistant/sensor/" + String( sensor_name ) + "/state";
(*document)["name"] = String( sensor_name_nice ) + " Temperature";
(*document)["device_class"] = "temperature";
if ( use_metric ) {
(*document)["unit_of_measurement"] = "°C";
}
else {
(*document)["unit_of_measurement"] = "°F";
}
(*document)["value_template"] = "{{ value_json.temperature }}";
build_config_device( document );
}
void read_temperature( double* temperature ) {
double temperature_c = NAN;
*temperature = NAN;
#ifdef USE_BMP280
if ( sensor.takeForcedMeasurement() ) {
temperature_c = ( double )sensor.readTemperature();
}
#elif defined( USE_SHT31 )
temperature_c = sensor.readTemperature();
#endif
if ( !isnan( temperature_c ) ) {
if ( use_metric ) {
*temperature = temperature_c;
}
else {
*temperature = temperature_c * 9 / 5 + 32;
}
}
if ( isnan( *temperature ) ) {
Serial.println( "Unable to take temperature measurement" );
}
}
#endif
#ifdef REPORT_VOLTAGE
void build_config_voltage( JsonDocument *document ) {
(*document)["unique_id"] = String( sensor_name ) + "_voltage";
(*document)["state_topic"] = "homeassistant/sensor/" + String( sensor_name ) + "/state";
(*document)["name"] = String( sensor_name_nice ) + " Voltage";
(*document)["device_class"] = "voltage";
(*document)["unit_of_measurement"] = "V";
(*document)["value_template"] = "{{ value_json.voltage }}";
build_config_device( document );
}
void read_voltage( double* voltage_v ) {
*voltage_v = ( double )analogRead( VOLTAGE_PIN );
*voltage_v = *voltage_v * 2 * 3.3 / 1024;
}
#endif
#ifdef REPORT_HUMIDITY
void build_config_humidity( JsonDocument *document ) {
(*document)["unique_id"] = String( sensor_name ) + "_humidity";
(*document)["state_topic"] = "homeassistant/sensor/" + String( sensor_name ) + "/state";
(*document)["name"] = String( sensor_name_nice ) + " Humidity";
(*document)["device_class"] = "humidity";
(*document)["unit_of_measurement"] = "%";
(*document)["value_template"] = "{{ value_json.humidity }}";
build_config_device( document );
}
void read_humidity( double* humidity ) {
*humidity = NAN;
#ifdef USE_SHT31
*humidity = sensor.readHumidity();
#endif
if ( isnan( *humidity ) ) {
Serial.println( "Unable to take humidity measurement" );
}
}
#endif
#ifdef REPORT_PRESSURE
void build_config_pressure( JsonDocument *document ) {
(*document)["unique_id"] = String( sensor_name ) + "_pressure";
(*document)["state_topic"] = "homeassistant/sensor/" + String( sensor_name ) + "/state";
(*document)["name"] = String( sensor_name_nice ) + " Pressure";
(*document)["device_class"] = "pressure";
if ( use_metric ) {
(*document)["unit_of_measurement"] = "hPa";
}
else {
(*document)["unit_of_measurement"] = "inHg";
}
(*document)["value_template"] = "{{ value_json.pressure }}";
build_config_device( document );
}
void read_pressure( double* pressure ) {
double pressure_pa = NAN;
*pressure = NAN;
#ifdef USE_BMP280
pressure_pa = sensor.readPressure();
#endif
if ( !isnan( pressure_pa ) ) {
if ( use_metric ) {
*pressure = pressure_pa / 100;
}
else {
*pressure = pressure_pa / 3386.389;
}
}
if ( isnan( *pressure ) ) {
Serial.println( "Unable to take pressure measurement" );
}
}
#endif
#ifdef REPORT_MEMORY
void build_config_memory( JsonDocument *document ) {
(*document)["unique_id"] = String( sensor_name ) + "_memory";
(*document)["state_topic"] = "homeassistant/sensor/" + String( sensor_name ) + "/state";
(*document)["name"] = String( sensor_name_nice ) + " Memory";
(*document)["unit_of_measurement"] = "bytes";
(*document)["value_template"] = "{{ value_json.memory }}";
build_config_device( document );
}
void read_memory( double* memory ) {
double memory_b = NAN;
*memory = NAN;
char top;
memory_b = &top - reinterpret_cast<char *>( sbrk( 0 ) );
if ( !isnan( memory_b ) ) {
*memory = memory_b;
}
if ( isnan( *memory ) ) {
Serial.println( "Unable to take memory measurement" );
}
}
#endif