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

Last change on this file since 9955 was 9955, checked in by stuerze, 15 months ago

minor changes

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#include <direct.h>
47#include <stdlib.h>
48#include <stdio.h>
49#endif
50#include <iostream>
51#include <iomanip>
52#include <sstream>
53
54#include "bnccaster.h"
55#include "bncrinex.h"
56#include "bnccore.h"
57#include "bncgetthread.h"
58#include "bncutils.h"
59#include "bncsettings.h"
60
61using namespace std;
62
63// Constructor
64////////////////////////////////////////////////////////////////////////////
65bncCaster::bncCaster() {
66
67 bncSettings settings;
68
69 connect(this, SIGNAL(newMessage(QByteArray,bool)),
70 BNC_CORE, SLOT(slotMessage(const QByteArray,bool)));
71
72 _outFile = 0;
73 _out = 0;
74 reopenOutFile();
75
76 int port = settings.value("outPort").toInt();
77
78 if (port != 0) {
79 _server = new QTcpServer;
80 _server->setProxy(QNetworkProxy::NoProxy);
81 if ( !_server->listen(QHostAddress::Any, port) ) {
82 QString message = "bncCaster: Cannot listen on sync port "
83 + QByteArray::number(port) + ": "
84 + _server->errorString();
85 emit newMessage(message.toLatin1(), true);
86 }
87 connect(_server, SIGNAL(newConnection()), this, SLOT(slotNewConnection()));
88 _sockets = new QList<QTcpSocket*>;
89 }
90 else {
91 _server = 0;
92 _sockets = 0;
93 }
94
95 int uPort = settings.value("outUPort").toInt();
96 if (uPort != 0) {
97 _uServer = new QTcpServer;
98 _uServer->setProxy(QNetworkProxy::NoProxy);
99 if ( !_uServer->listen(QHostAddress::Any, uPort) ) {
100 QString message = "bncCaster: Cannot listen on usync port "
101 + QByteArray::number(uPort) + ": "
102 + _uServer->errorString();
103 emit newMessage(message.toLatin1(), true);
104 }
105 connect(_uServer, SIGNAL(newConnection()), this, SLOT(slotNewUConnection()));
106 _uSockets = new QList<QTcpSocket*>;
107 }
108 else {
109 _uServer = 0;
110 _uSockets = 0;
111 }
112
113 _outLockTime = settings.value("outLockTime",false).toBool();
114 _samplingRateMult10 = int(settings.value("outSampl").toString().split("sec").first().toDouble() * 10.0);
115 _outWait = settings.value("outWait").toDouble();
116 if (_outWait <= 0.0) {
117 _outWait = 0.01;
118 }
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 _miscServer->setProxy(QNetworkProxy::NoProxy);
128 if ( !_miscServer->listen(QHostAddress::Any, _miscPort) ) {
129 QString message = "bncCaster: Cannot listen on miscellaneous output port "
130 + QByteArray::number(_miscPort) + ": "
131 + _miscServer->errorString();
132 emit newMessage(message.toLatin1(), true);
133 }
134 connect(_miscServer, SIGNAL(newConnection()), this, SLOT(slotNewMiscConnection()));
135 _miscSockets = new QList<QTcpSocket*>;
136 }
137 else {
138 _miscServer = 0;
139 _miscSockets = 0;
140 }
141}
142
143// Destructor
144////////////////////////////////////////////////////////////////////////////
145bncCaster::~bncCaster() {
146
147 QMutexLocker locker(&_mutex);
148
149 QListIterator<bncGetThread*> it(_threads);
150 while(it.hasNext()){
151 bncGetThread* thread = it.next();
152 disconnect(thread, 0, 0, 0);
153 _staIDs.removeAll(thread->staID());
154 _threads.removeAll(thread);
155 thread->terminate();
156 }
157 delete _out;
158 delete _outFile;
159 delete _server;
160 delete _sockets;
161 delete _uServer;
162 delete _uSockets;
163 delete _miscServer;
164 delete _miscSockets;
165}
166
167// New Observations
168////////////////////////////////////////////////////////////////////////////
169void bncCaster::slotNewObs(const QByteArray staID, QList<t_satObs> obsList) {
170
171 QMutexLocker locker(&_mutex);
172
173 reopenOutFile();
174
175 unsigned index = 0;
176 QMutableListIterator<t_satObs> it(obsList);
177 while (it.hasNext()) {
178 ++index;
179 t_satObs& obs = it.next();
180
181 // Rename the Station
182 // ------------------
183 obs._staID = staID.data();
184
185 // Update/Set Slip Counters
186 // ------------------------
187 setSlipCounters(obs);
188
189 // Output into the socket
190 // ----------------------
191 if (_uSockets) {
192
193 ostringstream oStr;
194 oStr.setf(ios::showpoint | ios::fixed);
195 oStr << obs._staID << " "
196 << setw(4) << obs._time.gpsw() << " "
197 << setw(14) << setprecision(7) << obs._time.gpssec() << " "
198 << bncRinex::asciiSatLine(obs,_outLockTime) << endl;
199
200 string hlpStr = oStr.str();
201
202 QMutableListIterator<QTcpSocket*> is(*_uSockets);
203 while (is.hasNext()) {
204 QTcpSocket* sock = is.next();
205 if (sock->state() == QAbstractSocket::ConnectedState) {
206 int numBytes = hlpStr.length();
207 if (myWrite(sock, hlpStr.c_str(), numBytes) != numBytes) {
208 delete sock;
209 is.remove();
210 }
211 }
212 else if (sock->state() != QAbstractSocket::ConnectingState) {
213 delete sock;
214 is.remove();
215 }
216 }
217 }
218
219 // First time: set the _lastDumpTime
220 // ---------------------------------
221 if (!_lastDumpTime.valid()) {
222 _lastDumpTime = obs._time - 1.0;
223 }
224
225 // An old observation - throw it away
226 // ----------------------------------
227 if (obs._time <= _lastDumpTime) {
228 if (index == 1) {
229 bncSettings settings;
230 if ( !settings.value("outFile").toString().isEmpty() ||
231 !settings.value("outPort").toString().isEmpty() ) {
232 emit( newMessage(QString("%1: Old or erroneous observation epoch %2 thrown away from %3")
233 .arg(staID.data())
234 .arg(string(obs._time).c_str())
235 .arg(obs._prn.toString().c_str())
236 .toLatin1(), true) );
237 }
238 }
239 continue;
240 }
241
242 // Save the observation
243 // --------------------
244 _epochs[obs._time].append(obs);
245
246 // Dump Epochs
247 // -----------
248 if ((obs._time - _outWait) > _lastDumpTime) {
249 dumpEpochs(obs._time - _outWait);
250 _lastDumpTime = obs._time - _outWait;
251 }
252 }
253}
254
255// New Connection
256////////////////////////////////////////////////////////////////////////////
257void bncCaster::slotNewConnection() {
258 _sockets->push_back( _server->nextPendingConnection() );
259 emit( newMessage(QString("New client connection on sync port: # %1")
260 .arg(_sockets->size()).toLatin1(), true) );
261}
262
263void bncCaster::slotNewUConnection() {
264 _uSockets->push_back( _uServer->nextPendingConnection() );
265 emit( newMessage(QString("New client connection on usync port: # %1")
266 .arg(_uSockets->size()).toLatin1(), true) );
267}
268
269// Add New Thread
270////////////////////////////////////////////////////////////////////////////
271void bncCaster::addGetThread(bncGetThread* getThread, bool noNewThread) {
272
273 qRegisterMetaType<t_satObs>("t_satObs");
274 qRegisterMetaType< QList<t_satObs> >("QList<t_satObs>");
275
276 connect(getThread, SIGNAL(newObs(QByteArray, QList<t_satObs>)),
277 this, SLOT(slotNewObs(QByteArray, QList<t_satObs>)));
278
279 connect(getThread, SIGNAL(newObs(QByteArray, QList<t_satObs>)),
280 this, SIGNAL(newObs(QByteArray, QList<t_satObs>)));
281
282 connect(getThread, SIGNAL(newRawData(QByteArray, QByteArray)),
283 this, SLOT(slotNewRawData(QByteArray, QByteArray)));
284
285 connect(getThread, SIGNAL(getThreadFinished(QByteArray)),
286 this, SLOT(slotGetThreadFinished(QByteArray)));
287
288 _staIDs.push_back(getThread->staID());
289 _threads.push_back(getThread);
290
291 if (noNewThread) {
292 getThread->run();
293 }
294 else {
295 getThread->start();
296 }
297}
298
299// Get Thread destroyed
300////////////////////////////////////////////////////////////////////////////
301void bncCaster::slotGetThreadFinished(QByteArray staID) {
302 QMutexLocker locker(&_mutex);
303
304 QListIterator<bncGetThread*> it(_threads);
305 while (it.hasNext()) {
306 bncGetThread* thread = it.next();
307 if (thread->staID() == staID) {
308 _threads.removeOne(thread);
309 }
310 }
311
312 _staIDs.removeAll(staID);
313 emit( newMessage(
314 QString("Decoding %1 stream(s)").arg(_staIDs.size()).toLatin1(), true) );
315 if (_staIDs.size() == 0) {
316 emit(newMessage("bncCaster: Last get thread terminated", true));
317 emit getThreadsFinished();
318 }
319}
320
321// Dump Complete Epochs
322////////////////////////////////////////////////////////////////////////////
323void bncCaster::dumpEpochs(const bncTime& maxTime) {
324
325 QMutableMapIterator<bncTime, QList<t_satObs> > itEpo(_epochs);
326 while (itEpo.hasNext()) {
327 itEpo.next();
328 const bncTime& epoTime = itEpo.key();
329 if (epoTime <= maxTime) {
330 const QList<t_satObs>& allObs = itEpo.value();
331 int sec = int(nint(epoTime.gpssec()*10));
332 if ( (_out || _sockets) && (sec % (_samplingRateMult10) == 0) ) {
333 QListIterator<t_satObs> it(allObs);
334 bool firstObs = true;
335 while (it.hasNext()) {
336 const t_satObs& obs = it.next();
337
338 ostringstream oStr;
339 oStr.setf(ios::showpoint | ios::fixed);
340 if (firstObs) {
341 firstObs = false;
342 oStr << "> " << obs._time.gpsw() << ' '
343 << setprecision(7) << obs._time.gpssec() << endl;
344 }
345 oStr << obs._staID << ' '
346 << bncRinex::asciiSatLine(obs,_outLockTime) << endl;
347 if (!it.hasNext()) {
348 oStr << endl;
349 }
350 string hlpStr = oStr.str();
351
352 // Output into the File
353 // --------------------
354 if (_out) {
355 *_out << hlpStr.c_str();
356 _out->flush();
357 }
358
359 // Output into the socket
360 // ----------------------
361 if (_sockets) {
362 QMutableListIterator<QTcpSocket*> is(*_sockets);
363 while (is.hasNext()) {
364 QTcpSocket* sock = is.next();
365 if (sock->state() == QAbstractSocket::ConnectedState) {
366 int numBytes = hlpStr.length();
367 if (myWrite(sock, hlpStr.c_str(), numBytes) != numBytes) {
368 delete sock;
369 is.remove();
370 }
371 }
372 else if (sock->state() != QAbstractSocket::ConnectingState) {
373 delete sock;
374 is.remove();
375 }
376 }
377 }
378 }
379 }
380 //_epochs.remove(epoTime);
381 itEpo.remove();
382 }
383 }
384}
385
386// Reread configuration (private slot)
387////////////////////////////////////////////////////////////////////////////
388void bncCaster::slotReadMountPoints() {
389
390 bncSettings settings;
391 settings.reRead();
392
393 readMountPoints();
394}
395
396// Read Mountpoints
397////////////////////////////////////////////////////////////////////////////
398void bncCaster::readMountPoints() {
399
400 bncSettings settings;
401
402 // Reread several options
403 // ----------------------
404 _samplingRateMult10 = int(settings.value("outSampl").toString().split("sec").first().toDouble() * 10.0);
405 _outWait = settings.value("outWait").toInt();
406 if (_outWait < 1) {
407 _outWait = 1;
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.