-
Notifications
You must be signed in to change notification settings - Fork 24
/
LBridge_RFduino_170729_1647.ino
2732 lines (2404 loc) · 81.8 KB
/
LBridge_RFduino_170729_1647.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
/*
* LBridge for RFduino / Simblee
*
* LBridge running on RFduino or Simblee platform (aka Transmiter2 from @MarekMacner)
*
* Reads every 5 min a Libre Freestyle sensor via NFC and transmit the BG readings to xDrip+ via BLE.
* Supports backfilling of older BG readings which were not transfered at the time of reading.
*
* Code used from the work of @UPetersen, @MarekMacner, @jstevensog, @savek-cc and @bertrooode
*
* keencave, 20.6.2017
*
* ToDo:
* - optimize BLE reconnect
* - only read changed NFC blocks from sensor for better battery performance
* - enable "hidden" power modes on BM019
*/
/*
* program configuration
*/
#define RFD // RFduino or Simblee platform?
#define N_USE_DEAD_SENSOR // we can test with a dead sensor
#define USE_SPIKE_FILTER // use a spike filter?
#define N_DB_RAW // debug raw data
#define N_SHOW_LIMITTER // show original Limitter output
#define N_DYNAMIC_TXID // get TXID automatically
#define N_XBEXT // xbridge+ code
#define N_T2 // T2 Transmiter from Marek?
// length of device name and advertisement <=15!!!
#define LB_NAME "xbridge0" // dont change "xbridge", space for 1 char left to indicate different versions
#define LB_ADVERT "rfduino" // dont change "rfduino"
#define LB_VERSION "0729_1647"
#define MAX_SENSOR_MINUTES (24*14*60+720) // max. livetime of the sensor, 14,5 days
#define SPIKE 40 // minimum delta to be a spike
#ifdef RFD
#include <RFduinoBLE.h>
#else
#include <SimbleeBLE.h>
#endif
#include <SPI.h>
#include <Stream.h>
#include <Memory.h>
#ifdef XBEXT
#include "xbridge_libre.h"
#endif
#define PIN_SPI_SCK 4
#define PIN_SPI_MOSI 5
#define PIN_SPI_MISO 3
#define PIN_SPI_SS 6
#define PIN_IRQ 2
#define ALL_BYTES 0x1007
#define IDN_DATA 0x2001
#define SYSTEM_INFORMATION_DATA 0x2002
#define BATTERY_DATA 0x2005
/* ------------------ program variables ----------- */
#define MIN_VOLTAGE 2100
//#define MAX_VOLTAGE 3200
#define MAX_VOLTAGE 3600 // adjust voltage measurement to have a wider rrange
unsigned long loop_cnt = 0; // count the 5 mins loops
static boolean show_ble = 1; // what is shown in serial monitor
static boolean show_state = 1; // show print_state() infos, disabled ftm
int ble_answer; // state counter, char from BLE reeived?
#define BLEBUFLEN 80 // BLE input buffer
unsigned char bleBuf[BLEBUFLEN];
int bleBufRi = 0; // BLE read and write index
int bleBufWi = 0;
// defines the xBridge protocol functional level. Sent in each packet as the last byte.
#define DEXBRIDGE_PROTO_LEVEL (0x01)
static volatile boolean do_sleep = 0; // indicates we should go to sleep between packets
static volatile boolean got_ack = 0; // indicates if we got an ack during the last do_services.
#ifdef XBEXT
static volatile boolean got_drp; // DataRequestPacket
#endif
static volatile boolean dex_tx_id_set; // indicates if the Dexcom Transmitter id (settings.dex_tx_id) has been set. Set in doServices.
static volatile boolean ble_connected; // bit indicating the BLE module is connected to the phone. Prevents us from sending data without this.
static volatile boolean got_ok = 0; // flag indicating we got OK from the HM-1x
static unsigned long last_ble_send_time;
static boolean crlf_printed = 0;
static volatile unsigned long pkt_time = 0;
//define the maximum command string length for USB commands.
#define COMMAND_MAXLEN 80
//structure of a USB command
typedef struct _command_buff
{
unsigned char commandBuffer[COMMAND_MAXLEN];
unsigned char nCurReadPos;
} t_command_buff;
static t_command_buff command_buff;
typedef struct _Dexcom_packet
{
unsigned long raw;
unsigned long ms;
} Dexcom_packet;
#define DXQUEUESIZE (8*12) // 8 h of queue
typedef struct {
volatile unsigned char read;
volatile unsigned char write;
Dexcom_packet buffer[DXQUEUESIZE];
} Dexcom_fifo;
Dexcom_fifo Pkts;
Dexcom_packet * DexPkt;
// structure of a raw record we will send.
typedef struct _nRawRecord
{
unsigned char size; //size of the packet.
unsigned char cmd_code; // code for this data packet. Always 00 for a Dexcom data packet.
unsigned long raw; //"raw" BGL value. ??? use unfiltered NFC readings here?
unsigned long filtered; //"filtered" BGL value
unsigned char dex_battery; //battery value
unsigned char my_battery; //xBridge battery value
unsigned long dex_src_id; //raw TXID of the Dexcom Transmitter
unsigned long delay;
unsigned char function; // Byte representing the xBridge code funcitonality. 01 = this level.
} nRawRecord;
// _xBridge_settings - Type definition for storage of xBridge_settings
// used for compatibility
typedef struct _xBridge_settings
{
unsigned long dex_tx_id = 0xA5B1AE; //4 bytes
unsigned long uart_baudrate; //4 bytes
} xBridge_settings; //14 bytes total
xBridge_settings settings;
// array of HM-1x baudrates for rate detection.
unsigned long uart_baudrate[9] = {9600L, 19200L, 38400L, 57600L, 115200L, 4800, 2400, 1200, 230400L};
#ifdef XBEXT
_QuarterPacket1 qpkt1;
_QuarterPacket2 qpkt2;
#endif
/* ------------- endof program veriables ---------- */
typedef struct __attribute__((packed))
{
uint8_t resultCode;
uint8_t deviceID[13];
uint8_t romCRC[2];
} IDNDataType;
typedef struct __attribute__((packed))
{
uint8_t uid[8];
uint8_t resultCode;
uint8_t responseFlags;
uint8_t infoFlags;
uint8_t errorCode;
String sensorSN;
} SystemInformationDataType;
typedef struct __attribute__((packed))
{
bool sensorDataOK;
String sensorSN;
byte sensorStatusByte;
String sensorStatusString;
byte nextTrend;
byte nextHistory;
uint16_t minutesSinceStart;
uint16_t minutesHistoryOffset;
uint16_t trend[16];
uint16_t history[32];
} SensorDataDataType;
uint16_t lastGlucose = 0;
uint16_t currentGlucose = 0;
boolean firstRun = 1;
int noDiffCount = 0; // determine 5 equal values from Libre sensor = dead
typedef struct __attribute__((packed))
{
long voltage;
int voltagePercent;
double temperatureC;
double temperatureF;
double rssi;
} SoCDataType;
typedef struct __attribute__((packed))
{
uint8_t allBytes[345];
} AllBytesDataType;
typedef struct __attribute__((packed))
{
float voltage;
float temperature;
} BatteryDataType;
typedef struct dataConfig
{
byte marker;
byte protocolType; // 1 - LimiTTer, 2 - Transmiter, 3 - LibreCGM, 4 - Transmiter II
byte runPeriod; // 0-9 main loop period in miutes, 0=on demenad
byte firmware; // firmware version starting 0x02
};
typedef enum {
UBP_TxFlagNone = 0 << 0,
UBP_TxFlagIsRPC = 1 << 0,
UBP_TxFlagRequiresACK = 1 << 1
} UBP_TxFlags;
bool UBP_isTxPending = false;
bool hostIsConnected = false;
extern void UBP_incomingChecksumFailed() __attribute__((weak));
extern void UBP_receivedPacket(unsigned short packetIdentifier, UBP_TxFlags txFlags, void *packetBuffer) __attribute__((weak));
extern void UBP_didAdvertise(bool start) __attribute__((weak));
extern void UBP_didConnect() __attribute__((weak));
extern void UBP_didDisconnect() __attribute__((weak));
byte resultBuffer[40];
byte dataBuffer[400];
byte NFCReady = 0; // 0 - not initialized, 1 - initialized, no data, 2 - initialized, data OK
bool sensorDataOK = false;
IDNDataType idnData;
SystemInformationDataType systemInformationData;
SensorDataDataType sensorData;
SoCDataType SoCData; // store processor variables
struct dataConfig valueSetup;
dataConfig *p;
AllBytesDataType allBytes;
BatteryDataType batteryData;
byte sensorDataHeader[24];
byte sensorDataBody[296];
byte sensorDataFooter[24];
byte noOfBuffersToTransmit = 1;
String TxBuffer[10];
String TxBuffer1 = "";
byte protocolType = 1; // 1 - LimiTTer, 2 - Transmiter, 3 - Transmiter II
byte runPeriod = 1; // czas w minutach - 0 = tylko na żądanie
// ====== changed by Bert Roode
//byte MY_FLASH_PAGE = 251; definition is not as it should be
#define MY_FLASH_PAGE 251
#define str(x) xstr(x) // double level of indirection required to get gcc
#define xstr(x) #x // to apply the stringizing operator correctly
unsigned int time_loop_started = 0;
unsigned int time_elapsed = 0;
// ====== end Bert Roode
bool BTconnected = false;
bool BatteryOK = false;
void setup()
{
p = (dataConfig*)ADDRESS_OF_PAGE(MY_FLASH_PAGE);
Serial.begin(9600);
delay(2000); // give serial interface time to settle
Serial.print("\r\n=== loop #"); Serial.print(loop_cnt);
Serial.print(" =====================================================================================================");
print_state("setup()");
print_state(" ------------------------------------------------------------------");
print_state(" --- LBridge starting ---");
print_state(" --- BLE Name: "); Serial.print(LB_NAME); Serial.print(" ---");
print_state(" --- Version: "); Serial.print(LB_VERSION); Serial.print(" ---");
print_state(" --- RAM used: "); Serial.print(ramUsed()); Serial.print(", Flash used: "); Serial.print(flashUsed()); Serial.print(" ---");
print_state(" --- Queue size: "); Serial.print(DXQUEUESIZE);
print_state(" --- Options:");
#ifdef USE_DEAD_SENSOR
print_state(" usage of dead sensors allowed");
#else
print_state(" detect dead sensor - quit sending readings after 14,5d");
#endif
#ifdef USE_SPIKE_FILTER
print_state(" remove spikes > +-"); Serial.print(SPIKE);
#else
print_state(" dont detect and remove spikes");
#endif
print_state(" ------------------------------------------------------------------");
print_state("setup - start - ");
SoC_Data();
setupInitData();
protocolType = p->protocolType;
runPeriod = p->runPeriod;
// runPeriod = 1; // loop time is 1 min, only for test
setupBluetoothConnection();
nfcInit();
// ====== changed by Bert Roode
// configWDT();
// reset the CR95HF because of possible instability
digitalWrite(PIN_SPI_SS, LOW);
SPI.transfer(0x01);
digitalWrite(PIN_SPI_SS, HIGH);
delay(1);
// ====== changed by Bert Roode
print_state("NFCReady = "); Serial.print(NFCReady);
Serial.print(", BatOK = "); Serial.print(BatteryOK);
print_state("setup - end - ");
// init xbridge queue
Pkts.read = 0;
Pkts.write = 0;
}
void loop()
{
Serial.print("\r\n=== loop #"); Serial.print(++loop_cnt); Serial.print(" === BT status "); Serial.print(BTconnected);
Serial.print(" ==="); Serial.printf(" RSSI: %f", SoCData.rssi);
Serial.print(" =================================================");
print_state("loop - start - BLE Name: "); Serial.print(LB_NAME); Serial.print(", Version: "); Serial.print(LB_VERSION);
Serial.print(", HW platform: ");
#ifdef RFD
Serial.print("RFduino");
#else
Serial.print("Simblee");
#endif
// ====== change by Bert Roode
time_loop_started = millis();
// ====== end change by Bert Roode
if (BatteryOK) {
readAllData();
if (NFCReady == 2) {
print_state("After sensor read, NFCReady = ");
Serial.print(NFCReady);
dataTransferBLE();
}
else {
print_state("No sensor data, ");
Serial.print("NFCReady = ");
Serial.print(NFCReady);
}
}
else {
print_state("low Battery - go sleep");
}
print_state("loop - end - ");
Serial.print(" NFCReady = ");
Serial.print(NFCReady);
// ====== start change by Bert Roode
time_elapsed = millis() - time_loop_started;
print_state("sleep for ");
Serial.print(60000 * runPeriod);
#ifdef RFD
RFduino_ULPDelay((60000 * runPeriod) - time_elapsed) ;
#else
Simblee_ULPDelay((60000 * runPeriod) - time_elapsed) ;
#endif
// restartWDT();
// ====== end change by Bert Roode
}
/* ********* BLE ************************ */
void dataTransferBLE()
{
if ( BTconnected )
print_state("we are connected - transfer data ...");
else
print_state("dataTransferBLE(), wait 40 s for BLE connect ...");
for (int i = 0; i < 40; i++) {
if (BTconnected) {
if (protocolType == 1) forLimiTTer();
else if (protocolType == 2) forTransmiter1();
else if (protocolType == 3) forTransmiter2();
else if (protocolType == 4) forLibreCGM();
break;
}
else {
// Serial.print("Not connected after ");
// Serial.println(i);
// Serial.printf("not connected after %d\rn", i);
waitDoingServices(1000, 1);
}
}
NFCReady = 1;
}
void setupBluetoothConnection()
{
print_state("setupBluetoothConnection() - ");
#ifdef RFD
if (protocolType == 1) RFduinoBLE.deviceName = LB_NAME;
else if (protocolType == 2) RFduinoBLE.deviceName = "LimiTTer";
else if (protocolType == 3) RFduinoBLE.deviceName = "Transmiter";
#ifdef T2
Serial.print("setting Transmiter device");
RFduinoBLE.advertisementData = "data";
RFduinoBLE.customUUID = "c97433f0-be8f-4dc8-b6f0-5343e6100eb4";
#else /* T2 */
// emulate a HM-11 module to be recognized like a LimiTTer running LBridge code
Serial.print("setting LimiTTer/xbridge device");
RFduinoBLE.advertisementData = LB_ADVERT;
RFduinoBLE.customUUID = "0000ffe0-0000-1000-8000-00805f9b34fb";
#endif /* T2 */
RFduinoBLE.advertisementInterval = MILLISECONDS(300);
RFduinoBLE.txPowerLevel = 4;
RFduinoBLE.begin();
#else /* RFD */
if (protocolType == 1) SimbleeBLE.deviceName = LB_NAME;
else if (protocolType == 2) SimbleeBLE.deviceName = "LimiTTer";
else if (protocolType == 3) SimbleeBLE.deviceName = "Transmiter";
// emulate a HM-11 module to be recognized like a LimiTTer running LBridge code
Serial.print(" - setting LimiTTer/xbridge device");
SimbleeBLE.advertisementData = LB_ADVERT;
SimbleeBLE.customUUID = "0000ffe0-0000-1000-8000-00805f9b34fb";
SimbleeBLE.advertisementInterval = MILLISECONDS(300);
SimbleeBLE.txPowerLevel = 4;
SimbleeBLE.begin();
#endif
Serial.print(" - done");
}
/* ************ BLE ********************* */
/* ************ CR95HF ********************* */
//============================================================================================================
void NFC_wakeUP()
{
print_state("NFC_wakeUp() - Send wake up pulse to CR95HF and configure to use SPI - ");
digitalWrite(PIN_IRQ, HIGH);
delay(10);
digitalWrite(PIN_IRQ, LOW);
delayMicroseconds(100);
digitalWrite(PIN_IRQ, HIGH);
delay(10);
Serial.print("done");
}
void NFC_CheckWakeUpEventRegister()
{
int length = 5;
byte command[length];
print_state("NFC_CheckWakeUpEventRegister()");
#ifdef RFD
while ( RFduinoBLE.radioActive );
#else
while ( SimbleeBLE.radioActive );
#endif
command[ 0] = 0x08;
command[ 1] = 0x03;
command[ 2] = 0x62;
command[ 3] = 0x01;
command[ 4] = 0x00;
send_NFC_PollReceive(command, sizeof(command));
print_NFC_WakeUpRegisterResponse();
}
void send_NFC_PollReceive(byte *command, int commandLength)
{
// print_state("send_NFC_PollReceive() - ");
send_NFC_Command(command, commandLength);
poll_NFC_UntilResponsIsReady();
receive_NFC_Response();
}
#define NFCTIMEOUT 500
void new_send_NFC_PollReceive(byte *command, int commandLength)
{
// print_state("send_NFC_PollReceive() - ");
digitalWrite(PIN_SPI_SS, LOW);
SPI.transfer(0x00);
for (int i = 0; i < commandLength; i++)
{
SPI.transfer(command[i]);
}
digitalWrite(PIN_SPI_SS, HIGH);
delay(1);
unsigned long ms = millis();
byte rb;
// print_state("poll_NFC_UntilResponsIsReady() - ");
digitalWrite(PIN_SPI_SS , LOW);
while ( (resultBuffer[0] != 8) && ((millis() - ms) < NFCTIMEOUT) )
{
rb = resultBuffer[0] = SPI.transfer(0x03);
// Serial.printf("SPI polling response byte:%x\r\n", resultBuffer[0]);
resultBuffer[0] = resultBuffer[0] & 0x08;
}
digitalWrite(PIN_SPI_SS, HIGH);
delay(1);
if ( millis() - ms > NFCTIMEOUT ) {
Serial.print("\r\n *** poll timeout *** -> response ");
Serial.print(rb);
}
digitalWrite(PIN_SPI_SS, LOW);
SPI.transfer(0x02);
resultBuffer[0] = SPI.transfer(0);
resultBuffer[1] = SPI.transfer(0);
for (byte i = 0; i < resultBuffer[1]; i++) resultBuffer[i + 2] = SPI.transfer(0);
digitalWrite(PIN_SPI_SS, HIGH);
delay(1);
Serial.print("done");
}
//============================================================================================================
void send_NFC_Command(byte *commandArray, int length)
{
digitalWrite(PIN_SPI_SS, LOW);
SPI.transfer(0x00);
for (int i = 0; i < length; i++) {
SPI.transfer(commandArray[i]);
}
digitalWrite(PIN_SPI_SS, HIGH);
delay(1);
}
void poll_NFC_UntilResponsIsReady()
{
unsigned long ms = millis();
byte rb;
// print_state("poll_NFC_UntilResponsIsReady() - ");
digitalWrite(PIN_SPI_SS , LOW);
while ( (resultBuffer[0] != 8) && ((millis() - ms) < NFCTIMEOUT) )
{
rb = resultBuffer[0] = SPI.transfer(0x03);
// Serial.printf("SPI polling response byte:%x\r\n", resultBuffer[0]);
resultBuffer[0] = resultBuffer[0] & 0x08;
}
digitalWrite(PIN_SPI_SS, HIGH);
delay(1);
if ( millis() - ms > NFCTIMEOUT ) {
Serial.print("\r\n *** poll timeout *** -> response ");
Serial.print(rb);
}
// else
// Serial.print("done");
}
void receive_NFC_Response()
{
// print_state("receive_NFC_Response()");
digitalWrite(PIN_SPI_SS, LOW);
SPI.transfer(0x02);
resultBuffer[0] = SPI.transfer(0);
resultBuffer[1] = SPI.transfer(0);
for (byte i = 0; i < resultBuffer[1]; i++) resultBuffer[i + 2] = SPI.transfer(0);
digitalWrite(PIN_SPI_SS, HIGH);
delay(1);
}
//============================================================================================================
void print_NFC_WakeUpRegisterResponse()
{
print_state("print_NFC_WakeUpRegisterResponse() - ");
Serial.printf("Result code (byte 0): %x", resultBuffer[0]);
Serial.printf(", Length of data (byte 1): %d", resultBuffer[1]);
if (resultBuffer[1] > 0)
{
for (int i = 2; i < 2 + resultBuffer[1]; i++)
{
Serial.printf(" Data byte %d: %x", i, resultBuffer[i]);
}
}
// print_state("... finished printing wake-up register result.");
}
//============================================================================================================
void SetNFCprotocolCommand()
{
for (int t = 0; t < 9; t++)
{
print_state("SetNFCprotocolCommand() - ");
int length = 4;
byte command[length];
command[ 0] = 0x02;
command[ 1] = 0x02;
command[ 2] = 0x01;
command[ 3] = 0x0F;
// command[ 3] = 0x0D;
send_NFC_PollReceive(command, sizeof(command));
Serial.print("resultBuffer: ");
for (byte i = 0; i < 2; i++) {
Serial.print(resultBuffer[i], HEX);
Serial.print(" ");
}
if ((resultBuffer[0] == 0) & (resultBuffer[1] == 0)) {
Serial.print(", Try=");
Serial.print(t);
Serial.print(" - PROTOCOL SET - OK");
NFCReady = 1;
break;
}
else {
Serial.print(", Try=");
Serial.print(t);
Serial.print(" - BAD RESPONSE TO SET PROTOCOL");
NFCReady = 0; // NFC not ready
}
}
Serial.print(" - done");
}
//============================================================================================================
void runIDNCommand(int maxTrials)
{
byte command[2];
print_state("runIDNCommand() - ");
command[0] = 0x01;
command[1] = 0x00;
delay(10);
Serial.printf("maxTrials: %d, RXBuffer[0]: %x", maxTrials, resultBuffer[0]);
runIDNCommandUntilNoError(command, sizeof(command), maxTrials);
}
void runIDNCommandUntilNoError(byte *command, int length, int maxTrials)
{
int count = 0;
bool success;
print_state("runIDNCommandUntilNoError() - ");
do
{
Serial.printf("Before: Count: %d, success: %b, resultBuffer[0]: %x", count, success, resultBuffer[0]);
count++;
memset(resultBuffer, 0, sizeof(resultBuffer));
send_NFC_PollReceive(command, sizeof(command));
success = idnResponseHasNoError();
Serial.printf("\r\nAfter: Count: %d, success: %b, resultBuffer[0]: %x", count, success, resultBuffer[0]);
} while ( !success && (count < maxTrials));
delay(10);
Serial.printf("Exiting at count: %d, resultBuffer[0]: %x", count, resultBuffer[0]);
}
bool idnResponseHasNoError()
{
print_state("idnResponseHasNoError() - ");
Serial.printf("IDN response is resultBuffer[0]: %x", resultBuffer[0]);
if (resultBuffer[0] == 0x00)
{
return true;
}
return false;
}
IDNDataType idnDataFromIDNResponse()
{
idnData.resultCode = resultBuffer[0];
for (int i = 0; i < 13; i++)
{
idnData.deviceID[i] = resultBuffer[i + 2];
}
idnData.romCRC[0] = resultBuffer[13 + 2];
idnData.romCRC[1] = resultBuffer[14 + 2];
return idnData;
}
void printIDNData(IDNDataType idnData)
{
print_state("printIDNData() - ");
String nfc = "";
// Serial.println("Printing IDN data:");
Serial.printf("Result code: %x", idnData.resultCode);
Serial.printf(", NFC Device ID [hex]: ");
Serial.printf("%x", idnData.deviceID[0]);
nfc += (char) idnData.deviceID[0];
for (int i = 1; i < 12; i++)
{
Serial.printf(":%x", idnData.deviceID[i]);
nfc += (char) idnData.deviceID[i];
}
Serial.println("");
Serial.printf("NFC Device ID [char]: ");
Serial.print(nfc);
Serial.printf(", NFC Device CRC %x:%x", idnData.romCRC[0], idnData.romCRC[1] );
// Serial.println("");
}
//============================================================================================================
void runSystemInformationCommandUntilNoError(int maxTrials)
{
memset(resultBuffer, 0, sizeof(resultBuffer));
// Serial.printf("maxTrials: %d, resultBuffer[0]: %x \r\n", maxTrials, resultBuffer[0]);
byte command[4];
command[0] = 0x04;
command[1] = 0x02;
command[2] = 0x03;
command[3] = 0x2B;
delay(10);
// Serial.printf("maxTrials: %d, resultBuffer[0]: %x \r\n", maxTrials, resultBuffer[0]);
runNFCcommandUntilNoError(command, sizeof(command), maxTrials);
}
void runNFCcommandUntilNoError(byte *command, int length, int maxTrials)
{
int count = 0;
bool success;
// print_state("runNFCcommandUntilNoError() - ");
do
{
delay(1);
// Serial.printf("Before: Count: %d, success: %b, resultBuffer[0]: %x \r\n", count, success, resultBuffer[0]);
count++;
send_NFC_PollReceive(command, sizeof(command));
success = responseHasNoError();
// Serial.printf("After: Count: %d, success: %b, resultBuffer[0]: %x \r\n", count, success, resultBuffer[0]);
} while ( !success && (count < maxTrials));
delay(1);
// Serial.printf("Exiting at count: %d, resultBuffer[0]: %x \r\n", count, resultBuffer[0]);
}
bool responseHasNoError()
{
// Serial.printf("Response is resultBuffer[0]: %x, resultBuffer[2]: %x \r\n", resultBuffer[0], resultBuffer[2]);
if (resultBuffer[0] == 0x80)
{
if ((resultBuffer[2] & 0x01) == 0)
{
return true;
}
}
return false;
}
SystemInformationDataType systemInformationDataFromGetSystemInformationResponse()
{
SystemInformationDataType systemInformationData;
systemInformationData.resultCode = resultBuffer[0];
systemInformationData.responseFlags = resultBuffer[2];
if (systemInformationData.resultCode == 0x80)
{
if ((systemInformationData.responseFlags & 0x01) == 0)
{
systemInformationData.infoFlags = resultBuffer[3];
for (int i = 0; i < 8; i++)
{
systemInformationData.uid[i] = resultBuffer[11 - i];
}
systemInformationData.errorCode = resultBuffer[resultBuffer[1] + 2 - 1];
}
else
{
systemInformationData.errorCode = resultBuffer[3];
}
systemInformationData.sensorSN = decodeSN(systemInformationData.uid);
sensorData.sensorSN = systemInformationData.sensorSN;
}
else
{
clearBuffer(systemInformationData.uid);
systemInformationData.errorCode = resultBuffer[3];
}
return systemInformationData;
}
void printSystemInformationData(SystemInformationDataType systemInformationData)
{
print_state("system information data: ");
Serial.printf("Result code: %x", systemInformationData.resultCode);
Serial.printf(", Response flags: %x", systemInformationData.responseFlags);
/*
Serial.printf("uid: %x", systemInformationData.uid[0]);
for (int i = 1; i < 8; i++)
{
Serial.printf(":%x", systemInformationData.uid[i]);
}
Serial.println("");
*/
Serial.print(", Sensor SN:");
Serial.print(systemInformationData.sensorSN);
Serial.printf(", Error code: %x - done", systemInformationData.errorCode);
}
void clearBuffer(byte *tmpBuffer)
{
memset(tmpBuffer, 0, sizeof(tmpBuffer));
}
//============================================================================================================
bool readSensorData()
{
byte resultCode = 0;
int trials = 0;
int maxTrials = 10;
print_state("readSensorData() - ");
clearBuffer(dataBuffer);
for (int i = 0; i < 43; i++) {
resultCode = ReadSingleBlockReturn(i);
// printf("resultCode 0x%x - ", resultCode);
if (resultCode != 0x80 && trials < maxTrials) {
// printf("Error 0x%x\n\r", resultCode);
i--; // repeat same block if error occured, but
trials++; // not more than maxTrials times per block
}
else if (trials >= maxTrials) {
break;
}
else {
trials = 0;
for (int j = 3; j < resultBuffer[1] + 3 - 4; j++) {
dataBuffer[i * 8 + j - 3] = resultBuffer[j];
// Serial.print(resultBuffer[j], HEX);
// Serial.print(" ");
}
// Serial.println(" ");
}
}
bool resultH = checkCRC16(dataBuffer, 0);
bool resultB = checkCRC16(dataBuffer, 1);
bool resultF = checkCRC16(dataBuffer, 2);
bool crcResult = false;
Serial.print(" CRC-Header check = ");
Serial.print(resultH);
Serial.print(" - CRC-Body check = ");
Serial.print(resultB);
Serial.print(" - CRC-Footer check = ");
Serial.print(resultF);
if (resultH && resultB && resultF) crcResult = true;
else crcResult = false;
Serial.print(" - CRC check ");
Serial.print(crcResult);
Serial.print(" - done");
if (crcResult) NFCReady = 2;
else NFCReady = 1;
return crcResult;
}
byte ReadSingleBlockReturn(int blockNum)
{
int length = 5;
byte command[length];
command[0] = 0x04;
command[1] = 0x03;
command[2] = 0x03;
command[3] = 0x20;
command[4] = blockNum;
send_NFC_Command(command, 5);
poll_NFC_UntilResponsIsReady();
receive_NFC_Response();
delay(1);
/*
if (resultBuffer[0] == 128)
{
Serial.printf("The block #%d:", blockNum);
for (byte i = 3; i < resultBuffer[1] + 3 - 4; i++)
{
Serial.print(resultBuffer[i], HEX);
Serial.print(" ");
}
Serial.println(" ");
}
else
{
Serial.print("NO Single block available - ");
Serial.print("RESPONSE CODE: ");
Serial.println(resultBuffer[0], HEX);
}
Serial.println(" ");
*/
return resultBuffer[0];
}
//============================================================================================================
void nfcInit()
{
// print_state("nfc_init()");
configSPI();
NFC_wakeUP();
//=========== changed by Bert Roode
// NFC_CheckWakeUpEventRegister();
//=========== end change by Bert Roode
NFCReady = 0;
SetNFCprotocolCommand();
runIDNCommand(10);
idnData = idnDataFromIDNResponse();
printIDNData(idnData);
}
void sendNFC_ToHibernate()
{
print_state("sendNFC-ToHibernate()");
// Bert Roode - length 16 instead of 17
int length = 16;
byte command[length];
command[ 0] = 0x07;
command[ 1] = 0x0E;
command[ 2] = 0x08;
command[ 3] = 0x04;
command[ 4] = 0x00;
command[ 5] = 0x04;
command[ 6] = 0x00;
command[ 7] = 0x18;
command[ 8] = 0x00;
command[ 9] = 0x00;
command[10] = 0x00;
command[11] = 0x00;
command[12] = 0x00;
command[13] = 0x00;
command[14] = 0x00;
command[15] = 0x00;
send_NFC_Command(command, sizeof(command));
}
/* ************ CR95HF ********************* */
/* ************ DataPrep ********************* */
void forLimiTTer()
{
print_state("forLimiTTer()");
#ifdef T2
noOfBuffersToTransmit = 1;
TxBuffer1 = "";
TxBuffer1 += String(sensorData.trend[0] * 100);
TxBuffer1 += " ";
TxBuffer1 += String(SoCData.voltage);
TxBuffer1 += " ";
TxBuffer1 += String(SoCData.voltagePercent);
TxBuffer1 += " ";
TxBuffer1 += String((int)(sensorData.minutesSinceStart / 10));
int LL = TxBuffer1.length();
Serial.print("for LimiTTer >>");
Serial.print(TxBuffer1);
Serial.print("<< ");
Serial.println(LL);
#ifdef RFD
RFduinoBLE.send(TxBuffer1.cstr(), TxBuffer1.length());
#else
SimbleeBLE.send(TxBuffer1.cstr(), TxBuffer1.length());
#endif
#else /* T2 */
boolean resend_pkt = 0;
while ((Pkts.read != Pkts.write) && BTconnected && ((millis() - pkt_time) < ((DXQUEUESIZE + 1) * 5000) )) {
got_ack = 0;
print_packet(&Pkts.buffer[Pkts.read]);
// wait 10 s for ack
int j;
for ( j = 0 ; j < 10 ; j++ ) {
waitDoingServicesInterruptible(1000, &got_ack, 1);
if ( !BTconnected ) {
print_state("connection lost during wait for ack, go to sleep");
break;
}
}
if (got_ack) {
print_state("got ack for read position ");
Serial.print(Pkts.read); Serial.print(F(" while write is "));
Serial.print(Pkts.write); Serial.print(F(", incrementing read to "));
if ( ++Pkts.read >= DXQUEUESIZE )
Pkts.read = 0; //increment read position since we got an ack for the last package
Serial.print(Pkts.read);
resend_pkt = 0;
}
else {
if ( !resend_pkt ) {
print_state("no ack received, try again");
resend_pkt = 1;
}
else {
print_state("no ack received, try again next wakeup");
resend_pkt = 0;
break;
}
}
} /* while (send all packets available) */
#endif /* T2 */
}
void forTransmiter1()
{
noOfBuffersToTransmit = 1;
TxBuffer1 = "";
TxBuffer1 += String(sensorData.trend[0] * 100);
TxBuffer1 += " ";