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

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

* empty log message *

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