//private void LedTest()
        //{
        //    var led = new Led(22);
        //    led.On();
        //    led.Off();
        //}

        private void UCSensor()
        {
            this.InitGpio();
            _animation = new BlinkAnimation(_led1, _led2);
            _animation.Start();
            _timer = ThreadPoolTimer.CreatePeriodicTimer(Timer_Tick, TimeSpan.FromMilliseconds(500));
        }
        //
        // Simulate the background task activity.
        //
        private void PeriodicTimerCallback(ThreadPoolTimer timer)
        {
            if ((_cancelRequested == false) && (_progress < 100))
            {
                _progress += 10;
                _taskInstance.Progress = _progress;
            }
            else
            {
                _periodicTimer.Cancel();

                var key = _taskInstance.Task.Name;

                //
                // Record that this background task ran.
                //
                String taskStatus = (_progress < 100) ? "Canceled with reason: " + _cancelReason.ToString() : "Completed";
                BackgroundTaskSample.TaskStatuses[key] = taskStatus;
                Debug.WriteLine("Background " + _taskInstance.Task.Name + taskStatus);

                //
                // Indicate that the background task has completed.
                //
                _deferral.Complete();
            }
        }
Esempio n. 3
0
        private void button_Click(object sender, RoutedEventArgs e)
        {
            Debug.WriteLine("StartButton thread id: " + Environment.CurrentManagedThreadId);

            TimeSpan period = TimeSpan.FromSeconds(1);
            PeriodicTimer = ThreadPoolTimer.CreatePeriodicTimer(ElapsedHander, period, DestroyedHandler);
        }
