1 /*
2 * Copyright (c) 2017-2021 Nordic Semiconductor ASA
3 * Copyright (c) 2015-2016 Intel Corporation
4 *
5 * SPDX-License-Identifier: Apache-2.0
6 */
7
8 #include <zephyr/sys/check.h>
9
10 #include <zephyr/bluetooth/bluetooth.h>
11
12 #define LOG_LEVEL CONFIG_BT_HCI_CORE_LOG_LEVEL
13 #include <zephyr/logging/log.h>
14 LOG_MODULE_REGISTER(bt_data);
15
bt_data_parse(struct net_buf_simple * ad,bool (* func)(struct bt_data * data,void * user_data),void * user_data)16 void bt_data_parse(struct net_buf_simple *ad,
17 bool (*func)(struct bt_data *data, void *user_data),
18 void *user_data)
19 {
20 while (ad->len > 1) {
21 struct bt_data data;
22 uint8_t len;
23
24 len = net_buf_simple_pull_u8(ad);
25 if (len == 0U) {
26 /* Early termination */
27 return;
28 }
29
30 if (len > ad->len) {
31 LOG_WRN("malformed advertising data %u / %u",
32 len, ad->len);
33 return;
34 }
35
36 data.type = net_buf_simple_pull_u8(ad);
37 data.data_len = len - 1;
38 data.data = ad->data;
39
40 if (!func(&data, user_data)) {
41 return;
42 }
43
44 net_buf_simple_pull(ad, len - 1);
45 }
46 }
47
bt_data_get_len(const struct bt_data data[],size_t data_count)48 size_t bt_data_get_len(const struct bt_data data[], size_t data_count)
49 {
50 size_t total_len = 0;
51
52 for (size_t i = 0; i < data_count; i++) {
53 total_len += sizeof(data[i].data_len) + sizeof(data[i].type) + data[i].data_len;
54 }
55
56 return total_len;
57 }
58
bt_data_serialize(const struct bt_data * input,uint8_t * output)59 size_t bt_data_serialize(const struct bt_data *input, uint8_t *output)
60 {
61 CHECKIF(input == NULL) {
62 LOG_DBG("input is NULL");
63 return 0;
64 }
65
66 CHECKIF(output == NULL) {
67 LOG_DBG("output is NULL");
68 return 0;
69 }
70
71 uint8_t ad_data_len = input->data_len;
72 uint8_t data_len = ad_data_len + 1;
73
74 output[0] = data_len;
75 output[1] = input->type;
76
77 memcpy(&output[2], input->data, ad_data_len);
78
79 return data_len + 1;
80 }
81