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

Last change on this file since 686 was 686, checked in by weber, 16 years ago

* empty log message *

File size: 18.8 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 }
[668]403 if ( _adviseFail < 1 && _adviseReco < 1 ) {
[658]404 initPause = 0;
405 }
406 currPause = initPause;
407
[35]408 // Read Incoming Data
409 // ------------------
410 while (true) {
[629]411 try {
412 if (_socket->state() != QAbstractSocket::ConnectedState) {
413 emit(newMessage(_staID + ": Socket not connected, reconnecting"));
414 tryReconnect();
415 }
[621]416
417 QListIterator<p_obs> it(_decoder->_obsList);
418 while (it.hasNext()) {
419 delete it.next();
420 }
421 _decoder->_obsList.clear();
422
[249]423 _socket->waitForReadyRead(_timeOut);
424 qint64 nBytes = _socket->bytesAvailable();
425 if (nBytes > 0) {
[567]426 emit newBytes(_staID, nBytes);
427
[249]428 char* data = new char[nBytes];
429 _socket->read(data, nBytes);
[406]430
[658]431 if (_inspSegm<1) {
432 _decoder->Decode(data, nBytes);
433 }
434 else {
435
436 // Decode data
437 // -----------
438 if (!_decodePause.isValid() ||
439 _decodePause.secsTo(QDateTime::currentDateTime()) >= currPause ) {
440
441 if (decode) {
442 if ( _decoder->Decode(data, nBytes) == success ) {
443 numSucc += 1;
444 }
445 if ( _decodeTime.secsTo(QDateTime::currentDateTime()) > _inspSegm ) {
446 decode = false;
447 }
[652]448 }
[658]449
450 // Check - once per inspect segment
451 // --------------------------------
452 if (!decode) {
453 _decodeTime = QDateTime::currentDateTime();
454 if (numSucc>0) {
455 secSucc += _inspSegm;
[668]456 if (secSucc > _adviseReco * 60) {
457 secSucc = _adviseReco * 60 + 1;
[658]458 }
459 numSucc = 0;
460 currPause = initPause;
461 _decodePause.setDate(QDate());
462 _decodePause.setTime(QTime());
463 }
464 else {
465 secFail += _inspSegm;
466 secSucc = 0;
[668]467 if (secFail > _adviseFail * 60) {
468 secFail = _adviseFail * 60 + 1;
[658]469 }
470 if (!_decodePause.isValid()) {
471 _decodePause = QDateTime::currentDateTime();
472 }
473 else {
474 _decodePause.setDate(QDate());
475 _decodePause.setTime(QTime());
476 secFail = secFail + currPause - _inspSegm;
477 currPause = currPause * 2;
478 if (currPause > 960) {
479 currPause = 960;
480 }
481 }
482 }
483
484 // End corrupt threshold
485 // ---------------------
[668]486 if ( begCorrupt && !endCorrupt && secSucc > _adviseReco * 60 ) {
[669]487 emit(newMessage(_staID + ": Corrupted recovery threshold exceeded"));
[658]488 callScript("End_Corrupted");
489 endCorrupt = true;
490 begCorrupt = false;
491 secFail = 0;
492 }
493 else {
494
495 // Begin corrupt threshold
496 // -----------------------
[668]497 if ( !begCorrupt && secFail > _adviseFail * 60 ) {
[669]498 emit(newMessage(_staID + ": Corrupted failure threshold exceeded"));
[658]499 callScript("Begin_Corrupted");
500 begCorrupt = true;
501 endCorrupt = false;
502 secSucc = 0;
503 numSucc = 0;
504 }
505 }
506 decode = true;
[650]507 }
508 }
[658]509 }
[650]510
[658]511 // End outage threshold
512 // --------------------
[668]513 if ( _decodeStart.isValid() && _decodeStart.secsTo(QDateTime::currentDateTime()) > _adviseReco * 60 ) {
[658]514 _decodeStart.setDate(QDate());
515 _decodeStart.setTime(QTime());
[686]516 if (_inspSegm>0) {
517 emit(newMessage(_staID + ": Outage recovery threshold exceeded"));
518 callScript("End_Outage");
519 }
[658]520 }
521
[331]522 delete [] data;
[423]523
[621]524 QListIterator<p_obs> it(_decoder->_obsList);
525 while (it.hasNext()) {
526 p_obs obs = it.next();
527
[351]528 // Check observation epoch
529 // -----------------------
530 int week;
531 double sec;
532 currentGPSWeeks(week, sec);
533
534 const double secPerWeek = 7.0 * 24.0 * 3600.0;
535 const double maxDt = 600.0;
536
[622]537 if (week < obs->_o.GPSWeek) {
[351]538 week += 1;
539 sec -= secPerWeek;
540 }
[622]541 if (week > obs->_o.GPSWeek) {
[351]542 week -= 1;
543 sec += secPerWeek;
544 }
[622]545 double dt = fabs(sec - obs->_o.GPSWeeks);
546 if (week != obs->_o.GPSWeek || dt > maxDt) {
[658]547 if (!wrongEpoch) {
548 emit( newMessage(_staID + ": Wrong observation epoch") );
549 wrongEpoch = true;
550 }
[621]551 delete obs;
[351]552 continue;
553 }
[658]554 else {
555 wrongEpoch = false;
556 }
[351]557
[408]558 // RINEX Output
559 // ------------
560 if (_rnx) {
[622]561 long iSec = long(floor(obs->_o.GPSWeeks+0.5));
562 long newTime = obs->_o.GPSWeek * 7*24*3600 + iSec;
[408]563 if (_samplingRate == 0 || iSec % _samplingRate == 0) {
[621]564 _rnx->deepCopy(obs);
[408]565 }
566 _rnx->dumpEpoch(newTime);
567 }
568
[621]569 bool firstObs = (obs == _decoder->_obsList.first());
[624]570 obs->_status = t_obs::posted;
[621]571 emit newObs(_staID, firstObs, obs);
[249]572 }
573 _decoder->_obsList.clear();
574 }
575 else {
576 emit(newMessage(_staID + ": Data Timeout, reconnecting"));
577 tryReconnect();
578 }
[35]579 }
[249]580 catch (const char* msg) {
581 emit(newMessage(_staID + msg));
[136]582 tryReconnect();
[35]583 }
584 }
585}
586
587// Exit
588////////////////////////////////////////////////////////////////////////////
589void bncGetThread::exit(int exitCode) {
590 if (exitCode!= 0) {
[88]591 emit error(_staID);
[35]592 }
593 QThread::exit(exitCode);
[148]594 terminate();
[35]595}
[82]596
[136]597// Try Re-Connect
598////////////////////////////////////////////////////////////////////////////
599void bncGetThread::tryReconnect() {
[408]600 if (_rnx) {
601 _rnx->setReconnectFlag(true);
602 }
[658]603 if ( !_decodeStart.isValid()) {
604 _decodeStop = QDateTime::currentDateTime();
605 }
[138]606 while (1) {
607 delete _socket; _socket = 0;
608 sleep(_nextSleep);
609 if ( initRun() == success ) {
[658]610 if ( !_decodeStop.isValid()) {
611 _decodeStart = QDateTime::currentDateTime();
612 }
[138]613 break;
614 }
615 else {
[658]616
617 // Begin outage threshold
618 // ----------------------
[668]619 if ( _decodeStop.isValid() && _decodeStop.secsTo(QDateTime::currentDateTime()) > _adviseFail * 60 ) {
[658]620 _decodeStop.setDate(QDate());
621 _decodeStop.setTime(QTime());
[686]622 if (_inspSegm>0) {
623 emit(newMessage(_staID + ": Outage failure threshold exceeded"));
624 callScript("Begin_Outage");
625 }
[658]626 }
[138]627 _nextSleep *= 2;
[442]628 if (_nextSleep > 256) {
629 _nextSleep = 256;
[152]630 }
[277]631 _nextSleep += rand() % 6;
[138]632 }
633 }
634 _nextSleep = 1;
[136]635}
[658]636
[668]637// Call advisory notice script
[658]638////////////////////////////////////////////////////////////////////////////
639void bncGetThread::callScript(const char* _comment) {
[672]640 QMutexLocker locker(&_mutex);
[668]641 if (!_adviseScript.isEmpty()) {
[672]642 msleep(1);
[658]643#ifdef WIN32
[668]644 QProcess::startDetached(_adviseScript, QStringList() << _staID << _comment) ;
[658]645#else
[668]646 QProcess::startDetached("nohup", QStringList() << _adviseScript << _staID << _comment) ;
[658]647#endif
648 }
649}
Note: See TracBrowser for help on using the repository browser.