示例#1
0
        private async void ClickMe_Click(object sender, RoutedEventArgs e)
        {
            //HelloMessage.Text = "Hello, Windows 10 IoT Core!";
            GpioController controller = GpioController.GetDefault();

            if (controller != null)
            {
                _pin1 = GpioController.GetDefault().OpenPin(piN, GpioSharingMode.Exclusive);
                _pin1.SetDriveMode(GpioPinDriveMode.Input);

                _dht1 = new Dht11(_pin1, GpioPinDriveMode.Input);
            }

            DhtReading reading = new DhtReading();

            reading = await _dht1.GetReadingAsync().AsTask();

            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();

            while (stopwatch.Elapsed < TimeSpan.FromSeconds(60))
            {
                if (reading.IsValid)
                {
                    var Temperature   = reading.Temperature;
                    var Humidity      = reading.Humidity;
                    var messageDialog = new MessageDialog(string.Format("Temperature : {0} - Humidity : {1}", Temperature, Humidity));
                    Task.Delay(5000).Wait();
                    await messageDialog.ShowAsync();
                }

                stopwatch.Stop();
            }
        }
示例#2
0
        private async void Timer_Tick(object sender, object e)
        {
            timer.Stop();
            try
            {
                dDhtReading = await dht22.GetReadingAsync().AsTask().ConfigureAwait(true);

                if (dDhtReading.IsValid)
                {
                    var temperature = Convert.ToSingle(dDhtReading.Temperature);
                    var humidity    = Convert.ToSingle(dDhtReading.Humidity);
                    lblTemperature.Text = string.Format("{0:0.0} °C", temperature);
                    lblHumidity.Text    = string.Format("{0:0.0} %", humidity);
                    //_SuccessCount++;
                }
                else
                {
                    lblLog.Text = "reading fail";
                    //_FailCount++;
                }
            }
            catch (Exception ex)
            {
                lblLog.Text = ex.ToString();
                //_FailCount++;
            }
            finally
            {
                timer.Start();
            }
        }
示例#3
0
        public static IDhtReading FromData(byte[] data)
        {
            IDhtReading returnValue = new DhtReading();

            // ***
            // *** Verify the checksum.
            // ***
            if (data.HasValidChecksum())
            {
                // ***
                // *** This is a valid reading, convert the temperature and humidity.
                // ***
                ((DhtReading)returnValue).Temperature = data.ToTemperature();
                ((DhtReading)returnValue).Humidity    = data.ToHumidty();
                ((DhtReading)returnValue).Result      = DhtReadingResult.Valid;
            }
            else
            {
                // ***
                // *** The checksum did not match.
                // ***
                ((DhtReading)returnValue).Temperature = 0F;
                ((DhtReading)returnValue).Humidity    = 0F;
                ((DhtReading)returnValue).Result      = DhtReadingResult.ChecksumError;
            }

            return(returnValue);
        }
示例#4
0
 /// <summary>
 ///
 /// </summary>
 private void GetReading()
 {
     try
     {
         DhtReading reading = new DhtReading();
         if (reading.IsValid)
         {
             var temperature = Convert.ToSingle(reading.Temperature);
             var humidity    = Convert.ToSingle(reading.Humidity);
             var lastUpdated = DateTimeOffset.Now;
             try
             {
                 SendDeviceToCloudMessagesAsync(humidity.ToString(CultureInfo.InvariantCulture),
                                                temperature.ToString(CultureInfo.InvariantCulture), lastUpdated, "");
             }
             catch (Exception)
             {
                 // some code to handle exception
             }
         }
     }
     catch (Exception)
     {
         // some code to handle exception
     }
 }
示例#5
0
 private void ShouldITurnOnAirCondition(DhtReading dhtData)
 {
     if ((dhtData.Temperature >= 24 || dhtData.Humidity >= 75) && !relayOn)
     {
         TurnOnRelay();
     }
 }
