コード例 #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());
        }
コード例 #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);
        }
コード例 #3
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));
             }
         });
     }
 }
コード例 #4
0
        private RestRequest RequestFromIARequest(IARequest request)
        {
            RestRequest result = new RestRequest();
            switch (request.Route.Action)
            {
                case "GET":
                    result.Method = Method.GET;
                    break;
                case "POST":
                    result.Method = Method.POST;
                    break;
                case "PUT":
                    result.Method = Method.PUT;
                    break;
                case "OPTIONS":
                    result.Method = Method.OPTIONS;
                    break;
                case "DELETE":
                    result.Method = Method.DELETE;
                    break;
                case "HEAD":
                    result.Method = Method.HEAD;
                    break;
                case "PATCH":
                    result.Method = Method.PATCH;
                    break;
                default:
                    result.Method = Method.GET;
                    break;
            }
            Dictionary<string, string> parameters = new Dictionary<string, string>(request.Parameters);
            result.Resource = ReplaceParameters(request.Route.Resource, parameters);
            foreach (KeyValuePair<string, string> parameter in parameters)
            {
                result.AddParameter(parameter.Key, parameter.Value);
            }
            if (request.Origin != null)
            {
                result.AddHeader("X-IA-Origin", request.Origin.Name);
            }
            foreach (KeyValuePair<string, string> metaentry in request.Metadata)
            {
                result.AddHeader(metaentry.Key, metaentry.Value);
            }

            result.AddHeader("Content-Type", request.ContentType);

            Parameter p = new Parameter();
            p.Value = System.Text.Encoding.UTF8.GetString(request.Body);
            p.Type = ParameterType.RequestBody;
            result.Parameters.Add(p);

            return result;
        }
コード例 #5
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);
         }
     });
 }
コード例 #6
0
        public void AllDevicesInViewTest()
        {
            Setup();
            PairableDevice observer = new PairableDevice
            {
                Location = new Point(0, 0),
                Orientation = 225,
                Identifier = "observer",
            };

            PairableDevice nearest = new PairableDevice
            {
                Location = new Point(-1, -1),
                Identifier = "nearest",
                Orientation = 20,
            };

            PairableDevice furthest = new PairableDevice
            {
                Location = new Point(-2, -2),
                Identifier = "furthest",
                Orientation = 20,
            };

            Server.Locator.Devices.Add(observer);
            Server.Locator.Devices.Add(furthest);
            Server.Locator.Devices.Add(nearest);

            Server.Start();
            Client.Start();
            WaitForConnections();

            IARequest request = new IARequest(Routes.GetAllDevicesInViewRoute);
            request.Parameters["identifier"] = observer.Identifier;

            Client.SendRequest(request, Server.IntAirAct.OwnDevice, delegate(IAResponse response, Exception e)
            {
                List<IntermediateDevice> intDevices = response.BodyAs<IntermediateDevice>();

                IntermediateDevice intDevice = intDevices.Find(x => x.identifier == nearest.Identifier);
                Assert.AreEqual(nearest.Location, intDevice.location);
                Assert.AreEqual(nearest.Orientation, intDevice.orientation);

                intDevice = intDevices.Find(x => x.identifier == furthest.Identifier);
                Assert.AreEqual(furthest.Location, intDevice.location);
                Assert.AreEqual(furthest.Orientation, intDevice.orientation);

                doneWaitingForResponse = true;
            });

            WaitForResponse();
            Teardown();
        }
コード例 #7
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);
                }
            });
        }
コード例 #8
0
ファイル: DeviceManager.cs プロジェクト: ase-lab/MSEAPI
        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);
        }
コード例 #9
0
        /// <summary>
        /// Handle a request with updated location for a device.
        /// </summary>
        /// <param name="request">IntAirAct Request</param>
        /// <param name="response">IntAirAct Response</param>
        public void UpdateDeviceLocation(IARequest request, IAResponse response)
        {
            IntermediatePoint intermediatePoint = request.BodyAs<IntermediatePoint>();
            Point result = intermediatePoint.ToPoint();

            String name = request.Parameters["identifier"];
            Device localDevice = locator.Devices.Find(d => d.Identifier.Equals(name));

            if (localDevice != null)
            {
                localDevice.Location = result;
                response.StatusCode = 201; // created
            }
            else
            {
                response.StatusCode = 404; // not found
            }
        }
