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

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

* empty log message *

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