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