Exemple #1
0
    public async Task <ServiceReply> Unsubscribe(string topic)
    {
        // Repeated fields cannot be instantiated in SerivceRequest creation; adding topic to unsubscribeTopics which is later sent to server with clientID
        RepeatedField <string> unsubscribeTopics = new RepeatedField <string>();

        unsubscribeTopics.Add(topic);

        Debug.Log("Unsubscribe from topic: " + topic + " (backend) + unsubscribeRepeatedField: " + unsubscribeTopics.Count);

        ServiceRequest topicUnsubscription = new ServiceRequest
        {
            Topic             = DEFAULT_TOPICS.SERVICES.TOPIC_SUBSCRIPTION,
            TopicSubscription = new TopicSubscription
            {
                ClientId          = clientSpecification.Id,
                UnsubscribeTopics = { unsubscribeTopics }
            }
        };

        var          task     = CallService(topicUnsubscription);
        ServiceReply subReply = await task;

        if (subReply.Error != null)
        {
            Debug.LogError("subReply Error! Error msg: " + subReply.Error.ToString());
            return(null);
        }

        // removing callback function from dictionary
        netmqTopicDataClient.RemoveTopicDataCallback(topic);

        return(subReply);
    }
Exemple #2
0
    // Topic subscription, called from upper layer (i.e. some MonoBahavior
    public async Task <ServiceReply> Subscribe(string topic, Action <TopicDataRecord> function)
    {
        // Repeated fields cannot be instantiated in SerivceRequest creation
        RepeatedField <string> subscribeTopics = new RepeatedField <string>();

        subscribeTopics.Add(topic);
        Debug.Log("Subscribing to topic: " + topic + " (backend), subscribeRepeatedField: " + subscribeTopics.Count);
        ServiceRequest topicSubscription = new ServiceRequest
        {
            Topic             = DEFAULT_TOPICS.SERVICES.TOPIC_SUBSCRIPTION,
            TopicSubscription = new TopicSubscription
            {
                ClientId        = clientSpecification.Id,
                SubscribeTopics = { subscribeTopics }
            }
        };

        var          task     = CallService(topicSubscription);
        ServiceReply subReply = await task;

        if (subReply.Error != null)
        {
            Debug.LogError("subReply Error! Error msg: " + subReply.Error.ToString());
            return(null);
        }

        // adding callback function to dictionary
        netmqTopicDataClient.AddTopicDataCallback(topic, function);

        return(subReply);
    }
Exemple #3
0
    private async Task <bool> UnsubscribeTopic(List <string> topics)
    {
        // Repeated fields cannot be instantiated in SerivceRequest creation; adding topic to unsubscribeTopics which is later sent to server with clientID
        RepeatedField <string> unsubscribeTopics = new RepeatedField <string>();

        unsubscribeTopics.Add(topics);
        ServiceRequest topicUnsubscription = new ServiceRequest
        {
            Topic             = UbiiConstants.Instance.DEFAULT_TOPICS.SERVICES.TOPIC_SUBSCRIPTION,
            TopicSubscription = new TopicSubscription
            {
                ClientId          = clientSpecification.Id,
                UnsubscribeTopics = { unsubscribeTopics }
            }
        };

        ServiceReply subReply = await CallService(topicUnsubscription);

        if (subReply.Error != null)
        {
            Debug.LogError("subReply Error! Error msg: " + subReply.Error.ToString());
            return(false);
        }

        foreach (string topic in topics)
        {
            topicDataClient.RemoveAllTopicCallbacks(topic);
        }
        return(true);
    }
Exemple #4
0
    public Task <ServiceReply> CallService(ServiceRequest request)
    {
        return(Task.Run <ServiceReply>(() =>
        {
            string json = request.ToString();

            string url = "http://" + this.host + ":" + this.port + "/services";

            var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method = "POST";

            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                streamWriter.Write(json);
            }
            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            var service_reply = new ServiceReply();

            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var responseText = streamReader.ReadToEnd();
                try
                {
                    service_reply = ServiceReply.Parser.ParseJson(responseText);
                }
                catch (Exception ex)
                {
                    Debug.LogError(ex.ToString());
                }
            }

            return service_reply;
        }));
    }