示例#6
0
        protected async Task <(double Temperature, double Humidity)> ReadTemperature(IDht device)
        {
            (double Temperature, double Humidity)returnValue = (0, 0);

            DhtReading reading = new DhtReading();

            reading = await device.GetReadingAsync().AsTask();

            if (reading.IsValid)
            {
                // ***
                // *** Get the values from the reading.
                // ***
                returnValue.Temperature = reading.Temperature;
                returnValue.Humidity    = reading.Humidity;
            }
            else
            {
                // ***
                // *** Show -1 so that it is evident there
                // *** is an error reading the device.
                // ***
                returnValue.Temperature = -1;
                returnValue.Humidity    = -1;
            }

            return(returnValue);
        }
示例#7
0
        private async void _timer_Tick(object sender, object e)
        {
            DhtReading reading = new DhtReading();
            int val = this.TotalAttempts;
            this.TotalAttempts++;

            reading = await _dht.GetReadingAsync().AsTask();

            _retryCount.Add(reading.RetryCount);
            this.OnPropertyChanged(nameof(AverageRetriesDisplay));
            this.OnPropertyChanged(nameof(TotalAttempts));
            this.OnPropertyChanged(nameof(PercentSuccess));

			if (reading.IsValid)
			{
				this.TotalSuccess++;
				this.Temperature = Convert.ToSingle(reading.Temperature);
				this.Humidity = Convert.ToSingle(reading.Humidity);
				this.LastUpdated = DateTimeOffset.Now;
				this.OnPropertyChanged(nameof(SuccessRate));
			}
			else
			{

			}

            this.OnPropertyChanged(nameof(LastUpdatedDisplay));
        }
示例#8
0
        private async void _timer_Tick(object sender, object e)
        {
            DhtReading reading = new DhtReading();
            int        val     = this.TotalAttempts;

            this.TotalAttempts++;

            reading = await _dht.GetReadingAsync().AsTask();

            _retryCount.Add(reading.RetryCount);
            this.OnPropertyChanged(nameof(AverageRetriesDisplay));
            this.OnPropertyChanged(nameof(TotalAttempts));
            this.OnPropertyChanged(nameof(PercentSuccess));

            if (reading.IsValid)
            {
                this.TotalSuccess++;
                this.Temperature = Convert.ToSingle(reading.Temperature);
                this.Humidity    = Convert.ToSingle(reading.Humidity);
                this.LastUpdated = DateTimeOffset.Now;
                this.OnPropertyChanged(nameof(SuccessRate));
            }
            else
            {
            }

            this.OnPropertyChanged(nameof(LastUpdatedDisplay));
        }
示例#9
0
        private async void UpdateTempValuesThread()
        {
            int times = 0;

            while (true)
            {
                for (int i = 0; i < Devices.temp_devices.Length; i++)
                {
                    DhtReading reading = await Devices.temp_devices[i].GetReadingAsync().AsTask();
                    if (reading.Temperature != 0 && reading.Humidity != 0)
                    {
                        Globals.dht11_values[i, 0] = reading.Temperature;
                        Globals.dht11_values[i, 1] = reading.Humidity;
                    }
                }

                await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
                                                                                                            () => { ShowTempDataOnUI(); });

                if (justOpened && times <= 3)
                {
                    times++;
                    if (times == 3)
                    {
                        justOpened = false;
                    }
                    Thread.Sleep(8000);
                }
                else
                {
                    Thread.Sleep(Globals.TempTimerInterval);
                }
            }
        }
示例#10
0
        private async void readSensor()

        {
            double temp = 0;

            double humidity = 0;



            DhtReading reading = await dht.GetReadingAsync().AsTask();

            if (reading.IsValid)

            {
                temp = reading.Temperature;

                humidity = reading.Humidity;



                Temperature = string.Format("{0:0.0}", temp);

                Humidity = string.Format("{0:0}", humidity);

                SensorRead?.Invoke(temp, humidity);
            }
        }
        private async Task ReadData()
        {
            reading = new DhtReading();

            try
            {
                reading = await _dht.GetReadingAsync();
            }
            catch (Exception e)
            {
            }
            if (reading.IsValid)
            {
                this.Temperature = Convert.ToSingle(reading.Temperature);
                this.Humidity    = Convert.ToSingle(reading.Humidity);
                this.Date        = DateTimeOffset.Now;

                F_Temperature.Text   = Temperature.ToString();
                this.F_Humidity.Text = Humidity.ToString();
                this.F_Date.Text     = Date.ToString(string.Format("dd.mm.yyyy, HH:MM:ss"));
            }
            else
            {
                throw new Exception("DHT Device did not answer");
            }
        }
示例#12
0
        public async Task ReadTemp()
        {
            await ReadTempHumidity();

            DhtReading reading = Reading;

            Debug.WriteLine("Temperature: " + reading.Temperature + " C, " + "Humidity: " + reading.Humidity + ", IsValid: " + reading.IsValid + ", TimedOut: " + reading.TimedOut + ", RetryCount: " + reading.RetryCount);
        }
示例#13
0
        private async void _dispatchTimer_Tick(object sender, object e)
        {
            try
            {
                DhtReading reading = new DhtReading();

                int val = this.TotalAttempts;

                this.TotalAttempts++;

                reading = await _dhtInterface.GetReadingAsync().AsTask();

                _retryCount.Add(reading.RetryCount);
                this.OnPropertyChanged(nameof(AverageRetriesDisplay));
                this.OnPropertyChanged(nameof(TotalAttempts));
                this.OnPropertyChanged(nameof(PercentSuccess));

                if (reading.IsValid) // if we are able to capture value, display those
                {
                    this.TotalSuccess++;
                    this.Temperature = Convert.ToSingle(reading.Temperature);
                    this.Humidity    = Convert.ToSingle(reading.Humidity);
                    this.LastUpdated = DateTimeOffset.Now;
                    this.OnPropertyChanged(nameof(SuccessRate));

                    var telemetryDataPoint = new
                    {
                        deviceId    = "iot1",
                        temperature = Temperature.ToString(),
                        humidity    = Humidity.ToString(),
                        date        = DateTime.Now.ToString("dd-MM-yyyy"),
                        hours       = DateTime.Now.Hour.ToString(),
                        minutes     = DateTime.Now.Minute.ToString(),
                        seconds     = DateTime.Now.Second.ToString()
                    };

                    var messageString = JsonConvert.SerializeObject(telemetryDataPoint);
                    var message       = new Message(Encoding.ASCII.GetBytes(messageString));

                    await deviceClient.SendEventAsync(message);


                    Debug.WriteLine(message);
                }
                else // log if the reading is not in valid state
                {
                    Debug.WriteLine(string.Format("IsValid: {0}, RetryCount: {1}, TimedOut: {2}, Humidity: {3}, Temperature: {4}", reading.IsValid, reading.RetryCount, reading.TimedOut, reading.Humidity, reading.Temperature));
                }

                this.OnPropertyChanged(nameof(LastUpdatedDisplay)); // show when the data was last updated
                this.OnPropertyChanged(nameof(DateTimeDisplay));
            }
            catch (Exception ex) // log any exception that occurs
            {
                Debug.WriteLine(ex.Message);
            }
        }
示例#14
0
        public static IDhtReading FromTimeout()
        {
            IDhtReading returnValue = new DhtReading();

            ((DhtReading)returnValue).Temperature = 0F;
            ((DhtReading)returnValue).Humidity    = 0F;
            ((DhtReading)returnValue).Result      = DhtReadingResult.Timeout;

            return(returnValue);
        }
示例#15
0
        public async void ReadSensor()
        {
            SensorReading = await Sensor.GetReadingAsync().AsTask();

            if (!SensorReading.IsValid)
            {
                Utils.LogLine("Błędny odczyt sensora.");
            }

            this.SendTemperatureSensorSocketUpdate();
        }
