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

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