Exemple #5
0
    public async Task <ServiceReply> SubscribeRegex(string regex, Action <TopicDataRecord> function)
    {
        //Debug.Log("Subscribing to topic: " + topic + " (backend), subscribeRepeatedField: " + subscribeTopics.Count);
        ServiceRequest topicSubscription = new ServiceRequest
        {
            Topic             = DEFAULT_TOPICS.SERVICES.TOPIC_SUBSCRIPTION,
            TopicSubscription = new TopicSubscription
            {
                ClientId             = clientSpecification.Id,
                SubscribeTopicRegexp = regex
            }
        };

        ServiceReply subReply = await CallService(topicSubscription);

        if (subReply.Error != null)
        {
            Debug.LogError("subReply Error! Error msg: " + subReply.Error.ToString());
            return(null);
        }

        // adding callback function to dictionary
        netmqTopicDataClient.AddTopicDataRegexCallback(regex, function);

        return(subReply);
    }
Exemple #6
0
    /// <summary>
    /// Callback for start session subscription
    /// </summary>
    /// <param name="record"></param>
    public async void OnStartSession(TopicDataRecord record)
    {
        List <ProcessingModule> localPMs = new List <ProcessingModule>();

        foreach (Ubii.Processing.ProcessingModule pm in record.Session.ProcessingModules)
        {
            if (pm.NodeId == this.GetID())
            {
                //Debug.Log("UbiiNode.OnStartSession() - applicable pm: " + pm);
                ProcessingModule newModule = this.processingModuleManager.CreateModule(pm);
                //Debug.Log("UbiiNode.OnStartSession() - created instance: " + newModule.ToString());
                if (newModule != null)
                {
                    localPMs.Add(newModule);
                }
            }
        }

        Google.Protobuf.Collections.RepeatedField <Ubii.Processing.ProcessingModule> elements = new Google.Protobuf.Collections.RepeatedField <Ubii.Processing.ProcessingModule>();
        foreach (ProcessingModule pm in localPMs)
        {
            elements.Add(pm.ToProtobuf());
        }
        ServiceRequest pmRuntimeAddRequest = new ServiceRequest
        {
            Topic = UbiiConstants.Instance.DEFAULT_TOPICS.SERVICES.PM_RUNTIME_ADD,
            ProcessingModuleList = new Ubii.Processing.ProcessingModuleList
            {
                Elements = { elements }
            }
        };
        //Debug.Log(nameof(OnStartSession) + " - runtime add request: " + pmRuntimeAddRequest);

        ServiceReply reply = await CallService(pmRuntimeAddRequest);

        //Debug.Log("start session runtime add PMs reply: " + reply);
        if (reply.Success != null)
        {
            try
            {
                bool success = await this.processingModuleManager.ApplyIOMappings(record.Session.IoMappings, record.Session.Id);

                foreach (var pm in localPMs)
                {
                    this.processingModuleManager.StartModule(new Ubii.Processing.ProcessingModule {
                        Id = pm.Id
                    });
                }
            }
            catch (Exception e)
            {
                Debug.LogError(e.ToString());
            }
        }
        else
        {
            //TODO: delete modules
        }
    }
Exemple #7
0
    public async Task <ServiceReply> RegisterDevice(Device ubiiDevice)
    {
        ServiceReply reply = await CallService(new ServiceRequest
        {
            Topic  = UbiiConstants.Instance.DEFAULT_TOPICS.SERVICES.DEVICE_REGISTRATION,
            Device = ubiiDevice
        });

        return(reply);
    }
Exemple #8
0
    public async Task <ServiceReply> RegisterDevice(Ubii.Devices.Device ubiiDevice)
    {
        ServiceReply deviceRegReply = await networkClient.RegisterDevice(ubiiDevice);

        if (deviceRegReply.Error == null)
        {
            registeredDevices.Add(deviceRegReply.Device.Id, deviceRegReply.Device);
        }

        return(deviceRegReply);
    }
    private async Task InitServerSpec()
    {
        // Call Service to receive serverSpecifications
        ServiceRequest serverConfigRequest = new ServiceRequest {
            Topic = UbiiConstants.Instance.DEFAULT_TOPICS.SERVICES.SERVER_CONFIG
        };

        var          task = CallService(serverConfigRequest);
        ServiceReply rep  = await task;

        serverSpecification = rep.Server;
    }
