//public XmlRpcValue stickaroundyouwench = null;
 public PendingConnection(XmlRpcClient client, Subscription s, string uri, XmlRpcValue chk)
 {
     this.client = client;
     this.chk = chk;
     parent = s;
     RemoteUri = uri;
 }
Example #2
0
            public List<String> publisher_update_task( String api, String topic, List<string> pub_uris) 
            {
                XmlRpcValue l = new XmlRpcValue();
                l.Set(0, api);
                l.Set(1, "");
                //XmlRpcValue ll = new XmlRpcValue();
                //l.Set(0, ll);
                for(int i = 0; i < pub_uris.Count; i++)
                {
                    XmlRpcValue ll = new XmlRpcValue(pub_uris[i]);
                    l.Set(i + 1, ll);
                }


                XmlRpcValue args = new XmlRpcValue();
                args.Set(0, "master");
                args.Set(1, topic);
                args.Set(2, l);
                       XmlRpcValue result = new XmlRpcValue(new XmlRpcValue(), new XmlRpcValue(), new XmlRpcValue(new XmlRpcValue())),
                        payload = new XmlRpcValue();

                 Ros_CSharp.master.host = api.Replace("http://","").Replace("/","").Split(':')[0];
                 Ros_CSharp.master.port =  int.Parse( api.Replace("http://", "").Replace("/", "").Split(':')[1]);
                 Ros_CSharp.master.execute("publisherUpdate", args, result, payload, false );
                
                return new List<string>(new []{"http://ERIC:1337"});
            }
Example #3
0
            public void service_update_task(String api, String service, String uri) 
            {
                XmlRpcValue args = new XmlRpcValue();
                args.Set(0, "master");
                args.Set(1, service);
                args.Set(2, uri);
                XmlRpcValue result = new XmlRpcValue(new XmlRpcValue(), new XmlRpcValue(), new XmlRpcValue(new XmlRpcValue())),
                 payload = new XmlRpcValue();

                Ros_CSharp.master.host = api.Replace("http://", "").Replace("/", "").Split(':')[0];
                Ros_CSharp.master.port = int.Parse(api.Replace("http://", "").Replace("/", "").Split(':')[1]);
                Ros_CSharp.master.execute("publisherUpdate", args, result, payload, false);
            }
Example #4
0
 /// <summary>
 ///     Gets all currently published and subscribed topics and adds them to the topic list
 /// </summary>
 /// <param name="topics"> List to store topics</param>
 /// <returns></returns>
 public static bool getTopics(ref TopicInfo[] topics)
 {
     List<TopicInfo> topicss = new List<TopicInfo>();
     XmlRpcValue args = new XmlRpcValue(), result = new XmlRpcValue(), payload = new XmlRpcValue();
     args.Set(0, this_node.Name);
     args.Set(1, "");
     if (!execute("getPublishedTopics", args, result, payload, true))
         return false;
     topicss.Clear();
     for (int i = 0; i < payload.Size; i++)
         topicss.Add(new TopicInfo(payload[i][0].Get<string>(), payload[i][1].Get<string>()));
     topics = topicss.ToArray();
     return true;
 }
        public override bool check()
        {
            XmlRpcValue chk = new XmlRpcValue();

            bool res = client.IsConnected;
            if (res == false)
                Console.WriteLine("DEAD MASTER DETECTED!");
            else
            {
                res &= client.ExecuteCheckDone(chk);
            }
            if (client.ExecuteCheckDone(chk))
            {
                return true;
            }
            return false;
        }
Example #6
0
        /// <summary>
        /// Get a list of all published topics
        /// </summary>
        /// <param name="parms"></param>
        /// <param name="result"></param>
        public void getPublishedTopics([In][Out] IntPtr parms, [In][Out] IntPtr result)
        {
            XmlRpcValue           res = XmlRpcValue.Create(ref result), parm = XmlRpcValue.Create(ref parms);
            List <List <String> > publishedtopics = handler.getPublishedTopics("", "");

            res.Set(0, 1);
            res.Set(1, "current system state");

            XmlRpcValue listofvalues = new XmlRpcValue();
            int         index        = 0;

            foreach (List <String> l in publishedtopics)
            {
                XmlRpcValue value = new XmlRpcValue();
                value.Set(0, l[0]); //Topic Name
                value.Set(1, l[1]); // Topic type
                listofvalues.Set(index, value);
                index++;
            }
            res.Set(2, listofvalues);
        }
Example #7
0
            internal SubscribeParamResponse(XmlRpcValue[]?a)
            {
                if (a is null ||
                    a.Length != 3 ||
                    !a[0].TryGetInteger(out int code) ||
                    !a[1].TryGetString(out string statusMessage))
                {
                    MarkError();
                    return;
                }

                base.responseCode = code;
                StatusMessage     = statusMessage;

                if (base.responseCode == StatusCode.Error)
                {
                    return;
                }

                ParameterValue = a[2];
            }
Example #8
0
        public static List <string> list()
        {
            List <string> ret = new List <string>();
            XmlRpcValue   parm = new XmlRpcValue(), result = new XmlRpcValue(), payload = new XmlRpcValue();

            parm.Set(0, this_node.Name);
            if (!master.execute("getParamNames", parm, result, payload, false))
            {
                return(ret);
            }
            if (result.Size != 3 || result[0].GetInt() != 1 || result[2].Type != XmlRpcValue.ValueType.TypeArray)
            {
                EDB.WriteLine("Expected a return code, a description, and a list!");
                return(ret);
            }
            for (int i = 0; i < payload.Size; i++)
            {
                ret.Add(payload[i].GetString());
            }
            return(ret);
        }
Example #9
0
 public void getInfo(XmlRpcValue info)
 {
     lock (publisher_links_mutex)
     {
         //EDB.WriteLine("SUB: getInfo with " + publisher_links.Count + " publinks in list");
         foreach (PublisherLink c in publisher_links)
         {
             //EDB.WriteLine("PUB: adding a curr_info to info!");
             XmlRpcValue curr_info = new XmlRpcValue();
             curr_info.Set(0, (int)c.ConnectionID);
             curr_info.Set(1, c.XmlRpc_Uri);
             curr_info.Set(2, "i");
             curr_info.Set(3, c.TransportType);
             curr_info.Set(4, name);
             //EDB.Write("PUB curr_info DUMP:\n\t");
             //curr_info.Dump();
             info.Set(info.Size, curr_info);
         }
         //EDB.WriteLine("SUB: outgoing info is of type: " + info.Type + " and has size: " + info.Size);
     }
 }
