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
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("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; }
114 _adviseFail = settings.value("adviseFail").toInt();
115 _adviseReco = settings.value("adviseReco").toInt();
116 _adviseScript = settings.value("adviseScript").toString();
117 expandEnvVar(_adviseScript);
118
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
129 msleep(100); //sleep 0.1 sec
130}
131
132// Destructor
133////////////////////////////////////////////////////////////////////////////
134bncGetThread::~bncGetThread() {
135 if (_socket) {
136 _socket->close();
137#if QT_VERSION == 0x040203
138 delete _socket;
139#else
140 _socket->deleteLater();
141#endif
142 }
143 delete _decoder;
144 delete _rnx;
145}
146
147#define AGENTVERSION "1.5"
148// Connect to Caster, send the Request (static)
149////////////////////////////////////////////////////////////////////////////
150QTcpSocket* bncGetThread::request(const QUrl& mountPoint,
151 QByteArray& latitude, QByteArray& longitude,
152 QByteArray& nmea, int timeOut,
153 QString& msg) {
154
155 // Connect the Socket
156 // ------------------
157 QSettings settings;
158 QString proxyHost = settings.value("proxyHost").toString();
159 int proxyPort = settings.value("proxyPort").toInt();
160
161 QTcpSocket* socket = new QTcpSocket();
162 if ( proxyHost.isEmpty() ) {
163 socket->connectToHost(mountPoint.host(), mountPoint.port());
164 }
165 else {
166 socket->connectToHost(proxyHost, proxyPort);
167 }
168 if (!socket->waitForConnected(timeOut)) {
169 msg += "Connect timeout\n";
170 delete socket;
171 return 0;
172 }
173
174 // Send Request
175 // ------------
176 QString uName = QUrl::fromPercentEncoding(mountPoint.userName().toAscii());
177 QString passW = QUrl::fromPercentEncoding(mountPoint.password().toAscii());
178 QByteArray userAndPwd;
179
180 if(!uName.isEmpty() || !passW.isEmpty())
181 {
182 userAndPwd = "Authorization: Basic " + (uName.toAscii() + ":" +
183 passW.toAscii()).toBase64() + "\r\n";
184 }
185
186 QUrl hlp;
187 hlp.setScheme("http");
188 hlp.setHost(mountPoint.host());
189 hlp.setPort(mountPoint.port());
190 hlp.setPath(mountPoint.path());
191
192 QByteArray reqStr;
193 if ( proxyHost.isEmpty() ) {
194 if (hlp.path().indexOf("/") != 0) hlp.setPath("/");
195 reqStr = "GET " + hlp.path().toAscii() + " HTTP/1.0\r\n";
196 } else {
197 reqStr = "GET " + hlp.toEncoded() + " HTTP/1.0\r\n";
198 }
199 reqStr += "User-Agent: NTRIP BNC/" AGENTVERSION "\r\n"
200 "Host: " + hlp.host().toAscii() + "\r\n"
201 + userAndPwd + "\r\n";
202
203// NMEA string to handle VRS stream
204// --------------------------------
205
206 double lat, lon;
207
208 lat = strtod(latitude,NULL);
209 lon = strtod(longitude,NULL);
210
211 if ((nmea == "yes") && (hlp.path().length() > 2) && (hlp.path().indexOf(".skl") < 0)) {
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";}
218 QTime ttime(QDateTime::currentDateTime().toUTC().time());
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
248 msg += reqStr;
249
250 socket->write(reqStr, reqStr.length());
251
252 if (!socket->waitForBytesWritten(timeOut)) {
253 msg += "Write timeout\n";
254 delete socket;
255 return 0;
256 }
257
258 return socket;
259}
260
261// Init Run
262////////////////////////////////////////////////////////////////////////////
263t_irc bncGetThread::initRun() {
264
265 // Initialize Socket
266 // -----------------
267 QString msg;
268 _socket = this->request(_mountPoint, _latitude, _longitude,
269 _nmea, _timeOut, msg);
270 if (!_socket) {
271 return failure;
272 }
273
274 // Read Caster Response
275 // --------------------
276 _socket->waitForReadyRead(_timeOut);
277 if (_socket->canReadLine()) {
278 QString line = _socket->readLine();
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);
297 if (_socket->bytesAvailable() <= 0) {
298 break;
299 }
300 }
301 }
302 }
303
304 if (line.indexOf("Unauthorized") != -1) {
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(";");
313 if (tags.at(1) == _staID_orig) {
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 }
332 emit(newMessage((_staID + ": Caster Response: " + line +
333 " Adjust User-ID and Password Register, see"
334 "\n " + reg).toAscii()));
335 return fatal;
336 }
337 if (line.indexOf("ICY 200 OK") != 0) {
338 emit(newMessage((_staID + ": Wrong Caster Response:\n" + line).toAscii()));
339 return failure;
340 }
341 }
342 else {
343 emit(newMessage(_staID + ": Response Timeout"));
344 return failure;
345 }
346
347 // Instantiate the filter
348 // ----------------------
349 if (!_decoder) {
350 if (_format.indexOf("RTCM_2") != -1) {
351 emit(newMessage("Get Data: " + _staID + " in RTCM 2.x format"));
352 _decoder = new RTCM2Decoder();
353 }
354 else if (_format.indexOf("RTCM_3") != -1) {
355 emit(newMessage("Get Data: " + _staID + " in RTCM 3.x format"));
356 _decoder = new RTCM3Decoder();
357 }
358 else if (_format.indexOf("RTIGS") != -1) {
359 emit(newMessage("Get Data: " + _staID + " in RTIGS format"));
360 _decoder = new RTIGSDecoder();
361 }
362 else if (_format.indexOf("SP3") != -1 || _format.indexOf("ZERO") != -1) {
363 emit(newMessage("Get Data: " + _staID + " in original format"));
364 _decoder = new bncZeroDecoder(_staID);
365 }
366 else {
367 emit(newMessage(_staID + ": Unknown data format " + _format));
368 return fatal;
369 }
370 }
371 return success;
372}
373
374// Run
375////////////////////////////////////////////////////////////////////////////
376void bncGetThread::run() {
377
378 t_irc irc = initRun();
379
380 if (irc == fatal) {
381 QThread::exit(1);
382 return;
383 }
384 else if (irc != success) {
385 emit(newMessage(_staID + ": initRun failed, reconnecting"));
386 tryReconnect();
387 }
388
389 bool wrongEpoch = false;
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 if ( _adviseFail < 1 && _adviseReco < 1 ) {
404 initPause = 0;
405 }
406 currPause = initPause;
407
408 // Read Incoming Data
409 // ------------------
410 while (true) {
411 try {
412 if (_socket->state() != QAbstractSocket::ConnectedState) {
413 emit(newMessage(_staID + ": Socket not connected, reconnecting"));
414 tryReconnect();
415 }
416
417 QListIterator<p_obs> it(_decoder->_obsList);
418 while (it.hasNext()) {
419 delete it.next();
420 }
421 _decoder->_obsList.clear();
422
423 _socket->waitForReadyRead(_timeOut);
424 qint64 nBytes = _socket->bytesAvailable();
425 if (nBytes > 0) {
426 emit newBytes(_staID, nBytes);
427
428 char* data = new char[nBytes];
429 _socket->read(data, nBytes);
430
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 }
448 }
449
450 // Check - once per inspect segment
451 // --------------------------------
452 if (!decode) {
453 _decodeTime = QDateTime::currentDateTime();
454 if (numSucc>0) {
455 secSucc += _inspSegm;
456 if (secSucc > _adviseReco * 60) {
457 secSucc = _adviseReco * 60 + 1;
458 }
459 numSucc = 0;
460 currPause = initPause;
461 _decodePause.setDate(QDate());
462 _decodePause.setTime(QTime());
463 }
464 else {
465 secFail += _inspSegm;
466 secSucc = 0;
467 if (secFail > _adviseFail * 60) {
468 secFail = _adviseFail * 60 + 1;
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 // ---------------------
486 if ( begCorrupt && !endCorrupt && secSucc > _adviseReco * 60 ) {
487 emit(newMessage(_staID + ": Corrupted recovery threshold exceeded"));
488 callScript("End_Corrupted");
489 endCorrupt = true;
490 begCorrupt = false;
491 secFail = 0;
492 }
493 else {
494
495 // Begin corrupt threshold
496 // -----------------------
497 if ( !begCorrupt && secFail > _adviseFail * 60 ) {
498 emit(newMessage(_staID + ": Corrupted failure threshold exceeded"));
499 callScript("Begin_Corrupted");
500 begCorrupt = true;
501 endCorrupt = false;
502 secSucc = 0;
503 numSucc = 0;
504 }
505 }
506 decode = true;
507 }
508 }
509 }
510
511 // End outage threshold
512 // --------------------
513 if ( _decodeStart.isValid() && _decodeStart.secsTo(QDateTime::currentDateTime()) > _adviseReco * 60 ) {
514 _decodeStart.setDate(QDate());
515 _decodeStart.setTime(QTime());
516 if (_inspSegm>0) {
517 emit(newMessage(_staID + ": Outage recovery threshold exceeded"));
518 callScript("End_Outage");
519 }
520 }
521
522 delete [] data;
523
524 QListIterator<p_obs> it(_decoder->_obsList);
525 while (it.hasNext()) {
526 p_obs obs = it.next();
527
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
537 if (week < obs->_o.GPSWeek) {
538 week += 1;
539 sec -= secPerWeek;
540 }
541 if (week > obs->_o.GPSWeek) {
542 week -= 1;
543 sec += secPerWeek;
544 }
545 double dt = fabs(sec - obs->_o.GPSWeeks);
546 if (week != obs->_o.GPSWeek || dt > maxDt) {
547 if (!wrongEpoch) {
548 emit( newMessage(_staID + ": Wrong observation epoch") );
549 wrongEpoch = true;
550 }
551 delete obs;
552 continue;
553 }
554 else {
555 wrongEpoch = false;
556 }
557
558 // RINEX Output
559 // ------------
560 if (_rnx) {
561 long iSec = long(floor(obs->_o.GPSWeeks+0.5));
562 long newTime = obs->_o.GPSWeek * 7*24*3600 + iSec;
563 if (_samplingRate == 0 || iSec % _samplingRate == 0) {
564 _rnx->deepCopy(obs);
565 }
566 _rnx->dumpEpoch(newTime);
567 }
568
569 bool firstObs = (obs == _decoder->_obsList.first());
570 obs->_status = t_obs::posted;
571 emit newObs(_staID, firstObs, obs);
572 }
573 _decoder->_obsList.clear();
574 }
575 else {
576 emit(newMessage(_staID + ": Data Timeout, reconnecting"));
577 tryReconnect();
578 }
579 }
580 catch (const char* msg) {
581 emit(newMessage(_staID + msg));
582 tryReconnect();
583 }
584 }
585}
586
587// Exit
588////////////////////////////////////////////////////////////////////////////
589void bncGetThread::exit(int exitCode) {
590 if (exitCode!= 0) {
591 emit error(_staID);
592 }
593 QThread::exit(exitCode);
594 terminate();
595}
596
597// Try Re-Connect
598////////////////////////////////////////////////////////////////////////////
599void bncGetThread::tryReconnect() {
600 if (_rnx) {
601 _rnx->setReconnectFlag(true);
602 }
603 if ( !_decodeStart.isValid()) {
604 _decodeStop = QDateTime::currentDateTime();
605 }
606 while (1) {
607 delete _socket; _socket = 0;
608 sleep(_nextSleep);
609 if ( initRun() == success ) {
610 if ( !_decodeStop.isValid()) {
611 _decodeStart = QDateTime::currentDateTime();
612 }
613 break;
614 }
615 else {
616
617 // Begin outage threshold
618 // ----------------------
619 if ( _decodeStop.isValid() && _decodeStop.secsTo(QDateTime::currentDateTime()) > _adviseFail * 60 ) {
620 _decodeStop.setDate(QDate());
621 _decodeStop.setTime(QTime());
622 if (_inspSegm>0) {
623 emit(newMessage(_staID + ": Outage failure threshold exceeded"));
624 callScript("Begin_Outage");
625 }
626 }
627 _nextSleep *= 2;
628 if (_nextSleep > 256) {
629 _nextSleep = 256;
630 }
631 _nextSleep += rand() % 6;
632 }
633 }
634 _nextSleep = 1;
635}
636
637// Call advisory notice script
638////////////////////////////////////////////////////////////////////////////
639void bncGetThread::callScript(const char* _comment) {
640 QMutexLocker locker(&_mutex);
641 if (!_adviseScript.isEmpty()) {
642 msleep(1);
643#ifdef WIN32
644 QProcess::startDetached(_adviseScript, QStringList() << _staID << _comment) ;
645#else
646 QProcess::startDetached("nohup", QStringList() << _adviseScript << _staID << _comment) ;
647#endif
648 }
649}
Note: See TracBrowser for help on using the repository browser.