1 // ExternalNet.hxx -- an net interface to an external flight dynamics model
3 // Written by Curtis Olson, started November 2001.
5 // Copyright (C) 2001 Curtis L. Olson - curt@flightgear.org
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.
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.
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.
23 #include <simgear/debug/logstream.hxx>
24 #include <simgear/io/lowlevel.hxx> // endian tests
26 #include <Main/fg_props.hxx>
28 #include "ExternalNet.hxx"
31 // FreeBSD works better with this included last ... (?)
32 #if defined(WIN32) && !defined(__CYGWIN__)
35 # include <netinet/in.h> // htonl() ntohl()
39 // The function htond is defined this way due to the way some
40 // processors and OSes treat floating point values. Some will raise
41 // an exception whenever a "bad" floating point value is loaded into a
42 // floating point register. Solaris is notorious for this, but then
43 // so is LynxOS on the PowerPC. By translating the data in place,
44 // there is no need to load a FP register with the "corruped" floating
45 // point value. By doing the BIG_ENDIAN test, I can optimize the
46 // routine for big-endian processors so it can be as efficient as
48 static void htond (double &x)
50 if ( sgIsLittleEndian() ) {
54 Double_Overlay = (int *) &x;
55 Holding_Buffer = Double_Overlay [0];
57 Double_Overlay [0] = htonl (Double_Overlay [1]);
58 Double_Overlay [1] = htonl (Holding_Buffer);
65 static void global2net( FGNetCtrls *net ) {
69 SGPropertyNode * node = fgGetNode("/controls", true);
70 net->version = FG_NET_CTRLS_VERSION;
71 net->aileron = node->getDoubleValue( "aileron" );
72 net->elevator = node->getDoubleValue( "elevator" );
73 net->elevator_trim = node->getDoubleValue( "elevator-trim" );
74 net->rudder = node->getDoubleValue( "rudder" );
75 net->flaps = node->getDoubleValue( "flaps" );
77 = node->getDoubleValue( "/systems/electrical/outputs/flaps",
79 net->num_engines = FGNetCtrls::FG_MAX_ENGINES;
80 for ( i = 0; i < FGNetCtrls::FG_MAX_ENGINES; ++i ) {
81 net->throttle[i] = node->getDoubleValue( "throttle", 0.0 );
82 net->mixture[i] = node->getDoubleValue( "mixture", 0.0 );
83 net->fuel_pump_power[i]
84 = node->getDoubleValue( "/systems/electrical/outputs/fuel-pump",
86 net->prop_advance[i] = node->getDoubleValue( "propeller-pitch", 0.0 );
87 net->magnetos[i] = node->getIntValue( "magnetos", 0 );
89 // cout << "Magnetos -> " << node->getIntValue( "magnetos", 0 );
92 = node->getDoubleValue( "/systems/electrical/outputs/starter",
95 // cout << " Starter -> " << node->getIntValue( "stater", false )
99 net->num_tanks = FGNetCtrls::FG_MAX_TANKS;
100 for ( i = 0; i < FGNetCtrls::FG_MAX_TANKS; ++i ) {
101 if ( node->getChild("fuel-selector", i) != 0 ) {
102 net->fuel_selector[i]
103 = node->getChild("fuel-selector", i)->getDoubleValue();
105 net->fuel_selector[i] = false;
108 net->num_wheels = FGNetCtrls::FG_MAX_WHEELS;
109 for ( i = 0; i < FGNetCtrls::FG_MAX_WHEELS; ++i ) {
110 if ( node->getChild("brakes", i) != 0 ) {
111 if ( node->getChild("parking-brake")->getDoubleValue() > 0.0 ) {
115 = node->getChild("brakes", i)->getDoubleValue();
122 node = fgGetNode("/controls/switches", true);
123 net->master_bat = node->getChild("master-bat")->getBoolValue();
124 net->master_alt = node->getChild("master-alt")->getBoolValue();
125 net->master_avionics = node->getChild("master-avionics")->getBoolValue();
127 net->wind_speed_kt = fgGetDouble("/environment/wind-speed-kt");
128 net->wind_dir_deg = fgGetDouble("/environment/wind-from-heading-deg");
130 // cur_fdm_state->get_ground_elev_ft() is what we want ... this
131 // reports the altitude of the aircraft.
132 // "/environment/ground-elevation-m" reports the ground elevation
133 // of the current view point which could change substantially if
134 // the user is switching views.
135 net->hground = cur_fdm_state->get_ground_elev_ft() * SG_FEET_TO_METER;
136 net->magvar = fgGetDouble("/environment/magnetic-variation-deg");
137 net->speedup = fgGetInt("/sim/speed-up");
139 if ( fgGetBool("/sim/freeze/master") ) {
142 if ( fgGetBool("/sim/freeze/position") ) {
145 if ( fgGetBool("/sim/freeze/fuel") ) {
149 // convert to network byte order
150 net->version = htonl(net->version);
152 htond(net->elevator);
153 htond(net->elevator_trim);
156 net->flaps_power = htonl(net->flaps_power);
157 for ( i = 0; i < FGNetCtrls::FG_MAX_ENGINES; ++i ) {
158 htond(net->throttle[i]);
159 htond(net->mixture[i]);
160 net->fuel_pump_power[i] = htonl(net->fuel_pump_power[i]);
161 htond(net->prop_advance[i]);
162 net->magnetos[i] = htonl(net->magnetos[i]);
163 net->starter_power[i] = htonl(net->starter_power[i]);
165 net->num_engines = htonl(net->num_engines);
166 for ( i = 0; i < FGNetCtrls::FG_MAX_TANKS; ++i ) {
167 net->fuel_selector[i] = htonl(net->fuel_selector[i]);
169 net->num_tanks = htonl(net->num_tanks);
170 for ( i = 0; i < FGNetCtrls::FG_MAX_WHEELS; ++i ) {
171 htond(net->brake[i]);
173 net->num_wheels = htonl(net->num_wheels);
174 net->gear_handle = htonl(net->gear_handle);
175 net->master_bat = htonl(net->master_bat);
176 net->master_alt = htonl(net->master_alt);
177 net->master_avionics = htonl(net->master_avionics);
178 htond(net->wind_speed_kt);
179 htond(net->wind_dir_deg);
182 net->speedup = htonl(net->speedup);
183 net->freeze = htonl(net->freeze);
187 static void net2global( FGNetFDM *net ) {
190 // Convert to the net buffer from network format
191 net->version = ntohl(net->version);
193 htond(net->longitude);
194 htond(net->latitude);
195 htond(net->altitude);
201 htond(net->thetadot);
204 htond(net->climb_rate);
208 htond(net->v_wind_body_north);
209 htond(net->v_wind_body_east);
210 htond(net->v_wind_body_down);
211 htond(net->stall_warning);
213 htond(net->A_X_pilot);
214 htond(net->A_Y_pilot);
215 htond(net->A_Z_pilot);
217 net->num_engines = htonl(net->num_engines);
218 for ( i = 0; i < net->num_engines; ++i ) {
219 htonl(net->eng_state[i]);
221 htond(net->fuel_flow[i]);
223 htond(net->oil_temp[i]);
224 htond(net->oil_px[i]);
227 net->num_tanks = htonl(net->num_tanks);
228 for ( i = 0; i < net->num_tanks; ++i ) {
229 htond(net->fuel_quantity[i]);
232 net->num_wheels = htonl(net->num_wheels);
233 // I don't need to convert the Wow flags, since they are one byte in size
234 htond(net->flap_deflection);
236 net->cur_time = ntohl(net->cur_time);
237 net->warp = ntohl(net->warp);
238 htond(net->visibility);
240 if ( net->version == FG_NET_FDM_VERSION ) {
241 // cout << "pos = " << net->longitude << " " << net->latitude << endl;
242 // cout << "sea level rad = " << cur_fdm_state->get_Sea_level_radius()
244 cur_fdm_state->_updateGeodeticPosition( net->latitude,
247 * SG_METER_TO_FEET );
248 cur_fdm_state->_set_Euler_Angles( net->phi,
251 cur_fdm_state->_set_Euler_Rates( net->phidot,
254 cur_fdm_state->_set_V_calibrated_kts( net->vcas );
255 cur_fdm_state->_set_Climb_Rate( net->climb_rate );
256 cur_fdm_state->_set_Velocities_Local( net->v_north,
259 cur_fdm_state->_set_Velocities_Wind_Body( net->v_wind_body_north,
260 net->v_wind_body_east,
261 net->v_wind_body_down );
263 fgSetDouble( "/sim/alarms/stall-warning", net->stall_warning );
264 cur_fdm_state->_set_Accels_Pilot_Body( net->A_X_pilot,
268 for ( i = 0; i < net->num_engines; ++i ) {
269 SGPropertyNode *node = fgGetNode( "engines/engine", i, true );
271 // node->setBoolValue("running", t->isRunning());
272 // node->setBoolValue("cranking", t->isCranking());
274 // cout << net->eng_state[i] << endl;
275 if ( net->eng_state[i] == 0 ) {
276 node->setBoolValue( "cranking", false );
277 node->setBoolValue( "running", false );
278 } else if ( net->eng_state[i] == 1 ) {
279 node->setBoolValue( "cranking", true );
280 node->setBoolValue( "running", false );
281 } else if ( net->eng_state[i] == 2 ) {
282 node->setBoolValue( "cranking", false );
283 node->setBoolValue( "running", true );
286 node->setDoubleValue( "rpm", net->rpm[i] );
287 node->setDoubleValue( "fuel-flow-gph", net->fuel_flow[i] );
288 node->setDoubleValue( "egt-degf", net->EGT[i] );
289 node->setDoubleValue( "oil-temperature-degf", net->oil_temp[i] );
290 node->setDoubleValue( "oil-pressure-psi", net->oil_px[i] );
293 for (i = 0; i < net->num_tanks; ++i ) {
294 SGPropertyNode * node
295 = fgGetNode("/consumables/fuel/tank", i, true);
296 node->setDoubleValue("level-gal_us", net->fuel_quantity[i] );
299 for (i = 0; i < net->num_wheels; ++i ) {
300 SGPropertyNode * node
301 = fgGetNode("/gear/gear", i, true);
302 node->setDoubleValue("wow", net->wow[i] );
305 fgSetDouble("/surface-positions/flap-pos-norm", net->flap_deflection);
306 SGPropertyNode * node = fgGetNode("/controls", true);
307 fgSetDouble("/surface-positions/elevator-pos-norm",
308 node->getDoubleValue( "elevator" ));
309 fgSetDouble("/surface-positions/rudder-pos-norm",
310 node->getDoubleValue( "rudder" ));
311 fgSetDouble("/surface-positions/left-aileron-pos-norm",
312 node->getDoubleValue( "aileron" ));
313 fgSetDouble("/surface-positions/right-aileron-pos-norm",
314 -node->getDoubleValue( "aileron" ));
316 /* these are ignored for now ... */
318 if ( net->cur_time ) {
319 fgSetLong("/sim/time/cur-time-override", net->cur_time);
322 globals->set_warp( net->warp );
323 last_warp = net->warp;
326 SG_LOG( SG_IO, SG_ALERT, "Error: version mismatch in net2global()" );
327 SG_LOG( SG_IO, SG_ALERT,
328 "\tread " << net->version << " need " << FG_NET_FDM_VERSION );
329 SG_LOG( SG_IO, SG_ALERT,
330 "\tsomeone needs to upgrade net_fdm.hxx and recompile." );
335 FGExternalNet::FGExternalNet( double dt, string host, int dop, int dip, int cp )
337 // set_delta_t( dt );
346 /////////////////////////////////////////////////////////
347 // Setup client udp connection (sends data to remote fdm)
349 if ( ! data_client.open( false ) ) {
350 SG_LOG( SG_FLIGHT, SG_ALERT, "Error opening client data channel" );
355 data_client.setBlocking( false );
357 if ( data_client.connect( fdm_host.c_str(), data_out_port ) == -1 ) {
358 printf("error connecting to %s:%d\n", fdm_host.c_str(), data_out_port);
362 /////////////////////////////////////////////////////////
363 // Setup server udp connection (for receiving data)
365 if ( ! data_server.open( false ) ) {
366 SG_LOG( SG_FLIGHT, SG_ALERT, "Error opening client server channel" );
371 data_server.setBlocking( false );
373 // allowed to read from a broadcast addr
374 // data_server.setBroadcast( true );
376 // if we bind to fdm_host = "" then we accept messages from
378 if ( data_server.bind( "", data_in_port ) == -1 ) {
379 printf("error binding to port %d\n", data_in_port);
385 FGExternalNet::~FGExternalNet() {
391 // Initialize the ExternalNet flight model, dt is the time increment
392 // for each subsequent iteration through the EOM
393 void FGExternalNet::init() {
394 // cout << "FGExternalNet::init()" << endl;
396 // Explicitly call the superclass's
397 // init method first.
400 double lon = fgGetDouble( "/sim/presets/longitude-deg" );
401 double lat = fgGetDouble( "/sim/presets/latitude-deg" );
402 double alt = fgGetDouble( "/sim/presets/altitude-ft" );
403 double ground = fgGetDouble( "/environment/ground-elevation-m" );
404 double heading = fgGetDouble("/sim/presets/heading-deg");
405 double speed = fgGetDouble( "/sim/presets/airspeed-kt" );
410 sprintf( cmd, "/longitude-deg?value=%.8f", lon );
411 http = new HTTPClient( fdm_host.c_str(), cmd_port, cmd );
412 while ( !http->isDone(1000000) ) http->poll(0);
415 sprintf( cmd, "/latitude-deg?value=%.8f", lat );
416 http = new HTTPClient( fdm_host.c_str(), cmd_port, cmd );
417 while ( !http->isDone(1000000) ) http->poll(0);
420 sprintf( cmd, "/altitude-ft?value=%.8f", alt );
421 http = new HTTPClient( fdm_host.c_str(), cmd_port, cmd );
422 while ( !http->isDone(1000000) ) http->poll(0);
425 sprintf( cmd, "/ground-m?value=%.8f", ground );
426 http = new HTTPClient( fdm_host.c_str(), cmd_port, cmd );
427 while ( !http->isDone(1000000) ) http->poll(0);
430 sprintf( cmd, "/speed-kts?value=%.8f", speed );
431 http = new HTTPClient( fdm_host.c_str(), cmd_port, cmd );
432 while ( !http->isDone(1000000) ) http->poll(0);
435 sprintf( cmd, "/heading-deg?value=%.8f", heading );
436 http = new HTTPClient( fdm_host.c_str(), cmd_port, cmd );
437 while ( !http->isDone(1000000) ) http->poll(0);
440 SG_LOG( SG_IO, SG_INFO, "before sending reset command." );
442 if( fgGetBool("/sim/presets/onground") ) {
443 sprintf( cmd, "/reset?value=ground" );
445 sprintf( cmd, "/reset?value=air" );
447 http = new HTTPClient( fdm_host.c_str(), cmd_port, cmd );
448 while ( !http->isDone(1000000) ) http->poll(0);
451 SG_LOG( SG_IO, SG_INFO, "Remote FDM init() finished." );
455 // Run an iteration of the EOM.
456 void FGExternalNet::update( double dt ) {
463 // Send control positions to remote fdm
464 length = sizeof(ctrls);
465 global2net( &ctrls );
466 if ( data_client.send( (char *)(& ctrls), length, 0 ) != length ) {
467 SG_LOG( SG_IO, SG_DEBUG, "Error writing data." );
469 SG_LOG( SG_IO, SG_DEBUG, "wrote control data." );
472 // Read next set of FDM data (blocking enabled to maintain 'sync')
473 length = sizeof(fdm);
474 while ( (result = data_server.recv( (char *)(& fdm), length, 0)) >= 0 ) {
475 SG_LOG( SG_IO, SG_DEBUG, "Success reading data." );