summaryrefslogtreecommitdiffstats
path: root/vehicle-signals/QtKuksaClient.cpp
blob: 901459debd9d071f992cdda62115f7774cb51d90 (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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
/*
 * Copyright (C) 2023 Konsulko Group
 *
 * SPDX-License-Identifier: Apache-2.0
 */

#include <QDebug>
#include <QSettings>
#include <QUrl>
#include <QFile>
#include <QtConcurrent>
#include <mutex>
#include <chrono>

#include "QtKuksaClient.h"

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

class QtKuksaClient::SubscribeReader : public grpc::ClientReadReactor<SubscribeResponse> {
public:
	SubscribeReader(VAL::Stub *stub,
			QtKuksaClient *client,
			VehicleSignalsConfig &config,
			const QMap<QString, bool> &s,
			const SubscribeRequest *request):
		client_(client),
		config_(config),
		signals_(s) {
		QString token = config_.authToken();
		if (!token.isEmpty()) {
			token.prepend("Bearer ");
			context_.AddMetadata(std::string("authorization"), token.toStdString());
		}
		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_);
			StartRead(&response_);
		}
	}
	void OnDone(const Status& s) override {
		status_ = s;
		if (client_) {
			if (config_.verbose() > 1)
				qDebug() << "QtKuksaClient::subscribe::Reader done";
			client_->handleSubscribeDone(signals_, status_);
		}

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

private:
	QtKuksaClient *client_;
	VehicleSignalsConfig config_;
	QMap<QString, bool> signals_;

	ClientContext context_;
	SubscribeResponse response_;
	std::mutex mutex_;
	Status status_;
};

QtKuksaClient::QtKuksaClient(const std::shared_ptr< ::grpc::ChannelInterface>& channel,
			     const VehicleSignalsConfig &config,
			     QObject *parent) :
	QObject(parent),
	m_channel(channel),
	m_config(config),
	m_connected(false)
{
        m_stub = VAL::NewStub(channel);

}

void QtKuksaClient::connect()
{
	// Check for connection in another thread
	QFuture<void> future = QtConcurrent::run(this, &QtKuksaClient::waitForConnected);
}

void QtKuksaClient::get(const QString &path, const bool actuator)
{
	m_connected_mutex.lock();
	if (!m_connected) {
		m_connected_mutex.unlock();
		return;
	}
	m_connected_mutex.unlock();
	
	ClientContext *context = new ClientContext();
	if (!context) {
		handleCriticalFailure("Could not create ClientContext");
		return;
	}
	QString token = m_config.authToken();
	if (!token.isEmpty()) {
		token.prepend("Bearer ");
		context->AddMetadata(std::string("authorization"), token.toStdString());
	}

	GetRequest request;
	auto entry = request.add_entries();
	entry->set_path(path.toStdString());
	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, context, response](Status s) {
				     if (s.ok())
					     handleGetResponse(response);
				     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 QtKuksaClient::set(const QString &path, const QString &value, const bool actuator)
{
	Datapoint dp;
	dp.set_string(value.toStdString());
	set(path, dp, actuator);
}

void QtKuksaClient::set(const QString &path, const qint32 value, const bool actuator)
{
	Datapoint dp;
	dp.set_int32(value);
	set(path, dp, actuator);
}

void QtKuksaClient::set(const QString &path, const qint64 value, const bool actuator)
{
	Datapoint dp;
	dp.set_int64(value);
	set(path, dp, actuator);
}

void QtKuksaClient::set(const QString &path, const quint32 value, const bool actuator)
{
	Datapoint dp;
	dp.set_uint32(value);
	set(path, dp, actuator);
}

void QtKuksaClient::set(const QString &path, const quint64 value, const bool actuator)
{
	Datapoint dp;
	dp.set_uint64(value);
	set(path, dp, actuator);
}

void QtKuksaClient::set(const QString &path, const float value, const bool actuator)
{
	Datapoint dp;
	dp.set_float_(value);
	set(path, dp, actuator);
}

void QtKuksaClient::set(const QString &path, const double value, const bool actuator)
{
	Datapoint dp;
	dp.set_double_(value);
	set(path, dp, actuator);
}

void QtKuksaClient::subscribe(const QString &path, const bool actuator)
{
	m_connected_mutex.lock();
	if (!m_connected) {
		m_connected_mutex.unlock();
		return;
	}
	m_connected_mutex.unlock();

	QMap<QString, bool> s;
	s[path] = actuator;
	subscribe(s);
}

void QtKuksaClient::subscribe(const QMap<QString, bool> &signals_)
{
	m_connected_mutex.lock();
	if (!m_connected) {
		m_connected_mutex.unlock();
		return;
	}
	m_connected_mutex.unlock();

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

	auto it = signals_.constBegin();
	while (it != signals_.constEnd()) {
		if (m_config.verbose() > 1)
			qDebug() << "QtKuksaClient::subscribe: adding " << it.key() << ", actuator " << it.value();
		auto entry = request->add_entries();
		entry->set_path(it.key().toStdString());
		entry->add_fields(Field::FIELD_PATH);	
		if (it.value())
			entry->add_fields(Field::FIELD_ACTUATOR_TARGET);
		else
			entry->add_fields(Field::FIELD_VALUE);
		++it;
	}

	SubscribeReader *reader = new SubscribeReader(m_stub.get(), this, m_config, signals_, request);
	if (!reader)
		handleCriticalFailure("Could not create SubscribeReader");

	delete request;
}

// Private

void QtKuksaClient::waitForConnected()
{
	while (!m_channel->WaitForConnected(std::chrono::system_clock::now() +
					  std::chrono::milliseconds(500)));

	m_connected_mutex.lock();
	m_connected = true;
	m_connected_mutex.unlock();

	qInfo() << "Databroker gRPC channel ready";
	emit connected();
}

void QtKuksaClient::set(const QString &path, const Datapoint &dp, const bool actuator)
{
	m_connected_mutex.lock();
	if (!m_connected) {
		m_connected_mutex.unlock();
		return;
	}
	m_connected_mutex.unlock();

	ClientContext *context = new ClientContext();
	if (!context) {
		handleCriticalFailure("Could not create ClientContext");
		return;
	}
	QString token = m_config.authToken();
	if (!token.isEmpty()) {
		token.prepend("Bearer ");
		context->AddMetadata(std::string("authorization"), token.toStdString());
	}

	SetRequest request;
	auto update = request.add_updates();
	auto entry = update->mutable_entry();
	entry->set_path(path.toStdString());
	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, context, response](Status s) {
					       if (s.ok())
						       handleSetResponse(response);
					       delete response;
					       delete context;
				       });
}

