Skip to content

Instantly share code, notes, and snippets.

@MZachmann
Last active May 11, 2020 12:04
Show Gist options
  • Save MZachmann/f732174fd0110cce0b6b116a7a5f1e47 to your computer and use it in GitHub Desktop.
Save MZachmann/f732174fd0110cce0b6b116a7a5f1e47 to your computer and use it in GitHub Desktop.
// GATT Battery Service
// MZachmann 2020
// MIT License
// this is the gatt standard battery level indicator
// it may send a notification when the battery level is set
#include <bluetooth/bluetooth.h>
#include <bluetooth/conn.h>
#include <bluetooth/gatt.h>
#include <bluetooth/uuid.h>
#include <logging/log.h>
LOG_MODULE_REGISTER(BtBls, LOG_LEVEL_INF);
// persistant characteristic data
static u8_t _BatteryLevel = 100U;
static bool _IsTxEnabled = false;
// notification changed callback, log it
static void NotifyEnabledCb(const struct bt_gatt_attr *attr, u16_t value)
{
ARG_UNUSED(attr);
_IsTxEnabled = (value == BT_GATT_CCC_NOTIFY);
LOG_INF("Battery level notification %s.", _IsTxEnabled ? "enabled" : "disabled");
}
// attribute read callback
static ssize_t ReadBlvlCb(struct bt_conn *conn,
const struct bt_gatt_attr *attr, void *buf,
u16_t len, u16_t offset)
{
u8_t lvl8 = _BatteryLevel;
return bt_gatt_attr_read(conn, attr, buf, len, offset, &lvl8, sizeof(lvl8));
}
// the heavy lifter that defines the service completely
BT_GATT_SERVICE_DEFINE(_BlsService,
BT_GATT_PRIMARY_SERVICE(BT_UUID_BAS),
BT_GATT_CHARACTERISTIC(BT_UUID_BAS_BATTERY_LEVEL,
BT_GATT_CHRC_READ | BT_GATT_CHRC_NOTIFY,
BT_GATT_PERM_READ, ReadBlvlCb, NULL,
&_BatteryLevel),
BT_GATT_CCC(NotifyEnabledCb,
BT_GATT_PERM_READ | BT_GATT_PERM_WRITE),
);
// ------------------------------------------------------------
// user-callable method to set the battery level in the service
// ------------------------------------------------------------
int BtSetBattery(u8_t level)
{
if(! _IsTxEnabled)
return -ENOEXEC;
if (level > 100U)
return -EINVAL;
_BatteryLevel = level; // the persistant value is used by the gatt reader
int rc = bt_gatt_notify(NULL, &_BlsService.attrs[1], &level, sizeof(level));
return (rc == -ENOTCONN) ? 0 : rc;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment