]> git.mxchange.org Git - flightgear.git/blob - src/FDM/ExternalNet/ExternalNet.cxx
Additional failure modeling.
[flightgear.git] / src / FDM / ExternalNet / ExternalNet.cxx
1 // ExternalNet.hxx -- an net interface to an external flight dynamics model
2 //
3 // Written by Curtis Olson, started November 2001.
4 //
5 // Copyright (C) 2001  Curtis L. Olson  - curt@flightgear.org
6 //
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.
11 //
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.
16 //
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.
20 //
21 // $Id$
22
23 #include <simgear/debug/logstream.hxx>
24 #include <simgear/io/lowlevel.hxx> // endian tests
25
26 #include <Main/fg_props.hxx>
27
28 #include "ExternalNet.hxx"
29
30
31 // FreeBSD works better with this included last ... (?)
32 #if defined(WIN32) && !defined(__CYGWIN__)
33 #  include <windows.h>
34 #else
35 #  include <netinet/in.h>       // htonl() ntohl()
36 #endif
37
38
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
47 // possible
48 static void htond (double &x)   
49 {
50     if ( sgIsLittleEndian() ) {
51         int    *Double_Overlay;
52         int     Holding_Buffer;
53     
54         Double_Overlay = (int *) &x;
55         Holding_Buffer = Double_Overlay [0];
56     
57         Double_Overlay [0] = htonl (Double_Overlay [1]);
58         Double_Overlay [1] = htonl (Holding_Buffer);
59     } else {
60         return;
61     }
62 }
63
64
65 static void global2net( FGNetCtrls *net ) {
66     int i;
67
68     // fill in values
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" );
76     net->flaps_power
77             = node->getDoubleValue( "/systems/electrical/outputs/flaps",
78                                     1.0 ) >= 1.0;
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",
85                                     1.0 ) >= 1.0;
86         net->prop_advance[i] = node->getDoubleValue( "propeller-pitch", 0.0 );
87         net->magnetos[i] = node->getIntValue( "magnetos", 0 );
88         if ( i == 0 ) {
89           // cout << "Magnetos -> " << node->getIntValue( "magnetos", 0 );
90         }
91         net->starter_power[i]
92             = node->getDoubleValue( "/systems/electrical/outputs/starter",
93                                     1.0 ) >= 1.0;
94         if ( i == 0 ) {
95           // cout << " Starter -> " << node->getIntValue( "stater", false )
96           //      << endl;
97         }
98     }
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();
104         } else {
105             net->fuel_selector[i] = false;
106         }
107     }
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 ) {
112                 net->brake[i] = 1.0;
113            } else {
114                 net->brake[i]
115                     = node->getChild("brakes", i)->getDoubleValue();
116             }
117         } else {
118             net->brake[i] = 0.0;
119         }
120     }
121
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();
126
127     net->wind_speed_kt = fgGetDouble("/environment/wind-speed-kt");
128     net->wind_dir_deg = fgGetDouble("/environment/wind-from-heading-deg");
129
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");
138     net->freeze = 0;
139     if ( fgGetBool("/sim/freeze/master") ) {
140         net->freeze |= 0x01;
141     }
142     if ( fgGetBool("/sim/freeze/position") ) {
143         net->freeze |= 0x02;
144     }
145     if ( fgGetBool("/sim/freeze/fuel") ) {
146         net->freeze |= 0x04;
147     }
148
149     // convert to network byte order
150     net->version = htonl(net->version);
151     htond(net->aileron);
152     htond(net->elevator);
153     htond(net->elevator_trim);
154     htond(net->rudder);
155     htond(net->flaps);
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]);
164     }
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]);
168     }
169     net->num_tanks = htonl(net->num_tanks);
170     for ( i = 0; i < FGNetCtrls::FG_MAX_WHEELS; ++i ) {
171         htond(net->brake[i]);
172     }
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);
180     htond(net->hground);
181     htond(net->magvar);
182     net->speedup = htonl(net->speedup);
183     net->freeze = htonl(net->freeze);
184 }
185
186
187 static void net2global( FGNetFDM *net ) {
188     int i;
189
190     // Convert to the net buffer from network format
191     net->version = ntohl(net->version);
192
193     htond(net->longitude);
194     htond(net->latitude);
195     htond(net->altitude);
196     htond(net->phi);
197     htond(net->theta);
198     htond(net->psi);
199
200     htond(net->phidot);
201     htond(net->thetadot);
202     htond(net->psidot);
203     htond(net->vcas);
204     htond(net->climb_rate);
205     htond(net->v_north);
206     htond(net->v_east);
207     htond(net->v_down);
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);
212
213     htond(net->A_X_pilot);
214     htond(net->A_Y_pilot);
215     htond(net->A_Z_pilot);
216
217     net->num_engines = htonl(net->num_engines);
218     for ( i = 0; i < net->num_engines; ++i ) {
219         htonl(net->eng_state[i]);
220         htond(net->rpm[i]);
221         htond(net->fuel_flow[i]);
222         htond(net->EGT[i]);
223         htond(net->oil_temp[i]);
224         htond(net->oil_px[i]);
225     }
226
227     net->num_tanks = htonl(net->num_tanks);
228     for ( i = 0; i < net->num_tanks; ++i ) {
229         htond(net->fuel_quantity[i]);
230     }
231
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);
235
236     net->cur_time = ntohl(net->cur_time);
237     net->warp = ntohl(net->warp);
238     htond(net->visibility);
239
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()
243         //      << endl;
244         cur_fdm_state->_updateGeodeticPosition( net->latitude,
245                                                 net->longitude,
246                                                 net->altitude
247                                                   * SG_METER_TO_FEET );
248         cur_fdm_state->_set_Euler_Angles( net->phi,
249                                           net->theta,
250                                           net->psi );
251         cur_fdm_state->_set_Euler_Rates( net->phidot,
252                                          net->thetadot,
253                                          net->psidot );
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,
257                                               net->v_east,
258                                               net->v_down );
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 );
262
263         fgSetDouble( "/sim/alarms/stall-warning", net->stall_warning );
264         cur_fdm_state->_set_Accels_Pilot_Body( net->A_X_pilot,
265                                                net->A_Y_pilot,
266                                                net->A_Z_pilot );
267
268         for ( i = 0; i < net->num_engines; ++i ) {
269             SGPropertyNode *node = fgGetNode( "engines/engine", i, true );
270             
271             // node->setBoolValue("running", t->isRunning());
272             // node->setBoolValue("cranking", t->isCranking());
273             
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 );
284             }
285
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] );         
291         }
292
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] );
297         }
298
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] );
303         }
304
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" ));
315
316         /* these are ignored for now  ... */
317         /*
318         if ( net->cur_time ) {
319             fgSetLong("/sim/time/cur-time-override", net->cur_time);
320         }
321
322         globals->set_warp( net->warp );
323         last_warp = net->warp;
324         */
325     } else {
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." );
331     }
332 }
333
334
335 FGExternalNet::FGExternalNet( double dt, string host, int dop, int dip, int cp )
336 {
337 //     set_delta_t( dt );
338
339     valid = true;
340
341     data_in_port = dip;
342     data_out_port = dop;
343     cmd_port = cp;
344     fdm_host = host;
345
346     /////////////////////////////////////////////////////////
347     // Setup client udp connection (sends data to remote fdm)
348
349     if ( ! data_client.open( false ) ) {
350         SG_LOG( SG_FLIGHT, SG_ALERT, "Error opening client data channel" );
351         valid = false;
352     }
353
354     // fire and forget
355     data_client.setBlocking( false );
356
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);
359         valid = false;
360     }
361
362     /////////////////////////////////////////////////////////
363     // Setup server udp connection (for receiving data)
364
365     if ( ! data_server.open( false ) ) {
366         SG_LOG( SG_FLIGHT, SG_ALERT, "Error opening client server channel" );
367         valid = false;
368     }
369
370     // disable blocking
371     data_server.setBlocking( false );
372
373     // allowed to read from a broadcast addr
374     // data_server.setBroadcast( true );
375
376     // if we bind to fdm_host = "" then we accept messages from
377     // anyone.
378     if ( data_server.bind( "", data_in_port ) == -1 ) {
379         printf("error binding to port %d\n", data_in_port);
380         valid = false;
381     }
382 }
383
384
385 FGExternalNet::~FGExternalNet() {
386     data_client.close();
387     data_server.close();
388 }
389
390
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;
395
396     // Explicitly call the superclass's
397     // init method first.
398     common_init();
399
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" );
406
407     char cmd[256];
408
409     HTTPClient *http;
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);
413     delete http;
414
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);
418     delete http;
419
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);
423     delete http;
424
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);
428     delete http;
429
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);
433     delete http;
434
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);
438     delete http;
439
440     SG_LOG( SG_IO, SG_INFO, "before sending reset command." );
441
442     if( fgGetBool("/sim/presets/onground") ) {
443       sprintf( cmd, "/reset?value=ground" );
444     } else {
445       sprintf( cmd, "/reset?value=air" );
446     }
447     http = new HTTPClient( fdm_host.c_str(), cmd_port, cmd );
448     while ( !http->isDone(1000000) ) http->poll(0);
449     delete http;
450
451     SG_LOG( SG_IO, SG_INFO, "Remote FDM init() finished." );
452 }
453
454
455 // Run an iteration of the EOM.
456 void FGExternalNet::update( double dt ) {
457     int length;
458     int result;
459
460     if (is_suspended())
461       return;
462
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." );
468     } else {
469         SG_LOG( SG_IO, SG_DEBUG, "wrote control data." );
470     }
471
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." );
476         net2global( &fdm );
477     }
478 }