]> git.mxchange.org Git - flightgear.git/blobdiff - src/Network/props.cxx
Interim windows build fix
[flightgear.git] / src / Network / props.cxx
index 7240d5cb236bcd360f1371ce348e909479bc0df2..5574b3402203cbffa0e0acef92d089339d43a274 100644 (file)
@@ -3,6 +3,7 @@
 //
 // Written by Curtis Olson, started September 2000.
 // Modified by Bernie Bright, May 2002.
+// Modified by Jean-Paul Anceaux, Dec 2015.
 //
 // Copyright (C) 2000  Curtis L. Olson - http://www.flightgear.org/~curt
 //
 #include <simgear/misc/strutils.hxx>
 #include <simgear/props/props.hxx>
 #include <simgear/props/props_io.hxx>
+#include <simgear/structure/exception.hxx>
 
 #include <sstream>
 #include <iostream>
 #include <errno.h>
 
 #include <Main/globals.hxx>
-#include <Main/viewmgr.hxx>
+#include <Viewer/viewmgr.hxx>
 
 #include <simgear/io/sg_netChat.hxx>
 
+#include <simgear/misc/strutils.hxx>
+
 #include "props.hxx"
 
+#include <map>
+#include <vector>
+#include <string>
+
+#include <boost/foreach.hpp>
+
 using std::stringstream;
 using std::ends;
 
@@ -55,7 +65,7 @@ using std::endl;
  * Props connection class.
  * This class represents a connection to props client.
  */
