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

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