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

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

* empty log message *

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