2 // Property server class.
4 // Written by Curtis Olson, started September 2000.
5 // Modified by Bernie Bright, May 2002.
7 // Copyright (C) 2000 Curtis L. Olson - http://www.flightgear.org/~curt
9 // This program is free software; you can redistribute it and/or
10 // modify it under the terms of the GNU General Public License as
11 // published by the Free Software Foundation; either version 2 of the
12 // License, or (at your option) any later version.
14 // This program is distributed in the hope that it will be useful, but
15 // WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 // General Public License for more details.
19 // You should have received a copy of the GNU General Public License
20 // along with this program; if not, write to the Free Software
21 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
30 #include <simgear/compiler.h>
31 #include <simgear/debug/logstream.hxx>
32 #include <simgear/structure/commands.hxx>
33 #include <simgear/misc/strutils.hxx>
34 #include <simgear/props/props.hxx>
35 #include <simgear/props/props_io.hxx>
36 #include <simgear/structure/exception.hxx>
42 #include <Main/globals.hxx>
43 #include <Viewer/viewmgr.hxx>
45 #include <simgear/io/sg_netChat.hxx>
47 #include <simgear/misc/strutils.hxx>
55 #include <boost/foreach.hpp>
57 using std::stringstream;
64 * Props connection class.
65 * This class represents a connection to props client.
67 class PropsChannel : public simgear::NetChat, public SGPropertyChangeListener
69 simgear::NetBuffer buffer;
72 * Current property node name.
90 * Append incoming data to our request buffer.
92 * @param s Character string to append to buffer
93 * @param n Number of characters to append.
95 void collectIncomingData( const char* s, int n );
98 * Process a complete request from the props client.
100 void foundTerminator();
102 // callback for registered listeners (subscriptions)
103 void valueChanged(SGPropertyNode *node);
106 typedef string_list ParameterList;
108 inline void node_not_found_error( const string& s ) const {
109 throw "node '" + s + "' not found";
112 void error(std::string msg) { // wrapper: prints errors to STDERR and to the telnet client
113 push( msg.c_str() ); push( getTerminator() );
114 SG_LOG(SG_NETWORK, SG_ALERT, __FILE__<<"@" << __LINE__ <<" in " << __FUNCTION__ <<":"<< msg.c_str() << std::endl);
118 bool check_args(const ParameterList &tok, const unsigned int num, const char* func) {
119 if (tok.size()-1 < num) {
120 error(string("Error:Wrong argument count for:")+string(func) );
126 std::vector<SGPropertyNode_ptr> _listeners;
127 typedef void (PropsChannel::*TelnetCallback) (const ParameterList&);
128 std::map<std::string, TelnetCallback> callback_map;
130 // callback implementations:
131 void subscribe(const ParameterList &p);
132 void unsubscribe(const ParameterList &p);
138 PropsChannel::PropsChannel()
143 setTerminator( "\r\n" );
144 callback_map["subscribe"] = &PropsChannel::subscribe;
145 callback_map["unsubscribe"] = &PropsChannel::unsubscribe;
148 PropsChannel::~PropsChannel() {
149 // clean up all registered listeners
150 BOOST_FOREACH(SGPropertyNode_ptr l, _listeners) {
151 l->removeChangeListener( this );
155 void PropsChannel::subscribe(const ParameterList ¶m) {
156 if (! check_args(param,1,"subscribe")) return;
158 std::string command = param[0];
159 const char* p = param[1].c_str();
162 //SG_LOG(SG_GENERAL, SG_ALERT, p << std::endl);
163 push( command.c_str() ); push ( " " );
165 push( getTerminator() );
167 SGPropertyNode *n = globals->get_props()->getNode( p,true );
169 error("Error:Tied properties cannot register listeners");
174 n->addChangeListener( this );
175 _listeners.push_back( n ); // housekeeping, save for deletion in dtor later on
177 error("listener could not be added");
181 void PropsChannel::unsubscribe(const ParameterList ¶m) {
182 if (!check_args(param,1,"unsubscribe")) return;
185 SGPropertyNode *n = globals->get_props()->getNode( param[1].c_str() );
187 n->removeChangeListener( this );
188 } catch (sg_exception&) {
189 error("Error:Listener could not be removed");
194 //TODO: provide support for different types of subscriptions MODES ? (child added/removed, thesholds, min/max)
195 void PropsChannel::valueChanged(SGPropertyNode* ptr) {
196 //SG_LOG(SG_GENERAL, SG_ALERT, __FILE__<< "@"<<__LINE__ << ":" << __FUNCTION__ << std::endl);
197 std::stringstream response;
198 response << ptr->getPath(true) << "=" << ptr->getStringValue() << getTerminator(); //TODO: use hashes, echo several properties at once
199 push( response.str().c_str() );
206 PropsChannel::collectIncomingData( const char* s, int n )
208 buffer.append( s, n );
211 // return a human readable form of the value "type"
213 getValueTypeString( const SGPropertyNode *node )
215 using namespace simgear;
224 props::Type type = node->getType();
225 if ( type == props::UNSPECIFIED ) {
226 result = "unspecified";
227 } else if ( type == props::NONE ) {
229 } else if ( type == props::BOOL ) {
231 } else if ( type == props::INT ) {
233 } else if ( type == props::LONG ) {
235 } else if ( type == props::FLOAT ) {
237 } else if ( type == props::DOUBLE ) {
239 } else if ( type == props::STRING ) {
251 PropsChannel::foundTerminator()
253 const char* cmd = buffer.getData();
254 SG_LOG( SG_IO, SG_INFO, "processing command = \"" << cmd << "\"" );
256 ParameterList tokens = simgear::strutils::split( cmd );
258 SGPropertyNode* node = globals->get_props()->getNode( path.c_str() );
261 if (!tokens.empty()) {
262 string command = tokens[0];
264 if (command == "ls") {
265 SGPropertyNode* dir = node;
266 if (tokens.size() == 2) {
267 if (tokens[1][0] == '/') {
268 dir = globals->get_props()->getNode( tokens[1].c_str() );
273 dir = globals->get_props()->getNode( s.c_str() );
277 node_not_found_error( tokens[1] );
281 for (int i = 0; i < dir->nChildren(); i++) {
282 SGPropertyNode * child = dir->getChild(i);
283 string line = child->getDisplayName(true);
285 if ( child->nChildren() > 0 ) {
288 if (mode == PROMPT) {
289 string value = child->getStringValue();
290 line += " =\t'" + value + "'\t(";
291 line += getValueTypeString( child );
296 line += getTerminator();
297 push( line.c_str() );
299 } else if ( command == "dump" ) {
301 if ( tokens.size() <= 1 ) {
302 writeProperties( buf, node );
303 buf << ends; // null terminate the string
304 push( buf.str().c_str() );
305 push( getTerminator() );
307 SGPropertyNode *child = node->getNode( tokens[1].c_str() );
309 writeProperties ( buf, child );
310 buf << ends; // null terminate the string
311 push( buf.str().c_str() );
312 push( getTerminator() );
314 node_not_found_error( tokens[1] );
318 else if ( command == "cd" ) {
319 if (tokens.size() == 2) {
320 SGPropertyNode* child = node->getNode( tokens[1].c_str() );
323 path = node->getPath();
325 node_not_found_error( tokens[1] );
328 } else if ( command == "pwd" ) {
329 string pwd = node->getPath();
335 push( getTerminator() );
336 } else if ( command == "get" || command == "show" ) {
337 if ( tokens.size() == 2 ) {
339 string value = node->getStringValue ( tokens[1].c_str(), "" );
340 if ( mode == PROMPT ) {
345 tmp += getValueTypeString(
346 node->getNode( tokens[1].c_str() ) );
352 push( getTerminator() );
354 } else if ( command == "set" ) {
355 if ( tokens.size() >= 2 ) {
357 for (unsigned int i = 2; i < tokens.size(); i++) {
362 node->getNode( tokens[1].c_str(), true )
363 ->setStringValue(value.c_str());
365 if ( mode == PROMPT ) {
366 // now fetch and write out the new value as confirmation
368 value = node->getStringValue ( tokens[1].c_str(), "" );
369 tmp = tokens[1] + " = '" + value + "' (";
370 tmp += getValueTypeString( node->getNode( tokens[1].c_str() ) );
373 push( getTerminator() );
376 } else if ( command == "reinit" ) {
377 if ( tokens.size() == 2 ) {
380 for ( unsigned int i = 1; i < tokens.size(); ++i ) {
381 cout << "props: adding subsystem = " << tokens[i] << endl;
382 SGPropertyNode *node = args.getNode("subsystem", i-1, true);
383 node->setStringValue( tokens[i].c_str() );
385 if ( !globals->get_commands()
386 ->execute( "reinit", &args) )
388 SG_LOG( SG_NETWORK, SG_ALERT,
389 "Command " << tokens[1] << " failed.");
390 if ( mode == PROMPT ) {
393 push( getTerminator() );
396 if ( mode == PROMPT ) {
397 tmp += "<completed>";
399 push( getTerminator() );
403 } else if ( command == "run" ) {
405 if ( tokens.size() >= 2 ) {
407 if ( tokens[1] == "reinit" ) {
408 for ( unsigned int i = 2; i < tokens.size(); ++i ) {
409 cout << "props: adding subsystem = " << tokens[i]
412 = args.getNode("subsystem", i-2, true);
413 node->setStringValue( tokens[i].c_str() );
415 } else if ( tokens[1] == "set-sea-level-air-temp-degc" ) {
416 for ( unsigned int i = 2; i < tokens.size(); ++i ) {
417 cout << "props: set-sl command = " << tokens[i]
420 = args.getNode("temp-degc", i-2, true);
421 node->setStringValue( tokens[i].c_str() );
423 } else if ( tokens[1] == "set-outside-air-temp-degc" ) {
424 for ( unsigned int i = 2; i < tokens.size(); ++i ) {
425 cout << "props: set-oat command = " << tokens[i]
428 = args.getNode("temp-degc", i-2, true);
429 node->setStringValue( tokens[i].c_str() );
431 } else if ( tokens[1] == "timeofday" ) {
432 for ( unsigned int i = 2; i < tokens.size(); ++i ) {
433 cout << "props: time of day command = " << tokens[i]
436 = args.getNode("timeofday", i-2, true);
437 node->setStringValue( tokens[i].c_str() );
439 } else if ( tokens[1] == "play-audio-message" ) {
440 if ( tokens.size() == 4 ) {
441 cout << "props: play audio message = " << tokens[2]
442 << " " << tokens[3] << endl;
443 SGPropertyNode *node;
444 node = args.getNode("path", 0, true);
445 node->setStringValue( tokens[2].c_str() );
446 node = args.getNode("file", 0, true);
447 node->setStringValue( tokens[3].c_str() );
450 if ( !globals->get_commands()
451 ->execute(tokens[1].c_str(), &args) )
453 SG_LOG( SG_NETWORK, SG_ALERT,
454 "Command " << tokens[1] << " failed.");
455 if ( mode == PROMPT ) {
458 push( getTerminator() );
461 if ( mode == PROMPT ) {
462 tmp += "<completed>";
464 push( getTerminator() );
468 if ( mode == PROMPT ) {
469 tmp += "no command specified";
471 push( getTerminator() );
474 } else if ( command == "quit" || command == "exit" ) {
478 } else if ( command == "data" ) {
480 } else if ( command == "prompt" ) {
482 } else if (callback_map.find(command) != callback_map.end() ) {
483 TelnetCallback t = callback_map[ command ];
487 error("No matching callback found for command:"+command);
491 Valid commands are:\r\n\
493 cd <dir> cd to a directory, '..' to move back\r\n\
494 data switch to raw data mode\r\n\
495 dump dump current state (in xml)\r\n\
496 get <var> show the value of a parameter\r\n\
497 help show this help message\r\n\
498 ls [<dir>] list directory\r\n\
499 prompt switch to interactive mode (default)\r\n\
500 pwd display your current path\r\n\
501 quit terminate connection\r\n\
502 run <command> run built in command\r\n\
503 set <var> <val> set <var> to a new <val>\r\n\
504 subscribe <var> subscribe to property changes \r\n\
505 unscubscribe <var> unscubscribe from property changes (var must be the property name/path used by subscribe)\r\n";
510 } catch ( const string& msg ) {
511 string error = "-ERR \"" + msg + "\"";
512 push( error.c_str() );
513 push( getTerminator() );
516 if ( mode == PROMPT ) {
517 string prompt = node->getPath();
518 if (prompt.empty()) {
522 push( prompt.c_str() );
531 FGProps::FGProps( const vector<string>& tokens )
535 // props,medium,direction,hz,hostname,port#,style
536 if (tokens.size() == 2) {
537 port = atoi( tokens[1].c_str() );
538 set_hz( 5 ); // default to processing requests @ 5Hz
539 } else if (tokens.size() == 7) {
542 int hz = strtol( tokens[3].c_str(), &endptr, 10 );
544 SG_LOG( SG_IO, SG_ALERT, "I/O poll frequency out of range" );
545 set_hz( 5 ); // default to processing requests @ 5Hz
547 SG_LOG( SG_IO, SG_INFO, "Setting I/O poll frequency to "
551 port = atoi( tokens[5].c_str() );
553 throw FGProtocolConfigError( "FGProps: incorrect number of configuration arguments" );
572 SG_LOG( SG_IO, SG_ALERT, "This shouldn't happen, but the channel "
573 << "is already in use, ignoring" );
577 if (!simgear::NetChannel::open())
579 SG_LOG( SG_IO, SG_ALERT, "FGProps: Failed to open network socket.");
583 int err = simgear::NetChannel::bind( "", port );
586 SG_LOG( SG_IO, SG_ALERT, "FGProps: Failed to open port #" << port << " - the port is already used (error " << err << ").");
590 err = simgear::NetChannel::listen( 5 );
593 SG_LOG( SG_IO, SG_ALERT, "FGProps: Failed to listen on port #" << port << "(error " << err << ").");
597 poller.addChannel(this);
599 SG_LOG( SG_IO, SG_INFO, "Props server started on port " << port );
611 SG_LOG( SG_IO, SG_INFO, "closing FGProps" );
629 FGProps::handleAccept()
631 simgear::IPAddress addr;
632 int handle = accept( &addr );
633 SG_LOG( SG_IO, SG_INFO, "Props server accepted connection from "
634 << addr.getHost() << ":" << addr.getPort() );
635 PropsChannel* channel = new PropsChannel();
636 channel->setHandle( handle );
637 poller.addChannel( channel );