Ejemplo n.º 1
0
        private async void DeviceToCloudMessage()
        {
            await _sensor.Initialize();

            float temperature = 0.00f;
            float humidity    = 0.00f;

            while (true)
            {
                temperature = await _sensor.ReadTemperature();

                humidity = await _sensor.ReadHumidity();

                var sensorData = new
                {
                    date = String.Format("{0}, {1}, {2}",
                                         DateTime.Now.ToLocalTime().TimeOfDay.Hours,
                                         DateTime.Now.ToLocalTime().TimeOfDay.Minutes,
                                         DateTime.Now.ToLocalTime().TimeOfDay.Seconds),
                    temperature = Math.Round(temperature, 2),
                    humidity    = Math.Round(humidity, 2)
                };
                var messageString = JsonConvert.SerializeObject(sensorData);
                var message       = new Message(byteArray: Encoding.ASCII.GetBytes(messageString));
                await deviceClient.SendEventAsync(message);

                Debug.WriteLine("{0} > Sending message: {1}", DateTime.Now, messageString);
                Task.Delay(10000).Wait(); // 11hours running not to exceed the limit of 8000 messages
            }
        }
Ejemplo n.º 2
0
        private async void DeviceToCloudMessage()
        {
            await _sensor.Initialize();

            float temperature = 0.00f;
            float humidity    = 0.00f;
            int   mId         = 0;

            while (true)
            {
                temperature = await _sensor.ReadTemperature();

                humidity = await _sensor.ReadHumidity();

                var sensorData = new
                {
                    messageId   = mId,
                    deviceId    = "Real Raspberry Device",
                    temperature = Math.Round(temperature, 5),
                    humidity    = Math.Round(humidity, 5)
                };
                var messageString = JsonConvert.SerializeObject(sensorData);
                var message       = new Message(Encoding.ASCII.GetBytes(messageString));
                await deviceClient.SendEventAsync(message);

                Debug.WriteLine("{0} > Sending message: {1}", DateTime.Now, messageString);
                mId++;
                Task.Delay(5000).Wait();
            }
        }
        private async void MeasureTimerTick(object sender, object e)
        {
            // read Temperature
            double temperature = await bme280Sensor.ReadTemperature();

            double humidity = await bme280Sensor.ReadHumidity();

            double pressure = await bme280Sensor.ReadPressure();

            float altitude = await bme280Sensor.ReadAltitude(seaLevelPressure);

            // convert to Fahrenheit
            //double fahrenheitTemperature = temperature * 1.8 + 32.0; // hhe

            // read Proximity
            //int proximity = vncl4010Sensor.ReadProximity(); //hhe

            //TemperatureStatus.Text = "The temperature is currently " + fahrenheitTemperature.ToString("n1") + "°F"; //hhe
            Location.Text   = webApiClient.device.Location;
            DeviceName.Text = webApiClient.device.Name;
            X.Text          = webApiClient.device.X;
            Y.Text          = webApiClient.device.Y;
            Z.Text          = webApiClient.device.Z;

            TemperatureStatus.Text = "The temperature is currently " + temperature.ToString("n1") + "°C";
            HumidityStatus.Text    = "The humidity is currently " + humidity.ToString("n1") + "%";
            PressureStatus.Text    = "The pressure is currently " + pressure.ToString("n1") + "";
            Altitude.Text          = "The altitude is currently " + altitude.ToString("n1") + " meters";

            await webApiClient.PutDevice(X.Text, Y.Text, Z.Text, temperature, humidity, pressure);
        }
