bas.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /** @file
  2. * @brief GATT Battery Service
  3. */
  4. /*
  5. * Copyright (c) 2018 Nordic Semiconductor ASA
  6. * Copyright (c) 2016 Intel Corporation
  7. *
  8. * SPDX-License-Identifier: Apache-2.0
  9. */
  10. #include <errno.h>
  11. #include <init.h>
  12. #include <sys/__assert.h>
  13. #include <stdbool.h>
  14. #include <zephyr/types.h>
  15. #include <acts_bluetooth/bluetooth.h>
  16. #include <acts_bluetooth/conn.h>
  17. #include <acts_bluetooth/gatt.h>
  18. #include <acts_bluetooth/uuid.h>
  19. #include <acts_bluetooth/services/bas.h>
  20. #define LOG_LEVEL CONFIG_BT_BAS_LOG_LEVEL
  21. #include <logging/log.h>
  22. LOG_MODULE_REGISTER(bas);
  23. static uint8_t battery_level = 100U;
  24. static void blvl_ccc_cfg_changed(const struct bt_gatt_attr *attr,
  25. uint16_t value)
  26. {
  27. ARG_UNUSED(attr);
  28. bool notif_enabled = (value == BT_GATT_CCC_NOTIFY);
  29. LOG_INF("BAS Notifications %s", notif_enabled ? "enabled" : "disabled");
  30. }
  31. static ssize_t read_blvl(struct bt_conn *conn,
  32. const struct bt_gatt_attr *attr, void *buf,
  33. uint16_t len, uint16_t offset)
  34. {
  35. uint8_t lvl8 = battery_level;
  36. return bt_gatt_attr_read(conn, attr, buf, len, offset, &lvl8,
  37. sizeof(lvl8));
  38. }
  39. BT_GATT_SERVICE_DEFINE(bas,
  40. BT_GATT_PRIMARY_SERVICE(BT_UUID_BAS),
  41. BT_GATT_CHARACTERISTIC(BT_UUID_BAS_BATTERY_LEVEL,
  42. BT_GATT_CHRC_READ | BT_GATT_CHRC_NOTIFY,
  43. BT_GATT_PERM_READ, read_blvl, NULL,
  44. &battery_level),
  45. BT_GATT_CCC(blvl_ccc_cfg_changed,
  46. BT_GATT_PERM_READ | BT_GATT_PERM_WRITE),
  47. );
  48. int bas_init(void)
  49. {
  50. return 0;
  51. }
  52. uint8_t bt_bas_get_battery_level(void)
  53. {
  54. return battery_level;
  55. }
  56. int bt_bas_set_battery_level(uint8_t level)
  57. {
  58. int rc;
  59. if (level > 100U) {
  60. return -EINVAL;
  61. }
  62. battery_level = level;
  63. rc = bt_gatt_notify(NULL, &bas.attrs[1], &level, sizeof(level));
  64. return rc == -ENOTCONN ? 0 : rc;
  65. }