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