Ejemplo n.º 4
0
        private async void DeviceToCloudMessage()
        {
            await _sensor.Initialize();

            float temperature = 0.00f;
            float humidity    = 0.00f;

            while (true)
            {
                temperature = await _sensor.ReadTemperature();

                humidity = await _sensor.ReadHumidity();

                var telemetryDataPoint = new
                {
                    date = String.Format("{0}, {1}, {2}",
                                         DateTime.Now.ToLocalTime().TimeOfDay.Hours,
                                         DateTime.Now.ToLocalTime().TimeOfDay.Minutes,
                                         DateTime.Now.ToLocalTime().TimeOfDay.Seconds),
                    temp  = Math.Round(temperature, 2),
                    humid = Math.Round(humidity, 2)
                };
                var messageString = JsonConvert.SerializeObject(telemetryDataPoint);
                var message       = new Message(Encoding.ASCII.GetBytes(messageString));

                await deviceClient.SendEventAsync(message);

                Debug.WriteLine("{0} > Sending message: {1}", DateTime.Now, messageString);

                Task.Delay(5000).Wait();
            }
        }
Ejemplo n.º 5
0
        private async void TakeReadingAsync(object sender, object e)
        {
            // Create variables to store the sensor data: temperature, pressure, humidity and altitude.
            var temperatureReadings = new List <float>();
            var pressureReadings    = new List <float>();
            var altitudeReadings    = new List <float>();
            var humidityReadings    = new List <float>();

            // Read 10 samples of the data
            for (int i = 0; i < 10; i++)
            {
                temperatureReadings.Add(await _BME280.ReadTemperature());
                pressureReadings.Add(await _BME280.ReadPressure());
                altitudeReadings.Add(await _BME280.ReadAltitude());
                humidityReadings.Add(await _BME280.ReadHumidity());
            }

            // Create a WeatherData object which will hold the
            // average of the 10 samples for each attribute.
            WeatherData weatherReading = new WeatherData
            {
                RecordingTime = DateTime.Now.ToUniversalTime(),
                Temperature   = temperatureReadings.Average(),
                Humidity      = humidityReadings.Average(),
                Pressure      = pressureReadings.Average(),
                Altitude      = altitudeReadings.Average()
            };

            // Send to console for debugging purposes
            Debug.WriteLine(weatherReading.ToString());

            // Send the reading to the event hub
            await _weatherDataSender.SendDataJsonUtf8Async(weatherReading);
        }
Ejemplo n.º 6
0
        private static void SensorTimerTick(object state)
        {
            // Read sensor data
            double derece = bme.ReadTemperature();
            double nem    = bme.ReadHumidity();
            double basinc = bme.ReadPressure();

            Debug.WriteLine("Sıcaklık: " + derece.ToString());
            Debug.WriteLine("Nem: " + nem.ToString());
            Debug.WriteLine("Basınç: " + basinc.ToString());

            count = count + 1;
            Debug.WriteLine("Sıra: " + count);
            Debug.WriteLine("--------------");

            Telemetry telemetry = new Telemetry();

            telemetry.Sicaklik = derece;
            telemetry.Nem      = nem;
            telemetry.Basinc   = basinc;

            // Convert telemetry JSON to string
            string telemetryJSON = JsonConvert.SerializeObject(telemetry);

            // Send data to IoT Hub
            AzureIoTHub.SendDevieceToCloudMessageAsync(telemetryJSON);
        }
Ejemplo n.º 7
0
 private static void SensorTimerTick(object state)
 {
     // Write sensor data to output / immediate window
     Debug.WriteLine("Temperature..: " + bme.ReadTemperature().ToString("00.0") + "C");
     Debug.WriteLine("Humidity.....: %" + bme.ReadHumidity().ToString("00.0" + "RH"));
     Debug.WriteLine("Pressure.....: " + bme.ReadPressure().ToString(".0") + "Pa");
     Debug.WriteLine("Altitude.....: " + bme.ReadAltitude(slp).ToString(".0") + "m");
     Debug.WriteLine("-----");
 }
