Inheritance: IBackgroundTaskDeferral
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            serviceDeferral = taskInstance.GetDeferral();
            taskInstance.Canceled += OnTaskCanceled;

            var triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails;

            if (triggerDetails == null)
            {
                serviceDeferral.Complete();
                return;
            }

            try
            {
                voiceServiceConnection = VoiceCommandServiceConnection.FromAppServiceTriggerDetails(triggerDetails);
                voiceServiceConnection.VoiceCommandCompleted += OnVoiceCommandCompleted;

                var voiceCommand = await voiceServiceConnection.GetVoiceCommandAsync();

                //Find the command name witch should match the VCD
                if (voiceCommand.CommandName == "buildit_help")
                {
                    var props = voiceCommand.Properties;
                    await CortanaHelpList();
                }
                await Task.Delay(1000);
                await ShowProgressScreen();
            }
            catch
            {
                Debug.WriteLine("Unable to process voice command");
            }
            serviceDeferral.Complete();
        }
        //
        // The Run method is the entry point of a background task.
        //
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
            Debug.WriteLine("Background " + taskInstance.Task.Name + " Starting...");

            // For performing asynchronous operations in the background task
            BackgroundTaskDeferral asyncDeferral = taskInstance.GetDeferral();

           

            //
            // Query BackgroundWorkCost
            // Guidance: If BackgroundWorkCost is high, then perform only the minimum amount
            // of work in the background task and return immediately.
            //
            var cost = BackgroundWorkCost.CurrentBackgroundWorkCost;
            var settings = ApplicationData.Current.LocalSettings;
            settings.Values["BackgroundWorkCost"] = cost.ToString();

            //
            // Associate a cancellation handler with the background task.
            //
            taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);

            //
            // Get the deferral object from the task instance, and take a reference to the taskInstance;
            //
            _deferral = taskInstance.GetDeferral();
            _taskInstance = taskInstance;

            _periodicTimer = ThreadPoolTimer.CreatePeriodicTimer(new TimerElapsedHandler(PeriodicTimerCallback), TimeSpan.FromSeconds(1));

            asyncDeferral.Complete();
        }
Esempio n. 3
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            // Create the deferral by requesting it from the task instance
            serviceDeferral = taskInstance.GetDeferral();

            AppServiceTriggerDetails triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails;

            if (triggerDetails != null && triggerDetails.Name.Equals("IMCommandVoice"))
            {
                voiceServiceConnection = VoiceCommandServiceConnection.FromAppServiceTriggerDetails(triggerDetails);

                VoiceCommand voiceCommand = await voiceServiceConnection.GetVoiceCommandAsync();

                // Perform the appropriate command depending on the operation defined in VCD
                switch (voiceCommand.CommandName)
                {
                    case "oldback":
                        VoiceCommandUserMessage userMessage = new VoiceCommandUserMessage();
                        userMessage.DisplayMessage = "The current temperature is 23 degrees";
                        userMessage.SpokenMessage = "The current temperature is 23 degrees";

                        VoiceCommandResponse response = VoiceCommandResponse.CreateResponse(userMessage, null);
                        await voiceServiceConnection.ReportSuccessAsync(response);
                        break;

                    default:
                        break;
                }
            }

            // Once the asynchronous method(s) are done, close the deferral
            serviceDeferral.Complete();
        }
