1 /*
2  * Copyright (c) 2023-2024 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 "network_collector_impl.h"
17 
18 #include "hiview_logger.h"
19 #include "network_decorator.h"
20 #ifdef COMMUNICATION_WIFI_ENABLE
21 #include "wifi_device.h"
22 #endif
23 
24 using namespace OHOS::HiviewDFX::UCollect;
25 
26 namespace OHOS {
27 namespace HiviewDFX {
28 namespace UCollectUtil {
29 DEFINE_LOG_TAG("UCollectUtil");
30 
Create()31 std::shared_ptr<NetworkCollector> NetworkCollector::Create()
32 {
33     return std::make_shared<NetworkDecorator>(std::make_shared<NetworkCollectorImpl>());
34 }
35 
36 #ifdef COMMUNICATION_WIFI_ENABLE
GetNetworkInfo(Wifi::WifiLinkedInfo & linkInfo)37 bool GetNetworkInfo(Wifi::WifiLinkedInfo& linkInfo)
38 {
39     std::shared_ptr<Wifi::WifiDevice> wifiDevicePtr = Wifi::WifiDevice::GetInstance(OHOS::WIFI_DEVICE_SYS_ABILITY_ID);
40     if (wifiDevicePtr == nullptr) {
41         return false;
42     }
43     bool isActive = false;
44     wifiDevicePtr->IsWifiActive(isActive);
45     if (!isActive) {
46         return false;
47     }
48     int ret = wifiDevicePtr->GetLinkedInfo(linkInfo);
49     if (ret != Wifi::WIFI_OPT_SUCCESS) {
50         HIVIEW_LOGE("GetLinkedInfo failed");
51         return false;
52     } else {
53         return true;
54     }
55 }
56 #endif
57 
CollectRate()58 CollectResult<NetworkRate> NetworkCollectorImpl::CollectRate()
59 {
60     CollectResult<NetworkRate> result;
61 #ifdef COMMUNICATION_WIFI_ENABLE
62     Wifi::WifiLinkedInfo linkInfo;
63     if (GetNetworkInfo(linkInfo)) {
64         NetworkRate& networkRate = result.data;
65         networkRate.rssi = linkInfo.rssi;
66         HIVIEW_LOGD("rssi = %d", networkRate.rssi);
67         networkRate.txBitRate = linkInfo.txLinkSpeed;
68         HIVIEW_LOGD("txBitRate = %d", networkRate.txBitRate);
69         networkRate.rxBitRate = linkInfo.rxLinkSpeed;
70         HIVIEW_LOGD("rxBitRate = %d", networkRate.rxBitRate);
71         result.retCode = UcError::SUCCESS;
72     } else {
73         HIVIEW_LOGE("IsWifiActive failed");
74         result.retCode = UcError::UNSUPPORT;
75     }
76 #endif
77     return result;
78 }
79 } // UCollectUtil
80 } // HiViewDFX
81 } // OHOS
82