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