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

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