public SenseHatMeasurement Measure()
        {
            SenseHatMeasurement senseHatMeasurement = null;

            try
            {
                using (var settings = RTIMUSettings.CreateDefault())
                    using (var pressure = settings.CreatePressure())
                        using (var humidity = settings.CreateHumidity())
                        {
                            RTPressureData pressureReadResult = pressure.Read();

                            _logger.LogInformation($"Pressure valid: {pressureReadResult.PressureValid}");
                            _logger.LogInformation($"Pressure: {pressureReadResult.Pressure}");
                            _logger.LogInformation($"Temperature valid: {pressureReadResult.TemperatureValid}");
                            _logger.LogInformation($"Temperature: {pressureReadResult.Temperatur}");


                            RTHumidityData humidityReadResult = humidity.Read();
                            _logger.LogInformation($"Humidity valid: {humidityReadResult.HumidityValid}");
                            _logger.LogInformation($"Humidity: {humidityReadResult.Humidity}");
                            _logger.LogInformation($"Temperature valid: {humidityReadResult.TemperatureValid}");
                            _logger.LogInformation($"Temperature: {humidityReadResult.Temperatur}");
                            senseHatMeasurement = new SenseHatMeasurement(pressureReadResult, humidityReadResult);
                        }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
            }

            return(senseHatMeasurement);
        }
Esempio n. 2
0
        // private static string RoomName = "dining-room";
        // private static string RoomName = "kitchen";
        // private static string RoomName = "basement";

        static void Main(string[] args)
        {
            var sensorReadingIntervalMilliseconds = 1000;
            var readings = new HomeAutomationReadings();

            using (var settings = RTIMUSettings.CreateDefault())
            {
                while (true)
                {
                    var temperature = GetTemperatureReading(settings);
                    // var humidity = GetHumidityReading(settings);
                    // var pressure = GetPressureReading(settings);
                    // var garageDoor = GetGarageDoorReading();

                    readings.TemperatureReading.Value = temperature.value;
                    // readings.HumidityReading.Value = humidity.value;
                    // readings.PressureReading.Value = pressure.value;
                    // readings.GarageDoorReading.Value = garageDoor.value;


                    Console.WriteLine(JsonSerializer.Serialize(temperature));
                    // Console.WriteLine(JsonSerializer.Serialize(humidity));
                    // Console.WriteLine(JsonSerializer.Serialize(pressure));
                    // Console.WriteLine(JsonSerializer.Serialize(garageDoor));

                    Thread.Sleep(sensorReadingIntervalMilliseconds);
                }
            }
        }
Esempio n. 3
0
        // private static string RoomName = "dining-room";
        // private static string RoomName = "kitchen";
        // private static string RoomName = "basement";

        static void Main(string[] args)
        {
            var sensorReadingIntervalMilliseconds = 1000;
            var readings = new HomeAutomationReadings();

            var joystickEvents = Joystick.Events
                                 .Subscribe(p =>
            {
                if (p.Key == JoystickKey.Enter && p.State == JoystickKeyState.Release)
                {
                    IsGarageDoorOpen = !IsGarageDoorOpen;
                    if (IsGarageDoorOpen)
                    {
                        Console.WriteLine("Garage door is open");
                    }
                    else
                    {
                        Console.WriteLine("Garage door is closed");
                    }
                }
            });

            using (var settings = RTIMUSettings.CreateDefault())
            {
                while (true)
                {
                    var temperature = GetTemperatureReading(settings);
                    var humidity    = GetHumidityReading(settings);
                    var pressure    = GetPressureReading(settings);
                    var garageDoor  = GetGarageDoorReading();

                    readings.TemperatureReading.Value = temperature.value;
                    readings.HumidityReading.Value    = humidity.value;
                    readings.PressureReading.Value    = pressure.value;
                    readings.GarageDoorReading.Value  = garageDoor.value;

                    Console.WriteLine(JsonSerializer.Serialize(temperature));
                    Console.WriteLine(JsonSerializer.Serialize(humidity));
                    Console.WriteLine(JsonSerializer.Serialize(pressure));
                    Console.WriteLine(JsonSerializer.Serialize(garageDoor));

                    var pixelList = new List <CellColor>();

                    AddPixelsForReading(pixelList, readings.TemperatureReading.Quadrant, readings.TemperatureReading.GetColor());
                    AddPixelsForReading(pixelList, readings.HumidityReading.Quadrant, readings.HumidityReading.GetColor());
                    AddPixelsForReading(pixelList, readings.PressureReading.Quadrant, readings.PressureReading.GetColor());
                    AddPixelsForReading(pixelList, readings.GarageDoorReading.Quadrant, readings.GarageDoorReading.GetColor());

                    var immutablePixels = new Sense.Led.Pixels(ImmutableList.Create(pixelList.ToArray()));

                    Sense.Led.LedMatrix.SetPixels(immutablePixels);
                    Sense.Led.LedMatrix.SetLowLight(true);

                    Thread.Sleep(sensorReadingIntervalMilliseconds);
                }
            }
        }
