コード例 #1
0
        private static AmbiantValues ReadAmbiantValues()
        {
            var ambiantValues = new AmbiantValues {
                Temperature = -273, Humidity = -1
            };

            for (int i = 1; i <= 100; i++)
            {
                ambiantValues.Attempts = i;

                using (Dht22 dht = new Dht22(DhtPin))
                {
                    var temperature = dht.Temperature;
                    var humidity    = dht.Humidity;

                    if (temperature.Kelvins != 0)
                    {
                        ambiantValues.Temperature = temperature.DegreesCelsius;
                        ambiantValues.Humidity    = humidity.Percent;

                        return(ambiantValues);
                    }
                }
            }

            return(ambiantValues);
        }
コード例 #2
0
ファイル: MainPage.xaml.cs プロジェクト: w9wen/App1
        private void InitGPIO()

        {
            gpioController = GpioController.GetDefault();

            if (gpioController == null)
            {
                GpioStatus.Text = "There is no GPIO controller on this device.";

                return;
            }

            GpioStatus.Text = "GPIO Great";

            gpioPinLED = gpioController.OpenPin(LED_PIN);
            gpioPinLED.SetDriveMode(GpioPinDriveMode.Output);
            gpioPinLED.Write(GpioPinValue.Low);

            timer          = new DispatcherTimer();
            timer.Interval = TimeSpan.FromMilliseconds(1500);
            timer.Tick    += Timer_Tick;

            gpioPinDHT = gpioController.OpenPin(DHT_PIN, GpioSharingMode.Exclusive);
            if (gpioPinDHT != null)
            {
                //DhtReading dhtReading = await gpioPinDHT.GetReadingAsync()
                dht22 = new Dht22(gpioPinDHT, GpioPinDriveMode.Input);
                timer.Start();
            }
        }
コード例 #3
0
        /// <summary>
        /// Read values from DHT22 sensor. It seems that the Dht22 support in Iot.Device.Bindings does not work very well,
        /// but this can be considered as example on how to easily add support for additional devices
        /// </summary>
        private IList <MeasurementData> GetDht22Measurements(SensorDevice sensorDevice)
        {
            var measurements = new List <MeasurementData>();

            var pinNumber = int.Parse(sensorDevice.Address);

            using (var dht22 = new Dht22(pinNumber, PinNumberingScheme.Logical))
            {
                if (dht22.IsLastReadSuccessful)
                {
                    measurements.Add(new MeasurementData()
                    {
                        SensorDeviceId = sensorDevice.Id, SensorId = "temperature", Value = dht22.Temperature.Celsius.ToString(_numberFormatInfo)
                    });
                    measurements.Add(new MeasurementData()
                    {
                        SensorDeviceId = sensorDevice.Id, SensorId = "humidity", Value = dht22.Temperature.Celsius.ToString(_numberFormatInfo)
                    });
                }
                else
                {
                    _logger.LogWarning($"{DateTime.Now}: Could not read data from {sensorDevice.Id}");
                }
            }

            return(measurements);
        }
コード例 #4
0
ファイル: TemperatureSensor.cs プロジェクト: jeremyhorgan/IoT
        public TemperatureSensor()
        {
#if USE_PI
            var dataPin = GpioController.GetDefault().OpenPin(4, GpioSharingMode.Exclusive);
            dataPin.SetDriveMode(GpioPinDriveMode.Input);

            _sensor = new Dht22(dataPin, GpioPinDriveMode.Input);
#endif
        }
コード例 #5
0
        public Task InitializeAsync()
        {
            var controller = GpioController.GetDefault();

            var dataPin    = controller.OpenPin(4, GpioSharingMode.Exclusive);
            var triggerPin = controller.OpenPin(11, GpioSharingMode.Exclusive);

            _sensor       = new Dht22(dataPin, GpioPinDriveMode.Input);
            IsInitialized = true;
            // return _sensor.Initialize();
            return(Task.CompletedTask);
        }
