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 #include "lnn_node_weight.h"
17
18 #include <string.h>
19
20 #include "bus_center_manager.h"
21 #include "lnn_device_info.h"
22 #include "lnn_log.h"
23 #include "softbus_adapter_crypto.h"
24 #include "softbus_def.h"
25 #include "softbus_error_code.h"
26
27 #define MAX_WEIGHT_VALUE 1000
28 #define BASE_WEIGHT_PHONE_VALUE 2000
29 #define BASE_WEIGHT_PAD_VALUE 3000
30 #define BASE_WEIGHT_TV_VALUE 8000
31 #define BASE_WEIGHT_AUDIO_VALUE 7000
32 #define BASE_WEIGHT_CAR_VALUE 5000
33 #define BASE_WEIGHT_PC_VALUE 4000
34
LnnGetLocalWeight(void)35 int32_t LnnGetLocalWeight(void)
36 {
37 static int32_t weight;
38 static bool isGenWeight = false;
39 uint8_t randVal = 0;
40
41 if (isGenWeight) {
42 return weight;
43 }
44 if (SoftBusGenerateRandomArray(&randVal, sizeof(randVal)) != SOFTBUS_OK) {
45 LNN_LOGE(LNN_BUILDER, "generate random weight fail");
46 return randVal;
47 }
48 weight = (int32_t)((randVal * MAX_WEIGHT_VALUE) / UINT8_MAX);
49 int32_t localDevTypeId = 0;
50 if (LnnGetLocalNumInfo(NUM_KEY_DEV_TYPE_ID, &localDevTypeId) != SOFTBUS_OK) {
51 localDevTypeId = 0;
52 }
53 switch (localDevTypeId) {
54 case TYPE_PHONE_ID:
55 weight += BASE_WEIGHT_PHONE_VALUE;
56 break;
57 case TYPE_PAD_ID:
58 weight += BASE_WEIGHT_PAD_VALUE;
59 break;
60 case TYPE_TV_ID:
61 weight += BASE_WEIGHT_TV_VALUE;
62 break;
63 case TYPE_AUDIO_ID:
64 weight += BASE_WEIGHT_AUDIO_VALUE;
65 break;
66 case TYPE_CAR_ID:
67 weight += BASE_WEIGHT_CAR_VALUE;
68 break;
69 case TYPE_PC_ID:
70 weight += BASE_WEIGHT_PC_VALUE;
71 break;
72 default:
73 break;
74 }
75 LNN_LOGD(LNN_BUILDER, "generate local weight=%{public}d", weight);
76 isGenWeight = true;
77 return weight;
78 }
79
LnnCompareNodeWeight(int32_t weight1,const char * masterUdid1,int32_t weight2,const char * masterUdid2)80 int32_t LnnCompareNodeWeight(int32_t weight1, const char *masterUdid1, int32_t weight2,
81 const char *masterUdid2)
82 {
83 if (weight1 != weight2) {
84 return weight1 - weight2;
85 }
86 if (masterUdid1 == NULL || masterUdid2 == NULL) {
87 LNN_LOGE(LNN_BUILDER, "nullptr");
88 return weight1 - weight2;
89 }
90 return strcmp(masterUdid1, masterUdid2);
91 }