Esempio n. 4
0
        static void Main(string[] args)
        {
            ConnectionMultiplexer redis           = ConnectionMultiplexer.Connect("localhost");
            var sensorReadingIntervalMilliseconds = 1000;

            readings = new HomeAutomationReadings();

            var joystickEvents = Joystick.Events
                                 .Subscribe(p =>
            {
                if (p.Key == JoystickKey.Enter && p.State == JoystickKeyState.Release)
                {
                    IsGarageDoorOpen = !IsGarageDoorOpen;
                    if (IsGarageDoorOpen)
                    {
                        Console.WriteLine("Garage door is open");
                    }
                    else
                    {
                        Console.WriteLine("Garage door is closed");
                    }
                }
            });


            redis
            .GetSubscriber()
            .Subscribe("incoming")
            .OnMessage(message => DisplaySensorReadings(message.Message));

            using (var settings = RTIMUSettings.CreateDefault())
            {
                while (true)
                {
                    var temperature = GetTemperatureReading(settings);
                    var humidity    = GetHumidityReading(settings);
                    var pressure    = GetPressureReading(settings);
                    var garageDoor  = GetGarageDoorReading();

                    readings.TemperatureReading.Value = temperature.value;
                    readings.HumidityReading.Value    = humidity.value;
                    readings.PressureReading.Value    = pressure.value;
                    readings.GarageDoorReading.Value  = garageDoor.value;

                    redis.GetSubscriber().Publish("outgoing", JsonSerializer.Serialize(temperature));
                    redis.GetSubscriber().Publish("outgoing", JsonSerializer.Serialize(humidity));
                    redis.GetSubscriber().Publish("outgoing", JsonSerializer.Serialize(pressure));
                    redis.GetSubscriber().Publish("outgoing", JsonSerializer.Serialize(garageDoor));

                    Thread.Sleep(sensorReadingIntervalMilliseconds);
                }
            }
        }
Esempio n. 5
0
        // private static string RoomName = "dining-room";
        // private static string RoomName = "kitchen";
        // private static string RoomName = "basement";

        static void Main(string[] args)
        {
            var sensorReadingIntervalMilliseconds = 1000;

            using (var settings = RTIMUSettings.CreateDefault())
            {
                while (true)
                {
                    // SENSOR LOGIC HERE

                    Thread.Sleep(sensorReadingIntervalMilliseconds);
                }
            }
        }
Esempio n. 6
0
 static async Task Main(string[] args)
 {
     var host = new HostBuilder()
                .ConfigureServices((hostContext, services) => {
         services.AddHostedService <RpiProbeHostedService>();
         services.AddSingleton <SerialPort>((_) => {
             var serialPort          = new SerialPort("/dev/ttyS0", 115200);
             serialPort.ReadTimeout  = 500;
             serialPort.WriteTimeout = 500;
             serialPort.NewLine      = "\r";
             serialPort.Open();
             return(serialPort);
         });
         services.AddTransient <GpsModuleStatusCommand>();
         services.AddTransient <GpsModuleCoordinatesCommand>();
         services.AddSingleton <RTIMUSettings>((_) => RTIMUSettings.CreateDefault());
         services.AddSingleton <RTIMU>((provider) => {
             var muSettings = provider.GetService <RTIMUSettings>();
             return(muSettings.CreateIMU());
         });
         services.AddSingleton <RTPressure>((provider) => {
             var muSettings = provider.GetService <RTIMUSettings>();
             return(muSettings.CreatePressure());
         });
         services.AddSingleton <RTHumidity>((provider) => {
             var muSettings = provider.GetService <RTIMUSettings>();
             return(muSettings.CreateHumidity());
         });
         services.AddTransient <SenseService>();
         services.AddTransient <ReportService>();
         services.AddSingleton <StatusReportService>();
         services.AddSingleton <TemperService>();
     })
                .ConfigureLogging(logConfig =>
     {
         logConfig.SetMinimumLevel(LogLevel.Information);
         logConfig.AddConsole();
     })
                .Build();
     await host.RunAsync();
 }
