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