Example #10
0
        private bool UnregisterService(string service)
        {
            XmlRpcValue args = new XmlRpcValue(), result = new XmlRpcValue(), payload = new XmlRpcValue();

            args.Set(0, ThisNode.Name);
            args.Set(1, service);
            args.Set(2, string.Format("rosrpc://{0}:{1}", Network.Host, connectionManager.TCPPort));

            bool unregisterSuccess = false;

            try
            {
                unregisterSuccess = Master.Execute("unregisterService", args, result, payload, false);
            }
            catch
            {
                // ignore exception during unregister
            }

            return(unregisterSuccess);
        }
Example #11
0
        /// <summary>
        ///     Deletes a parameter from the parameter server.
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static async Task <bool> Del(string key)
        {
            string mappedKey = Names.Resolve(key);

            XmlRpcValue parm = new XmlRpcValue(), result = new XmlRpcValue(), payload = new XmlRpcValue();

            parm.Set(0, ThisNode.Name);
            parm.Set(1, mappedKey);
            if (!await Master.ExecuteAsync("deleteParam", parm, result, payload, false).ConfigureAwait(false))
            {
                return(false);
            }

            lock (gate)
            {
                subscriptions.Remove(mappedKey);
                cachedValues.Remove(mappedKey);
            }

            return(true);
        }
Example #12
0
        public bool RequestTopic(string topic, XmlRpcValue protos, ref XmlRpcValue ret)
        {
            foreach (var proto in protos)
            {
                if (proto.Type != XmlRpcType.Array)
                {
                    this.logger.LogError("requestTopic protocol list was not a list of lists");
                    return(false);
                }

                if (proto[0].Type != XmlRpcType.String)
                {
                    this.logger.LogError("requestTopic received a protocol list in which a sublist did not start with a string");
                    return(false);
                }

                string proto_name = proto[0].GetString();

                if (proto_name == "TCPROS")
                {
                    var tcpRosParams = new XmlRpcValue("TCPROS", Network.Host, ConnectionManager.Instance.TCPPort);
                    ret.Set(0, 1);
                    ret.Set(1, "");
                    ret.Set(2, tcpRosParams);
                    return(true);
                }

                if (proto_name == "UDPROS")
                {
                    this.logger.LogWarning("Ignoring topics with 'UDPROS' as protocol");
                }
                else
                {
                    this.logger.LogWarning("An unsupported protocol was offered: [{0}]", proto_name);
                }
            }

            this.logger.LogError("No supported protocol was provided");
            return(false);
        }
Example #13
0
        ReadOnlyCollection <TopicTuple> CreateTuple(XmlRpcValue root)
        {
            if (!root.TryGetArray(out XmlRpcValue[] objTuples))
            {
                MarkError();
                return(Empty);
            }

            List <TopicTuple> result = new();

            foreach (var objTuple in objTuples)
            {
                if (!objTuple.TryGetArray(out XmlRpcValue[] tuple) ||
                    tuple.Length != 2 ||
                    !tuple[0].TryGetString(out string topic) ||
                    !tuple[1].TryGetArray(out XmlRpcValue[] tmpMembers))
                {
                    MarkError();
                    return(Empty);
                }

                string[] members = new string[tmpMembers.Length];
                for (int i = 0; i < members.Length; i++)
                {
                    if (!tmpMembers[i].TryGetString(out string member))
                    {
                        MarkError();
                        return(Empty);
                    }

                    members[i] = member;
                }

                result.Add(new TopicTuple(topic, members));
            }

            result.Sort();
            return(result.AsReadOnly());
        }
Example #14
0
        private void PublisherUpdateCallback(XmlRpcValue parm, XmlRpcValue result)
        {
            string        topic           = parm[1].GetString();
            List <string> publicationUris = parm[2].Select(x => x.GetString()).ToList();

            this.logger.LogDebug($"PublisherUpdateCallback for topic '{topic}' with URIs: {string.Join(", ", publicationUris)}");

            var pubUpdateTask = PubUpdate(topic, publicationUris);

            pubUpdateTask.WhenCompleted().WhenCompleted().Wait();

            if (pubUpdateTask.HasCompletedSuccessfully() && pubUpdateTask.Result)
            {
                XmlRpcManager.ResponseInt(1, "", 0)(result);
            }
            else
            {
                const string error = "Unknown error while handling XmlRpc call to pubUpdate";
                this.logger.LogError(error);
                XmlRpcManager.ResponseInt(0, error, 0)(result);
            }
        }
Example #15
0
        /// <summary>
        /// Unregister an existing subscriber
        /// </summary>
        /// <param name="parms"></param>
        /// <param name="result"></param>
        public void unregisterSubscriber([In][Out] IntPtr parms, [In][Out] IntPtr result)
        {
            XmlRpcValue res = XmlRpcValue.Create(ref result), parm = XmlRpcValue.Create(ref parms);

            String caller_id  = parm[0].GetString();
            String topic      = parm[1].GetString();
            String caller_api = parm[2].GetString();

            Console.WriteLine("UNSUBSCRIBING: " + caller_id + " : " + caller_api);

            int ret = handler.unregisterSubscriber(caller_id, topic, caller_api);

            res.Set(0, ret);
            res.Set(1, "unregistered " + caller_id + "as provder of " + topic);

            //throw new Exception("NOT IMPLEMENTED YET!");
            //XmlRpcValue args = new XmlRpcValue(this_node.Name, topic, XmlRpcManager.Instance.uri),
            //            result = new XmlRpcValue(),
            //            payload = new XmlRpcValue();
            //master.execute("unregisterSubscriber", args, ref result, ref payload, false);
            //return true;
        }
