]> git.mxchange.org Git - flightgear.git/blob - src/FDM/ExternalNet/ExternalNet.cxx
ExternalNet -> Updated to not repeat code from native_ctrls.
[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 #ifdef HAVE_CONFIG_H
24 #  include <config.h>
25 #endif
26
27 #include <simgear/debug/logstream.hxx>
28 #include <simgear/io/lowlevel.hxx> // endian tests
29
30 #include <Main/fg_props.hxx>
31 #include <Network/native_ctrls.hxx>
32
33 #include "ExternalNet.hxx"
34
35
36 // FreeBSD works better with this included last ... (?)
37 #if defined(WIN32) && !defined(__CYGWIN__)
38 #  include <windows.h>
39 #else
40 #  include <netinet/in.h>       // htonl() ntohl()
41 #endif
42
43 #if defined( linux )
44 #  include <sys/types.h>
45 #  include <sys/socket.h>
46 #endif
47
48 // The function htond is defined this way due to the way some
49 // processors and OSes treat floating point values.  Some will raise
50 // an exception whenever a "bad" floating point value is loaded into a
51 // floating point register.  Solaris is notorious for this, but then
52 // so is LynxOS on the PowerPC.  By translating the data in place,
53 // there is no need to load a FP register with the "corruped" floating
54 // point value.  By doing the BIG_ENDIAN test, I can optimize the
55 // routine for big-endian processors so it can be as efficient as
56 // possible
57 static void htond (double &x)   
58 {
59     if ( sgIsLittleEndian() ) {
60         int    *Double_Overlay;
61         int     Holding_Buffer;
62     
63         Double_Overlay = (int *) &x;
64         Holding_Buffer = Double_Overlay [0];
65     
66         Double_Overlay [0] = htonl (Double_Overlay [1]);
67         Double_Overlay [1] = htonl (Holding_Buffer);
68     } else {
69         return;
70     }
71 }
72
73
74 static void net2global( FGNetFDM *net ) {
75     int i;
76
77     // Convert to the net buffer from network format
78     net->version = ntohl(net->version);
79
80     htond(net->longitude);
81     htond(net->latitude);
82     htond(net->altitude);
83     htond(net->phi);
84     htond(net->theta);
85     htond(net->psi);
86
87     htond(net->phidot);
88     htond(net->thetadot);
89     htond(net->psidot);
90     htond(net->vcas);
91     htond(net->climb_rate);
92     htond(net->v_north);
93     htond(net->v_east);
94     htond(net->v_down);
95     htond(net->v_wind_body_north);
96     htond(net->v_wind_body_east);
97     htond(net->v_wind_body_down);
98     htond(net->stall_warning);
99
100     htond(net->A_X_pilot);
101     htond(net->A_Y_pilot);
102     htond(net->A_Z_pilot);
103
104     net->num_engines = htonl(net->num_engines);
105     for ( i = 0; i < net->num_engines; ++i ) {
106         htonl(net->eng_state[i]);
107         htond(net->rpm[i]);
108         htond(net->fuel_flow[i]);
109         htond(net->EGT[i]);
110         htond(net->oil_temp[i]);
111         htond(net->oil_px[i]);
112     }
113
114     net->num_tanks = htonl(net->num_tanks);
115     for ( i = 0; i < net->num_tanks; ++i ) {
116         htond(net->fuel_quantity[i]);
117     }
118
119     net->num_wheels = htonl(net->num_wheels);
120     // I don't need to convert the Wow flags, since they are one byte in size
121     htond(net->flap_deflection);
122
123     net->cur_time = ntohl(net->cur_time);
124     net->warp = ntohl(net->warp);
125     htond(net->visibility);
126
127     if ( net->version == FG_NET_FDM_VERSION ) {
128         // cout << "pos = " << net->longitude << " " << net->latitude << endl;
129         // cout << "sea level rad = " << cur_fdm_state->get_Sea_level_radius()
130         //      << endl;
131         cur_fdm_state->_updateGeodeticPosition( net->latitude,
132                                                 net->longitude,
133                                                 net->altitude
134                                                   * SG_METER_TO_FEET );
135         cur_fdm_state->_set_Euler_Angles( net->phi,
136                                           net->theta,
137                                           net->psi );
138         cur_fdm_state->_set_Euler_Rates( net->phidot,
139                                          net->thetadot,
140                                          net->psidot );
141         cur_fdm_state->_set_V_calibrated_kts( net->vcas );
142         cur_fdm_state->_set_Climb_Rate( net->climb_rate );
143         cur_fdm_state->_set_Velocities_Local( net->v_north,
144                                               net->v_east,
145                                               net->v_down );
146         cur_fdm_state->_set_Velocities_Wind_Body( net->v_wind_body_north,
147                                                   net->v_wind_body_east,
148                                                   net->v_wind_body_down );
149
150         fgSetDouble( "/sim/alarms/stall-warning", net->stall_warning );
151         cur_fdm_state->_set_Accels_Pilot_Body( net->A_X_pilot,
152                                                net->A_Y_pilot,
153                                                net->A_Z_pilot );
154
155         for ( i = 0; i < net->num_engines; ++i ) {
156             SGPropertyNode *node = fgGetNode( "engines/engine", i, true );
157             
158             // node->setBoolValue("running", t->isRunning());
159             // node->setBoolValue("cranking", t->isCranking());
160             
161             // cout << net->eng_state[i] << endl;
162             if ( net->eng_state[i] == 0 ) {
163                 node->setBoolValue( "cranking", false );
164                 node->setBoolValue( "running", false );
165             } else if ( net->eng_state[i] == 1 ) {
166                 node->setBoolValue( "cranking", true );
167                 node->setBoolValue( "running", false );
168             } else if ( net->eng_state[i] == 2 ) {
169                 node->setBoolValue( "cranking", false );
170                 node->setBoolValue( "running", true );
171             }
172
173             node->setDoubleValue( "rpm", net->rpm[i] );
174             node->setDoubleValue( "fuel-flow-gph", net->fuel_flow[i] );
175             node->setDoubleValue( "egt-degf", net->EGT[i] );
176             node->setDoubleValue( "oil-temperature-degf", net->oil_temp[i] );
177             node->setDoubleValue( "oil-pressure-psi", net->oil_px[i] );         
178         }
179
180         for (i = 0; i < net->num_tanks; ++i ) {
181             SGPropertyNode * node
182                 = fgGetNode("/consumables/fuel/tank", i, true);
183             node->setDoubleValue("level-gal_us", net->fuel_quantity[i] );
184         }
185
186         for (i = 0; i < net->num_wheels; ++i ) {
187             SGPropertyNode * node
188                 = fgGetNode("/gear/gear", i, true);
189             node->setDoubleValue("wow", net->wow[i] );
190         }
191
192         fgSetDouble("/surface-positions/flap-pos-norm", net->flap_deflection);
193         SGPropertyNode * node = fgGetNode("/controls", true);
194         fgSetDouble("/surface-positions/elevator-pos-norm", 
195                     node->getDoubleValue( "elevator" ));
196         fgSetDouble("/surface-positions/rudder-pos-norm", 
197                     node->getDoubleValue( "rudder" ));
198         fgSetDouble("/surface-positions/left-aileron-pos-norm", 
199                     node->getDoubleValue( "aileron" ));
200         fgSetDouble("/surface-positions/right-aileron-pos-norm", 
201                     -node->getDoubleValue( "aileron" ));
202
203         /* these are ignored for now  ... */
204         /*
205         if ( net->cur_time ) {
206             fgSetLong("/sim/time/cur-time-override", net->cur_time);
207         }
208
209         globals->set_warp( net->warp );
210         last_warp = net->warp;
211         */
212     } else {
213         SG_LOG( SG_IO, SG_ALERT, "Error: version mismatch in net2global()" );
214         SG_LOG( SG_IO, SG_ALERT,
215                 "\tread " << net->version << " need " << FG_NET_FDM_VERSION );
216         SG_LOG( SG_IO, SG_ALERT,
217                 "\tsomeone needs to upgrade net_fdm.hxx and recompile." );
218     }
219 }
220
221
222 FGExternalNet::FGExternalNet( double dt, string host, int dop, int dip, int cp )
223 {
224 //     set_delta_t( dt );
225
226     valid = true;
227
228     data_in_port = dip;
229     data_out_port = dop;
230     cmd_port = cp;
231     fdm_host = host;
232
233     /////////////////////////////////////////////////////////
234     // Setup client udp connection (sends data to remote fdm)
235
236     if ( ! data_client.open( false ) ) {
237         SG_LOG( SG_FLIGHT, SG_ALERT, "Error opening client data channel" );
238         valid = false;
239     }
240
241     // fire and forget
242     data_client.setBlocking( false );
243
244     if ( data_client.connect( fdm_host.c_str(), data_out_port ) == -1 ) {
245         printf("error connecting to %s:%d\n", fdm_host.c_str(), data_out_port);
246         valid = false;
247     }
248
249     /////////////////////////////////////////////////////////
250     // Setup server udp connection (for receiving data)
251
252     if ( ! data_server.open( false ) ) {
253         SG_LOG( SG_FLIGHT, SG_ALERT, "Error opening client server channel" );
254         valid = false;
255     }
256
257     // disable blocking
258     data_server.setBlocking( false );
259
260 #if defined( linux )
261     // set SO_REUSEADDR flag
262     int socket = data_server.getHandle();
263     int one = 1;
264     int result;
265     result = ::setsockopt( socket, SOL_SOCKET, SO_REUSEADDR,
266                            &one, sizeof(one) );
267 #endif
268
269     // allowed to read from a broadcast addr
270     // data_server.setBroadcast( true );
271
272     // if we bind to fdm_host = "" then we accept messages from
273     // anyone.
274     if ( data_server.bind( "", data_in_port ) == -1 ) {
275         printf("error binding to port %d\n", data_in_port);
276         valid = false;
277     }
278 }
279
280
281 FGExternalNet::~FGExternalNet() {
282     data_client.close();
283     data_server.close();
284 }
285
286
287 // Initialize the ExternalNet flight model, dt is the time increment
288 // for each subsequent iteration through the EOM
289 void FGExternalNet::init() {
290     // cout << "FGExternalNet::init()" << endl;
291
292     // Explicitly call the superclass's
293     // init method first.
294     common_init();
295
296     double lon = fgGetDouble( "/sim/presets/longitude-deg" );
297     double lat = fgGetDouble( "/sim/presets/latitude-deg" );
298     double alt = fgGetDouble( "/sim/presets/altitude-ft" );
299     double ground = fgGetDouble( "/environment/ground-elevation-m" );
300     double heading = fgGetDouble("/sim/presets/heading-deg");
301     double speed = fgGetDouble( "/sim/presets/airspeed-kt" );
302
303     char cmd[256];
304
305     HTTPClient *http;
306     sprintf( cmd, "/longitude-deg?value=%.8f", lon );
307     http = new HTTPClient( fdm_host.c_str(), cmd_port, cmd );
308     while ( !http->isDone(1000000) ) http->poll(0);
309     delete http;
310
311     sprintf( cmd, "/latitude-deg?value=%.8f", lat );
312     http = new HTTPClient( fdm_host.c_str(), cmd_port, cmd );
313     while ( !http->isDone(1000000) ) http->poll(0);
314     delete http;
315
316     sprintf( cmd, "/altitude-ft?value=%.8f", alt );
317     http = new HTTPClient( fdm_host.c_str(), cmd_port, cmd );
318     while ( !http->isDone(1000000) ) http->poll(0);
319     delete http;
320
321     sprintf( cmd, "/ground-m?value=%.8f", ground );
322     http = new HTTPClient( fdm_host.c_str(), cmd_port, cmd );
323     while ( !http->isDone(1000000) ) http->poll(0);
324     delete http;
325
326     sprintf( cmd, "/speed-kts?value=%.8f", speed );
327     http = new HTTPClient( fdm_host.c_str(), cmd_port, cmd );
328     while ( !http->isDone(1000000) ) http->poll(0);
329     delete http;
330
331     sprintf( cmd, "/heading-deg?value=%.8f", heading );
332     http = new HTTPClient( fdm_host.c_str(), cmd_port, cmd );
333     while ( !http->isDone(1000000) ) http->poll(0);
334     delete http;
335
336     SG_LOG( SG_IO, SG_INFO, "before sending reset command." );
337
338     if( fgGetBool("/sim/presets/onground") ) {
339       sprintf( cmd, "/reset?value=ground" );
340     } else {
341       sprintf( cmd, "/reset?value=air" );
342     }
343     http = new HTTPClient( fdm_host.c_str(), cmd_port, cmd );
344     while ( !http->isDone(1000000) ) http->poll(0);
345     delete http;
346
347     SG_LOG( SG_IO, SG_INFO, "Remote FDM init() finished." );
348 }
349
350
351 // Run an iteration of the EOM.
352 void FGExternalNet::update( double dt ) {
353     int length;
354     int result;
355
356     if (is_suspended())
357       return;
358
359     // Send control positions to remote fdm
360     length = sizeof(ctrls);
361     FGProps2NetCtrls( &ctrls );
362     if ( data_client.send( (char *)(& ctrls), length, 0 ) != length ) {
363         SG_LOG( SG_IO, SG_DEBUG, "Error writing data." );
364     } else {
365         SG_LOG( SG_IO, SG_DEBUG, "wrote control data." );
366     }
367
368     // Read next set of FDM data (blocking enabled to maintain 'sync')
369     length = sizeof(fdm);
370     while ( (result = data_server.recv( (char *)(& fdm), length, 0)) >= 0 ) {
371         SG_LOG( SG_IO, SG_DEBUG, "Success reading data." );
372         net2global( &fdm );
373     }
374 }