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 # include <sys/types.h>
40 # include <sys/socket.h>
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
52 static void htond (double &x)
54 if ( sgIsLittleEndian() ) {
58 Double_Overlay = (int *) &x;
59 Holding_Buffer = Double_Overlay [0];
61 Double_Overlay [0] = htonl (Double_Overlay [1]);
62 Double_Overlay [1] = htonl (Holding_Buffer);
69 static void global2net( FGNetCtrls *net ) {
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" );
81 = node->getDoubleValue( "/systems/electrical/outputs/flaps",
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",
90 net->prop_advance[i] = node->getDoubleValue( "propeller-pitch", 0.0 );
91 net->magnetos[i] = node->getIntValue( "magnetos", 0 );
93 // cout << "Magnetos -> " << node->getIntValue( "magnetos", 0 );
96 = node->getDoubleValue( "/systems/electrical/outputs/starter",
99 // cout << " Starter -> " << node->getIntValue( "stater", false )
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();
109 net->fuel_selector[i] = false;
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 ) {
119 = node->getChild("brakes", i)->getDoubleValue();
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();
131 net->wind_speed_kt = fgGetDouble("/environment/wind-speed-kt");
132 net->wind_dir_deg = fgGetDouble("/environment/wind-from-heading-deg");
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");
143 if ( fgGetBool("/sim/freeze/master") ) {
146 if ( fgGetBool("/sim/freeze/position") ) {
149 if ( fgGetBool("/sim/freeze/fuel") ) {
153 // convert to network byte order
154 net->version = htonl(net->version);
156 htond(net->elevator);
157 htond(net->elevator_trim);
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]);
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]);
173 net->num_tanks = htonl(net->num_tanks);
174 for ( i = 0; i < FGNetCtrls::FG_MAX_WHEELS; ++i ) {
175 htond(net->brake[i]);
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);
186 net->speedup = htonl(net->speedup);
187 net->freeze = htonl(net->freeze);
191 static void net2global( FGNetFDM *net ) {
194 // Convert to the net buffer from network format
195 net->version = ntohl(net->version);
197 htond(net->longitude);
198 htond(net->latitude);
199 htond(net->altitude);
205 htond(net->thetadot);
208 htond(net->climb_rate);
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);
217 htond(net->A_X_pilot);
218 htond(net->A_Y_pilot);
219 htond(net->A_Z_pilot);
221 net->num_engines = htonl(net->num_engines);
222 for ( i = 0; i < net->num_engines; ++i ) {
223 htonl(net->eng_state[i]);
225 htond(net->fuel_flow[i]);
227 htond(net->oil_temp[i]);
228 htond(net->oil_px[i]);
231 net->num_tanks = htonl(net->num_tanks);
232 for ( i = 0; i < net->num_tanks; ++i ) {
233 htond(net->fuel_quantity[i]);
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);
240 net->cur_time = ntohl(net->cur_time);
241 net->warp = ntohl(net->warp);
242 htond(net->visibility);
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()
248 cur_fdm_state->_updateGeodeticPosition( net->latitude,
251 * SG_METER_TO_FEET );
252 cur_fdm_state->_set_Euler_Angles( net->phi,
255 cur_fdm_state->_set_Euler_Rates( net->phidot,
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,
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 );
267 fgSetDouble( "/sim/alarms/stall-warning", net->stall_warning );
268 cur_fdm_state->_set_Accels_Pilot_Body( net->A_X_pilot,
272 for ( i = 0; i < net->num_engines; ++i ) {
273 SGPropertyNode *node = fgGetNode( "engines/engine", i, true );
275 // node->setBoolValue("running", t->isRunning());
276 // node->setBoolValue("cranking", t->isCranking());
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 );
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] );
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] );
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] );
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" ));
320 /* these are ignored for now ... */
322 if ( net->cur_time ) {
323 fgSetLong("/sim/time/cur-time-override", net->cur_time);
326 globals->set_warp( net->warp );
327 last_warp = net->warp;
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." );
339 FGExternalNet::FGExternalNet( double dt, string host, int dop, int dip, int cp )
341 // set_delta_t( dt );
350 /////////////////////////////////////////////////////////
351 // Setup client udp connection (sends data to remote fdm)
353 if ( ! data_client.open( false ) ) {
354 SG_LOG( SG_FLIGHT, SG_ALERT, "Error opening client data channel" );
359 data_client.setBlocking( false );
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);
366 /////////////////////////////////////////////////////////
367 // Setup server udp connection (for receiving data)
369 if ( ! data_server.open( false ) ) {
370 SG_LOG( SG_FLIGHT, SG_ALERT, "Error opening client server channel" );
375 data_server.setBlocking( false );
378 // set SO_REUSEADDR flag
379 int socket = data_server.getHandle();
382 result = ::setsockopt( socket, SOL_SOCKET, SO_REUSEADDR,
386 // allowed to read from a broadcast addr
387 // data_server.setBroadcast( true );
389 // if we bind to fdm_host = "" then we accept messages from
391 if ( data_server.bind( "", data_in_port ) == -1 ) {
392 printf("error binding to port %d\n", data_in_port);
398 FGExternalNet::~FGExternalNet() {
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;
409 // Explicitly call the superclass's
410 // init method first.
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" );
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);
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);
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);
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);
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);
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);
453 SG_LOG( SG_IO, SG_INFO, "before sending reset command." );
455 if( fgGetBool("/sim/presets/onground") ) {
456 sprintf( cmd, "/reset?value=ground" );
458 sprintf( cmd, "/reset?value=air" );
460 http = new HTTPClient( fdm_host.c_str(), cmd_port, cmd );
461 while ( !http->isDone(1000000) ) http->poll(0);
464 SG_LOG( SG_IO, SG_INFO, "Remote FDM init() finished." );
468 // Run an iteration of the EOM.
469 void FGExternalNet::update( double dt ) {
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." );
482 SG_LOG( SG_IO, SG_DEBUG, "wrote control data." );
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." );