public static void Main()
        {
            //Setup I2C pins for ESP32 board
            Configuration.SetPinFunction(21, DeviceFunction.I2C1_DATA);
            Configuration.SetPinFunction(22, DeviceFunction.I2C1_CLOCK);

            // if we are using TLS it requires valid date & time
            NetworkHelpers.SetupAndConnectNetwork(wifiSSID, wifiApPASSWORD, true);

            NetworkHelpers.CheckIP();
            Debug.WriteLine("Waiting for network up and IP address...");
            NetworkHelpers.IpAddressAvailable.WaitOne();


            bme280Sensor    = new BME280(1, BME280.I2CAddresses.Address0);
            someDeviceValue = random.Next(50);

            if (!SetupThingsBoard())
            {
                Debug.WriteLine("Error connecting to the server");
                return;
            }

            // launch telemetry thread
            Thread telemetryThread = new Thread(new ThreadStart(TelemetryLoop));

            telemetryThread.Start();

            Debug.WriteLine("Connected to the server.");

            while (true)
            {
                Thread.Sleep(1000);
            }
        }
예제 #2
0
        public static void Main()
        {
            //
            //  Create a new BME280 object and put the sensor into polling
            //  mode (update intervale set to 0ms).
            //
            BME280 sensor = new BME280(updateInterval: 0);

            string message;

            while (true)
            {
                //
                //  Make the sensor take new readings.
                //
                sensor.Update();
                //
                //  Prepare a message for the user and output to the debug console.
                //
                message  = "Temperature: " + sensor.Temperature.ToString("F1") + " C\n";
                message += "Humidity: " + sensor.Humidity.ToString("F1") + " %\n";
                message += "Pressure: " + (sensor.Pressure / 100).ToString("F0") + " hPa\n\n";
                Debug.Print(message);
                //
                //  Sleep for 1000ms before repeating the process.
                //
                Thread.Sleep(1000);
            }
        }
예제 #3
0
        public void TestDataConvert()
        {
            BME280        Sens       = new BME280(null);
            PrivateObject SensAccess = new PrivateObject(Sens);

            BME280.CompensationParameters CompParams = new BME280.CompensationParameters()
            {
                T1 = 27504,
                T2 = 26435,
                T3 = -1000,
                P1 = 36477,
                P2 = -10685,
                P3 = 3024,
                P4 = 2855,
                P5 = 140,
                P6 = -7,
                P7 = 15500,
                P8 = -14600,
                P9 = 6000
            };

            SensAccess.SetField("CompParams", CompParams);
            int IntTempOut = (int)SensAccess.Invoke("ProcessTemperatureInternal", 519888);

            Assert.AreEqual(128422, IntTempOut);

            double TempOut = (double)SensAccess.Invoke("ProcessTemperature", IntTempOut);

            Assert.IsTrue(Math.Abs(25.08 - TempOut) < 0.1);

            double PressOut = (double)SensAccess.Invoke("ProcessPressure", 415148, IntTempOut);

            Assert.IsTrue(Math.Abs(100653.265625 - PressOut) < 0.1);
        }
예제 #4
0
        private static void Main()
        {
            _sensor = new BME280(Hardware.SocketOne, BME280.I2CAddresses.Address0)
            {
                TemperatureUnit      = TemperatureUnits.Fahrenheit,
                PressureCompensation = PressureCompensationModes.SeaLevelCompensated
            };

            _sensor.SetRecommendedMode(BME280.RecommendedModes.WeatherMonitoring);

            while (true)
            {
                Debug.WriteLine("------Reading individual values-------");

                Debug.WriteLine($"Pressure.......: {_sensor.ReadPressure():F1} hPa");
                Debug.WriteLine($"Temperature....: {_sensor.ReadTemperature():F2} °F");
                Debug.WriteLine($"Humidity.......: {_sensor.ReadHumidity():F2} %RH");
                Debug.WriteLine($"Altitude.......: {_sensor.ReadAltitude():F0} meters\n");

                _sensor.ReadSensor(out Single pressure, out Single temperature, out Single humidity, out Single altitude);

                Debug.WriteLine("------Using the ReadSensor Method-------");
                Debug.WriteLine($"Pressure.......: {pressure:F1} hPa");
                Debug.WriteLine($"Temperature....: {temperature:F2} °F");
                Debug.WriteLine($"Humidity.......: {humidity:F2} %RH");
                Debug.WriteLine($"Altitude.......: {altitude:F0} meters\n");

                Thread.Sleep(5000);
            }
        }
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            try
            {
                bme280Sensor = new BME280(0x76);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"BME280 Initialisation failed:{ex.Message}");

                return;
            }

            try
            {
                azureIoTHubClient = DeviceClient.CreateFromConnectionString(AzureIoTHubConnectionString, TransportType.Mqtt);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"CreateFromConnectionString failed:{ex.Message}");
                return;
            }

            bme280InputPollingTimer = new Timer(SensorUpdateTimerCallback, null, timerDue, timerPeriod);

            backgroundTaskDeferral = taskInstance.GetDeferral();
        }
예제 #6
0
        public static async Task Main()
        {
            Console.WriteLine("Bme280 test");
            try
            {
                CancellationToken ct = default;

                var bme280   = new BME280("/dev/i2c-1", 0x76);
                var settings = new bme280_settings
                {
                    osr_h  = BME280_OVERSAMPLING_1X,
                    osr_p  = BME280_OVERSAMPLING_1X,
                    osr_t  = BME280_OVERSAMPLING_1X,
                    filter = BME280_FILTER_COEFF_OFF,
                };

                bme280.SetSensorSettings(ref settings, BME280_OSR_HUM_SEL | BME280_OSR_PRESS_SEL | BME280_OSR_TEMP_SEL);

                while (!ct.IsCancellationRequested)
                {
                    bme280.SetSensorMode(BME280_FORCED_MODE);
                    await Task.Delay(100, ct).ConfigureAwait(false);

                    var data = bme280.GetSensorData(BME280_ALL);
                    Console.WriteLine(FormattableString.Invariant($"T: {data.temperature / 100.0} degC, P: {data.pressure / 100.0} Pascal, H: {data.humidity / 1024.0} %rH"));
                    await Task.Delay(1000, ct).ConfigureAwait(false);
                }
            }
#pragma warning disable CA1031 // Do not catch general exception types
            catch (Exception ex)
#pragma warning restore CA1031 // Do not catch general exception types
            {
                Console.WriteLine(FormattableString.Invariant($"Error: {ex}"));
            }
        }
예제 #7
0
        public static void Main()
        {
            //
            //  BME280 temperature, humidity and pressure object.  This object should
            //  raise an interrupt when the changes in the sensor readings exceed the
            //  following:
            //
            //  Temperature: +/- 1 C
            //  Humidity: +/- 1 %
            //  Pressure: +/- 10 kPa (the default value for this threshold)
            //
            BME280 sensor = new BME280(temperatureChangeNotificationThreshold: 0.1F,
                                       humidityChangeNotificationThreshold: 1.0f);

            //
            //  Attach interrupt handlers to the temperature and pressure sensor.
            //
            sensor.HumidityChanged += (s, e) =>
            {
                Debug.Print("Current humidity: " + e.CurrentValue.ToString("f2"));
            };
            sensor.PressureChanged += (s, e) =>
            {
                Debug.Print("Current pressure: " + (e.CurrentValue / 100).ToString("f2"));
            };
            sensor.TemperatureChanged += (s, e) =>
            {
                Debug.Print("Current temperature: " + e.CurrentValue.ToString("f2"));
            };
            //
            //  Application can go to sleep now as readings will be dealt with by the
            //  interrupt handlers.
            //
            Thread.Sleep(Timeout.Infinite);
        }
예제 #8
0
        public MainPage()
        {
            this.InitializeComponent();

            bme280 = new BME280();
            initBme280();
        }
