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

Last change on this file since 2697 was 2697, checked in by mervart, 13 years ago
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
44#include "bnccaster.h"
45#include "bncrinex.h"
46#include "bncapp.h"
47#include "bncgetthread.h"
48#include "bncutils.h"
49#include "bncsettings.h"
50#include "RTCM/GPSDecoder.h"
51
52#define OLD_OBS_FORMAT 1
53
54class t_oldObsInternal {
55 public:
56
57 t_oldObsInternal(const t_obsInternal obs) {
58 strcpy(StatID, obs.StatID);
59 flags = 0;
60 satSys = obs.satSys;
61 satNum = obs.satNum;
62 slot = obs.slotNum;
63 GPSWeek = obs.GPSWeek;
64 GPSWeeks = obs.GPSWeeks;
65 C1 = obs.C1;
66 C2 = obs.C2;
67 P1 = obs.P1;
68 P2 = obs.P2;
69 L1 = obs.L1;
70 L2 = obs.L2;
71 slip_cnt_L1 = obs.slip_cnt_L1;
72 slip_cnt_L2 = obs.slip_cnt_L2;
73 lock_timei_L1 = -1;
74 lock_timei_L2 = -1;
75 S1 = obs.S1;
76 S2 = obs.S2;
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
103// Constructor
104////////////////////////////////////////////////////////////////////////////
105bncCaster::bncCaster(const QString& outFileName, int port) {
106
107 bncSettings settings;
108
109 connect(this, SIGNAL(newMessage(QByteArray,bool)),
110 (bncApp*) qApp, SLOT(slotMessage(const QByteArray,bool)));
111
112 if ( !outFileName.isEmpty() ) {
113 QString lName = outFileName;
114 expandEnvVar(lName);
115 _outFile = new QFile(lName);
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 }
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;
134 if ( !_server->listen(QHostAddress::Any, _port) ) {
135 emit newMessage("bncCaster: Cannot listen on sync port", true);
136 }
137 connect(_server, SIGNAL(newConnection()), this, SLOT(slotNewConnection()));
138 _sockets = new QList<QTcpSocket*>;
139 }
140 else {
141 _server = 0;
142 _sockets = 0;
143 }
144
145 int uPort = settings.value("outUPort").toInt();
146 if (uPort != 0) {
147 _uServer = new QTcpServer;
148 if ( !_uServer->listen(QHostAddress::Any, uPort) ) {
149 emit newMessage("bncCaster: Cannot listen on usync port", true);
150 }
151 connect(_uServer, SIGNAL(newConnection()), this, SLOT(slotNewUConnection()));
152 _uSockets = new QList<QTcpSocket*>;
153 }
154 else {
155 _uServer = 0;
156 _uSockets = 0;
157 }
158
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
173 _epochs = new QMultiMap<long, p_obs>;
174
175 _lastDumpSec = 0;
176
177 _confInterval = -1;
178}
179
180// Destructor
181////////////////////////////////////////////////////////////////////////////
182bncCaster::~bncCaster() {
183
184 QMutexLocker locker(&_mutex);
185
186 QListIterator<bncGetThread*> it(_threads);
187 while(it.hasNext()){
188 bncGetThread* thread = it.next();
189 thread->terminate();
190 }
191 delete _out;
192 delete _outFile;
193 delete _server;
194 delete _sockets;
195 delete _uServer;
196 delete _uSockets;
197 delete _nmeaServer;
198 delete _nmeaSockets;
199 if (_epochs) {
200 QListIterator<p_obs> it(_epochs->values());
201 while (it.hasNext()) {
202 delete it.next();
203 }
204 delete _epochs;
205 }
206}
207
208// New Observations
209////////////////////////////////////////////////////////////////////////////
210void bncCaster::newObs(const QByteArray staID, bool firstObs, p_obs obs) {
211
212 QMutexLocker locker(&_mutex);
213
214 obs->_status = t_obs::received;
215
216 long iSec = long(floor(obs->_o.GPSWeeks+0.5));
217 long newTime = obs->_o.GPSWeek * 7*24*3600 + iSec;
218
219 // Rename the Station
220 // ------------------
221 strncpy(obs->_o.StatID, staID.constData(),sizeof(obs->_o.StatID));
222 obs->_o.StatID[sizeof(obs->_o.StatID)-1] = '\0';
223
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 }
238 if (OLD_OBS_FORMAT) {
239 t_oldObsInternal oldObs(obs->_o);
240 int numBytes = sizeof(oldObs);
241 if (myWrite(sock, (const char*)(&oldObs), numBytes) != numBytes) {
242 ok = false;
243 }
244 }
245 else {
246 int numBytes = sizeof(obs->_o);
247 if (myWrite(sock, (const char*)(&obs->_o), numBytes) != numBytes) {
248 ok = false;
249 }
250 }
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
263 // First time, set the _lastDumpSec immediately
264 // --------------------------------------------
265 if (_lastDumpSec == 0) {
266 _lastDumpSec = newTime - 1;
267 }
268
269 // An old observation - throw it away
270 // ----------------------------------
271 if (newTime <= _lastDumpSec) {
272 if (firstObs) {
273 bncSettings settings;
274 if ( !settings.value("outFile").toString().isEmpty() ||
275 !settings.value("outPort").toString().isEmpty() ) {
276
277 QTime enomtime = QTime(0,0,0).addSecs(iSec);
278
279 emit( newMessage(QString("%1: Old epoch %2 (%3) thrown away")
280 .arg(staID.data()).arg(iSec)
281 .arg(enomtime.toString("HH:mm:ss"))
282 .toAscii(), true) );
283 }
284 }
285 delete obs;
286 return;
287 }
288
289 // Save the observation
290 // --------------------
291 _epochs->insert(newTime, obs);
292
293 // Dump Epochs
294 // -----------
295 if (newTime - _waitTime > _lastDumpSec) {
296 dumpEpochs(_lastDumpSec + 1, newTime - _waitTime);
297 _lastDumpSec = newTime - _waitTime;
298 }
299}
300
301// New Connection
302////////////////////////////////////////////////////////////////////////////
303void bncCaster::slotNewConnection() {
304 _sockets->push_back( _server->nextPendingConnection() );
305 emit( newMessage(QString("New client connection on sync port: # %1")
306 .arg(_sockets->size()).toAscii(), true) );
307}
308
309void bncCaster::slotNewUConnection() {
310 _uSockets->push_back( _uServer->nextPendingConnection() );
311 emit( newMessage(QString("New client connection on usync port: # %1")
312 .arg(_uSockets->size()).toAscii(), true) );
313}
314
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
321// Add New Thread
322////////////////////////////////////////////////////////////////////////////
323void bncCaster::addGetThread(bncGetThread* getThread, bool noNewThread) {
324
325 qRegisterMetaType<p_obs>("p_obs");
326 qRegisterMetaType<gpsephemeris>("gpsephemeris");
327 qRegisterMetaType<glonassephemeris>("glonassephemeris");
328
329 connect(getThread, SIGNAL(newObs(QByteArray, bool, p_obs)),
330 this, SLOT(newObs(QByteArray, bool, p_obs)),
331 Qt::DirectConnection);
332
333 connect(getThread, SIGNAL(getThreadFinished(QByteArray)),
334 this, SLOT(slotGetThreadFinished(QByteArray)));
335
336 connect(getThread, SIGNAL(newNMEAstr(QByteArray)),
337 this, SLOT(slotNewNMEAstr(QByteArray)));
338
339 connect(((bncApp*)qApp), SIGNAL(newEphGPS(gpsephemeris)),
340 getThread, SLOT(slotNewEphGPS(gpsephemeris)));
341
342 _staIDs.push_back(getThread->staID());
343 _threads.push_back(getThread);
344
345 if (noNewThread) {
346 getThread->run();
347 }
348 else {
349 getThread->start();
350 }
351}
352
353// Get Thread destroyed
354////////////////////////////////////////////////////////////////////////////
355void bncCaster::slotGetThreadFinished(QByteArray staID) {
356 QMutexLocker locker(&_mutex);
357
358 QListIterator<bncGetThread*> it(_threads);
359 while (it.hasNext()) {
360 bncGetThread* thread = it.next();
361 if (thread->staID() == staID) {
362 _threads.removeOne(thread);
363 }
364 }
365
366 _staIDs.removeAll(staID);
367 emit( newMessage(
368 QString("Decoding %1 stream(s)").arg(_staIDs.size()).toAscii(), true) );
369 if (_staIDs.size() == 0) {
370 emit(newMessage("bncCaster: Last get thread terminated", true));
371 emit getThreadsFinished();
372 }
373}
374
375// Dump Complete Epochs
376////////////////////////////////////////////////////////////////////////////
377void bncCaster::dumpEpochs(long minTime, long maxTime) {
378
379 const char begEpoch[] = "BEGEPOCH";
380 const char endEpoch[] = "ENDEPOCH";
381
382 const int begEpochNBytes = sizeof(begEpoch) - 1;
383 const int endEpochNBytes = sizeof(endEpoch) - 1;
384
385 for (long sec = minTime; sec <= maxTime; sec++) {
386
387 bool first = true;
388 QList<p_obs> allObs = _epochs->values(sec);
389
390 QListIterator<p_obs> it(allObs);
391 while (it.hasNext()) {
392 p_obs obs = it.next();
393
394 if (_samplingRate == 0 || sec % _samplingRate == 0) {
395
396 if (first) {
397 QTime enomtime = QTime(0,0,0).addSecs(static_cast<int>(floor(obs->_o.GPSWeeks+0.5)));
398// emit( newMessage( QString("Epoch %1 dumped").arg(enomtime.toString("HH:mm:ss")).toAscii(), true) ); // weber
399 }
400 // Output into the file
401 // --------------------
402 if (_out) {
403 if (first) {
404 _out->setFieldWidth(1); *_out << begEpoch << endl;
405 }
406
407 *_out << obs->_o.StatID << " " << obs->_o.GPSWeek << " ";
408 _out->setRealNumberPrecision(7);
409 *_out << obs->_o.GPSWeeks << " ";
410
411 *_out << bncRinex::rinexSatLine(obs->_o, ' ', ' ', ' ').c_str()
412 << endl;
413
414 if (!it.hasNext()) {
415 _out->setFieldWidth(1); *_out << endEpoch << endl;
416 }
417 _out->flush();
418 }
419
420 // Output into the socket
421 // ----------------------
422 if (_sockets) {
423 QMutableListIterator<QTcpSocket*> is(*_sockets);
424 while (is.hasNext()) {
425 QTcpSocket* sock = is.next();
426 if (sock->state() == QAbstractSocket::ConnectedState) {
427 bool ok = true;
428 if (first) {
429 if (myWrite(sock, begEpoch, begEpochNBytes) != begEpochNBytes) {
430 ok = false;
431 }
432 }
433 if (OLD_OBS_FORMAT) {
434 t_oldObsInternal oldObs(obs->_o);
435 int numBytes = sizeof(oldObs);
436 if (myWrite(sock, (const char*)(&oldObs), numBytes) != numBytes) {
437 ok = false;
438 }
439 }
440 else {
441 int numBytes = sizeof(obs->_o);
442 if (myWrite(sock, (const char*)(&obs->_o), numBytes) != numBytes) {
443 ok = false;
444 }
445 }
446 if (!it.hasNext()) {
447 if (myWrite(sock, endEpoch, endEpochNBytes) != endEpochNBytes) {
448 ok = false;
449 }
450 }
451 if (!ok) {
452 delete sock;
453 is.remove();
454 }
455 }
456 else if (sock->state() != QAbstractSocket::ConnectingState) {
457 delete sock;
458 is.remove();
459 }
460 }
461 }
462 }
463
464 delete obs;
465 _epochs->remove(sec);
466 first = false;
467 }
468 }
469}
470
471// Reread configuration
472////////////////////////////////////////////////////////////////////////////
473void bncCaster::slotReadMountPoints() {
474
475 bncSettings settings;
476
477 // Reread several options
478 // ----------------------
479 _samplingRate = settings.value("binSampl").toInt();
480 _waitTime = settings.value("waitTime").toInt();
481 if (_waitTime < 1) {
482 _waitTime = 1;
483 }
484
485 // Add new mountpoints
486 // -------------------
487 int iMount = -1;
488 QListIterator<QString> it(settings.value("mountPoints").toStringList());
489 while (it.hasNext()) {
490 ++iMount;
491 QStringList hlp = it.next().split(" ");
492 if (hlp.size() <= 1) continue;
493 QUrl url(hlp[0]);
494
495 // Does it already exist?
496 // ----------------------
497 bool existFlg = false;
498 QListIterator<bncGetThread*> iTh(_threads);
499 while (iTh.hasNext()) {
500 bncGetThread* thread = iTh.next();
501 if (thread->mountPoint() == url) {
502 existFlg = true;
503 break;
504 }
505 }
506
507 // New bncGetThread
508 // ----------------
509 if (!existFlg) {
510 QByteArray format = hlp[1].toAscii();
511 QByteArray latitude = hlp[2].toAscii();
512 QByteArray longitude = hlp[3].toAscii();
513 QByteArray nmea = hlp[4].toAscii();
514 QByteArray ntripVersion = hlp[5].toAscii();
515
516 bncGetThread* getThread = new bncGetThread(url, format, latitude,
517 longitude, nmea, ntripVersion, "");
518 addGetThread(getThread);
519 }
520 }
521
522 // Remove mountpoints
523 // ------------------
524 QListIterator<bncGetThread*> iTh(_threads);
525 while (iTh.hasNext()) {
526 bncGetThread* thread = iTh.next();
527
528 bool existFlg = false;
529 QListIterator<QString> it(settings.value("mountPoints").toStringList());
530 while (it.hasNext()) {
531 QStringList hlp = it.next().split(" ");
532 if (hlp.size() <= 1) continue;
533 QUrl url(hlp[0]);
534
535 if (thread->mountPoint() == url) {
536 existFlg = true;
537 break;
538 }
539 }
540
541 if (!existFlg) {
542 disconnect(thread, 0, 0, 0);
543 _staIDs.removeAll(thread->staID());
544 _threads.removeAll(thread);
545 thread->terminate();
546 }
547 }
548
549 emit mountPointsRead(_threads);
550 emit( newMessage(QString("Configuration read: "
551 + ((bncApp*) qApp)->confFileName()
552 + ", %1 stream(s)")
553 .arg(_threads.count()).toAscii(), true) );
554
555 // (Re-) Start the configuration timer
556 // -----------------------------------
557 int ms = 0;
558
559 if (_confInterval != -1) {
560 ms = 1000 * _confInterval;
561 }
562 else {
563 QTime currTime = currentDateAndTimeGPS().time();
564 QTime nextShotTime;
565
566 if (settings.value("onTheFlyInterval").toString() == "1 min") {
567 _confInterval = 60;
568 nextShotTime = QTime(currTime.hour(), currTime.minute()+1, 0);
569 }
570 else if (settings.value("onTheFlyInterval").toString() == "1 hour") {
571 _confInterval = 3600;
572 nextShotTime = QTime(currTime.hour()+1, 0, 0);
573 }
574 else {
575 _confInterval = 86400;
576 nextShotTime = QTime(23, 59, 59, 999);
577 }
578
579 ms = currTime.msecsTo(nextShotTime);
580 if (ms < 30000) {
581 ms = 30000;
582 }
583 }
584
585 QTimer::singleShot(ms, this, SLOT(slotReadMountPoints()));
586}
587
588//
589////////////////////////////////////////////////////////////////////////////
590int bncCaster::myWrite(QTcpSocket* sock, const char* buf, int bufLen) {
591 sock->write(buf, bufLen);
592 for (int ii = 1; ii <= 10; ii++) {
593 if (sock->waitForBytesWritten(10)) { // wait 10 ms
594 return bufLen;
595 }
596 }
597 return -1;
598}
599
600//
601////////////////////////////////////////////////////////////////////////////
602void bncCaster::slotNewNMEAstr(QByteArray str) {
603 if (_nmeaSockets) {
604 QMutableListIterator<QTcpSocket*> is(*_nmeaSockets);
605 while (is.hasNext()) {
606 QTcpSocket* sock = is.next();
607 if (sock->state() == QAbstractSocket::ConnectedState) {
608 sock->write(str);
609 }
610 else if (sock->state() != QAbstractSocket::ConnectingState) {
611 delete sock;
612 is.remove();
613 }
614 }
615 }
616}
Note: See TracBrowser for help on using the repository browser.