コード例 #10
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);
            }
        }
コード例 #11
0
        public override bool Equals(Object obj)
        {
            if (this == obj)
            {
                return(true);
            }

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

            IARequest request = (IARequest)obj;

            return((this.Route != null && this.Route.Equals(request.Route)) &&
                   (this.Metadata != null && this.Metadata.Equals(request.Metadata)) &&
                   (this.Parameters != null && this.Parameters.Equals(request.Parameters)) &&
                   (this.Origin.Equals(request.Origin)) &&
                   (this.Body == request.Body));
        }
コード例 #12
0
ファイル: PairingRecognizer.cs プロジェクト: ase-lab/MSEAPI
        public void Pair(PairableDevice pairingDevice, PairablePerson pairingPerson)
        {
            //Change the Pairing State
            pairingDevice.PairingState = PairingState.Paired;
            pairingPerson.PairingState = PairingState.Paired;

            //Create a Holds-Device and Held-By-Person Relationship
            pairingPerson.HeldDeviceIdentifier = pairingDevice.Identifier;
            pairingDevice.HeldByPersonIdentifier = pairingPerson.Identifier;

            List<IADevice> devices = intAirAct.Devices;
            IADevice device = devices.Find(d => d.Name == pairingDevice.Identifier);
            if (device != null)
            {
                IARequest request = new IARequest(Routes.BecomePairedRoute);
                intAirAct.SendRequest(request, device, delegate(IAResponse response, Exception exception)
                {
                    logger.TraceEvent(TraceEventType.Information, 0, "Error notifying Device {0} that it became paired.", pairingDevice.Identifier, pairingPerson.Identifier);
                });

            }

            logger.TraceEvent(TraceEventType.Information, 0, "Pairing Succeeded with Device {0} and Person {1}", pairingDevice.Identifier, pairingPerson.Identifier);
        }
コード例 #13
0
ファイル: MSELocator.cs プロジェクト: ase-lab/MSEAPI-CS
        private void CallIntAirActRoute(IARoute route, Dictionary<string, string> parameters, Delegate successGeneric, MSEErrorHandler failure)
        {
            //Setup Routes with Device in View
            IARequest request = new IARequest(route);

            //Add Parameters
            foreach (KeyValuePair<string, string> pair in parameters)
                request.Parameters[pair.Key] = pair.Value;

            //Get all devices that support this route
            IEnumerable devicesSupportingRoute = this.intAirAct.DevicesSupportingRoute(route);

            bool sentToServer = false;

            //Request Devices in View
            foreach (IADevice device in devicesSupportingRoute)
            {
                sentToServer = true;

                this.intAirAct.SendRequest(request, device, delegate(IAResponse response, Exception exception)
                {
                    if (exception != null)
                    {
                        failure(exception);
                    }

                    // QUESTION - Is this the same as saying if(successGeneric is MSEDeviceCollectionHandler)
                    if (successGeneric.GetType() == typeof(MSEDeviceCollectionHandler))
                    {
                        // Handle the response as if response was a collection
                        MSEDeviceCollectionHandler success = (MSEDeviceCollectionHandler)successGeneric;
                        List<MSEDevice> deviceList = Util.DeserializeIntoList(response.BodyAsString());
                        Util.CompleteDeviceListInformation(deviceList, this.intAirAct);

                        success(deviceList);
                        return;

                    }
                    else if(successGeneric.GetType() == typeof(MSESingleDeviceHandler))
                    {
                        // Handle the response as if response was a single device
                        MSESingleDeviceHandler success = (MSESingleDeviceHandler)successGeneric;
                        MSEDevice result = Util.DeserializeSingleDevice(response.BodyAsString());
                        Util.CompleteDeviceInformation(result, this.intAirAct);

                        success(result);
                        return;
                    }

                });

            }

            // If sentToServer is false, that means there was no devices capable of handling the route. This could mean that no devices can handle the route, or it just hasn't been found yet
            // I would normally use IEnumerable.Count, but that doesn't exist
            if (sentToServer == false)
            {
                failure(new Exception("MSE Error - There are no Devices discovered on the Network that can handle the " + route.Action + " " + route.Resource + " request. Is your Locator Server running and visible on the network?"));
                return;
            }
        }
