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 <chre.h>
29 #include <shared/nano_string.h>
30 #include <shared/send_message.h>
31
32 namespace chre {
33 namespace {
34
35 using nanoapp_testing::sendFatalFailureToHost;
36
messageFreeCallback(void * message,size_t size)37 void messageFreeCallback(void *message, size_t size) {
38 chreHeapFree(message);
39 }
40
nanoappHandleEvent(uint32_t senderInstanceId,uint16_t eventType,const void * eventData)41 extern "C" void nanoappHandleEvent(uint32_t senderInstanceId,
42 uint16_t eventType,
43 const void* eventData) {
44 if (eventType == CHRE_EVENT_MESSAGE_FROM_HOST) {
45 auto *msg = static_cast<const chreMessageFromHostData *>(eventData);
46
47 if (senderInstanceId != CHRE_INSTANCE_ID) {
48 sendFatalFailureToHost("Invalid sender instance ID:", &senderInstanceId);
49 }
50
51 uint8_t *messageBuffer =
52 static_cast<uint8_t*>(chreHeapAlloc(msg->messageSize));
53 if (msg->messageSize != 0 && messageBuffer == nullptr) {
54 sendFatalFailureToHost("Failed to allocate memory for message buffer");
55 }
56
57 std::memcpy(static_cast<void*>(messageBuffer), const_cast<void*>(msg->message),
58 msg->messageSize);
59
60 if (!chreSendMessageToHostEndpoint(
61 static_cast<void*>(messageBuffer), msg->messageSize,
62 msg->messageType, msg->hostEndpoint, messageFreeCallback)) {
63 sendFatalFailureToHost("Failed to send message to host");
64 }
65 }
66 }
67
nanoappStart(void)68 extern "C" bool nanoappStart(void) {
69 return true;
70 }
71
nanoappEnd(void)72 extern "C" void nanoappEnd(void) {
73 }
74
75 } // anonymous namespace
76 } // namespace chre
77