Esempio n. 7
0
        // private static string RoomName = "dining-room";
        // private static string RoomName = "kitchen";
        // private static string RoomName = "basement";

        static void Main(string[] args)
        {
            var sensorReadingIntervalMilliseconds = 1000;

            var joystickEvents = Joystick.Events
                                 .Subscribe(p =>
            {
                if (p.Key == JoystickKey.Enter && p.State == JoystickKeyState.Release)
                {
                    IsGarageDoorOpen = !IsGarageDoorOpen;
                    if (IsGarageDoorOpen)
                    {
                        Console.WriteLine("Garage door is open");
                    }
                    else
                    {
                        Console.WriteLine("Garage door is closed");
                    }
                }
            });

            using (var settings = RTIMUSettings.CreateDefault())
            {
                while (true)
                {
                    var temperature = GetTemperatureReading(settings);
                    var humidity    = GetHumidityReading(settings);
                    var pressure    = GetPressureReading(settings);
                    var garageDoor  = GetGarageDoorReading();

                    Console.WriteLine(JsonSerializer.Serialize(temperature));
                    Console.WriteLine(JsonSerializer.Serialize(humidity));
                    Console.WriteLine(JsonSerializer.Serialize(pressure));
                    Console.WriteLine(JsonSerializer.Serialize(garageDoor));

                    Thread.Sleep(sensorReadingIntervalMilliseconds);
                }
            }
        }
Esempio n. 8
0
        private static void TestRTIMULib()
        {
            using (var settings = RTIMUSettings.CreateDefault())
                using (var imu = settings.CreateIMU())
                    using (var pressure = settings.CreatePressure())
                        using (var humidity = settings.CreateHumidity())
                        {
                            while (true)
                            {
                                var imuData = imu.GetData();
                                Console.WriteLine($"Timestamp: {imuData.Timestamp:O}");
                                Console.WriteLine($"FusionPose: Valid: {imuData.FusionPoseValid}, Value: {imuData.FusionPose}");
                                Console.WriteLine($"FusionQPose: Valid: {imuData.FusionQPoseValid}, Value: {imuData.FusionQPose}");
                                Console.WriteLine($"Gyro: Valid: {imuData.GyroValid}, Value: {imuData.Gyro}");
                                Console.WriteLine($"Accel: Valid: {imuData.AccelValid}, Value: {imuData.Accel}");
                                Console.WriteLine($"Compass: Valid: {imuData.CompassValid}, Value: {imuData.Compass}");
                                Console.WriteLine();

                                var pressureReadResult = pressure.Read();
                                Console.WriteLine($"Pressure valid: {pressureReadResult.PressureValid}");
                                Console.WriteLine($"Pressure: {pressureReadResult.Pressure}");
                                Console.WriteLine($"Temperature valid: {pressureReadResult.TemperatureValid}");
                                Console.WriteLine($"Temperature: {pressureReadResult.Temperatur}");
                                Console.WriteLine();

                                var humidityReadResult = humidity.Read();
                                Console.WriteLine($"Humidity valid: {humidityReadResult.HumidityValid}");
                                Console.WriteLine($"Humidity: {humidityReadResult.Humidity}");
                                Console.WriteLine($"Temperature valid: {humidityReadResult.TemperatureValid}");
                                Console.WriteLine($"Temperature: {humidityReadResult.Temperatur}");

                                Console.WriteLine("===================================================");
                                Console.ReadLine();
                            }
                        }
        }