コード例 #6
0
        /// <summary>
        ///     Starts monitoring the temperature with the <see cref="Dht22" /> sensor.
        /// </summary>
        private async Task Measure()
        {
            using var dht = new Dht22(26);
            while (true)
            {
                // Try to read the temperature.
                var temp = dht.Temperature;
                if (!dht.IsLastReadSuccessful)
                {
                    continue;
                }

                // Try to read the humidity.
                var humidity = dht.Humidity.Percent;
                if (!dht.IsLastReadSuccessful)
                {
                    continue;
                }

                // In case something goes horribly wrong
                if (humidity > 100)
                {
                    break;
                }

                Console.WriteLine("New measurement:" +
                                  $"{temp.DegreesCelsius.ToString(CultureInfo.InvariantCulture)}c, " +
                                  $"{temp.DegreesFahrenheit.ToString(CultureInfo.InvariantCulture)}f, " +
                                  $"humidity {humidity.ToString(CultureInfo.InvariantCulture)}%");

                // Add the measurement to the database.
                try
                {
                    await _unitOfWork.Measurements.AddAsync(new Measurement
                    {
                        Celsius    = temp.DegreesCelsius,
                        Fahrenheit = temp.DegreesFahrenheit,
                        Kelvin     = temp.Kelvins,
                        Humidity   = humidity
                    }).ConfigureAwait(false);
                }
                catch (Exception e)
                {
                    Console.WriteLine($"Failed to add measurement to the DB, reason {e.Message}");
                    throw;
                }

                break;
            }
        }
コード例 #7
0
        static async Task Main(string[] args)
        {
            // load the config like connection strings.
            var    configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
            string url           = configuration["ConnectionStringSetting"];

            string hostName = System.Net.Dns.GetHostName();

            // GPIO Pin
            using (Dht22 dht = new Dht22(4))
            {
                while (true)
                {
                    //Temperature temperature = dht.Temperature;
                    double humidity = dht.Humidity;
                    double temp     = dht.Temperature.Celsius;

                    if (humidity > 0 && humidity < 100)
                    {
                        Metric metric = new Metric
                        {
                            HostName    = hostName,
                            TempCelsius = temp,
                            Humidity    = humidity
                        };
                        Console.WriteLine($"T: {metric.TempCelsius} H: {metric.Humidity}");

                        // Call the method to send data to the api as task. Task will run until completed.
                        try
                        {
                            await PostTemperature(metric, url);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.StackTrace);
                        }
                    }
                    else
                    {
                        Console.WriteLine($"Unable to read sensor (t: {dht.Temperature.Celsius} h: {dht.Humidity}) ");
                    }
                    Console.WriteLine("Sleeping for 10 seconds...");
                    Thread.Sleep(10000); // sleep for 10 seconds
                }
            }
        }
        private static async Task _runDht(WebSocket webSocket)
        {
            var cancellationToken = new CancellationTokenSource(TimeSpan.FromMinutes(3)).Token;

            using var dht = new Dht22(4);
            while (!cancellationToken.IsCancellationRequested)
            {
                // Try to read the temperature.
                var temp = dht.Temperature;
                if (!dht.IsLastReadSuccessful)
                {
                    continue;
                }

                // Try to read the humidity.
                var humidity = dht.Humidity;
                if (!dht.IsLastReadSuccessful)
                {
                    continue;
                }

                if (double.IsNaN(temp.DegreesCelsius) || double.IsNaN(humidity.Value))
                {
                    continue;
                }

                var res = $"Temperature: {temp.DegreesCelsius:0.0}°C, Humidity: {humidity.Value:0.0}%";
                Console.WriteLine(res);
                await webSocket.SendAsync(
                    buffer : new ArraySegment <byte>(
                        array: Encoding.UTF8.GetBytes(res),
                        offset: 0,
                        count: res.Length
                        ),
                    messageType : WebSocketMessageType.Text,
                    endOfMessage : true,
                    cancellationToken : CancellationToken.None
                    );

                await Task.Delay(2000, cancellationToken);
            }
        }