Example #16
0
        /// <summary>
        /// Returns list of all publications
        /// </summary>
        /// <param name="parms"></param>
        /// <param name="result"></param>
        public void getPublications([In][Out] IntPtr parms, [In][Out] IntPtr result)
        {
            XmlRpcValue res = XmlRpcValue.Create(ref result);

            res.Set(0, 1);                            //length
            res.Set(1, "publications");               //response too
            XmlRpcValue response = new XmlRpcValue(); //guts, new value here

            //response.Size = 0;
            List <List <String> > current = handler.getPublishedTopics("", "");

            for (int i = 0; i < current.Count; i += 2)
            {
                XmlRpcValue pub = new XmlRpcValue();
                pub.Set(0, current[0]);
                current.RemoveAt(0);
                pub.Set(1, current[0]);
                current.RemoveAt(0);
                response.Set(i, pub);
            }
            res.Set(2, response);
        }
Example #17
0
        private void PublisherUpdateCallback(XmlRpcValue parm, XmlRpcValue result)
        {
            var pubs = new List <string>();

            for (int idx = 0; idx < parm[2].Count; idx++)
            {
                pubs.Add(parm[2][idx].GetString());
            }
            var pubUpdateTask = PubUpdate(parm[1].GetString(), pubs);

            pubUpdateTask.WhenCompleted().WhenCompleted().Wait();
            if (pubUpdateTask.IsCompletedSuccessfully && pubUpdateTask.Result)
            {
                XmlRpcManager.ResponseInt(1, "", 0)(result);
            }
            else
            {
                const string error = "Unknown error while handling XmlRpc call to pubUpdate";
                this.logger.LogError(error);
                XmlRpcManager.ResponseInt(0, error, 0)(result);
            }
        }
        public static bool get <T> (string key, ref Dictionary <string, T> dict, bool cached = false)
        {
            XmlRpcValue val = new XmlRpcValue();

            if (!safeGet(key, ref val))
            {
                return(false);
            }

            if (val.Type != XmlRpcValue.ValueType.TypeStruct)
            {
                return(false);
            }

            dict = new Dictionary <string, T> (val.asStruct.Count);
            foreach (KeyValuePair <string, XmlRpcValue> pair in val.asStruct)
            {
                dict.Add(pair.Key, pair.Value.Get <T> ());
            }

            return(true);
        }
Example #19
0
        public bool requestTopic(string topic, XmlRpcValue protos, ref XmlRpcValue ret)
        {
            for (int proto_idx = 0; proto_idx < protos.Size; proto_idx++)
            {
                XmlRpcValue proto = protos[proto_idx];
                if (proto.Type != XmlRpcValue.ValueType.TypeArray)
                {
                    EDB.WriteLine("requestTopic protocol list was not a list of lists");
                    return(false);
                }
                if (proto[0].Type != XmlRpcValue.ValueType.TypeString)
                {
                    EDB.WriteLine(
                        "requestTopic received a protocol list in which a sublist did not start with a string");
                    return(false);
                }

                string proto_name = proto[0].Get <string>();

                if (proto_name == "TCPROS")
                {
                    XmlRpcValue tcp_ros_params = new XmlRpcValue("TCPROS", network.host, ConnectionManager.Instance.TCPPort);
                    ret.Set(0, 1);
                    ret.Set(1, "");
                    ret.Set(2, tcp_ros_params);
                    return(true);
                }
                if (proto_name == "UDPROS")
                {
                    EDB.WriteLine("IGNORING UDP GIZNARBAGE");
                }
                else
                {
                    EDB.WriteLine("an unsupported protocol was offered: [{0}]", proto_name);
                }
            }
            EDB.WriteLine("The caller to requestTopic has NO IDEA WHAT'S GOING ON!");
            return(false);
        }
Example #20
0
        public static bool kill(string node)
        {
            var cl = clientForNode(node);

            if (cl == null)
            {
                return(false);
            }

            XmlRpcValue req = new XmlRpcValue(), resp = new XmlRpcValue(), payl = new XmlRpcValue();

            req.Set(0, ThisNode.Name);
            req.Set(1, $"Node '{ThisNode.Name}' requests shutdown.");
            var respose = cl.Execute("shutdown", req);

            if (!respose.Success || !XmlRpcManager.Instance.ValidateXmlRpcResponse("shutdown", respose.Value, payl))
            {
                return(false);
            }

            return(true);
        }
Example #21
0
        public bool NegotiateConnection(string xmlrpc_uri)
        {
            int         protos = 0;
            XmlRpcValue tcpros_array = new XmlRpcValue(), protos_array = new XmlRpcValue(), Params = new XmlRpcValue();

            tcpros_array.Set(0, "TCPROS");
            protos_array.Set(protos++, tcpros_array);
            Params.Set(0, this_node.Name);
            Params.Set(1, name);
            Params.Set(2, protos_array);
            string peer_host = "";
            int    peer_port = 0;

            if (!network.splitURI(xmlrpc_uri, ref peer_host, ref peer_port))
            {
                EDB.WriteLine("Bad xml-rpc URI: [" + xmlrpc_uri + "]");
                return(false);
            }
            XmlRpcClient c = new XmlRpcClient(peer_host, peer_port);

            if (!c.IsConnected || !c.ExecuteNonBlock("requestTopic", Params))
            {
                EDB.WriteLine("Failed to contact publisher [" + peer_host + ":" + peer_port + "] for topic [" + name +
                              "]");
                c.Dispose();
                return(false);
            }
#if DEBUG
            EDB.WriteLine("Began asynchronous xmlrpc connection to http://" + peer_host + ":" + peer_port + "/ for topic [" + name +
                          "]");
#endif
            PendingConnection conn = new PendingConnection(c, this, xmlrpc_uri, Params);
            lock (pending_connections_mutex)
            {
                pending_connections.Add(conn);
            }
            XmlRpcManager.Instance.addAsyncConnection(conn);
            return(true);
        }
Example #22
0
 private static bool safeGet <T>(string key, ref T dest, object def = null)
 {
     try
     {
         XmlRpcValue v = getParam(key);
         if (v == null)
         {
             if (def == null)
             {
                 return(false);
             }
             dest = (T)def;
             return(true);
         }
         dest = v.Get <T>();
         return(true);
     }
     catch
     {
         return(false);
     }
 }
