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

Last change on this file since 9092 was 9088, checked in by stuerze, 4 years ago

adjusted allocation of slip and LTI according to the respective RTCM version

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