]> git.mxchange.org Git - flightgear.git/blob - src/FDM/ExternalNet.cxx
A couple fixes to the network fdm interface.
[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->prop_advance[i] = node->getDoubleValue( "propeller-pitch", 0.0 );
81         raw->magnetos[i] = node->getIntValue( "magnetos", 0 );
82         if ( i == 0 ) {
83           // cout << "Magnetos -> " << node->getIntValue( "magnetos", 0 );
84         }
85         raw->starter[i] = node->getBoolValue( "starter", false );
86         if ( i == 0 ) {
87           // cout << " Starter -> " << node->getIntValue( "stater", false )
88           //      << endl;
89         }
90     }
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 ) {
94             raw->fuel_selector[i]
95                 = node->getChild("fuel-selector", i)->getDoubleValue();
96         } else {
97             raw->fuel_selector[i] = false;
98         }
99     }
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 ) {
103             raw->brake[i]
104                 = node->getChild("brakes", i)->getDoubleValue();
105         } else {
106             raw->brake[i] = 0.0;
107         }
108     }
109     raw->hground = fgGetDouble( "/environment/ground-elevation-m" );
110     raw->magvar = fgGetDouble("/environment/magnetic-variation-deg");
111     raw->speedup = fgGetInt("/sim/speed-up");
112
113     // convert to network byte order
114     raw->version = htonl(raw->version);
115     htond(raw->aileron);
116     htond(raw->elevator);
117     htond(raw->elevator_trim);
118     htond(raw->rudder);
119     htond(raw->flaps);
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]);
126     }
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]);
130     }
131     raw->num_tanks = htonl(raw->num_tanks);
132     for ( i = 0; i < FGRawCtrls::FG_MAX_WHEELS; ++i ) {
133         htond(raw->brake[i]);
134     }
135     raw->num_wheels = htonl(raw->num_wheels);
136     htond(raw->hground);
137     htond(raw->magvar);
138     raw->speedup = htonl(raw->speedup);
139 }
140
141
142 static void net2global( FGNetFDM *net ) {
143     int i;
144
145     // Convert to the net buffer from network format
146     net->version = ntohl(net->version);
147
148     htond(net->longitude);
149     htond(net->latitude);
150     htond(net->altitude);
151     htond(net->phi);
152     htond(net->theta);
153     htond(net->psi);
154
155     htond(net->phidot);
156     htond(net->thetadot);
157     htond(net->psidot);
158     htond(net->vcas);
159     htond(net->climb_rate);
160
161     htond(net->A_X_pilot);
162     htond(net->A_Y_pilot);
163     htond(net->A_Z_pilot);
164
165     net->num_engines = htonl(net->num_engines);
166     for ( i = 0; i < net->num_engines; ++i ) {
167         htonl(net->eng_state[i]);
168         htond(net->rpm[i]);
169         htond(net->fuel_flow[i]);
170         htond(net->EGT[i]);
171         htond(net->oil_temp[i]);
172         htond(net->oil_px[i]);
173     }
174
175     net->num_tanks = htonl(net->num_tanks);
176     for ( i = 0; i < net->num_tanks; ++i ) {
177         htond(net->fuel_quantity[i]);
178     }
179
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);
183
184     net->cur_time = ntohl(net->cur_time);
185     net->warp = ntohl(net->warp);
186     htond(net->visibility);
187
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()
191         //      << endl;
192         cur_fdm_state->_updateGeodeticPosition( net->latitude,
193                                                 net->longitude,
194                                                 net->altitude
195                                                   * SG_METER_TO_FEET );
196         cur_fdm_state->_set_Euler_Angles( net->phi,
197                                           net->theta,
198                                           net->psi );
199         cur_fdm_state->_set_Euler_Rates( net->phidot,
200                                          net->thetadot,
201                                          net->psidot );
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,
205                                                net->A_Y_pilot,
206                                                net->A_Z_pilot );
207
208         for ( i = 0; i < net->num_engines; ++i ) {
209             SGPropertyNode *node = fgGetNode( "engines/engine", i, true );
210             
211             // node->setBoolValue("running", t->isRunning());
212             // node->setBoolValue("cranking", t->isCranking());
213             
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 );
224             }
225
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] );         
231         }
232
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] );
237         }
238
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] );
243         }
244
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" ));
255
256         /* these are ignored for now  ... */
257         /*
258         if ( net->cur_time ) {
259             fgSetLong("/sim/time/cur-time-override", net->cur_time);
260         }
261
262         globals->set_warp( net->warp );
263         last_warp = net->warp;
264         */
265     } else {
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." );
271     }
272 }
273
274
275 FGExternalNet::FGExternalNet( double dt, string host, int dop, int dip, int cp )
276 {
277 //     set_delta_t( dt );
278
279     valid = true;
280
281     data_in_port = dip;
282     data_out_port = dop;
283     cmd_port = cp;
284     fdm_host = host;
285
286     /////////////////////////////////////////////////////////
287     // Setup client udp connection (sends data to remote fdm)
288
289     if ( ! data_client.open( false ) ) {
290         SG_LOG( SG_FLIGHT, SG_ALERT, "Error opening client data channel" );
291         valid = false;
292     }
293
294     // fire and forget
295     data_client.setBlocking( false );
296
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);
299         valid = false;
300     }
301
302     /////////////////////////////////////////////////////////
303     // Setup server udp connection (for receiving data)
304
305     if ( ! data_server.open( false ) ) {
306         SG_LOG( SG_FLIGHT, SG_ALERT, "Error opening client server channel" );
307         valid = false;
308     }
309
310     // we want to block for incoming data in order to syncronize frame
311     // rates.
312     data_server.setBlocking( false /* don't block while testing */ );
313     // data_server.setBlocking( true /* don't block while testing */ );
314
315     // if we bind to fdm_host = "" then we accept messages from
316     // anyone.
317     if ( data_server.bind( fdm_host.c_str(), data_in_port ) == -1 ) {
318         printf("error binding to port %d\n", data_in_port);
319         valid = false;
320     }
321 }
322
323
324 FGExternalNet::~FGExternalNet() {
325     data_client.close();
326     data_server.close();
327 }
328
329
330 // Initialize the ExternalNet flight model, dt is the time increment
331 // for each subsequent iteration through the EOM
332 void FGExternalNet::init() {
333     // cout << "FGExternalNet::init()" << endl;
334
335     // Explicitly call the superclass's
336     // init method first.
337     common_init();
338
339     double lon = fgGetDouble( "/position/longitude-deg" );
340     double lat = fgGetDouble( "/position/latitude-deg" );
341     double ground = fgGetDouble( "/environment/ground-elevation-m" );
342     double heading = fgGetDouble("/orientation/heading-deg");
343
344     char cmd[256];
345
346     sprintf( cmd, "/longitude-deg?value=%.8f", lon );
347     new HTTPClient( fdm_host.c_str(), cmd_port, cmd );
348 //     cout << "before loop()" << endl;
349     netChannel::loop(0);
350 //     cout << "here" << endl;
351
352     sprintf( cmd, "/latitude-deg?value=%.8f", lat );
353     new HTTPClient( fdm_host.c_str(), cmd_port, cmd );
354     netChannel::loop(0);
355
356     sprintf( cmd, "/ground-m?value=%.8f", ground );
357     new HTTPClient( fdm_host.c_str(), cmd_port, cmd );
358     netChannel::loop(0);
359
360     sprintf( cmd, "/heading-deg?value=%.8f", heading );
361     new HTTPClient( fdm_host.c_str(), cmd_port, cmd );
362     netChannel::loop(0);
363
364     sprintf( cmd, "/reset?value=ground" );
365     new HTTPClient( fdm_host.c_str(), cmd_port, cmd );
366     netChannel::loop(0);
367 }
368
369
370 // Run an iteration of the EOM.
371 void FGExternalNet::update( double dt ) {
372     int length;
373     int result;
374
375     if (is_suspended())
376       return;
377
378     // Send control positions to remote fdm
379     length = sizeof(ctrls);
380     global2raw( &ctrls );
381     if ( data_client.send( (char *)(& ctrls), length, 0 ) != length ) {
382         SG_LOG( SG_IO, SG_ALERT, "Error writing data." );
383     } else {
384         SG_LOG( SG_IO, SG_ALERT, "wrote control data." );
385     }
386
387     // Read next set of FDM data (blocking enabled to maintain 'sync')
388     length = sizeof(fdm);
389     while ( (result = data_server.recv( (char *)(& fdm), length, 0)) >= 0 ) {
390         SG_LOG( SG_IO, SG_DEBUG, "Success reading data." );
391         net2global( &fdm );
392     }
393 }