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