Esempio n. 4
0
        /// <remarks>
        /// If you start any asynchronous methods here, prevent the task
        /// from closing prematurely by using BackgroundTaskDeferral as
        /// described in http://aka.ms/backgroundtaskdeferral
        /// </remarks>
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            // This deferral should have an instance reference, if it doesn't... the GC will
            // come some day, see that this method is not active anymore and the local variable
            // should be removed. Which results in the application being closed.
            _deferral = taskInstance.GetDeferral();
            var restRouteHandler = new RestRouteHandler();

            restRouteHandler.RegisterController<AsyncControllerSample>();
            restRouteHandler.RegisterController<FromContentControllerSample>();
            restRouteHandler.RegisterController<PerCallControllerSample>();
            restRouteHandler.RegisterController<SimpleParameterControllerSample>();
            restRouteHandler.RegisterController<SingletonControllerSample>();
            restRouteHandler.RegisterController<ThrowExceptionControllerSample>();
            restRouteHandler.RegisterController<WithResponseContentControllerSample>();

            var configuration = new HttpServerConfiguration()
                .ListenOnPort(8800)
                .RegisterRoute("api", restRouteHandler)
                .RegisterRoute(new StaticFileRouteHandler(@"Restup.DemoStaticFiles\Web"))
                .EnableCors(); // allow cors requests on all origins
            //  .EnableCors(x => x.AddAllowedOrigin("http://specificserver:<listen-port>"));

            var httpServer = new HttpServer(configuration);
            _httpServer = httpServer;
            
            await httpServer.StartServerAsync();

            // Dont release deferral, otherwise app will stop
        }
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            try {
                var triggerDetail = (AppServiceTriggerDetails) taskInstance.TriggerDetails;
                _deferral = taskInstance.GetDeferral();

                Hub.Instance.ForegroundConnection = triggerDetail.AppServiceConnection;
                Hub.Instance.ForegroundTask = this;

                taskInstance.Canceled += (s, e) => Close();
                triggerDetail.AppServiceConnection.ServiceClosed += (s, e) => Close();
            }
            catch (System.Exception e)
            {
                if (Hub.Instance.IsAppInsightsEnabled)
                {
                    Hub.Instance.RTCStatsManager.TrackException(e);
                }
                if (_deferral != null)
                {
                    _deferral.Complete();
                }
                throw e;
            }
        }
Esempio n. 6
0
        /// <summary>
        /// Hệ thống gọi đến hàm này khi association backgroundtask được bật
        /// </summary>
        /// <param name="taskInstance"> hệ thống tự tạo và truyền vào đây</param>
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            //System.Diagnostics.Debug.WriteLine("background run");
            taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(BackgroundTaskCanceled);
            taskInstance.Task.Completed += new BackgroundTaskCompletedEventHandler(BackgroundTaskCompleted);
            _backgroundstarted.Set();//
            _deferral = taskInstance.GetDeferral();

            //Playlist = new BackgroundPlaylist();
            _smtc = initSMTC();


            this._foregroundState = this.initForegroundState();

            BackgroundMediaPlayer.Current.CurrentStateChanged += BackgroundMediaPlayer_CurrentStateChanged;
            //Playlist = await BackgroundPlaylist.LoadBackgroundPlaylist("playlist.xml");
            Playlist = new BackgroundPlaylist();
            Playlist.ListPathsource = await BackgroundPlaylist.LoadCurrentPlaylist(Constant.CurrentPlaylist);
            
            if (_foregroundState != eForegroundState.Suspended)
            {
                ValueSet message = new ValueSet();
                message.Add(Constant.BackgroundTaskStarted, "");
                BackgroundMediaPlayer.SendMessageToForeground(message);
            }  
            Playlist.TrackChanged += Playlist_TrackChanged;
            BackgroundMediaPlayer.MessageReceivedFromForeground += BackgroundMediaPlayer_MessageReceivedFromForeground;
            BackgroundMediaPlayer.Current.MediaEnded +=Current_MediaEnded;
            ApplicationSettingHelper.SaveSettingsValue(Constant.BackgroundTaskState, Constant.BackgroundTaskRunning);
            isbackgroundtaskrunning = true;
            _loopState = eLoopState.None;
        }
