]> git.mxchange.org Git - flightgear.git/blob - terrasync.cxx
f8b8b25511d8f55d4b80f3ced0e426208951fb14
[flightgear.git] / terrasync.cxx
1 // terrasync.cxx -- "JIT" scenery fetcher
2 //
3 // Written by Curtis Olson, started November 2002.
4 //
5 // Copyright (C) 2002  Curtis L. Olson  - http://www.flightgear.org/~curt
6 // Copyright (C) 2008  Alexander R. Perry <alex.perry@ieee.org>
7 // Copyright (C) 2011  Thorsten Brehm <brehmt@gmail.com>
8 //
9 // This program is free software; you can redistribute it and/or
10 // modify it under the terms of the GNU General Public License as
11 // published by the Free Software Foundation; either version 2 of the
12 // License, or (at your option) any later version.
13 //
14 // This program is distributed in the hope that it will be useful, but
15 // WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17 // General Public License for more details.
18 //
19 // You should have received a copy of the GNU General Public License
20 // along with this program; if not, write to the Free Software
21 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
22 //
23 // $Id$
24
25 #ifdef HAVE_CONFIG_H
26 #include <config.h>
27 #endif
28
29 #ifdef HAVE_WINDOWS_H
30 #include <windows.h>
31 #endif
32
33 #ifdef __MINGW32__
34 #include <time.h>
35 #include <unistd.h>
36 #elif defined(_MSC_VER)
37 #   include <io.h>
38 #endif
39
40 #include <stdlib.h>             // atoi() atof() abs() system()
41 #include <signal.h>             // signal()
42
43 #include <simgear/compiler.h>
44
45 #include <iostream>
46 #include <fstream>
47 #include <string>
48
49 #include <simgear/io/raw_socket.hxx>
50 #include <simgear/scene/tsync/terrasync.hxx>
51
52 #if defined(_MSC_VER) || defined(__MINGW32__)
53     typedef void (__cdecl * sighandler_t)(int);
54 #elif defined( __APPLE__ ) || defined (__FreeBSD__)
55     typedef sig_t sighandler_t;
56 #endif
57
58 int termination_triggering_signals[] = {
59 #if defined(_MSC_VER) || defined(__MINGW32__)
60     SIGINT, SIGILL, SIGFPE, SIGSEGV, SIGTERM, SIGBREAK, SIGABRT,
61 #else
62     SIGHUP, SIGINT, SIGQUIT, SIGKILL, SIGTERM,
63 #endif
64     0};  // zero terminated
65
66 using namespace std;
67
68 const char* svn_base =
69     "http://terrascenery.googlecode.com/svn/trunk/data/Scenery";
70 const char* rsync_base = "scenery.flightgear.org::Scenery";
71
72 bool terminating = false;
73 sighandler_t prior_signal_handlers[32];
74
75 simgear::Socket theSocket;
76 simgear::SGTerraSync* pTerraSync = NULL;
77
78 /** display usage information */
79 static void
80 usage( const string& prog ) {
81     cout << "Usage:  terrasync [options]\n"
82             "Options:\n"
83             " -d <dest>       destination directory [required]\n"
84             " -R              transport using pipe to rsync\n"
85             " -S              transport using built-in svn\n"
86             " -e              transport using external svn client\n"
87             " -p <port>       listen on UDP port [default: 5501]\n"
88             " -s <source>     source base [default: '']\n"
89 #ifndef _MSC_VER
90             " -pid <pidfile>  write PID to file\n"
91 #endif
92             " -v              be more verbose\n";
93
94 #ifndef _MSC_VER
95     cout << "\n"
96             "Example:\n"
97             "  pid=$(cat $pidfile 2>/dev/null)\n"
98             "  if test -n \"$pid\" && kill -0 $pid ; then\n"
99             "      echo \"terrasync already running: $pid\"\n"
100             "  else\n"
101             "      nice /games/sport/fgs/utils/TerraSync/terrasync         \\\n"
102             "        -v -pid $pidfile -S -p 5500 -d /games/orig/terrasync &\n"
103             "  fi\n";
104 #endif
105 }
106
107 /** Signal handler for termination requests (Ctrl-C) */
108 void
109 terminate_request_handler(int param)
110 {
111     char msg[] = "\nReceived signal XX, intend to exit soon.\n"
112          "Repeat the signal to force immediate termination.\n";
113     msg[17] = '0' + param / 10;
114     msg[18] = '0' + param % 10;
115     if (write(1, msg, sizeof(msg) - 1) == -1)
116     {
117         // need to act write's return value to avoid GCC compiler warning
118         // "'write' declared with attribute warn_unused_result"
119         terminating = true; // dummy operation
120     }
121     terminating = true;
122     signal(param, prior_signal_handlers[param]);
123     theSocket.close();
124     if (pTerraSync)
125         pTerraSync->unbind();
126 }
127
128 /** Parse command-line options. */
129 void
130 parseOptions(int argc, char** argv, SGPropertyNode_ptr config,
131              bool& testing, int& verbose, int& port, const char* &pidfn)
132 {
133     // parse arguments
134     for (int i=1; i < argc; ++i )
135     {
136         string arg = argv[i];
137         if ( arg == "-p" ) {
138             ++i;
139             port = atoi( argv[i] );
140         } else if ( arg.find("-pid") == 0 ) {
141             ++i;
142             pidfn = argv[i];
143             cout << "pidfn: " << pidfn << endl;
144         } else if ( arg == "-s" ) {
145             ++i;
146             config->setStringValue("svn-server", argv[i]);
147         } else if ( arg == "-d" ) {
148             ++i;
149             config->setStringValue("scenery-dir", argv[i]);
150         } else if ( arg == "-R" ) {
151             config->setBoolValue("use-svn", false);
152         } else if ( arg == "-S" ) {
153             config->setBoolValue("use-built-in-svn", true);
154         } else if ( arg == "-e" ) {
155             config->setBoolValue("use-built-in-svn", false);
156         } else if ( arg == "-v" ) {
157             verbose++;
158         } else if ( arg == "-T" ) {
159             testing = true;
160         } else if ( arg == "-h" ) {
161             usage( argv[0] );
162             exit(0);
163         } else {
164             cerr << "Unrecognized command-line option '" << arg << "'" << endl;
165             usage( argv[0] );
166             exit(-1);
167         }
168     }
169 }
170
171 /** parse a single NMEA-0183 position message */
172 static void
173 parse_message( int verbose, const string &msg, int *lat, int *lon )
174 {
175     double dlat, dlon;
176     string text = msg;
177
178     if (verbose>=3)
179         cout << "message: '" << text << "'" << endl;
180
181     // find GGA string and advance to start of lat (see NMEA-0183 for protocol specs)
182     string::size_type pos = text.find( "$GPGGA" );
183     if ( pos == string::npos )
184     {
185         *lat = simgear::NOWHERE;
186         *lon = simgear::NOWHERE;
187         return;
188     }
189     string tmp = text.substr( pos + 7 );
190     pos = tmp.find( "," );
191     tmp = tmp.substr( pos + 1 );
192     // cout << "-> " << tmp << endl;
193
194     // find lat then advance to start of hemisphere
195     pos = tmp.find( "," );
196     string lats = tmp.substr( 0, pos );
197     dlat = atof( lats.c_str() ) / 100.0;
198     tmp = tmp.substr( pos + 1 );
199
200     // find N/S hemisphere and advance to start of lon
201     if ( tmp.substr( 0, 1 ) == "S" ) {
202         dlat = -dlat;
203     }
204     pos = tmp.find( "," );
205     tmp = tmp.substr( pos + 1 );
206
207     // find lon
208     pos = tmp.find( "," );
209     string lons = tmp.substr( 0, pos );
210     dlon = atof( lons.c_str() ) / 100.0;
211     tmp = tmp.substr( pos + 1 );
212
213     // find E/W hemisphere and advance to start of lon
214     if ( tmp.substr( 0, 1 ) == "W" ) {
215         dlon = -dlon;
216     }
217
218     if ( dlat < 0 ) {
219         *lat = (int)dlat - 1;
220     } else {
221         *lat = (int)dlat;
222     }
223
224     if ( dlon < 0 ) {
225         *lon = (int)dlon - 1;
226     } else {
227         *lon = (int)dlon;
228     }
229
230     if ((dlon == 0) && (dlat == 0)) {
231         *lon = simgear::NOWHERE;
232         *lat = simgear::NOWHERE;
233     }
234 }
235
236 /** Monitor UDP socket and process NMEA position updates. */
237 int
238 processRequests(SGPropertyNode_ptr config, bool testing, int verbose, int port)
239 {
240     const char* host = "localhost";
241     char msg[256];
242     int len;
243     int lat, lon;
244     bool connected = false;
245
246     // Must call this before any other net stuff
247     simgear::Socket::initSockets();
248
249     // open UDP socket
250     if ( !theSocket.open( false ) )
251     {
252         cerr << "error opening socket" << endl;
253         return -1;
254     }
255
256     if ( theSocket.bind( host, port ) == -1 )
257     {
258         cerr << "error binding to port " << port << endl;
259         return -1;
260     }
261
262     theSocket.setBlocking(true);
263
264     while ( (!terminating)&&
265             (!config->getBoolValue("stalled", false)) )
266     {
267         if (verbose >= 4)
268             cout << "main loop" << endl;
269         // main loop
270         bool recv_msg = false;
271         if ( testing )
272         {
273             // Testing without FGFS communication
274             lat = 37;
275             lon = -123;
276             recv_msg = true;
277         } else
278         {
279             if (verbose && pTerraSync->isIdle())
280             {
281                 cout << "Idle; waiting for FlightGear position data" << endl;
282             }
283             len = theSocket.recv(msg, sizeof(msg)-1, 0);
284             if (len >= 0)
285             {
286                 msg[len] = '\0';
287                 recv_msg = true;
288                 if (verbose>=2)
289                     cout << "recv length: " << len << endl;
290                 parse_message( verbose, msg, &lat, &lon );
291                 if ((!connected)&&
292                     (lat != simgear::NOWHERE)&&
293                     (lon != simgear::NOWHERE))
294                 {
295                     cout << "Valid position data received. Connected successfully." << endl;
296                     connected = true;
297                 }
298             }
299         }
300
301         if ( recv_msg )
302         {
303             pTerraSync->schedulePosition(lat, lon);
304         }
305
306         if ( testing )
307         {
308             if (pTerraSync->isIdle())
309                 terminating = true;
310             else
311                 SGTimeStamp::sleepForMSec(1000);
312         }
313     } // while !terminating
314
315     return 0;
316 }
317
318
319 int main( int argc, char **argv )
320 {
321     int port = 5501;
322     int verbose = 0;
323     int exit_code = 0;
324     bool testing = false;
325     const char* pidfn = "";
326
327     // default configuration
328     sglog().setLogLevels( SG_ALL, SG_ALERT);
329     SGPropertyNode_ptr root = new SGPropertyNode();
330     SGPropertyNode_ptr config = root->getNode("/sim/terrasync", true);
331     config->setStringValue("scenery-dir", "terrasyncdir");
332     config->setStringValue("svn-server", svn_base);
333     config->setStringValue("rsync-server", rsync_base);
334     config->setBoolValue("use-built-in-svn", true);
335     config->setBoolValue("use-svn", true);
336     config->setBoolValue("enabled", true);
337     config->setIntValue("max-errors", -1); // -1 = infinite
338
339     // parse command-line arguments
340     parseOptions(argc, argv, config, testing, verbose, port, pidfn);
341
342     if (verbose)
343         sglog().setLogLevels( SG_ALL, SG_INFO);
344
345 #ifndef _MSC_VER
346     // create PID file
347     if (*pidfn)
348     {
349         ofstream pidstream;
350         pidstream.open(pidfn);
351         if (!pidstream.good())
352         {
353             cerr << "Cannot open pid file '" << pidfn << "': ";
354             perror(0);
355             exit(2);
356         }
357         pidstream << getpid() << endl;
358         pidstream.close();
359     }
360 #endif
361
362     // install signal handlers
363     for (int* sigp=termination_triggering_signals; *sigp; sigp++)
364     {
365         prior_signal_handlers[*sigp] =
366             signal(*sigp, *terminate_request_handler);
367         if (verbose>=2)
368             cout << "Intercepting signal " << *sigp << endl;
369     }
370
371     {
372         pTerraSync = new simgear::SGTerraSync(root);
373         pTerraSync->bind();
374         pTerraSync->init();
375
376         // now monitor and process position updates
377         exit_code = processRequests(config, testing, verbose, port);
378
379         pTerraSync->unbind();
380         delete pTerraSync;
381         pTerraSync = NULL;
382     }
383
384     return exit_code;
385 }