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

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