示例#16
0
        private async void _timer_Tick(object sender, object e)
        {
            reading = new DhtReading();
            reading = await _dht.GetReadingAsync().AsTask();

            if (reading.IsValid)
            {
                txtTemp.Text = (reading.Temperature).ToString() + " °C" + "       " + (ConvertTemp.ConvertCelsiusToFahrenheit(reading.Temperature).ToString() + " °F");
            }
            else
            {
            }
        }
        private async void _timer_Tick(object sender, object e)
        {
            DhtReading reading = new DhtReading();
            int        val     = this.TotalAttempts;

            this.TotalAttempts++;

            reading = await _dht11.GetReadingAsync().AsTask();

            _retryCount.Add(reading.RetryCount);
            this.OnPropertyChanged(nameof(AverageRetriesDisplay));
            this.OnPropertyChanged(nameof(TotalAttempts));
            this.OnPropertyChanged(nameof(PercentSuccess));

            if (reading.IsValid)
            {
                this.TotalSuccess++;
                this.Temperature = Convert.ToSingle(reading.Temperature);
                this.Humidity    = Convert.ToSingle(reading.Humidity);
                this.LastUpdated = DateTimeOffset.Now;

                // Set IoT data.
                _sensorData                     = new SensorData();
                _sensorData.DeviceId            = _deviceName;
                _sensorData.Temperature         = Convert.ToSingle(reading.Temperature);
                _sensorData.ExternalTemperature = 20;
                _sensorData.Humidity            = Convert.ToSingle(reading.Humidity);

                // Blink led.
                this.BlinkLed();

                // Send IoT data.
                if (_sendToCloud)
                {
                    try {
                        await AzureIoTHub.SendDeviceToCloudMessageAsync(JsonConvert.SerializeObject(_sensorData));

                        _gridOffline.Visibility = Visibility.Collapsed;
                    }
                    catch (Exception ex) {
                        Debug.WriteLine("Problem sending to IoT Hub: " + ex.Message.ToString());
                        _gridOffline.Visibility = Visibility.Visible;
                    }
                }

                // Update UI.
                this.OnPropertyChanged(nameof(SuccessRate));
            }

            this.OnPropertyChanged(nameof(LastUpdatedDisplay));
        }
示例#18
0
        private async void readSensor()
        {
            DhtReading reading = await dht.GetReadingAsync().AsTask();

            if (reading.IsValid)
            {
                // Send reading to IoT Hub
                string message = "{\"temperature\":" + reading.Temperature.ToString() + ", \"humidity\":" + reading.Humidity.ToString() + "}";

                Message eventMessage = new Message(Encoding.UTF8.GetBytes(message));

                DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(IOTHUBCONNECTIONSTRING);
                await deviceClient.SendEventAsync(eventMessage);
            }
        }
示例#19
0
        private async void _timer_Tick(object sender, object e)
        {

            reading = new DhtReading();
            reading = await _dht.GetReadingAsync().AsTask();

            if (reading.IsValid)
            {
                txtTemp.Text = (reading.Temperature).ToString() + " °C" + "       " + (ConvertTemp.ConvertCelsiusToFahrenheit(reading.Temperature).ToString() + " °F");
            }
            else
            {

            }
        }
        private async void startDHT11(int port)
        {
            int     realport = 5;
            GpioPin pin      = null;

            pin = GpioController.GetDefault().OpenPin(realport, GpioSharingMode.Exclusive);
            Dht11 _dht = new Dht11(pin, GpioPinDriveMode.Input);

            pins.Add(pin);

            DhtReading reading = new DhtReading();

            reading = await _dht.GetReadingAsync().AsTask();

            callURLAPI(1, reading.Temperature);
            callURLAPI(2, reading.Humidity);
        }
