コード例 #1
0
        private MethodInfo FindMethod(Call serviceCall, object instanceDriver)
        {
            string serviceName = serviceCall.service;

            foreach (var m in instanceDriver.GetType().GetMethods())
            {
                if (m.Name.Equals(serviceName, System.StringComparison.InvariantCultureIgnoreCase))
                    return m;
            }

            return null;
        }
コード例 #2
0
        private void HandleStreamCall(Call serviceCall, CallContext messageContext)
        {
            if (serviceCall.serviceType == ServiceType.STREAM)
            {
                NetworkDevice networkDevice = messageContext.callerNetworkDevice;

                string host = Util.GetHost(networkDevice.networkDeviceName);
                for (int i = 0; i < serviceCall.channels; i++)
                {
                    ClientConnection con = gateway.OpenActiveConnection(host + ":" + serviceCall.channelIDs[i], serviceCall.channelType);
                    messageContext.AddConnection(con);
                }
            }
        }
コード例 #3
0
ファイル: DeviceDriver.cs プロジェクト: LBNunes/Avatar
        public void Handshake(Call serviceCall, Response serviceResponse, CallContext messageContext)
        {
            string deviceParameter = serviceCall.GetParameterString(DEVICE_KEY);

            if (deviceParameter == null)
            {
                serviceResponse.error = "No 'device' parameter informed.";
                return;
            }

            try
            {
                UpDevice device = UpDevice.FromJSON(Json.Deserialize(deviceParameter));

                gateway.deviceManager.RegisterDevice(device);

                serviceResponse.AddParameter(DEVICE_KEY, Json.Serialize(gateway.currentDevice.ToJSON()));

                //TODO: actually implement the driver register for other devices...
                //Response driversResponse = gateway.CallService(device, new Call("uos.DeviceDriver", "listDrivers"));
                //object driverList = driversResponse.GetResponseData("driverList");
                //if (driverList != null)
                //{
                //    var driverMap = (IDictionary<string, object>)Json.Deserialize(driverList.ToString());
                //    // TODO: this is duplicated with DeviceManager.registerRemoteDriverInstances
                //    foreach (string id in driverMap.Keys)
                //    {
                //        UpDriver upDriver = UpDriver.FromJSON(Json.Deserialize(driverMap[id].ToString()));
                //        DriverModel driverModel = new DriverModel(id, upDriver, device.name);
                //        gateway.driverManager.Insert(driverModel);
                //    }
                //}
            }
            catch (System.Exception e)
            {
                serviceResponse.error = e.Message;
                logger.LogError("Problems on handshake: " + e.Message + "," + e.StackTrace);
            }
        }
コード例 #4
0
        public Response CallService(object instance, Call call, CallContext context)
        {
            MethodInfo method = FindMethod(call, instance);

            if (method != null)
            {
                logger.Log(
                    "Calling service '" + call.service + "' of driver '" + call.driver + "' on instance '" + call.instanceId + "'");

                HandleStreamCall(call, context);

                Response response = new Response();
                method.Invoke(instance, new object[] { call, response, context });

                logger.Log("Finished service call.");
                return response;
            }
            else
                throw new System.Exception(
                    "No Service Implementation found for service '" + call.service +
                    "' on driver '" + call.driver + "' with id '" + call.instanceId + "'.");
        }
コード例 #5
0
ファイル: UnityGateway.cs プロジェクト: LBNunes/Avatar
        private void SendRegister(UpDevice device, IDictionary<string, object> parameters, ListenerInfo info)
        {
            // Send the event register request to the called device
            Call serviceCall = new Call(info.driver, REGISTER_LISTENER_SERVICE, info.instanceId);
            serviceCall.AddParameter(REGISTER_EVENT_LISTENER_EVENT_KEY_PARAMETER, info.eventKey);
            if (parameters != null)
            {
                foreach (var pair in parameters)
                {
                    if (pair.Key.Equals(REGISTER_EVENT_LISTENER_EVENT_KEY_PARAMETER, System.StringComparison.InvariantCultureIgnoreCase))
                        throw new System.ArgumentException("Can't use reserved keys as parameters for registerForEvent");
                    serviceCall.AddParameter(pair.Key, pair.Value);
                }
            }

            Response response = CallService(device, serviceCall);
            if (response == null)
                throw new System.Exception("No response received during register process.");
            else if (!string.IsNullOrEmpty(response.error))
                throw new System.Exception(response.error);
        }
