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" );
76 raw->num_engines = FGRawCtrls::FG_MAX_ENGINES;
77 for ( i = 0; i < FGRawCtrls::FG_MAX_ENGINES; ++i ) {
78 raw->throttle[i] = node->getDoubleValue( "throttle", 0.0 );
79 raw->mixture[i] = node->getDoubleValue( "mixture", 0.0 );
80 raw->prop_advance[i] = node->getDoubleValue( "propeller-pitch", 0.0 );
81 raw->magnetos[i] = node->getIntValue( "magnetos", 0 );
83 // cout << "Magnetos -> " << node->getIntValue( "magnetos", 0 );
85 raw->starter[i] = node->getBoolValue( "starter", false );
87 // cout << " Starter -> " << node->getIntValue( "stater", false )
91 raw->num_tanks = FGRawCtrls::FG_MAX_TANKS;
92 for ( i = 0; i < FGRawCtrls::FG_MAX_TANKS; ++i ) {
93 if ( node->getChild("fuel-selector", i) != 0 ) {
95 = node->getChild("fuel-selector", i)->getDoubleValue();
97 raw->fuel_selector[i] = false;
100 raw->num_wheels = FGRawCtrls::FG_MAX_WHEELS;
101 for ( i = 0; i < FGRawCtrls::FG_MAX_WHEELS; ++i ) {
102 if ( node->getChild("brakes", i) != 0 ) {
104 = node->getChild("brakes", i)->getDoubleValue();
109 raw->hground = fgGetDouble( "/environment/ground-elevation-m" );
110 raw->magvar = fgGetDouble("/environment/magnetic-variation-deg");
111 raw->speedup = fgGetInt("/sim/speed-up");
113 // convert to network byte order
114 raw->version = htonl(raw->version);
116 htond(raw->elevator);
117 htond(raw->elevator_trim);
120 for ( i = 0; i < FGRawCtrls::FG_MAX_ENGINES; ++i ) {
121 htond(raw->throttle[i]);
122 htond(raw->mixture[i]);
123 htond(raw->prop_advance[i]);
124 raw->magnetos[i] = htonl(raw->magnetos[i]);
125 raw->starter[i] = htonl(raw->starter[i]);
127 raw->num_engines = htonl(raw->num_engines);
128 for ( i = 0; i < FGRawCtrls::FG_MAX_TANKS; ++i ) {
129 raw->fuel_selector[i] = htonl(raw->fuel_selector[i]);
131 raw->num_tanks = htonl(raw->num_tanks);
132 for ( i = 0; i < FGRawCtrls::FG_MAX_WHEELS; ++i ) {
133 htond(raw->brake[i]);
135 raw->num_wheels = htonl(raw->num_wheels);
138 raw->speedup = htonl(raw->speedup);
142 static void net2global( FGNetFDM *net ) {
145 // Convert to the net buffer from network format
146 net->version = ntohl(net->version);
148 htond(net->longitude);
149 htond(net->latitude);
150 htond(net->altitude);
156 htond(net->thetadot);
159 htond(net->climb_rate);
161 htond(net->A_X_pilot);
162 htond(net->A_Y_pilot);
163 htond(net->A_Z_pilot);
165 net->num_engines = htonl(net->num_engines);
166 for ( i = 0; i < net->num_engines; ++i ) {
167 htonl(net->eng_state[i]);
169 htond(net->fuel_flow[i]);
171 htond(net->oil_temp[i]);
172 htond(net->oil_px[i]);
175 net->num_tanks = htonl(net->num_tanks);
176 for ( i = 0; i < net->num_tanks; ++i ) {
177 htond(net->fuel_quantity[i]);
180 net->num_wheels = htonl(net->num_wheels);
181 // I don't need to convert the Wow flags, since they are one byte in size
182 htond(net->flap_deflection);
184 net->cur_time = ntohl(net->cur_time);
185 net->warp = ntohl(net->warp);
186 htond(net->visibility);
188 if ( net->version == FG_NET_FDM_VERSION ) {
189 // cout << "pos = " << net->longitude << " " << net->latitude << endl;
190 // cout << "sea level rad = " << cur_fdm_state->get_Sea_level_radius()
192 cur_fdm_state->_updateGeodeticPosition( net->latitude,
195 * SG_METER_TO_FEET );
196 cur_fdm_state->_set_Euler_Angles( net->phi,
199 cur_fdm_state->_set_Euler_Rates( net->phidot,
202 cur_fdm_state->_set_V_calibrated_kts( net->vcas );
203 cur_fdm_state->_set_Climb_Rate( net->climb_rate );
204 cur_fdm_state->_set_Accels_Pilot_Body( net->A_X_pilot,
208 for ( i = 0; i < net->num_engines; ++i ) {
209 SGPropertyNode *node = fgGetNode( "engines/engine", i, true );
211 // node->setBoolValue("running", t->isRunning());
212 // node->setBoolValue("cranking", t->isCranking());
214 // cout << net->eng_state[i] << endl;
215 if ( net->eng_state[i] == 0 ) {
216 node->setBoolValue( "cranking", false );
217 node->setBoolValue( "running", false );
218 } else if ( net->eng_state[i] == 1 ) {
219 node->setBoolValue( "cranking", true );
220 node->setBoolValue( "running", false );
221 } else if ( net->eng_state[i] == 2 ) {
222 node->setBoolValue( "cranking", false );
223 node->setBoolValue( "running", true );
226 node->setDoubleValue( "rpm", net->rpm[i] );
227 node->setDoubleValue( "fuel-flow-gph", net->fuel_flow[i] );
228 node->setDoubleValue( "egt-degf", net->EGT[i] );
229 node->setDoubleValue( "oil-temperature-degf", net->oil_temp[i] );
230 node->setDoubleValue( "oil-pressure-psi", net->oil_px[i] );
233 for (i = 0; i < net->num_tanks; ++i ) {
234 SGPropertyNode * node
235 = fgGetNode("/consumables/fuel/tank", i, true);
236 node->setDoubleValue("level-gal_us", net->fuel_quantity[i] );
239 for (i = 0; i < net->num_wheels; ++i ) {
240 SGPropertyNode * node
241 = fgGetNode("/gear/gear", i, true);
242 node->setDoubleValue("wow", net->wow[i] );
245 fgSetDouble("/surface-positions/flap-pos-norm", net->flap_deflection);
246 SGPropertyNode * node = fgGetNode("/controls", true);
247 fgSetDouble("/surface-positions/elevator-pos-norm",
248 node->getDoubleValue( "elevator" ));
249 fgSetDouble("/surface-positions/rudder-pos-norm",
250 node->getDoubleValue( "rudder" ));
251 fgSetDouble("/surface-positions/left-aileron-pos-norm",
252 node->getDoubleValue( "aileron" ));
253 fgSetDouble("/surface-positions/right-aileron-pos-norm",
254 -node->getDoubleValue( "aileron" ));
256 /* these are ignored for now ... */
258 if ( net->cur_time ) {
259 fgSetLong("/sim/time/cur-time-override", net->cur_time);
262 globals->set_warp( net->warp );
263 last_warp = net->warp;
266 SG_LOG( SG_IO, SG_ALERT, "Error: version mismatch in net2global()" );
267 SG_LOG( SG_IO, SG_ALERT,
268 "\tread " << net->version << " need " << FG_NET_FDM_VERSION );
269 SG_LOG( SG_IO, SG_ALERT,
270 "\tsomeone needs to upgrade net_fdm.hxx and recompile." );
275 FGExternalNet::FGExternalNet( double dt, string host, int dop, int dip, int cp )
277 // set_delta_t( dt );
286 /////////////////////////////////////////////////////////
287 // Setup client udp connection (sends data to remote fdm)
289 if ( ! data_client.open( false ) ) {
290 SG_LOG( SG_FLIGHT, SG_ALERT, "Error opening client data channel" );
295 data_client.setBlocking( false );
297 if ( data_client.connect( fdm_host.c_str(), data_out_port ) == -1 ) {
298 printf("error connecting to %s:%d\n", fdm_host.c_str(), data_out_port);
302 /////////////////////////////////////////////////////////
303 // Setup server udp connection (for receiving data)
305 if ( ! data_server.open( false ) ) {
306 SG_LOG( SG_FLIGHT, SG_ALERT, "Error opening client server channel" );
311 data_server.setBlocking( false );
313 // allowed to read from a broadcast addr
314 data_server.setBroadcast( true );
316 // if we bind to fdm_host = "" then we accept messages from
318 if ( data_server.bind( "", data_in_port ) == -1 ) {
319 printf("error binding to port %d\n", data_in_port);
325 FGExternalNet::~FGExternalNet() {
331 // Initialize the ExternalNet flight model, dt is the time increment
332 // for each subsequent iteration through the EOM
333 void FGExternalNet::init() {
334 // cout << "FGExternalNet::init()" << endl;
336 // Explicitly call the superclass's
337 // init method first.
340 double lon = fgGetDouble( "/position/longitude-deg" );
341 double lat = fgGetDouble( "/position/latitude-deg" );
342 double ground = fgGetDouble( "/environment/ground-elevation-m" );
343 double heading = fgGetDouble("/orientation/heading-deg");
347 sprintf( cmd, "/longitude-deg?value=%.8f", lon );
348 new HTTPClient( fdm_host.c_str(), cmd_port, cmd );
349 // cout << "before loop()" << endl;
351 // cout << "here" << endl;
353 sprintf( cmd, "/latitude-deg?value=%.8f", lat );
354 new HTTPClient( fdm_host.c_str(), cmd_port, cmd );
357 sprintf( cmd, "/ground-m?value=%.8f", ground );
358 new HTTPClient( fdm_host.c_str(), cmd_port, cmd );
361 sprintf( cmd, "/heading-deg?value=%.8f", heading );
362 new HTTPClient( fdm_host.c_str(), cmd_port, cmd );
365 SG_LOG( SG_IO, SG_INFO, "before sending reset command." );
367 sprintf( cmd, "/reset?value=ground" );
368 new HTTPClient( fdm_host.c_str(), cmd_port, cmd );
371 SG_LOG( SG_IO, SG_INFO, "Remote FDM init() finished." );
375 // Run an iteration of the EOM.
376 void FGExternalNet::update( double dt ) {
383 // Send control positions to remote fdm
384 length = sizeof(ctrls);
385 global2raw( &ctrls );
386 if ( data_client.send( (char *)(& ctrls), length, 0 ) != length ) {
387 SG_LOG( SG_IO, SG_DEBUG, "Error writing data." );
389 SG_LOG( SG_IO, SG_DEBUG, "wrote control data." );
392 // Read next set of FDM data (blocking enabled to maintain 'sync')
393 length = sizeof(fdm);
394 while ( (result = data_server.recv( (char *)(& fdm), length, 0)) >= 0 ) {
395 SG_LOG( SG_IO, SG_DEBUG, "Success reading data." );