Esempio n. 4
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. 5
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));
 }
        private async void Page_Loaded(object sender, RoutedEventArgs e)
        {
            ftManager = new FTManager();
            timer = ThreadPoolTimer.CreatePeriodicTimer(Timer_Tick, TimeSpan.FromMilliseconds(500));

            await seClient.Connect();
        }
        private void Timer_Tick(ThreadPoolTimer timer)
        {
            try
            {
                var devicesList = ftManager.GetDeviceList();
                Debug.WriteLine(devicesList.Count);

                if (devicesList.Count > 0)
                {
                    timer.Cancel();

                    var infoNode = devicesList[0];
                    IFTDevice ftDevice = ftManager.OpenByDeviceID(infoNode.DeviceId);

#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                    ftDevice.SetBaudRateAsync(9600);
                    ftDevice.SetDataCharacteristicsAsync(WORD_LENGTH.BITS_8, STOP_BITS.BITS_1, PARITY.NONE);
                    ftDevice.SetFlowControlAsync(FLOW_CONTROL.NONE, 0x00, 0x00);
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed

                    device = new XBeeDevice(ftDevice);
                    ListenForData();
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Esempio n. 8
0
        private async void Timer_Tick(ThreadPoolTimer timer)
        {
            try
            {
                //perform inventory scan and read available RFID tags
                var tagInventory = await _reader.PerformInventoryScan();
                if(tagInventory.Count() > 0)
                {
                    //assemble readings in the expected structure
                    List<TrackerReadingModel> readings = new List<TrackerReadingModel>();
                    foreach(var tag in tagInventory)
                    {
                        TrackerReadingModel reading = new TrackerReadingModel();
                        reading.IpAddress = _ipAddress;
                        reading.TagId = BitConverter.ToString(tag);
                        reading.Reading = DateTime.Now;
                        readings.Add(reading);
                    }

                    //send reading data to the cloud service
                    using (var client = new HttpClient())
                    {
                        client.BaseAddress = new Uri("http://YOURBASEURL.COM/");
                        client.DefaultRequestHeaders.Accept.Clear();
                        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                        var response = await client.PostAsJsonAsync("api/reading/add-multi-readings", readings);
                    }
                }
            }
            catch (Exception ex)
            {
                //TODO: Logging of exception
            }
        }
Esempio n. 9
0
        void LogTemperatures(ThreadPoolTimer timer)
        {
            try
            {
                using (var oneWireDeviceHandler = new OneWireDeviceHandler())
                {
                    foreach (var device in oneWireDeviceHandler.GetDevices<DS18S20>())
                    {
                        var result = device.GetTemperature();
                        var extendedResult = device.GetExtendedTemperature();

                        // Insert code to log result in some way
                    }

                    foreach (var device in oneWireDeviceHandler.OneWireDevices.GetDevices<DS18B20>())
                    {
                        var result = device.GetTemperature();

                        // Insert code to log result in some way
                    }
                }
            }
            catch (Exception e)
            {
                // Insert code to log all exceptions!
            }
        }
Esempio n. 10
0
        public Controller(Func<string, int> callback)
        {
            _callback = callback;
            _timer = ThreadPoolTimer.CreatePeriodicTimer(Timer_Tick, TimeSpan.FromMilliseconds(5000));

            _gpio_controller = GpioController.GetDefault();

            // Create the Area(s)
            
            _areas = new List<Area>() { new Area( "Area 1",
                                                  new List<Zone>() { new Zone("Zone 1", _gpio_controller.OpenPin(ZONE_1)) },
                                                  new Flow("Flow 1", _gpio_controller.OpenPin(FLOW_1)),
                                                  new OverCurrent("OC 1", _gpio_controller.OpenPin(OC_1)),
                                                  callback )};
            
            /*
            _areas = new List<Area>() { new Area( "Area 1",
                                                  new List<Zone>() { new Zone("Zone 1", _gpio_controller.OpenPin(ZONE_1)),
                                                                     new Zone("Zone 2", _gpio_controller.OpenPin(ZONE_2)),
                                                                     new Zone("Zone 3", _gpio_controller.OpenPin(ZONE_3))
                                                                   },
                                                  new Flow("Flow 1", _gpio_controller.OpenPin(FLOW_1)),
                                                  new OverCurrent("OC 1", _gpio_controller.OpenPin(OC_1)),
                                                  callback ),
                                        new Area( "Area 2",
                                                  new List<Zone>() { new Zone("Zone 4", _gpio_controller.OpenPin(ZONE_4)),
                                                                     new Zone("Zone 5", _gpio_controller.OpenPin(ZONE_5))
                                                                   },
                                                  new Flow("Flow 2", _gpio_controller.OpenPin(FLOW_1)),
                                                  new OverCurrent("OC 2", _gpio_controller.OpenPin(OC_1)),
                                                  callback )
                                     };
            */
        }
Esempio n. 11
0
 private async void Timer_Tick(ThreadPoolTimer timer)
 {
     _timer.Cancel();
     SwitchLed(true);
     try
     {
         //var tempHumid = DeviceFactory.Build.TemperatureAndHumiditySensor(Pin.DigitalPin4, GrovePi.Sensors.TemperatureAndHumiditySensorModel.DHT11).TemperatureAndHumidity();
         //Debug.WriteLine(string.Format("Temperature={0} Humidity={1}", tempHumid.Temperature, tempHumid.Humidity));
         Int16 temp = 20; // Convert.ToInt16(tempHumid.Temperature);
         byte hum = 45; // Convert.ToByte(tempHumid.Humidity);
         using (var stream = new MemoryStream())
         {
             using (var writer = new BinaryWriter(stream))
             {
                 writer.Write(temp);
                 writer.Write(hum);
                 writer.Flush();
             }
             await _sigfox.SendAsync(stream.ToArray());
         }
     }
     finally
     {
         SwitchLed(false);
     }
 }
        private void PeriodicTimerCallback(ThreadPoolTimer timer)
        {
            if (ValueChangeCompleted == null)
            {
                return;
            }

            if (_simulatorGoingUp)
            {
                _startSimulatorValue = (ushort)(_startSimulatorValue + _stepSimulatorValue);
                if (_startSimulatorValue > _maxSimulatorValue)
                {
                    _startSimulatorValue = _maxSimulatorValue;
                    _simulatorGoingUp = false;
                }
            }
            else
            {
                _startSimulatorValue = (ushort)(_startSimulatorValue - _stepSimulatorValue);
                if (_startSimulatorValue < _minSimulatorValue)
                {
                    _startSimulatorValue = _minSimulatorValue;
                    _simulatorGoingUp = true;
                }
            }

            ValueChangeCompleted(HeartbeatMeasurement.GetHeartbeatMeasurementFromData(_startSimulatorValue, DateTimeOffset.Now));
        }
 public BlinkyExample(RemoteDevice arduino, int millisecodInterval)
 {
     Arduino = arduino;
     Interval = millisecodInterval;
     timer = ThreadPoolTimer.CreatePeriodicTimer(OnTimerElapsed,
                                 TimeSpan.FromMilliseconds(millisecodInterval));
 }
Esempio n. 14
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();

       


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

            timer = ThreadPoolTimer.CreatePeriodicTimer(this.Tick, TimeSpan.FromSeconds(2));
           

            //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. 15
0
        private void PopulateWeatherData(ThreadPoolTimer timer)
        {
            bool hasMutex = false;

            try
            {
                hasMutex = mutex.WaitOne(1000);
                if (hasMutex)
                {
                    weatherData.TimeStamp = DateTime.Now.ToLocalTime().ToString();

                    shield.BlueLEDPin.Write(Windows.Devices.Gpio.GpioPinValue.High);

                    weatherData.Altitude = shield.Altitude;
                    weatherData.BarometricPressure = shield.Pressure;
                    weatherData.CelsiusTemperature = shield.Temperature;
                    weatherData.FahrenheitTemperature = (weatherData.CelsiusTemperature * 9 / 5) + 32;
                    weatherData.Humidity = shield.Humidity;

                    shield.BlueLEDPin.Write(Windows.Devices.Gpio.GpioPinValue.Low);

                    // Push the WeatherData local/cloud storage (viewable at http://iotbuildlab.azurewebsites.net/)
                    WriteDataToIsolatedStorage();
                    SendDataToConnectTheDots();
                }
            }
            finally
            {
                if (hasMutex)
                {
                    mutex.ReleaseMutex();
                }
            }
        }
Esempio n. 16
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. 17
0
        //
        // Simulate the background task activity.
        //
        private void PeriodicTimerCallback(ThreadPoolTimer timer)
        {
            if ((_cancelRequested == false) && (_progress < 100))
            {
                _progress += 10;
                _taskInstance.Progress = _progress;
            }
            else
            {
                _periodicTimer.Cancel();

                var settings = ApplicationData.Current.LocalSettings;
                var key = _taskInstance.Task.Name;

                //
                // Write to LocalSettings to indicate that this background task ran.
                //
                settings.Values[key] = (_progress < 100) ? "Canceled with reason: " + _cancelReason.ToString() : "Completed";
                Debug.WriteLine("Background " + _taskInstance.Task.Name + settings.Values[key]);

                //
                // Indicate that the background task has completed.
                //
                _deferral.Complete();
            }
        }
Esempio n. 18
0
        public override async void Start()
        {
            if (_Started)
                return;
            _SequenceNumber = 1;

            try
            {
                // Connect to the Drone
                udpClient = new DatagramSocket();
                await udpClient.BindServiceNameAsync(_ServiceName);
                await udpClient.ConnectAsync(new HostName(DroneClient.Host), _ServiceName);
                udpWriter = new DataWriter(udpClient.OutputStream);

                udpWriter.WriteByte(1);
                await udpWriter.StoreAsync();

                _Timer = ThreadPoolTimer.CreatePeriodicTimer(new TimerElapsedHandler(timerElapsedHandler), TimeSpan.FromMilliseconds(25));
                _Started = true;
            }
            catch (Exception)
            {
                Stop();
            }
        }
        public async void Run(IBackgroundTaskInstance taskInstance) {
            await LogToFile("Run()");
            try {
                // Ensure our background task remains running
                taskDeferral = taskInstance.GetDeferral();

                // Initiate the SPI
                InitSPI();

                // test nå..
                //ReadTemperature(null);

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

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

                // 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;
            }
            await LogToFile("Run() done");
        }
        //
        // 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. 21
0
        private void Timer_Tick(ThreadPoolTimer timer)
        {
            var temperature = TemperatureSensorConfig.GetSensorMeasurement();
            var windspeed = WindspeedSensorConfig.GetSensorMeasurement();
            var barometricPressure = BarometricPressureSensorConfig.GetSensorMeasurement();

            var connectionParams = new ConnectionParameters(ConnectionConfig.ServiceBusNamespace,
                ConnectionConfig.EventHubName,
                ConnectionConfig.PolicyName,
                ConnectionConfig.PolicyKey,
                ConnectionConfig.PublisherName,
                ConnectionConfig.TokenTimeToLive);

            var amqpSender = new AmqpSender(connectionParams);

            Debug.WriteLine("Sending temperature to event hub via AMQP");
            var temperatureResult = amqpSender.Send(temperature);
            Debug.WriteLine(string.Format("Temperature sent via AMQP ({0}).", temperatureResult.ToString()));

            Debug.WriteLine("Sending wind speed to event hub via AMQP ");
            var windspeedResult = amqpSender.Send(windspeed);
            Debug.WriteLine(string.Format("Wind speed sent via AMQP ({0}).", windspeedResult.ToString()));

            Debug.WriteLine("Sending barometric pressure to event hub via AMQP ");
            var barometricPressureResult = amqpSender.Send(barometricPressure);
            Debug.WriteLine(string.Format("Barometric pressure sent via AMQP ({0}).", barometricPressureResult.ToString()));
        }
Esempio n. 22
0
 public override void Start()
 {
     base.Start();
     if (_Timer != null)
         return;
     _Timer = ThreadPoolTimer.CreatePeriodicTimer(new TimerElapsedHandler(timerElapsedHandler), TimeSpan.FromMilliseconds(100));
 }
        public void Connect(HTransportOptions options)
        {
            this.connStatus = ConnectionStatus.CONNECTING;
            this.options = options;

            //TODO init the connection timeout value!!
            connTimeout = new TimeSpan(0, 0, 0, 0, options.Timeout);

            string endpointHost = options.EndpointHost;
            int endpointPort = options.EndpointPort;
            string endpointPath = options.EndpointPath;

            string endpointAdress = ToEndpointAdress(endpointHost, endpointPort, endpointPath);

            connTimeoutTimer = ThreadPoolTimer.CreateTimer(timeout_Elapsed, connTimeout);

            socketIO = new Client(endpointAdress);

            socketIO.Message += socketIO_Message;
            socketIO.SocketConnectionClosed += socketIO_SocketConnectionClosed;
            socketIO.Error += socketIO_Error;
            socketIO.On("connect", (message) =>
                {
                    if (this.options.AuthCb != null)
                        this.options.AuthCb(options.Login, Login);
                    else
                        Login(options.Login, options.Password);
                });
            socketIO.ConnectAsync();
        }
    public void StartLocationTracker()
    {
     if( CanRunAsTask() )
      {
        BackgroundTaskBuilder geolocTaskBuilder = new BackgroundTaskBuilder();

        geolocTaskBuilder.Name = SampleBackgroundTaskName;
        geolocTaskBuilder.TaskEntryPoint = SampleBackgroundTaskEntryPoint;

        // Create a new timer triggering at a 15 minute interval
        var trigger = new TimeTrigger( UpdateInterval, true );

        // Associate the timer trigger with the background task builder
        geolocTaskBuilder.SetTrigger( trigger );

        // Register the background task
        _geolocTask = geolocTaskBuilder.Register();

        // Associate an event handler with the new background task
        _geolocTask.Completed += new BackgroundTaskCompletedEventHandler( OnCompleted );
      }
      else
      {
         task = new LocationBackgroundTask();
        timer = ThreadPoolTimer.CreatePeriodicTimer( TimerElapsed, new TimeSpan( TimeSpan.TicksPerMillisecond * 30000 ) );
     }
    }
Esempio n. 25
0
 public void Run(IBackgroundTaskInstance taskInstance)
 {
     deferral = taskInstance.GetDeferral();
     InitGPIO();
     timer = ThreadPoolTimer.CreatePeriodicTimer(Timer_Tick, TimeSpan.FromMilliseconds(500));
     
 }
Esempio n. 26
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. 27
0
 private async void UpdateTimer(ThreadPoolTimer timer)
 {
     await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
     {
         ShowIconLocation();   
     });
 }
Esempio n. 28
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));
        }
 private void TimerElapsed( ThreadPoolTimer timer )
 {
  var result = Windows.System.Threading.ThreadPool.RunAsync(
     (workItem) => {
       task.FetchPosition();
       LocationChanged();
     });
 }
Esempio n. 30
0
 public void Dispose()
 {
     if (threadPoolTimer != null)
     {
         threadPoolTimer.Cancel();
         threadPoolTimer = null;
     }
 }