-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebsocket_client.cpp
More file actions
948 lines (753 loc) · 24.1 KB
/
websocket_client.cpp
File metadata and controls
948 lines (753 loc) · 24.1 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
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
#include "websocket_client.h"
#include <QJsonArray>
#include <QJsonParseError>
#include <QMessageBox>
#include <QPushButton>
#include <QScrollBar>
#include <QtEndian>
#include <cstring>
#include <zstd.h>
#include <set>
#include "ui_websocket_client.h"
// =======================
// Connection dialog
// =======================
class WebsocketDialog : public QDialog
{
public:
WebsocketDialog() : QDialog(nullptr), ui(new Ui::WebSocketDialog)
{
// Build UI
ui->setupUi(this);
// Window title
setWindowTitle("WebSocket Client");
// Allow only valid TCP ports
ui->lineEditPort->setValidator(new QIntValidator(1, 65535, this));
ui->comboBox->setEnabled(false);
}
~WebsocketDialog() { delete ui; }
public:
Ui::WebSocketDialog* ui;
};
// =======================
// WebsocketClient
// =======================
WebsocketClient::WebsocketClient() : _running(false), _paused(false), _closing(false), _dialog(nullptr)
{
loadDefaultSettings();
setupSettings();
// Initial state
_state.mode = WsState::Mode::Close;
_state.req_in_flight = false;
// Pending request tracking
_pendingRequestId.clear();
_pendingMode = WsState::Mode::Close;
// Timer used to periodically request topics (only while selecting topics)
_topicsTimer.setInterval(1000);
connect(&_topicsTimer, &QTimer::timeout, this, &WebsocketClient::requestTopics);
// Heartbeat timer (used in Data mode)
_heartBeatTimer.setInterval(1000);
connect(&_heartBeatTimer, &QTimer::timeout, this, &WebsocketClient::sendHeartBeat);
// WebSocket signals
connect(&_socket, &QWebSocket::connected, this, &WebsocketClient::onConnected);
connect(&_socket, &QWebSocket::textMessageReceived, this, &WebsocketClient::onTextMessageReceived);
connect(&_socket, &QWebSocket::binaryMessageReceived, this, &WebsocketClient::onBinaryMessageReceived);
connect(&_socket, &QWebSocket::disconnected, this, &WebsocketClient::onDisconnected);
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
connect(&_socket, &QWebSocket::errorOccurred, this, &WebsocketClient::onError);
#else
connect(&_socket,
QOverload<QAbstractSocket::SocketError>::of(&QWebSocket::error),
this,
&WebsocketClient::onError);
#endif
}
void WebsocketClient::setupSettings()
{
// Action shown in PlotJuggler "Settings"
_action_settings = new QAction("Pause", this);
// Initial state
_action_settings->setText("Pause");
// Toggle pause / resume
connect(_action_settings, &QAction::triggered, this, [this]() {
// Not running
if (!_running) {
return;
}
// Request in flight
if (_state.req_in_flight) {
return;
}
// If paused -> resume
if (_paused) {
if (resume()) {
_paused = false;
_action_settings->setText("Pause");
}
} else {
// If running -> pause
if (pause()) {
_paused = true;
_action_settings->setText("Resume");
}
}
});
// Expose action to PlotJuggler
_actions = { _action_settings };
}
// =======================
// PlotJuggler actions
// =======================
const std::vector<QAction*>& WebsocketClient::availableActions()
{
return _actions;
}
// =======================
// Filter helpers
// =======================
static void applyTopicFilterKeepSelected(QTreeWidget* list, const QString& filter)
{
if (!list) return;
const QString fl = filter.trimmed().toLower();
for (int i = 0; i < list->topLevelItemCount(); i++) {
auto* it = list->topLevelItem(i);
const bool selected = it->isSelected();
if (fl.isEmpty()) {
it->setHidden(false);
continue;
}
const QString name = it->text(0).toLower();
const QString type = it->text(1).toLower();
const bool match = name.contains(fl) || type.contains(fl);
it->setHidden(!(match || selected));
}
}
// =======================
// Refresh text button
// =======================
void WebsocketClient::updateOkButton()
{
if (!_dialog || !_dialog->ui || !_dialog->ui->buttonBox) return;
auto b = _dialog->ui->buttonBox->button(QDialogButtonBox::Ok);
if (!b) return;
if (!_running) {
b->setEnabled(true);
b->setText("Connect");
return;
}
if (_state.mode == WsState::Mode::GetTopics) {
const bool hasSelection = _dialog->ui->topicsList &&
!_dialog->ui->topicsList->selectedItems().isEmpty();
b->setText("Subscribe");
b->setEnabled(hasSelection && !_state.req_in_flight);
return;
}
b->setEnabled(false);
}
// =======================
// Start client
// =======================
bool WebsocketClient::start(QStringList*)
{
// Already running
if (_running) return true;
// Create dialog (stack object)
WebsocketDialog dialog;
_dialog = &dialog;
dialog.ui->lineEditAddress->setText(_config.address);
dialog.ui->lineEditPort->setText(QString::number(_config.port));
// Rename OK button (will toggle between Connect/Subscribe)
auto okBtn = dialog.ui->buttonBox->button(QDialogButtonBox::Ok);
if (okBtn) okBtn->setText("Connect");
// Refresh button when topic selection changes
connect(dialog.ui->topicsList, &QTreeWidget::itemSelectionChanged, this, &WebsocketClient::updateOkButton);
// Refresh topic list applying the filter
connect(dialog.ui->lineEditFilter, &QLineEdit::textChanged,
this, [&](const QString&) {
applyTopicFilterKeepSelected(dialog.ui->topicsList, dialog.ui->lineEditFilter->text());
});
// =======================
// OK button logic
// =======================
connect(dialog.ui->buttonBox, &QDialogButtonBox::accepted, this, [&]() {
// Not connected: open socket
if (!_running) {
bool ok = false;
int p = dialog.ui->lineEditPort->text().toUShort(&ok);
if (!ok) {
QMessageBox::warning(nullptr, "WebSocket Client", "Invalid Port", QMessageBox::Ok);
return;
}
const QString adrr = dialog.ui->lineEditAddress->text().trimmed();
if (adrr.isEmpty()) {
QMessageBox::warning(nullptr, "WebSocket Client", "Invalid Address", QMessageBox::Ok);
return;
}
// BuildWebSocket URL
_url = QUrl(QString("ws://%1:%2").arg(adrr).arg(p));
// Disable button while connecting
auto b = dialog.ui->buttonBox->button(QDialogButtonBox::Ok);
if (b) b->setEnabled(false);
// Save profile settings
_config.address = adrr;
_config.port = p;
saveDefaultSettings();
// Open WebSocket
_socket.open(_url);
return;
}
// Already connected: subscribe to topics
if (_state.mode != WsState::Mode::GetTopics) return;
if (_state.req_in_flight) return;
if (!dialog.ui->topicsList) return;
const auto selected = dialog.ui->topicsList->selectedItems();
if (selected.isEmpty()) return;
// Build JSON array with selected topic names
QJsonArray arr;
// Refresh selected topics cache
_topics.clear();
for (auto* it : selected) {
const auto name = it->text(0);
const auto type = it->text(1);
if (name.isEmpty()) continue;
arr.append(name);
// Cache selected topics (schema will be filled after subscribe response)
TopicInfo info;
info.name = name;
info.type = type;
_topics.push_back(std::move(info));
}
if (arr.isEmpty()) return;
// Store topics name on profile
_config.topics.clear();
for (const auto& v : arr)
_config.topics << v.toString();
saveDefaultSettings();
// Update state: one request in-flight
_state.mode = WsState::Mode::Subscribe;
_state.req_in_flight = true;
// Send subscribe command
QJsonObject cmd;
cmd["command"] = "subscribe";
cmd["topics"] = arr;
// Track expected response
_pendingMode = WsState::Mode::Subscribe;
_pendingRequestId = sendCommand(cmd);
// Disable button until response arrives
auto b = dialog.ui->buttonBox->button(QDialogButtonBox::Ok);
if (b) b->setEnabled(false);
// Close dialog after subscribing (PlotJuggler takes over)
dialog.reject();
});
// =======================
// Cancel button
// =======================
connect(dialog.ui->buttonBox, &QDialogButtonBox::rejected, this, [&]() {
// Stop everything and close dialog
shutdown();
dialog.reject();
});
// Run dialog (blocking)
dialog.exec();
_dialog = nullptr;
// Connection failed or cancelled
if (!_running) {
shutdown();
return false;
}
return true;
}
void WebsocketClient::shutdown()
{
if (!_running) return;
_running = false;
_paused = false;
// Reset the text of the Plotjuggler settings
if (_action_settings) {
_action_settings->setText("Pause");
}
// Stop periodic timers
_topicsTimer.stop();
_heartBeatTimer.stop();
// Reset state machine
_state.mode = WsState::Mode::Close;
_state.req_in_flight = false;
// Reset pending request tracking
_pendingRequestId.clear();
_pendingMode = WsState::Mode::Close;
// Close dialog if still open
if (_dialog) _dialog->reject();
_dialog = nullptr;
// Clean topics cache
_topics.clear();
#ifdef PJ_BUILD
// Drop created parsers
_parsers_topic.clear();
// Clean data
dataMap().clear();
emit dataReceived();
#endif
// Close socket
_closing = true;
_socket.abort();
_socket.close();
}
bool WebsocketClient::pause()
{
// Pause streaming on server side
if (!_running) return false;
if (_state.req_in_flight) return false;
QJsonObject cmd;
cmd["command"] = "pause";
return !sendCommand(cmd).isEmpty();
}
bool WebsocketClient::resume()
{
// Resume streaming on server side
if (!_running) return false;
if (_state.req_in_flight) return false;
QJsonObject cmd;
cmd["command"] = "resume";
return !sendCommand(cmd).isEmpty();
}
bool WebsocketClient::unsubscribe()
{
// Unsubscribe currently selected topics
if (!_running) return false;
if (_state.req_in_flight) return false;
QJsonArray arr;
for (const auto& t : _topics) {
if (!t.name.isEmpty())
arr.append(t.name);
}
if (arr.isEmpty()) return false;
QJsonObject cmd;
cmd["command"] = "unsubscribe";
cmd["topics"] = arr;
return !sendCommand(cmd).isEmpty();
}
void WebsocketClient::onConnected()
{
_running = true;
qDebug() << "Connected";
// First step after connect: request topics
_state.mode = WsState::Mode::GetTopics;
_state.req_in_flight = true;
QJsonObject cmd;
cmd["command"] = "get_topics";
// Track expected response
_pendingMode = WsState::Mode::GetTopics;
_pendingRequestId = sendCommand(cmd);
// Start periodic topic refresh
_topicsTimer.start();
}
void WebsocketClient::onDisconnected()
{
if (_dialog && _dialog->ui && _dialog->ui->topicsList && _dialog->ui->buttonBox) {
_dialog->ui->topicsList->clear();
auto b = _dialog->ui->buttonBox->button(QDialogButtonBox::Ok);
if (b) b->setEnabled(true);
} else if (!_closing){
QMessageBox::warning(
nullptr,
"WebSocket Client",
"Server closed the connection",
QMessageBox::Ok);
}
if (!_running) return;
if (_closing) _closing = false;
// Stop topic polling
_topicsTimer.stop();
_heartBeatTimer.stop();
// Reset state machine
_state.mode = WsState::Mode::Close;
_state.req_in_flight = false;
// Reset pending request tracking
_pendingRequestId.clear();
_pendingMode = WsState::Mode::Close;
// Clear topics cache
_topics.clear();
#ifdef PJ_BUILD
// Drop created parsers
_parsers_topic.clear();
#endif
_running = false;
qDebug() << "Disconnected" << Qt::endl;
}
void WebsocketClient::onError(QAbstractSocket::SocketError)
{
//Show Qt socket error string
QMessageBox::warning(nullptr, "WebSocket Client", _socket.errorString(), QMessageBox::Ok);
onDisconnected();
}
void WebsocketClient::onTextMessageReceived(const QString& message)
{
if (!_running) return;
// Parse JSON message
QJsonParseError err;
const auto doc = QJsonDocument::fromJson(message.toUtf8(), &err);
if (err.error != QJsonParseError::NoError || !doc.isObject())
return;
const auto obj = doc.object();
// Validate protocol version
if (!obj.contains("protocol_version") ||
obj.value("protocol_version").toInt() != 1)
return;
const auto status = obj.value("status").toString();
const auto id = obj.value("id").toString();
// If a request is in-flight, only accept matching response "id"
if (_state.req_in_flight) {
if (_pendingRequestId.isEmpty() || id != _pendingRequestId)
return;
}
// Error response from server
if (status == "error") {
_state.req_in_flight = false;
// Reset pending request
_pendingRequestId.clear();
_pendingMode = WsState::Mode::Close;
const auto msg = obj.value("message").toString("Unknown error");
QMessageBox::warning(nullptr, "WebSocket Client", msg, QMessageBox::Ok);
return;
}
// Only handle successful responses
if (status != "success")
return;
// Request completed successfully
_state.req_in_flight = false;
// Save mode locally, then clear pending (avoid re-entrancy issues)
const auto handledMode = _pendingMode;
_pendingRequestId.clear();
_pendingMode = WsState::Mode::Close;
switch (handledMode) {
case WsState::Mode::GetTopics:
{
// Expect array of topics
if (!obj.contains("topics") || !obj.value("topics").isArray())
break;
// Dialog may already be closed
if (!_dialog || !_dialog->ui || !_dialog->ui->topicsList)
break;
auto* view = _dialog->ui->topicsList;
// Save current scroll position
auto* vsb = view->verticalScrollBar();
const int scroll_y = vsb ? vsb->value() : 0;
// Restore selection (persisted + current)
QStringList wanted = _config.topics;
for (auto* it : view->selectedItems()) {
const auto n = it->text(0);
if (!wanted.contains(n))
wanted << n;
}
_config.topics.clear();
// Update UI without triggering signals
view->setUpdatesEnabled(false);
view->blockSignals(true);
view->setVisible(false);
view->clear();
// Populate topic list
const auto topics = obj.value("topics").toArray();
for (const auto& v : topics) {
if (!v.isObject()) continue;
const auto t = v.toObject();
const auto name = t.value("name").toString();
const auto type = t.value("type").toString();
if (name.isEmpty()) continue;
auto* item = new QTreeWidgetItem(view);
item->setText(0, name);
item->setText(1, type);
// Restore previous selection
if (wanted.contains(name))
item->setSelected(true);
}
// Apply the filter after restore
if (_dialog->ui->lineEditFilter) {
applyTopicFilterKeepSelected(view, _dialog->ui->lineEditFilter->text());
}
view->resizeColumnToContents(0);
view->setVisible(true);
view->blockSignals(false);
view->setUpdatesEnabled(true);
// Check profile settings
updateOkButton();
// Restore scroll position after layout update
QTimer::singleShot(0, view, [view, scroll_y]() {
if (auto* sb = view->verticalScrollBar())
sb->setValue(scroll_y);
});
break;
}
case WsState::Mode::Subscribe:
{
// The server must return schemas for the accepted topics.
// Expected format:
// "schemas": {
// "/topic_a": { "name":"pkg/msg/Type", "encoding":"cdr", "definition":"..." },
// "/topic_b": { "name":"...", "encoding":"...", "definition":"..." }
// }
if (!obj.contains("schemas") || !obj.value("schemas").isObject()) {
_topics.clear();
#ifdef PJ_BUILD
_parsers_topic.clear();
#endif
break;
}
const auto schemas = obj.value("schemas").toObject();
// Keep only topics that the server confirmed
_topics.erase(
std::remove_if(_topics.begin(), _topics.end(),
[&](const TopicInfo& t){ return !schemas.contains(t.name); }),
_topics.end());
// Fill schema fields per topic
for (auto& t : _topics) {
const auto s = schemas.value(t.name).toObject();
t.schema_name = s.value("name").toString(t.type);
t.schema_encoding = s.value("encoding").toString();
t.schema_definition = s.value("definition").toString();
}
// Create parsers for accepted topics (PJ build only)
createParsersForTopics();
// Move to Data mode and start heartbeat
_state.mode = WsState::Mode::Data;
_heartBeatTimer.start();
break;
}
case WsState::Mode::Data:
{
// Text messages in data mode currently ignored
break;
}
case WsState::Mode::Close:
break;
default:
qWarning() << "Unhandled mode:" << int(handledMode);
break;
}
}
// =======================
// Binary helpers
// =======================
template <typename T>
static bool readLE(const uint8_t*& p, const uint8_t* end, T& out)
{
// Read POD type from buffer as little-endian
if (p + sizeof(T) > end) return false;
std::memcpy(&out, p, sizeof(T));
out = qFromLittleEndian(out);
p += sizeof(T);
return true;
}
bool WebsocketClient::parseDecompressedPayload(const QByteArray& decompressed, uint32_t expected_count)
{
// Payload format: repeated blocks
// [u16 topic_name_len][bytes topic_name][u64 ts_ns][u32 cdr_len][bytes cdr]
const uint8_t* q = reinterpret_cast<const uint8_t*>(decompressed.constData());
const uint8_t* qend = q + decompressed.size();
uint32_t parsed = 0;
// Parse until end of payload
while (q < qend) {
uint16_t name_len = 0;
if (!readLE(q, qend, name_len)) return false;
if (q + name_len > qend) return false;
QString topic = QString::fromUtf8(reinterpret_cast<const char*>(q), name_len);
q += name_len;
uint64_t ts_ns = 0;
if (!readLE(q, qend, ts_ns)) return false;
double ts_sec = double(ts_ns) * 1e-9;
uint32_t data_len = 0;
if (!readLE(q, qend, data_len)) return false;
if (q + data_len > qend) return false;
// CDR buffer points inside decompressed payload
const uint8_t* cdr = q;
q += data_len;
// Push message into parser / PlotJuggler
onRos2CdrMessage(topic, ts_sec, cdr, data_len);
parsed++;
}
// Header message_count must match parsed messages
if (parsed != expected_count) {
qWarning() << "Parsed messages mismatch. header=" << expected_count
<< "parsed=" << parsed
<< "decompressed=" << decompressed.size();
return false;
}
return true;
}
void WebsocketClient::onBinaryMessageReceived(const QByteArray& message)
{
if (!_running) return;
// Frame header must be at least 16 bytes
if (message.size() < 16) {
return;
}
// Frame header fields (little-endian)
const uint8_t* ptr = reinterpret_cast<const uint8_t*>(message.constData());
const uint8_t* end = ptr + message.size();
uint32_t magic = 0;
uint32_t message_count = 0;
uint32_t uncompressed_size = 0;
uint32_t flags = 0;
if (!readLE(ptr, end, magic)) return;
if (!readLE(ptr, end, message_count)) return;
if (!readLE(ptr, end, uncompressed_size)) return;
if (!readLE(ptr, end, flags)) return;
// Validate magic and flags
if (magic != 0x42524A50) { // "PJRB"
qWarning() << "Bad magic:" << Qt::hex << magic;
return;
}
if (flags != 0) {
qWarning() << "Bad flag:" << flags;
return;
}
// Compressed payload starts after 16-byte header
QByteArray compressed = message.mid(16);
if (compressed.isEmpty())
return;
// ZSTD decompress
QByteArray decompressed;
decompressed.resize(int(uncompressed_size));
size_t res = ZSTD_decompress(decompressed.data(),
size_t(decompressed.size()),
compressed.constData(),
size_t(compressed.size()));
if (ZSTD_isError(res)) {
qWarning() << "ZSTD_decompress error:" << ZSTD_getErrorName(res);
return;
}
// Resize to actual decompressed bytes
decompressed.resize(int(res));
// Parse messages inside payload
parseDecompressedPayload(decompressed, message_count);
}
// =======================
// Commands / requests
// =======================
QString WebsocketClient::sendCommand(QJsonObject obj)
{
if (_socket.state() != QAbstractSocket::ConnectedState) return QString();
// Every command must have a "command" field
if (!obj.contains("command"))
return QString();
// Generate unique ID if missing
if (!obj.contains("id"))
obj["id"] = QUuid::createUuid().toString(QUuid::WithoutBraces);
// Addprotocol version if missing
if (!obj.contains("protocol_version"))
obj["protocol_version"] = 1;
// Serialize and send JSON
QJsonDocument doc(obj);
_socket.sendTextMessage(QString::fromUtf8(doc.toJson(QJsonDocument::Compact)));
return obj["id"].toString();
}
void WebsocketClient::requestTopics()
{
if (_socket.state() != QAbstractSocket::ConnectedState) return;
// Only poll when connected and idle
if (!_running) return;
if (_state.mode != WsState::Mode::GetTopics) return;
if (_state.req_in_flight) return;
_state.req_in_flight = true;
QJsonObject cmd;
cmd["command"] = "get_topics";
// Track expected response
_pendingMode = WsState::Mode::GetTopics;
_pendingRequestId = sendCommand(cmd);
}
void WebsocketClient::sendHeartBeat()
{
if (_socket.state() != QAbstractSocket::ConnectedState) return;
// Heartbeat only in Data mode
if (!_running) return;
if (_state.mode != WsState::Mode::Data) return;
// Keep-alive / watchdog on server side
QJsonObject cmd;
cmd["command"] = "heartbeat";
sendCommand(cmd);
}
// =======================
// PlotJuggler integration
// =======================
void WebsocketClient::createParsersForTopics()
{
#ifdef PJ_BUILD
// Create one parser per subscribed topic using PlotJuggler factories
for (const auto& t : _topics) {
const std::string topic_name = t.name.toStdString();
// Already created
if (_parsers_topic.count(topic_name) != 0)
continue;
// IMPORTANT: factories are indexed by QString
const QString encoding_q = t.schema_encoding;
const QString schema_name_q = t.schema_name;
// Find parser factory by encoding (QString key)
auto factories = parserFactories();
auto it = factories->find(encoding_q);
if (it == factories->end()) {
// Warn only once per encoding
static std::set<QString> warned;
if (warned.insert(encoding_q).second) {
QMessageBox::warning(
nullptr,
"Encoding problem",
QString("No parser available for encoding [%0]").arg(encoding_q));
}
continue;
}
// Convert to std::string only for the createParser call (common in PJ)
const std::string schema_name = schema_name_q.toStdString();
const std::string definition = t.schema_definition.toStdString();
// Create parser instance
PJ::MessageParserPtr parser =
it->second->createParser(topic_name,
schema_name,
definition,
dataMap());
if (!parser)
continue;
_parsers_topic.emplace(topic_name, std::move(parser));
}
#endif
}
void WebsocketClient::onRos2CdrMessage(const QString& topic, double ts_sec, const uint8_t* cdr, uint32_t len)
{
#ifdef PJ_BUILD
// Route CDR blob to the parser created for this topic
const auto key = topic.toStdString();
auto it = _parsers_topic.find(key);
if (it == _parsers_topic.end())
return;
PJ::MessageRef msg_ref(cdr, len);
it->second->parseMessage(msg_ref, ts_sec);
// Notify PlotJuggler that new data is available
emit dataReceived();
#else
// Debug build: just log reception
Q_UNUSED(cdr);
Q_UNUSED(len);
qDebug() << "RX msg topic=" << topic << "ts=" << ts_sec << "cdr=" << len << Qt::endl;
#endif
}
// =======================
// PlotJuggler profiles
// =======================
void WebsocketClient::saveDefaultSettings()
{
QSettings s;
_config.saveToSettings(s, "WebsocketClient");
}
void WebsocketClient::loadDefaultSettings()
{
QSettings s;
_config.loadFromSettings(s, "WebsocketClient");
}
bool WebsocketClient::xmlSaveState(QDomDocument& doc, QDomElement& parent) const
{
_config.xmlSaveState(doc, parent);
return true;
}
bool WebsocketClient::xmlLoadState(const QDomElement& parent)
{
_config.xmlLoadState(parent);
return true;
}