35
35
#include < bluetooth/addr.h>
36
36
#include < bluetooth/gatt.h>
37
37
#include < logging/log.h>
38
+ #include < random/rand32.h>
38
39
#include < sys/byteorder.h>
39
40
#include < sys/util.h>
40
41
@@ -85,22 +86,40 @@ struct bt_gatt_service sChipoBleService = BT_GATT_SERVICE(sChipoBleAttributes);
85
86
// This value should be adjusted accordingly if the service declaration changes.
86
87
constexpr int kCHIPoBLE_CCC_AttributeIndex = 3 ;
87
88
88
- void InitRandomStaticAddress ()
89
+ CHIP_ERROR InitRandomStaticAddress ()
89
90
{
90
- # if !CONFIG_BT_PRIVACY
91
- // When the BT privacy feature is disabled, generate a random static address once per boot .
92
- // This must be done before bt_enable() has been called.
91
+ // Generate a random static address for the default identity.
92
+ // This must be done before bt_enable() as after that updating the default identity is not possible .
93
+ int error = 0 ;
93
94
bt_addr_le_t addr;
94
95
95
- int error = bt_addr_le_create_static (&addr);
96
- VerifyOrReturn (error == 0 , ChipLogError (DeviceLayer, " Failed to create BLE address: %d" , error));
96
+ #if CONFIG_BT_HOST_CRYPTO
97
+ // When CONFIG_BT_HOST_CRYPTO is enabled, bt_addr_le_create_static() depends on HCI transport
98
+ // which is not yet started at this point, so use a different method for generating the address
99
+ addr.type = BT_ADDR_LE_RANDOM;
100
+ error = sys_csrand_get (addr.a .val , sizeof (addr.a .val ));
101
+ BT_ADDR_SET_STATIC (&addr.a );
102
+ #else
103
+ error = bt_addr_le_create_static (&addr);
104
+ #endif
105
+
106
+ if (error)
107
+ {
108
+ ChipLogError (DeviceLayer, " Failed to create BLE address: %d" , error);
109
+ return System::MapErrorZephyr (error);
110
+ }
97
111
98
112
error = bt_id_create (&addr, nullptr );
99
- VerifyOrReturn (error == 0 , ChipLogError (DeviceLayer, " Failed to create BLE identity: %d" , error));
100
113
101
- ChipLogProgress (DeviceLayer, " BLE address was set to %02X:%02X:%02X:%02X:%02X:%02X" , addr.a .val [5 ], addr.a .val [4 ],
102
- addr.a .val [3 ], addr.a .val [2 ], addr.a .val [1 ], addr.a .val [0 ]);
103
- #endif
114
+ if (error)
115
+ {
116
+ ChipLogError (DeviceLayer, " Failed to create BLE identity: %d" , error);
117
+ return System::MapErrorZephyr (error);
118
+ }
119
+
120
+ ChipLogProgress (DeviceLayer, " BLE address: %02X:%02X:%02X:%02X:%02X:%02X" , addr.a .val [5 ], addr.a .val [4 ], addr.a .val [3 ],
121
+ addr.a .val [2 ], addr.a .val [1 ], addr.a .val [0 ]);
122
+ return CHIP_NO_ERROR;
104
123
}
105
124
106
125
} // unnamed namespace
@@ -116,7 +135,7 @@ CHIP_ERROR BLEManagerImpl::_Init()
116
135
117
136
memset (mSubscribedConns , 0 , sizeof (mSubscribedConns ));
118
137
119
- InitRandomStaticAddress ();
138
+ ReturnErrorOnFailure ( InitRandomStaticAddress () );
120
139
int err = bt_enable (NULL );
121
140
VerifyOrReturnError (err == 0 , MapErrorZephyr (err));
122
141
0 commit comments