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

Last change on this file since 605 was 605, checked in by mervart, 17 years ago

* empty log message *

File size: 13.5 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
106 // RINEX writer
107 // ------------
108 _samplingRate = settings.value("rnxSampl").toInt();
109 if ( settings.value("rnxPath").toString().isEmpty() ) {
110 _rnx = 0;
111 }
112 else {
113 _rnx = new bncRinex(_staID, mountPoint, format, latitude, longitude, nmea);
114 }
115
[319]116 msleep(100); //sleep 0.1 sec
[35]117}
118
119// Destructor
120////////////////////////////////////////////////////////////////////////////
121bncGetThread::~bncGetThread() {
[515]122 if (_socket) {
123 _socket->close();
[602]124 delete _socket; // not allowed in Qt - created in different thread
[515]125 }
[136]126 delete _decoder;
[35]127}
128
129// Connect to Caster, send the Request (static)
130////////////////////////////////////////////////////////////////////////////
[366]131QTcpSocket* bncGetThread::request(const QUrl& mountPoint,
132 QByteArray& latitude, QByteArray& longitude,
133 QByteArray& nmea, int timeOut,
[136]134 QString& msg) {
[35]135
[88]136 // Connect the Socket
137 // ------------------
138 QSettings settings;
139 QString proxyHost = settings.value("proxyHost").toString();
140 int proxyPort = settings.value("proxyPort").toInt();
141
[35]142 QTcpSocket* socket = new QTcpSocket();
143 if ( proxyHost.isEmpty() ) {
[88]144 socket->connectToHost(mountPoint.host(), mountPoint.port());
[35]145 }
146 else {
147 socket->connectToHost(proxyHost, proxyPort);
148 }
149 if (!socket->waitForConnected(timeOut)) {
[82]150 msg += "Connect timeout\n";
[35]151 delete socket;
152 return 0;
153 }
154
155 // Send Request
156 // ------------
[443]157 QString uName = QUrl::fromPercentEncoding(mountPoint.userName().toAscii());
158 QString passW = QUrl::fromPercentEncoding(mountPoint.password().toAscii());
[444]159 QByteArray userAndPwd = uName.toAscii() + ":" + passW.toAscii();
[92]160
161 QUrl hlp;
162 hlp.setScheme("http");
163 hlp.setHost(mountPoint.host());
164 hlp.setPort(mountPoint.port());
165 hlp.setPath(mountPoint.path());
166
[214]167 QByteArray reqStr;
168 if ( proxyHost.isEmpty() ) {
169 if (hlp.path().indexOf("/") != 0) hlp.setPath("/");
170 reqStr = "GET " + hlp.path().toAscii() +
171 " HTTP/1.0\r\n"
[565]172 "User-Agent: NTRIP BNC 1.5\r\n"
[214]173 "Authorization: Basic " +
[440]174 userAndPwd.toBase64() + "\r\n";
[214]175 } else {
176 reqStr = "GET " + hlp.toEncoded() +
177 " HTTP/1.0\r\n"
[565]178 "User-Agent: NTRIP BNC 1.5\r\n"
[214]179 "Authorization: Basic " +
[440]180 userAndPwd.toBase64() + "\r\n";
[205]181 }
[440]182 if (hlp.path().indexOf(".skl") > 0) { reqStr += "Host: " + hlp.host().toAscii() + "\r\n"; }
183 reqStr += "\r\n";
[205]184
[464]185// NMEA string to handle VRS stream
186// --------------------------------
[356]187
188 double lat, lon;
[366]189
190 lat = strtod(latitude,NULL);
191 lon = strtod(longitude,NULL);
192
[410]193 if ((nmea == "yes") && (hlp.path().length() > 2) && (hlp.path().indexOf(".skl") < 0)) {
[356]194 const char* flagN="N";
195 const char* flagE="E";
196 if (lon >180.) {lon=(lon-360.)*(-1.); flagE="W";}
197 if ((lon < 0.) && (lon >= -180.)) {lon=lon*(-1.); flagE="W";}
198 if (lon < -180.) {lon=(lon+360.); flagE="E";}
199 if (lat < 0.) {lat=lat*(-1.); flagN="S";}
[566]200 QTime ttime(QDateTime::currentDateTime().toUTC().time());
[356]201 int lat_deg = (int)lat;
202 double lat_min=(lat-lat_deg)*60.;
203 int lon_deg = (int)lon;
204 double lon_min=(lon-lon_deg)*60.;
205 int hh = 0 , mm = 0;
206 double ss = 0.0;
207 hh=ttime.hour();
208 mm=ttime.minute();
209 ss=(double)ttime.second()+0.001*ttime.msec();
210 QString gga;
211 gga += "GPGGA,";
212 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'));
213 gga += QString("%1%2,").arg((int)lat_deg,2, 10, QLatin1Char('0')).arg(lat_min, 7, 'f', 4, QLatin1Char('0'));
214 gga += flagN;
215 gga += QString(",%1%2,").arg((int)lon_deg,3, 10, QLatin1Char('0')).arg(lon_min, 7, 'f', 4, QLatin1Char('0'));
216 gga += flagE + QString(",1,05,1.00,+00100,M,10.000,M,,");
217 int xori;
218 char XOR = 0;
219 char *Buff =gga.toAscii().data();
220 int iLen = strlen(Buff);
221 for (xori = 0; xori < iLen; xori++) {
222 XOR ^= (char)Buff[xori];
223 }
224 gga += QString("*%1").arg(XOR, 2, 16, QLatin1Char('0'));
225 reqStr += "$";
226 reqStr += gga;
227 reqStr += "\r\n";
228 }
229
[82]230 msg += reqStr;
[35]231
232 socket->write(reqStr, reqStr.length());
233
234 if (!socket->waitForBytesWritten(timeOut)) {
[82]235 msg += "Write timeout\n";
[35]236 delete socket;
237 return 0;
238 }
239
240 return socket;
241}
242
[136]243// Init Run
[35]244////////////////////////////////////////////////////////////////////////////
[138]245t_irc bncGetThread::initRun() {
[35]246
[515]247 // Initialize Socket
248 // -----------------
249 QString msg;
[602]250 _socket = this->request(_mountPoint, _latitude, _longitude,
251 _nmea, _timeOut, msg);
[35]252 if (!_socket) {
[138]253 return failure;
[35]254 }
255
256 // Read Caster Response
257 // --------------------
[136]258 _socket->waitForReadyRead(_timeOut);
[35]259 if (_socket->canReadLine()) {
260 QString line = _socket->readLine();
[473]261
262 // Skip messages from proxy server
263 // -------------------------------
264 if (line.indexOf("ICY 200 OK") == -1 &&
265 line.indexOf("200 OK") != -1 ) {
266 bool proxyRespond = true;
267 while (true) {
268 if (_socket->canReadLine()) {
269 line = _socket->readLine();
270 if (!proxyRespond) {
271 break;
272 }
273 if (line.trimmed().isEmpty()) {
274 proxyRespond = false;
275 }
276 }
277 else {
278 _socket->waitForReadyRead(_timeOut);
[474]279 if (_socket->bytesAvailable() <= 0) {
280 break;
281 }
[473]282 }
283 }
284 }
285
[146]286 if (line.indexOf("Unauthorized") != -1) {
[192]287 QStringList table;
288 bncTableDlg::getFullTable(_mountPoint.host(), _mountPoint.port(), table);
289 QString net;
290 QStringListIterator it(table);
291 while (it.hasNext()) {
292 QString line = it.next();
293 if (line.indexOf("STR") == 0) {
294 QStringList tags = line.split(";");
[255]295 if (tags.at(1) == _staID_orig) {
[192]296 net = tags.at(7);
297 break;
298 }
299 }
300 }
301
302 QString reg;
303 it.toFront();
304 while (it.hasNext()) {
305 QString line = it.next();
306 if (line.indexOf("NET") == 0) {
307 QStringList tags = line.split(";");
308 if (tags.at(1) == net) {
309 reg = tags.at(7);
310 break;
311 }
312 }
313 }
[194]314 emit(newMessage((_staID + ": Caster Response: " + line +
[200]315 " Adjust User-ID and Password Register, see"
[194]316 "\n " + reg).toAscii()));
[192]317 return fatal;
[146]318 }
[35]319 if (line.indexOf("ICY 200 OK") != 0) {
[190]320 emit(newMessage((_staID + ": Wrong Caster Response:\n" + line).toAscii()));
[144]321 return failure;
[35]322 }
323 }
324 else {
[190]325 emit(newMessage(_staID + ": Response Timeout"));
[138]326 return failure;
[35]327 }
328
329 // Instantiate the filter
330 // ----------------------
[423]331 if (!_decoder) {
[136]332 if (_format.indexOf("RTCM_2") != -1) {
333 emit(newMessage("Get Data: " + _staID + " in RTCM 2.x format"));
[243]334 _decoder = new RTCM2Decoder();
[136]335 }
336 else if (_format.indexOf("RTCM_3") != -1) {
[569]337 emit(newMessage("Get Data: " + _staID + " in RTCM 3.x format"));
[511]338 _decoder = new RTCM3Decoder();
[136]339 }
340 else if (_format.indexOf("RTIGS") != -1) {
341 emit(newMessage("Get Data: " + _staID + " in RTIGS format"));
[293]342 _decoder = new RTIGSDecoder();
[136]343 }
[428]344 else if (_format.indexOf("SP3") != -1 || _format.indexOf("ZERO") != -1) {
345 emit(newMessage("Get Data: " + _staID + " in original format"));
[424]346 _decoder = new bncZeroDecoder(_staID);
[406]347 }
[136]348 else {
[190]349 emit(newMessage(_staID + ": Unknown data format " + _format));
[250]350 return fatal;
[136]351 }
[60]352 }
[138]353 return success;
[136]354}
[59]355
[136]356// Run
357////////////////////////////////////////////////////////////////////////////
358void bncGetThread::run() {
359
[229]360 t_irc irc = initRun();
361
362 if (irc == fatal) {
[192]363 QThread::exit(1);
364 return;
365 }
[229]366 else if (irc != success) {
[190]367 emit(newMessage(_staID + ": initRun failed, reconnecting"));
[138]368 tryReconnect();
369 }
[136]370
[35]371 // Read Incoming Data
372 // ------------------
373 while (true) {
[249]374 try {
375 if (_socket->state() != QAbstractSocket::ConnectedState) {
376 emit(newMessage(_staID + ": Socket not connected, reconnecting"));
377 tryReconnect();
[35]378 }
[249]379
380
381 _socket->waitForReadyRead(_timeOut);
382 qint64 nBytes = _socket->bytesAvailable();
383 if (nBytes > 0) {
[567]384 emit newBytes(_staID, nBytes);
385
[249]386 char* data = new char[nBytes];
387 _socket->read(data, nBytes);
[406]388
[249]389 _decoder->Decode(data, nBytes);
[331]390 delete [] data;
[423]391
[249]392 for (list<Observation*>::iterator it = _decoder->_obsList.begin();
393 it != _decoder->_obsList.end(); it++) {
[351]394
395 // Check observation epoch
396 // -----------------------
397 int week;
398 double sec;
399 currentGPSWeeks(week, sec);
400
401 const double secPerWeek = 7.0 * 24.0 * 3600.0;
402 const double maxDt = 600.0;
403
404 if (week < (*it)->GPSWeek) {
405 week += 1;
406 sec -= secPerWeek;
407 }
408 if (week > (*it)->GPSWeek) {
409 week -= 1;
410 sec += secPerWeek;
411 }
412 double dt = fabs(sec - (*it)->GPSWeeks);
413 if (week != (*it)->GPSWeek || dt > maxDt) {
414 emit( newMessage("Wrong observation epoch") );
415 delete (*it);
416 continue;
417 }
418
[408]419 // RINEX Output
420 // ------------
421 if (_rnx) {
422 long iSec = long(floor((*it)->GPSWeeks+0.5));
423 long newTime = (*it)->GPSWeek * 7*24*3600 + iSec;
424 if (_samplingRate == 0 || iSec % _samplingRate == 0) {
425 _rnx->deepCopy(*it);
426 }
427 _rnx->dumpEpoch(newTime);
428 }
429
[409]430 bool firstObs = (it == _decoder->_obsList.begin());
[463]431 emit newObs(_staID, firstObs, *it);
[249]432 }
433 _decoder->_obsList.clear();
434 }
435 else {
436 emit(newMessage(_staID + ": Data Timeout, reconnecting"));
437 tryReconnect();
438 }
[35]439 }
[249]440 catch (const char* msg) {
441 emit(newMessage(_staID + msg));
[136]442 tryReconnect();
[35]443 }
444 }
445}
446
447// Exit
448////////////////////////////////////////////////////////////////////////////
449void bncGetThread::exit(int exitCode) {
450 if (exitCode!= 0) {
[88]451 emit error(_staID);
[35]452 }
453 QThread::exit(exitCode);
[148]454 terminate();
[35]455}
[82]456
[136]457// Try Re-Connect
458////////////////////////////////////////////////////////////////////////////
459void bncGetThread::tryReconnect() {
[408]460 if (_rnx) {
461 _rnx->setReconnectFlag(true);
462 }
[138]463 while (1) {
464 delete _socket; _socket = 0;
465 sleep(_nextSleep);
466 if ( initRun() == success ) {
467 break;
468 }
469 else {
470 _nextSleep *= 2;
[442]471 if (_nextSleep > 256) {
472 _nextSleep = 256;
[152]473 }
[277]474 _nextSleep += rand() % 6;
[138]475 }
476 }
477 _nextSleep = 1;
[136]478}
Note: See TracBrowser for help on using the repository browser.