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

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

* empty log message *

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