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