Example #23
0
        public bool requestTopic(string topic, XmlRpcValue protos, ref XmlRpcValue ret)
        {
            for (int proto_idx = 0; proto_idx < protos.Count; proto_idx++)
            {
                XmlRpcValue proto = protos[proto_idx];
                if (proto.Type != XmlRpcType.Array)
                {
                    ROS.Error()($"[{ThisNode.Name}] requestTopic protocol list was not a list of lists");
                    return(false);
                }
                if (proto[0].Type != XmlRpcType.String)
                {
                    ROS.Error()($"[{ThisNode.Name}] requestTopic received a protocol list in which a sublist did not start with a string");
                    return(false);
                }

                string proto_name = proto[0].GetString();

                if (proto_name == "TCPROS")
                {
                    var tcpRosParams = new XmlRpcValue("TCPROS", Network.host, ConnectionManager.Instance.TCPPort);
                    ret.Set(0, 1);
                    ret.Set(1, "");
                    ret.Set(2, tcpRosParams);
                    return(true);
                }
                if (proto_name == "UDPROS")
                {
                    ROS.Warn()($"[{ThisNode.Name}] Ignoring topics with UdpRos as protocol");
                }
                else
                {
                    ROS.Warn()($"[{ThisNode.Name}] An unsupported protocol was offered: [{proto_name}]");
                }
            }

            ROS.Error()($"[{ThisNode.Name}] No supported protocol was provided");
            return(false);
        }
        public static bool get <T> (string key, ref List <T> list, bool cached = false)
        {
            XmlRpcValue val = new XmlRpcValue();

            if (!safeGet(key, ref val))
            {
                return(false);
            }

            if (val.Type != XmlRpcValue.ValueType.TypeArray)
            {
                return(false);
            }

            list = new List <T> (val.Size);
            for (int i = 0; i < val.Size; i++)
            {
                list.Add(val [i].Get <T> ());
            }

            return(true);
        }
Example #25
0
        /// <summary>
        /// Get a list of all published topics
        /// </summary>
        /// <param name="parms"></param>
        /// <param name="result"></param>
        public XmlRpcValue getPublishedTopics()
        {
            XmlRpcValue           res             = new XmlRpcValue();
            List <List <String> > publishedtopics = handler.getPublishedTopics("", "");

            res.Set(0, 1);
            res.Set(1, "current system state");

            XmlRpcValue listofvalues = new XmlRpcValue();
            int         index        = 0;

            foreach (List <String> l in publishedtopics)
            {
                XmlRpcValue value = new XmlRpcValue();
                value.Set(0, l[0]); //Topic Name
                value.Set(1, l[1]); // Topic type
                listofvalues.Set(index, value);
                index++;
            }
            res.Set(2, listofvalues);
            return(res);
        }
Example #26
0
        public XmlRpcValue getBusStats()
        {
            var publish_stats   = new XmlRpcValue();
            var subscribe_stats = new XmlRpcValue();
            var service_stats   = new XmlRpcValue();

            int pidx = 0;

            lock ( advertisedTopicsMutex )
            {
                publish_stats.SetArray(advertisedTopics.Count);
                foreach (Publication t in advertisedTopics)
                {
                    publish_stats.Set(pidx++, t.GetStats());
                }
            }

            int sidx = 0;

            lock ( subcriptionsMutex )
            {
                subscribe_stats.SetArray(subscriptions.Count);
                foreach (Subscription t in subscriptions)
                {
                    subscribe_stats.Set(sidx++, t.getStats());
                }
            }

            // TODO: fix for services
            service_stats.SetArray(0); //service_stats.Size = 0;

            var stats = new XmlRpcValue();

            stats.Set(0, publish_stats);
            stats.Set(1, subscribe_stats);
            stats.Set(2, service_stats);
            return(stats);
        }
Example #27
0
        /// <summary>
        ///     Manually update the value of a parameter
        /// </summary>
        /// <param name="key">Name of parameter</param>
        /// <param name="value">Value to update param to</param>
        public static void Update(string key, XmlRpcValue value)
        {
            if (value == null)
            {
                return;
            }

            key = Names.Clean(key);

            List <ParamDelegate> callbacks = null;

            lock (gate)
            {
                if (!cachedValues.ContainsKey(key))
                {
                    cachedValues.Add(key, value);
                }
                else
                {
                    cachedValues[key] = value;
                }

                if (!subscriptions.TryGetValue(key, out callbacks))
                {
                    return;
                }

                callbacks = new List <ParamDelegate>(callbacks);     // create isolation copy to execute callbacks outside lock
            }

            if (callbacks != null)
            {
                foreach (var cb in callbacks)
                {
                    cb(key, value);
                }
            }
        }
        public T param <T> (string param_name, T default_val)
        {
            if (!hasParam(param_name))
            {
                return(default_val);
            }
            try
            {
                XmlRpcValue v = Param.getParam(param_name);
                if (v == null || !v.Valid)
                {
                    return(default_val);
                }

                return(v.Get <T> ());
            }
            catch
            {
                return(default_val);
            }

            return(default_val);
        }
Example #29
0
        public static List <string> List()
        {
            var ret     = new List <string>();
            var parm    = new XmlRpcValue();
            var result  = new XmlRpcValue();
            var payload = new XmlRpcValue();

            parm.Set(0, ThisNode.Name);
            if (!Master.execute("getParamNames", parm, result, payload, false))
            {
                return(ret);
            }
            if (result.Count != 3 || result[0].GetInt() != 1 || result[2].Type != XmlRpcType.Array)
            {
                ROS.Warn()("Expected a return code, a description, and a list!");
                return(ret);
            }
            for (int i = 0; i < payload.Count; i++)
            {
                ret.Add(payload[i].GetString());
            }
            return(ret);
        }
Example #30
0
            public ReturnStruct registerSubscriber(String caller_id, String topic, String topic_type, String caller_api)
            {
                reg_manager.register_subscriber(topic, caller_id, caller_api);

                if (!topic_types.ContainsValue(topic_type))
                {
                    topic_types.Add(topic, topic_type);
                }
                List <String> puburis = publishers.get_apis(topic);

                ReturnStruct rtn = new ReturnStruct();

                rtn.statusMessage = String.Format("Subscribed to [{0}] ", topic);
                rtn.statusCode    = 1;
                rtn.value         = new XmlRpcValue();
                rtn.value.Set(0, new XmlRpcValue());
                for (int i = 0; i < puburis.Count(); i++)
                {
                    XmlRpcValue tmp = new XmlRpcValue(puburis[i]);
                    rtn.value.Set(i, tmp);
                }
                return(rtn);
            }