コード例 #14
0
ファイル: MSELocator.cs プロジェクト: ase-lab/MSEAPI-CS
        /// <summary>
        /// Notify the server of the device's current Location. Intended for use with stationary devices, since mobile devices can't
        /// determine their own location in the room.
        /// </summary>
        /// <param name="device">The Identifier and Location properties of this MSEDevice will be used for the update.</param>
        /// <param name="success"></param>
        /// <param name="failure"></param>
        public void UpdateDeviceLocation(MSEDevice device, MSESuccessHandler success, MSEErrorHandler failure)
        {
            IARequest updateRequest = new IARequest(Routes.SetLocationRoute);
            updateRequest.SetBodyWith(new IntermediatePoint(device.Location.Value));
            updateRequest.Parameters["identifier"] = device.Identifier;

            IEnumerable devicesSupportingRoutes = this.intAirAct.DevicesSupportingRoute(Routes.SetLocationRoute);
            foreach (IADevice iaDevice in devicesSupportingRoutes)
            {
                this.intAirAct.SendRequest(updateRequest, iaDevice, delegate(IAResponse response, Exception exception)
                {
                    if (exception != null)
                    {
                        failure(exception);
                        return;
                    }
                    else
                    {
                        success();
                    }
                });

                // Break, so that we only send the update to one server
                // How our system should function if there are multiple servers is undefined ...
                break;
            }
        }
コード例 #15
0
        private void SensorDepthFrameReady(object sender, DepthImageFrameReadyEventArgs e)
        {
            using (DepthImageFrame depthFrame = e.OpenDepthImageFrame())
            {
                if (depthFrame == null)
                {
                    return;
                }
                depthFrame.CopyPixelDataTo(this.depthPixels);

                // Calculate minimum depth in the field, use this as the ipad's distance
                int minDepth = 2000;

                for (int x = 300; x < 340; x++)
                {
                    for (int y = 180; y < 400; y++)
                    {
                        int d = (ushort)this.depthPixels[x + y * depthFrame.Width];
                        d = d >> DepthImageFrame.PlayerIndexBitmaskWidth;

                        if (d > 0 && d < minDepth)
                        {
                            minDepth = d;
                        }
                    }
                }

                // Change needs to be above a threshold, to minimize jitter
                if (Math.Abs(minDepth - lastObservedDepth) > REPORT_THRESHOLD)
                {
                    lastObservedDepth = minDepth;

                    //the reported depth is are averaged over the last few frames, to further minimize jitter
                    xPositionAverage.currentValue = minDepth;
                    double slice = ((xPositionAverage.currentValue - minimumDepthField) / (maximumDepthField - minimumDepthField)) * SLICES;

                    //Debug.WriteLine(minDepth + " " + slice);

                    processedDepthLabel.Content = "depth: " + (int)minDepth + " avg depth: " + xPositionAverage.currentValue + " slice: " + (int)slice;

                    IARoute route = IARoute.Post("/mrivisualizer/slice/{slicenumber}");

                    IEnumerable<IADevice> devices = intAirAct.DevicesSupportingRoute(route);
                    if (devices.Count() > 0)
                    {
                        IARequest request = new IARequest(route);
                        request.Parameters.Add("slicenumber", ""+(int)slice);
                        request.Origin = intAirAct.OwnDevice;
                        foreach (IADevice device in devices)
                        {
                            intAirAct.SendRequest(request, device);
                        }
                    }
                    else
                    {
                        Debug.WriteLine("no device");
                    }
                }

                //Debug.WriteLine(minDepth);
                rawDepthLabel.Content = "raw depth: " + (int)minDepth;
            }
        }