Ejemplo n.º 8
0
        private static void SensorTimerTick(object state)
        {
            // Read sensor data: al
            double al = apds.ReadAmbientLight();

            // Read sensor data: bme
            double derece  = bme.ReadTemperature();
            double nem     = bme.ReadHumidity();
            double basinc  = bme.ReadPressure();
            double UVIndex = veml.Calculate_Average_UV_Index();

            // Create telemetry instance to store sensor data
            Telemetry telemetry = new Telemetry();

            telemetry.AmbientLight = Math.Round(al, 2);
            telemetry.Temperature  = Math.Round(derece, 2);
            telemetry.Humidity     = Math.Round(nem, 2);
            telemetry.Pressure     = Math.Round(basinc, 2);
            telemetry.UVIndex      = Math.Round(UVIndex, 2);

            // Set Measurement Time
            DateTime localDate = DateTime.Now;

            //string utcFormat = localDate.ToUniversalTime().ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'");
            telemetry.DateTime = TimeZoneInfo.ConvertTime(localDate.ToUniversalTime(), TimeZoneInfo.Local).ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'");

            // Ex: Get GTB Standard Time zone - (GMT+02:00) Athens, Istanbul, Minsk
            //TimeZoneInfo SystemTimeZoneId = TimeZoneInfo.FindSystemTimeZoneById("GTB Standard Time");
            //DateTime LocalTime = TimeZoneInfo.ConvertTime(localDate, TimeZoneInfo.Local, SystemTimeZoneId);
            //Debug.WriteLine("LocalTime: " + LocalTime);

            // Write sensor data to output / immediate window
            Debug.WriteLine("Date Time: " + telemetry.DateTime);
            Debug.WriteLine("Ambient Light: " + telemetry.AmbientLight.ToString());
            Debug.WriteLine("Temperature: " + telemetry.Temperature.ToString());
            Debug.WriteLine("Humidity: " + telemetry.Humidity.ToString());
            Debug.WriteLine("Pressure: " + telemetry.Pressure.ToString());

            Debug.WriteLine("- - - - - - - - - - - - -");

            // Write sensor data to output / immediate window
            Debug.WriteLine("UVA........: " + veml.Read_RAW_UVA().ToString());
            Debug.WriteLine("UVB........: " + veml.Read_RAW_UVB().ToString());
            Debug.WriteLine("UVA Index..: " + veml.Calculate_UV_Index_A().ToString());
            Debug.WriteLine("UVB Index..: " + veml.Calculate_UV_Index_B().ToString());
            Debug.WriteLine("UV Index...: " + telemetry.UVIndex.ToString());
            count = count + 1;
            Debug.WriteLine("Sıra: " + count);
            Debug.WriteLine("--------------------------");

            // Convert telemetry JSON to string
            string telemetryJSON = JsonConvert.SerializeObject(telemetry);

            // Send data to IoT Hub
            SendDeviceToCloudMessageAsync(telemetryJSON);
        }
        private void _timer_Tick(object sender, object e)
        {
            var temp     = _bme280.ReadTemperature();
            var humidity = _bme280.ReadHumidity();
            var pressure = _bme280.ReadPressure();
            var altitude = _bme280.ReadAltitude(seaLevelPressure);

            if (temp.Status == System.Threading.Tasks.TaskStatus.RanToCompletion)
            {
                Debug.WriteLine("Temp: {0} deg C", temp.Result);
                this.t_temp.Text = temp.Result.ToString();
                SendDeviceToCloudMessagesAsync(temp.Result, "Temp");
            }
            else
            {
                Debug.WriteLine("Temp: {0} deg C", temp.Status);
                this.t_temp.Text = temp.Status.ToString();
            }

            if (humidity.Status == System.Threading.Tasks.TaskStatus.RanToCompletion)
            {
                Debug.WriteLine("Humidity: {0} %", humidity.Result);
                this.t_hum.Text = humidity.Result.ToString();
                SendDeviceToCloudMessagesAsync(humidity.Result, "Humidity");
            }
            else
            {
                Debug.WriteLine("Humidity: {0} %", humidity.Status);
                this.t_hum.Text = humidity.Status.ToString();
            }

            if (pressure.Status == System.Threading.Tasks.TaskStatus.RanToCompletion)
            {
                Debug.WriteLine("Pressure: {0} Pa", pressure.Result);
                this.t_pres.Text = pressure.Result.ToString();
                SendDeviceToCloudMessagesAsync(pressure.Result, "Pressure");
            }
            else
            {
                Debug.WriteLine("Pressure: {0} Pa", pressure.Status);
                this.t_pres.Text = pressure.Status.ToString();
            }

            if (altitude.Status == System.Threading.Tasks.TaskStatus.RanToCompletion)
            {
                Debug.WriteLine("Altitude: {0} m", altitude.Result);
                this.t_alt.Text = altitude.Result.ToString();
                SendDeviceToCloudMessagesAsync(altitude.Result, "Altitude");
            }
            else
            {
                Debug.WriteLine("Altitude: {0} m", altitude.Status);
                this.t_alt.Text = altitude.Status.ToString();
            }
        }
