1 /*
2  * Copyright (c) 2023-2023 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 #ifndef LOG_TAG
16 #define LOG_TAG "BluetoothDeviceManager"
17 #endif
18 
19 #include "bluetooth_device_manager.h"
20 
21 #include <thread>
22 
23 #include "bluetooth_audio_manager.h"
24 #include "audio_bluetooth_manager.h"
25 
26 namespace OHOS {
27 namespace Bluetooth {
28 using namespace AudioStandard;
29 
30 const int DEFAULT_COD = -1;
31 const int DEFAULT_MAJOR_CLASS = -1;
32 const int DEFAULT_MAJOR_MINOR_CLASS = -1;
33 const int A2DP_DEFAULT_SELECTION = -1;
34 const int HFP_DEFAULT_SELECTION = -1;
35 const int USER_SELECTION = 1;
36 const int ADDRESS_STR_LEN = 17;
37 const int START_POS = 6;
38 const int END_POS = 13;
39 const std::map<std::pair<int, int>, DeviceCategory> bluetoothDeviceCategoryMap_ = {
40     {std::make_pair(BluetoothDevice::MAJOR_AUDIO_VIDEO, BluetoothDevice::AUDIO_VIDEO_HEADPHONES), BT_HEADPHONE},
41     {std::make_pair(BluetoothDevice::MAJOR_AUDIO_VIDEO, BluetoothDevice::AUDIO_VIDEO_WEARABLE_HEADSET), BT_HEADPHONE},
42     {std::make_pair(BluetoothDevice::MAJOR_AUDIO_VIDEO, BluetoothDevice::AUDIO_VIDEO_LOUDSPEAKER), BT_SOUNDBOX},
43     {std::make_pair(BluetoothDevice::MAJOR_AUDIO_VIDEO, BluetoothDevice::AUDIO_VIDEO_HANDSFREE), BT_CAR},
44     {std::make_pair(BluetoothDevice::MAJOR_AUDIO_VIDEO, BluetoothDevice::AUDIO_VIDEO_CAR_AUDIO), BT_CAR},
45     {std::make_pair(BluetoothDevice::MAJOR_WEARABLE, BluetoothDevice::WEARABLE_GLASSES), BT_GLASSES},
46     {std::make_pair(BluetoothDevice::MAJOR_WEARABLE, BluetoothDevice::WEARABLE_WRIST_WATCH), BT_WATCH},
47 };
48 IDeviceStatusObserver *g_deviceObserver = nullptr;
49 std::mutex g_observerLock;
50 std::mutex g_a2dpDeviceLock;
51 std::mutex g_a2dpDeviceMapLock;
52 std::mutex g_a2dpWearStateMapLock;
53 std::map<std::string, BluetoothRemoteDevice> MediaBluetoothDeviceManager::a2dpBluetoothDeviceMap_;
54 std::map<std::string, BluetoothDeviceAction> MediaBluetoothDeviceManager::wearDetectionStateMap_;
55 std::vector<BluetoothRemoteDevice> MediaBluetoothDeviceManager::privacyDevices_;
56 std::vector<BluetoothRemoteDevice> MediaBluetoothDeviceManager::commonDevices_;
57 std::vector<BluetoothRemoteDevice> MediaBluetoothDeviceManager::negativeDevices_;
58 std::vector<BluetoothRemoteDevice> MediaBluetoothDeviceManager::connectingDevices_;
59 std::vector<BluetoothRemoteDevice> MediaBluetoothDeviceManager::virtualDevices_;
60 std::mutex g_hfpDeviceLock;
61 std::mutex g_hfpDeviceMapLock;
62 std::mutex g_hfpWearStateMapLock;
63 std::map<std::string, BluetoothRemoteDevice> HfpBluetoothDeviceManager::hfpBluetoothDeviceMap_;
64 std::map<std::string, BluetoothDeviceAction> HfpBluetoothDeviceManager::wearDetectionStateMap_;
65 std::vector<BluetoothRemoteDevice> HfpBluetoothDeviceManager::privacyDevices_;
66 std::vector<BluetoothRemoteDevice> HfpBluetoothDeviceManager::commonDevices_;
67 std::vector<BluetoothRemoteDevice> HfpBluetoothDeviceManager::negativeDevices_;
68 std::vector<BluetoothRemoteDevice> HfpBluetoothDeviceManager::connectingDevices_;
69 std::vector<BluetoothRemoteDevice> HfpBluetoothDeviceManager::virtualDevices_;
70 std::mutex HfpBluetoothDeviceManager::stopVirtualCallHandleLock_;
71 BluetoothStopVirtualCallHandle HfpBluetoothDeviceManager::stopVirtualCallHandle_ = { BluetoothRemoteDevice(), false};
72 
73 // LCOV_EXCL_START
GetEncryptAddr(const std::string &addr)74 std::string GetEncryptAddr(const std::string &addr)
75 {
76     if (addr.empty() || addr.length() != ADDRESS_STR_LEN) {
77         return std::string("");
78     }
79     std::string tmp = "**:**:**:**:**:**";
80     std::string out = addr;
81     for (int i = START_POS; i <= END_POS; i++) {
82         out[i] = tmp[i];
83     }
84     return out;
85 }
86 
RegisterDeviceObserver(IDeviceStatusObserver &observer)87 int32_t RegisterDeviceObserver(IDeviceStatusObserver &observer)
88 {
89     std::lock_guard<std::mutex> deviceLock(g_observerLock);
90     g_deviceObserver = &observer;
91     return SUCCESS;
92 }
93 
UnregisterDeviceObserver()94 void UnregisterDeviceObserver()
95 {
96     std::lock_guard<std::mutex> deviceLock(g_observerLock);
97     g_deviceObserver = nullptr;
98 }
99 
SendUserSelectionEvent(AudioStandard::DeviceType devType, const std::string &macAddress, int32_t eventType)100 void SendUserSelectionEvent(AudioStandard::DeviceType devType, const std::string &macAddress, int32_t eventType)
101 {
102     AUDIO_INFO_LOG("devType is %{public}d, eventType is%{public}d.", devType, eventType);
103     BluetoothRemoteDevice device;
104     if (devType == DEVICE_TYPE_BLUETOOTH_A2DP) {
105         if (MediaBluetoothDeviceManager::GetConnectedA2dpBluetoothDevice(macAddress, device) != SUCCESS) {
106             AUDIO_ERR_LOG("failed for the device is not connected.");
107             return;
108         }
109         BluetoothAudioManager::GetInstance().SendDeviceSelection(device, eventType,
110             HFP_DEFAULT_SELECTION, USER_SELECTION);
111     } else if (devType == DEVICE_TYPE_BLUETOOTH_SCO) {
112         if (HfpBluetoothDeviceManager::GetConnectedHfpBluetoothDevice(macAddress, device) != SUCCESS) {
113             AUDIO_ERR_LOG("failed for the device is not connected.");
114             return;
115         }
116         BluetoothAudioManager::GetInstance().SendDeviceSelection(device, A2DP_DEFAULT_SELECTION,
117             eventType, USER_SELECTION);
118     } else {
119         AUDIO_ERR_LOG("failed for the devType is not Bluetooth type.");
120     }
121 }
122 
IsBTWearDetectionEnable(const BluetoothRemoteDevice &device)123 bool IsBTWearDetectionEnable(const BluetoothRemoteDevice &device)
124 {
125     int32_t wearEnabledAbility = 0;
126     bool isWearSupported = false;
127     BluetoothAudioManager::GetInstance().GetWearDetectionState(device.GetDeviceAddr(), wearEnabledAbility);
128     BluetoothAudioManager::GetInstance().IsWearDetectionSupported(device.GetDeviceAddr(), isWearSupported);
129     AUDIO_INFO_LOG("wear detection on-off state: %{public}d, wear detection support state: %{public}d",
130         wearEnabledAbility, isWearSupported);
131     return (wearEnabledAbility == WEAR_ENABLED && isWearSupported);
132 }
133 
GetDeviceCategory(const BluetoothRemoteDevice &device)134 DeviceCategory GetDeviceCategory(const BluetoothRemoteDevice &device)
135 {
136     int cod = DEFAULT_COD;
137     int majorClass = DEFAULT_MAJOR_CLASS;
138     int majorMinorClass = DEFAULT_MAJOR_MINOR_CLASS;
139     device.GetDeviceProductType(cod, majorClass, majorMinorClass);
140     AUDIO_INFO_LOG("Device type majorClass: %{public}d, majorMinorClass: %{public}d.", majorClass, majorMinorClass);
141     DeviceCategory bluetoothCategory = CATEGORY_DEFAULT;
142     auto pos = bluetoothDeviceCategoryMap_.find(std::make_pair(majorClass, majorMinorClass));
143     if (pos != bluetoothDeviceCategoryMap_.end()) {
144         bluetoothCategory = pos->second;
145     }
146     return bluetoothCategory;
147 }
148 
SetMediaStack(const BluetoothRemoteDevice &device, int action)149 void MediaBluetoothDeviceManager::SetMediaStack(const BluetoothRemoteDevice &device, int action)
150 {
151     switch (action) {
152         case BluetoothDeviceAction::CONNECTING_ACTION:
153             HandleConnectingDevice(device);
154             break;
155         case BluetoothDeviceAction::CONNECT_ACTION:
156             HandleConnectDevice(device);
157             break;
158         case BluetoothDeviceAction::DISCONNECT_ACTION:
159             HandleDisconnectDevice(device);
160             break;
161         case BluetoothDeviceAction::WEAR_ACTION:
162             HandleWearDevice(device);
163             break;
164         case BluetoothDeviceAction::UNWEAR_ACTION:
165             HandleUnwearDevice(device);
166             break;
167         case BluetoothDeviceAction::ENABLEFROMREMOTE_ACTION:
168             HandleEnableDevice(device);
169             break;
170         case BluetoothDeviceAction::DISABLEFROMREMOTE_ACTION:
171             HandleDisableDevice(device);
172             break;
173         case BluetoothDeviceAction::ENABLE_WEAR_DETECTION_ACTION:
174             HandleWearEnable(device);
175             break;
176         case BluetoothDeviceAction::DISABLE_WEAR_DETECTION_ACTION:
177             HandleWearDisable(device);
178             break;
179         case BluetoothDeviceAction::USER_SELECTION_ACTION:
180             HandleUserSelection(device);
181             break;
182         case BluetoothDeviceAction::VIRTUAL_DEVICE_ADD_ACTION:
183             HandleVirtualConnectDevice(device);
184             break;
185         case BluetoothDeviceAction::VIRTUAL_DEVICE_REMOVE_ACTION:
186             HandleRemoveVirtualConnectDevice(device);
187             break;
188         default:
189             AUDIO_ERR_LOG("SetMediaStack failed due to the unknow action: %{public}d", action);
190             break;
191     }
192 }
193 
HandleConnectingDevice(const BluetoothRemoteDevice &device)194 void MediaBluetoothDeviceManager::HandleConnectingDevice(const BluetoothRemoteDevice &device)
195 {
196     if (IsA2dpBluetoothDeviceExist(device.GetDeviceAddr())) {
197         return;
198     }
199     AddDeviceInConfigVector(device, connectingDevices_);
200 }
201 
HandleConnectDevice(const BluetoothRemoteDevice &device)202 void MediaBluetoothDeviceManager::HandleConnectDevice(const BluetoothRemoteDevice &device)
203 {
204     if (IsA2dpBluetoothDeviceExist(device.GetDeviceAddr())) {
205         return;
206     }
207     RemoveDeviceInConfigVector(device, connectingDevices_);
208     // If the device was virtual connected, remove it from the negativeDevices_ list.
209     RemoveDeviceInConfigVector(device, negativeDevices_);
210     RemoveDeviceInConfigVector(device, virtualDevices_);
211     DeviceCategory bluetoothCategory = GetDeviceCategory(device);
212     AudioDeviceDescriptor desc;
213     desc.deviceCategory_ = bluetoothCategory;
214     switch (bluetoothCategory) {
215         case BT_GLASSES:
216         case BT_HEADPHONE:
217             if (IsBTWearDetectionEnable(device)) {
218                 AddDeviceInConfigVector(device, negativeDevices_);
219                 desc.deviceCategory_ = BT_UNWEAR_HEADPHONE;
220             } else {
221                 AddDeviceInConfigVector(device, privacyDevices_);
222             }
223             break;
224         case BT_SOUNDBOX:
225         case BT_CAR:
226             AddDeviceInConfigVector(device, commonDevices_);
227             break;
228         case BT_WATCH:
229             AddDeviceInConfigVector(device, negativeDevices_);
230             break;
231         default:
232             AUDIO_INFO_LOG("Unknow BT category, regard as bluetooth headset.");
233             AddDeviceInConfigVector(device, privacyDevices_);
234             desc.deviceCategory_ = BT_HEADPHONE;
235             break;
236     }
237     NotifyToUpdateAudioDevice(device, desc, DeviceStatus::ADD);
238 }
239 
HandleDisconnectDevice(const BluetoothRemoteDevice &device)240 void MediaBluetoothDeviceManager::HandleDisconnectDevice(const BluetoothRemoteDevice &device)
241 {
242     RemoveDeviceInConfigVector(device, connectingDevices_);
243     if (!IsA2dpBluetoothDeviceExist(device.GetDeviceAddr())) {
244         AUDIO_INFO_LOG("The device is already disconnected, ignore disconnect action.");
245         return;
246     }
247     RemoveDeviceInConfigVector(device, privacyDevices_);
248     RemoveDeviceInConfigVector(device, commonDevices_);
249     RemoveDeviceInConfigVector(device, negativeDevices_);
250     {
251         std::lock_guard<std::mutex> wearStateMapLock(g_a2dpWearStateMapLock);
252         wearDetectionStateMap_.erase(device.GetDeviceAddr());
253     }
254     AudioDeviceDescriptor desc;
255     desc.deviceCategory_ = CATEGORY_DEFAULT;
256     NotifyToUpdateAudioDevice(device, desc, DeviceStatus::REMOVE);
257 }
258 
HandleWearDevice(const BluetoothRemoteDevice &device)259 void MediaBluetoothDeviceManager::HandleWearDevice(const BluetoothRemoteDevice &device)
260 {
261     bool isDeviceExist = IsA2dpBluetoothDeviceExist(device.GetDeviceAddr());
262     CHECK_AND_RETURN_LOG(isDeviceExist,
263         "HandleWearDevice failed for the device has not be reported the connected action.");
264     RemoveDeviceInConfigVector(device, negativeDevices_);
265     RemoveDeviceInConfigVector(device, privacyDevices_);
266     AddDeviceInConfigVector(device, privacyDevices_);
267     {
268         std::lock_guard<std::mutex> wearStateMapLock(g_a2dpWearStateMapLock);
269         wearDetectionStateMap_[device.GetDeviceAddr()] = BluetoothDeviceAction::WEAR_ACTION;
270     }
271     AudioDeviceDescriptor desc;
272     desc.deviceType_ = DEVICE_TYPE_BLUETOOTH_A2DP;
273     desc.macAddress_ = device.GetDeviceAddr();
274     desc.deviceCategory_ = BT_HEADPHONE;
275     std::lock_guard<std::mutex> observerLock(g_observerLock);
276     if (g_deviceObserver != nullptr) {
277         g_deviceObserver->OnDeviceInfoUpdated(desc, DeviceInfoUpdateCommand::CATEGORY_UPDATE);
278     }
279 }
280 
HandleUnwearDevice(const BluetoothRemoteDevice &device)281 void MediaBluetoothDeviceManager::HandleUnwearDevice(const BluetoothRemoteDevice &device)
282 {
283     bool isDeviceExist = IsA2dpBluetoothDeviceExist(device.GetDeviceAddr());
284     CHECK_AND_RETURN_LOG(isDeviceExist, "HandleWearDevice failed for the device has not worn.");
285     RemoveDeviceInConfigVector(device, privacyDevices_);
286     RemoveDeviceInConfigVector(device, negativeDevices_);
287     AddDeviceInConfigVector(device, negativeDevices_);
288     {
289         std::lock_guard<std::mutex> wearStateMapLock(g_a2dpWearStateMapLock);
290         wearDetectionStateMap_[device.GetDeviceAddr()] = BluetoothDeviceAction::UNWEAR_ACTION;
291     }
292     AudioDeviceDescriptor desc;
293     desc.deviceType_ = DEVICE_TYPE_BLUETOOTH_A2DP;
294     desc.macAddress_ = device.GetDeviceAddr();
295     desc.deviceCategory_ = BT_UNWEAR_HEADPHONE;
296     std::lock_guard<std::mutex> observerLock(g_observerLock);
297     if (g_deviceObserver != nullptr) {
298         g_deviceObserver->OnDeviceInfoUpdated(desc, DeviceInfoUpdateCommand::CATEGORY_UPDATE);
299     }
300 }
301 
HandleEnableDevice(const BluetoothRemoteDevice &device)302 void MediaBluetoothDeviceManager::HandleEnableDevice(const BluetoothRemoteDevice &device)
303 {
304     if (!IsA2dpBluetoothDeviceExist(device.GetDeviceAddr())) {
305         AUDIO_ERR_LOG("HandleEnableDevice failed for the device has not connected.");
306         return;
307     }
308     AudioDeviceDescriptor desc;
309     desc.deviceType_ = DEVICE_TYPE_BLUETOOTH_A2DP;
310     desc.macAddress_ = device.GetDeviceAddr();
311     desc.isEnable_ = true;
312     std::lock_guard<std::mutex> observerLock(g_observerLock);
313     if (g_deviceObserver != nullptr) {
314         g_deviceObserver->OnDeviceInfoUpdated(desc, DeviceInfoUpdateCommand::ENABLE_UPDATE);
315     }
316 }
317 
HandleDisableDevice(const BluetoothRemoteDevice &device)318 void MediaBluetoothDeviceManager::HandleDisableDevice(const BluetoothRemoteDevice &device)
319 {
320     if (!IsA2dpBluetoothDeviceExist(device.GetDeviceAddr())) {
321         AUDIO_ERR_LOG("HandleDisableDevice failed for the device has not connected.");
322         return;
323     }
324     AudioDeviceDescriptor desc;
325     desc.deviceType_ = DEVICE_TYPE_BLUETOOTH_A2DP;
326     desc.macAddress_ = device.GetDeviceAddr();
327     desc.isEnable_ = false;
328     std::lock_guard<std::mutex> observerLock(g_observerLock);
329     if (g_deviceObserver != nullptr) {
330         g_deviceObserver->OnDeviceInfoUpdated(desc, DeviceInfoUpdateCommand::ENABLE_UPDATE);
331     }
332 }
333 
HandleWearEnable(const BluetoothRemoteDevice &device)334 void MediaBluetoothDeviceManager::HandleWearEnable(const BluetoothRemoteDevice &device)
335 {
336     if (!IsA2dpBluetoothDeviceExist(device.GetDeviceAddr())) {
337         AUDIO_ERR_LOG("HandleWearEnable failed for the device has not connected.");
338         return;
339     }
340     RemoveDeviceInConfigVector(device, negativeDevices_);
341     RemoveDeviceInConfigVector(device, privacyDevices_);
342     std::lock_guard<std::mutex> wearStateMapLock(g_a2dpWearStateMapLock);
343     AudioDeviceDescriptor desc;
344     desc.deviceType_ = DEVICE_TYPE_BLUETOOTH_A2DP;
345     desc.macAddress_ = device.GetDeviceAddr();
346     auto wearStateIter = wearDetectionStateMap_.find(device.GetDeviceAddr());
347     if (wearStateIter != wearDetectionStateMap_.end() &&
348         wearStateIter->second == BluetoothDeviceAction::WEAR_ACTION) {
349         AddDeviceInConfigVector(device, privacyDevices_);
350         desc.deviceCategory_ = BT_HEADPHONE;
351     } else {
352         AddDeviceInConfigVector(device, negativeDevices_);
353         desc.deviceCategory_ = BT_UNWEAR_HEADPHONE;
354     }
355     std::lock_guard<std::mutex> observerLock(g_observerLock);
356     if (g_deviceObserver != nullptr) {
357         g_deviceObserver->OnDeviceInfoUpdated(desc, DeviceInfoUpdateCommand::CATEGORY_UPDATE);
358     }
359 }
360 
HandleWearDisable(const BluetoothRemoteDevice &device)361 void MediaBluetoothDeviceManager::HandleWearDisable(const BluetoothRemoteDevice &device)
362 {
363     if (!IsA2dpBluetoothDeviceExist(device.GetDeviceAddr())) {
364         AUDIO_ERR_LOG("HandleWearDisable failed for the device has not connected.");
365         return;
366     }
367     RemoveDeviceInConfigVector(device, privacyDevices_);
368     RemoveDeviceInConfigVector(device, negativeDevices_);
369     AddDeviceInConfigVector(device, privacyDevices_);
370     AudioDeviceDescriptor desc;
371     desc.deviceType_ = DEVICE_TYPE_BLUETOOTH_A2DP;
372     desc.macAddress_ = device.GetDeviceAddr();
373     desc.deviceCategory_ = BT_HEADPHONE;
374     std::lock_guard<std::mutex> observerLock(g_observerLock);
375     if (g_deviceObserver != nullptr) {
376         g_deviceObserver->OnDeviceInfoUpdated(desc, DeviceInfoUpdateCommand::CATEGORY_UPDATE);
377     }
378 }
379 
HandleUserSelection(const BluetoothRemoteDevice &device)380 void MediaBluetoothDeviceManager::HandleUserSelection(const BluetoothRemoteDevice &device)
381 {
382     std::lock_guard<std::mutex> observerLock(g_observerLock);
383     if (g_deviceObserver != nullptr) {
384         g_deviceObserver->OnForcedDeviceSelected(DEVICE_TYPE_BLUETOOTH_A2DP, device.GetDeviceAddr());
385     }
386 }
387 
HandleVirtualConnectDevice(const BluetoothRemoteDevice &device)388 void MediaBluetoothDeviceManager::HandleVirtualConnectDevice(const BluetoothRemoteDevice &device)
389 {
390     if (IsA2dpBluetoothDeviceExist(device.GetDeviceAddr())) {
391         return;
392     }
393     AddDeviceInConfigVector(device, virtualDevices_);
394     DeviceCategory bluetoothCategory = GetDeviceCategory(device);
395     AudioDeviceDescriptor desc;
396     desc.deviceCategory_ = bluetoothCategory;
397     AddDeviceInConfigVector(device, negativeDevices_);
398     NotifyToUpdateVirtualDevice(device, desc, DeviceStatus::VIRTUAL_ADD);
399 }
400 
HandleRemoveVirtualConnectDevice(const BluetoothRemoteDevice &device)401 void MediaBluetoothDeviceManager::HandleRemoveVirtualConnectDevice(const BluetoothRemoteDevice &device)
402 {
403     if (IsA2dpBluetoothDeviceExist(device.GetDeviceAddr())) {
404         AUDIO_INFO_LOG("The device is already removed as virtual Devices, ignore remove action.");
405         return;
406     }
407     RemoveDeviceInConfigVector(device, virtualDevices_);
408     RemoveDeviceInConfigVector(device, negativeDevices_);
409     AudioDeviceDescriptor desc;
410     desc.deviceCategory_ = CATEGORY_DEFAULT;
411     NotifyToUpdateVirtualDevice(device, desc, DeviceStatus::VIRTUAL_REMOVE);
412 }
413 
AddDeviceInConfigVector(const BluetoothRemoteDevice &device, std::vector<BluetoothRemoteDevice> &deviceVector)414 void MediaBluetoothDeviceManager::AddDeviceInConfigVector(const BluetoothRemoteDevice &device,
415     std::vector<BluetoothRemoteDevice> &deviceVector)
416 {
417     std::lock_guard<std::mutex> a2dpDeviceLock(g_a2dpDeviceLock);
418     auto isPresent = [&device] (BluetoothRemoteDevice &bluetoothRemoteDevice) {
419         return device.GetDeviceAddr() == bluetoothRemoteDevice.GetDeviceAddr();
420     };
421     auto deviceIter = std::find_if(deviceVector.begin(), deviceVector.end(), isPresent);
422     if (deviceIter == deviceVector.end()) {
423         deviceVector.push_back(device);
424     }
425 }
426 
RemoveDeviceInConfigVector(const BluetoothRemoteDevice &device, std::vector<BluetoothRemoteDevice> &deviceVector)427 void MediaBluetoothDeviceManager::RemoveDeviceInConfigVector(const BluetoothRemoteDevice &device,
428     std::vector<BluetoothRemoteDevice> &deviceVector)
429 {
430     std::lock_guard<std::mutex> a2dpDeviceLock(g_a2dpDeviceLock);
431     auto isPresent = [&device] (BluetoothRemoteDevice &bluetoothRemoteDevice) {
432         return device.GetDeviceAddr() == bluetoothRemoteDevice.GetDeviceAddr();
433     };
434     auto deviceIter = std::find_if(deviceVector.begin(), deviceVector.end(), isPresent);
435     if (deviceIter != deviceVector.end()) {
436         deviceVector.erase(deviceIter);
437     }
438 }
439 
NotifyToUpdateAudioDevice(const BluetoothRemoteDevice &device, AudioDeviceDescriptor &desc, DeviceStatus deviceStatus)440 void MediaBluetoothDeviceManager::NotifyToUpdateAudioDevice(const BluetoothRemoteDevice &device,
441     AudioDeviceDescriptor &desc, DeviceStatus deviceStatus)
442 {
443     desc.deviceType_ = DEVICE_TYPE_BLUETOOTH_A2DP;
444     desc.deviceRole_ = DeviceRole::OUTPUT_DEVICE;
445     desc.macAddress_ = device.GetDeviceAddr();
446     desc.deviceName_ = device.GetDeviceName();
447     desc.connectState_ = ConnectState::CONNECTED;
448     AUDIO_INFO_LOG("a2dpBluetoothDeviceMap_ operation: %{public}d new bluetooth device, device address is %{public}s,\
449         category is %{public}d, device name is %{public}s", deviceStatus,
450         GetEncryptAddr(device.GetDeviceAddr()).c_str(), desc.deviceCategory_, desc.deviceName_.c_str());
451     {
452         std::lock_guard<std::mutex> deviceMapLock(g_a2dpDeviceMapLock);
453         if (deviceStatus == DeviceStatus::ADD) {
454             a2dpBluetoothDeviceMap_[device.GetDeviceAddr()] = device;
455         } else if (deviceStatus == DeviceStatus::REMOVE) {
456             if (a2dpBluetoothDeviceMap_.find(device.GetDeviceAddr()) != a2dpBluetoothDeviceMap_.end()) {
457                 a2dpBluetoothDeviceMap_.erase(device.GetDeviceAddr());
458             }
459         }
460     }
461     std::lock_guard<std::mutex> observerLock(g_observerLock);
462     CHECK_AND_RETURN_LOG(g_deviceObserver != nullptr, "NotifyToUpdateAudioDevice, device observer is null");
463     bool isConnected = deviceStatus == DeviceStatus::ADD;
464     g_deviceObserver->OnDeviceStatusUpdated(desc, isConnected);
465 }
466 
NotifyToUpdateVirtualDevice(const BluetoothRemoteDevice &device, AudioDeviceDescriptor &desc, DeviceStatus deviceStatus)467 void MediaBluetoothDeviceManager::NotifyToUpdateVirtualDevice(const BluetoothRemoteDevice &device,
468     AudioDeviceDescriptor &desc, DeviceStatus deviceStatus)
469 {
470     desc.deviceType_ = DEVICE_TYPE_BLUETOOTH_A2DP;
471     desc.deviceRole_ = DeviceRole::OUTPUT_DEVICE;
472     desc.macAddress_ = device.GetDeviceAddr();
473     desc.deviceName_ = device.GetDeviceName();
474     desc.connectState_ = ConnectState::VIRTUAL_CONNECTED;
475     std::lock_guard<std::mutex> observerLock(g_observerLock);
476     CHECK_AND_RETURN_LOG(g_deviceObserver != nullptr, "NotifyToUpdateVirtualDevice, device observer is null");
477     bool isConnected = deviceStatus == DeviceStatus::VIRTUAL_ADD;
478     g_deviceObserver->OnDeviceStatusUpdated(desc, isConnected);
479 }
480 
IsA2dpBluetoothDeviceExist(const std::string& macAddress)481 bool MediaBluetoothDeviceManager::IsA2dpBluetoothDeviceExist(const std::string& macAddress)
482 {
483     std::lock_guard<std::mutex> deviceMapLock(g_a2dpDeviceMapLock);
484     if (a2dpBluetoothDeviceMap_.find(macAddress) != a2dpBluetoothDeviceMap_.end()) {
485         return true;
486     }
487     return false;
488 }
489 
IsA2dpBluetoothDeviceConnecting(const std::string& macAddress)490 bool MediaBluetoothDeviceManager::IsA2dpBluetoothDeviceConnecting(const std::string& macAddress)
491 {
492     std::lock_guard<std::mutex> a2dpDeviceLock(g_a2dpDeviceLock);
493     auto deviceIter = std::find_if(connectingDevices_.begin(), connectingDevices_.end(),
494         [&macAddress] (BluetoothRemoteDevice &bluetoothRemoteDevice) {
495             return macAddress == bluetoothRemoteDevice.GetDeviceAddr();
496         });
497     if (deviceIter != connectingDevices_.end()) {
498         return true;
499     }
500     return false;
501 }
502 
GetConnectedA2dpBluetoothDevice(const std::string& macAddress, BluetoothRemoteDevice &device)503 int32_t MediaBluetoothDeviceManager::GetConnectedA2dpBluetoothDevice(const std::string& macAddress,
504     BluetoothRemoteDevice &device)
505 {
506     std::lock_guard<std::mutex> deviceMapLock(g_a2dpDeviceMapLock);
507     auto deviceIter = a2dpBluetoothDeviceMap_.find(macAddress);
508     if (deviceIter != a2dpBluetoothDeviceMap_.end()) {
509         device = deviceIter->second;
510         return SUCCESS;
511     }
512     return ERROR;
513 }
514 
GetAllA2dpBluetoothDevice()515 std::vector<BluetoothRemoteDevice> MediaBluetoothDeviceManager::GetAllA2dpBluetoothDevice()
516 {
517     std::lock_guard<std::mutex> deviceMapLock(g_a2dpDeviceMapLock);
518     std::vector<BluetoothRemoteDevice> a2dpList = {};
519     a2dpList.reserve(a2dpBluetoothDeviceMap_.size());
520     for (const auto &[macaddr, device] : a2dpBluetoothDeviceMap_) {
521         a2dpList.emplace_back(device);
522     }
523     return a2dpList;
524 }
525 
UpdateA2dpDeviceConfiguration(const BluetoothRemoteDevice &device, const AudioStreamInfo &streamInfo)526 void MediaBluetoothDeviceManager::UpdateA2dpDeviceConfiguration(const BluetoothRemoteDevice &device,
527     const AudioStreamInfo &streamInfo)
528 {
529     std::lock_guard<std::mutex> observerLock(g_observerLock);
530     CHECK_AND_RETURN_LOG(g_deviceObserver != nullptr, "UpdateA2dpDeviceConfiguration, device observer is null");
531     g_deviceObserver->OnDeviceConfigurationChanged(DEVICE_TYPE_BLUETOOTH_A2DP, device.GetDeviceAddr(),
532         device.GetDeviceName(), streamInfo);
533 }
534 
ClearAllA2dpBluetoothDevice()535 void MediaBluetoothDeviceManager::ClearAllA2dpBluetoothDevice()
536 {
537     AUDIO_INFO_LOG("Bluetooth service crashed and enter the ClearAllA2dpBluetoothDevice.");
538     {
539         std::lock_guard<std::mutex> a2dpDeviceLock(g_a2dpDeviceLock);
540         privacyDevices_.clear();
541         commonDevices_.clear();
542         negativeDevices_.clear();
543         connectingDevices_.clear();
544         virtualDevices_.clear();
545     }
546     std::lock_guard<std::mutex> deviceMapLock(g_a2dpDeviceMapLock);
547     std::lock_guard<std::mutex> wearStateMapLock(g_a2dpWearStateMapLock);
548     a2dpBluetoothDeviceMap_.clear();
549     wearDetectionStateMap_.clear();
550 }
551 
GetA2dpVirtualDeviceList()552 std::vector<BluetoothRemoteDevice> MediaBluetoothDeviceManager::GetA2dpVirtualDeviceList()
553 {
554     std::lock_guard<std::mutex> a2dpDeviceLock(g_hfpDeviceLock);
555     return virtualDevices_;
556 }
557 
SetHfpStack(const BluetoothRemoteDevice &device, int action)558 void HfpBluetoothDeviceManager::SetHfpStack(const BluetoothRemoteDevice &device, int action)
559 {
560     switch (action) {
561         case BluetoothDeviceAction::CONNECTING_ACTION:
562             HandleConnectingDevice(device);
563             break;
564         case BluetoothDeviceAction::CONNECT_ACTION:
565             HandleConnectDevice(device);
566             break;
567         case BluetoothDeviceAction::DISCONNECT_ACTION:
568             HandleDisconnectDevice(device);
569             break;
570         case BluetoothDeviceAction::WEAR_ACTION:
571             HandleWearDevice(device);
572             break;
573         case BluetoothDeviceAction::UNWEAR_ACTION:
574             HandleUnwearDevice(device);
575             break;
576         case BluetoothDeviceAction::ENABLEFROMREMOTE_ACTION:
577             HandleEnableDevice(device);
578             break;
579         case BluetoothDeviceAction::DISABLEFROMREMOTE_ACTION:
580             HandleDisableDevice(device);
581             break;
582         case BluetoothDeviceAction::ENABLE_WEAR_DETECTION_ACTION:
583             HandleWearEnable(device);
584             break;
585         case BluetoothDeviceAction::DISABLE_WEAR_DETECTION_ACTION:
586             HandleWearDisable(device);
587             break;
588         case BluetoothDeviceAction::USER_SELECTION_ACTION:
589             HandleUserSelection(device);
590             break;
591         case BluetoothDeviceAction::STOP_VIRTUAL_CALL:
592             HandleStopVirtualCall(device);
593             break;
594         case BluetoothDeviceAction::VIRTUAL_DEVICE_ADD_ACTION:
595             HandleVirtualConnectDevice(device);
596             break;
597         case BluetoothDeviceAction::VIRTUAL_DEVICE_REMOVE_ACTION:
598             HandleRemoveVirtualConnectDevice(device);
599             break;
600         default:
601             AUDIO_ERR_LOG("SetHfpStack failed due to the unknow action: %{public}d", action);
602             break;
603     }
604 }
605 
HandleConnectingDevice(const BluetoothRemoteDevice &device)606 void HfpBluetoothDeviceManager::HandleConnectingDevice(const BluetoothRemoteDevice &device)
607 {
608     if (IsHfpBluetoothDeviceExist(device.GetDeviceAddr())) {
609         return;
610     }
611     AddDeviceInConfigVector(device, connectingDevices_);
612 }
613 
HandleConnectDevice(const BluetoothRemoteDevice &device)614 void HfpBluetoothDeviceManager::HandleConnectDevice(const BluetoothRemoteDevice &device)
615 {
616     if (IsHfpBluetoothDeviceExist(device.GetDeviceAddr())) {
617         return;
618     }
619     RemoveDeviceInConfigVector(device, connectingDevices_);
620     RemoveDeviceInConfigVector(device, negativeDevices_);
621     RemoveDeviceInConfigVector(device, virtualDevices_);
622     DeviceCategory bluetoothCategory = GetDeviceCategory(device);
623     AudioDeviceDescriptor desc;
624     desc.deviceCategory_ = bluetoothCategory;
625     switch (bluetoothCategory) {
626         case BT_HEADPHONE:
627             if (IsBTWearDetectionEnable(device)) {
628                 AddDeviceInConfigVector(device, negativeDevices_);
629                 desc.deviceCategory_ = BT_UNWEAR_HEADPHONE;
630             } else {
631                 AddDeviceInConfigVector(device, privacyDevices_);
632             }
633             break;
634         case BT_GLASSES:
635             AddDeviceInConfigVector(device, privacyDevices_);
636             break;
637         case BT_SOUNDBOX:
638         case BT_CAR:
639             AddDeviceInConfigVector(device, commonDevices_);
640             break;
641         case BT_WATCH:
642             AddDeviceInConfigVector(device, negativeDevices_);
643             break;
644         default:
645             AUDIO_INFO_LOG("Unknow BT category, regard as bluetooth headset.");
646             AddDeviceInConfigVector(device, privacyDevices_);
647             desc.deviceCategory_ = BT_HEADPHONE;
648             break;
649     }
650     NotifyToUpdateAudioDevice(device, desc, DeviceStatus::ADD);
651 }
652 
HandleDisconnectDevice(const BluetoothRemoteDevice &device)653 void HfpBluetoothDeviceManager::HandleDisconnectDevice(const BluetoothRemoteDevice &device)
654 {
655     RemoveDeviceInConfigVector(device, connectingDevices_);
656     if (!IsHfpBluetoothDeviceExist(device.GetDeviceAddr())) {
657         AUDIO_INFO_LOG("The device is already disconnected, ignore disconnect action.");
658         return;
659     }
660     RemoveDeviceInConfigVector(device, privacyDevices_);
661     RemoveDeviceInConfigVector(device, commonDevices_);
662     RemoveDeviceInConfigVector(device, negativeDevices_);
663     {
664         std::lock_guard<std::mutex> wearStateMapLock(g_hfpWearStateMapLock);
665         wearDetectionStateMap_.erase(device.GetDeviceAddr());
666     }
667     AudioDeviceDescriptor desc;
668     desc.deviceCategory_ = CATEGORY_DEFAULT;
669     NotifyToUpdateAudioDevice(device, desc, DeviceStatus::REMOVE);
670 }
671 
HandleWearDevice(const BluetoothRemoteDevice &device)672 void HfpBluetoothDeviceManager::HandleWearDevice(const BluetoothRemoteDevice &device)
673 {
674     if (!IsHfpBluetoothDeviceExist(device.GetDeviceAddr())) {
675         AUDIO_ERR_LOG("HandleWearDevice failed for the device has not be reported the connected action.");
676         return;
677     }
678     RemoveDeviceInConfigVector(device, negativeDevices_);
679     RemoveDeviceInConfigVector(device, privacyDevices_);
680     AddDeviceInConfigVector(device, privacyDevices_);
681     {
682         std::lock_guard<std::mutex> wearStateMapLock(g_hfpWearStateMapLock);
683         wearDetectionStateMap_[device.GetDeviceAddr()] = BluetoothDeviceAction::WEAR_ACTION;
684     }
685     AudioDeviceDescriptor desc;
686     desc.deviceType_ = DEVICE_TYPE_BLUETOOTH_SCO;
687     desc.macAddress_ = device.GetDeviceAddr();
688     desc.deviceCategory_ = BT_HEADPHONE;
689     std::lock_guard<std::mutex> observerLock(g_observerLock);
690     if (g_deviceObserver != nullptr) {
691         g_deviceObserver->OnDeviceInfoUpdated(desc, DeviceInfoUpdateCommand::CATEGORY_UPDATE);
692     }
693 }
694 
HandleUnwearDevice(const BluetoothRemoteDevice &device)695 void HfpBluetoothDeviceManager::HandleUnwearDevice(const BluetoothRemoteDevice &device)
696 {
697     if (!IsHfpBluetoothDeviceExist(device.GetDeviceAddr())) {
698         AUDIO_ERR_LOG("HandleWearDevice failed for the device has not worn.");
699         return;
700     }
701     RemoveDeviceInConfigVector(device, privacyDevices_);
702     RemoveDeviceInConfigVector(device, negativeDevices_);
703     AddDeviceInConfigVector(device, negativeDevices_);
704     {
705         std::lock_guard<std::mutex> wearStateMapLock(g_hfpWearStateMapLock);
706         wearDetectionStateMap_[device.GetDeviceAddr()] = BluetoothDeviceAction::UNWEAR_ACTION;
707     }
708     AudioDeviceDescriptor desc;
709     desc.deviceType_ = DEVICE_TYPE_BLUETOOTH_SCO;
710     desc.macAddress_ = device.GetDeviceAddr();
711     desc.deviceCategory_ = BT_UNWEAR_HEADPHONE;
712     std::lock_guard<std::mutex> observerLock(g_observerLock);
713     if (g_deviceObserver != nullptr) {
714         g_deviceObserver->OnDeviceInfoUpdated(desc, DeviceInfoUpdateCommand::CATEGORY_UPDATE);
715     }
716 }
717 
HandleEnableDevice(const BluetoothRemoteDevice &device)718 void HfpBluetoothDeviceManager::HandleEnableDevice(const BluetoothRemoteDevice &device)
719 {
720     if (!IsHfpBluetoothDeviceExist(device.GetDeviceAddr())) {
721         AUDIO_ERR_LOG("HandleEnableDevice failed for the device has not connected.");
722         return;
723     }
724     AudioDeviceDescriptor desc;
725     desc.deviceType_ = DEVICE_TYPE_BLUETOOTH_SCO;
726     desc.macAddress_ = device.GetDeviceAddr();
727     desc.isEnable_ = true;
728     std::lock_guard<std::mutex> observerLock(g_observerLock);
729     if (g_deviceObserver != nullptr) {
730         g_deviceObserver->OnDeviceInfoUpdated(desc, DeviceInfoUpdateCommand::ENABLE_UPDATE);
731     }
732 }
733 
HandleDisableDevice(const BluetoothRemoteDevice &device)734 void HfpBluetoothDeviceManager::HandleDisableDevice(const BluetoothRemoteDevice &device)
735 {
736     if (!IsHfpBluetoothDeviceExist(device.GetDeviceAddr())) {
737         AUDIO_ERR_LOG("HandleDisableDevice failed for the device has not connected.");
738         return;
739     }
740     AudioDeviceDescriptor desc;
741     desc.deviceType_ = DEVICE_TYPE_BLUETOOTH_SCO;
742     desc.macAddress_ = device.GetDeviceAddr();
743     desc.isEnable_ = false;
744     std::lock_guard<std::mutex> observerLock(g_observerLock);
745     if (g_deviceObserver != nullptr) {
746         g_deviceObserver->OnDeviceInfoUpdated(desc, DeviceInfoUpdateCommand::ENABLE_UPDATE);
747     }
748 }
749 
HandleWearEnable(const BluetoothRemoteDevice &device)750 void HfpBluetoothDeviceManager::HandleWearEnable(const BluetoothRemoteDevice &device)
751 {
752     if (!IsHfpBluetoothDeviceExist(device.GetDeviceAddr())) {
753         AUDIO_ERR_LOG("HandleWearEnable failed for the device has not connected.");
754         return;
755     }
756     RemoveDeviceInConfigVector(device, negativeDevices_);
757     RemoveDeviceInConfigVector(device, privacyDevices_);
758     std::lock_guard<std::mutex> wearStateMapLock(g_hfpWearStateMapLock);
759     AudioDeviceDescriptor desc;
760     desc.deviceType_ = DEVICE_TYPE_BLUETOOTH_SCO;
761     desc.macAddress_ = device.GetDeviceAddr();
762     auto wearStateIter = wearDetectionStateMap_.find(device.GetDeviceAddr());
763     if (wearStateIter != wearDetectionStateMap_.end() &&
764         wearStateIter->second == BluetoothDeviceAction::WEAR_ACTION) {
765         AddDeviceInConfigVector(device, privacyDevices_);
766         desc.deviceCategory_ = BT_HEADPHONE;
767     } else {
768         AddDeviceInConfigVector(device, negativeDevices_);
769         desc.deviceCategory_ = BT_UNWEAR_HEADPHONE;
770     }
771     std::lock_guard<std::mutex> observerLock(g_observerLock);
772     if (g_deviceObserver != nullptr) {
773         g_deviceObserver->OnDeviceInfoUpdated(desc, DeviceInfoUpdateCommand::CATEGORY_UPDATE);
774     }
775 }
776 
HandleWearDisable(const BluetoothRemoteDevice &device)777 void HfpBluetoothDeviceManager::HandleWearDisable(const BluetoothRemoteDevice &device)
778 {
779     if (!IsHfpBluetoothDeviceExist(device.GetDeviceAddr())) {
780         AUDIO_ERR_LOG("HandleWearDisable failed for the device has not connected.");
781         return;
782     }
783     RemoveDeviceInConfigVector(device, privacyDevices_);
784     RemoveDeviceInConfigVector(device, negativeDevices_);
785     AddDeviceInConfigVector(device, privacyDevices_);
786     AudioDeviceDescriptor desc;
787     desc.deviceType_ = DEVICE_TYPE_BLUETOOTH_SCO;
788     desc.macAddress_ = device.GetDeviceAddr();
789     desc.deviceCategory_ = BT_HEADPHONE;
790     std::lock_guard<std::mutex> observerLock(g_observerLock);
791     if (g_deviceObserver != nullptr) {
792         g_deviceObserver->OnDeviceInfoUpdated(desc, DeviceInfoUpdateCommand::CATEGORY_UPDATE);
793     }
794 }
795 
HandleUserSelection(const BluetoothRemoteDevice &device)796 void HfpBluetoothDeviceManager::HandleUserSelection(const BluetoothRemoteDevice &device)
797 {
798     std::string deviceAddr = device.GetDeviceAddr();
799     DeviceCategory bluetoothCategory = GetDeviceCategory(device);
800     if (bluetoothCategory == BT_WATCH) {
801         std::lock_guard<std::mutex> wearStateMapLock(g_hfpWearStateMapLock);
802         std::lock_guard<std::mutex> hfpDeviceLock(g_hfpDeviceLock);
803         auto isPresent = [] (BluetoothRemoteDevice &bluetoothRemoteDevice) {
804             return wearDetectionStateMap_[bluetoothRemoteDevice.GetDeviceAddr()] == WEAR_ACTION;
805         };
806         auto deviceIter = std::find_if(privacyDevices_.rbegin(), privacyDevices_.rend(), isPresent);
807         if (deviceIter != privacyDevices_.rend()) {
808             deviceAddr = deviceIter->GetDeviceAddr();
809             AUDIO_INFO_LOG("Change user select device from watch %{public}s to wear headphone %{public}s",
810                 device.GetDeviceAddr().c_str(), deviceAddr.c_str());
811         }
812     }
813     std::lock_guard<std::mutex> observerLock(g_observerLock);
814     if (g_deviceObserver != nullptr) {
815         g_deviceObserver->OnForcedDeviceSelected(DEVICE_TYPE_BLUETOOTH_SCO, deviceAddr);
816     }
817 }
818 
HandleStopVirtualCall(const BluetoothRemoteDevice &device)819 void HfpBluetoothDeviceManager::HandleStopVirtualCall(const BluetoothRemoteDevice &device)
820 {
821     {
822         std::lock_guard<std::mutex> handleLock(stopVirtualCallHandleLock_);
823         stopVirtualCallHandle_.device = device;
824         stopVirtualCallHandle_.isWaitingForStoppingVirtualCall = true;
825     }
826     AUDIO_INFO_LOG("bluetooth service trigger disconnect sco");
827     std::thread disconnectScoThread = std::thread(&Bluetooth::AudioHfpManager::DisconnectSco);
828     disconnectScoThread.detach();
829 }
830 
HandleVirtualConnectDevice(const BluetoothRemoteDevice &device)831 void HfpBluetoothDeviceManager::HandleVirtualConnectDevice(const BluetoothRemoteDevice &device)
832 {
833     if (IsHfpBluetoothDeviceExist(device.GetDeviceAddr())) {
834         return;
835     }
836     AddDeviceInConfigVector(device, virtualDevices_);
837     DeviceCategory bluetoothCategory = GetDeviceCategory(device);
838     AudioDeviceDescriptor desc;
839     desc.deviceCategory_ = bluetoothCategory;
840     AddDeviceInConfigVector(device, negativeDevices_);
841     NotifyToUpdateVirtualDevice(device, desc, DeviceStatus::VIRTUAL_ADD);
842 }
843 
HandleRemoveVirtualConnectDevice(const BluetoothRemoteDevice &device)844 void HfpBluetoothDeviceManager::HandleRemoveVirtualConnectDevice(const BluetoothRemoteDevice &device)
845 {
846     if (IsHfpBluetoothDeviceExist(device.GetDeviceAddr())) {
847         AUDIO_INFO_LOG("The device is already removed as virtual Devices, ignore remove action.");
848         return;
849     }
850     RemoveDeviceInConfigVector(device, virtualDevices_);
851     RemoveDeviceInConfigVector(device, negativeDevices_);
852     AudioDeviceDescriptor desc;
853     desc.deviceCategory_ = CATEGORY_DEFAULT;
854     NotifyToUpdateVirtualDevice(device, desc, DeviceStatus::VIRTUAL_REMOVE);
855 }
856 
AddDeviceInConfigVector(const BluetoothRemoteDevice &device, std::vector<BluetoothRemoteDevice> &deviceVector)857 void HfpBluetoothDeviceManager::AddDeviceInConfigVector(const BluetoothRemoteDevice &device,
858     std::vector<BluetoothRemoteDevice> &deviceVector)
859 {
860     std::lock_guard<std::mutex> hfpDeviceLock(g_hfpDeviceLock);
861     auto isPresent = [&device] (BluetoothRemoteDevice &bluetoothRemoteDevice) {
862         return device.GetDeviceAddr() == bluetoothRemoteDevice.GetDeviceAddr();
863     };
864     auto deviceIter = std::find_if(deviceVector.begin(), deviceVector.end(), isPresent);
865     if (deviceIter == deviceVector.end()) {
866         deviceVector.push_back(device);
867     }
868 }
869 
RemoveDeviceInConfigVector(const BluetoothRemoteDevice &device, std::vector<BluetoothRemoteDevice> &deviceVector)870 void HfpBluetoothDeviceManager::RemoveDeviceInConfigVector(const BluetoothRemoteDevice &device,
871     std::vector<BluetoothRemoteDevice> &deviceVector)
872 {
873     std::lock_guard<std::mutex> hfpDeviceLock(g_hfpDeviceLock);
874     auto isPresent = [&device] (BluetoothRemoteDevice &bluetoothRemoteDevice) {
875         return device.GetDeviceAddr() == bluetoothRemoteDevice.GetDeviceAddr();
876     };
877     auto deviceIter = std::find_if(deviceVector.begin(), deviceVector.end(), isPresent);
878     if (deviceIter != deviceVector.end()) {
879         deviceVector.erase(deviceIter);
880     }
881 }
882 
NotifyToUpdateAudioDevice(const BluetoothRemoteDevice &device, AudioDeviceDescriptor &desc, DeviceStatus deviceStatus)883 void HfpBluetoothDeviceManager::NotifyToUpdateAudioDevice(const BluetoothRemoteDevice &device,
884     AudioDeviceDescriptor &desc, DeviceStatus deviceStatus)
885 {
886     desc.deviceType_ = DEVICE_TYPE_BLUETOOTH_SCO;
887     desc.macAddress_ = device.GetDeviceAddr();
888     desc.deviceName_ = device.GetDeviceName();
889     desc.connectState_ = ConnectState::DEACTIVE_CONNECTED;
890     AUDIO_INFO_LOG("hfpBluetoothDeviceMap_ operation: %{public}d new bluetooth device, device address is %{public}s,\
891         category is %{public}d, device name is %{public}s", deviceStatus,
892         GetEncryptAddr(device.GetDeviceAddr()).c_str(), desc.deviceCategory_, desc.deviceName_.c_str());
893     {
894         std::lock_guard<std::mutex> deviceMapLock(g_hfpDeviceMapLock);
895         if (deviceStatus == DeviceStatus::ADD) {
896             hfpBluetoothDeviceMap_[device.GetDeviceAddr()] = device;
897         } else if (deviceStatus == DeviceStatus::REMOVE) {
898             if (hfpBluetoothDeviceMap_.find(device.GetDeviceAddr()) != hfpBluetoothDeviceMap_.end()) {
899                 hfpBluetoothDeviceMap_.erase(device.GetDeviceAddr());
900             }
901         }
902     }
903     std::lock_guard<std::mutex> observerLock(g_observerLock);
904     if (g_deviceObserver == nullptr) {
905         AUDIO_ERR_LOG("NotifyToUpdateAudioDevice, device observer is null");
906         return;
907     }
908     bool isConnected = deviceStatus == DeviceStatus::ADD;
909     g_deviceObserver->OnDeviceStatusUpdated(desc, isConnected);
910 }
911 
NotifyToUpdateVirtualDevice(const BluetoothRemoteDevice &device, AudioDeviceDescriptor &desc, DeviceStatus deviceStatus)912 void HfpBluetoothDeviceManager::NotifyToUpdateVirtualDevice(const BluetoothRemoteDevice &device,
913     AudioDeviceDescriptor &desc, DeviceStatus deviceStatus)
914 {
915     desc.deviceType_ = DEVICE_TYPE_BLUETOOTH_SCO;
916     desc.macAddress_ = device.GetDeviceAddr();
917     desc.deviceName_ = device.GetDeviceName();
918     desc.connectState_ = ConnectState::VIRTUAL_CONNECTED;
919     std::lock_guard<std::mutex> observerLock(g_observerLock);
920     CHECK_AND_RETURN_LOG(g_deviceObserver != nullptr, "NotifyToUpdateVirtualDevice, device observer is null");
921     bool isConnected = deviceStatus == DeviceStatus::VIRTUAL_ADD;
922     g_deviceObserver->OnDeviceStatusUpdated(desc, isConnected);
923 }
924 
IsHfpBluetoothDeviceExist(const std::string& macAddress)925 bool HfpBluetoothDeviceManager::IsHfpBluetoothDeviceExist(const std::string& macAddress)
926 {
927     std::lock_guard<std::mutex> deviceMapLock(g_hfpDeviceMapLock);
928     if (hfpBluetoothDeviceMap_.find(macAddress) != hfpBluetoothDeviceMap_.end()) {
929         return true;
930     }
931     return false;
932 }
933 
IsHfpBluetoothDeviceConnecting(const std::string& macAddress)934 bool HfpBluetoothDeviceManager::IsHfpBluetoothDeviceConnecting(const std::string& macAddress)
935 {
936     std::lock_guard<std::mutex> hfpDeviceLock(g_hfpDeviceLock);
937     auto deviceIter = std::find_if(connectingDevices_.begin(), connectingDevices_.end(),
938         [&macAddress] (BluetoothRemoteDevice &bluetoothRemoteDevice) {
939             return macAddress == bluetoothRemoteDevice.GetDeviceAddr();
940         });
941     if (deviceIter != connectingDevices_.end()) {
942         return true;
943     }
944     return false;
945 }
946 
GetConnectedHfpBluetoothDevice(const std::string& macAddress, BluetoothRemoteDevice &device)947 int32_t HfpBluetoothDeviceManager::GetConnectedHfpBluetoothDevice(const std::string& macAddress,
948     BluetoothRemoteDevice &device)
949 {
950     std::lock_guard<std::mutex> deviceMapLock(g_hfpDeviceMapLock);
951     auto deviceIter = hfpBluetoothDeviceMap_.find(macAddress);
952     if (deviceIter != hfpBluetoothDeviceMap_.end()) {
953         device = deviceIter->second;
954         return SUCCESS;
955     }
956     return ERROR;
957 }
958 
GetAllHfpBluetoothDevice()959 std::vector<BluetoothRemoteDevice> HfpBluetoothDeviceManager::GetAllHfpBluetoothDevice()
960 {
961     std::lock_guard<std::mutex> deviceMapLock(g_hfpDeviceMapLock);
962     std::vector<BluetoothRemoteDevice> hfpList = {};
963     hfpList.reserve(hfpBluetoothDeviceMap_.size());
964     for (const auto &[macaddr, device] : hfpBluetoothDeviceMap_) {
965         hfpList.emplace_back(device);
966     }
967     return hfpList;
968 }
969 
ClearAllHfpBluetoothDevice()970 void HfpBluetoothDeviceManager::ClearAllHfpBluetoothDevice()
971 {
972     AUDIO_INFO_LOG("Bluetooth service crashed and enter the ClearAllhfpBluetoothDevice.");
973     {
974         std::lock_guard<std::mutex> hfpDeviceLock(g_hfpDeviceLock);
975         privacyDevices_.clear();
976         commonDevices_.clear();
977         negativeDevices_.clear();
978         connectingDevices_.clear();
979         virtualDevices_.clear();
980     }
981     std::lock_guard<std::mutex> deviceMapLock(g_hfpDeviceMapLock);
982     std::lock_guard<std::mutex> wearStateMapLock(g_hfpWearStateMapLock);
983     hfpBluetoothDeviceMap_.clear();
984     wearDetectionStateMap_.clear();
985 }
986 
OnScoStateChanged(const BluetoothRemoteDevice &device, bool isConnected, int reason)987 void HfpBluetoothDeviceManager::OnScoStateChanged(const BluetoothRemoteDevice &device, bool isConnected, int reason)
988 {
989     AudioDeviceDescriptor desc;
990     desc.deviceType_ = DEVICE_TYPE_BLUETOOTH_SCO;
991     desc.macAddress_ = device.GetDeviceAddr();
992     if (isConnected) {
993         desc.connectState_ = ConnectState::CONNECTED;
994     } else {
995         {
996             std::lock_guard<std::mutex> handleLock(stopVirtualCallHandleLock_);
997             if (device.GetDeviceAddr() == stopVirtualCallHandle_.device.GetDeviceAddr() &&
998                 stopVirtualCallHandle_.isWaitingForStoppingVirtualCall) {
999                 AUDIO_INFO_LOG("reason change to %{public}d", HFP_AG_SCO_REMOTE_USER_TERMINATED);
1000                 reason = HFP_AG_SCO_REMOTE_USER_TERMINATED;
1001                 stopVirtualCallHandle_.device = BluetoothRemoteDevice();
1002                 stopVirtualCallHandle_.isWaitingForStoppingVirtualCall = false;
1003             }
1004         }
1005         desc.connectState_ = reason == HFP_AG_SCO_REMOTE_USER_TERMINATED ?  ConnectState::SUSPEND_CONNECTED
1006                                                                          :  ConnectState::DEACTIVE_CONNECTED;
1007     }
1008     std::lock_guard<std::mutex> observerLock(g_observerLock);
1009     if (g_deviceObserver != nullptr) {
1010         g_deviceObserver->OnDeviceInfoUpdated(desc, DeviceInfoUpdateCommand::CONNECTSTATE_UPDATE);
1011     }
1012 }
1013 
GetHfpVirtualDeviceList()1014 std::vector<BluetoothRemoteDevice> HfpBluetoothDeviceManager::GetHfpVirtualDeviceList()
1015 {
1016     std::lock_guard<std::mutex> hfpDeviceLock(g_hfpDeviceLock);
1017     return virtualDevices_;
1018 }
1019 // LCOV_EXCL_STOP
1020 } // namespace Bluetooth
1021 } // namespace OHOS
1022