Exemple #10
0
        public MessageBase Read(SlpReader reader)
        {
            var v = reader.ReadByte();
            if (v != 1 && v != 2)
                throw new ServiceProtocolException(ServiceErrorCode.VersionNotSupported);

            var tmp = reader.ReadByte();
            MessageBase result = null;
            switch (tmp)
            {
                case 1:
                    result = new ServiceRequest();
                    break;
                case 2:
                    result = new ServiceReply();
                    break;
                case 3:
                    result = new ServiceRegistrationRequest();
                    break;
                case 4:
                    result = new ServiceDeregistrationRequest();
                    break;
                case 5:
                    result = new ServiceAcknowledgement();
                    break;
                case 6:
                    result = new AttributeRequest();
                    break;
                case 7:
                    result = new AttributeReply();
                    break;
                case 8:
                    result = new DirectoryAgentAdvert();
                    break;
                case 9:
                    result = new ServiceTypeRequest();
                    break;
                case 10:
                    result = new ServiceTypeReply();
                    break;
                case 11:
                    result = new ServiceAgentAdvert();
                    break;
                default:
                    throw new ServiceProtocolException(ServiceErrorCode.ParseError);
            }

            result.Version = v;
            result.Create(reader);

            return result;
        }
    public async Task <ServiceReply> RegisterDevice(Device ubiiDevice)
    {
        ServiceReply reply = await CallService(new ServiceRequest
        {
            Topic  = UbiiConstants.Instance.DEFAULT_TOPICS.SERVICES.DEVICE_REGISTRATION,
            Device = ubiiDevice
        });

        if (reply.Error == null)
        {
            registeredDevices.Add(reply.Device.Id, reply.Device);
        }

        return(reply);
    }
Exemple #12
0
    public async Task <ServiceReply> DeregisterDevice(Device ubiiDevice)
    {
        ServiceReply reply = await CallService(new ServiceRequest
        {
            Topic  = UbiiConstants.Instance.DEFAULT_TOPICS.SERVICES.DEVICE_DEREGISTRATION,
            Device = ubiiDevice
        });

        if (reply.Error != null)
        {
            Debug.LogError("Deregister Device Error: " + reply.Error.Message);
        }

        return(reply);
    }
Exemple #13
0
    private async void Initialize()
    {
        this.service_client = new UbiiServiceClientREST(this.host, this.service_port);

        // get server configuration
        ServiceRequest serverConfigRequest = new ServiceRequest {
            Topic = ubii.DEFAULT_TOPICS.SERVICES.SERVER_CONFIG
        };
        ServiceReply reply = await this.service_client.CallService(serverConfigRequest);

        if (reply.Server == null)
        {
            Debug.LogError("CallService(SERVER_CONFIG) failed");
            return;
        }
        server_config = reply.Server;
        Debug.Log("server_config: " + server_config);

        // register client
        ServiceRequest clientRegistrationRequest = new ServiceRequest {
            Topic  = ubii.DEFAULT_TOPICS.SERVICES.CLIENT_REGISTRATION,
            Client = new Ubii.Clients.Client {
                Name = client_name
            }
        };

        reply = await this.service_client.CallService(clientRegistrationRequest);

        if (reply.Client == null)
        {
            Debug.LogError("CallService(CLIENT_REGISTRATION) failed");
            return;
        }
        client_specification = reply.Client;
        Debug.Log("client_specification: " + client_specification);

        // setup topic data socket
        topicdata_client = new UbiiTopicDataClientWS(client_specification.Id, host, Int32.Parse(server_config.PortTopicDataWs));

        var test_topic = "/test/topic/unity";

        await Subscribe(test_topic, (TopicDataRecord record) =>
        {
            Debug.Log(record);
        });

        topicdata_client.SendTestTopicData(test_topic);
    }
Exemple #14
0
    public async Task <bool> SubscribeTopic(string topic, Action <TopicDataRecord> callback)
    {
        if (callback == null)
        {
            Debug.LogError("SubscribeTopic() - callback is NULL!");
            return(false);
        }

        if (this.topicDataClient.IsSubscribed(topic))
        {
            topicDataClient.AddTopicCallback(topic, callback);
            return(true);
        }

        // Repeated fields cannot be instantiated in SerivceRequest creation
        RepeatedField <string> subscribeTopics = new RepeatedField <string>();

        subscribeTopics.Add(topic);

        //Debug.Log("Subscribing to topic: " + topic + " (backend), subscribeRepeatedField: " + subscribeTopics.Count);
        ServiceRequest topicSubscription = new ServiceRequest
        {
            Topic             = UbiiConstants.Instance.DEFAULT_TOPICS.SERVICES.TOPIC_SUBSCRIPTION,
            TopicSubscription = new TopicSubscription
            {
                ClientId        = clientSpecification.Id,
                SubscribeTopics = { subscribeTopics }
            }
        };

        // adding callback function to dictionary
        topicDataClient.AddTopicCallback(topic, callback);

        ServiceReply subReply = await CallService(topicSubscription);

        //Debug.Log("UbiiNetworkClient.SubscribeTopic() - " + topic + " - reply: " + subReply);
        if (subReply.Error != null)
        {
            Debug.LogError("subReply Error! Error msg: " + subReply.Error.ToString());
            topicDataClient.RemoveTopicCallback(topic, callback);
            return(false);
        }

        return(true);
    }
    public async Task <ServiceReply> DeregisterDevice(Device ubiiDevice)
    {
        ServiceReply reply = await CallService(new ServiceRequest
        {
            Topic  = UbiiConstants.Instance.DEFAULT_TOPICS.SERVICES.DEVICE_DEREGISTRATION,
            Device = ubiiDevice
        });

        if (reply.Error != null)
        {
            Debug.LogError("Deregister Device Error: " + reply.Error.Message);
        }
        if (!registeredDevices.Remove(ubiiDevice.Id))
        {
            Debug.LogError("Device " + ubiiDevice.Name + " could not be removed from local list.");
        }
        Debug.Log("Deregistering " + ubiiDevice + " successful!");
        return(reply);
    }
