summaryrefslogtreecommitdiffstats
path: root/src/KuksaClient.cpp
blob: 844ce0ed8079d6ff4d07dd841fa0c7a874d90028 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
/*
 * Copyright (C) 2023 Konsulko Group
 *
 * SPDX-License-Identifier: Apache-2.0
 */

#include <string>
#include <regex>
#include <iterator>
#include <mutex>

#include "KuksaClient.h"

using grpc::Channel;
using grpc::ClientContext;
using grpc::ClientReader;
using grpc::Status;

KuksaClient::KuksaClient(const std::shared_ptr< ::grpc::ChannelInterface>& channel, const KuksaConfig &config) :
	m_config(config)
{
	m_stub = VAL::NewStub(channel);
}

void KuksaClient::get(const std::string &path, GetResponseCallback cb, const bool actuator)
{
	ClientContext *context = new ClientContext();
	if (!context) {
		handleCriticalFailure("Could not create ClientContext");
		return;
	}
	std::string token = m_config.authToken();
	if (!token.empty()) {
		token.insert(0, std::string("Bearer "));
		context->AddMetadata(std::string("authorization"), token);
	}

	GetRequest request;
	auto entry = request.add_entries();
	entry->set_path(path);
	entry->add_fields(Field::FIELD_PATH);	
	if (actuator)
		entry->add_fields(Field::FIELD_ACTUATOR_TARGET);
	else
		entry->add_fields(Field::FIELD_VALUE);

	GetResponse *response = new GetResponse();
	if (!response) {
		handleCriticalFailure("Could not create GetResponse");
		return;
	}

	// NOTE: Using ClientUnaryReactor instead of the shortcut method
	//       would allow getting detailed errors.
	m_stub->async()->Get(context, &request, response,
			     [this, cb, context, response](Status s) {
				     if (s.ok())
					     handleGetResponse(response, cb);
				     delete response;
				     delete context;
			     });
}

// Since a set request needs a Datapoint with the appropriate type value,
// checking the signal metadata to get the type would be a requirement for
// a generic set call that takes a string as argument.  For now, assume
// that set with a string is specifically for a signal of string type.

void KuksaClient::set(const std::string &path, const std::string &value, SetResponseCallback cb, const bool actuator)
{
	Datapoint dp;
	dp.set_string(value);
	set(path, dp, cb, actuator);
}

void KuksaClient::set(const std::string &path, const int8_t value, SetResponseCallback cb, const bool actuator)
{
	Datapoint dp;
	dp.set_int32(value);
	set(path, dp, cb, actuator);
}

void KuksaClient::set(const std::string &path, const int16_t value, SetResponseCallback cb, const bool actuator)
{
	Datapoint dp;
	dp.set_int32(value);
	set(path, dp, cb, actuator);
}

void KuksaClient::set(const std::string &path, const int32_t value, SetResponseCallback cb, const bool actuator)
{
	Datapoint dp;
	dp.set_int32(value);
	set(path, dp, cb, actuator);
}

void KuksaClient::set(const std::string &path, const int64_t value, SetResponseCallback cb, const bool actuator)
{
	Datapoint dp;
	dp.set_int64(value);
	set(path, dp, cb, actuator);
}

void KuksaClient::set(const std::string &path, const uint8_t value, SetResponseCallback cb, const bool actuator)
{
	Datapoint dp;
	dp.set_uint32(value);
	set(path, dp, cb, actuator);
}

void KuksaClient::set(const std::string &path, const uint16_t value, SetResponseCallback cb, const bool actuator)
{
	Datapoint dp;
	dp.set_uint32(value);
	set(path, dp, cb, actuator);
}

void KuksaClient::set(const std::string &path, const uint32_t value, SetResponseCallback cb, const bool actuator)
{
	Datapoint dp;
	dp.set_uint32(value);
	set(path, dp, cb, actuator);
}

void KuksaClient::set(const std::string &path, const uint64_t value, SetResponseCallback cb, const bool actuator)
{
	Datapoint dp;
	dp.set_uint64(value);
	set(path, dp, cb, actuator);
}

void KuksaClient::set(const std::string &path, const float value, SetResponseCallback cb, const bool actuator)
{
	Datapoint dp;
	dp.set_float_(value);
	set(path, dp, cb, actuator);
}

void KuksaClient::set(const std::string &path, const double value, SetResponseCallback cb, const bool actuator)
{
	Datapoint dp;
	dp.set_double_(value);
	set(path, dp, cb, actuator);
}

void KuksaClient::subscribe(const std::string &path,
			    SubscribeResponseCallback cb,
			    const bool actuator,
			    SubscribeDoneCallback done_cb)
{
	SubscribeRequest *request = new SubscribeRequest();
	if (!request) {
		handleCriticalFailure("Could not create SubscribeRequest");
		return;
	}

	auto entry = request->add_entries();
	entry->set_path(path);
	entry->add_fields(Field::FIELD_PATH);	
	if (actuator)
		entry->add_fields(Field::FIELD_ACTUATOR_TARGET);
	else
		entry->add_fields(Field::FIELD_VALUE);

	subscribe(request, cb, done_cb);
}

void KuksaClient::subscribe(const std::map<std::string, bool> signals,
			    SubscribeResponseCallback cb,
			    SubscribeDoneCallback done_cb)
{
	SubscribeRequest *request = new SubscribeRequest();
	if (!request) {
		handleCriticalFailure("Could not create SubscribeRequest");
		return;
	}

	for(auto it = signals.cbegin(); it != signals.cend(); ++it) {
		auto entry = request->add_entries();
		entry->set_path(it->first);
		entry->add_fields(Field::FIELD_PATH);	
		if (it->second)
			entry->add_fields(Field::FIELD_ACTUATOR_TARGET);
		else
			entry->add_fields(Field::FIELD_VALUE);
	}

	subscribe(request, cb, done_cb);
}