コード例 #6
0
ファイル: UnityGateway.cs プロジェクト: LBNunes/Avatar
 private Response RemoteServiceCall(
     UpDevice target,
     Call serviceCall,
     StreamConnectionThreadData[] streamData,
     CallContext messageContext)
 {
     try
     {
         logger.Log("Call service on " + target.name + ": " + Json.Serialize(serviceCall.ToJSON()));
         // Encodes and sends call message.
         string msg = Json.Serialize(serviceCall.ToJSON()) + "\n";
         Response r;
         string responseMsg = SendMessage(msg, target);
         if (responseMsg != null)
         {
             r = Response.FromJSON(Json.Deserialize(responseMsg));
             r.messageContext = messageContext;
             return r;
         }
         else
             throw new System.Exception("No response received from call.");
     }
     catch (System.Exception e)
     {
         logger.LogError("Error on remote service call: " + e.ToString());
         CloseStreams(streamData);
         throw new ServiceCallException(e);
     }
 }
コード例 #7
0
ファイル: UnityGateway.cs プロジェクト: LBNunes/Avatar
        private StreamConnectionThreadData[] OpenStreamChannel(UpDevice device, Call serviceCall, CallContext messageContext)
        {
            StreamConnectionThreadData[] data = null;

            //Channel type decision
            string netType = null;
            if (serviceCall.channelType != null)
                netType = serviceCall.channelType;
            else
            {
                UpNetworkInterface network = GetAppropriateInterface(device);
                netType = network.netType;
            }

            int channels = serviceCall.channels;
            data = new StreamConnectionThreadData[channels];
            string[] channelIDs = new string[channels];

            for (int i = 0; i < channels; i++)
            {
                NetworkDevice networkDevice = GetAvailableNetworkDevice(netType);
                channelIDs[i] = Util.GetPort(networkDevice.networkDeviceName);
                StreamConnectionThreadData thread = new StreamConnectionThreadData(this, messageContext, networkDevice);
                thread.thread.Start();
                data[i] = thread;
            }

            serviceCall.channelIDs = channelIDs;
            serviceCall.channelType = netType;

            return data;
        }
コード例 #8
0
ファイル: UnityGateway.cs プロジェクト: LBNunes/Avatar
        private Response LocalServiceCall(
            Call serviceCall,
            StreamConnectionThreadData[] streamData,
            CallContext messageContext)
        {
            logger.Log("Handling Local ServiceCall");

            try
            {
                Response response = HandleServiceCall(serviceCall, messageContext);
                response.messageContext = messageContext;

                return response;
            }
            catch (System.Exception e)
            {
                // if there was an opened stream channel, it must be closed
                CloseStreams(streamData);
                throw new ServiceCallException(e);
            }
        }
コード例 #9
0
ファイル: UnityGateway.cs プロジェクト: LBNunes/Avatar
 private bool IsApplicationCall(Call serviceCall)
 {
     return (serviceCall.driver != null) && serviceCall.driver.Equals("app", System.StringComparison.InvariantCultureIgnoreCase);
 }