Exemple #16
0
    // This is only for testing / demonstration purposes on how a device registration works with ubiiClient
    private async Task InitTestDevices()
    {
        // RepeatedFields have to be declared separately and then added to the service request
        RepeatedField <Ubii.Devices.Component> components = new RepeatedField <Ubii.Devices.Component>();

        components.Add(new Ubii.Devices.Component {
            Topic = "TestBool", MessageFormat = "boolean", IoType = Ubii.Devices.Component.Types.IOType.Input
        });

        // Device Registration
        ServiceRequest deviceRegistration = new ServiceRequest
        {
            Topic  = DEFAULT_TOPICS.SERVICES.DEVICE_REGISTRATION,
            Device = new Device
            {
                Name       = "TestDevice1",
                DeviceType = Device.Types.DeviceType.Participant,
                ClientId   = clientSpecification.Id,
                Components = { components }
            }
        };

        Debug.Log("DeviceRegistration #1 Components: " + deviceRegistration.ToString());

        var          task = CallService(deviceRegistration);
        ServiceReply svr  = await task;

        if (svr.Device != null)
        {
            deviceSpecifications.Add(svr.Device);
            Debug.Log("DeviceSpecifications #1: " + deviceSpecifications[0].ToString());
            Debug.Log("DeviceSpecifications #1 Components: " + deviceSpecifications[0].Components.ToString());
        }
        else if (svr.Error != null)
        {
            Debug.Log("SVR Error: " + svr.Error.ToString());
        }
        else
        {
            Debug.Log("An unknown error occured");
        }
    }
Exemple #17
0
    private async Task InitClientReg()
    {
        // Client Registration
        ServiceRequest clientRegistration = new ServiceRequest
        {
            Topic  = DEFAULT_TOPICS.SERVICES.CLIENT_REGISTRATION,
            Client = new Client {
                Name = name,
            },
        };

        if (id != null && id != "")
        {
            clientRegistration.Client.Id = id;
        }

        var          task = CallService(clientRegistration);
        ServiceReply rep  = await task;

        clientSpecification = rep.Client;
    }
Exemple #18
0
    public async Task <ServiceReply> CallService(ServiceRequest request)
    {
        Google.Protobuf.JsonFormatter.Settings settings = new Google.Protobuf.JsonFormatter.Settings(true).WithFormatEnumsAsIntegers(true);
        string              requestJSON = new Google.Protobuf.JsonFormatter(settings).Format(request);
        StringContent       content     = new StringContent(requestJSON, Encoding.UTF8, "application/json");
        HttpResponseMessage response    = await this.httpClient.PostAsync(this.serviceURL, content);

        string responseJSON = await response.Content.ReadAsStringAsync();

        //TODO: this is a stupid hack for the Google.Protobuf.JsonParser as the server JSON response includes an identifier for the
        // protocol buffer oneof field "type" that would result in an error

        /*string responseCleaned = Regex.Replace(responseJSON, ",\"type\":\".*\"", "");
         * responseCleaned = Regex.Replace(responseCleaned, "\"type\":\".*\"", "");*/

        ServiceReply serviceReply = Google.Protobuf.JsonParser.Default.Parse <ServiceReply>(responseJSON);

        return(serviceReply);

        //return new ServiceReply { Error = new Ubii.General.Error { Message = "not implemented" } };
    }
