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

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

* empty log message *

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