1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19 #include <stdint.h>
20 #include <assert.h>
21 #include <string.h>
22 #include <errno.h>
23 #include <stdio.h>
24 #include "securec.h"
25 #include "os/os.h"
26 #include "nimble/hci_common.h"
27 #include "nimble/ble_hci_trans.h"
28 #include "host/ble_monitor.h"
29 #include "ble_hs_priv.h"
30 #include "ble_monitor_priv.h"
31
ble_hs_hci_cmd_transport(struct ble_hci_cmd * cmd)32 static int ble_hs_hci_cmd_transport(struct ble_hci_cmd *cmd)
33 {
34 int rc;
35 #if BLE_MONITOR
36 ble_monitor_send(BLE_MONITOR_OPCODE_COMMAND_PKT, cmd,
37 cmd->length + sizeof(*cmd));
38 #endif
39 rc = ble_hci_trans_hs_cmd_tx((uint8_t *) cmd);
40 switch (rc) {
41 case 0:
42 return 0;
43
44 case BLE_ERR_MEM_CAPACITY:
45 return BLE_HS_ENOMEM_EVT;
46
47 default:
48 return BLE_HS_EUNKNOWN;
49 }
50 }
51
ble_hs_hci_cmd_send(uint16_t opcode,uint8_t len,const void * cmddata)52 static int ble_hs_hci_cmd_send(uint16_t opcode, uint8_t len, const void *cmddata)
53 {
54 struct ble_hci_cmd *cmd;
55 int rc;
56 cmd = (void *) ble_hci_trans_buf_alloc(BLE_HCI_TRANS_BUF_CMD);
57 BLE_HS_DBG_ASSERT(cmd != NULL);
58 cmd->opcode = htole16(opcode);
59 cmd->length = len;
60
61 if (len != 0) {
62 memcpy_s(cmd->data, sizeof(cmd->data), cmddata, len);
63 }
64
65 rc = ble_hs_hci_cmd_transport(cmd);
66 if (rc == 0) {
67 STATS_INC(ble_hs_stats, hci_cmd);
68 } else {
69 BLE_HS_LOG(DEBUG, "ble_hs_hci_cmd_send failure; rc=%d\n", rc);
70 }
71
72 return rc;
73 }
74
ble_hs_hci_cmd_send_buf(uint16_t opcode,const void * buf,uint8_t buf_len)75 int ble_hs_hci_cmd_send_buf(uint16_t opcode, const void *buf, uint8_t buf_len)
76 {
77 switch (ble_hs_sync_state) {
78 case BLE_HS_SYNC_STATE_BAD:
79 return BLE_HS_ENOTSYNCED;
80
81 case BLE_HS_SYNC_STATE_BRINGUP:
82 if (!ble_hs_is_parent_task()) {
83 return BLE_HS_ENOTSYNCED;
84 }
85
86 break;
87
88 case BLE_HS_SYNC_STATE_GOOD:
89 break;
90
91 default:
92 BLE_HS_DBG_ASSERT(0);
93 return BLE_HS_EUNKNOWN;
94 }
95
96 return ble_hs_hci_cmd_send(opcode, buf_len, buf);
97 }