コード例 #16
0
        void GetNearestDeviceInView(IARequest request, IAResponse response)
        {
            String deviceIdentifier = request.Parameters["identifier"];

            // Find the associated device in the Current Devices
            Device observer = locator.Devices.Find(d => d.Identifier.Equals(deviceIdentifier));
            if (observer == null)
            {
                //TODO: Should we use distinct status codes for distinct failure types here?
                response.StatusCode = 404;
                return;
            }

            // Find the nearest device that we observe
            Device nearestDevice = locator.GetNearestDeviceInView(observer);
            if (nearestDevice == null)
            {
                response.StatusCode = 404;
                return;
            }

            // Prepare the device for serialization
            IntermediateDevice intermediateDevice = PairableDevice.GetCompleteIntermediateDevice(nearestDevice);
            if (intermediateDevice == null)
            {
                response.StatusCode = 404;
                return;
            }

            response.SetBodyWith(intermediateDevice);
        }
コード例 #17
0
ファイル: MSEMultiSurface.cs プロジェクト: ase-lab/MSEAPI-CS
        /// <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");
                }
            });
        }
コード例 #18
0
 public void SendRequest(IARequest request, IADevice device)
 {
     this.client.SendRequest(request, device);
 }
コード例 #19
0
ファイル: MSEMultiSurface.cs プロジェクト: ase-lab/MSEAPI-CS
        public void Pair()
        {
            IARoute route = Routes.RequestPairingRoute;
            IEnumerable<IADevice> devices = IntAirAct.DevicesSupportingRoute(route);

            IARequest request = new IARequest(route);
            request.Parameters.Add("identifier", IntAirAct.OwnDevice.Name);
            request.Origin = IntAirAct.OwnDevice;
            foreach (IADevice device in devices)
            {
                IntAirAct.SendRequest(request, device, delegate(IAResponse response, Exception e)
                {
                    // log error maybe
                });
            }
        }
コード例 #20
0
ファイル: MSEMultiSurface.cs プロジェクト: ase-lab/MSEAPI-CS
        /// <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");
                }

            });
        }
コード例 #21
0
ファイル: IAIntAirAct.cs プロジェクト: ase-lab/IntAirActCS
 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));
             }
         });
     }
 }
コード例 #22
0
ファイル: IAIntAirAct.cs プロジェクト: ase-lab/IntAirActCS
 public void SendRequest(IARequest request, IADevice device, Action<IAResponse, Exception> action)
 {
     this.client.SendRequest(request, device, action);
 }
コード例 #23
0
ファイル: IAIntAirAct.cs プロジェクト: ase-lab/IntAirActCS
 public void SendRequest(IARequest request, IADevice device)
 {
     this.client.SendRequest(request, device);
 }
コード例 #24
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);
                };
            }
        }
コード例 #25
0
ファイル: MSEMultiSurface.cs プロジェクト: ase-lab/MSEAPI-CS
        /// <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");
                }
            });
        }
コード例 #26
0
        private RestRequest RequestFromIARequest(IARequest request)
        {
            RestRequest result = new RestRequest();

            switch (request.Route.Action)
            {
            case "GET":
                result.Method = Method.GET;
                break;

            case "POST":
                result.Method = Method.POST;
                break;

            case "PUT":
                result.Method = Method.PUT;
                break;

            case "OPTIONS":
                result.Method = Method.OPTIONS;
                break;

            case "DELETE":
                result.Method = Method.DELETE;
                break;

            case "HEAD":
                result.Method = Method.HEAD;
                break;

            case "PATCH":
                result.Method = Method.PATCH;
                break;

            default:
                result.Method = Method.GET;
                break;
            }
            Dictionary <string, string> parameters = new Dictionary <string, string>(request.Parameters);

            result.Resource = ReplaceParameters(request.Route.Resource, parameters);
            foreach (KeyValuePair <string, string> parameter in parameters)
            {
                result.AddParameter(parameter.Key, parameter.Value);
            }
            request.Origin.Foreach(x =>
            {
                result.AddHeader("X-IA-Origin", x.Name);
            });
            foreach (KeyValuePair <string, string> metaentry in request.Metadata)
            {
                result.AddHeader(metaentry.Key, metaentry.Value);
            }

            result.AddHeader("Content-Type", request.ContentType);

            Parameter p = new Parameter();

            p.Value = System.Text.Encoding.UTF8.GetString(request.Body);
            p.Type  = ParameterType.RequestBody;
            result.Parameters.Add(p);

            return(result);
        }
