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

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