Esempio n. 9
0
        private static async void SendDeviceToCloudMessagesAsync()
        {
            Console.WriteLine("=== Serializing the Sensor Data to JSON format ===========");

            // Connect to the IoT hub using the MQTT protocol
            s_deviceClient = DeviceClient.CreateFromConnectionString(s_connectionString, TransportType.Mqtt);

            // Initial telemetry values
            double currentTemperature = 0;

            using (var settings = RTIMUSettings.CreateDefault())
                using (var imu = settings.CreateIMU())
                    using (var pressure = settings.CreatePressure())
                        using (var humidity = settings.CreateHumidity())

                            while (true)
                            {
                                var imuData            = imu.GetData();
                                var humidityReadResult = humidity.Read();
                                var pressureReadResult = pressure.Read();

                                // Display RAW sensor data
                                Console.WriteLine();
                                Console.WriteLine($"Timestamp: {imuData.Timestamp:O}");
                                Console.WriteLine($"FusionPose: {imuData.FusionPose}");
                                Console.WriteLine($"FusionQPose: {imuData.FusionQPose}");
                                Console.WriteLine($"Gyro: {imuData.Gyro}");
                                Console.WriteLine($"Accel: {imuData.Accel}");
                                Console.WriteLine($"Compass: {imuData.Compass}");
                                Console.WriteLine();
                                Console.WriteLine($"Pressure: {pressureReadResult.Pressure}");
                                Console.WriteLine($"Humidity: {humidityReadResult.Humidity}");
                                Console.WriteLine($"Temperature: {humidityReadResult.Temperatur}");

                                // Convert Celsius to Fahrenheit
                                currentTemperature = humidityReadResult.Temperatur * 1.8 + 32;

                                // Create JSON message
                                Telemetry telemetryRow = new Telemetry();
                                telemetryRow.DeviceId    = "<Your Raspberry Pi Device Name>"; // i.e. raspberrypi-det-01
                                telemetryRow.MessageId   = 314;
                                telemetryRow.CreatedDate = DateTime.UtcNow;
                                telemetryRow.Temperature = Math.Round(Convert.ToDecimal(currentTemperature), 2);
                                telemetryRow.Humidity    = Math.Round(Convert.ToDecimal(humidityReadResult.Humidity), 2);
                                telemetryRow.Pressure    = Math.Round(Convert.ToDecimal(pressureReadResult.Pressure), 2);

                                // Serialize sensor data to JSON format
                                string messageString = JsonConvert.SerializeObject(telemetryRow);

                                // Encode the characters into a sequence of bytes.
                                var message = new Message(Encoding.ASCII.GetBytes(messageString));

                                Console.WriteLine();
                                Console.WriteLine("=== Sending data to IoT Hub ==============================");

                                // Send the telemetry message
                                await s_deviceClient.SendEventAsync(message).ConfigureAwait(false);

                                Console.WriteLine($"=== {DateTime.Now}, {messageString}");
                                Console.WriteLine();

                                // Wait 5 secs
                                await Task.Delay(5000).ConfigureAwait(false);
                            }
        }