Esempio n. 7
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            // Ensure our background task remains running
            taskDeferral = taskInstance.GetDeferral();

            // Mutex will be used to ensure only one thread at a time is talking to the shield / isolated storage
            mutex = new Mutex(false, mutexId);

            // Initialize ConnectTheDots Settings
            localSettings.ServicebusNamespace = "iotbuildlab-ns";
            localSettings.EventHubName = "ehdevices";
            localSettings.KeyName = "D1";
            localSettings.Key = "iQFNbyWTYRBwypMtPmpfJVz+NBgR32YHrQC0ZSvId20=";
            localSettings.DisplayName = GetHostName();
            localSettings.Organization = "IoT Build Lab";
            localSettings.Location = "USA";

            SaveSettings();

            // Initialize WeatherShield
            await shield.BeginAsync();

            // Create a timer-initiated ThreadPool task to read data from I2C
            i2cTimer = ThreadPoolTimer.CreatePeriodicTimer(PopulateWeatherData, TimeSpan.FromSeconds(i2cReadIntervalSeconds));

            // Start the server
            server = new HttpServer(port);
            var asyncAction = ThreadPool.RunAsync((w) => { server.StartServer(shield, weatherData); });

            // Task cancellation handler, release our deferral there 
            taskInstance.Canceled += OnCanceled;

            // Create a timer-initiated ThreadPool task to renew SAS token regularly
            SasTokenRenewTimer = ThreadPoolTimer.CreatePeriodicTimer(RenewSasToken, TimeSpan.FromMinutes(15));
        }
        public async void Run(IBackgroundTaskInstance taskInstance) {
            try {
                // Ensure our background task remains running
                taskDeferral = taskInstance.GetDeferral();

                // Initialize cloud connection
                azureConnector = new AzureConnector();
                await azureConnector.InitAsync();

                // Initialize WeatherShield
                await shield.BeginAsync();

                // Create a timer-initiated ThreadPool task to read data from I2C
                ThreadPoolTimer.CreatePeriodicTimer(async (source) => {
                    await readAndSendWeatherRecord();
                }, TimeSpan.FromSeconds(weatherShieldReadInterval));

                // Task cancellation handler, release our deferral there
                taskInstance.Canceled += OnCanceled;
            } catch(Exception ex) {
                await LogExceptionAsync(nameof(Run), ex);
                if(Debugger.IsAttached) {
                    Debugger.Break();
                }

                // If it goes to shit here, rethrow which will terminate the process - but at least we have it logged!
                throw;
            }
        }
Esempio n. 9
0
        public async void Run( IBackgroundTaskInstance taskInstance )
        {
            Deferral = taskInstance.GetDeferral();

            XParameter[] Params = SavedChannels.Parameters( "channel" );

            if ( Params.Length == 0 )
            {
                Deferral.Complete();
                return;
            }

            // Associate a cancellation handler with the background task.
            taskInstance.Canceled += new BackgroundTaskCanceledEventHandler( OnCanceled );

            foreach ( XParameter Param in Params )
            {
                CurrentTask = new XParameter( DateTime.Now.ToFileTime() + "" );
                CurrentTask.SetValue( new XKey[] {
                    new XKey( "name", taskInstance.Task.Name )
                    , new XKey( "start", true )
                    , new XKey( "end", false )
                } );

                PushNotificationChannel channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();

                if ( channel.Uri != Param.GetValue( "uri" ) )
                {
                    await RenewChannel( Param.GetValue( "provider" ), Param.Id, Uri.EscapeDataString( channel.Uri ) );
                }

            }

            Deferral.Complete();
        }
Esempio n. 10
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            // Ensure our background task remains running
            taskDeferral = taskInstance.GetDeferral();

            // Mutex will be used to ensure only one thread at a time is talking to the shield / isolated storage
            mutex = new Mutex(false, mutexId);
         
            // Initialize ConnectTheDots Settings
            localSettings.ServicebusNamespace = "windowactuator-ns";
            localSettings.EventHubName = "ehdevices";
            localSettings.KeyName = "D1";
            localSettings.Key = "1uMOwjURpgGX9l5JqnYeatBkIRoLzP7qH8YGFUeAIrU=";
            localSettings.DisplayName = GetHostName();
            localSettings.Organization = "Ulster University";
            localSettings.Location = "North Europe";

            SaveSettings();

            // Initialize WeatherShield
            await shield.BeginAsync();

            // Create a timer-initiated ThreadPool task to read data from I2C
            i2cTimer = ThreadPoolTimer.CreatePeriodicTimer(PopulateWeatherData, TimeSpan.FromSeconds(i2cReadIntervalSeconds));

            // Start the server
            server = new HttpServer(port);
            var asyncAction = ThreadPool.RunAsync((w) => { server.StartServer(shield, weatherData); });

            // Task cancellation handler, release our deferral there 
            taskInstance.Canceled += OnCanceled;

            // Create a timer-initiated ThreadPool task to renew SAS token regularly
            SasTokenRenewTimer = ThreadPoolTimer.CreatePeriodicTimer(RenewSasToken, TimeSpan.FromMinutes(15));
        }
Esempio n. 11
0
 public void Run(IBackgroundTaskInstance taskInstance)
 {
     _deferral = taskInstance.GetDeferral();
     Init();
     temperatureTimer = ThreadPoolTimer.CreatePeriodicTimer(temperatureTimer_Tick, TimeSpan.FromMinutes(5));
     thermostatStatusTimer = ThreadPoolTimer.CreatePeriodicTimer(thermostatStatusTimer_Tick, TimeSpan.FromMilliseconds(500));
 }
