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

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

* empty log message *

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