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