Esempio n. 12
0
 public void Run(IBackgroundTaskInstance taskInstance)
 {
     deferral = taskInstance.GetDeferral();
     InitGPIO();
     
     GetBusArrivalData();
 }
 /// <summary>
 /// Entry point for the background task.
 /// </summary>
 public async void Run(IBackgroundTaskInstance taskInstance)
 {
     var triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails;
     if (null != triggerDetails && triggerDetails.Name == "LightControllerVoiceCommandService")
     {
         _deferral = taskInstance.GetDeferral();
         taskInstance.Canceled += (s, e) => _deferral.Complete();
         if (true != await InitializeAsync(triggerDetails))
         {
             return;
         }
         // These command phrases are coded in the VoiceCommands.xml file.
         switch (_voiceCommand.CommandName)
         {
             case "changeLightsState": await ChangeLightStateAsync(); break;
             case "changeLightsColor": await SelectColorAsync(); break;
             case "changeLightStateByName": await ChangeSpecificLightStateAsync(); break;
             default: await _voiceServiceConnection.RequestAppLaunchAsync(
                 CreateCortanaResponse("Launching HueLightController")); break;
         }
         // keep alive for 1 second to ensure all HTTP requests sent.
         await Task.Delay(1000);
         _deferral.Complete();
     }
 }
        /// <summary> 
        /// Background task entry point.
        /// </summary> 
        /// <param name="taskInstance"></param>
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            Accelerometer = Accelerometer.GetDefault();

            if (null != Accelerometer)
            {
                SampleCount = 0;

                // Select a report interval that is both suitable for the purposes of the app and supported by the sensor.
                uint minReportIntervalMsecs = Accelerometer.MinimumReportInterval;
                Accelerometer.ReportInterval = minReportIntervalMsecs > 16 ? minReportIntervalMsecs : 16;

                // Subscribe to accelerometer ReadingChanged events.
                Accelerometer.ReadingChanged += new TypedEventHandler<Accelerometer, AccelerometerReadingChangedEventArgs>(ReadingChanged);

                // Take a deferral that is released when the task is completed.
                Deferral = taskInstance.GetDeferral();

                // Get notified when the task is canceled.
                taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);

                // Store a setting so that the app knows that the task is running.
                ApplicationData.Current.LocalSettings.Values["IsBackgroundTaskActive"] = true;
            }
        }
        /// <summary>
        /// Performs the work of a background task. The system calls this method when the associated
        /// background task has been triggered.
        /// </summary>
        /// <param name="taskInstance">
        /// An interface to an instance of the background task. The system creates this instance when the
        /// task has been triggered to run.
        /// </param>
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            Debug.WriteLine("Background Audio Task " + taskInstance.Task.Name + " starting");

            this.systemMediaTransportControl = SystemMediaTransportControls.GetForCurrentView();
            this.systemMediaTransportControl.IsEnabled = true;
            this.systemMediaTransportControl.IsPauseEnabled = true;
            this.systemMediaTransportControl.IsPlayEnabled = true;
            this.systemMediaTransportControl.IsNextEnabled = true;
            this.systemMediaTransportControl.IsPreviousEnabled = true;

            // Wire up system media control events
            this.systemMediaTransportControl.ButtonPressed += this.OnSystemMediaTransportControlButtonPressed;
            this.systemMediaTransportControl.PropertyChanged += this.OnSystemMediaTransportControlPropertyChanged;

            // Wire up background task events
            taskInstance.Canceled += this.OnTaskCanceled;
            taskInstance.Task.Completed += this.OnTaskcompleted;

            // Initialize message channel 
            BackgroundMediaPlayer.MessageReceivedFromForeground += this.OnMessageReceivedFromForeground;

            // Notify foreground that we have started playing
            BackgroundMediaPlayer.SendMessageToForeground(new ValueSet() { { "BackgroundTaskStarted", "" } });
            this.backgroundTaskStarted.Set();
            this.backgroundTaskRunning = true;

            this.deferral = taskInstance.GetDeferral();
        }
Esempio n. 16
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            deferral = taskInstance.GetDeferral();
            ConnectToScreen(0x4a);

            car = new SerialCarHardwareInterface(null);
        }