示例#21
0
        private async void _timer_Tick(object sender, object e)
        {
            DhtReading reading = new DhtReading();
            int        val     = this.TotalAttempts;

            this.TotalAttempts++;

            reading = await _dht1.GetReadingAsync(30).AsTask();

            _retryCount.Add(reading.RetryCount);
            this.OnPropertyChanged(nameof(AverageRetriesDisplay));
            this.OnPropertyChanged(nameof(TotalAttempts));
            this.OnPropertyChanged(nameof(PercentSuccess));

            if (reading.IsValid)
            {
                this.TotalSuccess++;
                this.Temperature = Convert.ToSingle(reading.Temperature);
                this.Humidity    = Convert.ToSingle(reading.Humidity);
                this.LastUpdated = DateTimeOffset.Now;
                this.OnPropertyChanged(nameof(SuccessRate));
                DataItem myItem = new DataItem(lastID++, sensorID, DateTime.Now, (float)reading.Temperature, (float)reading.Humidity);
                itemList.Add(myItem);
                try
                {
                    sendToIotHub(myItem);
                }
                catch (Exception ex) //DeviceNotFoundException ex)
                {
                    Debug.WriteLine(ex.Message);
                }
            }
            this.OnPropertyChanged(nameof(LastUpdatedDisplay));

            if (readSensor2)
            {
                reading = new DhtReading();
                reading = await _dht2.GetReadingAsync(30).AsTask();

                if (reading.IsValid)
                {
                    Humi2.Text = reading.Humidity.ToString("F2");
                    Temp2.Text = reading.Temperature.ToString("F2");
                }
            }
        }
        private async void timer_Tick(object sender, object e)
        {
            DhtReading reading = new DhtReading();

            reading = await sensor.GetReadingAsync().AsTask();

            if (reading.IsValid)
            {
                this.temperatura = Convert.ToSingle(reading.Temperature);
                this.umidade     = Convert.ToSingle(reading.Humidity);

                //Aqui é possível chamar uma API, passando os valores de temperatura e umidade, fazendo que sua API insira em seu banco de dados esses valores
                var url      = "SUA_URL_AQUI";
                var token    = "SEU_TOKEN_AQUI";
                var client   = new HttpClient();
                var response = client.GetAsync(new Uri($"http://{url}/api/UpdateInfo/{token}?temperatura={this.temperatura}&umidade={this.umidade}"));
            }
        }
