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

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

* empty log message *

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