Esempio n. 17
0
        //TemperatureSensors tempSensors;

        public void Run(IBackgroundTaskInstance taskInstance)
        {
            //if (!_started)
            //{
            //    tempSensors = new TemperatureSensors();
            //    tempSensors.InitSensors();
            //    _started = true;
            //}
            
            // Associate a cancellation handler with the background task. 
            taskInstance.Canceled += TaskInstance_Canceled;

            // Get the deferral object from the task instance
            serviceDeferral = taskInstance.GetDeferral();

            var appService = taskInstance.TriggerDetails as AppServiceTriggerDetails;
            if (appService != null && appService.Name == "App2AppComService")
            {
                appServiceConnection = appService.AppServiceConnection;
                appServiceConnection.RequestReceived += AppServiceConnection_RequestReceived; ;
            }

            // just run init, maybe don't need the above...
            Initialize();
        }
Esempio n. 18
0
        public Task RunAsync(IBackgroundTaskInstance taskInstance)
        {
            if (taskInstance == null) throw new ArgumentNullException(nameof(taskInstance));

            _deferral = taskInstance.GetDeferral();
            return RunAsync();
        }
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            System.Diagnostics.Debug.WriteLine("WE are @ Background");
            _deferral = taskInstance.GetDeferral();
            _taskInstance = taskInstance;
            _taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);

            GattCharacteristicNotificationTriggerDetails details = (GattCharacteristicNotificationTriggerDetails)taskInstance.TriggerDetails;

            //get the characteristics data and get heartbeat value out from it
            byte[] ReceivedData = new byte[details.Value.Length];
            DataReader.FromBuffer(details.Value).ReadBytes(ReceivedData);

            HeartbeatMeasurement tmpMeasurement = HeartbeatMeasurement.GetHeartbeatMeasurementFromData(ReceivedData);

            System.Diagnostics.Debug.WriteLine("Background heartbeast values: " + tmpMeasurement.HeartbeatValue);

            // send heartbeat values via progress callback
            _taskInstance.Progress = tmpMeasurement.HeartbeatValue;

            //update the value to the Tile
            LiveTile.UpdateSecondaryTile("" + tmpMeasurement.HeartbeatValue);
            
            //Check if we are within the limits, and alert by starting the app if we are not
            alertType alert = await checkHeartbeatLevels(tmpMeasurement.HeartbeatValue);

            _deferral.Complete();
        }
Esempio n. 20
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            // Ensure our background task remains running
            taskDeferral = taskInstance.GetDeferral();

            // Mutex will be used to ensure only one thread at a time is talking to the shield / isolated storage
            mutex = new Mutex(false, mutexId);

            // Initialize ConnectTheDots Settings
            localSettings.ServicebusNamespace = "YOURSERVICEBUS-ns";
            localSettings.EventHubName = "ehdevices";
            localSettings.KeyName = "D1";
            localSettings.Key = "YOUR_KEY";
            localSettings.DisplayName = "YOUR_DEVICE_NAME";
            localSettings.Organization = "YOUR_ORGANIZATION_OR_SELF";
            localSettings.Location = "YOUR_LOCATION";

            SaveSettings();

            // Initialize WeatherShield
            await shield.BeginAsync();

            // Create a timer-initiated ThreadPool task to read data from I2C
            i2cTimer = ThreadPoolTimer.CreatePeriodicTimer(PopulateWeatherData, TimeSpan.FromSeconds(i2cReadIntervalSeconds));

            // Start the server
            server = new HttpServer(port);
            var asyncAction = ThreadPool.RunAsync((w) => { server.StartServer(weatherData); });

            // Task cancellation handler, release our deferral there 
            taskInstance.Canceled += OnCanceled;

            // Create a timer-initiated ThreadPool task to renew SAS token regularly
            SASTokenRenewTimer = ThreadPoolTimer.CreatePeriodicTimer(RenewSASToken, TimeSpan.FromMinutes(15));
        }
