-
Notifications
You must be signed in to change notification settings - Fork 5
/
Acurite_00592TX_Decoder_ESP32a.ino
1295 lines (1070 loc) · 45.9 KB
/
Acurite_00592TX_Decoder_ESP32a.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
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**********************************************************************
* Arduino code to decode the Acurite 00592TX wireless temperature sensor
*
* The 00592TX wireless temperature probe contains a 433.92 MHz
* wireless transmitter. The temperature from the sensor is
* sent approximately every 18 seconds. Their are three sensor
* ID's: A, B and C
*
* This device is also known as 00592TX, 06002M and 06044 and
* as other devices...
*
* The 00592TX typically sends three blocks of SYNC pulse + DATA stream
* per temperature reading. So we have three chance's of decoding a block.
*
* The 00592TX first emits a random length string of
* random width hi/lo pulses, most likeley to provide receiver
* AGC synchronization.
*
* The sensor then emits 4 data sync pulses of approximately 50%
* duty cycle and ~1.2 ms period. The sync pulses start with a
* high level and continue for 4 high / low pulses.
*
* The data bits immediately follow the fourth low of the data
* sync pulses. Data bits are sent every ~0.61 msec as:
*
* 1 bit ~0.4 msec high followed by ~0.2 msec low
* 0 bit ~0.2 msec high followed by ~0.4 msec low
*
* The 00592TX sends the 4 sync pulses followed by
* 7 bytes of data equalling 56 bits.
*
* The code below works by receiving a level change interrupt
* on each changing edge of the data stream from the RF module
* and recording the time in uSec between each edge.
*
* 8 measured hi and lo pulses in a row, 4 high and 4 low, of
* approximately ~600uSec each constitue a sync stream.
*
* The remaining 56 bits of data, or 112 edges, are measured
* and converted to 1s and 0s by checking the high to low
* pulse times.
*
* The first 4 pulses, or 8 edges, are the sync pulses followed
*
* We measure 8 sync edges followed by 112 data edges so the
* time capture buffer needs to be at least 120 bytes long.
*
* The data stream is 7 bytes long.
* The first and second bytes are unique address bytes per probe.
* The upper two bits of the first byte are the probe channel indicator:
*
* 11 = channel A --> Refrigerator
* 10 = channel B --> Freezer
* 00 = channel C --> Extra
*
* The remaining 6 bits of the first byte and the 8 bits of the second
* byte are a unique identifier per device. If you need more that 3 sensor
* adding a check by serial number could expand this gateway.
*
* The next byte is a status byte, normal = 0x44,
* 0x84 if battery is low. If Vbatt < ~2.5v, we get a low battery
*
* The next byte is humidity and is encoded as the
* lower 7 bits
*
* The next two bytes are the temperature. The temperature is encoded as the
* lower 7 bits of both bytes with the most significant bit being an
* even parity bit. The MSB will be set if required to insure an even
* number of bits are set to 1 in the byte. If the least significant
* seven bits have an even number of 1 bits set the MSB will be 0,
* otherwise the MSB will be set to 1 to insure an even number of bits.
*
* Temperature Range: -40º to 158º F, -40º C to 70º C
* Humidity Range: 1% to 99% Relative Humidity
*
* The last byte is a simple running sum, modulo 256, of the previous 6 data bytes.
*
* The block of data is sent 3 time, we only decode one of the blocks
*
* MQTT:
* If a message is sent to this device by topic: SUBSCRIBE_TOPIC, with a "R"
* in the 1st byte, we will reset all min/max settings
*
* MQTT Data Sent:
* Temperature, Min, Max, Humidity and Battery Status for the devices
* Alarms for temperature and Low Battery
*
* E-Mail:
* If enable, alarms are also send via E-mail or SMS
* http://www.emailtextmessages.com/
*
* Integration time for alarms can be set for each sensor.
*
* Radio:
* Using an RXB6 or equivalent, connect to 3.3v, gnd and connect dataout
* to an interrupt pin on CPU.
*
* RFM69 connect DIO-2 to interrupt pin on CPU.
*
* Antenna is 17.2cm long at 433MHz for a 1/4 wave.
*
* *********************************************************************
* Ideas on decoding protocol and prototype code from
* Ray Wang (Rayshobby LLC) http://rayshobby.net/?p=8998
*
* Code based on Ray Wang's humidity _display.ino source.
*
* *********************************************************************
*
CHANGE LOG:
*
* DATE REV DESCRIPTION
* ----------- --- ----------------------------------------------------------
* 13-Apr-2018 1.0g TRL - First Build
* 14-Apr-2018 1.0h TRL - Now you can have MQTT or E-mail, or both
* 15-Apr-2018 1.0i TRL - Release version
*
* Notes: 1) Tested with Arduino 1.8.5
* 2) Testing with a 433Mhz RFM69
* RFM69OOK lib from https://github.com/kobuki/RFM69OOK
* DIO2 connected to pin interrupt pin.
* 3) Tested with a RXB6 and Aurel RX-MID receivers
* 4) Tested using a TTGO R1 ESP32 module
* 5) ESP32 and ESP8266 supported sending data via MQTT and E-Mail
* 6) ESP8266 tested with a NodeMCU 1.0
* 7) Added E-mail-SMS Support NOTE:You must edit Gsender.h with your E-mail info
* 8)
*
* Todo: 1) Fix issues with RFM69 receiver, work in progress, not working
* 2) Code refactoring and consolidation of functions
* 3)
* 4)
* 5)
*
* Tom Lafleur --> [email protected]
*
*/
/* ************************************************************* */
#define VERBOSE_OUTPUT
//#define DISPLAY_BIT_TIMING
//#define DISPLAY_DATA_BYTES
//#define MyDEBUG
//#define IF_MQTT
#define IF_EMAIL
//#define RFM69
#define SKETCHNAME "Started, Acu-Rite 00592TX Decoder, "
#define SKETCHVERSION "Ver: 1.0h"
#define OLED U8X8_SSD1306_128X64_NONAME_HW_I2C // OLED-Display on board
// On the Arduino connect the data pin, the pin that will be
// toggling with the incomming data from the RF module, to
// a pin that can be configured for interrupt
// on change, change to high or low.
#include <Arduino.h>
#include <stdarg.h>
#include <Wire.h> // http://arduino.cc/en/Reference/Wire ??
#include "Gsender.h"
#include "MovingAverage.h"
#include <PubSubClient.h>
// OLED Display
#include <U8g2lib.h> // https://github.com/olikraus/u8g2
#ifdef RFM69
#include <RFM69OOK.h>
#include <SPI.h>
#include <RFM69OOKregisters.h>
RFM69OOK radio;
#endif
/* ************************************************************* */
// Select processor includes
#ifdef ARDUINO_ARCH_ESP32
#include <WiFi.h>
#include <esp_wps.h>
#include <WiFiClientSecure.h>
#endif
#ifdef ARDUINO_ARCH_ESP8266
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#endif
// Ring buffer size has to be large enough to fit
// data and sync signal, at least 120
// round up to 128 for now
#define RING_BUFFER_SIZE 128
#define SYNC_HIGH 600
#define SYNC_LOW 600
#define SYNC_TOLL 100 // +- Tolerance for sync pulse
#define PULSE_LONG 400
#define PULSE_SHORT 220
#define PULSE_TOLL 100 // +- Tolerance for bit timming
#define BIT1_HIGH PULSE_LONG
#define BIT1_LOW PULSE_SHORT
#define BIT0_HIGH PULSE_SHORT
#define BIT0_LOW PULSE_LONG
#define PULSE_SHORT_NOISE PULSE_SHORT - PULSE_TOLL // anything shorter that this is noise
#define PULSE_LONG_NOISE SYNC_HIGH + SYNC_TOLL // anything longer that this is noise
// create an instance of WiFi client
WiFiClient espClient;
// WiFi information
// change it with your ssid-password
const char* ssid = "MySSID"; // <----------- Change This
const char* password = "MyPassWord"; // <----------- Change This
#ifdef IF_EMAIL
const char* MySendToAddress = "MyEmail"; // <----------- Change This for E-Mail
// const char* MySendToAddress = "[email protected]"; // <----------- Change This for SMS
// For SMS format, see --> http://www.emailtextmessages.com/
#endif
uint8_t connection_state = 0; // Connected to WIFI or not
uint16_t reconnect_interval = 10000; // If not connected wait time to try again
// MQTT Server IP Address or FQDN
const char* mqtt_server = "192.168.167.32"; // <----------- Change This
#ifdef IF_MQTT
// create an instance of PubSubClient
PubSubClient client(espClient);
#else
// create a null instance of PubSubClient
PubSubClient client;
#endif
// My topics, format header is MyID=Site ID, MySensor=Sensor number // <----------- Change These as needed
#define MyID "RSF"
#define MySensor "S1"
#define ATEMP_TOPIC MyID "/" MySensor "/A/Temp"
#define BTEMP_TOPIC MyID "/" MySensor "/B/Temp"
#define CTEMP_TOPIC MyID "/" MySensor "/C/Temp"
#define AHUM_TOPIC MyID "/" MySensor "/A/Hum"
#define BHUM_TOPIC MyID "/" MySensor "/B/Hum"
#define CHUM_TOPIC MyID "/" MySensor "/C/Hum"
#define ABATT_TOPIC MyID "/" MySensor "/A/BATT"
#define BBATT_TOPIC MyID "/" MySensor "/B/BATT"
#define CBATT_TOPIC MyID "/" MySensor "/C/BATT"
#define AALARM_TOPIC MyID "/" MySensor "/A/ALARM"
#define BALARM_TOPIC MyID "/" MySensor "/B/ALARM"
#define CALARM_TOPIC MyID "/" MySensor "/C/ALARM"
#define AMIN_TOPIC MyID "/" MySensor "/A/MIN"
#define AMAX_TOPIC MyID "/" MySensor "/A/MAX"
#define BMIN_TOPIC MyID "/" MySensor "/B/MIN"
#define BMAX_TOPIC MyID "/" MySensor "/B/MAX"
#define CMIN_TOPIC MyID "/" MySensor "/C/MIN"
#define CMAX_TOPIC MyID "/" MySensor "/C/MAX"
#define BattALARM_TOPIC MyID "/" MySensor "/BATT/ALARM"
#define SUBSCRIBE_TOPIC MyID "/" MySensor "/+/RESET"
// create an instance for Moving Average
MovingAverage <float> AAVD (60); // create a moving average over last n values to trigger an alarm // <----------- Change These as needed
MovingAverage <float> BAVD (60); // 60 * ~18 sec = 1080sec = 18min
MovingAverage <float> CAVD (60);
#define MAX_ATEMP 45.0 // Max temperature for refrigerator, device A // <----------- Change These as needed
#define MAX_BTEMP 20.0 // Max temperature for freezer, device B
#define MAX_CTEMP 99.0 // Max temperature for device C
#define AlarmTimeToWait 120L // Wait this amount of time for next alarm message, in Minutes // <----------- Change These as needed
#define BattAlarmTimeToWait 1440L // Wait this amount of time for next battery alarm message, in Minutes
unsigned long LastTimeA = 0; // This is ID: A, used for the refrigerator
unsigned long LastTimeB = 0; // This is ID: B, used for the freezer
unsigned long LastTimeC = 0; // This is ID: C, Extra unit
unsigned long LastTimeBatt = 0; // Low battery
bool A_Flag = false; // This is ID: A, used for the refrigerator
bool B_Flag = false; // This is ID: B, used for the freezer
bool C_Flag = false; // This is ID: C, Extra unit
bool Batt_Flag = false; // This is low battery flag
unsigned long currentMillis = 0; // a 1 Minute clock timer
unsigned long interval = 60000; // = 60 sec --> 1 Minure
unsigned long previousMillis = 0;
unsigned long Minute = 0;
unsigned long BlockFailCounter = 0;
unsigned long CSFailCounter = 0;
char msg [60]; // char string buffer
char msg1[60]; // char string buffer
/* ************************************************************* */
#define SYNCPULSECNT 4 // 4 sync pulses (8 edges)
#define SYNCPULSEEDGES (SYNCPULSECNT * 2 )
#define DATABYTESCNT 7 // Number of bytes to look for
#define DATABITSCNT (DATABYTESCNT * 8) // Number of bits to look for
#define DATABITSEDGES (DATABITSCNT * 2) // Number of edges to look for
// The pulse durations are measured in micro seconds between pulse edges.
unsigned long pulseDurations[RING_BUFFER_SIZE]; // where we store the pulse edges
unsigned int syncIndex = 0; // index of the last bit time of the sync signal
unsigned int dataIndex = 0; // index of the first bit time of the data bits (syncIndex+1)
bool syncFound = false; // true if sync pulses found
bool received = false; // true if enough sync pulses bits are found
unsigned int changeCount = 0; // Count of pulses edges
unsigned char dataBytes[DATABYTESCNT]; // Decoded data storage
unsigned long mytime = 0; // event time
float temp = 0; // temperature
int hum = 0;
// The Min-Max for each sensor
float AMinTemp = 158; // Max temp is 158deg
float AMaxTemp = -40;
float BMinTemp = 158; // Max temp is 158deg
float BMaxTemp = -40;
float CMinTemp = 158; // Max temp is 158deg
float CMaxTemp = -40;
/* ************************************************************* */
#ifdef ARDUINO_ARCH_ESP32
/* pin that is attached to interrupt */
#define DATAPIN 12 // interrupt pin
byte interruptPin = DATAPIN;
#define MyInterrupt (digitalPinToInterrupt(interruptPin))
#define MyLED 2 // TTOG V1
// define below are use in debug as trigers to logic analyzer
#define MySync 36 // Trigger on Sync found
#define MyBit 37 // Trigger on bit edge
#define MyFrame 38 // Trigger at end of frame
// Hardware pin definitions for TTGOv1 Board with OLED SSD1306 I2C Display
#define OLED_RST 16 // ESP32 GPIO16 (Pin16) -- SD1306 Reset
#define OLED_SCL 15 // ESP32 GPIO15 (Pin15) -- SD1306 Clock
#define OLED_SDA 4 // ESP32 GPIO4 (Pin4) -- SD1306 Data
/* ************************************************************* */
#elif ARDUINO_ARCH_ESP8266
#define DATAPIN 2 // 2 is interrupt
byte interruptPin = DATAPIN;
#define MyInterrupt (digitalPinToInterrupt(interruptPin))
// Note: their are two LED on the NodeMCU Rev1 board
// D0-->16 on the board and D4-->2 on the ESP12 that is connected to U1-TXD
#define MyLED 16
// define below are use in debug as trigers to logic analyzer
#define MySync 3 // Trigger on Sync found
#define MyBit 4 // Trigger on bit edge
#define MyFrame 5 // Trigger at end of frame
// Hardware pin definitions for OLED SSD1306 I2C Display
// #define OLED_RST 16 // ESP32 GPIO16 (Pin16) -- SD1306 Reset
// #define OLED_SCL 15 // ESP32 GPIO15 (Pin15) -- SD1306 Clock
// #define OLED_SDA 4 // ESP32 GPIO4 (Pin4) -- SD1306 Data
#else
#error CPU undefined.....
#endif
// create an instance for OLED Display
#ifdef OLED
OLED u8x8(OLED_RST, OLED_SCL, OLED_SDA);
#else
U8X8_NULL u8x8;
#endif
/* ************************************************************* */
#ifdef OLED
void init_display(void)
{
u8x8.begin();
u8x8.setFont(u8x8_font_chroma48medium8_r);
u8x8.clear();
u8x8.setFlipMode(1);
}
#endif // OLED
/* ************************************************************* */
void receivedCallback(char* topic, byte* payload, unsigned int length)
{
Serial.println("Message received: ");
Serial.println(topic);
Serial.print("payload: ");
for (int i = 0; i < length; i++)
{
Serial.print((char)payload[i]);
}
Serial.println();
if ((char)payload[0] == 'R')
{
Serial.println("Reset Received");
// reset the Min-Max for each sensor
AMinTemp = 158; // Max temp is 158deg
AMaxTemp = -40;
BMinTemp = 158; // Max temp is 158deg
BMaxTemp = -40;
CMinTemp = 158; // Max temp is 158deg
CMaxTemp = -40;
}
}
/* ************************************************************* */
void mqttconnect()
{
/* Loop until reconnected */
while (!client.connected())
{
Serial.println();
Serial.print("MQTT connecting to: ");
Serial.println (mqtt_server);
/* client ID */
String clientId = WiFi.macAddress(); // use our MAC address as MQTT Client ID
/* connect now */
if (client.connect(clientId.c_str()))
{
Serial.print("MQTT connected, Client ID: ");
Serial.println(clientId);
/* subscribe topic with default QoS 0*/
client.subscribe(SUBSCRIBE_TOPIC);
} else
{
Serial.print("failed, status code =");
Serial.print(client.state());
Serial.println("try again in 5 seconds");
/* Wait 5 seconds before retrying */
delay(5000);
}
} // End of: while (!client.connected())
} // End of: mqttconnect()
/* ************************************************************* */
uint8_t WiFiConnect(const char* nSSID = nullptr, const char* nPassword = nullptr)
{
static uint32_t attempt = 0;
WiFi.disconnect();
Serial.print("Connecting WiFi to: ");
if(nSSID) {
WiFi.begin(nSSID, nPassword);
Serial.println(nSSID);
} else {
WiFi.begin(ssid, password);
Serial.println(ssid);
}
uint8_t i = 0;
while( (WiFi.status()!= WL_CONNECTED) && (i++ < 50) ) // wait for a connection
{
delay(250);
Serial.print(".");
}
++attempt;
if (attempt >= 15) // well, we have a problem, lets reboot...
{
Serial.println ("Unable to connect to WiFi, Rebooting...");
ESP.restart(); // <---------------- experiment
}
Serial.println("");
if(i >= 51) // if we can't make a connection
{
Serial.print("Connection: TIMEOUT on attempt: ");
Serial.println(attempt);
WiFi.disconnect();
return false;
}
Serial.println("Connection: ESTABLISHED"); // Ok, all is good, we have a connection
Serial.print ("Got IP address: ");
Serial.println(WiFi.localIP());
return true;
}
/* ************************************************************* */
void Awaits()
{
uint32_t ts = millis();
while(!connection_state)
{
delay(250);
if(millis() > (ts + reconnect_interval) && !connection_state)
{
connection_state = WiFiConnect();
ts = millis();
}
}
}
/* ************************************************************* */
/*
* Will print 8-bit formatted hex
*/
void PrintHex8(uint8_t *data, uint8_t length)
{
char tmp[length*2+1];
byte first;
int j = 0;
for (uint8_t i = 0; i < length; i++)
{
first = (data[i] >> 4) | 48;
if (first > 57) tmp[j] = first + (byte)39;
else tmp[j] = first ;
j++;
first = (data[i] & 0x0F) | 48;
if (first > 57) tmp[j] = first + (byte)39;
else tmp[j] = first;
j++;
}
tmp[length*2] = 0;
Serial.print("0x");
Serial.print(tmp);
}
//* ************************************************************* */
// Prints a byte as binary with leading zero's
void printBits(byte myByte)
{
for(byte mask = 0x80; mask; mask >>= 1)
{
if(mask & myByte)
Serial.print('1');
else
Serial.print('0');
}
}
//* ************************************************************* */
// Checksum of bits
uint8_t CheckSum(uint8_t const message[], unsigned nBytes)
{
unsigned int sum = 0;
unsigned i;
for (i = 0; i <= nBytes; ++i)
{
sum = sum + message[i];
}
sum = (sum & 0x000000ff);
return ((uint8_t) sum );
}
/* ************************************************************* */
/*
* Look for the sync pulse train of 4 high-low pulses of
* 600 uS high and 600 uS low.
* idx is index of last captured bit duration.
* Search backwards 8 times looking for 4 pulses
* approximately 600uS long.
*
*/
bool isSync(unsigned int idx)
{
// check if we've received 4 sync pulses of correct timing
for( int i = 0; i < SYNCPULSEEDGES; i += 2 )
{
unsigned long t1 = pulseDurations[(idx+RING_BUFFER_SIZE-i) % RING_BUFFER_SIZE];
unsigned long t0 = pulseDurations[(idx+RING_BUFFER_SIZE-i-1) % RING_BUFFER_SIZE];
// If any of the preceeding 8 pulses are out of bounds, short or long,
// return false, no sync found
if( t0<(SYNC_HIGH-SYNC_TOLL) || t0>(SYNC_HIGH+SYNC_TOLL) || t1<(SYNC_LOW-SYNC_TOLL) || t1>(SYNC_LOW+SYNC_TOLL) )
{ return false; }
}
return true;
}
/* ************************************************************* */
/* Interrupt handler
* Set to interrupt on edge (level change) high or low transition.
* Change the state of the Arduino LED on each interrupt.
*/
void interrupt_handler()
{
volatile static unsigned long duration = 0;
volatile static unsigned long lastTime = 0;
volatile static unsigned int ringIndex = 0;
volatile static unsigned int syncCount = 0;
volatile static unsigned int bitState = 0;
// Ignore this interrupt if we haven't finished processing the previous
// received block in the main loop.
if( received == true ) {return;} // return, we are not finish with processor last block
bitState = digitalRead (DATAPIN);
digitalWrite(MyLED, bitState); // LED to show receiver activity
// calculating timing since last change
long time = micros();
duration = time - lastTime;
lastTime = time;
// Known errors in bit stream are runt's --> short and long pulses.
// If we ever get a really short, or really long
// pulse's we know there is an error in the bit stream
// and should start over.
if ( (duration > (PULSE_LONG_NOISE)) || (duration < (PULSE_SHORT_NOISE)) ) // This pulse must be noise...
{
received = false;
syncFound = false;
changeCount = 0; // restart, start looking for sync and data bits again
}
// if we have good data, store data in ring buffer
ringIndex = (ringIndex + 1) % RING_BUFFER_SIZE;
pulseDurations[ringIndex] = duration;
changeCount++; // found another edge
#ifdef MyDEBUG
digitalWrite(MyBit, !digitalRead(MyBit) ); // LED to show we have a bit
// digitalWrite (MyBit, LOW);
// delayMicroseconds (5);
// digitalWrite (MyBit, HIGH);
#endif
// detected sync signal
if( isSync (ringIndex) ) // check for sync on each bit received
{
syncFound = true;
changeCount = 0; // lets restart looking for data bits again
syncIndex = ringIndex;
dataIndex = (syncIndex + 1) % RING_BUFFER_SIZE;
#ifdef MyDEBUG
digitalWrite(MySync, !digitalRead(MySync) ); // LED to show we have sync
// digitalWrite (MySync, LOW);
// delayMicroseconds (5);
// digitalWrite (MySync, HIGH);
#endif
}
// If a sync has been found, then start looking for the
// data bit edges in DATABITSEDGES
if( syncFound )
{
// not enough bits yet?, so no full message block has been received yet
if( changeCount < DATABITSEDGES )
{ received = false; }
else
if( changeCount >= DATABITSEDGES ) // check for too many bits
{
changeCount = DATABITSEDGES; // lets keep bits we have, checksum will kill this block if bad
detachInterrupt(MyInterrupt); // disable interrupt to avoid new data corrupting the buffer
received = true;
}
#ifdef MyDEBUG
digitalWrite(MyFrame, !digitalRead(MyFrame) ); // LED to show that we have full block of data
// digitalWrite (MyFrame, LOW);
// delayMicroseconds (50);
// digitalWrite (MyFrame, HIGHƒ);
#endif
} // end of if syncFound
} // end of interrupt_handler
const char compile_date[] = __DATE__ ", " __TIME__;
/* ************************************************************* */
/* ************************************************************* */
/* ************************************************************* */
void setup()
{
Serial.begin(115200);
delay(2000);
Serial.println("");
Serial.print(SKETCHNAME);
#ifdef RFM69
Serial.println("RFM69");
#else
Serial.println("External Receiver");
#endif
Serial.println (SKETCHVERSION);
Serial.println (compile_date);
Serial.println("");
pinMode(DATAPIN, INPUT); // data interrupt pin set for input
pinMode(MyLED, OUTPUT); // LED output
digitalWrite (MyLED, LOW);
#ifdef MyDEBUG
pinMode(MySync, OUTPUT); // sync bit output
digitalWrite (MySync, LOW);
pinMode(MyBit, OUTPUT); // data bit output
digitalWrite (MyBit, LOW);
pinMode(MyFrame, OUTPUT); // end of frame bit output
digitalWrite (MyFrame, LOW);
#endif
#ifdef RFM69
pinMode( 14, INPUT); // RFM69 RST
//digitalWrite (14, LOW);
pinMode(26, INPUT); // DIO-0
pinMode(33, INPUT); // DIO-1
pinMode(32, INPUT); // DIO-2 This is where we get the RX data --> comnnected to interrupt pin
radio.initialize();
//radio.setBandwidth(OOK_BW_10_4);
radio.setRSSIThreshold(-70);
radio.setFixedThreshold(20);
radio.setSensitivityBoost(SENSITIVITY_BOOST_HIGH);
radio.setFrequencyMHz(433.92);
radio.receiveBegin();
#endif
// Setup WiFi
// WiFi.config(ip, dns, gateway, subnet); // if using static addressing
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
connection_state = WiFiConnect();
if(!connection_state) // if not connected to WIFI
Awaits(); // constantly trying to connect
delay (1000);
/* configure the MQTT server with IPaddress and port */
client.setServer(mqtt_server, 1883);
/* this receivedCallback function will be invoked
when client received subscribed topic */
client.setCallback(receivedCallback);
#ifdef OLED
// initialize the OLED display
init_display();
u8x8.drawString(0, 0,"00592 Decoder");
u8x8.setCursor(0,1);
u8x8.printf("%d.%d.%d.%d",WiFi.localIP()[0], WiFi.localIP()[1], WiFi.localIP()[2], WiFi.localIP()[3] );
#endif
pinMode(MyInterrupt, INPUT_PULLUP);
attachInterrupt(MyInterrupt, interrupt_handler, CHANGE);
} // end of setup
/* ************************************************************* */
/*
* Convert pulse durations to bits.
*
* 1 bit ~0.4 msec high followed by ~0.2 msec low
* 0 bit ~0.2 msec high followed by ~0.4 msec low
*
*/
int convertTimingToBit(unsigned int t0, unsigned int t1)
{
if( t0 > (BIT1_HIGH-PULSE_TOLL) && t0 < (BIT1_HIGH+PULSE_TOLL) && t1 > (BIT1_LOW-PULSE_TOLL) && t1 < (BIT1_LOW+PULSE_TOLL) )
{ return 1; }
else if( t0 > (BIT0_HIGH-PULSE_TOLL) && t0 < (BIT0_HIGH+PULSE_TOLL) && t1 > (BIT0_LOW-PULSE_TOLL) && t1 < (BIT0_LOW+PULSE_TOLL) )
{ return 0; }
return -1; // error, if undefined bit timimg
}
/* ************************************************************* */
// 00592TX send's a meassge every ~18 sec, so lets average temperature
// over a number of sample, if is greater that our alarm settings, we need to send
// an alarm, but only once every so many minutes. We donot want to send
// an alert on a peak reading.
void MaxSensorAAlarm (float temp)
{
if (A_Flag == false) // see if this is 1st time here for this alarm...
{
snprintf (msg, 10, "%6.2f", temp);
client.publish (AALARM_TOPIC, msg);
#ifdef IF_EMAIL
Gsender *gsender = Gsender::Instance(); // Getting pointer to class instance
sprintf (msg1, "%s %s Sensor Alarm! ID=A", MyID, MySensor);
sprintf (msg, "Alarm set at: %6.2fF, Temperature is: %6.2fF\n", MAX_ATEMP, temp);
if(gsender->Subject(msg1)->Send(MySendToAddress, msg))
{
Serial.println("E-mail Message sent.");
} else
{
Serial.print("E-Mail, Error, sending message: ");
Serial.println(gsender->getError());
}
#endif
Serial.println ("Sensor Alarm, ID: A");
A_Flag = true;
LastTimeA = Minute; // save the current time
}
else
{
if ( Minute >= (LastTimeA + AlarmTimeToWait ) ) // see if it time to re-send alarm
{ A_Flag = false; } // Yes, reset alarm flag
}
}
/* ************************************************************* */
void MaxSensorBAlarm(float temp)
{
if (B_Flag == false) // see if this is 1st time here for this alarm...
{
snprintf (msg, 10, "%6.2f", temp);
client.publish (BALARM_TOPIC, msg);
#ifdef IF_EMAIL
Gsender *gsender = Gsender::Instance(); // Getting pointer to class instance
sprintf (msg1, "%s %s Sensor Alarm! ID=B", MyID, MySensor);
sprintf (msg, "Alarm set at: %6.2fF, Temperature is: %6.2fF\n", MAX_BTEMP, temp);
if(gsender->Subject(msg1)->Send(MySendToAddress, msg))
{
Serial.println("E-Mail Message sent.");
} else
{
Serial.print("E-Mail, Error sending message: ");
Serial.println(gsender->getError());
}
#endif
Serial.println ("Sensor Alarm, ID: B");
B_Flag = true;
LastTimeB = Minute; // save the current time
}
else
{
if ( Minute >= (LastTimeB + AlarmTimeToWait ) ) // see if it time to re-send alarm
{ B_Flag = false; } // Yes, reset alarm flag
}
}
/* ************************************************************* */
void MaxSensorCAlarm(float temp)
{
if (C_Flag == false) // see if this is 1st time here for this alarm...
{
snprintf (msg, 10, "%6.2f", temp);
client.publish (CALARM_TOPIC, msg);
#ifdef IF_EMAIL
Gsender *gsender = Gsender::Instance(); // Getting pointer to class instance
sprintf (msg1, "%s %s Sensor Alarm! ID=C", MyID, MySensor);
sprintf (msg, "Alarm set at: %6.2fF, Temperature is: %6.2fF\n", MAX_CTEMP, temp);
if(gsender->Subject(msg1)->Send(MySendToAddress, msg))
{
Serial.println("E-Mail Message sent.");
} else
{
Serial.print("E-Mail, Error sending message: ");
Serial.println(gsender->getError());
}
#endif
Serial.println ("Sensor Alarm, ID: C");
C_Flag = true;
LastTimeC = Minute; // save the current time
}
else
{
if ( Minute >= (LastTimeC + AlarmTimeToWait ) ) // see if it time to re-send alarm
{ C_Flag = false; } // Yes, reset alarm flag
}
}
/* ************************************************************* */
void BatteryLowAlarm (int device)
{
device = (device & 0x02); // only two bits are used
if (Batt_Flag == false) // see if this is first time here for this alarm...
{ // we should do this for each sensor, but maybe next time
if (device == 0x03) { snprintf (msg, 50, "Battery Low, Sensor: A"); }
if (device == 0x02) { snprintf (msg, 50, "Battery Low, Sensor: B"); }
if (device == 0x01) { snprintf (msg, 50, "Battery Low, Sensor: Unknown"); }
if (device == 0x00) { snprintf (msg, 50, "Battery Low, Sensor: C"); }
Serial.println (msg);
client.publish (BattALARM_TOPIC, msg);
#ifdef IF_EMAIL
Gsender *gsender = Gsender::Instance(); // Getting pointer to class instance
sprintf (msg1, "%s %s Sensor Low Battery Alarm!", MyID, MySensor);
// We will get message body from msg buffer above
if(gsender->Subject(msg1)->Send(MySendToAddress, msg))
{
Serial.println("E-Mail Message sent.");
}
else
{
Serial.print("Error sending message: ");
Serial.println(gsender->getError());
}
#endif
Batt_Flag = true;
LastTimeBatt = Minute; // save the current time
}
else
{
if ( Minute >= (LastTimeBatt + BattAlarmTimeToWait ) ) // see if it time to re-send alarm
{ Batt_Flag = false; } // Yes, reset alarm flag
}
}
/* ************************************************************* */
int acurite_getHumidity (uint8_t byte)
{
// range: 1 to 99 %RH
int humidity = byte & 0x7F;
return humidity;
}
/* ************************************************************* */
float acurite_getTemp_6044M(byte hibyte, byte lobyte)
{
// range -40 to 158 F, -40º C to 70º C --> returns temp in deg C
int highbits = (hibyte & 0x0F) << 7;
int lowbits = lobyte & 0x7F;
int rawtemp = highbits | lowbits;
float temp = (rawtemp / 10.0) - 100;
return temp;
}
/* ************************************************************* */
float convCF(float c)
{
return ((c * 1.8) + 32);
}
/* ************************************************************* */
uint16_t acurite_txr_getSensorId(uint8_t byte)
{
return ((byte & 0xc0) >> 6);
}
/* ************************************************************* */
uint16_t acurite_txr_getSensorSN(uint8_t hibyte, uint8_t lobyte)
{
return ((hibyte & 0x3f) << 8) | lobyte;
}
/* ************************************************************* */
bool acurite_txr_getBattery(uint8_t battery)
{
if ( (battery & 0x80) == 0x80 ) // check if battery is low
{ return true; } // Yes, its low
return false;
}
/* ************************************************************* */