Repository navigation
Expand file tree
/
Copy pathWebSocketListener.cpp
More file actions
763 lines (615 loc) · 18.7 KB
/
Copy pathWebSocketListener.cpp
File metadata and controls
763 lines (615 loc) · 18.7 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
#include "WebSocketListener.h"
#include "Say.h"
#include <libwebsockets.h>
#include <pugixml.hpp>
#include <iostream>
#include <cstring>
WebSocketListener::WebSocketListener (const std::string &deviceIp, const Callbacks &callbacks, int comboWindowMs, bool quiet)
: m_deviceIp (deviceIp),
m_wsUrl ("ws://" + deviceIp + ":8080"),
m_callbacks (callbacks),
m_comboWindowMs (comboWindowMs),
m_context (nullptr),
m_wsi (nullptr),
m_state (State::IDLE),
m_pendingPreset (0),
m_sequence (0),
m_invalidSeenSincePress (false),
m_running (false),
m_stopRequested (false),
m_lastPressTime (),
m_playBusy (false),
m_reconnectTimer (),
m_reconnecting (false),
m_everConnected (false),
m_quiet (quiet)
{
m_reconnectTimer.self = this;
}
WebSocketListener::~WebSocketListener ()
{
stop ();
if (m_playThread.joinable ())
{
m_playThread.join ();
}
if (m_context != nullptr)
{
lws_sul_cancel (&m_reconnectTimer.sul);
lws_context_destroy (m_context);
m_context = nullptr;
}
}
bool WebSocketListener::parsePresetEvent (const std::string &message, int &presetId)
{
pugi::xml_document doc;
if (!doc.load_string (message.c_str ()))
{
return (false);
}
const pugi::xml_node preset = doc.select_node ("//nowSelectionUpdated/preset").node ();
if (!preset)
{
return (false);
}
const pugi::xml_attribute id = preset.attribute ("id");
if (!id)
{
return (false);
}
presetId = id.as_int ();
return (presetId != 0);
}
// The speaker's report that it could not skip, which is how a press of the remote's next or
// previous button shows on a stream it was handed:
// <errorUpdate ...><error value="4301" name="QPLAY_SKIP_NEXT_FAILED" ...>SkipNext failed.</error>
// <errorUpdate ...><error value="4302" name="QPLAY_SKIP_PREV_FAILED" ...>SkipPrev failed.</error>
bool WebSocketListener::parseSkipFailure (const std::string &message, bool &forward)
{
pugi::xml_document doc;
if (!doc.load_string (message.c_str ()))
{
return (false);
}
const pugi::xml_node error = doc.select_node ("//errorUpdate/error").node ();
if (!error)
{
return (false);
}
const std::string name = error.attribute ("name").value ();
const int value = error.attribute ("value").as_int ();
if (name == "QPLAY_SKIP_NEXT_FAILED" || value == 4301)
{
forward = true;
return (true);
}
if (name == "QPLAY_SKIP_PREV_FAILED" || value == 4302)
{
forward = false;
return (true);
}
return (false);
}
// The speaker's volume report, pushed whenever the level or mute changes:
// <updates ...><volumeUpdated><volume><targetvolume>15</targetvolume>
// <actualvolume>15</actualvolume><muteenabled>false</muteenabled></volume></volumeUpdated></updates>
bool WebSocketListener::parseVolume (const std::string &message, int &target, int &actual, bool &muted)
{
pugi::xml_document doc;
if (!doc.load_string (message.c_str ()))
{
return (false);
}
const pugi::xml_node volume = doc.select_node ("//volumeUpdated/volume").node ();
if (!volume)
{
return (false);
}
target = volume.child ("targetvolume").text ().as_int ();
actual = volume.child ("actualvolume").text ().as_int ();
muted = (std::strcmp (volume.child_value ("muteenabled"), "true") == 0);
return (true);
}
void WebSocketListener::armTimer (int milliseconds)
{
if (m_wsi != nullptr)
{
lws_set_timer_usecs (m_wsi, static_cast<lws_usec_t> (milliseconds) * 1000);
}
}
void WebSocketListener::cancelTimer ()
{
if (m_wsi != nullptr)
{
lws_set_timer_usecs (m_wsi, LWS_SET_TIMER_USEC_CANCEL);
}
}
void WebSocketListener::startPlayback (int presetId)
{
cancelTimer ();
m_state = State::IDLE;
m_pendingPreset = 0;
requestPlay (presetId, PlayReason::PRESS);
}
void WebSocketListener::requestPlay (int presetId, PlayReason reason, const std::string &streamName)
{
{
std::lock_guard<std::mutex> lock (m_playMutex);
// A listener being retired plays nothing more.
if (m_stopRequested)
{
return;
}
m_playRequest.pending = true;
m_playRequest.presetId = presetId;
m_playRequest.reason = reason;
m_playRequest.streamName = streamName;
}
// lws_service() keeps sleeping after firing a callback, so the loop would not notice this
// request until some unrelated event arrived. Break the wait explicitly; this is the one lws
// call made for calling from any thread.
if (m_context != nullptr)
{
lws_cancel_service (m_context);
}
}
void WebSocketListener::onTimer ()
{
if (m_stopRequested)
{
return;
}
if (m_sequence != 0)
{
if (!m_quiet)
{
Say () << ">>> No further digit arrived.\n";
}
resolveSequence ();
return;
}
if (m_state == State::WAITING_FOR_INVALID)
{
if (!m_quiet)
{
Say () << "\n>>> Gave up waiting for the speaker to finish preset "
<< m_pendingPreset << ".\n";
Say () << ">>> Not starting playback; the expected transition never happened.\n\n";
}
m_state = State::IDLE;
m_pendingPreset = 0;
}
}
// Decide what the digits pressed so far mean, and either play now or wait for the speaker's
// failing preset attempt to land first.
void WebSocketListener::resolveSequence ()
{
const int preset = m_sequence;
m_sequence = 0;
cancelTimer ();
std::string presetName;
if (!m_callbacks.presetInfo || !m_callbacks.presetInfo (preset, presetName))
{
if (!m_quiet)
{
Say () << ">>> No stream configured for preset " << preset << "; ignoring\n\n";
}
m_state = State::IDLE;
m_pendingPreset = 0;
return;
}
if (!m_quiet)
{
Say () << ">>> Preset " << preset << " -> " << presetName << "\n";
}
// Playing before the speaker's own attempt fails lets that failure wipe our metadata, which
// loses the station name on the display. If the failure already arrived, go straight ahead.
if (m_invalidSeenSincePress)
{
if (!m_quiet)
{
Say () << ">>> Speaker already gave up on it; starting playback.\n\n";
}
startPlayback (preset);
}
else
{
if (!m_quiet)
{
Say () << ">>> Waiting for the speaker to finish its own preset handling...\n\n";
}
m_state = State::WAITING_FOR_INVALID;
m_pendingPreset = preset;
armTimer (PRESET_TIMEOUT * 1000);
}
}
void WebSocketListener::onButtonPressed (int button)
{
m_lastPressTime = std::chrono::steady_clock::now ();
if (m_callbacks.press)
{
m_callbacks.press ();
}
// Each press starts a fresh wait for that press's INVALID_SOURCE.
m_invalidSeenSincePress = false;
m_sequence = (m_sequence * 10) + button;
if (!m_quiet)
{
Say () << "\n>>> Button " << button << " pressed; sequence so far: " << m_sequence << "\n";
}
// Keep collecting only while some configured preset is longer than what we have and starts
// with it. Once nothing can extend it, the sequence is final.
if (m_callbacks.couldExtend && m_callbacks.couldExtend (m_sequence))
{
const int window = m_comboWindowMs;
armTimer (window);
if (!m_quiet)
{
Say () << ">>> Waiting " << window << "ms for another digit...\n";
}
return;
}
resolveSequence ();
}
void WebSocketListener::handleEvent (const std::string &message)
{
// Stopped, as when control moves to another speaker: what this one says is no longer news.
if (m_stopRequested)
{
return;
}
if (!m_quiet)
{
Say () << "EVENT:\n" << message << "\n" << std::string (70, '-') << "\n";
}
SoundTouchClient::NowPlaying now;
if (SoundTouchClient::parseNowPlayingXml (message, now) && m_callbacks.source)
{
m_callbacks.source (now);
}
const std::string &source = now.source;
// A skip button: the stream it drops next is the press's doing, not the speaker giving up.
bool forward = false;
if (parseSkipFailure (message, forward))
{
m_lastPressTime = std::chrono::steady_clock::now ();
if (!m_quiet)
{
Say () << ">>> " << (forward ? "Next" : "Previous") << " pressed on the remote\n";
}
if (m_callbacks.skip)
{
m_callbacks.skip (forward);
}
return;
}
// Volume: the knob, the app or the remote moved it. Only in-memory state to update.
int volTarget = 0;
int volActual = 0;
bool volMuted = false;
if (parseVolume (message, volTarget, volActual, volMuted))
{
if (m_callbacks.volume)
{
m_callbacks.volume (volTarget, volActual, volMuted);
}
return;
}
if (source == "INVALID_SOURCE")
{
m_invalidSeenSincePress = true;
if (m_state != State::WAITING_FOR_INVALID)
{
// Not the tail of a press, nor something control is starting: the speaker gave up on
// what it was playing all by itself.
const bool afterPress = (std::chrono::steady_clock::now () - m_lastPressTime < PRESS_GRACE);
if (!afterPress && m_sequence == 0 && !m_playBusy && m_callbacks.unexpectedStop)
{
if (!m_quiet)
{
Say () << ">>> INVALID_SOURCE with no button pressed\n";
}
m_callbacks.unexpectedStop ();
return;
}
if (!m_quiet)
{
Say () << ">>> INVALID_SOURCE noted (nothing pending yet)\n";
}
return;
}
if (!m_quiet)
{
Say () << "\n>>> Preset " << m_pendingPreset << " failed on the speaker (cloud is gone).\n";
Say () << ">>> Taking over with direct UPnP playback.\n\n";
}
startPlayback (m_pendingPreset);
return;
}
int button = 0;
if (parsePresetEvent (message, button))
{
onButtonPressed (button);
}
}
int WebSocketListener::webSocketCallback (
struct lws *wsi,
enum lws_callback_reasons reason,
void *user,
void *in,
size_t len
)
{
WebSocketListener *listener = static_cast<WebSocketListener *> (lws_context_user (lws_get_context (wsi)));
(void) user;
switch (reason)
{
case LWS_CALLBACK_CLIENT_ESTABLISHED :
{
if (listener != nullptr)
{
listener->onConnected ();
}
break;
}
case LWS_CALLBACK_CLIENT_RECEIVE :
{
if (listener != nullptr)
{
listener->handleEvent (std::string (static_cast<const char *> (in), len));
}
break;
}
case LWS_CALLBACK_TIMER :
{
if (listener != nullptr)
{
listener->onTimer ();
}
break;
}
case LWS_CALLBACK_CLIENT_CONNECTION_ERROR :
{
// Said once per outage: it is tried again every few seconds until the speaker is back.
if ((listener == nullptr || !listener->m_quiet) && (listener == nullptr || !listener->m_reconnecting))
{
Say (std::cerr) << "\nWebSocket connection error"
<< ((in != nullptr) ? std::string (": ") + static_cast<const char *> (in) : std::string ())
<< "\n";
}
if (listener != nullptr)
{
listener->onDisconnected ();
}
break;
}
case LWS_CALLBACK_CLIENT_CLOSED :
{
if (listener == nullptr || !listener->m_quiet)
{
Say () << "\nWebSocket connection closed\n";
}
if (listener != nullptr)
{
listener->onDisconnected ();
}
break;
}
default :
{
break;
}
}
return (0);
}
bool WebSocketListener::connect ()
{
static const struct lws_protocols protocols[] =
{
{
"gabbo",
webSocketCallback,
0,
4096,
0,
nullptr,
0
},
{ nullptr, nullptr, 0, 0, 0, nullptr, 0 }
};
struct lws_context_creation_info info;
// Errors and warnings only: its notices repeat every failed attempt while the speaker is away.
lws_set_log_level (LLL_ERR | LLL_WARN, nullptr);
std::memset (&info, 0, sizeof (info));
info.port = CONTEXT_PORT_NO_LISTEN;
info.protocols = protocols;
info.gid = -1;
info.uid = -1;
info.options = 0;
info.user = this;
m_context = lws_create_context (&info);
if (m_context == nullptr)
{
if (!m_quiet)
{
Say (std::cerr) << "Failed to create libwebsockets context\n";
}
return (false);
}
// The speaker may not be reachable yet, say mid-boot or before the network is up. Keep trying,
// as after losing it later; only a context that cannot be created is fatal.
if (!openConnection ())
{
onDisconnected ();
}
return (true);
}
bool WebSocketListener::openConnection ()
{
struct lws_client_connect_info ccinfo;
std::memset (&ccinfo, 0, sizeof (ccinfo));
ccinfo.context = m_context;
ccinfo.address = m_deviceIp.c_str ();
ccinfo.port = 8080;
ccinfo.path = "/";
ccinfo.host = m_deviceIp.c_str ();
ccinfo.origin = m_deviceIp.c_str ();
ccinfo.protocol = "gabbo";
ccinfo.pwsi = &m_wsi;
m_wsi = lws_client_connect_via_info (&ccinfo);
return (m_wsi != nullptr);
}
void WebSocketListener::onConnected ()
{
if (m_stopRequested)
{
return;
}
const bool again = m_everConnected;
if (!m_quiet)
{
if (m_everConnected)
{
Say () << "\n>>> Reconnected to the speaker; listening for buttons again.\n";
Say () << std::string (70, '-') << "\n";
}
else
{
Say () << "\nCONNECTED\n\n";
Say () << "Listening for physical preset buttons. Press Ctrl-C to stop.\n";
Say () << std::string (70, '-') << "\n";
}
}
m_reconnecting = false;
m_everConnected = true;
if (m_callbacks.connected)
{
m_callbacks.connected (again);
}
}
void WebSocketListener::onDisconnected ()
{
m_wsi = nullptr;
// A combo being typed, or a wait for the speaker's own preset handling, cannot finish
// without its events.
m_sequence = 0;
m_state = State::IDLE;
m_pendingPreset = 0;
if (m_callbacks.disconnected)
{
m_callbacks.disconnected ();
}
if (m_stopRequested)
{
return;
}
if (!m_reconnecting)
{
if (!m_quiet)
{
if (m_everConnected)
{
Say () << ">>> Lost the speaker's events (rebooting, or off the network?); retrying every "
<< RECONNECT_SECONDS << "s\n";
}
else
{
Say () << ">>> Cannot reach the speaker at " << m_deviceIp << " yet; retrying every "
<< RECONNECT_SECONDS << "s\n";
}
}
m_reconnecting = true;
}
scheduleReconnect ();
}
void WebSocketListener::scheduleReconnect ()
{
lws_sul_schedule (m_context, 0, &m_reconnectTimer.sul, reconnectCallback,
static_cast<lws_usec_t> (RECONNECT_SECONDS) * LWS_USEC_PER_SEC);
}
void WebSocketListener::reconnectCallback (lws_sorted_usec_list_t *sul)
{
WebSocketListener *self = reinterpret_cast<ReconnectTimer *> (sul)->self;
if (self->m_stopRequested)
{
return;
}
// A refusal can come back at once, or later as a connection error; either way, try again.
if (!self->openConnection ())
{
self->scheduleReconnect ();
}
}
void WebSocketListener::run ()
{
m_running = true;
if (!m_quiet)
{
Say () << "\nConnecting to " << m_wsUrl << "\n";
}
while (m_running && !m_stopRequested)
{
lws_service (m_context, 0);
// While a playback is in flight, leave the request waiting so it is picked up when that
// finishes. A newer press simply overwrites it, so the last button pressed wins.
if (!m_playBusy)
{
PlayRequest request;
{
std::lock_guard<std::mutex> lock (m_playMutex);
request = m_playRequest;
m_playRequest.pending = false;
}
if (request.pending && m_callbacks.play && !m_stopRequested)
{
if (m_playThread.joinable ())
{
m_playThread.join ();
}
m_playBusy = true;
// Runs off the service loop so the HTTP calls do not stall the WebSocket.
m_playThread = std::thread ([this, request] ()
{
// A resume that finds nothing to do reports why itself.
if (!m_callbacks.play (request.presetId, request.reason, request.streamName)
&& request.reason == PlayReason::PRESS)
{
if (request.streamName.empty ())
{
Say (std::cerr) << ">>> Failed to start preset " << request.presetId << "\n";
}
else
{
Say (std::cerr) << ">>> Failed to start " << request.streamName << "\n";
}
}
m_playBusy = false;
// Wake the loop so a request queued while this was in flight runs at once.
lws_cancel_service (m_context);
});
}
}
}
if (m_playThread.joinable ())
{
if (m_playBusy && !m_quiet)
{
Say () << "Waiting for the playback request in flight to finish...\n";
}
m_playThread.join ();
}
m_running = false;
}
void WebSocketListener::stop ()
{
{
std::lock_guard<std::mutex> lock (m_playMutex);
m_stopRequested = true;
m_playRequest.pending = false;
}
// lws_service() would otherwise sleep on until the speaker next sent something.
if (m_context != nullptr)
{
lws_cancel_service (m_context);
}
}