コード例 #9
0
ファイル: Program.cs プロジェクト: mapitman/pitempd
        public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup <Startup>();
            webBuilder.UseUrls("http://*:80");
        })
        .UseSystemd()
        .ConfigureServices((hostContext, services) =>
        {
            DhtBase sensor = null;
            if (!args.Contains("--fake"))
            {
                sensor = new Dht22(2);
            }

            services.AddSingleton(x => new TemperatureSensor(sensor));
            services.AddSingleton <TemperatureService>();
            services.AddHostedService <TemperatureServiceWorker>();
            services.AddHostedService <TemperatureWorker>();
        });
コード例 #10
0
        private async void InitGPIO()
        {
            pinSensor = null;

            // 初始化Sensor
            if (this.objGpio != null)
            {
                pinSensor = this.objGpio.OpenPin(this.SensorPinNo, GpioSharingMode.Exclusive);
            }

            // 如果有抓到Sensor的Pin腳,就開始收集資料
            if (pinSensor != null)
            {
                objDht = new Dht22(pinSensor, GpioPinDriveMode.Input);
                await GetSensorData();
            }
            else
            {
                base.SetError("GPIO/PIN 無法初始化");
            }
        }
コード例 #11
0
        static void GetTempDHTxx1Wire()
        {
            int delayMs = 2000;
            //1-Wire:
            int pin = 26;

            Console.WriteLine("Using DH22-1-Wire1");
            bool lastResult = true;

            using (Dht22 dht = new Dht22(pin))
            {
                if (dht == null)
                {
                    Console.WriteLine("Dht22 instantiation failed");
                }
                else
                {
                    while (true)
                    {
                        var  temp    = dht.Temperature.Celsius;
                        bool result1 = dht.IsLastReadSuccessful;
                        var  humid   = dht.Humidity;
                        bool result2 = dht.IsLastReadSuccessful;
                        if (!result1 || !result2)
                        {
                            Console.Write(".");
                            lastResult = false;
                        }
                        else
                        {
                            //Sanity Check
                            bool resultIsValid = true;
                            if (temp is double.NaN)
                            {
                                resultIsValid = false;
                            }
コード例 #12
0
        public static void Run()
        {
            var pinNumber = 4;

            Console.WriteLine($"Weather Test on GPIO {pinNumber}");
            var sensor   = new Dht22(pinNumber);
            var attempts = 0;

            while (true)
            {
                Pi.Wait(2500);
                if (sensor.Update())
                {
                    Console.WriteLine($"The current temperature is {sensor.Temperature.Fahrenheit} " +
                                      $"and the humidity is {sensor.Humidity}%");
                    Console.WriteLine($"Attempts since last update {attempts}");
                    attempts = 0;
                }
                else
                {
                    attempts++;
                }
            }
        }
コード例 #13
0
        public ISensorReading ReadSensor()
        {
            var result = new HumidityTemperatureReading
            {
                Humidity = 0
            };

            using (Dht22 dht = new Dht22(_gpioPin))
            {
                //sometimes the sensor returns NaN's
                while (result.Humidity == 0)
                {
                    result.Temperature = dht.Temperature;
                    result.Humidity    = dht.Humidity;

                    if (result.Humidity == 0)
                    {
                        System.Threading.Thread.Sleep(1000);
                    }
                }
            }

            return(result);
        }
コード例 #14
0
 public HumitureService(GpioService gpioService)
 {
     dht22 = new Dht22(pinNumber, PinNumberingScheme.Board, gpioService.GpioController, false);
 }
コード例 #15
0
        public static void Main(string[] args)
        {
            Console.WriteLine("Hello DHT!");
            Console.WriteLine("Select the DHT sensor you want to use:");
            Console.WriteLine(" 1. DHT10 on I2C");
            Console.WriteLine(" 2. DHT11 on GPIO");
            Console.WriteLine(" 3. DHT12 on GPIO");
            Console.WriteLine(" 4. DHT21 on GPIO");
            Console.WriteLine(" 5. DHT22 on GPIO");
            var choice = Console.ReadKey();

            Console.WriteLine();
            if (choice.KeyChar == '1')
            {
                Console.WriteLine("Press any key to stop the reading");
                // Init DHT10 through I2C
                I2cConnectionSettings settings = new I2cConnectionSettings(1, Dht10.DefaultI2cAddress);
                I2cDevice             device   = I2cDevice.Create(settings);

                using (Dht10 dht = new Dht10(device))
                {
                    Dht(dht);
                }

                return;
            }

            Console.WriteLine("Which pin do you want to use in the logical pin schema?");
            var pinChoise = Console.ReadLine();
            int pin;

            try
            {
                pin = Convert.ToInt32(pinChoise);
            }
            catch (Exception ex) when(ex is FormatException || ex is OverflowException)
            {
                Console.WriteLine("Can't convert pin number.");
                return;
            }

            Console.WriteLine("Press any key to stop the reading");

            switch (choice.KeyChar)
            {
            case '2':
                Console.WriteLine($"Reading temperature and humidity on DHT11, pin {pin}");
                using (var dht11 = new Dht11(pin))
                {
                    Dht(dht11);
                }

                break;

            case '3':
                Console.WriteLine($"Reading temperature and humidity on DHT12, pin {pin}");
                using (var dht12 = new Dht12(pin))
                {
                    Dht(dht12);
                }

                break;

            case '4':
                Console.WriteLine($"Reading temperature and humidity on DHT21, pin {pin}");
                using (var dht21 = new Dht21(pin))
                {
                    Dht(dht21);
                }

                break;

            case '5':
                Console.WriteLine($"Reading temperature and humidity on DHT22, pin {pin}");
                using (var dht22 = new Dht22(pin))
                {
                    Dht(dht22);
                }

                break;

            default:
                Console.WriteLine("Please select one of the option.");
                break;
            }
        }
コード例 #16
0
        private async void MainPollDHT(GpioPin gpioPin, string Sensor)
        {
            Dht22      dht22   = new Dht22(gpioPin, GpioPinDriveMode.Input);
            DhtReading reading = await dht22.GetReadingAsync().AsTask();

            Debug.WriteLine(string.Format("{0} DHT Valid {1}", Sensor, reading.IsValid));

            if (reading.IsValid)
            {
                Debug.WriteLine(string.Format("{0} DHT Reading:", Sensor));
                Debug.WriteLine(reading.Temperature);
                Debug.WriteLine(reading.Humidity);
                if (Sensor == "Intake")
                {
                    intakeDHTData = (new DHTData()
                    {
                        Temp = reading.Temperature,
                        Hum = reading.Humidity
                    });
                }
                else if (Sensor == "Outtake")
                {
                    outtakeDHTData = (new DHTData()
                    {
                        Temp = reading.Temperature,
                        Hum = reading.Humidity
                    });
                }
                else if (Sensor == "Main")
                {
                    mainDHTData = (new DHTData()
                    {
                        Temp = reading.Temperature,
                        Hum = reading.Humidity
                    });
                }

                System.Threading.Thread.Sleep(1000);
                string cmdString = "INSERT INTO [dbo].[sensorReadings] ([timestamp],[sensor],[temp], [hum], [retryCount]) ";
                cmdString += "VALUES('" + DateTime.Now + "','" + Sensor + "', '" + reading.Temperature + "', '" + reading.Humidity + "', '" + reading.RetryCount + "');";
                cmd        = new SqlCommand(cmdString, myConnection);
                try
                {
                    cmd.ExecuteNonQuery();
                }
                catch (SqlException e)
                {
                    Debug.WriteLine(string.Format("Failed SQL- {0}", e.Message.ToString()));
                }
                catch (NullReferenceException e)
                {
                    Debug.WriteLine(string.Format("Failed Bullshit- {0}", e.Message.ToString()));
                }
                catch (InvalidOperationException e)
                {
                    Debug.WriteLine(string.Format("Failed Bullshit- {0}", e.Message.ToString()));
                }
            }
            else
            {
                //Error something here
            }
        }