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

Last change on this file since 2711 was 2711, checked in by mervart, 13 years ago
File size: 17.6 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_obs& 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, t_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 delete _epochs;
200}
201
202// New Observations
203////////////////////////////////////////////////////////////////////////////
204void bncCaster::newObs(const QByteArray staID, bool firstObs, t_obs obs) {
205
206 QMutexLocker locker(&_mutex);
207
208 long iSec = long(floor(obs.GPSWeeks+0.5));
209 long newTime = obs.GPSWeek * 7*24*3600 + iSec;
210
211 // Rename the Station
212 // ------------------
213 strncpy(obs.StatID, staID.constData(),sizeof(obs.StatID));
214 obs.StatID[sizeof(obs.StatID)-1] = '\0';
215
216 const char begObs[] = "BEGOBS";
217 const int begObsNBytes = sizeof(begObs) - 1;
218
219 // Output into the socket
220 // ----------------------
221 if (_uSockets) {
222 QMutableListIterator<QTcpSocket*> is(*_uSockets);
223 while (is.hasNext()) {
224 QTcpSocket* sock = is.next();
225 if (sock->state() == QAbstractSocket::ConnectedState) {
226 bool ok = true;
227 if (myWrite(sock, begObs, begObsNBytes) != begObsNBytes) {
228 ok = false;
229 }
230 if (OLD_OBS_FORMAT) {
231 t_oldObsInternal oldObs(obs);
232 int numBytes = sizeof(oldObs);
233 if (myWrite(sock, (const char*)(&oldObs), numBytes) != numBytes) {
234 ok = false;
235 }
236 }
237 else {
238 int numBytes = sizeof(obs);
239 if (myWrite(sock, (const char*)(&obs), numBytes) != numBytes) {
240 ok = false;
241 }
242 }
243 if (!ok) {
244 delete sock;
245 is.remove();
246 }
247 }
248 else if (sock->state() != QAbstractSocket::ConnectingState) {
249 delete sock;
250 is.remove();
251 }
252 }
253 }
254
255 // First time, set the _lastDumpSec immediately
256 // --------------------------------------------
257 if (_lastDumpSec == 0) {
258 _lastDumpSec = newTime - 1;
259 }
260
261 // An old observation - throw it away
262 // ----------------------------------
263 if (newTime <= _lastDumpSec) {
264 if (firstObs) {
265 bncSettings settings;
266 if ( !settings.value("outFile").toString().isEmpty() ||
267 !settings.value("outPort").toString().isEmpty() ) {
268
269 QTime enomtime = QTime(0,0,0).addSecs(iSec);
270
271 emit( newMessage(QString("%1: Old epoch %2 (%3) thrown away")
272 .arg(staID.data()).arg(iSec)
273 .arg(enomtime.toString("HH:mm:ss"))
274 .toAscii(), true) );
275 }
276 }
277 return;
278 }
279
280 // Save the observation
281 // --------------------
282 _epochs->insert(newTime, obs);
283
284 // Dump Epochs
285 // -----------
286 if (newTime - _waitTime > _lastDumpSec) {
287 dumpEpochs(_lastDumpSec + 1, newTime - _waitTime);
288 _lastDumpSec = newTime - _waitTime;
289 }
290}
291
292// New Connection
293////////////////////////////////////////////////////////////////////////////
294void bncCaster::slotNewConnection() {
295 _sockets->push_back( _server->nextPendingConnection() );
296 emit( newMessage(QString("New client connection on sync port: # %1")
297 .arg(_sockets->size()).toAscii(), true) );
298}
299
300void bncCaster::slotNewUConnection() {
301 _uSockets->push_back( _uServer->nextPendingConnection() );
302 emit( newMessage(QString("New client connection on usync port: # %1")
303 .arg(_uSockets->size()).toAscii(), true) );
304}
305
306void bncCaster::slotNewNMEAConnection() {
307 _nmeaSockets->push_back( _nmeaServer->nextPendingConnection() );
308 emit( newMessage(QString("New PPP client on port: # %1")
309 .arg(_nmeaSockets->size()).toAscii(), true) );
310}
311
312// Add New Thread
313////////////////////////////////////////////////////////////////////////////
314void bncCaster::addGetThread(bncGetThread* getThread, bool noNewThread) {
315
316 qRegisterMetaType<t_obs>("t_obs");
317 qRegisterMetaType<gpsephemeris>("gpsephemeris");
318 qRegisterMetaType<glonassephemeris>("glonassephemeris");
319
320 connect(getThread, SIGNAL(newObs(QByteArray, bool, t_obs)),
321 this, SLOT(newObs(QByteArray, bool, t_obs)));
322
323 connect(getThread, SIGNAL(getThreadFinished(QByteArray)),
324 this, SLOT(slotGetThreadFinished(QByteArray)));
325
326 connect(getThread, SIGNAL(newNMEAstr(QByteArray)),
327 this, SLOT(slotNewNMEAstr(QByteArray)));
328
329 connect(((bncApp*)qApp), SIGNAL(newEphGPS(gpsephemeris)),
330 getThread, SLOT(slotNewEphGPS(gpsephemeris)));
331
332 _staIDs.push_back(getThread->staID());
333 _threads.push_back(getThread);
334
335 if (noNewThread) {
336 getThread->run();
337 }
338 else {
339 getThread->start();
340 }
341}
342
343// Get Thread destroyed
344////////////////////////////////////////////////////////////////////////////
345void bncCaster::slotGetThreadFinished(QByteArray staID) {
346 QMutexLocker locker(&_mutex);
347
348 QListIterator<bncGetThread*> it(_threads);
349 while (it.hasNext()) {
350 bncGetThread* thread = it.next();
351 if (thread->staID() == staID) {
352 _threads.removeOne(thread);
353 }
354 }
355
356 _staIDs.removeAll(staID);
357 emit( newMessage(
358 QString("Decoding %1 stream(s)").arg(_staIDs.size()).toAscii(), true) );
359 if (_staIDs.size() == 0) {
360 emit(newMessage("bncCaster: Last get thread terminated", true));
361 emit getThreadsFinished();
362 }
363}
364
365// Dump Complete Epochs
366////////////////////////////////////////////////////////////////////////////
367void bncCaster::dumpEpochs(long minTime, long maxTime) {
368
369 const char begEpoch[] = "BEGEPOCH";
370 const char endEpoch[] = "ENDEPOCH";
371
372 const int begEpochNBytes = sizeof(begEpoch) - 1;
373 const int endEpochNBytes = sizeof(endEpoch) - 1;
374
375 for (long sec = minTime; sec <= maxTime; sec++) {
376
377 bool first = true;
378 QList<t_obs> allObs = _epochs->values(sec);
379
380 QListIterator<t_obs> it(allObs);
381 while (it.hasNext()) {
382 const t_obs& obs = it.next();
383
384 if (_samplingRate == 0 || sec % _samplingRate == 0) {
385
386 if (first) {
387 QTime enomtime = QTime(0,0,0).addSecs(static_cast<int>(floor(obs.GPSWeeks+0.5)));
388// emit( newMessage( QString("Epoch %1 dumped").arg(enomtime.toString("HH:mm:ss")).toAscii(), true) ); // weber
389 }
390 // Output into the file
391 // --------------------
392 if (_out) {
393 if (first) {
394 _out->setFieldWidth(1); *_out << begEpoch << endl;
395 }
396
397 *_out << obs.StatID << " " << obs.GPSWeek << " ";
398 _out->setRealNumberPrecision(7);
399 *_out << obs.GPSWeeks << " ";
400
401 *_out << bncRinex::rinexSatLine(obs, ' ', ' ', ' ').c_str()
402 << endl;
403
404 if (!it.hasNext()) {
405 _out->setFieldWidth(1); *_out << endEpoch << endl;
406 }
407 _out->flush();
408 }
409
410 // Output into the socket
411 // ----------------------
412 if (_sockets) {
413 QMutableListIterator<QTcpSocket*> is(*_sockets);
414 while (is.hasNext()) {
415 QTcpSocket* sock = is.next();
416 if (sock->state() == QAbstractSocket::ConnectedState) {
417 bool ok = true;
418 if (first) {
419 if (myWrite(sock, begEpoch, begEpochNBytes) != begEpochNBytes) {
420 ok = false;
421 }
422 }
423 if (OLD_OBS_FORMAT) {
424 t_oldObsInternal oldObs(obs);
425 int numBytes = sizeof(oldObs);
426 if (myWrite(sock, (const char*)(&oldObs), numBytes) != numBytes) {
427 ok = false;
428 }
429 }
430 else {
431 int numBytes = sizeof(obs);
432 if (myWrite(sock, (const char*)(&obs), numBytes) != numBytes) {
433 ok = false;
434 }
435 }
436 if (!it.hasNext()) {
437 if (myWrite(sock, endEpoch, endEpochNBytes) != endEpochNBytes) {
438 ok = false;
439 }
440 }
441 if (!ok) {
442 delete sock;
443 is.remove();
444 }
445 }
446 else if (sock->state() != QAbstractSocket::ConnectingState) {
447 delete sock;
448 is.remove();
449 }
450 }
451 }
452 }
453
454 _epochs->remove(sec);
455 first = false;
456 }
457 }
458}
459
460// Reread configuration
461////////////////////////////////////////////////////////////////////////////
462void bncCaster::slotReadMountPoints() {
463
464 bncSettings settings;
465
466 // Reread several options
467 // ----------------------
468 _samplingRate = settings.value("binSampl").toInt();
469 _waitTime = settings.value("waitTime").toInt();
470 if (_waitTime < 1) {
471 _waitTime = 1;
472 }
473
474 // Add new mountpoints
475 // -------------------
476 int iMount = -1;
477 QListIterator<QString> it(settings.value("mountPoints").toStringList());
478 while (it.hasNext()) {
479 ++iMount;
480 QStringList hlp = it.next().split(" ");
481 if (hlp.size() <= 1) continue;
482 QUrl url(hlp[0]);
483
484 // Does it already exist?
485 // ----------------------
486 bool existFlg = false;
487 QListIterator<bncGetThread*> iTh(_threads);
488 while (iTh.hasNext()) {
489 bncGetThread* thread = iTh.next();
490 if (thread->mountPoint() == url) {
491 existFlg = true;
492 break;
493 }
494 }
495
496 // New bncGetThread
497 // ----------------
498 if (!existFlg) {
499 QByteArray format = hlp[1].toAscii();
500 QByteArray latitude = hlp[2].toAscii();
501 QByteArray longitude = hlp[3].toAscii();
502 QByteArray nmea = hlp[4].toAscii();
503 QByteArray ntripVersion = hlp[5].toAscii();
504
505 bncGetThread* getThread = new bncGetThread(url, format, latitude,
506 longitude, nmea, ntripVersion, "");
507 addGetThread(getThread);
508 }
509 }
510
511 // Remove mountpoints
512 // ------------------
513 QListIterator<bncGetThread*> iTh(_threads);
514 while (iTh.hasNext()) {
515 bncGetThread* thread = iTh.next();
516
517 bool existFlg = false;
518 QListIterator<QString> it(settings.value("mountPoints").toStringList());
519 while (it.hasNext()) {
520 QStringList hlp = it.next().split(" ");
521 if (hlp.size() <= 1) continue;
522 QUrl url(hlp[0]);
523
524 if (thread->mountPoint() == url) {
525 existFlg = true;
526 break;
527 }
528 }
529
530 if (!existFlg) {
531 disconnect(thread, 0, 0, 0);
532 _staIDs.removeAll(thread->staID());
533 _threads.removeAll(thread);
534 thread->terminate();
535 }
536 }
537
538 emit mountPointsRead(_threads);
539 emit( newMessage(QString("Configuration read: "
540 + ((bncApp*) qApp)->confFileName()
541 + ", %1 stream(s)")
542 .arg(_threads.count()).toAscii(), true) );
543
544 // (Re-) Start the configuration timer
545 // -----------------------------------
546 int ms = 0;
547
548 if (_confInterval != -1) {
549 ms = 1000 * _confInterval;
550 }
551 else {
552 QTime currTime = currentDateAndTimeGPS().time();
553 QTime nextShotTime;
554
555 if (settings.value("onTheFlyInterval").toString() == "1 min") {
556 _confInterval = 60;
557 nextShotTime = QTime(currTime.hour(), currTime.minute()+1, 0);
558 }
559 else if (settings.value("onTheFlyInterval").toString() == "1 hour") {
560 _confInterval = 3600;
561 nextShotTime = QTime(currTime.hour()+1, 0, 0);
562 }
563 else {
564 _confInterval = 86400;
565 nextShotTime = QTime(23, 59, 59, 999);
566 }
567
568 ms = currTime.msecsTo(nextShotTime);
569 if (ms < 30000) {
570 ms = 30000;
571 }
572 }
573
574 QTimer::singleShot(ms, this, SLOT(slotReadMountPoints()));
575}
576
577//
578////////////////////////////////////////////////////////////////////////////
579int bncCaster::myWrite(QTcpSocket* sock, const char* buf, int bufLen) {
580 sock->write(buf, bufLen);
581 for (int ii = 1; ii <= 10; ii++) {
582 if (sock->waitForBytesWritten(10)) { // wait 10 ms
583 return bufLen;
584 }
585 }
586 return -1;
587}
588
589//
590////////////////////////////////////////////////////////////////////////////
591void bncCaster::slotNewNMEAstr(QByteArray str) {
592 if (_nmeaSockets) {
593 QMutableListIterator<QTcpSocket*> is(*_nmeaSockets);
594 while (is.hasNext()) {
595 QTcpSocket* sock = is.next();
596 if (sock->state() == QAbstractSocket::ConnectedState) {
597 sock->write(str);
598 }
599 else if (sock->state() != QAbstractSocket::ConnectingState) {
600 delete sock;
601 is.remove();
602 }
603 }
604 }
605}
Note: See TracBrowser for help on using the repository browser.