Ejemplo n.º 1
0
        public Promise <Try <IAResponse> > Send(IARequest request, IADevice device)
        {
            Try <IAResponse> result = null;

            SendRequest(request, device, delegate(IAResponse response, Exception e)
            {
                result = MetaTry.Try <IAResponse>(() => {
                    if (e != null)
                    {
                        throw new Exception(e.Message, e);
                    }
                    else
                    {
                        return(response);
                    }
                });
            });
            return(((Func <Try <IAResponse> >) delegate()
            {
                while (result == null)
                {
                    ;
                }
                return result;
            }).AsPromise());
        }
Ejemplo n.º 2
0
        private HttpWebRequest CreateRequest(IADevice device, IARequest iaRequest)
        {
            Dictionary <string, string> parameters = new Dictionary <string, string>(iaRequest.Parameters);
            string path = ReplaceParameters(iaRequest.Route.Resource, parameters);

            if (parameters.Count > 0)
            {
                path += "?";
            }

            foreach (KeyValuePair <string, string> parameter in parameters)
            {
                string key   = Nancy.Helpers.HttpUtility.UrlEncode(parameter.Key);
                string value = Nancy.Helpers.HttpUtility.UrlEncode(parameter.Value);
                path += String.Format("{0}={1}&", key, value);
            }

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(String.Format("http://{0}:{1}{2}", device.Host, device.Port, path));

            request.ContentType = iaRequest.ContentType;
            request.Method      = iaRequest.Route.Action;

            iaRequest.Origin.Foreach(x =>
            {
                request.Headers.Add(String.Format("X-IA-Origin: {0}", x.Name));
            });
            foreach (KeyValuePair <string, string> metaentry in iaRequest.Metadata)
            {
                request.Headers.Add(String.Format("{0}: {1}", metaentry.Key, metaentry.Value));
            }

            return(request);
        }
Ejemplo n.º 3
0
        private void OnServiceLost(SDService service)
        {
            IADevice device = new IADevice(service.Name, service.Hostname, service.Port, null);

            this.devices.Remove(device);
            OnDeviceLost(device);
        }
Ejemplo n.º 4
0
 private void OnServiceFound(SDService service, bool ownService)
 {
     if (ownService)
     {
         IADevice device = new IADevice(service.Name, service.Hostname, service.Port, this.SupportedRoutes);
         this.OwnDevice = device.AsOption();
         OnDeviceFound(device, true);
     }
     else
     {
         IADevice  device  = new IADevice(service.Name, service.Hostname, service.Port, null);
         IARequest request = new IARequest(IARoute.Get("/routes"));
         SendRequest(request, device, delegate(IAResponse response, Exception error)
         {
             if (error == null)
             {
                 if (response.StatusCode == 200)
                 {
                     List <IARoute> supportedRoutes = response.BodyAs <IARoute>();
                     IADevice deviceWithRoutes      = new IADevice(service.Name, service.Hostname, service.Port, new HashSet <IARoute>(supportedRoutes));
                     this.devices.Add(deviceWithRoutes);
                     OnDeviceFound(deviceWithRoutes, false);
                 }
                 else
                 {
                     Console.WriteLine(String.Format("An error ocurred trying to request routes from {0}", device));
                 }
             }
             else
             {
                 Console.WriteLine(String.Format("An error ocurred: {0}", error));
             }
         });
     }
 }
Ejemplo n.º 5
0
 protected virtual void OnDeviceFound(IADevice device, bool ownDevice)
 {
     if (DeviceFound != null)
     {
         DeviceFound(device, ownDevice);
     }
 }
 private void DeviceLost(IADevice device)
 {
     Application.Current.Dispatcher.BeginInvoke(new Action(() =>
     {
         OutputText.Text += device.Name + " disconnected\n";
     }));
 }
 private void DeviceFound(IADevice device, bool ownDevice)
 {
     Application.Current.Dispatcher.BeginInvoke(new Action(() =>
     {
         OutputText.Text += device.Name + " connected" + (ownDevice == true ? ", own device\n" : "\n");
     }));
 }
Ejemplo n.º 8
0
 protected virtual void OnDeviceLost(IADevice device)
 {
     if (DeviceLost != null)
     {
         DeviceLost(device);
     }
 }
Ejemplo n.º 9
0
 public IARequest(IARoute route, Dictionary<String, String> metadata, Dictionary<String, String> parameters, IADevice origin, byte[] body, string contentType)
     : base(body, contentType)
 {
     this.Route = route;
     this.Metadata = metadata;
     this.Parameters = parameters;
     this.Origin = origin;
 }
