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, const void *eventData) {
43   if (eventType == CHRE_EVENT_MESSAGE_FROM_HOST) {
44     auto *msg = static_cast<const chreMessageFromHostData *>(eventData);
45 
46     if (senderInstanceId != CHRE_INSTANCE_ID) {
47       sendFatalFailureToHost("Invalid sender instance ID:", &senderInstanceId);
48     }
49 
50     uint8_t *messageBuffer =
51         static_cast<uint8_t *>(chreHeapAlloc(msg->messageSize));
52     if (msg->messageSize != 0 && messageBuffer == nullptr) {
53       sendFatalFailureToHost("Failed to allocate memory for message buffer");
54     }
55 
56     std::memcpy(static_cast<void *>(messageBuffer),
57                 const_cast<void *>(msg->message), msg->messageSize);
58 
59     if (!chreSendMessageToHostEndpoint(
60             static_cast<void *>(messageBuffer), msg->messageSize,
61             msg->messageType, msg->hostEndpoint, messageFreeCallback)) {
62       sendFatalFailureToHost("Failed to send message to host");
63     }
64   }
65 }
66 
nanoappStart(void)67 extern "C" bool nanoappStart(void) {
68   return true;
69 }
70 
nanoappEnd(void)71 extern "C" void nanoappEnd(void) {}
72 
73 }  // anonymous namespace
74 }  // namespace chre
75