Esempio n. 21
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            // Ensure our background task remains running
            taskDeferral = taskInstance.GetDeferral();

            // Mutex will be used to ensure only one thread at a time is talking to the shield / isolated storage
            mutex = new Mutex(false, mutexId);

            // Initialize WeatherShield
            await shield.BeginAsync();

            //Initialise the MCP3008 ADC Chip
            mcp3008.Initialize();

            // Create a timer-initiated ThreadPool task to read data from I2C
            i2cTimer = ThreadPoolTimer.CreatePeriodicTimer(PopulateWeatherData, TimeSpan.FromSeconds(i2cReadIntervalSeconds));

            //Create a timer-initiated ThreadPool task to read data from the interrupt handler counting the wind instrument activity
            windInterruptSample = ThreadPoolTimer.CreatePeriodicTimer(MeasureWindEventData, TimeSpan.FromSeconds(windInterruptSampleInterval));

            // Task cancellation handler, release our deferral there 
            taskInstance.Canceled += OnCanceled;

            //Create the interrupt handler listening to the wind speed pin (13).  Triggers the GpioPin.ValueChanged event on that pin 
            //connected to the anemometer.
            shield.WindSpeedPin.ValueChanged += WindSpeedPin_ValueChanged;

            //Create the interrupt handler listening to the rain guage pin (26).  Triggers the Gpio.ValueChanged event on that pin
            //connected to the rain guage. 
            shield.RainPin.ValueChanged += RainPin_ValueChanged;
    }
Esempio n. 22
0
        //
        // The Run method is the entry point of a background task.
        //
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            var details = taskInstance.TriggerDetails as ToastNotificationActionTriggerDetail;
            if (details != null)
            {
                string arguments = details.Argument;
                var userInput = details.UserInput;
            }
            Debug.WriteLine("Background " + taskInstance.Task.Name + " Starting...");
            //
            // Query BackgroundWorkCost
            // Guidance: If BackgroundWorkCost is high, then perform only the minimum amount
            // of work in the background task and return immediately.
            //
            var cost = BackgroundWorkCost.CurrentBackgroundWorkCost;
            var settings = ApplicationData.Current.LocalSettings;
            settings.Values["BackgroundWorkCost"] = cost.ToString();
            //
            // Associate a cancellation handler with the background task.
            //
            taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);

            //
            // Get the deferral object from the task instance, and take a reference to the taskInstance;
            //
            _deferral = taskInstance.GetDeferral();
            _taskInstance = taskInstance;
            _deferral.Complete();

            // _periodicTimer = ThreadPoolTimer.CreatePeriodicTimer(new TimerElapsedHandler(PeriodicTimerCallback), TimeSpan.FromSeconds(1));
        }
Esempio n. 23
0
 public void Run(IBackgroundTaskInstance taskInstance)
 {
     deferral = taskInstance.GetDeferral();
     InitGPIO();
     timer = ThreadPoolTimer.CreatePeriodicTimer(Timer_Tick, TimeSpan.FromMilliseconds(500));
     
 }
Esempio n. 24
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            deferral = taskInstance.GetDeferral();

            //Motor starts off
            currentPulseWidth = 0;

            //The stopwatch will be used to precisely time calls to pulse the motor.
            stopwatch = Stopwatch.StartNew();

            GpioController controller = GpioController.GetDefault();

            //Buttons are attached to pins 5 and 6 to control which direction the motor should run in
            //Interrupts (ValueChanged) events are used to notify this app when the buttons are pressed
            forwardButton = controller.OpenPin(5);
            forwardButton.DebounceTimeout = new TimeSpan(0, 0, 0, 0, 250);
            forwardButton.SetDriveMode(GpioPinDriveMode.Input);
            forwardButton.ValueChanged += _forwardButton_ValueChanged;

            backwardButton = controller.OpenPin(6);
            backwardButton.SetDriveMode(GpioPinDriveMode.Input);
            forwardButton.DebounceTimeout = new TimeSpan(0, 0, 0, 0, 250);
            backwardButton.ValueChanged += _backgwardButton_ValueChanged;


            servoPin = controller.OpenPin(13);
            servoPin.SetDriveMode(GpioPinDriveMode.Output);

            
           

            //You do not need to await this, as your goal is to have this run for the lifetime of the application
            Windows.System.Threading.ThreadPool.RunAsync(this.MotorThread, Windows.System.Threading.WorkItemPriority.High);
        }
