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

Last change on this file since 4987 was 4987, checked in by mervart, 9 years ago
File size: 15.5 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#include <iostream>
44#include <iomanip>
45#include <sstream>
46
47#include "bnccaster.h"
48#include "bncrinex.h"
49#include "bncapp.h"
50#include "bncgetthread.h"
51#include "bncutils.h"
52#include "bncsettings.h"
53#include "RTCM/GPSDecoder.h"
54#ifdef RTROVER_INTERFACE
55# include "RTRover/bncrtrover.h"
56#endif
57
58using namespace std;
59
60// Constructor
61////////////////////////////////////////////////////////////////////////////
62bncCaster::bncCaster(const QString& outFileName, int port) {
63
64 bncSettings settings;
65
66 connect(this, SIGNAL(newMessage(QByteArray,bool)),
67 (bncApp*) qApp, SLOT(slotMessage(const QByteArray,bool)));
68
69 if ( !outFileName.isEmpty() ) {
70 QString lName = outFileName;
71 expandEnvVar(lName);
72 _outFile = new QFile(lName);
73 if ( Qt::CheckState(settings.value("rnxAppend").toInt()) == Qt::Checked) {
74 _outFile->open(QIODevice::WriteOnly | QIODevice::Append);
75 }
76 else {
77 _outFile->open(QIODevice::WriteOnly);
78 }
79 _out = new QTextStream(_outFile);
80 _out->setRealNumberNotation(QTextStream::FixedNotation);
81 }
82 else {
83 _outFile = 0;
84 _out = 0;
85 }
86
87 _port = port;
88
89 if (_port != 0) {
90 _server = new QTcpServer;
91 if ( !_server->listen(QHostAddress::Any, _port) ) {
92 emit newMessage("bncCaster: Cannot listen on sync port", true);
93 }
94 connect(_server, SIGNAL(newConnection()), this, SLOT(slotNewConnection()));
95 _sockets = new QList<QTcpSocket*>;
96 }
97 else {
98 _server = 0;
99 _sockets = 0;
100 }
101
102 int uPort = settings.value("outUPort").toInt();
103 if (uPort != 0) {
104 _uServer = new QTcpServer;
105 if ( !_uServer->listen(QHostAddress::Any, uPort) ) {
106 emit newMessage("bncCaster: Cannot listen on usync port", true);
107 }
108 connect(_uServer, SIGNAL(newConnection()), this, SLOT(slotNewUConnection()));
109 _uSockets = new QList<QTcpSocket*>;
110 }
111 else {
112 _uServer = 0;
113 _uSockets = 0;
114 }
115
116 int nmeaPort = settings.value("nmeaPort").toInt();
117 if (nmeaPort != 0) {
118 _nmeaServer = new QTcpServer;
119 if ( !_nmeaServer->listen(QHostAddress::Any, nmeaPort) ) {
120 emit newMessage("bncCaster: Cannot listen on port", true);
121 }
122 connect(_nmeaServer, SIGNAL(newConnection()), this, SLOT(slotNewNMEAConnection()));
123 _nmeaSockets = new QList<QTcpSocket*>;
124 }
125 else {
126 _nmeaServer = 0;
127 _nmeaSockets = 0;
128 }
129
130 _epochs = new QMultiMap<long, t_obs>;
131
132 _samplingRate = settings.value("binSampl").toInt();
133 _waitTime = settings.value("waitTime").toInt();
134 _lastDumpSec = 0;
135 _confInterval = -1;
136#ifdef RTROVER_INTERFACE
137 if (!settings.value("rtroverMode").toString().isEmpty()) {
138 _bncRtrover = new t_bncRtrover();
139 _bncRtrover->start();
140 }
141 else {
142 _bncRtrover = 0;
143 }
144#endif
145}
146
147// Destructor
148////////////////////////////////////////////////////////////////////////////
149bncCaster::~bncCaster() {
150
151 QMutexLocker locker(&_mutex);
152
153 QListIterator<bncGetThread*> it(_threads);
154 while(it.hasNext()){
155 bncGetThread* thread = it.next();
156 thread->terminate();
157 }
158 delete _out;
159 delete _outFile;
160 delete _server;
161 delete _sockets;
162 delete _uServer;
163 delete _uSockets;
164 delete _nmeaServer;
165 delete _nmeaSockets;
166 delete _epochs;
167#ifdef RTROVER_INTERFACE
168 if (_bncRtrover) {
169 _bncRtrover->quit();
170 _bncRtrover->deleteLater();
171 }
172#endif
173}
174
175// New Observations
176////////////////////////////////////////////////////////////////////////////
177void bncCaster::newObs(const QByteArray staID, bool firstObs, t_obs obs) {
178
179 QMutexLocker locker(&_mutex);
180
181 long iSec = long(floor(obs.GPSWeeks+0.5));
182 long newTime = obs.GPSWeek * 7*24*3600 + iSec;
183
184 // Rename the Station
185 // ------------------
186 strncpy(obs.StatID, staID.constData(),sizeof(obs.StatID));
187 obs.StatID[sizeof(obs.StatID)-1] = '\0';
188
189 // Output into the socket
190 // ----------------------
191 if (_uSockets) {
192
193 ostringstream oStr;
194 oStr.setf(ios::showpoint | ios::fixed);
195 oStr << obs.StatID << " "
196 << obs.GPSWeek << " "
197 << setprecision(7) << obs.GPSWeeks << " "
198 << bncRinex::asciiSatLine(obs) << 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 _lastDumpSec immediately
220 // --------------------------------------------
221 if (_lastDumpSec == 0) {
222 _lastDumpSec = newTime - 1;
223 }
224
225 // An old observation - throw it away
226 // ----------------------------------
227 if (newTime <= _lastDumpSec) {
228 if (firstObs) {
229 bncSettings settings;
230 if ( !settings.value("outFile").toString().isEmpty() ||
231 !settings.value("outPort").toString().isEmpty() ) {
232
233 QTime enomtime = QTime(0,0,0).addSecs(iSec);
234
235 emit( newMessage(QString("%1: Old epoch %2 (%3) thrown away")
236 .arg(staID.data()).arg(iSec)
237 .arg(enomtime.toString("HH:mm:ss"))
238 .toAscii(), true) );
239 }
240 }
241 return;
242 }
243
244 // Save the observation
245 // --------------------
246 _epochs->insert(newTime, obs);
247
248 // Dump Epochs
249 // -----------
250 if (newTime - _waitTime > _lastDumpSec) {
251 dumpEpochs(_lastDumpSec + 1, newTime - _waitTime);
252 _lastDumpSec = newTime - _waitTime;
253 }
254}
255
256// New Connection
257////////////////////////////////////////////////////////////////////////////
258void bncCaster::slotNewConnection() {
259 _sockets->push_back( _server->nextPendingConnection() );
260 emit( newMessage(QString("New client connection on sync port: # %1")
261 .arg(_sockets->size()).toAscii(), true) );
262}
263
264void bncCaster::slotNewUConnection() {
265 _uSockets->push_back( _uServer->nextPendingConnection() );
266 emit( newMessage(QString("New client connection on usync port: # %1")
267 .arg(_uSockets->size()).toAscii(), true) );
268}
269
270void bncCaster::slotNewNMEAConnection() {
271 _nmeaSockets->push_back( _nmeaServer->nextPendingConnection() );
272 emit( newMessage(QString("New PPP client on port: # %1")
273 .arg(_nmeaSockets->size()).toAscii(), true) );
274}
275
276// Add New Thread
277////////////////////////////////////////////////////////////////////////////
278void bncCaster::addGetThread(bncGetThread* getThread, bool noNewThread) {
279
280 qRegisterMetaType<t_obs>("t_obs");
281 qRegisterMetaType<gpsephemeris>("gpsephemeris");
282 qRegisterMetaType<glonassephemeris>("glonassephemeris");
283 qRegisterMetaType<galileoephemeris>("galileoephemeris");
284
285 connect(getThread, SIGNAL(newObs(QByteArray, bool, t_obs)),
286 this, SLOT(newObs(QByteArray, bool, t_obs)));
287
288#ifdef RTROVER_INTERFACE
289 if (_bncRtrover) {
290 connect(getThread, SIGNAL(newObs(QByteArray, bool, t_obs)),
291 _bncRtrover, SLOT(slotNewObs(QByteArray, bool, t_obs)));
292 }
293#endif
294
295 connect(getThread, SIGNAL(getThreadFinished(QByteArray)),
296 this, SLOT(slotGetThreadFinished(QByteArray)));
297
298 connect(getThread, SIGNAL(newNMEAstr(QByteArray)),
299 this, SLOT(slotNewNMEAstr(QByteArray)));
300
301 _staIDs.push_back(getThread->staID());
302 _threads.push_back(getThread);
303
304 if (noNewThread) {
305 getThread->run();
306 }
307 else {
308 getThread->start();
309 }
310}
311
312// Get Thread destroyed
313////////////////////////////////////////////////////////////////////////////
314void bncCaster::slotGetThreadFinished(QByteArray staID) {
315 QMutexLocker locker(&_mutex);
316
317 QListIterator<bncGetThread*> it(_threads);
318 while (it.hasNext()) {
319 bncGetThread* thread = it.next();
320 if (thread->staID() == staID) {
321 _threads.removeOne(thread);
322 }
323 }
324
325 _staIDs.removeAll(staID);
326 emit( newMessage(
327 QString("Decoding %1 stream(s)").arg(_staIDs.size()).toAscii(), true) );
328 if (_staIDs.size() == 0) {
329 emit(newMessage("bncCaster: Last get thread terminated", true));
330 emit getThreadsFinished();
331 }
332}
333
334// Dump Complete Epochs
335////////////////////////////////////////////////////////////////////////////
336void bncCaster::dumpEpochs(long minTime, long maxTime) {
337
338 for (long sec = minTime; sec <= maxTime; sec++) {
339
340 QList<t_obs> allObs = _epochs->values(sec);
341
342 bool firstEpoLine = true;
343
344 QListIterator<t_obs> it(allObs);
345 while (it.hasNext()) {
346 const t_obs& obs = it.next();
347
348 if (_samplingRate == 0 || sec % _samplingRate == 0) {
349
350 if (_out || _sockets) {
351 ostringstream oStr;
352 oStr.setf(ios::showpoint | ios::fixed);
353 if (firstEpoLine) {
354 firstEpoLine = false;
355 oStr << "> " << obs.GPSWeek << ' '
356 << setprecision(7) << obs.GPSWeeks << endl;;
357 }
358 oStr << obs.StatID << ' ' << bncRinex::asciiSatLine(obs) << endl;
359 if (!it.hasNext()) {
360 oStr << endl;
361 }
362 string hlpStr = oStr.str();
363
364 // Output into the File
365 // --------------------
366 if (_out) {
367 *_out << hlpStr.c_str();
368 _out->flush();
369 }
370
371 // Output into the socket
372 // ----------------------
373 if (_sockets) {
374 QMutableListIterator<QTcpSocket*> is(*_sockets);
375 while (is.hasNext()) {
376 QTcpSocket* sock = is.next();
377 if (sock->state() == QAbstractSocket::ConnectedState) {
378 int numBytes = hlpStr.length();
379 if (myWrite(sock, hlpStr.c_str(), numBytes) != numBytes) {
380 delete sock;
381 is.remove();
382 }
383 }
384 else if (sock->state() != QAbstractSocket::ConnectingState) {
385 delete sock;
386 is.remove();
387 }
388 }
389 }
390 }
391 }
392
393 _epochs->remove(sec);
394 }
395 }
396}
397
398// Reread configuration (private slot)
399////////////////////////////////////////////////////////////////////////////
400void bncCaster::slotReadMountPoints() {
401
402 bncSettings settings;
403 settings.reRead();
404
405 readMountPoints();
406}
407
408// Read Mountpoints
409////////////////////////////////////////////////////////////////////////////
410void bncCaster::readMountPoints() {
411
412 bncSettings settings;
413
414 // Reread several options
415 // ----------------------
416 _samplingRate = settings.value("binSampl").toInt();
417 _waitTime = settings.value("waitTime").toInt();
418 if (_waitTime < 1) {
419 _waitTime = 1;
420 }
421
422 // Add new mountpoints
423 // -------------------
424 int iMount = -1;
425 QListIterator<QString> it(settings.value("mountPoints").toStringList());
426 while (it.hasNext()) {
427 ++iMount;
428 QStringList hlp = it.next().split(" ");
429 if (hlp.size() <= 1) continue;
430 QUrl url(hlp[0]);
431
432 // Does it already exist?
433 // ----------------------
434 bool existFlg = false;
435 QListIterator<bncGetThread*> iTh(_threads);
436 while (iTh.hasNext()) {
437 bncGetThread* thread = iTh.next();
438 if (thread->mountPoint() == url) {
439 existFlg = true;
440 break;
441 }
442 }
443
444 // New bncGetThread
445 // ----------------
446 if (!existFlg) {
447 QByteArray format = hlp[1].toAscii();
448 QByteArray latitude = hlp[2].toAscii();
449 QByteArray longitude = hlp[3].toAscii();
450 QByteArray nmea = hlp[4].toAscii();
451 QByteArray ntripVersion = hlp[5].toAscii();
452
453 bncGetThread* getThread = new bncGetThread(url, format, latitude,
454 longitude, nmea, ntripVersion);
455 addGetThread(getThread);
456 }
457 }
458
459 // Remove mountpoints
460 // ------------------
461 QListIterator<bncGetThread*> iTh(_threads);
462 while (iTh.hasNext()) {
463 bncGetThread* thread = iTh.next();
464
465 bool existFlg = false;
466 QListIterator<QString> it(settings.value("mountPoints").toStringList());
467 while (it.hasNext()) {
468 QStringList hlp = it.next().split(" ");
469 if (hlp.size() <= 1) continue;
470 QUrl url(hlp[0]);
471
472 if (thread->mountPoint() == url) {
473 existFlg = true;
474 break;
475 }
476 }
477
478 if (!existFlg) {
479 disconnect(thread, 0, 0, 0);
480 _staIDs.removeAll(thread->staID());
481 _threads.removeAll(thread);
482 thread->terminate();
483 }
484 }
485
486 emit mountPointsRead(_threads);
487 emit( newMessage(QString("Configuration read: "
488 + ((bncApp*) qApp)->confFileName()
489 + ", %1 stream(s)")
490 .arg(_threads.count()).toAscii(), true) );
491
492 // (Re-) Start the configuration timer
493 // -----------------------------------
494 int ms = 0;
495
496 if (_confInterval != -1) {
497 ms = 1000 * _confInterval;
498 }
499 else {
500 QTime currTime = currentDateAndTimeGPS().time();
501 QTime nextShotTime;
502
503 if (settings.value("onTheFlyInterval").toString() == "1 min") {
504 _confInterval = 60;
505 nextShotTime = QTime(currTime.hour(), currTime.minute()+1, 0);
506 }
507 else if (settings.value("onTheFlyInterval").toString() == "5 min") {
508 _confInterval = 300;
509 nextShotTime = QTime(currTime.hour(), currTime.minute()+5, 0);
510 }
511 else if (settings.value("onTheFlyInterval").toString() == "1 hour") {
512 _confInterval = 3600;
513 nextShotTime = QTime(currTime.hour()+1, 0, 0);
514 }
515 else {
516 _confInterval = 86400;
517 nextShotTime = QTime(23, 59, 59, 999);
518 }
519
520 ms = currTime.msecsTo(nextShotTime);
521 if (ms < 30000) {
522 ms = 30000;
523 }
524 }
525
526 QTimer::singleShot(ms, this, SLOT(slotReadMountPoints()));
527}
528
529//
530////////////////////////////////////////////////////////////////////////////
531int bncCaster::myWrite(QTcpSocket* sock, const char* buf, int bufLen) {
532 sock->write(buf, bufLen);
533 for (int ii = 1; ii <= 10; ii++) {
534 if (sock->waitForBytesWritten(10)) { // wait 10 ms
535 return bufLen;
536 }
537 }
538 return -1;
539}
540
541//
542////////////////////////////////////////////////////////////////////////////
543void bncCaster::slotNewNMEAstr(QByteArray str) {
544 if (_nmeaSockets) {
545 QMutableListIterator<QTcpSocket*> is(*_nmeaSockets);
546 while (is.hasNext()) {
547 QTcpSocket* sock = is.next();
548 if (sock->state() == QAbstractSocket::ConnectedState) {
549 sock->write(str);
550 }
551 else if (sock->state() != QAbstractSocket::ConnectingState) {
552 delete sock;
553 is.remove();
554 }
555 }
556 }
557}
Note: See TracBrowser for help on using the repository browser.