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

Last change on this file since 616 was 616, checked in by mervart, 16 years ago

* empty log message *

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