Ejemplo n.º 10
0
 public void SendRequest(IARequest request, IADevice device, Action<IAResponse, Exception> action)
 {
     RestClient client = ClientFromDevice(device);
     RestRequest restRequest = RequestFromIARequest(request);
     client.ExecuteAsync(restRequest, response =>
     {
         if (action != null)
         {
             action(IAResponseFromRestResponse(response), response.ErrorException);
         }
     });
 }
Ejemplo n.º 11
0
        public void SendRequest(IARequest request, IADevice device, Action <IAResponse, Exception> action)
        {
            RestClient  client      = ClientFromDevice(device);
            RestRequest restRequest = RequestFromIARequest(request);

            client.ExecuteAsync(restRequest, response =>
            {
                if (action != null)
                {
                    action(IAResponseFromRestResponse(response), response.ErrorException);
                }
            });
        }
Ejemplo n.º 12
0
        public override bool Equals(Object obj)
        {
            if (this == obj)
            {
                return(true);
            }

            if (obj == null || (obj as IADevice) == null)
            {
                return(false);
            }

            IADevice device = (IADevice)obj;

            return(this.Name != null && this.Name.Equals(device.Name));
        }
Ejemplo n.º 13
0
        public void DeviceFound(IADevice iaDevice, bool ownDevice)
        {
            PairableDevice pairableDevice = new PairableDevice
            {
                Identifier = iaDevice.Name,
                PairingState = PairingState.NotPaired
            };

            FindDeviceWidthAndHeight(iaDevice);

            if (iaDevice.SupportedRoutes.Contains(Routes.GetLocationRoute))
            {
                IARequest request = new IARequest(Routes.GetLocationRoute);
                IntAirAct.SendRequest(request, iaDevice, delegate(IAResponse response, Exception error)
                {
                    if (response == null || response.StatusCode == 404)
                    {
                        // Device has no location

                    }
                    else if (response.StatusCode == 200)
                    {
                        IntermediatePoint intermediatePoint = response.BodyAs<IntermediatePoint>();
                        Point result = intermediatePoint.ToPoint();

                        Device localDevice = locator.Devices.Find(d => d.Identifier.Equals(iaDevice.Name));

                        if (localDevice != null)
                        {
                            localDevice.Location = result;
                            response.StatusCode = 201; // created
                        }
                        else
                        {
                            response.StatusCode = 404; // not found
                        }

                    }
                });
            }

            locator.Devices.Add(pairableDevice);

            if (DeviceAdded != null)
                DeviceAdded(this, pairableDevice);
        }
Ejemplo n.º 14
0
        public void SendRequest(IARequest request, IADevice device, Action <IAResponse, Exception> action)
        {
            HttpWebRequest webRequest = CreateRequest(device, request);
            RequestState   state      = new RequestState
            {
                WebRequest = webRequest,
                Action     = action,
                IARequest  = request
            };

            if (request.Route.Action == "GET" || request.Route.Action == "HEAD")
            {
                webRequest.BeginGetResponse(GetResponse, state);
            }
            else
            {
                webRequest.BeginGetRequestStream(GetResponseStream, state);
            }
        }
