source: ntrip/trunk/BNC/bncgetthread.cpp@ 688

Last change on this file since 688 was 688, checked in by weber, 17 years ago

* empty log message *

File size: 18.7 KB
RevLine 
[280]1// Part of BNC, a utility for retrieving decoding and
[464]2// converting GNSS data streams from NTRIP broadcasters.
[280]3//
[464]4// Copyright (C) 2007
[280]5// German Federal Agency for Cartography and Geodesy (BKG)
6// http://www.bkg.bund.de
[464]7// Czech Technical University Prague, Department of Geodesy
[280]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.
[35]24
25/* -------------------------------------------------------------------------
[93]26 * BKG NTRIP Client
[35]27 * -------------------------------------------------------------------------
28 *
29 * Class: bncGetThread
30 *
31 * Purpose: Thread that retrieves data from NTRIP caster
32 *
33 * Author: L. Mervart
34 *
35 * Created: 24-Dec-2005
36 *
37 * Changes:
38 *
39 * -----------------------------------------------------------------------*/
40
[277]41#include <stdlib.h>
42
[35]43#include <QFile>
44#include <QTextStream>
45#include <QtNetwork>
[356]46#include <QTime>
[35]47
48#include "bncgetthread.h"
[192]49#include "bnctabledlg.h"
[243]50#include "bncapp.h"
[352]51#include "bncutils.h"
[408]52#include "bncrinex.h"
[423]53#include "bnczerodecoder.h"
[65]54
[243]55#include "RTCM/RTCM2Decoder.h"
[297]56#include "RTCM3/RTCM3Decoder.h"
[293]57#include "RTIGS/RTIGSDecoder.h"
[35]58
59using namespace std;
60
61// Constructor
62////////////////////////////////////////////////////////////////////////////
[278]63bncGetThread::bncGetThread(const QUrl& mountPoint,
[366]64 const QByteArray& format,
65 const QByteArray& latitude,
66 const QByteArray& longitude,
67 const QByteArray& nmea, int iMount) {
[605]68
69 setTerminationEnabled(true);
70
[350]71 _decoder = 0;
72 _mountPoint = mountPoint;
73 _staID = mountPoint.path().mid(1).toAscii();
74 _staID_orig = _staID;
75 _format = format;
[366]76 _latitude = latitude;
77 _longitude = longitude;
78 _nmea = nmea;
[350]79 _socket = 0;
80 _timeOut = 20*1000; // 20 seconds
81 _nextSleep = 1; // 1 second
82 _iMount = iMount; // index in mountpoints array
[255]83
84 // Check name conflict
85 // -------------------
86 QSettings settings;
87 QListIterator<QString> it(settings.value("mountPoints").toStringList());
88 int num = 0;
[278]89 int ind = -1;
[255]90 while (it.hasNext()) {
[278]91 ++ind;
[255]92 QStringList hlp = it.next().split(" ");
93 if (hlp.size() <= 1) continue;
94 QUrl url(hlp[0]);
95 if (_mountPoint.path() == url.path()) {
[278]96 if (_iMount > ind) {
97 ++num;
[255]98 }
99 }
100 }
[278]101
102 if (num > 0) {
103 _staID = _staID.left(_staID.length()-1) + QString("%1").arg(num).toAscii();
[255]104 }
[408]105
[658]106 // Notice threshold
107 // ----------------
[686]108 _inspSegm = 50;
109 if ( settings.value("obsRate").toString().isEmpty() ) { _inspSegm = 0; }
110 if ( settings.value("obsRate").toString().indexOf("1 Hz") != -1 ) { _inspSegm = 10; }
111 if ( settings.value("obsRate").toString().indexOf("0.5 Hz") != -1 ) { _inspSegm = 20; }
112 if ( settings.value("obsRate").toString().indexOf("0.2 Hz") != -1 ) { _inspSegm = 40; }
113 if ( settings.value("obsRate").toString().indexOf("0.1 Hz") != -1 ) { _inspSegm = 50; }
[668]114 _adviseFail = settings.value("adviseFail").toInt();
115 _adviseReco = settings.value("adviseReco").toInt();
116 _adviseScript = settings.value("adviseScript").toString();
117 expandEnvVar(_adviseScript);
[658]118
[408]119 // RINEX writer
120 // ------------
121 _samplingRate = settings.value("rnxSampl").toInt();
122 if ( settings.value("rnxPath").toString().isEmpty() ) {
123 _rnx = 0;
124 }
125 else {
126 _rnx = new bncRinex(_staID, mountPoint, format, latitude, longitude, nmea);
127 }
128
[319]129 msleep(100); //sleep 0.1 sec
[35]130}
131
132// Destructor
133////////////////////////////////////////////////////////////////////////////
134bncGetThread::~bncGetThread() {
[515]135 if (_socket) {
136 _socket->close();
[613]137#if QT_VERSION == 0x040203
138 delete _socket;
139#else
[612]140 _socket->deleteLater();
[613]141#endif
[515]142 }
[617]143 delete _decoder;
[606]144 delete _rnx;
[35]145}
146
[645]147#define AGENTVERSION "1.5"
[35]148// Connect to Caster, send the Request (static)
149////////////////////////////////////////////////////////////////////////////
[366]150QTcpSocket* bncGetThread::request(const QUrl& mountPoint,
151 QByteArray& latitude, QByteArray& longitude,
152 QByteArray& nmea, int timeOut,
[136]153 QString& msg) {
[35]154
[88]155 // Connect the Socket
156 // ------------------
157 QSettings settings;
158 QString proxyHost = settings.value("proxyHost").toString();
159 int proxyPort = settings.value("proxyPort").toInt();
160
[35]161 QTcpSocket* socket = new QTcpSocket();
162 if ( proxyHost.isEmpty() ) {
[88]163 socket->connectToHost(mountPoint.host(), mountPoint.port());
[35]164 }
165 else {
166 socket->connectToHost(proxyHost, proxyPort);
167 }
168 if (!socket->waitForConnected(timeOut)) {
[82]169 msg += "Connect timeout\n";
[35]170 delete socket;
171 return 0;
172 }
173
174 // Send Request
175 // ------------
[443]176 QString uName = QUrl::fromPercentEncoding(mountPoint.userName().toAscii());
177 QString passW = QUrl::fromPercentEncoding(mountPoint.password().toAscii());
[645]178 QByteArray userAndPwd;
[92]179
[645]180 if(!uName.isEmpty() || !passW.isEmpty())
181 {
182 userAndPwd = "Authorization: Basic " + (uName.toAscii() + ":" +
183 passW.toAscii()).toBase64() + "\r\n";
184 }
185
[92]186 QUrl hlp;
187 hlp.setScheme("http");
188 hlp.setHost(mountPoint.host());
189 hlp.setPort(mountPoint.port());
190 hlp.setPath(mountPoint.path());
191
[214]192 QByteArray reqStr;
193 if ( proxyHost.isEmpty() ) {
194 if (hlp.path().indexOf("/") != 0) hlp.setPath("/");
[645]195 reqStr = "GET " + hlp.path().toAscii() + " HTTP/1.0\r\n";
[214]196 } else {
[645]197 reqStr = "GET " + hlp.toEncoded() + " HTTP/1.0\r\n";
[205]198 }
[645]199 reqStr += "User-Agent: NTRIP BNC/" AGENTVERSION "\r\n"
200 "Host: " + hlp.host().toAscii() + "\r\n"
201 + userAndPwd + "\r\n";
[205]202
[464]203// NMEA string to handle VRS stream
204// --------------------------------
[356]205
206 double lat, lon;
[366]207
208 lat = strtod(latitude,NULL);
209 lon = strtod(longitude,NULL);
210
[410]211 if ((nmea == "yes") && (hlp.path().length() > 2) && (hlp.path().indexOf(".skl") < 0)) {
[356]212 const char* flagN="N";
213 const char* flagE="E";
214 if (lon >180.) {lon=(lon-360.)*(-1.); flagE="W";}
215 if ((lon < 0.) && (lon >= -180.)) {lon=lon*(-1.); flagE="W";}
216 if (lon < -180.) {lon=(lon+360.); flagE="E";}
217 if (lat < 0.) {lat=lat*(-1.); flagN="S";}
[566]218 QTime ttime(QDateTime::currentDateTime().toUTC().time());
[356]219 int lat_deg = (int)lat;
220 double lat_min=(lat-lat_deg)*60.;
221 int lon_deg = (int)lon;
222 double lon_min=(lon-lon_deg)*60.;
223 int hh = 0 , mm = 0;
224 double ss = 0.0;
225 hh=ttime.hour();
226 mm=ttime.minute();
227 ss=(double)ttime.second()+0.001*ttime.msec();
228 QString gga;
229 gga += "GPGGA,";
230 gga += QString("%1%2%3,").arg((int)hh, 2, 10, QLatin1Char('0')).arg((int)mm, 2, 10, QLatin1Char('0')).arg((int)ss, 2, 10, QLatin1Char('0'));
231 gga += QString("%1%2,").arg((int)lat_deg,2, 10, QLatin1Char('0')).arg(lat_min, 7, 'f', 4, QLatin1Char('0'));
232 gga += flagN;
233 gga += QString(",%1%2,").arg((int)lon_deg,3, 10, QLatin1Char('0')).arg(lon_min, 7, 'f', 4, QLatin1Char('0'));
234 gga += flagE + QString(",1,05,1.00,+00100,M,10.000,M,,");
235 int xori;
236 char XOR = 0;
237 char *Buff =gga.toAscii().data();
238 int iLen = strlen(Buff);
239 for (xori = 0; xori < iLen; xori++) {
240 XOR ^= (char)Buff[xori];
241 }
242 gga += QString("*%1").arg(XOR, 2, 16, QLatin1Char('0'));
243 reqStr += "$";
244 reqStr += gga;
245 reqStr += "\r\n";
246 }
247
[82]248 msg += reqStr;
[35]249
250 socket->write(reqStr, reqStr.length());
251
252 if (!socket->waitForBytesWritten(timeOut)) {
[82]253 msg += "Write timeout\n";
[35]254 delete socket;
255 return 0;
256 }
257
258 return socket;
259}
260
[136]261// Init Run
[35]262////////////////////////////////////////////////////////////////////////////
[138]263t_irc bncGetThread::initRun() {
[35]264
[515]265 // Initialize Socket
266 // -----------------
267 QString msg;
[602]268 _socket = this->request(_mountPoint, _latitude, _longitude,
269 _nmea, _timeOut, msg);
[35]270 if (!_socket) {
[138]271 return failure;
[35]272 }
273
274 // Read Caster Response
275 // --------------------
[136]276 _socket->waitForReadyRead(_timeOut);
[35]277 if (_socket->canReadLine()) {
278 QString line = _socket->readLine();
[473]279
280 // Skip messages from proxy server
281 // -------------------------------
282 if (line.indexOf("ICY 200 OK") == -1 &&
283 line.indexOf("200 OK") != -1 ) {
284 bool proxyRespond = true;
285 while (true) {
286 if (_socket->canReadLine()) {
287 line = _socket->readLine();
288 if (!proxyRespond) {
289 break;
290 }
291 if (line.trimmed().isEmpty()) {
292 proxyRespond = false;
293 }
294 }
295 else {
296 _socket->waitForReadyRead(_timeOut);
[474]297 if (_socket->bytesAvailable() <= 0) {
298 break;
299 }
[473]300 }
301 }
302 }
303
[146]304 if (line.indexOf("Unauthorized") != -1) {
[192]305 QStringList table;
306 bncTableDlg::getFullTable(_mountPoint.host(), _mountPoint.port(), table);
307 QString net;
308 QStringListIterator it(table);
309 while (it.hasNext()) {
310 QString line = it.next();
311 if (line.indexOf("STR") == 0) {
312 QStringList tags = line.split(";");
[255]313 if (tags.at(1) == _staID_orig) {
[192]314 net = tags.at(7);
315 break;
316 }
317 }
318 }
319
320 QString reg;
321 it.toFront();
322 while (it.hasNext()) {
323 QString line = it.next();
324 if (line.indexOf("NET") == 0) {
325 QStringList tags = line.split(";");
326 if (tags.at(1) == net) {
327 reg = tags.at(7);
328 break;
329 }
330 }
331 }
[194]332 emit(newMessage((_staID + ": Caster Response: " + line +
[200]333 " Adjust User-ID and Password Register, see"
[194]334 "\n " + reg).toAscii()));
[192]335 return fatal;
[146]336 }
[35]337 if (line.indexOf("ICY 200 OK") != 0) {
[190]338 emit(newMessage((_staID + ": Wrong Caster Response:\n" + line).toAscii()));
[144]339 return failure;
[35]340 }
341 }
342 else {
[190]343 emit(newMessage(_staID + ": Response Timeout"));
[138]344 return failure;
[35]345 }
346
347 // Instantiate the filter
348 // ----------------------
[423]349 if (!_decoder) {
[136]350 if (_format.indexOf("RTCM_2") != -1) {
351 emit(newMessage("Get Data: " + _staID + " in RTCM 2.x format"));
[243]352 _decoder = new RTCM2Decoder();
[136]353 }
354 else if (_format.indexOf("RTCM_3") != -1) {
[569]355 emit(newMessage("Get Data: " + _staID + " in RTCM 3.x format"));
[511]356 _decoder = new RTCM3Decoder();
[136]357 }
358 else if (_format.indexOf("RTIGS") != -1) {
359 emit(newMessage("Get Data: " + _staID + " in RTIGS format"));
[293]360 _decoder = new RTIGSDecoder();
[136]361 }
[428]362 else if (_format.indexOf("SP3") != -1 || _format.indexOf("ZERO") != -1) {
363 emit(newMessage("Get Data: " + _staID + " in original format"));
[424]364 _decoder = new bncZeroDecoder(_staID);
[406]365 }
[136]366 else {
[190]367 emit(newMessage(_staID + ": Unknown data format " + _format));
[250]368 return fatal;
[136]369 }
[60]370 }
[138]371 return success;
[136]372}
[59]373
[136]374// Run
375////////////////////////////////////////////////////////////////////////////
376void bncGetThread::run() {
377
[229]378 t_irc irc = initRun();
379
380 if (irc == fatal) {
[192]381 QThread::exit(1);
382 return;
383 }
[229]384 else if (irc != success) {
[190]385 emit(newMessage(_staID + ": initRun failed, reconnecting"));
[138]386 tryReconnect();
387 }
[136]388
[681]389 bool wrongEpoch = false;
[658]390 bool decode = true;
391 int numSucc = 0;
392 int secSucc = 0;
393 int secFail = 0;
394 int initPause = 30;
395 int currPause = 0;
396 bool begCorrupt = false;
397 bool endCorrupt = false;
398 _decodeTime = QDateTime::currentDateTime();
399
400 if (initPause < _inspSegm) {
401 initPause = _inspSegm;
402 }
403 currPause = initPause;
404
[35]405 // Read Incoming Data
406 // ------------------
407 while (true) {
[629]408 try {
409 if (_socket->state() != QAbstractSocket::ConnectedState) {
410 emit(newMessage(_staID + ": Socket not connected, reconnecting"));
411 tryReconnect();
412 }
[621]413
414 QListIterator<p_obs> it(_decoder->_obsList);
415 while (it.hasNext()) {
416 delete it.next();
417 }
418 _decoder->_obsList.clear();
419
[249]420 _socket->waitForReadyRead(_timeOut);
421 qint64 nBytes = _socket->bytesAvailable();
422 if (nBytes > 0) {
[567]423 emit newBytes(_staID, nBytes);
424
[249]425 char* data = new char[nBytes];
426 _socket->read(data, nBytes);
[406]427
[658]428 if (_inspSegm<1) {
429 _decoder->Decode(data, nBytes);
430 }
431 else {
432
433 // Decode data
434 // -----------
435 if (!_decodePause.isValid() ||
436 _decodePause.secsTo(QDateTime::currentDateTime()) >= currPause ) {
437
438 if (decode) {
439 if ( _decoder->Decode(data, nBytes) == success ) {
440 numSucc += 1;
441 }
442 if ( _decodeTime.secsTo(QDateTime::currentDateTime()) > _inspSegm ) {
443 decode = false;
444 }
[652]445 }
[658]446
447 // Check - once per inspect segment
448 // --------------------------------
449 if (!decode) {
450 _decodeTime = QDateTime::currentDateTime();
451 if (numSucc>0) {
452 secSucc += _inspSegm;
[668]453 if (secSucc > _adviseReco * 60) {
454 secSucc = _adviseReco * 60 + 1;
[658]455 }
456 numSucc = 0;
457 currPause = initPause;
458 _decodePause.setDate(QDate());
459 _decodePause.setTime(QTime());
460 }
461 else {
462 secFail += _inspSegm;
463 secSucc = 0;
[668]464 if (secFail > _adviseFail * 60) {
465 secFail = _adviseFail * 60 + 1;
[658]466 }
467 if (!_decodePause.isValid()) {
468 _decodePause = QDateTime::currentDateTime();
469 }
470 else {
471 _decodePause.setDate(QDate());
472 _decodePause.setTime(QTime());
473 secFail = secFail + currPause - _inspSegm;
474 currPause = currPause * 2;
475 if (currPause > 960) {
476 currPause = 960;
477 }
478 }
479 }
480
481 // End corrupt threshold
482 // ---------------------
[668]483 if ( begCorrupt && !endCorrupt && secSucc > _adviseReco * 60 ) {
[669]484 emit(newMessage(_staID + ": Corrupted recovery threshold exceeded"));
[658]485 callScript("End_Corrupted");
486 endCorrupt = true;
487 begCorrupt = false;
488 secFail = 0;
489 }
490 else {
491
492 // Begin corrupt threshold
493 // -----------------------
[668]494 if ( !begCorrupt && secFail > _adviseFail * 60 ) {
[669]495 emit(newMessage(_staID + ": Corrupted failure threshold exceeded"));
[658]496 callScript("Begin_Corrupted");
497 begCorrupt = true;
498 endCorrupt = false;
499 secSucc = 0;
500 numSucc = 0;
501 }
502 }
503 decode = true;
[650]504 }
505 }
[658]506 }
[650]507
[658]508 // End outage threshold
509 // --------------------
[668]510 if ( _decodeStart.isValid() && _decodeStart.secsTo(QDateTime::currentDateTime()) > _adviseReco * 60 ) {
[658]511 _decodeStart.setDate(QDate());
512 _decodeStart.setTime(QTime());
[686]513 if (_inspSegm>0) {
514 emit(newMessage(_staID + ": Outage recovery threshold exceeded"));
515 callScript("End_Outage");
516 }
[658]517 }
518
[331]519 delete [] data;
[423]520
[621]521 QListIterator<p_obs> it(_decoder->_obsList);
522 while (it.hasNext()) {
523 p_obs obs = it.next();
524
[351]525 // Check observation epoch
526 // -----------------------
527 int week;
528 double sec;
529 currentGPSWeeks(week, sec);
530
531 const double secPerWeek = 7.0 * 24.0 * 3600.0;
532 const double maxDt = 600.0;
533
[622]534 if (week < obs->_o.GPSWeek) {
[351]535 week += 1;
536 sec -= secPerWeek;
537 }
[622]538 if (week > obs->_o.GPSWeek) {
[351]539 week -= 1;
540 sec += secPerWeek;
541 }
[622]542 double dt = fabs(sec - obs->_o.GPSWeeks);
543 if (week != obs->_o.GPSWeek || dt > maxDt) {
[658]544 if (!wrongEpoch) {
545 emit( newMessage(_staID + ": Wrong observation epoch") );
546 wrongEpoch = true;
547 }
[621]548 delete obs;
[351]549 continue;
550 }
[658]551 else {
552 wrongEpoch = false;
553 }
[351]554
[408]555 // RINEX Output
556 // ------------
557 if (_rnx) {
[622]558 long iSec = long(floor(obs->_o.GPSWeeks+0.5));
559 long newTime = obs->_o.GPSWeek * 7*24*3600 + iSec;
[408]560 if (_samplingRate == 0 || iSec % _samplingRate == 0) {
[621]561 _rnx->deepCopy(obs);
[408]562 }
563 _rnx->dumpEpoch(newTime);
564 }
565
[621]566 bool firstObs = (obs == _decoder->_obsList.first());
[624]567 obs->_status = t_obs::posted;
[621]568 emit newObs(_staID, firstObs, obs);
[249]569 }
570 _decoder->_obsList.clear();
571 }
572 else {
573 emit(newMessage(_staID + ": Data Timeout, reconnecting"));
574 tryReconnect();
575 }
[35]576 }
[249]577 catch (const char* msg) {
578 emit(newMessage(_staID + msg));
[136]579 tryReconnect();
[35]580 }
581 }
582}
583
584// Exit
585////////////////////////////////////////////////////////////////////////////
586void bncGetThread::exit(int exitCode) {
587 if (exitCode!= 0) {
[88]588 emit error(_staID);
[35]589 }
590 QThread::exit(exitCode);
[148]591 terminate();
[35]592}
[82]593
[136]594// Try Re-Connect
595////////////////////////////////////////////////////////////////////////////
596void bncGetThread::tryReconnect() {
[408]597 if (_rnx) {
598 _rnx->setReconnectFlag(true);
599 }
[658]600 if ( !_decodeStart.isValid()) {
601 _decodeStop = QDateTime::currentDateTime();
602 }
[138]603 while (1) {
604 delete _socket; _socket = 0;
605 sleep(_nextSleep);
606 if ( initRun() == success ) {
[658]607 if ( !_decodeStop.isValid()) {
608 _decodeStart = QDateTime::currentDateTime();
609 }
[138]610 break;
611 }
612 else {
[658]613
614 // Begin outage threshold
615 // ----------------------
[668]616 if ( _decodeStop.isValid() && _decodeStop.secsTo(QDateTime::currentDateTime()) > _adviseFail * 60 ) {
[658]617 _decodeStop.setDate(QDate());
618 _decodeStop.setTime(QTime());
[686]619 if (_inspSegm>0) {
620 emit(newMessage(_staID + ": Outage failure threshold exceeded"));
621 callScript("Begin_Outage");
622 }
[658]623 }
[138]624 _nextSleep *= 2;
[442]625 if (_nextSleep > 256) {
626 _nextSleep = 256;
[152]627 }
[277]628 _nextSleep += rand() % 6;
[138]629 }
630 }
631 _nextSleep = 1;
[136]632}
[658]633
[668]634// Call advisory notice script
[658]635////////////////////////////////////////////////////////////////////////////
636void bncGetThread::callScript(const char* _comment) {
[672]637 QMutexLocker locker(&_mutex);
[668]638 if (!_adviseScript.isEmpty()) {
[672]639 msleep(1);
[658]640#ifdef WIN32
[668]641 QProcess::startDetached(_adviseScript, QStringList() << _staID << _comment) ;
[658]642#else
[668]643 QProcess::startDetached("nohup", QStringList() << _adviseScript << _staID << _comment) ;
[658]644#endif
645 }
646}
Note: See TracBrowser for help on using the repository browser.