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

Last change on this file since 459 was 459, checked in by mervart, 15 years ago

* empty log message *

File size: 13.1 KB
Line 
1// Part of BNC, a utility for retrieving decoding and
2// converting GNSS data streams from NTRIP broadcasters,
3// written by Leos Mervart.
4//
5// Copyright (C) 2006
6// German Federal Agency for Cartography and Geodesy (BKG)
7// http://www.bkg.bund.de
8// Czech Technical University Prague, Department of Advanced Geodesy
9// http://www.fsv.cvut.cz
10//
11// Email: euref-ip@bkg.bund.de
12//
13// This program is free software; you can redistribute it and/or
14// modify it under the terms of the GNU General Public License
15// as published by the Free Software Foundation, version 2.
16//
17// This program is distributed in the hope that it will be useful,
18// but WITHOUT ANY WARRANTY; without even the implied warranty of
19// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20// GNU General Public License for more details.
21//
22// You should have received a copy of the GNU General Public License
23// along with this program; if not, write to the Free Software
24// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
25
26/* -------------------------------------------------------------------------
27 * BKG NTRIP Client
28 * -------------------------------------------------------------------------
29 *
30 * Class: bncGetThread
31 *
32 * Purpose: Thread that retrieves data from NTRIP caster
33 *
34 * Author: L. Mervart
35 *
36 * Created: 24-Dec-2005
37 *
38 * Changes:
39 *
40 * -----------------------------------------------------------------------*/
41
42#include <stdlib.h>
43
44#include <QFile>
45#include <QTextStream>
46#include <QtNetwork>
47#include <QTime>
48
49#include "bncgetthread.h"
50#include "bnctabledlg.h"
51#include "bncapp.h"
52#include "bncutils.h"
53#include "bncrinex.h"
54#include "bnczerodecoder.h"
55
56#include "RTCM/RTCM2Decoder.h"
57#include "RTCM3/RTCM3Decoder.h"
58#include "RTIGS/RTIGSDecoder.h"
59
60using namespace std;
61
62// Constructor
63////////////////////////////////////////////////////////////////////////////
64bncGetThread::bncGetThread(const QUrl& mountPoint,
65 const QByteArray& format,
66 const QByteArray& latitude,
67 const QByteArray& longitude,
68 const QByteArray& nmea, int iMount) {
69 _decoder = 0;
70 _mountPoint = mountPoint;
71 _staID = mountPoint.path().mid(1).toAscii();
72 _staID_orig = _staID;
73 _format = format;
74 _latitude = latitude;
75 _longitude = longitude;
76 _nmea = nmea;
77 _socket = 0;
78 _timeOut = 20*1000; // 20 seconds
79 _nextSleep = 1; // 1 second
80 _iMount = iMount; // index in mountpoints array
81
82 // Check name conflict
83 // -------------------
84 QSettings settings;
85 QListIterator<QString> it(settings.value("mountPoints").toStringList());
86 int num = 0;
87 int ind = -1;
88 while (it.hasNext()) {
89 ++ind;
90 QStringList hlp = it.next().split(" ");
91 if (hlp.size() <= 1) continue;
92 QUrl url(hlp[0]);
93 if (_mountPoint.path() == url.path()) {
94 if (_iMount > ind) {
95 ++num;
96 }
97 }
98 }
99
100 if (num > 0) {
101 _staID = _staID.left(_staID.length()-1) + QString("%1").arg(num).toAscii();
102 }
103
104 // RINEX writer
105 // ------------
106 _samplingRate = settings.value("rnxSampl").toInt();
107 if ( settings.value("rnxPath").toString().isEmpty() ) {
108 _rnx = 0;
109 }
110 else {
111 _rnx = new bncRinex(_staID, mountPoint, format, latitude, longitude, nmea);
112 }
113
114 msleep(100); //sleep 0.1 sec
115}
116
117// Destructor
118////////////////////////////////////////////////////////////////////////////
119bncGetThread::~bncGetThread() {
120 delete _socket;
121 delete _decoder;
122}
123
124// Connect to Caster, send the Request (static)
125////////////////////////////////////////////////////////////////////////////
126QTcpSocket* bncGetThread::request(const QUrl& mountPoint,
127 QByteArray& latitude, QByteArray& longitude,
128 QByteArray& nmea, int timeOut,
129 QString& msg) {
130
131 // Connect the Socket
132 // ------------------
133 QSettings settings;
134 QString proxyHost = settings.value("proxyHost").toString();
135 int proxyPort = settings.value("proxyPort").toInt();
136
137 QTcpSocket* socket = new QTcpSocket();
138 if ( proxyHost.isEmpty() ) {
139 socket->connectToHost(mountPoint.host(), mountPoint.port());
140 }
141 else {
142 socket->connectToHost(proxyHost, proxyPort);
143 }
144 if (!socket->waitForConnected(timeOut)) {
145 msg += "Connect timeout\n";
146 delete socket;
147 return 0;
148 }
149
150 // Send Request
151 // ------------
152 QString uName = QUrl::fromPercentEncoding(mountPoint.userName().toAscii());
153 QString passW = QUrl::fromPercentEncoding(mountPoint.password().toAscii());
154 QByteArray userAndPwd = uName.toAscii() + ":" + passW.toAscii();
155
156 QUrl hlp;
157 hlp.setScheme("http");
158 hlp.setHost(mountPoint.host());
159 hlp.setPort(mountPoint.port());
160 hlp.setPath(mountPoint.path());
161
162 QByteArray reqStr;
163 if ( proxyHost.isEmpty() ) {
164 if (hlp.path().indexOf("/") != 0) hlp.setPath("/");
165 reqStr = "GET " + hlp.path().toAscii() +
166 " HTTP/1.0\r\n"
167 "User-Agent: NTRIP BNC 1.2b\r\n"
168 "Authorization: Basic " +
169 userAndPwd.toBase64() + "\r\n";
170 } else {
171 reqStr = "GET " + hlp.toEncoded() +
172 " HTTP/1.0\r\n"
173 "User-Agent: NTRIP BNC 1.2b\r\n"
174 "Authorization: Basic " +
175 userAndPwd.toBase64() + "\r\n";
176 }
177 if (hlp.path().indexOf(".skl") > 0) { reqStr += "Host: " + hlp.host().toAscii() + "\r\n"; }
178 reqStr += "\r\n";
179
180//////////////////////////////////////////////////////////////////
181// Additional NMEA String in request to handle VRS data streams //
182// will be ignored from standard casters //
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(QTime::currentTime());
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
228 msg += reqStr;
229
230 socket->write(reqStr, reqStr.length());
231
232 if (!socket->waitForBytesWritten(timeOut)) {
233 msg += "Write timeout\n";
234 delete socket;
235 return 0;
236 }
237
238 return socket;
239}
240
241// Init Run
242////////////////////////////////////////////////////////////////////////////
243t_irc bncGetThread::initRun() {
244
245 // Send the Request
246 // ----------------
247 QString msg;
248
249 _socket = bncGetThread::request(_mountPoint, _latitude, _longitude, _nmea, _timeOut, msg);
250
251 //// emit(newMessage(msg.toAscii()));
252
253 if (!_socket) {
254 return failure;
255 }
256
257 // Read Caster Response
258 // --------------------
259 _socket->waitForReadyRead(_timeOut);
260 if (_socket->canReadLine()) {
261 QString line = _socket->readLine();
262 if (line.indexOf("Unauthorized") != -1) {
263 QStringList table;
264 bncTableDlg::getFullTable(_mountPoint.host(), _mountPoint.port(), table);
265 QString net;
266 QStringListIterator it(table);
267 while (it.hasNext()) {
268 QString line = it.next();
269 if (line.indexOf("STR") == 0) {
270 QStringList tags = line.split(";");
271 if (tags.at(1) == _staID_orig) {
272 net = tags.at(7);
273 break;
274 }
275 }
276 }
277
278 QString reg;
279 it.toFront();
280 while (it.hasNext()) {
281 QString line = it.next();
282 if (line.indexOf("NET") == 0) {
283 QStringList tags = line.split(";");
284 if (tags.at(1) == net) {
285 reg = tags.at(7);
286 break;
287 }
288 }
289 }
290 emit(newMessage((_staID + ": Caster Response: " + line +
291 " Adjust User-ID and Password Register, see"
292 "\n " + reg).toAscii()));
293 return fatal;
294 }
295 if (line.indexOf("ICY 200 OK") != 0) {
296 emit(newMessage((_staID + ": Wrong Caster Response:\n" + line).toAscii()));
297 return failure;
298 }
299 }
300 else {
301 emit(newMessage(_staID + ": Response Timeout"));
302 return failure;
303 }
304
305 // Instantiate the filter
306 // ----------------------
307 if (!_decoder) {
308 if (_format.indexOf("RTCM_2") != -1) {
309 emit(newMessage("Get Data: " + _staID + " in RTCM 2.x format"));
310 _decoder = new RTCM2Decoder();
311 }
312 else if (_format.indexOf("RTCM_3") != -1) {
313 emit(newMessage("Get Data: " + _staID + " in RTCM 3.0 format"));
314 _decoder = new RTCM3Decoder();
315 }
316 else if (_format.indexOf("RTIGS") != -1) {
317 emit(newMessage("Get Data: " + _staID + " in RTIGS format"));
318 _decoder = new RTIGSDecoder();
319 }
320 else if (_format.indexOf("SP3") != -1 || _format.indexOf("ZERO") != -1) {
321 emit(newMessage("Get Data: " + _staID + " in original format"));
322 _decoder = new bncZeroDecoder(_staID);
323 }
324 else {
325 emit(newMessage(_staID + ": Unknown data format " + _format));
326 return fatal;
327 }
328 }
329 return success;
330}
331
332// Run
333////////////////////////////////////////////////////////////////////////////
334void bncGetThread::run() {
335
336 t_irc irc = initRun();
337
338 if (irc == fatal) {
339 QThread::exit(1);
340 return;
341 }
342 else if (irc != success) {
343 emit(newMessage(_staID + ": initRun failed, reconnecting"));
344 tryReconnect();
345 }
346
347 // Read Incoming Data
348 // ------------------
349 while (true) {
350 try {
351 if (_socket->state() != QAbstractSocket::ConnectedState) {
352 emit(newMessage(_staID + ": Socket not connected, reconnecting"));
353 tryReconnect();
354 }
355
356
357 _socket->waitForReadyRead(_timeOut);
358 qint64 nBytes = _socket->bytesAvailable();
359 if (nBytes > 0) {
360 char* data = new char[nBytes];
361 _socket->read(data, nBytes);
362
363 _decoder->Decode(data, nBytes);
364 delete [] data;
365
366 for (list<Observation*>::iterator it = _decoder->_obsList.begin();
367 it != _decoder->_obsList.end(); it++) {
368
369 // Check observation epoch
370 // -----------------------
371 int week;
372 double sec;
373 currentGPSWeeks(week, sec);
374
375 const double secPerWeek = 7.0 * 24.0 * 3600.0;
376 const double maxDt = 600.0;
377
378 if (week < (*it)->GPSWeek) {
379 week += 1;
380 sec -= secPerWeek;
381 }
382 if (week > (*it)->GPSWeek) {
383 week -= 1;
384 sec += secPerWeek;
385 }
386 double dt = fabs(sec - (*it)->GPSWeeks);
387 if (week != (*it)->GPSWeek || dt > maxDt) {
388 emit( newMessage("Wrong observation epoch") );
389 delete (*it);
390 continue;
391 }
392
393 // RINEX Output
394 // ------------
395 if (_rnx) {
396 long iSec = long(floor((*it)->GPSWeeks+0.5));
397 long newTime = (*it)->GPSWeek * 7*24*3600 + iSec;
398 if (_samplingRate == 0 || iSec % _samplingRate == 0) {
399 _rnx->deepCopy(*it);
400 }
401 _rnx->dumpEpoch(newTime);
402 }
403
404 emit newBytes(_staID, sizeof(**it));
405 bool firstObs = (it == _decoder->_obsList.begin());
406 _global_caster->newObs(_staID, firstObs, *it);
407 }
408 _decoder->_obsList.clear();
409 }
410 else {
411 emit(newMessage(_staID + ": Data Timeout, reconnecting"));
412 tryReconnect();
413 }
414 }
415 catch (const char* msg) {
416 emit(newMessage(_staID + msg));
417 tryReconnect();
418 }
419 }
420}
421
422// Exit
423////////////////////////////////////////////////////////////////////////////
424void bncGetThread::exit(int exitCode) {
425 if (exitCode!= 0) {
426 emit error(_staID);
427 }
428 QThread::exit(exitCode);
429 terminate();
430}
431
432// Try Re-Connect
433////////////////////////////////////////////////////////////////////////////
434void bncGetThread::tryReconnect() {
435 if (_rnx) {
436 _rnx->setReconnectFlag(true);
437 }
438 while (1) {
439 delete _socket; _socket = 0;
440 sleep(_nextSleep);
441 if ( initRun() == success ) {
442 break;
443 }
444 else {
445 _nextSleep *= 2;
446 if (_nextSleep > 256) {
447 _nextSleep = 256;
448 }
449 _nextSleep += rand() % 6;
450 }
451 }
452 _nextSleep = 1;
453}
Note: See TracBrowser for help on using the repository browser.