co2-firmware/components/BTlib/BTlib_nimble.c
2022-04-13 23:13:22 +02:00

86 lines
2.1 KiB
C

#include "BTlib_nimble.h"
#include "nimble/ble.h"
#include "esp_nimble_hci.h"
#include "nimble/nimble_port.h"
#include "services/gap/ble_svc_gap.h"
#include "services/gatt/ble_svc_gatt.h"
#include "nimble/nimble_port_freertos.h"
static uint8_t ble_addr_type;
static void ble_advertise(void){
ESP_ERROR_CHECK(ble_gap_adv_set_fields(&adv_fields));
ESP_ERROR_CHECK(ble_gap_adv_start(ble_addr_type, NULL, BLE_HS_FOREVER, &adv_params, ble_gap_event, NULL));
}
static int ble_gap_event(struct ble_gap_event *event, void* arg){
switch(event->type){
case BLE_GAP_EVENT_CONNECT:
ESP_LOGI(NIMBLE_LOG_TAG, "connect event");
if(event->connect.status)
ble_advertise();
conn_handle = event->connect.conn_handle;
break;
case BLE_GAP_EVENT_DISCONNECT:
ESP_LOGI(NIMBLE_LOG_TAG, "disconnect event");
ble_advertise();
break;
case BLE_GAP_EVENT_ADV_COMPLETE:
ESP_LOGI(NIMBLE_LOG_TAG, "adv complete");
ble_advertise();
break;
case BLE_GAP_EVENT_SUBSCRIBE:
ESP_LOGI(NIMBLE_LOG_TAG, "subscribe event notify : %b", notify_state);
if(event->subscribe.attr_handle == es_hrm_handle)
notify_state = event->subscribe.cur_notify;
break;
case BLE_GAP_EVENT_MTU:
ESP_LOGI(NIMBLE_LOG_TAG, "MTU event");
break;
}
return ESP_OK;
}
static int gatt_svr_init(void){
ble_svc_gap_init();
ble_svc_gatt_init();
int res;
res = ble_gatts_count_cfg(gatt_svr_svcs);
if(res)
return res;
res = ble_gatts_add_svcs(gatt_svr_svcs);
return res;
}
static void ble_on_sync(void){
//TODO
ESP_LOGI(NIMBLE_LOG_TAG, "on sync event");
ble_advertise();
}
static void ble_on_reset(int reason){
ESP_LOGI(NIMBLE_LOG_TAG, "on reset event %d", reason);
}
static void ble_host_task(void* param){
nimble_port_run();
// return on stop
nimble_port_freertos_deinit();
}
void initBle(configuration_data_t* main_conf){
ESP_ERROR_CHECK(esp_nimble_hci_and_controller_init());
nimble_port_init();
ble_hs_cfg.sync_cb = ble_on_sync;
ble_hs_cfg.reset_cb = ble_on_reset;
ESP_ERROR_CHECK(gatt_srv_init());
ESP_ERROR_CHECK(ble_svc_gap_device_name_set(main_conf->hostname));
nimble_port_freertos_init(ble_host_task);
}