Esempio n. 10
0
        public async Task Run()
        {
            // runs loop to send telemetry

            // set up a callback for connection status change
            _client.SetConnectionStatusChangesHandler(ConnectionStatusChangeHandler);

            // set up callback for Desired Property update (Settings/Properties in IoT Central)
            await _client.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertyChangedAsync, null).ConfigureAwait(false);

            // set up callback for Methond (Command in IoT Central)
            await _client.SetMethodHandlerAsync("displayMessage", DisplayMessage, null).ConfigureAwait(false);

            Twin twin = await _client.GetTwinAsync().ConfigureAwait(false);

            Console.WriteLine("\r\nDevice Twin received:");
            Console.WriteLine($"{twin.ToJson(Newtonsoft.Json.Formatting.Indented)}");

            // Properties in IoT Central looks like this
            //   "properties": {
            //    "desired": {
            //      "isCelsius": {
            //        "value": true
            //      },
            //      "$version": 2
            //    },

            if (twin.Properties.Desired.Contains("isCelsius") && twin.Properties.Desired["isCelsius"]["value"] != null)
            {
                _bCelsius = twin.Properties.Desired["isCelsius"]["value"];

                // update reported properties to keep UI and device state in synch
                TwinCollection twinValue = new TwinCollection();
                twinValue["desiredVersion"] = twin.Properties.Desired["$version"];
                twinValue["statusCode"]     = 200;
                twinValue["value"]          = _bCelsius;

                TwinCollection reportedProperties = new TwinCollection();
                reportedProperties["isCelsius"] = twinValue;

                await _client.UpdateReportedPropertiesAsync(reportedProperties).ConfigureAwait(false);
            }

            if (_hasSenseHat)
            {
                // read sensor data from SenseHat
                using (var settings = RTIMUSettings.CreateDefault())
                    using (var imu = settings.CreateIMU())
                        using (var humidity = settings.CreateHumidity())
                            using (var pressure = settings.CreatePressure())
                            {
                                while (true)
                                {
                                    var imuData            = imu.GetData();
                                    var humidityReadResult = humidity.Read();

                                    if (humidityReadResult.HumidityValid && humidityReadResult.TemperatureValid)
                                    {
                                        string buffer;
                                        // format telemetry based on settings from Cloud
                                        if (_bCelsius)
                                        {
                                            buffer = $"{{\"humidity\":{humidityReadResult.Humidity:F2},\"tempC\":{humidityReadResult.Temperatur:F2}}}";
                                        }
                                        else
                                        {
                                            double fahrenheit = (humidityReadResult.Temperatur * 9 / 5) + 32;
                                            buffer = $"{{\"humidity\":{humidityReadResult.Humidity:F2},\"tempF\":{fahrenheit:F2}}}";
                                        }

                                        using (var telemetryMessage = new Message(Encoding.UTF8.GetBytes(buffer)))
                                        {
                                            Console.WriteLine($"Message Out : {buffer}");
                                            await _client.SendEventAsync(telemetryMessage).ConfigureAwait(false);
                                        }
                                    }
                                    else
                                    {
                                        Console.WriteLine("Err : Sensor data not valid");
                                    }

                                    await Task.Delay(3 * 1000);
                                }
                            }
            }
            else
            {
                // simulate sensor date
                string buffer;
                var    simulatorData = new SimulatorData
                {
                    TempCMax    = 36,
                    HumidityMax = 100,
                    TempC       = 30,
                    Humidity    = 40,
                };

                while (true)
                {
                    if (simulatorData.TempC > simulatorData.TempCMax)
                    {
                        simulatorData.TempC += Rnd.NextDouble() - 0.5; // add value between [-0.5..0.5]
                    }
                    else
                    {
                        simulatorData.TempC += -0.25 + (Rnd.NextDouble() * 1.5); // add value between [-0.25..1.25] - average +0.5
                    }

                    if (simulatorData.Humidity > simulatorData.HumidityMax)
                    {
                        simulatorData.Humidity += Rnd.NextDouble() - 0.5; // add value between [-0.5..0.5]
                    }
                    else
                    {
                        simulatorData.Humidity += -0.25 + (Rnd.NextDouble() * 1.5); // add value between [-0.25..1.25] - average +0.5
                    }

                    // format telemetry based on settings from Cloud
                    if (_bCelsius)
                    {
                        buffer = $"{{\"humidity\":{simulatorData.Humidity:F2},\"tempC\":{simulatorData.TempC:F2}}}";
                    }
                    else
                    {
                        double fahrenheit = (simulatorData.TempC * 9 / 5) + 32;
                        buffer = $"{{\"humidity\":{simulatorData.Humidity:F2},\"tempF\":{fahrenheit:F2}}}";
                    }

                    using (var telemetryMessage = new Message(Encoding.UTF8.GetBytes(buffer)))
                    {
                        Console.WriteLine($"Message Out : {buffer}");
                        await _client.SendEventAsync(telemetryMessage).ConfigureAwait(false);
                    }

                    await Task.Delay(3 * 1000);
                }
            }
        }