Exemple #19
0
    private async Task InitServerSpec()
    {
        // Call Service to receive serverSpecifications
        ServiceRequest serverConfigRequest = new ServiceRequest {
            Topic = UbiiConstants.Instance.DEFAULT_TOPICS.SERVICES.SERVER_CONFIG
        };

        ServiceReply reply = await CallService(serverConfigRequest);

        if (reply.Server != null)
        {
            serverSpecification = reply.Server;
        }
        else if (reply.Error != null)
        {
            Debug.LogError(reply.Error.ToString());
        }
        else
        {
            Debug.LogError("UbiiNetworkClient - unkown server response during server specification retrieval");
        }
    }
Exemple #20
0
    public async Task <bool> SubscribeRegex(string regex, Action <TopicDataRecord> callback)
    {
        if (callback == null)
        {
            Debug.LogError("SubscribeRegex() - callback is NULL!");
            return(false);
        }

        if (this.topicDataClient.IsSubscribed(regex))
        {
            topicDataClient.AddTopicRegexCallback(regex, callback);
            return(true);
        }

        //Debug.Log("Subscribing to topic: " + topic + " (backend), subscribeRepeatedField: " + subscribeTopics.Count);
        ServiceRequest subscriptionRequest = new ServiceRequest
        {
            Topic             = UbiiConstants.Instance.DEFAULT_TOPICS.SERVICES.TOPIC_SUBSCRIPTION,
            TopicSubscription = new TopicSubscription {
                ClientId = clientSpecification.Id
            }
        };

        subscriptionRequest.TopicSubscription.SubscribeTopicRegexp.Add(regex);

        ServiceReply subReply = await CallService(subscriptionRequest);

        if (subReply.Error != null)
        {
            Debug.LogError("subReply Error! Error msg: " + subReply.Error.ToString());
            return(false);
        }

        // adding callback function to dictionary
        topicDataClient.AddTopicRegexCallback(regex, callback);

        return(true);
    }
Exemple #21
0
    private async Task <bool> UnsubscribeRegex(string regex)
    {
        ServiceRequest unsubscribeRequest = new ServiceRequest
        {
            Topic             = UbiiConstants.Instance.DEFAULT_TOPICS.SERVICES.TOPIC_SUBSCRIPTION,
            TopicSubscription = new TopicSubscription {
                ClientId = clientSpecification.Id
            }
        };

        unsubscribeRequest.TopicSubscription.UnsubscribeTopicRegexp.Add(regex);

        ServiceReply subReply = await CallService(unsubscribeRequest);

        if (subReply.Error != null)
        {
            Debug.LogError("subReply Error! Error msg: " + subReply.Error.ToString());
            return(false);
        }
        // remove regex from topicdataclient
        topicDataClient.RemoveAllTopicRegexCallbacks(regex);
        return(true);
    }
Exemple #22
0
    private async Task <bool> InitClientRegistration(Ubii.Clients.Client clientSpecs)
    {
        ServiceRequest clientRegistration = new ServiceRequest
        {
            Topic  = UbiiConstants.Instance.DEFAULT_TOPICS.SERVICES.CLIENT_REGISTRATION,
            Client = clientSpecs
        };
        //if(isDedicatedProcessingNode)
        //  TODO:  clientRegistration.Client.ProcessingModules = ...

        ServiceReply reply = await CallService(clientRegistration);

        if (reply.Client != null)
        {
            clientSpecification = reply.Client;
            return(true);
        }
        else if (reply.Error != null)
        {
            Debug.LogError("UbiiNetworkClient.InitClientRegistration() - " + reply);
        }

        return(false);
    }
Exemple #23
0
        public MessageBase Read(SlpReader reader)
        {
            var v = reader.ReadByte();

            if (v != 1 && v != 2)
            {
                throw new ServiceProtocolException(ServiceErrorCode.VersionNotSupported);
            }

            var         tmp    = reader.ReadByte();
            MessageBase result = null;

            switch (tmp)
            {
            case 1:
                result = new ServiceRequest();
                break;

            case 2:
                result = new ServiceReply();
                break;

            case 3:
                result = new ServiceRegistrationRequest();
                break;

            case 4:
                result = new ServiceDeregistrationRequest();
                break;

            case 5:
                result = new ServiceAcknowledgement();
                break;

            case 6:
                result = new AttributeRequest();
                break;

            case 7:
                result = new AttributeReply();
                break;

            case 8:
                result = new DirectoryAgentAdvert();
                break;

            case 9:
                result = new ServiceTypeRequest();
                break;

            case 10:
                result = new ServiceTypeReply();
                break;

            case 11:
                result = new ServiceAgentAdvert();
                break;

            default:
                throw new ServiceProtocolException(ServiceErrorCode.ParseError);
            }

            result.Version = v;
            result.Create(reader);

            return(result);
        }