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

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

* empty log message *

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