コード例 #27
0
ファイル: MSEMultiSurface.cs プロジェクト: ase-lab/MSEAPI-CS
 public void UpdateOrieantaion(double orientation)
 {
     //Windows.Devices.Sensors.Accelerometer requires VS2012
     var route = Routes.SetOrientationRoute;
     var request = new IARequest(route);
     request.Parameters.Add("identifier", IntAirAct.OwnDevice.Name);
     request.SetBodyWith(orientation);
     IEnumerable<IADevice> devices = IntAirAct.DevicesSupportingRoute(route);
     foreach (IADevice device in devices)
     {
         IntAirAct.SendRequest(request, device, delegate(IAResponse response, Exception e)
         {
             // log error maybe
         });
     }
 }
コード例 #28
0
 public void SendRequest(IARequest request, IADevice device, Action <IAResponse, Exception> action)
 {
     this.client.SendRequest(request, device, action);
 }
コード例 #29
0
 void UpdateDevicePairingState(IARequest request, IAResponse response)
 {
     Console.WriteLine(request.Parameters["identifier"]);
     pairingRecognizer.DevicePairAttempt(request.Parameters["identifier"]);
 }
コード例 #30
0
        void GetNearestDeviceInRange(IARequest request, IAResponse response)
        {
            String deviceIdentifier = request.Parameters["identifier"];
            double range = Double.Parse(request.Parameters["range"]);

            // Find the associated device in the Current Devices
            Device observer = locator.Devices.Find(d => d.Identifier.Equals(deviceIdentifier));
            if (observer == null)
            {
                response.StatusCode = 404;
                return;
            }

            Device nearestDevice = locator.GetNearestDeviceWithinRange(observer, range);
            if (nearestDevice == null)
            {
                response.StatusCode = 404;
                return;
            }

            IntermediateDevice intermediateDevice = PairableDevice.GetCompleteIntermediateDevice(nearestDevice);
            if (intermediateDevice == null)
            {
                response.StatusCode = 404;
                return;
            }

            // Respond with the device
            response.SetBodyWith(intermediateDevice);
        }
コード例 #31
0
ファイル: DeviceManager.cs プロジェクト: ase-lab/MSEAPI
        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
                        {

                        }

                    }
                });

            }
        }
コード例 #32
0
        private void DispatchImage(String imagePath)
        {
            IARoute route = IARoute.Post("/seismicaction/updateready");
            IEnumerable<IADevice> devices = this.intAirAct.DevicesSupportingRoute(route);
            if (devices.Count() > 0)
            {
                IARequest request = new IARequest(route);

                foreach (IADevice device in devices)
                {
                    this.intAirAct.SendRequest(request, device, delegate(IAResponse response, Exception error)
                    {
                        if (error == null)
                        {
                            Debug.WriteLine("Signal sent to iPad");
                        }
                        else
                        {
                            Debug.WriteLine("An error ocurred");
                        }

                    });
                }
            }
            else
            {
                Debug.WriteLine("No devices supporting the request route found");
            }
        }
コード例 #33
0
        /// <summary>
        /// Handle a request with updated information for a device.
        /// Presently, only used to update device location
        /// </summary>
        /// <param name="request">IntAirAct Request</param>
        /// <param name="response">IntAirAct Response</param>
        void UpdateDeviceOrientation(IARequest request, IAResponse response)
        {
            string result = request.BodyAsString();
            //TODO: Handle parse failure gracefully
            float newOrientation = float.Parse(result);

            String name = request.Parameters["identifier"];
            Device localDevice = locator.Devices.Find(d => d.Identifier.Equals(name));

            if (localDevice != null)
            {
                localDevice.Orientation = newOrientation;
                response.StatusCode = 201; // created
            }
            else
            {
                response.StatusCode = 404; // not found
            }
        }