Ejemplo n.º 15
0
        public DeviceControl(PairableDevice pairableDevice, IADevice iaDevice)
        {
            InitializeComponent();

            this.iaDevice = iaDevice;
            this.pairableDevice = pairableDevice;

            deviceRotationControl = new DeviceRotationControl();
            deviceRotationControl.onSliderValueChanged += new EventHandler<RotationSliderEventArgs>(onOrientationSliderChanged);
            canvas.Children.Add(deviceRotationControl);
            Canvas.SetLeft(deviceRotationControl, -170);
            Canvas.SetTop(deviceRotationControl, -40);

            //Setup Events
            pairableDevice.LocationChanged += onLocationChanged;
            pairableDevice.OrientationChanged += onOrientationChanged;
            pairableDevice.PairingStateChanged += onPairingStateChanged;

            LeftLine.StrokeThickness = DrawingResources.DEVICE_FOV_WIDTH;
            RightLine.StrokeThickness = DrawingResources.DEVICE_FOV_WIDTH;

            //Setup Display
            DeviceNameLabel.Text = pairableDevice.Identifier;
            InnerBorder.BorderBrush = DrawingResources.unpairedBrush;

            // If it supports this route, then we know it's a surface
            if (iaDevice.SupportedRoutes.Contains(Routes.GetLocationRoute))
            {
                MyDisplayState = DisplayState.UnlocatedAndOnStackPanel;
            }
            // Likewise, if it supports this route, we know it's a pairable device
            else if (iaDevice.SupportedRoutes.Contains(Routes.BecomePairedRoute))
            {
                MyDisplayState = DisplayState.UnpairedAndOnStackPanel;
            }

            formatForStackPanel();
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Send a Dictionary to another device
        /// </summary>
        /// <param name="dictionary">The dictionary to send</param>
        /// <param name="dictionaryType">The dictionary type. This is shown on the receiving end and so you can just it to differentiate dictionaries</param>
        /// <param name="targetDevice">The target device (NOTE - targetDevice must not be null)</param>
        /// <param name="gesture">The Gesture used to send the image</param>
        public void SendDictionary(Dictionary<string, string> dictionary, string dictionaryType, Dictionary<string, double> intersectionPoint, IADevice targetDevice, MSEGesture gesture)
        {
            if (dictionary == null)
            {
                logger.TraceEvent(TraceEventType.Error, 0, "MSE Error: Only a valid dictionary can be sent. Your dictionary was null");
                return;
            }

            if (dictionaryType == null)
            {
                logger.TraceEvent(TraceEventType.Error, 0, "MSE Error: A valid dictionary type is required, your dictionary type was null");
                return;
            }

            if (targetDevice == null)
            {
                logger.TraceEvent(TraceEventType.Error, 0, "MSE Error: Target Device must has a non null NetworkDevice");
                return;
            }

            IARequest request = new IARequest(Routes.DictionaryRoute);
            request.Parameters["dictionarytype"] = dictionaryType;
            request.Parameters["x"] = intersectionPoint["x"].ToString();
            request.Parameters["y"] = intersectionPoint["y"].ToString();
            request.SetBodyWith(dictionary);
            request.Origin = this.IntAirAct.OwnDevice;

            if (request.Body == null)
            {
                logger.TraceEvent(TraceEventType.Error, 0, "MSE Error: Your dictionary of " + dictionaryType + " type, could not be serialized.");
                return;
            }

            this.IntAirAct.SendRequest(request, targetDevice, delegate(IAResponse response, Exception error)
            {
                if (error != null)
                {
                    logger.TraceEvent(TraceEventType.Error, 0, "MSE Error: Sending Dictionary " + dictionaryType + " to " + Routes.DictionaryRoute + " Failed");
                }
            });
        }
Ejemplo n.º 17
0
        public NancyRouteModule(NancyServerAdapter adapter)
        {
            foreach (KeyValuePair <IARoute, Action <IARequest, IAResponse> > kvp in adapter.Routes)
            {
                IARoute route = kvp.Key;
                Action <IARequest, IAResponse> action = kvp.Value;
                RouteBuilder rb = new RouteBuilder(route.Action, this);
                rb[route.Resource] = nancyDynamicDictionary =>
                {
                    Dictionary <string, string> parameters = new Dictionary <string, string>();

                    // get parameters out of path
                    foreach (string key in nancyDynamicDictionary)
                    {
                        DynamicDictionaryValue value = nancyDynamicDictionary[key];
                        string urldecoded            = HttpUtility.UrlDecode(value.ToString());
                        parameters.Add(key, urldecoded);
                    }

                    // get parameters out of query string
                    foreach (string key in Request.Query)
                    {
                        DynamicDictionaryValue value = Request.Query[key];
                        parameters.Add(key, "" + value.Value);
                    }
                    string contentType = Request.Headers.ContentType;

                    IADevice origin = null;
                    if (Request.Headers.Keys.Contains("X-IA-Origin"))
                    {
                        IAIntAirAct intAirAct = TinyIoC.TinyIoCContainer.Current.Resolve <IAIntAirAct>();
                        if (intAirAct != null)
                        {
                            origin = intAirAct.DeviceWithName(Request.Headers["X-IA-Origin"].First());
                        }
                    }

                    Dictionary <string, string> metadata = new Dictionary <string, string>();
                    foreach (KeyValuePair <string, IEnumerable <string> > header in Request.Headers)
                    {
                        var value = header.Value.First();
                        metadata[header.Key] = value;
                    }

                    IARequest  iaRequest  = new IARequest(route, metadata, parameters, origin, Request.BodyAsByte(), contentType);
                    IAResponse iaResponse = new IAResponse();
                    action(iaRequest, iaResponse);
                    Response response = new Response();
                    response.StatusCode = (HttpStatusCode)iaResponse.StatusCode;
                    response.Contents   = stream =>
                    {
                        var writer = new BinaryWriter(stream);
                        writer.Write(iaResponse.Body);
                        writer.Flush();
                    };
                    response.Headers = iaResponse.Metadata;

                    response.ContentType = iaResponse.ContentType;

                    return(response);
                };
            }
        }
Ejemplo n.º 18
0
 public void SendRequest(IARequest request, IADevice device, Action<IAResponse, Exception> action)
 {
     this.client.SendRequest(request, device, action);
 }
Ejemplo n.º 19
0
 public void SendRequest(IARequest request, IADevice device)
 {
     this.client.SendRequest(request, device);
 }
Ejemplo n.º 20
0
 public void SendRequest(IARequest request, IADevice device)
 {
     this.client.SendRequest(request, device);
 }
Ejemplo n.º 21
0
 public void SendRequest(IARequest request, IADevice device, Action <IAResponse, Exception> action)
 {
     this.client.SendRequest(request, device, action);
 }
Ejemplo n.º 22
0
 protected virtual void OnDeviceFound(IADevice device, bool ownDevice)
 {
     if (DeviceFound != null)
     {
         DeviceFound(device, ownDevice);
     }
 }
Ejemplo n.º 23
0
 private RestClient ClientFromDevice(IADevice device)
 {
     return(new RestClient(String.Format("http://{0}:{1}", device.Host, device.Port)));
 }
Ejemplo n.º 24
0
 protected virtual void OnDeviceLost(IADevice device)
 {
     if (DeviceLost != null)
     {
         DeviceLost(device);
     }
 }
Ejemplo n.º 25
0
 public void SendRequest(IARequest request, IADevice device)
 {
     this.SendRequest(request, device, null);
 }
Ejemplo n.º 26
0
        private void FindDeviceWidthAndHeight(IADevice iaDevice)
        {
            //Does the device contain and width and height route
            if (iaDevice.SupportedRoutes.Contains(Routes.GetWidthAndHeightRoute))
            {
                IARequest request = new IARequest(Routes.GetWidthAndHeightRoute);
                IntAirAct.SendRequest(request, iaDevice, delegate(IAResponse response, Exception error)
                {
                    if (response == null || response.StatusCode == 404)
                    {
                        logger.TraceEvent(TraceEventType.Error, 100, "All devices should provide a width and height");
                    }
                    else if (response.StatusCode == 200)
                    {
                        Dictionary<String,double> dictionary = response.BodyAs<Dictionary<String,double>>();

                        Device localDevice = locator.Devices.Find(d => d.Identifier.Equals(iaDevice.Name));

                        //Device still exists, set width and height for device
                        if (localDevice != null)
                        {
                            localDevice.Height = dictionary["height"];
                            localDevice.Width = dictionary["width"];

                        }
                        //Otherwise, device has disappeared, no action required
                        else
                        {

                        }

                    }
                });

            }
        }
Ejemplo n.º 27
0
 private void OnServiceFound(SDService service, bool ownService)
 {
     if (ownService)
     {
         IADevice device = new IADevice(service.Name, service.Hostname, service.Port, this.SupportedRoutes);
         this.OwnDevice = device;
         OnDeviceFound(device, true);
     }
     else
     {
         IADevice device = new IADevice(service.Name, service.Hostname, service.Port, null);
         IARequest request = new IARequest(IARoute.Get("/routes"));
         SendRequest(request, device, delegate(IAResponse response, Exception error)
         {
             if (error == null)
             {
                 if (response.StatusCode == 200)
                 {
                     List<IARoute> supportedRoutes = response.BodyAs<IARoute>();
                     IADevice deviceWithRoutes = new IADevice(service.Name, service.Hostname, service.Port, new HashSet<IARoute>(supportedRoutes));
                     this.devices.Add(deviceWithRoutes);
                     OnDeviceFound(deviceWithRoutes, false);
                 }
                 else
                 {
                     Console.WriteLine(String.Format("An error ocurred trying to request routes from {0}", device));
                 }
             }
             else
             {
                 Console.WriteLine(String.Format("An error ocurred: {0}", error));
             }
         });
     }
 }
Ejemplo n.º 28
0
 private void OnServiceLost(SDService service)
 {
     IADevice device = new IADevice(service.Name, service.Hostname, service.Port, null);
     this.devices.Remove(device);
     OnDeviceLost(device);
 }
Ejemplo n.º 29
0
 public IARequest(IARoute route, Dictionary <String, String> metadata, Dictionary <String, String> parameters, IADevice origin, byte[] body, string contentType)
     : base(body, contentType)
 {
     this.Route      = route;
     this.Metadata   = metadata;
     this.Parameters = parameters;
     this.Origin     = origin.AsOption();
 }
Ejemplo n.º 30
0
        /// <summary>
        /// Send Data to another Device
        /// </summary>
        /// <param name="data">The data to send</param>
        /// <param name="targetDevice">The target device (NOTE - targetDevice must not be null)</param>
        /// <param name="gesture">The Gesture used to send the image</param>
        public void SendData(byte[] data, Dictionary<string, double> intersectionPoint, IADevice targetDevice, MSEGesture gesture)
        {
            if (data == null)
            {
                logger.TraceEvent(TraceEventType.Error, 0, "MSE Error: Only valid data can be sent. Your data object was set to null");
                return;
            }

            if (targetDevice == null)
            {
                logger.TraceEvent(TraceEventType.Error, 0, "MSE Error: Target Device must have a non null NetworkDevice");
                return;
            }

            //Create Request
            IARequest request = new IARequest(Routes.DataRoute);
            request.Body = data;
            request.Parameters["x"] = intersectionPoint["x"].ToString();
            request.Parameters["y"] = intersectionPoint["y"].ToString();
            request.Origin = this.IntAirAct.OwnDevice;

            this.IntAirAct.SendRequest(request, targetDevice, delegate(IAResponse response, Exception error)
            {
                if (error != null)
                {
                    logger.TraceEvent(TraceEventType.Error, 0, "Sending Data to " + Routes.DataRoute + " Failed");
                }

            });
        }
Ejemplo n.º 31
0
 public void SendRequest(IARequest request, IADevice device)
 {
     this.SendRequest(request, device, null);
 }
Ejemplo n.º 32
0
        /// <summary>
        /// Send an image to a target device
        /// </summary>
        /// <param name="image">The image to send</param>
        /// <param name="imageName">The name of the image</param>
        /// <param name="targetDevice">The target IADevice (NOTE - targetDevice must not be null)</param>
        /// <param name="gesture">The Gesture used to send the image</param>
        public void SendImage(Image image, String imageName, Dictionary<string, double> intersectionPoint, IADevice targetDevice, MSEGesture gesture)
        {
            MemoryStream ms = new MemoryStream();

            // Saves the image into the MemoryStream
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);

            // Converts image to a byte array
            byte[] imageAsData = ms.ToArray();

            if (imageAsData == null)
            {
                logger.TraceEvent(TraceEventType.Error, 0, "MSE Error: Only a valid image can be sent. Your image " + imageName + " was not valid");
                return;
            }

            if (imageName == null)
            {
                logger.TraceEvent(TraceEventType.Error, 0, "MSE Error: A valid image name is required to send images, your image name was null");
                return;
            }

            if (targetDevice == null)
            {
                logger.TraceEvent(TraceEventType.Error, 0, "MSE Error: Target Device must has a non null NetworkDevice");
                return;
            }

            //Create Request
            IARequest request = new IARequest(Routes.ImageRoute);
            request.Body = imageAsData;
            request.Parameters["imagename"] = imageName;
            request.Parameters["x"] = intersectionPoint["x"].ToString();
            request.Parameters["y"] = intersectionPoint["y"].ToString();

            request.Origin = this.IntAirAct.OwnDevice;

            this.IntAirAct.SendRequest(request, targetDevice, delegate(IAResponse response, Exception error)
            {
                if (error == null)
                {
                    logger.TraceEvent(TraceEventType.Error, 0, "Sending Image " + imageName + " to " + Routes.ImageRoute + "Failed");
                }
            });
        }
