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

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

* empty log message *

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