コード例 #34
0
ファイル: DICOMViewer.xaml.cs プロジェクト: ase-lab/MRITable2
        private void SendToIpad()
        {
            SaveVisualToPNG(inkingCanvas, "mripicture.png");

            IARoute route = IARoute.Post("/mriimage/updateready");
            IEnumerable<IADevice> devices = this.intAirAct.DevicesSupportingRoute(route);
            if (devices.Count() > 0)
            {
                IARequest request = new IARequest(route);

                foreach (IADevice device in devices)
                {
                    this.intAirAct.SendRequest(request, device, delegate(IAResponse response, Exception error)
                    {
                        if (error == null)
                        {
                            Debug.WriteLine("Signal sent to iPad");
                        }
                        else
                        {
                            Debug.WriteLine("An error ocurred");
                        }

                    });
                }
            }
            else
            {
                Debug.WriteLine("No devices supporting the request route found");
            }
        }
コード例 #35
0
ファイル: MainWindow.xaml.cs プロジェクト: ase-lab/MSEAPI
        protected override void OnDrop(DragEventArgs e)
        {
            string DataType = e.Data.GetFormats(true)[0];

            //if the object dropped is a tracker
            if (DataType == "trackerControl")
            {
                base.OnDrop(e);
                Point mouseLocation = e.GetPosition(sharedCanvas);

                // Grab the data we packed into the DataObject
                TrackerControl trackerControl = (TrackerControl)e.Data.GetData("trackerControl");

                // Hide the Ghost and Text since a Drop has been made
                MainWindow.GhostBorder.Visibility = System.Windows.Visibility.Hidden;
                ghostTextBlock.Visibility = System.Windows.Visibility.Hidden;

                // Return the Opacity of the TrackerControl
                trackerControl.Opacity = 1;

                trackerControl.Tracker.Location = DrawingResources.ConvertFromDisplayCoordinatesToMeters(mouseLocation, sharedCanvas);

                // Check if the TrackerControl is already a child of Shared Canvas
                Point canvasBounds = new Point(DrawingResources.ConvertFromMetersToPixelsX(DrawingResources.ROOM_WIDTH, sharedCanvas), DrawingResources.ConvertFromMetersToPixelsY(DrawingResources.ROOM_HEIGHT, sharedCanvas));

                if (!trackerControl.IsDescendantOf(SharedCanvas))
                {
                    trackerControl.formatForCanvas();
                    kinectWrapPanel.Children.Remove(trackerControl);
                    SharedCanvas.Children.Add(trackerControl);

                    if (trackerControl.Tracker.Orientation == null)
                        trackerControl.Tracker.Orientation = 270;
                }

                // if the cursor is outside the canvas, put the tracker back in stackpanel.
                else if (!(mouseLocation.X < canvasBounds.X && mouseLocation.Y < canvasBounds.Y))
                {
                    trackerControl.Tracker.StopStreaming();
                    cleanUpKinectPersons(trackerControl.Tracker.Identifier);
                    trackerControl.formatForStackPanel();
                    SharedCanvas.Children.Remove(trackerControl);
                    kinectWrapPanel.Children.Add(trackerControl);
                }
            }

            //if the objet dropped is a device.
            else if (DataType == "deviceControl")
            {
                base.OnDrop(e);
                Point mouseLocation = e.GetPosition(sharedCanvas);

                // Grab the data we packed into the DataObject
                DeviceControl deviceControl = (DeviceControl)e.Data.GetData("deviceControl");

                // Hide the Ghost and Text since a Drop has been made
                MainWindow.GhostBorder.Visibility = System.Windows.Visibility.Hidden;
                ghostTextBlock.Visibility = System.Windows.Visibility.Hidden;

                // Return the Opacity of the DeviceControl
                deviceControl.Opacity = 1;

                PairableDevice device = deviceControl.PairableDevice;
                IADevice iaDevice = deviceControl.IADevice;

                IARequest request = new IARequest(Routes.SetLocationRoute);
                request.Parameters["identifier"] = iaDevice.Name;

                Point canvasBounds = new Point(DrawingResources.ConvertFromMetersToPixelsX(DrawingResources.ROOM_WIDTH, sharedCanvas), DrawingResources.ConvertFromMetersToPixelsY(DrawingResources.ROOM_HEIGHT, sharedCanvas));

                //if the dragged device is a pairable device (i.e iPad)
                if (!iaDevice.SupportedRoutes.Contains(Routes.GetLocationRoute))
                {
                    Point mouseLocationOnCanvas = mouseLocation = DrawingResources.ConvertFromDisplayCoordinatesToMeters(mouseLocation, sharedCanvas);
                    bool pairedToNewDevice = false;

                    foreach (KeyValuePair<PairablePerson, PersonControl> keyPair in PersonControlDictionary)
                    {
                        Point personLocation = keyPair.Key.Location.Value;
                        double distance = Math.Sqrt(Math.Pow(mouseLocationOnCanvas.X - personLocation.X, 2) + Math.Pow(mouseLocationOnCanvas.Y - personLocation.Y, 2));

                        //if the mouse drop is close to a person, pair the device with that person.
                        if (distance < 0.3 && (device.HeldByPersonIdentifier == keyPair.Key.Identifier || keyPair.Key.PairingState != PairingState.Paired))
                        {
                            if (device.PairingState == PairingState.Paired || device.PairingState == PairingState.PairedButOccluded)
                                kinectManager.PairingRecognizer.UnpairDevice(device);

                            kinectManager.PairingRecognizer.Pair(device, keyPair.Key);
                            pairedToNewDevice = true;
                            break;
                        }
                    }

                    //if the mouse drop is not close to a person then unpair the device.
                    if (!pairedToNewDevice)
                        kinectManager.PairingRecognizer.UnpairDevice(device);
                }

                //if the dragged device is not a pairable device (i.e table-top)
                else if (iaDevice.SupportedRoutes.Contains(Routes.GetLocationRoute))
                {
                    if (mouseLocation.X < canvasBounds.X && mouseLocation.Y < canvasBounds.Y)
                    {
                        // Dropped within Canvas, so we want to place it on the canvas
                        device.Location = DrawingResources.ConvertFromDisplayCoordinatesToMeters(mouseLocation, sharedCanvas);
                        request.SetBodyWith(new IntermediatePoint(device.Location.Value));
                    }
                    else
                    {
                        // Not dropped within Canvas, so we want to put it back on the stack panel
                        device.Location = null;
                        request.SetBodyWith(null);
                    }

                    // Send a request to the Device that their location has changed
                    kinectManager.IntAirAct.SendRequest(request, iaDevice);
                }
            }
        }
