• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2025 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include <iostream>
17 #include <sstream>
18 #include "usb_device_info_parser.h"
19 
20 typedef enum {
21     POSTION_ONE = 1,
22     POSTION_TWO = 2,
23 } POSITION;
24 
UsbDeviceInfoParser()25 UsbDeviceInfoParser::UsbDeviceInfoParser()
26     : devInfoRegex_(".*Bus=([0-9]+).*Dev#=\\s*([0-9]+).*")
27 {
28 }
29 
Find(const std::string & productRegex)30 std::optional<UsbDeviceInfo> UsbDeviceInfoParser::Find(const std::string& productRegex)
31 {
32     std::ifstream filePath("/sys/kernel/debug/usb/devices");
33     std::string line;
34     UsbDeviceInfo deviceInfo;
35     const std::string prefix = "S:  Product=";
36     while (std::getline(filePath, line)) {
37         if (line.empty()) {
38             continue;
39         }
40 
41         if (line[0] == 'T') {
42             std::smatch match;
43             if (!std::regex_match(line, match, devInfoRegex_)) {
44                 std::cout << __func__ << ":" << __LINE__ << " regex_match failed" << std::endl;
45                 return std::nullopt;
46             }
47 
48             deviceInfo.busNum = std::stoi(match.str(POSTION_ONE));
49             deviceInfo.devNum = std::stoi(match.str(POSTION_TWO));
50         }
51 
52         if (line.find(prefix) == std::string::npos) {
53             continue;
54         }
55 
56         auto product = line.substr(prefix.size(), line.size());
57         std::smatch match;
58         if (!std::regex_match(product, match, std::regex(productRegex))) {
59             std::cout << __func__ << ":" << __LINE__ << " regex_match [" << product << "] with ["
60                 << productRegex << "] failed" << std::endl;
61             continue;
62         }
63         deviceInfo.productNum = product;
64         return std::optional<UsbDeviceInfo>(deviceInfo);
65     }
66 
67     return std::nullopt;
68 }
69