fix(usb):comment event attach device information

Signed-off-by: wu-chengwen <wuchengwen4@huawei.com>
This commit is contained in:
wu-chengwen
2022-06-06 20:36:55 +08:00
parent c0a5d519c9
commit 70f6031007
29 changed files with 1004 additions and 314 deletions
+29
View File
@@ -0,0 +1,29 @@
BasedOnStyle: Webkit
ColumnLimit: 120
PointerAlignment: Right
AlignAfterOpenBracket: DontAlign
AlignTrailingComments: true
AlignConsecutiveMacros: Consecutive
IndentCaseLabels: true
BreakBeforeBinaryOperators: None
SpaceBeforeParens: ControlStatementsExceptControlMacros
SpacesInCStyleCastParentheses: false
AlignEscapedNewlines: Left
NamespaceIndentation: None
FixNamespaceComments: true
ConstructorInitializerAllOnOneLineOrOnePerLine: true
BreakConstructorInitializers: AfterColon
AlignArrayOfStructures: Left
AllowShortFunctionsOnASingleLine: Empty
AllowShortLambdasOnASingleLine: Empty
AlwaysBreakTemplateDeclarations: true
SpaceInEmptyBlock: false
LambdaBodyIndentation: Signature
BreakBeforeTernaryOperators: false
Cpp11BracedListStyle: true
SpaceAroundPointerQualifiers: Both
ForEachMacros:
- 'DLIST_FOR_EACH_ENTRY'
- 'DLIST_FOR_EACH_ENTRY_REVERSE'
- 'DLIST_FOR_EACH_ENTRY_SAFE'
+66 -41
View File
@@ -1,23 +1,26 @@
# USB Manager<a name="EN-US_TOPIC_0000001124094823"></a>
# USB Manager `<a name="EN-US_TOPIC_0000001124094823"></a>`
- [Introduction](#section11660541593)
- [Directory Structure](#section19472752217)
- [Available APIs](#section19472752218)
- [Development Example](#section19472752219)
- [Repositories Involved](#section63151229062)
- [Introduction](#section11660541593)
- [Directory Structure](#section19472752217)
- [Available APIs](#section19472752218)
- [Development Example](#section19472752219)
- [Repositories Involved](#section63151229062)
## Introduction`<a name="section11660541593"></a>`
## Introduction<a name="section11660541593"></a>
The following figure shows the USB service architecture.
**Figure 1** USB service architecture<a name="fig15658513184019"></a>
**Figure 1** USB service architecture`<a name="fig15658513184019"></a>`
![](figures/usb-manager-architecture.png "USB_service_architecture")
The architecture logically consists of three layers:
1. USB API: provides USB APIs that implement various basic functions, for example, query of the USB device list, USB device plug notification, USB host and device mode switching, bulk transfer, control transfer, right management, and function switching in device mode.
2. USB Service: interacts with the HAL layer to receive, parse, and distribute data, manages foreground and background policies, and performs USB device management and right control.
3. USB HAL: provides driver capability APIs that can be directly called in user mode. The APIs are classified into the DDK initialization class, interface operation class, and request operation class by function. They can be used to perform DDK initialization, bind/release and open/close an interface, allocate/release a request, and implement isochronous or non-isochronous transfer. The USB HAL code is stored in [drivers\_peripheral](https://gitee.com/openharmony/drivers_peripheral/blob/master/README.md).
## Directory Structure<a name="section19472752217"></a>
## Directory Structure`<a name="section19472752217"></a>`
```
base/usb/usb_manager
├── interfaces # APIs
@@ -30,58 +33,70 @@ base/usb/usb_manager
└── test # Test cases
└── utils # Utilities
```
## Available APIs<a name="section19472752218"></a>
## Available APIs`<a name="section19472752218"></a>`
### [External APIs](https://gitee.com/openharmony/usb_manager/blob/master/interfaces/kits/js/@ohos.usb.d.ts)
### Internal APIs
#### Host APIs
| **API**| **Description**|
| --- | --- |
| int32_t OpenDevice(const UsbDevice &device, USBDevicePipe &pip); | Opens a USB device to set up a connection.|
| bool Close(const USBDevicePipe &pip); | Closes a USB device to release all system resources related to the device.|
| int32_t GetDevices(std::vector &deviceList); | Obtains the USB device list.|
| int32_t SetConfiguration(USBDevicePipe &pip, const USBConfig &config); | Sets the current configuration of the USB device.|
| int32_t ClaimInterface(USBDevicePipe &pip, const UsbInterface &interface, bool force); | Claims a USB interface exclusively. This must be done before data transfer.|
| int32_t ReleaseInterface(USBDevicePipe &pip, const UsbInterface &interface); | Releases a USB interface. This is usually done after data transfer.|
| int32_t SetInterface(USBDevicePipe &pipe, const UsbInterface &interface); | Sets the alternate settings for the specified USB interface. This allows you to switch between two interfaces with the same ID but different alternate settings.|
| int32_t BulkTransfer(USBDevicePipe &pip, const USBEndpoint &endpoint, std::vector<uint8_t> &vdata, int32_t timeout); | Writes data on a specified endpoint during bulk transfer.|
| int32_t ControlTransfer(USBDevicePipe &pip, const UsbCtrlTransfer &ctrl, std::vector<uint8_t> &vdata); | Performs control transfer for endpoint 0 of the device. The data transfer direction is determined by the request type. If the result of **requestType & USB_ENDPOINT_DIR_MASK** is **USB_DIR_OUT**, the endpoint is in the data writing direction; if the result is **USB_DIR_IN**, the endpoint is in the data reading direction.|
| int32_t RequestInitialize(UsbRequest &request); | Initializes a request.|
| int32_t RequestQueue(UsbRequest &request); | Sends or receives requests for isochronous transfer on a specified endpoint. The data transfer direction is determined by the endpoint direction.|
| int32_t PipeRequestWait(USBDevicePipe &pip, int64_t timeout, UsbRequest &req); | Waits for the operation result of the isochronous transfer request in <b>RequestQueue</b>.|
| int32_t RequestAbort(UsbRequest &request); | Cancels the data transfer requests to be processed.|
| int32_t RequestFree(UsbRequest &request); | Requests for releasing data.|
| bool HasRight(std::string deviceName); | Checks whether the application has permission to access the USB device.|
| int32_t RequestRight(std::string deviceName); | Requests for permission to access the USB device.|
| **API** | **Description** |
| -------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| int32_t OpenDevice(const UsbDevice &device, USBDevicePipe &pip); | Opens a USB device to set up a connection. |
| bool Close(const USBDevicePipe &pip); | Closes a USB device to release all system resources related to the device. |
| int32_t GetDevices(std::vector &deviceList); | Obtains the USB device list. |
| int32_t SetConfiguration(USBDevicePipe &pip, const USBConfig &config); | Sets the current configuration of the USB device. |
| int32_t ClaimInterface(USBDevicePipe &pip, const UsbInterface &interface, bool force); | Claims a USB interface exclusively. This must be done before data transfer. |
| int32_t ReleaseInterface(USBDevicePipe &pip, const UsbInterface &interface); | Releases a USB interface. This is usually done after data transfer. |
| int32_t SetInterface(USBDevicePipe &pipe, const UsbInterface &interface); | Sets the alternate settings for the specified USB interface. This allows you to switch between two interfaces with the same ID but different alternate settings. |
| int32_t BulkTransfer(USBDevicePipe &pip, const USBEndpoint &endpoint, std::vector<uint8_t> &vdata, int32_t timeout); | Writes data on a specified endpoint during bulk transfer. |
| int32_t ControlTransfer(USBDevicePipe &pip, const UsbCtrlTransfer &ctrl, std::vector<uint8_t> &vdata); | Performs control transfer for endpoint 0 of the device. The data transfer direction is determined by the request type. If the result of**requestType & USB_ENDPOINT_DIR_MASK** is **USB_DIR_OUT**, the endpoint is in the data writing direction; if the result is **USB_DIR_IN**, the endpoint is in the data reading direction. |
| int32_t RequestInitialize(UsbRequest &request); | Initializes a request. |
| int32_t RequestQueue(UsbRequest &request); | Sends or receives requests for isochronous transfer on a specified endpoint. The data transfer direction is determined by the endpoint direction. |
| int32_t PipeRequestWait(USBDevicePipe &pip, int64_t timeout, UsbRequest &req); | Waits for the operation result of the isochronous transfer request in`<b>`RequestQueue`</b>`. |
| int32_t RequestAbort(UsbRequest &request); | Cancels the data transfer requests to be processed. |
| int32_t RequestFree(UsbRequest &request); | Requests for releasing data. |
| bool HasRight(std::string deviceName); | Checks whether the application has permission to access the USB device. |
| int32_t RequestRight(std::string deviceName); | Requests for permission to access the USB device. |
#### Device APIs
| **API**| **Description**|
| --- | --- |
| int32_t GetCurrentFunctions(int32_t &funcs); | Obtains the list of functions (represented by bit field) supported by the current device.|
| int32_t SetCurrentFunctions(int32_t funcs); | Sets the list of functions (represented by bit field) supported by the current device.|
| int32_t UsbFunctionsFromString(std::string funcs); | Converts the string descriptor of a given USB function list to a numeric mask combination.|
| std::string UsbFunctionsToString(int32_t funcs); | Converts the numeric mask combination of a given USB function list to a string descriptor.|
| **API** | **Description** |
| -------------------------------------------------- | ------------------------------------------------------------------------------------------ |
| int32_t GetCurrentFunctions(int32_t &funcs); | Obtains the list of functions (represented by bit field) supported by the current device. |
| int32_t SetCurrentFunctions(int32_t funcs); | Sets the list of functions (represented by bit field) supported by the current device. |
| int32_t UsbFunctionsFromString(std::string funcs); | Converts the string descriptor of a given USB function list to a numeric mask combination. |
| std::string UsbFunctionsToString(int32_t funcs); | Converts the numeric mask combination of a given USB function list to a string descriptor. |
#### Port APIs
| **API**| **Description**|
| --- | --- |
| int32_t GetPorts(std::vector &usbPorts); | Obtains the port list.|
| int32_t SetPortRole(int32_t portId, int32_t powerRole, int32_t dataRole); | Sets the port role.|
| int32_t GetSupportedModes(int32_t portId, int32_t &supportedModes); | Obtains the mask combination for the supported mode list of a given port.|
## Development Example<a name="section19472752219"></a>
| **API** | **Description** |
| ------------------------------------------------------------------------- | ------------------------------------------------------------------------- |
| int32_t GetPorts(std::vector &usbPorts); | Obtains the port list. |
| int32_t SetPortRole(int32_t portId, int32_t powerRole, int32_t dataRole); | Sets the port role. |
| int32_t GetSupportedModes(int32_t portId, int32_t &supportedModes); | Obtains the mask combination for the supported mode list of a given port. |
## Development Example`<a name="section19472752219"></a>`
The following provides some examples on how to use major APIs. For detailed service code, see [js_unittest](test/native/js_unittest).
#### Host Development
In this example, the USB device serves as the host and connects to the device to implement data transfer.
1. Obtain the USB device list.
```JS
// Import the USB API package.
import usb from '@ohos.usb';
// Obtain the USB device list.
var deviceList = usb.getDevices();
```
2. Obtain the device operation permissions.
```JS
// device name
var deviceName = deviceList[0].name;
@@ -92,14 +107,18 @@ usb.requestRight(deviceName).then(hasRight => {
console.info("usb device request right failed : " + error);
});
```
3. Open the USB device.
```JS
// Open the USB device, and obtain the device pipe for data transfer.
var pipe = usb.connectDevice(deviceList[0]);
// Claim the USB interface.
usb.claimInterface(pipe, interface, true); // Among the input arguments, interface refers to the one to be operated on the USB device.
```
4. Perform data transfer.
```JS
// Read data. Select the corresponding RX endpoint (endpoint.direction == 0x80) from deviceList for data transfer. The data data to be transferred is encapsulated in dataUint8Array.
usb.bulkTransfer(pipe, inEndpoint, dataUint8Array, 15000).then(dataLength => {
@@ -124,14 +143,20 @@ usb.bulkTransfer(this.pip, this.outEndpoint, dataUint8Array, 15000).then(dataLen
console.info("usb writeData error : " + JSON.stringify(error));
});
```
5. Release the USB interface, and close the USB device.
```JS
usb.releaseInterface(pipe, interface);
usb.closePipe(pipe);
```
#### Device Development
In this example, the USB device is used as the device to set the ACM, ECM, and HDC functions.
1. Set the USB functions.
```JS
usb.setCurrentFunctions(funType).then(data => {
console.info("usb setCurrentFunctions : " + data);
@@ -140,7 +165,7 @@ usb.setCurrentFunctions(funType).then(data => {
});
```
## Repositories Involved<a name="section63151229062"></a>
## Repositories Involved`<a name="section63151229062"></a>`
[Drive Subsystem](https://gitee.com/openharmony/docs/blob/master/en/readme/driver-subsystem.md)
+2 -1
View File
@@ -29,7 +29,8 @@
"libhilog",
"ipc_core",
"system_ability_fwk",
"samgr_proxy"
"samgr_proxy",
"jsoncpp"
],
"third_party": []
},
+5 -2
View File
@@ -14,7 +14,10 @@
import("//base/usb/usb_manager/usbmgr.gni")
config("usbsrv_private_config") {
include_dirs = [ "${usb_manager_path}/services/zidl/include" ]
include_dirs = [
"${usb_manager_path}/services/zidl/include",
"//third_party/jsoncpp/include/json",
]
}
config("usbsrv_public_config") {
@@ -38,7 +41,7 @@ ohos_shared_library("usbsrv_client") {
public_configs = [ ":usbsrv_public_config" ]
deps = []
deps = [ "//third_party/jsoncpp:jsoncpp" ]
external_deps = [
"eventhandler:libeventhandler",
@@ -37,6 +37,20 @@ public:
this->name_ = name;
this->interfaces_ = interfaces;
}
explicit USBConfig(const Json::Value &config)
{
id_ = config["id"].asInt();
attributes_ = config["attributes"].asInt();
maxPower_ = config["maxPower"].asInt();
name_ = config["name"].asString();
Json::Value interfaces = config["interfaces"];
for (uint32_t idx = 0; idx < interfaces.size(); ++idx) {
interfaces_.emplace_back(interfaces[idx]);
}
}
USBConfig() {}
~USBConfig() {}
@@ -142,6 +156,25 @@ public:
return this->iConfiguration_;
}
Json::Value ToJson() const
{
Json::Value config;
config["id"] = id_;
config["attributes"] = attributes_;
config["maxPower"] = maxPower_;
config["name"] = name_;
config["isRemoteWakeup"] = IsRemoteWakeup();
config["isSelfPowered"] = IsSelfPowered();
Json::Value interfaces;
for (auto &intf : interfaces_) {
interfaces.append(intf.ToJson());
}
config["interfaces"] = interfaces;
return config;
}
private:
int32_t id_ = INVALID_USB_INT_VALUE;
int32_t attributes_ = INVALID_USB_INT_VALUE;
@@ -46,6 +46,27 @@ public:
this->configs_ = configs;
}
explicit UsbDevice(const Json::Value &device)
{
busNum_ = device["busNum"].asUInt();
devAddr_ = device["devAddress"].asUInt();
serial_ = device["serial"].asString();
name_ = device["name"].asString();
manufacturerName_ = device["manufacturerName"].asString();
productName_ = device["productName"].asString();
version_ = device["version"].asString();
vendorId_ = device["vendorId"].asInt();
productId_ = device["productId"].asInt();
klass_ = device["clazz"].asInt();
subClass_ = device["subClass"].asInt();
protocol_ = device["protocol"].asInt();
Json::Value configs = device["configs"];
for (uint32_t idx = 0; idx < configs.size(); ++idx) {
configs_.emplace_back(configs[idx]);
}
}
UsbDevice() {}
~UsbDevice() {}
@@ -289,6 +310,31 @@ public:
return this->bcdDevice_;
}
Json::Value ToJson() const
{
Json::Value device;
device["busNum"] = busNum_;
device["devAddress"] = devAddr_;
device["serial"] = serial_;
device["name"] = name_;
device["manufacturerName"] = manufacturerName_;
device["productName"] = productName_;
device["version"] = version_;
device["vendorId"] = vendorId_;
device["productId"] = productId_;
device["clazz"] = klass_;
device["subClass"] = subClass_;
device["protocol"] = protocol_;
Json::Value configs;
for (auto &cfg : configs_) {
configs.append(cfg.ToJson());
}
device["configs"] = configs;
return device;
}
private:
std::string name_;
std::string manufacturerName_;
@@ -20,6 +20,7 @@
#include <sstream>
#include <string>
#include "usb_common.h"
#include "json.h"
namespace OHOS {
namespace USB {
@@ -32,6 +33,16 @@ public:
this->interval_ = interval;
this->maxPacketSize_ = maxPacketSize;
}
explicit USBEndpoint(const Json::Value &endpoint)
{
address_ = endpoint["address"].asInt();
attributes_ = endpoint["attributes"].asInt();
interval_ = endpoint["interval"].asInt();
maxPacketSize_ = endpoint["maxPacketSize"].asInt();
interfaceId_ = endpoint["interfaceId"].asUInt();
}
USBEndpoint() {}
~USBEndpoint() {}
@@ -124,6 +135,21 @@ public:
return interfaceId_;
}
Json::Value ToJson() const
{
Json::Value endpoint;
endpoint["address"] = address_;
endpoint["attributes"] = attributes_;
endpoint["interval"] = interval_;
endpoint["maxPacketSize"] = maxPacketSize_;
endpoint["direction"] = GetDirection();
endpoint["number"] = GetEndpointNumber();
endpoint["type"] = GetType();
endpoint["interfaceId"] = interfaceId_;
return endpoint;
}
private:
int32_t address_ = INVALID_USB_INT_VALUE;
int32_t attributes_ = INVALID_USB_INT_VALUE;
@@ -43,6 +43,21 @@ public:
this->endpoints_ = endpoints;
}
explicit UsbInterface(const Json::Value &interface)
{
id_ = interface["id"].asInt();
protocol_ = interface["protocol"].asInt();
klass_ = interface["clazz"].asInt();
subClass_ = interface["subClass"].asInt();
alternateSetting_ = interface["alternateSetting"].asInt();
name_ = interface["name"].asString();
Json::Value endpoints = interface["endpoints"];
for (uint32_t idx = 0; idx < endpoints.size(); ++idx) {
endpoints_.emplace_back(endpoints[idx]);
}
}
UsbInterface() {}
const std::string &GetName() const
@@ -161,6 +176,25 @@ public:
return this->iInterface_;
}
Json::Value ToJson() const
{
Json::Value interface;
interface["id"] = id_;
interface["protocol"] = protocol_;
interface["clazz"] = klass_;
interface["subClass"] = subClass_;
interface["alternateSetting"] = alternateSetting_;
interface["name"] = name_;
Json::Value endpoints;
for (const auto &ep : endpoints_) {
endpoints.append(ep.ToJson());
}
interface["endpoints"] = endpoints;
return interface;
}
private:
int32_t id_ = INT32_MAX;
int32_t protocol_ = INT32_MAX;
@@ -21,6 +21,7 @@
#include <memory>
#include <mutex>
#include <singleton.h>
#include "iremote_object.h"
#include "iusb_srv.h"
#include "usb_device.h"
@@ -55,8 +56,8 @@ public:
std::string UsbFunctionsToString(int32_t funcs);
int32_t ClaimInterface(USBDevicePipe &pip, const UsbInterface &interface, bool force);
int32_t ReleaseInterface(USBDevicePipe &pip, const UsbInterface &interface);
int32_t BulkTransfer(USBDevicePipe &pip, const USBEndpoint &endpoint, std::vector<uint8_t> &bufferData,
int32_t timeOut);
int32_t BulkTransfer(
USBDevicePipe &pip, const USBEndpoint &endpoint, std::vector<uint8_t> &bufferData, int32_t timeOut);
int32_t ControlTransfer(USBDevicePipe &pip, const UsbCtrlTransfer &ctrl, std::vector<uint8_t> &bufferData);
int32_t SetConfiguration(USBDevicePipe &pip, const USBConfig &config);
int32_t SetInterface(USBDevicePipe &pipe, const UsbInterface &interface);
@@ -0,0 +1,62 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef USB_SRV_SUPPORT_H
#include <string>
namespace OHOS {
namespace USB {
struct UsbSrvSupport {
static constexpr std::string_view CONNECTED {"connected"};
static constexpr std::string_view FUNCTION_NAME_NONE {"none"};
static constexpr std::string_view FUNCTION_NAME_HDC {"hdc"};
static constexpr std::string_view FUNCTION_NAME_ACM {"acm"};
static constexpr std::string_view FUNCTION_NAME_ECM {"ecm"};
static constexpr std::string_view FUNCTION_NAME_MTP {"mtp"};
static constexpr std::string_view FUNCTION_NAME_PTP {"ptp"};
enum PowerRole : int32_t {
POWER_ROLE_NONE,
POWER_ROLE_SOURCE,
POWER_ROLE_SINK,
};
enum DataRole : int32_t {
DTA_ROLE_NONE,
DATA_ROLE_HOST,
DATA_ROLE_DEVICE,
};
enum PortMode : int32_t {
PORT_MODE_NONE,
PORT_MODE_DEVICE,
PORT_MODE_HOST,
};
enum Function : uint32_t {
FUNCTION_NONE = 0,
FUNCTION_ACM = 1,
FUNCTION_ECM = 2,
FUNCTION_HDC = 4,
FUNCTION_MTP = 8,
FUNCTION_PTP = 16,
};
};
} // namespace USB
} // namespace OHOS
#define USB_SRV_SUPPORT_H
#endif // USB_SRV_SUPPORT_H
+2
View File
@@ -18,6 +18,7 @@ config("usbnapi_private_config") {
"//foundation/arkui/napi/native_engine",
"//foundation/arkui/napi/interfaces/kits",
"//third_party/node/src",
"//third_party/jsoncpp/include/json",
"${usb_manager_path}/interfaces/kits/js/napi/include",
"${usb_manager_path}/interfaces/innerkits/native/include",
]
@@ -35,6 +36,7 @@ ohos_shared_library("usb") {
deps = [
"${usb_manager_path}/interfaces/innerkits:usbsrv_client",
"//foundation/arkui/napi:ace_napi",
"//third_party/jsoncpp:jsoncpp",
]
external_deps = [
"hiviewdfx_hilog_native:libhilog",
+2 -2
View File
@@ -601,8 +601,8 @@ static napi_value CoreSetCurrentFunctions(napi_env env, napi_callback_info info)
napi_typeof(env, argv[INDEX_0], &type);
NAPI_ASSERT(env, type == napi_number, "Wrong argument type. Number expected.");
int32_t funcs = 0;
napi_get_value_int32(env, argv[INDEX_0], &funcs);
uint32_t funcs = 0;
napi_get_value_uint32(env, argv[INDEX_0], &funcs);
auto asyncContext = new(std::nothrow) USBFunctionAsyncContext();
NAPI_ASSERT(env, asyncContext != nullptr, "Create USBFunctionAsyncContext failed.");
+6 -3
View File
@@ -14,7 +14,7 @@
import("//base/usb/usb_manager/usbmgr.gni")
config("usbsrv_private_config") {
include_dirs = []
include_dirs = [ "//third_party/jsoncpp/include/json" ]
}
config("usbsrv_public_config") {
@@ -29,7 +29,7 @@ ohos_shared_library("usbservice") {
sources = [
"${usb_manager_path}/services/zidl/src/usb_srv_stub.cpp",
"native/src/usb_descriptor_parser.cpp",
"native/src/usb_function_manager.cpp",
"native/src/usb_device_manager.cpp",
"native/src/usb_host_manager.cpp",
"native/src/usb_port_manager.cpp",
"native/src/usb_right_manager.cpp",
@@ -46,7 +46,10 @@ ohos_shared_library("usbservice") {
public_configs = [ ":usbsrv_public_config" ]
deps = [ "${usb_manager_path}/interfaces/innerkits:usbsrv_client" ]
deps = [
"${usb_manager_path}/interfaces/innerkits:usbsrv_client",
"//third_party/jsoncpp:jsoncpp",
]
external_deps = [
"ability_base:want",
@@ -19,33 +19,29 @@
#include <map>
#include <string>
#include <vector>
#include "usb_common.h"
#include "usb_srv_support.h"
#include "usbd_subscriber.h"
namespace OHOS {
namespace USB {
class UsbFunctionManager {
class UsbDeviceManager {
public:
static bool AreSettableFunctions(int32_t funcs);
static int32_t FromStringFunctions(std::string_view funcs);
static std::string ToStringFunctions(int32_t func);
static void updateFunctions(int32_t func);
static int32_t getCurrentFunctions();
static constexpr std::string_view FUNCTION_NAME_NONE = "none";
static constexpr std::string_view FUNCTION_NAME_HDC = "hdc";
static constexpr std::string_view FUNCTION_NAME_ACM = "acm";
static constexpr std::string_view FUNCTION_NAME_ECM = "ecm";
static constexpr int32_t FUNCTION_NONE = 0;
static constexpr int32_t FUNCTION_ACM = 1;
static constexpr int32_t FUNCTION_ECM = 2;
static constexpr int32_t FUNCTION_HDC = 4;
static uint32_t ConvertFromString(std::string_view funcs);
static std::string ConvertToString(uint32_t func);
void UpdateFunctions(int32_t func);
int32_t GetCurrentFunctions();
void HandleEvent(int32_t status);
private:
static constexpr int32_t FUNCTION_SETTABLE = FUNCTION_HDC | FUNCTION_ACM | FUNCTION_ECM;
static constexpr int32_t FUNCTION_SETTABLE =
UsbSrvSupport::FUNCTION_HDC | UsbSrvSupport::FUNCTION_ACM | UsbSrvSupport::FUNCTION_ECM;
static const std::map<std::string_view, int32_t> FUNCTION_MAPPING_N2C;
static int32_t currentFunctions;
int32_t currentFunctions_ {0};
bool connected_ {false};
};
} // namespace USB
} // namespace OHOS
@@ -19,6 +19,7 @@
#include <map>
#include <string>
#include <vector>
#include "system_ability.h"
#include "usb_device.h"
#include "usb_right_manager.h"
@@ -36,6 +37,8 @@ public:
bool AddDevice(UsbDevice *dev);
private:
bool PublishCommonEvent(const std::string &event, const UsbDevice &dev);
MAP_STR_DEVICE devices_;
SystemAbility *systemAbility_;
};
+1 -2
View File
@@ -29,8 +29,6 @@ class UsbPortManager {
public:
UsbPortManager();
~UsbPortManager();
typedef std::map<int32_t, UsbPort> PortMap;
PortMap portMap;
void Init();
void Init(int32_t test);
@@ -43,6 +41,7 @@ public:
void RemovePort(int32_t portId);
private:
std::map<int32_t, UsbPort> portMap_;
};
} // namespace USB
} // namespace OHOS
+3 -2
View File
@@ -22,7 +22,7 @@
#include "iremote_object.h"
#include "iusb_srv.h"
#include "system_ability.h"
#include "usb_function_manager.h"
#include "usb_device_manager.h"
#include "usb_host_manager.h"
#include "usb_port_manager.h"
#include "usb_right_manager.h"
@@ -86,6 +86,7 @@ public:
bool AddDevice(uint8_t busNum, uint8_t devAddr);
bool DelDevice(uint8_t busNum, uint8_t devAddr);
void UpdateUsbPort(int32_t portId, int32_t powerRole, int32_t dataRole, int32_t mode);
void UpdateDeviceState(int32_t status);
int32_t GetDeviceInfo(uint8_t busNum, uint8_t devAddr, UsbDevice &dev);
int32_t GetDeviceInfoDescriptor(const UsbDev &uDev, std::vector<uint8_t> &descriptor, UsbDevice &dev);
int32_t GetConfigDescriptor(UsbDevice &dev, std::vector<uint8_t> &descriptor);
@@ -107,10 +108,10 @@ private:
std::shared_ptr<UsbHostManager> usbHostManger_;
std::shared_ptr<UsbRightManager> usbRightManager_;
std::shared_ptr<UsbPortManager> usbPortManager_;
std::shared_ptr<UsbDeviceManager> usbDeviceManager_;
std::shared_ptr<AppExecFwk::EventRunner> eventRunner_;
std::shared_ptr<UsbServerEventHandler> handler_;
sptr<UsbServiceSubscriber> usbdSubscriber_;
std::map<std::string, PortInfo> portMap;
};
} // namespace USB
} // namespace OHOS
+164
View File
@@ -0,0 +1,164 @@
/*
* Copyright (c) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "usb_device_manager.h"
#include "common_event_data.h"
#include "common_event_manager.h"
#include "common_event_support.h"
#include "usb_errors.h"
#include "usb_srv_support.h"
#include "usbd_client.h"
using namespace OHOS::AAFwk;
using namespace OHOS::EventFwk;
namespace OHOS {
namespace USB {
const std::map<std::string_view, int32_t> UsbDeviceManager::FUNCTION_MAPPING_N2C = {
{UsbSrvSupport::FUNCTION_NAME_NONE, UsbSrvSupport::FUNCTION_NONE},
{UsbSrvSupport::FUNCTION_NAME_ACM, UsbSrvSupport::FUNCTION_ACM},
{UsbSrvSupport::FUNCTION_NAME_ECM, UsbSrvSupport::FUNCTION_ECM},
{UsbSrvSupport::FUNCTION_NAME_HDC, UsbSrvSupport::FUNCTION_HDC},
{UsbSrvSupport::FUNCTION_NAME_MTP, UsbSrvSupport::FUNCTION_MTP},
{UsbSrvSupport::FUNCTION_NAME_PTP, UsbSrvSupport::FUNCTION_PTP},
};
bool UsbDeviceManager::AreSettableFunctions(int32_t funcs)
{
return funcs == UsbSrvSupport::FUNCTION_NONE || ((~FUNCTION_SETTABLE & funcs) == 0);
}
uint32_t UsbDeviceManager::ConvertFromString(std::string_view strFun)
{
if (strFun == UsbSrvSupport::FUNCTION_NAME_NONE) {
return UsbSrvSupport::FUNCTION_NONE;
}
size_t len = strFun.length();
if (len == 0) {
return UEC_SERVICE_INVALID_VALUE;
}
std::vector<std::string_view> vModeStr;
size_t pos = 0;
while (pos < len) {
size_t find_pos = strFun.find(",", pos);
if (find_pos == strFun.npos) {
vModeStr.push_back(strFun.substr(pos, len - pos));
break;
}
vModeStr.push_back(strFun.substr(pos, find_pos - pos));
pos = find_pos + 1;
}
uint32_t ret = 0;
for (auto &&item : vModeStr) {
auto it = FUNCTION_MAPPING_N2C.find(item);
if (it != FUNCTION_MAPPING_N2C.end()) {
ret |= it->second;
} else {
USB_HILOGE(MODULE_USB_SERVICE, "UsbDeviceManager::ConvertFromString Invalid argument of usb function");
return UEC_SERVICE_INVALID_VALUE;
}
}
return ret;
}
std::string UsbDeviceManager::ConvertToString(uint32_t function)
{
std::string stream;
if (function <= UsbSrvSupport::FUNCTION_NONE || function > FUNCTION_SETTABLE) {
stream = std::string {UsbSrvSupport::FUNCTION_NAME_NONE};
return stream;
}
bool flag = false;
if ((function & UsbSrvSupport::FUNCTION_HDC) != 0) {
stream = std::string {UsbSrvSupport::FUNCTION_NAME_HDC};
flag = true;
}
if ((function & UsbSrvSupport::FUNCTION_ACM) != 0) {
if (flag) {
stream = stream + ",";
}
stream = stream + std::string {UsbSrvSupport::FUNCTION_NAME_ACM};
flag = true;
}
if ((function & UsbSrvSupport::FUNCTION_ECM) != 0) {
if (flag) {
stream = stream + ",";
}
stream = stream + std::string {UsbSrvSupport::FUNCTION_NAME_ECM};
flag = true;
}
USB_HILOGI(MODULE_USB_SERVICE, "UsbDeviceManager::ConvertToString success");
return stream;
}
void UsbDeviceManager::UpdateFunctions(int32_t func)
{
currentFunctions_ = func;
}
int32_t UsbDeviceManager::GetCurrentFunctions()
{
return currentFunctions_;
}
void UsbDeviceManager::HandleEvent(int32_t status)
{
switch (status) {
case ACT_UPDEVICE: {
connected_ = true;
UsbdClient::GetInstance().GetCurrentFunctions(currentFunctions_);
break;
}
case ACT_DOWNDEVICE: {
connected_ = false;
break;
}
default:
USB_HILOGE(MODULE_USB_SERVICE, "invalid status %{public}d", status);
return;
}
Want want;
want.SetAction(CommonEventSupport::COMMON_EVENT_USB_STATE);
want.SetParam(std::string {UsbSrvSupport::CONNECTED}, connected_);
uint32_t remainderFunc = currentFunctions_;
// start from bit 1
uint32_t bit = 1;
while (remainderFunc != 0) {
if (remainderFunc & bit) {
want.SetParam(ConvertToString(bit), true);
// set current bit to zero
remainderFunc &= ~bit;
}
// 1 means to next bit
bit = bit << 1;
}
CommonEventData data(want);
CommonEventPublishInfo publishInfo;
publishInfo.SetOrdered(true);
USB_HILOGI(MODULE_SERVICE,
"send COMMON_EVENT_USB_STATE broadcast connected:%{public}d, currentFunctions:%{public}u", connected_,
currentFunctions_);
CommonEventManager::PublishCommonEvent(data, publishInfo);
}
} // namespace USB
} // namespace OHOS
@@ -1,113 +0,0 @@
/*
* Copyright (c) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "usb_function_manager.h"
#include "usb_errors.h"
namespace OHOS {
namespace USB {
const std::map<std::string_view, int32_t> UsbFunctionManager::FUNCTION_MAPPING_N2C = {
{FUNCTION_NAME_NONE, FUNCTION_NONE},
{FUNCTION_NAME_ACM, FUNCTION_ACM},
{FUNCTION_NAME_ECM, FUNCTION_ECM},
{FUNCTION_NAME_HDC, FUNCTION_HDC},
};
int32_t UsbFunctionManager::currentFunctions = 0;
bool UsbFunctionManager::AreSettableFunctions(int32_t funcs)
{
return funcs == FUNCTION_NONE || ((~FUNCTION_SETTABLE & funcs) == 0);
}
int32_t UsbFunctionManager::FromStringFunctions(std::string_view strFun)
{
if (strFun.compare(FUNCTION_NAME_NONE) == 0) {
return FUNCTION_NONE;
}
size_t len = strFun.length();
if (len == 0) {
return UEC_SERVICE_INVALID_VALUE;
}
std::vector<std::string_view> vModeStr;
size_t pos = 0;
while (pos < len) {
size_t find_pos = strFun.find(",", pos);
if (find_pos == strFun.npos) {
vModeStr.push_back(strFun.substr(pos, len - pos));
break;
}
vModeStr.push_back(strFun.substr(pos, find_pos - pos));
pos = find_pos + 1;
}
int32_t ret = 0;
for (auto &&item : vModeStr) {
auto it = FUNCTION_MAPPING_N2C.find(item);
if (it != FUNCTION_MAPPING_N2C.end()) {
ret |= it->second;
} else {
USB_HILOGE(MODULE_USB_SERVICE, "UsbFunctionManager::FromStringFunctions Invalid argument of usb function");
return UEC_SERVICE_INVALID_VALUE;
}
}
return ret;
}
std::string UsbFunctionManager::ToStringFunctions(int32_t intFun)
{
std::string stream;
if (intFun <= FUNCTION_NONE || intFun > FUNCTION_SETTABLE) {
stream = std::string { FUNCTION_NAME_NONE };
return stream;
}
bool flag = false;
if ((intFun & FUNCTION_HDC) != 0) {
stream = std::string { FUNCTION_NAME_HDC };
flag = true;
}
if ((intFun & FUNCTION_ACM) != 0) {
if (flag) {
stream = stream + ",";
}
stream = stream + std::string { FUNCTION_NAME_ACM };
flag = true;
}
if ((intFun & FUNCTION_ECM) != 0) {
if (flag) {
stream = stream + ",";
}
stream = stream + std::string { FUNCTION_NAME_ECM };
flag = true;
}
USB_HILOGI(MODULE_USB_SERVICE, "UsbFunctionManager::ToStringFunctions success");
return stream;
}
void UsbFunctionManager::updateFunctions(int32_t func)
{
currentFunctions = func;
}
int32_t UsbFunctionManager::getCurrentFunctions()
{
return currentFunctions;
}
} // namespace USB
} // namespace OHOS
+49 -12
View File
@@ -14,9 +14,15 @@
*/
#include "usb_host_manager.h"
#include "common_event_data.h"
#include "common_event_manager.h"
#include "common_event_support.h"
#include "hilog_wrapper.h"
#include "usb_serial_reader.h"
using namespace OHOS::AAFwk;
using namespace OHOS::EventFwk;
namespace OHOS {
namespace USB {
UsbHostManager::UsbHostManager(SystemAbility *systemAbility)
@@ -26,9 +32,9 @@ UsbHostManager::UsbHostManager(SystemAbility *systemAbility)
UsbHostManager::~UsbHostManager() {}
void UsbHostManager::GetDevices(MAP_STR_DEVICE &Devices)
void UsbHostManager::GetDevices(MAP_STR_DEVICE &devices)
{
Devices = devices_;
devices = devices_;
}
bool UsbHostManager::DelDevice(uint8_t busNum, uint8_t devNum)
@@ -36,16 +42,25 @@ bool UsbHostManager::DelDevice(uint8_t busNum, uint8_t devNum)
std::string name = std::to_string(busNum) + "-" + std::to_string(devNum);
MAP_STR_DEVICE::iterator iter = devices_.find(name);
if (iter == devices_.end()) {
USB_HILOGF(MODULE_SERVICE, "name:%{public}s bus:%{public}hhu dev:%{public}hhu not exist", name.c_str(),
busNum, devNum);
USB_HILOGF(MODULE_SERVICE, "name:%{public}s bus:%{public}hhu dev:%{public}hhu not exist", name.c_str(), busNum,
devNum);
return false;
}
USB_HILOGI(MODULE_SERVICE, "device:%{public}s bus:%{public}hhu dev:%{public}hhu erase ", name.c_str(), busNum,
devNum);
USB_HILOGI(
MODULE_SERVICE, "device:%{public}s bus:%{public}hhu dev:%{public}hhu erase ", name.c_str(), busNum, devNum);
UsbDevice *devOld = iter->second;
if (devOld == nullptr) {
USB_HILOGE(MODULE_SERVICE, "invalid device");
return false;
}
auto isSuccess = PublishCommonEvent(CommonEventSupport::COMMON_EVENT_USB_DEVICE_DETACHED, *devOld);
if (!isSuccess) {
USB_HILOGW(MODULE_SERVICE, "send device attached broadcast failed");
}
delete devOld;
devices_.erase(iter);
if (devOld)
delete devOld;
return true;
}
@@ -55,6 +70,12 @@ bool UsbHostManager::AddDevice(UsbDevice *dev)
USB_HILOGF(MODULE_SERVICE, "device is NULL");
return false;
}
auto isSuccess = PublishCommonEvent(CommonEventSupport::COMMON_EVENT_USB_DEVICE_ATTACHED, *dev);
if (!isSuccess) {
USB_HILOGW(MODULE_SERVICE, "send device attached broadcast failed");
}
uint8_t busNum = dev->GetBusNum();
uint8_t devNum = dev->GetDevAddr();
std::string name = std::to_string(busNum) + "-" + std::to_string(devNum);
@@ -63,14 +84,30 @@ bool UsbHostManager::AddDevice(UsbDevice *dev)
USB_HILOGF(MODULE_SERVICE, "device:%{public}s bus:%{public}hhu dev:%{public}hhu already exist", name.c_str(),
busNum, devNum);
UsbDevice *devOld = iter->second;
delete devOld;
devices_.erase(iter);
if (devOld)
delete devOld;
}
USB_HILOGI(MODULE_SERVICE, "device:%{public}s bus:%{public}hhu dev:%{public}hhu insert", name.c_str(), busNum,
devNum);
USB_HILOGI(
MODULE_SERVICE, "device:%{public}s bus:%{public}hhu dev:%{public}hhu insert", name.c_str(), busNum, devNum);
devices_.insert(std::pair<std::string, UsbDevice *>(name, dev));
return true;
}
bool UsbHostManager::PublishCommonEvent(const std::string &event, const UsbDevice &dev)
{
Want want;
want.SetAction(event);
CommonEventData data(want);
Json::StreamWriterBuilder builder;
builder["indentation"] = "";
auto jsonString = Json::writeString(builder, dev.ToJson());
data.SetData(jsonString);
CommonEventPublishInfo publishInfo;
publishInfo.SetOrdered(true);
USB_HILOGI(MODULE_SERVICE, "send %{public}s broadcast device:%{public}s", event.c_str(), jsonString.c_str());
return CommonEventManager::PublishCommonEvent(data, publishInfo);
}
} // namespace USB
} // namespace OHOS
+15 -17
View File
@@ -42,8 +42,8 @@ void UsbPortManager::Init()
int32_t UsbPortManager::GetPorts(std::vector<UsbPort> &ports)
{
if (portMap.size() > 0) {
for (auto it = portMap.begin(); it != portMap.end(); ++it) {
if (portMap_.size() > 0) {
for (auto it = portMap_.begin(); it != portMap_.end(); ++it) {
ports.push_back(it->second);
}
USB_HILOGI(MODULE_USB_SERVICE, "UsbPortManager::GetPorts success");
@@ -51,7 +51,7 @@ int32_t UsbPortManager::GetPorts(std::vector<UsbPort> &ports)
} else {
int32_t ret = QueryPort();
if (ret == UEC_OK) {
for (auto it = portMap.begin(); it != portMap.end(); ++it) {
for (auto it = portMap_.begin(); it != portMap_.end(); ++it) {
ports.push_back(it->second);
}
USB_HILOGI(MODULE_USB_SERVICE, "UsbPortManager::QueryPort and GetPorts success");
@@ -64,8 +64,8 @@ int32_t UsbPortManager::GetPorts(std::vector<UsbPort> &ports)
int32_t UsbPortManager::GetSupportedModes(int32_t portId, int32_t &supportedModes)
{
auto it = portMap.find(portId);
if (it != portMap.end()) {
auto it = portMap_.find(portId);
if (it != portMap_.end()) {
supportedModes = it->second.supportedModes;
USB_HILOGI(MODULE_USB_SERVICE, "UsbPortManager::GetSupportedModes success");
return UEC_OK;
@@ -103,8 +103,8 @@ int32_t UsbPortManager::QueryPort()
void UsbPortManager::UpdatePort(int32_t portId, int32_t powerRole, int32_t dataRole, int32_t mode)
{
USB_HILOGI(MODULE_USB_SERVICE, "UsbPortManager::updatePort run");
auto it = portMap.find(portId);
if (it != portMap.end()) {
auto it = portMap_.find(portId);
if (it != portMap_.end()) {
if (it->second.id == portId) {
it->second.usbPortStatus.currentPowerRole = powerRole;
it->second.usbPortStatus.currentDataRole = dataRole;
@@ -119,25 +119,23 @@ void UsbPortManager::UpdatePort(int32_t portId, int32_t powerRole, int32_t dataR
void UsbPortManager::AddPort(UsbPort &port)
{
USB_HILOGI(MODULE_USB_SERVICE, "addPort run");
auto it = portMap.find(port.id);
if (it == portMap.end()) {
portMap.insert(PortMap::value_type(port.id, port));
USB_HILOGI(MODULE_USB_SERVICE, "addPort seccess");
auto res = portMap_.insert(std::map<int32_t, UsbPort>::value_type(port.id, port));
if (!res.second) {
USB_HILOGW(MODULE_USB_SERVICE, "addPort port id duplicated");
return;
}
USB_HILOGE(MODULE_USB_SERVICE, "addPort false");
USB_HILOGI(MODULE_USB_SERVICE, "addPort successed");
}
void UsbPortManager::RemovePort(int32_t portId)
{
USB_HILOGI(MODULE_USB_SERVICE, "removePort run");
auto it = portMap.find(portId);
if (it != portMap.end()) {
portMap.erase(it);
USB_HILOGI(MODULE_USB_SERVICE, "removePort seccess");
size_t num = portMap_.erase(portId);
if (num == 0) {
USB_HILOGW(MODULE_USB_SERVICE, "removePort false");
return;
}
USB_HILOGE(MODULE_USB_SERVICE, "removePort false");
USB_HILOGI(MODULE_USB_SERVICE, "removePort seccess");
}
} // namespace USB
} // namespace OHOS
+92 -24
View File
@@ -59,6 +59,7 @@ UsbService::UsbService() : SystemAbility(USB_SYSTEM_ABILITY_ID, true)
usbHostManger_ = std::make_shared<UsbHostManager>(nullptr);
usbRightManager_ = std::make_shared<UsbRightManager>();
usbPortManager_ = std::make_shared<UsbPortManager>();
usbDeviceManager_ = std::make_shared<UsbDeviceManager>();
}
UsbService::~UsbService() {}
@@ -89,6 +90,11 @@ void UsbService::OnStart()
return;
}
}
if (usbPortManager_ == nullptr) {
USB_HILOGE(MODULE_USB_SERVICE, "invalid usbPortManager_");
return;
}
usbPortManager_->Init();
ready_ = true;
@@ -154,13 +160,13 @@ void UsbService::OnStop()
bool UsbService::IsCommonEventServiceAbilityExist()
{
sptr<ISystemAbilityManager> sm = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (!sm) {
if (sm == nullptr) {
USB_HILOGE(MODULE_USB_SERVICE,
"IsCommonEventServiceAbilityExist Get ISystemAbilityManager "
"failed, no SystemAbilityManager");
return false;
}
sptr<IRemoteObject> remote = sm->CheckSystemAbility(COMMON_EVENT_SERVICE_ABILITY_ID);
sptr<IRemoteObject> remote = sm->CheckSystemAbility(COMMON_EVENT_SERVICE_ID);
if (!remote) {
USB_HILOGE(MODULE_USB_SERVICE, "No CesServiceAbility");
return false;
@@ -189,28 +195,43 @@ bool UsbService::HasRight(std::string deviceName)
{
USB_HILOGI(MODULE_USB_SERVICE, "calling usbRightManager HasRight");
std::string bundleName;
if (GetBundleName(bundleName)) {
USB_HILOGI(MODULE_USB_SERVICE, "HasRight bundleName = %{public}s", bundleName.c_str());
return usbRightManager_->HasRight(deviceName, bundleName);
if (!GetBundleName(bundleName)) {
USB_HILOGE(MODULE_USB_SERVICE, "HasRight GetBundleName false");
return false;
}
USB_HILOGE(MODULE_USB_SERVICE, "HasRight GetBundleName false");
return false;
USB_HILOGI(MODULE_USB_SERVICE, "HasRight bundleName = %{public}s", bundleName.c_str());
if (usbRightManager_ == nullptr) {
USB_HILOGE(MODULE_USB_SERVICE, "invalid usbRightManager_");
return false;
}
return usbRightManager_->HasRight(deviceName, bundleName);
}
int32_t UsbService::RequestRight(std::string deviceName)
{
USB_HILOGI(MODULE_USB_SERVICE, "calling usbRightManager RequestRight");
std::string bundleName;
if (GetBundleName(bundleName)) {
USB_HILOGI(MODULE_USB_SERVICE, "RequestRight bundleName = %{public}s", bundleName.c_str());
return usbRightManager_->RequestRight(deviceName, bundleName);
if (!GetBundleName(bundleName)) {
USB_HILOGI(MODULE_USB_SERVICE, "RequestRight GetBundleName false");
return UEC_SERVICE_INNER_ERR;
}
USB_HILOGI(MODULE_USB_SERVICE, "RequestRight GetBundleName false");
return UEC_SERVICE_INNER_ERR;
if (usbRightManager_ == nullptr) {
USB_HILOGE(MODULE_USB_SERVICE, "invalid usbRightManager_");
return UEC_SERVICE_INVALID_VALUE;
}
USB_HILOGI(MODULE_USB_SERVICE, "RequestRight bundleName = %{public}s", bundleName.c_str());
return usbRightManager_->RequestRight(deviceName, bundleName);
}
int32_t UsbService::RemoveRight(std::string deviceName)
{
if (usbRightManager_ == nullptr) {
USB_HILOGE(MODULE_USB_SERVICE, "invalid usbRightManager_");
return UEC_SERVICE_INVALID_VALUE;
}
if (usbRightManager_->RemoveDeviceRight(deviceName)) {
return UEC_OK;
}
@@ -220,6 +241,12 @@ int32_t UsbService::RemoveRight(std::string deviceName)
int32_t UsbService::GetDevices(std::vector<UsbDevice> &deviceList)
{
std::map<std::string, UsbDevice *> devices;
if (usbHostManger_ == nullptr) {
USB_HILOGE(MODULE_USB_SERVICE, "invalid usbHostManger_");
return UEC_SERVICE_INVALID_VALUE;
}
usbHostManger_->GetDevices(devices);
USB_HILOGI(MODULE_USB_SERVICE, "list size %{public}zu", devices.size());
for (auto it = devices.begin(); it != devices.end(); ++it) {
@@ -228,38 +255,52 @@ int32_t UsbService::GetDevices(std::vector<UsbDevice> &deviceList)
return UEC_OK;
}
int32_t UsbService::GetCurrentFunctions(int32_t &funcs)
int32_t UsbService::GetCurrentFunctions(int32_t &functions)
{
return UsbdClient::GetInstance().GetCurrentFunctions(funcs);
return UsbdClient::GetInstance().GetCurrentFunctions(functions);
}
int32_t UsbService::SetCurrentFunctions(int32_t funcs)
int32_t UsbService::SetCurrentFunctions(int32_t functions)
{
USB_HILOGI(MODULE_USB_SERVICE, "func = %{public}d", funcs);
return UsbdClient::GetInstance().SetCurrentFunctions(funcs);
USB_HILOGI(MODULE_USB_SERVICE, "func = %{public}d", functions);
if (usbDeviceManager_ == nullptr) {
USB_HILOGE(MODULE_USB_SERVICE, "invalid usbDeviceManager_");
return UEC_SERVICE_INVALID_VALUE;
}
usbDeviceManager_->UpdateFunctions(functions);
return UsbdClient::GetInstance().SetCurrentFunctions(functions);
}
int32_t UsbService::UsbFunctionsFromString(std::string_view funcs)
{
USB_HILOGI(MODULE_USB_SERVICE, "calling UsbFunctionsFromString");
return UsbFunctionManager::FromStringFunctions(funcs);
return UsbDeviceManager::ConvertFromString(funcs);
}
std::string UsbService::UsbFunctionsToString(int32_t funcs)
{
USB_HILOGI(MODULE_USB_SERVICE, "calling UsbFunctionsToString");
return UsbFunctionManager::ToStringFunctions(funcs);
return UsbDeviceManager::ConvertToString(funcs);
}
int32_t UsbService::GetPorts(std::vector<UsbPort> &ports)
{
USB_HILOGI(MODULE_USB_SERVICE, "calling usbPortManager getPorts");
if (usbPortManager_ == nullptr) {
USB_HILOGE(MODULE_USB_SERVICE, "invalid usbPortManager_");
return UEC_SERVICE_INVALID_VALUE;
}
return usbPortManager_->GetPorts(ports);
}
int32_t UsbService::GetSupportedModes(int32_t portId, int32_t &supportedModes)
{
USB_HILOGI(MODULE_USB_SERVICE, "calling usbPortManager getSupportedModes");
if (usbPortManager_ == nullptr) {
USB_HILOGE(MODULE_USB_SERVICE, "invalid usbPortManager_");
return UEC_SERVICE_INVALID_VALUE;
}
return usbPortManager_->GetSupportedModes(portId, supportedModes);
}
@@ -567,12 +608,18 @@ bool UsbService::AddDevice(uint8_t busNum, uint8_t devAddr)
int32_t ret = GetDeviceInfo(busNum, devAddr, *devInfo);
USB_HILOGI(MODULE_USB_SERVICE, "GetDeviceInfo ret=%{public}d", ret);
if (ret == UEC_OK) {
usbHostManger_->AddDevice(devInfo);
return true;
if (ret != UEC_OK) {
delete devInfo;
return false;
}
delete devInfo;
return false;
if (usbHostManger_ == nullptr) {
USB_HILOGE(MODULE_USB_SERVICE, "invalid usbHostManger_");
return false;
}
usbHostManger_->AddDevice(devInfo);
return true;
}
bool UsbService::DelDevice(uint8_t busNum, uint8_t devAddr)
@@ -582,14 +629,35 @@ bool UsbService::DelDevice(uint8_t busNum, uint8_t devAddr)
if (ret != UEC_OK) {
USB_HILOGE(MODULE_USBD, "Close device failed width ret = %{public}d", ret);
}
if (usbHostManger_ == nullptr) {
USB_HILOGE(MODULE_USB_SERVICE, "invalid usbHostManger_");
return false;
}
return usbHostManger_->DelDevice(busNum, devAddr);
}
void UsbService::UpdateUsbPort(int32_t portId, int32_t powerRole, int32_t dataRole, int32_t mode)
{
if (usbPortManager_ == nullptr) {
USB_HILOGE(MODULE_USB_SERVICE, "invalid usbPortManager_");
return;
}
usbPortManager_->UpdatePort(portId, powerRole, dataRole, mode);
}
void UsbService::UpdateDeviceState(int32_t status)
{
if (usbDeviceManager_ == nullptr) {
USB_HILOGE(MODULE_USB_SERVICE, "invalid usbDeviceManager_");
return;
}
usbDeviceManager_->HandleEvent(status);
}
bool UsbService::GetBundleName(std::string &bundleName)
{
#ifdef USB_RIGHT_TEST
+22 -61
View File
@@ -15,7 +15,7 @@
#include "usb_service_subscriber.h"
#include <sys/time.h>
#include "json.h"
#include "common_event_data.h"
#include "common_event_manager.h"
#include "common_event_support.h"
@@ -31,8 +31,6 @@ using namespace OHOS::EventFwk;
namespace OHOS {
namespace USB {
const int32_t MSEC_TIME = 1000;
UsbServiceSubscriber::UsbServiceSubscriber() {}
int32_t UsbServiceSubscriber::PortChangedEvent(int32_t portId, int32_t powerRole, int32_t dataRole, int32_t mode)
@@ -43,10 +41,21 @@ int32_t UsbServiceSubscriber::PortChangedEvent(int32_t portId, int32_t powerRole
return UEC_SERVICE_GET_USB_SERVICE_FAILED;
}
Json::Value port;
port["portId"] = portId;
port["powerRole"] = powerRole;
port["dataRole"] = dataRole;
port["mode"] = mode;
Json::StreamWriterBuilder builder;
builder["indentation"] = "";
auto jsonString = Json::writeString(builder, port);
Want want;
want.SetAction(CommonEventSupport::COMMON_EVENT_USB_PORT_CHANGED);
pms->UpdateUsbPort(portId, powerRole, dataRole, mode);
CommonEventData data;
data.SetData(jsonString);
data.SetWant(want);
CommonEventPublishInfo publishInfo;
publishInfo.SetOrdered(true);
@@ -57,79 +66,31 @@ int32_t UsbServiceSubscriber::PortChangedEvent(int32_t portId, int32_t powerRole
return isSuccess;
}
int32_t Invoking(const UsbInfo &info, Want &want)
{
int32_t ret = 0;
switch (info.getDevInfoStatus()) {
case ACT_DEVUP:
want.SetAction(CommonEventSupport::COMMON_EVENT_USB_DEVICE_ATTACHED);
break;
case ACT_DEVDOWN:
want.SetAction(CommonEventSupport::COMMON_EVENT_USB_DEVICE_DETACHED);
break;
case ACT_UPDEVICE:
want.SetAction(CommonEventSupport::COMMON_EVENT_USB_ACCESSORY_ATTACHED);
break;
case ACT_DOWNDEVICE:
want.SetAction(CommonEventSupport::COMMON_EVENT_USB_ACCESSORY_DETACHED);
break;
default:
ret = -1;
break;
}
return ret;
}
int32_t UsbServiceSubscriber::DeviceEvent(const UsbInfo &info)
{
struct timeval start;
gettimeofday(&start, NULL);
int32_t status = info.getDevInfoStatus();
int32_t ret = UEC_OK;
Want want;
USB_HILOGW(MODULE_USBD, "status:%{public}d bus:%{public}d dev:%{public}d", status, info.getDevInfoBusNum(),
info.getDevInfoDevNum());
if (Invoking(info, want) == -1) {
return ret;
}
CommonEventData data;
data.SetWant(want);
CommonEventPublishInfo publishInfo;
publishInfo.SetOrdered(true);
bool isSuccess = CommonEventManager::PublishCommonEvent(data, publishInfo);
if (!isSuccess) {
USB_HILOGE(MODULE_USB_SERVICE, "failed to publish USB_CHANGED event");
ret = UEC_SERVICE_NO_INIT;
}
struct timeval end;
gettimeofday(&end, NULL);
int64_t tackTime = (end.tv_sec - start.tv_sec) * MSEC_TIME + (end.tv_usec - start.tv_usec) / MSEC_TIME;
USB_HILOGD(MODULE_USB_SERVICE, "end call subscriber usb device tached event, takes : %{public}lld ms",
(long long)tackTime);
if ((ACT_UPDEVICE == status) || (ACT_DOWNDEVICE == status)) {
return ret;
}
int32_t busNum = info.getDevInfoBusNum();
int32_t devAddr = info.getDevInfoDevNum();
USB_HILOGW(MODULE_USBD, "status:%{public}d bus:%{public}d dev:%{public}d", status, busNum, devAddr);
auto pms = DelayedSpSingleton<UsbService>::GetInstance();
if (pms == nullptr) {
USB_HILOGE(MODULE_USB_SERVICE, "failed to GetInstance");
return UEC_SERVICE_GET_USB_SERVICE_FAILED;
}
if ((ACT_UPDEVICE == status) || (ACT_DOWNDEVICE == status)) {
pms->UpdateDeviceState(status);
return UEC_OK;
}
int32_t busNum = info.getDevInfoBusNum();
int32_t devAddr = info.getDevInfoDevNum();
if (status == ACT_DEVUP) {
USB_HILOGE(MODULE_USB_SERVICE, "usb attached");
USB_HILOGI(MODULE_USB_SERVICE, "usb attached");
pms->AddDevice(busNum, devAddr);
} else {
USB_HILOGE(MODULE_USB_SERVICE, "usb detached");
USB_HILOGI(MODULE_USB_SERVICE, "usb detached");
pms->DelDevice(busNum, devAddr);
}
return ret;
return UEC_OK;
}
} // namespace USB
} // namespace OHOS
+3 -3
View File
@@ -208,12 +208,12 @@ int32_t UsbServerStub::OnRemoteRequest(uint32_t code, MessageParcel &data, Messa
int32_t UsbServerStub::DoGetCurrentFunctions(MessageParcel &data, MessageParcel &reply, MessageOption &option)
{
int32_t funcs;
int32_t ret = GetCurrentFunctions(funcs);
int32_t functions;
int32_t ret = GetCurrentFunctions(functions);
if (ret != UEC_OK) {
return ret;
}
WRITE_PARCEL_WITH_RET(reply, Int32, funcs, UEC_SERVICE_WRITE_PARCEL_ERROR);
WRITE_PARCEL_WITH_RET(reply, Int32, functions, UEC_SERVICE_WRITE_PARCEL_ERROR);
return UEC_OK;
}
+32
View File
@@ -22,6 +22,7 @@ config("module_private_config") {
include_dirs = [
"include",
"${usb_manager_path}/test/common/include/",
"//third_party/jsoncpp/include/json",
]
}
@@ -144,12 +145,43 @@ ohos_unittest("test_usbcore") {
]
}
ohos_unittest("test_usbevent") {
module_out_path = module_output_path
sources = [ "src/usb_event_test.cpp" ]
configs = [
"${utils_path}:utils_config",
":module_private_config",
]
deps = [
"${usb_manager_path}/interfaces/innerkits:usbsrv_client",
"${usb_manager_path}/services:usbservice",
"//third_party/googletest:gtest_main",
"//third_party/jsoncpp:jsoncpp",
]
external_deps = [
"ability_base:want",
"bundle_framework:appexecfwk_base",
"common_event_service:cesfwk_innerkits",
"eventhandler:libeventhandler",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"safwk:system_ability_fwk",
"samgr_standard:samgr_proxy",
"usb_device_driver:usbd_client",
"utils_base:utils",
]
}
group("unittest") {
testonly = true
deps = [
":test_bulkcallback",
":test_usbcore",
":test_usbdevicepipe",
":test_usbevent",
":test_usbrequest",
]
}
@@ -27,6 +27,7 @@
#include "usb_errors.h"
#include "usb_service.h"
#include "usb_srv_client.h"
#include "usb_srv_support.h"
using namespace testing::ext;
using namespace OHOS::USB;
@@ -191,7 +192,7 @@ HWTEST_F(UsbCoreTest, UsbFunctionsFromString001, TestSize.Level1)
{
USB_HILOGI(MODULE_USB_SERVICE, "Case Start : UsbFunctionsFromString001 : SetConfig");
auto &instance = UsbSrvClient::GetInstance();
int32_t funcCode = instance.UsbFunctionsFromString(UsbFunctionManager::FUNCTION_NAME_NONE);
int32_t funcCode = instance.UsbFunctionsFromString(UsbSrvSupport::FUNCTION_NAME_NONE);
USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::functionsFromString=%{public}d", funcCode);
ASSERT_TRUE(funcCode != UEC_SERVICE_INVALID_VALUE);
USB_HILOGI(MODULE_USB_SERVICE, "Case End : UsbFunctionsFromString001 : SetConfig");
@@ -206,7 +207,7 @@ HWTEST_F(UsbCoreTest, UsbFunctionsFromString002, TestSize.Level1)
{
USB_HILOGI(MODULE_USB_SERVICE, "Case Start : UsbFunctionsFromString002 : SetConfig");
auto &instance = UsbSrvClient::GetInstance();
int32_t funcCode = instance.UsbFunctionsFromString(UsbFunctionManager::FUNCTION_NAME_HDC);
int32_t funcCode = instance.UsbFunctionsFromString(UsbSrvSupport::FUNCTION_NAME_HDC);
USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::functionsFromString=%{public}d", funcCode);
ASSERT_TRUE(funcCode != UEC_SERVICE_INVALID_VALUE);
USB_HILOGI(MODULE_USB_SERVICE, "Case End : UsbFunctionsFromString002 : SetConfig");
@@ -221,7 +222,7 @@ HWTEST_F(UsbCoreTest, UsbFunctionsFromString003, TestSize.Level1)
{
USB_HILOGI(MODULE_USB_SERVICE, "Case Start : UsbFunctionsFromString003 : SetConfig");
auto &instance = UsbSrvClient::GetInstance();
int32_t funcCode = instance.UsbFunctionsFromString(UsbFunctionManager::FUNCTION_NAME_ACM);
int32_t funcCode = instance.UsbFunctionsFromString(UsbSrvSupport::FUNCTION_NAME_ACM);
USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::functionsFromString=%{public}d", funcCode);
ASSERT_TRUE(funcCode != UEC_SERVICE_INVALID_VALUE);
USB_HILOGI(MODULE_USB_SERVICE, "Case End : UsbFunctionsFromString003 : SetConfig");
@@ -236,7 +237,7 @@ HWTEST_F(UsbCoreTest, UsbFunctionsFromString004, TestSize.Level1)
{
USB_HILOGI(MODULE_USB_SERVICE, "Case Start : UsbFunctionsFromString004 : SetConfig");
auto &instance = UsbSrvClient::GetInstance();
int32_t funcCode = instance.UsbFunctionsFromString(UsbFunctionManager::FUNCTION_NAME_ECM);
int32_t funcCode = instance.UsbFunctionsFromString(UsbSrvSupport::FUNCTION_NAME_ECM);
USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::functionsFromString=%{public}d", funcCode);
ASSERT_TRUE(funcCode != UEC_SERVICE_INVALID_VALUE);
USB_HILOGI(MODULE_USB_SERVICE, "Case End : UsbFunctionsFromString004 : SetConfig");
@@ -283,7 +284,7 @@ HWTEST_F(UsbCoreTest, UsbFunctionsToString001, TestSize.Level1)
{
USB_HILOGI(MODULE_USB_SERVICE, "Case Start : UsbFunctionsToString001 : SetConfig");
auto &instance = UsbSrvClient::GetInstance();
std::string funcName = instance.UsbFunctionsToString(UsbFunctionManager::FUNCTION_NONE);
std::string funcName = instance.UsbFunctionsToString(UsbSrvSupport::FUNCTION_NONE);
USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::UsbFunctionsToString=%{public}s", funcName.c_str());
USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::UsbFunctionsToString=%{public}zu", funcName.size());
ASSERT_TRUE(!(funcName.empty()));
@@ -299,7 +300,7 @@ HWTEST_F(UsbCoreTest, UsbFunctionsToString002, TestSize.Level1)
{
USB_HILOGI(MODULE_USB_SERVICE, "Case Start : UsbFunctionsToString002 : SetConfig");
auto &instance = UsbSrvClient::GetInstance();
std::string funcName = instance.UsbFunctionsToString(UsbFunctionManager::FUNCTION_HDC);
std::string funcName = instance.UsbFunctionsToString(UsbSrvSupport::FUNCTION_HDC);
USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::UsbFunctionsToString=%{public}s", funcName.c_str());
ASSERT_TRUE(!(funcName.empty()));
USB_HILOGI(MODULE_USB_SERVICE, "Case End : UsbFunctionsToString002 : SetConfig");
@@ -314,7 +315,7 @@ HWTEST_F(UsbCoreTest, UsbFunctionsToString003, TestSize.Level1)
{
USB_HILOGI(MODULE_USB_SERVICE, "Case Start : UsbFunctionsToString003 : SetConfig");
auto &instance = UsbSrvClient::GetInstance();
std::string funcName = instance.UsbFunctionsToString(UsbFunctionManager::FUNCTION_ACM);
std::string funcName = instance.UsbFunctionsToString(UsbSrvSupport::FUNCTION_ACM);
USB_HILOGI(MODULE_USB_SERVICE, "UsbFunctionServiceTest::UsbFunctionsToString=%{public}s", funcName.c_str());
ASSERT_TRUE(!(funcName.empty()));
USB_HILOGI(MODULE_USB_SERVICE, "Case End : UsbFunctionsToString003 : SetConfig");
@@ -329,7 +330,7 @@ HWTEST_F(UsbCoreTest, UsbFunctionsToString004, TestSize.Level1)
{
USB_HILOGI(MODULE_USB_SERVICE, "Case Start : UsbFunctionsToString004 : SetConfig");
auto &instance = UsbSrvClient::GetInstance();
std::string funcName = instance.UsbFunctionsToString(UsbFunctionManager::FUNCTION_ECM);
std::string funcName = instance.UsbFunctionsToString(UsbSrvSupport::FUNCTION_ECM);
USB_HILOGI(MODULE_USB_SERVICE, "UsbFunctionServiceTest::UsbFunctionsToString=%{public}s", funcName.c_str());
ASSERT_TRUE(!(funcName.empty()));
USB_HILOGI(MODULE_USB_SERVICE, "Case End : UsbFunctionsToString004 : SetConfig");
@@ -0,0 +1,278 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <gtest/gtest.h>
#include <iostream>
#include <json/json.h>
#include <semaphore.h>
#include "common_event_manager.h"
#include "common_event_support.h"
#include "usb_srv_client.h"
#include "usb_srv_support.h"
using namespace OHOS::EventFwk;
using namespace testing::ext;
using namespace OHOS::USB;
namespace OHOS {
namespace USB {
class UsbEventTest : public testing::Test {
public:
void SetUp() override;
void TearDown() override;
static sem_t testSem_;
};
sem_t UsbEventTest::testSem_ {};
class UsbSubscriberTest : public CommonEventSubscriber {
public:
explicit UsbSubscriberTest(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) {}
void OnReceiveEvent(const CommonEventData &data) override
{
eventData_ = data;
sem_post(&UsbEventTest::testSem_);
}
static CommonEventData eventData_;
};
CommonEventData UsbSubscriberTest::eventData_ {};
void UsbEventTest::SetUp()
{
sem_init(&UsbEventTest::testSem_, 1, 0);
}
void UsbEventTest::TearDown()
{
sem_destroy(&UsbEventTest::testSem_);
}
/**
* @tc.name: usbStateEvent001
* @tc.desc: usb gadget connected event
* @tc.type: FUNC
*/
HWTEST_F(UsbEventTest, usbStateEvent001, TestSize.Level1)
{
// subscribe usb common event
MatchingSkills matchingSkills;
matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_USB_STATE);
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
std::shared_ptr<UsbSubscriberTest> subscriber = std::make_shared<UsbSubscriberTest>(subscriberInfo);
CommonEventManager::SubscribeCommonEvent(subscriber);
std::cout << "please connect the gadget to some host" << std::endl;
// block until UsbSubscriberTest post
sem_wait(&UsbEventTest::testSem_);
CommonEventManager::UnSubscribeCommonEvent(subscriber);
auto &want = UsbSubscriberTest::eventData_.GetWant();
EXPECT_EQ(want.GetAction(), CommonEventSupport::COMMON_EVENT_USB_STATE);
EXPECT_TRUE(want.GetBoolParam(std::string {UsbSrvSupport::CONNECTED}, false));
EXPECT_TRUE(want.GetBoolParam(std::string {UsbSrvSupport::FUNCTION_NAME_HDC}, false));
}
/**
* @tc.name: usbStateEvent002
* @tc.desc: usb gadget disconnected event
* @tc.type: FUNC
*/
HWTEST_F(UsbEventTest, usbStateEvent002, TestSize.Level1)
{
MatchingSkills matchingSkills;
matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_USB_STATE);
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
std::shared_ptr<UsbSubscriberTest> subscriber = std::make_shared<UsbSubscriberTest>(subscriberInfo);
CommonEventManager::SubscribeCommonEvent(subscriber);
std::cout << "please disconnect the gadget" << std::endl;
// block until UsbSubscriberTest post
sem_wait(&UsbEventTest::testSem_);
CommonEventManager::UnSubscribeCommonEvent(subscriber);
auto &want = UsbSubscriberTest::eventData_.GetWant();
EXPECT_EQ(want.GetAction(), CommonEventSupport::COMMON_EVENT_USB_STATE);
EXPECT_FALSE(want.GetBoolParam(std::string {UsbSrvSupport::CONNECTED}, true));
EXPECT_TRUE(want.GetBoolParam(std::string {UsbSrvSupport::FUNCTION_NAME_HDC}, false));
}
/**
* @tc.name: usbDeviceAttached
* @tc.desc: usb device attached event
* @tc.type: FUNC
*/
HWTEST_F(UsbEventTest, usbDeviceAttached, TestSize.Level1)
{
MatchingSkills matchingSkills;
matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_USB_DEVICE_ATTACHED);
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
std::shared_ptr<UsbSubscriberTest> subscriber = std::make_shared<UsbSubscriberTest>(subscriberInfo);
CommonEventManager::SubscribeCommonEvent(subscriber);
std::cout << "please connect a device to the host" << std::endl;
// block until UsbSubscriberTest post
sem_wait(&UsbEventTest::testSem_);
CommonEventManager::UnSubscribeCommonEvent(subscriber);
auto &want = UsbSubscriberTest::eventData_.GetWant();
EXPECT_EQ(want.GetAction(), CommonEventSupport::COMMON_EVENT_USB_DEVICE_ATTACHED);
// parse string to Json::Value
std::string deviceStr = UsbSubscriberTest::eventData_.GetData();
std::cout << deviceStr << std::endl;
Json::CharReaderBuilder builder;
JSONCPP_STRING err;
const std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
Json::Value deviceJson;
auto parseResult = reader->parse(deviceStr.c_str(), deviceStr.c_str() + deviceStr.length(), &deviceJson, &err);
EXPECT_TRUE(parseResult);
// valid device
UsbDevice device(deviceJson);
EXPECT_NE(device.GetiProduct(), 0);
EXPECT_NE(device.GetiManufacturer(), 0);
EXPECT_GT(device.GetConfigCount(), 0);
// valid config
USBConfig config;
device.GetConfig(0, config);
EXPECT_NE(config.GetAttributes(), 0);
EXPECT_GT(config.GetInterfaceCount(), 0);
// valid interface
UsbInterface interface;
config.GetInterface(0, interface);
EXPECT_NE(interface.GetClass(), 0);
EXPECT_NE(interface.GetEndpointCount(), 0);
// valid endpoint
auto endpoint = interface.GetEndpoint(0);
EXPECT_NE(endpoint.value().GetAttributes(), 0);
}
/**
* @tc.name: usbDeviceDetached
* @tc.desc: usb device detached event
* @tc.type: FUNC
*/
HWTEST_F(UsbEventTest, usbDeviceDetached, TestSize.Level1)
{
MatchingSkills matchingSkills;
matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_USB_DEVICE_DETACHED);
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
std::shared_ptr<UsbSubscriberTest> subscriber = std::make_shared<UsbSubscriberTest>(subscriberInfo);
CommonEventManager::SubscribeCommonEvent(subscriber);
std::cout << "please disconnect the device to the host" << std::endl;
// block until UsbSubscriberTest post
sem_wait(&UsbEventTest::testSem_);
CommonEventManager::UnSubscribeCommonEvent(subscriber);
auto &want = UsbSubscriberTest::eventData_.GetWant();
EXPECT_EQ(want.GetAction(), CommonEventSupport::COMMON_EVENT_USB_DEVICE_DETACHED);
std::string deviceStr = UsbSubscriberTest::eventData_.GetData();
std::cout << deviceStr << std::endl;
Json::CharReaderBuilder builder;
JSONCPP_STRING err;
const std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
Json::Value deviceJson;
auto parseResult = reader->parse(deviceStr.c_str(), deviceStr.c_str() + deviceStr.length(), &deviceJson, &err);
EXPECT_TRUE(parseResult);
// valid device
UsbDevice device(deviceJson);
EXPECT_NE(device.GetiProduct(), 0);
EXPECT_NE(device.GetiManufacturer(), 0);
}
/**
* @tc.name: usbPortChangedToHost
* @tc.desc: usb port change to host event
* @tc.type: FUNC
*/
HWTEST_F(UsbEventTest, usbPortChangedToHost, TestSize.Level1)
{
MatchingSkills matchingSkills;
matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_USB_PORT_CHANGED);
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
std::shared_ptr<UsbSubscriberTest> subscriber = std::make_shared<UsbSubscriberTest>(subscriberInfo);
CommonEventManager::SubscribeCommonEvent(subscriber);
std::cout << "please switch port to host" << std::endl;
// block until UsbSubscriberTest post
sem_wait(&UsbEventTest::testSem_);
CommonEventManager::UnSubscribeCommonEvent(subscriber);
auto &want = UsbSubscriberTest::eventData_.GetWant();
EXPECT_EQ(want.GetAction(), CommonEventSupport::COMMON_EVENT_USB_PORT_CHANGED);
std::string portStr = UsbSubscriberTest::eventData_.GetData();
std::cout << portStr << std::endl;
Json::CharReaderBuilder builder;
JSONCPP_STRING err;
const std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
Json::Value portJson;
auto parseResult = reader->parse(portStr.c_str(), portStr.c_str() + portStr.length(), &portJson, &err);
EXPECT_TRUE(parseResult);
// valid event
EXPECT_EQ(portJson["mode"].asInt(), UsbSrvSupport::PORT_MODE_HOST);
}
/**
* @tc.name: usbPortChangedToDevice
* @tc.desc: usb port change to device event
* @tc.type: FUNC
*/
HWTEST_F(UsbEventTest, usbPortChangedToDevice, TestSize.Level1)
{
MatchingSkills matchingSkills;
matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_USB_PORT_CHANGED);
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
std::shared_ptr<UsbSubscriberTest> subscriber = std::make_shared<UsbSubscriberTest>(subscriberInfo);
CommonEventManager::SubscribeCommonEvent(subscriber);
std::cout << "please switch port to device" << std::endl;
// block until UsbSubscriberTest post
sem_wait(&UsbEventTest::testSem_);
CommonEventManager::UnSubscribeCommonEvent(subscriber);
auto &want = UsbSubscriberTest::eventData_.GetWant();
EXPECT_EQ(want.GetAction(), CommonEventSupport::COMMON_EVENT_USB_PORT_CHANGED);
std::string portStr = UsbSubscriberTest::eventData_.GetData();
std::cout << portStr << std::endl;
Json::CharReaderBuilder builder;
JSONCPP_STRING err;
const std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
Json::Value portJson;
auto parseResult = reader->parse(portStr.c_str(), portStr.c_str() + portStr.length(), &portJson, &err);
EXPECT_TRUE(parseResult);
// valid event
EXPECT_EQ(portJson["mode"].asInt(), UsbSrvSupport::PORT_MODE_DEVICE);
}
} // namespace USB
} // namespace OHOS
+2 -2
View File
@@ -31,7 +31,7 @@ ohos_executable("usb_function_port_test") {
"usb_device_driver:usbd_client",
"utils_base:utils",
]
install_enable = true
install_enable = false
subsystem_name = "usb"
part_name = "usb_manager_native"
part_name = "usb_manager"
}
+2 -2
View File
@@ -47,7 +47,7 @@ static void PrintHelp()
static void GetCurrentFunctionInfo()
{
int32_t funcs = -1;
int32_t funcs = 0;
string strFun = "";
int32_t ret = g_usbClient.GetCurrentFunctions(funcs);
if (ret) {
@@ -128,7 +128,7 @@ int32_t main(int32_t argc, char *argv[])
return 0;
}
int32_t mode;
uint32_t mode;
if ((!strcmp(argv[CMD_INDEX], "-f"))) {
mode = stoi(argv[PARAM_INDEX]);
FunctionSwitch(g_usbClient, mode);