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." );
293 // Initialize the ExternalPipe flight model using the property
294 // protocol, dt is the time increment for each subsequent iteration
296 void FGExternalPipe::init_property() {
297 cout << "init_property()" << endl;
299 double lon = fgGetDouble( "/sim/presets/longitude-deg" );
300 double lat = fgGetDouble( "/sim/presets/latitude-deg" );
301 double alt = fgGetDouble( "/sim/presets/altitude-ft" );
302 double ground = get_Runway_altitude_m();
303 double heading = fgGetDouble("/sim/presets/heading-deg");
304 double speed = fgGetDouble( "/sim/presets/airspeed-kt" );
305 double weight = fgGetDouble( "/sim/aircraft-weight-lbs" );
306 double cg_offset = fgGetDouble( "/sim/aircraft-cg-offset-inches" );
311 sprintf( cmd, "init longitude-deg=%.8f", lon );
312 result = write_property( pd1, cmd );
314 sprintf( cmd, "init latitude-deg=%.8f", lat );
315 result = write_property( pd1, cmd );
317 sprintf( cmd, "init altitude-ft=%.8f", alt );
318 result = write_property( pd1, cmd );
320 sprintf( cmd, "init ground-m=%.8f", ground );
321 result = write_property( pd1, cmd );
323 sprintf( cmd, "init speed-kts=%.8f", speed );
324 result = write_property( pd1, cmd );
326 sprintf( cmd, "init heading-deg=%.8f", heading );
327 result = write_property( pd1, cmd );
329 if ( weight > 1000.0 ) {
330 sprintf( cmd, "init aircraft-weight-lbs=%.2f", weight );
331 result = write_property( pd1, cmd );
333 last_weight = weight;
335 if ( cg_offset > -5.0 || cg_offset < 5.0 ) {
336 sprintf( cmd, "init aircraft-cg-offset-inches=%.2f", cg_offset );
337 result = write_property( pd1, cmd );
339 last_cg_offset = cg_offset;
341 SG_LOG( SG_IO, SG_ALERT, "before sending reset command." );
343 if( fgGetBool("/sim/presets/onground") ) {
344 sprintf( cmd, "reset ground" );
346 sprintf( cmd, "reset air" );
348 result = write_property( pd1, cmd );
352 SG_LOG( SG_IO, SG_ALERT, "Remote FDM init() finished." );
356 // Wrapper for the ExternalPipe update routines. dt is the time
357 // increment for each subsequent iteration through the EOM
358 void FGExternalPipe::update( double dt ) {
359 if ( _protocol == "binary" ) {
361 } else if ( _protocol == "property" ) {
364 SG_LOG( SG_IO, SG_ALERT, "Init(): Unknown ExternalPipe protocol."
365 << " Must be 'binary' or 'property'."
366 << " (assuming binary)" );
371 // Run an iteration of the EOM.
372 void FGExternalPipe::update_binary( double dt ) {
374 SG_LOG( SG_IO, SG_INFO, "Start FGExternalPipe::udpate_binary()" );
379 if ( is_suspended() ) {
383 int iterations = _calc_multiloop(dt);
385 double weight = fgGetDouble( "/sim/aircraft-weight-lbs" );
386 static double last_weight = 0.0;
387 if ( fabs( weight - last_weight ) > 0.01 ) {
389 sprintf( cmd, "aircraft-weight-lbs=%.2f", weight );
390 result = write_binary( '1', pd1, cmd, strlen(cmd) );
392 last_weight = weight;
394 double cg_offset = fgGetDouble( "/sim/aircraft-cg-offset-inches" );
395 if ( fabs( cg_offset - last_cg_offset ) > 0.01 ) {
397 sprintf( cmd, "aircraft-cg-offset-inches=%.2f", cg_offset );
398 result = write_binary( '1', pd1, cmd, strlen(cmd) );
400 last_cg_offset = cg_offset;
402 // Send control positions to remote fdm
403 length = sizeof(ctrls);
404 FGProps2NetCtrls( &ctrls, true, false );
406 *((int *)ptr) = iterations;
407 // cout << "iterations = " << iterations << endl;
409 memcpy( ptr, (char *)(&ctrls), length );
410 // cout << "writing control structure, size = "
411 // << length + sizeof(int) << endl;
413 result = write_binary( '2', pd1, buf, length + sizeof(int) );
417 length = sizeof(fdm);
418 // cout << "about to read fdm data from remote fdm." << endl;
419 result = fread( (char *)(& fdm), length, 1, pd2 );
421 SG_LOG( SG_IO, SG_ALERT, "Read error from named pipe: "
422 << fifo_name_2 << " expected 1 item, but got " << result );
424 // cout << " read successful." << endl;
425 FGNetFDM2Props( &fdm, false );
431 // Process remote FDM "set" commands
433 void FGExternalPipe::process_set_command( const string_list &tokens ) {
434 if ( tokens[1] == "geodetic_position" ) {
435 double lat_rad = atof( tokens[2].c_str() );
436 double lon_rad = atof( tokens[3].c_str() );
437 double alt_m = atof( tokens[4].c_str() );
438 _updateGeodeticPosition( lat_rad, lon_rad,
439 alt_m * SG_METER_TO_FEET );
441 double agl_m = alt_m - get_Runway_altitude_m();
442 _set_Altitude_AGL( agl_m * SG_METER_TO_FEET );
443 } else if ( tokens[1] == "euler_angles" ) {
444 double phi_rad = atof( tokens[2].c_str() );
445 double theta_rad = atof( tokens[3].c_str() );
446 double psi_rad = atof( tokens[4].c_str() );
447 _set_Euler_Angles( phi_rad, theta_rad, psi_rad );
448 } else if ( tokens[1] == "euler_rates" ) {
449 double phidot = atof( tokens[2].c_str() );
450 double thetadot = atof( tokens[3].c_str() );
451 double psidot = atof( tokens[4].c_str() );
452 _set_Euler_Rates( phidot, thetadot, psidot );
453 } else if ( tokens[1] == "ned" ) {
454 double north_fps = atof( tokens[2].c_str() );
455 double east_fps = atof( tokens[3].c_str() );
456 double down_fps = atof( tokens[4].c_str() );
457 _set_Velocities_Local( north_fps, east_fps, down_fps );
458 } else if ( tokens[1] == "alpha" ) {
459 _set_Alpha( atof(tokens[2].c_str()) );
460 } else if ( tokens[1] == "beta" ) {
461 _set_Beta( atof(tokens[2].c_str()) );
464 _set_V_calibrated_kts( net->vcas );
465 _set_Climb_Rate( net->climb_rate );
466 _set_Velocities_Local( net->v_north,
469 _set_Velocities_Wind_Body( net->v_wind_body_north,
470 net->v_wind_body_east,
471 net->v_wind_body_down );
473 _set_Accels_Pilot_Body( net->A_X_pilot,
478 fgSetString( tokens[1].c_str(), tokens[2].c_str() );
483 // Run an iteration of the EOM.
484 void FGExternalPipe::update_property( double dt ) {
485 // cout << "update_property()" << endl;
488 // SG_LOG( SG_IO, SG_INFO, "Start FGExternalPipe::udpate()" );
493 if ( is_suspended() ) {
497 int iterations = _calc_multiloop(dt);
499 double weight = fgGetDouble( "/sim/aircraft-weight-lbs" );
500 static double last_weight = 0.0;
501 if ( fabs( weight - last_weight ) > 0.01 ) {
502 sprintf( cmd, "init aircraft-weight-lbs=%.2f", weight );
503 result = write_property( pd1, cmd );
505 last_weight = weight;
507 double cg_offset = fgGetDouble( "/sim/aircraft-cg-offset-inches" );
508 if ( fabs( cg_offset - last_cg_offset ) > 0.01 ) {
509 sprintf( cmd, "init aircraft-cg-offset-inches=%.2f", cg_offset );
510 result = write_property( pd1, cmd );
512 last_cg_offset = cg_offset;
514 // Send requested property values to fdm
515 for ( unsigned int i = 0; i < nodes.size(); i++ ) {
516 sprintf( cmd, "set %s %s", property_names[i].c_str(),
517 nodes[i]->getStringValue() );
518 // cout << " sending " << cmd << endl;
519 result = write_property( pd1, cmd );
522 sprintf( cmd, "update %d", iterations );
523 write_property( pd1, cmd );
528 // cout << "ready to read fdm response" << endl;
531 if ( fgets( cmd, 256, pd2 ) == NULL ) {
532 cout << "Error reading data" << endl;
534 // cout << " read " << strlen(cmd) << " bytes" << endl;
535 // cout << cmd << endl;
538 // chop trailing newline
539 cmd[strlen(cmd)-1] = '\0';
541 // cout << cmd << endl;
542 string_list tokens = simgear::strutils::split( cmd, " " );
544 if ( tokens[0] == "request" ) {
545 // save the long form name
546 property_names.push_back( tokens[1] );
548 // now do the property name lookup and cache the pointer
549 SGPropertyNode *node = fgGetNode( tokens[1].c_str() );
550 if ( node == NULL ) {
551 // node doesn't exist so create with requested type
552 node = fgGetNode( tokens[1].c_str(), true );
553 if ( tokens[2] == "bool" ) {
554 node->setBoolValue(false);
555 } else if ( tokens[2] == "int" ) {
556 node->setIntValue(0);
557 } else if ( tokens[2] == "double" ) {
558 node->setDoubleValue(0.0);
559 } else if ( tokens[2] == "string" ) {
560 node->setStringValue("");
562 cout << "Unknown data type: " << tokens[2]
563 << " for " << tokens[1] << endl;
566 nodes.push_back( node );
567 } else if ( tokens[0] == "set" ) {
568 process_set_command( tokens );
569 } else if ( tokens[0] == "update" ) {
572 cout << "unknown command = " << cmd << endl;