示例#23
0
        private async void Timer_Tick(object sender)
        {
            try
            {
                DhtReading reading = new DhtReading();
                reading = await _dht11.GetReadingAsync(3).AsTask();

                if (reading.IsValid)
                {
                    Console.WriteLine(reading.Temperature);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
        private async void _timer_Tick(object sender, object e)
        {
            DhtReading reading = new DhtReading();
            int        val     = this.TotalAttempts;

            this.TotalAttempts++;

            reading = await _dht.GetReadingAsync().AsTask();

            _retryCount.Add(reading.RetryCount);
            this.OnPropertyChanged(nameof(AverageRetriesDisplay));
            this.OnPropertyChanged(nameof(TotalAttempts));
            this.OnPropertyChanged(nameof(PercentSuccess));

            if (reading.IsValid)
            {
                this.TotalSuccess++;
                this.Temperature = Convert.ToSingle(reading.Temperature);
                this.Humidity    = Convert.ToSingle(reading.Humidity);
                this.LastUpdated = DateTimeOffset.Now;
                this.OnPropertyChanged(nameof(SuccessRate));
                var temp     = this.TemperatureDisplay;
                var humidity = this.HumidityDisplay;

                if ((humidity == "30.0% RH") || (humidity == "31.0% RH") || (humidity == "32.0% RH") || (humidity == "33.0% RH") || (humidity == "34.0% RH") || (humidity == "35.0% RH") || (humidity == "36.0% RH") || (humidity == "37.0% RH") || (humidity == "38.0% RH") || (humidity == "39.0% RH") || (humidity == "40.0% RH") || (humidity == "41.0% RH") || (humidity == "42.0% RH") || (humidity == "43.0% RH") || (humidity == "44.0% RH") || (humidity == "45.0% RH") || (humidity == "46.0% RH") || (humidity == "47.0% RH") || (humidity == "48.0% RH") || (humidity == "49.0% RH") || (humidity == "50.0% RH") || (humidity == "51.0% RH") || (humidity == "52.0% RH") || (humidity == "53.0% RH") || (humidity == "54.0% RH") || (humidity == "55.0% RH"))
                {
                    if (value == GpioPinValue.Low)
                    {
                        value = GpioPinValue.High;
                        pin.Write(value);
                    }
                }
                else
                {
                    value = GpioPinValue.Low;
                    pin.Write(value);
                }

                SendToCloud(temp, humidity);
            }

            this.OnPropertyChanged(nameof(LastUpdatedDisplay));
        }
示例#25
0
        private async void _timer_Tick(object sender, object e)
        {
            DhtReading reading = new DhtReading();
            int        val     = this.TotalAttempts;

            this.TotalAttempts++;

            reading = await _dht.GetReadingAsync().AsTask();

            _retryCount.Add(reading.RetryCount);
            this.OnPropertyChanged(nameof(AverageRetriesDisplay));
            this.OnPropertyChanged(nameof(TotalAttempts));
            this.OnPropertyChanged(nameof(PercentSuccess));

            if (reading.IsValid)
            {
                this.TotalSuccess++;
                this.Temperature = Convert.ToSingle(reading.Temperature);
                this.Humidity    = Convert.ToSingle(reading.Humidity);

                //Send to cloud
                var telemetryDataPoint = new
                {
                    DeviceId       = 1,
                    temperature    = reading.Temperature,
                    unitOfTemp     = "C",
                    humidity       = reading.Humidity,
                    unitOfHumidity = "%",
                    TimeFlag       = Convert.ToString(DateTime.Now)
                };
                var messageString = JsonConvert.SerializeObject(telemetryDataPoint);
                var message       = new Message(System.Text.Encoding.ASCII.GetBytes(messageString));
                await deviceClient1.SendEventAsync(message);

                Debug.WriteLine(messageString);

                this.LastUpdated = DateTimeOffset.Now;
                this.OnPropertyChanged(nameof(SuccessRate));
            }

            this.OnPropertyChanged(nameof(LastUpdatedDisplay));
        }
示例#26
0
        private async Task SendDataToAzureAsync(DhtReading dhtData)
        {
            var cloudData = new
            {
                DeviceId    = Config.deviceId,
                Temperature = dhtData.Temperature,
                Humidity    = dhtData.Humidity,
                Time        = DateTime.Now,
                RetryCount  = dhtData.RetryCount
            };

            var messageString = JsonConvert.SerializeObject(cloudData);
            var message       = new Microsoft.Azure.Devices.Client.Message(Encoding.UTF8.GetBytes(messageString));

            var deviceClient = DeviceClient.CreateFromConnectionString(Config.deviceConnectionString);

            await deviceClient.SendEventAsync(message);

            Debug.WriteLine("{0} > Sending message: {1}", DateTime.Now, messageString);
        }
示例#27
0
        private async Task ReadData()
        {
            reading = new DhtReading();

            try
            {
                reading = await _dht.GetReadingAsync();
            }
            catch (Exception e)
            {
            }
            if (reading.IsValid)
            {
                var Temperature = Convert.ToSingle(reading.Temperature);
                var Humidity    = Convert.ToSingle(reading.Humidity);
            }
            else
            {
                throw new Exception("DHT Device did not answer");
            }
        }
        private async void _dispatchTimer_Tick(object sender, object e)
        {
            try
            {
                DhtReading reading = new DhtReading();

                int val = this.TotalAttempts;

                this.TotalAttempts++;

                reading = await _dhtInterface.GetReadingAsync().AsTask();

                _retryCount.Add(reading.RetryCount);
                this.OnPropertyChanged(nameof(AverageRetriesDisplay));
                this.OnPropertyChanged(nameof(TotalAttempts));
                this.OnPropertyChanged(nameof(PercentSuccess));

                if (reading.IsValid) // if we are able to capture value, display those
                {
                    this.TotalSuccess++;
                    this.Temperature = Convert.ToSingle(reading.Temperature);
                    this.Humidity = Convert.ToSingle(reading.Humidity);
                    this.LastUpdated = DateTimeOffset.Now;
                    this.OnPropertyChanged(nameof(SuccessRate));
                }
                else // log if the reading is not in valid state
                {
                    Debug.WriteLine(string.Format("IsValid: {0}, RetryCount: {1}, TimedOut: {2}, Humidity: {3}, Temperature: {4}", reading.IsValid, reading.RetryCount, reading.TimedOut, reading.Humidity, reading.Temperature));
                }

                this.OnPropertyChanged(nameof(LastUpdatedDisplay)); // show when the data was last updated
                this.OnPropertyChanged(nameof(DateTimeDisplay));
            }
            catch(Exception ex) // log any exception that occurs
            {
                Debug.WriteLine(ex.Message);
            }
        }
示例#29
0
        private async Task GetSensorData()
        {
            tiSensor.Stop();
            try
            {
                reading = await objDht.GetReadingAsync().AsTask();

                if (reading.IsValid)
                {
                    strLastSuccessTime = DateTime.UtcNow.ToString();
                    string strOperationText = "{0:0.0} °C, {1:0.0} %";
                    // 取得溫濕度的資料
                    var temperature = Convert.ToSingle(reading.Temperature);
                    var humidity    = Convert.ToSingle(reading.Humidity);
                    strOperationText = string.Format(strOperationText, temperature, humidity);
                    base.SetOperation(strOperationText, DateTime.UtcNow);

                    // 送至IoT Hub
                    await this.IoTHub.Send(reading.Temperature, reading.Humidity);
                }
                else
                {
                    base.SetError("偵測裝置無法讀取");
                    // 讀不到資訊,等待一秒後再讀一次
                    await Task.Delay(TimeSpan.FromSeconds(1));

                    await this.GetSensorData();
                }
            }
            catch (Exception ex)
            {
                base.SetError(ex.Message);
            }
            finally
            {
                tiSensor.Start();
            }
        }
        private async void _dispatchTimer_Tick(object sender, object e)
        {
            try
            {
                DhtReading reading = new DhtReading();

                int val = this.TotalAttempts;

                this.TotalAttempts++;

                reading = await _dhtInterface.GetReadingAsync().AsTask();

                _retryCount.Add(reading.RetryCount);
                this.OnPropertyChanged(nameof(AverageRetriesDisplay));
                this.OnPropertyChanged(nameof(TotalAttempts));
                this.OnPropertyChanged(nameof(PercentSuccess));

                if (reading.IsValid) // if we are able to capture value, display those
                {
                    this.TotalSuccess++;
                    this.Temperature = Convert.ToSingle(reading.Temperature);
                    this.Humidity    = Convert.ToSingle(reading.Humidity);
                    this.LastUpdated = DateTimeOffset.Now;
                    this.OnPropertyChanged(nameof(SuccessRate));
                }
                else // log if the reading is not in valid state
                {
                    Debug.WriteLine(string.Format("IsValid: {0}, RetryCount: {1}, TimedOut: {2}, Humidity: {3}, Temperature: {4}", reading.IsValid, reading.RetryCount, reading.TimedOut, reading.Humidity, reading.Temperature));
                }

                this.OnPropertyChanged(nameof(LastUpdatedDisplay)); // show when the data was last updated
                this.OnPropertyChanged(nameof(DateTimeDisplay));
            }
            catch (Exception ex) // log any exception that occurs
            {
                Debug.WriteLine(ex.Message);
            }
        }
示例#31
0
        private async Task ReadTempHumidity()
        {
            if (dhtlock == null)
            {
                InitDHT22();
            }
            Reading = new DhtReading();
            int val = this.TotalAttempts;

            this.TotalAttempts++;

            Reading = await _dht.GetReadingAsync().AsTask();

            _retryCount.Add(Reading.RetryCount);

            if (Reading.IsValid)
            {
                this.TotalSuccess++;
                this.Temperature = Convert.ToSingle(Reading.Temperature);
                this.Humidity    = Convert.ToSingle(Reading.Humidity);
                this.LastUpdated = DateTimeOffset.Now;
            }
        }
示例#32
0
        private async void _timer_Tick(object sender, object e)
        {
            float      temperature;
            DhtReading reading = new DhtReading();

            totalAttempts++;

            reading = await _dht.GetReadingAsync().AsTask();

            _retryCount.Add(reading.RetryCount);


            if (reading.IsValid)
            {
                totalSuccess++;
                temperature = Convert.ToSingle(reading.Temperature);


                var telemetryDataPoint = new
                {
                    messageId      = totalSuccess,
                    deviceId       = deviceName,
                    temperature    = temperature,
                    humidity       = Convert.ToSingle(reading.Humidity),
                    lastUpdated    = DateTimeOffset.Now,
                    successRate    = this.SuccessRate,
                    percentSuccess = this.PercentSuccess
                };

                var messageString = JsonConvert.SerializeObject(telemetryDataPoint);
                var message       = new Message(Encoding.ASCII.GetBytes(messageString));
                message.Properties.Add("temperatureAlert", (temperature > 24) ? "true" : "false");

                await deviceClient.SendEventAsync(message);
            }
        }
示例#33
0
        // USE DHT11 REFERENCE TO READING DATA

        private async void _timer_Tick(object sender, object e)
        {
            DhtReading reading = new DhtReading();

            reading = await _dht11.GetReadingAsync().AsTask();

            _retryCount.Add(reading.RetryCount);

            if (reading.IsValid)
            {

                this.Temperature = Convert.ToSingle(reading.Temperature);
                this.Humidity = Convert.ToSingle(reading.Humidity);
            }
        }
示例#34
0
        // takes an instant reading or returns the average accumulated value, and returns
        // the interpreted value adjusted by calibration settings.
        public async Task <Models.Measurement> GetTemperature()
        {
            Measurement result = _lastMeasurement;

            try
            {
                if (_pin == null || _dht11 == null)
                {
                    int pinNumber = TEMPERATUREDATAPIN; // default
                    if (CalibrationSettings.ContainsKey(TempGpioPinNumberSetting))
                    {
                        pinNumber = Int32.Parse(CalibrationSettings[TempGpioPinNumberSetting].ToString());
                    }
                    var c = GpioController.GetDefault();
                    if (c != null)
                    {
                        _pin = c.OpenPin(pinNumber, GpioSharingMode.Exclusive);
                        if (_pin != null)
                        {
                            _dht11 = new Dht11(_pin, GpioPinDriveMode.Input);
                        }
                    }
                }
                if (_dht11 == null)
                {
                    return(null);
                }

                DhtReading reading = await _dht11.GetReadingAsync().AsTask();

                for (int retries = 0; retries < 10; retries++)
                {
                    if (reading.TimedOut)
                    {
                        Debug.Write(".");
                    }
                    else if (!reading.IsValid)
                    {
                        Debug.Write("x");
                    }
                    else
                    {
                        break;
                    }
                }
                if (reading.IsValid)
                {
                    //Debug.WriteLine($"Temp reading = {reading.Temperature}");
                    Measurement.UnitsOfMeasure units = Measurement.UnitsOfMeasure.Fahrenheit;
                    if (CalibrationSettings.ContainsKey(PreferredTemperatureUnits))
                    {
                        units = (Measurement.UnitsOfMeasure)Enum.Parse(typeof(Measurement.UnitsOfMeasure), CalibrationSettings[PreferredTemperatureUnits].ToString());
                    }
                    Measurement adjust = new Measurement(0.0f, Measurement.UnitsOfMeasure.Fahrenheit);
                    if (CalibrationSettings.ContainsKey(AdjustTemperatureSetting))
                    {
                        adjust = CalibrationSettings[AdjustTemperatureSetting] as Measurement;
                    }

                    float temperature = (float)reading.Temperature;
                    temperature   = Convert(Measurement.UnitsOfMeasure.Celsius, units, temperature);
                    adjust.Amount = Convert(adjust.Units, units, adjust.Amount);
                    adjust.Units  = units;
                    temperature  += adjust.Amount; // now that we know they are in the same (preferred) units

                    result           = new Measurement(temperature, units);
                    _lastMeasurement = result;
                    OnTemperatureChanged(new MeasurementChangedEventArgs(result));
                }
                else
                {
                    KegLogger.KegLogException(new TemperatureException("Custom: Unable to Read temperature."), "GetTemperature", SeverityLevel.Warning);
                    Debug.WriteLine($"Unable to read temperature.");
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Error, " + ex.Message);
                KegLogger.KegLogException(ex, "GetTemperature", SeverityLevel.Critical);
            }

            return(result);
        }
示例#35
0
        private async void _timer_Tick(object sender, object e)
        {
            DhtReading reading = new DhtReading();

            reading = await _dht11.GetReadingAsync().AsTask();

            _retryCount.Add(reading.RetryCount);

            if (reading.IsValid)
            {

                this.Temperature = Convert.ToSingle(reading.Temperature);
                this.Humidity = Convert.ToSingle(reading.Humidity);
                this.LastUpdated = DateTimeOffset.Now;

            }

            this.OnPropertyChanged(nameof(LastUpdatedDisplay));
        }