Ejemplo n.º 10
0
        private async void _timer_Tick(object sender, object e)
        {
            Model.Temperature = (int)await _bme280.ReadTemperature();

            Model.Humidity = (int)await _bme280.ReadHumidity();

            Model.Pressure = (int)await _bme280.ReadPressure();

            //var altitude = await _bme280.ReadAltitude(seaLevelPressure);
            Debug.WriteLine("Temp: {0} deg C", args: Model.Temperature);
            Debug.WriteLine("Humidity: {0} %", args: Model.Humidity);
            Debug.WriteLine("Pressure: {0} Pa", args: Model.Pressure);
            //Debug.WriteLine("Altitude: {0} m", altitude);
        }
Ejemplo n.º 11
0
        public async Task <TemperatureReadings> ReadAsync()
        {
            float temp = await _bme280.ReadTemperature();

            float humidity = await _bme280.ReadHumidity();

            float pressure = await _bme280.ReadPressure();

            var data = new TemperatureReadings
            {
                Temperature = temp.Truncate(2),
                Humidity    = humidity.Truncate(2),
                Pressure    = pressure.Truncate(2),
                Source      = TemperatureSensorType.BME280
            };

            return(data);
        }
Ejemplo n.º 12
0
        private async Task ReadData()
        {
            string status = "";

            double avgTemp   = 0;
            double avgHum    = 0;
            double avgPres   = 0;
            int    tempCount = 0;
            int    humCount  = 0;
            int    presCount = 0;

            Log.Info("ReadData");
            // Read and format Sensor data
            try
            {
                if (bmp180 != null)
                {
                    var sensorData = await bmp180.GetSensorDataAsync(Bmp180AccuracyMode.UltraHighResolution);

                    detailData.Bmp180Temperature = sensorData.Temperature;
                    detailData.Bmp180Pressure    = sensorData.Pressure;

                    avgTemp += sensorData.Temperature;
                    ++tempCount;

                    avgPres += sensorData.Pressure;
                    ++presCount;
                    Log.Debug($"BMP180: {detailData.Bmp180Temperature},N/A,{detailData.Bmp180Pressure}");
                }
            }
            catch (Exception ex)
            {
                status = "Bmp180 Error: " + ex.Message;
                Log.Error("Bmp180 read Error", ex);
                detailData.Bmp180Temperature = double.NaN;
                detailData.Bmp180Pressure    = double.NaN;
            }


            try
            {
                if (bme280 != null)
                {
                    if (bme280ForceMode)
                    {
                        await bme280.TakeForcedMeasurement();
                    }

                    // Read Temperature
                    detailData.Bme280Temperature = await bme280.ReadTemperature();

                    avgTemp += detailData.Bme280Temperature;
                    ++tempCount;
                    // Read Humidity
                    detailData.Bme280Humidity = await bme280.ReadHumidity();

                    avgHum += detailData.Bme280Humidity;
                    ++humCount;

                    // Read Barometric Pressure
                    detailData.Bme280Pressure = await bme280.ReadPressure() / 100.0;

                    avgPres += detailData.Bme280Pressure;
                    ++presCount;
                    Log.Debug($"BME280: {detailData.Bme280Temperature},{detailData.Bme280Humidity},{detailData.Bme280Pressure}");
                }
            }
            catch (Exception ex)
            {
                status = "Bme280 Error: " + ex.Message;
                Log.Error("Bme280 read Error", ex);
                detailData.Bme280Temperature = double.NaN;
                detailData.Bme280Humidity    = double.NaN;
                detailData.Bme280Pressure    = double.NaN;
            }


            try
            {
                if (dhtSensor != null)
                {
                    DhtReading reading = new DhtReading();
                    reading = await dhtSensor.GetReadingAsync();

                    if (reading.IsValid)
                    {
                        // ***
                        // *** Get the values from the reading.
                        // ***
                        detailData.DhtTemperature = reading.Temperature;
                        detailData.DhtHumidity    = reading.Humidity;

                        avgTemp += reading.Temperature;
                        ++tempCount;
                        avgHum += reading.Humidity;
                        ++humCount;
                        Log.Debug($"DHT22: {detailData.DhtTemperature},{detailData.DhtHumidity},N/A,");
                    }
                    else
                    {
                        Log.Debug($"DHT22: invalid reading");
                    }
                }
            }
            catch (Exception ex)
            {
                status = "DHT22 Error: " + ex.Message;
                Log.Error("DHT22 read Error", ex);
                detailData.DhtTemperature = double.NaN;
                detailData.DhtHumidity    = double.NaN;
            }


            //calculate average
            avgTemp /= tempCount;
            avgHum  /= humCount;
            avgPres /= presCount;

            basicData.CurrentTemperature = avgTemp;
            basicData.CurrentHumidity    = avgHum;
            basicData.CurrentPressure    = avgPres;


            if (status.Length > 0)
            {
                OnStatusChanged(status);
            }
        }
