1 /*
2  * Copyright 2020 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 #include <nos/NuggetClientDebuggable.h>
18 #include <limits>
19 #include <nos/transport.h>
20 #include <application.h>
21 
22 namespace nos {
23 
NuggetClientDebuggable(const char * name,uint32_t config,request_cb_t req_fn,response_cb_t resp_fn)24 NuggetClientDebuggable::NuggetClientDebuggable(
25   const char* name, uint32_t config,
26   request_cb_t req_fn, response_cb_t resp_fn)
27   : NuggetClient(name, config),
28     request_cb_(req_fn), response_cb_(resp_fn) {}
29 
CallApp(uint32_t appId,uint16_t arg,const std::vector<uint8_t> & request,std::vector<uint8_t> * response)30 uint32_t NuggetClientDebuggable::CallApp(uint32_t appId, uint16_t arg,
31                                          const std::vector<uint8_t>& request,
32                                          std::vector<uint8_t>* response) {
33   if (!open_) {
34     return APP_ERROR_IO;
35   }
36 
37   if (request.size() > std::numeric_limits<uint32_t>::max()) {
38     return APP_ERROR_TOO_MUCH;
39   }
40 
41   const uint32_t requestSize = request.size();
42   uint32_t replySize = 0;
43   uint8_t* replyData = nullptr;
44 
45   if (response != nullptr) {
46     response->resize(response->capacity());
47     replySize = response->size();
48     replyData = response->data();
49   }
50 
51   if (request_cb_) {
52     (request_cb_)(request);
53   }
54 
55   uint32_t status_code = nos_call_application(&device_, appId, arg,
56                                               request.data(), requestSize,
57                                               replyData, &replySize);
58 
59   if (response != nullptr) {
60     response->resize(replySize);
61     if (response_cb_) {
62       (response_cb_)(status_code, *response);
63     }
64   }
65 
66   return status_code;
67 }
68 
69 }  // namespace nos
70