• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-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 
16 #include <regex>
17 #include "usb_device_manager.h"
18 #include <hdf_base.h>
19 #include "common_event_data.h"
20 #include "common_event_manager.h"
21 #include "common_event_support.h"
22 #include "usb_connection_notifier.h"
23 #include "hisysevent.h"
24 #include "usb_errors.h"
25 #include "usb_srv_support.h"
26 #include "usbd_type.h"
27 
28 using namespace OHOS::AAFwk;
29 using namespace OHOS::EventFwk;
30 using namespace OHOS::HiviewDFX;
31 using namespace OHOS::HDI::Usb::V1_0;
32 
33 namespace OHOS {
34 namespace USB {
35 constexpr int32_t PARAM_COUNT_TWO = 2;
36 constexpr int32_t PARAM_COUNT_THR = 3;
37 constexpr int32_t DECIMAL_BASE = 10;
38 constexpr uint32_t CMD_INDEX = 1;
39 constexpr uint32_t PARAM_INDEX = 2;
40 constexpr uint32_t DELAY_CONNECT_INTERVAL = 1000;
41 constexpr uint32_t DELAY_DISCONN_INTERVAL = 1400;
42 const std::map<std::string_view, uint32_t> UsbDeviceManager::FUNCTION_MAPPING_N2C = {
43     {UsbSrvSupport::FUNCTION_NAME_NONE, UsbSrvSupport::FUNCTION_NONE},
44     {UsbSrvSupport::FUNCTION_NAME_ACM, UsbSrvSupport::FUNCTION_ACM},
45     {UsbSrvSupport::FUNCTION_NAME_ECM, UsbSrvSupport::FUNCTION_ECM},
46     {UsbSrvSupport::FUNCTION_NAME_HDC, UsbSrvSupport::FUNCTION_HDC},
47     {UsbSrvSupport::FUNCTION_NAME_MTP, UsbSrvSupport::FUNCTION_MTP},
48     {UsbSrvSupport::FUNCTION_NAME_PTP, UsbSrvSupport::FUNCTION_PTP},
49     {UsbSrvSupport::FUNCTION_NAME_RNDIS, UsbSrvSupport::FUNCTION_RNDIS},
50     {UsbSrvSupport::FUNCTION_NAME_NCM, UsbSrvSupport::FUNCTION_NCM},
51     {UsbSrvSupport::FUNCTION_NAME_STORAGE, UsbSrvSupport::FUNCTION_STORAGE},
52     {UsbSrvSupport::FUNCTION_NAME_DEVMODE_AUTH, UsbSrvSupport::FUNCTION_DEVMODE_AUTH},
53 };
54 
UsbDeviceManager()55 UsbDeviceManager::UsbDeviceManager()
56 {
57     USB_HILOGI(MODULE_USB_SERVICE, "UsbDeviceManager::Init start");
58 #ifndef USB_MANAGER_V2_0
59     if (usbd_ == nullptr) {
60         usbd_ = IUsbInterface::Get();
61         USB_HILOGI(MODULE_USB_SERVICE, "%{public}s:%{public}d usbd_ == nullptr: %{public}d",
62             __func__, __LINE__, usbd_ == nullptr);
63     } else {
64         USB_HILOGW(MODULE_USB_SERVICE, "%{public}s:usbd_ != nullptr", __func__);
65     }
66     if (usbd_ == nullptr) {
67         USB_HILOGE(MODULE_USB_SERVICE, "UsbDeviceManager::Get inteface failed");
68     }
69 #endif // USB_MANAGER_V2_0
70 }
71 
72 #ifdef USB_MANAGER_V2_0
InitUsbDeviceInterface()73 bool UsbDeviceManager::InitUsbDeviceInterface()
74 {
75     USB_HILOGI(MODULE_USB_SERVICE, "InitUsbDeviceInterface in");
76     usbDeviceInterface_ = HDI::Usb::V2_0::IUsbDeviceInterface::Get();
77     if (usbDeviceInterface_ == nullptr) {
78         USB_HILOGE(MODULE_USB_SERVICE, "InitUsbDeviceInterface get usbDeviceInterface_ is nullptr");
79         return false;
80     }
81 
82     usbManagerSubscriber_ = new (std::nothrow) UsbManagerSubscriber();
83     if (usbManagerSubscriber_ == nullptr) {
84         USB_HILOGE(MODULE_USB_SERVICE, "Init failed");
85         return false;
86     }
87 
88     ErrCode ret = usbDeviceInterface_->BindUsbdDeviceSubscriber(usbManagerSubscriber_);
89     USB_HILOGI(MODULE_USB_SERVICE, "entry InitUsbDeviceInterface ret: %{public}d", ret);
90     return SUCCEEDED(ret);
91 }
92 
Stop()93 void UsbDeviceManager::Stop()
94 {
95     if (usbDeviceInterface_ == nullptr) {
96         USB_HILOGE(MODULE_USB_SERVICE, "UsbDeviceManager::usbDeviceInterface_ is nullptr");
97         return;
98     }
99     usbDeviceInterface_->UnbindUsbdDeviceSubscriber(usbManagerSubscriber_);
100     Memory::MemMgrClient::GetInstance().NotifyProcessStatus(getpid(), 1, 0, USB_SYSTEM_ABILITY_ID);
101 }
102 
BindUsbdSubscriber(const sptr<HDI::Usb::V2_0::IUsbdSubscriber> & subscriber)103 int32_t UsbDeviceManager::BindUsbdSubscriber(const sptr<HDI::Usb::V2_0::IUsbdSubscriber> &subscriber)
104 {
105     if (usbDeviceInterface_ == nullptr) {
106         USB_HILOGE(MODULE_USB_SERVICE, "UsbDeviceManager::BulkCancel usbDeviceInterface_ is nullptr");
107         return UEC_SERVICE_INVALID_VALUE;
108     }
109     return usbDeviceInterface_->BindUsbdDeviceSubscriber(subscriber);
110 }
111 
UnbindUsbdSubscriber(const sptr<HDI::Usb::V2_0::IUsbdSubscriber> & subscriber)112 int32_t UsbDeviceManager::UnbindUsbdSubscriber(const sptr<HDI::Usb::V2_0::IUsbdSubscriber> &subscriber)
113 {
114     if (usbDeviceInterface_ == nullptr) {
115         USB_HILOGE(MODULE_USB_SERVICE, "UsbDeviceManager::BulkCancel usbDeviceInterface_ is nullptr");
116         return UEC_SERVICE_INVALID_VALUE;
117     }
118     return usbDeviceInterface_->UnbindUsbdDeviceSubscriber(subscriber);
119 }
120 #endif
121 
GetCurrentFunctions(int32_t & funcs)122 int32_t UsbDeviceManager::GetCurrentFunctions(int32_t& funcs)
123 {
124 #ifdef USB_MANAGER_V2_0
125     if (usbDeviceInterface_ == nullptr) {
126         USB_HILOGE(MODULE_USB_SERVICE, "UsbDeviceManager::usbDeviceInterface_ is nullptr");
127         return UEC_SERVICE_INVALID_VALUE;
128     }
129     std::lock_guard<std::mutex> guard(functionMutex_);
130     return usbDeviceInterface_->GetCurrentFunctions(funcs);
131 #else
132     if (usbd_ == nullptr) {
133         USB_HILOGE(MODULE_USB_SERVICE, "UsbDeviceManager::usbd_ is nullptr");
134         return UEC_SERVICE_INVALID_VALUE;
135     }
136     std::lock_guard<std::mutex> guard(functionMutex_);
137     return usbd_->GetCurrentFunctions(funcs);
138 #endif // USB_MANAGER_V2_0
139 }
140 
141 #ifdef USB_MANAGER_V2_0
SetCurrentFunctions(int32_t funcs)142 int32_t UsbDeviceManager::SetCurrentFunctions(int32_t funcs)
143 {
144     if (usbDeviceInterface_ == nullptr) {
145         USB_HILOGE(MODULE_USB_SERVICE, "UsbDeviceManager::usbDeviceInterface_ is nullptr");
146         return UEC_SERVICE_INVALID_VALUE;
147     }
148     int32_t lastFunc;
149     std::lock_guard<std::mutex> guard(functionMutex_);
150     if (usbDeviceInterface_->GetCurrentFunctions(lastFunc) != UEC_OK) {
151         USB_HILOGE(MODULE_USB_SERVICE, "UsbDeviceManager::get current functions fail");
152         ReportUsbOperationFaultSysEvent("FUNCTION_CHANGED", UEC_SERVICE_INVALID_VALUE, "DevIntfGetFunc is failed");
153         return UEC_SERVICE_INVALID_VALUE;
154     }
155     if (lastFunc == funcs) {
156         USB_HILOGI(MODULE_USB_SERVICE, "UsbDeviceManager::no change in functionality");
157         return UEC_OK;
158     }
159     int32_t ret = usbDeviceInterface_->SetCurrentFunctions(funcs);
160     if (ret != UEC_OK) {
161         USB_HILOGE(MODULE_USB_SERVICE, "UsbDeviceManager::usbDeviceInterface_ set function error");
162         ReportUsbOperationFaultSysEvent("FUNCTION_CHANGED", ret, "DevIntfSetFunc is failed");
163         if (ret == HDF_ERR_NOT_SUPPORT) {
164             return UEC_SERVICE_FUNCTION_NOT_SUPPORT;
165         }
166         return ret;
167     }
168     UpdateFunctions(funcs);
169     return UEC_OK;
170 }
171 #else
SetCurrentFunctions(int32_t funcs)172 int32_t UsbDeviceManager::SetCurrentFunctions(int32_t funcs)
173 {
174     if (usbd_ == nullptr) {
175         USB_HILOGE(MODULE_USB_SERVICE, "UsbDeviceManager::usbd_ is nullptr");
176         return UEC_SERVICE_INVALID_VALUE;
177     }
178     int32_t lastFunc;
179     std::lock_guard<std::mutex> guard(functionMutex_);
180     if (usbd_->GetCurrentFunctions(lastFunc) != UEC_OK) {
181         USB_HILOGE(MODULE_USB_SERVICE, "UsbDeviceManager::get current functions fail");
182         ReportUsbOperationFaultSysEvent("FUNCTION_CHANGED", UEC_SERVICE_INVALID_VALUE, "UsbdfGetFunc is failed");
183         return UEC_SERVICE_INVALID_VALUE;
184     }
185     if (lastFunc == funcs) {
186         USB_HILOGI(MODULE_USB_SERVICE, "UsbDeviceManager::no change in functionality");
187         return UEC_OK;
188     }
189     int32_t ret = usbd_->SetCurrentFunctions(funcs);
190     if (ret != UEC_OK) {
191         USB_HILOGE(MODULE_USB_SERVICE, "UsbDeviceManager::usbd_ set function error");
192         ReportUsbOperationFaultSysEvent("FUNCTION_CHANGED", UEC_SERVICE_INVALID_VALUE, "UsbdSetFunc is failed");
193         if (ret == HDF_ERR_NOT_SUPPORT) {
194             return UEC_SERVICE_FUNCTION_NOT_SUPPORT;
195         }
196         return ret;
197     }
198     UpdateFunctions(funcs);
199     return UEC_OK;
200 }
201 #endif // USB_MANAGER_V2_0
202 
Init()203 int32_t UsbDeviceManager::Init()
204 {
205     std::shared_ptr<UsbFunctionSwitchWindow> window_ = UsbFunctionSwitchWindow::GetInstance();
206     if (window_ == nullptr) {
207         USB_HILOGE(MODULE_USB_SERVICE, "get usb function switch window failed");
208         return UEC_SERVICE_INNER_ERR;
209     }
210 
211     int32_t ret = window_->Init();
212     if (ret != UEC_OK) {
213         USB_HILOGE(MODULE_USB_SERVICE, "Init usb function switch window failed");
214     }
215     return ret;
216 }
217 
SetUsbd(const sptr<IUsbInterface> & usbd)218 int32_t UsbDeviceManager::SetUsbd(const sptr<IUsbInterface> &usbd)
219 {
220     if (usbd == nullptr) {
221         USB_HILOGE(MODULE_USB_SERVICE, "UsbDeviceManager usbd is nullptr");
222         return UEC_SERVICE_INVALID_VALUE;
223     }
224     if (usbd_ == nullptr) {
225         usbd_ = usbd;
226     } else {
227         USB_HILOGW(MODULE_USB_SERVICE, "%{public}s:usbd_ != nullptr", __func__);
228     }
229     return UEC_OK;
230 }
231 
IsSettableFunctions(int32_t funcs)232 bool UsbDeviceManager::IsSettableFunctions(int32_t funcs)
233 {
234     return static_cast<uint32_t>(funcs) == UsbSrvSupport::FUNCTION_NONE ||
235         ((~functionSettable_ & static_cast<uint32_t>(funcs)) == 0);
236 }
237 
ConvertFromString(std::string_view strFun)238 uint32_t UsbDeviceManager::ConvertFromString(std::string_view strFun)
239 {
240     if (strFun == UsbSrvSupport::FUNCTION_NAME_NONE) {
241         return UsbSrvSupport::FUNCTION_NONE;
242     }
243 
244     size_t len = strFun.length();
245     if (len == 0) {
246         return UEC_SERVICE_INVALID_VALUE;
247     }
248 
249     std::vector<std::string_view> vModeStr;
250     size_t pos = 0;
251     while (pos < len) {
252         size_t findPos = strFun.find(",", pos);
253         if (findPos == strFun.npos) {
254             vModeStr.push_back(strFun.substr(pos, len - pos));
255             break;
256         }
257         vModeStr.push_back(strFun.substr(pos, findPos - pos));
258         pos = findPos + 1;
259     }
260 
261     uint32_t ret = 0;
262     for (auto &&item : vModeStr) {
263         auto it = FUNCTION_MAPPING_N2C.find(item);
264         if (it != FUNCTION_MAPPING_N2C.end()) {
265             ret |= it->second;
266         } else {
267             USB_HILOGE(MODULE_USB_SERVICE, "UsbDeviceManager::ConvertFromString Invalid argument of usb function");
268             return UEC_SERVICE_INVALID_VALUE;
269         }
270     }
271 
272     return ret;
273 }
274 
ConvertToString(uint32_t function)275 std::string UsbDeviceManager::ConvertToString(uint32_t function)
276 {
277     std::string stream;
278     if (function <= UsbSrvSupport::FUNCTION_NONE || function > functionSettable_) {
279         return std::string {UsbSrvSupport::FUNCTION_NAME_NONE};
280     }
281     bool flag = false;
282     for (auto it = FUNCTION_MAPPING_N2C.begin(); it != FUNCTION_MAPPING_N2C.end(); ++it) {
283         if ((function & it->second) != 0) {
284             if (flag) {
285                 stream += ",";
286             }
287             stream += std::string {it->first};
288             flag = true;
289         }
290     }
291     USB_HILOGI(MODULE_USB_SERVICE, "UsbDeviceManager::ConvertToString success");
292     return stream;
293 }
294 
UpdateFunctions(int32_t func)295 void UsbDeviceManager::UpdateFunctions(int32_t func)
296 {
297     USB_HILOGI(MODULE_USB_SERVICE, "%{public}s: func %{public}d, currentFunctions_ %{public}d", __func__, func,
298         currentFunctions_);
299     if (func == currentFunctions_) {
300         return;
301     }
302     ReportFuncChangeSysEvent(currentFunctions_, func);
303     currentFunctions_ = func;
304     BroadcastFuncChange(connected_, currentFunctions_);
305     ProcessFunctionNotifier(connected_, func);
306 }
307 
GetCurrentFunctions()308 int32_t UsbDeviceManager::GetCurrentFunctions()
309 {
310     return currentFunctions_;
311 }
312 
ProcessStatus(int32_t status,bool & curConnect)313 void UsbDeviceManager::ProcessStatus(int32_t status, bool &curConnect)
314 {
315     switch (status) {
316         case ACT_UPDEVICE:
317             curConnect = true;
318             gadgetConnected_ = true;
319             break;
320         case ACT_DOWNDEVICE:
321             curConnect = false;
322             gadgetConnected_ = false;
323             break;
324         case ACT_ACCESSORYUP:
325         case ACT_ACCESSORYDOWN:
326         case ACT_ACCESSORYSEND: {
327             isDisableDialog_ = true;
328             USB_HILOGI(MODULE_USB_SERVICE, "disable dialog success");
329             ProcessFunctionSwitchWindow(false);
330             return;
331         }
332         default:
333             USB_HILOGE(MODULE_USB_SERVICE, "invalid status %{public}d", status);
334             return;
335     }
336 }
337 
338 #ifdef USB_MANAGER_V2_0
HandleEvent(int32_t status)339 void UsbDeviceManager::HandleEvent(int32_t status)
340 {
341     if (usbDeviceInterface_ == nullptr) {
342         return;
343     }
344     bool curConnect = false;
345     ProcessStatus(status, curConnect);
346     UsbTimerWrapper::GetInstance()->Unregister(delayDisconnTimerId_);
347     if (curConnect && (connected_ != curConnect)) {
348         auto task = [&]() {
349             connected_ = true;
350             GetCurrentFunctions(currentFunctions_);
351             ProcessFuncChange(connected_, currentFunctions_, isDisableDialog_);
352         };
353         delayDisconnTimerId_ = UsbTimerWrapper::GetInstance()->Register(task, DELAY_CONNECT_INTERVAL, true);
354     } else if (!curConnect && (connected_ != curConnect)) {
355         auto task = [&]() {
356             USB_HILOGI(MODULE_USB_SERVICE, "execute disconnect task:%{public}d", currentFunctions_);
357             connected_ = false;
358             isDisableDialog_ = false;
359             if ((static_cast<uint32_t>(currentFunctions_) & USB_FUNCTION_MTP) != 0 ||
360                 (static_cast<uint32_t>(currentFunctions_) & USB_FUNCTION_PTP) != 0) {
361                 currentFunctions_ = static_cast<uint32_t>(currentFunctions_) &
362                     (~USB_FUNCTION_MTP) & (~USB_FUNCTION_PTP);
363                 USB_HILOGI(MODULE_USB_SERVICE, "usb function reset %{public}d", currentFunctions_);
364                 currentFunctions_ = currentFunctions_ == 0 ? USB_FUNCTION_STORAGE : currentFunctions_;
365                 usbDeviceInterface_->SetCurrentFunctions(currentFunctions_);
366             } else if ((static_cast<uint32_t>(currentFunctions_) & USB_FUNCTION_DEVMODE_AUTH) != 0) {
367                 currentFunctions_ = USB_FUNCTION_STORAGE;
368                 usbDeviceInterface_->SetCurrentFunctions(currentFunctions_);
369             }
370             ProcessFuncChange(connected_, currentFunctions_);
371             return;
372         };
373         delayDisconnTimerId_ = UsbTimerWrapper::GetInstance()->Register(task, DELAY_DISCONN_INTERVAL, true);
374     } else {
375         USB_HILOGI(MODULE_USB_SERVICE, "else info cur status %{public}d, bconnected: %{public}d", status, connected_);
376     }
377 }
378 #else
HandleEvent(int32_t status)379 void UsbDeviceManager::HandleEvent(int32_t status)
380 {
381     if (usbd_ == nullptr) {
382         return;
383     }
384     bool curConnect = false;
385     ProcessStatus(status, curConnect);
386     UsbTimerWrapper::GetInstance()->Unregister(delayDisconnTimerId_);
387     if (curConnect && (connected_ != curConnect)) {
388         auto task = [&]() {
389             connected_ = true;
390             GetCurrentFunctions(currentFunctions_);
391             ProcessFuncChange(connected_, currentFunctions_, isDisableDialog_);
392         };
393         delayDisconnTimerId_ = UsbTimerWrapper::GetInstance()->Register(task, DELAY_CONNECT_INTERVAL, true);
394     } else if (!curConnect && (connected_ != curConnect)) {
395         auto task = [&]() {
396             USB_HILOGI(MODULE_USB_SERVICE, "execute disconnect task:%{public}d", currentFunctions_);
397             connected_ = false;
398             isDisableDialog_ = false;
399             if ((static_cast<uint32_t>(currentFunctions_) & USB_FUNCTION_MTP) != 0 ||
400                 (static_cast<uint32_t>(currentFunctions_) & USB_FUNCTION_PTP) != 0) {
401                 currentFunctions_ = static_cast<uint32_t>(currentFunctions_) &
402                     (~USB_FUNCTION_MTP) & (~USB_FUNCTION_PTP);
403                 USB_HILOGI(MODULE_USB_SERVICE, "usb function reset %{public}d", currentFunctions_);
404                 currentFunctions_ = currentFunctions_ == 0 ? USB_FUNCTION_STORAGE : currentFunctions_;
405                 usbd_->SetCurrentFunctions(currentFunctions_);
406             } else if ((static_cast<uint32_t>(currentFunctions_) & USB_FUNCTION_DEVMODE_AUTH) != 0) {
407                 currentFunctions_ = USB_FUNCTION_STORAGE;
408                 usbd_->SetCurrentFunctions(currentFunctions_);
409             }
410             ProcessFuncChange(connected_, currentFunctions_);
411             return;
412         };
413         delayDisconnTimerId_ = UsbTimerWrapper::GetInstance()->Register(task, DELAY_DISCONN_INTERVAL, true);
414     } else {
415         USB_HILOGI(MODULE_USB_SERVICE, "else info cur status %{public}d, bconnected: %{public}d", status, connected_);
416     }
417 }
418 #endif // USB_MANAGER_V2_0
419 
UserChangeProcess()420 int32_t UsbDeviceManager::UserChangeProcess()
421 {
422     USB_HILOGI(MODULE_USB_SERVICE, "%{public}s: in", __func__);
423     int32_t ret = HDF_FAILURE;
424     if ((static_cast<uint32_t>(currentFunctions_) & USB_FUNCTION_MTP) != 0 ||
425         (static_cast<uint32_t>(currentFunctions_) & USB_FUNCTION_PTP) != 0) {
426         uint32_t func = static_cast<uint32_t>(currentFunctions_) & (~USB_FUNCTION_MTP) & (~USB_FUNCTION_PTP);
427         func = func == 0 ? USB_FUNCTION_STORAGE : func;
428         USB_HILOGI(MODULE_USB_SERVICE, "usb function reset %{public}d", func);
429         int32_t funcs = static_cast<int32_t>(func);
430 #ifdef USB_MANAGER_V2_0
431         ret = usbDeviceInterface_->SetCurrentFunctions(funcs);
432 #else
433         ret = usbd_->SetCurrentFunctions(funcs);
434 #endif // USB_MANAGER_V2_0
435         if (ret == ERR_OK && funcs != currentFunctions_) {
436             currentFunctions_ = funcs;
437             ReportFuncChangeSysEvent(currentFunctions_, funcs);
438             BroadcastFuncChange(connected_, currentFunctions_);
439         }
440     }
441     ProcessFunctionNotifier(connected_, currentFunctions_);
442     return ret;
443 }
444 
BroadcastFuncChange(bool connected,int32_t currentFunc)445 void UsbDeviceManager::BroadcastFuncChange(bool connected, int32_t currentFunc)
446 {
447     USB_HILOGI(MODULE_USB_SERVICE, "Current Connect %{public}d,bconnected: %{public}d", connected, currentFunc);
448     CommonEventManager::RemoveStickyCommonEvent(CommonEventSupport::COMMON_EVENT_USB_STATE);
449     Want want;
450     want.SetAction(CommonEventSupport::COMMON_EVENT_USB_STATE);
451 
452     want.SetParam(std::string {UsbSrvSupport::CONNECTED}, connected);
453     uint32_t remainderFunc = static_cast<uint32_t>(currentFunc);
454     // start from bit 1
455     uint32_t bit = 1;
456     while (remainderFunc != 0) {
457         if (remainderFunc & bit) {
458             want.SetParam(ConvertToString(bit), true);
459             // set current bit to zero
460             remainderFunc &= ~bit;
461         }
462         // 1 means to next bit
463         bit = bit << 1;
464     }
465     CommonEventData data(want);
466     CommonEventPublishInfo publishInfo;
467     publishInfo.SetSticky(true);
468     USB_HILOGI(MODULE_SERVICE, "send COMMON_EVENT_USB_STATE broadcast connected:%{public}d, "
469         "currentFunctions:%{public}d", connected, currentFunc);
470     CommonEventManager::PublishCommonEvent(data, publishInfo);
471     ReportDevicePlugSysEvent(currentFunc, connected);
472 }
473 
ProcessFuncChange(bool connected,int32_t currentFunc,bool isDisableDialog)474 void UsbDeviceManager::ProcessFuncChange(bool connected, int32_t currentFunc, bool isDisableDialog)
475 {
476     USB_HILOGI(MODULE_USB_SERVICE, "%{public}s: connected %{public}d, currentFunc %{public}d, isDisableDialog "
477                                    "%{public}d", __func__, connected, currentFunc, isDisableDialog);
478     BroadcastFuncChange(connected, currentFunc);
479     if (!isDisableDialog) {
480         ProcessFunctionSwitchWindow(connected);
481     }
482     ProcessFunctionNotifier(connected, currentFunc);
483 }
484 
SetChargeFlag(bool isReverseCharge)485 void UsbDeviceManager::SetChargeFlag(bool isReverseCharge)
486 {
487     isReverseCharge_ = isReverseCharge;
488 }
489 
ProcessFunctionNotifier(bool connected,int32_t func)490 void UsbDeviceManager::ProcessFunctionNotifier(bool connected, int32_t func)
491 {
492     USB_HILOGI(MODULE_USB_SERVICE, "%{public}s: connected %{public}d, func %{public}d, hasHdcNotifier_ %{public}d",
493                __func__, connected, func, hasHdcNotifier_);
494     uint32_t func_uint = static_cast<uint32_t>(func);
495     if (connected) {
496         if (func_uint & USB_FUNCTION_MTP) {
497             UsbConnectionNotifier::GetInstance()->SendNotification(USB_FUNC_MTP);
498         } else if (func_uint & USB_FUNCTION_PTP) {
499             UsbConnectionNotifier::GetInstance()->SendNotification(USB_FUNC_PTP);
500         } else if (isReverseCharge_) {
501             UsbConnectionNotifier::GetInstance()->SendNotification(USB_FUNC_REVERSE_CHARGE);
502         } else {
503             UsbConnectionNotifier::GetInstance()->SendNotification(USB_FUNC_CHARGE);
504         }
505 
506         if ((func_uint & USB_FUNCTION_HDC) && !hasHdcNotifier_) {
507             UsbConnectionNotifier::GetInstance()->SendHdcNotification();
508             hasHdcNotifier_ = true;
509         }
510         if (!(func_uint & USB_FUNCTION_HDC) && hasHdcNotifier_) {
511             UsbConnectionNotifier::GetInstance()->CancelHdcNotification();
512             hasHdcNotifier_ = false;
513         }
514     } else {
515         UsbConnectionNotifier::GetInstance()->CancelNotification();
516         if (hasHdcNotifier_) {
517             UsbConnectionNotifier::GetInstance()->CancelHdcNotification();
518             hasHdcNotifier_ = false;
519         }
520     }
521 }
522 
ProcessFunctionSwitchWindow(bool connected)523 void UsbDeviceManager::ProcessFunctionSwitchWindow(bool connected)
524 {
525     USB_HILOGI(MODULE_USB_SERVICE, "%{public}s: connected %{public}d", __func__, connected);
526     std::shared_ptr<UsbFunctionSwitchWindow> window_ = UsbFunctionSwitchWindow::GetInstance();
527     if (window_ == nullptr) {
528         USB_HILOGE(MODULE_USB_SERVICE, "show window: get usb function switch window failed");
529         return;
530     }
531 
532     if (connected) {
533         USB_HILOGD(MODULE_USB_SERVICE, "start pop up usb service switch window");
534         if (!window_->PopUpFunctionSwitchWindow()) {
535             USB_HILOGE(MODULE_USB_SERVICE, "start pop up usb service switch window failed");
536         }
537     } else {
538         USB_HILOGD(MODULE_USB_SERVICE, "start dismiss usb service switch window");
539         if (!window_->DismissFunctionSwitchWindow()) {
540             USB_HILOGE(MODULE_USB_SERVICE, "start dismiss usb service switch window failed");
541         }
542     }
543 }
544 
GetDumpHelp(int32_t fd)545 void UsbDeviceManager::GetDumpHelp(int32_t fd)
546 {
547     dprintf(fd, "========= dump the all device function =========\n");
548     dprintf(fd, "usb_device -a:    Query all function\n");
549     dprintf(fd, "usb_device -f Q:  Query Current function\n");
550     dprintf(fd, "------------------------------------------------\n");
551 }
552 
DumpGetSupportFunc(int32_t fd)553 void UsbDeviceManager::DumpGetSupportFunc(int32_t fd)
554 {
555     dprintf(fd, "Usb Device function list info:\n");
556     dprintf(fd, "current function: %s\n", ConvertToString(currentFunctions_).c_str());
557     dprintf(fd, "supported functions list: %s\n", ConvertToString(functionSettable_).c_str());
558 }
559 
StringToInteger(const std::string & str,int32_t & result)560 bool StringToInteger(const std::string &str, int32_t &result)
561 {
562     char *endptr = nullptr;
563     errno = 0;
564     int64_t number = std::strtol(str.c_str(), &endptr, DECIMAL_BASE);
565     if (errno != 0 || number < INT32_MIN || number > INT32_MAX) {
566         USB_HILOGE(MODULE_USB_SERVICE, "number is out of range");
567         return false;
568     }
569     if (endptr == nullptr || endptr == str.c_str() || *endptr != '\0') {
570         USB_HILOGE(MODULE_USB_SERVICE, "conversion failed");
571         return false;
572     }
573     result = static_cast<int32_t>(number);
574     return true;
575 }
576 
577 #ifdef USB_MANAGER_V2_0
DumpSetFunc(int32_t fd,const std::string & args)578 void UsbDeviceManager::DumpSetFunc(int32_t fd, const std::string &args)
579 {
580     int32_t currentFunction;
581     int32_t ret;
582     if (usbDeviceInterface_ == nullptr) {
583         USB_HILOGE(MODULE_USB_SERVICE, "UsbDeviceManager::DumpSetFunc usbDeviceInterface_ is nullptr");
584         return;
585     }
586     if (args.compare("Q") == 0) {
587         ret = usbDeviceInterface_->GetCurrentFunctions(currentFunction);
588         if (ret != UEC_OK) {
589             dprintf(fd, "GetCurrentFunctions failed: %d\n", ret);
590             return;
591         }
592         dprintf(fd, "current function: %s\n", ConvertToString(currentFunction).c_str());
593         return;
594     }
595     dprintf(fd, "Invalid input, please enter a valid argument\n");
596     GetDumpHelp(fd);
597 }
598 #else
DumpSetFunc(int32_t fd,const std::string & args)599 void UsbDeviceManager::DumpSetFunc(int32_t fd, const std::string &args)
600 {
601     int32_t currentFunction;
602     int32_t ret;
603     if (usbd_ == nullptr) {
604         USB_HILOGE(MODULE_USB_SERVICE, "UsbDeviceManager::DumpSetFunc usbd_ is nullptr");
605         return;
606     }
607     if (args.compare("Q") == 0) {
608         ret = usbd_->GetCurrentFunctions(currentFunction);
609         if (ret != UEC_OK) {
610             dprintf(fd, "GetCurrentFunctions failed: %d\n", ret);
611             return;
612         }
613         dprintf(fd, "current function: %s\n", ConvertToString(currentFunction).c_str());
614         return;
615     }
616     dprintf(fd, "Invalid input, please enter a valid argument\n");
617     GetDumpHelp(fd);
618 }
619 #endif // USB_MANAGER_V2_0
620 
Dump(int32_t fd,const std::vector<std::string> & args)621 void UsbDeviceManager::Dump(int32_t fd, const std::vector<std::string> &args)
622 {
623     if (args.size() < PARAM_COUNT_TWO || args.size() > PARAM_COUNT_THR) {
624         GetDumpHelp(fd);
625         return;
626     }
627 
628     if (args[CMD_INDEX] == "-a" && args.size() == PARAM_COUNT_TWO) {
629         DumpGetSupportFunc(fd);
630     } else if (args[CMD_INDEX] == "-f" && args.size() == PARAM_COUNT_THR) {
631         DumpSetFunc(fd, args[PARAM_INDEX]);
632     } else {
633         dprintf(fd, "func param error, please enter again\n");
634         GetDumpHelp(fd);
635     }
636 }
637 
ReportUsbOperationFaultSysEvent(const std::string & operationType,int32_t failReason,const std::string & failDescription)638 void UsbDeviceManager::ReportUsbOperationFaultSysEvent(const std::string &operationType, int32_t failReason,
639     const std::string &failDescription)
640 {
641     HiSysEventWrite(HiSysEvent::Domain::USB, "OPERATION_FAULT",
642         HiSysEvent::EventType::FAULT, "OPERATION_TYPE_NAME", operationType,
643         "FAIL_REASON", failReason,
644         "FAIL_DESCRIPTION", failDescription);
645 }
646 
ReportFuncChangeSysEvent(int32_t currentFunctions,int32_t updateFunctions)647 void UsbDeviceManager::ReportFuncChangeSysEvent(int32_t currentFunctions, int32_t updateFunctions)
648 {
649     USB_HILOGI(MODULE_USB_SERVICE, "Device function Indicates the switch point information:");
650     HiSysEventWrite(HiSysEvent::Domain::USB, "FUNCTION_CHANGED",
651         HiSysEvent::EventType::BEHAVIOR, "CURRENT_FUNCTION",
652         currentFunctions_, "UPDATE_FUNCTION", updateFunctions);
653 }
654 
ReportDevicePlugSysEvent(int32_t currentFunctions,bool connected)655 void UsbDeviceManager::ReportDevicePlugSysEvent(int32_t currentFunctions, bool connected)
656 {
657     USB_HILOGI(MODULE_USB_SERVICE, "Device mode Indicates the insertion and removal information:");
658     HiSysEventWrite(HiSysEvent::Domain::USB, "PLUG_IN_OUT_DEVICE_MODE",
659         HiSysEvent::EventType::BEHAVIOR, "CURRENT_FUNCTIONS",
660         currentFunctions, "CONNECTED", connected);
661 }
IsGadgetConnected(void)662 bool UsbDeviceManager::IsGadgetConnected(void)
663 {
664     return gadgetConnected_;
665 }
666 } // namespace USB
667 } // namespace OHOS
668