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

Last change on this file since 2184 was 2184, checked in by mervart, 14 years ago

* empty log message *

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