コード例 #36
0
ファイル: MSELocator.cs プロジェクト: ase-lab/MSEAPI-CS
        public void UpdateDeviceOrientation(MSEDevice device, MSESuccessHandler success, MSEErrorHandler failure)
        {
            IARequest request = new IARequest(Routes.SetOrientationRoute);
            request.SetBodyWithString(device.Orientation.Value.ToString());
            request.Parameters["identifier"] = device.Identifier;

            IEnumerable devicesSupportingRoutes = this.intAirAct.DevicesSupportingRoute(Routes.SetOrientationRoute);
            foreach (IADevice iaDevice in devicesSupportingRoutes)
            {
                this.intAirAct.SendRequest(request, iaDevice, delegate(IAResponse response, Exception exception)
                {
                    if (exception != null)
                    {
                        failure(exception);
                        return;
                    }
                    else
                    {
                        success();
                    }
                });

                break;
            }
        }
コード例 #37
0
 public void SendRequest(IARequest request, IADevice device)
 {
     this.SendRequest(request, device, null);
 }
コード例 #38
0
 public void SendRequest(IARequest request, IADevice device)
 {
     this.SendRequest(request, device, null);
 }
コード例 #39
0
        void GetOffsetAngle(IARequest request, IAResponse response)
        {
            // Find the device
            String deviceIdentifier = request.Parameters["identifier"];
            Device requestingDevice = locator.Devices.Find(d => d.Identifier == deviceIdentifier);

            // Device Does Not Exist
            if (requestingDevice == null)
            {
                response.StatusCode = 404; // not found
                return;
            }

            if (requestingDevice.Location.HasValue && locator.Trackers[0].Location.HasValue)
            {
                Point requestingDeviceLocation = requestingDevice.Location.Value;
                Point offsetLocation = locator.Trackers[0].Location.Value;

                double angle = Util.AngleBetweenPoints(requestingDeviceLocation, offsetLocation);
                response.SetBodyWith(angle);

                //response.SetBodyWith(90);
            }
            else
            {
                // Device doesn't have location
                response.StatusCode = 400;
            }
        }
