-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscorecontroller.cpp
More file actions
1370 lines (1233 loc) · 44.1 KB
/
scorecontroller.cpp
File metadata and controls
1370 lines (1233 loc) · 44.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
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
*
Copyright (C) 2016 Gabriele Salvato
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <QDir>
#include <QTimer>
#include <QMessageBox>
#include <QThread>
#include <QNetworkInterface>
#include <QUdpSocket>
#include <QWebSocket>
#include <QBuffer>
#include <QFileDialog>
#include <QPushButton>
#include <QHostInfo>
#include <QGroupBox>
#include <QGridLayout>
#include <QLabel>
#include <QCloseEvent>
#include <QProcessEnvironment>
#include <QStandardPaths>
#include "scorecontroller.h"
#include "clientlistdialog.h"
#include "utility.h"
#include "fileserver.h"
#include "generalsetupdialog.h"
#define DISCOVERY_PORT 45453
#define SERVER_SOCKET_PORT 45454
#define SPOT_UPDATER_PORT 45455
#define SLIDE_UPDATER_PORT 45456
/*!
* \brief ScoreController::ScoreController
* This is the base class of all the game controllers
* \param myPanelType
* \param parent
*/
ScoreController::ScoreController(int myPanelType, QWidget *parent)
: QWidget(parent)
, pSettings(Q_NULLPTR)
, pGeneralSetupDialog(Q_NULLPTR)
, panelType(myPanelType)
, pClientListDialog(Q_NULLPTR)
, discoveryPort(DISCOVERY_PORT)
, serverPort(SERVER_SOCKET_PORT)
, discoveryAddress(QHostAddress("224.0.0.1"))
, pSlideServerThread(Q_NULLPTR)
, pSlideUpdaterServer(Q_NULLPTR)
, slideUpdaterPort(SLIDE_UPDATER_PORT)
, pSpotServerThread(Q_NULLPTR)
, pSpotUpdaterServer(Q_NULLPTR)
, spotUpdaterPort(SPOT_UPDATER_PORT)
{
// For Message Logging...
logFile = Q_NULLPTR;
QIcon myIcon(WINDOW_ICON);
setWindowIcon(myIcon);
// Block until a network connection is available
if(WaitForNetworkReady() != QMessageBox::Ok) {
exit(0);
}
// Initialize some useful dialogs...
pGeneralSetupDialog = new GeneralSetupDialog(panelType, this);
pClientListDialog = new ClientListDialog(this);
#ifdef Q_OS_ANDROID
pGeneralSetupDialog->setWindowFlags(Qt::Window);
pClientListDialog->setWindowFlags(Qt::Window);
#endif
// A List of IP Addresses of the connected Score Panels
sIpAddresses = QStringList();
// Logged messages (if enabled) will be written in the following folder
sLogDir = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation);
if(!sLogDir.endsWith(QString("/"))) sLogDir+= QString("/");
// The default Directories to look for the slides and spots
sSlideDir = QStandardPaths::writableLocation(QStandardPaths::PicturesLocation);
if(!sSlideDir.endsWith(QString("/"))) sSlideDir+= QString("/");
sSpotDir = QStandardPaths::writableLocation(QStandardPaths::MoviesLocation);
if(!sSpotDir.endsWith(QString("/"))) sSpotDir+= QString("/");
slideList = QFileInfoList();
spotList = QFileInfoList();
iCurrentSlide = 0;
iCurrentSpot = 0;
if((panelType < FIRST_PANEL_TYPE) ||
(panelType > LAST_PANEL_TYPE)) {
logMessage(logFile,
Q_FUNC_INFO,
QString("Panel Type forced to FIRST_PANEL_TYPE"));
panelType = FIRST_PANEL_TYPE;
}
// Pan-Tilt Camera management
connect(pClientListDialog, SIGNAL(disableVideo()),
this, SLOT(onStopCamera()));
connect(pClientListDialog, SIGNAL(enableVideo(QString)),
this, SLOT(onStartCamera(QString)));
connect(pClientListDialog, SIGNAL(newPanValue(QString,int)),
this, SLOT(onSetNewPanValue(QString,int)));
connect(pClientListDialog, SIGNAL(newTiltValue(QString,int)),
this, SLOT(onSetNewTiltValue(QString,int)));
// Panel orientation management
connect(pClientListDialog, SIGNAL(getDirection(QString)),
this, SLOT(onGetPanelDirection(QString)));
connect(pClientListDialog, SIGNAL(changeDirection(QString,PanelDirection)),
this, SLOT(onChangePanelDirection(QString,PanelDirection)));
// Score Only Panel management
connect(pClientListDialog, SIGNAL(getScoreOnly(QString)),
this, SLOT(onGetIsPanelScoreOnly(QString)));
connect(pClientListDialog, SIGNAL(changeScoreOnly(QString,bool)),
this, SLOT(onSetScoreOnly(QString,bool)));
myStatus = showPanel;
}
/*!
* \brief ScoreController::prepareServices Prepare all the services for the Score Panels
*
* It Starts the Discovery service as well as the Slide and Spot file transfer services
* It start the ScorePanel Server too.
*/
void
ScoreController::prepareServices() {
// Start listening to the discovery port
if(!prepareDiscovery()) {
logMessage(logFile,
Q_FUNC_INFO,
QString("!prepareDiscovery()"));
close();
}
// Prepare the Server port for the Panels to connect to
else if(!prepareServer()) {
close();
}
else {
prepareSpotUpdateService();
prepareSlideUpdateService();
}
}
/*!
* \brief ScoreController::prepareDirectories
* To select the directories from which the Slides and the Spots will be taken.
*/
void
ScoreController::prepareDirectories() {
QDir slideDir(sSlideDir);
QDir spotDir(sSpotDir);
if(!slideDir.exists() || !spotDir.exists()) {
onButtonSetupClicked();
slideDir.setPath(sSlideDir);
if(!slideDir.exists())
sSlideDir = QStandardPaths::displayName(QStandardPaths::GenericDataLocation);
if(!sSlideDir.endsWith(QString("/"))) sSlideDir+= QString("/");
spotDir.setPath(sSpotDir);
if(!spotDir.exists())
sSpotDir = QStandardPaths::displayName(QStandardPaths::GenericDataLocation);
if(!sSpotDir.endsWith(QString("/"))) sSpotDir+= QString("/");
pSettings->setValue("directories/slides", sSlideDir);
pSettings->setValue("directories/spots", sSpotDir);
}
else {
QStringList filter(QStringList() << "*.jpg" << "*.jpeg" << "*.png" << "*.JPG" << "*.JPEG" << "*.PNG");
slideDir.setNameFilters(filter);
slideList = slideDir.entryInfoList();
#ifdef LOG_VERBOSE
logMessage(logFile,
Q_FUNC_INFO,
QString("Slides directory: %1 Found %2 Slides")
.arg(sSlideDir)
.arg(slideList.count()));
#endif
QStringList nameFilter(QStringList() << "*.mp4"<< "*.MP4");
spotDir.setNameFilters(nameFilter);
spotDir.setFilter(QDir::Files);
spotList = spotDir.entryInfoList();
#ifdef LOG_VERBOSE
logMessage(logFile,
Q_FUNC_INFO,
QString("Spot directory: %1 Found %2 Spots")
.arg(sSpotDir)
.arg(spotList.count()));
#endif
}
}
/*!
* \brief ScoreController::prepareSpotUpdateService Starts a "Spot Update" Service
*/
void
ScoreController::prepareSpotUpdateService() {
pSpotUpdaterServer = new FileServer(QString("SpotUpdater"), logFile, Q_NULLPTR);
connect(pSpotUpdaterServer, SIGNAL(fileServerDone(bool)),
this, SLOT(onSpotServerDone(bool)));
pSpotUpdaterServer->setServerPort(spotUpdaterPort);
pSpotServerThread = new QThread();
pSpotUpdaterServer->moveToThread(pSpotServerThread);
connect(this, SIGNAL(startSpotServer()),
pSpotUpdaterServer, SLOT(onStartServer()));
connect(this, SIGNAL(closeSpotServer()),
pSpotUpdaterServer, SLOT(onCloseServer()));
pSpotServerThread->start(QThread::LowestPriority);
}
/*!
* \brief ScoreController::prepareSlideUpdateService Starts a "Slide Update" Service
*/
void
ScoreController::prepareSlideUpdateService() {
pSlideUpdaterServer = new FileServer(QString("SlideUpdater"), logFile, Q_NULLPTR);
connect(pSlideUpdaterServer, SIGNAL(fileServerDone(bool)),
this, SLOT(onSlideServerDone(bool)));
pSlideUpdaterServer->setServerPort(slideUpdaterPort);
pSlideServerThread = new QThread();
pSlideUpdaterServer->moveToThread(pSlideServerThread);
connect(this, SIGNAL(startSlideServer()),
pSlideUpdaterServer, SLOT(onStartServer()));
connect(this, SIGNAL(closeSlideServer()),
pSlideUpdaterServer, SLOT(onCloseServer()));
pSlideServerThread->start(QThread::LowestPriority);
}
/*!
* \brief ScoreController::WaitForNetworkReady Wait For Network Ready
* \return
*/
int
ScoreController::WaitForNetworkReady() {
int iResponse;
while(!isConnectedToNetwork()) {
iResponse = QMessageBox::critical(this,
tr("Connessione Assente"),
tr("Connettiti alla rete e ritenta"),
QMessageBox::Retry,
QMessageBox::Abort);
if(iResponse == QMessageBox::Abort) {
return iResponse;
}
QThread::sleep(1);
}
return QMessageBox::Ok;
}
// Do nothing. All the housekeeping is done in "closeEvent()" manager
ScoreController::~ScoreController() = default;
/*!
* \brief ScoreController::onSlideServerDone
* Called from the Slide Updater Server when a transfer with a client has completed
* \param bError
*/
void
ScoreController::onSlideServerDone(bool bError) {
Q_UNUSED(bError)
#ifdef LOG_VERBOSE
// Log a Message just to inform
if(bError) {
logMessage(logFile,
Q_FUNC_INFO,
QString("Slide server stopped with errors"));
}
else {
logMessage(logFile,
Q_FUNC_INFO,
QString("Slide server stopped without errors"));
}
#endif
}
/*!
* \brief ScoreController::onSpotServerDone Called from the Spot Updater Server when a
* transfer with a client has completed
* \param bError
*/
void
ScoreController::onSpotServerDone(bool bError) {
Q_UNUSED(bError)
#ifdef LOG_VERBOSE
// Log a Message just to inform
if(bError) {
logMessage(logFile,
Q_FUNC_INFO,
QString("Spot server stopped with errors"));
}
else {
logMessage(logFile,
Q_FUNC_INFO,
QString("Spot server stopped without errors"));
}
#endif
}
/*!
* \brief ScoreController::prepareDiscover Start a "Discovery Service"y
* \return
*
* Start a "Discovery Service" that make possible to clients to discover
* the presence of this Score Controller Server, independently from its
* network address.
* It listen for a short message from clients and then
* send back an appropriate answer.
*/
bool
ScoreController::prepareDiscovery() {
bool bSuccess = false;
sIpAddresses = QStringList();
QList<QNetworkInterface> interfaceList = QNetworkInterface::allInterfaces();
for(int i=0; i<interfaceList.count(); i++)
{
const QNetworkInterface& interface = interfaceList.at(i);
if(interface.flags().testFlag(QNetworkInterface::IsUp) &&
interface.flags().testFlag(QNetworkInterface::IsRunning) &&
interface.flags().testFlag(QNetworkInterface::CanMulticast) &&
!interface.flags().testFlag(QNetworkInterface::IsLoopBack))
{
QList<QNetworkAddressEntry> list = interface.addressEntries();
for(int j=0; j<list.count(); j++)
{
if(list[j].ip().protocol() == QAbstractSocket::IPv4Protocol) {
auto* pDiscoverySocket = new QUdpSocket(this);
if(pDiscoverySocket->bind(QHostAddress::AnyIPv4, discoveryPort, QUdpSocket::ShareAddress)) {
pDiscoverySocket->joinMulticastGroup(discoveryAddress);
sIpAddresses.append(list[j].ip().toString());
discoverySocketArray.append(pDiscoverySocket);
connect(pDiscoverySocket, SIGNAL(readyRead()),
this, SLOT(onProcessConnectionRequest()));
bSuccess = true;
#ifdef LOG_VERBOSE
logMessage(logFile,
Q_FUNC_INFO,
QString("Listening for connections at address: %1 port:%2")
.arg(discoveryAddress.toString())
.arg(discoveryPort));
#endif
}
else {
logMessage(logFile,
Q_FUNC_INFO,
QString("Unable to bound %1")
.arg(discoveryAddress.toString()));
}
}
}// for(int j=0; j<list.count(); j++)
}
}// for(int i=0; i<interfaceList.count(); i++)
return bSuccess;
}
/*!
* \brief ScoreController::onStartCamera
* Called when the user asked to start the live camera
* \param sClientIp
*/
void
ScoreController::onStartCamera(const QString& sClientIp) {
QHostAddress hostAddress(sClientIp);
for(int i=0; i<connectionList.count(); i++) {
if(connectionList.at(i).clientAddress.toIPv4Address() == hostAddress.toIPv4Address()) {
QString sMessage = QString("<live>1</live>");
SendToOne(connectionList.at(i).pClientSocket, sMessage);
sMessage = QString("<getPanTilt>1</getPanTilt>");
SendToOne(connectionList.at(i).pClientSocket, sMessage);
return;
}
myStatus = showCamera;
}
}
/*!
* \brief ScoreController::onStopCamera Called when the user asked to stop the live camera
*/
void
ScoreController::onStopCamera() {
QString sMessage = QString("<endlive>1</endlive>");
SendToAll(sMessage);
myStatus = showPanel;
}
/*!
* \brief ScoreController::onSetNewPanValue
* Called when the user asked to pan the live camera on a given Panel
* \param sClientIp
* \param newPan
*/
void
ScoreController::onSetNewPanValue(const QString& sClientIp, int newPan) {
QHostAddress hostAddress(sClientIp);
for(int i=0; i<connectionList.count(); i++) {
if(connectionList.at(i).clientAddress.toIPv4Address() == hostAddress.toIPv4Address()) {
QString sMessage = QString("<pan>%1</pan>").arg(newPan);
SendToOne(connectionList.at(i).pClientSocket, sMessage);
return;
}
}
}
/*!
* \brief ScoreController::onSetNewTiltValue
* Called when the user asked to tilt the live camera on a given Panel.
* \param sClientIp
* \param newTilt
*/
void
ScoreController::onSetNewTiltValue(const QString& sClientIp, int newTilt) {
QHostAddress hostAddress(sClientIp);
for(int i=0; i<connectionList.count(); i++) {
if(connectionList.at(i).clientAddress.toIPv4Address() == hostAddress.toIPv4Address()) {
QString sMessage = QString("<tilt>%1</tilt>").arg(newTilt);
SendToOne(connectionList.at(i).pClientSocket, sMessage);
return;
}
}
}
/*!
* \brief ScoreController::onSetScoreOnly
* Called when the user asked to set the panel to show only the score:
* No slides, spots or camera.
* \param sClientIp
* \param bScoreOnly
*/
void
ScoreController::onSetScoreOnly(const QString& sClientIp, bool bScoreOnly) {
#ifdef LOG_VERBOSE
logMessage(logFile,
Q_FUNC_INFO,
QString("Client %1 ScoreOnly: %2")
.arg(sClientIp)
.arg(bScoreOnly));
#endif
QHostAddress hostAddress(sClientIp);
for(int i=0; i<connectionList.count(); i++) {
if(connectionList.at(i).clientAddress.toIPv4Address() == hostAddress.toIPv4Address()) {
QString sMessage = QString("<setScoreOnly>%1</setScoreOnly>").arg(bScoreOnly);
SendToOne(connectionList.at(i).pClientSocket, sMessage);
return;
}
}
}
/*!
* \brief ScoreController::prepareLogFile
* Prepare the file for logging (if enabled at compilation time)
* \return
*/
bool
ScoreController::prepareLogFile() {
#if defined(LOG_MESG)
QFileInfo checkFile(logFileName);
if(checkFile.exists() && checkFile.isFile()) {
QDir renamed;
renamed.remove(logFileName+QString(".bkp"));
renamed.rename(logFileName, logFileName+QString(".bkp"));
}
logFile = new QFile(logFileName);
if (!logFile->open(QIODevice::WriteOnly)) {
QMessageBox::information(this, tr("Volley Controller"),
tr("Impossibile aprire il file %1: %2.")
.arg(logFileName, logFile->errorString()));
delete logFile;
logFile = Q_NULLPTR;
}
#endif
return true;
}
/*!
* \brief ScoreController::isConnectedToNetwork
* Chech if the computer is connected to a network
* \return true if a network connection is available
*/
bool
ScoreController::isConnectedToNetwork() {
QList<QNetworkInterface> ifaces = QNetworkInterface::allInterfaces();
bool result = false;
for(int i=0; i<ifaces.count(); i++) {
const QNetworkInterface& iface = ifaces.at(i);
if(iface.flags().testFlag(QNetworkInterface::IsUp) &&
iface.flags().testFlag(QNetworkInterface::IsRunning) &&
iface.flags().testFlag(QNetworkInterface::CanBroadcast) &&
!iface.flags().testFlag(QNetworkInterface::IsLoopBack))
{
for(int j=0; j<iface.addressEntries().count(); j++) {
if(!result) result = true;
}
}
}
#ifdef LOG_VERBOSE
logMessage(logFile,
Q_FUNC_INFO,
result ? QString("true") : QString("false"));
#endif
return result;
}
/*!
* \brief ScoreController::onProcessConnectionRequest Called when a new client ask to be connected
*/
void
ScoreController::onProcessConnectionRequest() {
QByteArray datagram, request;
QString sToken;
auto* pDiscoverySocket = qobject_cast<QUdpSocket*>(sender());
QString sNoData = QString("NoData");
QString sMessage;
Q_UNUSED(sMessage)
QHostAddress hostAddress;
quint16 port=0;
while(pDiscoverySocket->hasPendingDatagrams()) {
datagram.resize(int(pDiscoverySocket->pendingDatagramSize()));
pDiscoverySocket->readDatagram(datagram.data(), datagram.size(), &hostAddress, &port);
request.append(datagram.data());
/*!
* \todo Do we have to limit the maximum amount of data that can be received ???
*/
}
sToken = XML_Parse(request.data(), "getServer");
if(sToken != sNoData) {
sendAcceptConnection(pDiscoverySocket, hostAddress, port);
#ifdef LOG_VERBOSE
logMessage(logFile,
Q_FUNC_INFO,
QString("Connection request from: %1 at Address %2:%3")
.arg(sToken, hostAddress.toString())
.arg(port));
#endif
// If a Client with the same address asked for a Server it means that
// the connections has dropped (at least it think so). Then remove it
// from the connected clients list
RemoveClient(hostAddress);
#ifdef LOG_VERBOSE
logMessage(logFile,
Q_FUNC_INFO,
QString("Sent: %1")
.arg(sMessage));
#endif
UpdateUI();// To disable some buttons if this was the last client
}
}
/*!
* \brief ScoreController::sendAcceptConnection
* Called to accept a request connection from a Panel
* \param pDiscoverySocket
* \param hostAddress
* \param port
*
* It sends to the client the IP addresses that this server
* listen to for connections and the Panel Type to show.
*/
void
ScoreController::sendAcceptConnection(QUdpSocket* pDiscoverySocket, const QHostAddress& hostAddress, quint16 port) {
QString sString = QString("%1,%2").arg(sIpAddresses.at(0)).arg(panelType);
for(int i=1; i<sIpAddresses.count(); i++) {
sString += QString(";%1,%2").arg(sIpAddresses.at(i)).arg(panelType);
}
QString sMessage = "<serverIP>" + sString + "</serverIP>";
QByteArray datagram = sMessage.toUtf8();
qint64 bytesWritten = pDiscoverySocket->writeDatagram(datagram.data(), datagram.size(), hostAddress, port);
Q_UNUSED(bytesWritten)
if(bytesWritten != datagram.size()) {
logMessage(logFile,
Q_FUNC_INFO,
QString("Unable to send data !"));
}
}
/*!
* \brief ScoreController::closeEvent
* Manage the termination of this server
* \param event
*/
void
ScoreController::closeEvent(QCloseEvent *event) {
Q_UNUSED(event)
QString sMessage;
#ifdef LOG_VERBOSE
logMessage(logFile,
Q_FUNC_INFO,
QString("Closing"));
#endif
// Close all the discovery sockets
for(int i=0; i<discoverySocketArray.count(); i++) {
QUdpSocket* pSocket = discoverySocketArray.at(i);
if(pSocket != Q_NULLPTR) {
pSocket->disconnect();
if(pSocket->isValid())
pSocket->abort();
pSocket->deleteLater();
}
}
discoverySocketArray.clear();
//Close the file transfer servers (if active)
emit closeSpotServer();
emit closeSlideServer();
// If there are Panels connected would we switch they off ?
if(connectionList.count() > 0) {
QMessageBox msgBox;
msgBox.setText("Sto per Chiudere l'App...");
msgBox.setInformativeText("Spengo i pannelli ?");
msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
msgBox.setDefaultButton(QMessageBox::No);
int answer = msgBox.exec();
if(answer == QMessageBox::No) {
for(int i=0; i<connectionList.count(); i++) {
connectionList.at(i).pClientSocket->disconnect();
if(connectionList.at(i).pClientSocket->isValid())
connectionList.at(i).pClientSocket->close(QWebSocketProtocol::CloseCodeNormal,
"Server Closed");
connectionList.at(i).pClientSocket->deleteLater();
}
connectionList.clear();
}
else {
sMessage = "<kill>1</kill>";
SendToAll(sMessage);
}
}
// Close and delete the Panel Server
if(pPanelServer != Q_NULLPTR) {
pPanelServer->closeServer();
pPanelServer->deleteLater();
pPanelServer = Q_NULLPTR;
}
// Close and delete the QSettings Object
if(pSettings != Q_NULLPTR) {
delete pSettings;
pSettings = Q_NULLPTR;
}
// Close and delete the Clients List Dialog
if(pClientListDialog != Q_NULLPTR) {
pClientListDialog->disconnect();
delete pClientListDialog;
pClientListDialog = Q_NULLPTR;
}
// Close and delete the General Setup Dialog
if(pGeneralSetupDialog != Q_NULLPTR) {
pGeneralSetupDialog->disconnect();
delete pGeneralSetupDialog;
pGeneralSetupDialog = Q_NULLPTR;
}
// Close the Log File (if any) and delete the Log File Object
if(logFile) {
logFile->flush();
logFile->close();
delete logFile;
logFile = Q_NULLPTR;
}
#ifdef LOG_VERBOSE
logMessage(logFile,
Q_FUNC_INFO,
QString("Closed !"));
#endif
// Finally Close this widget
close();
}
/*!
* \brief ScoreController::prepareServer
* Prepare the Server for accepting new connections
* \return
*/
bool
ScoreController::prepareServer() {
pPanelServer = new NetServer(QString("PanelServer"), logFile, this);
if(!pPanelServer->prepareServer(serverPort)) {
#ifdef LOG_VERBOSE
logMessage(logFile,
Q_FUNC_INFO,
QString("prepareServer() Failed !"));
#endif
pPanelServer->deleteLater();
pPanelServer = Q_NULLPTR;
return false;
}
connect(pPanelServer, SIGNAL(newConnection(QWebSocket*)),
this, SLOT(onNewConnection(QWebSocket*)));
return true;
}
/*!
* \brief ScoreController::onProcessTextMessage
* Called to process the Text messages received by this Server
* \param sMessage
*/
void
ScoreController::onProcessTextMessage(QString sMessage) {
QString sToken;
QString sNoData = QString("NoData");
// The Panel is asking for the Status
sToken = XML_Parse(sMessage, "getStatus");
if(sToken != sNoData) {
auto *pClient = qobject_cast<QWebSocket *>(sender());
SendToOne(pClient, FormatStatusMsg());
}// getStatus
// The Panel communicates the local Pan and Tilt values
sToken = XML_Parse(sMessage, "pan_tilt");
if(sToken != sNoData) {
QStringList values = QStringList(sToken.split(",",Qt::SkipEmptyParts));
pClientListDialog->remotePanTiltReceived(values.at(0).toInt(), values.at(1).toInt());
}// pan_tilt
// The Panel communicates its orientation
sToken = XML_Parse(sMessage, "orientation");
if(sToken != sNoData) {
bool ok;
int iDirection = sToken.toInt(&ok);
if(!ok) {
logMessage(logFile,
Q_FUNC_INFO,
QString("Illegal Direction received: %1")
.arg(sToken));
return;
}
auto direction = static_cast<PanelDirection>(iDirection);
pClientListDialog->remoteDirectionReceived(direction);
}// orientation
// The Panel communicates if it shows only the score
sToken = XML_Parse(sMessage, "isScoreOnly");
if(sToken != sNoData) {
bool ok;
auto isScoreOnly = bool(sToken.toInt(&ok));
if(!ok) {
logMessage(logFile,
Q_FUNC_INFO,
QString("Illegal Score Only value received: %1")
.arg(sToken));
return;
}
pClientListDialog->remoteScoreOnlyValueReceived(isScoreOnly);
}// isScoreOnly
}
/*!
* \brief ScoreController::SendToAll
* Send the same message to all the connected clients
* \param sMessage The message sent
* \return
*/
int
ScoreController::SendToAll(const QString& sMessage) {
#ifdef LOG_VERBOSE
logMessage(logFile,
Q_FUNC_INFO,
sMessage);
#endif
for(int i=0; i< connectionList.count(); i++) {
SendToOne(connectionList.at(i).pClientSocket, sMessage);
}
return 0;
}
/*!
* \brief ScoreController::SendToOne
* Send a message to a single connected client
* \param pClient The client
* \param sMessage The message
* \return
*/
int
ScoreController::SendToOne(QWebSocket* pClient, const QString& sMessage) {
if (pClient->isValid()) {
for(int i=0; i< connectionList.count(); i++) {
if(connectionList.at(i).clientAddress.toIPv4Address() ==
pClient->peerAddress().toIPv4Address()) {
qint64 written = pClient->sendTextMessage(sMessage);
Q_UNUSED(written)
if(written != sMessage.length()) {
logMessage(logFile,
Q_FUNC_INFO,
QString("Error writing %1").arg(sMessage));
}
#ifdef LOG_VERBOSE
else {
logMessage(logFile,
Q_FUNC_INFO,
QString("Sent %1 to: %2")
.arg(sMessage, pClient->peerAddress().toString()));
}
#endif
break;
}
}
}
else {
logMessage(logFile,
Q_FUNC_INFO,
QString("Client socket is invalid !"));
RemoveClient(pClient->peerAddress());
UpdateUI();
}
return 0;
}
/*!
* \brief ScoreController::RemoveClient
* Remove a client from the list of connected clients rebuilding the list itself
* \param hAddress Address of the client to remove
*/
void
ScoreController::RemoveClient(const QHostAddress& hAddress) {
QString sFound = QString(" Not present");
Q_UNUSED(sFound)
QWebSocket *pClientToClose = Q_NULLPTR;
pClientListDialog->clear();
for(int i=connectionList.count()-1; i>=0; i--) {
if(connectionList.at(i).clientAddress.toIPv4Address() ==
hAddress.toIPv4Address())
{
pClientToClose = connectionList.at(i).pClientSocket;
pClientToClose->disconnect(); // No more events from this socket
if(pClientToClose->isValid())
pClientToClose->close(QWebSocketProtocol::CloseCodeNormal,
tr("Socket disconnection"));
pClientToClose->deleteLater();
pClientToClose = Q_NULLPTR;
connectionList.removeAt(i);
#ifdef LOG_VERBOSE
sFound = " Removed !";
logMessage(logFile,
Q_FUNC_INFO,
QString("%1 %2")
.arg(hAddress.toString(), sFound));
#endif
} else {
pClientListDialog->addItem(connectionList.at(i).clientAddress.toString());
}
}
}
/*!
* \brief ScoreController::UpdateUI
* To update the buttons upon the first connection or last disconnection
*/
void
ScoreController::UpdateUI() {
if(connectionList.count() == 1) {
startStopLoopSpotButton->setEnabled(true);
startStopSlideShowButton->setEnabled(true);
startStopLiveCameraButton->setEnabled(true);
panelControlButton->setEnabled(true);
//>>>>>>>generalSetupButton->setDisabled(true);
shutdownButton->setEnabled(true);
}
else if(connectionList.count() == 0) {
startStopLoopSpotButton->setDisabled(true);
QPixmap pixmap(":/buttonIcons/PlaySpots.png");
QIcon ButtonIcon(pixmap);
startStopLoopSpotButton->setIcon(ButtonIcon);
startStopLoopSpotButton->setIconSize(pixmap.rect().size());
startStopSlideShowButton->setDisabled(true);
pixmap.load(":/buttonIcons/PlaySlides.png");
ButtonIcon.addPixmap(pixmap);
startStopSlideShowButton->setIcon(ButtonIcon);
startStopSlideShowButton->setIconSize(pixmap.rect().size());
startStopLiveCameraButton->setDisabled(true);
pixmap.load(":/buttonIcons/Camera.png");
ButtonIcon.addPixmap(pixmap);
startStopLiveCameraButton->setIcon(ButtonIcon);
startStopLiveCameraButton->setIconSize(pixmap.rect().size());
panelControlButton->setDisabled(true);
generalSetupButton->setEnabled(true);
shutdownButton->setDisabled(true);
myStatus = showPanel;
}
}
/*!
* \brief ScoreController::onNewConnection
* Invoked when a new Panel ask to be connected
* \param pClient The Panel WebSocket pointer
*/
void
ScoreController::onNewConnection(QWebSocket *pClient) {
QHostAddress address = pClient->peerAddress();
QString sAddress = address.toString();
connect(pClient, SIGNAL(textMessageReceived(QString)),
this, SLOT(onProcessTextMessage(QString)));
connect(pClient, SIGNAL(binaryMessageReceived(QByteArray)),
this, SLOT(onProcessBinaryMessage(QByteArray)));
connect(pClient, SIGNAL(disconnected()),
this, SLOT(onClientDisconnected()));
RemoveClient(address);
connection newConnection;
newConnection.pClientSocket = pClient;
newConnection.clientAddress = address;
connectionList.append(newConnection);
pClientListDialog->addItem(sAddress);
UpdateUI();
#ifdef LOG_VERBOSE
logMessage(logFile,
Q_FUNC_INFO,
QString("Client connected: %1")
.arg(sAddress));
#endif
}
/*!
* \brief ScoreController::onClientDisconnected
* Invoked when a Panel disconnects (Usually because a network problem)
*/
void
ScoreController::onClientDisconnected() {
auto* pClient = qobject_cast<QWebSocket *>(sender());
#ifdef LOG_VERBOSE
QString sDiconnectedAddress = pClient->peerAddress().toString();
logMessage(logFile,
Q_FUNC_INFO,
QString("%1 disconnected because %2. Close code: %3")
.arg(sDiconnectedAddress, pClient->closeReason())
.arg(pClient->closeCode()));
#endif
RemoveClient(pClient->peerAddress());
UpdateUI();
}
/*!
* \brief ScoreController::onProcessBinaryMessage
* Should never be called !
* \param message
*/
void
ScoreController::onProcessBinaryMessage(QByteArray message) {
Q_UNUSED(message)
logMessage(logFile,
Q_FUNC_INFO,
QString("Unexpected binary message received !"));
}
/*!