Example #31
0
        public static async Task <IList <string> > List()
        {
            var ret     = new List <string>();
            var parm    = new XmlRpcValue();
            var result  = new XmlRpcValue();
            var payload = new XmlRpcValue();

            parm.Set(0, ThisNode.Name);
            if (!await Master.ExecuteAsync("getParamNames", parm, result, payload, false).ConfigureAwait(false))
            {
                return(ret);
            }
            if (result.Count != 3 || result[0].GetInt() != 1 || result[2].Type != XmlRpcType.Array)
            {
                logger.LogWarning("Expected a return code, a description, and a list!");
                return(ret);
            }
            for (int i = 0; i < payload.Count; i++)
            {
                ret.Add(payload[i].GetString());
            }
            return(ret);
        }
Example #32
0
        /// <summary>
        /// Returns list of all publications
        /// </summary>
        /// <param name="parms"></param>
        /// <param name="result"></param>
        public XmlRpcValue getPublications()
        {
            XmlRpcValue res = new XmlRpcValue();

            res.Set(0, 1);                            //length
            res.Set(1, "publications");               //response too
            XmlRpcValue response = new XmlRpcValue(); //guts, new value here

            //response.Size = 0;
            List <List <String> > current = handler.getPublishedTopics("", "");

            for (int i = 0; i < current.Count; i += 2)
            {
                XmlRpcValue pub = new XmlRpcValue();
                pub.Set(0, current[0]);
                current.RemoveAt(0);
                pub.Set(1, current[0]);
                current.RemoveAt(0);
                response.Set(i, pub);
            }
            res.Set(2, response);
            return(res);
        }
Example #33
0
        /// <summary>
        /// Notify subscribers of an update??
        /// </summary>
        /// <param name="parms"></param>
        /// <param name="result"></param>
        public void pubUpdate([In][Out] XmlRpcValue parms, [In][Out] XmlRpcValue result)
        {
            //throw new Exception("NOT IMPLEMENTED YET!");
            //mlRpcValue parm = XmlRpcValue.Create(ref parms);
            //List<string> pubs = new List<string>();
            //for (int idx = 0; idx < parm[2].Size; idx++)
            //    pubs.Add(parm[2][idx].Get<string>());
            //if (pubUpdate(parm[1].Get<string>(), pubs))
            //    XmlRpcManager.Instance.responseInt(1, "", 0)(result);
            //else
            //{
            //    EDB.WriteLine("Unknown Error");
            //    XmlRpcManager.Instance.responseInt(0, "Unknown Error or something", 0)(result);
            //}



            //EDB.WriteLine("TopicManager is updating publishers for " + topic);
            //Subscription sub = null;
            //lock (subs_mutex)
            //{
            //    if (shutting_down) return false;
            //    foreach (Subscription s in subscriptions)
            //    {
            //        if (s.name != topic || s.IsDropped)
            //            continue;
            //        sub = s;
            //        break;
            //    }
            //}
            //if (sub != null)
            //    return sub.pubUpdate(pubs);
            //else
            //    EDB.WriteLine("got a request for updating publishers of topic " + topic +
            //                  ", but I don't have any subscribers to that topic.");
            //return false;
        }
Example #34
0
        public bool NegotiateConnection(string xmlRpcUri)
        {
            int         protos = 0;
            XmlRpcValue tcpros_array = new XmlRpcValue(), protos_array = new XmlRpcValue(), Params = new XmlRpcValue();

            tcpros_array.Set(0, "TCPROS");
            protos_array.Set(protos++, tcpros_array);
            Params.Set(0, ThisNode.Name);
            Params.Set(1, name);
            Params.Set(2, protos_array);
            if (!Network.SplitUri(xmlRpcUri, out string peerHost, out int peerPort))
            {
                ROS.Error()($"[{ThisNode.Name}] Bad xml-rpc URI: [{xmlRpcUri}]");
                return(false);
            }

            var client = new XmlRpcClient(peerHost, peerPort);
            var requestTopicTask = client.ExecuteAsync("requestTopic", Params);

            if (requestTopicTask.IsFaulted)
            {
                ROS.Error()($"[{ThisNode.Name}] Failed to contact publisher [{peerHost}:{peerPort}for topic [{name}]");
                return(false);
            }

            ROS.Debug()($"[{ThisNode.Name}] Began asynchronous xmlrpc connection to http://{peerHost}:{peerPort}/ for topic [{name}]");

            var conn = new PendingConnection(client, requestTopicTask, xmlRpcUri);

            lock ( pendingConnections )
            {
                pendingConnections.Add(conn);
                requestTopicTask.ContinueWith(t => PendingConnectionDone(conn, t));
            }

            return(true);
        }
Example #35
0
        public static bool GetImpl(string key, out XmlRpcValue value, bool useCache)
        {
            string mappepKey = Names.Resolve(key);

            value = new XmlRpcValue();

            if (useCache)
            {
                lock (gate)
                {
                    if (cachedValues.TryGetValue(mappepKey, out var cachedValue) && !cachedValue.IsEmpty)
                    {
                        value = cachedValue;
                        return(true);
                    }
                }
            }

            XmlRpcValue parm2 = new XmlRpcValue(), result2 = new XmlRpcValue();

            parm2.Set(0, ThisNode.Name);
            parm2.Set(1, mappepKey);
            value.SetArray(0);

            bool ret = Master.Execute("getParam", parm2, result2, value, false);

            if (ret && useCache)
            {
                lock (gate)
                {
                    cachedValues[mappepKey] = value;
                }
            }

            return(ret);
        }