Esempio n. 25
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            Adapter adapter = null;
            deferral = taskInstance.GetDeferral();

            try
            {
                adapter = new Adapter();
                dsbBridge = new DsbBridge(adapter);

                var initResult = dsbBridge.Initialize();
                if (initResult != 0)
                {
                    throw new Exception("DSB Bridge initialization failed!");
                }
            }
            catch (Exception ex)
            {
                if (dsbBridge != null)
                {
                    dsbBridge.Shutdown();
                }

                if (adapter != null)
                {
                    adapter.Shutdown();
                }

                throw;
            }
        }
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            InitializeAndSetMediaTransportControl();

            taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);
            taskInstance.Task.Completed += Taskcompleted;

            var value = ApplicationSettingsHelper.ReadResetSettingsValue(ConstantValues.AppState);

            if (value == null)
                _foregroundAppState = ForegroundAppStatus.Unknown;
            else
                _foregroundAppState = (ForegroundAppStatus)Enum.Parse(typeof(ForegroundAppStatus), value.ToString());

            BackgroundMediaPlayer.Current.CurrentStateChanged += Current_CurrentStateChanged;

            UpdateQueue();

            _queue.TrackChanged += playList_TrackChanged;

            BackgroundMediaPlayer.MessageReceivedFromForeground += BackgroundMediaPlayer_MessageReceivedFromForeground;

            if (_foregroundAppState != ForegroundAppStatus.Suspended)
            {
                ValueSet message = new ValueSet { { ConstantValues.BackgroundTaskStarted, "" } };
                BackgroundMediaPlayer.SendMessageToForeground(message);
            }

            _backgroundTaskStarted.Set();
            _backgroundtaskrunning = true;
            
            ApplicationSettingsHelper.SaveSettingsValue(ConstantValues.BackgroundTaskState, ConstantValues.BackgroundTaskRunning);
            _deferral = taskInstance.GetDeferral();
        }
Esempio n. 27
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            try
            {
                if (Hub.Instance.VoipTaskInstance != null)
                {
                    Debug.WriteLine("VoipTask already started.");
                    return;
                }

                _deferral = taskInstance.GetDeferral();
                Hub.Instance.VoipTaskInstance = this;
                Debug.WriteLine($"{DateTime.Now} VoipTask started.");
                taskInstance.Canceled += (s, e) => CloseVoipTask();
            }
            catch (Exception e)
            {
                if (Hub.Instance.IsAppInsightsEnabled)
                {
                    Hub.Instance.RTCStatsManager.TrackException(e);
                }
                if (_deferral != null)
                {
                    _deferral.Complete();
                }
                throw e;
            }
        }
Esempio n. 28
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            _settingsUtility = new SettingsUtility();

            _foregroundMessenger = new ForegroundMessenger();
            _smtcWrapper = new SmtcWrapper(BackgroundMediaPlayer.Current.SystemMediaTransportControls);
            _playerWrapper = new PlayerWrapper(_smtcWrapper, _foregroundMessenger, _settingsUtility);

            _settingsUtility.Write(ApplicationSettingsConstants.BackgroundTaskState,
                BackgroundTaskState.Running);

            // Send information to foreground that background task has been started if app is active
            if (_playerWrapper.ForegroundAppState != AppState.Suspended)
                MessageHelper.SendMessageToForeground(new BackgroundAudioTaskStartedMessage());

            // This must be retrieved prior to subscribing to events below which use it
            _deferral = taskInstance.GetDeferral();

            // Mark the background task as started to unblock SMTC Play operation (see related WaitOne on this signal)
            TaskStarted.Set();

            // Associate a cancellation and completed handlers with the background task.
            taskInstance.Task.Completed += TaskCompleted;
            // event may raise immediately before continung thread excecution so must be at the end
            taskInstance.Canceled += OnCanceled;
        }
Esempio n. 29
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            deferral = taskInstance.GetDeferral();

            Initialize();
            Start();
        }
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            deferral = taskInstance.GetDeferral();
            Services.IoC.Register();
            var container = Container.Instance;
            logger = container.Resolve<ILogger>();

            taskInstance.Task.Completed += onTaskCompleted;
            taskInstance.Canceled += onTaskCanceled;
            logger.LogMessage("BackgroundUpdater: Task initialized.", LoggingLevel.Information);

            var episodeListManager = container.Resolve<IEpisodeListManager>();
            await episodeListManager.Initialization;
            var oldEpisodeList = EpisodeList.Instance.ToList();
            await episodeListManager.LoadEpisodeListFromServerAsync();
            var diff = EpisodeList.Instance.Except(oldEpisodeList).ToList();
            if (diff.Any())
            {
                var downloadManager = container.Resolve<IDownloadManager>();
                await downloadManager.Initialization;
                foreach (var episode in diff)
                {
                    await downloadManager.DownloadEpisode(episode);
                }
            }

            deferral.Complete();
        }