예제 #9
0
        protected override async Task RunContinuouslyAsync(IMqttClient client, TimeSpan delay, CancellationToken stoppingToken)
        {
            var bme280   = new BME280("/dev/i2c-1", 0x76);
            var settings = new bme280_settings
            {
                osr_h  = BME280_OVERSAMPLING_1X,
                osr_p  = BME280_OVERSAMPLING_1X,
                osr_t  = BME280_OVERSAMPLING_1X,
                filter = BME280_FILTER_COEFF_OFF
            };

            bme280.SetSensorSettings(ref settings, BME280_OSR_HUM_SEL | BME280_OSR_PRESS_SEL | BME280_OSR_TEMP_SEL);

            var oldData        = new bme280_data();
            var nextReportTime = DateTimeOffset.MinValue;

            while (!stoppingToken.IsCancellationRequested)
            {
                bme280.SetSensorMode(BME280_FORCED_MODE);
                await Task.Delay(100, stoppingToken).ConfigureAwait(false);

                var data = bme280.GetSensorData(BME280_ALL);
                var now  = DateTimeOffset.UtcNow;
                if ((now > nextReportTime) || ShouldReport(ref oldData, ref data))
                {
                    await SendReading(client, data, stoppingToken);

                    oldData        = data;
                    nextReportTime = now.AddSeconds(60);
                }
                await Task.Delay(delay, stoppingToken);
            }
        }
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            try
            {
                bme280Sensor = new BME280(0x76);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"BME280 Initialisation failed:{ex.Message}");

                return;
            }

            try
            {
                azureIoTHubClient = DeviceClient.CreateFromConnectionString(AzureIoTHubConnectionString, TransportType.Mqtt);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"CreateFromConnectionString failed:{ex.Message}");
                return;
            }

            try
            {
                deviceTwin = azureIoTHubClient.GetTwinAsync().Result;
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Azure IoT Hub device twin configuration retrieval failed:{ex.Message}");
                return;
            }

            try
            {
                if (deviceTwin.Properties.Desired.Contains("TimerDue"))
                {
                    timerDue = TimeSpan.Parse(deviceTwin.Properties.Desired["TimerDue"].ToString());
                }

                if (deviceTwin.Properties.Desired.Contains("TimerPeriod"))
                {
                    timerPeriod = TimeSpan.Parse(deviceTwin.Properties.Desired["TimerPeriod"].ToString());
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Sensor due or period configuration retrieval failed, using default:{ex.Message}");
                return;
            }

            bme280InputPollingTimer = new Timer(SensorUpdateTimerCallback, null, timerDue, timerPeriod);

            backgroundTaskDeferral = taskInstance.GetDeferral();
        }
예제 #11
0
        public MeadowApp()
        {
            Console.WriteLine("Initializing...");

            // configure our BME280 on the I2C Bus
            var i2c = Device.CreateI2cBus();

            bme280 = new BME280(
                i2c,
                BME280.I2cAddress.Adddress0x77 //default
                );

            // TODO: SPI version

            // Example that uses an IObersvable subscription to only be notified
            // when the temperature changes by at least a degree, and humidty by 5%.
            // (blowing hot breath on the sensor should trigger)
            bme280.Subscribe(new FilterableObserver <AtmosphericConditionChangeResult, AtmosphericConditions>(
                                 h => {
                Console.WriteLine($"Temp and pressure changed by threshold; new temp: {h.New.Temperature}, old: {h.Old.Temperature}");
            },
                                 e => {
                return(
                    (Math.Abs(e.Delta.Temperature) > 1)
                    &&
                    (Math.Abs(e.Delta.Pressure) > 5)
                    );
            }
                                 ));

            // classical .NET events can also be used:
            bme280.Updated += (object sender, AtmosphericConditionChangeResult e) => {
                Console.WriteLine($"  Temperature: {e.New.Temperature}ºC");
                Console.WriteLine($"  Pressure: {e.New.Pressure}hPa");
                Console.WriteLine($"  Relative Humidity: {e.New.Humidity}%");
            };


            // just for funsies.
            Console.WriteLine($"ChipID: {bme280.GetChipID():X2}");
            //Thread.Sleep(1000);

            //// is this necessary? if so, it should probably be tucked into the driver
            //Console.WriteLine("Reset");
            //bme280.Reset();

            // get an initial reading
            ReadConditions().Wait();

            // start updating continuously
            bme280.StartUpdating();
        }
예제 #12
0
 public async Task <bool> Initialize()
 {
     try
     {
         _bme280Sensor = new BME280(_i2cAddress);
         return(true);
     }
     catch (Exception e)
     {
         Debug.WriteLine(e);
     }
     return(false);
 }
예제 #13
0
 public PixelSensor()
 {
     Icon = "ac_unit";
     //BMP280 sensor
     try
     {
         sensor = new BME280();
     }
     catch (Exception e)
     {
         Logger.Log(ConsoleColor.Red, e.Message);
     }
     //Tickrate = 10000;
 }
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            try
            {
                bme280Sensor = new BME280(0x76);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }

            bme280InputPollingTimer = new Timer(SensorUpdateTimerCallback, null, timerDue, timerPeriod);

            backgroundTaskDeferral = taskInstance.GetDeferral();
        }
예제 #15
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            backgroundTaskDeferral = taskInstance.GetDeferral();
            taskInstance.Canceled += TaskInstance_Canceled;

            Debug.WriteLine(Windows.ApplicationModel.Package.Current.Id.FamilyName);

            // Setup the BME280 sensor and timer
            if (bme280Sensor == null)
            {
                try
                {
                    bme280Sensor = new BME280(0x76);

                    bme280InputPollingTimer = new Timer(SensorUpdateTimerCallback, null, timerDue, timerPeriod);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                }
            }

            var appServiceTrigger = taskInstance.TriggerDetails as AppServiceTriggerDetails;

            if (appServiceTrigger != null)
            {
                Debug.WriteLine("appServiceTrigger != null");

                // Verify that the app service connection is requesting the "" that this class provides
                if (appServiceTrigger.Name.Equals("SensorServerEnd"))
                {
                    // Store the connection and subscribe to the "RequestRecieved" event to be notified when clients send messages
                    connection = appServiceTrigger.AppServiceConnection;
                    connection.RequestReceived += Connection_RequestReceived;
                }
                else
                {
                    backgroundTaskDeferral.Complete();
                    Debug.WriteLine("5");
                }
            }
            else
            {
                Debug.WriteLine("appServiceTrigger == null");
            }
        }
예제 #16
0
        public static void Main()
        {
            //Setup I2C pins for ESP32 board
            Configuration.SetPinFunction(21, DeviceFunction.I2C1_DATA);
            Configuration.SetPinFunction(22, DeviceFunction.I2C1_CLOCK);

            BME280 bme280Sensor = new BME280(1, BME280.I2CAddresses.Address0);

            while (true)
            {
                Debug.WriteLine(bme280Sensor.ReadHumidity());
                Debug.WriteLine(bme280Sensor.ReadPressure());
                Debug.WriteLine(bme280Sensor.ReadTemperature());

                Thread.Sleep(10000);
            }
        }
예제 #17
0
        public void Initialize()
        {
            this.ADC = new TLV2544(this.SPI0, new DigitalOutPi(16));// { TraceLogging = true };
            TLV2544.Configuration Config = TLV2544.DefaultConfig;
            Config.VoltageRef         = TLV2544.VoltageReference.INTERNAL_2V;
            Config.ConversionClockSrc = TLV2544.ConversionClockSrc.INTERNAL;
            Config.UseEOCPin          = true;
            //Config.UseLongSample = true;
            this.ADC.Configure(Config);

            this.Thermocouple = new MAX31855(this.SPI0, new DigitalOutPi(18));
            this.UVLight      = new VEML6070(this.I2C1);
            this.Atmospheric  = new BME280(this.I2C1);
            this.Atmospheric.Configure();

            this.Atmospheric.ChangeMode(BME280.Mode.NORMAL);
            this.AirQuality   = new MQ135(this.ADC.Inputs[0], 3300, 6400, 4.6);
            this.SoilMoisture = new VH400(this.ADC.Inputs[1]);

            this.TakeReadings = true;
        }
