]> git.mxchange.org Git - flightgear.git/blob - src/FDM/ExternalNet.cxx
Added static port system and a new altimeter model connected to it.
[flightgear.git] / src / FDM / 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 global2raw( FGRawCtrls *raw ) {
66     int i;
67
68     // fill in values
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->flaps_power
77             = node->getDoubleValue( "/systems/electrical/outputs/flaps",
78                                     1.0 ) >= 1.0;
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",
85                                     1.0 ) >= 1.0;
86         raw->prop_advance[i] = node->getDoubleValue( "propeller-pitch", 0.0 );
87         raw->magnetos[i] = node->getIntValue( "magnetos", 0 );
88         if ( i == 0 ) {
89           // cout << "Magnetos -> " << node->getIntValue( "magnetos", 0 );
90         }
91         raw->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     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();
104         } else {
105             raw->fuel_selector[i] = false;
106         }
107     }
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 ) {
111             raw->brake[i]
112                 = node->getChild("brakes", i)->getDoubleValue();
113         } else {
114             raw->brake[i] = 0.0;
115         }
116     }
117
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();
122
123     raw->hground = fgGetDouble( "/environment/ground-elevation-m" );
124     raw->magvar = fgGetDouble("/environment/magnetic-variation-deg");
125     raw->speedup = fgGetInt("/sim/speed-up");
126
127     // convert to network byte order
128     raw->version = htonl(raw->version);
129     htond(raw->aileron);
130     htond(raw->elevator);
131     htond(raw->elevator_trim);
132     htond(raw->rudder);
133     htond(raw->flaps);
134     raw->flaps_power = htonl(raw->flaps_power);
135     for ( i = 0; i < FGRawCtrls::FG_MAX_ENGINES; ++i ) {
136         htond(raw->throttle[i]);
137         htond(raw->mixture[i]);
138         raw->fuel_pump_power[i] = htonl(raw->fuel_pump_power[i]);
139         htond(raw->prop_advance[i]);
140         raw->magnetos[i] = htonl(raw->magnetos[i]);
141         raw->starter_power[i] = htonl(raw->starter_power[i]);
142     }
143     raw->num_engines = htonl(raw->num_engines);
144     for ( i = 0; i < FGRawCtrls::FG_MAX_TANKS; ++i ) {
145         raw->fuel_selector[i] = htonl(raw->fuel_selector[i]);
146     }
147     raw->num_tanks = htonl(raw->num_tanks);
148     for ( i = 0; i < FGRawCtrls::FG_MAX_WHEELS; ++i ) {
149         htond(raw->brake[i]);
150     }
151     raw->num_wheels = htonl(raw->num_wheels);
152     raw->gear_handle = htonl(raw->gear_handle);
153     raw->master_bat = htonl(raw->master_bat);
154     raw->master_alt = htonl(raw->master_alt);
155     raw->master_avionics = htonl(raw->master_avionics);
156     htond(raw->hground);
157     htond(raw->magvar);
158     raw->speedup = htonl(raw->speedup);
159 }
160
161
162 static void net2global( FGNetFDM *net ) {
163     int i;
164
165     // Convert to the net buffer from network format
166     net->version = ntohl(net->version);
167
168     htond(net->longitude);
169     htond(net->latitude);
170     htond(net->altitude);
171     htond(net->phi);
172     htond(net->theta);
173     htond(net->psi);
174
175     htond(net->phidot);
176     htond(net->thetadot);
177     htond(net->psidot);
178     htond(net->vcas);
179     htond(net->climb_rate);
180     htond(net->v_north);
181     htond(net->v_east);
182     htond(net->v_down);
183
184     htond(net->A_X_pilot);
185     htond(net->A_Y_pilot);
186     htond(net->A_Z_pilot);
187
188     net->num_engines = htonl(net->num_engines);
189     for ( i = 0; i < net->num_engines; ++i ) {
190         htonl(net->eng_state[i]);
191         htond(net->rpm[i]);
192         htond(net->fuel_flow[i]);
193         htond(net->EGT[i]);
194         htond(net->oil_temp[i]);
195         htond(net->oil_px[i]);
196     }
197
198     net->num_tanks = htonl(net->num_tanks);
199     for ( i = 0; i < net->num_tanks; ++i ) {
200         htond(net->fuel_quantity[i]);
201     }
202
203     net->num_wheels = htonl(net->num_wheels);
204     // I don't need to convert the Wow flags, since they are one byte in size
205     htond(net->flap_deflection);
206
207     net->cur_time = ntohl(net->cur_time);
208     net->warp = ntohl(net->warp);
209     htond(net->visibility);
210
211     if ( net->version == FG_NET_FDM_VERSION ) {
212         // cout << "pos = " << net->longitude << " " << net->latitude << endl;
213         // cout << "sea level rad = " << cur_fdm_state->get_Sea_level_radius()
214         //      << endl;
215         cur_fdm_state->_updateGeodeticPosition( net->latitude,
216                                                 net->longitude,
217                                                 net->altitude
218                                                   * SG_METER_TO_FEET );
219         cur_fdm_state->_set_Euler_Angles( net->phi,
220                                           net->theta,
221                                           net->psi );
222         cur_fdm_state->_set_Euler_Rates( net->phidot,
223                                          net->thetadot,
224                                          net->psidot );
225         cur_fdm_state->_set_V_calibrated_kts( net->vcas );
226         cur_fdm_state->_set_Climb_Rate( net->climb_rate );
227         cur_fdm_state->_set_Velocities_Local( net->v_north,
228                                               net->v_east,
229                                               net->v_down );
230         cur_fdm_state->_set_Accels_Pilot_Body( net->A_X_pilot,
231                                                net->A_Y_pilot,
232                                                net->A_Z_pilot );
233
234         for ( i = 0; i < net->num_engines; ++i ) {
235             SGPropertyNode *node = fgGetNode( "engines/engine", i, true );
236             
237             // node->setBoolValue("running", t->isRunning());
238             // node->setBoolValue("cranking", t->isCranking());
239             
240             // cout << net->eng_state[i] << endl;
241             if ( net->eng_state[i] == 0 ) {
242                 node->setBoolValue( "cranking", false );
243                 node->setBoolValue( "running", false );
244             } else if ( net->eng_state[i] == 1 ) {
245                 node->setBoolValue( "cranking", true );
246                 node->setBoolValue( "running", false );
247             } else if ( net->eng_state[i] == 2 ) {
248                 node->setBoolValue( "cranking", false );
249                 node->setBoolValue( "running", true );
250             }
251
252             node->setDoubleValue( "rpm", net->rpm[i] );
253             node->setDoubleValue( "fuel-flow-gph", net->fuel_flow[i] );
254             node->setDoubleValue( "egt-degf", net->EGT[i] );
255             node->setDoubleValue( "oil-temperature-degf", net->oil_temp[i] );
256             node->setDoubleValue( "oil-pressure-psi", net->oil_px[i] );         
257         }
258
259         for (i = 0; i < net->num_tanks; ++i ) {
260             SGPropertyNode * node
261                 = fgGetNode("/consumables/fuel/tank", i, true);
262             node->setDoubleValue("level-gal_us", net->fuel_quantity[i] );
263         }
264
265         for (i = 0; i < net->num_wheels; ++i ) {
266             SGPropertyNode * node
267                 = fgGetNode("/gear/gear", i, true);
268             node->setDoubleValue("wow", net->wow[i] );
269         }
270
271         fgSetDouble("/surface-positions/flap-pos-norm", net->flap_deflection);
272         SGPropertyNode * node = fgGetNode("/controls", true);
273         fgSetDouble("/surface-positions/elevator-pos-norm", 
274                     node->getDoubleValue( "elevator" ));
275         fgSetDouble("/surface-positions/rudder-pos-norm", 
276                     node->getDoubleValue( "rudder" ));
277         fgSetDouble("/surface-positions/left-aileron-pos-norm", 
278                     node->getDoubleValue( "aileron" ));
279         fgSetDouble("/surface-positions/right-aileron-pos-norm", 
280                     -node->getDoubleValue( "aileron" ));
281
282         /* these are ignored for now  ... */
283         /*
284         if ( net->cur_time ) {
285             fgSetLong("/sim/time/cur-time-override", net->cur_time);
286         }
287
288         globals->set_warp( net->warp );
289         last_warp = net->warp;
290         */
291     } else {
292         SG_LOG( SG_IO, SG_ALERT, "Error: version mismatch in net2global()" );
293         SG_LOG( SG_IO, SG_ALERT,
294                 "\tread " << net->version << " need " << FG_NET_FDM_VERSION );
295         SG_LOG( SG_IO, SG_ALERT,
296                 "\tsomeone needs to upgrade net_fdm.hxx and recompile." );
297     }
298 }
299
300
301 FGExternalNet::FGExternalNet( double dt, string host, int dop, int dip, int cp )
302 {
303 //     set_delta_t( dt );
304
305     valid = true;
306
307     data_in_port = dip;
308     data_out_port = dop;
309     cmd_port = cp;
310     fdm_host = host;
311
312     /////////////////////////////////////////////////////////
313     // Setup client udp connection (sends data to remote fdm)
314
315     if ( ! data_client.open( false ) ) {
316         SG_LOG( SG_FLIGHT, SG_ALERT, "Error opening client data channel" );
317         valid = false;
318     }
319
320     // fire and forget
321     data_client.setBlocking( false );
322
323     if ( data_client.connect( fdm_host.c_str(), data_out_port ) == -1 ) {
324         printf("error connecting to %s:%d\n", fdm_host.c_str(), data_out_port);
325         valid = false;
326     }
327
328     /////////////////////////////////////////////////////////
329     // Setup server udp connection (for receiving data)
330
331     if ( ! data_server.open( false ) ) {
332         SG_LOG( SG_FLIGHT, SG_ALERT, "Error opening client server channel" );
333         valid = false;
334     }
335
336     // disable blocking
337     data_server.setBlocking( false );
338
339     // allowed to read from a broadcast addr
340     // data_server.setBroadcast( true );
341
342     // if we bind to fdm_host = "" then we accept messages from
343     // anyone.
344     if ( data_server.bind( "", data_in_port ) == -1 ) {
345         printf("error binding to port %d\n", data_in_port);
346         valid = false;
347     }
348 }
349
350
351 FGExternalNet::~FGExternalNet() {
352     data_client.close();
353     data_server.close();
354 }
355
356
357 // Initialize the ExternalNet flight model, dt is the time increment
358 // for each subsequent iteration through the EOM
359 void FGExternalNet::init() {
360     // cout << "FGExternalNet::init()" << endl;
361
362     // Explicitly call the superclass's
363     // init method first.
364     common_init();
365
366     double lon = fgGetDouble( "/position/longitude-deg" );
367     double lat = fgGetDouble( "/position/latitude-deg" );
368     double ground = fgGetDouble( "/environment/ground-elevation-m" );
369     double heading = fgGetDouble("/orientation/heading-deg");
370
371     char cmd[256];
372
373     sprintf( cmd, "/longitude-deg?value=%.8f", lon );
374     new HTTPClient( fdm_host.c_str(), cmd_port, cmd );
375 //     cout << "before loop()" << endl;
376     netChannel::loop(0);
377 //     cout << "here" << endl;
378
379     sprintf( cmd, "/latitude-deg?value=%.8f", lat );
380     new HTTPClient( fdm_host.c_str(), cmd_port, cmd );
381     netChannel::loop(0);
382
383     sprintf( cmd, "/ground-m?value=%.8f", ground );
384     new HTTPClient( fdm_host.c_str(), cmd_port, cmd );
385     netChannel::loop(0);
386
387     sprintf( cmd, "/heading-deg?value=%.8f", heading );
388     new HTTPClient( fdm_host.c_str(), cmd_port, cmd );
389     netChannel::loop(0);
390
391     SG_LOG( SG_IO, SG_INFO, "before sending reset command." );
392
393     sprintf( cmd, "/reset?value=ground" );
394     new HTTPClient( fdm_host.c_str(), cmd_port, cmd );
395     netChannel::loop(0);
396
397     SG_LOG( SG_IO, SG_INFO, "Remote FDM init() finished." );
398 }
399
400
401 // Run an iteration of the EOM.
402 void FGExternalNet::update( double dt ) {
403     int length;
404     int result;
405
406     if (is_suspended())
407       return;
408
409     // Send control positions to remote fdm
410     length = sizeof(ctrls);
411     global2raw( &ctrls );
412     if ( data_client.send( (char *)(& ctrls), length, 0 ) != length ) {
413         SG_LOG( SG_IO, SG_DEBUG, "Error writing data." );
414     } else {
415         SG_LOG( SG_IO, SG_DEBUG, "wrote control data." );
416     }
417
418     // Read next set of FDM data (blocking enabled to maintain 'sync')
419     length = sizeof(fdm);
420     while ( (result = data_server.recv( (char *)(& fdm), length, 0)) >= 0 ) {
421         SG_LOG( SG_IO, SG_DEBUG, "Success reading data." );
422         net2global( &fdm );
423     }
424 }