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 "core/common/platform_bridge.h"
17
18 #include "base/log/log.h"
19 #include "base/utils/utils.h"
20 #include "frameworks/bridge/codec/function_call.h"
21 #include "frameworks/bridge/codec/standard_function_codec.h"
22
23 namespace OHOS::Ace {
24
25 const char INTERNAL_MODULE_GROUP[] = "AcePluginGroup/FeatureAbility";
26 const char FUNCTION_NAME[] = "callAbility";
27
28 using namespace Framework;
29
SendMessage(const std::vector<CodecData> & args,const PlatformCallbackHandler & handler)30 void PlatformBridge::SendMessage(const std::vector<CodecData>& args, const PlatformCallbackHandler& handler)
31 {
32 int32_t callbackId = callbackIds_++;
33 auto result = callBackHandlers_.try_emplace(callbackId, handler);
34 if (!result.second) {
35 LOGE("module callback function has been existed!");
36 return;
37 }
38
39 FunctionCall functionCall(FUNCTION_NAME, args);
40 StandardFunctionCodec codec;
41 std::vector<uint8_t> dataBuf;
42 codec.EncodeFunctionCall(functionCall, dataBuf);
43
44 auto dispatcher = dispatcher_.Upgrade();
45 CHECK_NULL_VOID(dispatcher);
46 dispatcher->Dispatch(INTERNAL_MODULE_GROUP, std::move(dataBuf), callbackId, true);
47 }
48
HandleCallback(int32_t callbackId,std::vector<uint8_t> && messageData)49 void PlatformBridge::HandleCallback(int32_t callbackId, std::vector<uint8_t>&& messageData)
50 {
51 std::string resultString;
52 CodecData codecResult;
53 StandardFunctionCodec codec;
54 if (codec.DecodePlatformMessage(messageData, codecResult)) {
55 resultString = codecResult.GetStringValue();
56 if (resultString.empty()) {
57 LOGE("reply message is empty!");
58 return;
59 }
60 } else {
61 LOGE("decode platform reply message failed!");
62 return;
63 }
64
65 auto itFunc = callBackHandlers_.find(callbackId);
66 if (itFunc != callBackHandlers_.end()) {
67 auto handler = itFunc->second;
68 if (handler) {
69 handler(resultString);
70 }
71 callBackHandlers_.erase(itFunc);
72 }
73 }
74
75 } // namespace OHOS::Ace
76