1 /*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 /**
18 * A simple nanoapp to echoes a message from the host.
19 *
20 * This nanoapp will send received messages back to the host endpoint with the
21 * same message contents.
22 */
23
24 #include <cinttypes>
25 #include <cstdint>
26 #include <cstring>
27
28 #include <shared/macros.h>
29 #include <shared/nano_string.h>
30 #include <shared/send_message.h>
31
32 #include "chre/util/macros.h"
33 #include "chre_api/chre.h"
34
35 namespace chre {
36 namespace {
37
messageFreeCallback(void * message,size_t size)38 void messageFreeCallback(void *message, size_t size) {
39 UNUSED_VAR(size);
40
41 chreHeapFree(message);
42 }
43
nanoappHandleEvent(uint32_t senderInstanceId,uint16_t eventType,const void * eventData)44 extern "C" void nanoappHandleEvent(uint32_t senderInstanceId,
45 uint16_t eventType, const void *eventData) {
46 if (eventType == CHRE_EVENT_MESSAGE_FROM_HOST) {
47 auto *msg = static_cast<const chreMessageFromHostData *>(eventData);
48
49 if (senderInstanceId != CHRE_INSTANCE_ID) {
50 EXPECT_FAIL_RETURN("Invalid sender instance ID:", &senderInstanceId);
51 }
52
53 uint8_t *messageBuffer =
54 static_cast<uint8_t *>(chreHeapAlloc(msg->messageSize));
55 if (msg->messageSize != 0 && messageBuffer == nullptr) {
56 EXPECT_FAIL_RETURN("Failed to allocate memory for message buffer");
57 }
58
59 std::memcpy(static_cast<void *>(messageBuffer),
60 const_cast<void *>(msg->message), msg->messageSize);
61
62 if (!chreSendMessageToHostEndpoint(
63 static_cast<void *>(messageBuffer), msg->messageSize,
64 msg->messageType, msg->hostEndpoint, messageFreeCallback)) {
65 EXPECT_FAIL_RETURN("Failed to send message to host");
66 }
67 }
68 }
69
nanoappStart(void)70 extern "C" bool nanoappStart(void) {
71 return true;
72 }
73
nanoappEnd(void)74 extern "C" void nanoappEnd(void) {}
75
76 } // anonymous namespace
77 } // namespace chre
78