Ejemplo n.º 33
0
 private RestClient ClientFromDevice(IADevice device)
 {
     return new RestClient(String.Format("http://{0}:{1}", device.Host, device.Port));
 }
Ejemplo n.º 34
0
        public void DeviceLost(IADevice iaDevice)
        {
            List<PairablePerson> pairablePersons = locator.Persons.OfType<PairablePerson>().ToList<PairablePerson>();
            List<PairableDevice> pairableDevices = locator.Devices.OfType<PairableDevice>().ToList<PairableDevice>();

            // Find and remove the pairable device from the Locator's list of devices
            PairableDevice pairableDevice = pairableDevices.Find(d => d.Identifier.Equals(iaDevice.Name));
            locator.Devices.Remove(pairableDevice);

            // If the device was paired, we mark its corresponding person unpaired.
            PairablePerson person = pairablePersons.Find(p => p.Identifier.Equals(pairableDevice.HeldByPersonIdentifier));
            if (person != null)
            {
                //Remove the pairing information associated with the Perpon
                person.HeldDeviceIdentifier = null;
                person.PairingState = PairingState.NotPaired;
            }
            pairableDevice.HeldByPersonIdentifier = null;

            if (pairableDevice == null)
            {
                System.Diagnostics.Debug.WriteLine("ERROR: tried to remove nonexistent pairable device.");
            }

            if (DeviceRemoved != null)
                DeviceRemoved(this, pairableDevice);
        }