-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathadapterclient.cpp
More file actions
391 lines (354 loc) · 12.8 KB
/
adapterclient.cpp
File metadata and controls
391 lines (354 loc) · 12.8 KB
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
#include "ProtocolAdapter/adapterclient.h"
#include "util/scopelogging.h"
#include <QJsonArray>
AdapterClient::AdapterClient(AdapterProcess* pProcess, QObject* parent, int handshakeTimeoutMs)
: QObject(parent), _pProcess(pProcess), _handshakeTimeoutMs(handshakeTimeoutMs)
{
Q_ASSERT(pProcess);
_pProcess->setParent(this);
_handshakeTimer.setSingleShot(true);
connect(&_handshakeTimer, &QTimer::timeout, this, &AdapterClient::onHandshakeTimeout);
connect(_pProcess, &AdapterProcess::responseReceived, this, &AdapterClient::onResponseReceived);
connect(_pProcess, &AdapterProcess::errorReceived, this, &AdapterClient::onErrorReceived);
connect(_pProcess, &AdapterProcess::processError, this, &AdapterClient::onProcessError);
connect(_pProcess, &AdapterProcess::processFinished, this, &AdapterClient::onProcessFinished);
connect(_pProcess, &AdapterProcess::notificationReceived, this, &AdapterClient::onNotificationReceived);
}
AdapterClient::~AdapterClient() = default;
void AdapterClient::prepareAdapter(const QString& adapterPath)
{
if (_state != State::IDLE)
{
qCWarning(scopeComm) << "AdapterClient: prepareAdapter called in non-idle state";
return;
}
if (!_pProcess->start(adapterPath))
{
return;
}
qCInfo(scopeComm) << "AdapterClient: process started, sending initialize";
_state = State::INITIALIZING;
_handshakeTimer.start(_handshakeTimeoutMs);
_pProcess->sendRequest("adapter.initialize", QJsonObject());
}
void AdapterClient::provideConfig(QJsonObject config, QStringList registerExpressions)
{
if (_state != State::AWAITING_CONFIG)
{
qCWarning(scopeComm) << "AdapterClient: provideConfig called in unexpected state" << static_cast<int>(_state);
return;
}
_pendingExpressions = registerExpressions;
_pendingConfig = config;
_pendingAuxRequests.clear();
_state = State::CONFIGURING;
_handshakeTimer.start(_handshakeTimeoutMs);
QJsonObject params;
params["config"] = _pendingConfig;
_pProcess->sendRequest("adapter.configure", params);
}
void AdapterClient::requestReadData()
{
if (_state != State::ACTIVE)
{
qCWarning(scopeComm) << "AdapterClient: requestReadData called in non-active state";
return;
}
_pProcess->sendRequest("adapter.readData", QJsonObject());
}
void AdapterClient::requestStatus()
{
if (_state != State::ACTIVE)
{
qCWarning(scopeComm) << "AdapterClient: requestStatus called in non-active state";
return;
}
_pProcess->sendRequest("adapter.getStatus", QJsonObject());
}
/*!
* \brief Request the adapter's data point schema while awaiting configuration.
*/
void AdapterClient::requestDataPointSchema()
{
if (_state != State::AWAITING_CONFIG)
{
qCWarning(scopeComm) << "AdapterClient: requestDataPointSchema called in unexpected state"
<< static_cast<int>(_state);
return;
}
_pendingAuxRequests["adapter.dataPointSchema"] = _pProcess->sendRequest("adapter.dataPointSchema", QJsonObject());
}
/*!
* \brief Request a human-readable description of a data point expression.
* \param expression The data point expression string to describe.
*/
void AdapterClient::describeDataPoint(const QString& expression)
{
if (_state != State::AWAITING_CONFIG && _state != State::ACTIVE)
{
qCWarning(scopeComm) << "AdapterClient: describeDataPoint called in unexpected state"
<< static_cast<int>(_state);
return;
}
QJsonObject params;
params["expression"] = expression;
_pendingAuxRequests["adapter.describeDataPoint"] = _pProcess->sendRequest("adapter.describeDataPoint", params);
}
/*!
* \brief Validate a data point expression string via the adapter.
* \param expression The data point expression string to validate.
*/
void AdapterClient::validateDataPoint(const QString& expression)
{
if (_state != State::AWAITING_CONFIG && _state != State::ACTIVE)
{
qCWarning(scopeComm) << "AdapterClient: validateDataPoint called in unexpected state"
<< static_cast<int>(_state);
return;
}
QJsonObject params;
params["expression"] = expression;
_pendingAuxRequests["adapter.validateDataPoint"] = _pProcess->sendRequest("adapter.validateDataPoint", params);
}
/*!
* \brief Send an adapter.buildExpression request to construct a data point expression string.
* \param addressFields Address field values as returned by the data point schema form.
* \param dataType Data type identifier; omitted from params when empty.
* \param deviceId Device identifier; omitted from params when zero.
*/
void AdapterClient::buildExpression(const QJsonObject& addressFields, const QString& dataType, deviceId_t deviceId)
{
if (_state != State::AWAITING_CONFIG && _state != State::ACTIVE)
{
qCWarning(scopeComm) << "AdapterClient: buildExpression called in unexpected state" << static_cast<int>(_state);
return;
}
QJsonObject params;
params["fields"] = addressFields;
const QString trimmedDataType = dataType.trimmed();
if (!trimmedDataType.isEmpty())
{
params["dataType"] = trimmedDataType;
}
if (deviceId != 0)
{
params["deviceId"] = static_cast<qint64>(deviceId);
}
_pendingAuxRequests["adapter.buildExpression"] = _pProcess->sendRequest("adapter.buildExpression", params);
}
void AdapterClient::stopSession()
{
if (_state == State::IDLE || _state == State::STOPPING)
{
return;
}
_handshakeTimer.stop();
_pendingAuxRequests.clear();
if (_state == State::ACTIVE || _state == State::STARTING)
{
_state = State::STOPPING;
_pProcess->sendRequest("adapter.shutdown", QJsonObject());
_handshakeTimer.start(_handshakeTimeoutMs);
}
else
{
_state = State::STOPPING;
_pProcess->stop();
/* sessionStopped is emitted from onProcessFinished once the process exits */
}
}
void AdapterClient::onResponseReceived(int id, const QString& method, const QJsonValue& result)
{
if (result.isObject())
{
handleLifecycleResponse(id, method, result.toObject());
}
else
{
qCWarning(scopeComm) << "AdapterClient: unexpected non-object result for" << method;
_handshakeTimer.stop();
/* Set IDLE before stop() so onProcessFinished's IDLE guard suppresses any
duplicate sessionError emission when the process exits asynchronously. */
_pendingAuxRequests.clear();
_state = State::IDLE;
_pProcess->stop();
emit sessionError(QString("Unexpected non-object result for %1").arg(method));
}
}
void AdapterClient::onErrorReceived(int id, const QString& method, const QJsonObject& error)
{
Q_UNUSED(id)
_handshakeTimer.stop();
QString errorMsg = error.value("message").toString();
qCWarning(scopeComm) << "AdapterClient: error for" << method << ":" << errorMsg;
State previousState = _state;
/* Set IDLE before stop() so onProcessFinished's IDLE guard suppresses any
duplicate sessionError emission when the process exits asynchronously. */
_pendingAuxRequests.clear();
_state = State::IDLE;
_pProcess->stop();
if (previousState != State::STOPPING)
{
emit sessionError(QString("Adapter error on %1: %2").arg(method, errorMsg));
}
}
void AdapterClient::onProcessError(const QString& message)
{
_handshakeTimer.stop();
if (_state != State::STOPPING)
{
_pendingAuxRequests.clear();
_state = State::IDLE;
emit sessionError(message);
}
}
void AdapterClient::onProcessFinished()
{
_handshakeTimer.stop();
_pendingAuxRequests.clear();
if (_state == State::STOPPING)
{
_state = State::IDLE;
emit sessionStopped();
}
else if (_state != State::IDLE)
{
_state = State::IDLE;
emit sessionError("Adapter process exited unexpectedly");
}
}
void AdapterClient::onHandshakeTimeout()
{
qCWarning(scopeComm) << "AdapterClient: handshake timed out in state" << static_cast<int>(_state);
bool wasStopping = (_state == State::STOPPING);
_pendingAuxRequests.clear();
_state = State::IDLE;
_pProcess->stop();
if (wasStopping)
{
emit sessionStopped();
}
else
{
emit sessionError("Adapter handshake timed out");
}
}
void AdapterClient::onNotificationReceived(QString method, QJsonValue params)
{
if (method != QStringLiteral("adapter.diagnostic"))
{
return;
}
if (!params.isObject())
{
qCWarning(scopeComm) << "AdapterClient: adapter.diagnostic params is not an object";
return;
}
QJsonObject obj = params.toObject();
emit diagnosticReceived(obj.value(QStringLiteral("level")).toString(),
obj.value(QStringLiteral("message")).toString());
}
void AdapterClient::handleLifecycleResponse(int id, const QString& method, const QJsonObject& result)
{
if (method == "adapter.initialize" && _state == State::INITIALIZING)
{
qCInfo(scopeComm) << "AdapterClient: initialized, sending describe";
_state = State::DESCRIBING;
_pProcess->sendRequest("adapter.describe", QJsonObject());
}
else if (method == "adapter.describe" && _state == State::DESCRIBING)
{
qCInfo(scopeComm) << "AdapterClient: described, awaiting config";
_handshakeTimer.stop();
_state = State::AWAITING_CONFIG;
emit describeResult(result);
}
else if (method == "adapter.configure" && _state == State::CONFIGURING)
{
qCInfo(scopeComm) << "AdapterClient: configured, sending start";
_state = State::STARTING;
QJsonObject params;
params["registers"] = QJsonArray::fromStringList(_pendingExpressions);
_pProcess->sendRequest("adapter.start", params);
}
else if (method == "adapter.start" && _state == State::STARTING)
{
qCInfo(scopeComm) << "AdapterClient: started";
_handshakeTimer.stop();
_state = State::ACTIVE;
emit sessionStarted();
}
else if (method == "adapter.readData" && _state == State::ACTIVE)
{
ResultDoubleList results;
const QJsonArray registers = result["registers"].toArray();
for (const QJsonValue& entry : registers)
{
QJsonObject reg = entry.toObject();
if (reg["valid"].toBool())
{
results.append(ResultDouble(reg["value"].toDouble(), ResultState::State::SUCCESS));
}
else
{
results.append(ResultDouble(0.0, ResultState::State::INVALID));
}
}
emit readDataResult(results);
}
else if (method == "adapter.getStatus" && _state == State::ACTIVE)
{
emit statusResult(result["active"].toBool());
}
else if (method == "adapter.shutdown" && _state == State::STOPPING)
{
qCInfo(scopeComm) << "AdapterClient: shutdown acknowledged";
_pProcess->stop();
/* sessionStopped is emitted from onProcessFinished once the process exits */
}
else if (method == "adapter.dataPointSchema" && _state == State::AWAITING_CONFIG)
{
if (_pendingAuxRequests.value(method, -1) != id)
{
qCWarning(scopeComm) << "AdapterClient: ignoring stale response for" << method;
return;
}
_pendingAuxRequests.remove(method);
emit dataPointSchemaResult(result);
}
else if (method == "adapter.describeDataPoint" && (_state == State::AWAITING_CONFIG || _state == State::ACTIVE))
{
if (_pendingAuxRequests.value(method, -1) != id)
{
qCWarning(scopeComm) << "AdapterClient: ignoring stale response for" << method;
return;
}
_pendingAuxRequests.remove(method);
emit describeDataPointResult(result);
}
else if (method == "adapter.validateDataPoint" && (_state == State::AWAITING_CONFIG || _state == State::ACTIVE))
{
if (_pendingAuxRequests.value(method, -1) != id)
{
qCWarning(scopeComm) << "AdapterClient: ignoring stale response for" << method;
return;
}
_pendingAuxRequests.remove(method);
emit validateDataPointResult(result["valid"].toBool(), result["error"].toString());
}
else if (method == "adapter.buildExpression" && (_state == State::AWAITING_CONFIG || _state == State::ACTIVE))
{
if (_pendingAuxRequests.value(method, -1) != id)
{
qCWarning(scopeComm) << "AdapterClient: ignoring stale response for" << method;
return;
}
_pendingAuxRequests.remove(method);
emit buildExpressionResult(result["expression"].toString());
}
else
{
qCWarning(scopeComm) << "AdapterClient: unexpected response for" << method << "in state"
<< static_cast<int>(_state);
}
}