コード例 #10
0
ファイル: DeviceManager.cs プロジェクト: LBNunes/Avatar
        private void FindDrivers(HashSet<string> unknownDrivers, UpDevice upDevice)
        {
            Call call = new Call(DEVICE_DRIVER_NAME, "tellEquivalentDrivers", null);
            call.AddParameter(DRIVERS_NAME_KEY, Json.Serialize(new List<string>(unknownDrivers)));

            try
            {
                Response equivalentDriverResponse = gateway.CallService(upDevice, call);

                if ((equivalentDriverResponse != null) && string.IsNullOrEmpty(equivalentDriverResponse.error))
                {
                    string interfaces = equivalentDriverResponse.GetResponseString(INTERFACES_KEY);

                    if (interfaces != null)
                    {
                        List<UpDriver> drivers = new List<UpDriver>();
                        List<object> interfacesJson = Json.Deserialize(interfaces) as List<object>;

                        for (int i = 0; i < interfacesJson.Count; ++i)
                        {
                            UpDriver upDriver = UpDriver.FromJSON(Json.Deserialize(interfacesJson[i] as string));
                            drivers.Add(upDriver);
                        }

                        try
                        {
                            driverManager.AddToEquivalenceTree(drivers);
                        }
                        catch (InterfaceValidationException)
                        {
                            logger.LogError("Not possible to add to equivalence tree due to wrong interface specification.");
                        }

                        foreach (DriverModel dependent in dependents)
                        {
                            try
                            {
                                driverManager.Insert(dependent);
                            }
                            catch (DriverNotFoundException)
                            {
                                logger.LogError(
                                    "Not possible to register driver '" +
                                    dependent.driver.name + "' due to unknown equivalent driver.");
                            }
                            catch (System.Exception)
                            {
                                logger.LogError(
                                    "Problems occurred in the registering of driver '" +
                                    dependent.driver.name + "' with instanceId '" + dependent.id +
                                    "' in the device '" + upDevice.name + "' and it will not be registered.");
                            }
                        }
                    }
                    else
                        logger.LogError(
                            "Not possible to call service on device '" + upDevice.name +
                            "' for no equivalent drivers on the service response.");
                }
                else
                {
                    logger.LogError(
                        "Not possible to call service on device '" + upDevice.name +
                        (equivalentDriverResponse == null ? ": null" : "': Cause : " + equivalentDriverResponse.error));
                }
            }
            catch (ServiceCallException)
            {
                logger.LogError("Not possible to call service on device '" + upDevice.name);
            }
        }
コード例 #11
0
ファイル: DeviceDriver.cs プロジェクト: LBNunes/Avatar
 public void Goodbye(Call serviceCall, Response serviceResponse, CallContext messageContext)
 {
     gateway.deviceManager.DeviceLeft(messageContext.callerNetworkDevice);
 }
コード例 #12
0
ファイル: DeviceDriver.cs プロジェクト: LBNunes/Avatar
        public void ListDrivers(Call serviceCall, Response serviceResponse, CallContext messageContext)
        {
            logger.Log("Handling DeviceDriverImpl#listDrivers service");

            try
            {
                IDictionary<string, object> parameters = serviceCall.parameters;
                DriverManager driverManager = gateway.driverManager;

                // Handles parameters to filter message...
                IList<DriverData> listDrivers =
                    driverManager.ListDrivers(
                        ((parameters != null) ? (parameters[DRIVER_NAME_KEY] as string) : null),
                        gateway.currentDevice.name
                    );

                IDictionary<string, object> driversList = new Dictionary<string, object>();
                if ((listDrivers != null) && (listDrivers.Count > 0))
                {
                    foreach (var driver in listDrivers)
                        driversList[driver.instanceID] = driver.driver.ToJSON();
                }

                IDictionary<string, object> responseData = new Dictionary<string, object>();
                responseData[DRIVER_LIST_KEY] = driversList;
                serviceResponse.responseData = responseData;
            }
            catch (System.Exception e)
            {
                serviceResponse.error = e.Message;
                logger.LogError("Problem on ListDrivers service: " + e.Message + "," + e.StackTrace);
            }
        }
コード例 #13
0
ファイル: UnityGateway.cs プロジェクト: LBNunes/Avatar
        private void UnregisterForEvent(ListenerInfo listenerInfo)
        {
            // Send the event register request to the called device
            Call call = new Call(listenerInfo.driver, UNREGISTER_LISTENER_SERVICE, listenerInfo.instanceId);
            call.AddParameter(REGISTER_EVENT_LISTENER_EVENT_KEY_PARAMETER, listenerInfo.eventKey);

            Response response = CallService(listenerInfo.device, call);
            if (response == null)
                throw new ServiceCallException("No response receive from unregister service call.");
            if (!string.IsNullOrEmpty(response.error))
                throw new ServiceCallException(response.error);
        }
