source: ntrip/branches/BNC_2.12/src/bnccaster.cpp@ 8677

Last change on this file since 8677 was 8667, checked in by stuerze, 6 years ago

error message improved

File size: 16.4 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#include <iostream>
44#include <iomanip>
45#include <sstream>
46
47#include "bnccaster.h"
48#include "bncrinex.h"
49#include "bnccore.h"
50#include "bncgetthread.h"
51#include "bncutils.h"
52#include "bncsettings.h"
53
54using namespace std;
55
56// Constructor
57////////////////////////////////////////////////////////////////////////////
58bncCaster::bncCaster() {
59
60 bncSettings settings;
61
62 connect(this, SIGNAL(newMessage(QByteArray,bool)),
63 BNC_CORE, SLOT(slotMessage(const QByteArray,bool)));
64
65 _outFile = 0;
66 _out = 0;
67 reopenOutFile();
68
69 int port = settings.value("outPort").toInt();
70
71 if (port != 0) {
72 _server = new QTcpServer;
73 if ( !_server->listen(QHostAddress::Any, port) ) {
74 emit newMessage("bncCaster: Cannot listen on sync port", true);
75 }
76 connect(_server, SIGNAL(newConnection()), this, SLOT(slotNewConnection()));
77 _sockets = new QList<QTcpSocket*>;
78 }
79 else {
80 _server = 0;
81 _sockets = 0;
82 }
83
84 int uPort = settings.value("outUPort").toInt();
85 if (uPort != 0) {
86 _uServer = new QTcpServer;
87 if ( !_uServer->listen(QHostAddress::Any, uPort) ) {
88 emit newMessage("bncCaster: Cannot listen on usync port", true);
89 }
90 connect(_uServer, SIGNAL(newConnection()), this, SLOT(slotNewUConnection()));
91 _uSockets = new QList<QTcpSocket*>;
92 }
93 else {
94 _uServer = 0;
95 _uSockets = 0;
96 }
97
98 _outLockTime = settings.value("outLockTime",false).toBool();
99 _samplingRateMult10 = int(settings.value("outSampl").toString().split("sec").first().toDouble() * 10.0);
100 _outWait = settings.value("outWait").toDouble();
101 if (_outWait <= 0.0) {
102 _outWait = 0.01;
103 }
104 _confInterval = -1;
105
106 // Miscellaneous output port
107 // -------------------------
108 _miscMount = settings.value("miscMount").toString();
109 _miscPort = settings.value("miscPort").toInt();
110 if (!_miscMount.isEmpty() && _miscPort != 0) {
111 _miscServer = new QTcpServer;
112 if ( !_miscServer->listen(QHostAddress::Any, _miscPort) ) {
113 emit newMessage("bncCaster: Cannot listen on Miscellaneous Output Port", true);
114 }
115 connect(_miscServer, SIGNAL(newConnection()), this, SLOT(slotNewMiscConnection()));
116 _miscSockets = new QList<QTcpSocket*>;
117 }
118 else {
119 _miscServer = 0;
120 _miscSockets = 0;
121 }
122}
123
124// Destructor
125////////////////////////////////////////////////////////////////////////////
126bncCaster::~bncCaster() {
127
128 QMutexLocker locker(&_mutex);
129
130 QListIterator<bncGetThread*> it(_threads);
131 while(it.hasNext()){
132 bncGetThread* thread = it.next();
133 disconnect(thread, 0, 0, 0);
134 _staIDs.removeAll(thread->staID());
135 _threads.removeAll(thread);
136 thread->terminate();
137 }
138 delete _out;
139 delete _outFile;
140 delete _server;
141 delete _sockets;
142 delete _uServer;
143 delete _uSockets;
144 delete _miscServer;
145 delete _miscSockets;
146}
147
148// New Observations
149////////////////////////////////////////////////////////////////////////////
150void bncCaster::slotNewObs(const QByteArray staID, QList<t_satObs> obsList) {
151
152 QMutexLocker locker(&_mutex);
153
154 reopenOutFile();
155
156 unsigned index = 0;
157 QMutableListIterator<t_satObs> it(obsList);
158 while (it.hasNext()) {
159 ++index;
160 t_satObs& obs = it.next();
161
162 // Rename the Station
163 // ------------------
164 obs._staID = staID.data();
165
166 // Output into the socket
167 // ----------------------
168 if (_uSockets) {
169
170 ostringstream oStr;
171 oStr.setf(ios::showpoint | ios::fixed);
172 oStr << obs._staID << " "
173 << setw(4) << obs._time.gpsw() << " "
174 << setw(14) << setprecision(7) << obs._time.gpssec() << " "
175 << bncRinex::asciiSatLine(obs,_outLockTime) << endl;
176
177 string hlpStr = oStr.str();
178
179 QMutableListIterator<QTcpSocket*> is(*_uSockets);
180 while (is.hasNext()) {
181 QTcpSocket* sock = is.next();
182 if (sock->state() == QAbstractSocket::ConnectedState) {
183 int numBytes = hlpStr.length();
184 if (myWrite(sock, hlpStr.c_str(), numBytes) != numBytes) {
185 delete sock;
186 is.remove();
187 }
188 }
189 else if (sock->state() != QAbstractSocket::ConnectingState) {
190 delete sock;
191 is.remove();
192 }
193 }
194 }
195
196 // First time: set the _lastDumpTime
197 // ---------------------------------
198 if (!_lastDumpTime.valid()) {
199 _lastDumpTime = obs._time - 1.0;
200 }
201 // An old observation - throw it away
202 // ----------------------------------
203 if (obs._time <= _lastDumpTime) {
204 if (index == 1) {
205 bncSettings settings;
206 if ( !settings.value("outFile").toString().isEmpty() ||
207 !settings.value("outPort").toString().isEmpty() ) {
208 emit( newMessage(QString("%1: Old or erroneous observation epoch %2 thrown away from %3")
209 .arg(staID.data())
210 .arg(string(obs._time).c_str())
211 .arg(obs._prn.toString().c_str())
212 .toAscii(), true) );
213 }
214 }
215 continue;
216 }
217
218 // Save the observation
219 // --------------------
220 _epochs[obs._time].append(obs);
221
222 // Dump Epochs
223 // -----------
224 if (obs._time - _outWait > _lastDumpTime) {
225 dumpEpochs(obs._time - _outWait);
226 _lastDumpTime = obs._time - _outWait;
227 }
228 }
229}
230
231// New Connection
232////////////////////////////////////////////////////////////////////////////
233void bncCaster::slotNewConnection() {
234 _sockets->push_back( _server->nextPendingConnection() );
235 emit( newMessage(QString("New client connection on sync port: # %1")
236 .arg(_sockets->size()).toAscii(), true) );
237}
238
239void bncCaster::slotNewUConnection() {
240 _uSockets->push_back( _uServer->nextPendingConnection() );
241 emit( newMessage(QString("New client connection on usync port: # %1")
242 .arg(_uSockets->size()).toAscii(), true) );
243}
244
245// Add New Thread
246////////////////////////////////////////////////////////////////////////////
247void bncCaster::addGetThread(bncGetThread* getThread, bool noNewThread) {
248
249 qRegisterMetaType<t_satObs>("t_satObs");
250 qRegisterMetaType< QList<t_satObs> >("QList<t_satObs>");
251
252 connect(getThread, SIGNAL(newObs(QByteArray, QList<t_satObs>)),
253 this, SLOT(slotNewObs(QByteArray, QList<t_satObs>)));
254
255 connect(getThread, SIGNAL(newObs(QByteArray, QList<t_satObs>)),
256 this, SIGNAL(newObs(QByteArray, QList<t_satObs>)));
257
258 connect(getThread, SIGNAL(newRawData(QByteArray, QByteArray)),
259 this, SLOT(slotNewRawData(QByteArray, QByteArray)));
260
261 connect(getThread, SIGNAL(getThreadFinished(QByteArray)),
262 this, SLOT(slotGetThreadFinished(QByteArray)));
263
264 _staIDs.push_back(getThread->staID());
265 _threads.push_back(getThread);
266
267 if (noNewThread) {
268 getThread->run();
269 }
270 else {
271 getThread->start();
272 }
273}
274
275// Get Thread destroyed
276////////////////////////////////////////////////////////////////////////////
277void bncCaster::slotGetThreadFinished(QByteArray staID) {
278 QMutexLocker locker(&_mutex);
279
280 QListIterator<bncGetThread*> it(_threads);
281 while (it.hasNext()) {
282 bncGetThread* thread = it.next();
283 if (thread->staID() == staID) {
284 _threads.removeOne(thread);
285 }
286 }
287
288 _staIDs.removeAll(staID);
289 emit( newMessage(
290 QString("Decoding %1 stream(s)").arg(_staIDs.size()).toAscii(), true) );
291 if (_staIDs.size() == 0) {
292 emit(newMessage("bncCaster: Last get thread terminated", true));
293 emit getThreadsFinished();
294 }
295}
296
297// Dump Complete Epochs
298////////////////////////////////////////////////////////////////////////////
299void bncCaster::dumpEpochs(const bncTime& maxTime) {
300
301 QMutableMapIterator<bncTime, QList<t_satObs> > itEpo(_epochs);
302 while (itEpo.hasNext()) {
303 itEpo.next();
304 const bncTime& epoTime = itEpo.key();
305 if (epoTime <= maxTime) {
306 const QList<t_satObs>& allObs = itEpo.value();
307 int sec = int(nint(epoTime.gpssec()*10));
308 if ( (_out || _sockets) && (sec % (_samplingRateMult10) == 0) ) {
309 QListIterator<t_satObs> it(allObs);
310 bool firstObs = true;
311 while (it.hasNext()) {
312 const t_satObs& obs = it.next();
313
314 ostringstream oStr;
315 oStr.setf(ios::showpoint | ios::fixed);
316 if (firstObs) {
317 firstObs = false;
318 oStr << "> " << obs._time.gpsw() << ' '
319 << setprecision(7) << obs._time.gpssec() << endl;
320 }
321 oStr << obs._staID << ' '
322 << bncRinex::asciiSatLine(obs,_outLockTime) << endl;
323 if (!it.hasNext()) {
324 oStr << endl;
325 }
326 string hlpStr = oStr.str();
327
328 // Output into the File
329 // --------------------
330 if (_out) {
331 *_out << hlpStr.c_str();
332 _out->flush();
333 }
334
335 // Output into the socket
336 // ----------------------
337 if (_sockets) {
338 QMutableListIterator<QTcpSocket*> is(*_sockets);
339 while (is.hasNext()) {
340 QTcpSocket* sock = is.next();
341 if (sock->state() == QAbstractSocket::ConnectedState) {
342 int numBytes = hlpStr.length();
343 if (myWrite(sock, hlpStr.c_str(), numBytes) != numBytes) {
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 _epochs.remove(epoTime);
357 }
358 }
359}
360
361// Reread configuration (private slot)
362////////////////////////////////////////////////////////////////////////////
363void bncCaster::slotReadMountPoints() {
364
365 bncSettings settings;
366 settings.reRead();
367
368 readMountPoints();
369}
370
371// Read Mountpoints
372////////////////////////////////////////////////////////////////////////////
373void bncCaster::readMountPoints() {
374
375 bncSettings settings;
376
377 // Reread several options
378 // ----------------------
379 _samplingRateMult10 = int(settings.value("outSampl").toString().split("sec").first().toDouble() * 10.0);
380 _outWait = settings.value("outWait").toInt();
381 if (_outWait < 1) {
382 _outWait = 1;
383 }
384
385 // Add new mountpoints
386 // -------------------
387 int iMount = -1;
388 QListIterator<QString> it(settings.value("mountPoints").toStringList());
389 while (it.hasNext()) {
390 ++iMount;
391 QStringList hlp = it.next().split(" ");
392 if (hlp.size() < 7) continue;
393 QUrl url(hlp[0]);
394
395 // Does it already exist?
396 // ----------------------
397 bool existFlg = false;
398 QListIterator<bncGetThread*> iTh(_threads);
399 while (iTh.hasNext()) {
400 bncGetThread* thread = iTh.next();
401 if (thread->mountPoint() == url) {
402 existFlg = true;
403 break;
404 }
405 }
406
407 // New bncGetThread
408 // ----------------
409 if (!existFlg) {
410 QByteArray format = hlp[1].toAscii();
411 QByteArray latitude = hlp[3].toAscii();
412 QByteArray longitude = hlp[4].toAscii();
413 QByteArray nmea = hlp[5].toAscii();
414 QByteArray ntripVersion = hlp[6].toAscii();
415
416 bncGetThread* getThread = new bncGetThread(url, format, latitude,
417 longitude, nmea, ntripVersion);
418 addGetThread(getThread);
419
420 }
421 }
422
423 // Remove mountpoints
424 // ------------------
425 QListIterator<bncGetThread*> iTh(_threads);
426 while (iTh.hasNext()) {
427 bncGetThread* thread = iTh.next();
428
429 bool existFlg = false;
430 QListIterator<QString> it(settings.value("mountPoints").toStringList());
431 while (it.hasNext()) {
432 QStringList hlp = it.next().split(" ");
433 if (hlp.size() <= 1) continue;
434 QUrl url(hlp[0]);
435
436 if (thread->mountPoint() == url) {
437 existFlg = true;
438 break;
439 }
440 }
441
442 if (!existFlg) {
443 disconnect(thread, 0, 0, 0);
444 _staIDs.removeAll(thread->staID());
445 _threads.removeAll(thread);
446 thread->terminate();
447 }
448 }
449
450 emit mountPointsRead(_threads);
451 emit( newMessage(QString("Configuration read: "
452 + BNC_CORE->confFileName()
453 + ", %1 stream(s)")
454 .arg(_threads.count()).toAscii(), true) );
455
456 // (Re-) Start the configuration timer
457 // -----------------------------------
458 if (settings.value("onTheFlyInterval").toString() == "no") {
459 return;
460 }
461
462 int ms = 0;
463
464 if (_confInterval != -1) {
465 ms = 1000 * _confInterval;
466 }
467 else {
468 QTime currTime = currentDateAndTimeGPS().time();
469 QTime nextShotTime;
470
471 if (settings.value("onTheFlyInterval").toString() == "1 min") {
472 _confInterval = 60;
473 nextShotTime = QTime(currTime.hour(), currTime.minute()+1, 0);
474 }
475 else if (settings.value("onTheFlyInterval").toString() == "5 min") {
476 _confInterval = 300;
477 nextShotTime = QTime(currTime.hour(), currTime.minute()+5, 0);
478 }
479 else if (settings.value("onTheFlyInterval").toString() == "1 hour") {
480 _confInterval = 3600;
481 nextShotTime = QTime(currTime.hour()+1, 0, 0);
482 }
483 else {
484 _confInterval = 86400;
485 nextShotTime = QTime(23, 59, 59, 999);
486 }
487
488 ms = currTime.msecsTo(nextShotTime);
489 if (ms < 30000) {
490 ms = 30000;
491 }
492 }
493
494 QTimer::singleShot(ms, this, SLOT(slotReadMountPoints()));
495}
496
497//
498////////////////////////////////////////////////////////////////////////////
499int bncCaster::myWrite(QTcpSocket* sock, const char* buf, int bufLen) {
500 sock->write(buf, bufLen);
501 for (int ii = 1; ii <= 10; ii++) {
502 if (sock->waitForBytesWritten(10)) { // wait 10 ms
503 return bufLen;
504 }
505 }
506 return -1;
507}
508
509//
510////////////////////////////////////////////////////////////////////////////
511void bncCaster::reopenOutFile() {
512
513 bncSettings settings;
514
515 QString outFileName = settings.value("outFile").toString();
516 if ( !outFileName.isEmpty() ) {
517 expandEnvVar(outFileName);
518 if (!_outFile || _outFile->fileName() != outFileName) {
519 delete _out;
520 delete _outFile;
521 _outFile = new QFile(outFileName);
522 if ( Qt::CheckState(settings.value("rnxAppend").toInt()) == Qt::Checked) {
523 _outFile->open(QIODevice::WriteOnly | QIODevice::Append);
524 }
525 else {
526 _outFile->open(QIODevice::WriteOnly);
527 }
528 _out = new QTextStream(_outFile);
529 _out->setRealNumberNotation(QTextStream::FixedNotation);
530 }
531 }
532 else {
533 delete _out; _out = 0;
534 delete _outFile; _outFile = 0;
535 }
536}
537
538// Output into the Miscellaneous socket
539////////////////////////////////////////////////////////////////////////////
540void bncCaster::slotNewRawData(QByteArray staID, QByteArray data) {
541 if (_miscSockets && (_miscMount == "ALL" || _miscMount == staID)) {
542 QMutableListIterator<QTcpSocket*> is(*_miscSockets);
543 while (is.hasNext()) {
544 QTcpSocket* sock = is.next();
545 if (sock->state() == QAbstractSocket::ConnectedState) {
546 sock->write(data);
547 }
548 else if (sock->state() != QAbstractSocket::ConnectingState) {
549 delete sock;
550 is.remove();
551 }
552 }
553 }
554}
555
556// New Connection
557////////////////////////////////////////////////////////////////////////////
558void bncCaster::slotNewMiscConnection() {
559 _miscSockets->push_back( _miscServer->nextPendingConnection() );
560 emit( newMessage(QString("New client connection on Miscellaneous Output Port: # %1")
561 .arg(_miscSockets->size()).toAscii(), true) );
562}
Note: See TracBrowser for help on using the repository browser.