Пример #1
0
 protected DevicePortalConnection GetDevicePortal()
 {
     if (cachedDevicePortal == null)
     {
         cachedDevicePortal = FindObjectOfType <DevicePortalConnection>();
     }
     return(cachedDevicePortal);
 }
Пример #2
0
 // Sample RequestReceived handler demonstrating response construction, based on request
 private void DevicePortalConnection_RequestReceived(DevicePortalConnection sender, DevicePortalConnectionRequestReceivedEventArgs args)
 {
     if (args.RequestMessage.RequestUri.AbsolutePath.ToString() == statusUri.ToString())
     {
         args.ResponseMessage.StatusCode = HttpStatusCode.Ok;
         args.ResponseMessage.Content    = new HttpStringContent("{ \"status\": \"good\" }");
         args.ResponseMessage.Content.Headers.ContentType = new HttpMediaTypeHeaderValue("application/json");
     }
     else
     {
         args.ResponseMessage.StatusCode = HttpStatusCode.NotFound;
     }
 }
Пример #3
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            // Take a deferral to allow the background task to continue executing
            this._taskDeferral     = taskInstance.GetDeferral();
            taskInstance.Canceled += TaskInstance_Canceled;

            // Create a DevicePortal client from an AppServiceConnection
            var details = taskInstance.TriggerDetails as AppServiceTriggerDetails;
            var appServiceConnection = details.AppServiceConnection;

            _devicePortalConnection = DevicePortalConnection.GetForAppServiceConnection(appServiceConnection);

            // Add Closed, RequestReceived handlers
            _devicePortalConnection.Closed          += _devicePortalConnection_Closed;
            _devicePortalConnection.RequestReceived += DevicePortalConnection_RequestReceived;
        }
Пример #4
0
// Implement background task handler with a DevicePortalConnection
        protected override void OnBackgroundActivated(BackgroundActivatedEventArgs args)
        {
            // Take a deferral to allow the background task to continue executing
            var taskInstance = args.TaskInstance;

            this.taskDeferral      = taskInstance.GetDeferral();
            taskInstance.Canceled += TaskInstance_Canceled;

            // Create a DevicePortal client from an AppServiceConnection
            var details = taskInstance.TriggerDetails as AppServiceTriggerDetails;
            var appServiceConnection = details.AppServiceConnection;

            this.devicePortalConnection = DevicePortalConnection.GetForAppServiceConnection(appServiceConnection);

            // Add handlers for RequestReceived and Closed events
            devicePortalConnection.RequestReceived += DevicePortalConnection_RequestReceived;
            devicePortalConnection.Closed          += DevicePortalConnection_Closed;
        }
Пример #5
0
        private void DevicePortalConnection_RequestReceived(DevicePortalConnection sender, DevicePortalConnectionRequestReceivedEventArgs args)
        {
            var req = args.RequestMessage;
            var res = args.ResponseMessage;

            if (req.RequestUri.AbsolutePath.EndsWith("/echo"))
            {
                // construct an html response message
                string con  = "<h1>" + req.RequestUri.AbsoluteUri + "</h1><br/>";
                var    proc = Windows.System.Diagnostics.ProcessDiagnosticInfo.GetForCurrentProcess();
                con        += String.Format("This process is consuming {0} bytes (Working Set)<br/>", proc.MemoryUsage.GetReport().WorkingSetSizeInBytes);
                con        += String.Format("The process PID is {0}<br/>", proc.ProcessId);
                con        += String.Format("The executable filename is {0}", proc.ExecutableFileName);
                res.Content = new HttpStringContent(con);
                res.Content.Headers.ContentType = new HttpMediaTypeHeaderValue("text/html");
                res.StatusCode = HttpStatusCode.Ok;
            }
            //...
        }
Пример #6
0
 private void DevicePortalConnection_Closed(DevicePortalConnection sender, DevicePortalConnectionClosedEventArgs args)
 {
     Close();
 }
Пример #7
0
 // Complete the deferral if task is canceled or DevicePortal connection closed
 private void Close()
 {
     this.devicePortalConnection = null;
     this.taskDeferral.Complete();
 }
