]> git.mxchange.org Git - flightgear.git/blob - src/FDM/ExternalNet/ExternalNet.cxx
Set SO_REUSEADDR on incoming UDP socket so other processes on the host
[flightgear.git] / src / FDM / ExternalNet / ExternalNet.cxx
1 // ExternalNet.hxx -- an net interface to an external flight dynamics model
2 //
3 // Written by Curtis Olson, started November 2001.
4 //
5 // Copyright (C) 2001  Curtis L. Olson  - curt@flightgear.org
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 //
21 // $Id$
22
23 #include <simgear/debug/logstream.hxx>
24 #include <simgear/io/lowlevel.hxx> // endian tests
25
26 #include <Main/fg_props.hxx>
27
28 #include "ExternalNet.hxx"
29
30
31 // FreeBSD works better with this included last ... (?)
32 #if defined(WIN32) && !defined(__CYGWIN__)
33 #  include <windows.h>
34 #else
35 #  include <netinet/in.h>       // htonl() ntohl()
36 #endif
37
38 #if defined( linux )
39 #  include <sys/types.h>
40 #  include <sys/socket.h>
41 #endif
42
43 // The function htond is defined this way due to the way some
44 // processors and OSes treat floating point values.  Some will raise
45 // an exception whenever a "bad" floating point value is loaded into a
46 // floating point register.  Solaris is notorious for this, but then
47 // so is LynxOS on the PowerPC.  By translating the data in place,
48 // there is no need to load a FP register with the "corruped" floating
49 // point value.  By doing the BIG_ENDIAN test, I can optimize the
50 // routine for big-endian processors so it can be as efficient as
51 // possible
52 static void htond (double &x)   
53 {
54     if ( sgIsLittleEndian() ) {
55         int    *Double_Overlay;
56         int     Holding_Buffer;
57     
58         Double_Overlay = (int *) &x;
59         Holding_Buffer = Double_Overlay [0];
60     
61         Double_Overlay [0] = htonl (Double_Overlay [1]);
62         Double_Overlay [1] = htonl (Holding_Buffer);
63     } else {
64         return;
65     }
66 }
67
68
69 static void global2net( FGNetCtrls *net ) {
70     int i;
71
72     // fill in values
73     SGPropertyNode * node = fgGetNode("/controls", true);
74     net->version = FG_NET_CTRLS_VERSION;
75     net->aileron = node->getDoubleValue( "aileron" );
76     net->elevator = node->getDoubleValue( "elevator" );
77     net->elevator_trim = node->getDoubleValue( "elevator-trim" );
78     net->rudder = node->getDoubleValue( "rudder" );
79     net->flaps = node->getDoubleValue( "flaps" );
80     net->flaps_power
81             = node->getDoubleValue( "/systems/electrical/outputs/flaps",
82                                     1.0 ) >= 1.0;
83     net->num_engines = FGNetCtrls::FG_MAX_ENGINES;
84     for ( i = 0; i < FGNetCtrls::FG_MAX_ENGINES; ++i ) {
85         net->throttle[i] = node->getDoubleValue( "throttle", 0.0 );
86         net->mixture[i] = node->getDoubleValue( "mixture", 0.0 );
87         net->fuel_pump_power[i]
88             = node->getDoubleValue( "/systems/electrical/outputs/fuel-pump",
89                                     1.0 ) >= 1.0;
90         net->prop_advance[i] = node->getDoubleValue( "propeller-pitch", 0.0 );
91         net->magnetos[i] = node->getIntValue( "magnetos", 0 );
92         if ( i == 0 ) {
93           // cout << "Magnetos -> " << node->getIntValue( "magnetos", 0 );
94         }
95         net->starter_power[i]
96             = node->getDoubleValue( "/systems/electrical/outputs/starter",
97                                     1.0 ) >= 1.0;
98         if ( i == 0 ) {
99           // cout << " Starter -> " << node->getIntValue( "stater", false )
100           //      << endl;
101         }
102     }
103     net->num_tanks = FGNetCtrls::FG_MAX_TANKS;
104     for ( i = 0; i < FGNetCtrls::FG_MAX_TANKS; ++i ) {
105         if ( node->getChild("fuel-selector", i) != 0 ) {
106             net->fuel_selector[i]
107                 = node->getChild("fuel-selector", i)->getDoubleValue();
108         } else {
109             net->fuel_selector[i] = false;
110         }
111     }
112     net->num_wheels = FGNetCtrls::FG_MAX_WHEELS;
113     for ( i = 0; i < FGNetCtrls::FG_MAX_WHEELS; ++i ) {
114         if ( node->getChild("brakes", i) != 0 ) {
115             if ( node->getChild("parking-brake")->getDoubleValue() > 0.0 ) {
116                 net->brake[i] = 1.0;
117            } else {
118                 net->brake[i]
119                     = node->getChild("brakes", i)->getDoubleValue();
120             }
121         } else {
122             net->brake[i] = 0.0;
123         }
124     }
125
126     node = fgGetNode("/controls/switches", true);
127     net->master_bat = node->getChild("master-bat")->getBoolValue();
128     net->master_alt = node->getChild("master-alt")->getBoolValue();
129     net->master_avionics = node->getChild("master-avionics")->getBoolValue();
130
131     net->wind_speed_kt = fgGetDouble("/environment/wind-speed-kt");
132     net->wind_dir_deg = fgGetDouble("/environment/wind-from-heading-deg");
133
134     // cur_fdm_state->get_ground_elev_ft() is what we want ... this
135     // reports the altitude of the aircraft.
136     // "/environment/ground-elevation-m" reports the ground elevation
137     // of the current view point which could change substantially if
138     // the user is switching views.
139     net->hground = cur_fdm_state->get_ground_elev_ft() * SG_FEET_TO_METER;
140     net->magvar = fgGetDouble("/environment/magnetic-variation-deg");
141     net->speedup = fgGetInt("/sim/speed-up");
142     net->freeze = 0;
143     if ( fgGetBool("/sim/freeze/master") ) {
144         net->freeze |= 0x01;
145     }
146     if ( fgGetBool("/sim/freeze/position") ) {
147         net->freeze |= 0x02;
148     }
149     if ( fgGetBool("/sim/freeze/fuel") ) {
150         net->freeze |= 0x04;
151     }
152
153     // convert to network byte order
154     net->version = htonl(net->version);
155     htond(net->aileron);
156     htond(net->elevator);
157     htond(net->elevator_trim);
158     htond(net->rudder);
159     htond(net->flaps);
160     net->flaps_power = htonl(net->flaps_power);
161     for ( i = 0; i < FGNetCtrls::FG_MAX_ENGINES; ++i ) {
162         htond(net->throttle[i]);
163         htond(net->mixture[i]);
164         net->fuel_pump_power[i] = htonl(net->fuel_pump_power[i]);
165         htond(net->prop_advance[i]);
166         net->magnetos[i] = htonl(net->magnetos[i]);
167         net->starter_power[i] = htonl(net->starter_power[i]);
168     }
169     net->num_engines = htonl(net->num_engines);
170     for ( i = 0; i < FGNetCtrls::FG_MAX_TANKS; ++i ) {
171         net->fuel_selector[i] = htonl(net->fuel_selector[i]);
172     }
173     net->num_tanks = htonl(net->num_tanks);
174     for ( i = 0; i < FGNetCtrls::FG_MAX_WHEELS; ++i ) {
175         htond(net->brake[i]);
176     }
177     net->num_wheels = htonl(net->num_wheels);
178     net->gear_handle = htonl(net->gear_handle);
179     net->master_bat = htonl(net->master_bat);
180     net->master_alt = htonl(net->master_alt);
181     net->master_avionics = htonl(net->master_avionics);
182     htond(net->wind_speed_kt);
183     htond(net->wind_dir_deg);
184     htond(net->hground);
185     htond(net->magvar);
186     net->speedup = htonl(net->speedup);
187     net->freeze = htonl(net->freeze);
188 }
189
190
191 static void net2global( FGNetFDM *net ) {
192     int i;
193
194     // Convert to the net buffer from network format
195     net->version = ntohl(net->version);
196
197     htond(net->longitude);
198     htond(net->latitude);
199     htond(net->altitude);
200     htond(net->phi);
201     htond(net->theta);
202     htond(net->psi);
203
204     htond(net->phidot);
205     htond(net->thetadot);
206     htond(net->psidot);
207     htond(net->vcas);
208     htond(net->climb_rate);
209     htond(net->v_north);
210     htond(net->v_east);
211     htond(net->v_down);
212     htond(net->v_wind_body_north);
213     htond(net->v_wind_body_east);
214     htond(net->v_wind_body_down);
215     htond(net->stall_warning);
216
217     htond(net->A_X_pilot);
218     htond(net->A_Y_pilot);
219     htond(net->A_Z_pilot);
220
221     net->num_engines = htonl(net->num_engines);
222     for ( i = 0; i < net->num_engines; ++i ) {
223         htonl(net->eng_state[i]);
224         htond(net->rpm[i]);
225         htond(net->fuel_flow[i]);
226         htond(net->EGT[i]);
227         htond(net->oil_temp[i]);
228         htond(net->oil_px[i]);
229     }
230
231     net->num_tanks = htonl(net->num_tanks);
232     for ( i = 0; i < net->num_tanks; ++i ) {
233         htond(net->fuel_quantity[i]);
234     }
235
236     net->num_wheels = htonl(net->num_wheels);
237     // I don't need to convert the Wow flags, since they are one byte in size
238     htond(net->flap_deflection);
239
240     net->cur_time = ntohl(net->cur_time);
241     net->warp = ntohl(net->warp);
242     htond(net->visibility);
243
244     if ( net->version == FG_NET_FDM_VERSION ) {
245         // cout << "pos = " << net->longitude << " " << net->latitude << endl;
246         // cout << "sea level rad = " << cur_fdm_state->get_Sea_level_radius()
247         //      << endl;
248         cur_fdm_state->_updateGeodeticPosition( net->latitude,
249                                                 net->longitude,
250                                                 net->altitude
251                                                   * SG_METER_TO_FEET );
252         cur_fdm_state->_set_Euler_Angles( net->phi,
253                                           net->theta,
254                                           net->psi );
255         cur_fdm_state->_set_Euler_Rates( net->phidot,
256                                          net->thetadot,
257                                          net->psidot );
258         cur_fdm_state->_set_V_calibrated_kts( net->vcas );
259         cur_fdm_state->_set_Climb_Rate( net->climb_rate );
260         cur_fdm_state->_set_Velocities_Local( net->v_north,
261                                               net->v_east,
262                                               net->v_down );
263         cur_fdm_state->_set_Velocities_Wind_Body( net->v_wind_body_north,
264                                                   net->v_wind_body_east,
265                                                   net->v_wind_body_down );
266
267         fgSetDouble( "/sim/alarms/stall-warning", net->stall_warning );
268         cur_fdm_state->_set_Accels_Pilot_Body( net->A_X_pilot,
269                                                net->A_Y_pilot,
270                                                net->A_Z_pilot );
271
272         for ( i = 0; i < net->num_engines; ++i ) {
273             SGPropertyNode *node = fgGetNode( "engines/engine", i, true );
274             
275             // node->setBoolValue("running", t->isRunning());
276             // node->setBoolValue("cranking", t->isCranking());
277             
278             // cout << net->eng_state[i] << endl;
279             if ( net->eng_state[i] == 0 ) {
280                 node->setBoolValue( "cranking", false );
281                 node->setBoolValue( "running", false );
282             } else if ( net->eng_state[i] == 1 ) {
283                 node->setBoolValue( "cranking", true );
284                 node->setBoolValue( "running", false );
285             } else if ( net->eng_state[i] == 2 ) {
286                 node->setBoolValue( "cranking", false );
287                 node->setBoolValue( "running", true );
288             }
289
290             node->setDoubleValue( "rpm", net->rpm[i] );
291             node->setDoubleValue( "fuel-flow-gph", net->fuel_flow[i] );
292             node->setDoubleValue( "egt-degf", net->EGT[i] );
293             node->setDoubleValue( "oil-temperature-degf", net->oil_temp[i] );
294             node->setDoubleValue( "oil-pressure-psi", net->oil_px[i] );         
295         }
296
297         for (i = 0; i < net->num_tanks; ++i ) {
298             SGPropertyNode * node
299                 = fgGetNode("/consumables/fuel/tank", i, true);
300             node->setDoubleValue("level-gal_us", net->fuel_quantity[i] );
301         }
302
303         for (i = 0; i < net->num_wheels; ++i ) {
304             SGPropertyNode * node
305                 = fgGetNode("/gear/gear", i, true);
306             node->setDoubleValue("wow", net->wow[i] );
307         }
308
309         fgSetDouble("/surface-positions/flap-pos-norm", net->flap_deflection);
310         SGPropertyNode * node = fgGetNode("/controls", true);
311         fgSetDouble("/surface-positions/elevator-pos-norm", 
312                     node->getDoubleValue( "elevator" ));
313         fgSetDouble("/surface-positions/rudder-pos-norm", 
314                     node->getDoubleValue( "rudder" ));
315         fgSetDouble("/surface-positions/left-aileron-pos-norm", 
316                     node->getDoubleValue( "aileron" ));
317         fgSetDouble("/surface-positions/right-aileron-pos-norm", 
318                     -node->getDoubleValue( "aileron" ));
319
320         /* these are ignored for now  ... */
321         /*
322         if ( net->cur_time ) {
323             fgSetLong("/sim/time/cur-time-override", net->cur_time);
324         }
325
326         globals->set_warp( net->warp );
327         last_warp = net->warp;
328         */
329     } else {
330         SG_LOG( SG_IO, SG_ALERT, "Error: version mismatch in net2global()" );
331         SG_LOG( SG_IO, SG_ALERT,
332                 "\tread " << net->version << " need " << FG_NET_FDM_VERSION );
333         SG_LOG( SG_IO, SG_ALERT,
334                 "\tsomeone needs to upgrade net_fdm.hxx and recompile." );
335     }
336 }
337
338
339 FGExternalNet::FGExternalNet( double dt, string host, int dop, int dip, int cp )
340 {
341 //     set_delta_t( dt );
342
343     valid = true;
344
345     data_in_port = dip;
346     data_out_port = dop;
347     cmd_port = cp;
348     fdm_host = host;
349
350     /////////////////////////////////////////////////////////
351     // Setup client udp connection (sends data to remote fdm)
352
353     if ( ! data_client.open( false ) ) {
354         SG_LOG( SG_FLIGHT, SG_ALERT, "Error opening client data channel" );
355         valid = false;
356     }
357
358     // fire and forget
359     data_client.setBlocking( false );
360
361     if ( data_client.connect( fdm_host.c_str(), data_out_port ) == -1 ) {
362         printf("error connecting to %s:%d\n", fdm_host.c_str(), data_out_port);
363         valid = false;
364     }
365
366     /////////////////////////////////////////////////////////
367     // Setup server udp connection (for receiving data)
368
369     if ( ! data_server.open( false ) ) {
370         SG_LOG( SG_FLIGHT, SG_ALERT, "Error opening client server channel" );
371         valid = false;
372     }
373
374     // disable blocking
375     data_server.setBlocking( false );
376
377 #if defined( linux )
378     // set SO_REUSEADDR flag
379     int socket = data_server.getHandle();
380     int one = 1;
381     int result;
382     result = ::setsockopt( socket, SOL_SOCKET, SO_REUSEADDR,
383                            &one, sizeof(one) );
384 #endif
385
386     // allowed to read from a broadcast addr
387     // data_server.setBroadcast( true );
388
389     // if we bind to fdm_host = "" then we accept messages from
390     // anyone.
391     if ( data_server.bind( "", data_in_port ) == -1 ) {
392         printf("error binding to port %d\n", data_in_port);
393         valid = false;
394     }
395 }
396
397
398 FGExternalNet::~FGExternalNet() {
399     data_client.close();
400     data_server.close();
401 }
402
403
404 // Initialize the ExternalNet flight model, dt is the time increment
405 // for each subsequent iteration through the EOM
406 void FGExternalNet::init() {
407     // cout << "FGExternalNet::init()" << endl;
408
409     // Explicitly call the superclass's
410     // init method first.
411     common_init();
412
413     double lon = fgGetDouble( "/sim/presets/longitude-deg" );
414     double lat = fgGetDouble( "/sim/presets/latitude-deg" );
415     double alt = fgGetDouble( "/sim/presets/altitude-ft" );
416     double ground = fgGetDouble( "/environment/ground-elevation-m" );
417     double heading = fgGetDouble("/sim/presets/heading-deg");
418     double speed = fgGetDouble( "/sim/presets/airspeed-kt" );
419
420     char cmd[256];
421
422     HTTPClient *http;
423     sprintf( cmd, "/longitude-deg?value=%.8f", lon );
424     http = new HTTPClient( fdm_host.c_str(), cmd_port, cmd );
425     while ( !http->isDone(1000000) ) http->poll(0);
426     delete http;
427
428     sprintf( cmd, "/latitude-deg?value=%.8f", lat );
429     http = new HTTPClient( fdm_host.c_str(), cmd_port, cmd );
430     while ( !http->isDone(1000000) ) http->poll(0);
431     delete http;
432
433     sprintf( cmd, "/altitude-ft?value=%.8f", alt );
434     http = new HTTPClient( fdm_host.c_str(), cmd_port, cmd );
435     while ( !http->isDone(1000000) ) http->poll(0);
436     delete http;
437
438     sprintf( cmd, "/ground-m?value=%.8f", ground );
439     http = new HTTPClient( fdm_host.c_str(), cmd_port, cmd );
440     while ( !http->isDone(1000000) ) http->poll(0);
441     delete http;
442
443     sprintf( cmd, "/speed-kts?value=%.8f", speed );
444     http = new HTTPClient( fdm_host.c_str(), cmd_port, cmd );
445     while ( !http->isDone(1000000) ) http->poll(0);
446     delete http;
447
448     sprintf( cmd, "/heading-deg?value=%.8f", heading );
449     http = new HTTPClient( fdm_host.c_str(), cmd_port, cmd );
450     while ( !http->isDone(1000000) ) http->poll(0);
451     delete http;
452
453     SG_LOG( SG_IO, SG_INFO, "before sending reset command." );
454
455     if( fgGetBool("/sim/presets/onground") ) {
456       sprintf( cmd, "/reset?value=ground" );
457     } else {
458       sprintf( cmd, "/reset?value=air" );
459     }
460     http = new HTTPClient( fdm_host.c_str(), cmd_port, cmd );
461     while ( !http->isDone(1000000) ) http->poll(0);
462     delete http;
463
464     SG_LOG( SG_IO, SG_INFO, "Remote FDM init() finished." );
465 }
466
467
468 // Run an iteration of the EOM.
469 void FGExternalNet::update( double dt ) {
470     int length;
471     int result;
472
473     if (is_suspended())
474       return;
475
476     // Send control positions to remote fdm
477     length = sizeof(ctrls);
478     global2net( &ctrls );
479     if ( data_client.send( (char *)(& ctrls), length, 0 ) != length ) {
480         SG_LOG( SG_IO, SG_DEBUG, "Error writing data." );
481     } else {
482         SG_LOG( SG_IO, SG_DEBUG, "wrote control data." );
483     }
484
485     // Read next set of FDM data (blocking enabled to maintain 'sync')
486     length = sizeof(fdm);
487     while ( (result = data_server.recv( (char *)(& fdm), length, 0)) >= 0 ) {
488         SG_LOG( SG_IO, SG_DEBUG, "Success reading data." );
489         net2global( &fdm );
490     }
491 }