Example #36
0
        /// <summary>
        /// </summary>
        /// <param name="method"></param>
        /// <param name="request">Full request to send to the master </param>
        /// <param name="response">Full response including status code and status message. Initially empty.</param>
        /// <param name="payload">Location to store the actual data requested, if any.</param>
        /// <param name="wait_for_master">If you recieve an unseccessful status code, keep retrying.</param>
        /// <returns></returns>
        public static bool execute(string method, XmlRpcValue request, XmlRpcValue response, XmlRpcValue payload,
            bool wait_for_master)
        {
            try
            {
                DateTime startTime = DateTime.Now;
                string master_host = host;
                int master_port = port;

                CachedXmlRpcClient client = XmlRpcManager.Instance.getXMLRPCClient(master_host, master_port, "/");
                bool printed = false;
                bool success = false;

                while (!success)
                {
                    // Check if we are shutting down
                    if (XmlRpcManager.Instance.shutting_down)
                        return false;

                    // if the client is connected, execute the RPC call
                    success = client.IsConnected && client.Execute(method, request, response);

                    if (client.IsConnected && !success)
                    {
                        if (response != null && response.asArray != null && response.asArray.Length >= 2)
                            EDB.WriteLine("Execute failed: return={0}, desc={1}", response[0].asInt, response[1].asString);
                        else
                            EDB.WriteLine("response type == " + (response != null ? response.Type.ToString() : "null"));
                    }

                    // Set success to false when response validation fails
                    if (success && !XmlRpcManager.Instance.validateXmlrpcResponse(method, response, payload))
                        success = false;

                    if (success)
                    {
                        XmlRpcManager.Instance.releaseXMLRPCClient(client);
                        return true;
                    }
                    if (!wait_for_master)
                    {
                        XmlRpcManager.Instance.releaseXMLRPCClient(client);
                        return false;
                    }

                    if (!printed)
                    {
                        EDB.WriteLine("[{0}] FAILED TO CONTACT MASTER AT [{1}:{2}]. {3}", method, master_host,
                            master_port, (wait_for_master ? "Retrying for the next "+retryTimeout.TotalSeconds+" seconds..." : ""));
                        printed = true;
                    }
                    if (retryTimeout.TotalSeconds > 0 && DateTime.Now.Subtract(startTime) > retryTimeout)
                    {
                        EDB.WriteLine("[{0}] Timed out trying to connect to the master after [{1}] seconds", method,
                            retryTimeout.TotalSeconds);
                        XmlRpcManager.Instance.releaseXMLRPCClient(client);
                        return false;
                    }

                    //recreate the client, thereby causing it to reinitiate its connection (gross, but effective -- should really be done in xmlrpcwin32)
                    XmlRpcManager.Instance.releaseXMLRPCClient(client);
                    client = null;
                    Thread.Sleep(250);
                    client = XmlRpcManager.Instance.getXMLRPCClient(master_host, master_port, "/");
                }
            }
            catch (Exception e)
            {
                EDB.WriteLine(e);
            }
            EDB.WriteLine("Master API call: {0} failed!\n\tRequest:\n{1}", method, request);
            return false;
        }
Example #37
0
 public bool ExecuteNonBlock(string method, XmlRpcValue parameters)
 {
     return client.ExecuteNonBlock(method, parameters);
 }
Example #38
0
 public bool ExecuteNonBlock(string method, XmlRpcValue parameters)
 {
     return executenonblock(instance, method, parameters.instance);
 }
Example #39
0
 public bool ExecuteCheckDone(XmlRpcValue result)
 {
     return executecheckdone(instance, result.instance);
 }
