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

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