1 // ExternalPipe.cxx -- a "pipe" interface to an external flight dynamics model
3 // Written by Curtis Olson, started March 2003.
5 // Copyright (C) 2003 Curtis L. Olson - http://www.flightgear.org/~curt
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.
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.
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.
28 # include <sys/types.h> // mkfifo() umask()
29 # include <sys/stat.h> // mkfifo() umask()
30 # include <errno.h> // perror()
31 # include <unistd.h> // unlink()
34 #include <stdio.h> // FILE*, fopen(), fread(), fwrite(), et. al.
36 #include <simgear/debug/logstream.hxx>
37 #include <simgear/io/lowlevel.hxx> // endian tests
38 #include <simgear/misc/strutils.hxx> // split()
40 #include <Main/fg_props.hxx>
41 #include <Network/native_ctrls.hxx>
42 #include <Network/native_fdm.hxx>
43 #include <Scenery/scenery.hxx>
45 #include "ExternalPipe.hxx"
48 static const int MAX_BUF = 32768;
50 FGExternalPipe::FGExternalPipe( double dt, string name, string protocol ) {
53 last_cg_offset = -9999.9;
55 buf = new char[MAX_BUF];
57 // clear property request list
58 property_names.clear();
62 fifo_name_1 = name + "1";
63 fifo_name_2 = name + "2";
65 SG_LOG( SG_IO, SG_ALERT, "ExternalPipe Inited with " << name );
67 // Make the named pipe
70 result = mkfifo( fifo_name_1.c_str(), 0644 );
72 SG_LOG( SG_IO, SG_ALERT, "Unable to create named pipe: "
74 perror( "ExternalPipe()" );
76 result = mkfifo( fifo_name_2.c_str(), 0644 );
78 SG_LOG( SG_IO, SG_ALERT, "Unable to create named pipe: "
80 perror( "ExternalPipe()" );
83 pd1 = fopen( fifo_name_1.c_str(), "w" );
85 SG_LOG( SG_IO, SG_ALERT, "Unable to open named pipe: " << fifo_name_1 );
88 pd2 = fopen( fifo_name_2.c_str(), "r" );
90 SG_LOG( SG_IO, SG_ALERT, "Unable to open named pipe: " << fifo_name_2 );
97 if ( _protocol != "binary" && _protocol != "property" ) {
98 SG_LOG( SG_IO, SG_ALERT, "Constructor(): Unknown ExternalPipe protocol."
99 << " Must be 'binary' or 'property'."
100 << " (assuming binary)" );
101 _protocol = "binary";
106 FGExternalPipe::~FGExternalPipe() {
109 SG_LOG( SG_IO, SG_INFO, "Closing up the ExternalPipe." );
114 result = fclose( pd1 );
116 SG_LOG( SG_IO, SG_ALERT, "Unable to close named pipe: "
118 perror( "~FGExternalPipe()" );
120 result = fclose( pd2 );
122 SG_LOG( SG_IO, SG_ALERT, "Unable to close named pipe: "
124 perror( "~FGExternalPipe()" );
130 static int write_binary( char cmd_type, FILE *pd, char *cmd, int len ) {
132 char *buf = new char[len + 3];
134 // write 2 byte command length + command type + command
135 unsigned char hi = (len + 1) / 256;
136 unsigned char lo = (len + 1) - (hi * 256);
138 // cout << "len = " << len << " hi = " << (int)hi << " lo = "
139 // << (int)lo << endl;
145 memcpy( buf + 3, cmd, len );
147 if ( cmd_type == '1' ) {
149 for ( int i = 0; i < len + 3; ++i ) {
152 cout << "' (" << cmd << ")" << endl;
153 } else if ( cmd_type == '2' ) {
154 cout << "writing controls packet" << endl;
156 cout << "writing unknown command?" << endl;
159 // for ( int i = 0; i < len + 3; ++i ) {
160 // cout << " " << (int)buf[i];
164 int result = fwrite( buf, len + 3, 1, pd );
166 perror( "write_binary()" );
167 SG_LOG( SG_IO, SG_ALERT, "Write error to named pipe: " << pd );
169 // cout << "wrote " << len + 3 << " bytes." << endl;
180 static int write_property( FILE *pd, char *cmd ) {
181 int len = strlen(cmd);
184 char *buf = new char[len + 1];
186 memcpy( buf, cmd, len );
189 int result = fwrite( buf, len + 1, 1, pd );
190 if ( result == len + 1 ) {
191 perror( "write_property()" );
192 SG_LOG( SG_IO, SG_ALERT, "Write error to named pipe: " << pd );
194 // cout << "wrote " << len + 1 << " bytes." << endl;
205 // Wrapper for the ExternalPipe flight model initialization. dt is
206 // the time increment for each subsequent iteration through the EOM
207 void FGExternalPipe::init() {
208 // Explicitly call the superclass's
209 // init method first.
212 if ( _protocol == "binary" ) {
214 } else if ( _protocol == "property" ) {
217 SG_LOG( SG_IO, SG_ALERT, "Init(): Unknown ExternalPipe protocol."
218 << " Must be 'binary' or 'property'."
219 << " (assuming binary)" );
224 // Initialize the ExternalPipe flight model using the binary protocol,
225 // dt is the time increment for each subsequent iteration through the
227 void FGExternalPipe::init_binary() {
228 cout << "init_binary()" << endl;
230 double lon = fgGetDouble( "/sim/presets/longitude-deg" );
231 double lat = fgGetDouble( "/sim/presets/latitude-deg" );
232 double alt = fgGetDouble( "/sim/presets/altitude-ft" );
233 double ground = get_Runway_altitude_m();
234 double heading = fgGetDouble("/sim/presets/heading-deg");
235 double speed = fgGetDouble( "/sim/presets/airspeed-kt" );
236 double weight = fgGetDouble( "/sim/aircraft-weight-lbs" );
237 double cg_offset = fgGetDouble( "/sim/aircraft-cg-offset-inches" );
242 sprintf( cmd, "longitude-deg=%.8f", lon );
243 result = write_binary( '1', pd1, cmd, strlen(cmd) );
245 sprintf( cmd, "latitude-deg=%.8f", lat );
246 result = write_binary( '1', pd1, cmd, strlen(cmd) );
248 sprintf( cmd, "altitude-ft=%.8f", alt );
249 result = write_binary( '1', pd1, cmd, strlen(cmd) );
251 sprintf( cmd, "ground-m=%.8f", ground );
252 result = write_binary( '1', pd1, cmd, strlen(cmd) );
254 sprintf( cmd, "speed-kts=%.8f", speed );
255 result = write_binary( '1', pd1, cmd, strlen(cmd) );
257 sprintf( cmd, "heading-deg=%.8f", heading );
258 result = write_binary( '1', pd1, cmd, strlen(cmd) );
260 if ( weight > 1000.0 ) {
261 sprintf( cmd, "aircraft-weight-lbs=%.2f", weight );
262 result = write_binary( '1', pd1, cmd, strlen(cmd) );
264 last_weight = weight;
266 if ( cg_offset > -5.0 || cg_offset < 5.0 ) {
267 sprintf( cmd, "aircraft-cg-offset-inches=%.2f", cg_offset );
268 result = write_binary( '1', pd1, cmd, strlen(cmd) );
270 last_cg_offset = cg_offset;
272 SG_LOG( SG_IO, SG_ALERT, "before sending reset command." );
274 if( fgGetBool("/sim/presets/onground") ) {
275 sprintf( cmd, "reset=ground" );
277 sprintf( cmd, "reset=air" );
279 result = write_binary( '1', pd1, cmd, strlen(cmd) );
283 SG_LOG( SG_IO, SG_ALERT, "Remote FDM init() finished." );
287 // Initialize the ExternalPipe flight model using the property
288 // protocol, dt is the time increment for each subsequent iteration
290 void FGExternalPipe::init_property() {
291 cout << "init_property()" << endl;
293 double lon = fgGetDouble( "/sim/presets/longitude-deg" );
294 double lat = fgGetDouble( "/sim/presets/latitude-deg" );
295 double alt = fgGetDouble( "/sim/presets/altitude-ft" );
296 double ground = get_Runway_altitude_m();
297 double heading = fgGetDouble("/sim/presets/heading-deg");
298 double speed = fgGetDouble( "/sim/presets/airspeed-kt" );
299 double weight = fgGetDouble( "/sim/aircraft-weight-lbs" );
300 double cg_offset = fgGetDouble( "/sim/aircraft-cg-offset-inches" );
305 sprintf( cmd, "init longitude-deg=%.8f", lon );
306 result = write_property( pd1, cmd );
308 sprintf( cmd, "init latitude-deg=%.8f", lat );
309 result = write_property( pd1, cmd );
311 sprintf( cmd, "init altitude-ft=%.8f", alt );
312 result = write_property( pd1, cmd );
314 sprintf( cmd, "init ground-m=%.8f", ground );
315 result = write_property( pd1, cmd );
317 sprintf( cmd, "init speed-kts=%.8f", speed );
318 result = write_property( pd1, cmd );
320 sprintf( cmd, "init heading-deg=%.8f", heading );
321 result = write_property( pd1, cmd );
323 if ( weight > 1000.0 ) {
324 sprintf( cmd, "init aircraft-weight-lbs=%.2f", weight );
325 result = write_property( pd1, cmd );
327 last_weight = weight;
329 if ( cg_offset > -5.0 || cg_offset < 5.0 ) {
330 sprintf( cmd, "init aircraft-cg-offset-inches=%.2f", cg_offset );
331 result = write_property( pd1, cmd );
333 last_cg_offset = cg_offset;
335 SG_LOG( SG_IO, SG_ALERT, "before sending reset command." );
337 if( fgGetBool("/sim/presets/onground") ) {
338 sprintf( cmd, "reset ground" );
340 sprintf( cmd, "reset air" );
342 result = write_property( pd1, cmd );
346 SG_LOG( SG_IO, SG_ALERT, "Remote FDM init() finished." );
350 // Wrapper for the ExternalPipe update routines. dt is the time
351 // increment for each subsequent iteration through the EOM
352 void FGExternalPipe::update( double dt ) {
353 if ( _protocol == "binary" ) {
355 } else if ( _protocol == "property" ) {
358 SG_LOG( SG_IO, SG_ALERT, "Init(): Unknown ExternalPipe protocol."
359 << " Must be 'binary' or 'property'."
360 << " (assuming binary)" );
365 // Run an iteration of the EOM.
366 void FGExternalPipe::update_binary( double dt ) {
368 SG_LOG( SG_IO, SG_INFO, "Start FGExternalPipe::udpate_binary()" );
373 if ( is_suspended() ) {
377 int iterations = _calc_multiloop(dt);
379 double weight = fgGetDouble( "/sim/aircraft-weight-lbs" );
380 static double last_weight = 0.0;
381 if ( fabs( weight - last_weight ) > 0.01 ) {
383 sprintf( cmd, "aircraft-weight-lbs=%.2f", weight );
384 result = write_binary( '1', pd1, cmd, strlen(cmd) );
386 last_weight = weight;
388 double cg_offset = fgGetDouble( "/sim/aircraft-cg-offset-inches" );
389 if ( fabs( cg_offset - last_cg_offset ) > 0.01 ) {
391 sprintf( cmd, "aircraft-cg-offset-inches=%.2f", cg_offset );
392 result = write_binary( '1', pd1, cmd, strlen(cmd) );
394 last_cg_offset = cg_offset;
396 // Send control positions to remote fdm
397 length = sizeof(ctrls);
398 FGProps2NetCtrls( &ctrls, true, false );
400 *((int *)ptr) = iterations;
401 // cout << "iterations = " << iterations << endl;
403 memcpy( ptr, (char *)(&ctrls), length );
404 cout << "writing control structure, size = "
405 << length + sizeof(int) << endl;
407 result = write_binary( '2', pd1, buf, length + sizeof(int) );
411 length = sizeof(fdm);
412 cout << "about to read fdm data from remote fdm." << endl;
413 result = fread( (char *)(& fdm), length, 1, pd2 );
415 SG_LOG( SG_IO, SG_ALERT, "Read error from named pipe: "
416 << fifo_name_2 << " expected 1 item, but got " << result );
418 cout << " read successful." << endl;
420 FGNetFDM2Props( &fdm, false );
425 // Process remote FDM "set" commands
426 static void process_set_command( const string_list &tokens ) {
427 if ( tokens[1] == "geodetic_position" ) {
428 double lat_rad = atof( tokens[2].c_str() );
429 double lon_rad = atof( tokens[3].c_str() );
430 double alt_m = atof( tokens[4].c_str() );
431 cur_fdm_state->_updateGeodeticPosition( lat_rad, lon_rad,
432 alt_m * SG_METER_TO_FEET );
434 double agl_m = alt_m - cur_fdm_state->get_Runway_altitude_m();
435 cur_fdm_state->_set_Altitude_AGL( agl_m * SG_METER_TO_FEET );
436 } else if ( tokens[1] == "euler_angles" ) {
437 double phi_rad = atof( tokens[2].c_str() );
438 double theta_rad = atof( tokens[3].c_str() );
439 double psi_rad = atof( tokens[4].c_str() );
440 cur_fdm_state->_set_Euler_Angles( phi_rad, theta_rad, psi_rad );
441 } else if ( tokens[1] == "euler_rates" ) {
442 double phidot = atof( tokens[2].c_str() );
443 double thetadot = atof( tokens[3].c_str() );
444 double psidot = atof( tokens[4].c_str() );
445 cur_fdm_state->_set_Euler_Rates( phidot, thetadot, psidot );
446 } else if ( tokens[1] == "alpha" ) {
447 cur_fdm_state->_set_Alpha( atof(tokens[2].c_str()) );
448 } else if ( tokens[1] == "beta" ) {
449 cur_fdm_state->_set_Beta( atof(tokens[2].c_str()) );
452 cur_fdm_state->_set_V_calibrated_kts( net->vcas );
453 cur_fdm_state->_set_Climb_Rate( net->climb_rate );
454 cur_fdm_state->_set_Velocities_Local( net->v_north,
457 cur_fdm_state->_set_Velocities_Wind_Body( net->v_wind_body_north,
458 net->v_wind_body_east,
459 net->v_wind_body_down );
461 cur_fdm_state->_set_Accels_Pilot_Body( net->A_X_pilot,
466 fgSetString( tokens[1].c_str(), tokens[2].c_str() );
471 // Run an iteration of the EOM.
472 void FGExternalPipe::update_property( double dt ) {
473 // cout << "update_property()" << endl;
476 // SG_LOG( SG_IO, SG_INFO, "Start FGExternalPipe::udpate()" );
481 if ( is_suspended() ) {
485 int iterations = _calc_multiloop(dt);
487 double weight = fgGetDouble( "/sim/aircraft-weight-lbs" );
488 static double last_weight = 0.0;
489 if ( fabs( weight - last_weight ) > 0.01 ) {
490 sprintf( cmd, "init aircraft-weight-lbs=%.2f", weight );
491 result = write_property( pd1, cmd );
493 last_weight = weight;
495 double cg_offset = fgGetDouble( "/sim/aircraft-cg-offset-inches" );
496 if ( fabs( cg_offset - last_cg_offset ) > 0.01 ) {
497 sprintf( cmd, "init aircraft-cg-offset-inches=%.2f", cg_offset );
498 result = write_property( pd1, cmd );
500 last_cg_offset = cg_offset;
502 // Send requested property values to fdm
503 for ( unsigned int i = 0; i < nodes.size(); i++ ) {
504 sprintf( cmd, "set %s %s", property_names[i].c_str(),
505 nodes[i]->getStringValue() );
506 // cout << " sending " << cmd << endl;
507 result = write_property( pd1, cmd );
510 sprintf( cmd, "update %d", iterations );
511 write_property( pd1, cmd );
516 // cout << "ready to read fdm response" << endl;
519 if ( fgets( cmd, 256, pd2 ) == NULL ) {
520 cout << "Error reading data" << endl;
522 // cout << " read " << strlen(cmd) << " bytes" << endl;
525 // chop trailing newline
526 cmd[strlen(cmd)-1] = '\0';
528 // cout << cmd << endl;
529 string_list tokens = simgear::strutils::split( cmd, " " );
531 if ( tokens[0] == "request" ) {
532 // save the long form name
533 property_names.push_back( tokens[1] );
535 // now do the property name lookup and cache the pointer
536 SGPropertyNode *node = fgGetNode( tokens[1].c_str() );
537 if ( node == NULL ) {
538 // node doesn't exist so create with requested type
539 node = fgGetNode( tokens[1].c_str(), true );
540 if ( tokens[2] == "bool" ) {
541 node->setBoolValue(true);
542 } else if ( tokens[2] == "int" ) {
543 node->setIntValue(0);
544 } else if ( tokens[2] == "double" ) {
545 node->setDoubleValue(0.0);
546 } else if ( tokens[2] == "string" ) {
547 node->setStringValue("");
549 cout << "Unknown data type: " << tokens[2]
550 << " for " << tokens[1] << endl;
553 nodes.push_back( node );
554 } else if ( tokens[0] == "set" ) {
555 process_set_command( tokens );
556 } else if ( tokens[0] == "update" ) {
559 cout << "unknown command = " << cmd << endl;