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