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

Last change on this file since 426 was 425, checked in by mervart, 18 years ago

* empty log message *

File size: 12.9 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 QByteArray userAndPwd = mountPoint.userName().toAscii() + ":" +
153 mountPoint.password().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.2b\r\n"
167 "Authorization: Basic " +
168 userAndPwd.toBase64() + "\r\n\r\n";
169 } else {
170 reqStr = "GET " + hlp.toEncoded() +
171 " HTTP/1.0\r\n"
172 "User-Agent: NTRIP BNC 1.2b\r\n"
173 "Authorization: Basic " +
174 userAndPwd.toBase64() + "\r\n\r\n";
175 }
176
177//////////////////////////////////////////////////////////////////
178// Additional NMEA String in request to handle VRS data streams //
179// will be ignored from standard casters //
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
225 msg += reqStr;
226
227 socket->write(reqStr, reqStr.length());
228
229 if (!socket->waitForBytesWritten(timeOut)) {
230 msg += "Write timeout\n";
231 delete socket;
232 return 0;
233 }
234
235 return socket;
236}
237
238// Init Run
239////////////////////////////////////////////////////////////////////////////
240t_irc bncGetThread::initRun() {
241
242 // Send the Request
243 // ----------------
244 QString msg;
245
246 _socket = bncGetThread::request(_mountPoint, _latitude, _longitude, _nmea, _timeOut, msg);
247
248 //// emit(newMessage(msg.toAscii()));
249
250 if (!_socket) {
251 return failure;
252 }
253
254 // Read Caster Response
255 // --------------------
256 _socket->waitForReadyRead(_timeOut);
257 if (_socket->canReadLine()) {
258 QString line = _socket->readLine();
259 if (line.indexOf("Unauthorized") != -1) {
260 QStringList table;
261 bncTableDlg::getFullTable(_mountPoint.host(), _mountPoint.port(), table);
262 QString net;
263 QStringListIterator it(table);
264 while (it.hasNext()) {
265 QString line = it.next();
266 if (line.indexOf("STR") == 0) {
267 QStringList tags = line.split(";");
268 if (tags.at(1) == _staID_orig) {
269 net = tags.at(7);
270 break;
271 }
272 }
273 }
274
275 QString reg;
276 it.toFront();
277 while (it.hasNext()) {
278 QString line = it.next();
279 if (line.indexOf("NET") == 0) {
280 QStringList tags = line.split(";");
281 if (tags.at(1) == net) {
282 reg = tags.at(7);
283 break;
284 }
285 }
286 }
287 emit(newMessage((_staID + ": Caster Response: " + line +
288 " Adjust User-ID and Password Register, see"
289 "\n " + reg).toAscii()));
290 return fatal;
291 }
292 if (line.indexOf("ICY 200 OK") != 0) {
293 emit(newMessage((_staID + ": Wrong Caster Response:\n" + line).toAscii()));
294 return failure;
295 }
296 }
297 else {
298 emit(newMessage(_staID + ": Response Timeout"));
299 return failure;
300 }
301
302 // Instantiate the filter
303 // ----------------------
304 if (!_decoder) {
305 if (_format.indexOf("RTCM_2") != -1) {
306 emit(newMessage("Get Data: " + _staID + " in RTCM 2.x format"));
307 _decoder = new RTCM2Decoder();
308 }
309 else if (_format.indexOf("RTCM_3") != -1) {
310 emit(newMessage("Get Data: " + _staID + " in RTCM 3.0 format"));
311 _decoder = new RTCM3Decoder();
312 }
313 else if (_format.indexOf("RTIGS") != -1) {
314 emit(newMessage("Get Data: " + _staID + " in RTIGS format"));
315 _decoder = new RTIGSDecoder();
316 }
317 else if (_format.indexOf("SP3") != -1 || _format.indexOf("ASCII") != -1) {
318 emit(newMessage("Get Data: " + _staID + " in ASCII format"));
319 _decoder = new bncZeroDecoder(_staID);
320 }
321 else {
322 emit(newMessage(_staID + ": Unknown data format " + _format));
323 return fatal;
324 }
325 }
326 return success;
327}
328
329// Run
330////////////////////////////////////////////////////////////////////////////
331void bncGetThread::run() {
332
333 t_irc irc = initRun();
334
335 if (irc == fatal) {
336 QThread::exit(1);
337 return;
338 }
339 else if (irc != success) {
340 emit(newMessage(_staID + ": initRun failed, reconnecting"));
341 tryReconnect();
342 }
343
344 // Read Incoming Data
345 // ------------------
346 while (true) {
347 try {
348 if (_socket->state() != QAbstractSocket::ConnectedState) {
349 emit(newMessage(_staID + ": Socket not connected, reconnecting"));
350 tryReconnect();
351 }
352
353
354 _socket->waitForReadyRead(_timeOut);
355 qint64 nBytes = _socket->bytesAvailable();
356 if (nBytes > 0) {
357 char* data = new char[nBytes];
358 _socket->read(data, nBytes);
359
360 _decoder->Decode(data, nBytes);
361 delete [] data;
362
363 for (list<Observation*>::iterator it = _decoder->_obsList.begin();
364 it != _decoder->_obsList.end(); it++) {
365
366 // Check observation epoch
367 // -----------------------
368 int week;
369 double sec;
370 currentGPSWeeks(week, sec);
371
372 const double secPerWeek = 7.0 * 24.0 * 3600.0;
373 const double maxDt = 600.0;
374
375 if (week < (*it)->GPSWeek) {
376 week += 1;
377 sec -= secPerWeek;
378 }
379 if (week > (*it)->GPSWeek) {
380 week -= 1;
381 sec += secPerWeek;
382 }
383 double dt = fabs(sec - (*it)->GPSWeeks);
384 if (week != (*it)->GPSWeek || dt > maxDt) {
385 emit( newMessage("Wrong observation epoch") );
386 delete (*it);
387 continue;
388 }
389
390 // RINEX Output
391 // ------------
392 if (_rnx) {
393 long iSec = long(floor((*it)->GPSWeeks+0.5));
394 long newTime = (*it)->GPSWeek * 7*24*3600 + iSec;
395 if (_samplingRate == 0 || iSec % _samplingRate == 0) {
396 _rnx->deepCopy(*it);
397 }
398 _rnx->dumpEpoch(newTime);
399 }
400
401 emit newObs(_staID, *it);
402 bool firstObs = (it == _decoder->_obsList.begin());
403 _global_caster->newObs(_staID, firstObs, *it);
404 }
405 _decoder->_obsList.clear();
406 }
407 else {
408 emit(newMessage(_staID + ": Data Timeout, reconnecting"));
409 tryReconnect();
410 }
411 }
412 catch (const char* msg) {
413 emit(newMessage(_staID + msg));
414 tryReconnect();
415 }
416 }
417}
418
419// Exit
420////////////////////////////////////////////////////////////////////////////
421void bncGetThread::exit(int exitCode) {
422 if (exitCode!= 0) {
423 emit error(_staID);
424 }
425 QThread::exit(exitCode);
426 terminate();
427}
428
429// Try Re-Connect
430////////////////////////////////////////////////////////////////////////////
431void bncGetThread::tryReconnect() {
432 if (_rnx) {
433 _rnx->setReconnectFlag(true);
434 }
435 while (1) {
436 delete _socket; _socket = 0;
437 sleep(_nextSleep);
438 if ( initRun() == success ) {
439 break;
440 }
441 else {
442 _nextSleep *= 2;
443 if (_nextSleep > 128) {
444 _nextSleep = 128;
445 }
446 _nextSleep += rand() % 6;
447 }
448 }
449 _nextSleep = 1;
450}
Note: See TracBrowser for help on using the repository browser.