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

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

* empty log message *

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