void QtKuksaClient::handleGetResponse(const GetResponse *response)
{
	if (!(response && response->entries_size()))
		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();

		QString path = QString::fromStdString(it->path());
		QString value;
		QString timestamp;		
		if (convertDatapoint(dp, value, timestamp)) {
			if (m_config.verbose() > 1)
				qDebug() << "QtKuksaClient::handleGetResponse: path = " << path << ", value = " << value;

			emit getResponse(path, value, timestamp);
		}
	}
}

void QtKuksaClient::handleSetResponse(const SetResponse *response)
{
	if (!(response && response->errors_size()))
		return;

	for (auto it = response->errors().begin(); it != response->errors().end(); ++it) {
		QString path = QString::fromStdString(it->path());
		QString error = QString::fromStdString(it->error().reason());
		emit setResponse(path, error);
	}

}

void QtKuksaClient::handleSubscribeResponse(const SubscribeResponse *response)
{
	if (!(response && response->updates_size()))
		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();
		QString path = QString::fromStdString(entry.path());

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

		QString value;
		QString timestamp;		
		if (convertDatapoint(dp, value, timestamp)) {
			if (m_config.verbose() > 1)
				qDebug() << "QtKuksaClient::handleSubscribeResponse: path = " << path << ", value = " << value;
	
			emit subscribeResponse(path, value, timestamp);
		}
	}
}

void QtKuksaClient::handleSubscribeDone(const QMap<QString, bool> &signals_, const Status &status)
{
	qInfo() << "QtKuksaClient::handleSubscribeDone: enter";
	if (m_config.verbose() > 1)
		qDebug() << "Subscribe status = " << status.error_code() <<
			" (" << QString::fromStdString(status.error_message()) << ")";

	emit subscribeDone(signals_, status.error_code() == grpc::CANCELLED);
}

bool QtKuksaClient::convertDatapoint(const Datapoint &dp, QString &value, QString &timestamp)
{
	// NOTE: Currently no array type support

	if (dp.has_string())
		value = QString::fromStdString(dp.string());
	else if (dp.has_int32())
		value = QString::number(dp.int32());
	else if (dp.has_int64())
		value = QString::number(dp.int64());
	else if (dp.has_uint32())
		value = QString::number(dp.uint32());
	else if (dp.has_uint64())
		value = QString::number(dp.uint64());
	else if (dp.has_float_())
		value = QString::number(dp.float_(), 'f', 6);
	else if (dp.has_double_())
		value = QString::number(dp.double_(), 'f', 6);
	else if (dp.has_bool_())
		value = dp.bool_() ? "true" : "false";
	else {
		if (m_config.verbose())
			qWarning() << "Malformed response (unsupported value type)";
		return false;
	}

	timestamp = QString::number(dp.timestamp().seconds()) + "." + QString::number(dp.timestamp().nanos());
	return true;
}

void QtKuksaClient::handleCriticalFailure(const QString &error)
{
	if (error.size())
		qCritical() << error;
}