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

Last change on this file since 1372 was 1353, checked in by mervart, 16 years ago

* empty log message *

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