Ejemplo n.º 1
0
        /// <summary>
        /// Initializes the ModuleClient and sets up the callback to receive
        /// messages containing temperature information
        /// </summary>
        static async Task Init()
        {
            MqttTransportSettings mqttSetting = new MqttTransportSettings(TransportType.Mqtt_Tcp_Only);

            ITransportSettings[] settings = { mqttSetting };

            // Open a connection to the Edge runtime
            IoTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings);

            await IoTHubModuleClient.OpenAsync();

            Console.WriteLine("IoT Hub module client initialized.");

            // Register callback to be called when a message is received by the module
            //await ioTHubModuleClient.SetInputMessageHandlerAsync("input1", PipeMessage, ioTHubModuleClient);

            //initialize Raspberry
            _raspberryPins = new Pins();
            _raspberryPins.ConnectGpio();
            _raspberryPins.LoopGpioPins();

            _paradox1738 = new Paradox1738();
            _paradox1738.ParadoxSecurity();
            _paradox1738.IRSensorsReading();

            //Receive Netatmo data
            _receiveNetatmoData = new ReceiveNetatmoData();
            _receiveNetatmoData.ReceiveData();

            //read from ome temperature sensors
            _homeTemperature = new HomeTemperature();
            _homeTemperature.ReadTemperature();

            //Starting schedulers
            _co2Scheduler = new Co2();
            _co2Scheduler.CheckCo2Async();

            _saunaHeating = new SaunaHeating();
            _saunaHeating.CheckHeatingTime();

            _heatingScheduler = new Heating();
            _heatingScheduler.ReduceHeatingSchedulerAsync();

            //Receive IoTHub commands
            _receiveData = new ReceiveData();
            _receiveData.ReceiveCommandsAsync();

            //query WiFiProbes
            _wiFiProbes = new WiFiProbes();
            _wiFiProbes.QueryWiFiProbes();

            //shelly's
            TelemetryDataClass.isOutsideLightsOn = await Shelly.GetShellyState(Shelly.OutsideLight);

            SomeoneAtHome.CheckLightStatuses();

            //Send data to IoTHub
            _sendData = new SendTelemetryData();
            _sendData.SendTelemetryEventsAsync();
        }
        private async Task <MethodResponse> HomeEdgeDeviceManagement(MethodRequest methodRequest, object userContext)
        {
            ReceiveData   receiveData = new ReceiveData();
            List <string> command     = new List <string>();

            try
            {
                var HomeCommands = JsonDocument.Parse(methodRequest.DataAsJson).RootElement;
                if (HomeCommands.TryGetProperty("Ventilation", out JsonElement ventilation) && ventilation.GetBoolean() == !TelemetryDataClass.isVentilationOn)
                {
                    string cmd = ventilation.GetBoolean() ? CommandNames.OPEN_VENT : CommandNames.CLOSE_VENT;
                    command.Add(cmd);
                }
                if (HomeCommands.TryGetProperty("Sauna", out JsonElement sauna) && (sauna.GetBoolean() == !TelemetryDataClass.isSaunaOn))
                {
                    string cmd = sauna.GetBoolean() ? CommandNames.TURN_ON_SAUNA : CommandNames.TURN_OFF_SAUNA;
                    command.Add(cmd);
                }
                if (HomeCommands.TryGetProperty("Water", out JsonElement water) && water.GetBoolean() == !TelemetryDataClass.isWaterHeatingOn)
                {
                    string cmd = water.GetBoolean() ? CommandNames.TURN_ON_HOTWATERPUMP : CommandNames.TURN_OFF_HOTWATERPUMP;
                    command.Add(cmd);
                }
                if (HomeCommands.TryGetProperty("Heating", out JsonElement heating) && heating.GetBoolean() == !TelemetryDataClass.isHeatingOn)
                {
                    string cmd = heating.GetBoolean() ? CommandNames.TURN_ON_HEATING : CommandNames.TURN_OFF_HEATING;
                    command.Add(cmd);
                }
                if (HomeCommands.TryGetProperty("NormalTemp", out JsonElement normalTemp) && normalTemp.GetBoolean() == !TelemetryDataClass.isNormalHeating)
                {
                    string cmd = normalTemp.GetBoolean() ? CommandNames.NORMAL_TEMP_COMMAND : CommandNames.REDUCE_TEMP_COMMAND;
                    command.Add(cmd);
                }
                if (HomeCommands.TryGetProperty("Vacation", out JsonElement vacation) && vacation.GetBoolean() == !TelemetryDataClass.isHomeInVacation)
                {
                    string cmd = vacation.GetBoolean() ? CommandNames.TURN_ON_VACATION : CommandNames.TURN_OFF_VACATION;
                    SomeoneAtHome.IsSecurityManuallyOn = false; //if "vacation" is turned on or off then security is back in automatic mode
                    command.Add(cmd);
                }
                if (HomeCommands.TryGetProperty("Security", out JsonElement security) && security.GetBoolean() == !TelemetryDataClass.isHomeSecured)
                {
                    string cmd = security.GetBoolean() ? CommandNames.TURN_ON_SECURITY : CommandNames.TURN_OFF_SECURITY;
                    SomeoneAtHome.IsSecurityManuallyOn = true; //override automatic security, this can be turned off with "vacation" mode
                    command.Add(cmd);
                }
                if (HomeCommands.TryGetProperty("Temperatures", out JsonElement temperatures))
                {
                    //this data is coming from PowerApps
                    var    Temperatures = JsonSerializer.Deserialize <List <SensorReading> >(temperatures.GetRawText());
                    string jsonString   = JsonSerializer.Serialize(Temperatures);
                    var    filename     = Methods.GetFilePath(CONSTANT.FILENAME_ROOM_TEMPERATURES);
                    await Methods.SaveStringToLocalFile(filename, jsonString);

                    HomeTemperature.SetTemperatures(Temperatures);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Home device management: " + e.ToString());
            }

            foreach (string cmd in command)
            {
                if (cmd != null)
                {
                    receiveData.ProcessCommand(cmd);
                }
            }

            //This data goes back directly to PowerApps through Azure Functions
            var reportedProperties = new TwinCollection();

            reportedProperties["Ventilation"]          = TelemetryDataClass.isVentilationOn;
            reportedProperties["Water"]                = TelemetryDataClass.isWaterHeatingOn;
            reportedProperties["Heating"]              = TelemetryDataClass.isHeatingOn;
            reportedProperties["NormalTemp"]           = TelemetryDataClass.isNormalHeating;
            reportedProperties["Vacation"]             = TelemetryDataClass.isHomeInVacation;
            reportedProperties["VacationTime"]         = TelemetryDataClass.VacationTime.ToString("HH:mm dd.MM.yyyy");
            reportedProperties["Security"]             = TelemetryDataClass.isHomeSecured;
            reportedProperties["HomeSecuredTime"]      = TelemetryDataClass.HomeSecuredTime.ToString("HH:mm dd.MM.yyyy");
            reportedProperties["IsSecurityManuallyOn"] = SomeoneAtHome.IsSecurityManuallyOn;
            reportedProperties["Co2"]               = NetatmoDataClass.Co2;
            reportedProperties["Temperature"]       = NetatmoDataClass.Temperature;
            reportedProperties["Humidity"]          = NetatmoDataClass.Humidity;
            reportedProperties["TemperatureOut"]    = NetatmoDataClass.TemperatureOut;
            reportedProperties["BatteryPercent"]    = NetatmoDataClass.BatteryPercent;
            reportedProperties["isRoomHeatingNow"]  = Pins.IsRoomHeatingOn;
            reportedProperties["isWaterHeatingNow"] = Pins.IsWaterHeatingOn;
            reportedProperties["Sauna"]             = TelemetryDataClass.isSaunaOn;
            reportedProperties["isSaunaDoorOpen"]   = Pins.IsSaunaDoorOpen;
            reportedProperties["SaunaStartedTime"]  = TelemetryDataClass.SaunaStartedTime.ToString("HH:mm");
            reportedProperties["isSaunaHeatingNow"] = !(bool)Pins.PinRead(Pins.saunaHeatOutPin);
            reportedProperties["isSomeoneAtHome"]   = TelemetryDataClass.isSomeoneAtHome;
            reportedProperties["isOutsideLightsOn"] = TelemetryDataClass.isOutsideLightsOn;
            reportedProperties["isGarageLightsOn"]  = TelemetryDataClass.isGarageLightsOn;
            reportedProperties["isHomeDoorOpen"]    = TelemetryDataClass.isHomeDoorOpen;
            reportedProperties["Temperatures"]      = HomeTemperature.ListOfAllSensors.Temperatures;
            reportedProperties["Localdevices"]      = WiFiProbes.WiFiDevicesToPowerApps;

            var response = Encoding.ASCII.GetBytes(reportedProperties.ToJson());

            return(new MethodResponse(response, 200));
        }