source: ntrip/trunk/BNC/src/bnccaster.cpp@ 6433

Last change on this file since 6433 was 6432, checked in by mervart, 10 years ago
File size: 17.4 KB
Line 
1// Part of BNC, a utility for retrieving decoding and
2// converting GNSS data streams from NTRIP broadcasters.
3//
4// Copyright (C) 2007
5// German Federal Agency for Cartography and Geodesy (BKG)
6// http://www.bkg.bund.de
7// Czech Technical University Prague, Department of Geodesy
8// http://www.fsv.cvut.cz
9//
10// Email: euref-ip@bkg.bund.de
11//
12// This program is free software; you can redistribute it and/or
13// modify it under the terms of the GNU General Public License
14// as published by the Free Software Foundation, version 2.
15//
16// This program is distributed in the hope that it will be useful,
17// but WITHOUT ANY WARRANTY; without even the implied warranty of
18// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19// GNU General Public License for more details.
20//
21// You should have received a copy of the GNU General Public License
22// along with this program; if not, write to the Free Software
23// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
24
25/* -------------------------------------------------------------------------
26 * BKG NTRIP Client
27 * -------------------------------------------------------------------------
28 *
29 * Class: bncCaster
30 *
31 * Purpose: buffers and disseminates the data
32 *
33 * Author: L. Mervart
34 *
35 * Created: 24-Dec-2005
36 *
37 * Changes:
38 *
39 * -----------------------------------------------------------------------*/
40
41#include <math.h>
42#include <unistd.h>
43#include <iostream>
44#include <iomanip>
45#include <sstream>
46
47#include "bnccaster.h"
48#include "bncrinex.h"
49#include "bnccore.h"
50#include "bncgetthread.h"
51#include "bncutils.h"
52#include "bncsettings.h"
53
54using namespace std;
55
56// Constructor
57////////////////////////////////////////////////////////////////////////////
58bncCaster::bncCaster() {
59
60 bncSettings settings;
61
62 connect(this, SIGNAL(newMessage(QByteArray,bool)),
63 BNC_CORE, SLOT(slotMessage(const QByteArray,bool)));
64
65 _outFile = 0;
66 _out = 0;
67 reopenOutFile();
68
69 _port = settings.value("outPort").toInt();
70
71 if (_port != 0) {
72 _server = new QTcpServer;
73 if ( !_server->listen(QHostAddress::Any, _port) ) {
74 emit newMessage("bncCaster: Cannot listen on sync port", true);
75 }
76 connect(_server, SIGNAL(newConnection()), this, SLOT(slotNewConnection()));
77 _sockets = new QList<QTcpSocket*>;
78 }
79 else {
80 _server = 0;
81 _sockets = 0;
82 }
83
84 int uPort = settings.value("outUPort").toInt();
85 if (uPort != 0) {
86 _uServer = new QTcpServer;
87 if ( !_uServer->listen(QHostAddress::Any, uPort) ) {
88 emit newMessage("bncCaster: Cannot listen on usync port", true);
89 }
90 connect(_uServer, SIGNAL(newConnection()), this, SLOT(slotNewUConnection()));
91 _uSockets = new QList<QTcpSocket*>;
92 }
93 else {
94 _uServer = 0;
95 _uSockets = 0;
96 }
97
98 int nmeaPort = settings.value("PPP/nmeaPort").toInt();
99 if (nmeaPort != 0) {
100 _nmeaServer = new QTcpServer;
101 if ( !_nmeaServer->listen(QHostAddress::Any, nmeaPort) ) {
102 emit newMessage("bncCaster: Cannot listen on port", true);
103 }
104 connect(_nmeaServer, SIGNAL(newConnection()), this, SLOT(slotNewNMEAConnection()));
105 connect(BNC_CORE, SIGNAL(newNMEAstr(QByteArray, QByteArray)),
106 this, SLOT(slotNewNMEAstr(QByteArray, QByteArray)));
107 _nmeaSockets = new QList<QTcpSocket*>;
108 }
109 else {
110 _nmeaServer = 0;
111 _nmeaSockets = 0;
112 }
113
114 _epochs = new QMultiMap<long, t_satObs>;
115
116 _samplingRate = settings.value("binSampl").toInt();
117 _waitTime = settings.value("waitTime").toInt();
118 _lastDumpSec = 0;
119 _confInterval = -1;
120
121 // Miscellaneous output port
122 // -------------------------
123 _miscMount = settings.value("miscMount").toString();
124 _miscPort = settings.value("miscPort").toInt();
125 if (!_miscMount.isEmpty() && _miscPort != 0) {
126 _miscServer = new QTcpServer;
127 if ( !_miscServer->listen(QHostAddress::Any, _miscPort) ) {
128 emit newMessage("bncCaster: Cannot listen on Miscellaneous Output Port", true);
129 }
130 connect(_miscServer, SIGNAL(newConnection()), this, SLOT(slotNewMiscConnection()));
131 _miscSockets = new QList<QTcpSocket*>;
132 }
133 else {
134 _miscServer = 0;
135 _miscSockets = 0;
136 }
137}
138
139// Destructor
140////////////////////////////////////////////////////////////////////////////
141bncCaster::~bncCaster() {
142
143 QMutexLocker locker(&_mutex);
144
145 QListIterator<bncGetThread*> it(_threads);
146 while(it.hasNext()){
147 bncGetThread* thread = it.next();
148 thread->terminate();
149 }
150 delete _out;
151 delete _outFile;
152 delete _server;
153 delete _sockets;
154 delete _uServer;
155 delete _uSockets;
156 delete _nmeaServer;
157 delete _nmeaSockets;
158 delete _epochs;
159 delete _miscServer;
160 delete _miscSockets;
161}
162
163// New Observations
164////////////////////////////////////////////////////////////////////////////
165void bncCaster::slotNewObs(const QByteArray staID, QList<t_satObs> obsList) {
166
167 QMutexLocker locker(&_mutex);
168
169 reopenOutFile();
170
171 unsigned index = 0;
172 QMutableListIterator<t_satObs> it(obsList);
173 while (it.hasNext()) {
174 ++index;
175 t_satObs& obs = it.next();
176
177 long iSec = long(floor(obs._time.gpssec()+0.5));
178 long newTime = obs._time.gpsw() * 7*24*3600 + iSec;
179
180 // Rename the Station
181 // ------------------
182 obs._staID = staID.data();
183
184 // Output into the socket
185 // ----------------------
186 if (_uSockets) {
187
188 ostringstream oStr;
189 oStr.setf(ios::showpoint | ios::fixed);
190 oStr << obs._staID << " "
191 << setw(4) << obs._time.gpsw() << " "
192 << setw(14) << setprecision(7) << obs._time.gpssec() << " "
193 << bncRinex::asciiSatLine(obs) << endl;
194
195 string hlpStr = oStr.str();
196
197 QMutableListIterator<QTcpSocket*> is(*_uSockets);
198 while (is.hasNext()) {
199 QTcpSocket* sock = is.next();
200 if (sock->state() == QAbstractSocket::ConnectedState) {
201 int numBytes = hlpStr.length();
202 if (myWrite(sock, hlpStr.c_str(), numBytes) != numBytes) {
203 delete sock;
204 is.remove();
205 }
206 }
207 else if (sock->state() != QAbstractSocket::ConnectingState) {
208 delete sock;
209 is.remove();
210 }
211 }
212 }
213
214 // First time, set the _lastDumpSec immediately
215 // --------------------------------------------
216 if (_lastDumpSec == 0) {
217 _lastDumpSec = newTime - 1;
218 }
219
220 // An old observation - throw it away
221 // ----------------------------------
222 if (newTime <= _lastDumpSec) {
223 if (index == 1) {
224 bncSettings settings;
225 if ( !settings.value("outFile").toString().isEmpty() ||
226 !settings.value("outPort").toString().isEmpty() ) {
227
228 QTime enomtime = QTime(0,0,0).addSecs(iSec);
229
230 emit( newMessage(QString("%1: Old epoch %2 (%3) thrown away")
231 .arg(staID.data()).arg(iSec)
232 .arg(enomtime.toString("HH:mm:ss"))
233 .toAscii(), true) );
234 }
235 }
236 continue;
237 }
238
239 // Save the observation
240 // --------------------
241 _epochs->insert(newTime, obs);
242
243 // Dump Epochs
244 // -----------
245 if (newTime - _waitTime > _lastDumpSec) {
246 dumpEpochs(_lastDumpSec + 1, newTime - _waitTime);
247 _lastDumpSec = newTime - _waitTime;
248 }
249 }
250}
251
252// New Connection
253////////////////////////////////////////////////////////////////////////////
254void bncCaster::slotNewConnection() {
255 _sockets->push_back( _server->nextPendingConnection() );
256 emit( newMessage(QString("New client connection on sync port: # %1")
257 .arg(_sockets->size()).toAscii(), true) );
258}
259
260void bncCaster::slotNewUConnection() {
261 _uSockets->push_back( _uServer->nextPendingConnection() );
262 emit( newMessage(QString("New client connection on usync port: # %1")
263 .arg(_uSockets->size()).toAscii(), true) );
264}
265
266void bncCaster::slotNewNMEAConnection() {
267 _nmeaSockets->push_back( _nmeaServer->nextPendingConnection() );
268 emit( newMessage(QString("New PPP client on port: # %1")
269 .arg(_nmeaSockets->size()).toAscii(), true) );
270}
271
272// Add New Thread
273////////////////////////////////////////////////////////////////////////////
274void bncCaster::addGetThread(bncGetThread* getThread, bool noNewThread) {
275
276 qRegisterMetaType<t_satObs>("t_satObs");
277 qRegisterMetaType< QList<t_satObs> >("QList<t_satObs>");
278
279 connect(getThread, SIGNAL(newObs(QByteArray, QList<t_satObs>)),
280 this, SLOT(slotNewObs(QByteArray, QList<t_satObs>)));
281
282 connect(getThread, SIGNAL(newObs(QByteArray, QList<t_satObs>)),
283 this, SIGNAL(newObs(QByteArray, QList<t_satObs>)));
284
285 connect(getThread, SIGNAL(newRawData(QByteArray, QByteArray)),
286 this, SLOT(slotNewRawData(QByteArray, QByteArray)));
287
288 connect(getThread, SIGNAL(getThreadFinished(QByteArray)),
289 this, SLOT(slotGetThreadFinished(QByteArray)));
290
291 _staIDs.push_back(getThread->staID());
292 _threads.push_back(getThread);
293
294 if (noNewThread) {
295 getThread->run();
296 }
297 else {
298 getThread->start();
299 }
300}
301
302// Get Thread destroyed
303////////////////////////////////////////////////////////////////////////////
304void bncCaster::slotGetThreadFinished(QByteArray staID) {
305 QMutexLocker locker(&_mutex);
306
307 QListIterator<bncGetThread*> it(_threads);
308 while (it.hasNext()) {
309 bncGetThread* thread = it.next();
310 if (thread->staID() == staID) {
311 _threads.removeOne(thread);
312 }
313 }
314
315 _staIDs.removeAll(staID);
316 emit( newMessage(
317 QString("Decoding %1 stream(s)").arg(_staIDs.size()).toAscii(), true) );
318 if (_staIDs.size() == 0) {
319 emit(newMessage("bncCaster: Last get thread terminated", true));
320 emit getThreadsFinished();
321 }
322}
323
324// Dump Complete Epochs
325////////////////////////////////////////////////////////////////////////////
326void bncCaster::dumpEpochs(long minTime, long maxTime) {
327
328 for (long sec = minTime; sec <= maxTime; sec++) {
329
330 if ( (_out || _sockets) &&
331 (_samplingRate == 0 || sec % _samplingRate == 0) ) {
332
333 QList<t_satObs> allObs = _epochs->values(sec);
334
335 QListIterator<t_satObs> it(allObs);
336 bool firstObs = true;
337 while (it.hasNext()) {
338 const t_satObs& obs = it.next();
339
340 ostringstream oStr;
341 oStr.setf(ios::showpoint | ios::fixed);
342 if (firstObs) {
343 firstObs = false;
344 oStr << "> " << obs._time.gpsw() << ' '
345 << setprecision(7) << obs._time.gpssec() << endl;;
346 }
347 oStr << obs._staID << ' ' << bncRinex::asciiSatLine(obs) << endl;
348 if (!it.hasNext()) {
349 oStr << endl;
350 }
351 string hlpStr = oStr.str();
352
353 // Output into the File
354 // --------------------
355 if (_out) {
356 *_out << hlpStr.c_str();
357 _out->flush();
358 }
359
360 // Output into the socket
361 // ----------------------
362 if (_sockets) {
363 QMutableListIterator<QTcpSocket*> is(*_sockets);
364 while (is.hasNext()) {
365 QTcpSocket* sock = is.next();
366 if (sock->state() == QAbstractSocket::ConnectedState) {
367 int numBytes = hlpStr.length();
368 if (myWrite(sock, hlpStr.c_str(), numBytes) != numBytes) {
369 delete sock;
370 is.remove();
371 }
372 }
373 else if (sock->state() != QAbstractSocket::ConnectingState) {
374 delete sock;
375 is.remove();
376 }
377 }
378 }
379 }
380 }
381 _epochs->remove(sec);
382 }
383}
384
385// Reread configuration (private slot)
386////////////////////////////////////////////////////////////////////////////
387void bncCaster::slotReadMountPoints() {
388
389 bncSettings settings;
390 settings.reRead();
391
392 readMountPoints();
393}
394
395// Read Mountpoints
396////////////////////////////////////////////////////////////////////////////
397void bncCaster::readMountPoints() {
398
399 bncSettings settings;
400
401 // Reread several options
402 // ----------------------
403 _samplingRate = settings.value("binSampl").toInt();
404 _waitTime = settings.value("waitTime").toInt();
405 if (_waitTime < 1) {
406 _waitTime = 1;
407 }
408
409 // Add new mountpoints
410 // -------------------
411 int iMount = -1;
412 QListIterator<QString> it(settings.value("mountPoints").toStringList());
413 while (it.hasNext()) {
414 ++iMount;
415 QStringList hlp = it.next().split(" ");
416 if (hlp.size() <= 1) continue;
417 QUrl url(hlp[0]);
418
419 // Does it already exist?
420 // ----------------------
421 bool existFlg = false;
422 QListIterator<bncGetThread*> iTh(_threads);
423 while (iTh.hasNext()) {
424 bncGetThread* thread = iTh.next();
425 if (thread->mountPoint() == url) {
426 existFlg = true;
427 break;
428 }
429 }
430
431 // New bncGetThread
432 // ----------------
433 if (!existFlg) {
434 QByteArray format = hlp[1].toAscii();
435 QByteArray latitude = hlp[2].toAscii();
436 QByteArray longitude = hlp[3].toAscii();
437 QByteArray nmea = hlp[4].toAscii();
438 QByteArray ntripVersion = hlp[5].toAscii();
439
440 bncGetThread* getThread = new bncGetThread(url, format, latitude,
441 longitude, nmea, ntripVersion);
442 addGetThread(getThread);
443 }
444 }
445
446 // Remove mountpoints
447 // ------------------
448 QListIterator<bncGetThread*> iTh(_threads);
449 while (iTh.hasNext()) {
450 bncGetThread* thread = iTh.next();
451
452 bool existFlg = false;
453 QListIterator<QString> it(settings.value("mountPoints").toStringList());
454 while (it.hasNext()) {
455 QStringList hlp = it.next().split(" ");
456 if (hlp.size() <= 1) continue;
457 QUrl url(hlp[0]);
458
459 if (thread->mountPoint() == url) {
460 existFlg = true;
461 break;
462 }
463 }
464
465 if (!existFlg) {
466 disconnect(thread, 0, 0, 0);
467 _staIDs.removeAll(thread->staID());
468 _threads.removeAll(thread);
469 thread->terminate();
470 }
471 }
472
473 emit mountPointsRead(_threads);
474 emit( newMessage(QString("Configuration read: "
475 + BNC_CORE->confFileName()
476 + ", %1 stream(s)")
477 .arg(_threads.count()).toAscii(), true) );
478
479 // (Re-) Start the configuration timer
480 // -----------------------------------
481 int ms = 0;
482
483 if (_confInterval != -1) {
484 ms = 1000 * _confInterval;
485 }
486 else {
487 QTime currTime = currentDateAndTimeGPS().time();
488 QTime nextShotTime;
489
490 if (settings.value("onTheFlyInterval").toString() == "1 min") {
491 _confInterval = 60;
492 nextShotTime = QTime(currTime.hour(), currTime.minute()+1, 0);
493 }
494 else if (settings.value("onTheFlyInterval").toString() == "5 min") {
495 _confInterval = 300;
496 nextShotTime = QTime(currTime.hour(), currTime.minute()+5, 0);
497 }
498 else if (settings.value("onTheFlyInterval").toString() == "1 hour") {
499 _confInterval = 3600;
500 nextShotTime = QTime(currTime.hour()+1, 0, 0);
501 }
502 else {
503 _confInterval = 86400;
504 nextShotTime = QTime(23, 59, 59, 999);
505 }
506
507 ms = currTime.msecsTo(nextShotTime);
508 if (ms < 30000) {
509 ms = 30000;
510 }
511 }
512
513 QTimer::singleShot(ms, this, SLOT(slotReadMountPoints()));
514}
515
516//
517////////////////////////////////////////////////////////////////////////////
518int bncCaster::myWrite(QTcpSocket* sock, const char* buf, int bufLen) {
519 sock->write(buf, bufLen);
520 for (int ii = 1; ii <= 10; ii++) {
521 if (sock->waitForBytesWritten(10)) { // wait 10 ms
522 return bufLen;
523 }
524 }
525 return -1;
526}
527
528//
529////////////////////////////////////////////////////////////////////////////
530void bncCaster::slotNewNMEAstr(QByteArray /* staID */, QByteArray str) {
531 if (_nmeaSockets) {
532 QMutableListIterator<QTcpSocket*> is(*_nmeaSockets);
533 while (is.hasNext()) {
534 QTcpSocket* sock = is.next();
535 if (sock->state() == QAbstractSocket::ConnectedState) {
536 sock->write(str);
537 }
538 else if (sock->state() != QAbstractSocket::ConnectingState) {
539 delete sock;
540 is.remove();
541 }
542 }
543 }
544}
545
546//
547////////////////////////////////////////////////////////////////////////////
548void bncCaster::reopenOutFile() {
549
550 bncSettings settings;
551
552 QString outFileName = settings.value("outFile").toString();
553 if ( !outFileName.isEmpty() ) {
554 expandEnvVar(outFileName);
555 if (!_outFile || _outFile->fileName() != outFileName) {
556 delete _out;
557 delete _outFile;
558 _outFile = new QFile(outFileName);
559 if ( Qt::CheckState(settings.value("rnxAppend").toInt()) == Qt::Checked) {
560 _outFile->open(QIODevice::WriteOnly | QIODevice::Append);
561 }
562 else {
563 _outFile->open(QIODevice::WriteOnly);
564 }
565 _out = new QTextStream(_outFile);
566 _out->setRealNumberNotation(QTextStream::FixedNotation);
567 }
568 }
569 else {
570 delete _out; _out = 0;
571 delete _outFile; _outFile = 0;
572 }
573}
574
575// Output into the Miscellaneous socket
576////////////////////////////////////////////////////////////////////////////
577void bncCaster::slotNewRawData(QByteArray staID, QByteArray data) {
578 if (_miscSockets && (_miscMount == "ALL" || _miscMount == staID)) {
579 QMutableListIterator<QTcpSocket*> is(*_miscSockets);
580 while (is.hasNext()) {
581 QTcpSocket* sock = is.next();
582 if (sock->state() == QAbstractSocket::ConnectedState) {
583 sock->write(data);
584 }
585 else if (sock->state() != QAbstractSocket::ConnectingState) {
586 delete sock;
587 is.remove();
588 }
589 }
590 }
591}
592
593// New Connection
594////////////////////////////////////////////////////////////////////////////
595void bncCaster::slotNewMiscConnection() {
596 _miscSockets->push_back( _miscServer->nextPendingConnection() );
597 emit( newMessage(QString("New client connection on Miscellaneous Output Port: # %1")
598 .arg(_miscSockets->size()).toAscii(), true) );
599}
Note: See TracBrowser for help on using the repository browser.