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
20 #include "host/ble_hs.h"
21 #include "host/util/util.h"
22
23 #if MYNEWT_VAL(BLE_CONTROLLER)
24 #include "controller/ble_hw.h"
25 #endif
26
ble_hs_util_ensure_rand_addr(void)27 static int ble_hs_util_ensure_rand_addr(void)
28 {
29 ble_addr_t addr;
30 int rc;
31 /* If we already have a random address, then we are done. */
32 rc = ble_hs_id_copy_addr(BLE_ADDR_RANDOM, NULL, NULL);
33 if (rc == 0) {
34 return 0;
35 }
36
37 rc = ble_hs_id_gen_rnd(0, &addr);
38 assert(rc == 0);
39 rc = ble_hs_id_set_rnd(addr.val);
40 assert(rc == 0);
41 return 0;
42 }
43
ble_hs_util_ensure_addr(int prefer_random)44 int ble_hs_util_ensure_addr(int prefer_random)
45 {
46 int rc;
47
48 if (prefer_random) {
49 /* Try to load a random address. */
50 rc = ble_hs_util_ensure_rand_addr();
51 if (rc == BLE_HS_ENOADDR) {
52 /* No random address; try to load a public address. */
53 rc = ble_hs_id_copy_addr(BLE_ADDR_PUBLIC, NULL, NULL);
54 }
55 } else {
56 /* Try to load a public address. */
57 rc = ble_hs_id_copy_addr(BLE_ADDR_PUBLIC, NULL, NULL);
58 if (rc == BLE_HS_ENOADDR) {
59 /* No public address; try to load a random address. */
60 rc = ble_hs_util_ensure_rand_addr();
61 }
62 }
63
64 return rc;
65 }