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

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