1 /*
2  * Copyright (c) 2022 Nordic Semiconductor ASA
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <errno.h>
8 #include <stdbool.h>
9 #include <stddef.h>
10 #include <stdint.h>
11 
12 #include <zephyr/autoconf.h>
13 #include <zephyr/bluetooth/gatt.h>
14 #include <zephyr/bluetooth/audio/tbs.h>
15 #include <zephyr/bluetooth/audio/csip.h>
16 #include <zephyr/bluetooth/conn.h>
17 #include <zephyr/bluetooth/uuid.h>
18 #include <zephyr/logging/log.h>
19 #include <zephyr/sys/check.h>
20 #include <zephyr/sys/util_macro.h>
21 
22 #include "cap_internal.h"
23 
24 LOG_MODULE_REGISTER(bt_cap_acceptor, CONFIG_BT_CAP_ACCEPTOR_LOG_LEVEL);
25 
26 #if defined(CONFIG_BT_CAP_ACCEPTOR_SET_MEMBER)
27 
28 static struct bt_gatt_attr svc_attrs[] = {
29 	BT_GATT_PRIMARY_SERVICE(BT_UUID_CAS),
30 	BT_GATT_INCLUDE_SERVICE(NULL) /* To be overwritten */
31 };
32 
bt_cap_acceptor_register(const struct bt_csip_set_member_register_param * param,struct bt_csip_set_member_svc_inst ** svc_inst)33 int bt_cap_acceptor_register(const struct bt_csip_set_member_register_param *param,
34 			     struct bt_csip_set_member_svc_inst **svc_inst)
35 {
36 	static struct bt_gatt_service cas;
37 	int err;
38 
39 	CHECKIF(param->set_size == 0U) {
40 		LOG_DBG("param->set_size shall be non-zero");
41 		return -EINVAL;
42 	}
43 
44 	CHECKIF(param->rank == 0U) {
45 		LOG_DBG("param->rank shall be non-zero");
46 		return -EINVAL;
47 	}
48 
49 	err = bt_csip_set_member_register(param, svc_inst);
50 	if (err != 0) {
51 		LOG_DBG("Failed to register CSIP");
52 		return err;
53 	}
54 
55 	cas = (struct bt_gatt_service)BT_GATT_SERVICE(svc_attrs);
56 
57 	/* Overwrite the include definition with the CSIP */
58 	cas.attrs[1].user_data = bt_csip_set_member_svc_decl_get(*svc_inst);
59 
60 	err = bt_gatt_service_register(&cas);
61 	if (err) {
62 		const int csip_err = bt_csip_set_member_unregister(*svc_inst);
63 
64 		if (csip_err) {
65 			LOG_ERR("Failed to unregister CSIS: %d", csip_err);
66 		}
67 
68 		cas.attrs[1].user_data = NULL;
69 		LOG_DBG("Failed to register CAS");
70 
71 		return err;
72 	}
73 
74 	return 0;
75 }
76 
77 #else /* CONFIG_BT_CAP_ACCEPTOR_SET_MEMBER */
78 
79 BT_GATT_SERVICE_DEFINE(cas_svc,
80 	BT_GATT_PRIMARY_SERVICE(BT_UUID_CAS)
81 	/* TODO: Add support for included CSIP */
82 );
83 
84 #endif /* CONFIG_BT_CAP_ACCEPTOR_SET_MEMBER */
85 
bt_cap_acceptor_ccid_exist(const struct bt_conn * conn,uint8_t ccid)86 bool bt_cap_acceptor_ccid_exist(const struct bt_conn *conn, uint8_t ccid)
87 {
88 	if (IS_ENABLED(CONFIG_BT_TBS_CLIENT_CCID) &&
89 	    bt_tbs_client_get_by_ccid(conn, ccid) != NULL) {
90 		return true;
91 	}
92 
93 	/* TODO: check mcs */
94 
95 	return false;
96 }
97