Example #40
0
        /// <summary>
        /// </summary>
        /// <param name="method"></param>
        /// <param name="request">Full request to send to the master </param>
        /// <param name="response">Full response including status code and status message. Initially empty.</param>
        /// <param name="payload">Location to store the actual data requested, if any.</param>
        /// <param name="wait_for_master">If you recieve an unseccessful status code, keep retrying.</param>
        /// <returns></returns>
        public static bool execute(string method, XmlRpcValue request, ref XmlRpcValue response, ref XmlRpcValue payload,
            bool wait_for_master)
        {
            try
            {
                DateTime startTime = DateTime.Now;
                string master_host = host;
                int master_port = port;

                //EDB.WriteLine("Trying to connect to master @ " + master_host + ":" + master_port);
                XmlRpcClient client = XmlRpcManager.Instance.getXMLRPCClient(master_host, master_port, "/");
                bool printed = false;
                bool ok = true;
                while (!client.IsConnected && !ROS._shutting_down && !XmlRpcManager.Instance.shutting_down ||
                       !(ok = client.Execute(method, request, response) && XmlRpcManager.Instance.validateXmlrpcResponse(method, response, ref payload)))
                {
                    if (!wait_for_master)
                    {
                        XmlRpcManager.Instance.releaseXMLRPCClient(client);
                        return false;
                    }
                    if (!printed)
                    {
                        EDB.WriteLine("[{0}] FAILED TO CONTACT MASTER AT [{1}:{2}]. {3}", method, master_host,
                            master_port, (wait_for_master ? "Retrying..." : ""));
                        printed = true;
                    }
                    if (retryTimeout.TotalSeconds > 0 && DateTime.Now.Subtract(startTime) > retryTimeout)
                    {
                        EDB.WriteLine("[{0}] Timed out trying to connect to the master after [{1}] seconds", method,
                            retryTimeout.TotalSeconds);
                        XmlRpcManager.Instance.releaseXMLRPCClient(client);
                        return false;
                    }
                    Thread.Sleep(10);
                }
                if (ok && !firstsucces)
                {
                    firstsucces = true;
                    //EDB.WriteLine(string.Format("CONNECTED TO MASTER AT [{0}:{1}]", master_host, master_port));
                }
                XmlRpcManager.Instance.releaseXMLRPCClient(client);
                return true;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            return false;
        }
Example #41
0
 public bool Execute(string method, XmlRpcValue parameters, XmlRpcValue result)
 {
     bool r = execute(instance, method, parameters.instance, result.instance);
     return r;
 }
Example #42
0
 public void setParam(String caller_id, String key, XmlRpcValue value) 
 {
     key = Names.resolve_name(key,caller_id);
     param_server.set_param(key, value, _notify_param_subscribers);
 }
Example #43
0
 public void Execute(XmlRpcValue parms, XmlRpcValue reseseses)
 {
     _FUNC(parms, reseseses);
 }
Example #44
0
 /// <summary>
 ///     Checks if master is running? I think.
 /// </summary>
 /// <returns></returns>
 public static bool check()
 {
     XmlRpcValue args = new XmlRpcValue(), result = new XmlRpcValue(), payload = new XmlRpcValue();
     args.Set(0, this_node.Name);
     return execute("getPid", args, result, payload, false);
 }
Example #45
0
            /// <summary>
            /// Register a publisher
            /// </summary>
            /// <param name="caller_id"></param>
            /// <param name="topic"></param>
            /// <param name="topic_type"></param>
            /// <param name="caller_api"></param>
            /// <returns></returns>
            public ReturnStruct registerPublisher(String caller_id, String topic, String topic_type, String caller_api) 
            {
                reg_manager.register_publisher(topic, caller_id, caller_api);
                if (!topic_types.ContainsValue(topic_type))
                    topic_types.Add(topic, topic_type);
                List<String> puburis = publishers.get_apis(topic);
                List<String> sub_uris = subscribers.get_apis(topic);
                _notify_topic_subscribers(topic, puburis, sub_uris);

                ReturnStruct rtn = new ReturnStruct();
                rtn.statusMessage = String.Format("Registered [{0}] as publisher of [{1}]", caller_id, topic);
                rtn.statusCode = 1;
                rtn.value = new XmlRpcValue();
                rtn.value.Set(0, new XmlRpcValue());
                for (int i = 0; i < sub_uris.Count(); i++)
                {
                    XmlRpcValue tmp = new XmlRpcValue(sub_uris[0]);
                    rtn.value.Set(i, tmp);
                }
                return rtn;
            }
Example #46
0
        // Execute the named procedure on the remote server.
        // Params should be an array of the arguments for the method.
        // Returns true if the request was sent and a result received (although the result
        // might be a fault).
        public bool Execute(string method, XmlRpcValue parameters, XmlRpcValue result)
        {
            XmlRpcUtil.log(XmlRpcUtil.XMLRPC_LOG_LEVEL.SPEW, "XmlRpcClient::Execute: method {0} (_connectionState {0}).", method, _connectionState);
            lock (this)
            {
                //result = null;
                // This is not a thread-safe operation, if you want to do multithreading, use separate
                // clients for each thread. If you want to protect yourself from multiple threads
                // accessing the same client, replace this code with a real mutex.
                if (_executing)
                    return false;

                _executing = true;
                //ClearFlagOnExit cf(_executing);

                _sendAttempts = 0;
                _isFault = false;

                if (!setupConnection())
                {
                    _executing = false;
                    return false;
                }

                if (!generateRequest(method, parameters))
                {
                    _executing = false;
                    return false;
                }

                double msTime = -1.0;
                _disp.Work(msTime);

                if (_connectionState != ConnectionState.IDLE || !parseResponse(result, header.DataString))
                {
                    _executing = false;
                    return false;
                }

                XmlRpcUtil.log(XmlRpcUtil.XMLRPC_LOG_LEVEL.DEBUG, "XmlRpcClient::execute: method {0} completed.", method);
                _executing = false;
            }
            _executing = false;
            return true;
        }
Example #47
0
        /// <summary>
        ///     Gets all currently existing nodes and adds them to the nodes list
        /// </summary>
        /// <param name="nodes">List to store nodes</param>
        /// <returns></returns>
        public static bool getNodes(ref string[] nodes)
        {
            List<string> names = new List<string>();
            XmlRpcValue args = new XmlRpcValue(), result = new XmlRpcValue(), payload = new XmlRpcValue();
            args.Set(0, this_node.Name);

            if (!execute("getSystemState", args, result, payload, true))
            {
                return false;
            }
            for (int i = 0; i < payload.Size; i++)
            {
                for (int j = 0; j < payload[i].Size; j++)
                {
                    XmlRpcValue val = payload[i][j][1];
                    for (int k = 0; k < val.Size; k++)
                    {
                        string name = val[k].Get<string>();
                        names.Add(name);
                    }
                }
            }
            nodes = names.ToArray();
            return true;
        }
Example #48
0
 public void Execute(XmlRpcValue parms, out XmlRpcValue reseseses)
 {
     SegFault();
     reseseses = new XmlRpcValue();
     execute(instance, parms.instance, reseseses.instance);
 }
Example #49
0
 public void getInfo(XmlRpcValue info)
 {
     lock (subscriber_links_mutex)
     {
         foreach (SubscriberLink c in subscriber_links)
         {
             XmlRpcValue curr_info = new XmlRpcValue();
             curr_info.Set(0, (int) c.connection_id);
             curr_info.Set(1, c.destination_caller_id);
             curr_info.Set(2, "o");
             curr_info.Set(3, "TCPROS");
             curr_info.Set(4, Name);
             info.Set(info.Size, curr_info);
         }
     }
 }
Example #50
0
 public static bool kill(string node)
 {
     CachedXmlRpcClient cl = clientForNode(node);
     if (cl == null)
         return false;
     XmlRpcValue req = new XmlRpcValue(), resp = new XmlRpcValue(), payl = new XmlRpcValue();
     req.Set(0, this_node.Name);
     req.Set(1, "Out of respect for Mrs. " + this_node.Name);
     if (!cl.Execute("shutdown", req, resp) || !XmlRpcManager.Instance.validateXmlrpcResponse("lookupNode", resp, payl))
         return false;
     payl.Dump();
     XmlRpcManager.Instance.releaseXMLRPCClient(cl);
     return true;
 }
Example #51
0
 public XmlRpcValue GetStats()
 {
     XmlRpcValue stats = new XmlRpcValue();
     stats.Set(0, Name);
     XmlRpcValue conn_data = new XmlRpcValue();
     conn_data.SetArray(0);
     lock (subscriber_links_mutex)
     {
         int cidx = 0;
         foreach (SubscriberLink sub_link in subscriber_links)
         {
             SubscriberLink.Stats s = sub_link.stats;
             XmlRpcValue inside = new XmlRpcValue();
             inside.Set(0, sub_link.connection_id);
             inside.Set(1, s.bytes_sent);
             inside.Set(2, s.message_data_sent);
             inside.Set(3, s.messages_sent);
             inside.Set(4, 0);
             conn_data.Set(cidx++, inside);
         }
     }
     stats.Set(1, conn_data);
     return stats;
 }
Example #52
0
        // Convert the response xml into a result value
        private bool parseResponse(XmlRpcValue result, string _response)
        {
            bool success = true;
            //XmlRpcValue result = null;
            using (XmlReader reader = XmlReader.Create(new StringReader(_response)))
            {
                XmlDocument response = new XmlDocument();
                response.Load(reader);
                // Parse response xml into result
                //int offset = 0;
                XmlNodeList resp = response.GetElementsByTagName("methodResponse");
                XmlNode responseNode = resp[0];

                //if (!XmlRpcUtil.findTag(METHODRESPONSE_TAG, _response, out offset))
                if (resp.Count == 0)
                {
                    XmlRpcUtil.error("Error in XmlRpcClient::parseResponse: Invalid response - no methodResponse. Response:\n{0}", _response);
                    return false;
                }

                XmlElement pars = responseNode["params"];
                XmlElement fault = responseNode["fault"];

                //result = new XmlRpcValue();
                if (pars != null)
                {
                    bool isArray = false;
                    var selection = pars.SelectNodes("param");
                    if (selection.Count > 1)
                    {
                        result.SetArray(selection.Count);
                        int i = 0;
                        foreach (XmlNode par in selection)
                        {
                            var value = new XmlRpcValue();
                            value.fromXml(par["value"]);
                            result[i++] = value;
                        }
                    }
                    else if (selection.Count == 1)
                    {
                        result.fromXml(selection[0]["value"]);
                    }
                    else
                        success = false;
                }
                else if (fault != null && result.fromXml(fault))
                {
                    success = false;
                }
                else
                {
                    XmlRpcUtil.error("Error in XmlRpcClient::parseResponse: Invalid response - no param or fault tag. Response:\n{0}", _response);
                }
                _response = "";
            }
            return success;
        }
Example #53
0
        // Execute the named procedure on the remote server, non-blocking.
        // Params should be an array of the arguments for the method.
        // Returns true if the request was sent and a result received (although the result
        // might be a fault).
        public bool ExecuteNonBlock(string method, XmlRpcValue parameters)
        {
            XmlRpcUtil.log(XmlRpcUtil.XMLRPC_LOG_LEVEL.SPEW, "XmlRpcClient::ExecuteNonBlock: method {0} (_connectionState {0}.", method, _connectionState);

            // This is not a thread-safe operation, if you want to do multithreading, use separate
            // clients for each thread. If you want to protect yourself from multiple threads
            // accessing the same client, replace this code with a real mutex.

            XmlRpcValue result = new XmlRpcValue();
            if (_executing)
                return false;

            _executing = true;

            _sendAttempts = 0;
            _isFault = false;

            if (!setupConnection())
            {
                _executing = false;
                return false;
            }

            if (!generateRequest(method, parameters))
            {
                _executing = false;
                return false;
            }

            _executing = false;
            return true;
        }
Example #54
0
 public bool Execute(string method, XmlRpcValue parameters, XmlRpcValue result)
 {
     return client.Execute(method, parameters, result);
 }
Example #55
0
 public bool ExecuteCheckDone(XmlRpcValue result)
 {
     //result.clear();
     // Are we done yet?
     if (_connectionState != ConnectionState.IDLE)
         return false;
     if (!parseResponse(result, header.DataString))
     {
         // Hopefully the caller can determine that parsing failed.
     }
     XmlRpcUtil.log(XmlRpcUtil.XMLRPC_LOG_LEVEL.DEBUG, "XmlRpcClient::execute: method completed.");
     return true;
 }
Example #56
0
        private string generateRequestStr(string methodName, XmlRpcValue parameters)
        {
            string body = REQUEST_BEGIN;
            body += methodName;
            body += REQUEST_END_METHODNAME;

            // If params is an array, each element is a separate parameter
            if (parameters.Valid)
            {
                body += PARAMS_TAG;
                if (parameters.Type == XmlRpcValue.ValueType.TypeArray)
                {
                    for (int i = 0; i < parameters.Length; ++i)
                    {
                        body += PARAM_TAG;
                        body += parameters[i].toXml();
                        body += PARAM_ETAG;
                    }
                }
                else
                {
                    body += PARAM_TAG;
                    body += parameters.toXml();
                    body += PARAM_ETAG;
                }

                body += PARAMS_ETAG;
            }
            body += REQUEST_END;
            return body;
        }
Example #57
0
            public ReturnStruct registerSubscriber(String caller_id, String topic, String topic_type, String caller_api) 
            {
                reg_manager.register_subscriber(topic, caller_id, caller_api);

                if (!topic_types.ContainsValue(topic_type))
                    topic_types.Add(topic, topic_type);
                List<String> puburis = publishers.get_apis(topic);

                ReturnStruct rtn = new ReturnStruct();
                rtn.statusMessage = String.Format("Subscribed to [{0}] ", topic);
                rtn.statusCode = 1;
                rtn.value = new XmlRpcValue();
                rtn.value.Set(0, new XmlRpcValue());
                for (int i = 0; i < puburis.Count(); i++)
                {
                    XmlRpcValue tmp = new XmlRpcValue(puburis[i]);
                    rtn.value.Set(i, tmp);
                }
                return rtn;
            }
Example #58
0
        // Encode the request to call the specified method with the specified parameters into xml
        private bool generateRequest(string methodName, XmlRpcValue parameters)
        {
            string body = generateRequestStr(methodName, parameters);

            string header = generateHeader(body);
            XmlRpcUtil.log(XmlRpcUtil.XMLRPC_LOG_LEVEL.DEBUG, "XmlRpcClient::generateRequest: header is {0} bytes, content-length is {1}.", header.Length, body.Length);

            _request = header + body;
            return true;
        }
Example #59
0
 public bool ExecuteCheckDone(XmlRpcValue result)
 {
     return client.ExecuteCheckDone(result);
 }
Example #60
0
 internal static CachedXmlRpcClient clientForNode(string nodename)
 {
     XmlRpcValue args = new XmlRpcValue();
     args.Set(0, this_node.Name);
     args.Set(1, nodename);
     XmlRpcValue resp = new XmlRpcValue();
     XmlRpcValue payl = new XmlRpcValue();
     if (!execute("lookupNode", args, resp, payl, true))
         return null;
     if (!XmlRpcManager.Instance.validateXmlrpcResponse("lookupNode", resp, payl))
         return null;
     string nodeuri = payl.GetString();
     string nodehost = null;
     int nodeport = 0;
     if (!network.splitURI(nodeuri, ref nodehost, ref nodeport) || nodehost == null || nodeport <= 0)
         return null;
     return XmlRpcManager.Instance.getXMLRPCClient(nodehost, nodeport, nodeuri);
 }