コード例 #40
0
ファイル: PersonManager.cs プロジェクト: ase-lab/MSEAPI
        private void RemoveOldPeople(List<Skeleton> skeletons, List<PairablePerson> pairablePersons, List<PairableDevice> pairableDevices, String kinectID)
        {
            // If a person has dissappeared, remove the kinect ID from they TrackIDwithSkeletonID dictionary
            List<PairablePerson> vanishedPersons = new List<PairablePerson>();
            foreach (PairablePerson person in pairablePersons)
            {
                foreach (KeyValuePair<string, string> entry in person.TrackerIDwithSkeletonID.ToList())
                {
                    if (entry.Key != null && entry.Key.Equals(kinectID))
                    {
                        bool found = false;
                        foreach (Skeleton skeleton in skeletons)
                        {
                            if (entry.Value.Equals(skeleton.TrackingId.ToString()))
                            {
                                found = true;
                            }
                        }
                        if (!found)
                        {
                            // Remove from the dictionary
                            person.TrackerIDwithSkeletonID.Remove(kinectID);
                        }
                    }
                }

                //If that person is not tracked by anyone then make them an occluded person.
                if(person.TrackerIDwithSkeletonID.Count == 0)
                {

                    //Remove Held-By-Person Identifier
                    PairableDevice device = pairableDevices.Find(x => x.Identifier.Equals(person.HeldDeviceIdentifier));

                    // If the person was not paired to a device, we can remove them immediately
                    if (device == null)
                    {
                        RemovePerson(vanishedPersons, person);

                    }
                    // If the person was paired, then we allow a grace period for them to reappear, to avoid immediately unpairing them
                    else
                    {

                        if (person.PairingState == PairingState.Paired)
                        {
                            person.PairingState = PairingState.PairedButOccluded;
                            person.Identifier = null;
                        }
                        // The person will remain with PairingState == PairedButOccluded for a few seconds, after which it will mark itself NotPaired
                        // If this happens, we remove the person for good, and unpair their device
                        else if (person.PairingState == PairingState.NotPaired)
                        {
                            device.HeldByPersonIdentifier = null;
                            device.PairingState = PairingState.NotPaired;

                            // Dispatch a message to the device
                            IARequest request = new IARequest(Routes.BecomeUnpairedRoute);
                            // Find the IntAirAct device matching the current device.
                            IADevice iaDevice = intAirAct.Devices.Find(d => d.Name == device.Identifier);
                            intAirAct.SendRequest(request, iaDevice);
                            System.Diagnostics.Debug.WriteLine(iaDevice.Name + " " + iaDevice.Host);

                            RemovePerson(vanishedPersons, person);
                        }

                    }

                }
            }
            foreach (PairablePerson person in vanishedPersons)
            {
                pairablePersons.Remove(person);
            }
        }
コード例 #41
0
        /// <summary>
        /// Handle a request for information about a device
        /// </summary>
        /// <param name="request"></param>
        /// <param name="response"></param>
        void GetDevice(IARequest request, IAResponse response)
        {
            String deviceIdentifier = request.Parameters["identifier"];

            // Find the associated device in the Current Devices
            Device device = locator.Devices.Find(d => d.Identifier.Equals(deviceIdentifier));
            if (device == null)
            {
                response.StatusCode = 404;
                return;
            }

            // Get the intermediateDevice for serialization
            IntermediateDevice intermediateDevice = PairableDevice.GetCompleteIntermediateDevice(device);
            if (intermediateDevice == null)
            {
                //TODO: Should this status code be different, to reflect that the device exists but couldn't be returned due to incompleteness?
                response.StatusCode = 404;
                return;
            }

            // Respond with the device
            response.SetBodyWith(intermediateDevice);
        }