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