barback32/main/ble.c
Morgan 'ARR\!' Allen 30ae25fa04
Some checks are pending
ci/woodpecker/push/woodpecker Pipeline is pending
migrating to BAROS32 based BLE definitions
2024-11-15 15:39:49 -08:00

485 lines
13 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include "esp_system.h"
#include "esp_nimble_hci.h"
#include "nimble/nimble_port.h"
#include "nimble/nimble_port_freertos.h"
#include "host/ble_hs.h"
#include "host/util/util.h"
#include "services/gap/ble_svc_gap.h"
#include "services/bas/ble_svc_bas.h"
#include "driver/gpio.h"
#include "barback.h"
#include "baros.h"
#include "main.h"
#include "ble.h"
#include "pumps.h"
#define TAG "BLE"
#define CONFIG_CACO_MAX_SERVICES (10)
#define CACO_BLE_ADV_PERIOD (4000)
static const char *device_name = CONFIG_BARBACK_ID;
static uint8_t blehr_addr_type;
static uint16_t conn_handle;
static uint16_t ble_svc_handle;
static uint16_t svc_handle_button;
// ^^^OLD^^^
// |||NEW|||
typedef struct {
uint16_t conn_handle;
} barback_ble_t;
static uint16_t pump_duration_svc_val_handles[4];
static event_callback_handle_t callback_handlers[CONFIG_CACO_MAX_SERVICES] = { 0 };
static int ble_gap_event(struct ble_gap_event *event, void *arg);
static int svc_access_system(uint16_t conn_handle, uint16_t attr_handle, struct ble_gatt_access_ctxt *ctxt, void *arg);
static int barback_ble_char_access(uint16_t conn_handle, uint16_t attr_handle, struct ble_gatt_access_ctxt *ctxt, void *arg);
static barback_ble_access_t barback_ble_pump_access_enabled = {
.read = pumps_get_enabled,
.write = pumps_set_enabled
};
#define BLE_CHAR_PUMP_ENABLED(idx) {\
.uuid = BLE_UUID16_DECLARE(BAROS_BLE_SERVICE_PUMP_ENABLED + idx),\
.access_cb = barback_ble_char_access,\
.arg = &barback_ble_pump_access_enabled,\
.val_handle = &ble_svc_handle,\
.flags = BLE_GATT_CHR_F_NOTIFY | BLE_GATT_CHR_F_WRITE | BLE_GATT_CHR_F_READ\
}
static barback_ble_access_t barback_ble_pump_access_state = {
.read = pumps_get_running,
};
#define BLE_CHAR_PUMP_STATE(idx) {\
.uuid = BLE_UUID16_DECLARE(BAROS_BLE_SERVICE_PUMP_STATE + idx),\
.access_cb = barback_ble_char_access,\
.arg = &barback_ble_pump_access_state,\
.val_handle = &ble_svc_handle,\
.flags = BLE_GATT_CHR_F_NOTIFY | BLE_GATT_CHR_F_READ\
}
static barback_ble_access_t barback_ble_pump_access_duration = {
.read = pumps_get_duration,
.write = pumps_set_duration
};
#define BLE_CHAR_PUMP_DURATION(idx) {\
.uuid = BLE_UUID16_DECLARE(BAROS_BLE_SERVICE_PUMP_DURATION + idx),\
.access_cb = barback_ble_char_access,\
.arg = &barback_ble_pump_access_duration,\
.val_handle = &pump_duration_svc_val_handles[idx - 1],\
.flags = BLE_GATT_CHR_F_WRITE | BLE_GATT_CHR_F_NOTIFY | BLE_GATT_CHR_F_READ\
}
static const struct ble_gatt_svc_def service_defs[] = {
{
.type = BLE_GATT_SVC_TYPE_PRIMARY,
.uuid = BLE_UUID16_DECLARE(BAROS_BLE_SERVICE_PUMP_ENABLED),
.characteristics = (struct ble_gatt_chr_def[]) {
BLE_CHAR_PUMP_ENABLED(1),
BLE_CHAR_PUMP_ENABLED(2),
BLE_CHAR_PUMP_ENABLED(3),
BLE_CHAR_PUMP_ENABLED(4),
{ 0 }
},
}, {
.type = BLE_GATT_SVC_TYPE_PRIMARY,
.uuid = BLE_UUID16_DECLARE(BAROS_BLE_SERVICE_PUMP_STATE),
.characteristics = (struct ble_gatt_chr_def[]) {
BLE_CHAR_PUMP_STATE(1),
BLE_CHAR_PUMP_STATE(2),
BLE_CHAR_PUMP_STATE(3),
BLE_CHAR_PUMP_STATE(4),
{ 0 }
},
}, {
.type = BLE_GATT_SVC_TYPE_PRIMARY,
.uuid = BLE_UUID16_DECLARE(BAROS_BLE_SERVICE_PUMP_DURATION),
.characteristics = (struct ble_gatt_chr_def[]) {
BLE_CHAR_PUMP_DURATION(1),
BLE_CHAR_PUMP_DURATION(2),
BLE_CHAR_PUMP_DURATION(3),
BLE_CHAR_PUMP_DURATION(4),
{ 0 }
},
}, {
.type = BLE_GATT_SVC_TYPE_PRIMARY,
.uuid = BLE_UUID16_DECLARE(BAROS_BLE_SERVICE_BARBACK),
.characteristics = (struct ble_gatt_chr_def[]) {
{
.uuid = BLE_UUID16_DECLARE(BAROS_CHAR_POUR),
.access_cb = svc_access_system,
.val_handle = &ble_svc_handle,
.flags = BLE_GATT_CHR_F_WRITE | BLE_GATT_CHR_F_READ
}, {
.uuid = BLE_UUID16_DECLARE(BAROS_CHAR_BUTTON),
.access_cb = svc_access_system,
.val_handle = &svc_handle_button,
.flags = BLE_GATT_CHR_F_READ | BLE_GATT_CHR_F_NOTIFY
},
{ 0 }
}
},
{ 0 } // no more services
};
static int gatt_svr_chr_write(struct os_mbuf *om, uint16_t min_len, uint16_t max_len,
void *dst, uint16_t *len) {
uint16_t om_len;
int rc;
om_len = OS_MBUF_PKTLEN(om);
if (om_len < min_len || om_len > max_len) {
return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN;
}
rc = ble_hs_mbuf_to_flat(om, dst, max_len, len);
if (rc != 0) {
return BLE_ATT_ERR_UNLIKELY;
}
return 0;
}
static int svc_access_system(uint16_t conn_handle, uint16_t attr_handle, struct ble_gatt_access_ctxt *ctxt, void *arg) {
uint16_t uuid16 = ble_uuid_u16(ctxt->chr->uuid);
uint8_t value = 0;
ESP_LOGI(TAG, "0x%02X access: %d", uuid16, ctxt->op);
if(ctxt->op == BLE_GATT_ACCESS_OP_READ_CHR) {
} else if(ctxt->op == BLE_GATT_ACCESS_OP_WRITE_CHR) {
gatt_svr_chr_write(
ctxt->om,
sizeof value,
sizeof value,
&value, NULL
);
switch(uuid16) {
case BAROS_CHAR_POUR:
if(value == 1) {
ESP_LOGI(TAG, "starting pumps");
pumps_run();
} else {
ESP_LOGI(TAG, "stoping pumps");
pumps_stop();
}
break;
case BAROS_CHAR_BUTTON:
break;
}
}
return 0;
}
static int barback_ble_char_access(uint16_t conn_handle, uint16_t attr_handle, struct ble_gatt_access_ctxt *ctxt, void *arg) {
uint16_t chr_uuid = ble_uuid_u16(ctxt->chr->uuid);
// match the UUID against 0b111
uint8_t idx = (chr_uuid & 0x07) - 1;
uint8_t value = 0;
barback_ble_access_t *access = (barback_ble_access_t *)arg;
ESP_LOGI(TAG, "conn_handle: %d attr_handle: %d char: 0x%02X op: %s", conn_handle, attr_handle, chr_uuid, (ctxt->op == 0 ? "read" : ctxt->op == 1 ? "write" : "unknown"));
if(ctxt->op == BLE_GATT_ACCESS_OP_WRITE_CHR) {
gatt_svr_chr_write(
ctxt->om,
sizeof value,
sizeof value,
&value, NULL
);
struct ble_gap_conn_desc notifiee;
// TODO
// this could needs to be verified, it might actually be needed
// NiBLE could be passing notifications itself on chr_handler changes
for (uint16_t i = 0; i < CONFIG_NIMBLE_MAX_CONNECTIONS; i++) {
if(ble_gap_conn_find(i, &notifiee) == ESP_OK) {
ble_gattc_notify_custom(i, attr_handle, ctxt->om);
}
}
if(access == NULL) {
ESP_LOGI(TAG, "no read/write functions defined");
return 0;
}
if(access->write != NULL) {
ESP_LOGI(TAG, "calling BLE write function: %d %d", idx, value);
access->write(idx, value);
}
} else if(access != NULL && ctxt->op == BLE_GATT_ACCESS_OP_READ_CHR) {
if(access->read == NULL) {
ESP_LOGW(TAG, "Attempted read without defining access.read");
return 1;
}
uint8_t value = access->read(idx);
ESP_LOGI(TAG, "returning read idx: %d value: %d", idx, value);
os_mbuf_append(ctxt->om, &value, sizeof value);
}
return 0;
}
static void ble_advertise(void) {
// check if already adverting
if(ble_gap_adv_active()) return;
struct ble_gap_adv_params adv_params;
struct ble_hs_adv_fields fields;
int rc;
/*
* Set the advertisement data included in our advertisements:
* o Flags (indicates advertisement type and other general info)
* o Advertising tx power
* o Device name
*/
memset(&fields, 0, sizeof(fields));
/*
* Advertise two flags:
* o Discoverability in forthcoming advertisement (general)
* o BLE-only (BR/EDR unsupported)
*/
fields.flags = BLE_HS_ADV_F_DISC_GEN |
BLE_HS_ADV_F_BREDR_UNSUP;
/*
* Indicate that the TX power level field should be included; have the
* stack fill this value automatically. This is done by assigning the
* special value BLE_HS_ADV_TX_PWR_LVL_AUTO.
*/
fields.tx_pwr_lvl_is_present = 1;
fields.tx_pwr_lvl = BLE_HS_ADV_TX_PWR_LVL_AUTO;
fields.name = (uint8_t *)device_name;
fields.name_len = strlen(device_name);
fields.name_is_complete = 1;
rc = ble_gap_adv_set_fields(&fields);
if (rc != 0) {
ESP_LOGE(TAG, "error setting advertisement data; rc=%d\n", rc);
return;
}
/* Begin advertising */
memset(&adv_params, 0, sizeof(adv_params));
adv_params.conn_mode = BLE_GAP_CONN_MODE_UND;
adv_params.disc_mode = BLE_GAP_DISC_MODE_GEN;
rc = ble_gap_adv_start(blehr_addr_type, NULL, BLE_HS_FOREVER,
&adv_params, ble_gap_event, NULL);
if (rc != 0) {
ESP_LOGE(TAG, "error enabling advertisement; rc=%d\n", rc);
return;
}
}
static int ble_gap_event(struct ble_gap_event *event, void *arg) {
switch (event->type) {
case BLE_GAP_EVENT_DISC: {
struct ble_hs_adv_fields fields;
ESP_ERROR_CHECK(ble_hs_adv_parse_fields(&fields, event->disc.data, event->disc.length_data));
if(fields.name != NULL) {
char *name = (char*)malloc(fields.name_len);
memcpy(name, (uint8_t*)fields.name, fields.name_len);
name[fields.name_len] = '\0';
ESP_LOGI(TAG, "DISCOVERY: %s", name);
if(strstr(name, "BARBACK") != NULL) {
ESP_LOGI(TAG, "Let's Party!");
uint8_t addr_type;
ble_gap_disc_cancel();
ESP_ERROR_CHECK(ble_hs_id_infer_auto(0, &addr_type));
ESP_ERROR_CHECK(ble_gap_connect(addr_type, &event->disc.addr, 30000, NULL, ble_gap_event, NULL));
}
}
return 0;
}
case BLE_GAP_EVENT_CONNECT:
/* A new connection was established or a connection attempt failed */
conn_handle = event->connect.conn_handle;
ESP_LOGI(TAG, "connection %s; conn_handle: %d status=%d\n",
event->connect.status == 0 ? "established" : "failed",
conn_handle,
event->connect.status
);
// always keep advertising
ble_advertise();
break;
case BLE_GAP_EVENT_DISCONNECT:
ESP_LOGI(TAG, "disconnect; reason=%d\n", event->disconnect.reason);
/* Connection terminated; resume advertising */
ble_advertise();
break;
case BLE_GAP_EVENT_ADV_COMPLETE:
ESP_LOGI(TAG, "adv complete\n");
ble_advertise();
break;
case BLE_GAP_EVENT_SUBSCRIBE:
ESP_LOGI(TAG, "subscribe event; cur_notify=%d\n value handle; "
"val_handle=%d\n",
event->subscribe.cur_notify, event->subscribe.attr_handle);
if(event->subscribe.attr_handle == svc_handle_button) {
}
break;
case BLE_GAP_EVENT_CONN_UPDATE:
ESP_LOGI(TAG, "BLE_GAP_EVENT_CONN_UPDATE, conn_handle: %d status: %d",
event->mtu.conn_handle,
event->enc_change.status
);
break;
case BLE_GAP_EVENT_ENC_CHANGE:
ESP_LOGI(TAG, "BLE_GAP_EVENT_ENC_CHANGE");
break;
case BLE_GAP_EVENT_MTU:
ESP_LOGI(TAG, "mtu update event; conn_handle=%d mtu=%d\n",
event->mtu.conn_handle,
event->mtu.value);
break;
case BLE_GAP_EVENT_NOTIFY_RX:
ESP_LOGI(TAG, "BLE_GAP_EVENT_NOTIFY_RX; conn_handle=%d mtu=%d attr_handle=%d\n",
event->mtu.conn_handle,
event->mtu.value,
event->notify_rx.attr_handle);
break;
case BLE_GAP_EVENT_NOTIFY_TX:
ESP_LOGI(TAG, "BLE_GAP_EVENT_NOTIFY_TX; conn_handle=%d mtu=%d\n",
event->mtu.conn_handle,
event->mtu.value);
break;
default:
ESP_LOGW(TAG, "unhandled ble_gap_event; conn_handle=%d type=%d\n",
event->mtu.conn_handle,
event->type
);
}
return 0;
}
void ble_init_buddy_client() {
uint8_t addr_type;
struct ble_gap_disc_params disc_params = {
.filter_duplicates = 1,
.passive = 1,
.itvl = 0,
.window = 0,
.filter_policy = 0,
.limited = 0,
};
ESP_ERROR_CHECK(ble_hs_id_infer_auto(0, &addr_type));
ESP_ERROR_CHECK(ble_gap_disc(addr_type, BLE_HS_FOREVER, &disc_params, ble_gap_event, &addr_type));
}
static void on_sync() {
ESP_LOGI(TAG, "on_sync");
int err;
err = ble_hs_id_infer_auto(0, &blehr_addr_type);
ESP_ERROR_CHECK(err);
uint8_t addr_val[6] = {0};
err = ble_hs_id_copy_addr(blehr_addr_type, addr_val, NULL);
ESP_ERROR_CHECK(err);
ble_advertise();
ble_init_buddy_client();
}
static void on_reset(int reason) {
ESP_LOGE(TAG, "on_reset, reason: %d", reason);
}
void nimble_host_task(void *param) {
nimble_port_run();
}
int8_t ble_send_notification(void *buf, uint8_t size) {
struct os_mbuf *om;
om = ble_hs_mbuf_from_flat(buf, size);
return ble_gattc_notify_custom(conn_handle, svc_handle_button, om);
}
void ble_init(char *name) {
esp_err_t err;
memset(&callback_handlers, 0, sizeof(event_callback_handle_t) * CONFIG_CACO_MAX_SERVICES);
//ESP_ERROR_CHECK(esp_nimble_hci_and_controller_init());
nimble_port_init();
ble_hs_cfg.sync_cb = on_sync;
ble_hs_cfg.reset_cb = on_reset;
// initialize services
err = ble_gatts_count_cfg(service_defs);
ESP_ERROR_CHECK(err);
err = ble_gatts_add_svcs(service_defs);
ESP_ERROR_CHECK(err);
ESP_LOGI(TAG, "Setting device name: %s", name);
device_name = name;
err = ble_svc_gap_device_name_set(name);
ESP_ERROR_CHECK(err);
vTaskDelay(500 / portTICK_PERIOD_MS);
nimble_port_freertos_init(nimble_host_task);
}