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

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