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

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

* empty log message *

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