1 /*
2  * Copyright (c) 2021 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 #ifndef OHOS_DISTRIBUTED_HARDWARE_CAPABILITY_UTILS_H
17 #define OHOS_DISTRIBUTED_HARDWARE_CAPABILITY_UTILS_H
18 
19 #include <cstdint>
20 #include <memory>
21 #include <string>
22 
23 #include "capability_info.h"
24 #include "distributed_hardware_log.h"
25 
26 #undef DH_LOG_TAG
27 #define DH_LOG_TAG "CapabilityUtils"
28 
29 namespace OHOS {
30 namespace DistributedHardware {
31 class CapabilityInfo;
32 enum class CapabilityInfoFilter : uint32_t {
33     FILTER_DH_ID = 0,
34     FILTER_DEVICE_ID = 1,
35     FILTER_DEVICE_NAME = 2,
36     FILTER_DEVICE_TYPE = 3,
37     FILTER_DH_TYPE = 4,
38     FILTER_DH_ATTRS = 5
39 };
40 
41 template<typename T>
GetCapabilityByValue(const std::string & value,std::shared_ptr<T> & capPtr)42 int32_t GetCapabilityByValue(const std::string &value, std::shared_ptr<T> &capPtr)
43 {
44     if (capPtr == nullptr) {
45         capPtr = std::make_shared<T>();
46     }
47     return capPtr->FromJsonString(value);
48 }
49 
50 std::string GetCapabilityKey(const std::string &deviceId, const std::string &dhId);
51 bool IsCapKeyMatchDeviceId(const std::string &key, const std::string &deviceId);
52 
53 template<typename T>
IsCapInfoJsonEqual(const std::string & firstData,const std::string & lastData)54 bool IsCapInfoJsonEqual(const std::string &firstData, const std::string &lastData)
55 {
56     cJSON *firstJson = cJSON_Parse(firstData.c_str());
57     if (firstJson == NULL) {
58         DHLOGE("firstData parse failed");
59         return false;
60     }
61     T firstCapInfo;
62     FromJson(firstJson, firstCapInfo);
63     cJSON *lastJson = cJSON_Parse(lastData.c_str());
64     if (lastJson == NULL) {
65         DHLOGE("lastData parse failed");
66         cJSON_Delete(firstJson);
67         return false;
68     }
69     T lastCapInfo;
70     FromJson(lastJson, lastCapInfo);
71     cJSON_Delete(firstJson);
72     cJSON_Delete(lastJson);
73     return firstCapInfo.Compare(lastCapInfo);
74 }
75 } // namespace DistributedHardware
76 } // namespace OHOS
77 #endif
78