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