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 #include <nos/NuggetClient.h>
18 #include <limits>
19 #include <nos/transport.h>
20 #include <application.h>
21
22 namespace nos {
23
NuggetClient(const std::string & name)24 NuggetClient::NuggetClient(const std::string& name)
25 : device_name_(name), open_(false) {
26 }
27
NuggetClient(const char * name,uint32_t config)28 NuggetClient::NuggetClient(const char* name, uint32_t config)
29 : device_name_(name ? name : ""), open_(false) {
30 device_ = { .config = config };
31 }
32
~NuggetClient()33 NuggetClient::~NuggetClient() {
34 Close();
35 }
36
Open()37 void NuggetClient::Open() {
38 if (!open_) {
39 open_ = nos_device_open(
40 device_name_.empty() ? nullptr : device_name_.c_str(), &device_) == 0;
41 }
42 }
43
Close()44 void NuggetClient::Close() {
45 if (open_) {
46 device_.ops.close(device_.ctx);
47 open_ = false;
48 }
49 }
50
IsOpen() const51 bool NuggetClient::IsOpen() const {
52 return open_;
53 }
54
CallApp(uint32_t appId,uint16_t arg,const std::vector<uint8_t> & request,std::vector<uint8_t> * response)55 uint32_t NuggetClient::CallApp(uint32_t appId, uint16_t arg,
56 const std::vector<uint8_t>& request,
57 std::vector<uint8_t>* response) {
58 if (!open_) {
59 return APP_ERROR_IO;
60 }
61
62 if (request.size() > std::numeric_limits<uint32_t>::max()) {
63 return APP_ERROR_TOO_MUCH;
64 }
65
66 const uint32_t requestSize = request.size();
67 uint32_t replySize = 0;
68 uint8_t* replyData = nullptr;
69
70 if (response != nullptr) {
71 response->resize(response->capacity());
72 replySize = response->size();
73 replyData = response->data();
74 }
75
76 uint32_t status_code = nos_call_application(&device_, appId, arg,
77 request.data(), requestSize,
78 replyData, &replySize);
79
80 if (response != nullptr) {
81 response->resize(replySize);
82 }
83
84 return status_code;
85 }
86
Reset() const87 uint32_t NuggetClient::Reset() const {
88
89 if (!open_)
90 return APP_ERROR_NOT_READY;
91
92 return device_.ops.reset(device_.ctx);
93 }
94
Device()95 nos_device* NuggetClient::Device() {
96 return open_ ? &device_ : nullptr;
97 }
98
Device() const99 const nos_device* NuggetClient::Device() const {
100 return open_ ? &device_ : nullptr;
101 }
102
DeviceName() const103 const std::string& NuggetClient::DeviceName() const {
104 return device_name_;
105 }
106
107 } // namespace nos
108