Ejemplo n.º 13
0
        static void Main(string[] args)
        {
            MMALCamera cam = MMALCamera.Instance;

            // Create observable that will generate an incrementing number every second
            var observable = Observable.Generate(1, x => true, x => x + 1, x => x, x => TimeSpan.FromSeconds(1));

            var relay  = OutputPort.Create(17, OutputPort.InitialValue.Low).Result;
            var light1 = OutputPort.Create(27, OutputPort.InitialValue.Low).Result;
            var light2 = OutputPort.Create(22, OutputPort.InitialValue.Low).Result;
            var button = InputPort.Create(24, GpioEdge.Both).Result;

            // Write true whenever the number is even and odd when the number is odd
            using (var imgCaptureHandler = new ImageStreamCaptureHandler("/home/pi/images/", "jpg"))
                using (observable.Select(x => x % 2 == 0).Subscribe(relay))
                    using (observable.Select(x => x % 2 == 0).Subscribe(light1))
                        //using (observable.Select(x => x % 2 != 0).Subscribe(light2))
                        //using (button.Do(pressed => Console.WriteLine(pressed)).Subscribe())
                        using (button.Subscribe(light2))
                            using (var i2cBus = new I2CBusPI("/dev/i2c-1"))
                            {
                                var takePictureTask = cam.TakePicture(imgCaptureHandler, MMALEncoding.JPEG, MMALEncoding.I420);

                                var i2cDevice = new I2CDevicePI(i2cBus, Display.DefaultI2CAddress);

                                var sensor = new BME280Sensor(i2cBus, 1014);

                                var display = new SSD1306.Display(i2cDevice, 128, 64);
                                display.Init();

                                var dfont = new AdafruitSinglePageFont();

                                for (int i = 0; i < 100; i++)
                                {
                                    display.WriteLineBuff(dfont, $"Temperature: {sensor.ReadTemperature().Result} °C", $"Pressure: {sensor.ReadPressure().Result} Pa", $"Humidity: {sensor.ReadHumidity().Result} %", $"Altitude: {sensor.ReadAltitude().Result} m", "Line 5", "Line 6", "Line 7", "Line 8");
                                    display.DisplayUpdate();
                                }

                                //for (int i = 0; i < 100; i++)
                                //    display.DrawPixel(i, i);

                                takePictureTask.Wait();
                                display.ClearDisplay();
                            }
            // releasing relay
            relay.Write(true);
            // turning of light
            light1.Write(false);
            light2.Write(false);
            // Cleanup disposes all unmanaged resources and unloads Broadcom library. To be called when no more processing is to be done
            // on the camera.
            cam.Cleanup();
        }