コード例 #14
0
ファイル: DriverManager.cs プロジェクト: LBNunes/Avatar
        public Response HandleServiceCall(Call serviceCall, CallContext messageContext)
        {
            //Handle named InstanceCall
            DriverModel model = null;
            if (serviceCall.instanceId != null)
            {
                //Find DriversInstance
                lock (_driverdao_lock) { model = driverDao.Retrieve(serviceCall.instanceId, currentDevice.name); }
                if (model == null)
                {
                    logger.LogError("No Instance found with id '" + serviceCall.instanceId + "'");
                    throw new System.Exception("No Instance found with id '" + serviceCall.instanceId + "'");
                }
            }
            else
            {
                //Handle non-named InstanceCall
                List<DriverModel> list;
                lock (_driverdao_lock) { list = driverDao.List(serviceCall.driver, currentDevice.name); }
                //Tries to find an equivalent driver...
                if ((list == null) || (list.Count == 0))
                {
                    TreeNode driverNode = null;
                    if (!driverHash.TryGetValue(serviceCall.driver, out driverNode))
                    {
                        logger.Log("No instance found for handling driver '" + serviceCall.driver + "'");
                        throw new System.Exception("No instance found for handling driver '" + serviceCall.driver + "'");
                    }

                    list = FindEquivalentDriver(driverNode.children);
                    if ((list == null) || (list.Count == 0))
                    {
                        logger.Log("No instance found for handling driver '" + serviceCall.driver + "'");
                        throw new System.Exception("No instance found for handling driver '" + serviceCall.driver + "'");
                    }
                }

                // Select the first driver found (since no specific instance was informed)
                model = list[0];
            }

            return gateway.reflectionServiceCaller.CallService(instances[model.rowid], serviceCall, messageContext);
        }
コード例 #15
0
ファイル: Call.cs プロジェクト: LBNunes/Avatar
        public static Call FromJSON(object jsonObj)
        {
            Call call = new Call();
            Message.FromJSON(call, jsonObj);

            IDictionary<string, object> json = jsonObj as IDictionary<string, object>;

            call.driver = Util.JsonOptString(json, "driver");
            call.service = Util.JsonOptString(json, "service");
            call.parameters = Util.JsonOptField(json, "parameters") as IDictionary<string, object>;
            call.instanceId = Util.JsonOptString(json, "instanceId");
            call.serviceType = Util.JsonOptEnum<ServiceType>(json, "serviceType", call.serviceType);
            call.channels = Util.JsonOptInt(json, "channels", call.channels);

            List<string> ids = Util.JsonOptField(json, "channelIDs") as List<string>;
            if (ids != null)
            {
                call.channelIDs = new string[ids.Count];
                ids.CopyTo(call.channelIDs, 0);
            }

            call.channelType = Util.JsonOptString(json, "channelType");
            call.securityType = Util.JsonOptString(json, "securityType");

            return call;
        }
コード例 #16
0
ファイル: UnityGateway.cs プロジェクト: lhsantos/ubimon
 private bool IsApplicationCall(Call serviceCall)
 {
     return((serviceCall.driver != null) && serviceCall.driver.Equals("app", System.StringComparison.InvariantCultureIgnoreCase));
 }
コード例 #17
0
        private void FindDrivers(HashSet <string> unknownDrivers, UpDevice upDevice)
        {
            Call call = new Call(DEVICE_DRIVER_NAME, "tellEquivalentDrivers", null);

            call.AddParameter(DRIVERS_NAME_KEY, Json.Serialize(new List <string>(unknownDrivers)));

            try
            {
                Response equivalentDriverResponse = gateway.CallService(upDevice, call);

                if ((equivalentDriverResponse != null) && string.IsNullOrEmpty(equivalentDriverResponse.error))
                {
                    string interfaces = equivalentDriverResponse.GetResponseString(INTERFACES_KEY);

                    if (interfaces != null)
                    {
                        List <UpDriver> drivers        = new List <UpDriver>();
                        List <object>   interfacesJson = Json.Deserialize(interfaces) as List <object>;

                        for (int i = 0; i < interfacesJson.Count; ++i)
                        {
                            UpDriver upDriver = UpDriver.FromJSON(Json.Deserialize(interfacesJson[i] as string));
                            drivers.Add(upDriver);
                        }

                        try
                        {
                            driverManager.AddToEquivalenceTree(drivers);
                        }
                        catch (InterfaceValidationException)
                        {
                            logger.LogError("Not possible to add to equivalence tree due to wrong interface specification.");
                        }

                        foreach (DriverModel dependent in dependents)
                        {
                            try
                            {
                                driverManager.Insert(dependent);
                            }
                            catch (DriverNotFoundException)
                            {
                                logger.LogError(
                                    "Not possible to register driver '" +
                                    dependent.driver.name + "' due to unknown equivalent driver.");
                            }
                            catch (System.Exception)
                            {
                                logger.LogError(
                                    "Problems occurred in the registering of driver '" +
                                    dependent.driver.name + "' with instanceId '" + dependent.id +
                                    "' in the device '" + upDevice.name + "' and it will not be registered.");
                            }
                        }
                    }
                    else
                    {
                        logger.LogError(
                            "Not possible to call service on device '" + upDevice.name +
                            "' for no equivalent drivers on the service response.");
                    }
                }
                else
                {
                    logger.LogError(
                        "Not possible to call service on device '" + upDevice.name +
                        (equivalentDriverResponse == null ? ": null" : "': Cause : " + equivalentDriverResponse.error));
                }
            }
            catch (ServiceCallException)
            {
                logger.LogError("Not possible to call service on device '" + upDevice.name);
            }
        }
