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.
27 #include <simgear/debug/logstream.hxx>
28 #include <simgear/io/lowlevel.hxx> // endian tests
30 #include <Main/fg_props.hxx>
31 #include <Network/native_ctrls.hxx>
33 #include "ExternalNet.hxx"
36 // FreeBSD works better with this included last ... (?)
37 #if defined(WIN32) && !defined(__CYGWIN__)
40 # include <netinet/in.h> // htonl() ntohl()
44 # include <sys/types.h>
45 # include <sys/socket.h>
48 // The function htond is defined this way due to the way some
49 // processors and OSes treat floating point values. Some will raise
50 // an exception whenever a "bad" floating point value is loaded into a
51 // floating point register. Solaris is notorious for this, but then
52 // so is LynxOS on the PowerPC. By translating the data in place,
53 // there is no need to load a FP register with the "corruped" floating
54 // point value. By doing the BIG_ENDIAN test, I can optimize the
55 // routine for big-endian processors so it can be as efficient as
57 static void htond (double &x)
59 if ( sgIsLittleEndian() ) {
63 Double_Overlay = (int *) &x;
64 Holding_Buffer = Double_Overlay [0];
66 Double_Overlay [0] = htonl (Double_Overlay [1]);
67 Double_Overlay [1] = htonl (Holding_Buffer);
74 static void net2global( FGNetFDM *net ) {
77 // Convert to the net buffer from network format
78 net->version = ntohl(net->version);
80 htond(net->longitude);
91 htond(net->climb_rate);
95 htond(net->v_wind_body_north);
96 htond(net->v_wind_body_east);
97 htond(net->v_wind_body_down);
98 htond(net->stall_warning);
100 htond(net->A_X_pilot);
101 htond(net->A_Y_pilot);
102 htond(net->A_Z_pilot);
104 net->num_engines = htonl(net->num_engines);
105 for ( i = 0; i < net->num_engines; ++i ) {
106 htonl(net->eng_state[i]);
108 htond(net->fuel_flow[i]);
110 htond(net->oil_temp[i]);
111 htond(net->oil_px[i]);
114 net->num_tanks = htonl(net->num_tanks);
115 for ( i = 0; i < net->num_tanks; ++i ) {
116 htond(net->fuel_quantity[i]);
119 net->num_wheels = htonl(net->num_wheels);
120 // I don't need to convert the Wow flags, since they are one byte in size
121 htond(net->flap_deflection);
123 net->cur_time = ntohl(net->cur_time);
124 net->warp = ntohl(net->warp);
125 htond(net->visibility);
127 if ( net->version == FG_NET_FDM_VERSION ) {
128 // cout << "pos = " << net->longitude << " " << net->latitude << endl;
129 // cout << "sea level rad = " << cur_fdm_state->get_Sea_level_radius()
131 cur_fdm_state->_updateGeodeticPosition( net->latitude,
134 * SG_METER_TO_FEET );
135 cur_fdm_state->_set_Euler_Angles( net->phi,
138 cur_fdm_state->_set_Euler_Rates( net->phidot,
141 cur_fdm_state->_set_V_calibrated_kts( net->vcas );
142 cur_fdm_state->_set_Climb_Rate( net->climb_rate );
143 cur_fdm_state->_set_Velocities_Local( net->v_north,
146 cur_fdm_state->_set_Velocities_Wind_Body( net->v_wind_body_north,
147 net->v_wind_body_east,
148 net->v_wind_body_down );
150 fgSetDouble( "/sim/alarms/stall-warning", net->stall_warning );
151 cur_fdm_state->_set_Accels_Pilot_Body( net->A_X_pilot,
155 for ( i = 0; i < net->num_engines; ++i ) {
156 SGPropertyNode *node = fgGetNode( "engines/engine", i, true );
158 // node->setBoolValue("running", t->isRunning());
159 // node->setBoolValue("cranking", t->isCranking());
161 // cout << net->eng_state[i] << endl;
162 if ( net->eng_state[i] == 0 ) {
163 node->setBoolValue( "cranking", false );
164 node->setBoolValue( "running", false );
165 } else if ( net->eng_state[i] == 1 ) {
166 node->setBoolValue( "cranking", true );
167 node->setBoolValue( "running", false );
168 } else if ( net->eng_state[i] == 2 ) {
169 node->setBoolValue( "cranking", false );
170 node->setBoolValue( "running", true );
173 node->setDoubleValue( "rpm", net->rpm[i] );
174 node->setDoubleValue( "fuel-flow-gph", net->fuel_flow[i] );
175 node->setDoubleValue( "egt-degf", net->EGT[i] );
176 node->setDoubleValue( "oil-temperature-degf", net->oil_temp[i] );
177 node->setDoubleValue( "oil-pressure-psi", net->oil_px[i] );
180 for (i = 0; i < net->num_tanks; ++i ) {
181 SGPropertyNode * node
182 = fgGetNode("/consumables/fuel/tank", i, true);
183 node->setDoubleValue("level-gal_us", net->fuel_quantity[i] );
186 for (i = 0; i < net->num_wheels; ++i ) {
187 SGPropertyNode * node
188 = fgGetNode("/gear/gear", i, true);
189 node->setDoubleValue("wow", net->wow[i] );
192 fgSetDouble("/surface-positions/flap-pos-norm", net->flap_deflection);
193 SGPropertyNode * node = fgGetNode("/controls", true);
194 fgSetDouble("/surface-positions/elevator-pos-norm",
195 node->getDoubleValue( "elevator" ));
196 fgSetDouble("/surface-positions/rudder-pos-norm",
197 node->getDoubleValue( "rudder" ));
198 fgSetDouble("/surface-positions/left-aileron-pos-norm",
199 node->getDoubleValue( "aileron" ));
200 fgSetDouble("/surface-positions/right-aileron-pos-norm",
201 -node->getDoubleValue( "aileron" ));
203 /* these are ignored for now ... */
205 if ( net->cur_time ) {
206 fgSetLong("/sim/time/cur-time-override", net->cur_time);
209 globals->set_warp( net->warp );
210 last_warp = net->warp;
213 SG_LOG( SG_IO, SG_ALERT, "Error: version mismatch in net2global()" );
214 SG_LOG( SG_IO, SG_ALERT,
215 "\tread " << net->version << " need " << FG_NET_FDM_VERSION );
216 SG_LOG( SG_IO, SG_ALERT,
217 "\tsomeone needs to upgrade net_fdm.hxx and recompile." );
222 FGExternalNet::FGExternalNet( double dt, string host, int dop, int dip, int cp )
224 // set_delta_t( dt );
233 /////////////////////////////////////////////////////////
234 // Setup client udp connection (sends data to remote fdm)
236 if ( ! data_client.open( false ) ) {
237 SG_LOG( SG_FLIGHT, SG_ALERT, "Error opening client data channel" );
242 data_client.setBlocking( false );
244 if ( data_client.connect( fdm_host.c_str(), data_out_port ) == -1 ) {
245 printf("error connecting to %s:%d\n", fdm_host.c_str(), data_out_port);
249 /////////////////////////////////////////////////////////
250 // Setup server udp connection (for receiving data)
252 if ( ! data_server.open( false ) ) {
253 SG_LOG( SG_FLIGHT, SG_ALERT, "Error opening client server channel" );
258 data_server.setBlocking( false );
261 // set SO_REUSEADDR flag
262 int socket = data_server.getHandle();
265 result = ::setsockopt( socket, SOL_SOCKET, SO_REUSEADDR,
269 // allowed to read from a broadcast addr
270 // data_server.setBroadcast( true );
272 // if we bind to fdm_host = "" then we accept messages from
274 if ( data_server.bind( "", data_in_port ) == -1 ) {
275 printf("error binding to port %d\n", data_in_port);
281 FGExternalNet::~FGExternalNet() {
287 // Initialize the ExternalNet flight model, dt is the time increment
288 // for each subsequent iteration through the EOM
289 void FGExternalNet::init() {
290 // cout << "FGExternalNet::init()" << endl;
292 // Explicitly call the superclass's
293 // init method first.
296 double lon = fgGetDouble( "/sim/presets/longitude-deg" );
297 double lat = fgGetDouble( "/sim/presets/latitude-deg" );
298 double alt = fgGetDouble( "/sim/presets/altitude-ft" );
299 double ground = fgGetDouble( "/environment/ground-elevation-m" );
300 double heading = fgGetDouble("/sim/presets/heading-deg");
301 double speed = fgGetDouble( "/sim/presets/airspeed-kt" );
306 sprintf( cmd, "/longitude-deg?value=%.8f", lon );
307 http = new HTTPClient( fdm_host.c_str(), cmd_port, cmd );
308 while ( !http->isDone(1000000) ) http->poll(0);
311 sprintf( cmd, "/latitude-deg?value=%.8f", lat );
312 http = new HTTPClient( fdm_host.c_str(), cmd_port, cmd );
313 while ( !http->isDone(1000000) ) http->poll(0);
316 sprintf( cmd, "/altitude-ft?value=%.8f", alt );
317 http = new HTTPClient( fdm_host.c_str(), cmd_port, cmd );
318 while ( !http->isDone(1000000) ) http->poll(0);
321 sprintf( cmd, "/ground-m?value=%.8f", ground );
322 http = new HTTPClient( fdm_host.c_str(), cmd_port, cmd );
323 while ( !http->isDone(1000000) ) http->poll(0);
326 sprintf( cmd, "/speed-kts?value=%.8f", speed );
327 http = new HTTPClient( fdm_host.c_str(), cmd_port, cmd );
328 while ( !http->isDone(1000000) ) http->poll(0);
331 sprintf( cmd, "/heading-deg?value=%.8f", heading );
332 http = new HTTPClient( fdm_host.c_str(), cmd_port, cmd );
333 while ( !http->isDone(1000000) ) http->poll(0);
336 SG_LOG( SG_IO, SG_INFO, "before sending reset command." );
338 if( fgGetBool("/sim/presets/onground") ) {
339 sprintf( cmd, "/reset?value=ground" );
341 sprintf( cmd, "/reset?value=air" );
343 http = new HTTPClient( fdm_host.c_str(), cmd_port, cmd );
344 while ( !http->isDone(1000000) ) http->poll(0);
347 SG_LOG( SG_IO, SG_INFO, "Remote FDM init() finished." );
351 // Run an iteration of the EOM.
352 void FGExternalNet::update( double dt ) {
359 // Send control positions to remote fdm
360 length = sizeof(ctrls);
361 FGProps2NetCtrls( &ctrls );
362 if ( data_client.send( (char *)(& ctrls), length, 0 ) != length ) {
363 SG_LOG( SG_IO, SG_DEBUG, "Error writing data." );
365 SG_LOG( SG_IO, SG_DEBUG, "wrote control data." );
368 // Read next set of FDM data (blocking enabled to maintain 'sync')
369 length = sizeof(fdm);
370 while ( (result = data_server.recv( (char *)(& fdm), length, 0)) >= 0 ) {
371 SG_LOG( SG_IO, SG_DEBUG, "Success reading data." );