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