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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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()
35 #include <stdio.h> // FILE*, fopen(), fread(), fwrite(), et. al.
36 #include <iostream> // for cout, endl
38 #include <simgear/debug/logstream.hxx>
39 #include <simgear/io/lowlevel.hxx> // endian tests
40 #include <simgear/misc/strutils.hxx> // split()
42 #include <Main/fg_props.hxx>
43 #include <Network/native_ctrls.hxx>
44 #include <Network/native_fdm.hxx>
45 #include <Scenery/scenery.hxx>
47 #include "ExternalPipe.hxx"
52 static const int MAX_BUF = 32768;
54 FGExternalPipe::FGExternalPipe( double dt, string name, string protocol ) {
57 last_cg_offset = -9999.9;
59 buf = new char[MAX_BUF];
61 // clear property request list
62 property_names.clear();
66 fifo_name_1 = name + "1";
67 fifo_name_2 = name + "2";
69 SG_LOG( SG_IO, SG_ALERT, "ExternalPipe Inited with " << name );
71 // Make the named pipe
74 result = mkfifo( fifo_name_1.c_str(), 0644 );
76 SG_LOG( SG_IO, SG_ALERT, "Unable to create named pipe: "
78 perror( "ExternalPipe()" );
80 result = mkfifo( fifo_name_2.c_str(), 0644 );
82 SG_LOG( SG_IO, SG_ALERT, "Unable to create named pipe: "
84 perror( "ExternalPipe()" );
87 pd1 = fopen( fifo_name_1.c_str(), "w" );
89 SG_LOG( SG_IO, SG_ALERT, "Unable to open named pipe: " << fifo_name_1 );
92 pd2 = fopen( fifo_name_2.c_str(), "r" );
94 SG_LOG( SG_IO, SG_ALERT, "Unable to open named pipe: " << fifo_name_2 );
101 if ( _protocol != "binary" && _protocol != "property" ) {
102 SG_LOG( SG_IO, SG_ALERT, "Constructor(): Unknown ExternalPipe protocol."
103 << " Must be 'binary' or 'property'."
104 << " (assuming binary)" );
105 _protocol = "binary";
110 FGExternalPipe::~FGExternalPipe() {
113 SG_LOG( SG_IO, SG_INFO, "Closing up the ExternalPipe." );
118 result = fclose( pd1 );
120 SG_LOG( SG_IO, SG_ALERT, "Unable to close named pipe: "
122 perror( "~FGExternalPipe()" );
124 result = fclose( pd2 );
126 SG_LOG( SG_IO, SG_ALERT, "Unable to close named pipe: "
128 perror( "~FGExternalPipe()" );
134 static int write_binary( char cmd_type, FILE *pd, char *cmd, int len ) {
136 char *buf = new char[len + 3];
138 // write 2 byte command length + command type + command
139 unsigned char hi = (len + 1) / 256;
140 unsigned char lo = (len + 1) - (hi * 256);
142 // cout << "len = " << len << " hi = " << (int)hi << " lo = "
143 // << (int)lo << endl;
149 memcpy( buf + 3, cmd, len );
151 if ( cmd_type == '1' ) {
153 cout << (int)hi << " ";
154 cout << (int)lo << " '";
155 for ( int i = 2; i < len + 3; ++i ) {
158 cout << "' (" << cmd << ")" << endl;
159 } else if ( cmd_type == '2' ) {
160 // cout << "writing controls packet" << endl;
162 cout << "writing unknown command?" << endl;
165 // for ( int i = 0; i < len + 3; ++i ) {
166 // cout << " " << (int)buf[i];
170 int result = fwrite( buf, len + 3, 1, pd );
172 perror( "write_binary()" );
173 SG_LOG( SG_IO, SG_ALERT, "Write error to named pipe: " << pd );
175 // cout << "wrote " << len + 3 << " bytes." << endl;
186 static int write_property( FILE *pd, char *cmd ) {
187 int len = strlen(cmd);
190 char *buf = new char[len + 1];
192 memcpy( buf, cmd, len );
195 int result = fwrite( buf, len + 1, 1, pd );
196 if ( result == len + 1 ) {
197 perror( "write_property()" );
198 SG_LOG( SG_IO, SG_ALERT, "Write error to named pipe: " << pd );
200 // cout << "wrote " << len + 1 << " bytes." << endl;
211 // Wrapper for the ExternalPipe flight model initialization. dt is
212 // the time increment for each subsequent iteration through the EOM
213 void FGExternalPipe::init() {
214 // Explicitly call the superclass's
215 // init method first.
218 if ( _protocol == "binary" ) {
220 } else if ( _protocol == "property" ) {
223 SG_LOG( SG_IO, SG_ALERT, "Init(): Unknown ExternalPipe protocol."
224 << " Must be 'binary' or 'property'."
225 << " (assuming binary)" );
230 // Initialize the ExternalPipe flight model using the binary protocol,
231 // dt is the time increment for each subsequent iteration through the
233 void FGExternalPipe::init_binary() {
234 cout << "init_binary()" << endl;
236 double lon = fgGetDouble( "/sim/presets/longitude-deg" );
237 double lat = fgGetDouble( "/sim/presets/latitude-deg" );
238 double alt = fgGetDouble( "/sim/presets/altitude-ft" );
239 double ground = get_Runway_altitude_m();
240 double heading = fgGetDouble("/sim/presets/heading-deg");
241 double speed = fgGetDouble( "/sim/presets/airspeed-kt" );
242 double weight = fgGetDouble( "/sim/aircraft-weight-lbs" );
243 double cg_offset = fgGetDouble( "/sim/aircraft-cg-offset-inches" );
248 sprintf( cmd, "longitude-deg=%.8f", lon );
249 result = write_binary( '1', pd1, cmd, strlen(cmd) );
251 sprintf( cmd, "latitude-deg=%.8f", lat );
252 result = write_binary( '1', pd1, cmd, strlen(cmd) );
254 sprintf( cmd, "altitude-ft=%.8f", alt );
255 result = write_binary( '1', pd1, cmd, strlen(cmd) );
257 sprintf( cmd, "ground-m=%.8f", ground );
258 result = write_binary( '1', pd1, cmd, strlen(cmd) );
260 sprintf( cmd, "speed-kts=%.8f", speed );
261 result = write_binary( '1', pd1, cmd, strlen(cmd) );
263 sprintf( cmd, "heading-deg=%.8f", heading );
264 result = write_binary( '1', pd1, cmd, strlen(cmd) );
266 if ( weight > 1000.0 ) {
267 sprintf( cmd, "aircraft-weight-lbs=%.2f", weight );
268 result = write_binary( '1', pd1, cmd, strlen(cmd) );
270 last_weight = weight;
272 if ( cg_offset > -5.0 || cg_offset < 5.0 ) {
273 sprintf( cmd, "aircraft-cg-offset-inches=%.2f", cg_offset );
274 result = write_binary( '1', pd1, cmd, strlen(cmd) );
276 last_cg_offset = cg_offset;
278 SG_LOG( SG_IO, SG_ALERT, "before sending reset command." );
280 if( fgGetBool("/sim/presets/onground") ) {
281 sprintf( cmd, "reset=ground" );
283 sprintf( cmd, "reset=air" );
285 result = write_binary( '1', pd1, cmd, strlen(cmd) );
289 SG_LOG( SG_IO, SG_ALERT, "Remote FDM init() finished." );
291 (void) result; // ignore result
295 // Initialize the ExternalPipe flight model using the property
296 // protocol, dt is the time increment for each subsequent iteration
298 void FGExternalPipe::init_property() {
299 cout << "init_property()" << endl;
301 double lon = fgGetDouble( "/sim/presets/longitude-deg" );
302 double lat = fgGetDouble( "/sim/presets/latitude-deg" );
303 double alt = fgGetDouble( "/sim/presets/altitude-ft" );
304 double ground = get_Runway_altitude_m();
305 double heading = fgGetDouble("/sim/presets/heading-deg");
306 double speed = fgGetDouble( "/sim/presets/airspeed-kt" );
307 double weight = fgGetDouble( "/sim/aircraft-weight-lbs" );
308 double cg_offset = fgGetDouble( "/sim/aircraft-cg-offset-inches" );
313 sprintf( cmd, "init longitude-deg=%.8f", lon );
314 result = write_property( pd1, cmd );
316 sprintf( cmd, "init latitude-deg=%.8f", lat );
317 result = write_property( pd1, cmd );
319 sprintf( cmd, "init altitude-ft=%.8f", alt );
320 result = write_property( pd1, cmd );
322 sprintf( cmd, "init ground-m=%.8f", ground );
323 result = write_property( pd1, cmd );
325 sprintf( cmd, "init speed-kts=%.8f", speed );
326 result = write_property( pd1, cmd );
328 sprintf( cmd, "init heading-deg=%.8f", heading );
329 result = write_property( pd1, cmd );
331 if ( weight > 1000.0 ) {
332 sprintf( cmd, "init aircraft-weight-lbs=%.2f", weight );
333 result = write_property( pd1, cmd );
335 last_weight = weight;
337 if ( cg_offset > -5.0 || cg_offset < 5.0 ) {
338 sprintf( cmd, "init aircraft-cg-offset-inches=%.2f", cg_offset );
339 result = write_property( pd1, cmd );
341 last_cg_offset = cg_offset;
343 SG_LOG( SG_IO, SG_ALERT, "before sending reset command." );
345 if( fgGetBool("/sim/presets/onground") ) {
346 sprintf( cmd, "reset ground" );
348 sprintf( cmd, "reset air" );
350 result = write_property( pd1, cmd );
354 SG_LOG( SG_IO, SG_ALERT, "Remote FDM init() finished." );
356 (void) result; // ignore result
360 // Wrapper for the ExternalPipe update routines. dt is the time
361 // increment for each subsequent iteration through the EOM
362 void FGExternalPipe::update( double dt ) {
363 if ( _protocol == "binary" ) {
365 } else if ( _protocol == "property" ) {
368 SG_LOG( SG_IO, SG_ALERT, "Init(): Unknown ExternalPipe protocol."
369 << " Must be 'binary' or 'property'."
370 << " (assuming binary)" );
375 // Run an iteration of the EOM.
376 void FGExternalPipe::update_binary( double dt ) {
378 SG_LOG( SG_IO, SG_INFO, "Start FGExternalPipe::udpate_binary()" );
383 if ( is_suspended() ) {
387 int iterations = _calc_multiloop(dt);
389 double weight = fgGetDouble( "/sim/aircraft-weight-lbs" );
390 static double last_weight = 0.0;
391 if ( fabs( weight - last_weight ) > 0.01 ) {
393 sprintf( cmd, "aircraft-weight-lbs=%.2f", weight );
394 result = write_binary( '1', pd1, cmd, strlen(cmd) );
396 last_weight = weight;
398 double cg_offset = fgGetDouble( "/sim/aircraft-cg-offset-inches" );
399 if ( fabs( cg_offset - last_cg_offset ) > 0.01 ) {
401 sprintf( cmd, "aircraft-cg-offset-inches=%.2f", cg_offset );
402 result = write_binary( '1', pd1, cmd, strlen(cmd) );
404 last_cg_offset = cg_offset;
406 // Send control positions to remote fdm
407 length = sizeof(ctrls);
408 FGProps2NetCtrls( &ctrls, true, false );
410 *((int *)ptr) = iterations;
411 // cout << "iterations = " << iterations << endl;
413 memcpy( ptr, (char *)(&ctrls), length );
414 // cout << "writing control structure, size = "
415 // << length + sizeof(int) << endl;
417 result = write_binary( '2', pd1, buf, length + sizeof(int) );
421 length = sizeof(fdm);
422 // cout << "about to read fdm data from remote fdm." << endl;
423 result = fread( (char *)(& fdm), length, 1, pd2 );
425 SG_LOG( SG_IO, SG_ALERT, "Read error from named pipe: "
426 << fifo_name_2 << " expected 1 item, but got " << result );
428 // cout << " read successful." << endl;
429 FGNetFDM2Props( &fdm, false );
435 // Process remote FDM "set" commands
437 void FGExternalPipe::process_set_command( const string_list &tokens ) {
438 if ( tokens[1] == "geodetic_position" ) {
439 double lat_rad = atof( tokens[2].c_str() );
440 double lon_rad = atof( tokens[3].c_str() );
441 double alt_m = atof( tokens[4].c_str() );
442 _updateGeodeticPosition( lat_rad, lon_rad,
443 alt_m * SG_METER_TO_FEET );
445 double agl_m = alt_m - get_Runway_altitude_m();
446 _set_Altitude_AGL( agl_m * SG_METER_TO_FEET );
447 } else if ( tokens[1] == "euler_angles" ) {
448 double phi_rad = atof( tokens[2].c_str() );
449 double theta_rad = atof( tokens[3].c_str() );
450 double psi_rad = atof( tokens[4].c_str() );
451 _set_Euler_Angles( phi_rad, theta_rad, psi_rad );
452 } else if ( tokens[1] == "euler_rates" ) {
453 double phidot = atof( tokens[2].c_str() );
454 double thetadot = atof( tokens[3].c_str() );
455 double psidot = atof( tokens[4].c_str() );
456 _set_Euler_Rates( phidot, thetadot, psidot );
457 } else if ( tokens[1] == "ned" ) {
458 double north_fps = atof( tokens[2].c_str() );
459 double east_fps = atof( tokens[3].c_str() );
460 double down_fps = atof( tokens[4].c_str() );
461 _set_Velocities_Local( north_fps, east_fps, down_fps );
462 } else if ( tokens[1] == "alpha" ) {
463 _set_Alpha( atof(tokens[2].c_str()) );
464 } else if ( tokens[1] == "beta" ) {
465 _set_Beta( atof(tokens[2].c_str()) );
468 _set_V_calibrated_kts( net->vcas );
469 _set_Climb_Rate( net->climb_rate );
470 _set_Velocities_Local( net->v_north,
473 _set_Velocities_Body( net->v_body_u,
477 _set_Accels_Pilot_Body( net->A_X_pilot,
482 fgSetString( tokens[1].c_str(), tokens[2].c_str() );
487 // Run an iteration of the EOM.
488 void FGExternalPipe::update_property( double dt ) {
489 // cout << "update_property()" << endl;
492 // SG_LOG( SG_IO, SG_INFO, "Start FGExternalPipe::udpate()" );
497 if ( is_suspended() ) {
501 int iterations = _calc_multiloop(dt);
503 double weight = fgGetDouble( "/sim/aircraft-weight-lbs" );
504 static double last_weight = 0.0;
505 if ( fabs( weight - last_weight ) > 0.01 ) {
506 sprintf( cmd, "init aircraft-weight-lbs=%.2f", weight );
507 result = write_property( pd1, cmd );
509 last_weight = weight;
511 double cg_offset = fgGetDouble( "/sim/aircraft-cg-offset-inches" );
512 if ( fabs( cg_offset - last_cg_offset ) > 0.01 ) {
513 sprintf( cmd, "init aircraft-cg-offset-inches=%.2f", cg_offset );
514 result = write_property( pd1, cmd );
516 last_cg_offset = cg_offset;
518 // Send requested property values to fdm
519 for ( unsigned int i = 0; i < nodes.size(); i++ ) {
520 sprintf( cmd, "set %s %s", property_names[i].c_str(),
521 nodes[i]->getStringValue() );
522 // cout << " sending " << cmd << endl;
523 result = write_property( pd1, cmd );
526 sprintf( cmd, "update %d", iterations );
527 write_property( pd1, cmd );
532 // cout << "ready to read fdm response" << endl;
535 if ( fgets( cmd, 256, pd2 ) == NULL ) {
536 cout << "Error reading data" << endl;
538 // cout << " read " << strlen(cmd) << " bytes" << endl;
539 // cout << cmd << endl;
542 // chop trailing newline
543 cmd[strlen(cmd)-1] = '\0';
545 // cout << cmd << endl;
546 string_list tokens = simgear::strutils::split( cmd, " " );
548 if ( tokens[0] == "request" ) {
549 // save the long form name
550 property_names.push_back( tokens[1] );
552 // now do the property name lookup and cache the pointer
553 SGPropertyNode *node = fgGetNode( tokens[1].c_str() );
554 if ( node == NULL ) {
555 // node doesn't exist so create with requested type
556 node = fgGetNode( tokens[1].c_str(), true );
557 if ( tokens[2] == "bool" ) {
558 node->setBoolValue(false);
559 } else if ( tokens[2] == "int" ) {
560 node->setIntValue(0);
561 } else if ( tokens[2] == "double" ) {
562 node->setDoubleValue(0.0);
563 } else if ( tokens[2] == "string" ) {
564 node->setStringValue("");
566 cout << "Unknown data type: " << tokens[2]
567 << " for " << tokens[1] << endl;
570 nodes.push_back( node );
571 } else if ( tokens[0] == "set" ) {
572 process_set_command( tokens );
573 } else if ( tokens[0] == "update" ) {
576 cout << "unknown command = " << cmd << endl;
580 (void) result; // ignore result