-class PropsChannel : public simgear::NetChat
+class PropsChannel : public simgear::NetChat, public SGPropertyChangeListener
 {
     simgear::NetBuffer buffer;
 
@@ -75,6 +85,7 @@ public:
      * Constructor.
      */
     PropsChannel();
+    ~PropsChannel();
 
     /**
      * Append incoming data to our request buffer.
@@ -89,10 +100,37 @@ public:
      */
     void foundTerminator();
 
+    // callback for registered listeners (subscriptions)
+    void valueChanged(SGPropertyNode *node);
 private:
+
+    typedef string_list ParameterList;
+
     inline void node_not_found_error( const string& s ) const {
         throw "node '" + s + "' not found";
     }
+
+    void error(std::string msg) {  // wrapper: prints errors to STDERR and to the telnet client
+           push( msg.c_str() ); push( getTerminator() );
+           SG_LOG(SG_NETWORK, SG_ALERT, __FILE__<<"@" << __LINE__ <<" in " << __FUNCTION__ <<":"<< msg.c_str() << std::endl);
+    }
+
+
+    bool check_args(const ParameterList &tok, const unsigned int num, const char* func) {
+           if (tok.size()-1 < num) {
+                   error(string("Error:Wrong argument count for:")+string(func) );
+                   return false;
+           }
+           return true;
+    }
+
+    std::vector<SGPropertyNode_ptr> _listeners;
+    typedef void (PropsChannel::*TelnetCallback) (const ParameterList&);
+    std::map<std::string, TelnetCallback> callback_map;
+
+    // callback implementations:
+    void subscribe(const ParameterList &p);
+    void unsubscribe(const ParameterList &p);
 };
 
 /**
@@ -104,6 +142,62 @@ PropsChannel::PropsChannel()
       mode(PROMPT)
 {
     setTerminator( "\r\n" );
+    callback_map["subscribe"]  =       &PropsChannel::subscribe;
+    callback_map["unsubscribe"]        =       &PropsChannel::unsubscribe;
+}
+
+PropsChannel::~PropsChannel() {
+  // clean up all registered listeners
+    BOOST_FOREACH(SGPropertyNode_ptr l, _listeners) {
+    l->removeChangeListener( this  );
+ }
+}
+
+void PropsChannel::subscribe(const ParameterList &param) {
+       if (! check_args(param,1,"subscribe")) return;
+
+       std::string command = param[0];
+       const char* p = param[1].c_str();
+       if (!p) return;
+
+  //SG_LOG(SG_GENERAL, SG_ALERT, p << std::endl);
+  push( command.c_str() ); push ( " " );
+  push( p );
+  push( getTerminator() );
+
+  SGPropertyNode *n = globals->get_props()->getNode( p,true );
+       if ( n->isTied() ) {
+               error("Error:Tied properties cannot register listeners");
+               return;
+       }
+
+       if (n) {
+    n->addChangeListener( this );
+        _listeners.push_back( n ); // housekeeping, save for deletion in dtor later on
+  } else {
+                error("listener could not be added");
+  }
+}
+
+void PropsChannel::unsubscribe(const ParameterList &param) {
+  if (!check_args(param,1,"unsubscribe")) return;
+
+  try {
+   SGPropertyNode *n = globals->get_props()->getNode( param[1].c_str() );
+   if (n)
+    n->removeChangeListener( this );
+  } catch (sg_exception&) {
+         error("Error:Listener could not be removed");
+  }
+}
+
+
+//TODO: provide support for different types of subscriptions MODES ? (child added/removed, thesholds, min/max)
+  void PropsChannel::valueChanged(SGPropertyNode* ptr) {
+  //SG_LOG(SG_GENERAL, SG_ALERT, __FILE__<< "@"<<__LINE__ << ":" << __FUNCTION__ << std::endl);
+  std::stringstream response;
+  response << ptr->getPath(true) << "=" <<  ptr->getStringValue() << getTerminator(); //TODO: use hashes, echo several properties at once
+  push( response.str().c_str() );
 }
 
 /**
@@ -160,7 +254,7 @@ PropsChannel::foundTerminator()
     const char* cmd = buffer.getData();
     SG_LOG( SG_IO, SG_INFO, "processing command = \"" << cmd << "\"" );
 
-    vector<string> tokens = simgear::strutils::split( cmd );
+    ParameterList tokens = simgear::strutils::split( cmd );
 
     SGPropertyNode* node = globals->get_props()->getNode( path.c_str() );
 
@@ -386,7 +480,85 @@ PropsChannel::foundTerminator()
                 mode = DATA;
             } else if ( command == "prompt" ) {
                 mode = PROMPT;
-            } else {
+            } else if (callback_map.find(command) != callback_map.end() ) {
+                  TelnetCallback t = callback_map[ command ];
+                  if (t)
+                          (this->*t) (tokens);
+                  else
+                          error("No matching callback found for command:"+command);
+           }
+      else if ( command == "seti" ) {
+        string value, tmp;
+        if (tokens.size() == 3) {
+              node->getNode( tokens[1].c_str(), true )
+                ->setIntValue(atoi(tokens[2].c_str()));
+          }
+          if ( mode == PROMPT ) {
+              tmp = tokens[1].c_str();
+              tmp += " " + tokens[2];
+              tmp += " (";
+              tmp += getValueTypeString( node->getNode( tokens[1].c_str() ) );
+              tmp += ")";
+              push( tmp.c_str() );
+              push( getTerminator() );
+          }
+      }
+      else if ( command == "setd" || command == "setf") {
+          string value, tmp;
+          if (tokens.size() == 3) {
+            node->getNode( tokens[1].c_str(), true )
+                ->setDoubleValue(atof(tokens[2].c_str()));
+          }
+          if ( mode == PROMPT ) {
+              tmp = tokens[1].c_str();
+              tmp += " ";
+              tmp += tokens[2].c_str();
+              tmp += " (";
+              tmp += getValueTypeString( node->getNode( tokens[1].c_str() ) );
+              tmp += ")";
+              push( tmp.c_str() );
+              push( getTerminator() );
+          }
+      }
+      else if ( command == "setb" ) {
+          string tmp, value;
+          if (tokens.size() == 3) {
+            if (tokens[2] == "false" || tokens[2] == "0") {
+              node->getNode( tokens[1].c_str(), true )
+                  ->setBoolValue(false);
+              value = " False ";
+            }
+            if (tokens[2] == "true" || tokens[2] == "1"){
+              node->getNode( tokens[1].c_str(), true )
+                  ->setBoolValue(true);
+              value = " True ";
+            }
+            if ( mode == PROMPT ) {
+                tmp = tokens[1].c_str();
+                tmp += value;
+                tmp += " (";
+                tmp += getValueTypeString( node->getNode( tokens[1].c_str() ) );
+                tmp += ")";
+                push( tmp.c_str() );
+                push( getTerminator() );
+            }
+
+          }
+     }
+      else if ( command == "del" ) {
+          string tmp;
+          if (tokens.size() == 3){
+             node->getNode( tokens[1].c_str(), true )->removeChild(tokens[2].c_str(),0);
+          }
+          if ( mode == PROMPT ) {
+              tmp = "Delete ";
+              tmp += tokens[1].c_str();
+              tmp += tokens[2];
+              push( tmp.c_str() );
+              push( getTerminator() );
+          }
+      }
+           else {
                 const char* msg = "\
 Valid commands are:\r\n\
 \r\n\
@@ -400,7 +572,14 @@ prompt             switch to interactive mode (default)\r\n\
 pwd                display your current path\r\n\
 quit               terminate connection\r\n\
 run <command>      run built in command\r\n\
-set <var> <val>    set <var> to a new <val>\r\n";
+set <var> <val>    set String <var> to a new <val>\r\n\
+setb <var> <val>   set Bool <var> to a new <val> only work with the foling value 0, 1, true, false\r\n\
+setd <var> <val>   set Double <var> to a new <val>\r\n\
+setf <var> <val>   alias for setd\r\n\
+seti <var> <val>   set Int <var> to a new <val>\r\n\
+del <var> <nod>    delete <nod> in <var>\r\n\
+subscribe <var>           subscribe to property changes \r\n\
+unscubscribe <var>  unscubscribe from property changes (var must be the property name/path used by subscribe)\r\n";
                 push( msg );
             }
         }
@@ -450,7 +629,6 @@ FGProps::FGProps( const vector<string>& tokens )
     } else {
         throw FGProtocolConfigError( "FGProps: incorrect number of configuration arguments" );
     }
-    printf( "Property server started on port %d\n", port );
 }
 
 /**
@@ -473,9 +651,28 @@ FGProps::open()
         return false;
     }
 
-    simgear::NetChannel::open();
-    simgear::NetChannel::bind( "", port );
-    simgear::NetChannel::listen( 5 );
+    if (!simgear::NetChannel::open())
+    {
+        SG_LOG( SG_IO, SG_ALERT, "FGProps: Failed to open network socket.");
+        return false;
+    }
+
+    int err = simgear::NetChannel::bind( "", port );
+    if (err)
+    {
+        SG_LOG( SG_IO, SG_ALERT, "FGProps: Failed to open port #" << port << " - the port is already used (error " << err << ").");
+        return false;
+    }
+
+    err = simgear::NetChannel::listen( 5 );
+    if (err)
+    {
+        SG_LOG( SG_IO, SG_ALERT, "FGProps: Failed to listen on port #" << port << "(error " << err << ").");
+        return false;
+    }
+
+    poller.addChannel(this);
+
     SG_LOG( SG_IO, SG_INFO, "Props server started on port " << port );
 
     set_enabled( true );
@@ -498,7 +695,7 @@ FGProps::close()
 bool
 FGProps::process()
 {
-    simgear::NetChannel::poll();
+    poller.poll();
     return true;
 }
 
@@ -514,4 +711,5 @@ FGProps::handleAccept()
             << addr.getHost() << ":" << addr.getPort() );
     PropsChannel* channel = new PropsChannel();
     channel->setHandle( handle );
+    poller.addChannel( channel );
 }