コード例 #18
0
ファイル: UnityGateway.cs プロジェクト: LBNunes/Avatar
        /// <summary>
        /// Calls a service and waits for response.
        /// </summary>
        /// <param name="device"></param>
        /// <param name="serviceCall"></param>
        /// <returns></returns>
        public Response CallService(UpDevice device, Call serviceCall)
        {
            if (
                    (serviceCall == null) ||
                    (serviceCall.driver == null) || (serviceCall.driver.Length == 0) ||
                    (serviceCall.service == null) || (serviceCall.service.Length == 0))
                throw new System.ArgumentException("Service Driver or Service Name is empty");

            StreamConnectionThreadData[] streamConData = null;

            CallContext messageContext = new CallContext();

            messageContext.callerNetworkDevice = new LoopbackDevice(1);

            // In case of a Stream Service, a Stream Channel must be opened
            if (serviceCall.serviceType == ServiceType.STREAM)
                streamConData = OpenStreamChannel(device, serviceCall, messageContext);

            if (IsLocalCall(device))
                return LocalServiceCall(serviceCall, streamConData, messageContext);
            else
                return RemoteServiceCall(device, serviceCall, streamConData, messageContext);
        }
コード例 #19
0
ファイル: UnityGateway.cs プロジェクト: LBNunes/Avatar
 /// <summary>
 /// Starts an asynchronous service call that will notify callback when any response is done.
 /// </summary>
 /// <param name="device"></param>
 /// <param name="serviceCall"></param>
 /// <param name="callback"></param>
 /// <param name="state"></param>
 public void CallServiceAsync(
     UpDevice device,
     Call serviceCall,
     uOSServiceCallBack callback,
     object state = null
 )
 {
     uOSServiceCallInfo info = new uOSServiceCallInfo { device = device, call = serviceCall, asyncState = state };
     new Thread(new ThreadStart(
         delegate()
         {
             try
             {
                 Response r = CallService(device, serviceCall);
                 PushEvent(callback, info, r, null);
             }
             catch (System.Exception e) { PushEvent(callback, info, null, e); }
         })
     ).Start();
 }
コード例 #20
0
ファイル: DeviceDriver.cs プロジェクト: LBNunes/Avatar
        /// <summary>
        /// This method is responsible for informing the unknown equivalent driverss.
        /// </summary>
        /// <param name="serviceCall"></param>
        /// <param name="serviceResponse"></param>
        /// <param name="messageContext"></param>
        public void TellEquivalentDrivers(Call serviceCall, Response serviceResponse, CallContext messageContext)
        {
            try
            {
                string equivalentDrivers = serviceCall.GetParameterString(DRIVERS_NAME_KEY);
                IList<object> equivalentDriversJson = Json.Deserialize(equivalentDrivers) as IList<object>;
                List<object> jsonList = new List<object>();
                IDictionary<string, object> responseData = new Dictionary<string, object>();

                for (int i = 0; i < equivalentDriversJson.Count; i++)
                {
                    string equivalentDriver = equivalentDriversJson[i] as string;
                    UpDriver driver = gateway.driverManager.GetDriverFromEquivalanceTree(equivalentDriver);

                    if (driver != null)
                        AddToEquivalanceList(jsonList, driver);
                }

                responseData[INTERFACES_KEY] = Json.Serialize(jsonList);
                serviceResponse.responseData = responseData;
            }
            catch (System.Exception e)
            {
                logger.LogError("Problems on equivalent drivers. " + e.StackTrace);
            }
        }
