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