-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.c
3427 lines (2913 loc) · 130 KB
/
main.c
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
/*
* main.c
*
* Copyright (C) 2019 takurx, Yoshihiro Nakagawa <taku3wzr@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Copyright (c) 2014 - 2018, Nordic Semiconductor ASA
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
/** @file
*
* @defgroup ble_sdk_uart_over_ble_main main.c
* @{
* @ingroup ble_sdk_app_nus_eval
* @brief UART over BLE application main file.
*
* This file contains the source code for a sample application that uses the Nordic UART service.
* This application uses the @ref srvlib_conn_params module.
*/
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include "nrf.h"
#include "nrf_drv_saadc.h"
#include "nrf_drv_ppi.h"
#include "nrf_drv_timer.h"
#include "nrf_gpio.h"
#include "nrf_drv_gpiote.h"
#include "nrf_drv_rtc.h"
#include "nrf_drv_clock.h"
#include "boards.h"
#include "nrf_delay.h"
#include "app_error.h"
#include "ble.h"
#include "ble_err.h"
#include "ble_hci.h"
#include "ble_srv_common.h"
#include "ble_advdata.h"
#include "ble_advertising.h"
#include "ble_bas.h"
#include "ble_hrs.h"
#include "ble_hts.h"
#include "ble_dis.h"
#include "ble_conn_params.h"
#include "sensorsim.h"
#include "nrf_sdh.h"
#include "nrf_sdh_soc.h"
#include "nrf_sdh_ble.h"
#include "app_timer.h"
#include "peer_manager.h"
#include "peer_manager_handler.h"
#include "ble_nus.h"
#include "app_uart.h"
#include "app_util_platform.h"
#include "app_error.h"
#include "nrf_drv_twi.h"
#include "nrf_delay.h"
#include <bh1792.h>
#include <hr_bh1792.h>
#include "bsp_btn_ble.h"
#include "fds.h"
#include "ble_conn_state.h"
#include "nrf_ble_gatt.h"
#include "nrf_ble_qwr.h"
#include "nrf_pwr_mgmt.h"
#if defined (UART_PRESENT)
#include "nrf_uart.h"
#endif
#if defined (UARTE_PRESENT)
#include "nrf_uarte.h"
#endif
#include "nrf_log.h"
#include "nrf_log_ctrl.h"
#include "nrf_log_default_backends.h"
#include "nrf_drv_clock.h"
#include "nrf_fstorage.h"
#include "nrf_fstorage_sd.h"
#define FIRMWARE_VERSION "2p0p4" /* Firmware version, 'ver' command on NUS, :'major'p'minor'p'revision'*/
#define DEVICE_NAME "Herbio+" /**< Name of device. Will be included in the advertising data. */
#define NUS_SERVICE_UUID_TYPE BLE_UUID_TYPE_VENDOR_BEGIN /**< UUID type for the Nordic UART Service (vendor specific). */
#define MANUFACTURER_NAME "Herbio Co., Ltd." /**< Manufacturer. Will be passed to Device Information Service. */
//#define MODEL_NUM "EXAMPLE" /**< Model number. Will be passed to Device Information Service. */
#define MANUFACTURER_ID 0x1122334455 /**< Manufacturer ID, part of System ID. Will be passed to Device Information Service. */
#define ORG_UNIQUE_ID 0x667788 /**< Organizational Unique ID, part of System ID. Will be passed to Device Information Service. */
#define APP_BLE_OBSERVER_PRIO 3 /**< Application's BLE observer priority. You shouldn't need to modify this value. */
#define APP_BLE_CONN_CFG_TAG 1 /**< A tag identifying the SoftDevice BLE configuration. */
#define APP_ADV_INTERVAL 64 /**< The advertising interval (in units of 0.625 ms. This value corresponds to 40 ms). */
#define APP_ADV_DURATION 18000 /**< The advertising duration (180 seconds) in units of 10 milliseconds. */
#define MIN_CONN_INTERVAL MSEC_TO_UNITS(20, UNIT_1_25_MS) /**< Minimum acceptable connection interval (20 ms), Connection interval uses 1.25 ms units. */
#define MAX_CONN_INTERVAL MSEC_TO_UNITS(75, UNIT_1_25_MS) /**< Maximum acceptable connection interval (75 ms), Connection interval uses 1.25 ms units. */
#define BATTERY_LEVEL_MEAS_INTERVAL APP_TIMER_TICKS(2000) /**< Battery level measurement interval (ticks). */
#define MIN_BATTERY_LEVEL 81 /**< Minimum battery level as returned by the simulated measurement function. */
#define MAX_BATTERY_LEVEL 100 /**< Maximum battery level as returned by the simulated measurement function. */
#define BATTERY_LEVEL_INCREMENT 1 /**< Value by which the battery level is incremented/decremented for each call to the simulated measurement function. */
#define HEART_RATE_MEAS_INTERVAL APP_TIMER_TICKS(1000) /**< Heart rate measurement interval (ticks). */
#define MIN_HEART_RATE 140 /**< Minimum heart rate as returned by the simulated measurement function. */
#define MAX_HEART_RATE 300 /**< Maximum heart rate as returned by the simulated measurement function. */
#define HEART_RATE_INCREMENT 10 /**< Value by which the heart rate is incremented/decremented for each call to the simulated measurement function. */
#define RR_INTERVAL_INTERVAL APP_TIMER_TICKS(300) /**< RR interval interval (ticks). */
#define MIN_RR_INTERVAL 100 /**< Minimum RR interval as returned by the simulated measurement function. */
#define MAX_RR_INTERVAL 500 /**< Maximum RR interval as returned by the simulated measurement function. */
#define RR_INTERVAL_INCREMENT 1 /**< Value by which the RR interval is incremented/decremented for each call to the simulated measurement function. */
#define TEMPERATURE_MEAS_INTERVAL APP_TIMER_TICKS(1000) /**< temperature measurement interval (ticks). */
#define MIN_TEMPERATURE 33 /**< Minimum temperature as returned by the simulated measurement function. */
#define MAX_TEMPERATURE 42 /**< Maximum temperature as returned by the simulated measurement function. */
#define TEMPERATURE_INCREMENT 1 /**< Value by which the temperature is incremented/decremented for each call to the simulated measurement function. */
#define SENSOR_CONTACT_DETECTED_INTERVAL APP_TIMER_TICKS(5000) /**< Sensor Contact Detected toggle interval (ticks). */
//#define DEBUG_MEAS_INTERVAL 1
//#define TWI_DISABLE 1
#define CODE_NOT_WEARING 1 /**< heartbeat not measuring, not wearing or not start >**/
#ifndef DEBUG_MEAS_INTERVAL
#define DATA_RECORD_MEAS_INTERVAL APP_TIMER_TICKS(10000) /**< Body Temp. and Heart rate data record interval (ticks). */
#else
//for debug setting
#define DATA_RECORD_MEAS_INTERVAL APP_TIMER_TICKS(100) /**< Body Temp. and Heart rate data record interval (ticks). */
#endif
#define DATA_OUTPUT_INTERVAL APP_TIMER_TICKS(25) /**< nus(nordic uart service) data output interval (ticks). */
//#define DATA_OUTPUT_INTERVAL APP_TIMER_TICKS(40) /**< nus(nordic uart service) data output interval (ticks). */
#define TEMP_TYPE_AS_CHARACTERISTIC 0 /**< Determines if temperature type is given as characteristic (1) or as a field of measurement (0). */
#define MIN_CELCIUS_DEGREES 3688 /**< Minimum temperature in celcius for use in the simulated measurement function (multiplied by 100 to avoid floating point arithmetic). */
#define MAX_CELCIUS_DEGRESS 3972 /**< Maximum temperature in celcius for use in the simulated measurement function (multiplied by 100 to avoid floating point arithmetic). */
#define CELCIUS_DEGREES_INCREMENT 36 /**< Value by which temperature is incremented/decremented for each call to the simulated measurement function (multiplied by 100 to avoid floating point arithmetic). */
#define SLAVE_LATENCY 0 /**< Slave latency. */
#define CONN_SUP_TIMEOUT MSEC_TO_UNITS(4000, UNIT_10_MS) /**< Connection supervisory timeout (4 seconds). */
#define FIRST_CONN_PARAMS_UPDATE_DELAY APP_TIMER_TICKS(5000) /**< Time from initiating event (connect or start of indication) to first time sd_ble_gap_conn_param_update is called (5 seconds). */
#define NEXT_CONN_PARAMS_UPDATE_DELAY APP_TIMER_TICKS(30000) /**< Time between each call to sd_ble_gap_conn_param_update after the first call (30 seconds). */
#define MAX_CONN_PARAMS_UPDATE_COUNT 3 /**< Number of attempts before giving up the connection parameter negotiation. */
#define SEC_PARAM_BOND 1 /**< Perform bonding. */
#define SEC_PARAM_MITM 0 /**< Man In The Middle protection not required. */
#define SEC_PARAM_LESC 0 /**< LE Secure Connections not enabled. */
#define SEC_PARAM_KEYPRESS 0 /**< Keypress notifications not enabled. */
#define SEC_PARAM_IO_CAPABILITIES BLE_GAP_IO_CAPS_NONE /**< No I/O capabilities. */
#define SEC_PARAM_OOB 0 /**< Out Of Band data not available. */
#define SEC_PARAM_MIN_KEY_SIZE 7 /**< Minimum encryption key size. */
#define SEC_PARAM_MAX_KEY_SIZE 16 /**< Maximum encryption key size. */
#define DEAD_BEEF 0xDEADBEEF /**< Value used as error code on stack dump, can be used to identify stack location on stack unwind. */
#define UART_TX_BUF_SIZE 256 /**< UART TX buffer size. */
#define UART_RX_BUF_SIZE 256 /**< UART RX buffer size. */
BLE_NUS_DEF(m_nus, NRF_SDH_BLE_TOTAL_LINK_COUNT); /**< BLE NUS service instance. */
BLE_HRS_DEF(m_hrs); /**< Heart rate service instance. */
APP_TIMER_DEF(m_battery_timer_id); /**< Battery timer. */
BLE_BAS_DEF(m_bas); /**< Structure used to identify the battery service. */
BLE_HTS_DEF(m_hts);
NRF_BLE_GATT_DEF(m_gatt); /**< GATT module instance. */
NRF_BLE_QWR_DEF(m_qwr); /**< Context for the Queued Write module.*/
BLE_ADVERTISING_DEF(m_advertising); /**< Advertising module instance. */
APP_TIMER_DEF(m_heart_rate_timer_id); /**< Heart rate measurement timer. */
APP_TIMER_DEF(m_rr_interval_timer_id); /**< RR interval timer. */
APP_TIMER_DEF(m_sensor_contact_timer_id); /**< Sensor contact detected timer. */
APP_TIMER_DEF(m_temperature_timer_id); /**< Temperature measurement timer. */
APP_TIMER_DEF(m_data_record_timer_id); /**< Measurement data record timer. */
APP_TIMER_DEF(m_data_output_timer_id); /**< Measurement data output timer. */
static uint16_t m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - 3; /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
static bool m_rr_interval_enabled = true; /**< Flag for enabling and disabling the registration of new RR interval measurements (the purpose of disabling this is just to test sending HRM without RR interval data. */
static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; /**< Handle of the current connection. */
static bool m_hts_meas_ind_conf_pending = false; /**< Flag to keep track of when an indication confirmation is pending. */
static sensorsim_cfg_t m_battery_sim_cfg; /**< Battery Level sensor simulator configuration. */
static sensorsim_state_t m_battery_sim_state; /**< Battery Level sensor simulator state. */
static sensorsim_cfg_t m_temp_celcius_sim_cfg; /**< Temperature simulator configuration. */
static sensorsim_state_t m_temp_celcius_sim_state; /**< Temperature simulator state. */
static sensorsim_cfg_t m_heart_rate_sim_cfg; /**< Heart Rate sensor simulator configuration. */
static sensorsim_state_t m_heart_rate_sim_state; /**< Heart Rate sensor simulator state. */
static sensorsim_cfg_t m_rr_interval_sim_cfg; /**< RR Interval sensor simulator configuration. */
static sensorsim_state_t m_rr_interval_sim_state; /**< RR Interval sensor simulator state. */
static ble_uuid_t m_sr_uuids[] = /**< Universally unique service identifier. */
{
{BLE_UUID_NUS_SERVICE, NUS_SERVICE_UUID_TYPE}
};
static ble_uuid_t m_adv_uuids[] = /**< Universally unique service identifier. */
{
{BLE_UUID_HEART_RATE_SERVICE, BLE_UUID_TYPE_BLE},
{BLE_UUID_HEALTH_THERMOMETER_SERVICE, BLE_UUID_TYPE_BLE},
{BLE_UUID_BATTERY_SERVICE, BLE_UUID_TYPE_BLE},
{BLE_UUID_DEVICE_INFORMATION_SERVICE, BLE_UUID_TYPE_BLE}
};
#define SAMPLES_IN_BUFFER 1
static const nrf_drv_timer_t m_timer = NRF_DRV_TIMER_INSTANCE(1);
static nrf_saadc_value_t m_buffer_pool[2][SAMPLES_IN_BUFFER];
static nrf_ppi_channel_t m_ppi_channel;
//typedef enum
//{
static const int STATE_ADVERTISING = 0; // 0: Blink GREEN: Advertising that Before Pairing
static const int STATE_PAIRING = 1; // 1: GREEN: Pairing and Idle state
static const int STATE_MEASURING = 2; // 2: RED: Measring state and Pairing
static const int STATE_EMERGENCY = 3; // 3: Blink GREEN and RED: Emergency
static const int STATE_MEASURINGADVERTISING = 4; // 4: Blink RED: Measuring and Adverting
static const int STATE_BOOTING = 5; // 5: BLUE: boot, reboot from sleep
static const int STATE_SLEEPING = 6; // 6: Blink BLUE: go to sleep
//}
static volatile int State_keeper = STATE_ADVERTISING;
static volatile bool State_emergency_lock = false;
/* TWI instance ID. */
#define TWI_INSTANCE_ID 0
//#ifdef BSP_BUTTON_0
// #define PIN_IN BSP_BUTTON_0
#ifdef BSP_BUTTON_3
#define PIN_IN BSP_BUTTON_3
#endif
#ifndef PIN_IN
#error "Please indicate input pin"
#endif
//#ifdef BSP_LED_0
// #define PIN_OUT BSP_LED_0
#ifdef BSP_LED_3
#define PIN_OUT BSP_LED_3
#endif
#ifndef PIN_OUT
#error "Please indicate output pin"
#endif
APP_TIMER_DEF(m_bh1792glc_timer_id);
//#define BH1792GLC_MEAS_INTERVAL APP_TIMER_TICKS(1000) //1 Hz Timer
//#define BH1792GLC_MEAS_INTERVAL APP_TIMER_TICKS(25) //40 Hz Timer
//#define BH1792GLC_MEAS_INTERVAL APP_TIMER_TICKS(10) //100 Hz Timer
#define BH1792GLC_MEAS_INTERVAL APP_TIMER_TICKS(31) //32.258 Hz Timer
/* Indicates if operation on TWI has ended (when received). */
static volatile bool m_xfer_done = false;
/* TWI instance. */
static const nrf_drv_twi_t m_twi = NRF_DRV_TWI_INSTANCE(TWI_INSTANCE_ID);
volatile static bool twi_tx_done = false;
volatile static bool twi_rx_done = false;
bh1792_t m_bh1792;
bh1792_data_t m_bh1792_dat;
int32_t i2c_write(uint8_t slv_adr, uint8_t reg_adr, uint8_t *reg, uint8_t reg_size);
int32_t i2c_read(uint8_t slv_adr, uint8_t reg_adr, uint8_t *reg, uint8_t reg_size);
#define BH1792_TWI_TIMEOUT 10000
#define BH1792_TWI_BUFFER_SIZE 8 // 8byte = tx max(7) + addr(1)
uint8_t twi_tx_buffer[BH1792_TWI_BUFFER_SIZE];
static void advertising_start(bool erase_bonds);
static void temperature_measurement_send(void);
static void fstorage_evt_handler(nrf_fstorage_evt_t * p_evt);
NRF_FSTORAGE_DEF(nrf_fstorage_t fstorage) =
{
/* Set a handler for fstorage events. */
.evt_handler = fstorage_evt_handler,
/* These below are the boundaries of the flash space assigned to this instance of fstorage.
* You must set these manually, even at runtime, before nrf_fstorage_init() is called.
* The function nrf5_flash_end_addr_get() can be used to retrieve the last address on the
* last page of flash available to write data. */
.start_addr = 0x60000,
.end_addr = 0x6ffff,
};
/* Dummy data to write to flash. */
//static uint32_t m_data = 0xBADC0FFE;
//static char m_hello_world[] = "hello world";
/**@brief Helper function to obtain the last address on the last page of the on-chip flash that
* can be used to write user data.
*/
static uint32_t nrf5_flash_end_addr_get()
{
uint32_t const bootloader_addr = NRF_UICR->NRFFW[0];
uint32_t const page_sz = NRF_FICR->CODEPAGESIZE;
uint32_t const code_sz = NRF_FICR->CODESIZE;
return (bootloader_addr != 0xFFFFFFFF ?
bootloader_addr : (code_sz * page_sz));
}
static void fstorage_evt_handler(nrf_fstorage_evt_t * p_evt)
{
if (p_evt->result != NRF_SUCCESS)
{
NRF_LOG_INFO("--> Event received: ERROR while executing an fstorage operation.");
return;
}
switch (p_evt->id)
{
case NRF_FSTORAGE_EVT_WRITE_RESULT:
{
NRF_LOG_INFO("--> Event received: wrote %d bytes at address 0x%x.",
p_evt->len, p_evt->addr);
} break;
case NRF_FSTORAGE_EVT_ERASE_RESULT:
{
NRF_LOG_INFO("--> Event received: erased %d page from address 0x%x.",
p_evt->len, p_evt->addr);
} break;
default:
break;
}
}
/**@brief Function for initializing the nrf log module.
*/
static void log_init(void)
{
ret_code_t err_code = NRF_LOG_INIT(NULL);
APP_ERROR_CHECK(err_code);
NRF_LOG_DEFAULT_BACKENDS_INIT();
}
/**@brief Function for handling app_uart events.
*
* @details This function will receive a single character from the app_uart module and append it to
* a string. The string will be be sent over BLE when the last character received was a
* 'new line' '\n' (hex 0x0A) or if the string has reached the maximum data length.
*/
/**@snippet [Handling the data received over UART] */
void uart_event_handle(app_uart_evt_t * p_event)
{
static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
static uint8_t index = 0;
uint32_t err_code;
switch (p_event->evt_type)
{
case APP_UART_DATA_READY:
UNUSED_VARIABLE(app_uart_get(&data_array[index]));
index++;
if ((data_array[index - 1] == '\n') ||
(data_array[index - 1] == '\r') ||
(index >= m_ble_nus_max_data_len))
{
if (index > 1)
{
NRF_LOG_DEBUG("Ready to send data over BLE NUS");
NRF_LOG_HEXDUMP_DEBUG(data_array, index);
do
{
uint16_t length = (uint16_t)index;
err_code = ble_nus_data_send(&m_nus, data_array, &length, m_conn_handle);
if ((err_code != NRF_ERROR_INVALID_STATE) &&
(err_code != NRF_ERROR_RESOURCES) &&
(err_code != NRF_ERROR_NOT_FOUND))
{
APP_ERROR_CHECK(err_code);
}
} while (err_code == NRF_ERROR_RESOURCES);
}
index = 0;
}
break;
case APP_UART_COMMUNICATION_ERROR:
APP_ERROR_HANDLER(p_event->data.error_communication);
break;
case APP_UART_FIFO_ERROR:
APP_ERROR_HANDLER(p_event->data.error_code);
break;
default:
break;
}
}
/**@snippet [Handling the data received over UART] */
#define EBSHCNZWZ_RX_PIN_NUMBER 24
#define EBSHCNZWZ_TX_PIN_NUMBER 25
#define EBSHCNZWZ_RTS_PIN_NUMBER 26
#define EBSHCNZWZ_CTS_PIN_NUMBER 27
/**@brief Function for initializing the UART module.
*/
/**@snippet [UART Initialization] */
static void uart_init(void)
{
uint32_t err_code;
app_uart_comm_params_t const comm_params =
{
.rx_pin_no = EBSHCNZWZ_RX_PIN_NUMBER,
.tx_pin_no = EBSHCNZWZ_TX_PIN_NUMBER,
.rts_pin_no = EBSHCNZWZ_RTS_PIN_NUMBER,
.cts_pin_no = EBSHCNZWZ_CTS_PIN_NUMBER,
.flow_control = APP_UART_FLOW_CONTROL_DISABLED,
.use_parity = false,
#if defined (UART_PRESENT)
.baud_rate = NRF_UART_BAUDRATE_115200
#else
.baud_rate = NRF_UARTE_BAUDRATE_115200
#endif
};
APP_UART_FIFO_INIT(&comm_params,
UART_RX_BUF_SIZE,
UART_TX_BUF_SIZE,
uart_event_handle,
APP_IRQ_PRIORITY_LOWEST,
err_code);
APP_ERROR_CHECK(err_code);
}
/**@snippet [UART Initialization] */
/**@brief Function starting the internal LFCLK oscillator.
*
* @details This is needed by RTC1 which is used by the Application Timer
* (When SoftDevice is enabled the LFCLK is always running and this is not needed).
*/
static void lfclk_request(void)
{
ret_code_t err_code = nrf_drv_clock_init();
APP_ERROR_CHECK(err_code);
nrf_drv_clock_lfclk_request(NULL);
}
/**
* @brief Function for configuring: PIN_IN pin for input, PIN_OUT pin for output,
* and configures GPIOTE to give an interrupt on pin change.
*/
#define LED_3_COLOR_BLUE_PIN 20
#define LED_3_COLOR_GREEN_PIN 18
#define LED_3_COLOR_RED_PIN 4
#define SWITCH1_PIN 8
#define BH1792GLC_SCL_PIN 7
#define BH1792GLC_SDA_PIN 6
#define BH1792GLC_INT_PIN 5
void bh1792_isr(nrf_drv_gpiote_pin_t pin, nrf_gpiote_polarity_t action);
static volatile bool LED_output_state = true;
void in_pin_handler(nrf_drv_gpiote_pin_t pin, nrf_gpiote_polarity_t action)
{
LED_output_state = !LED_output_state;
}
static void gpio_init(void)
{
ret_code_t err_code;
err_code = nrf_drv_gpiote_init();
APP_ERROR_CHECK(err_code);
// bh1792glc, arudino_10_pin, 5
nrf_drv_gpiote_in_config_t in_config_bh1792 = GPIOTE_CONFIG_IN_SENSE_HITOLO(true); // interrupt when falling edge
in_config_bh1792.pull = NRF_GPIO_PIN_PULLUP;
err_code = nrf_drv_gpiote_in_init(BH1792GLC_INT_PIN, &in_config_bh1792, bh1792_isr);
APP_ERROR_CHECK(err_code);
#ifndef TWI_DISABLE
nrf_drv_gpiote_in_event_enable(BH1792GLC_INT_PIN, true);
//nrf_drv_gpiote_in_event_disable(BH1792GLC_INT_PIN);
#else
//nrf_drv_gpiote_in_event_enable(BH1792GLC_INT_PIN, false);
#endif
// 3-color LED LED_3_COLOR_BLUE_PIN, 20
nrf_drv_gpiote_out_config_t out_config_blue = GPIOTE_CONFIG_OUT_SIMPLE(true);
err_code = nrf_drv_gpiote_out_init(LED_3_COLOR_BLUE_PIN, &out_config_blue);
APP_ERROR_CHECK(err_code);
// 3-color LED LED_3_COLOR_GREEN_PIN, 18
nrf_drv_gpiote_out_config_t out_config_green = GPIOTE_CONFIG_OUT_SIMPLE(true);
err_code = nrf_drv_gpiote_out_init(LED_3_COLOR_GREEN_PIN, &out_config_green);
APP_ERROR_CHECK(err_code);
// 3-color LED LED_3_COLOR_RED_PIN, 4
nrf_drv_gpiote_out_config_t out_config_red = GPIOTE_CONFIG_OUT_SIMPLE(true);
err_code = nrf_drv_gpiote_out_init(LED_3_COLOR_RED_PIN, &out_config_red);
APP_ERROR_CHECK(err_code);
// SWITCH1, 8
nrf_drv_gpiote_in_config_t in_config_switch1 = GPIOTE_CONFIG_IN_SENSE_HITOLO(true);
in_config_switch1.pull = NRF_GPIO_PIN_PULLUP;
err_code = nrf_drv_gpiote_in_init(SWITCH1_PIN, &in_config_switch1, in_pin_handler);
APP_ERROR_CHECK(err_code);
nrf_drv_gpiote_in_event_enable(SWITCH1_PIN, true);
}
static void battery_level_meas_timeout_handler(void * p_context);
static void heart_rate_meas_timeout_handler(void * p_context);
static void rr_interval_timeout_handler(void * p_context);
static void temperature_meas_timeout_handler(void * p_context);
static void sensor_contact_detected_timeout_handler(void * p_context);
static void bh1792glc_meas_timeout_handler(void * p_context);
static void meas_data_record_timeout_handler(void * p_context);
static void meas_data_output_timeout_handler(void * p_context);
/**@brief Function for initializing the timer module.
*/
static void timers_init(void)
{
ret_code_t err_code;
// Initialize timer module.
err_code = app_timer_init();
APP_ERROR_CHECK(err_code);
// Create timers.
err_code = app_timer_create(&m_battery_timer_id,
APP_TIMER_MODE_REPEATED,
battery_level_meas_timeout_handler);
APP_ERROR_CHECK(err_code);
err_code = app_timer_create(&m_heart_rate_timer_id,
APP_TIMER_MODE_REPEATED,
heart_rate_meas_timeout_handler);
APP_ERROR_CHECK(err_code);
err_code = app_timer_create(&m_rr_interval_timer_id,
APP_TIMER_MODE_REPEATED,
rr_interval_timeout_handler);
APP_ERROR_CHECK(err_code);
err_code = app_timer_create(&m_temperature_timer_id,
APP_TIMER_MODE_REPEATED,
temperature_meas_timeout_handler);
APP_ERROR_CHECK(err_code);
err_code = app_timer_create(&m_sensor_contact_timer_id,
APP_TIMER_MODE_REPEATED,
sensor_contact_detected_timeout_handler);
APP_ERROR_CHECK(err_code);
err_code = app_timer_create(&m_bh1792glc_timer_id,
APP_TIMER_MODE_REPEATED,
bh1792glc_meas_timeout_handler);
APP_ERROR_CHECK(err_code);
err_code = app_timer_create(&m_data_record_timer_id,
APP_TIMER_MODE_REPEATED,
meas_data_record_timeout_handler);
APP_ERROR_CHECK(err_code);
err_code = app_timer_create(&m_data_output_timer_id,
APP_TIMER_MODE_REPEATED,
meas_data_output_timeout_handler);
APP_ERROR_CHECK(err_code);
}
/**@brief Function for performing a battery measurement, and update the Battery Level characteristic in the Battery Service.
*/
volatile float Battery_percent = 0.0;
static void battery_level_update(void)
{
ret_code_t err_code;
uint8_t battery_level;
//battery_level = (uint8_t)sensorsim_measure(&m_battery_sim_state, &m_battery_sim_cfg);
battery_level = (uint8_t)(Battery_percent);
err_code = ble_bas_battery_level_update(&m_bas, battery_level, BLE_CONN_HANDLE_ALL);
if ((err_code != NRF_SUCCESS) &&
(err_code != NRF_ERROR_INVALID_STATE) &&
(err_code != NRF_ERROR_RESOURCES) &&
(err_code != NRF_ERROR_BUSY) &&
(err_code != BLE_ERROR_GATTS_SYS_ATTR_MISSING) &&
(err_code != NRF_ERROR_FORBIDDEN)
)
{
APP_ERROR_HANDLER(err_code);
}
}
/**@brief Function for handling the Battery measurement timer timeout.
*
* @details This function will be called each time the battery level measurement timer expires.
*
* @param[in] p_context Pointer used for passing some arbitrary information (context) from the
* app_start_timer() call to the timeout handler.
*/
static void battery_level_meas_timeout_handler(void * p_context)
{
UNUSED_PARAMETER(p_context);
battery_level_update();
}
/**@brief Function for handling the Heart rate measurement timer timeout.
*
* @details This function will be called each time the heart rate measurement timer expires.
* It will exclude RR Interval data from every third measurement.
*
* @param[in] p_context Pointer used for passing some arbitrary information (context) from the
* app_start_timer() call to the timeout handler.
*/
bool Debug_output_heart_rate = false;
bool Debug_output_body_temperature = false;
bool Debug_output_battery_temperature = false;
bool Debug_output_battery_voltage = false;
bool Debug_output_current_time = true;
uint8_t Bpm = 0U;
uint8_t Wearing = 0U;
static void heart_rate_meas_timeout_handler(void * p_context)
{
static uint32_t cnt = 0;
ret_code_t err_code;
uint16_t heart_rate;
UNUSED_PARAMETER(p_context);
//heart_rate = (uint16_t)sensorsim_measure(&m_heart_rate_sim_state, &m_heart_rate_sim_cfg);
heart_rate = Bpm;
cnt++;
err_code = ble_hrs_heart_rate_measurement_send(&m_hrs, heart_rate);
if ((err_code != NRF_SUCCESS) &&
(err_code != NRF_ERROR_INVALID_STATE) &&
(err_code != NRF_ERROR_RESOURCES) &&
(err_code != NRF_ERROR_BUSY) &&
(err_code != BLE_ERROR_GATTS_SYS_ATTR_MISSING) &&
(err_code != NRF_ERROR_FORBIDDEN)
)
{
APP_ERROR_HANDLER(err_code);
}
// Disable RR Interval recording every third heart rate measurement.
// NOTE: An application will normally not do this. It is done here just for testing generation
// of messages without RR Interval measurements.
m_rr_interval_enabled = ((cnt % 3) != 0);
}
/**@brief Function for handling the RR interval timer timeout.
*
* @details This function will be called each time the RR interval timer expires.
*
* @param[in] p_context Pointer used for passing some arbitrary information (context) from the
* app_start_timer() call to the timeout handler.
*/
static void rr_interval_timeout_handler(void * p_context)
{
UNUSED_PARAMETER(p_context);
if (m_rr_interval_enabled)
{
uint16_t rr_interval;
rr_interval = (uint16_t)sensorsim_measure(&m_rr_interval_sim_state,
&m_rr_interval_sim_cfg);
ble_hrs_rr_interval_add(&m_hrs, rr_interval);
}
}
/**@brief Function for populating simulated health thermometer measurement.
*/
volatile float Body_temperature = 0.0;
volatile float Battery_temperature = 0.0;
static ble_date_time_t time_stamp = { 2019, 7, 31, 19, 8, 40 };
static const int month_days[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
static void hts_measurement(ble_hts_meas_t * p_meas)
{
uint32_t celciusX100;
p_meas->temp_in_fahr_units = false;
p_meas->time_stamp_present = true;
p_meas->temp_type_present = (TEMP_TYPE_AS_CHARACTERISTIC ? false : true);
//celciusX100 = sensorsim_measure(&m_temp_celcius_sim_state, &m_temp_celcius_sim_cfg);
celciusX100 = (uint32_t)(Body_temperature * 100);
p_meas->temp_in_celcius.exponent = -2;
p_meas->temp_in_celcius.mantissa = celciusX100;
p_meas->temp_in_fahr.exponent = -2;
p_meas->temp_in_fahr.mantissa = (32 * 100) + ((celciusX100 * 9) / 5);
p_meas->time_stamp = time_stamp;
//p_meas->temp_type = BLE_HTS_TEMP_TYPE_FINGER;
p_meas->temp_type = BLE_HTS_TEMP_TYPE_BODY;
// update simulated time stamp
time_stamp.seconds++;
if (time_stamp.seconds > 59)
{
time_stamp.seconds = 0;
time_stamp.minutes++;
if (time_stamp.minutes > 59)
{
time_stamp.minutes = 0;
time_stamp.hours++;
if (time_stamp.hours > 23)
{
time_stamp.hours = 0;
time_stamp.day++;
if (time_stamp.day > month_days[time_stamp.month])
{
if (time_stamp.month == 2)
{
if ((time_stamp.year % 4 == 0 && time_stamp.year % 100 != 0) || (time_stamp.year % 400 == 0)) // leap year
{
if (time_stamp.day > month_days[time_stamp.month] + 1)
{
time_stamp.day = 1;
time_stamp.month++;
}
}
else // not leap year
{
time_stamp.day = 1;
time_stamp.month++;
}
}
else
{
time_stamp.day = 1;
time_stamp.month++;
if (time_stamp.month > 12)
{
time_stamp.month = 1;
time_stamp.year++;
}
}
}
}
}
}
if (Debug_output_current_time == true)
{
NRF_LOG_INFO("%04d-%02d-%02dT%02d:%02d:%02d", time_stamp.year, time_stamp.month, time_stamp.day, time_stamp.hours, time_stamp.minutes, time_stamp.seconds);
}
}
/**@brief Function for handling the Temperature measurement timer timeout.
*
* @details
*
* @param[in] p_context Pointer used for passing some arbitrary information (context) from the
* app_start_timer() call to the timeout handler.
*/
static void temperature_meas_timeout_handler(void * p_context)
{
ble_hts_meas_t simulated_meas;
ret_code_t err_code;
UNUSED_PARAMETER(p_context);
hts_measurement(&simulated_meas);
err_code = ble_hts_measurement_send(&m_hts, &simulated_meas);
switch (err_code)
{
case NRF_SUCCESS:
// Measurement was successfully sent, wait for confirmation.
m_hts_meas_ind_conf_pending = true;
break;
case NRF_ERROR_INVALID_STATE:
// Ignore error.
break;
default:
//APP_ERROR_HANDLER(err_code);
break;
}
if ((err_code != NRF_SUCCESS) &&
(err_code != NRF_ERROR_INVALID_STATE) &&
(err_code != NRF_ERROR_RESOURCES) &&
(err_code != NRF_ERROR_BUSY) &&
(err_code != BLE_ERROR_GATTS_SYS_ATTR_MISSING) &&
(err_code != NRF_ERROR_FORBIDDEN)
)
{
APP_ERROR_HANDLER(err_code);
}
}
/**@brief Function for handling the Sensor Contact Detected timer timeout.
*
* @details This function will be called each time the Sensor Contact Detected timer expires.
*
* @param[in] p_context Pointer used for passing some arbitrary information (context) from the
* app_start_timer() call to the timeout handler.
*/
static void sensor_contact_detected_timeout_handler(void * p_context)
{
static bool sensor_contact_detected = false;
UNUSED_PARAMETER(p_context);
sensor_contact_detected = !sensor_contact_detected;
ble_hrs_sensor_contact_detected_update(&m_hrs, sensor_contact_detected);
}
static void timer_isr(void * p_context)
{
//UNUSED_PARAMETER(p_context);
//NRF_LOG_INFO("timer_isr.");
int32_t ret = 0;
nrf_drv_gpiote_in_event_disable(BH1792GLC_INT_PIN);
//m_bh1792.prm.led_cur1 = BH1792_PRM_LED_CUR1_MA(0);
//m_bh1792.prm.led_cur2 = BH1792_PRM_LED_CUR2_MA(0);
pw_GetParam(BH1792_PRM_CTRL2_CUR_LED1, &(m_bh1792.prm.led_cur1));
pw_GetParam(BH1792_PRM_CTRL3_CUR_LED2, &(m_bh1792.prm.led_cur2));
ret = bh1792_SetParams();
//ret = bh1792_StartMeasure();
//error_check(ret, "bh1792_StartMeasure");
ret = hr_bh1792_StartMeasure();
//error_check(ret, "hr_bh1792_StartMeasure");
nrf_drv_gpiote_in_event_enable(BH1792GLC_INT_PIN, true);
}
/**@brief Function for handling the BH1792GLC measurement timer timeout.
*
* @details This function will be called each time BH1792GLC measurement timer expires.
*
* @param[in] p_context Pointer used for passing some arbitrary information (context) from the
* app_start_timer() call to the timeout handler.
*/
static void bh1792glc_meas_timeout_handler(void * p_context)
{
//NRF_LOG_INFO("bh1792glc measure timer interrupt.");
timer_isr(p_context);
}
/**
* @brief TWI events handler.
*/
void twi_handler(nrf_drv_twi_evt_t const * p_event, void * p_context)
{
switch(p_event->type)
{
case NRF_DRV_TWI_EVT_DONE:
switch(p_event->xfer_desc.type)
{
case NRF_DRV_TWI_XFER_TX:
twi_tx_done = true;
break;
case NRF_DRV_TWI_XFER_TXTX:
twi_tx_done = true;
break;
case NRF_DRV_TWI_XFER_RX:
twi_rx_done = true;
//m_xfer_done = true;
break;
case NRF_DRV_TWI_XFER_TXRX:
twi_rx_done = true;
//m_xfer_done = true;
break;
default:
break;
}
break;
case NRF_DRV_TWI_EVT_ADDRESS_NACK:
break;
case NRF_DRV_TWI_EVT_DATA_NACK:
break;
default:
break;
}
}
/**
* @brief Measurement data record events handler.
*/
#ifndef DEBUG_MEAS_INTERVAL
#define Num_of_data_hr_hr 256
static volatile unsigned int Count_10sec = 59; // 10 minutes
#else
//for debug setting
#define Num_of_data_hr_hr 32
//for debug setting
static volatile unsigned int Count_10sec = 9; // 100 seconds
#endif
static volatile unsigned int Meas10sec = 0;
static volatile unsigned int Write_index_data_hr_hr = 0;
static volatile unsigned int Read_index_data_hr_hr = 0;
static volatile unsigned int Count_index_data_hr_hr = 0;
/**@brief record every 10 mintutes,
* temprature: 6 points between 10 seconds
* heart_rate: 60 second average
*/
typedef struct
{
ble_date_time_t start_time; // 7byte = 56 = 16 + 8 + 8 + 8 + 8 + 8
//uint8_t reserved_0; // 1byte = 8
float body_temperature_array[6]; // 4byte = 32
uint16_t heart_rate; // 2byte = 16
uint16_t reserved_1; // 2byte = 16
} ble_data_ht_hr_t;