-
Notifications
You must be signed in to change notification settings - Fork 9
/
STM32_Logger_Beacon.ino
1199 lines (1054 loc) · 35.6 KB
/
STM32_Logger_Beacon.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
//=====================================================================
// Leafony Platform sample sketch
// Application : STM32 BLE Logger Beacon Example
// Processor : STM32L452RE (Nucleo-64/Nucleo L452RE)
// Arduino IDE : 1.8.12
// STM32 Core : Ver1.9.0
//
// Leaf configuration
// (1) AI01 4-Sensors
// (2) AP03 STM32 MCU
// (3) AZ01 USB
// (4) AC02 BLE Sugar
// (5) AV0X Battery Leaf
//
// Description
// センサデータをBeaconで送信しながらSTM32のFlashに書き込み、
// Webbluetoothから接続要求があれば、Flashのデータをすべて送信するサンプルスケッチです。
//
// (c) 2021 LEAFONY SYSTEMS Co., Ltd
// Released under the MIT license
// https://opensource.org/licenses/MIT
//
// Rev.01 2021/04/01 First release
//=====================================================================
// Required Libraries
// https://github.com/ameltech/sme-hts221-library
// https://github.com/closedcube/ClosedCube_OPT3001_Arduino
// https://github.com/Leafony/TBGLib
// https://github.com/tomozh/arduino_ST7032
// https://github.com/stm32duino/STM32LowPower
// https://github.com/stm32duino/STM32RTC
//=====================================================================
#include <SoftwareSerial.h>
#include <Wire.h>
#include <EEPROM.h>
#include "STM32LowPower.h"
#include <STM32RTC.h>
#include "RTClib.h"
#include <Adafruit_LIS3DH.h>
#include <HTS221.h>
#include <ClosedCube_OPT3001.h>
#include "TBGLib.h"
//=====================================================================
// Sketch firmware version
//=====================================================================
const String FIRMWARE_VERSION = "2021.09.140";
//=====================================================================
// BLE Local device name
//=====================================================================
const String strDeviceNamePrefix = "Leaf_";
const String strDeviceNameUnique = "A";
String strDeviceName = strDeviceNamePrefix + strDeviceNameUnique;
//=====================================================================
// シリアルコンソールへのデバック出力
// #define DEBUG = 出力あり
// //#define DEBUG = 出力なし(コメントアウトする)
//=====================================================================
#define DEBUG
//=====================================================================
// スリープ時間、送信時間の設定
// DEFAULT_SLEEP_INTERVAL : スリープ時間 (秒)
// DEFAULT_WAKE_INTERVAL :Beacon送信時間 (秒)
// DEFAULT_CLICK_WAKE_INTERVAL : ダブルタップをしたときの起動時間 (秒)
//=====================================================================
#define DEFAULT_SLEEP_INTERVAL 60
#define DEFAULT_WAKE_INTERVAL 1
#define DEFAULT_CLICK_WAKE_INTERVAL 20
//=====================================================================
// センサ測定間隔、データ保存間隔の設定
// DEFAULT_SENS_FREQ : センサON頻度
// DEFAULT_SAVE_RREQ :データ保存頻度
//=====================================================================
#define DEFAULT_SENS_FREQ 1 // TODO: implement dynamic sens frequency
#define DEFAULT_SAVE_FREQ 1 // TODO: implement dynamic save frequency
//=====================================================================
// IO pins definition
//=====================================================================
// for STM32 29-pin leaf
#define BLE_WAKEUP PB12 // D7 PB12
#define BLE_RX PA0 // [A2] PA1
#define BLE_TX PA1 // [A1] PA0
#define INT_0 PC7 // INT0
#define INT_1 PB3 // INT1
// for STM32 58-pin leaf Bus-A
// #define BLE_WAKEUP PA8
// #define BLE_TX PA1
// #define BLE_RX PA0
// #define INT_0 PC7
// #define INT_1 PB3
// for STM32 58-pin leaf Bus-B
// #define BLE_WAKEUP PB11
// #define BLE_TX PC5
// #define BLE_RX PC4
// #define INT_0 PC7
// #define INT_1 PB3
//=====================================================================
// プログラム内で使用する定数定義
//
//=====================================================================
// I2C addresses
#define LIS2DH_ADDRESS 0x19 // Accelerometer (SD0/SA0 pin = VCC)
#define OPT3001_ADDRESS 0x45 // Ambient Light Sensor (ADDR pin = VCC)
#define LCD_I2C_EXPANDER_ADDR 0x1A // LCD I2C Expander
#define BATT_ADC_ADDR 0x50 // Battery ADC
// Adjust this number for the sensitivity of the 'click' force
// this strongly depend on the range! for 16G, try 5-10
// for 8G, try 10-20. for 4G try 20-40. for 2G try 40-80
#define CLICKTHRESHHOLD 80
#define SINGLETAP 1
#define DOUBLETAP 2
// BLE states
#define BLE_STATE_STANDBY (0)
#define BLE_STATE_SCANNING (1)
#define BLE_STATE_ADVERTISING (2)
#define BLE_STATE_CONNECTING (3)
#define BLE_STATE_CONNECTED_MASTER (4)
#define BLE_STATE_CONNECTED_SLAVE (5)
// BLE Connecting Mode
#define MODE_IDLE (0)
#define MODE_SEND_DATA (1)
#define MODE_CLEAR_EEPROM (2)
// BLE Advertising Interval
// Example: If the minimum advertisement interval is 40ms and the maximum advertisement interval is 100ms
// then the real advertisement interval will be mostly the middle value (70ms) plus a randomly added 20ms delay,
// which needs to be added according to the Bluetooth specification.
#define MIN_ADV_INTVAL 200 // 200 * 0.625ms = 125ms
#define MAX_ADV_INTVAL 400 // 400 * 0.625ms = 250ms
// Baudrate
#define SERIAL_BAUD 115200
//=====================================================================
// objects
//=====================================================================
// Sensors
Adafruit_LIS3DH accel = Adafruit_LIS3DH();
ClosedCube_OPT3001 light;
// BLE
HardwareSerial Serialble(BLE_TX, BLE_RX);
BGLib ble112((HardwareSerial *)&Serialble, 0, 0);
// RTC
STM32RTC& rtc = STM32RTC::getInstance();
//=====================================================================
// Variables
//=====================================================================
// LIS2DH : accelerometer
float dataX_g, dataY_g, dataZ_g;
float dataTilt = 0;
// HTS221 : Temperature/Humidity
float dataTemp = 0;
float dataHumid = 0;
// OPT3001 : Light
float dataLight = 0;
// Battery voltage
float dataBatt = 0;
// BLE
volatile bool bSystemBootBle = false;
volatile uint8_t ble_state = BLE_STATE_STANDBY;
bool bBleConnected = false;
uint8_t mode = MODE_IDLE;
// EEPROM ringbuffer
uint16_t rb_addr = 0; // ringbuffer read address
const uint8_t RINGBUFF_OFFSET_ADDR = 20;
const uint8_t PACKET_LENGTH = 12;
uint16_t wake_intval = DEFAULT_WAKE_INTERVAL; // Wake time
uint16_t click_wake_intval = DEFAULT_CLICK_WAKE_INTERVAL; // Click interrupt wake time
uint16_t sleep_intval = DEFAULT_SLEEP_INTERVAL; // Sleep time
uint16_t sens_freq = DEFAULT_SENS_FREQ; // Sensor ON frequency
uint16_t save_freq = DEFAULT_SAVE_FREQ; // Data save frequency
// On-Clicked Interrupt
bool onClickedFlag = false;
//----------------------------------------------
// Accelerometer double-tap interrupt
//----------------------------------------------
void onClicked() {
onClickedFlag = true;
}
//----------------------------------------------
// IO ports initialization
//----------------------------------------------
void setupPort() {
pinMode(BLE_WAKEUP, OUTPUT); // BLE Wakeup/Sleep
digitalWrite(BLE_WAKEUP, HIGH); // BLE Wakeup
}
//-----------------------------------------------
// BLE initialization
//-----------------------------------------------
void setupBLE() {
#ifdef DEBUG
Serial.println("setupBLE()");
#endif
// set up internal status handlers
ble112.onBusy = onBusy;
ble112.onIdle = onIdle;
ble112.onTimeout = onTimeout;
// set up BGLib event handlers
ble112.ble_evt_gatt_server_attribute_value = my_evt_gatt_server_attribute_value;
ble112.ble_evt_le_connection_opend = my_evt_le_connection_opend;
ble112.ble_evt_le_connection_closed = my_evt_le_connection_closed;
ble112.ble_evt_system_boot = my_evt_system_boot;
ble112.ble_evt_system_awake = my_evt_system_awake;
ble112.ble_rsp_system_get_bt_address = my_rsp_system_get_bt_address;
Serialble.begin(9600);
uint8_t tm=0;
while (!bSystemBootBle && tm <150){ // Wait for BLE Start-up
ble112.checkActivity(100);
tm++;
delay(10);
}
// ble_rsp_system_get_bt_address handler is called.
ble112.ble_cmd_system_get_bt_address();
while (ble112.checkActivity(100));
// set advertising parameters
ble112.ble_cmd_le_gap_set_adv_parameters(MIN_ADV_INTVAL, MAX_ADV_INTVAL, 7); /* [BGLIB] <interval_min> <interval_max> <channel_map> */
while (ble112.checkActivity(100));
}
//-----------------------------------------------
// BLE Advertising data configuration
//-----------------------------------------------
void StartAdvData() {
// char charTemp[7], charHumid[7], charBatt[7];
uint16_t temp, humid, illum, battVolt;
char userData[15];
uint8_t dataLen;
uint8_t stLen;
uint8_t adv_data[25]; // advertising data (max 25bytes)
uint8_t index = 0;
//-------------------------
// Sensors data
//-------------------------
temp = (uint16_t)(dataTemp * 256);
humid = (uint16_t)(dataHumid * 256);
battVolt = (uint16_t)(dataBatt * 256);
illum = (uint16_t)dataLight;
//-------------------------
// Advertising Packet
//-------------------------
// AD Structure 1 (Flags)
adv_data[index++] = 0x02; // field length
adv_data[index++] = BGLIB_GAP_AD_TYPE_FLAGS; // AD Type (Flags)
adv_data[index++] = (1 << 1) | (1 << 2); // LE General Discover Mode | BR/EDR Not Supported
// AD Structure 2 (Complete Local Name)
adv_data[index++] = strDeviceName.length() + 1; // field length
adv_data[index++] = BGLIB_GAP_AD_TYPE_LOCALNAME_COMPLETE; // AD Type (Complete Local Name)
for (uint8_t i = 0; i < strDeviceName.length(); i++) {
adv_data[index++] = strDeviceName.charAt(i); // Local Name
}
// AD Structure 3 (Manufacturer Specific Data)
adv_data[index++] = 9; // field lengh
adv_data[index++] = 0xff; // AD Type (Manufacturer Specific Data)
adv_data[index++] = (illum >> 8) & 0xFF; // Illuminance (Upper)
adv_data[index++] = illum & 0xFF; // Illuminance (Lower)
adv_data[index++] = (temp >> 8) & 0xFF; // Temperature (Upper)
adv_data[index++] = temp & 0xFF; // Temperature (Lower)
adv_data[index++] = (humid >> 8) & 0xFF; // Humidity (Upper)
adv_data[index++] = humid & 0xFF; // Humidity (Lower)
adv_data[index++] = (battVolt >> 8) & 0xFF; // Battery Voltage (Upper)
adv_data[index++] = battVolt & 0xFF; // Battery Boltage (Lower)
// register advertising packet
stLen = index;
ble112.ble_cmd_le_gap_set_adv_data(SCAN_RSP_ADVERTISING_PACKETS, stLen, adv_data);
while (ble112.checkActivity(1000));
// index = 0 LE_GAP_SCANNABLE_NON_CONNECTABLE / LE_GAP_UNDIRECTED_CONNECTABLE
ble112.ble_cmd_le_gap_start_advertising(0, LE_GAP_USER_DATA, LE_GAP_UNDIRECTED_CONNECTABLE);
while (ble112.checkActivity(1000));
}
//-----------------------------------------------
// Sensors initialization
//-----------------------------------------------
void setupSensors() {
#ifdef DEBUG
Serial.println("Initializing sensors...");
#endif
// LIS2DH (accelerometer)
accel.begin(LIS2DH_ADDRESS);
accel.setRange(LIS3DH_RANGE_2_G); // Full scale +/- 2G
accel.setDataRate(LIS3DH_DATARATE_50_HZ); // Data rate = 10Hz
accel.setClick(DOUBLETAP, CLICKTHRESHHOLD); // enable click interrupt
// enable interrupt from accelerometer click event
LowPower.attachInterruptWakeup(INT_1, onClicked, RISING, DEEP_SLEEP_MODE);
// HTS221 (temperature /humidity)
smeHumidity.begin();
// OPT3001 (light)
OPT3001_Config newConfig;
OPT3001_ErrorCode errorConfig;
light.begin(OPT3001_ADDRESS);
newConfig.RangeNumber = B1100; // automatic full scale
newConfig.ConvertionTime = B0; // convertion time = 100ms
newConfig.ModeOfConversionOperation = B01; // single-shot conversion
newConfig.Latch = B0; // hysteresis-style
errorConfig = light.writeConfig(newConfig);
delay(100); // wait until all sensors are ready
#ifdef DEBUG
Serial.println("Sensors initialized.");
#endif
}
//--------------------------------------------------------------------
// Get sensors values
//--------------------------------------------------------------------
void getSensors() {
// HTS221 (temperature & humidity)
smeHumidity.begin();
dataTemp = (float)smeHumidity.readTemperature();
dataHumid = (float)smeHumidity.readHumidity();
//--------------------
// 2点補正用データ
//--------------------
// 温度補正用データ0
float TL0 = 25.0; // 4-Sensors温度測定値
float TM0 = 25.0; // 温度計等測定値
// 温度補正用データ1
float TL1 = 40.0; // 4-Sensors温度測定値
float TM1 = 40.0; // 温度計等測定値
// 湿度補正用データ0
float HL0 = 60.0; // 4-Sensors湿度測定値
float HM0 = 60.0; // 湿度計等測定値
// 湿度補正用データ1
float HL1 = 80.0; // 4-Sensors湿度測定値
float HM1 = 80.0; // 湿度計等測定値
//-------------------------
// 温度と湿度の2点補正
//-------------------------
dataTemp=TM0+(TM1-TM0)*(dataTemp-TL0)/(TL1-TL0); // 温度補正
dataHumid=HM0+(HM1-HM0)*(dataHumid-HL0)/(HL1-HL0); // 湿度補正
// if (dataHumid >= 100)
// {
// dataHumid=100;
// }
// OPT3001 (illuminance)
delay(100);
OPT3001 result = light.readResult();
dataLight = result.lux;
// ADC081C027(ADC) battery voltage
uint8_t adcVal1 = 0;
uint8_t adcVal2 = 0;
Wire.beginTransmission(BATT_ADC_ADDR);
Wire.write(0x00);
Wire.endTransmission(false);
Wire.requestFrom(BATT_ADC_ADDR, 2);
adcVal1 = Wire.read();
adcVal2 = Wire.read();
//測定値がFFならバッテリリーフはつながっていない
if (adcVal1 == 0xff && adcVal2 == 0xff) {
adcVal1 = adcVal2 = 0;
}
//電圧計算 ADC * ((リファレンス電圧(3.3V)/ ADCの分解能(256)) * 分圧比(2倍))
double temp_mv = ((double)((adcVal1 << 4) | (adcVal2 >> 4)) * 3300 * 2) / 256;
dataBatt = (float)(temp_mv / 1000);
#ifdef DEBUG
Serial.println("");
Serial.println("--- sensors data ---");
Serial.println(" Tmp[degC] = " + String(dataTemp));
Serial.println(" Hum[%] = " + String(dataHumid));
Serial.println(" Lum[lx] = " + String(dataLight));
Serial.println(" Bat[V] = " + String(dataBatt));
Serial.println("");
#endif
}
//-----------------------------------------
// sleep sensors
// センサーリーフをスリープさせる
//-----------------------------------------
void sleepSensors() {
// HTS221 sleep
smeHumidity.deactivate();
// OPT3001 sleep
OPT3001_Config newConfig;
OPT3001_ErrorCode errorConfig;
newConfig.ModeOfConversionOperation = B00;
errorConfig = light.writeConfig(newConfig);
}
//-----------------------------------------
// wakeup sensors
// センサーリーフをスリープから復帰させる
//-----------------------------------------
void wakeupSensors() {
#ifdef DEBUG
Serial.println(F("Wakeup Sensors."));
#endif
// HTS221 wakeup
smeHumidity.activate();
// OPT3001 wakeup
OPT3001_Config newConfig;
OPT3001_ErrorCode errorConfig;
newConfig.RangeNumber = B1100; // automatic full scale
newConfig.ModeOfConversionOperation = B01; //single-shot conversion
errorConfig = light.writeConfig(newConfig);
delay(300);
}
//---------------------------------------
// sleep BLE
// BLE リーフをスリープさせる
//---------------------------------------
void sleepBLE() {
#ifdef DEBUG
Serial.println("Sleep BLE");
#endif
ble112.ble_cmd_le_gap_stop_advertising(0);
while (ble112.checkActivity());
ble112.ble_cmd_system_halt(1);
while (ble112.checkActivity());
digitalWrite(BLE_WAKEUP, LOW);
}
//---------------------------------------
// wakeup BLE
// BLEリーフをスリープから復帰させる
//---------------------------------------
void wakeupBLE() {
#ifdef DEBUG
Serial.println("Wakeup BLE");
#endif
digitalWrite(BLE_WAKEUP, HIGH);
delay(10);
ble112.ble_cmd_system_halt(0);
while (ble112.checkActivity());
ble112.ble_cmd_le_gap_set_adv_parameters(MIN_ADV_INTVAL, MAX_ADV_INTVAL, 7); /* [BGLIB] <interval_min> <interval_max> <channel_map> */
while (ble112.checkActivity());
}
//---------------------------------------
// EEPROM
//
// Address Map
// Addr, Description
// 0, EEPROM Configuration Check (if 0xAA: EEPROM is configured)
// 1, EEPROM Configuration Check (if 0xAA: EEPROM is configured)
// 2, Wake Interval (Upper)
// 3, Wake Interval (Lower)
// 4, Sleep Interval (Upper)
// 5, Sleep Interval (Lower)
// 6, Sens Frequency (Upper)
// 7, Sens Frequency (Lower)
// 8, Save Frequency (Upper)
// 9, Save Frequency (Lower)
// 10-11, Reserved
// 12, Device Name [0]
// 13, Device Name [1]
// 14, Device Name [2]
// 15, Device Name [3]
// 16, Device Name [4]
// 17-19, Reserved
//---------------------------------------
void setupEEPROM() {
bool eeprom_configured = false;
// EEPROM Configuration Check
if (EEPROM.read(0) == 0xAA && EEPROM.read(1) == 0xAA) {
#ifdef DEBUG
Serial.println("EEPROM is already configured!");
#endif
eeprom_configured = true;
} else {
#ifdef DEBUG
Serial.println("EEPROM is not configured. All variables are set to default.");
#endif
}
if (eeprom_configured) {
// Load saved registers
// wake_intval = (EEPROM.read(2) << 8) + EEPROM.read(3); // Reserved
sleep_intval = (EEPROM.read(4) << 8) + EEPROM.read(5);
// sens_freq = (EEPROM.read(6) << 8) + EEPROM.read(7); // Reserved
// save_freq = (EEPROM.read(8) << 8) + EEPROM.read(9); // Reserved
// Load device name
strDeviceName = strDeviceNamePrefix;
for (uint8_t i=0; i<5; i++){
char c = EEPROM.read(12+i);
// c is NOT alphabet or numeric
if (!((c>='a' && c<='z') || (c>='A' && c<='Z') || (c>='0' && c<='9'))) {
if (i==0) { // Device Name is not set.
strDeviceName += strDeviceNameUnique; // Set default unique name.
}
break;
}
// c is alphabet or numeric
else {
strDeviceName += String(c);
}
}
#ifdef DEBUG
Serial.print("BLE Device Name is ");
Serial.println(strDeviceName);
#endif
} else {
// Set default value
wake_intval = DEFAULT_WAKE_INTERVAL;
sleep_intval = DEFAULT_SLEEP_INTERVAL;
sens_freq = DEFAULT_SENS_FREQ;
save_freq = DEFAULT_SAVE_FREQ;
// Save default value
EEPROM.write(2, (wake_intval >> 8) & 0xFF);
EEPROM.write(3, (wake_intval & 0xFF));
EEPROM.write(4, (sleep_intval >> 8) & 0xFF);
EEPROM.write(5, (sleep_intval & 0xFF));
EEPROM.write(6, (sens_freq >> 8) & 0xFF);
EEPROM.write(7, (sens_freq & 0xFF));
EEPROM.write(8, (save_freq >> 8) & 0xFF);
EEPROM.write(9, (save_freq & 0xFF));
EEPROM.write(0, 0xAA); // EEPROM configured
EEPROM.write(1, 0xAA); // EEPROM configured
}
// EEPROM Test
for (uint16_t rb_work; rb_work < EEPROM.length(); rb_work++) {
EEPROM.read(rb_work);
}
// when address is invalid;
if (rb_addr >= EEPROM.length() || (rb_addr - RINGBUFF_OFFSET_ADDR) % PACKET_LENGTH != 0) {
rb_addr = RINGBUFF_OFFSET_ADDR;
}
#ifdef DEBUG
Serial.print("EEPROM length: ");
Serial.println(EEPROM.length());
Serial.print("Ring buffer read address: ");
Serial.println(rb_addr);
Serial.print("WAKE_INTERVAL: ");
Serial.print(wake_intval);
Serial.println(" seconds");
Serial.print("SLEEP_INTERVAL: ");
Serial.print(sleep_intval);
Serial.println(" seconds");
// Serial.print("SENS_FREQ = ");
// Serial.println(sens_freq);
// Serial.print("SAVE_FREQ = ");
// Serial.println(save_freq);
#endif
}
/**
*
*/
void writeEEPROM() {
uint16_t temp, humid, illum, battVolt;
uint32_t u_time;
if (!rtc.isTimeSet()) {
// RTC is not set, skip to save data.
return;
}
// Get current time from RTC
u_time = getTimestamp();
// Reset the ring buffer address when the size is not enough;
if (rb_addr + PACKET_LENGTH >= EEPROM.length()) {
rb_addr = RINGBUFF_OFFSET_ADDR;
}
#ifdef DEBUG
Serial.println("");
Serial.print("writeEEPROM(): ADDR=");
Serial.print(rb_addr);
Serial.print(", timestamp=");
Serial.println(u_time);
#endif
// Write the sensors data to EEPROM.
temp = (uint16_t)(dataTemp * 256.0);
humid = (uint16_t)(dataHumid * 256.0);
illum = (uint16_t)dataLight;
battVolt = (uint16_t)(dataBatt * 256.0);
uint8_t data[12];
data[0] = (temp >> 8) & 0xFF;
data[1] = temp & 0xFF;
data[2] = (humid >> 8) & 0xFF;
data[3] = humid & 0xFF;
data[4] = (illum >> 8) & 0xFF;
data[5] = illum & 0xFF;
data[6] = (battVolt >> 8) & 0xFF;
data[7] = battVolt & 0xFF;
data[8] = (u_time >> 0) & 0xFF;
data[9] = (u_time >> 8) & 0xFF;
data[10] = (u_time >> 16) & 0xFF;
data[11] = (u_time >> 24) & 0xFF;
for (uint8_t i = 0; i < 12; i++) {
EEPROM.write(rb_addr + i, data[i]);
delay(10); // EEPROM書き込み後しばらく待つ
}
// write next ring buffer address to RTC backup register.
rb_addr += PACKET_LENGTH;
#ifdef DEBUG
Serial.print("{ temp = ");
Serial.print(temp);
Serial.print(", humid = ");
Serial.print(humid);
Serial.print(", illum = ");
Serial.print(illum);
Serial.print(", batt = ");
Serial.print(battVolt);
Serial.println(" }");
Serial.print("Next ringbuffer address: ");
Serial.println(rb_addr);
Serial.println("");
#endif
}
/**
* decode RTC to timestamp.
*/
uint32_t getTimestamp() {
if (!rtc.isTimeSet()) {
return 0;
}
uint8_t year = rtc.getYear();
uint8_t month = rtc.getMonth();
uint8_t day = rtc.getDay();
uint8_t hours = rtc.getHours();
uint8_t minutes = rtc.getMinutes();
uint8_t seconds = rtc.getSeconds();
#ifdef DEBUG
Serial.print("RTC Timestamp: ");
Serial.print(year + 2000);
Serial.print("/");
Serial.print(month);
Serial.print("/");
Serial.print(day);
Serial.print(" ");
Serial.print(hours);
Serial.print(":");
Serial.print(minutes);
Serial.print(":");
Serial.print(seconds);
Serial.println(" (GMT+0)");
#endif
DateTime date (year, month, day, hours, minutes, seconds);
return date.unixtime();
}
/**
*
*/
void sleepAllDevices() {
sleepBLE();
sleepSensors();
#ifdef DEBUG
Serial.print(">>> STM32 deepsleep (restart after ");
Serial.print(sleep_intval);
Serial.println(" seconds) >>>");
Serial.flush();
#endif
LowPower.deepSleep(sleep_intval * 1000);
}
/**
*
*/
void setup() {
Serial.begin(SERIAL_BAUD);
LowPower.begin(); // Configure low power
Wire.begin(); // I2C 100KHz
rtc.begin(); // initialize RTC 24H format
#ifdef DEBUG
Serial.print("FIRMWARE VERSION: ");
Serial.println(FIRMWARE_VERSION);
Serial.print("CPU Clock Frequency = ");
Serial.println(HAL_RCC_GetHCLKFreq());
Serial.println("=========================================");
Serial.println("Setup start.");
#endif
setupPort();
setupEEPROM();
setupSensors();
setupBLE();
#ifdef DEBUG
Serial.println("Setup finished.");
Serial.println("=========================================");
#endif
}
/**
*
*/
void loop() {
if (!bBleConnected) { // when BLE is not connected.
#ifdef DEBUG
Serial.println("<<< Wake up <<<");
#endif
wakeupSensors();
wakeupBLE();
getSensors();
sleepSensors();
writeEEPROM();
StartAdvData();
if (onClickedFlag) { // onClicked Interrupt
onClickedFlag = false;
#ifdef DEBUG
Serial.println("STM32 on Clicked!");
Serial.print("Start advertising ");
Serial.print(click_wake_intval);
Serial.println(" seconds.");
Serial.flush();
#endif
// Continue Advertising; (check BLE status every 0.1 secound.)
for (int i = 0; i < click_wake_intval * 10; i++) {
delay(100);
// check ble status; if connection requested, my_evt_le_connection_opend handler is called.
ble112.checkActivity();
}
} else { // Normal operation
#ifdef DEBUG
Serial.print("Start advertising (");
Serial.print(wake_intval);
Serial.println("s)");
#endif
// Continue Advertising;
for (int i = 0; i <= wake_intval * 10; i++) {
delay(100);
// don't check activity, if ble is not connectable during normal advertising operation.
// ble112.checkActivity();
}
// bBleConnected turns true at this time, when the connection is requested;
}
// when the connection is not requested, shutdown all devices during SLEEP_INTERVAL seconds;
if (!bBleConnected) {
// accel.setClick(DOUBLETAP, CLICKTHRESHHOLD); // Enable Interrupt
accel.getClick(); // Enable Interrupt
sleepAllDevices();
}
} else { // when ble is connected, this scope will run continuously.
if (mode == MODE_SEND_DATA) {
#ifdef DEBUG
Serial.println("Start to send data.");
#endif
for (int i = RINGBUFF_OFFSET_ADDR; i < EEPROM.length(); i += PACKET_LENGTH) {
char sendData[PACKET_LENGTH];
for (int j=0; j<PACKET_LENGTH; j++) {
sendData[j] = EEPROM.read(i + j);
}
ble112.ble_cmd_gatt_server_send_characteristic_notification(1, 0x000C, PACKET_LENGTH, (const uint8_t *)sendData);
while (ble112.checkActivity(1000));
}
#ifdef DEBUG
Serial.println("Finish to send data.");
#endif
// after all the data trasnported,
ble112.ble_cmd_gatt_server_send_characteristic_notification(1, 0x000C, 6, (const uint8_t *)"finish");
while (ble112.checkActivity(1000));
mode = MODE_IDLE;
}
else if (mode == MODE_CLEAR_EEPROM) {
for(int i = RINGBUFF_OFFSET_ADDR; i < EEPROM.length(); i++) {
EEPROM.write(i, 0);
#ifdef DEBUG
if (i % 10 == 0) {
Serial.print(i);
Serial.print("/");
Serial.println(EEPROM.length() - RINGBUFF_OFFSET_ADDR);
char sendData[PACKET_LENGTH];
uint8_t len = sprintf(sendData, "%05d", i);
ble112.ble_cmd_gatt_server_send_characteristic_notification(1, 0x000C, len, (const uint8_t *)sendData);
while (ble112.checkActivity(1000));
}
#endif
}
ble112.ble_cmd_gatt_server_send_characteristic_notification(1, 0x000C, 6, (const uint8_t *)"finish");
while (ble112.checkActivity(1000));
mode = MODE_IDLE;
} else { // MODE_IDLE
ble112.checkActivity(100);
}
}
}
// ================================================================
// INTERNAL BGLIB CLASS CALLBACK FUNCTIONS
// ================================================================
// called when the module begins sending a command
void onBusy()
{
}
// called when the module receives a complete response or "system_boot" event
void onIdle()
{
}
// called when the parser does not read the expected response in the specified time limit
void onTimeout()
{
ble_state = BLE_STATE_STANDBY;
}
// called immediately before beginning UART TX of a command
void onBeforeTXCommand()
{
}
// called immediately after finishing UART TX
void onTXCommandComplete()
{
// allow module to return to sleep (assuming here that digital pin 5 is connected to the BLE wake-up pin)
}
// called when the attribute value changed
void my_evt_gatt_server_attribute_value(const struct ble_msg_gatt_server_attribute_value_evt_t *msg)
{
uint16 attribute = (uint16)msg->attribute;
uint16 offset = 0;
uint8 value_len = msg->value.len;
uint8 value_data[20];
String rcv_data;
rcv_data = "";
for (uint8_t i = 0; i < value_len; i++)
{
rcv_data += (char)(msg->value.data[i]);
}
#ifdef DEBUG
Serial.print("###\tgatt_server_attribute_value: { ");
Serial.print("connection: ");
Serial.print(msg->connection, HEX);
Serial.print(", attribute: ");
Serial.print((uint16_t)msg->attribute, HEX);
Serial.print(", att_opcode: ");
Serial.print(msg->att_opcode, HEX);
Serial.print(", offset: ");
Serial.print((uint16_t)msg->offset, HEX);
Serial.print(", value_len: ");
Serial.print(msg->value.len, HEX);
Serial.print(", value_data: ");
Serial.print(rcv_data);
Serial.println(" }");
#endif
// Received BLE Commands
if (rcv_data.startsWith("getData"))
{
// Start to send EEPROM data
mode = MODE_SEND_DATA;
}
else if (rcv_data.startsWith("getRomSize"))
{
char sendData[8];
uint8_t len = sprintf(sendData, "%06d", EEPROM.length());
ble112.ble_cmd_gatt_server_send_characteristic_notification(1, 0x000C, len, (const uint8_t *)sendData);
while (ble112.checkActivity(1000));
}
else if (rcv_data.startsWith("getSleep"))
{
// send SLEEP_INTERVAL
char sendData[8];
uint8_t len = sprintf(sendData, "%05d", (int)sleep_intval);
ble112.ble_cmd_gatt_server_send_characteristic_notification(1, 0x000C, len, (const uint8_t *)sendData);
while (ble112.checkActivity(1000));
}
else if (rcv_data.startsWith("getWake"))
{
// send WAKE_INTERVAL
char sendData[8];
uint8_t len = sprintf(sendData, "%05d", (int)wake_intval);
ble112.ble_cmd_gatt_server_send_characteristic_notification(1, 0x000C, len, (const uint8_t *)sendData);
while (ble112.checkActivity(1000));
}
else if (rcv_data.startsWith("getSensFreq"))
{
// send SENS_FREQ
char sendData[8];
uint8_t len = sprintf(sendData, "%05d", (int)sens_freq);
ble112.ble_cmd_gatt_server_send_characteristic_notification(1, 0x000C, len, (const uint8_t *)sendData);
while (ble112.checkActivity(1000));
}
else if (rcv_data.startsWith("getSaveFreq"))
{
// send SAVE_FREQ
char sendData[8];
uint8_t len = sprintf(sendData, "%05d", (int)save_freq);
ble112.ble_cmd_gatt_server_send_characteristic_notification(1, 0x000C, len, (const uint8_t *)sendData);
while (ble112.checkActivity(1000));
}
else if (rcv_data.startsWith("setSleep"))
{
// rcv_data = "setSleep <SLEEP_INTERVAL>"
uint16_t num = rcv_data.substring(9).toInt();
EEPROM.write(4, (num >> 8) & 0xFF); // sleep_intval
EEPROM.write(5, (num & 0xFF)); // sleep_intval
sleep_intval = num;
#ifdef DEBUG
Serial.print("Sleep interval is changed. (");
Serial.print(num);
Serial.println("s)");
#endif
}
else if (rcv_data.startsWith("setWake"))
{
// rcv_data = "setWake <WAKE_INTERVAL>"
uint16_t num = rcv_data.substring(8).toInt();
EEPROM.write(2, (num >> 8) & 0xFF); // wake_intval
EEPROM.write(3, (num & 0xFF)); // wake_intval
wake_intval = num;
#ifdef DEBUG
Serial.print("Wake interval is changed. (");
Serial.print(num);