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

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