source: ntrip/branches/BNC_2.11.0/src/bnccaster.cpp@ 6630

Last change on this file since 6630 was 5649, checked in by weber, 11 years ago

Comment lines edited

File size: 17.9 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#include "RTCM/GPSDecoder.h"
54#ifdef RTROVER_INTERFACE
55# include "RTRover/bncrtrover.h"
56#endif
57
58using namespace std;
59
60// Constructor
61////////////////////////////////////////////////////////////////////////////
62bncCaster::bncCaster() {
63
64 bncSettings settings;
65
66 connect(this, SIGNAL(newMessage(QByteArray,bool)),
67 BNC_CORE, SLOT(slotMessage(const QByteArray,bool)));
68
69 _outFile = 0;
70 _out = 0;
71 reopenOutFile();
72
73 _port = settings.value("outPort").toInt();
74
75 if (_port != 0) {
76 _server = new QTcpServer;
77 if ( !_server->listen(QHostAddress::Any, _port) ) {
78 emit newMessage("bncCaster: Cannot listen on sync port", true);
79 }
80 connect(_server, SIGNAL(newConnection()), this, SLOT(slotNewConnection()));
81 _sockets = new QList<QTcpSocket*>;
82 }
83 else {
84 _server = 0;
85 _sockets = 0;
86 }
87
88 int uPort = settings.value("outUPort").toInt();
89 if (uPort != 0) {
90 _uServer = new QTcpServer;
91 if ( !_uServer->listen(QHostAddress::Any, uPort) ) {
92 emit newMessage("bncCaster: Cannot listen on usync port", true);
93 }
94 connect(_uServer, SIGNAL(newConnection()), this, SLOT(slotNewUConnection()));
95 _uSockets = new QList<QTcpSocket*>;
96 }
97 else {
98 _uServer = 0;
99 _uSockets = 0;
100 }
101
102 int nmeaPort = settings.value("nmeaPort").toInt();
103 if (nmeaPort != 0) {
104 _nmeaServer = new QTcpServer;
105 if ( !_nmeaServer->listen(QHostAddress::Any, nmeaPort) ) {
106 emit newMessage("bncCaster: Cannot listen on port", true);
107 }
108 connect(_nmeaServer, SIGNAL(newConnection()), this, SLOT(slotNewNMEAConnection()));
109 _nmeaSockets = new QList<QTcpSocket*>;
110 }
111 else {
112 _nmeaServer = 0;
113 _nmeaSockets = 0;
114 }
115
116 _epochs = new QMultiMap<long, t_obs>;
117
118 _samplingRate = settings.value("binSampl").toInt();
119 _waitTime = settings.value("waitTime").toInt();
120 _lastDumpSec = 0;
121 _confInterval = -1;
122#ifdef RTROVER_INTERFACE
123 if (!settings.value("rtroverMode").toString().isEmpty()) {
124 _bncRtrover = new t_bncRtrover();
125 _bncRtrover->start();
126 }
127 else {
128 _bncRtrover = 0;
129 }
130#endif
131
132 // Miscellaneous output port
133 // -------------------------
134 _miscMount = settings.value("miscMount").toString();
135 _miscPort = settings.value("miscPort").toInt();
136 if (!_miscMount.isEmpty() && _miscPort != 0) {
137 _miscServer = new QTcpServer;
138 if ( !_miscServer->listen(QHostAddress::Any, _miscPort) ) {
139 emit newMessage("bncCaster: Cannot listen on Miscellaneous Output Port", true);
140 }
141 connect(_miscServer, SIGNAL(newConnection()), this, SLOT(slotNewMiscConnection()));
142 _miscSockets = new QList<QTcpSocket*>;
143 }
144 else {
145 _miscServer = 0;
146 _miscSockets = 0;
147 }
148}
149
150// Destructor
151////////////////////////////////////////////////////////////////////////////
152bncCaster::~bncCaster() {
153
154 QMutexLocker locker(&_mutex);
155
156 QListIterator<bncGetThread*> it(_threads);
157 while(it.hasNext()){
158 bncGetThread* thread = it.next();
159 thread->terminate();
160 }
161 delete _out;
162 delete _outFile;
163 delete _server;
164 delete _sockets;
165 delete _uServer;
166 delete _uSockets;
167 delete _nmeaServer;
168 delete _nmeaSockets;
169 delete _epochs;
170#ifdef RTROVER_INTERFACE
171 if (_bncRtrover) {
172 _bncRtrover->quit();
173 _bncRtrover->deleteLater();
174 }
175#endif
176 delete _miscServer;
177 delete _miscSockets;
178}
179
180// New Observations
181////////////////////////////////////////////////////////////////////////////
182void bncCaster::slotNewObs(const QByteArray staID, QList<t_obs> obsList) {
183
184 QMutexLocker locker(&_mutex);
185
186 reopenOutFile();
187
188 unsigned index = 0;
189 QMutableListIterator<t_obs> it(obsList);
190 while (it.hasNext()) {
191 ++index;
192 t_obs& obs = it.next();
193
194 long iSec = long(floor(obs.GPSWeeks+0.5));
195 long newTime = obs.GPSWeek * 7*24*3600 + iSec;
196
197 // Rename the Station
198 // ------------------
199 strncpy(obs.StatID, staID.constData(),sizeof(obs.StatID));
200 obs.StatID[sizeof(obs.StatID)-1] = '\0';
201
202 // Output into the socket
203 // ----------------------
204 if (_uSockets) {
205
206 ostringstream oStr;
207 oStr.setf(ios::showpoint | ios::fixed);
208 oStr << obs.StatID << " "
209 << setw(4) << obs.GPSWeek << " "
210 << setw(14) << setprecision(7) << obs.GPSWeeks << " "
211 << bncRinex::asciiSatLine(obs) << endl;
212
213 string hlpStr = oStr.str();
214
215 QMutableListIterator<QTcpSocket*> is(*_uSockets);
216 while (is.hasNext()) {
217 QTcpSocket* sock = is.next();
218 if (sock->state() == QAbstractSocket::ConnectedState) {
219 int numBytes = hlpStr.length();
220 if (myWrite(sock, hlpStr.c_str(), numBytes) != numBytes) {
221 delete sock;
222 is.remove();
223 }
224 }
225 else if (sock->state() != QAbstractSocket::ConnectingState) {
226 delete sock;
227 is.remove();
228 }
229 }
230 }
231
232 // First time, set the _lastDumpSec immediately
233 // --------------------------------------------
234 if (_lastDumpSec == 0) {
235 _lastDumpSec = newTime - 1;
236 }
237
238 // An old observation - throw it away
239 // ----------------------------------
240 if (newTime <= _lastDumpSec) {
241 if (index == 1) {
242 bncSettings settings;
243 if ( !settings.value("outFile").toString().isEmpty() ||
244 !settings.value("outPort").toString().isEmpty() ) {
245
246 QTime enomtime = QTime(0,0,0).addSecs(iSec);
247
248 emit( newMessage(QString("%1: Old epoch %2 (%3) thrown away")
249 .arg(staID.data()).arg(iSec)
250 .arg(enomtime.toString("HH:mm:ss"))
251 .toAscii(), true) );
252 }
253 }
254 continue;
255 }
256
257 // Save the observation
258 // --------------------
259 _epochs->insert(newTime, obs);
260
261 // Dump Epochs
262 // -----------
263 if (newTime - _waitTime > _lastDumpSec) {
264 dumpEpochs(_lastDumpSec + 1, newTime - _waitTime);
265 _lastDumpSec = newTime - _waitTime;
266 }
267 }
268}
269
270// New Connection
271////////////////////////////////////////////////////////////////////////////
272void bncCaster::slotNewConnection() {
273 _sockets->push_back( _server->nextPendingConnection() );
274 emit( newMessage(QString("New client connection on sync port: # %1")
275 .arg(_sockets->size()).toAscii(), true) );
276}
277
278void bncCaster::slotNewUConnection() {
279 _uSockets->push_back( _uServer->nextPendingConnection() );
280 emit( newMessage(QString("New client connection on usync port: # %1")
281 .arg(_uSockets->size()).toAscii(), true) );
282}
283
284void bncCaster::slotNewNMEAConnection() {
285 _nmeaSockets->push_back( _nmeaServer->nextPendingConnection() );
286 emit( newMessage(QString("New PPP client on port: # %1")
287 .arg(_nmeaSockets->size()).toAscii(), true) );
288}
289
290// Add New Thread
291////////////////////////////////////////////////////////////////////////////
292void bncCaster::addGetThread(bncGetThread* getThread, bool noNewThread) {
293
294 qRegisterMetaType<t_obs>("t_obs");
295 qRegisterMetaType< QList<t_obs> >("QList<t_obs>");
296 qRegisterMetaType<gpsephemeris>("gpsephemeris");
297 qRegisterMetaType<glonassephemeris>("glonassephemeris");
298 qRegisterMetaType<galileoephemeris>("galileoephemeris");
299
300 connect(getThread, SIGNAL(newObs(QByteArray, QList<t_obs>)),
301 this, SLOT(slotNewObs(QByteArray, QList<t_obs>)));
302
303 connect(getThread, SIGNAL(newRawData(QByteArray, QByteArray)),
304 this, SLOT(slotNewRawData(QByteArray, QByteArray)));
305
306#ifdef RTROVER_INTERFACE
307 if (_bncRtrover) {
308 connect(getThread, SIGNAL(newObs(QByteArray, QList<t_obs>)),
309 _bncRtrover, SLOT(slotNewObs(QByteArray, QList<t_obs>)));
310 }
311#endif
312
313 connect(getThread, SIGNAL(getThreadFinished(QByteArray)),
314 this, SLOT(slotGetThreadFinished(QByteArray)));
315
316 connect(getThread, SIGNAL(newNMEAstr(QByteArray)),
317 this, SLOT(slotNewNMEAstr(QByteArray)));
318
319 _staIDs.push_back(getThread->staID());
320 _threads.push_back(getThread);
321
322 if (noNewThread) {
323 getThread->run();
324 }
325 else {
326 getThread->start();
327 }
328}
329
330// Get Thread destroyed
331////////////////////////////////////////////////////////////////////////////
332void bncCaster::slotGetThreadFinished(QByteArray staID) {
333 QMutexLocker locker(&_mutex);
334
335 QListIterator<bncGetThread*> it(_threads);
336 while (it.hasNext()) {
337 bncGetThread* thread = it.next();
338 if (thread->staID() == staID) {
339 _threads.removeOne(thread);
340 }
341 }
342
343 _staIDs.removeAll(staID);
344 emit( newMessage(
345 QString("Decoding %1 stream(s)").arg(_staIDs.size()).toAscii(), true) );
346 if (_staIDs.size() == 0) {
347 emit(newMessage("bncCaster: Last get thread terminated", true));
348 emit getThreadsFinished();
349 }
350}
351
352// Dump Complete Epochs
353////////////////////////////////////////////////////////////////////////////
354void bncCaster::dumpEpochs(long minTime, long maxTime) {
355
356 for (long sec = minTime; sec <= maxTime; sec++) {
357
358 if ( (_out || _sockets) &&
359 (_samplingRate == 0 || sec % _samplingRate == 0) ) {
360
361 QList<t_obs> allObs = _epochs->values(sec);
362
363 QListIterator<t_obs> it(allObs);
364 bool firstObs = true;
365 while (it.hasNext()) {
366 const t_obs& obs = it.next();
367
368 ostringstream oStr;
369 oStr.setf(ios::showpoint | ios::fixed);
370 if (firstObs) {
371 firstObs = false;
372 oStr << "> " << obs.GPSWeek << ' '
373 << setprecision(7) << obs.GPSWeeks << endl;;
374 }
375 oStr << obs.StatID << ' ' << bncRinex::asciiSatLine(obs) << endl;
376 if (!it.hasNext()) {
377 oStr << endl;
378 }
379 string hlpStr = oStr.str();
380
381 // Output into the File
382 // --------------------
383 if (_out) {
384 *_out << hlpStr.c_str();
385 _out->flush();
386 }
387
388 // Output into the socket
389 // ----------------------
390 if (_sockets) {
391 QMutableListIterator<QTcpSocket*> is(*_sockets);
392 while (is.hasNext()) {
393 QTcpSocket* sock = is.next();
394 if (sock->state() == QAbstractSocket::ConnectedState) {
395 int numBytes = hlpStr.length();
396 if (myWrite(sock, hlpStr.c_str(), numBytes) != numBytes) {
397 delete sock;
398 is.remove();
399 }
400 }
401 else if (sock->state() != QAbstractSocket::ConnectingState) {
402 delete sock;
403 is.remove();
404 }
405 }
406 }
407 }
408 }
409 _epochs->remove(sec);
410 }
411}
412
413// Reread configuration (private slot)
414////////////////////////////////////////////////////////////////////////////
415void bncCaster::slotReadMountPoints() {
416
417 bncSettings settings;
418 settings.reRead();
419
420 readMountPoints();
421}
422
423// Read Mountpoints
424////////////////////////////////////////////////////////////////////////////
425void bncCaster::readMountPoints() {
426
427 bncSettings settings;
428
429 // Reread several options
430 // ----------------------
431 _samplingRate = settings.value("binSampl").toInt();
432 _waitTime = settings.value("waitTime").toInt();
433 if (_waitTime < 1) {
434 _waitTime = 1;
435 }
436
437 // Add new mountpoints
438 // -------------------
439 int iMount = -1;
440 QListIterator<QString> it(settings.value("mountPoints").toStringList());
441 while (it.hasNext()) {
442 ++iMount;
443 QStringList hlp = it.next().split(" ");
444 if (hlp.size() <= 1) continue;
445 QUrl url(hlp[0]);
446
447 // Does it already exist?
448 // ----------------------
449 bool existFlg = false;
450 QListIterator<bncGetThread*> iTh(_threads);
451 while (iTh.hasNext()) {
452 bncGetThread* thread = iTh.next();
453 if (thread->mountPoint() == url) {
454 existFlg = true;
455 break;
456 }
457 }
458
459 // New bncGetThread
460 // ----------------
461 if (!existFlg) {
462 QByteArray format = hlp[1].toAscii();
463 QByteArray latitude = hlp[2].toAscii();
464 QByteArray longitude = hlp[3].toAscii();
465 QByteArray nmea = hlp[4].toAscii();
466 QByteArray ntripVersion = hlp[5].toAscii();
467
468 bncGetThread* getThread = new bncGetThread(url, format, latitude,
469 longitude, nmea, ntripVersion);
470 addGetThread(getThread);
471 }
472 }
473
474 // Remove mountpoints
475 // ------------------
476 QListIterator<bncGetThread*> iTh(_threads);
477 while (iTh.hasNext()) {
478 bncGetThread* thread = iTh.next();
479
480 bool existFlg = false;
481 QListIterator<QString> it(settings.value("mountPoints").toStringList());
482 while (it.hasNext()) {
483 QStringList hlp = it.next().split(" ");
484 if (hlp.size() <= 1) continue;
485 QUrl url(hlp[0]);
486
487 if (thread->mountPoint() == url) {
488 existFlg = true;
489 break;
490 }
491 }
492
493 if (!existFlg) {
494 disconnect(thread, 0, 0, 0);
495 _staIDs.removeAll(thread->staID());
496 _threads.removeAll(thread);
497 thread->terminate();
498 }
499 }
500
501 emit mountPointsRead(_threads);
502 emit( newMessage(QString("Configuration read: "
503 + BNC_CORE->confFileName()
504 + ", %1 stream(s)")
505 .arg(_threads.count()).toAscii(), true) );
506
507 // (Re-) Start the configuration timer
508 // -----------------------------------
509 int ms = 0;
510
511 if (_confInterval != -1) {
512 ms = 1000 * _confInterval;
513 }
514 else {
515 QTime currTime = currentDateAndTimeGPS().time();
516 QTime nextShotTime;
517
518 if (settings.value("onTheFlyInterval").toString() == "1 min") {
519 _confInterval = 60;
520 nextShotTime = QTime(currTime.hour(), currTime.minute()+1, 0);
521 }
522 else if (settings.value("onTheFlyInterval").toString() == "5 min") {
523 _confInterval = 300;
524 nextShotTime = QTime(currTime.hour(), currTime.minute()+5, 0);
525 }
526 else if (settings.value("onTheFlyInterval").toString() == "1 hour") {
527 _confInterval = 3600;
528 nextShotTime = QTime(currTime.hour()+1, 0, 0);
529 }
530 else {
531 _confInterval = 86400;
532 nextShotTime = QTime(23, 59, 59, 999);
533 }
534
535 ms = currTime.msecsTo(nextShotTime);
536 if (ms < 30000) {
537 ms = 30000;
538 }
539 }
540
541 QTimer::singleShot(ms, this, SLOT(slotReadMountPoints()));
542}
543
544//
545////////////////////////////////////////////////////////////////////////////
546int bncCaster::myWrite(QTcpSocket* sock, const char* buf, int bufLen) {
547 sock->write(buf, bufLen);
548 for (int ii = 1; ii <= 10; ii++) {
549 if (sock->waitForBytesWritten(10)) { // wait 10 ms
550 return bufLen;
551 }
552 }
553 return -1;
554}
555
556//
557////////////////////////////////////////////////////////////////////////////
558void bncCaster::slotNewNMEAstr(QByteArray str) {
559 if (_nmeaSockets) {
560 QMutableListIterator<QTcpSocket*> is(*_nmeaSockets);
561 while (is.hasNext()) {
562 QTcpSocket* sock = is.next();
563 if (sock->state() == QAbstractSocket::ConnectedState) {
564 sock->write(str);
565 }
566 else if (sock->state() != QAbstractSocket::ConnectingState) {
567 delete sock;
568 is.remove();
569 }
570 }
571 }
572}
573
574//
575////////////////////////////////////////////////////////////////////////////
576void bncCaster::reopenOutFile() {
577
578 bncSettings settings;
579
580 QString outFileName = settings.value("outFile").toString();
581 if ( !outFileName.isEmpty() ) {
582 expandEnvVar(outFileName);
583 if (!_outFile || _outFile->fileName() != outFileName) {
584 delete _out;
585 delete _outFile;
586 _outFile = new QFile(outFileName);
587 if ( Qt::CheckState(settings.value("rnxAppend").toInt()) == Qt::Checked) {
588 _outFile->open(QIODevice::WriteOnly | QIODevice::Append);
589 }
590 else {
591 _outFile->open(QIODevice::WriteOnly);
592 }
593 _out = new QTextStream(_outFile);
594 _out->setRealNumberNotation(QTextStream::FixedNotation);
595 }
596 }
597 else {
598 delete _out; _out = 0;
599 delete _outFile; _outFile = 0;
600 }
601}
602
603// Output into the Miscellaneous socket
604////////////////////////////////////////////////////////////////////////////
605void bncCaster::slotNewRawData(QByteArray staID, QByteArray data) {
606 if (_miscSockets && (_miscMount == "ALL" || _miscMount == staID)) {
607 QMutableListIterator<QTcpSocket*> is(*_miscSockets);
608 while (is.hasNext()) {
609 QTcpSocket* sock = is.next();
610 if (sock->state() == QAbstractSocket::ConnectedState) {
611 sock->write(data);
612 }
613 else if (sock->state() != QAbstractSocket::ConnectingState) {
614 delete sock;
615 is.remove();
616 }
617 }
618 }
619}
620
621// New Connection
622////////////////////////////////////////////////////////////////////////////
623void bncCaster::slotNewMiscConnection() {
624 _miscSockets->push_back( _miscServer->nextPendingConnection() );
625 emit( newMessage(QString("New client connection on Miscellaneous Output Port: # %1")
626 .arg(_miscSockets->size()).toAscii(), true) );
627}
Note: See TracBrowser for help on using the repository browser.