예제 #18
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            var                deviceId           = "";
            var                deviceSettings     = default(AutodiscoverResult);
            CameraStatus       cameraStatus       = CameraStatus.NotInstalled;
            GroveBaseHatStatus groveBaseHatStatus = GroveBaseHatStatus.NotInstalled;

            #region Set up device autodiscovery
            //keep autodiscovering until we get a connection string
            while (string.IsNullOrEmpty(deviceSettings?.ConnectionString) == true)
            {
                try
                {
                    deviceId       = DeviceIdService.GetDeviceId();
                    deviceSettings = AutodiscoverService.GetDeviceSettings(deviceId);

                    LoggingService.Log($"Device settings retrieved for DeviceId:{deviceId}");
                }
                catch (Exception ex)
                {
                    LoggingService.Error($"Autodiscovery failed", ex);
                    Thread.Sleep(30000);
                }
            }
            #endregion

            #region Set up IoT Hub Connection
            try
            {
                azureIoTHubClient = DeviceClient.CreateFromConnectionString(deviceSettings.ConnectionString, TransportType.Mqtt);
            }
            catch (Exception ex)
            {
                LoggingService.Error($"Azure IoT Hub connection failed", ex);
                //TODO: set up a way for this to retry instead of fail?
                return;
            }
            #endregion

            #region Report device startup
            SendPayloadToIoTHub(new DeviceEvent()
            {
                ApplicationStarted = true
            });
            #endregion

            #region Retrieve device twin
            try
            {
                deviceTwin = azureIoTHubClient.GetTwinAsync().Result;
            }
            catch (Exception ex)
            {
                LoggingService.Error($"Azure IoT Hub device twin configuration retrieval failed", ex);
                //TODO: set up a way for this to retry instead of fail?
                return;
            }
            #endregion

            #region Report device properties
            try
            {
                TwinCollection reportedProperties;
                reportedProperties = new TwinCollection();

                // This is from the OS
                reportedProperties["Timezone"]    = TimeZoneSettings.CurrentTimeZoneDisplayName;
                reportedProperties["OSVersion"]   = Environment.OSVersion.VersionString;
                reportedProperties["MachineName"] = Environment.MachineName;

                // This is from the application manifest
                Package        package   = Package.Current;
                PackageId      packageId = package.Id;
                PackageVersion version   = packageId.Version;
                reportedProperties["ApplicationDisplayName"] = package.DisplayName;
                reportedProperties["ApplicationName"]        = packageId.Name;
                reportedProperties["ApplicationVersion"]     = string.Format($"{version.Major}.{version.Minor}.{version.Build}.{version.Revision}");

                // Unique identifier from the hardware
                SystemIdentificationInfo systemIdentificationInfo = SystemIdentification.GetSystemIdForPublisher();
                using (DataReader reader = DataReader.FromBuffer(systemIdentificationInfo.Id))
                {
                    byte[] bytes = new byte[systemIdentificationInfo.Id.Length];
                    reader.ReadBytes(bytes);
                    reportedProperties["SystemId"] = BitConverter.ToString(bytes);
                }

                azureIoTHubClient.UpdateReportedPropertiesAsync(reportedProperties).Wait();
            }
            catch (Exception ex)
            {
                LoggingService.Error($"Azure IoT Hub device twin configuration retrieval failed", ex);
                //TODO: set up a way for this to retry instead of fail?
                return;
            }
            #endregion

            #region Wire up device reboot command handler
            try
            {
                azureIoTHubClient.SetMethodHandlerAsync("Restart", RestartAsync, null);
            }
            catch (Exception ex)
            {
                LoggingService.Error($"Azure IoT Hub device method handler configuration failed", ex);
                return;
            }
            #endregion

            #region Set up Grove Base Hat for RPI if installed
            if (deviceTwin.Properties.Desired.Contains("GroveBaseHatForRPIInstalled"))
            {
                groveBaseHatStatus = GroveBaseHatStatus.Installed;

                try
                {
                    if (deviceTwin.Properties.Desired["GroveBaseHatForRPIInstalled"].value == true)
                    {
                        GroveBaseHatAnalogPorts = new AnalogPorts();
                        GroveBaseHatAnalogPorts.Initialise();
                        LoggingService.Log($"Grove Base Hat for RPI Firmware version:{GroveBaseHatAnalogPorts.Version()}");

                        bme280Sensor = new BME280(0x76);

                        // Wire up the sensor update handler
                        azureIoTHubClient.SetMethodHandlerAsync("SensorUpdate", SensorUpdateAsync, deviceId);

                        // If the SensorUpdatePeriod greater than 0 start timer
                        int sensorUpdatePeriod = deviceTwin.Properties.Desired["SensorUpdatePeriod"].value;
                        LoggingService.Log($"Sensor update period:{sensorUpdatePeriod} seconds");
                        if (sensorUpdatePeriod > 0)
                        {
                            sensorUpdateTimer  = new Timer(SensorUpdateTimerCallback, deviceId, SensorUpdateDuePeriod, new TimeSpan(0, 0, sensorUpdatePeriod));
                            groveBaseHatStatus = GroveBaseHatStatus.Automatic;
                        }
                        else
                        {
                            groveBaseHatStatus = GroveBaseHatStatus.Enabled;
                        }
                    }
                }
                catch (Exception ex)
                {
                    LoggingService.Error($"Grove Base Hat for RPI sensor configuration failed", ex);
                    return;
                }
            }
            SendPayloadToIoTHub(new DeviceStatus()
            {
                GroveBaseHatStatus = groveBaseHatStatus
            });
            #endregion

            #region Set up Camera if installed
            if (deviceTwin.Properties.Desired.Contains("CameraInstalled"))
            {
                cameraStatus = CameraStatus.Installed;

                try
                {
                    if (deviceTwin.Properties.Desired["CameraInstalled"].value == true)
                    {
                        mediaCapture = new MediaCapture();
                        mediaCapture.InitializeAsync().AsTask().Wait();

                        // Wire up the image update handler
                        azureIoTHubClient.SetMethodHandlerAsync("ImageUpdate", ImageUpdateAsync, deviceId);

                        // If the CameraUpdatePeriod greater than 0 start timer
                        int imageUpdatePeriod = deviceTwin.Properties.Desired["ImageUpdatePeriod"].value;
                        LoggingService.Log($"Image update period:{imageUpdatePeriod} seconds");
                        if (imageUpdatePeriod > 0)
                        {
                            ImageUpdatetimer = new Timer(ImageUpdateTimerCallback, deviceId, ImageUpdateDueDefault, new TimeSpan(0, 0, imageUpdatePeriod));
                            cameraStatus     = CameraStatus.Automatic;
                        }
                        else
                        {
                            cameraStatus = CameraStatus.Enabled;
                        }
                    }
                }
                catch (Exception ex)
                {
                    LoggingService.Error($"Image capture configuration failed", ex);
                }
            }
            SendPayloadToIoTHub(new DeviceStatus()
            {
                CameraStatus = cameraStatus
            });
            #endregion

            //enable task to continue running in background
            backgroundTaskDeferral = taskInstance.GetDeferral();
        }
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            try
            {
                bme280Sensor = new BME280(0x76);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"BME280 Initialisation failed:{ex.Message}");

                return;
            }

            try
            {
                GpioController gpioController = GpioController.GetDefault();
                outputGpioPin = gpioController.OpenPin(OutputGpioPinNumber);
                outputGpioPin.SetDriveMode(GpioPinDriveMode.Output);
                outputGpioPin.Write(GpioPinValue.Low);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Actuator GPIO Initialisation failed:{ex.Message}");

                return;
            }

            try
            {
                azureIoTHubClient = DeviceClient.CreateFromConnectionString(AzureIoTHubConnectionString, TransportType.Mqtt);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"CreateFromConnectionString failed:{ex.Message}");
                return;
            }

            try
            {
                azureIoTHubClient.SetMethodHandlerAsync("RestartDevice", RestartAsync, null);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Azure IoT Hub device method handler configuration failed:{ex.Message}");
                return;
            }

            try
            {
                azureIoTHubClient.SetMethodHandlerAsync("ActuatorToggle", ActuatorAsync, null);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Azure IoT Hub device Actuator method handler configuration failed:{ex.Message}");
                return;
            }

            bme280InputPollingTimer = new Timer(SensorUpdateTimerCallback, null, timerDue, timerPeriod);

            backgroundTaskDeferral = taskInstance.GetDeferral();
        }
