1
6
7
12
13
14
15
16
17
18
19
20
21
26
30
31
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
102
103
104
108
112
113
114
115
120
121
122
123
127
128
129
130
134
135
136
137
138
139
140
141
142
/* ... */
#include "common.h"
#include "gap.h"
#include "gatt_svc.h"
#include "heart_rate.h"
#include "led.h"5 includes
void ble_store_config_init(void);
static void nimble_host_config_init(void);
static void nimble_host_task(void *param);
/* ... */
static void on_stack_reset(int reason) {
ESP_LOGI(TAG, "nimble stack reset, reset reason: %d", reason);
}{ ... }
static void on_stack_sync(void) {
adv_init();
}{ ... }
static void nimble_host_config_init(void) {
ble_hs_cfg.reset_cb = on_stack_reset;
ble_hs_cfg.sync_cb = on_stack_sync;
ble_hs_cfg.gatts_register_cb = gatt_svr_register_cb;
ble_hs_cfg.store_status_cb = ble_store_util_status_rr;
ble_hs_cfg.sm_io_cap = BLE_HS_IO_DISPLAY_ONLY;
ble_hs_cfg.sm_bonding = 1;
ble_hs_cfg.sm_mitm = 1;
ble_hs_cfg.sm_our_key_dist |= BLE_SM_PAIR_KEY_DIST_ENC | BLE_SM_PAIR_KEY_DIST_ID;
ble_hs_cfg.sm_their_key_dist |= BLE_SM_PAIR_KEY_DIST_ENC | BLE_SM_PAIR_KEY_DIST_ID;
ble_store_config_init();
}{ ... }
static void nimble_host_task(void *param) {
ESP_LOGI(TAG, "nimble host task has been started!");
nimble_port_run();
vTaskDelete(NULL);
}{ ... }
static void heart_rate_task(void *param) {
ESP_LOGI(TAG, "heart rate task has been started!");
while (1) {
update_heart_rate();
ESP_LOGI(TAG, "heart rate updated to %d", get_heart_rate());
send_heart_rate_indication();
vTaskDelay(HEART_RATE_TASK_PERIOD);
}{...}
vTaskDelete(NULL);
}{ ... }
void app_main(void) {
int rc;
uint32_t seed = esp_random();
esp_err_t ret;
led_init();
srand(seed);
/* ... */
ret = nvs_flash_init();
if (ret == ESP_ERR_NVS_NO_FREE_PAGES ||
ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
ESP_ERROR_CHECK(nvs_flash_erase());
ret = nvs_flash_init();
}{...}
if (ret != ESP_OK) {
ESP_LOGE(TAG, "failed to initialize nvs flash, error code: %d ", ret);
return;
}{...}
ret = nimble_port_init();
if (ret != ESP_OK) {
ESP_LOGE(TAG, "failed to initialize nimble stack, error code: %d ",
ret);
return;
}{...}
rc = gap_init();
if (rc != 0) {
ESP_LOGE(TAG, "failed to initialize GAP service, error code: %d", rc);
return;
}{...}
rc = gatt_svc_init();
if (rc != 0) {
ESP_LOGE(TAG, "failed to initialize GATT server, error code: %d", rc);
return;
}{...}
nimble_host_config_init();
xTaskCreate(nimble_host_task, "NimBLE Host", 4*1024, NULL, 5, NULL);
xTaskCreate(heart_rate_task, "Heart Rate", 4*1024, NULL, 5, NULL);
return;
}{ ... }