void KuksaClient::subscribe(const SubscribeRequest *request,
			    SubscribeResponseCallback cb,
			    SubscribeDoneCallback done_cb)
{
	if (!(request && cb))
		return;

	class Reader : public grpc::ClientReadReactor<SubscribeResponse> {
	public:
		Reader(VAL::Stub *stub,
		       KuksaClient *client,
		       KuksaConfig &config,
		       const SubscribeRequest *request,
		       SubscribeResponseCallback cb,
		       SubscribeDoneCallback done_cb):
			client_(client),
			config_(config),
			request_(request),
			cb_(cb),
			done_cb_(done_cb) {
			std::string token = config_.authToken();
			if (!token.empty()) {
				token.insert(0, std::string("Bearer "));
				context_.AddMetadata(std::string("authorization"), token);
			}
			stub->async()->Subscribe(&context_, request, this);
			StartRead(&response_);
			StartCall();
		}
		void OnReadDone(bool ok) override {
			std::unique_lock<std::mutex> lock(mutex_);
			if (ok) {
				if (client_)
					client_->handleSubscribeResponse(&response_, cb_);
				StartRead(&response_);
			}
		}
		void OnDone(const Status& s) override {
			status_ = s;
			if (client_) {
				if (config_.verbose() > 1)
					std::cerr << "KuksaClient::subscribe::Reader done" << std::endl;
				client_->handleSubscribeDone(request_, status_, done_cb_);
			}

			// gRPC engine is done with us, safe to self-delete
			delete request_;
			delete this;
		}

	private:
		KuksaClient *client_;
		KuksaConfig config_;
		const SubscribeRequest *request_;
		SubscribeResponseCallback cb_;
		SubscribeDoneCallback done_cb_;

		ClientContext context_;
		SubscribeResponse response_;
		std::mutex mutex_;
		Status status_;
	};
	Reader *reader = new Reader(m_stub.get(), this, m_config, request, cb, done_cb);
	if (!reader)
		handleCriticalFailure("Could not create Subscribe reader");
}

// Private

void KuksaClient::set(const std::string &path, const Datapoint &dp, SetResponseCallback cb, const bool actuator)
{
	ClientContext *context = new ClientContext();
	if (!context) {
		handleCriticalFailure("Could not create ClientContext");
		return;
	}
	std::string token = m_config.authToken();
	if (!token.empty()) {
		token.insert(0, std::string("Bearer "));
		context->AddMetadata(std::string("authorization"), token);
	}

	SetRequest request;
	auto update = request.add_updates();
	auto entry = update->mutable_entry();
	entry->set_path(path);
	if (actuator) {
		auto target = entry->mutable_actuator_target();
		*target = dp;
		update->add_fields(Field::FIELD_ACTUATOR_TARGET);
	} else {
		auto value = entry->mutable_value();
		*value = dp;
		update->add_fields(Field::FIELD_VALUE);		
	}

	SetResponse *response = new SetResponse();
	if (!response) {
		handleCriticalFailure("Could not create SetResponse");
		delete context;
		return;
	}

	// NOTE: Using ClientUnaryReactor instead of the shortcut method
	//       would allow getting detailed errors.
	m_stub->async()->Set(context, &request, response,
				       [this, cb, context, response](Status s) {
					       if (s.ok())
						       handleSetResponse(response, cb);
					       delete response;
					       delete context;
				       });
}

void KuksaClient::handleGetResponse(const GetResponse *response, GetResponseCallback cb)
{
	if (!(response && response->entries_size() && cb))
		return;

	for (auto it = response->entries().begin(); it != response->entries().end(); ++it) {
		// We expect paths in the response entries
		if (!it->path().size())
			continue;

		Datapoint dp;
		if (it->has_actuator_target())
			dp = it->actuator_target();
		else
			dp = it->value();
		cb(it->path(), dp);
	}
}

void KuksaClient::handleSetResponse(const SetResponse *response, SetResponseCallback cb)
{
	if (!(response && response->errors_size() && cb))
		return;

	for (auto it = response->errors().begin(); it != response->errors().end(); ++it) {
		cb(it->path(), it->error());
	}

}

void KuksaClient::handleSubscribeResponse(const SubscribeResponse *response, SubscribeResponseCallback cb)
{
	if (!(response && response->updates_size() && cb))
		return;

	for (auto it = response->updates().begin(); it != response->updates().end(); ++it) {
		// We expect entries that have paths in the response
		if (!(it->has_entry() && it->entry().path().size()))
			continue;

		auto entry = it->entry();
		if (m_config.verbose())
			std::cout << "KuksaClient::handleSubscribeResponse: got value for " << entry.path() << std::endl;

		Datapoint dp;
		if (entry.has_actuator_target())
			dp = entry.actuator_target();
		else
			dp = entry.value();

		cb(entry.path(), dp);
	}
}

void KuksaClient::handleSubscribeDone(const SubscribeRequest *request,
				      const Status &status,
				      SubscribeDoneCallback cb)
{
	if (cb)
		cb(request, status);
}

void KuksaClient::handleCriticalFailure(const std::string &error)
{
	if (error.size())
		std::cerr << error << std::endl;
	exit(1);
}