예제 #20
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            try
            {
                bme280Sensor = new BME280(0x76);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"BME280 Initialisation failed:{ex.Message}");

                return;
            }

            try
            {
                TpmDevice myDevice = new TpmDevice(0);                 // Use logical device 0 on the TPM

                azureIoTHubUri      = myDevice.GetHostName();
                deviceId            = myDevice.GetDeviceId();
                sasToken            = myDevice.GetSASToken((uint)sasTokenValidityPeriod.TotalSeconds);
                sasTokenIssuedAtUtc = DateTime.UtcNow;
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"TpmDevice.GetSASToken failed:{ex.Message}");
                return;
            }

            try
            {
                azureIoTHubClient = DeviceClient.Create(azureIoTHubUri, AuthenticationMethodFactory.CreateAuthenticationWithToken(deviceId, sasToken), TransportType.Mqtt);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"DeviceClient.Create with TPM info failed:{ex.Message}");
                return;
            }

            try
            {
                azureIoTHubClient.SetMethodHandlerAsync("Restart", RestartAsync, null);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Azure IoT Hub device method handler configuration failed:{ex.Message}");
                return;
            }

            try
            {
                TwinCollection reportedProperties;
                reportedProperties = new TwinCollection();

                // This is from the OS
                reportedProperties["Timezone"]    = TimeZoneSettings.CurrentTimeZoneDisplayName;
                reportedProperties["OSVersion"]   = Environment.OSVersion.VersionString;
                reportedProperties["MachineName"] = Environment.MachineName;

                // This is from the application manifest
                Package        package   = Package.Current;
                PackageId      packageId = package.Id;
                PackageVersion version   = packageId.Version;
                reportedProperties["ApplicationDisplayName"] = package.DisplayName;
                reportedProperties["ApplicationName"]        = packageId.Name;
                reportedProperties["ApplicationVersion"]     = string.Format($"{version.Major}.{version.Minor}.{version.Build}.{version.Revision}");

                // Unique identifier from the hardware
                SystemIdentificationInfo systemIdentificationInfo = SystemIdentification.GetSystemIdForPublisher();
                using (DataReader reader = DataReader.FromBuffer(systemIdentificationInfo.Id))
                {
                    byte[] bytes = new byte[systemIdentificationInfo.Id.Length];
                    reader.ReadBytes(bytes);
                    reportedProperties["SystemId"] = BitConverter.ToString(bytes);
                }

                azureIoTHubClient.UpdateReportedPropertiesAsync(reportedProperties).Wait();
            }
            catch (Exception ex)
            {
                Debug.Print($"Azure IoT Hub device twin configuration retrieval failed:{ex.Message}");
                return;
            }

            try
            {
                deviceTwin = azureIoTHubClient.GetTwinAsync().Result;
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Azure IoT Hub device twin configuration retrieval failed:{ex.Message}");
                return;
            }

            try
            {
                if (deviceTwin.Properties.Desired.Contains("TimerDue"))
                {
                    timerDue = TimeSpan.Parse(deviceTwin.Properties.Desired["TimerDue"].ToString());
                }

                if (deviceTwin.Properties.Desired.Contains("TimerPeriod"))
                {
                    timerPeriod = TimeSpan.Parse(deviceTwin.Properties.Desired["TimerPeriod"].ToString());
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Sensor due or period configuration retrieval failed using default:{ex.Message}");
                return;
            }

            bme280InputPollingTimer = new Timer(SensorUpdateTimerCallback, null, timerDue, timerPeriod);

            // enable task to continue running in background
            backgroundTaskDeferral = taskInstance.GetDeferral();
        }
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            DeviceRegistrationResult result;

            try
            {
                bme280Sensor = new BME280(0x76);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"BME280 Initialisation failed:{ex.Message}");

                return;
            }

            try
            {
                using (var security = new SecurityProviderTpmHsm(RegistrationId))
                    using (var transport = new ProvisioningTransportHandlerHttp())
                    {
                        string base64EK = Convert.ToBase64String(security.GetEndorsementKey());

                        ProvisioningDeviceClient provClient = ProvisioningDeviceClient.Create(GlobalDeviceEndpoint, IdScope, security, transport);

                        result = provClient.RegisterAsync().ConfigureAwait(false).GetAwaiter().GetResult();

                        IAuthenticationMethod auth = new DeviceAuthenticationWithTpm(result.DeviceId, security);

                        azureIoTHubClient = DeviceClient.Create(result.AssignedHub, auth, TransportType.Mqtt);
                    }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"DeviceClient.Create with TPM info failed:{ex.Message}");
                return;
            }

            try
            {
                azureIoTHubClient.SetMethodHandlerAsync("Restart", RestartAsync, null);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Azure IoT Hub device method handler configuration failed:{ex.Message}");
                return;
            }

            try
            {
                TwinCollection reportedProperties;
                reportedProperties = new TwinCollection();

                // This is from the OS
                reportedProperties["Timezone"]    = TimeZoneSettings.CurrentTimeZoneDisplayName;
                reportedProperties["OSVersion"]   = Environment.OSVersion.VersionString;
                reportedProperties["MachineName"] = Environment.MachineName;

                // This is from the application manifest
                Package        package   = Package.Current;
                PackageId      packageId = package.Id;
                PackageVersion version   = packageId.Version;
                reportedProperties["ApplicationDisplayName"] = package.DisplayName;
                reportedProperties["ApplicationName"]        = packageId.Name;
                reportedProperties["ApplicationVersion"]     = string.Format($"{version.Major}.{version.Minor}.{version.Build}.{version.Revision}");

                // Unique identifier from the hardware
                SystemIdentificationInfo systemIdentificationInfo = SystemIdentification.GetSystemIdForPublisher();
                using (DataReader reader = DataReader.FromBuffer(systemIdentificationInfo.Id))
                {
                    byte[] bytes = new byte[systemIdentificationInfo.Id.Length];
                    reader.ReadBytes(bytes);
                    reportedProperties["SystemId"] = BitConverter.ToString(bytes);
                }

                azureIoTHubClient.UpdateReportedPropertiesAsync(reportedProperties).Wait();
            }
            catch (Exception ex)
            {
                Debug.Print($"Azure IoT Hub device twin configuration retrieval failed:{ex.Message}");
                return;
            }

            try
            {
                deviceTwin = azureIoTHubClient.GetTwinAsync().Result;
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Azure IoT Hub device twin configuration retrieval failed:{ex.Message}");
                return;
            }

            try
            {
                if (deviceTwin.Properties.Desired.Contains("TimerDue"))
                {
                    timerDue = TimeSpan.Parse(deviceTwin.Properties.Desired["TimerDue"].ToString());
                }

                if (deviceTwin.Properties.Desired.Contains("TimerPeriod"))
                {
                    timerPeriod = TimeSpan.Parse(deviceTwin.Properties.Desired["TimerPeriod"].ToString());
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Sensor due or period configuration retrieval failed using default:{ex.Message}");
                return;
            }

            bme280InputPollingTimer = new Timer(SensorUpdateTimerCallback, null, timerDue, timerPeriod);

            //enable task to continue running in background
            backgroundTaskDeferral = taskInstance.GetDeferral();
        }
        public async System.Threading.Tasks.Task <ActionResult <IEnumerable <string> > > GetAsync()
        {
            try
            {
                Pi.Init <BootstrapWiringPi>();

                var pinrelayR1 = 26;
                var pinrelayR2 = 20;
                var pinrelayR3 = 21;
                var delay      = 500;

                if (_IsRelayOn)
                {
                    Pi.Gpio[pinrelayR1].PinMode = GpioPinDriveMode.Output;
                    System.Threading.Thread.Sleep(delay);
                    Pi.Gpio[pinrelayR2].PinMode = GpioPinDriveMode.Output;
                    System.Threading.Thread.Sleep(delay);
                    Pi.Gpio[pinrelayR3].PinMode = GpioPinDriveMode.Output;
                    System.Threading.Thread.Sleep(delay);
                }

                AgriData agriData = new AgriData();

                //bme280
                if (_IsBME280On)
                {
                    BME280 bme280 = new BME280();
                    Console.WriteLine("0aa");
                    await bme280.InitializeAsync();

                    agriData.Temperature = await bme280.ReadTemperatureAsync();

                    agriData.Humidity = await bme280.ReadHumidityAsync();

                    agriData.Pressure = await bme280.ReadPreasureAsync();

                    agriData.Date = DateTime.Now;
                    Console.WriteLine("0b");
                    var MeasurementTemperature = _context.Measurements
                                                 .Where(s => s.Relay.RelayName == "Relay1")
                                                 .SingleOrDefault(s => s.Name == "Temperature");
                    var MeasurementHumidity = _context.Measurements
                                              .Where(s => s.Relay.RelayName == "Relay1")
                                              .SingleOrDefault(s => s.Name == "Humidity");
                    var MeasurementPressure = _context.Measurements
                                              .Where(s => s.Relay.RelayName == "Relay1")
                                              .SingleOrDefault(s => s.Name == "Pressure");
                    Console.WriteLine("0c");
                    MeasurementsValues mvTemperature = new MeasurementsValues()
                    {
                        Measurement = MeasurementTemperature,
                        Value       = agriData.Temperature,
                        DateTime    = agriData.Date,
                    };
                    MeasurementsValues mvHumidity = new MeasurementsValues()
                    {
                        Measurement = MeasurementHumidity,
                        Value       = agriData.Humidity,
                        DateTime    = agriData.Date
                    };
                    MeasurementsValues mvPressure = new MeasurementsValues()
                    {
                        Measurement = MeasurementPressure,
                        Value       = agriData.Pressure,
                        DateTime    = agriData.Date
                    };
                    Console.WriteLine("0a");
                    _context.Add(mvTemperature);
                    _context.Add(mvHumidity);
                    _context.Add(mvPressure);
                    _context.SaveChanges();
                }
                Console.WriteLine("1");
                //SoilMoisture
                if (_IsSoilMoistureOn)
                {
                    Pi.Spi.Channel0Frequency = SpiChannel.MinFrequency;

                    byte[] response = new byte[3];
                    byte[] request  = new byte[3] {
                        0x01, 0x80, 0
                    };
                    response = Pi.Spi.Channel0.SendReceive(request);

                    int result = 0;
                    result   = response[1] & 0x03;
                    result <<= 8;
                    result  += response[2];

                    double moisture_percentage = (100 - ((result / 1023.00) * 100));
                    agriData.SoilMoisture = moisture_percentage;

                    var MeasurementSoilMoisture = _context.Measurements
                                                  .Where(s => s.Relay.RelayName == "Relay1")
                                                  .SingleOrDefault(s => s.Name == "SoilMoisture");

                    MeasurementsValues mvSoilMoisture = new MeasurementsValues()
                    {
                        Measurement = MeasurementSoilMoisture,
                        Value       = Convert.ToSingle(agriData.SoilMoisture), //for float
                        DateTime    = agriData.Date
                    };
                    Console.WriteLine("0an");
                    _context.Add(mvSoilMoisture);
                    _context.SaveChanges();
                }
                Console.WriteLine("2");
                //lum
                if (_IsLumOn)
                {
                    var readBuffer = new byte[2];

                    var lumDevice = Pi.I2C.AddDevice(0x23);

                    lumDevice.Write(0x23);

                    for (var i = 0; i < readBuffer.Length; i++)
                    {
                        readBuffer[i] = lumDevice.Read();
                    }

                    var lightLevel = -1.1;

                    lightLevel = readBuffer[0] << 8 | readBuffer[1];
                    Console.WriteLine("Lum ReadBuffer:" + readBuffer);
                    agriData.Lum = lightLevel / 1.2;

                    //Select From Database
                    var MeasurementLum = _context.Measurements
                                         .Where(s => s.Relay.RelayName == "Relay1")
                                         .SingleOrDefault(s => s.Name == "Lum");

                    MeasurementsValues mvLum = new MeasurementsValues()
                    {
                        Measurement = MeasurementLum,
                        Value       = Convert.ToSingle(agriData.Lum), //for float
                        DateTime    = agriData.Date
                    };
                    Console.WriteLine("Lum:" + lightLevel);
                    _context.Add(mvLum);
                    _context.SaveChanges();
                }
                Console.WriteLine("3");
                //Pi.Gpio[pinrelay].PinMode = GpioPinDriveMode.Output;
                //System.Threading.Thread.Sleep(delay);
                if (_IsRelayOn)
                {
                    #region RELAY1

                    //ForRelay1

                    var entity1R1 = _context.RulesForRelays
                                    .Where(s => s.Relay.RelayName == "Relay1")
                                    .ToList();
                    var getRelayR1 = _context.Relays
                                     .Where(s => s.RelayName == "Relay1").FirstOrDefault();

                    var getSoilMoistureR1 = _context.Measurements
                                            .Where(s => s.Relay == getRelayR1)
                                            .Where(s => s.Name == "SoilMoisture").FirstOrDefault();
                    var getLumR1 = _context.Measurements
                                   .Where(s => s.Relay == getRelayR1)
                                   .Where(s => s.Name == "Lum").FirstOrDefault();
                    var getTemperatureR1 = _context.Measurements
                                           .Where(s => s.Relay == getRelayR1)
                                           .Where(s => s.Name == "Temperature").FirstOrDefault();

                    var getPressureR1 = _context.Measurements
                                        .Where(s => s.Relay == getRelayR1)
                                        .Where(s => s.Name == "Pressure").FirstOrDefault();

                    var getHumidityR1 = _context.Measurements
                                        .Where(s => s.Relay == getRelayR1)
                                        .Where(s => s.Name == "Humidity").FirstOrDefault();

                    var findInentity1R1SoilMoisture = entity1R1.Any(s => s.Measurement == getSoilMoistureR1);
                    var findentity1R1Lum            = entity1R1.Any(s => s.Measurement == getLumR1);
                    var findentity1R1Temperature    = entity1R1.Any(s => s.Measurement == getTemperatureR1);
                    var findentity1R1Pressure       = entity1R1.Any(s => s.Measurement == getPressureR1);
                    var findentity1R1Humidity       = entity1R1.Any(s => s.Measurement == getHumidityR1);



                    if (findInentity1R1SoilMoisture)
                    {
                        var SoilMoistureDownLevelR1 = _context.Measurements
                                                      .Where(s => s.Relay == getRelayR1)
                                                      .SingleOrDefault(s => s.Name == "SoilMoisture").DownLevel;

                        var SoilMoistureUpLevelR1 = _context.Measurements
                                                    .Where(s => s.Relay == getRelayR1)
                                                    .SingleOrDefault(s => s.Name == "SoilMoisture").UpLevel;

                        if (agriData.SoilMoisture < SoilMoistureDownLevelR1)
                        {
                            StaticFunc._IsWateredSoilMoistureR1 = false;
                        }
                        if (agriData.SoilMoisture > SoilMoistureUpLevelR1)
                        {
                            StaticFunc._IsWateredSoilMoistureR1 = true;
                        }
                    }
                    else
                    {
                        StaticFunc._IsWateredSoilMoistureR1 = false;
                    }

                    if (findentity1R1Lum)
                    {
                        var LumDownLevelR1 = _context.Measurements
                                             .Where(s => s.Relay == getRelayR1)
                                             .SingleOrDefault(s => s.Name == "Lum").DownLevel;

                        var LumUpLevelR1 = _context.Measurements
                                           .Where(s => s.Relay == getRelayR1)
                                           .SingleOrDefault(s => s.Name == "Lum").UpLevel;

                        if (agriData.Lum < LumDownLevelR1)
                        {
                            StaticFunc._IsWateredLumR1 = false;
                        }
                        if (agriData.Lum > LumUpLevelR1)
                        {
                            StaticFunc._IsWateredLumR1 = true;
                        }
                    }
                    else
                    {
                        StaticFunc._IsWateredLumR1 = false;
                    }

                    if (findentity1R1Temperature)
                    {
                        var TemperatureDownLevelR1 = _context.Measurements
                                                     .Where(s => s.Relay == getRelayR1)
                                                     .SingleOrDefault(s => s.Name == "Temperature").DownLevel;

                        var TemperatureUpLevelR1 = _context.Measurements
                                                   .Where(s => s.Relay == getRelayR1)
                                                   .SingleOrDefault(s => s.Name == "Temperature").UpLevel;

                        if (agriData.Temperature < TemperatureDownLevelR1)
                        {
                            StaticFunc._IsWateredTemperatureR1 = false;
                        }
                        if (agriData.Temperature > TemperatureUpLevelR1)
                        {
                            StaticFunc._IsWateredTemperatureR1 = true;
                        }
                    }
                    else
                    {
                        StaticFunc._IsWateredTemperatureR1 = false;
                    }

                    if (findentity1R1Pressure)
                    {
                        var PressureDownLevelR1 = _context.Measurements
                                                  .Where(s => s.Relay == getRelayR1)
                                                  .SingleOrDefault(s => s.Name == "Pressure").DownLevel;

                        var PressureUpLevelR1 = _context.Measurements
                                                .Where(s => s.Relay == getRelayR1)
                                                .SingleOrDefault(s => s.Name == "Pressure").UpLevel;

                        if (agriData.Pressure < PressureDownLevelR1)
                        {
                            StaticFunc._IsWateredPressureR1 = false;
                        }
                        if (agriData.Pressure > PressureUpLevelR1)
                        {
                            StaticFunc._IsWateredPressureR1 = true;
                        }
                    }
                    else
                    {
                        StaticFunc._IsWateredPressureR1 = false;
                    }

                    if (findentity1R1Humidity)
                    {
                        var HumidityDownLevelR1 = _context.Measurements
                                                  .Where(s => s.Relay == getRelayR1)
                                                  .SingleOrDefault(s => s.Name == "Humidity").DownLevel;

                        var HumidityUpLevelR1 = _context.Measurements
                                                .Where(s => s.Relay == getRelayR1)
                                                .SingleOrDefault(s => s.Name == "Humidity").UpLevel;

                        if (agriData.Humidity < HumidityDownLevelR1)
                        {
                            StaticFunc._IsWateredHumidityR1 = false;
                        }
                        if (agriData.Humidity > HumidityUpLevelR1)
                        {
                            StaticFunc._IsWateredHumidityR1 = true;
                        }
                    }
                    else
                    {
                        StaticFunc._IsWateredHumidityR1 = false;
                    }

                    //if (agriData.SoilMoisture < SoilMoistureDownLevel && agriData.Lum < LumDownLevel && StaticFunc._firstTime==1)
                    //{
                    //    StaticFunc._IsWatered = false;
                    //}
                    //if (agriData.SoilMoisture > SoilMoistureUpLevel)
                    //{
                    //    StaticFunc._IsWatered = true;
                    //}

                    //if (StaticFunc._IsWatered == false)
                    //{
                    //    Pi.Gpio[pinrelay].Write(false); // Relay On
                    //    System.Threading.Thread.Sleep(delay);
                    //    agriData.IsRelayOnNotification= StaticFunc._IsRelayNotificaton = true;
                    //}
                    //else
                    //{
                    //    Pi.Gpio[pinrelay].Write(true); // Relay Off
                    //    System.Threading.Thread.Sleep(delay);
                    //    agriData.IsRelayOnNotification = StaticFunc._IsRelayNotificaton = false;
                    //}


                    if (StaticFunc._IsWateredSoilMoistureR1 == false &&
                        StaticFunc._IsWateredLumR1 == false &&
                        StaticFunc._IsWateredTemperatureR1 == false &&
                        StaticFunc._IsWateredPressureR1 == false &&
                        StaticFunc._IsWateredHumidityR1 == false)
                    {
                        Pi.Gpio[pinrelayR1].Write(false); // Relay On
                        System.Threading.Thread.Sleep(delay);
                        agriData.IsRelayOnNotification = StaticFunc._IsRelayNotificaton = true;
                        agriData.IsR1On = true;
                    }
                    else
                    {
                        Pi.Gpio[pinrelayR1].Write(true); // Relay Off
                        System.Threading.Thread.Sleep(delay);
                        agriData.IsRelayOnNotification = StaticFunc._IsRelayNotificaton = false;
                        agriData.IsR1On = false;
                    }

                    StaticFunc._firstTime = 1;


                    #endregion RELAY1

                    #region RELAY2

                    //ForRelay1

                    var entity1R2 = _context.RulesForRelays
                                    .Where(s => s.Relay.RelayName == "Relay2")
                                    .ToList();

                    var getRelayR2 = _context.Relays
                                     .Where(s => s.RelayName == "Relay2").FirstOrDefault();

                    var getSoilMoistureR2 = _context.Measurements
                                            .Where(s => s.Relay == getRelayR2)
                                            .Where(s => s.Name == "SoilMoisture").FirstOrDefault();
                    var getLumR2 = _context.Measurements
                                   .Where(s => s.Relay == getRelayR2)
                                   .Where(s => s.Name == "Lum").FirstOrDefault();
                    var getTemperatureR2 = _context.Measurements
                                           .Where(s => s.Relay == getRelayR2)
                                           .Where(s => s.Name == "Temperature").FirstOrDefault();

                    var getPressureR2 = _context.Measurements
                                        .Where(s => s.Relay == getRelayR2)
                                        .Where(s => s.Name == "Pressure").FirstOrDefault();

                    var getHumidityR2 = _context.Measurements
                                        .Where(s => s.Relay == getRelayR2)
                                        .Where(s => s.Name == "Humidity").FirstOrDefault();

                    var findInentity1R2SoilMoisture = entity1R2.Any(s => s.Measurement == getSoilMoistureR2);
                    var findentity1R2Lum            = entity1R2.Any(s => s.Measurement == getLumR2);
                    var findentity1R2Temperature    = entity1R2.Any(s => s.Measurement == getTemperatureR2);
                    var findentity1R2Pressure       = entity1R2.Any(s => s.Measurement == getPressureR2);
                    var findentity1R2Humidity       = entity1R2.Any(s => s.Measurement == getHumidityR2);

                    if (findInentity1R2SoilMoisture)
                    {
                        var SoilMoistureDownLevelR2 = _context.Measurements
                                                      .Where(s => s.Relay == getRelayR2)
                                                      .SingleOrDefault(s => s.Name == "SoilMoisture").DownLevel;

                        var SoilMoistureUpLevelR2 = _context.Measurements
                                                    .Where(s => s.Relay == getRelayR2)
                                                    .SingleOrDefault(s => s.Name == "SoilMoisture").UpLevel;

                        if (agriData.SoilMoisture < SoilMoistureDownLevelR2)
                        {
                            StaticFunc._IsWateredSoilMoistureR2 = false;
                        }
                        if (agriData.SoilMoisture > SoilMoistureUpLevelR2)
                        {
                            StaticFunc._IsWateredSoilMoistureR2 = true;
                        }
                    }
                    else
                    {
                        StaticFunc._IsWateredSoilMoistureR2 = false;
                    }

                    if (findentity1R2Lum)
                    {
                        var LumDownLevelR2 = _context.Measurements
                                             .Where(s => s.Relay == getRelayR2)
                                             .SingleOrDefault(s => s.Name == "Lum").DownLevel;

                        var LumUpLevelR2 = _context.Measurements
                                           .Where(s => s.Relay == getRelayR2)
                                           .SingleOrDefault(s => s.Name == "Lum").UpLevel;

                        if (agriData.Lum < LumDownLevelR2)
                        {
                            StaticFunc._IsWateredLumR2 = false;
                        }
                        if (agriData.Lum > LumUpLevelR2)
                        {
                            StaticFunc._IsWateredLumR2 = true;
                        }
                    }
                    else
                    {
                        StaticFunc._IsWateredLumR2 = false;
                    }

                    if (findentity1R2Temperature)
                    {
                        var TemperatureDownLevelR2 = _context.Measurements
                                                     .Where(s => s.Relay == getRelayR2)
                                                     .SingleOrDefault(s => s.Name == "Temperature").DownLevel;

                        var TemperatureUpLevelR2 = _context.Measurements
                                                   .Where(s => s.Relay == getRelayR2)
                                                   .SingleOrDefault(s => s.Name == "Temperature").UpLevel;

                        if (agriData.Temperature < TemperatureDownLevelR2)
                        {
                            StaticFunc._IsWateredTemperatureR2 = false;
                        }
                        if (agriData.Temperature > TemperatureUpLevelR2)
                        {
                            StaticFunc._IsWateredTemperatureR2 = true;
                        }
                    }
                    else
                    {
                        StaticFunc._IsWateredTemperatureR2 = false;
                    }

                    if (findentity1R2Pressure)
                    {
                        var PressureDownLevelR2 = _context.Measurements
                                                  .Where(s => s.Relay == getRelayR2)
                                                  .SingleOrDefault(s => s.Name == "Pressure").DownLevel;

                        var PressureUpLevelR2 = _context.Measurements
                                                .Where(s => s.Relay == getRelayR2)
                                                .SingleOrDefault(s => s.Name == "Pressure").UpLevel;

                        if (agriData.Pressure < PressureDownLevelR2)
                        {
                            StaticFunc._IsWateredPressureR2 = false;
                        }
                        if (agriData.Pressure > PressureUpLevelR2)
                        {
                            StaticFunc._IsWateredPressureR2 = true;
                        }
                    }
                    else
                    {
                        StaticFunc._IsWateredPressureR2 = false;
                    }

                    if (findentity1R2Humidity)
                    {
                        var HumidityDownLevelR2 = _context.Measurements
                                                  .Where(s => s.Relay == getRelayR2)
                                                  .SingleOrDefault(s => s.Name == "Humidity").DownLevel;

                        var HumidityUpLevelR2 = _context.Measurements
                                                .Where(s => s.Relay == getRelayR2)
                                                .SingleOrDefault(s => s.Name == "Humidity").UpLevel;

                        Console.WriteLine($"HumiditySensor: {agriData.Humidity}");


                        Console.WriteLine($"HumidityDownLevel: {HumidityDownLevelR2}");
                        Console.WriteLine($"HumidityUpLevel: {HumidityUpLevelR2}");

                        if (agriData.Humidity < HumidityDownLevelR2)
                        {
                            StaticFunc._IsWateredHumidityR2 = false;
                        }
                        if (agriData.Humidity > HumidityUpLevelR2)
                        {
                            StaticFunc._IsWateredHumidityR2 = true;
                        }
                    }
                    else
                    {
                        StaticFunc._IsWateredHumidityR2 = false;
                    }

                    //if (agriData.SoilMoisture < SoilMoistureDownLevel && agriData.Lum < LumDownLevel && StaticFunc._firstTime==1)
                    //{
                    //    StaticFunc._IsWatered = false;
                    //}
                    //if (agriData.SoilMoisture > SoilMoistureUpLevel)
                    //{
                    //    StaticFunc._IsWatered = true;
                    //}

                    //if (StaticFunc._IsWatered == false)
                    //{
                    //    Pi.Gpio[pinrelay].Write(false); // Relay On
                    //    System.Threading.Thread.Sleep(delay);
                    //    agriData.IsRelayOnNotification= StaticFunc._IsRelayNotificaton = true;
                    //}
                    //else
                    //{
                    //    Pi.Gpio[pinrelay].Write(true); // Relay Off
                    //    System.Threading.Thread.Sleep(delay);
                    //    agriData.IsRelayOnNotification = StaticFunc._IsRelayNotificaton = false;
                    //}

                    if (StaticFunc._IsWateredSoilMoistureR2 == false &&
                        StaticFunc._IsWateredLumR2 == false &&
                        StaticFunc._IsWateredTemperatureR2 == false &&
                        StaticFunc._IsWateredPressureR2 == false &&
                        StaticFunc._IsWateredHumidityR2 == false)
                    {
                        Pi.Gpio[pinrelayR2].Write(false); // Relay On
                        System.Threading.Thread.Sleep(delay);
                        agriData.IsRelayOnNotification = StaticFunc._IsRelayNotificaton = true;
                        agriData.IsR2On = true;
                    }
                    else
                    {
                        Pi.Gpio[pinrelayR2].Write(true); // Relay Off
                        System.Threading.Thread.Sleep(delay);
                        agriData.IsRelayOnNotification = StaticFunc._IsRelayNotificaton = false;
                        agriData.IsR2On = false;
                    }

                    StaticFunc._firstTime = 1;

                    #endregion RELAY2

                    #region RELAY3

                    //ForRelay1

                    var entity1R3 = _context.RulesForRelays
                                    .Where(s => s.Relay.RelayName == "Relay3")
                                    .ToList();
                    var getRelayR3 = _context.Relays
                                     .Where(s => s.RelayName == "Relay3").FirstOrDefault();

                    var getSoilMoistureR3 = _context.Measurements
                                            .Where(s => s.Relay == getRelayR3)
                                            .Where(s => s.Name == "SoilMoisture").FirstOrDefault();
                    var getLumR3 = _context.Measurements
                                   .Where(s => s.Relay == getRelayR3)
                                   .Where(s => s.Name == "Lum").FirstOrDefault();
                    var getTemperatureR3 = _context.Measurements
                                           .Where(s => s.Relay == getRelayR3)
                                           .Where(s => s.Name == "Temperature").FirstOrDefault();


                    var getPressureR3 = _context.Measurements
                                        .Where(s => s.Relay == getRelayR3)
                                        .Where(s => s.Name == "Pressure").FirstOrDefault();

                    var getHumidityR3 = _context.Measurements
                                        .Where(s => s.Relay == getRelayR3)
                                        .Where(s => s.Name == "Humidity").FirstOrDefault();

                    var findentity1R3Pressure = entity1R3.Any(s => s.Measurement == getPressureR3);
                    var findentity1R3Humidity = entity1R3.Any(s => s.Measurement == getHumidityR3);



                    var findInentity1R3SoilMoisture = entity1R3.Any(s => s.Measurement == getSoilMoistureR3);
                    var findentity1R3Lum            = entity1R3.Any(s => s.Measurement == getLumR3);
                    var findentity1R3Temperature    = entity1R3.Any(s => s.Measurement == getTemperatureR3);

                    if (findInentity1R3SoilMoisture)
                    {
                        var SoilMoistureDownLevelR3 = _context.Measurements
                                                      .Where(s => s.Relay == getRelayR3)
                                                      .SingleOrDefault(s => s.Name == "SoilMoisture").DownLevel;

                        var SoilMoistureUpLevelR3 = _context.Measurements
                                                    .Where(s => s.Relay == getRelayR3)
                                                    .SingleOrDefault(s => s.Name == "SoilMoisture").UpLevel;

                        if (agriData.SoilMoisture < SoilMoistureDownLevelR3)
                        {
                            StaticFunc._IsWateredSoilMoistureR3 = false;
                        }
                        if (agriData.SoilMoisture > SoilMoistureUpLevelR3)
                        {
                            StaticFunc._IsWateredSoilMoistureR3 = true;
                        }
                    }
                    else
                    {
                        StaticFunc._IsWateredSoilMoistureR3 = false;
                    }

                    if (findentity1R3Lum)
                    {
                        var LumDownLevelR3 = _context.Measurements
                                             .Where(s => s.Relay == getRelayR3)
                                             .SingleOrDefault(s => s.Name == "Lum").DownLevel;

                        var LumUpLevelR3 = _context.Measurements
                                           .Where(s => s.Relay == getRelayR3)
                                           .SingleOrDefault(s => s.Name == "Lum").UpLevel;

                        if (agriData.Lum < LumDownLevelR3)
                        {
                            StaticFunc._IsWateredLumR3 = false;
                        }
                        if (agriData.Lum > LumUpLevelR3)
                        {
                            StaticFunc._IsWateredLumR3 = true;
                        }
                    }
                    else
                    {
                        StaticFunc._IsWateredLumR3 = false;
                    }

                    if (findentity1R3Temperature)
                    {
                        var TemperatureDownLevelR3 = _context.Measurements
                                                     .Where(s => s.Relay == getRelayR3)
                                                     .SingleOrDefault(s => s.Name == "Temperature").DownLevel;

                        var TemperatureUpLevelR3 = _context.Measurements
                                                   .Where(s => s.Relay == getRelayR3)
                                                   .SingleOrDefault(s => s.Name == "Temperature").UpLevel;

                        if (agriData.Temperature < TemperatureDownLevelR3)
                        {
                            StaticFunc._IsWateredTemperatureR3 = false;
                        }
                        if (agriData.Temperature > TemperatureUpLevelR3)
                        {
                            StaticFunc._IsWateredTemperatureR3 = true;
                        }
                    }
                    else
                    {
                        StaticFunc._IsWateredTemperatureR3 = false;
                    }

                    if (findentity1R3Pressure)
                    {
                        var PressureDownLevelR3 = _context.Measurements
                                                  .Where(s => s.Relay == getRelayR3)
                                                  .SingleOrDefault(s => s.Name == "Pressure").DownLevel;

                        var PressureUpLevelR3 = _context.Measurements
                                                .Where(s => s.Relay == getRelayR3)
                                                .SingleOrDefault(s => s.Name == "Pressure").UpLevel;

                        if (agriData.Pressure < PressureDownLevelR3)
                        {
                            StaticFunc._IsWateredPressureR3 = false;
                        }
                        if (agriData.Pressure > PressureUpLevelR3)
                        {
                            StaticFunc._IsWateredPressureR3 = true;
                        }
                    }
                    else
                    {
                        StaticFunc._IsWateredPressureR3 = false;
                    }

                    if (findentity1R3Humidity)
                    {
                        var HumidityDownLevelR3 = _context.Measurements
                                                  .Where(s => s.Relay == getRelayR3)
                                                  .SingleOrDefault(s => s.Name == "Humidity").DownLevel;

                        var HumidityUpLevelR3 = _context.Measurements
                                                .Where(s => s.Relay == getRelayR3)
                                                .SingleOrDefault(s => s.Name == "Humidity").UpLevel;

                        Console.WriteLine($"HumiditySensor: {agriData.Humidity}");


                        Console.WriteLine($"HumidityDownLevel: {HumidityDownLevelR3}");
                        Console.WriteLine($"HumidityUpLevel: {HumidityUpLevelR3}");

                        if (agriData.Humidity < HumidityDownLevelR3)
                        {
                            StaticFunc._IsWateredHumidityR3 = false;
                        }
                        if (agriData.Humidity > HumidityUpLevelR3)
                        {
                            StaticFunc._IsWateredHumidityR3 = true;
                        }
                    }
                    else
                    {
                        StaticFunc._IsWateredHumidityR3 = false;
                    }

                    //if (agriData.SoilMoisture < SoilMoistureDownLevel && agriData.Lum < LumDownLevel && StaticFunc._firstTime==1)
                    //{
                    //    StaticFunc._IsWatered = false;
                    //}
                    //if (agriData.SoilMoisture > SoilMoistureUpLevel)
                    //{
                    //    StaticFunc._IsWatered = true;
                    //}

                    //if (StaticFunc._IsWatered == false)
                    //{
                    //    Pi.Gpio[pinrelay].Write(false); // Relay On
                    //    System.Threading.Thread.Sleep(delay);
                    //    agriData.IsRelayOnNotification= StaticFunc._IsRelayNotificaton = true;
                    //}
                    //else
                    //{
                    //    Pi.Gpio[pinrelay].Write(true); // Relay Off
                    //    System.Threading.Thread.Sleep(delay);
                    //    agriData.IsRelayOnNotification = StaticFunc._IsRelayNotificaton = false;
                    //}

                    Console.WriteLine("R1");
                    Console.WriteLine("_IsWateredSoilMoistureR1=" + StaticFunc._IsWateredSoilMoistureR1);
                    Console.WriteLine("_IsWateredLumR1=" + StaticFunc._IsWateredLumR1);
                    Console.WriteLine("_IsWateredTemperatureR1=" + StaticFunc._IsWateredTemperatureR1);
                    Console.WriteLine("_IsWateredPressureR1=" + StaticFunc._IsWateredPressureR1);
                    Console.WriteLine("_IsWateredHumidityR1=" + StaticFunc._IsWateredHumidityR1);
                    Console.WriteLine("R2");
                    Console.WriteLine("_IsWateredSoilMoistureR2=" + StaticFunc._IsWateredSoilMoistureR2);
                    Console.WriteLine("_IsWateredLumR2=" + StaticFunc._IsWateredLumR2);
                    Console.WriteLine("_IsWateredTemperatureR2=" + StaticFunc._IsWateredTemperatureR2);
                    Console.WriteLine("_IsWateredPressureR1=" + StaticFunc._IsWateredPressureR2);
                    Console.WriteLine("_IsWateredHumidityR1=" + StaticFunc._IsWateredHumidityR2);
                    Console.WriteLine("R3");
                    Console.WriteLine("_IsWateredSoilMoistureR3=" + StaticFunc._IsWateredSoilMoistureR3);
                    Console.WriteLine("_IsWateredLumR3=" + StaticFunc._IsWateredLumR3);
                    Console.WriteLine("_IsWateredTemperatureR3=" + StaticFunc._IsWateredTemperatureR3);
                    Console.WriteLine("_IsWateredPressureR1=" + StaticFunc._IsWateredPressureR3);
                    Console.WriteLine("_IsWateredHumidityR1=" + StaticFunc._IsWateredHumidityR3);

                    if (StaticFunc._IsWateredSoilMoistureR3 == false &&
                        StaticFunc._IsWateredLumR3 == false &&
                        StaticFunc._IsWateredTemperatureR3 == false &&
                        StaticFunc._IsWateredPressureR3 == false &&
                        StaticFunc._IsWateredHumidityR3 == false)
                    {
                        Pi.Gpio[pinrelayR3].Write(false); // Relay On
                        System.Threading.Thread.Sleep(delay);
                        agriData.IsRelayOnNotification = StaticFunc._IsRelayNotificaton = true;
                        agriData.IsR3On = true;
                    }
                    else
                    {
                        Pi.Gpio[pinrelayR3].Write(true); // Relay Off
                        System.Threading.Thread.Sleep(delay);
                        agriData.IsRelayOnNotification = StaticFunc._IsRelayNotificaton = false;
                        agriData.IsR3On = false;
                    }

                    StaticFunc._firstTime = 1;


                    #endregion
                }

                Console.WriteLine("4");

                agriData.IsActive = true;

                return(Ok(agriData));
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Lathos:{ex.Message}");
                return(NotFound($"Lathos:{ex.Message}"));
            }
        }
