hts.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. /** @file
  2. * @brief HTS Service sample
  3. */
  4. /*
  5. * Copyright (c) 2020 SixOctets Systems
  6. * Copyright (c) 2019 Aaron Tsui <aaron.tsui@outlook.com>
  7. *
  8. * SPDX-License-Identifier: Apache-2.0
  9. */
  10. #include <errno.h>
  11. #include <stddef.h>
  12. #include <string.h>
  13. #include "base/byteorder.h"
  14. #include "base/types.h"
  15. #include <bluetooth/bluetooth.h>
  16. #include <bluetooth/conn.h>
  17. #include <bluetooth/gatt.h>
  18. #include <bluetooth/uuid.h>
  19. #include <logging/bt_log_impl.h>
  20. static uint8_t simulate_htm;
  21. static uint8_t indicating;
  22. static struct bt_gatt_indicate_params ind_params;
  23. static void htmc_ccc_cfg_changed(const struct bt_gatt_attr *attr, uint16_t value)
  24. {
  25. simulate_htm = (value == BT_GATT_CCC_INDICATE) ? 1 : 0;
  26. }
  27. static void indicate_cb(struct bt_conn *conn, struct bt_gatt_indicate_params *params, uint8_t err)
  28. {
  29. printk("Indication %s\n", err != 0U ? "fail" : "success");
  30. indicating = 0U;
  31. }
  32. static void indicate_destroy(struct bt_gatt_indicate_params *params)
  33. {
  34. printk("Indication complete\n");
  35. indicating = 0U;
  36. }
  37. /* Health Thermometer Service Declaration */
  38. BT_GATT_SERVICE_DEFINE(hts_svc, BT_GATT_PRIMARY_SERVICE(BT_UUID_HTS),
  39. BT_GATT_CHARACTERISTIC(BT_UUID_HTS_MEASUREMENT, BT_GATT_CHRC_INDICATE,
  40. BT_GATT_PERM_NONE, NULL, NULL, NULL),
  41. BT_GATT_CCC(htmc_ccc_cfg_changed, BT_GATT_PERM_READ | BT_GATT_PERM_WRITE),
  42. /* more optional Characteristics */
  43. );
  44. void hts_init(void)
  45. {
  46. printk("no temperature device; using simulated data\n");
  47. }
  48. void hts_indicate(void)
  49. {
  50. /* Temperature measurements simulation */
  51. if (simulate_htm)
  52. {
  53. static uint8_t htm[5];
  54. static double temperature = 20U;
  55. uint32_t mantissa;
  56. uint8_t exponent;
  57. // int r;
  58. if (indicating)
  59. {
  60. return;
  61. }
  62. temperature++;
  63. if (temperature == 30U)
  64. {
  65. temperature = 20U;
  66. }
  67. printk("temperature is %gC\n", temperature);
  68. mantissa = (uint32_t)(temperature * 100);
  69. exponent = (uint8_t)-2;
  70. htm[0] = 0; /* temperature in celsius */
  71. sys_put_le24(mantissa, (uint8_t *)&htm[1]);
  72. htm[4] = exponent;
  73. ind_params.attr = &hts_svc.attrs[2];
  74. ind_params.func = indicate_cb;
  75. ind_params.destroy = indicate_destroy;
  76. ind_params.data = &htm;
  77. ind_params.len = sizeof(htm);
  78. if (bt_gatt_indicate(NULL, &ind_params) == 0)
  79. {
  80. indicating = 1U;
  81. }
  82. }
  83. }