コード例 #21
0
ファイル: UnityGateway.cs プロジェクト: LBNunes/Avatar
        public Response HandleServiceCall(Call serviceCall, CallContext messageContext)
        {
            NetworkDevice netDevice = messageContext.callerNetworkDevice;
            if (netDevice != null)
            {
                if (netDevice is LoopbackDevice)
                    messageContext.callerDevice = currentDevice;
                else
                {
                    string addr = Util.GetHost(netDevice.networkDeviceName);
                    string type = netDevice.networkDeviceType;
                    messageContext.callerDevice = deviceManager.RetrieveDevice(addr, type);
                }
            }

            if (IsApplicationCall(serviceCall))
            {
                if (app == null)
                    throw new System.InvalidOperationException("No valid app instance set.");
                return reflectionServiceCaller.CallService(app, serviceCall, messageContext);
            }
            else
                return driverManager.HandleServiceCall(serviceCall, messageContext);
        }
コード例 #22
0
ファイル: UnityGateway.cs プロジェクト: LBNunes/Avatar
 private Call BuildRegisterCall(IDictionary<string, object> parameters, ListenerInfo info)
 {
     Call serviceCall = new Call(info.driver, REGISTER_LISTENER_SERVICE, info.instanceId);
     serviceCall.AddParameter(REGISTER_EVENT_LISTENER_EVENT_KEY_PARAMETER, info.eventKey);
     if (parameters != null)
     {
         foreach (var pair in parameters)
         {
             if (pair.Key.Equals(REGISTER_EVENT_LISTENER_EVENT_KEY_PARAMETER, System.StringComparison.InvariantCultureIgnoreCase))
                 throw new System.ArgumentException("Can't use reserved keys as parameters for registerForEvent");
             serviceCall.AddParameter(pair.Key, pair.Value);
         }
     }
     return serviceCall;
 }
コード例 #23
0
ファイル: DeviceManager.cs プロジェクト: LBNunes/Avatar
        private UpDevice DoHandshake(NetworkDevice device)
        {
            try
            {
                // Create a Dummy device just for calling it
                logger.Log("Trying to handshake with device : " + device.networkDeviceName);

                UpDevice dummyDevice = new UpDevice(device.networkDeviceName);
                dummyDevice.AddNetworkInterface(device.networkDeviceName, device.networkDeviceType);

                Call call = new Call(DEVICE_DRIVER_NAME, "handshake", null);
                call.AddParameter("device", Json.Serialize(currentDevice.ToJSON()));

                Response response = gateway.CallService(dummyDevice, call);
                if ((response != null) && string.IsNullOrEmpty(response.error))
                {
                    // in case of a success greeting process, register the device in the neighborhood database
                    object responseDevice = response.GetResponseData("device");
                    if (responseDevice != null)
                    {
                        UpDevice remoteDevice;
                        if (responseDevice is string)
                            remoteDevice = UpDevice.FromJSON(Json.Deserialize(responseDevice as string));
                        else
                            remoteDevice = UpDevice.FromJSON(responseDevice);

                        RegisterDevice(remoteDevice);
                        logger.Log("Registered device " + remoteDevice.name);

                        return remoteDevice;
                    }
                    else
                        logger.LogError(
                            "Not possible complete handshake with device '" + device.networkDeviceName +
                            "' for no device on the handshake response.");
                }
                else
                {
                    logger.LogError(
                        "Not possible to handshake with device '" +
                        device.networkDeviceName +
                        (response == null ? ": No Response received." : "': Cause : " + response.error));
                }
            }
            catch (System.Exception e)
            {
                logger.Log(e.StackTrace);
                logger.LogError("Not possible to handshake with device '" + device.networkDeviceName + "'. " + e.Message);
            }

            return null;
        }