Пример #8
0
        private void DevicePortalConnection_RequestReceived(DevicePortalConnection sender, DevicePortalConnectionRequestReceivedEventArgs args)
        {
            var req = args.RequestMessage;
            var res = args.ResponseMessage;

            if (req.RequestUri.AbsolutePath.ToString() == statusUri.ToString())
            {
                args.ResponseMessage.StatusCode = HttpStatusCode.Ok;
                MemoryStream mem = new MemoryStream();
                serializer.WriteObject(mem, AppSettings.Current);
                mem.Position = 0;
                args.ResponseMessage.Content = new HttpStringContent(new StreamReader(mem).ReadToEnd());
                args.ResponseMessage.Content.Headers.ContentType = new HttpMediaTypeHeaderValue("application/json");
                return;
            }

            if (req.RequestUri.AbsolutePath.ToString() == updateUri.ToString())
            {
                WwwFormUrlDecoder decoder = new WwwFormUrlDecoder(req.RequestUri.Query);
                AppSettings.Current.DARKSKY_API_KEY      = decoder.GetFirstValueByName("DARKSKY_API_KEY");
                AppSettings.Current.RAIL_API_KEY         = decoder.GetFirstValueByName("RAIL_API_KEY");
                AppSettings.Current.STATION_CRS          = decoder.GetFirstValueByName("STATION_CRS");
                AppSettings.Current.LOCATION_LAT         = double.Parse(decoder.GetFirstValueByName("LOCATION_LAT"));
                AppSettings.Current.LOCATION_LNG         = double.Parse(decoder.GetFirstValueByName("LOCATION_LNG"));
                AppSettings.Current.GET_DRINK_TIME       = int.Parse(decoder.GetFirstValueByName("GET_DRINK_TIME"));
                AppSettings.Current.DRINK_UP_TIME        = int.Parse(decoder.GetFirstValueByName("DRINK_UP_TIME"));
                AppSettings.Current.WALK_TIME_TO_STATION = int.Parse(decoder.GetFirstValueByName("WALK_TIME_TO_STATION"));

                AppSettings.Current.Save();
                args.ResponseMessage.StatusCode = HttpStatusCode.Ok;
                args.ResponseMessage.Content    = new HttpStringContent("{ \"status\": \"good\" }");
                args.ResponseMessage.Content.Headers.ContentType =
                    new HttpMediaTypeHeaderValue("application/json");
                return;
            }

            if (req.RequestUri.LocalPath.ToLower().Contains("/www/") || req.RequestUri.LocalPath.ToLower().EndsWith("/"))
            {
                var filePath = req.RequestUri.AbsolutePath.Replace('/', '\\').ToLower();
                //filePath = filePath.Replace("\\departureboard", "");
                if (filePath.EndsWith(@"\"))
                {
                    filePath += @"\www\index.html";
                }
                try
                {
                    var fileStream = Windows.ApplicationModel.Package.Current.InstalledLocation.OpenStreamForReadAsync(filePath).GetAwaiter().GetResult();
                    res.StatusCode = HttpStatusCode.Ok;
                    res.Content    = new HttpStreamContent(fileStream.AsInputStream());
                    res.Content.Headers.ContentType = new HttpMediaTypeHeaderValue("text/html");
                }
                catch (FileNotFoundException e)
                {
                    string con = String.Format("<h1>{0} - not found</h1>\r\n", filePath);
                    con           += "Exception: " + e.ToString();
                    res.Content    = new HttpStringContent(con);
                    res.StatusCode = HttpStatusCode.NotFound;
                    res.Content.Headers.ContentType = new HttpMediaTypeHeaderValue("text/html");
                }
                return;
            }

            args.ResponseMessage.StatusCode = HttpStatusCode.NotFound;
        }
Пример #9
0
        private void DevicePortalGUI()
        {
            DevicePortalConnection devicePortal = GetDevicePortal();

            if (devicePortal == null)
            {
                return;
            }

            devicePortalFoldout = EditorGUILayout.Foldout(devicePortalFoldout, "Device Portal");
            if (devicePortalFoldout)
            {
                using (new EditorGUILayout.VerticalScope("Box"))
                {
                    bool prevEnabled = GUI.enabled;
                    GUILayout.Label("DevicePortal", EditorStyles.boldLabel);

                    string stateText, buttonText;
                    bool   canPressButton = true;
                    Action onPressButton  = () => { };
                    switch (devicePortal.State)
                    {
                    case DevicePortalState.NotConnected:
                        stateText      = "<color=silver>Not Connected</color>";
                        canPressButton =
                            !string.IsNullOrWhiteSpace(devicePortalUser) &&
                            !string.IsNullOrEmpty(devicePortalPassword) &&
                            IPAddress.TryParse(holographicCameraIPAddress, out var _) &&
                            EditorApplication.isPlaying;
                        buttonText    = "Connect";
                        onPressButton = () => devicePortal.StartConnect(holographicCameraIPAddress, devicePortalUser, devicePortalPassword);
                        break;

                    case DevicePortalState.Connecting:
                        stateText     = "<color=silver>Connecting...</color>";
                        buttonText    = "Cancel";
                        onPressButton = devicePortal.CancelConnect;
                        break;

                    case DevicePortalState.NotStarted:
                        stateText      = "<color=red>App was not started</color>";
                        canPressButton = devicePortal.IsAppInstalled;
                        buttonText     = "Start App";
                        onPressButton  = devicePortal.StartApp;
                        break;

                    case DevicePortalState.NotRunning:
                        stateText     = "<color=orange>Started, but not running</color>";
                        buttonText    = "Stop App";
                        onPressButton = devicePortal.StopApp;
                        break;

                    case DevicePortalState.Running:
                        stateText     = "<color=green>Running</color>";
                        buttonText    = "Stop App";
                        onPressButton = devicePortal.StopApp;
                        break;

                    case DevicePortalState.Starting:
                        stateText      = "<color=orange>Starting...</color>";
                        buttonText     = "Cancel";
                        canPressButton = false;
                        break;

                    case DevicePortalState.Stopping:
                        stateText      = "<color=orange>Stopping...</color>";
                        canPressButton = false;
                        buttonText     = "Cancel";
                        break;

                    default:
                        stateText      = "<color=magenta>I don't know</color>";
                        canPressButton = true;
                        buttonText     = "Disconnect";
                        onPressButton  = devicePortal.Disconnect;
                        break;
                    }
                    GUIStyle appStateStyle = EditorStyles.textField;
                    appStateStyle.richText  = true;
                    appStateStyle.fontStyle = FontStyle.Bold;
                    using (new GUILayout.HorizontalScope())
                    {
                        GUI.enabled = false;
                        EditorGUILayout.TextField("State", stateText, appStateStyle);
                        GUI.enabled = prevEnabled && canPressButton;
                        if (GUILayout.Button(buttonText, GUILayout.Width(connectAndDisconnectButtonWidth)))
                        {
                            onPressButton();
                        }

                        GUI.enabled = prevEnabled;
                        if (devicePortal.IsConnected && GUILayout.Button("Disconnect", GUILayout.Width(connectAndDisconnectButtonWidth)))
                        {
                            devicePortal.Disconnect();
                        }
                    }

                    GUI.enabled = false;
                    EditorGUILayout.TextField("IP address", holographicCameraIPAddress);

                    GUI.enabled          = prevEnabled && devicePortal.State == DevicePortalState.NotConnected;
                    devicePortalUser     = EditorGUILayout.TextField("Username", devicePortalUser);
                    devicePortalPassword = EditorGUILayout.PasswordField("Password", devicePortalPassword);
                    EditorGUILayout.Space();

                    GUI.enabled = prevEnabled && devicePortal.IsConnected;
                    GUILayout.Label("Health", EditorStyles.boldLabel);
                    EditorGUILayout.FloatField(new GUIContent("CPU", "The amount of CPU used by the app"), devicePortal.CPUUsage);
                    EditorGUILayout.TextField(new GUIContent("RAM", "The amount of RAM used by the app"), $"{devicePortal.WorkingSet / 1024 / 1024}MiB");
                    EditorGUILayout.TextField("Battery", $"{(int)(devicePortal.BatteryLevel * 100)}% {(devicePortal.IsPowered ? "- Powered" : "")}");

                    GUI.enabled = prevEnabled;
                }
            }
        }