source: ntrip/trunk/BNC/bnccaster.cpp@ 2704

Last change on this file since 2704 was 2702, checked in by mervart, 15 years ago
File size: 17.9 KB
RevLine 
[280]1// Part of BNC, a utility for retrieving decoding and
[464]2// converting GNSS data streams from NTRIP broadcasters.
[280]3//
[464]4// Copyright (C) 2007
[280]5// German Federal Agency for Cartography and Geodesy (BKG)
6// http://www.bkg.bund.de
[464]7// Czech Technical University Prague, Department of Geodesy
[280]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.
[35]24
25/* -------------------------------------------------------------------------
[93]26 * BKG NTRIP Client
[35]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
[222]41#include <math.h>
[636]42#include <unistd.h>
[222]43
[35]44#include "bnccaster.h"
[2697]45#include "bncrinex.h"
[1170]46#include "bncapp.h"
[35]47#include "bncgetthread.h"
[134]48#include "bncutils.h"
[1535]49#include "bncsettings.h"
[207]50#include "RTCM/GPSDecoder.h"
[35]51
[2694]52#define OLD_OBS_FORMAT 1
53
54class t_oldObsInternal {
55 public:
56
[2702]57 t_oldObsInternal(const t_obs* obs) {
58 strcpy(StatID, obs->_o.StatID);
[2694]59 flags = 0;
[2702]60 satSys = obs->_o.satSys;
61 satNum = obs->_o.satNum;
62 slot = obs->_o.slotNum;
63 GPSWeek = obs->_o.GPSWeek;
64 GPSWeeks = obs->_o.GPSWeeks;
65 C1 = obs->_o.C1;
66 C2 = obs->_o.C2;
67 P1 = obs->_o.P1;
68 P2 = obs->_o.P2;
69 L1 = obs->L1();
70 L2 = obs->L2();
71 slip_cnt_L1 = obs->_o.slip_cnt_L1;
72 slip_cnt_L2 = obs->_o.slip_cnt_L2;
[2694]73 lock_timei_L1 = -1;
74 lock_timei_L2 = -1;
[2702]75 S1 = obs->S1();
76 S2 = obs->S2();
[2694]77 SNR1 = 0;
78 SNR2 = 0;
79 }
80 int flags;
81 char StatID[20+1]; // Station ID
82 char satSys; // Satellite System ('G' or 'R')
83 int satNum; // Satellite Number (PRN for GPS NAVSTAR)
84 int slot; // Slot Number (for Glonass)
85 int GPSWeek; // Week of GPS-Time
86 double GPSWeeks; // Second of Week (GPS-Time)
87 double C1; // CA-code pseudorange (meters)
88 double C2; // CA-code pseudorange (meters)
89 double P1; // P1-code pseudorange (meters)
90 double P2; // P2-code pseudorange (meters)
91 double L1; // L1 carrier phase (cycles)
92 double L2; // L2 carrier phase (cycles)
93 int slip_cnt_L1; // L1 cumulative loss of continuity indicator (negative$
94 int slip_cnt_L2; // L2 cumulative loss of continuity indicator (negative$
95 int lock_timei_L1; // L1 last lock time indicator (negative$
96 int lock_timei_L2; // L2 last lock time indicator (negative$
97 double S1; // L1 signal-to noise ratio
98 double S2; // L2 signal-to noise ratio
99 int SNR1; // L1 signal-to noise ratio (mapped to integer)
100 int SNR2; // L2 signal-to noise ratio (mapped to integer)
101};
102
[35]103// Constructor
104////////////////////////////////////////////////////////////////////////////
105bncCaster::bncCaster(const QString& outFileName, int port) {
106
[1535]107 bncSettings settings;
[275]108
[1299]109 connect(this, SIGNAL(newMessage(QByteArray,bool)),
110 (bncApp*) qApp, SLOT(slotMessage(const QByteArray,bool)));
[1228]111
[35]112 if ( !outFileName.isEmpty() ) {
[134]113 QString lName = outFileName;
114 expandEnvVar(lName);
115 _outFile = new QFile(lName);
[275]116 if ( Qt::CheckState(settings.value("rnxAppend").toInt()) == Qt::Checked) {
117 _outFile->open(QIODevice::WriteOnly | QIODevice::Append);
118 }
119 else {
120 _outFile->open(QIODevice::WriteOnly);
121 }
[35]122 _out = new QTextStream(_outFile);
123 _out->setRealNumberNotation(QTextStream::FixedNotation);
124 }
125 else {
126 _outFile = 0;
127 _out = 0;
128 }
129
130 _port = port;
131
132 if (_port != 0) {
133 _server = new QTcpServer;
[1228]134 if ( !_server->listen(QHostAddress::Any, _port) ) {
[1450]135 emit newMessage("bncCaster: Cannot listen on sync port", true);
[1228]136 }
[35]137 connect(_server, SIGNAL(newConnection()), this, SLOT(slotNewConnection()));
138 _sockets = new QList<QTcpSocket*>;
139 }
140 else {
141 _server = 0;
142 _sockets = 0;
143 }
144
[1222]145 int uPort = settings.value("outUPort").toInt();
146 if (uPort != 0) {
147 _uServer = new QTcpServer;
[1228]148 if ( !_uServer->listen(QHostAddress::Any, uPort) ) {
[1450]149 emit newMessage("bncCaster: Cannot listen on usync port", true);
[1228]150 }
[1222]151 connect(_uServer, SIGNAL(newConnection()), this, SLOT(slotNewUConnection()));
152 _uSockets = new QList<QTcpSocket*>;
153 }
154 else {
155 _uServer = 0;
156 _uSockets = 0;
157 }
158
[2183]159 int nmeaPort = settings.value("nmeaPort").toInt();
160 if (nmeaPort != 0) {
161 _nmeaServer = new QTcpServer;
162 if ( !_nmeaServer->listen(QHostAddress::Any, nmeaPort) ) {
163 emit newMessage("bncCaster: Cannot listen on port", true);
164 }
165 connect(_nmeaServer, SIGNAL(newConnection()), this, SLOT(slotNewNMEAConnection()));
166 _nmeaSockets = new QList<QTcpSocket*>;
167 }
168 else {
169 _nmeaServer = 0;
170 _nmeaSockets = 0;
171 }
172
[622]173 _epochs = new QMultiMap<long, p_obs>;
[35]174
[2316]175 _lastDumpSec = 0;
[133]176
[1705]177 _confInterval = -1;
[35]178}
179
180// Destructor
181////////////////////////////////////////////////////////////////////////////
182bncCaster::~bncCaster() {
[2647]183
184 QMutexLocker locker(&_mutex);
185
[186]186 QListIterator<bncGetThread*> it(_threads);
187 while(it.hasNext()){
188 bncGetThread* thread = it.next();
[1525]189 thread->terminate();
[186]190 }
[35]191 delete _out;
192 delete _outFile;
[187]193 delete _server;
[631]194 delete _sockets;
[1222]195 delete _uServer;
196 delete _uSockets;
[2186]197 delete _nmeaServer;
198 delete _nmeaSockets;
[603]199 if (_epochs) {
[622]200 QListIterator<p_obs> it(_epochs->values());
[603]201 while (it.hasNext()) {
202 delete it.next();
203 }
204 delete _epochs;
205 }
[35]206}
207
208// New Observations
209////////////////////////////////////////////////////////////////////////////
[622]210void bncCaster::newObs(const QByteArray staID, bool firstObs, p_obs obs) {
[35]211
[243]212 QMutexLocker locker(&_mutex);
213
[624]214 obs->_status = t_obs::received;
215
[2316]216 long iSec = long(floor(obs->_o.GPSWeeks+0.5));
217 long newTime = obs->_o.GPSWeek * 7*24*3600 + iSec;
[35]218
[160]219 // Rename the Station
220 // ------------------
[622]221 strncpy(obs->_o.StatID, staID.constData(),sizeof(obs->_o.StatID));
222 obs->_o.StatID[sizeof(obs->_o.StatID)-1] = '\0';
[160]223
[1222]224 const char begObs[] = "BEGOBS";
225 const int begObsNBytes = sizeof(begObs) - 1;
226
227 // Output into the socket
228 // ----------------------
229 if (_uSockets) {
230 QMutableListIterator<QTcpSocket*> is(*_uSockets);
231 while (is.hasNext()) {
232 QTcpSocket* sock = is.next();
233 if (sock->state() == QAbstractSocket::ConnectedState) {
234 bool ok = true;
235 if (myWrite(sock, begObs, begObsNBytes) != begObsNBytes) {
236 ok = false;
237 }
[2694]238 if (OLD_OBS_FORMAT) {
[2702]239 t_oldObsInternal oldObs(obs);
[2694]240 int numBytes = sizeof(oldObs);
241 if (myWrite(sock, (const char*)(&oldObs), numBytes) != numBytes) {
242 ok = false;
243 }
[1222]244 }
[2694]245 else {
246 int numBytes = sizeof(obs->_o);
247 if (myWrite(sock, (const char*)(&obs->_o), numBytes) != numBytes) {
248 ok = false;
249 }
250 }
[1222]251 if (!ok) {
252 delete sock;
253 is.remove();
254 }
255 }
256 else if (sock->state() != QAbstractSocket::ConnectingState) {
257 delete sock;
258 is.remove();
259 }
260 }
261 }
262
[35]263 // First time, set the _lastDumpSec immediately
264 // --------------------------------------------
[2316]265 if (_lastDumpSec == 0) {
266 _lastDumpSec = newTime - 1;
[35]267 }
268
269 // An old observation - throw it away
270 // ----------------------------------
[2316]271 if (newTime <= _lastDumpSec) {
[257]272 if (firstObs) {
[1535]273 bncSettings settings;
[257]274 if ( !settings.value("outFile").toString().isEmpty() ||
275 !settings.value("outPort").toString().isEmpty() ) {
[1810]276
[2316]277 QTime enomtime = QTime(0,0,0).addSecs(iSec);
[1810]278
279 emit( newMessage(QString("%1: Old epoch %2 (%3) thrown away")
[2316]280 .arg(staID.data()).arg(iSec)
[1810]281 .arg(enomtime.toString("HH:mm:ss"))
282 .toAscii(), true) );
[257]283 }
[181]284 }
[35]285 delete obs;
[350]286 return;
[35]287 }
288
[160]289 // Save the observation
290 // --------------------
[2316]291 _epochs->insert(newTime, obs);
[393]292
[462]293 // Dump Epochs
294 // -----------
[2316]295 if (newTime - _waitTime > _lastDumpSec) {
296 dumpEpochs(_lastDumpSec + 1, newTime - _waitTime);
297 _lastDumpSec = newTime - _waitTime;
[252]298 }
[35]299}
300
301// New Connection
302////////////////////////////////////////////////////////////////////////////
303void bncCaster::slotNewConnection() {
304 _sockets->push_back( _server->nextPendingConnection() );
[1450]305 emit( newMessage(QString("New client connection on sync port: # %1")
[1299]306 .arg(_sockets->size()).toAscii(), true) );
[35]307}
308
[1222]309void bncCaster::slotNewUConnection() {
310 _uSockets->push_back( _uServer->nextPendingConnection() );
[1450]311 emit( newMessage(QString("New client connection on usync port: # %1")
[1299]312 .arg(_uSockets->size()).toAscii(), true) );
[1222]313}
314
[2183]315void bncCaster::slotNewNMEAConnection() {
316 _nmeaSockets->push_back( _nmeaServer->nextPendingConnection() );
317 emit( newMessage(QString("New PPP client on port: # %1")
318 .arg(_nmeaSockets->size()).toAscii(), true) );
319}
320
[35]321// Add New Thread
322////////////////////////////////////////////////////////////////////////////
[2528]323void bncCaster::addGetThread(bncGetThread* getThread, bool noNewThread) {
[624]324
325 qRegisterMetaType<p_obs>("p_obs");
[2585]326 qRegisterMetaType<gpsephemeris>("gpsephemeris");
327 qRegisterMetaType<glonassephemeris>("glonassephemeris");
[624]328
[628]329 connect(getThread, SIGNAL(newObs(QByteArray, bool, p_obs)),
[2701]330 this, SLOT(newObs(QByteArray, bool, p_obs))); /// Qt::DirectConnection);
[463]331
[1556]332 connect(getThread, SIGNAL(getThreadFinished(QByteArray)),
333 this, SLOT(slotGetThreadFinished(QByteArray)));
[35]334
[2182]335 connect(getThread, SIGNAL(newNMEAstr(QByteArray)),
336 this, SLOT(slotNewNMEAstr(QByteArray)));
337
[1807]338 connect(((bncApp*)qApp), SIGNAL(newEphGPS(gpsephemeris)),
[2585]339 getThread, SLOT(slotNewEphGPS(gpsephemeris)));
[1807]340
[88]341 _staIDs.push_back(getThread->staID());
[186]342 _threads.push_back(getThread);
[1170]343
[2528]344 if (noNewThread) {
345 getThread->run();
346 }
347 else {
348 getThread->start();
349 }
[35]350}
351
[1556]352// Get Thread destroyed
[35]353////////////////////////////////////////////////////////////////////////////
[1556]354void bncCaster::slotGetThreadFinished(QByteArray staID) {
[243]355 QMutexLocker locker(&_mutex);
[1560]356
357 QListIterator<bncGetThread*> it(_threads);
358 while (it.hasNext()) {
359 bncGetThread* thread = it.next();
360 if (thread->staID() == staID) {
361 _threads.removeOne(thread);
362 }
363 }
364
[88]365 _staIDs.removeAll(staID);
[82]366 emit( newMessage(
[1986]367 QString("Decoding %1 stream(s)").arg(_staIDs.size()).toAscii(), true) );
[88]368 if (_staIDs.size() == 0) {
[1450]369 emit(newMessage("bncCaster: Last get thread terminated", true));
[1556]370 emit getThreadsFinished();
[35]371 }
372}
373
374// Dump Complete Epochs
375////////////////////////////////////////////////////////////////////////////
[2316]376void bncCaster::dumpEpochs(long minTime, long maxTime) {
[35]377
[1182]378 const char begEpoch[] = "BEGEPOCH";
379 const char endEpoch[] = "ENDEPOCH";
[35]380
[1182]381 const int begEpochNBytes = sizeof(begEpoch) - 1;
382 const int endEpochNBytes = sizeof(endEpoch) - 1;
383
[2316]384 for (long sec = minTime; sec <= maxTime; sec++) {
[140]385
[35]386 bool first = true;
[2316]387 QList<p_obs> allObs = _epochs->values(sec);
[1999]388
[622]389 QListIterator<p_obs> it(allObs);
[35]390 while (it.hasNext()) {
[622]391 p_obs obs = it.next();
[35]392
[2316]393 if (_samplingRate == 0 || sec % _samplingRate == 0) {
[1810]394
395 if (first) {
396 QTime enomtime = QTime(0,0,0).addSecs(static_cast<int>(floor(obs->_o.GPSWeeks+0.5)));
[1821]397// emit( newMessage( QString("Epoch %1 dumped").arg(enomtime.toString("HH:mm:ss")).toAscii(), true) ); // weber
[1810]398 }
[140]399 // Output into the file
400 // --------------------
401 if (_out) {
[35]402 if (first) {
[1810]403 _out->setFieldWidth(1); *_out << begEpoch << endl;
[35]404 }
[2697]405
406 *_out << obs->_o.StatID << " " << obs->_o.GPSWeek << " ";
407 _out->setRealNumberPrecision(7);
408 *_out << obs->_o.GPSWeeks << " ";
409
410 *_out << bncRinex::rinexSatLine(obs->_o, ' ', ' ', ' ').c_str()
411 << endl;
412
[35]413 if (!it.hasNext()) {
[341]414 _out->setFieldWidth(1); *_out << endEpoch << endl;
[35]415 }
[347]416 _out->flush();
[35]417 }
[140]418
419 // Output into the socket
420 // ----------------------
421 if (_sockets) {
[637]422 QMutableListIterator<QTcpSocket*> is(*_sockets);
[140]423 while (is.hasNext()) {
424 QTcpSocket* sock = is.next();
[397]425 if (sock->state() == QAbstractSocket::ConnectedState) {
[637]426 bool ok = true;
[397]427 if (first) {
[1182]428 if (myWrite(sock, begEpoch, begEpochNBytes) != begEpochNBytes) {
[637]429 ok = false;
430 }
[397]431 }
[2694]432 if (OLD_OBS_FORMAT) {
[2702]433 t_oldObsInternal oldObs(obs);
[2694]434 int numBytes = sizeof(oldObs);
435 if (myWrite(sock, (const char*)(&oldObs), numBytes) != numBytes) {
436 ok = false;
437 }
[637]438 }
[2694]439 else {
440 int numBytes = sizeof(obs->_o);
441 if (myWrite(sock, (const char*)(&obs->_o), numBytes) != numBytes) {
442 ok = false;
443 }
444 }
[397]445 if (!it.hasNext()) {
[1182]446 if (myWrite(sock, endEpoch, endEpochNBytes) != endEpochNBytes) {
[637]447 ok = false;
448 }
[397]449 }
[637]450 if (!ok) {
451 delete sock;
452 is.remove();
453 }
[140]454 }
[637]455 else if (sock->state() != QAbstractSocket::ConnectingState) {
456 delete sock;
457 is.remove();
458 }
[140]459 }
460 }
[73]461 }
462
[35]463 delete obs;
[2316]464 _epochs->remove(sec);
[35]465 first = false;
466 }
467 }
468}
[1170]469
470// Reread configuration
471////////////////////////////////////////////////////////////////////////////
[1179]472void bncCaster::slotReadMountPoints() {
[1170]473
[1535]474 bncSettings settings;
[1170]475
476 // Reread several options
477 // ----------------------
[2316]478 _samplingRate = settings.value("binSampl").toInt();
479 _waitTime = settings.value("waitTime").toInt();
480 if (_waitTime < 1) {
481 _waitTime = 1;
[1170]482 }
483
484 // Add new mountpoints
485 // -------------------
486 int iMount = -1;
487 QListIterator<QString> it(settings.value("mountPoints").toStringList());
488 while (it.hasNext()) {
489 ++iMount;
490 QStringList hlp = it.next().split(" ");
491 if (hlp.size() <= 1) continue;
492 QUrl url(hlp[0]);
493
494 // Does it already exist?
495 // ----------------------
496 bool existFlg = false;
497 QListIterator<bncGetThread*> iTh(_threads);
498 while (iTh.hasNext()) {
499 bncGetThread* thread = iTh.next();
500 if (thread->mountPoint() == url) {
501 existFlg = true;
502 break;
503 }
504 }
505
506 // New bncGetThread
507 // ----------------
508 if (!existFlg) {
509 QByteArray format = hlp[1].toAscii();
510 QByteArray latitude = hlp[2].toAscii();
511 QByteArray longitude = hlp[3].toAscii();
512 QByteArray nmea = hlp[4].toAscii();
[1353]513 QByteArray ntripVersion = hlp[5].toAscii();
[1170]514
515 bncGetThread* getThread = new bncGetThread(url, format, latitude,
[1770]516 longitude, nmea, ntripVersion, "");
[1170]517 addGetThread(getThread);
518 }
519 }
520
521 // Remove mountpoints
522 // ------------------
523 QListIterator<bncGetThread*> iTh(_threads);
524 while (iTh.hasNext()) {
525 bncGetThread* thread = iTh.next();
526
527 bool existFlg = false;
528 QListIterator<QString> it(settings.value("mountPoints").toStringList());
529 while (it.hasNext()) {
530 QStringList hlp = it.next().split(" ");
531 if (hlp.size() <= 1) continue;
532 QUrl url(hlp[0]);
533
534 if (thread->mountPoint() == url) {
535 existFlg = true;
536 break;
537 }
538 }
539
540 if (!existFlg) {
541 disconnect(thread, 0, 0, 0);
542 _staIDs.removeAll(thread->staID());
543 _threads.removeAll(thread);
544 thread->terminate();
545 }
546 }
547
[1179]548 emit mountPointsRead(_threads);
[1529]549 emit( newMessage(QString("Configuration read: "
[1542]550 + ((bncApp*) qApp)->confFileName()
[1529]551 + ", %1 stream(s)")
[1299]552 .arg(_threads.count()).toAscii(), true) );
[1176]553
[1170]554 // (Re-) Start the configuration timer
555 // -----------------------------------
556 int ms = 0;
557
[1705]558 if (_confInterval != -1) {
[1170]559 ms = 1000 * _confInterval;
560 }
561 else {
562 QTime currTime = currentDateAndTimeGPS().time();
563 QTime nextShotTime;
564
565 if (settings.value("onTheFlyInterval").toString() == "1 min") {
566 _confInterval = 60;
567 nextShotTime = QTime(currTime.hour(), currTime.minute()+1, 0);
568 }
569 else if (settings.value("onTheFlyInterval").toString() == "1 hour") {
570 _confInterval = 3600;
571 nextShotTime = QTime(currTime.hour()+1, 0, 0);
572 }
573 else {
574 _confInterval = 86400;
575 nextShotTime = QTime(23, 59, 59, 999);
576 }
577
578 ms = currTime.msecsTo(nextShotTime);
[1176]579 if (ms < 30000) {
580 ms = 30000;
581 }
[1170]582 }
583
[1705]584 QTimer::singleShot(ms, this, SLOT(slotReadMountPoints()));
[1170]585}
[1182]586
587//
588////////////////////////////////////////////////////////////////////////////
589int bncCaster::myWrite(QTcpSocket* sock, const char* buf, int bufLen) {
[1229]590 sock->write(buf, bufLen);
591 for (int ii = 1; ii <= 10; ii++) {
592 if (sock->waitForBytesWritten(10)) { // wait 10 ms
593 return bufLen;
[1182]594 }
595 }
[1229]596 return -1;
[1182]597}
[2182]598
599//
600////////////////////////////////////////////////////////////////////////////
601void bncCaster::slotNewNMEAstr(QByteArray str) {
[2184]602 if (_nmeaSockets) {
603 QMutableListIterator<QTcpSocket*> is(*_nmeaSockets);
604 while (is.hasNext()) {
605 QTcpSocket* sock = is.next();
606 if (sock->state() == QAbstractSocket::ConnectedState) {
607 sock->write(str);
608 }
609 else if (sock->state() != QAbstractSocket::ConnectingState) {
610 delete sock;
611 is.remove();
612 }
613 }
614 }
[2182]615}
Note: See TracBrowser for help on using the repository browser.