예제 #23
0
 private void STVarChanged(Topic snd, TopicChanged p) {
   if(p.Visited(_owner, true)) {
     return;
   }
   for(int i=_drivers.Count-1; i>=0; i--) {
     if(_drivers[i].VarChanged(snd, p.Art==TopicChanged.ChangeArt.Remove)) {
       if(p.Art==TopicChanged.ChangeArt.Remove) {
         lock(_drivers) {
           _drivers.RemoveAt(i);
         }
       }
       return;
     }
   }
   if(p.Art==TopicChanged.ChangeArt.Remove) {
     return;
   }
   TWICommon drv=null;
   switch(snd.name) {
   case "LM75_T0":
   case "LM75_T1":
   case "LM75_T2":
   case "LM75_T3":
     drv=new LM75(snd);
     break;
   case "CC2D_T":
   case "CC2D_H":
     drv=new CC2D(snd);
     break;
   case "HIH61_T":
   case "HIH61_H":
     drv=new HIH61xx(snd);
     break;
   case "SI7020_T":
   case "SI7020_H":
     drv=new SI7020(snd);
     break;
   case "BMP180_T":
   case "BMP180_P":
     drv=new BMP180(snd);
     break;
   case "BME280_T":
   case "BME280_P":
   case "BME280_H":
     drv=new BME280(snd);
     break;
   case "BLINKM_8":
   case "BLINKM_9":
   case "BLINKM_10":
     drv=new Blinky(snd);
     break;
   case "BH1750_0":
   case "BH1750_1":
     drv=new BH1750(snd);
     break;
   case "EXP_0":
   case "EXP_1":
   case "EXP_2":
   case "EXP_3":
   case "EXP_4":
   case "EXP_5":
   case "EXP_6":
   case "EXP_7":
     drv=new Expander(snd);
     break;
   //case "SI1143":
   //  drv=new SI1143(snd);
   //  break;
   default:
     if(snd.name.Length>2 && snd.name.Length<6 && (snd.name.StartsWith("Sa") || snd.name.StartsWith("Ra"))) {
       drv=new RawDevice(snd);
     }
     break;
   }
   if(drv!=null) {
     lock(_drivers) {
       for(int i=_drivers.Count-1; i>=0; i--) {
         if(_drivers[i].VarChanged(snd, false)) {
           drv=null;
           break;
         }
       }
       if(drv!=null) {
         _drivers.Add(drv);
       }
     }
   }
 }
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            try
            {
                bme280Sensor = new BME280(0x76);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"BME280 Initialisation failed:{ex.Message}");

                return;
            }

            try
            {
                azureIoTHubClient = DeviceClient.CreateFromConnectionString(AzureIoTHubConnectionString, TransportType.Mqtt);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"CreateFromConnectionString failed:{ex.Message}");
                return;
            }

            try
            {
                azureIoTHubClient.SetMethodHandlerAsync("RestartDevice", RestartAsync, null);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Azure IoT Hub device Restart method handler configuration failed:{ex.Message}");
                return;
            }

            try
            {
                TwinCollection reportedProperties;
                reportedProperties = new TwinCollection();

                // This is from the OS
                reportedProperties["Timezone"]    = TimeZoneSettings.CurrentTimeZoneDisplayName;
                reportedProperties["OSVersion"]   = Environment.OSVersion.VersionString;
                reportedProperties["MachineName"] = Environment.MachineName;

                // This is from the application manifest
                Package        package   = Package.Current;
                PackageId      packageId = package.Id;
                PackageVersion version   = packageId.Version;
                reportedProperties["ApplicationDisplayName"] = package.DisplayName;
                reportedProperties["ApplicationName"]        = packageId.Name;
                reportedProperties["ApplicationVersion"]     = string.Format($"{version.Major}.{version.Minor}.{version.Build}.{version.Revision}");

                // Unique identifier from the hardware
                SystemIdentificationInfo systemIdentificationInfo = SystemIdentification.GetSystemIdForPublisher();
                using (DataReader reader = DataReader.FromBuffer(systemIdentificationInfo.Id))
                {
                    byte[] bytes = new byte[systemIdentificationInfo.Id.Length];
                    reader.ReadBytes(bytes);
                    reportedProperties["SystemId"] = BitConverter.ToString(bytes);
                }

                azureIoTHubClient.UpdateReportedPropertiesAsync(reportedProperties).Wait();
            }
            catch (Exception ex)
            {
                Debug.Print($"Azure IoT Hub device twin configuration retrieval failed:{ex.Message}");
                return;
            }

            try
            {
                deviceTwin = azureIoTHubClient.GetTwinAsync().Result;
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Azure IoT Hub device twin configuration retrieval failed:{ex.Message}");
                return;
            }

            try
            {
                if (deviceTwin.Properties.Desired.Contains("TimerDue"))
                {
                    timerDue = TimeSpan.Parse(deviceTwin.Properties.Desired["TimerDue"].ToString());
                }

                if (deviceTwin.Properties.Desired.Contains("TimerPeriod"))
                {
                    timerPeriod = TimeSpan.Parse(deviceTwin.Properties.Desired["TimerPeriod"].ToString());
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Sensor due or period configuration retrieval failed using default:{ex.Message}");
                return;
            }

            bme280InputPollingTimer = new Timer(SensorUpdateTimerCallback, null, timerDue, timerPeriod);

            backgroundTaskDeferral = taskInstance.GetDeferral();
        }