private static string GetEventIdentifier(UpDevice device, string driver, string instanceId, string eventKey) { StringBuilder id = new StringBuilder(); if ((device != null) && (device.name != null) && (device.name.Length > 0)) { id.Append("@" + device.name); } if ((driver != null) && (driver.Length > 0)) { id.Append("*" + driver); } if ((eventKey != null) && (eventKey.Length > 0)) { id.Append("." + eventKey); } if ((instanceId != null) && (instanceId.Length > 0)) { id.Append("#" + instanceId); } return(id.ToString()); }
public void Add(UpDevice device) { if (device.networks != null) { foreach (UpNetworkInterface ni in device.networks) { interfaceMap[GenerateInterfaceKey(ni)] = device; List<UpDevice> devices = null; if (!networkTypeMap.TryGetValue(ni.netType, out devices)) { devices = new List<UpDevice>(); networkTypeMap[ni.netType] = devices; } devices.Add(device); if (!addressMap.TryGetValue(ni.networkAddress, out devices)) { devices = new List<UpDevice>(); addressMap[ni.networkAddress] = devices; } devices.Add(device); } } deviceMap[device.name.ToLower()] = device; }
private bool IsLocalCall(UpDevice device) { return ((device == null) || (device.name == null) || (device.name.Equals(currentDevice.name, System.StringComparison.InvariantCultureIgnoreCase))); }
private UpNetworkInterface GetAppropriateInterface(UpDevice deviceProvider) { //List of compatible network interfaces List <UpNetworkInterface> compatibleNetworks = new List <UpNetworkInterface>(); //Solves the different network link problem: foreach (UpNetworkInterface thisNetInterface in currentDevice.networks) { foreach (UpNetworkInterface providerNetInterface in deviceProvider.networks) { if (thisNetInterface.netType.Equals(providerNetInterface.netType)) { compatibleNetworks.Add(providerNetInterface); break; } } } //Checks if none compatible interface is available if (compatibleNetworks.Count == 0) { logger.LogError("ConnectivityManager - Lacks connectivity between the devices for this service"); throw new System.Exception("ConnectivityManager - Lacks connectivity between the devices for this service"); } //Gets the best choice of network for this service //UpNetworkInterface networkInterface = servicesBestInterface(compatibleNetworks, serviceCall); //return networkInterface; return(compatibleNetworks[0]); }
/// <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)); } }
private List <ListenerInfo> FindListeners(UpDevice device, string driver, string instanceId, string eventKey) { List <ListenerInfo> listeners = null; // First filter the listeners by the event key. if (eventKey == null) { // In this case all eventKeys must be checked for the listener to be removed. listeners = new List <ListenerInfo>(); foreach (var list in listenerMap.Values) { listeners.AddRange(list); } } else { // In case a eventKey is informed, then only the listeners for that event key must be used. string eventIdentifier = GetEventIdentifier(device, driver, instanceId, eventKey); if (!listenerMap.TryGetValue(eventIdentifier, out listeners)) { listeners = null; } } return(listeners); }
public void Register( UOSEventListener listener, UpDevice device, string driver, string instanceId = null, string eventKey = null, IDictionary <string, object> parameters = null) { // If the listener is already registered it cannot be registered again string eventIdentifier = GetEventIdentifier(device, driver, instanceId, eventKey); logger.Log("Registering listener for event :" + eventIdentifier); List <ListenerInfo> list; if (!listenerMap.TryGetValue(eventIdentifier, out list)) { list = null; } if (FindListener(listener, list) == null) { ListenerInfo info = new ListenerInfo(); info.driver = driver; info.instanceId = instanceId; info.eventKey = eventKey; info.listener = listener; info.device = device; RegisterNewListener(device, parameters, eventIdentifier, info); } }
public void Add(UpDevice device) { if (device.networks != null) { foreach (UpNetworkInterface ni in device.networks) { interfaceMap[GenerateInterfaceKey(ni)] = device; List <UpDevice> devices = null; if (!networkTypeMap.TryGetValue(ni.netType, out devices)) { devices = new List <UpDevice>(); networkTypeMap[ni.netType] = devices; } devices.Add(device); if (!addressMap.TryGetValue(ni.networkAddress, out devices)) { devices = new List <UpDevice>(); addressMap[ni.networkAddress] = devices; } devices.Add(device); } } deviceMap[device.name.ToLower()] = device; }
/// <summary> /// Registers a device in the neighborhood of the current device. /// </summary> /// <param name="device">Device to be registered.</param> public void RegisterDevice(UpDevice device) { lock (_devicedao_lock) { deviceDao.Add(device); } }
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); } }
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); } }
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); }
/// <summary> /// Removes a listener for receiving Notify events and notifies the event driver of its removal. /// </summary> /// <param name="listener"></param> /// <param name="device"></param> /// <param name="driver"></param> /// <param name="instanceId"></param> /// <param name="eventKey"></param> public void Unregister( UOSEventListener listener, UpDevice device = null, string driver = null, string instanceId = null, string eventKey = null) { List <ListenerInfo> listeners = FindListeners(device, driver, instanceId, eventKey); if (listeners == null) { return; } System.Exception e = null; foreach (var li in listeners) { // only if its the same listener, it should be removed if (li.listener.Equals(listener)) { bool remove = true; // If the driver name is informed, and it's not the same, it must not be removed if ((driver != null) && (li.driver != null)) { remove = remove && li.driver.Equals(driver, System.StringComparison.InvariantCultureIgnoreCase); } // If the instanceId is informed, and it's not the same, it must not be removed if ((instanceId != null) && (li.instanceId != null)) { remove = remove && li.instanceId.Equals(instanceId, System.StringComparison.InvariantCultureIgnoreCase); } if (remove) { try { //Notify device of the listener removal UnregisterForEvent(li); } catch (System.Exception ex) { string id = GetEventIdentifier(device, driver, instanceId, eventKey); logger.LogError("Failed to unregister for event " + id + ": " + e.Message); e = ex; } } } } if (e != null) { throw e; } }
public void Notify(Notify notify, UpDevice device) { if (IsLocalCall(device)) { HandleNotify(notify, device); } else { RemoteNotify(notify, device); } }
public UpDevice Find(string name) { UpDevice device = null; if (deviceMap.TryGetValue(name.ToLower(), out device)) { return(device); } return(null); }
public static UpDevice FromJSON(object json) { IDictionary<string, object> dict = json as IDictionary<string, object>; UpDevice device = new UpDevice(); device.name = Util.JsonOptString(dict, "name"); device.networks = FromNetworks(dict); device.meta = FromMeta(dict); return device; }
public static UpDevice FromJSON(object json) { IDictionary <string, object> dict = json as IDictionary <string, object>; UpDevice device = new UpDevice(); device.name = Util.JsonOptString(dict, "name"); device.networks = FromNetworks(dict); device.meta = FromMeta(dict); return(device); }
public override bool Equals(object obj) { if (obj == null || !(obj is UpDevice)) { return(false); } UpDevice d = (UpDevice)obj; return (Util.Compare(this.name, d.name) && Util.Compare(this.networks, d.networks) && Util.Compare(this.meta, d.meta)); }
public DeviceManager( uOSSettings settings, UnityGateway gateway, UpDevice currentDevice) { this.gateway = gateway; this.logger = gateway.logger; this.currentDevice = currentDevice; this.deviceDao = new DeviceDAO(); this.deviceDao.Add(currentDevice); this.driverManager = gateway.driverManager; this.unknownDrivers = new HashSet <string>(); this.dependents = new HashSet <DriverModel>(); }
public DeviceManager( uOSSettings settings, UnityGateway gateway, UpDevice currentDevice) { this.gateway = gateway; this.logger = gateway.logger; this.currentDevice = currentDevice; this.deviceDao = new DeviceDAO(); this.deviceDao.Add(currentDevice); this.driverManager = gateway.driverManager; this.unknownDrivers = new HashSet<string>(); this.dependents = new HashSet<DriverModel>(); }
private void RemoteNotify(Notify notify, UpDevice device) { if ( device == null || notify == null || string.IsNullOrEmpty(notify.driver) || string.IsNullOrEmpty(notify.eventKey)) { throw new System.ArgumentException("Either the device or notification is invalid."); } string message = Json.Serialize(notify.ToJSON()); SendMessage(message, device, false); }
public void Delete(string name) { UpDevice device = Find(name); if (device.networks != null) { foreach (UpNetworkInterface ni in device.networks) { interfaceMap.Remove(GenerateInterfaceKey(ni)); networkTypeMap[ni.netType].Remove(device); addressMap[ni.networkAddress].Remove(device); } } deviceMap.Remove(name.ToLower()); }
/// <summary> /// Finds data about a device present in the neighborhood. /// </summary> /// <param name="networkAddress">Address of the Device to be found.</param> /// <param name="networkType">NetworkType of Address of the Device to be found.</param> /// <returns>The device, if found; null, otherwise.</returns> public UpDevice RetrieveDevice(string networkAddress, string networkType) { List <UpDevice> list; lock (_devicedao_lock) { list = deviceDao.List(networkAddress, networkType); } if ((list != null) && (list.Count > 0)) { UpDevice foundDevice = list[0]; logger.Log("Device with addr '" + networkAddress + "' found on network '" + networkType + "' resolved to " + foundDevice); return(foundDevice); } logger.Log("No device found with addr '" + networkAddress + "' on network '" + networkType + "'."); return(null); }
private void HandleNotify(string message, NetworkDevice clientDevice) { try { Notify notify = Notify.FromJSON(Json.Deserialize(message)); UpDevice device = gateway.RetrieveDevice( Util.GetHost(clientDevice.networkDeviceName), clientDevice.networkDeviceType); gateway.HandleNotify(notify, device); } catch (System.Exception e) { PushLog("Internal Failure. Notify cannot be handled. ", e); } }
public DriverManager( uOSSettings settings, UnityGateway gateway, UpDevice currentDevice) { this.settings = settings; this.gateway = gateway; this.logger = gateway.logger; this.driverDao = new DriverDAO(); this.currentDevice = currentDevice; this.instances = new Dictionary <long?, UOSDriver>(); this.toInitialize = new List <string>(); this.driverHash = new Dictionary <string, TreeNode>(); InitTree(); }
public DriverManager( uOSSettings settings, UnityGateway gateway, UpDevice currentDevice) { this.settings = settings; this.gateway = gateway; this.logger = gateway.logger; this.driverDao = new DriverDAO(); this.currentDevice = currentDevice; this.instances = new Dictionary<long?, UOSDriver>(); this.toInitialize = new List<string>(); this.driverHash = new Dictionary<string, TreeNode>(); InitTree(); }
private string SendMessage(string msg, UpDevice target, bool waitForResponse = true) { UpNetworkInterface netInt = GetAppropriateInterface(target); string networkAddress = netInt.networkAddress; string networkType = netInt.netType; ClientConnection con = OpenActiveConnection(networkAddress, networkType); if (con == null) { logger.LogWarning("Not possible to stablish a connection with '" + networkAddress + "' of type '" + networkType + "'."); return(null); } try { byte[] data = Encoding.UTF8.GetBytes(msg); con.Write(data, 0, data.Length); // Gets response. string response = null; if (waitForResponse) { data = con.Read(); if (data != null) { response = Encoding.UTF8.GetString(data); if (response.Trim().Length == 0) { response = null; } } } con.Close(); return(response); } catch (System.Exception) { if (con.connected) { con.Close(); } throw; } }
private void RegisterNewListener( UpDevice device, IDictionary <string, object> parameters, string eventIdentifier, ListenerInfo info) { if (device != null) { SendRegister(device, parameters, info); } // If the registry process goes ok, then add the listenner to the listener map List <ListenerInfo> listeners = null; if (!listenerMap.TryGetValue(eventIdentifier, out listeners)) { listenerMap[eventIdentifier] = listeners = new List <ListenerInfo>(); } listeners.Add(info); logger.Log("Registered listener for event :" + eventIdentifier); }
/// <summary> /// Called by radar whenever a device enters the space. /// </summary> /// <param name="device"></param> public void DeviceEntered(NetworkDevice device) { if (device == null) { return; } // verify if device entered is the current device string deviceHost = Util.GetHost(device.networkDeviceName); foreach (UpNetworkInterface networkInterface in this.currentDevice.networks) { string currentDeviceHost = Util.GetHost(networkInterface.networkAddress); if (deviceHost != null && deviceHost.Equals(currentDeviceHost)) { logger.Log("Host of device entered is the same of current device:" + device.networkDeviceName); return; } } // verify if already know this device. UpDevice upDevice = RetrieveDevice(deviceHost, device.networkDeviceType); if (upDevice == null) { // Does handshake on a new thread... new Thread(new ThreadStart(delegate() { upDevice = DoHandshake(device); if (upDevice != null) { DoDriversRegistry(device, upDevice); } })).Start(); } else { logger.Log("Already known device " + device.networkDeviceName); } }
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); } }
public void HandleNotify(Notify notify, UpDevice device) { if ((notify == null) || (notify.eventKey == null) || (notify.eventKey.Length == 0)) { logger.Log("No information in notify to handle."); } if ((listenerMap == null) || (listenerMap.Count == 0)) { logger.Log("No listeners waiting for notify events."); return; } //Notifying listeners from more specific to more general entries string eventIdentifier; List <ListenerInfo> listeners; // First full entries (device, driver, event, intanceId) eventIdentifier = GetEventIdentifier(device, notify.driver, notify.instanceId, notify.eventKey); if (listenerMap.TryGetValue(eventIdentifier, out listeners)) { HandleNotify(notify, listeners, eventIdentifier); } // After less general entries (device, driver, event) eventIdentifier = GetEventIdentifier(device, notify.driver, null, notify.eventKey); if (listenerMap.TryGetValue(eventIdentifier, out listeners)) { HandleNotify(notify, listeners, eventIdentifier); } // An then the least general entries (driver, event) eventIdentifier = GetEventIdentifier(null, notify.driver, null, notify.eventKey); if (listenerMap.TryGetValue(eventIdentifier, out listeners)) { HandleNotify(notify, listeners, eventIdentifier); } }
public List <UpDevice> List(string address, string networktype) { if ((address != null) && (networktype != null)) { List <UpDevice> ret = new List <UpDevice>(); string key = GenerateInterfaceKey(new UpNetworkInterface(networktype, address)); UpDevice upDevice = null; if (interfaceMap.TryGetValue(key, out upDevice)) { ret.Add(upDevice); } return(ret); } else if (address != null) { List <UpDevice> devices = null; if (addressMap.TryGetValue(address, out devices)) { return(new List <UpDevice>(new HashSet <UpDevice>(devices))); } } else if (networktype != null) { List <UpDevice> devices = null; if (networkTypeMap.TryGetValue(networktype, out devices)) { return(new List <UpDevice>(new HashSet <UpDevice>(devices))); } } else { return(List()); } return(new List <UpDevice>()); }
/// <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(); }
private void DoDriversRegistry(NetworkDevice device, UpDevice upDevice) { try { Response response = gateway.CallService(upDevice, new Call(DEVICE_DRIVER_NAME, "listDrivers")); if ((response != null) && (response.responseData != null) && (response.GetResponseData("driverList") != null)) { try { IDictionary <string, object> driversListMap = null; object temp = response.GetResponseData("driverList"); if (temp is IDictionary <string, object> ) { driversListMap = temp as IDictionary <string, object>; //TODO: Not tested. Why? } else { driversListMap = Json.Deserialize(temp.ToString()) as IDictionary <string, object>; } List <string> ids = new List <string>(driversListMap.Keys); RegisterRemoteDriverInstances(upDevice, driversListMap, ids.ToArray()); } catch (System.Exception e) { logger.LogError( "Problems occurred while registering drivers from device '" + upDevice.name + "' . " + e.Message); } } } catch (System.Exception) { logger.LogError( "Not possible to discover services from device '" + device.networkDeviceName + "'. Possibly not a uOS Device."); } }
/// <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); }
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); }
private string SendMessage(string msg, UpDevice target, bool waitForResponse = true) { UpNetworkInterface netInt = GetAppropriateInterface(target); string networkAddress = netInt.networkAddress; string networkType = netInt.netType; ClientConnection con = OpenActiveConnection(networkAddress, networkType); if (con == null) { logger.LogWarning("Not possible to stablish a connection with '" + networkAddress + "' of type '" + networkType + "'."); return null; } try { byte[] data = Encoding.UTF8.GetBytes(msg); con.Write(data, 0, data.Length); // Gets response. string response = null; if (waitForResponse) { data = con.Read(); if (data != null) { response = Encoding.UTF8.GetString(data); if (response.Trim().Length == 0) response = null; } } con.Close(); return response; } catch (System.Exception) { if (con.connected) con.Close(); throw; } }
public void Notify(Notify notify, UpDevice device) { if (IsLocalCall(device)) HandleNotify(notify, device); else RemoteNotify(notify, device); }
/// <summary> /// Removes a listener for receiving Notify events and notifies the event driver of its removal. /// </summary> /// <param name="listener"></param> /// <param name="device"></param> /// <param name="driver"></param> /// <param name="instanceId"></param> /// <param name="eventKey"></param> public void Unregister( UOSEventListener listener, UpDevice device = null, string driver = null, string instanceId = null, string eventKey = null) { List<ListenerInfo> listeners = FindListeners(device, driver, instanceId, eventKey); if (listeners == null) return; System.Exception e = null; foreach (var li in listeners) { // only if its the same listener, it should be removed if (li.listener.Equals(listener)) { bool remove = true; // If the driver name is informed, and it's not the same, it must not be removed if ((driver != null) && (li.driver != null)) remove = remove && li.driver.Equals(driver, System.StringComparison.InvariantCultureIgnoreCase); // If the instanceId is informed, and it's not the same, it must not be removed if ((instanceId != null) && (li.instanceId != null)) remove = remove && li.instanceId.Equals(instanceId, System.StringComparison.InvariantCultureIgnoreCase); if (remove) { try { //Notify device of the listener removal UnregisterForEvent(li); } catch (System.Exception ex) { string id = GetEventIdentifier(device, driver, instanceId, eventKey); logger.LogError("Failed to unregister for event " + id + ": " + e.Message); e = ex; } } } } if (e != null) throw e; }
public void Update(string oldname, UpDevice device) { Delete(oldname); Add(device); }
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; }
private bool IsLocalCall(UpDevice device) { return (device == null) || (device.name == null) || (device.name.Equals(currentDevice.name, System.StringComparison.InvariantCultureIgnoreCase)); }
private UpNetworkInterface GetAppropriateInterface(UpDevice deviceProvider) { //List of compatible network interfaces List<UpNetworkInterface> compatibleNetworks = new List<UpNetworkInterface>(); //Solves the different network link problem: foreach (UpNetworkInterface thisNetInterface in currentDevice.networks) { foreach (UpNetworkInterface providerNetInterface in deviceProvider.networks) { if (thisNetInterface.netType.Equals(providerNetInterface.netType)) { compatibleNetworks.Add(providerNetInterface); break; } } } //Checks if none compatible interface is available if (compatibleNetworks.Count == 0) { logger.LogError("ConnectivityManager - Lacks connectivity between the devices for this service"); throw new System.Exception("ConnectivityManager - Lacks connectivity between the devices for this service"); } //Gets the best choice of network for this service //UpNetworkInterface networkInterface = servicesBestInterface(compatibleNetworks, serviceCall); //return networkInterface; return compatibleNetworks[0]; }
private List<ListenerInfo> FindListeners(UpDevice device, string driver, string instanceId, string eventKey) { List<ListenerInfo> listeners = null; // First filter the listeners by the event key. if (eventKey == null) { // In this case all eventKeys must be checked for the listener to be removed. listeners = new List<ListenerInfo>(); foreach (var list in listenerMap.Values) listeners.AddRange(list); } else { // In case a eventKey is informed, then only the listeners for that event key must be used. string eventIdentifier = GetEventIdentifier(device, driver, instanceId, eventKey); if (!listenerMap.TryGetValue(eventIdentifier, out listeners)) listeners = null; } return listeners; }
private static string GetEventIdentifier(UpDevice device, string driver, string instanceId, string eventKey) { StringBuilder id = new StringBuilder(); if ((device != null) && (device.name != null) && (device.name.Length > 0)) id.Append("@" + device.name); if ((driver != null) && (driver.Length > 0)) id.Append("*" + driver); if ((eventKey != null) && (eventKey.Length > 0)) id.Append("." + eventKey); if ((instanceId != null) && (instanceId.Length > 0)) id.Append("#" + instanceId); return id.ToString(); }
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); } }
private void DoDriversRegistry(NetworkDevice device, UpDevice upDevice) { try { Response response = gateway.CallService(upDevice, new Call(DEVICE_DRIVER_NAME, "listDrivers")); if ((response != null) && (response.responseData != null) && (response.GetResponseData("driverList") != null)) { try { IDictionary<string, object> driversListMap = null; object temp = response.GetResponseData("driverList"); if (temp is IDictionary<string, object>) driversListMap = temp as IDictionary<string, object>; //TODO: Not tested. Why? else driversListMap = Json.Deserialize(temp.ToString()) as IDictionary<string, object>; List<string> ids = new List<string>(driversListMap.Keys); RegisterRemoteDriverInstances(upDevice, driversListMap, ids.ToArray()); } catch (System.Exception e) { logger.LogError( "Problems occurred while registering drivers from device '" + upDevice.name + "' . " + e.Message); } } } catch (System.Exception) { logger.LogError( "Not possible to discover services from device '" + device.networkDeviceName + "'. Possibly not a uOS Device."); } }
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; }
private void RegisterRemoteDriverInstances(UpDevice upDevice, IDictionary<string, object> driversListMap, string[] instanceIds) { foreach (string id in instanceIds) { object instance = driversListMap[id]; if (instance is string) instance = Json.Deserialize(instance as string); UpDriver upDriver = UpDriver.FromJSON(instance); DriverModel driverModel = new DriverModel(id, upDriver, upDevice.name); try { driverManager.Insert(driverModel); } catch (DriverNotFoundException e) { unknownDrivers.UnionWith(e.driversNames); dependents.Add(driverModel); } catch (System.Exception) { logger.LogError( "Problems occurred in the registering of driver '" + upDriver.name + "' with instanceId '" + id + "' in the device '" + upDevice.name + "' and it will not be registered."); } } if (unknownDrivers.Count > 0) FindDrivers(unknownDrivers, upDevice); }
public void Register( UOSEventListener listener, UpDevice device, string driver, string instanceId = null, string eventKey = null, IDictionary<string, object> parameters = null) { // If the listener is already registered it cannot be registered again string eventIdentifier = GetEventIdentifier(device, driver, instanceId, eventKey); logger.Log("Registering listener for event :" + eventIdentifier); List<ListenerInfo> list; if (!listenerMap.TryGetValue(eventIdentifier, out list)) list = null; if (FindListener(listener, list) == null) { ListenerInfo info = new ListenerInfo(); info.driver = driver; info.instanceId = instanceId; info.eventKey = eventKey; info.listener = listener; info.device = device; RegisterNewListener(device, parameters, eventIdentifier, info); } }
private void RemoteNotify(Notify notify, UpDevice device) { if ( device == null || notify == null || string.IsNullOrEmpty(notify.driver) || string.IsNullOrEmpty(notify.eventKey)) throw new System.ArgumentException("Either the device or notification is invalid."); string message = Json.Serialize(notify.ToJSON()); SendMessage(message, device, false); }
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); } }
private void PrepareDeviceAndDrivers() { UpDevice currentDevice = new UpDevice(); if (settings.deviceName != null) { string name = settings.deviceName.Trim(); if (name.Length > 0) currentDevice.name = name; } else currentDevice.name = Dns.GetHostName(); if ((currentDevice.name == null) || (currentDevice.name.ToLower() == "localhost")) currentDevice.name = SystemInfo.deviceName; if ((currentDevice.name == null) || currentDevice.name.ToLower().Contains("unknown")) currentDevice.name = System.Environment.UserName; currentDevice.AddProperty("platform", "unity-" + Application.platform.ToString().ToLower()); var networks = new List<UpNetworkInterface>(); foreach (ChannelManager cm in channelManagers.Values) { foreach (var host in cm.ListHosts()) { var nInf = new UpNetworkInterface(); nInf.netType = cm.GetNetworkDeviceType(); nInf.networkAddress = host; networks.Add(nInf); } } currentDevice.networks = networks; driverManager = new DriverManager(settings, this, currentDevice); deviceManager = new DeviceManager(settings, this, currentDevice); foreach (var driver in settings.drivers) { System.Type type = null; try { type = Util.GetType(driver); } catch (System.Exception) { } string error = null; object instance = null; if ((type == null) || (type.GetInterface("UOS.UOSDriver") == null) || (!type.IsClass) || (type.IsAbstract)) error = driver + " is not a valid concrete type which implements UOSDriver interface"; else { if (type.IsSubclassOf(typeof(MonoBehaviour))) { object[] components = UnityEngine.Object.FindObjectsOfType(type); if (components.Length == 0) error = "no instance of MonoBehaviour " + driver + " was found in the scene"; else if (components.Length > 1) error = "multiple instances of MonoBehaviour " + driver + " were found in the scene"; else instance = components[0]; } else { try { instance = System.Activator.CreateInstance(type); } catch (System.Reflection.TargetInvocationException e) { error = "constructor exception: " + e.InnerException; } catch (System.Exception) { error = "couldn't instantiate " + driver + " using default constructor"; } } } if (error != null) logger.LogError("Driver initialisation failure: " + error + "."); else { var driverInstance = (UOSDriver)instance; driverManager.DeployDriver(driverInstance); } } driverManager.InitDrivers(); }
public void HandleNotify(Notify notify, UpDevice device) { if ((notify == null) || (notify.eventKey == null) || (notify.eventKey.Length == 0)) logger.Log("No information in notify to handle."); if ((listenerMap == null) || (listenerMap.Count == 0)) { logger.Log("No listeners waiting for notify events."); return; } //Notifying listeners from more specific to more general entries string eventIdentifier; List<ListenerInfo> listeners; // First full entries (device, driver, event, intanceId) eventIdentifier = GetEventIdentifier(device, notify.driver, notify.instanceId, notify.eventKey); if (listenerMap.TryGetValue(eventIdentifier, out listeners)) HandleNotify(notify, listeners, eventIdentifier); // After less general entries (device, driver, event) eventIdentifier = GetEventIdentifier(device, notify.driver, null, notify.eventKey); if (listenerMap.TryGetValue(eventIdentifier, out listeners)) HandleNotify(notify, listeners, eventIdentifier); // An then the least general entries (driver, event) eventIdentifier = GetEventIdentifier(null, notify.driver, null, notify.eventKey); if (listenerMap.TryGetValue(eventIdentifier, out listeners)) HandleNotify(notify, listeners, eventIdentifier); }
private void RegisterNewListener( UpDevice device, IDictionary<string, object> parameters, string eventIdentifier, ListenerInfo info) { if (device != null) SendRegister(device, parameters, info); // If the registry process goes ok, then add the listenner to the listener map List<ListenerInfo> listeners = null; if (!listenerMap.TryGetValue(eventIdentifier, out listeners)) listenerMap[eventIdentifier] = listeners = new List<ListenerInfo>(); listeners.Add(info); logger.Log("Registered listener for event :" + eventIdentifier); }