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 global2raw( FGRawCtrls *raw ) {
69 SGPropertyNode * node = fgGetNode("/controls", true);
70 raw->version = FG_RAW_CTRLS_VERSION;
71 raw->aileron = node->getDoubleValue( "aileron" );
72 raw->elevator = node->getDoubleValue( "elevator" );
73 raw->elevator_trim = node->getDoubleValue( "elevator-trim" );
74 raw->rudder = node->getDoubleValue( "rudder" );
75 raw->flaps = node->getDoubleValue( "flaps" );
77 = node->getDoubleValue( "/systems/electrical/outputs/flaps",
79 raw->num_engines = FGRawCtrls::FG_MAX_ENGINES;
80 for ( i = 0; i < FGRawCtrls::FG_MAX_ENGINES; ++i ) {
81 raw->throttle[i] = node->getDoubleValue( "throttle", 0.0 );
82 raw->mixture[i] = node->getDoubleValue( "mixture", 0.0 );
83 raw->fuel_pump_power[i]
84 = node->getDoubleValue( "/systems/electrical/outputs/fuel-pump",
86 raw->prop_advance[i] = node->getDoubleValue( "propeller-pitch", 0.0 );
87 raw->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 raw->num_tanks = FGRawCtrls::FG_MAX_TANKS;
100 for ( i = 0; i < FGRawCtrls::FG_MAX_TANKS; ++i ) {
101 if ( node->getChild("fuel-selector", i) != 0 ) {
102 raw->fuel_selector[i]
103 = node->getChild("fuel-selector", i)->getDoubleValue();
105 raw->fuel_selector[i] = false;
108 raw->num_wheels = FGRawCtrls::FG_MAX_WHEELS;
109 for ( i = 0; i < FGRawCtrls::FG_MAX_WHEELS; ++i ) {
110 if ( node->getChild("brakes", i) != 0 ) {
112 = node->getChild("brakes", i)->getDoubleValue();
118 node = fgGetNode("/controls/switches", true);
119 raw->master_bat = node->getChild("master-bat")->getBoolValue();
120 raw->master_alt = node->getChild("master-alt")->getBoolValue();
121 raw->master_avionics = node->getChild("master-avionics")->getBoolValue();
123 // cur_fdm_state->get_ground_elev_ft() is what we want ... this
124 // reports the altitude of the aircraft.
125 // "/environment/ground-elevation-m" reports the ground elevation
126 // of the current view point which could change substantially if
127 // the user is switching views.
128 raw->hground = cur_fdm_state->get_ground_elev_ft() * SG_FEET_TO_METER;
129 raw->magvar = fgGetDouble("/environment/magnetic-variation-deg");
130 raw->speedup = fgGetInt("/sim/speed-up");
132 // convert to network byte order
133 raw->version = htonl(raw->version);
135 htond(raw->elevator);
136 htond(raw->elevator_trim);
139 raw->flaps_power = htonl(raw->flaps_power);
140 for ( i = 0; i < FGRawCtrls::FG_MAX_ENGINES; ++i ) {
141 htond(raw->throttle[i]);
142 htond(raw->mixture[i]);
143 raw->fuel_pump_power[i] = htonl(raw->fuel_pump_power[i]);
144 htond(raw->prop_advance[i]);
145 raw->magnetos[i] = htonl(raw->magnetos[i]);
146 raw->starter_power[i] = htonl(raw->starter_power[i]);
148 raw->num_engines = htonl(raw->num_engines);
149 for ( i = 0; i < FGRawCtrls::FG_MAX_TANKS; ++i ) {
150 raw->fuel_selector[i] = htonl(raw->fuel_selector[i]);
152 raw->num_tanks = htonl(raw->num_tanks);
153 for ( i = 0; i < FGRawCtrls::FG_MAX_WHEELS; ++i ) {
154 htond(raw->brake[i]);
156 raw->num_wheels = htonl(raw->num_wheels);
157 raw->gear_handle = htonl(raw->gear_handle);
158 raw->master_bat = htonl(raw->master_bat);
159 raw->master_alt = htonl(raw->master_alt);
160 raw->master_avionics = htonl(raw->master_avionics);
163 raw->speedup = htonl(raw->speedup);
167 static void net2global( FGNetFDM *net ) {
170 // Convert to the net buffer from network format
171 net->version = ntohl(net->version);
173 htond(net->longitude);
174 htond(net->latitude);
175 htond(net->altitude);
181 htond(net->thetadot);
184 htond(net->climb_rate);
188 htond(net->stall_warning);
190 htond(net->A_X_pilot);
191 htond(net->A_Y_pilot);
192 htond(net->A_Z_pilot);
194 net->num_engines = htonl(net->num_engines);
195 for ( i = 0; i < net->num_engines; ++i ) {
196 htonl(net->eng_state[i]);
198 htond(net->fuel_flow[i]);
200 htond(net->oil_temp[i]);
201 htond(net->oil_px[i]);
204 net->num_tanks = htonl(net->num_tanks);
205 for ( i = 0; i < net->num_tanks; ++i ) {
206 htond(net->fuel_quantity[i]);
209 net->num_wheels = htonl(net->num_wheels);
210 // I don't need to convert the Wow flags, since they are one byte in size
211 htond(net->flap_deflection);
213 net->cur_time = ntohl(net->cur_time);
214 net->warp = ntohl(net->warp);
215 htond(net->visibility);
217 if ( net->version == FG_NET_FDM_VERSION ) {
218 // cout << "pos = " << net->longitude << " " << net->latitude << endl;
219 // cout << "sea level rad = " << cur_fdm_state->get_Sea_level_radius()
221 cur_fdm_state->_updateGeodeticPosition( net->latitude,
224 * SG_METER_TO_FEET );
225 cur_fdm_state->_set_Euler_Angles( net->phi,
228 cur_fdm_state->_set_Euler_Rates( net->phidot,
231 cur_fdm_state->_set_V_calibrated_kts( net->vcas );
232 cur_fdm_state->_set_Climb_Rate( net->climb_rate );
233 cur_fdm_state->_set_Velocities_Local( net->v_north,
236 fgSetDouble( "/sim/aero/alarms/stall-warning", net->stall_warning );
237 cur_fdm_state->_set_Accels_Pilot_Body( net->A_X_pilot,
241 for ( i = 0; i < net->num_engines; ++i ) {
242 SGPropertyNode *node = fgGetNode( "engines/engine", i, true );
244 // node->setBoolValue("running", t->isRunning());
245 // node->setBoolValue("cranking", t->isCranking());
247 // cout << net->eng_state[i] << endl;
248 if ( net->eng_state[i] == 0 ) {
249 node->setBoolValue( "cranking", false );
250 node->setBoolValue( "running", false );
251 } else if ( net->eng_state[i] == 1 ) {
252 node->setBoolValue( "cranking", true );
253 node->setBoolValue( "running", false );
254 } else if ( net->eng_state[i] == 2 ) {
255 node->setBoolValue( "cranking", false );
256 node->setBoolValue( "running", true );
259 node->setDoubleValue( "rpm", net->rpm[i] );
260 node->setDoubleValue( "fuel-flow-gph", net->fuel_flow[i] );
261 node->setDoubleValue( "egt-degf", net->EGT[i] );
262 node->setDoubleValue( "oil-temperature-degf", net->oil_temp[i] );
263 node->setDoubleValue( "oil-pressure-psi", net->oil_px[i] );
266 for (i = 0; i < net->num_tanks; ++i ) {
267 SGPropertyNode * node
268 = fgGetNode("/consumables/fuel/tank", i, true);
269 node->setDoubleValue("level-gal_us", net->fuel_quantity[i] );
272 for (i = 0; i < net->num_wheels; ++i ) {
273 SGPropertyNode * node
274 = fgGetNode("/gear/gear", i, true);
275 node->setDoubleValue("wow", net->wow[i] );
278 fgSetDouble("/surface-positions/flap-pos-norm", net->flap_deflection);
279 SGPropertyNode * node = fgGetNode("/controls", true);
280 fgSetDouble("/surface-positions/elevator-pos-norm",
281 node->getDoubleValue( "elevator" ));
282 fgSetDouble("/surface-positions/rudder-pos-norm",
283 node->getDoubleValue( "rudder" ));
284 fgSetDouble("/surface-positions/left-aileron-pos-norm",
285 node->getDoubleValue( "aileron" ));
286 fgSetDouble("/surface-positions/right-aileron-pos-norm",
287 -node->getDoubleValue( "aileron" ));
289 /* these are ignored for now ... */
291 if ( net->cur_time ) {
292 fgSetLong("/sim/time/cur-time-override", net->cur_time);
295 globals->set_warp( net->warp );
296 last_warp = net->warp;
299 SG_LOG( SG_IO, SG_ALERT, "Error: version mismatch in net2global()" );
300 SG_LOG( SG_IO, SG_ALERT,
301 "\tread " << net->version << " need " << FG_NET_FDM_VERSION );
302 SG_LOG( SG_IO, SG_ALERT,
303 "\tsomeone needs to upgrade net_fdm.hxx and recompile." );
308 FGExternalNet::FGExternalNet( double dt, string host, int dop, int dip, int cp )
310 // set_delta_t( dt );
319 /////////////////////////////////////////////////////////
320 // Setup client udp connection (sends data to remote fdm)
322 if ( ! data_client.open( false ) ) {
323 SG_LOG( SG_FLIGHT, SG_ALERT, "Error opening client data channel" );
328 data_client.setBlocking( false );
330 if ( data_client.connect( fdm_host.c_str(), data_out_port ) == -1 ) {
331 printf("error connecting to %s:%d\n", fdm_host.c_str(), data_out_port);
335 /////////////////////////////////////////////////////////
336 // Setup server udp connection (for receiving data)
338 if ( ! data_server.open( false ) ) {
339 SG_LOG( SG_FLIGHT, SG_ALERT, "Error opening client server channel" );
344 data_server.setBlocking( false );
346 // allowed to read from a broadcast addr
347 // data_server.setBroadcast( true );
349 // if we bind to fdm_host = "" then we accept messages from
351 if ( data_server.bind( "", data_in_port ) == -1 ) {
352 printf("error binding to port %d\n", data_in_port);
358 FGExternalNet::~FGExternalNet() {
364 // Initialize the ExternalNet flight model, dt is the time increment
365 // for each subsequent iteration through the EOM
366 void FGExternalNet::init() {
367 // cout << "FGExternalNet::init()" << endl;
369 // Explicitly call the superclass's
370 // init method first.
373 double lon = fgGetDouble( "/position/longitude-deg" );
374 double lat = fgGetDouble( "/position/latitude-deg" );
375 double ground = fgGetDouble( "/environment/ground-elevation-m" );
376 double heading = fgGetDouble("/orientation/heading-deg");
381 sprintf( cmd, "/longitude-deg?value=%.8f", lon );
382 http = new HTTPClient( fdm_host.c_str(), cmd_port, cmd );
383 while ( !http->isDone() ) http->poll(0);
386 sprintf( cmd, "/latitude-deg?value=%.8f", lat );
387 http = new HTTPClient( fdm_host.c_str(), cmd_port, cmd );
388 while ( !http->isDone() ) http->poll(0);
391 sprintf( cmd, "/ground-m?value=%.8f", ground );
392 http = new HTTPClient( fdm_host.c_str(), cmd_port, cmd );
393 while ( !http->isDone() ) http->poll(0);
396 sprintf( cmd, "/heading-deg?value=%.8f", heading );
397 http = new HTTPClient( fdm_host.c_str(), cmd_port, cmd );
398 while ( !http->isDone() ) http->poll(0);
401 SG_LOG( SG_IO, SG_INFO, "before sending reset command." );
403 sprintf( cmd, "/reset?value=ground" );
404 http = new HTTPClient( fdm_host.c_str(), cmd_port, cmd );
405 while ( !http->isDone() ) http->poll(0);
408 SG_LOG( SG_IO, SG_INFO, "Remote FDM init() finished." );
412 // Run an iteration of the EOM.
413 void FGExternalNet::update( double dt ) {
420 // Send control positions to remote fdm
421 length = sizeof(ctrls);
422 global2raw( &ctrls );
423 if ( data_client.send( (char *)(& ctrls), length, 0 ) != length ) {
424 SG_LOG( SG_IO, SG_DEBUG, "Error writing data." );
426 SG_LOG( SG_IO, SG_DEBUG, "wrote control data." );
429 // Read next set of FDM data (blocking enabled to maintain 'sync')
430 length = sizeof(fdm);
431 while ( (result = data_server.recv( (char *)(& fdm), length, 0)) >= 0 ) {
432 SG_LOG( SG_IO, SG_DEBUG, "Success reading data." );