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

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

* empty log message *

File size: 14.0 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 // 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
116 msleep(100); //sleep 0.1 sec
117}
118
119// Destructor
120////////////////////////////////////////////////////////////////////////////
121bncGetThread::~bncGetThread() {
122 if (_socket) {
123 _socket->close();
124#if QT_VERSION == 0x040203
125 delete _socket;
126#else
127 _socket->deleteLater();
128#endif
129 }
130 delete _decoder;
131 delete _rnx;
132}
133
134#define AGENTVERSION "1.5"
135// Connect to Caster, send the Request (static)
136////////////////////////////////////////////////////////////////////////////
137QTcpSocket* bncGetThread::request(const QUrl& mountPoint,
138 QByteArray& latitude, QByteArray& longitude,
139 QByteArray& nmea, int timeOut,
140 QString& msg) {
141
142 // Connect the Socket
143 // ------------------
144 QSettings settings;
145 QString proxyHost = settings.value("proxyHost").toString();
146 int proxyPort = settings.value("proxyPort").toInt();
147
148 QTcpSocket* socket = new QTcpSocket();
149 if ( proxyHost.isEmpty() ) {
150 socket->connectToHost(mountPoint.host(), mountPoint.port());
151 }
152 else {
153 socket->connectToHost(proxyHost, proxyPort);
154 }
155 if (!socket->waitForConnected(timeOut)) {
156 msg += "Connect timeout\n";
157 delete socket;
158 return 0;
159 }
160
161 // Send Request
162 // ------------
163 QString uName = QUrl::fromPercentEncoding(mountPoint.userName().toAscii());
164 QString passW = QUrl::fromPercentEncoding(mountPoint.password().toAscii());
165 QByteArray userAndPwd;
166
167 if(!uName.isEmpty() || !passW.isEmpty())
168 {
169 userAndPwd = "Authorization: Basic " + (uName.toAscii() + ":" +
170 passW.toAscii()).toBase64() + "\r\n";
171 }
172
173 QUrl hlp;
174 hlp.setScheme("http");
175 hlp.setHost(mountPoint.host());
176 hlp.setPort(mountPoint.port());
177 hlp.setPath(mountPoint.path());
178
179 QByteArray reqStr;
180 if ( proxyHost.isEmpty() ) {
181 if (hlp.path().indexOf("/") != 0) hlp.setPath("/");
182 reqStr = "GET " + hlp.path().toAscii() + " HTTP/1.0\r\n";
183 } else {
184 reqStr = "GET " + hlp.toEncoded() + " HTTP/1.0\r\n";
185 }
186 reqStr += "User-Agent: NTRIP BNC/" AGENTVERSION "\r\n"
187 "Host: " + hlp.host().toAscii() + "\r\n"
188 + userAndPwd + "\r\n";
189
190// NMEA string to handle VRS stream
191// --------------------------------
192
193 double lat, lon;
194
195 lat = strtod(latitude,NULL);
196 lon = strtod(longitude,NULL);
197
198 if ((nmea == "yes") && (hlp.path().length() > 2) && (hlp.path().indexOf(".skl") < 0)) {
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";}
205 QTime ttime(QDateTime::currentDateTime().toUTC().time());
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
235 msg += reqStr;
236
237 socket->write(reqStr, reqStr.length());
238
239 if (!socket->waitForBytesWritten(timeOut)) {
240 msg += "Write timeout\n";
241 delete socket;
242 return 0;
243 }
244
245 return socket;
246}
247
248// Init Run
249////////////////////////////////////////////////////////////////////////////
250t_irc bncGetThread::initRun() {
251
252 // Initialize Socket
253 // -----------------
254 QString msg;
255 _socket = this->request(_mountPoint, _latitude, _longitude,
256 _nmea, _timeOut, msg);
257 if (!_socket) {
258 return failure;
259 }
260
261 // Read Caster Response
262 // --------------------
263 _socket->waitForReadyRead(_timeOut);
264 if (_socket->canReadLine()) {
265 QString line = _socket->readLine();
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);
284 if (_socket->bytesAvailable() <= 0) {
285 break;
286 }
287 }
288 }
289 }
290
291 if (line.indexOf("Unauthorized") != -1) {
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(";");
300 if (tags.at(1) == _staID_orig) {
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 }
319 emit(newMessage((_staID + ": Caster Response: " + line +
320 " Adjust User-ID and Password Register, see"
321 "\n " + reg).toAscii()));
322 return fatal;
323 }
324 if (line.indexOf("ICY 200 OK") != 0) {
325 emit(newMessage((_staID + ": Wrong Caster Response:\n" + line).toAscii()));
326 return failure;
327 }
328 }
329 else {
330 emit(newMessage(_staID + ": Response Timeout"));
331 return failure;
332 }
333
334 // Instantiate the filter
335 // ----------------------
336 if (!_decoder) {
337 if (_format.indexOf("RTCM_2") != -1) {
338 emit(newMessage("Get Data: " + _staID + " in RTCM 2.x format"));
339 _decoder = new RTCM2Decoder();
340 }
341 else if (_format.indexOf("RTCM_3") != -1) {
342 emit(newMessage("Get Data: " + _staID + " in RTCM 3.x format"));
343 _decoder = new RTCM3Decoder();
344 }
345 else if (_format.indexOf("RTIGS") != -1) {
346 emit(newMessage("Get Data: " + _staID + " in RTIGS format"));
347 _decoder = new RTIGSDecoder();
348 }
349 else if (_format.indexOf("SP3") != -1 || _format.indexOf("ZERO") != -1) {
350 emit(newMessage("Get Data: " + _staID + " in original format"));
351 _decoder = new bncZeroDecoder(_staID);
352 }
353 else {
354 emit(newMessage(_staID + ": Unknown data format " + _format));
355 return fatal;
356 }
357 }
358 return success;
359}
360
361// Run
362////////////////////////////////////////////////////////////////////////////
363void bncGetThread::run() {
364
365 t_irc irc = initRun();
366
367 if (irc == fatal) {
368 QThread::exit(1);
369 return;
370 }
371 else if (irc != success) {
372 emit(newMessage(_staID + ": initRun failed, reconnecting"));
373 tryReconnect();
374 }
375
376 // Read Incoming Data
377 // ------------------
378 while (true) {
379 try {
380 if (_socket->state() != QAbstractSocket::ConnectedState) {
381 emit(newMessage(_staID + ": Socket not connected, reconnecting"));
382 tryReconnect();
383 }
384
385 QListIterator<p_obs> it(_decoder->_obsList);
386 while (it.hasNext()) {
387 delete it.next();
388 }
389 _decoder->_obsList.clear();
390
391 _socket->waitForReadyRead(_timeOut);
392 qint64 nBytes = _socket->bytesAvailable();
393 if (nBytes > 0) {
394 emit newBytes(_staID, nBytes);
395
396 char* data = new char[nBytes];
397 _socket->read(data, nBytes);
398
399 if ( !_decodeFailure.isValid() ||
400 _decodeFailure.secsTo(QDateTime::currentDateTime()) > 10 ) {
401 if ( _decoder->Decode(data, nBytes) == success ) {
402 _decodeFailure.setDate(QDate());
403 _decodeFailure.setTime(QTime());
404 }
405 else {
406 _decodeFailure = QDateTime::currentDateTime();
407 }
408 }
409
410 delete [] data;
411
412 QListIterator<p_obs> it(_decoder->_obsList);
413 while (it.hasNext()) {
414 p_obs obs = it.next();
415
416 // Check observation epoch
417 // -----------------------
418 int week;
419 double sec;
420 currentGPSWeeks(week, sec);
421
422 const double secPerWeek = 7.0 * 24.0 * 3600.0;
423 const double maxDt = 600.0;
424
425 if (week < obs->_o.GPSWeek) {
426 week += 1;
427 sec -= secPerWeek;
428 }
429 if (week > obs->_o.GPSWeek) {
430 week -= 1;
431 sec += secPerWeek;
432 }
433 double dt = fabs(sec - obs->_o.GPSWeeks);
434 if (week != obs->_o.GPSWeek || dt > maxDt) {
435 emit( newMessage("Wrong observation epoch") );
436 delete obs;
437 continue;
438 }
439
440 // RINEX Output
441 // ------------
442 if (_rnx) {
443 long iSec = long(floor(obs->_o.GPSWeeks+0.5));
444 long newTime = obs->_o.GPSWeek * 7*24*3600 + iSec;
445 if (_samplingRate == 0 || iSec % _samplingRate == 0) {
446 _rnx->deepCopy(obs);
447 }
448 _rnx->dumpEpoch(newTime);
449 }
450
451 bool firstObs = (obs == _decoder->_obsList.first());
452 obs->_status = t_obs::posted;
453 emit newObs(_staID, firstObs, obs);
454 }
455 _decoder->_obsList.clear();
456 }
457 else {
458 emit(newMessage(_staID + ": Data Timeout, reconnecting"));
459 tryReconnect();
460 }
461 }
462 catch (const char* msg) {
463 emit(newMessage(_staID + msg));
464 tryReconnect();
465 }
466 }
467}
468
469// Exit
470////////////////////////////////////////////////////////////////////////////
471void bncGetThread::exit(int exitCode) {
472 if (exitCode!= 0) {
473 emit error(_staID);
474 }
475 QThread::exit(exitCode);
476 terminate();
477}
478
479// Try Re-Connect
480////////////////////////////////////////////////////////////////////////////
481void bncGetThread::tryReconnect() {
482 if (_rnx) {
483 _rnx->setReconnectFlag(true);
484 }
485 while (1) {
486 delete _socket; _socket = 0;
487 sleep(_nextSleep);
488 if ( initRun() == success ) {
489 break;
490 }
491 else {
492 _nextSleep *= 2;
493 if (_nextSleep > 256) {
494 _nextSleep = 256;
495 }
496 _nextSleep += rand() % 6;
497 }
498 }
499 _nextSleep = 1;
500}
Note: See TracBrowser for help on using the repository browser.