• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022 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 #define LOG_TAG "CommunicationStrategy"
17 #include "communication_strategy.h"
18 #include "log_print.h"
19 #include "kvstore_utils.h"
20 
21 namespace OHOS {
22 namespace AppDistributedKv {
GetInstance()23 CommunicationStrategy &CommunicationStrategy::GetInstance()
24 {
25     static CommunicationStrategy instance;
26     return instance;
27 }
28 
RegGetSyncDataSize(const std::string & type,const std::function<size_t (const std::string &)> & getDataSize)29 void CommunicationStrategy::RegGetSyncDataSize(const std::string &type,
30     const std::function<size_t(const std::string &)> &getDataSize)
31 {
32     calcDataSizes_.InsertOrAssign(type, getDataSize);
33 }
34 
CalcSyncDataSize(const std::string & deviceId)35 size_t CommunicationStrategy::CalcSyncDataSize(const std::string &deviceId)
36 {
37     size_t dataSize = 0;
38     calcDataSizes_.ForEach([&dataSize, &deviceId](const std::string &key, auto &value) {
39         if (value) {
40             dataSize += value(deviceId);
41         }
42         return false;
43     });
44     ZLOGD("calc data size:%{public}zu.", dataSize);
45     return dataSize;
46 }
47 
SetStrategy(const std::string & deviceId,Strategy strategy,const std::function<void (const std::string &,Strategy)> & action)48 void CommunicationStrategy::SetStrategy(const std::string &deviceId, Strategy strategy,
49                                         const std::function<void(const std::string &, Strategy)> &action)
50 {
51     auto value = strategy;
52     if (strategy == Strategy::ON_LINE_SELECT_CHANNEL && CalcSyncDataSize(deviceId) < SWITCH_CONNECTION_THRESHOLD) {
53         value = Strategy::DEFAULT;
54     }
55     if (action) {
56         action(deviceId, value);
57     }
58     strategys_.InsertOrAssign(deviceId, value);
59     return ;
60 }
61 
GetStrategy(const std::string & deviceId)62 CommunicationStrategy::Strategy CommunicationStrategy::GetStrategy(const std::string &deviceId)
63 {
64     auto result = strategys_.Find(deviceId);
65     if (!result.first) {
66         return Strategy::DEFAULT;
67     }
68 
69     return result.second;
70 }
71 }  // namespace AppDistributedKv
72 }  // namespace OHOS