From ac642ae5cd66d807e2317f33bc81f4520748ddf7 Mon Sep 17 00:00:00 2001 From: Christian Kratky Date: Sat, 16 Jul 2016 12:05:59 +0200 Subject: [PATCH 01/61] Fix project settings and bin directory. --- SDK/Api/HA4IoT.Api.AzureCloud/HA4IoT.Api.AzureCloud.csproj | 4 ++-- .../HA4IoT.Api.LocalRestServer.csproj | 6 +++--- SDK/Api/HA4IoT.Api/HA4IoT.Api.csproj | 4 ++-- .../HA4IoT.ExternalServices.OpenWeatherMap.csproj | 6 +++--- .../HA4IoT.ExternalServices.TelegramBot.csproj | 6 +++--- .../HA4IoT.ExternalServices.Twitter.csproj | 4 ++-- SDK/HA4IoT.Actuators/HA4IoT.Actuators.csproj | 6 +++--- SDK/HA4IoT.Actuators/Properties/HA4IoT.Actuators.rd.xml | 2 +- SDK/HA4IoT.Automations/HA4IoT.Automations.csproj | 4 ++-- SDK/HA4IoT.Components/HA4IoT.Components.csproj | 6 +++--- SDK/HA4IoT.Conditions/HA4IoT.Conditions.csproj | 4 ++-- SDK/HA4IoT.Configuration/HA4IoT.Configuration.csproj | 4 ++-- SDK/HA4IoT.Contracts/HA4IoT.Contracts.csproj | 6 +++--- SDK/HA4IoT.Core/HA4IoT.Core.csproj | 6 +++--- SDK/HA4IoT.Core/Properties/HA4IoT.Core.rd.xml | 2 +- SDK/HA4IoT.Logger/HA4IoT.Logger.csproj | 6 +++--- SDK/HA4IoT.Logger/Properties/HA4IoT.Notifications.rd.xml | 2 +- SDK/HA4IoT.Networking/HA4IoT.Networking.csproj | 6 +++--- SDK/HA4IoT.Networking/Properties/HA4IoT.Networking.rd.xml | 2 +- SDK/HA4IoT.PersonalAgent/HA4IoT.PersonalAgent.csproj | 4 ++-- SDK/HA4IoT.Sensors/HA4IoT.Sensors.csproj | 6 +++--- SDK/HA4IoT.Telemetry/HA4IoT.Telemetry.csproj | 6 +++--- SDK/HA4IoT.Telemetry/Properties/HA4IoT.Telemetry.rd.xml | 2 +- .../HA4IoT.Hardware.CCTools/HA4IoT.Hardware.CCTools.csproj | 4 ++-- .../Properties/HA4IoT.Hardware.CCTools.rd.xml | 2 +- .../HA4IoT.Hardware.I2CHardwareBridge.csproj | 6 +++--- .../Properties/HA4IoT.Hardware.I2CHardwareBridge.rd.xml | 2 +- SDK/Hardware/HA4IoT.Hardware.Knx/HA4IoT.Hardware.Knx.csproj | 6 +++--- SDK/Hardware/HA4IoT.Hardware.Pi2/HA4IoT.Hardware.Pi2.csproj | 6 +++--- .../Properties/HA4IoT.Hardware.Pi2.rd.xml | 2 +- .../HA4IoT.Hardware.PortExpanderDrivers.csproj | 6 +++--- .../Properties/HA4IoT.Hardware.PortExpanderDrivers.rd.xml | 2 +- .../HA4IoT.Hardware.RemoteSwitch.csproj | 6 +++--- .../Properties/HA4IoT.Hardware.RemoteSwitch.rd.xml | 2 +- SDK/Hardware/HA4IoT.Hardware/HA4IoT.Hardware.csproj | 6 +++--- .../HA4IoT.Hardware/Properties/HA4IoT.Hardware.rd.xml | 2 +- .../Properties/HA4IoT.Tests.Mockups.rd.xml | 2 +- 37 files changed, 79 insertions(+), 79 deletions(-) diff --git a/SDK/Api/HA4IoT.Api.AzureCloud/HA4IoT.Api.AzureCloud.csproj b/SDK/Api/HA4IoT.Api.AzureCloud/HA4IoT.Api.AzureCloud.csproj index 270dda2b..33cc31d2 100644 --- a/SDK/Api/HA4IoT.Api.AzureCloud/HA4IoT.Api.AzureCloud.csproj +++ b/SDK/Api/HA4IoT.Api.AzureCloud/HA4IoT.Api.AzureCloud.csproj @@ -39,7 +39,7 @@ x86 true - bin\x86\Debug\ + ..\..\bin\x86\ DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP ;2008 full @@ -61,7 +61,7 @@ ARM true - bin\ARM\Debug\ + ..\..\bin\ARM\ DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP ;2008 full diff --git a/SDK/Api/HA4IoT.Api.LocalHttpServer/HA4IoT.Api.LocalRestServer.csproj b/SDK/Api/HA4IoT.Api.LocalHttpServer/HA4IoT.Api.LocalRestServer.csproj index 23a95c94..1a4ea0a5 100644 --- a/SDK/Api/HA4IoT.Api.LocalHttpServer/HA4IoT.Api.LocalRestServer.csproj +++ b/SDK/Api/HA4IoT.Api.LocalHttpServer/HA4IoT.Api.LocalRestServer.csproj @@ -39,7 +39,7 @@ x86 true - bin\x86\Debug\ + ..\..\bin\x86\ DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP ;2008 full @@ -61,8 +61,8 @@ ARM true - bin\ARM\Debug\ - DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP + ..\..\bin\ARM\ + TRACE;DEBUG;..\bin\ARM ;2008 full ARM diff --git a/SDK/Api/HA4IoT.Api/HA4IoT.Api.csproj b/SDK/Api/HA4IoT.Api/HA4IoT.Api.csproj index c9034474..63040caa 100644 --- a/SDK/Api/HA4IoT.Api/HA4IoT.Api.csproj +++ b/SDK/Api/HA4IoT.Api/HA4IoT.Api.csproj @@ -39,7 +39,7 @@ x86 true - bin\x86\Debug\ + ..\..\bin\x86\ DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP ;2008 full @@ -61,7 +61,7 @@ ARM true - bin\ARM\Debug\ + ..\..\bin\ARM\ DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP ;2008 full diff --git a/SDK/ExternalServices/HA4IoT.ExternalServices.OpenWeatherMap/HA4IoT.ExternalServices.OpenWeatherMap.csproj b/SDK/ExternalServices/HA4IoT.ExternalServices.OpenWeatherMap/HA4IoT.ExternalServices.OpenWeatherMap.csproj index e249ac2a..e423324a 100644 --- a/SDK/ExternalServices/HA4IoT.ExternalServices.OpenWeatherMap/HA4IoT.ExternalServices.OpenWeatherMap.csproj +++ b/SDK/ExternalServices/HA4IoT.ExternalServices.OpenWeatherMap/HA4IoT.ExternalServices.OpenWeatherMap.csproj @@ -12,7 +12,7 @@ en-US UAP 10.0.10586.0 - 10.0.10240.0 + 10.0.10586.0 14 512 {A5A43C5B-DE2A-4C0C-9213-0A381AF9435A};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} @@ -39,7 +39,7 @@ x86 true - bin\x86\Debug\ + ..\..\bin\x86\ DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP ;2008 full @@ -61,7 +61,7 @@ ARM true - bin\ARM\Debug\ + ..\..\bin\ARM\ DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP ;2008 full diff --git a/SDK/ExternalServices/HA4IoT.ExternalServices.TelegramBot/HA4IoT.ExternalServices.TelegramBot.csproj b/SDK/ExternalServices/HA4IoT.ExternalServices.TelegramBot/HA4IoT.ExternalServices.TelegramBot.csproj index 3887d136..1c0c3c07 100644 --- a/SDK/ExternalServices/HA4IoT.ExternalServices.TelegramBot/HA4IoT.ExternalServices.TelegramBot.csproj +++ b/SDK/ExternalServices/HA4IoT.ExternalServices.TelegramBot/HA4IoT.ExternalServices.TelegramBot.csproj @@ -12,7 +12,7 @@ en-US UAP 10.0.10586.0 - 10.0.10240.0 + 10.0.10586.0 14 512 {A5A43C5B-DE2A-4C0C-9213-0A381AF9435A};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} @@ -39,7 +39,7 @@ x86 true - bin\x86\Debug\ + ..\..\bin\x86\ DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP ;2008 full @@ -61,7 +61,7 @@ ARM true - bin\ARM\Debug\ + ..\..\bin\ARM\ DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP ;2008 full diff --git a/SDK/ExternalServices/HA4IoT.ExternalServices.Twitter/HA4IoT.ExternalServices.Twitter.csproj b/SDK/ExternalServices/HA4IoT.ExternalServices.Twitter/HA4IoT.ExternalServices.Twitter.csproj index ad62bc50..528c5cec 100644 --- a/SDK/ExternalServices/HA4IoT.ExternalServices.Twitter/HA4IoT.ExternalServices.Twitter.csproj +++ b/SDK/ExternalServices/HA4IoT.ExternalServices.Twitter/HA4IoT.ExternalServices.Twitter.csproj @@ -39,7 +39,7 @@ x86 true - bin\x86\Debug\ + ..\..\bin\x86\ DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP ;2008 full @@ -61,7 +61,7 @@ ARM true - bin\ARM\Debug\ + ..\..\bin\ARM\ DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP ;2008 full diff --git a/SDK/HA4IoT.Actuators/HA4IoT.Actuators.csproj b/SDK/HA4IoT.Actuators/HA4IoT.Actuators.csproj index 7a0b51b2..1cafd4d0 100644 --- a/SDK/HA4IoT.Actuators/HA4IoT.Actuators.csproj +++ b/SDK/HA4IoT.Actuators/HA4IoT.Actuators.csproj @@ -39,7 +39,7 @@ ARM true - bin\ARM\Debug\ + ..\bin\ARM\ DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP ;2008 full @@ -88,7 +88,7 @@ x86 true - bin\x86\Debug\ + ..\bin\x86\ DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP ;2008 full @@ -149,7 +149,7 @@ - + diff --git a/SDK/HA4IoT.Actuators/Properties/HA4IoT.Actuators.rd.xml b/SDK/HA4IoT.Actuators/Properties/HA4IoT.Actuators.rd.xml index 4a7edc82..03017683 100644 --- a/SDK/HA4IoT.Actuators/Properties/HA4IoT.Actuators.rd.xml +++ b/SDK/HA4IoT.Actuators/Properties/HA4IoT.Actuators.rd.xml @@ -25,7 +25,7 @@ http://go.microsoft.com/fwlink/?LinkId=613100 --> - + diff --git a/SDK/HA4IoT.Automations/HA4IoT.Automations.csproj b/SDK/HA4IoT.Automations/HA4IoT.Automations.csproj index 40bd4f0c..9428c77b 100644 --- a/SDK/HA4IoT.Automations/HA4IoT.Automations.csproj +++ b/SDK/HA4IoT.Automations/HA4IoT.Automations.csproj @@ -39,7 +39,7 @@ x86 true - bin\x86\Debug\ + ..\bin\x86\ DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP ;2008 full @@ -61,7 +61,7 @@ ARM true - bin\ARM\Debug\ + ..\bin\ARM\ DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP ;2008 full diff --git a/SDK/HA4IoT.Components/HA4IoT.Components.csproj b/SDK/HA4IoT.Components/HA4IoT.Components.csproj index 91be3603..3208c586 100644 --- a/SDK/HA4IoT.Components/HA4IoT.Components.csproj +++ b/SDK/HA4IoT.Components/HA4IoT.Components.csproj @@ -12,7 +12,7 @@ en-US UAP 10.0.10586.0 - 10.0.10240.0 + 10.0.10586.0 14 512 {A5A43C5B-DE2A-4C0C-9213-0A381AF9435A};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} @@ -39,7 +39,7 @@ x86 true - bin\x86\Debug\ + ..\bin\x86\ DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP ;2008 full @@ -61,7 +61,7 @@ ARM true - bin\ARM\Debug\ + ..\bin\ARM\ DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP ;2008 full diff --git a/SDK/HA4IoT.Conditions/HA4IoT.Conditions.csproj b/SDK/HA4IoT.Conditions/HA4IoT.Conditions.csproj index 9cf48a45..1befa1c1 100644 --- a/SDK/HA4IoT.Conditions/HA4IoT.Conditions.csproj +++ b/SDK/HA4IoT.Conditions/HA4IoT.Conditions.csproj @@ -39,7 +39,7 @@ x86 true - bin\x86\Debug\ + ..\bin\x86\ DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP ;2008 full @@ -61,7 +61,7 @@ ARM true - bin\ARM\Debug\ + ..\bin\ARM\ DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP ;2008 full diff --git a/SDK/HA4IoT.Configuration/HA4IoT.Configuration.csproj b/SDK/HA4IoT.Configuration/HA4IoT.Configuration.csproj index e7bad2de..d10163d9 100644 --- a/SDK/HA4IoT.Configuration/HA4IoT.Configuration.csproj +++ b/SDK/HA4IoT.Configuration/HA4IoT.Configuration.csproj @@ -39,7 +39,7 @@ x86 true - bin\x86\Debug\ + ..\bin\x86\ DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP ;2008 full @@ -61,7 +61,7 @@ ARM true - bin\ARM\Debug\ + ..\bin\ARM\ DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP ;2008 full diff --git a/SDK/HA4IoT.Contracts/HA4IoT.Contracts.csproj b/SDK/HA4IoT.Contracts/HA4IoT.Contracts.csproj index 707e2e4b..f389de5c 100644 --- a/SDK/HA4IoT.Contracts/HA4IoT.Contracts.csproj +++ b/SDK/HA4IoT.Contracts/HA4IoT.Contracts.csproj @@ -39,7 +39,7 @@ ARM true - bin\ARM\Debug\ + ..\bin\ARM\ DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP ;2008 full @@ -83,7 +83,7 @@ x86 true - bin\x86\Debug\ + ..\bin\x86\ DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP ;2008 full @@ -236,7 +236,7 @@ - + 14.0 diff --git a/SDK/HA4IoT.Core/HA4IoT.Core.csproj b/SDK/HA4IoT.Core/HA4IoT.Core.csproj index d9123ead..c7dd10e1 100644 --- a/SDK/HA4IoT.Core/HA4IoT.Core.csproj +++ b/SDK/HA4IoT.Core/HA4IoT.Core.csproj @@ -39,7 +39,7 @@ ARM true - bin\ARM\Debug\ + ..\bin\ARM\ DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP ;2008 full @@ -88,7 +88,7 @@ x86 true - bin\x86\Debug\ + ..\bin\x86\ DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP ;2008 full @@ -136,7 +136,7 @@ - + diff --git a/SDK/HA4IoT.Core/Properties/HA4IoT.Core.rd.xml b/SDK/HA4IoT.Core/Properties/HA4IoT.Core.rd.xml index 487bc0b6..7e3dacba 100644 --- a/SDK/HA4IoT.Core/Properties/HA4IoT.Core.rd.xml +++ b/SDK/HA4IoT.Core/Properties/HA4IoT.Core.rd.xml @@ -25,7 +25,7 @@ http://go.microsoft.com/fwlink/?LinkId=613100 --> - + diff --git a/SDK/HA4IoT.Logger/HA4IoT.Logger.csproj b/SDK/HA4IoT.Logger/HA4IoT.Logger.csproj index 255c6e97..a949baca 100644 --- a/SDK/HA4IoT.Logger/HA4IoT.Logger.csproj +++ b/SDK/HA4IoT.Logger/HA4IoT.Logger.csproj @@ -39,7 +39,7 @@ ARM true - bin\ARM\Debug\ + ..\bin\ARM\ DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP ;2008 full @@ -88,7 +88,7 @@ x86 true - bin\x86\Debug\ + ..\bin\x86\ DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP ;2008 full @@ -118,7 +118,7 @@ - + diff --git a/SDK/HA4IoT.Logger/Properties/HA4IoT.Notifications.rd.xml b/SDK/HA4IoT.Logger/Properties/HA4IoT.Notifications.rd.xml index 00398852..f6a7c2d5 100644 --- a/SDK/HA4IoT.Logger/Properties/HA4IoT.Notifications.rd.xml +++ b/SDK/HA4IoT.Logger/Properties/HA4IoT.Notifications.rd.xml @@ -25,7 +25,7 @@ http://go.microsoft.com/fwlink/?LinkId=613100 --> - + diff --git a/SDK/HA4IoT.Networking/HA4IoT.Networking.csproj b/SDK/HA4IoT.Networking/HA4IoT.Networking.csproj index 6f91342b..9cb2cd8a 100644 --- a/SDK/HA4IoT.Networking/HA4IoT.Networking.csproj +++ b/SDK/HA4IoT.Networking/HA4IoT.Networking.csproj @@ -39,7 +39,7 @@ ARM true - bin\ARM\Debug\ + ..\bin\ARM\ DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP ;2008 full @@ -90,7 +90,7 @@ x86 true - bin\x86\Debug\ + ..\bin\x86\ DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP ;2008 full @@ -139,7 +139,7 @@ - + diff --git a/SDK/HA4IoT.Networking/Properties/HA4IoT.Networking.rd.xml b/SDK/HA4IoT.Networking/Properties/HA4IoT.Networking.rd.xml index 71578a99..48f341ef 100644 --- a/SDK/HA4IoT.Networking/Properties/HA4IoT.Networking.rd.xml +++ b/SDK/HA4IoT.Networking/Properties/HA4IoT.Networking.rd.xml @@ -25,7 +25,7 @@ http://go.microsoft.com/fwlink/?LinkId=613100 --> - + diff --git a/SDK/HA4IoT.PersonalAgent/HA4IoT.PersonalAgent.csproj b/SDK/HA4IoT.PersonalAgent/HA4IoT.PersonalAgent.csproj index ed122c9e..c0245c5a 100644 --- a/SDK/HA4IoT.PersonalAgent/HA4IoT.PersonalAgent.csproj +++ b/SDK/HA4IoT.PersonalAgent/HA4IoT.PersonalAgent.csproj @@ -39,7 +39,7 @@ x86 true - bin\x86\Debug\ + ..\bin\x86\ DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP ;2008 full @@ -61,7 +61,7 @@ ARM true - bin\ARM\Debug\ + ..\bin\ARM\ DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP ;2008 full diff --git a/SDK/HA4IoT.Sensors/HA4IoT.Sensors.csproj b/SDK/HA4IoT.Sensors/HA4IoT.Sensors.csproj index e5830db5..7360bb7b 100644 --- a/SDK/HA4IoT.Sensors/HA4IoT.Sensors.csproj +++ b/SDK/HA4IoT.Sensors/HA4IoT.Sensors.csproj @@ -12,7 +12,7 @@ en-US UAP 10.0.10586.0 - 10.0.10240.0 + 10.0.10586.0 14 512 {A5A43C5B-DE2A-4C0C-9213-0A381AF9435A};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} @@ -39,7 +39,7 @@ x86 true - bin\x86\Debug\ + ..\bin\x86\ DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP ;2008 full @@ -61,7 +61,7 @@ ARM true - bin\ARM\Debug\ + ..\bin\ARM\ DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP ;2008 full diff --git a/SDK/HA4IoT.Telemetry/HA4IoT.Telemetry.csproj b/SDK/HA4IoT.Telemetry/HA4IoT.Telemetry.csproj index a6030169..ad40f37d 100644 --- a/SDK/HA4IoT.Telemetry/HA4IoT.Telemetry.csproj +++ b/SDK/HA4IoT.Telemetry/HA4IoT.Telemetry.csproj @@ -39,7 +39,7 @@ ARM true - bin\ARM\Debug\ + ..\bin\ARM\ DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP ;2008 full @@ -87,7 +87,7 @@ x86 true - bin\x86\Debug\ + ..\bin\x86\ DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP ;2008 full @@ -116,7 +116,7 @@ - + diff --git a/SDK/HA4IoT.Telemetry/Properties/HA4IoT.Telemetry.rd.xml b/SDK/HA4IoT.Telemetry/Properties/HA4IoT.Telemetry.rd.xml index 7f6c1005..e130dcbc 100644 --- a/SDK/HA4IoT.Telemetry/Properties/HA4IoT.Telemetry.rd.xml +++ b/SDK/HA4IoT.Telemetry/Properties/HA4IoT.Telemetry.rd.xml @@ -25,7 +25,7 @@ http://go.microsoft.com/fwlink/?LinkId=613100 --> - + diff --git a/SDK/Hardware/HA4IoT.Hardware.CCTools/HA4IoT.Hardware.CCTools.csproj b/SDK/Hardware/HA4IoT.Hardware.CCTools/HA4IoT.Hardware.CCTools.csproj index 8b7ee757..8434a9a1 100644 --- a/SDK/Hardware/HA4IoT.Hardware.CCTools/HA4IoT.Hardware.CCTools.csproj +++ b/SDK/Hardware/HA4IoT.Hardware.CCTools/HA4IoT.Hardware.CCTools.csproj @@ -39,7 +39,7 @@ ARM true - bin\ARM\Debug\ + ..\..\bin\ARM\ DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP ;2008 full @@ -132,7 +132,7 @@ - + diff --git a/SDK/Hardware/HA4IoT.Hardware.CCTools/Properties/HA4IoT.Hardware.CCTools.rd.xml b/SDK/Hardware/HA4IoT.Hardware.CCTools/Properties/HA4IoT.Hardware.CCTools.rd.xml index 899638b9..cce24cad 100644 --- a/SDK/Hardware/HA4IoT.Hardware.CCTools/Properties/HA4IoT.Hardware.CCTools.rd.xml +++ b/SDK/Hardware/HA4IoT.Hardware.CCTools/Properties/HA4IoT.Hardware.CCTools.rd.xml @@ -25,7 +25,7 @@ http://go.microsoft.com/fwlink/?LinkId=613100 --> - + diff --git a/SDK/Hardware/HA4IoT.Hardware.I2CHardwareBridge/HA4IoT.Hardware.I2CHardwareBridge.csproj b/SDK/Hardware/HA4IoT.Hardware.I2CHardwareBridge/HA4IoT.Hardware.I2CHardwareBridge.csproj index b6246062..9394616d 100644 --- a/SDK/Hardware/HA4IoT.Hardware.I2CHardwareBridge/HA4IoT.Hardware.I2CHardwareBridge.csproj +++ b/SDK/Hardware/HA4IoT.Hardware.I2CHardwareBridge/HA4IoT.Hardware.I2CHardwareBridge.csproj @@ -39,7 +39,7 @@ ARM true - bin\ARM\Debug\ + ..\..\bin\ARM\ DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP ;2008 full @@ -83,7 +83,7 @@ x86 true - bin\x86\Debug\ + ..\..\bin\x86\ DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP ;2008 full @@ -119,7 +119,7 @@ - + diff --git a/SDK/Hardware/HA4IoT.Hardware.I2CHardwareBridge/Properties/HA4IoT.Hardware.I2CHardwareBridge.rd.xml b/SDK/Hardware/HA4IoT.Hardware.I2CHardwareBridge/Properties/HA4IoT.Hardware.I2CHardwareBridge.rd.xml index 6685c2a3..9249af39 100644 --- a/SDK/Hardware/HA4IoT.Hardware.I2CHardwareBridge/Properties/HA4IoT.Hardware.I2CHardwareBridge.rd.xml +++ b/SDK/Hardware/HA4IoT.Hardware.I2CHardwareBridge/Properties/HA4IoT.Hardware.I2CHardwareBridge.rd.xml @@ -25,7 +25,7 @@ http://go.microsoft.com/fwlink/?LinkID=391919 --> - + diff --git a/SDK/Hardware/HA4IoT.Hardware.Knx/HA4IoT.Hardware.Knx.csproj b/SDK/Hardware/HA4IoT.Hardware.Knx/HA4IoT.Hardware.Knx.csproj index 5fc622ca..f35e680b 100644 --- a/SDK/Hardware/HA4IoT.Hardware.Knx/HA4IoT.Hardware.Knx.csproj +++ b/SDK/Hardware/HA4IoT.Hardware.Knx/HA4IoT.Hardware.Knx.csproj @@ -12,7 +12,7 @@ en-US UAP 10.0.10586.0 - 10.0.10240.0 + 10.0.10586.0 14 512 {A5A43C5B-DE2A-4C0C-9213-0A381AF9435A};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} @@ -39,7 +39,7 @@ x86 true - bin\x86\Debug\ + ..\..\bin\x86\ DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP ;2008 full @@ -61,7 +61,7 @@ ARM true - bin\ARM\Debug\ + ..\..\bin\ARM\ DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP ;2008 full diff --git a/SDK/Hardware/HA4IoT.Hardware.Pi2/HA4IoT.Hardware.Pi2.csproj b/SDK/Hardware/HA4IoT.Hardware.Pi2/HA4IoT.Hardware.Pi2.csproj index 2d8c9e16..42c5b5f1 100644 --- a/SDK/Hardware/HA4IoT.Hardware.Pi2/HA4IoT.Hardware.Pi2.csproj +++ b/SDK/Hardware/HA4IoT.Hardware.Pi2/HA4IoT.Hardware.Pi2.csproj @@ -39,7 +39,7 @@ ARM true - bin\ARM\Debug\ + ..\..\bin\ARM\ DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP ;2008 full @@ -87,7 +87,7 @@ x86 true - bin\x86\Debug\ + ..\..\bin\x86\ DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP ;2008 full @@ -116,7 +116,7 @@ - + diff --git a/SDK/Hardware/HA4IoT.Hardware.Pi2/Properties/HA4IoT.Hardware.Pi2.rd.xml b/SDK/Hardware/HA4IoT.Hardware.Pi2/Properties/HA4IoT.Hardware.Pi2.rd.xml index bf5700a5..bdcafb89 100644 --- a/SDK/Hardware/HA4IoT.Hardware.Pi2/Properties/HA4IoT.Hardware.Pi2.rd.xml +++ b/SDK/Hardware/HA4IoT.Hardware.Pi2/Properties/HA4IoT.Hardware.Pi2.rd.xml @@ -25,7 +25,7 @@ http://go.microsoft.com/fwlink/?LinkId=613100 --> - + diff --git a/SDK/Hardware/HA4IoT.Hardware.PortExpanderDrivers/HA4IoT.Hardware.PortExpanderDrivers.csproj b/SDK/Hardware/HA4IoT.Hardware.PortExpanderDrivers/HA4IoT.Hardware.PortExpanderDrivers.csproj index 7b5cfe7c..3fcc4d14 100644 --- a/SDK/Hardware/HA4IoT.Hardware.PortExpanderDrivers/HA4IoT.Hardware.PortExpanderDrivers.csproj +++ b/SDK/Hardware/HA4IoT.Hardware.PortExpanderDrivers/HA4IoT.Hardware.PortExpanderDrivers.csproj @@ -39,7 +39,7 @@ ARM true - bin\ARM\Debug\ + ..\..\bin\ARM\ DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP ;2008 full @@ -83,7 +83,7 @@ x86 true - bin\x86\Debug\ + ..\..\bin\x86\ DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP ;2008 full @@ -119,7 +119,7 @@ - + diff --git a/SDK/Hardware/HA4IoT.Hardware.PortExpanderDrivers/Properties/HA4IoT.Hardware.PortExpanderDrivers.rd.xml b/SDK/Hardware/HA4IoT.Hardware.PortExpanderDrivers/Properties/HA4IoT.Hardware.PortExpanderDrivers.rd.xml index c4457df5..041c811c 100644 --- a/SDK/Hardware/HA4IoT.Hardware.PortExpanderDrivers/Properties/HA4IoT.Hardware.PortExpanderDrivers.rd.xml +++ b/SDK/Hardware/HA4IoT.Hardware.PortExpanderDrivers/Properties/HA4IoT.Hardware.PortExpanderDrivers.rd.xml @@ -25,7 +25,7 @@ http://go.microsoft.com/fwlink/?LinkID=391919 --> - + diff --git a/SDK/Hardware/HA4IoT.Hardware.RemoteSwitch/HA4IoT.Hardware.RemoteSwitch.csproj b/SDK/Hardware/HA4IoT.Hardware.RemoteSwitch/HA4IoT.Hardware.RemoteSwitch.csproj index f9a978ce..edd39e74 100644 --- a/SDK/Hardware/HA4IoT.Hardware.RemoteSwitch/HA4IoT.Hardware.RemoteSwitch.csproj +++ b/SDK/Hardware/HA4IoT.Hardware.RemoteSwitch/HA4IoT.Hardware.RemoteSwitch.csproj @@ -39,7 +39,7 @@ ARM true - bin\ARM\Debug\ + ..\..\bin\ARM\ DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP ;2008 full @@ -87,7 +87,7 @@ x86 true - bin\x86\Debug\ + ..\..\bin\x86\ DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP ;2008 full @@ -128,7 +128,7 @@ - + diff --git a/SDK/Hardware/HA4IoT.Hardware.RemoteSwitch/Properties/HA4IoT.Hardware.RemoteSwitch.rd.xml b/SDK/Hardware/HA4IoT.Hardware.RemoteSwitch/Properties/HA4IoT.Hardware.RemoteSwitch.rd.xml index c7e72f48..cd4b3186 100644 --- a/SDK/Hardware/HA4IoT.Hardware.RemoteSwitch/Properties/HA4IoT.Hardware.RemoteSwitch.rd.xml +++ b/SDK/Hardware/HA4IoT.Hardware.RemoteSwitch/Properties/HA4IoT.Hardware.RemoteSwitch.rd.xml @@ -25,7 +25,7 @@ http://go.microsoft.com/fwlink/?LinkId=613100 --> - + diff --git a/SDK/Hardware/HA4IoT.Hardware/HA4IoT.Hardware.csproj b/SDK/Hardware/HA4IoT.Hardware/HA4IoT.Hardware.csproj index ac356487..6f70d6d9 100644 --- a/SDK/Hardware/HA4IoT.Hardware/HA4IoT.Hardware.csproj +++ b/SDK/Hardware/HA4IoT.Hardware/HA4IoT.Hardware.csproj @@ -39,7 +39,7 @@ ARM true - bin\ARM\Debug\ + ..\..\bin\ARM\ DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP ;2008 full @@ -88,7 +88,7 @@ x86 true - bin\x86\Debug\ + ..\..\bin\x86\ DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP ;2008 full @@ -122,7 +122,7 @@ - + diff --git a/SDK/Hardware/HA4IoT.Hardware/Properties/HA4IoT.Hardware.rd.xml b/SDK/Hardware/HA4IoT.Hardware/Properties/HA4IoT.Hardware.rd.xml index 4590e9e2..7a80e5d5 100644 --- a/SDK/Hardware/HA4IoT.Hardware/Properties/HA4IoT.Hardware.rd.xml +++ b/SDK/Hardware/HA4IoT.Hardware/Properties/HA4IoT.Hardware.rd.xml @@ -25,7 +25,7 @@ http://go.microsoft.com/fwlink/?LinkId=613100 --> - + diff --git a/Tests/HA4IoT.Tests.Mockups/Properties/HA4IoT.Tests.Mockups.rd.xml b/Tests/HA4IoT.Tests.Mockups/Properties/HA4IoT.Tests.Mockups.rd.xml index aee9b185..c05b3639 100644 --- a/Tests/HA4IoT.Tests.Mockups/Properties/HA4IoT.Tests.Mockups.rd.xml +++ b/Tests/HA4IoT.Tests.Mockups/Properties/HA4IoT.Tests.Mockups.rd.xml @@ -25,7 +25,7 @@ http://go.microsoft.com/fwlink/?LinkId=613100 --> - + From 0cf42e218178861bbf4479b7dd1f635a4b7eb7f7 Mon Sep 17 00:00:00 2001 From: Christian Kratky Date: Sun, 31 Jul 2016 20:25:21 +0200 Subject: [PATCH 02/61] Fix the configuration --- .../Rooms/ChildrensRoomConfiguration.cs | 2 +- .../Rooms/OfficeConfiguration.cs | 5 +++-- .../Rooms/ReadingRoomConfiguration.cs | 2 +- .../Rooms/StoreroomConfiguration.cs | 12 +++++++++--- HA4IoT.sln | 4 ---- 5 files changed, 14 insertions(+), 11 deletions(-) diff --git a/Controllers/HA4IoT.Controller.Main/Rooms/ChildrensRoomConfiguration.cs b/Controllers/HA4IoT.Controller.Main/Rooms/ChildrensRoomConfiguration.cs index 9740d571..35285e30 100644 --- a/Controllers/HA4IoT.Controller.Main/Rooms/ChildrensRoomConfiguration.cs +++ b/Controllers/HA4IoT.Controller.Main/Rooms/ChildrensRoomConfiguration.cs @@ -56,7 +56,7 @@ public override void Setup() var room = Controller.CreateArea(Room.ChildrensRoom) .WithTemperatureSensor(ChildrensRoom.TemperatureSensor, i2cHardwareBridge.DHT22Accessor.GetTemperatureSensor(SensorPin)) .WithHumiditySensor(ChildrensRoom.HumiditySensor, i2cHardwareBridge.DHT22Accessor.GetHumiditySensor(SensorPin)) - .WithLamp(ChildrensRoom.LightCeilingMiddle, hsrel5[HSREL5Pin.GPIO1].WithInvertedState()) + .WithLamp(ChildrensRoom.LightCeilingMiddle, hsrel5[HSREL5Pin.GPIO0]) .WithRollerShutter(ChildrensRoom.RollerShutter, hsrel5[HSREL5Pin.Relay4], hsrel5[HSREL5Pin.Relay3]) .WithSocket(ChildrensRoom.SocketWindow, hsrel5[HSREL5Pin.Relay0]) .WithSocket(ChildrensRoom.SocketWallLeft, hsrel5[HSREL5Pin.Relay1]) diff --git a/Controllers/HA4IoT.Controller.Main/Rooms/OfficeConfiguration.cs b/Controllers/HA4IoT.Controller.Main/Rooms/OfficeConfiguration.cs index 6779ecdb..b7747af9 100644 --- a/Controllers/HA4IoT.Controller.Main/Rooms/OfficeConfiguration.cs +++ b/Controllers/HA4IoT.Controller.Main/Rooms/OfficeConfiguration.cs @@ -106,8 +106,9 @@ private void SetupLight(StateMachine light, HSREL8 hsrel8, HSPE8OutputOnly hspe8 var mr = hsrel8[HSREL8Pin.GPIO1].WithInvertedState(); // Rear lights (left, right) - var rl = hsrel8[HSREL8Pin.GPIO5].WithInvertedState(); - var rr = hsrel8[HSREL8Pin.GPIO4].WithInvertedState(); + // Two mechanical relays. + var rl = hsrel8[HSREL8Pin.GPIO5]; + var rr = hsrel8[HSREL8Pin.GPIO4]; light.AddOffState() .WithLowOutput(fl) diff --git a/Controllers/HA4IoT.Controller.Main/Rooms/ReadingRoomConfiguration.cs b/Controllers/HA4IoT.Controller.Main/Rooms/ReadingRoomConfiguration.cs index 11596ba4..043b8ee4 100644 --- a/Controllers/HA4IoT.Controller.Main/Rooms/ReadingRoomConfiguration.cs +++ b/Controllers/HA4IoT.Controller.Main/Rooms/ReadingRoomConfiguration.cs @@ -56,7 +56,7 @@ public override void Setup() var room = Controller.CreateArea(Room.ReadingRoom) .WithTemperatureSensor(ReadingRoom.TemperatureSensor, i2cHardwareBridge.DHT22Accessor.GetTemperatureSensor(SensorPin)) .WithHumiditySensor(ReadingRoom.HumiditySensor, i2cHardwareBridge.DHT22Accessor.GetHumiditySensor(SensorPin)) - .WithLamp(ReadingRoom.LightCeilingMiddle, hsrel5.GetOutput(6).WithInvertedState()) + .WithLamp(ReadingRoom.LightCeilingMiddle, hsrel5[HSREL5Pin.GPIO0]) .WithRollerShutter(ReadingRoom.RollerShutter, hsrel5[HSREL5Pin.Relay4], hsrel5[HSREL5Pin.Relay3]) .WithSocket(ReadingRoom.SocketWindow, hsrel5[HSREL5Pin.Relay0]) .WithSocket(ReadingRoom.SocketWallLeft, hsrel5[HSREL5Pin.Relay1]) diff --git a/Controllers/HA4IoT.Controller.Main/Rooms/StoreroomConfiguration.cs b/Controllers/HA4IoT.Controller.Main/Rooms/StoreroomConfiguration.cs index d47da100..db21e8fc 100644 --- a/Controllers/HA4IoT.Controller.Main/Rooms/StoreroomConfiguration.cs +++ b/Controllers/HA4IoT.Controller.Main/Rooms/StoreroomConfiguration.cs @@ -1,6 +1,7 @@ using System; using HA4IoT.Actuators.Lamps; using HA4IoT.Actuators.Sockets; +using HA4IoT.Actuators.StateMachines; using HA4IoT.Automations; using HA4IoT.Contracts.Core; using HA4IoT.Contracts.Hardware; @@ -43,8 +44,8 @@ public override void Setup() var storeroom = Controller.CreateArea(Room.Storeroom) .WithMotionDetector(Storeroom.MotionDetector, input3.GetInput(12)) .WithMotionDetector(Storeroom.MotionDetectorCatLitterBox, input3.GetInput(11).WithInvertedState()) - .WithLamp(Storeroom.LightCeiling, hsrel5Stairway.GetOutput(7).WithInvertedState()) - .WithSocket(Storeroom.CatLitterBoxFan, hsrel8LowerHeatingValves.GetOutput(15)); + .WithLamp(Storeroom.LightCeiling, hsrel5Stairway[HSREL5Pin.GPIO1]) + .WithSocket(Storeroom.CatLitterBoxFan, hsrel5Stairway[HSREL5Pin.GPIO2]); storeroom.SetupTurnOnAndOffAutomation() .WithTrigger(storeroom.GetMotionDetector(Storeroom.MotionDetector)) @@ -56,7 +57,12 @@ public override void Setup() .WithTarget(storeroom.Socket(Storeroom.CatLitterBoxFan)) .WithOnDuration(TimeSpan.FromMinutes(2)); - storeroom.WithSocket(Storeroom.CirculatingPump, hsrel5UpperHeatingValves.GetOutput(3)); + storeroom.WithSocket(Storeroom.CirculatingPump, hsrel5UpperHeatingValves[HSREL5Pin.Relay3]); + + // Both relays are used for water source selection (True+True = Lowerr, False+False = Upper) + // Second relays is with capacitor. Disable second with delay before disable first one. + hsrel5UpperHeatingValves[HSREL5Pin.GPIO0].Write(BinaryState.Low); + hsrel5UpperHeatingValves[HSREL5Pin.GPIO1].Write(BinaryState.Low); storeroom.SetupTurnOnAndOffAutomation() .WithTrigger(Controller.GetArea(AreaIdFactory.Create(Room.Kitchen)).GetMotionDetector(KitchenConfiguration.Kitchen.MotionDetector)) diff --git a/HA4IoT.sln b/HA4IoT.sln index 44e3f98f..a1bb67d2 100644 --- a/HA4IoT.sln +++ b/HA4IoT.sln @@ -469,8 +469,6 @@ Global {4558BE1E-0A43-40FC-A697-3732398FB126}.Debug|x86 (For local).ActiveCfg = Debug|x86 {4558BE1E-0A43-40FC-A697-3732398FB126}.Debug|x86 (For local).Build.0 = Debug|x86 {4558BE1E-0A43-40FC-A697-3732398FB126}.Release|ARM (For Raspberry Pi).ActiveCfg = Release|ARM - {4558BE1E-0A43-40FC-A697-3732398FB126}.Release|ARM (For Raspberry Pi).Build.0 = Release|ARM - {4558BE1E-0A43-40FC-A697-3732398FB126}.Release|ARM (For Raspberry Pi).Deploy.0 = Release|ARM {4558BE1E-0A43-40FC-A697-3732398FB126}.Release|x86 (For local).ActiveCfg = Release|x86 {4558BE1E-0A43-40FC-A697-3732398FB126}.Release|x86 (For local).Build.0 = Release|x86 {1EC3A5D0-65C8-4396-BD56-9179A8BD00D4}.Debug|ARM (For Raspberry Pi).ActiveCfg = Debug|ARM @@ -497,8 +495,6 @@ Global {DF91A86C-235F-44E7-AA3C-72FA0B786250}.Debug|x86 (For local).ActiveCfg = Debug|x86 {DF91A86C-235F-44E7-AA3C-72FA0B786250}.Debug|x86 (For local).Build.0 = Debug|x86 {DF91A86C-235F-44E7-AA3C-72FA0B786250}.Release|ARM (For Raspberry Pi).ActiveCfg = Release|ARM - {DF91A86C-235F-44E7-AA3C-72FA0B786250}.Release|ARM (For Raspberry Pi).Build.0 = Release|ARM - {DF91A86C-235F-44E7-AA3C-72FA0B786250}.Release|ARM (For Raspberry Pi).Deploy.0 = Release|ARM {DF91A86C-235F-44E7-AA3C-72FA0B786250}.Release|x86 (For local).ActiveCfg = Release|x86 {DF91A86C-235F-44E7-AA3C-72FA0B786250}.Release|x86 (For local).Build.0 = Release|x86 {DF91A86C-235F-44E7-AA3C-72FA0B786250}.Release|x86 (For local).Deploy.0 = Release|x86 From 454007b394f4b798d9bad77764ab0c3480841e29 Mon Sep 17 00:00:00 2001 From: Christian Kratky Date: Sat, 13 Aug 2016 15:27:12 +0200 Subject: [PATCH 03/61] Add new dedicated services for outside values which can contain different implementations (providers). --- .../HA4IoT.Controller.Cellar/Controller.cs | 25 +++- .../HA4IoT.Controller.Cellar.csproj | 4 + .../HA4IoT.Controller.Default/Controller.cs | 21 ++- .../HA4IoT.Controller.Default.csproj | 4 + .../HA4IoT.Controller.Demo/Controller.cs | 2 +- .../HA4IoT.Controller.Main/Controller.cs | 31 +++- .../HA4IoT.Controller.Main.csproj | 4 + .../Rooms/BedroomConfiguration.cs | 1 + .../Rooms/FloorConfiguration.cs | 1 + .../Rooms/KitchenConfiguration.cs | 1 + .../Rooms/StoreroomConfiguration.cs | 1 + HA4IoT.sln | 19 ++- ...IoT.ExternalServices.OpenWeatherMap.csproj | 5 - .../OpenWeatherMapDaylightService.cs | 38 ----- .../OpenWeatherMapOutdoorHumidityService.cs | 30 ---- ...OpenWeatherMapOutdoorTemperatureService.cs | 30 ---- .../OpenWeatherMapResponseParser.cs | 5 +- .../OpenWeatherMapService.cs | 88 ++++++----- .../OpenWeatherMapWeatherService.cs | 30 ---- .../OpenWeatherMapWeatherSituationParser.cs | 83 ++++++----- ...enWeatherMapWeatherStationApiDispatcher.cs | 47 ------ .../ConditionalOnAutomation.cs | 3 +- .../ConditionalOnAutomationExtensions.cs | 1 + .../RollerShutterAutomation.cs | 9 +- .../RollerShutterAutomationExtensions.cs | 3 +- .../TurnOnAndOffAutomation.cs | 9 +- .../Specialized/IsDayCondition.cs | 5 +- .../Specialized/IsNightCondition.cs | 5 +- .../Specialized/TimeRangeCondition.cs | 2 +- .../DefaultConfigurationExtender.cs | 1 - SDK/HA4IoT.Contracts/HA4IoT.Contracts.csproj | 16 +- .../Daylight/DaylightFetchedEventArgs.cs | 17 +++ .../Services/Daylight/IDaylightProvider.cs | 9 ++ .../Services/Daylight/IDaylightService.cs | 13 ++ .../Services/IDaylightService.cs | 11 -- .../IOutdoorHumidityProvider.cs | 9 ++ .../IOutdoorHumidityService.cs | 11 ++ .../OutdoorHumidityFetchedEventArgs.cs | 14 ++ .../IOutdoorTemperatureProvider.cs | 9 ++ .../IOutdoorTemperatureService.cs | 11 ++ .../OutdoorTemperatureFetchedEventArgs.cs | 14 ++ .../Services/System/DateTimeService.cs | 6 +- .../Weather/IOutdoorHumidityService.cs | 7 - .../Weather/IOutdoorTemperatureService.cs | 7 - .../Services/Weather/IWeatherProvider.cs | 9 ++ .../Services/Weather/IWeatherService.cs | 8 +- .../{WeatherSituation.cs => Weather.cs} | 2 +- .../Weather/WeatherFetchedEventArgs.cs | 14 ++ SDK/HA4IoT.Core/DateTimeService.cs | 25 +--- SDK/HA4IoT.Networking/JsonObjectExtensions.cs | 23 +++ .../PersonalAgentMessageProcessor.cs | 8 +- .../ControllerSlave/ControllerSlaveService.cs | 115 +++++++++++++++ .../Environment/DaylightService.cs | 44 ++++++ .../Environment/OutdoorTemperatureService.cs | 43 ++++++ .../Environment/OutdootHumidityService.cs | 43 ++++++ .../Environment/WeatherService.cs | 42 ++++++ SDK/HA4IoT.Services/HA4IoT.Services.csproj | 139 ++++++++++++++++++ .../Properties/AssemblyInfo.cs | 14 ++ .../Properties/HA4IoT.Services.rd.xml | 33 +++++ SDK/HA4IoT.Services/project.json | 16 ++ .../ConditionalOnAutomationTests.cs | 1 + .../RollerShutterAutomationTests.cs | 10 +- .../ConfigurationParserTests.cs | 13 +- .../HA4IoT.Core.Tests/ServiceLocatorTests.cs | 20 +-- Tests/HA4IoT.Tests.Mockups/TestController.cs | 1 + .../TestDateTimeService.cs | 19 +-- .../TestDaylightService.cs | 12 +- .../TestWeatherStation.cs | 39 ++--- 68 files changed, 919 insertions(+), 436 deletions(-) delete mode 100644 SDK/ExternalServices/HA4IoT.ExternalServices.OpenWeatherMap/OpenWeatherMapDaylightService.cs delete mode 100644 SDK/ExternalServices/HA4IoT.ExternalServices.OpenWeatherMap/OpenWeatherMapOutdoorHumidityService.cs delete mode 100644 SDK/ExternalServices/HA4IoT.ExternalServices.OpenWeatherMap/OpenWeatherMapOutdoorTemperatureService.cs delete mode 100644 SDK/ExternalServices/HA4IoT.ExternalServices.OpenWeatherMap/OpenWeatherMapWeatherService.cs delete mode 100644 SDK/ExternalServices/HA4IoT.ExternalServices.OpenWeatherMap/OpenWeatherMapWeatherStationApiDispatcher.cs create mode 100644 SDK/HA4IoT.Contracts/Services/Daylight/DaylightFetchedEventArgs.cs create mode 100644 SDK/HA4IoT.Contracts/Services/Daylight/IDaylightProvider.cs create mode 100644 SDK/HA4IoT.Contracts/Services/Daylight/IDaylightService.cs delete mode 100644 SDK/HA4IoT.Contracts/Services/IDaylightService.cs create mode 100644 SDK/HA4IoT.Contracts/Services/OutdoorHumidity/IOutdoorHumidityProvider.cs create mode 100644 SDK/HA4IoT.Contracts/Services/OutdoorHumidity/IOutdoorHumidityService.cs create mode 100644 SDK/HA4IoT.Contracts/Services/OutdoorHumidity/OutdoorHumidityFetchedEventArgs.cs create mode 100644 SDK/HA4IoT.Contracts/Services/OutdoorTemperature/IOutdoorTemperatureProvider.cs create mode 100644 SDK/HA4IoT.Contracts/Services/OutdoorTemperature/IOutdoorTemperatureService.cs create mode 100644 SDK/HA4IoT.Contracts/Services/OutdoorTemperature/OutdoorTemperatureFetchedEventArgs.cs delete mode 100644 SDK/HA4IoT.Contracts/Services/Weather/IOutdoorHumidityService.cs delete mode 100644 SDK/HA4IoT.Contracts/Services/Weather/IOutdoorTemperatureService.cs create mode 100644 SDK/HA4IoT.Contracts/Services/Weather/IWeatherProvider.cs rename SDK/HA4IoT.Contracts/Services/Weather/{WeatherSituation.cs => Weather.cs} (97%) create mode 100644 SDK/HA4IoT.Contracts/Services/Weather/WeatherFetchedEventArgs.cs create mode 100644 SDK/HA4IoT.Services/ControllerSlave/ControllerSlaveService.cs create mode 100644 SDK/HA4IoT.Services/Environment/DaylightService.cs create mode 100644 SDK/HA4IoT.Services/Environment/OutdoorTemperatureService.cs create mode 100644 SDK/HA4IoT.Services/Environment/OutdootHumidityService.cs create mode 100644 SDK/HA4IoT.Services/Environment/WeatherService.cs create mode 100644 SDK/HA4IoT.Services/HA4IoT.Services.csproj create mode 100644 SDK/HA4IoT.Services/Properties/AssemblyInfo.cs create mode 100644 SDK/HA4IoT.Services/Properties/HA4IoT.Services.rd.xml create mode 100644 SDK/HA4IoT.Services/project.json diff --git a/Controllers/HA4IoT.Controller.Cellar/Controller.cs b/Controllers/HA4IoT.Controller.Cellar/Controller.cs index b0336074..c6c9cfd7 100644 --- a/Controllers/HA4IoT.Controller.Cellar/Controller.cs +++ b/Controllers/HA4IoT.Controller.Cellar/Controller.cs @@ -10,13 +10,19 @@ using HA4IoT.Contracts.Components; using HA4IoT.Contracts.Hardware; using HA4IoT.Contracts.Services; +using HA4IoT.Contracts.Services.Daylight; +using HA4IoT.Contracts.Services.OutdoorHumidity; +using HA4IoT.Contracts.Services.OutdoorTemperature; using HA4IoT.Contracts.Services.System; +using HA4IoT.Contracts.Services.Weather; using HA4IoT.Core; using HA4IoT.ExternalServices.OpenWeatherMap; using HA4IoT.Hardware; using HA4IoT.Hardware.CCTools; using HA4IoT.Hardware.Pi2; using HA4IoT.Sensors.Buttons; +using HA4IoT.Services; +using HA4IoT.Services.Environment; namespace HA4IoT.Controller.Cellar { @@ -48,7 +54,7 @@ private enum Garden StateMachine } - public Controller(int statusLedNumber) + public Controller(int statusLedNumber) : base(statusLedNumber) { } @@ -59,15 +65,20 @@ protected override async Task ConfigureAsync() AddDevice(new BuiltInI2CBus()); - ServiceLocator.RegisterService(typeof (OpenWeatherMapWeatherService), - new OpenWeatherMapService(ApiController, - ServiceLocator.GetService(), - ServiceLocator.GetService(), - ServiceLocator.GetService())); + var openWeatherMapService = new OpenWeatherMapService( + ServiceLocator.GetService(), + ServiceLocator.GetService(), + ServiceLocator.GetService()); + + ServiceLocator.RegisterService(typeof(IOutdoorTemperatureService), new OutdoorTemperatureService(openWeatherMapService, ServiceLocator.GetService())); + ServiceLocator.RegisterService(typeof(IOutdoorHumidityService), new OutdootHumidityService(openWeatherMapService, ServiceLocator.GetService())); + ServiceLocator.RegisterService(typeof(IDaylightService), new DaylightService(openWeatherMapService, ServiceLocator.GetService())); + ServiceLocator.RegisterService(typeof(IWeatherService), new WeatherService(openWeatherMapService, ServiceLocator.GetService())); + ServiceLocator.RegisterService(typeof(OpenWeatherMapService), openWeatherMapService); var ccToolsFactory = new CCToolsBoardController(this, GetDevice()); var hsrt16 = ccToolsFactory.CreateHSRT16(Device.CellarHSRT16, new I2CSlaveAddress(32)); - + var garden = this.CreateArea(RoomId.Garden) .WithLamp(Garden.LampTerrace, hsrt16[HSRT16Pin.Relay15]) .WithLamp(Garden.LampGarage, hsrt16[HSRT16Pin.Relay14]) diff --git a/Controllers/HA4IoT.Controller.Cellar/HA4IoT.Controller.Cellar.csproj b/Controllers/HA4IoT.Controller.Cellar/HA4IoT.Controller.Cellar.csproj index 7747b062..63bf06f2 100644 --- a/Controllers/HA4IoT.Controller.Cellar/HA4IoT.Controller.Cellar.csproj +++ b/Controllers/HA4IoT.Controller.Cellar/HA4IoT.Controller.Cellar.csproj @@ -145,6 +145,10 @@ {2BBEF090-4FEE-4FB7-9CF1-F6597F2C53EA} HA4IoT.Core + + {6FD41DDA-4369-43C1-807A-B1BC43ECBDBF} + HA4IoT.Services + {287A9BD0-4037-4ADD-986F-54056F059EAE} HA4IoT.Hardware diff --git a/Controllers/HA4IoT.Controller.Default/Controller.cs b/Controllers/HA4IoT.Controller.Default/Controller.cs index 1a6eb153..003f6aa8 100644 --- a/Controllers/HA4IoT.Controller.Default/Controller.cs +++ b/Controllers/HA4IoT.Controller.Default/Controller.cs @@ -2,13 +2,18 @@ using HA4IoT.Configuration; using HA4IoT.Contracts.Hardware; using HA4IoT.Contracts.Services; +using HA4IoT.Contracts.Services.Daylight; +using HA4IoT.Contracts.Services.OutdoorHumidity; +using HA4IoT.Contracts.Services.OutdoorTemperature; using HA4IoT.Contracts.Services.System; +using HA4IoT.Contracts.Services.Weather; using HA4IoT.Core; using HA4IoT.ExternalServices.OpenWeatherMap; using HA4IoT.Hardware; using HA4IoT.Hardware.CCTools; using HA4IoT.Hardware.I2CHardwareBridge; using HA4IoT.Hardware.Pi2; +using HA4IoT.Services.Environment; namespace HA4IoT.Controller.Default { @@ -31,12 +36,16 @@ protected override async Task ConfigureAsync() AddDevice(pi2PortController); AddDevice(ccToolsBoardController); - ServiceLocator.RegisterService( - typeof(OpenWeatherMapWeatherService), - new OpenWeatherMapService(ApiController, - ServiceLocator.GetService(), - ServiceLocator.GetService(), - ServiceLocator.GetService())); + var openWeatherMapService = new OpenWeatherMapService( + ServiceLocator.GetService(), + ServiceLocator.GetService(), + ServiceLocator.GetService()); + + ServiceLocator.RegisterService(typeof(IOutdoorTemperatureService), new OutdoorTemperatureService(openWeatherMapService, ServiceLocator.GetService())); + ServiceLocator.RegisterService(typeof(IOutdoorHumidityService), new OutdootHumidityService(openWeatherMapService, ServiceLocator.GetService())); + ServiceLocator.RegisterService(typeof(IDaylightService), new DaylightService(openWeatherMapService, ServiceLocator.GetService())); + ServiceLocator.RegisterService(typeof(IWeatherService), new WeatherService(openWeatherMapService, ServiceLocator.GetService())); + ServiceLocator.RegisterService(typeof(OpenWeatherMapService), openWeatherMapService); var configurationParser = new ConfigurationParser(this); configurationParser.RegisterConfigurationExtender(new DefaultConfigurationExtender(configurationParser, this)); diff --git a/Controllers/HA4IoT.Controller.Default/HA4IoT.Controller.Default.csproj b/Controllers/HA4IoT.Controller.Default/HA4IoT.Controller.Default.csproj index 5d060197..3f57a513 100644 --- a/Controllers/HA4IoT.Controller.Default/HA4IoT.Controller.Default.csproj +++ b/Controllers/HA4IoT.Controller.Default/HA4IoT.Controller.Default.csproj @@ -141,6 +141,10 @@ {2BBEF090-4FEE-4FB7-9CF1-F6597F2C53EA} HA4IoT.Core + + {6FD41DDA-4369-43C1-807A-B1BC43ECBDBF} + HA4IoT.Services + {287A9BD0-4037-4ADD-986F-54056F059EAE} HA4IoT.Hardware diff --git a/Controllers/HA4IoT.Controller.Demo/Controller.cs b/Controllers/HA4IoT.Controller.Demo/Controller.cs index 86267d35..7f6fd7e9 100644 --- a/Controllers/HA4IoT.Controller.Demo/Controller.cs +++ b/Controllers/HA4IoT.Controller.Demo/Controller.cs @@ -62,7 +62,7 @@ protected override async Task ConfigureAsync() ServiceLocator.RegisterService(typeof(SynonymService), new SynonymService()); ServiceLocator.RegisterService(typeof (OpenWeatherMapService), - new OpenWeatherMapService(ApiController, + new OpenWeatherMapService( ServiceLocator.GetService(), ServiceLocator.GetService(), ServiceLocator.GetService())); diff --git a/Controllers/HA4IoT.Controller.Main/Controller.cs b/Controllers/HA4IoT.Controller.Main/Controller.cs index ed65be3a..9c73e56f 100644 --- a/Controllers/HA4IoT.Controller.Main/Controller.cs +++ b/Controllers/HA4IoT.Controller.Main/Controller.cs @@ -14,8 +14,15 @@ using HA4IoT.Hardware.RemoteSwitch.Codes; using HA4IoT.Contracts.PersonalAgent; using HA4IoT.Contracts.Services; +using HA4IoT.Contracts.Services.Daylight; +using HA4IoT.Contracts.Services.OutdoorHumidity; +using HA4IoT.Contracts.Services.OutdoorTemperature; using HA4IoT.Contracts.Services.System; +using HA4IoT.Contracts.Services.Weather; using HA4IoT.PersonalAgent; +using HA4IoT.Services; +using HA4IoT.Services.ControllerSlave; +using HA4IoT.Services.Environment; namespace HA4IoT.Controller.Main { @@ -40,13 +47,8 @@ protected override async Task ConfigureAsync() AddDevice(SetupRemoteSwitchController()); ServiceLocator.RegisterService(typeof(SynonymService), new SynonymService()); - ServiceLocator.RegisterService(typeof(OpenWeatherMapService), - new OpenWeatherMapService( - ApiController, - ServiceLocator.GetService(), - ServiceLocator.GetService(), - ServiceLocator.GetService())); + SetupOpenWeatherMapService(); SetupTelegramBot(); SetupTwitterClient(); @@ -81,6 +83,23 @@ protected override async Task ConfigureAsync() await base.ConfigureAsync(); } + private void SetupOpenWeatherMapService() + { + var controllerSlaveService = new ControllerSlaveService("127.0.0.1", ServiceLocator.GetService(), ServiceLocator.GetService()); + ServiceLocator.RegisterService(typeof(ControllerSlaveService), controllerSlaveService); + + var openWeatherMapService = new OpenWeatherMapService( + ServiceLocator.GetService(), + ServiceLocator.GetService(), + ServiceLocator.GetService()); + + ServiceLocator.RegisterService(typeof(IOutdoorTemperatureService), new OutdoorTemperatureService(openWeatherMapService, ServiceLocator.GetService())); + ServiceLocator.RegisterService(typeof(IOutdoorHumidityService), new OutdootHumidityService(openWeatherMapService, ServiceLocator.GetService())); + ServiceLocator.RegisterService(typeof(IDaylightService), new DaylightService(openWeatherMapService, ServiceLocator.GetService())); + ServiceLocator.RegisterService(typeof(IWeatherService), new WeatherService(openWeatherMapService, ServiceLocator.GetService())); + ServiceLocator.RegisterService(typeof(OpenWeatherMapService), openWeatherMapService); + } + private void SetupTelegramBot() { TelegramBotService telegramBotService; diff --git a/Controllers/HA4IoT.Controller.Main/HA4IoT.Controller.Main.csproj b/Controllers/HA4IoT.Controller.Main/HA4IoT.Controller.Main.csproj index 4e11c788..e654035c 100644 --- a/Controllers/HA4IoT.Controller.Main/HA4IoT.Controller.Main.csproj +++ b/Controllers/HA4IoT.Controller.Main/HA4IoT.Controller.Main.csproj @@ -175,6 +175,10 @@ {2BBEF090-4FEE-4FB7-9CF1-F6597F2C53EA} HA4IoT.Core + + {6FD41DDA-4369-43C1-807A-B1BC43ECBDBF} + HA4IoT.Services + {1EC3A5D0-65C8-4396-BD56-9179A8BD00D4} HA4IoT.Hardware.Knx diff --git a/Controllers/HA4IoT.Controller.Main/Rooms/BedroomConfiguration.cs b/Controllers/HA4IoT.Controller.Main/Rooms/BedroomConfiguration.cs index 43b23edf..a518a461 100644 --- a/Controllers/HA4IoT.Controller.Main/Rooms/BedroomConfiguration.cs +++ b/Controllers/HA4IoT.Controller.Main/Rooms/BedroomConfiguration.cs @@ -10,6 +10,7 @@ using HA4IoT.Contracts.Components; using HA4IoT.Contracts.Hardware; using HA4IoT.Contracts.Services; +using HA4IoT.Contracts.Services.Daylight; using HA4IoT.Core; using HA4IoT.Hardware; using HA4IoT.Hardware.CCTools; diff --git a/Controllers/HA4IoT.Controller.Main/Rooms/FloorConfiguration.cs b/Controllers/HA4IoT.Controller.Main/Rooms/FloorConfiguration.cs index 267d5e05..84315f22 100644 --- a/Controllers/HA4IoT.Controller.Main/Rooms/FloorConfiguration.cs +++ b/Controllers/HA4IoT.Controller.Main/Rooms/FloorConfiguration.cs @@ -12,6 +12,7 @@ using HA4IoT.Contracts.Core; using HA4IoT.Contracts.Hardware; using HA4IoT.Contracts.Services; +using HA4IoT.Contracts.Services.Daylight; using HA4IoT.Core; using HA4IoT.Hardware; using HA4IoT.Hardware.CCTools; diff --git a/Controllers/HA4IoT.Controller.Main/Rooms/KitchenConfiguration.cs b/Controllers/HA4IoT.Controller.Main/Rooms/KitchenConfiguration.cs index 11fb4e64..59e6801b 100644 --- a/Controllers/HA4IoT.Controller.Main/Rooms/KitchenConfiguration.cs +++ b/Controllers/HA4IoT.Controller.Main/Rooms/KitchenConfiguration.cs @@ -8,6 +8,7 @@ using HA4IoT.Contracts.Core; using HA4IoT.Contracts.Hardware; using HA4IoT.Contracts.Services; +using HA4IoT.Contracts.Services.Daylight; using HA4IoT.Core; using HA4IoT.Hardware; using HA4IoT.Hardware.CCTools; diff --git a/Controllers/HA4IoT.Controller.Main/Rooms/StoreroomConfiguration.cs b/Controllers/HA4IoT.Controller.Main/Rooms/StoreroomConfiguration.cs index db21e8fc..0b2f0547 100644 --- a/Controllers/HA4IoT.Controller.Main/Rooms/StoreroomConfiguration.cs +++ b/Controllers/HA4IoT.Controller.Main/Rooms/StoreroomConfiguration.cs @@ -6,6 +6,7 @@ using HA4IoT.Contracts.Core; using HA4IoT.Contracts.Hardware; using HA4IoT.Contracts.Services; +using HA4IoT.Contracts.Services.Daylight; using HA4IoT.Core; using HA4IoT.Hardware; using HA4IoT.Hardware.CCTools; diff --git a/HA4IoT.sln b/HA4IoT.sln index a1bb67d2..c061202a 100644 --- a/HA4IoT.sln +++ b/HA4IoT.sln @@ -129,6 +129,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HA4IoT.Hardware.CCTools.Tes EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HA4IoT.Core.Tests", "Tests\HA4IoT.Core.Tests\HA4IoT.Core.Tests.csproj", "{4BD2A0F3-4CFC-41EE-ACE3-BE41A4A75C48}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HA4IoT.Services", "SDK\HA4IoT.Services\HA4IoT.Services.csproj", "{6FD41DDA-4369-43C1-807A-B1BC43ECBDBF}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|ARM (For Raspberry Pi) = Debug|ARM (For Raspberry Pi) @@ -397,8 +399,8 @@ Global {E1EDAC4B-83B9-46F4-9F6A-3BAE97D79F29}.Debug|x86 (For local).Build.0 = Debug|x86 {E1EDAC4B-83B9-46F4-9F6A-3BAE97D79F29}.Release|ARM (For Raspberry Pi).ActiveCfg = Release|ARM {E1EDAC4B-83B9-46F4-9F6A-3BAE97D79F29}.Release|ARM (For Raspberry Pi).Build.0 = Release|ARM - {E1EDAC4B-83B9-46F4-9F6A-3BAE97D79F29}.Release|x86 (For local).ActiveCfg = Release|Any CPU - {E1EDAC4B-83B9-46F4-9F6A-3BAE97D79F29}.Release|x86 (For local).Build.0 = Release|Any CPU + {E1EDAC4B-83B9-46F4-9F6A-3BAE97D79F29}.Release|x86 (For local).ActiveCfg = Release|x86 + {E1EDAC4B-83B9-46F4-9F6A-3BAE97D79F29}.Release|x86 (For local).Build.0 = Release|x86 {0F244152-1BF5-46E4-93DD-E769B38CE9DB}.Debug|ARM (For Raspberry Pi).ActiveCfg = Debug|ARM {0F244152-1BF5-46E4-93DD-E769B38CE9DB}.Debug|ARM (For Raspberry Pi).Build.0 = Debug|ARM {0F244152-1BF5-46E4-93DD-E769B38CE9DB}.Debug|x86 (For local).ActiveCfg = Debug|x86 @@ -434,6 +436,7 @@ Global {F931A02F-DCAD-4301-8DAD-B7D722A9C410}.Debug|x86 (For local).ActiveCfg = Debug|x86 {F931A02F-DCAD-4301-8DAD-B7D722A9C410}.Release|ARM (For Raspberry Pi).ActiveCfg = Release|x86 {F931A02F-DCAD-4301-8DAD-B7D722A9C410}.Release|x86 (For local).ActiveCfg = Release|x86 + {F931A02F-DCAD-4301-8DAD-B7D722A9C410}.Release|x86 (For local).Build.0 = Release|x86 {56F4E6B0-8C46-4715-A9F3-00A6573C2CF4}.Debug|ARM (For Raspberry Pi).ActiveCfg = Debug|ARM {56F4E6B0-8C46-4715-A9F3-00A6573C2CF4}.Debug|ARM (For Raspberry Pi).Build.0 = Debug|ARM {56F4E6B0-8C46-4715-A9F3-00A6573C2CF4}.Debug|x86 (For local).ActiveCfg = Debug|x86 @@ -485,12 +488,14 @@ Global {38B1BC5D-21DD-4BAB-8CA1-6008518D21F1}.Debug|x86 (For local).Build.0 = Debug|x86 {38B1BC5D-21DD-4BAB-8CA1-6008518D21F1}.Release|ARM (For Raspberry Pi).ActiveCfg = Release|x86 {38B1BC5D-21DD-4BAB-8CA1-6008518D21F1}.Release|x86 (For local).ActiveCfg = Release|x86 + {38B1BC5D-21DD-4BAB-8CA1-6008518D21F1}.Release|x86 (For local).Build.0 = Release|x86 {15C79C50-497E-40EF-840E-65B0464417CF}.Debug|ARM (For Raspberry Pi).ActiveCfg = Debug|x86 {15C79C50-497E-40EF-840E-65B0464417CF}.Debug|ARM (For Raspberry Pi).Build.0 = Debug|x86 {15C79C50-497E-40EF-840E-65B0464417CF}.Debug|x86 (For local).ActiveCfg = Debug|x86 {15C79C50-497E-40EF-840E-65B0464417CF}.Debug|x86 (For local).Build.0 = Debug|x86 {15C79C50-497E-40EF-840E-65B0464417CF}.Release|ARM (For Raspberry Pi).ActiveCfg = Release|x86 {15C79C50-497E-40EF-840E-65B0464417CF}.Release|x86 (For local).ActiveCfg = Release|x86 + {15C79C50-497E-40EF-840E-65B0464417CF}.Release|x86 (For local).Build.0 = Release|x86 {DF91A86C-235F-44E7-AA3C-72FA0B786250}.Debug|ARM (For Raspberry Pi).ActiveCfg = Debug|ARM {DF91A86C-235F-44E7-AA3C-72FA0B786250}.Debug|x86 (For local).ActiveCfg = Debug|x86 {DF91A86C-235F-44E7-AA3C-72FA0B786250}.Debug|x86 (For local).Build.0 = Debug|x86 @@ -503,6 +508,15 @@ Global {4BD2A0F3-4CFC-41EE-ACE3-BE41A4A75C48}.Debug|x86 (For local).Build.0 = Debug|x86 {4BD2A0F3-4CFC-41EE-ACE3-BE41A4A75C48}.Release|ARM (For Raspberry Pi).ActiveCfg = Release|x86 {4BD2A0F3-4CFC-41EE-ACE3-BE41A4A75C48}.Release|x86 (For local).ActiveCfg = Release|x86 + {4BD2A0F3-4CFC-41EE-ACE3-BE41A4A75C48}.Release|x86 (For local).Build.0 = Release|x86 + {6FD41DDA-4369-43C1-807A-B1BC43ECBDBF}.Debug|ARM (For Raspberry Pi).ActiveCfg = Debug|ARM + {6FD41DDA-4369-43C1-807A-B1BC43ECBDBF}.Debug|ARM (For Raspberry Pi).Build.0 = Debug|ARM + {6FD41DDA-4369-43C1-807A-B1BC43ECBDBF}.Debug|x86 (For local).ActiveCfg = Debug|Any CPU + {6FD41DDA-4369-43C1-807A-B1BC43ECBDBF}.Debug|x86 (For local).Build.0 = Debug|Any CPU + {6FD41DDA-4369-43C1-807A-B1BC43ECBDBF}.Release|ARM (For Raspberry Pi).ActiveCfg = Release|Any CPU + {6FD41DDA-4369-43C1-807A-B1BC43ECBDBF}.Release|ARM (For Raspberry Pi).Build.0 = Release|Any CPU + {6FD41DDA-4369-43C1-807A-B1BC43ECBDBF}.Release|x86 (For local).ActiveCfg = Release|x86 + {6FD41DDA-4369-43C1-807A-B1BC43ECBDBF}.Release|x86 (For local).Build.0 = Release|x86 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -562,5 +576,6 @@ Global {15C79C50-497E-40EF-840E-65B0464417CF} = {AF6D96DE-60FE-4711-A888-3F6A06AF1628} {DF91A86C-235F-44E7-AA3C-72FA0B786250} = {C66A0C8B-0AAA-40C0-8D27-BD5B7BF1EF46} {4BD2A0F3-4CFC-41EE-ACE3-BE41A4A75C48} = {C66A0C8B-0AAA-40C0-8D27-BD5B7BF1EF46} + {6FD41DDA-4369-43C1-807A-B1BC43ECBDBF} = {982ABB4E-A5DC-4C78-87A3-30BF49DD5764} EndGlobalSection EndGlobal diff --git a/SDK/ExternalServices/HA4IoT.ExternalServices.OpenWeatherMap/HA4IoT.ExternalServices.OpenWeatherMap.csproj b/SDK/ExternalServices/HA4IoT.ExternalServices.OpenWeatherMap/HA4IoT.ExternalServices.OpenWeatherMap.csproj index e423324a..35d0149e 100644 --- a/SDK/ExternalServices/HA4IoT.ExternalServices.OpenWeatherMap/HA4IoT.ExternalServices.OpenWeatherMap.csproj +++ b/SDK/ExternalServices/HA4IoT.ExternalServices.OpenWeatherMap/HA4IoT.ExternalServices.OpenWeatherMap.csproj @@ -108,14 +108,9 @@ - - - - - diff --git a/SDK/ExternalServices/HA4IoT.ExternalServices.OpenWeatherMap/OpenWeatherMapDaylightService.cs b/SDK/ExternalServices/HA4IoT.ExternalServices.OpenWeatherMap/OpenWeatherMapDaylightService.cs deleted file mode 100644 index dd5462b1..00000000 --- a/SDK/ExternalServices/HA4IoT.ExternalServices.OpenWeatherMap/OpenWeatherMapDaylightService.cs +++ /dev/null @@ -1,38 +0,0 @@ -using System; -using Windows.Data.Json; -using HA4IoT.Contracts.Services; -using HA4IoT.Networking; - -namespace HA4IoT.ExternalServices.OpenWeatherMap -{ - public class OpenWeatherMapDaylightService : ServiceBase, IDaylightService - { - private TimeSpan _sunrise; - private TimeSpan _sunset; - - public override JsonObject ExportStatusToJsonObject() - { - var status = base.ExportStatusToJsonObject(); - status.SetNamedTimeSpan("Sunrise", _sunrise); - status.SetNamedTimeSpan("Sunset", _sunset); - - return status; - } - - public TimeSpan GetSunrise() - { - return _sunrise; - } - - public TimeSpan GetSunset() - { - return _sunset; - } - - internal void Update(TimeSpan sunrise, TimeSpan sunset) - { - _sunrise = sunrise; - _sunset = sunset; - } - } -} diff --git a/SDK/ExternalServices/HA4IoT.ExternalServices.OpenWeatherMap/OpenWeatherMapOutdoorHumidityService.cs b/SDK/ExternalServices/HA4IoT.ExternalServices.OpenWeatherMap/OpenWeatherMapOutdoorHumidityService.cs deleted file mode 100644 index 8f9bd318..00000000 --- a/SDK/ExternalServices/HA4IoT.ExternalServices.OpenWeatherMap/OpenWeatherMapOutdoorHumidityService.cs +++ /dev/null @@ -1,30 +0,0 @@ -using Windows.Data.Json; -using HA4IoT.Contracts.Services; -using HA4IoT.Contracts.Services.Weather; -using HA4IoT.Networking; - -namespace HA4IoT.ExternalServices.OpenWeatherMap -{ - public class OpenWeatherMapOutdoorHumidityService : ServiceBase, IOutdoorHumidityService - { - private float _outdoorHumidity; - - public override JsonObject ExportStatusToJsonObject() - { - var status = base.ExportStatusToJsonObject(); - status.SetNamedNumber("OutdoorTemperature", _outdoorHumidity); - - return status; - } - - public float GetOutdoorHumidity() - { - return _outdoorHumidity; - } - - internal void Update(float outdoorHumidity) - { - _outdoorHumidity = outdoorHumidity; - } - } -} diff --git a/SDK/ExternalServices/HA4IoT.ExternalServices.OpenWeatherMap/OpenWeatherMapOutdoorTemperatureService.cs b/SDK/ExternalServices/HA4IoT.ExternalServices.OpenWeatherMap/OpenWeatherMapOutdoorTemperatureService.cs deleted file mode 100644 index 504d0e92..00000000 --- a/SDK/ExternalServices/HA4IoT.ExternalServices.OpenWeatherMap/OpenWeatherMapOutdoorTemperatureService.cs +++ /dev/null @@ -1,30 +0,0 @@ -using Windows.Data.Json; -using HA4IoT.Contracts.Services; -using HA4IoT.Contracts.Services.Weather; -using HA4IoT.Networking; - -namespace HA4IoT.ExternalServices.OpenWeatherMap -{ - public class OpenWeatherMapOutdoorTemperatureService : ServiceBase, IOutdoorTemperatureService - { - private float _outdoorTemperature; - - public override JsonObject ExportStatusToJsonObject() - { - var status = base.ExportStatusToJsonObject(); - status.SetNamedNumber("OutdoorTemperature", _outdoorTemperature); - - return status; - } - - public float GetOutdoorTemperature() - { - return _outdoorTemperature; - } - - internal void Update(float outdoorTemperature) - { - _outdoorTemperature = outdoorTemperature; - } - } -} diff --git a/SDK/ExternalServices/HA4IoT.ExternalServices.OpenWeatherMap/OpenWeatherMapResponseParser.cs b/SDK/ExternalServices/HA4IoT.ExternalServices.OpenWeatherMap/OpenWeatherMapResponseParser.cs index 3097f68b..b957326f 100644 --- a/SDK/ExternalServices/HA4IoT.ExternalServices.OpenWeatherMap/OpenWeatherMapResponseParser.cs +++ b/SDK/ExternalServices/HA4IoT.ExternalServices.OpenWeatherMap/OpenWeatherMapResponseParser.cs @@ -1,7 +1,6 @@ using System; using System.Linq; using Windows.Data.Json; -using HA4IoT.Contracts.Services; using HA4IoT.Contracts.Services.Weather; namespace HA4IoT.ExternalServices.OpenWeatherMap @@ -16,7 +15,7 @@ public class OpenWeatherMapResponseParser public TimeSpan Sunset { get; private set; } - public WeatherSituation Situation { get; private set; } + public Weather Weather { get; private set; } public void Parse(string source) { @@ -33,7 +32,7 @@ public void Parse(string source) Sunset = UnixTimeStampToDateTime(sunsetValue).TimeOfDay; var situationValue = weather.First().GetObject().GetNamedValue("id"); - Situation = new OpenWeatherMapWeatherSituationParser().Parse(situationValue); + Weather = new OpenWeatherMapWeatherSituationParser().Parse(situationValue); Temperature = (float) main.GetNamedNumber("temp", 0); Humidity = (float) main.GetNamedNumber("humidity", 0); diff --git a/SDK/ExternalServices/HA4IoT.ExternalServices.OpenWeatherMap/OpenWeatherMapService.cs b/SDK/ExternalServices/HA4IoT.ExternalServices.OpenWeatherMap/OpenWeatherMapService.cs index bc99c880..d4b2e29c 100644 --- a/SDK/ExternalServices/HA4IoT.ExternalServices.OpenWeatherMap/OpenWeatherMapService.cs +++ b/SDK/ExternalServices/HA4IoT.ExternalServices.OpenWeatherMap/OpenWeatherMapService.cs @@ -7,29 +7,35 @@ using HA4IoT.Contracts.Core; using HA4IoT.Contracts.Logging; using HA4IoT.Contracts.Services; +using HA4IoT.Contracts.Services.Daylight; +using HA4IoT.Contracts.Services.OutdoorHumidity; +using HA4IoT.Contracts.Services.OutdoorTemperature; using HA4IoT.Contracts.Services.System; using HA4IoT.Contracts.Services.Weather; using HA4IoT.Networking; namespace HA4IoT.ExternalServices.OpenWeatherMap { - public class OpenWeatherMapService : ServiceBase + public class OpenWeatherMapService : ServiceBase, IOutdoorTemperatureProvider, IOutdoorHumidityProvider, IDaylightProvider, IWeatherProvider { private readonly string _cacheFilename = StoragePath.WithFilename("OpenWeatherMapCache.json"); private readonly IDateTimeService _dateTimeService; private readonly ISystemInformationService _systemInformationService; - - private readonly OpenWeatherMapOutdoorTemperatureService _outdoorTemperatureService = new OpenWeatherMapOutdoorTemperatureService(); - private readonly OpenWeatherMapOutdoorHumidityService _outdoorHumdityService = new OpenWeatherMapOutdoorHumidityService(); - private readonly OpenWeatherMapWeatherService _weatherService = new OpenWeatherMapWeatherService(); - private readonly OpenWeatherMapDaylightService _daylightService = new OpenWeatherMapDaylightService(); private string _previousResponse; + + private float _temperature; + private float _humidity; + private TimeSpan _sunrise; + private TimeSpan _sunset; + private Weather _weather; - public OpenWeatherMapService(IApiController apiController, IDateTimeService dateTimeService, ISchedulerService schedulerService, ISystemInformationService systemInformationService) + public OpenWeatherMapService( + IDateTimeService dateTimeService, + ISchedulerService schedulerService, + ISystemInformationService systemInformationService) { - if (apiController == null) throw new ArgumentNullException(nameof(apiController)); if (dateTimeService == null) throw new ArgumentNullException(nameof(dateTimeService)); if (systemInformationService == null) throw new ArgumentNullException(nameof(systemInformationService)); @@ -37,42 +43,29 @@ public OpenWeatherMapService(IApiController apiController, IDateTimeService date _systemInformationService = systemInformationService; LoadPersistedValues(); - - new OpenWeatherMapWeatherStationApiDispatcher(this, apiController).ExposeToApi(); - + schedulerService.RegisterSchedule("OpenWeatherMapServiceUpdater", TimeSpan.FromMinutes(5), Refresh); } + public event EventHandler OutdoorTemperatureFetched; + public event EventHandler OutdoorHumidityFetched; + public event EventHandler DaylightFetched; + public event EventHandler WeatherFetched; + public override JsonObject ExportStatusToJsonObject() { var result = new JsonObject(); - result.SetNamedString("situation", _weatherService.GetWeather().ToString()); - result.SetNamedNumber("temperature", _outdoorTemperatureService.GetOutdoorTemperature()); - result.SetNamedNumber("humidity", _outdoorHumdityService.GetOutdoorHumidity()); + result.SetNamedString("situation", _weather.ToString()); + result.SetNamedNumber("temperature", _temperature); + result.SetNamedNumber("humidity", _humidity); - result.SetNamedTimeSpan("sunrise", _daylightService.GetSunrise()); - result.SetNamedTimeSpan("sunset", _daylightService.GetSunset()); + result.SetNamedTimeSpan("sunrise", _sunrise); + result.SetNamedTimeSpan("sunset", _sunset); return result; } - public void SetStatus(WeatherSituation situation, float temperature, float humidity, TimeSpan sunrise, TimeSpan sunset) - { - _weatherService.Update(situation); - _outdoorTemperatureService.Update(temperature); - _outdoorHumdityService.Update(humidity); - _daylightService.Update(sunrise, sunset); - } - - public override void CompleteRegistration(IServiceLocator serviceLocator) - { - serviceLocator.RegisterService(typeof(IOutdoorTemperatureService), _outdoorTemperatureService); - serviceLocator.RegisterService(typeof(IOutdoorHumidityService), _outdoorHumdityService); - serviceLocator.RegisterService(typeof(IWeatherService), _weatherService); - serviceLocator.RegisterService(typeof(IDaylightService), _daylightService); - } - public override void HandleApiCommand(IApiContext apiContext) { Refresh(); @@ -95,10 +88,10 @@ private void Refresh() _previousResponse = response; - _systemInformationService.Set("OpenWeatherMapService/LastUpdatedTimestamp", _dateTimeService.GetDateTime()); + _systemInformationService.Set("OpenWeatherMapService/LastUpdatedTimestamp", _dateTimeService.Now); } - _systemInformationService.Set("OpenWeatherMapService/LastFetchedTimestamp", _dateTimeService.GetDateTime()); + _systemInformationService.Set("OpenWeatherMapService/LastFetchedTimestamp", _dateTimeService.Now); } private string FetchWeatherData() @@ -124,13 +117,28 @@ private string FetchWeatherData() private void ParseWeatherData(string weatherData) { - var parser = new OpenWeatherMapResponseParser(); - parser.Parse(weatherData); + try + { + var parser = new OpenWeatherMapResponseParser(); + parser.Parse(weatherData); + + _weather = parser.Weather; + WeatherFetched?.Invoke(this, new WeatherFetchedEventArgs(parser.Weather)); + + _temperature = parser.Temperature; + OutdoorTemperatureFetched?.Invoke(this, new OutdoorTemperatureFetchedEventArgs(_temperature)); - _weatherService.Update(parser.Situation); - _outdoorTemperatureService.Update(parser.Temperature); - _outdoorHumdityService.Update(parser.Humidity); - _daylightService.Update(parser.Sunrise, parser.Sunset); + _humidity = parser.Humidity; + OutdoorHumidityFetched?.Invoke(this, new OutdoorHumidityFetchedEventArgs(_humidity)); + + _sunrise = parser.Sunrise; + _sunset = parser.Sunset; + DaylightFetched?.Invoke(this, new DaylightFetchedEventArgs(_sunrise, _sunset)); + } + catch (Exception exception) + { + Log.Warning(exception, $"Error while parsing Open Weather Map response ({weatherData})."); + } } private void LoadPersistedValues() diff --git a/SDK/ExternalServices/HA4IoT.ExternalServices.OpenWeatherMap/OpenWeatherMapWeatherService.cs b/SDK/ExternalServices/HA4IoT.ExternalServices.OpenWeatherMap/OpenWeatherMapWeatherService.cs deleted file mode 100644 index 435449b5..00000000 --- a/SDK/ExternalServices/HA4IoT.ExternalServices.OpenWeatherMap/OpenWeatherMapWeatherService.cs +++ /dev/null @@ -1,30 +0,0 @@ -using Windows.Data.Json; -using HA4IoT.Contracts.Services; -using HA4IoT.Contracts.Services.Weather; -using HA4IoT.Networking; - -namespace HA4IoT.ExternalServices.OpenWeatherMap -{ - public class OpenWeatherMapWeatherService : ServiceBase, IWeatherService - { - private WeatherSituation _weather; - - public override JsonObject ExportStatusToJsonObject() - { - var status = base.ExportStatusToJsonObject(); - status.SetNamedString("Weather", _weather.ToString()); - - return status; - } - - public WeatherSituation GetWeather() - { - return _weather; - } - - internal void Update(WeatherSituation weather) - { - _weather = weather; - } - } -} diff --git a/SDK/ExternalServices/HA4IoT.ExternalServices.OpenWeatherMap/OpenWeatherMapWeatherSituationParser.cs b/SDK/ExternalServices/HA4IoT.ExternalServices.OpenWeatherMap/OpenWeatherMapWeatherSituationParser.cs index a5b05b87..aeba49ea 100644 --- a/SDK/ExternalServices/HA4IoT.ExternalServices.OpenWeatherMap/OpenWeatherMapWeatherSituationParser.cs +++ b/SDK/ExternalServices/HA4IoT.ExternalServices.OpenWeatherMap/OpenWeatherMapWeatherSituationParser.cs @@ -1,30 +1,29 @@ using System; using Windows.Data.Json; -using HA4IoT.Contracts.Services; using HA4IoT.Contracts.Services.Weather; namespace HA4IoT.ExternalServices.OpenWeatherMap { public class OpenWeatherMapWeatherSituationParser { - public WeatherSituation Parse(JsonValue id) + public Weather Parse(JsonValue id) { switch (Convert.ToInt32(id.GetNumber())) { - case 200: return WeatherSituation.ThunderstormWithLightRain; - case 201: return WeatherSituation.ThunderstormWithRain; - case 202: return WeatherSituation.ThunderstormWithHeavyRain; - case 210: return WeatherSituation.LightThunderstorm; - case 211: return WeatherSituation.Thunderstorm; - case 212: return WeatherSituation.HeavyThunderstorm; - case 221: return WeatherSituation.RaggedThunderstorm; - case 230: return WeatherSituation.ThunderstormWithLightDrizzle; - case 231: return WeatherSituation.ThunderstormWithDrizzle; - case 232: return WeatherSituation.ThunderstormWithHeavyDrizzle; + case 200: return Weather.ThunderstormWithLightRain; + case 201: return Weather.ThunderstormWithRain; + case 202: return Weather.ThunderstormWithHeavyRain; + case 210: return Weather.LightThunderstorm; + case 211: return Weather.Thunderstorm; + case 212: return Weather.HeavyThunderstorm; + case 221: return Weather.RaggedThunderstorm; + case 230: return Weather.ThunderstormWithLightDrizzle; + case 231: return Weather.ThunderstormWithDrizzle; + case 232: return Weather.ThunderstormWithHeavyDrizzle; - case 300: return WeatherSituation.LightIntensityDrizzle; - case 301: return WeatherSituation.Drizzle; - case 302: return WeatherSituation.HeavyIntensityDrizzle; + case 300: return Weather.LightIntensityDrizzle; + case 301: return Weather.Drizzle; + case 302: return Weather.HeavyIntensityDrizzle; //TODO: ////310 light intensity drizzle rain 09d @@ -34,39 +33,39 @@ public WeatherSituation Parse(JsonValue id) ////314 heavy shower rain and drizzle 09d ////321 shower drizzle 09d - case 500: return WeatherSituation.LightRain; - case 501: return WeatherSituation.ModerateRain; - case 502: return WeatherSituation.HeavyIntensityRain; - case 503: return WeatherSituation.VeryHeavyRain; - case 504: return WeatherSituation.ExtremeRain; - case 511: return WeatherSituation.FreezingRain; - case 520: return WeatherSituation.LightIntensityShowerRain; - case 521: return WeatherSituation.ShowerRain; - case 522: return WeatherSituation.HeavyIntensityShowerRain; - case 531: return WeatherSituation.RaggedShowerRain; + case 500: return Weather.LightRain; + case 501: return Weather.ModerateRain; + case 502: return Weather.HeavyIntensityRain; + case 503: return Weather.VeryHeavyRain; + case 504: return Weather.ExtremeRain; + case 511: return Weather.FreezingRain; + case 520: return Weather.LightIntensityShowerRain; + case 521: return Weather.ShowerRain; + case 522: return Weather.HeavyIntensityShowerRain; + case 531: return Weather.RaggedShowerRain; - case 600: return WeatherSituation.LightSnow; - case 601: return WeatherSituation.Snow; - case 602: return WeatherSituation.HeavySnow; - case 611: return WeatherSituation.Sleet; - case 612: return WeatherSituation.ShowerSleet; - case 615: return WeatherSituation.LightRainAndSnow; - case 616: return WeatherSituation.RainAndSnow; - case 620: return WeatherSituation.LightShowerSnow; - case 621: return WeatherSituation.ShowerSnow; - case 622: return WeatherSituation.HeavyShowerSnow; + case 600: return Weather.LightSnow; + case 601: return Weather.Snow; + case 602: return Weather.HeavySnow; + case 611: return Weather.Sleet; + case 612: return Weather.ShowerSleet; + case 615: return Weather.LightRainAndSnow; + case 616: return Weather.RainAndSnow; + case 620: return Weather.LightShowerSnow; + case 621: return Weather.ShowerSnow; + case 622: return Weather.HeavyShowerSnow; - case 701: return WeatherSituation.Mist; + case 701: return Weather.Mist; - case 800: return WeatherSituation.SkyIsClear; - case 801: return WeatherSituation.FewClouds; - case 802: return WeatherSituation.ScatteredClouds; - case 803: return WeatherSituation.BrokenClouds; - case 804: return WeatherSituation.OvercastClouds; + case 800: return Weather.SkyIsClear; + case 801: return Weather.FewClouds; + case 802: return Weather.ScatteredClouds; + case 803: return Weather.BrokenClouds; + case 804: return Weather.OvercastClouds; default: { - return WeatherSituation.Unknown; + return Weather.Unknown; } } } diff --git a/SDK/ExternalServices/HA4IoT.ExternalServices.OpenWeatherMap/OpenWeatherMapWeatherStationApiDispatcher.cs b/SDK/ExternalServices/HA4IoT.ExternalServices.OpenWeatherMap/OpenWeatherMapWeatherStationApiDispatcher.cs deleted file mode 100644 index 988885c9..00000000 --- a/SDK/ExternalServices/HA4IoT.ExternalServices.OpenWeatherMap/OpenWeatherMapWeatherStationApiDispatcher.cs +++ /dev/null @@ -1,47 +0,0 @@ -using System; -using HA4IoT.Contracts.Api; -using HA4IoT.Contracts.Services; -using HA4IoT.Contracts.Services.Weather; - -namespace HA4IoT.ExternalServices.OpenWeatherMap -{ - public class OpenWeatherMapWeatherStationApiDispatcher - { - // TODO: Consider add API handling methods to service interface. - private readonly OpenWeatherMapService _weatherStation; - private readonly IApiController _apiController; - - public OpenWeatherMapWeatherStationApiDispatcher(OpenWeatherMapService weatherStation, IApiController apiController) - { - if (weatherStation == null) throw new ArgumentNullException(nameof(weatherStation)); - if (apiController == null) throw new ArgumentNullException(nameof(apiController)); - - _weatherStation = weatherStation; - _apiController = apiController; - } - - public void ExposeToApi() - { - _apiController.RouteRequest("weatherStation", HandleApiGet); - _apiController.RouteCommand("weatherStation", HandleApiPost); - } - - private void HandleApiPost(IApiContext apiContext) - { - var situationValue = apiContext.Request.GetNamedString("situation", WeatherSituation.Unknown.ToString()); - var situation = (WeatherSituation)Enum.Parse(typeof (WeatherSituation), situationValue, true); - - var temperature = (float)apiContext.Request.GetNamedNumber("temperature"); - var humidity = (float)apiContext.Request.GetNamedNumber("humidity"); - var sunrise = TimeSpan.Parse(apiContext.Request.GetNamedString("sunrise")); - var sunset = TimeSpan.Parse(apiContext.Request.GetNamedString("sunset")); - - _weatherStation.SetStatus(situation, temperature, humidity, sunrise, sunset); - } - - private void HandleApiGet(IApiContext apiContext) - { - apiContext.Response = _weatherStation.ExportStatusToJsonObject(); - } - } -} diff --git a/SDK/HA4IoT.Automations/ConditionalOnAutomation.cs b/SDK/HA4IoT.Automations/ConditionalOnAutomation.cs index 2d1e966f..b66df233 100644 --- a/SDK/HA4IoT.Automations/ConditionalOnAutomation.cs +++ b/SDK/HA4IoT.Automations/ConditionalOnAutomation.cs @@ -6,6 +6,7 @@ using HA4IoT.Contracts.Actuators; using HA4IoT.Contracts.Automations; using HA4IoT.Contracts.Services; +using HA4IoT.Contracts.Services.Daylight; using HA4IoT.Contracts.Services.System; namespace HA4IoT.Automations @@ -29,7 +30,7 @@ public ConditionalOnAutomation(AutomationId id, ISchedulerService schedulerServi public ConditionalOnAutomation WithOnAtNightRange() { - var nightCondition = new TimeRangeCondition(_dateTimeService).WithStart(_daylightService.GetSunset).WithEnd(_daylightService.GetSunrise); + var nightCondition = new TimeRangeCondition(_dateTimeService).WithStart(_daylightService.Sunset).WithEnd(_daylightService.Sunrise); WithCondition(ConditionRelation.And, nightCondition); return this; diff --git a/SDK/HA4IoT.Automations/ConditionalOnAutomationExtensions.cs b/SDK/HA4IoT.Automations/ConditionalOnAutomationExtensions.cs index 16167e42..280ab2e3 100644 --- a/SDK/HA4IoT.Automations/ConditionalOnAutomationExtensions.cs +++ b/SDK/HA4IoT.Automations/ConditionalOnAutomationExtensions.cs @@ -1,6 +1,7 @@ using System; using HA4IoT.Contracts.Areas; using HA4IoT.Contracts.Services; +using HA4IoT.Contracts.Services.Daylight; using HA4IoT.Contracts.Services.System; namespace HA4IoT.Automations diff --git a/SDK/HA4IoT.Automations/RollerShutterAutomation.cs b/SDK/HA4IoT.Automations/RollerShutterAutomation.cs index 1006c323..c9bd3424 100644 --- a/SDK/HA4IoT.Automations/RollerShutterAutomation.cs +++ b/SDK/HA4IoT.Automations/RollerShutterAutomation.cs @@ -9,8 +9,9 @@ using HA4IoT.Contracts.Core; using HA4IoT.Contracts.Logging; using HA4IoT.Contracts.Services; +using HA4IoT.Contracts.Services.Daylight; +using HA4IoT.Contracts.Services.OutdoorTemperature; using HA4IoT.Contracts.Services.System; -using HA4IoT.Contracts.Services.Weather; namespace HA4IoT.Automations { @@ -147,7 +148,7 @@ public void PerformPendingActions() private bool DoNotOpenDueToTimeIsAffected() { if (SpecialSettingsWrapper.SkipBeforeTimestampIsEnabled && - SpecialSettingsWrapper.SkipBeforeTimestamp > _dateTimeService.GetTime()) + SpecialSettingsWrapper.SkipBeforeTimestamp > _dateTimeService.Time) { return true; } @@ -158,7 +159,7 @@ private bool DoNotOpenDueToTimeIsAffected() private bool TooHotIsAffected() { if (SpecialSettingsWrapper.AutoCloseIfTooHotIsEnabled && - _outdoorTemperatureService.GetOutdoorTemperature() > SpecialSettingsWrapper.AutoCloseIfTooHotTemperaure) + _outdoorTemperatureService.OutdoorTemperature > SpecialSettingsWrapper.AutoCloseIfTooHotTemperaure) { return true; } @@ -169,7 +170,7 @@ private bool TooHotIsAffected() private bool TooColdIsAffected() { if (SpecialSettingsWrapper.SkipIfFrozenIsEnabled && - _outdoorTemperatureService.GetOutdoorTemperature() < SpecialSettingsWrapper.SkipIfFrozenTemperature) + _outdoorTemperatureService.OutdoorTemperature < SpecialSettingsWrapper.SkipIfFrozenTemperature) { return true; } diff --git a/SDK/HA4IoT.Automations/RollerShutterAutomationExtensions.cs b/SDK/HA4IoT.Automations/RollerShutterAutomationExtensions.cs index ee29f216..f37768de 100644 --- a/SDK/HA4IoT.Automations/RollerShutterAutomationExtensions.cs +++ b/SDK/HA4IoT.Automations/RollerShutterAutomationExtensions.cs @@ -1,8 +1,9 @@ using System; using HA4IoT.Contracts.Areas; using HA4IoT.Contracts.Services; +using HA4IoT.Contracts.Services.Daylight; +using HA4IoT.Contracts.Services.OutdoorTemperature; using HA4IoT.Contracts.Services.System; -using HA4IoT.Contracts.Services.Weather; namespace HA4IoT.Automations { diff --git a/SDK/HA4IoT.Automations/TurnOnAndOffAutomation.cs b/SDK/HA4IoT.Automations/TurnOnAndOffAutomation.cs index 91a1d2d4..f0481cd3 100644 --- a/SDK/HA4IoT.Automations/TurnOnAndOffAutomation.cs +++ b/SDK/HA4IoT.Automations/TurnOnAndOffAutomation.cs @@ -11,6 +11,7 @@ using HA4IoT.Contracts.Core.Settings; using HA4IoT.Contracts.Sensors; using HA4IoT.Contracts.Services; +using HA4IoT.Contracts.Services.Daylight; using HA4IoT.Contracts.Services.System; using HA4IoT.Contracts.Triggers; @@ -133,8 +134,8 @@ public TurnOnAndOffAutomation WithEnabledAtDay(IDaylightService daylightService) { if (daylightService == null) throw new ArgumentNullException(nameof(daylightService)); - Func start = () => daylightService.GetSunrise().Add(TimeSpan.FromHours(1)); - Func end = () => daylightService.GetSunset().Subtract(TimeSpan.FromHours(1)); + Func start = () => daylightService.Sunrise.Add(TimeSpan.FromHours(1)); + Func end = () => daylightService.Sunset.Subtract(TimeSpan.FromHours(1)); _enablingConditionsValidator.WithCondition(ConditionRelation.Or, new TimeRangeCondition(_dateTimeService).WithStart(start).WithEnd(end)); return this; @@ -144,8 +145,8 @@ public TurnOnAndOffAutomation WithEnabledAtNight(IDaylightService daylightServic { if (daylightService == null) throw new ArgumentNullException(nameof(daylightService)); - Func start = () => daylightService.GetSunset().Subtract(TimeSpan.FromHours(1)); - Func end = () => daylightService.GetSunrise().Add(TimeSpan.FromHours(1)); + Func start = () => daylightService.Sunset.Subtract(TimeSpan.FromHours(1)); + Func end = () => daylightService.Sunrise.Add(TimeSpan.FromHours(1)); _enablingConditionsValidator.WithCondition(ConditionRelation.Or, new TimeRangeCondition(_dateTimeService).WithStart(start).WithEnd(end)); return this; diff --git a/SDK/HA4IoT.Conditions/Specialized/IsDayCondition.cs b/SDK/HA4IoT.Conditions/Specialized/IsDayCondition.cs index 39f1b9b8..53250d13 100644 --- a/SDK/HA4IoT.Conditions/Specialized/IsDayCondition.cs +++ b/SDK/HA4IoT.Conditions/Specialized/IsDayCondition.cs @@ -1,5 +1,6 @@ using System; using HA4IoT.Contracts.Services; +using HA4IoT.Contracts.Services.Daylight; using HA4IoT.Contracts.Services.System; namespace HA4IoT.Conditions.Specialized @@ -11,8 +12,8 @@ public IsDayCondition(IDaylightService daylightService, IDateTimeService dateTim { if (daylightService == null) throw new ArgumentNullException(nameof(daylightService)); - WithStart(daylightService.GetSunrise); - WithEnd(daylightService.GetSunset); + WithStart(daylightService.Sunrise); + WithEnd(daylightService.Sunset); } } } diff --git a/SDK/HA4IoT.Conditions/Specialized/IsNightCondition.cs b/SDK/HA4IoT.Conditions/Specialized/IsNightCondition.cs index 8ba51e42..c1ade6da 100644 --- a/SDK/HA4IoT.Conditions/Specialized/IsNightCondition.cs +++ b/SDK/HA4IoT.Conditions/Specialized/IsNightCondition.cs @@ -1,5 +1,6 @@ using System; using HA4IoT.Contracts.Services; +using HA4IoT.Contracts.Services.Daylight; using HA4IoT.Contracts.Services.System; namespace HA4IoT.Conditions.Specialized @@ -11,8 +12,8 @@ public IsNightCondition(IDaylightService daylightService, IDateTimeService dateT { if (daylightService == null) throw new ArgumentNullException(nameof(daylightService)); - WithStart(daylightService.GetSunset); - WithEnd(daylightService.GetSunrise); + WithStart(daylightService.Sunset); + WithEnd(daylightService.Sunrise); } } } diff --git a/SDK/HA4IoT.Conditions/Specialized/TimeRangeCondition.cs b/SDK/HA4IoT.Conditions/Specialized/TimeRangeCondition.cs index dd067383..63a3f6af 100644 --- a/SDK/HA4IoT.Conditions/Specialized/TimeRangeCondition.cs +++ b/SDK/HA4IoT.Conditions/Specialized/TimeRangeCondition.cs @@ -85,7 +85,7 @@ private ConditionState Check() } var timeRangeChecker = new TimeRangeChecker(); - if (timeRangeChecker.IsTimeInRange(_dateTimeService.GetTime(), startValue, endValue)) + if (timeRangeChecker.IsTimeInRange(_dateTimeService.Time, startValue, endValue)) { return ConditionState.Fulfilled; } diff --git a/SDK/HA4IoT.Configuration/DefaultConfigurationExtender.cs b/SDK/HA4IoT.Configuration/DefaultConfigurationExtender.cs index 59ba2196..82097121 100644 --- a/SDK/HA4IoT.Configuration/DefaultConfigurationExtender.cs +++ b/SDK/HA4IoT.Configuration/DefaultConfigurationExtender.cs @@ -80,7 +80,6 @@ private IDevice ParseI2CBus(XElement element) private IService ParseWeatherStation(XElement element) { return new OpenWeatherMapService( - Controller.ApiController, Controller.ServiceLocator.GetService(), Controller.ServiceLocator.GetService(), Controller.ServiceLocator.GetService()); diff --git a/SDK/HA4IoT.Contracts/HA4IoT.Contracts.csproj b/SDK/HA4IoT.Contracts/HA4IoT.Contracts.csproj index f389de5c..f641af1d 100644 --- a/SDK/HA4IoT.Contracts/HA4IoT.Contracts.csproj +++ b/SDK/HA4IoT.Contracts/HA4IoT.Contracts.csproj @@ -211,15 +211,23 @@ - + + + + + + - - + + + + + @@ -235,7 +243,7 @@ - + diff --git a/SDK/HA4IoT.Contracts/Services/Daylight/DaylightFetchedEventArgs.cs b/SDK/HA4IoT.Contracts/Services/Daylight/DaylightFetchedEventArgs.cs new file mode 100644 index 00000000..211f7e2d --- /dev/null +++ b/SDK/HA4IoT.Contracts/Services/Daylight/DaylightFetchedEventArgs.cs @@ -0,0 +1,17 @@ +using System; + +namespace HA4IoT.Contracts.Services.Daylight +{ + public class DaylightFetchedEventArgs : EventArgs + { + public DaylightFetchedEventArgs(TimeSpan sunrise, TimeSpan sunset) + { + Sunrise = sunrise; + Sunset = sunset; + } + + public TimeSpan Sunrise { get; } + + public TimeSpan Sunset { get; } + } +} diff --git a/SDK/HA4IoT.Contracts/Services/Daylight/IDaylightProvider.cs b/SDK/HA4IoT.Contracts/Services/Daylight/IDaylightProvider.cs new file mode 100644 index 00000000..267cc4b3 --- /dev/null +++ b/SDK/HA4IoT.Contracts/Services/Daylight/IDaylightProvider.cs @@ -0,0 +1,9 @@ +using System; + +namespace HA4IoT.Contracts.Services.Daylight +{ + public interface IDaylightProvider + { + event EventHandler DaylightFetched; + } +} diff --git a/SDK/HA4IoT.Contracts/Services/Daylight/IDaylightService.cs b/SDK/HA4IoT.Contracts/Services/Daylight/IDaylightService.cs new file mode 100644 index 00000000..a6fe7979 --- /dev/null +++ b/SDK/HA4IoT.Contracts/Services/Daylight/IDaylightService.cs @@ -0,0 +1,13 @@ +using System; + +namespace HA4IoT.Contracts.Services.Daylight +{ + public interface IDaylightService : IService + { + TimeSpan Sunrise { get; } + + TimeSpan Sunset { get; } + + DateTime? Timestamp { get; } + } +} diff --git a/SDK/HA4IoT.Contracts/Services/IDaylightService.cs b/SDK/HA4IoT.Contracts/Services/IDaylightService.cs deleted file mode 100644 index a7182688..00000000 --- a/SDK/HA4IoT.Contracts/Services/IDaylightService.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System; - -namespace HA4IoT.Contracts.Services -{ - public interface IDaylightService : IService - { - TimeSpan GetSunrise(); - - TimeSpan GetSunset(); - } -} diff --git a/SDK/HA4IoT.Contracts/Services/OutdoorHumidity/IOutdoorHumidityProvider.cs b/SDK/HA4IoT.Contracts/Services/OutdoorHumidity/IOutdoorHumidityProvider.cs new file mode 100644 index 00000000..7340157f --- /dev/null +++ b/SDK/HA4IoT.Contracts/Services/OutdoorHumidity/IOutdoorHumidityProvider.cs @@ -0,0 +1,9 @@ +using System; + +namespace HA4IoT.Contracts.Services.OutdoorHumidity +{ + public interface IOutdoorHumidityProvider + { + event EventHandler OutdoorHumidityFetched; + } +} diff --git a/SDK/HA4IoT.Contracts/Services/OutdoorHumidity/IOutdoorHumidityService.cs b/SDK/HA4IoT.Contracts/Services/OutdoorHumidity/IOutdoorHumidityService.cs new file mode 100644 index 00000000..9fef9b47 --- /dev/null +++ b/SDK/HA4IoT.Contracts/Services/OutdoorHumidity/IOutdoorHumidityService.cs @@ -0,0 +1,11 @@ +using System; + +namespace HA4IoT.Contracts.Services.OutdoorHumidity +{ + public interface IOutdoorHumidityService : IService + { + float OutdoorHumidity { get; } + + DateTime? Timestamp { get; } + } +} diff --git a/SDK/HA4IoT.Contracts/Services/OutdoorHumidity/OutdoorHumidityFetchedEventArgs.cs b/SDK/HA4IoT.Contracts/Services/OutdoorHumidity/OutdoorHumidityFetchedEventArgs.cs new file mode 100644 index 00000000..c67928c8 --- /dev/null +++ b/SDK/HA4IoT.Contracts/Services/OutdoorHumidity/OutdoorHumidityFetchedEventArgs.cs @@ -0,0 +1,14 @@ +using System; + +namespace HA4IoT.Contracts.Services.OutdoorHumidity +{ + public class OutdoorHumidityFetchedEventArgs : EventArgs + { + public OutdoorHumidityFetchedEventArgs(float value) + { + OutdoorHumidity = value; + } + + public float OutdoorHumidity { get; } + } +} diff --git a/SDK/HA4IoT.Contracts/Services/OutdoorTemperature/IOutdoorTemperatureProvider.cs b/SDK/HA4IoT.Contracts/Services/OutdoorTemperature/IOutdoorTemperatureProvider.cs new file mode 100644 index 00000000..c45541f2 --- /dev/null +++ b/SDK/HA4IoT.Contracts/Services/OutdoorTemperature/IOutdoorTemperatureProvider.cs @@ -0,0 +1,9 @@ +using System; + +namespace HA4IoT.Contracts.Services.OutdoorTemperature +{ + public interface IOutdoorTemperatureProvider + { + event EventHandler OutdoorTemperatureFetched; + } +} diff --git a/SDK/HA4IoT.Contracts/Services/OutdoorTemperature/IOutdoorTemperatureService.cs b/SDK/HA4IoT.Contracts/Services/OutdoorTemperature/IOutdoorTemperatureService.cs new file mode 100644 index 00000000..c693533e --- /dev/null +++ b/SDK/HA4IoT.Contracts/Services/OutdoorTemperature/IOutdoorTemperatureService.cs @@ -0,0 +1,11 @@ +using System; + +namespace HA4IoT.Contracts.Services.OutdoorTemperature +{ + public interface IOutdoorTemperatureService : IService + { + float OutdoorTemperature { get; } + + DateTime? Timestamp { get; } + } +} diff --git a/SDK/HA4IoT.Contracts/Services/OutdoorTemperature/OutdoorTemperatureFetchedEventArgs.cs b/SDK/HA4IoT.Contracts/Services/OutdoorTemperature/OutdoorTemperatureFetchedEventArgs.cs new file mode 100644 index 00000000..7e7b5fa7 --- /dev/null +++ b/SDK/HA4IoT.Contracts/Services/OutdoorTemperature/OutdoorTemperatureFetchedEventArgs.cs @@ -0,0 +1,14 @@ +using System; + +namespace HA4IoT.Contracts.Services.OutdoorTemperature +{ + public class OutdoorTemperatureFetchedEventArgs : EventArgs + { + public OutdoorTemperatureFetchedEventArgs(float value) + { + OutdoorTemperature = value; + } + + public float OutdoorTemperature { get; } + } +} diff --git a/SDK/HA4IoT.Contracts/Services/System/DateTimeService.cs b/SDK/HA4IoT.Contracts/Services/System/DateTimeService.cs index f7078a68..52d764cf 100644 --- a/SDK/HA4IoT.Contracts/Services/System/DateTimeService.cs +++ b/SDK/HA4IoT.Contracts/Services/System/DateTimeService.cs @@ -4,10 +4,10 @@ namespace HA4IoT.Contracts.Services.System { public interface IDateTimeService : IService { - DateTime GetDate(); + DateTime Date { get; } - TimeSpan GetTime(); + TimeSpan Time { get; } - DateTime GetDateTime(); + DateTime Now { get; } } } diff --git a/SDK/HA4IoT.Contracts/Services/Weather/IOutdoorHumidityService.cs b/SDK/HA4IoT.Contracts/Services/Weather/IOutdoorHumidityService.cs deleted file mode 100644 index 976b664d..00000000 --- a/SDK/HA4IoT.Contracts/Services/Weather/IOutdoorHumidityService.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace HA4IoT.Contracts.Services.Weather -{ - public interface IOutdoorHumidityService : IService - { - float GetOutdoorHumidity(); - } -} diff --git a/SDK/HA4IoT.Contracts/Services/Weather/IOutdoorTemperatureService.cs b/SDK/HA4IoT.Contracts/Services/Weather/IOutdoorTemperatureService.cs deleted file mode 100644 index 2821e80c..00000000 --- a/SDK/HA4IoT.Contracts/Services/Weather/IOutdoorTemperatureService.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace HA4IoT.Contracts.Services.Weather -{ - public interface IOutdoorTemperatureService : IService - { - float GetOutdoorTemperature(); - } -} diff --git a/SDK/HA4IoT.Contracts/Services/Weather/IWeatherProvider.cs b/SDK/HA4IoT.Contracts/Services/Weather/IWeatherProvider.cs new file mode 100644 index 00000000..862695ee --- /dev/null +++ b/SDK/HA4IoT.Contracts/Services/Weather/IWeatherProvider.cs @@ -0,0 +1,9 @@ +using System; + +namespace HA4IoT.Contracts.Services.Weather +{ + public interface IWeatherProvider + { + event EventHandler WeatherFetched; + } +} diff --git a/SDK/HA4IoT.Contracts/Services/Weather/IWeatherService.cs b/SDK/HA4IoT.Contracts/Services/Weather/IWeatherService.cs index a1b7c96a..608854f5 100644 --- a/SDK/HA4IoT.Contracts/Services/Weather/IWeatherService.cs +++ b/SDK/HA4IoT.Contracts/Services/Weather/IWeatherService.cs @@ -1,7 +1,11 @@ -namespace HA4IoT.Contracts.Services.Weather +using System; + +namespace HA4IoT.Contracts.Services.Weather { public interface IWeatherService : IService { - WeatherSituation GetWeather(); + Weather Weather { get; } + + DateTime? Timestamp { get; } } } diff --git a/SDK/HA4IoT.Contracts/Services/Weather/WeatherSituation.cs b/SDK/HA4IoT.Contracts/Services/Weather/Weather.cs similarity index 97% rename from SDK/HA4IoT.Contracts/Services/Weather/WeatherSituation.cs rename to SDK/HA4IoT.Contracts/Services/Weather/Weather.cs index ae2df973..2b4b710d 100644 --- a/SDK/HA4IoT.Contracts/Services/Weather/WeatherSituation.cs +++ b/SDK/HA4IoT.Contracts/Services/Weather/Weather.cs @@ -1,6 +1,6 @@ namespace HA4IoT.Contracts.Services.Weather { - public enum WeatherSituation + public enum Weather { Unknown, diff --git a/SDK/HA4IoT.Contracts/Services/Weather/WeatherFetchedEventArgs.cs b/SDK/HA4IoT.Contracts/Services/Weather/WeatherFetchedEventArgs.cs new file mode 100644 index 00000000..cd3f864d --- /dev/null +++ b/SDK/HA4IoT.Contracts/Services/Weather/WeatherFetchedEventArgs.cs @@ -0,0 +1,14 @@ +using System; + +namespace HA4IoT.Contracts.Services.Weather +{ + public class WeatherFetchedEventArgs : EventArgs + { + public WeatherFetchedEventArgs(Weather weather) + { + Weather = weather; + } + + public Weather Weather { get; } + } +} diff --git a/SDK/HA4IoT.Core/DateTimeService.cs b/SDK/HA4IoT.Core/DateTimeService.cs index 53259360..0b35dd56 100644 --- a/SDK/HA4IoT.Core/DateTimeService.cs +++ b/SDK/HA4IoT.Core/DateTimeService.cs @@ -8,26 +8,17 @@ namespace HA4IoT.Core { public class DateTimeService : ServiceBase, IDateTimeService { - public DateTime GetDate() - { - return DateTime.Now.Date; - } - - public TimeSpan GetTime() - { - return DateTime.Now.TimeOfDay; - } - - public DateTime GetDateTime() - { - return DateTime.Now; - } + public DateTime Date => DateTime.Now.Date; + public TimeSpan Time => DateTime.Now.TimeOfDay; + + public DateTime Now => DateTime.Now; + public override void HandleApiRequest(IApiContext apiContext) { - apiContext.Response.SetNamedDateTime("Date", GetDate()); - apiContext.Response.SetNamedTimeSpan("Time", GetTime()); - apiContext.Response.SetNamedDateTime("DateTime", GetDateTime()); + apiContext.Response.SetNamedDateTime("Date", Date); + apiContext.Response.SetNamedTimeSpan("Time", Time); + apiContext.Response.SetNamedDateTime("Now", Now); } } } diff --git a/SDK/HA4IoT.Networking/JsonObjectExtensions.cs b/SDK/HA4IoT.Networking/JsonObjectExtensions.cs index 986f83f9..ada6196d 100644 --- a/SDK/HA4IoT.Networking/JsonObjectExtensions.cs +++ b/SDK/HA4IoT.Networking/JsonObjectExtensions.cs @@ -1,6 +1,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Globalization; using System.Reflection; using System.Text; using Windows.Data.Json; @@ -294,6 +295,14 @@ public static void SetNamedNumber(this JsonObject jsonObject, string name, doubl } } + public static void SetNamedEnum(this JsonObject jsonObject, string name, Enum value) + { + if (jsonObject == null) throw new ArgumentNullException(nameof(jsonObject)); + if (name == null) throw new ArgumentNullException(nameof(name)); + + jsonObject.SetNamedValue(name, JsonValue.CreateStringValue(value.ToString())); + } + public static void SetNamedBoolean(this JsonObject jsonObject, string name, bool value) { if (jsonObject == null) throw new ArgumentNullException(nameof(jsonObject)); @@ -363,6 +372,20 @@ public static void SetNamedTimeSpan(this JsonObject jsonObject, string name, Tim } } + public static TimeSpan? GetNamedTimeSpan(this JsonObject jsonObject, string name) + { + if (jsonObject == null) throw new ArgumentNullException(nameof(jsonObject)); + if (name == null) throw new ArgumentNullException(nameof(name)); + + var value = jsonObject.GetNamedValue(name); + if (value.ValueType == JsonValueType.Null) + { + return null; + } + + return TimeSpan.ParseExact(value.GetString(), "c", DateTimeFormatInfo.InvariantInfo); + } + public static JsonObject WithNamedString(this JsonObject jsonObject, string name, string value) { if (jsonObject == null) throw new ArgumentNullException(nameof(jsonObject)); diff --git a/SDK/HA4IoT.PersonalAgent/PersonalAgentMessageProcessor.cs b/SDK/HA4IoT.PersonalAgent/PersonalAgentMessageProcessor.cs index eba83aec..633c4569 100644 --- a/SDK/HA4IoT.PersonalAgent/PersonalAgentMessageProcessor.cs +++ b/SDK/HA4IoT.PersonalAgent/PersonalAgentMessageProcessor.cs @@ -10,6 +10,8 @@ using HA4IoT.Components; using HA4IoT.Contracts.Logging; using HA4IoT.Contracts.Services; +using HA4IoT.Contracts.Services.OutdoorHumidity; +using HA4IoT.Contracts.Services.OutdoorTemperature; using HA4IoT.Contracts.Services.Weather; namespace HA4IoT.PersonalAgent @@ -183,9 +185,9 @@ private string GetWeatherStatus() var response = new StringBuilder(); response.AppendLine($"{Emoji.BarChart} Das Wetter ist aktuell:"); - response.AppendLine($"Temperatur: {outdoorTemperatureService.GetOutdoorTemperature()}°C"); - response.AppendLine($"Luftfeuchtigkeit: {outdoorHumidityService.GetOutdoorHumidity()}%"); - response.AppendLine($"Situation: {weatherService.GetWeather()}"); + response.AppendLine($"Temperatur: {outdoorTemperatureService.OutdoorTemperature}°C"); + response.AppendLine($"Luftfeuchtigkeit: {outdoorHumidityService.OutdoorHumidity}%"); + response.AppendLine($"Situation: {weatherService.Weather}"); return response.ToString(); } diff --git a/SDK/HA4IoT.Services/ControllerSlave/ControllerSlaveService.cs b/SDK/HA4IoT.Services/ControllerSlave/ControllerSlaveService.cs new file mode 100644 index 00000000..bb4cad0a --- /dev/null +++ b/SDK/HA4IoT.Services/ControllerSlave/ControllerSlaveService.cs @@ -0,0 +1,115 @@ +using System; +using HA4IoT.Contracts.Logging; +using HA4IoT.Contracts.Services; +using HA4IoT.Contracts.Services.Daylight; +using HA4IoT.Contracts.Services.OutdoorHumidity; +using HA4IoT.Contracts.Services.OutdoorTemperature; +using HA4IoT.Contracts.Services.Weather; +using System.Net.Http; +using Windows.Data.Json; +using HA4IoT.Contracts.Services.System; +using HA4IoT.Networking; + +namespace HA4IoT.Services.ControllerSlave +{ + public class ControllerSlaveService : ServiceBase, IOutdoorTemperatureProvider, IOutdoorHumidityProvider, IDaylightProvider, IWeatherProvider + { + private readonly string _masterControllerAddress; + private readonly IDateTimeService _dateTimeService; + + public event EventHandler OutdoorTemperatureFetched; + public event EventHandler OutdoorHumidityFetched; + public event EventHandler DaylightFetched; + public event EventHandler WeatherFetched; + + private DateTime? _lastPull; + private DateTime? _lastSuccessfulPull; + + public ControllerSlaveService(string masterControllerAddress, ISchedulerService scheduler, IDateTimeService dateTimeService) + { + if (masterControllerAddress == null) throw new ArgumentNullException(nameof(masterControllerAddress)); + if (scheduler == null) throw new ArgumentNullException(nameof(scheduler)); + if (dateTimeService == null) throw new ArgumentNullException(nameof(dateTimeService)); + + _masterControllerAddress = masterControllerAddress; + _dateTimeService = dateTimeService; + + scheduler.RegisterSchedule("ControllerSlavePolling", TimeSpan.FromMinutes(5), PullValues); + } + + public override JsonObject ExportStatusToJsonObject() + { + var status = base.ExportStatusToJsonObject(); + status.SetNamedDateTime("LastPull", _lastPull); + status.SetNamedDateTime("LastSuccessfulPull", _lastSuccessfulPull); + + return status; + } + + private void PullValues() + { + Log.Verbose($"Pulling values from master controller '{_masterControllerAddress}'."); + _lastPull = _dateTimeService.Now; + + try + { + PullOutsideTemperature(); + PullOutsideHumidity(); + PullDaylight(); + PullWeather(); + + _lastSuccessfulPull = _dateTimeService.Now; + } + catch (Exception exception) + { + Log.Warning(exception, "Unable to pull values from master controller."); + } + } + + private void PullWeather() + { + var response = PullValue("IWeatherService"); + var value = response.GetNamedString("Weather"); + var weather = (Weather)Enum.Parse(typeof(Weather), value); + WeatherFetched?.Invoke(this, new WeatherFetchedEventArgs(weather)); + } + + private void PullDaylight() + { + var response = PullValue("IDaylightService"); + var sunrise = response.GetNamedTimeSpan("Sunrise").Value; + var sunset = response.GetNamedTimeSpan("Sunset").Value; + DaylightFetched?.Invoke(this, new DaylightFetchedEventArgs(sunrise, sunset)); + } + + private void PullOutsideTemperature() + { + var response = PullValue("IOutdoorTemperatureService"); + var outsideTemperature = (float)response.GetNamedNumber("OutdoorTemperature"); + OutdoorTemperatureFetched?.Invoke(this, new OutdoorTemperatureFetchedEventArgs(outsideTemperature)); + } + + private void PullOutsideHumidity() + { + var response = PullValue("IOutdoorHumidityService"); + var outsideTemperature = (float)response.GetNamedNumber("OutdoorHumidity"); + OutdoorHumidityFetched?.Invoke(this, new OutdoorHumidityFetchedEventArgs(outsideTemperature)); + } + + private JsonObject PullValue(string serviceName) + { + var uri = new Uri($"http://{_masterControllerAddress}:80/api/service/{serviceName}"); + using (var webClient = new HttpClient()) + { + string body = webClient.GetStringAsync(uri).Result; + + if (body == null) + { + throw new Exception($"Received no response from '{uri}'."); + } + + return JsonObject.Parse(body); + } + } + } +} diff --git a/SDK/HA4IoT.Services/Environment/DaylightService.cs b/SDK/HA4IoT.Services/Environment/DaylightService.cs new file mode 100644 index 00000000..3233ae89 --- /dev/null +++ b/SDK/HA4IoT.Services/Environment/DaylightService.cs @@ -0,0 +1,44 @@ +using System; +using Windows.Data.Json; +using HA4IoT.Contracts.Services; +using HA4IoT.Contracts.Services.Daylight; +using HA4IoT.Contracts.Services.System; +using HA4IoT.Networking; + +namespace HA4IoT.Services.Environment +{ + public class DaylightService : ServiceBase, IDaylightService + { + private readonly IDateTimeService _dateTimeService; + + public DaylightService(IDaylightProvider provider, IDateTimeService dateTimeService) + { + if (provider == null) throw new ArgumentNullException(nameof(provider)); + if (dateTimeService == null) throw new ArgumentNullException(nameof(dateTimeService)); + + _dateTimeService = dateTimeService; + provider.DaylightFetched += Update; + } + + public TimeSpan Sunrise { get; private set; } + public TimeSpan Sunset { get; private set; } + public DateTime? Timestamp { get; private set; } + + public override JsonObject ExportStatusToJsonObject() + { + var status = base.ExportStatusToJsonObject(); + status.SetNamedTimeSpan("Sunrise", Sunrise); + status.SetNamedTimeSpan("Sunset", Sunset); + status.SetNamedDateTime("Timestamp", Timestamp); + + return status; + } + + private void Update(object sender, DaylightFetchedEventArgs e) + { + Sunrise = e.Sunrise; + Sunset = e.Sunset; + Timestamp = _dateTimeService.Now; + } + } +} diff --git a/SDK/HA4IoT.Services/Environment/OutdoorTemperatureService.cs b/SDK/HA4IoT.Services/Environment/OutdoorTemperatureService.cs new file mode 100644 index 00000000..1dc19607 --- /dev/null +++ b/SDK/HA4IoT.Services/Environment/OutdoorTemperatureService.cs @@ -0,0 +1,43 @@ +using System; +using Windows.Data.Json; +using HA4IoT.Contracts.Services; +using HA4IoT.Contracts.Services.OutdoorTemperature; +using HA4IoT.Contracts.Services.System; +using HA4IoT.Networking; + +namespace HA4IoT.Services.Environment +{ + public class OutdoorTemperatureService : ServiceBase, IOutdoorTemperatureService + { + private readonly IDateTimeService _dateTimeService; + + public OutdoorTemperatureService(IOutdoorTemperatureProvider provider, IDateTimeService dateTimeService) + { + if (provider == null) throw new ArgumentNullException(nameof(provider)); + if (dateTimeService == null) throw new ArgumentNullException(nameof(dateTimeService)); + + _dateTimeService = dateTimeService; + provider.OutdoorTemperatureFetched += Update; + } + + public float OutdoorTemperature { get; private set; } + + public DateTime? Timestamp { get; private set; } + + private void Update(object sender, OutdoorTemperatureFetchedEventArgs e) + { + // TODO: Check for significant changes and round value. + OutdoorTemperature = (float)Math.Round(Convert.ToDouble(e.OutdoorTemperature), 1); + Timestamp = _dateTimeService.Now; + } + + public override JsonObject ExportStatusToJsonObject() + { + var status = base.ExportStatusToJsonObject(); + status.SetNamedNumber("OutdoorTemperature", OutdoorTemperature); + status.SetNamedDateTime("Timestamp", Timestamp); + + return status; + } + } +} diff --git a/SDK/HA4IoT.Services/Environment/OutdootHumidityService.cs b/SDK/HA4IoT.Services/Environment/OutdootHumidityService.cs new file mode 100644 index 00000000..fc6a8567 --- /dev/null +++ b/SDK/HA4IoT.Services/Environment/OutdootHumidityService.cs @@ -0,0 +1,43 @@ +using System; +using Windows.Data.Json; +using HA4IoT.Contracts.Services; +using HA4IoT.Contracts.Services.OutdoorHumidity; +using HA4IoT.Contracts.Services.System; +using HA4IoT.Networking; + +namespace HA4IoT.Services.Environment +{ + public class OutdootHumidityService : ServiceBase, IOutdoorHumidityService + { + private readonly IDateTimeService _dateTimeService; + + public OutdootHumidityService(IOutdoorHumidityProvider provider, IDateTimeService dateTimeService) + { + if (provider == null) throw new ArgumentNullException(nameof(provider)); + if (dateTimeService == null) throw new ArgumentNullException(nameof(dateTimeService)); + + _dateTimeService = dateTimeService; + provider.OutdoorHumidityFetched += Update; + } + + public float OutdoorHumidity { get; private set; } + + public DateTime? Timestamp { get; private set; } + + private void Update(object sender, OutdoorHumidityFetchedEventArgs e) + { + // TODO: Check for significant changes and round value. + OutdoorHumidity = e.OutdoorHumidity; + Timestamp = _dateTimeService.Now; + } + + public override JsonObject ExportStatusToJsonObject() + { + var status = base.ExportStatusToJsonObject(); + status.SetNamedNumber("OutdoorHumidity", OutdoorHumidity); + status.SetNamedDateTime("Timestamp", Timestamp); + + return status; + } + } +} diff --git a/SDK/HA4IoT.Services/Environment/WeatherService.cs b/SDK/HA4IoT.Services/Environment/WeatherService.cs new file mode 100644 index 00000000..6681f6e7 --- /dev/null +++ b/SDK/HA4IoT.Services/Environment/WeatherService.cs @@ -0,0 +1,42 @@ +using System; +using Windows.Data.Json; +using HA4IoT.Contracts.Services; +using HA4IoT.Contracts.Services.System; +using HA4IoT.Contracts.Services.Weather; +using HA4IoT.Networking; + +namespace HA4IoT.Services.Environment +{ + public class WeatherService : ServiceBase, IWeatherService + { + private readonly IDateTimeService _dateTimeService; + + public WeatherService(IWeatherProvider provider, IDateTimeService dateTimeService) + { + if (provider == null) throw new ArgumentNullException(nameof(provider)); + if (dateTimeService == null) throw new ArgumentNullException(nameof(dateTimeService)); + + _dateTimeService = dateTimeService; + provider.WeatherFetched += Update; + } + + public DateTime? Timestamp { get; private set; } + + public Weather Weather { get; private set; } + + public override JsonObject ExportStatusToJsonObject() + { + var status = base.ExportStatusToJsonObject(); + status.SetNamedEnum("Weather", Weather); + status.SetNamedDateTime("Timestamp", Timestamp); + + return status; + } + + private void Update(object sender, WeatherFetchedEventArgs e) + { + Weather = e.Weather; + Timestamp = _dateTimeService.Now; + } + } +} diff --git a/SDK/HA4IoT.Services/HA4IoT.Services.csproj b/SDK/HA4IoT.Services/HA4IoT.Services.csproj new file mode 100644 index 00000000..b0066782 --- /dev/null +++ b/SDK/HA4IoT.Services/HA4IoT.Services.csproj @@ -0,0 +1,139 @@ + + + + + Debug + AnyCPU + {6FD41DDA-4369-43C1-807A-B1BC43ECBDBF} + Library + Properties + HA4IoT.Services + HA4IoT.Services + en-US + UAP + 10.0.10586.0 + 10.0.10586.0 + 14 + 512 + {A5A43C5B-DE2A-4C0C-9213-0A381AF9435A};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE;NETFX_CORE;WINDOWS_UWP + prompt + 4 + + + x86 + true + bin\x86\Debug\ + DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP + ;2008 + full + x86 + false + prompt + + + x86 + bin\x86\Release\ + TRACE;NETFX_CORE;WINDOWS_UWP + true + ;2008 + pdbonly + x86 + false + prompt + + + ARM + true + ..\bin\ARM\ + DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP + ;2008 + full + ARM + false + prompt + + + ARM + bin\ARM\Release\ + TRACE;NETFX_CORE;WINDOWS_UWP + true + ;2008 + pdbonly + ARM + false + prompt + + + x64 + true + bin\x64\Debug\ + DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP + ;2008 + full + x64 + false + prompt + + + x64 + bin\x64\Release\ + TRACE;NETFX_CORE;WINDOWS_UWP + true + ;2008 + pdbonly + x64 + false + prompt + + + + + + + + + + + + + + + + + {E1EDAC4B-83B9-46F4-9F6A-3BAE97D79F29} + HA4IoT.Contracts + + + {D4E0A3F9-6521-4AEE-815A-E2A60323FB63} + HA4IoT.Networking + + + + 14.0 + + + + \ No newline at end of file diff --git a/SDK/HA4IoT.Services/Properties/AssemblyInfo.cs b/SDK/HA4IoT.Services/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..f1c1927b --- /dev/null +++ b/SDK/HA4IoT.Services/Properties/AssemblyInfo.cs @@ -0,0 +1,14 @@ +using System.Reflection; +using System.Runtime.InteropServices; + +[assembly: AssemblyTitle("HA4IoT.Services")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Christian Kratky")] +[assembly: AssemblyProduct("HA4IoT")] +[assembly: AssemblyCopyright("Copyright © Christian Kratky 2016")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] +[assembly: ComVisible(false)] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/SDK/HA4IoT.Services/Properties/HA4IoT.Services.rd.xml b/SDK/HA4IoT.Services/Properties/HA4IoT.Services.rd.xml new file mode 100644 index 00000000..08b20150 --- /dev/null +++ b/SDK/HA4IoT.Services/Properties/HA4IoT.Services.rd.xml @@ -0,0 +1,33 @@ + + + + + + + + + diff --git a/SDK/HA4IoT.Services/project.json b/SDK/HA4IoT.Services/project.json new file mode 100644 index 00000000..92d14561 --- /dev/null +++ b/SDK/HA4IoT.Services/project.json @@ -0,0 +1,16 @@ +{ + "dependencies": { + "Microsoft.NETCore.UniversalWindowsPlatform": "5.1.0" + }, + "frameworks": { + "uap10.0": {} + }, + "runtimes": { + "win10-arm": {}, + "win10-arm-aot": {}, + "win10-x86": {}, + "win10-x86-aot": {}, + "win10-x64": {}, + "win10-x64-aot": {} + } +} \ No newline at end of file diff --git a/Tests/HA4IoT.Automations.Tests/ConditionalOnAutomationTests.cs b/Tests/HA4IoT.Automations.Tests/ConditionalOnAutomationTests.cs index 6fe5fff9..65611850 100644 --- a/Tests/HA4IoT.Automations.Tests/ConditionalOnAutomationTests.cs +++ b/Tests/HA4IoT.Automations.Tests/ConditionalOnAutomationTests.cs @@ -1,6 +1,7 @@ using FluentAssertions; using HA4IoT.Contracts.Actuators; using HA4IoT.Contracts.Services; +using HA4IoT.Contracts.Services.Daylight; using HA4IoT.Contracts.Services.System; using HA4IoT.Tests.Mockups; using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; diff --git a/Tests/HA4IoT.Automations.Tests/RollerShutterAutomationTests.cs b/Tests/HA4IoT.Automations.Tests/RollerShutterAutomationTests.cs index a26d847d..7261127c 100644 --- a/Tests/HA4IoT.Automations.Tests/RollerShutterAutomationTests.cs +++ b/Tests/HA4IoT.Automations.Tests/RollerShutterAutomationTests.cs @@ -23,14 +23,14 @@ public void SkipOpen_BecauseTooCold() { Setup(); - _weatherStation.SetTemperature(1.5F); + _weatherStation.OutdoorTemperature = 1.5F; _automation.WithDoNotOpenIfOutsideTemperatureIsBelowThan(2); _automation.PerformPendingActions(); _rollerShutter.GetState().ShouldBeEquivalentTo(RollerShutterStateId.Off); Setup(); - _weatherStation.SetTemperature(2.5F); + _weatherStation.OutdoorTemperature = 2.5F; _automation.WithDoNotOpenIfOutsideTemperatureIsBelowThan(2); _automation.PerformPendingActions(); _rollerShutter.GetState().ShouldBeEquivalentTo(RollerShutterStateId.MovingUp); @@ -42,12 +42,12 @@ public void Close_BecauseTooHot() Setup(); SkipOpenDueToSunrise(); - _weatherStation.SetTemperature(20F); + _weatherStation.OutdoorTemperature = 20F; _automation.WithCloseIfOutsideTemperatureIsGreaterThan(25); _automation.PerformPendingActions(); _rollerShutter.GetState().ShouldBeEquivalentTo(RollerShutterStateId.Off); - _weatherStation.SetTemperature(25.5F); + _weatherStation.OutdoorTemperature = 25.5F; _automation.PerformPendingActions(); _rollerShutter.GetState().ShouldBeEquivalentTo(RollerShutterStateId.MovingDown); } @@ -89,7 +89,7 @@ private void Setup() var testRollerShutterFactory = new TestRollerShutterFactory(_controller.Timer); _weatherStation = new TestWeatherStation(); - _weatherStation.SetTemperature(20); + _weatherStation.OutdoorTemperature = 20; _daylightService = new TestDaylightService(); _rollerShutter = testRollerShutterFactory.CreateTestRollerShutter(); diff --git a/Tests/HA4IoT.Configuration.Tests/ConfigurationParserTests.cs b/Tests/HA4IoT.Configuration.Tests/ConfigurationParserTests.cs index c864c83f..94ae43cf 100644 --- a/Tests/HA4IoT.Configuration.Tests/ConfigurationParserTests.cs +++ b/Tests/HA4IoT.Configuration.Tests/ConfigurationParserTests.cs @@ -7,6 +7,7 @@ using HA4IoT.Contracts.Components; using HA4IoT.Contracts.Core; using HA4IoT.Contracts.Hardware; +using HA4IoT.Contracts.Services; using HA4IoT.Contracts.Services.Weather; using HA4IoT.Hardware.CCTools; using HA4IoT.Hardware.I2CHardwareBridge; @@ -45,12 +46,12 @@ public void Parse_Areas() controller.GetAreas().Count.ShouldBeEquivalentTo(1); } - [TestMethod] - public void Parse_WeatherStation() - { - var controller = GetController(); - controller.ServiceLocator.GetService(); - } + ////[TestMethod] + ////public void Parse_WeatherStation() + ////{ + //// var controller = GetController(); + //// controller.ServiceLocator.GetService(); + ////} [TestMethod] public void Parse_Socket() diff --git a/Tests/HA4IoT.Core.Tests/ServiceLocatorTests.cs b/Tests/HA4IoT.Core.Tests/ServiceLocatorTests.cs index e63ecb3c..54bf6f48 100644 --- a/Tests/HA4IoT.Core.Tests/ServiceLocatorTests.cs +++ b/Tests/HA4IoT.Core.Tests/ServiceLocatorTests.cs @@ -4,6 +4,7 @@ using HA4IoT.Contracts.Api; using HA4IoT.Contracts.Core; using HA4IoT.Contracts.Services; +using HA4IoT.Contracts.Services.Daylight; using HA4IoT.Contracts.Services.System; using HA4IoT.Tests.Mockups; using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; @@ -115,20 +116,11 @@ public void CompleteRegistration(IServiceLocator serviceLocator) throw new NotImplementedException(); } - public DateTime GetDate() - { - throw new NotImplementedException(); - } - - public TimeSpan GetTime() - { - throw new NotImplementedException(); - } - - public DateTime GetDateTime() - { - throw new NotImplementedException(); - } + public DateTime Date { get; set; } + + public TimeSpan Time { get; set; } + + public DateTime Now { get; set; } } } } diff --git a/Tests/HA4IoT.Tests.Mockups/TestController.cs b/Tests/HA4IoT.Tests.Mockups/TestController.cs index da20a4d6..a86b3de7 100644 --- a/Tests/HA4IoT.Tests.Mockups/TestController.cs +++ b/Tests/HA4IoT.Tests.Mockups/TestController.cs @@ -1,6 +1,7 @@ using System; using HA4IoT.Contracts.Logging; using HA4IoT.Contracts.Services; +using HA4IoT.Contracts.Services.Daylight; using HA4IoT.Contracts.Services.System; using HA4IoT.Core; using HA4IoT.Core.Scheduling; diff --git a/Tests/HA4IoT.Tests.Mockups/TestDateTimeService.cs b/Tests/HA4IoT.Tests.Mockups/TestDateTimeService.cs index 0c85ea23..fdaa715d 100644 --- a/Tests/HA4IoT.Tests.Mockups/TestDateTimeService.cs +++ b/Tests/HA4IoT.Tests.Mockups/TestDateTimeService.cs @@ -13,19 +13,10 @@ public void SetTime(TimeSpan time) DateTime = new DateTime(DateTime.Year, DateTime.Month, DateTime.Day, time.Hours, time.Minutes, time.Seconds); } - public DateTime GetDate() - { - return DateTime.Date; - } - - public TimeSpan GetTime() - { - return DateTime.TimeOfDay; - } - - public DateTime GetDateTime() - { - return DateTime; - } + public DateTime Date => DateTime.Date; + + public TimeSpan Time => DateTime.TimeOfDay; + + public DateTime Now => this.DateTime; } } diff --git a/Tests/HA4IoT.Tests.Mockups/TestDaylightService.cs b/Tests/HA4IoT.Tests.Mockups/TestDaylightService.cs index e45770bb..8000fad7 100644 --- a/Tests/HA4IoT.Tests.Mockups/TestDaylightService.cs +++ b/Tests/HA4IoT.Tests.Mockups/TestDaylightService.cs @@ -1,5 +1,6 @@ using System; using HA4IoT.Contracts.Services; +using HA4IoT.Contracts.Services.Daylight; namespace HA4IoT.Tests.Mockups { @@ -13,15 +14,6 @@ public TestDaylightService() public TimeSpan Sunrise { get; set; } public TimeSpan Sunset { get; set; } - - public TimeSpan GetSunrise() - { - return Sunrise; - } - - public TimeSpan GetSunset() - { - return Sunset; - } + public DateTime? Timestamp { get; set; } } } diff --git a/Tests/HA4IoT.Tests.Mockups/TestWeatherStation.cs b/Tests/HA4IoT.Tests.Mockups/TestWeatherStation.cs index 3faeddb2..58296868 100644 --- a/Tests/HA4IoT.Tests.Mockups/TestWeatherStation.cs +++ b/Tests/HA4IoT.Tests.Mockups/TestWeatherStation.cs @@ -1,42 +1,23 @@ -using HA4IoT.Contracts.Services; +using System; +using HA4IoT.Contracts.Services; +using HA4IoT.Contracts.Services.OutdoorHumidity; +using HA4IoT.Contracts.Services.OutdoorTemperature; using HA4IoT.Contracts.Services.Weather; namespace HA4IoT.Tests.Mockups { public class TestWeatherStation : ServiceBase, IWeatherService, IOutdoorTemperatureService, IOutdoorHumidityService { - private float _temperature; - private float _humidity; - private WeatherSituation _weather; + public Weather Weather { get; set; } - public void SetTemperature(float value) - { - _temperature = value; - } + DateTime? IWeatherService.Timestamp { get; } - public void SetHumidity(float value) - { - _humidity = value; - } + public float OutdoorTemperature { get; set; } - public void SetWeather(WeatherSituation weather) - { - _weather = weather; - } + DateTime? IOutdoorTemperatureService.Timestamp { get; } - public WeatherSituation GetWeather() - { - return _weather; - } + public float OutdoorHumidity { get; set; } - public float GetOutdoorTemperature() - { - return _temperature; - } - - public float GetOutdoorHumidity() - { - return _humidity; - } + DateTime? IOutdoorHumidityService.Timestamp { get; } } } From c7b5995849cd88f6587f19355585e6b62d72c12f Mon Sep 17 00:00:00 2001 From: Christian Kratky Date: Sun, 14 Aug 2016 16:16:17 +0200 Subject: [PATCH 04/61] Add services --- .../HA4IoT.Controller.Cellar/Controller.cs | 12 +- .../HA4IoT.Controller.Default/Controller.cs | 6 +- .../HA4IoT.Controller.Demo/Controller.cs | 24 +- .../HA4IoT.Controller.Local/Controller.cs | 22 +- .../HA4IoT.Controller.Local.csproj | 4 + .../CatLitterBoxSender.cs | 13 +- .../HA4IoT.Controller.Main/Controller.cs | 119 +------- .../HA4IoT.Controller.Main.csproj | 1 - .../Rooms/BedroomConfiguration.cs | 55 ++-- .../Rooms/ChildrensRoomConfiguration.cs | 50 ++-- .../Rooms/FloorConfiguration.cs | 63 ++-- .../Rooms/KitchenConfiguration.cs | 63 ++-- .../Rooms/LivingRoomConfiguration.cs | 46 +-- .../Rooms/LowerBathroomConfiguration.cs | 45 ++- .../Rooms/OfficeConfiguration.cs | 76 +++-- .../Rooms/ReadingRoomConfiguration.cs | 50 ++-- .../Rooms/RoomConfiguration.cs | 27 -- .../Rooms/StoreroomConfiguration.cs | 61 ++-- .../Rooms/UpperBathroomConfiguration.cs | 58 ++-- .../HA4IoT.Controller.Main/StartupTask.cs | 164 ++++++++++- HA4IoT.sln | 15 +- .../LocalHttpServerApiDispatcherEndpoint.cs | 6 +- .../{ApiController.cs => ApiService.cs} | 13 +- SDK/Api/HA4IoT.Api/HA4IoT.Api.csproj | 2 +- .../PersonalAgentToTelegramBotDispatcher.cs | 16 +- .../HA4IoT.ExternalServices.Twitter.csproj | 4 +- .../TweetAction.cs | 6 +- ...tterService.cs => TwitterClientService.cs} | 2 +- ...tory.cs => TwitterClientServiceFactory.cs} | 8 +- SDK/HA4IoT.Actuators/ActuatorExtensions.cs | 9 - SDK/HA4IoT.Actuators/Animations/Animation.cs | 15 +- .../Animations/DirectionAnimation.cs | 3 +- .../LogicalBinaryStateActuator.cs | 9 +- .../LogicalBinaryStateActuatorExtensions.cs | 2 +- .../RollerShutters/RollerShutter.cs | 9 +- .../RollerShutters/RollerShutterExtensions.cs | 2 +- .../HA4IoT.Components.csproj | 4 - .../ConfigurationExtenderBase.cs | 67 ----- .../ConfigurationExtensions.cs | 154 ---------- .../ConfigurationParser.cs | 181 ------------ .../DefaultConfigurationExtender.cs | 239 ---------------- .../HA4IoT.Configuration.csproj | 39 --- .../Pi2ConfigurationExtender.cs | 6 - .../Api/{IApiController.cs => IApiService.cs} | 2 +- .../Areas}/AreaIdFactory.cs | 3 +- SDK/HA4IoT.Contracts/Areas/IArea.cs | 13 +- SDK/HA4IoT.Contracts/Areas/IAreaService.cs | 15 + ...ionController.cs => IAutomationService.cs} | 3 +- .../IComponentService.cs} | 7 +- SDK/HA4IoT.Contracts/Core/IAreaController.cs | 14 - SDK/HA4IoT.Contracts/Core/IController.cs | 11 +- .../Core/IHomeAutomationTimer.cs | 9 - SDK/HA4IoT.Contracts/Core/IInitializer.cs | 12 + .../Core/IServiceController.cs | 17 -- .../Core/IStartupCompletedNotification.cs | 7 + .../Core/ServiceAlreadyRegisteredException.cs | 12 - SDK/HA4IoT.Contracts/Core/ServiceLocator.cs | 79 ------ .../Core/ServiceNotRegisteredException.cs | 12 - .../Core/ServiceRegistration.cs | 21 -- SDK/HA4IoT.Contracts/Core/TimedAction.cs | 11 +- SDK/HA4IoT.Contracts/HA4IoT.Contracts.csproj | 25 +- .../Hardware/IBinaryInputController.cs | 2 +- .../Hardware/IBinaryOutputController.cs | 2 +- .../Services/System/IContainerService.cs | 15 + ...DateTimeService.cs => IDateTimeService.cs} | 0 .../System/IDeviceService.cs} | 4 +- .../System/II2CBusService.cs} | 5 +- .../Services/System/ITimerService.cs | 12 + SDK/HA4IoT.Core/AreaCollection.cs | 10 - SDK/HA4IoT.Core/ControllerApiDispatcher.cs | 72 ++++- SDK/HA4IoT.Core/ControllerBase.cs | 268 ++++++------------ SDK/HA4IoT.Core/ControllerExtensions.cs | 26 -- .../{Discovery => }/DiscoveryServer.cs | 2 +- SDK/HA4IoT.Core/HA4IoT.Core.csproj | 37 ++- SDK/HA4IoT.Core/project.json | 3 +- SDK/HA4IoT.Logger/UdpLogger.cs | 2 +- .../HA4IoT.PersonalAgent.csproj | 4 - .../MessageContextFactory.cs | 13 +- .../PersonalAgentMessageProcessor.cs | 52 ++-- .../PersonalAgentToApiDispatcher.cs | 16 +- SDK/HA4IoT.PersonalAgent/SynonymService.cs | 20 +- .../SynonymServiceStorage.cs | 16 +- SDK/HA4IoT.Sensors/Buttons/Button.cs | 5 +- .../Buttons/ButtonExtensions.cs | 8 +- .../Areas}/Area.cs | 28 +- SDK/HA4IoT.Services/Areas/AreaCollection.cs | 8 + SDK/HA4IoT.Services/Areas/AreaService.cs | 50 ++++ .../Areas/AreaServiceExtensions.cs | 21 ++ .../Areas}/AreaSettingsWrapper.cs | 2 +- .../Automations}/AutomationCollection.cs | 2 +- .../Automations/AutomationService.cs | 36 +++ .../Components/ComponentCollection.cs} | 5 +- .../Components/ComponentService.cs | 63 ++++ .../ControllerSlave/ControllerSlaveService.cs | 10 +- .../ControllerSlaveServiceOptions.cs | 7 + .../Devices}/DeviceCollection.cs | 2 +- SDK/HA4IoT.Services/Devices/DeviceService.cs | 37 +++ .../Devices/DeviceServiceExtensions.cs | 18 ++ .../GenericControllerCollection.cs | 2 +- SDK/HA4IoT.Services/HA4IoT.Services.csproj | 36 +++ .../Health}/HealthService.cs | 27 +- .../Health/HealthServiceOptions.cs | 7 + .../Scheduling/Schedule.cs | 2 +- .../Scheduling/SchedulerService.cs | 15 +- .../System/ContainerService.cs | 41 +++ .../System}/DateTimeService.cs | 2 +- .../System}/SystemInformationService.cs | 5 +- .../System}/Timeout.cs | 2 +- .../System/TimerService.cs} | 8 +- SDK/HA4IoT.Services/project.json | 3 +- SDK/HA4IoT.Settings/HA4IoT.Settings.csproj | 126 ++++++++ .../Properties/AssemblyInfo.cs | 14 + .../Properties/HA4IoT.Settings.rd.xml | 33 +++ .../SettingsContainer.cs | 4 +- .../SettingsContainerApiDispatcher.cs | 8 +- SDK/HA4IoT.Settings/project.json | 16 ++ SDK/HA4IoT.Telemetry/ActuatorMonitor.cs | 17 +- .../ComponentStateHistoryTracker.cs | 2 +- ...rdController.cs => CCToolsBoardService.cs} | 60 ++-- .../CCToolsConfigurationExtender.cs | 157 ---------- .../HA4IoT.Hardware.CCTools.csproj | 7 +- .../HSPE16InputOnly.cs | 3 +- .../HSPE16OutputOnly.cs | 3 +- .../HA4IoT.Hardware.CCTools/HSPE8InputOnly.cs | 3 +- .../HSPE8OutputOnly.cs | 3 +- .../HA4IoT.Hardware.CCTools/HSREL5.cs | 3 +- .../HA4IoT.Hardware.CCTools/HSREL8.cs | 3 +- .../HA4IoT.Hardware.CCTools/HSRT16.cs | 3 +- .../I2CHardwareBridge.cs | 5 +- .../I2CHardwareBridgeConfigurationExtender.cs | 3 +- .../HA4IoT.Hardware.Pi2.csproj | 4 +- .../{Pi2Port.cs => Pi2Gpio.cs} | 4 +- ...Pi2PortController.cs => Pi2GpioService.cs} | 35 ++- .../MAX7311Driver.cs | 5 +- .../PCA9555ADriver.cs | 3 +- .../PCA9555Driver.cs | 3 +- .../PCF8574ADriver.cs | 3 +- .../PCF8574Driver.cs | 5 +- .../HA4IoT.Hardware.RemoteSwitch.csproj | 2 +- .../LPD433MhzSignalSender.cs | 2 +- ...etController.cs => RemoteSocketService.cs} | 19 +- ...iltInI2CBus.cs => BuiltInI2CBusService.cs} | 30 +- .../HA4IoT.Hardware/ControllerExtensions.cs | 14 - .../HA4IoT.Hardware/HA4IoT.Hardware.csproj | 3 +- .../AutomaticTurnOnAndOffAutomationTests.cs | 16 +- .../LogicalBinaryStateActuatorTests.cs | 2 +- .../RollerShutterTests.cs | 2 +- Tests/HA4IoT.Actuators.Tests/TriggerTests.cs | 2 +- .../AutomationTests.cs | 4 +- .../ConditionalOnAutomationTests.cs | 2 +- .../RollerShutterAutomationTests.cs | 3 +- .../ConfigurationParserTests.cs | 3 +- .../HA4IoT.Configuration.Tests.csproj | 1 - .../TestConfigurationExtender.cs | 28 -- .../HA4IoT.Core.Tests.csproj | 1 - .../HA4IoT.Core.Tests/ServiceLocatorTests.cs | 126 -------- Tests/HA4IoT.Tests.Mockups/TestButton.cs | 5 +- .../HA4IoT.Tests.Mockups/TestButtonFactory.cs | 11 +- Tests/HA4IoT.Tests.Mockups/TestController.cs | 4 +- .../TestHomeAutomationTimer.cs | 3 +- .../TestHttpRequestController.cs | 2 +- Tests/HA4IoT.Tests.Mockups/TestI2CBus.cs | 3 +- .../HA4IoT.Tests.Mockups/TestRollerShutter.cs | 5 +- .../TestRollerShutterFactory.cs | 11 +- 164 files changed, 1699 insertions(+), 2216 deletions(-) delete mode 100644 Controllers/HA4IoT.Controller.Main/Rooms/RoomConfiguration.cs rename SDK/Api/HA4IoT.Api/{ApiController.cs => ApiService.cs} (94%) rename SDK/ExternalServices/HA4IoT.ExternalServices.Twitter/{TwitterService.cs => TwitterClientService.cs} (98%) rename SDK/ExternalServices/HA4IoT.ExternalServices.Twitter/{TwitterServiceFactory.cs => TwitterClientServiceFactory.cs} (88%) delete mode 100644 SDK/HA4IoT.Configuration/ConfigurationExtenderBase.cs delete mode 100644 SDK/HA4IoT.Configuration/ConfigurationExtensions.cs delete mode 100644 SDK/HA4IoT.Configuration/ConfigurationParser.cs delete mode 100644 SDK/HA4IoT.Configuration/DefaultConfigurationExtender.cs delete mode 100644 SDK/HA4IoT.Configuration/Pi2ConfigurationExtender.cs rename SDK/HA4IoT.Contracts/Api/{IApiController.cs => IApiService.cs} (90%) rename SDK/{HA4IoT.Core => HA4IoT.Contracts/Areas}/AreaIdFactory.cs (77%) create mode 100644 SDK/HA4IoT.Contracts/Areas/IAreaService.cs rename SDK/HA4IoT.Contracts/Automations/{IAutomationController.cs => IAutomationService.cs} (81%) rename SDK/HA4IoT.Contracts/{Core/IActuatorController.cs => Components/IComponentService.cs} (70%) delete mode 100644 SDK/HA4IoT.Contracts/Core/IAreaController.cs delete mode 100644 SDK/HA4IoT.Contracts/Core/IHomeAutomationTimer.cs create mode 100644 SDK/HA4IoT.Contracts/Core/IInitializer.cs delete mode 100644 SDK/HA4IoT.Contracts/Core/IServiceController.cs create mode 100644 SDK/HA4IoT.Contracts/Core/IStartupCompletedNotification.cs delete mode 100644 SDK/HA4IoT.Contracts/Core/ServiceAlreadyRegisteredException.cs delete mode 100644 SDK/HA4IoT.Contracts/Core/ServiceLocator.cs delete mode 100644 SDK/HA4IoT.Contracts/Core/ServiceNotRegisteredException.cs delete mode 100644 SDK/HA4IoT.Contracts/Core/ServiceRegistration.cs create mode 100644 SDK/HA4IoT.Contracts/Services/System/IContainerService.cs rename SDK/HA4IoT.Contracts/Services/System/{DateTimeService.cs => IDateTimeService.cs} (100%) rename SDK/HA4IoT.Contracts/{Core/IDeviceController.cs => Services/System/IDeviceService.cs} (80%) rename SDK/HA4IoT.Contracts/{Hardware/II2CBus.cs => Services/System/II2CBusService.cs} (84%) create mode 100644 SDK/HA4IoT.Contracts/Services/System/ITimerService.cs delete mode 100644 SDK/HA4IoT.Core/AreaCollection.cs delete mode 100644 SDK/HA4IoT.Core/ControllerExtensions.cs rename SDK/HA4IoT.Core/{Discovery => }/DiscoveryServer.cs (98%) rename SDK/{HA4IoT.Core => HA4IoT.Services/Areas}/Area.cs (79%) create mode 100644 SDK/HA4IoT.Services/Areas/AreaCollection.cs create mode 100644 SDK/HA4IoT.Services/Areas/AreaService.cs create mode 100644 SDK/HA4IoT.Services/Areas/AreaServiceExtensions.cs rename SDK/{HA4IoT.Core => HA4IoT.Services/Areas}/AreaSettingsWrapper.cs (94%) rename SDK/{HA4IoT.Core => HA4IoT.Services/Automations}/AutomationCollection.cs (79%) create mode 100644 SDK/HA4IoT.Services/Automations/AutomationService.cs rename SDK/{HA4IoT.Core/ActuatorCollection.cs => HA4IoT.Services/Components/ComponentCollection.cs} (53%) create mode 100644 SDK/HA4IoT.Services/Components/ComponentService.cs create mode 100644 SDK/HA4IoT.Services/ControllerSlave/ControllerSlaveServiceOptions.cs rename SDK/{HA4IoT.Core => HA4IoT.Services/Devices}/DeviceCollection.cs (79%) create mode 100644 SDK/HA4IoT.Services/Devices/DeviceService.cs create mode 100644 SDK/HA4IoT.Services/Devices/DeviceServiceExtensions.cs rename SDK/{HA4IoT.Core => HA4IoT.Services}/GenericControllerCollection.cs (98%) rename SDK/{HA4IoT.Core => HA4IoT.Services/Health}/HealthService.cs (78%) create mode 100644 SDK/HA4IoT.Services/Health/HealthServiceOptions.cs rename SDK/{HA4IoT.Core => HA4IoT.Services}/Scheduling/Schedule.cs (94%) rename SDK/{HA4IoT.Core => HA4IoT.Services}/Scheduling/SchedulerService.cs (89%) create mode 100644 SDK/HA4IoT.Services/System/ContainerService.cs rename SDK/{HA4IoT.Core => HA4IoT.Services/System}/DateTimeService.cs (95%) rename SDK/{HA4IoT.Core => HA4IoT.Services/System}/SystemInformationService.cs (92%) rename SDK/{HA4IoT.Core/Timer => HA4IoT.Services/System}/Timeout.cs (97%) rename SDK/{HA4IoT.Core/Timer/HomeAutomationTimer.cs => HA4IoT.Services/System/TimerService.cs} (78%) create mode 100644 SDK/HA4IoT.Settings/HA4IoT.Settings.csproj create mode 100644 SDK/HA4IoT.Settings/Properties/AssemblyInfo.cs create mode 100644 SDK/HA4IoT.Settings/Properties/HA4IoT.Settings.rd.xml rename SDK/{HA4IoT.Core/Settings => HA4IoT.Settings}/SettingsContainer.cs (98%) rename SDK/{HA4IoT.Core/Settings => HA4IoT.Settings}/SettingsContainerApiDispatcher.cs (84%) create mode 100644 SDK/HA4IoT.Settings/project.json rename SDK/Hardware/HA4IoT.Hardware.CCTools/{CCToolsBoardController.cs => CCToolsBoardService.cs} (64%) delete mode 100644 SDK/Hardware/HA4IoT.Hardware.CCTools/CCToolsConfigurationExtender.cs rename SDK/Hardware/HA4IoT.Hardware.Pi2/{Pi2Port.cs => Pi2Gpio.cs} (96%) rename SDK/Hardware/HA4IoT.Hardware.Pi2/{Pi2PortController.cs => Pi2GpioService.cs} (56%) rename SDK/Hardware/HA4IoT.Hardware.RemoteSwitch/{RemoteSocketController.cs => RemoteSocketService.cs} (78%) rename SDK/Hardware/HA4IoT.Hardware/{BuiltInI2CBus.cs => BuiltInI2CBusService.cs} (83%) delete mode 100644 SDK/Hardware/HA4IoT.Hardware/ControllerExtensions.cs delete mode 100644 Tests/HA4IoT.Configuration.Tests/TestConfigurationExtender.cs delete mode 100644 Tests/HA4IoT.Core.Tests/ServiceLocatorTests.cs diff --git a/Controllers/HA4IoT.Controller.Cellar/Controller.cs b/Controllers/HA4IoT.Controller.Cellar/Controller.cs index c6c9cfd7..8ca9900d 100644 --- a/Controllers/HA4IoT.Controller.Cellar/Controller.cs +++ b/Controllers/HA4IoT.Controller.Cellar/Controller.cs @@ -59,12 +59,10 @@ public Controller(int statusLedNumber) { } - protected override async Task ConfigureAsync() + protected override async Task ConfigureAsync(IDeviceService deviceService) { - var pi2PortController = new Pi2PortController(); - - AddDevice(new BuiltInI2CBus()); - + var pi2PortController = new Pi2GpioService(); + var openWeatherMapService = new OpenWeatherMapService( ServiceLocator.GetService(), ServiceLocator.GetService(), @@ -76,7 +74,7 @@ protected override async Task ConfigureAsync() ServiceLocator.RegisterService(typeof(IWeatherService), new WeatherService(openWeatherMapService, ServiceLocator.GetService())); ServiceLocator.RegisterService(typeof(OpenWeatherMapService), openWeatherMapService); - var ccToolsFactory = new CCToolsBoardController(this, GetDevice()); + var ccToolsFactory = new CCToolsBoardService(this, GetDevice()); var hsrt16 = ccToolsFactory.CreateHSRT16(Device.CellarHSRT16, new I2CSlaveAddress(32)); var garden = this.CreateArea(RoomId.Garden) @@ -98,7 +96,7 @@ protected override async Task ConfigureAsync() .WithOnAtNightRange() .WithOffBetweenRange(TimeSpan.Parse("22:30:00"), TimeSpan.Parse("05:00:00")); - Timer.Tick += (s, e) => { pi2PortController.PollOpenInputPorts(); }; + TimerService.Tick += (s, e) => { pi2PortController.PollOpenInputPorts(); }; await base.ConfigureAsync(); } diff --git a/Controllers/HA4IoT.Controller.Default/Controller.cs b/Controllers/HA4IoT.Controller.Default/Controller.cs index 003f6aa8..eeaf64cf 100644 --- a/Controllers/HA4IoT.Controller.Default/Controller.cs +++ b/Controllers/HA4IoT.Controller.Default/Controller.cs @@ -28,10 +28,8 @@ public Controller() protected override async Task ConfigureAsync() { - AddDevice(new BuiltInI2CBus()); - - var pi2PortController = new Pi2PortController(); - var ccToolsBoardController = new CCToolsBoardController(this, GetDevice()); + var pi2PortController = new Pi2GpioService(); + var ccToolsBoardController = new CCToolsBoardService(this, GetDevice()); AddDevice(pi2PortController); AddDevice(ccToolsBoardController); diff --git a/Controllers/HA4IoT.Controller.Demo/Controller.cs b/Controllers/HA4IoT.Controller.Demo/Controller.cs index 7f6fd7e9..b63fde2e 100644 --- a/Controllers/HA4IoT.Controller.Demo/Controller.cs +++ b/Controllers/HA4IoT.Controller.Demo/Controller.cs @@ -1,12 +1,8 @@ using System; using System.Threading.Tasks; -using HA4IoT.Actuators.Connectors; using HA4IoT.Actuators.Lamps; -using HA4IoT.Actuators.RollerShutters; -using HA4IoT.Actuators.Sockets; using HA4IoT.Actuators.StateMachines; using HA4IoT.Actuators.Triggers; -using HA4IoT.Automations; using HA4IoT.Contracts.Actions; using HA4IoT.Contracts.Actuators; using HA4IoT.Contracts.Areas; @@ -25,15 +21,11 @@ using HA4IoT.Hardware; using HA4IoT.Hardware.CCTools; using HA4IoT.Hardware.I2CHardwareBridge; -using HA4IoT.Hardware.Pi2; using HA4IoT.Hardware.RemoteSwitch; using HA4IoT.Hardware.RemoteSwitch.Codes; using HA4IoT.PersonalAgent; using HA4IoT.Sensors.Buttons; using HA4IoT.Sensors.HumiditySensors; -using HA4IoT.Sensors.MotionDetectors; -using HA4IoT.Sensors.TemperatureSensors; -using HA4IoT.Sensors.Windows; namespace HA4IoT.Controller.Demo { @@ -47,18 +39,10 @@ public Controller() { } - protected override async Task ConfigureAsync() + protected override async Task ConfigureAsync(IDeviceService deviceService) { - AddDevice(new BuiltInI2CBus()); - - var piPortController = new Pi2PortController(); - AddDevice(piPortController); - - var ccToolsBoardController = new CCToolsBoardController(this, GetDevice()); - AddDevice(ccToolsBoardController); - // Setup the remote switch 433Mhz sender which is attached to the I2C bus (Arduino Nano). - AddDevice(new I2CHardwareBridge(new I2CSlaveAddress(50), GetDevice(), ServiceLocator.GetService())); + deviceService.AddDevice(new I2CHardwareBridge(new I2CSlaveAddress(50), GetDevice(), ServiceLocator.GetService())); ServiceLocator.RegisterService(typeof(SynonymService), new SynonymService()); ServiceLocator.RegisterService(typeof (OpenWeatherMapService), @@ -72,7 +56,7 @@ protected override async Task ConfigureAsync() ServiceLocator.GetService().TryLoadPersistedSynonyms(); ServiceLocator.GetService().RegisterDefaultComponentStateSynonyms(this); - Timer.Tick += (s, e) => + TimerService.Tick += (s, e) => { piPortController.PollOpenInputPorts(); ccToolsBoardController.PollInputBoardStates(); @@ -163,7 +147,7 @@ private void SetupTelegramBot() private void SetupRoom() { - var ccToolsBoardController = GetDevice(); + var ccToolsBoardController = GetDevice(); var hspe16 = ccToolsBoardController.CreateHSPE16InputOnly(InstalledDevice.HSPE16, new I2CSlaveAddress(41)); var hsrel8 = ccToolsBoardController.CreateHSREL8(InstalledDevice.HSRel8, new I2CSlaveAddress(40)); diff --git a/Controllers/HA4IoT.Controller.Local/Controller.cs b/Controllers/HA4IoT.Controller.Local/Controller.cs index d68a443f..d22b45cb 100644 --- a/Controllers/HA4IoT.Controller.Local/Controller.cs +++ b/Controllers/HA4IoT.Controller.Local/Controller.cs @@ -9,6 +9,7 @@ using HA4IoT.Contracts.Areas; using HA4IoT.Contracts.Components; using HA4IoT.Contracts.Sensors; +using HA4IoT.Contracts.Services.System; using HA4IoT.Core; using HA4IoT.Hardware.Knx; @@ -26,9 +27,12 @@ public Controller(MainPage mainPage) _mainPage = mainPage; } - protected override async Task ConfigureAsync() + protected override async Task ConfigureAsync(IContainerService factoryService) { - var area = new Area(new AreaId("TestArea"), this); + var areaService = factoryService.GetInstance(); + var timerService = factoryService.GetInstance(); + + var area = areaService.CreateArea(new AreaId("TestArea")); area.AddComponent(new Lamp(new ComponentId("Lamp1"), await _mainPage.CreateDemoBinaryComponent("Lamp 1"))); area.AddComponent(new Lamp(new ComponentId("Lamp2"), await _mainPage.CreateDemoBinaryComponent("Lamp 2"))); area.AddComponent(new Lamp(new ComponentId("Lamp3"), await _mainPage.CreateDemoBinaryComponent("Lamp 3"))); @@ -40,11 +44,11 @@ protected override async Task ConfigureAsync() area.AddComponent(new Socket(new ComponentId("Socket2"), knxController.CreateDigitalJoinEndpoint("d2"))); area.AddComponent(new Socket(new ComponentId("Socket3"), knxController.CreateDigitalJoinEndpoint("d30"))); - area.AddComponent(new Sensors.Buttons.Button(new ComponentId("Button1"), await _mainPage.CreateDemoButton("Button 1"), Timer)); - area.AddComponent(new Sensors.Buttons.Button(new ComponentId("Button2"), await _mainPage.CreateDemoButton("Button 2"), Timer)); - area.AddComponent(new Sensors.Buttons.Button(new ComponentId("Button3"), await _mainPage.CreateDemoButton("Button 3"), Timer)); - area.AddComponent(new Sensors.Buttons.Button(new ComponentId("Button4"), await _mainPage.CreateDemoButton("Button 4"), Timer)); - area.AddComponent(new Sensors.Buttons.Button(new ComponentId("Button5"), await _mainPage.CreateDemoButton("Button 5"), Timer)); + area.AddComponent(new Sensors.Buttons.Button(new ComponentId("Button1"), await _mainPage.CreateDemoButton("Button 1"), timerService)); + area.AddComponent(new Sensors.Buttons.Button(new ComponentId("Button2"), await _mainPage.CreateDemoButton("Button 2"), timerService)); + area.AddComponent(new Sensors.Buttons.Button(new ComponentId("Button3"), await _mainPage.CreateDemoButton("Button 3"), timerService)); + area.AddComponent(new Sensors.Buttons.Button(new ComponentId("Button4"), await _mainPage.CreateDemoButton("Button 4"), timerService)); + area.AddComponent(new Sensors.Buttons.Button(new ComponentId("Button5"), await _mainPage.CreateDemoButton("Button 5"), timerService)); area.GetComponent(new ComponentId("Button1")).GetPressedShortlyTrigger().Attach(area.GetComponent(new ComponentId("Lamp1")).GetSetNextStateAction()); area.GetComponent(new ComponentId("Button1")).GetPressedLongTrigger().Attach(area.GetComponent(new ComponentId("Lamp2")).GetSetNextStateAction()); @@ -60,8 +64,8 @@ protected override async Task ConfigureAsync() area.GetComponent("Button5".AsComponentId()) .GetPressedShortlyTrigger() .Attach(area.GetComponent("Socket3".AsComponentId()).GetSetNextStateAction()); - - AddArea(area); + + areaService.AddArea(area); } } } diff --git a/Controllers/HA4IoT.Controller.Local/HA4IoT.Controller.Local.csproj b/Controllers/HA4IoT.Controller.Local/HA4IoT.Controller.Local.csproj index 4cfd4e15..624c0da5 100644 --- a/Controllers/HA4IoT.Controller.Local/HA4IoT.Controller.Local.csproj +++ b/Controllers/HA4IoT.Controller.Local/HA4IoT.Controller.Local.csproj @@ -163,6 +163,10 @@ {8892e736-cdd0-48eb-ad9e-a1c8aa230fd7} HA4IoT.Sensors + + {6FD41DDA-4369-43C1-807A-B1BC43ECBDBF} + HA4IoT.Services + {1EC3A5D0-65C8-4396-BD56-9179A8BD00D4} HA4IoT.Hardware.Knx diff --git a/Controllers/HA4IoT.Controller.Main/CatLitterBoxSender.cs b/Controllers/HA4IoT.Controller.Main/CatLitterBoxSender.cs index 4a6eb277..a1a1b570 100644 --- a/Controllers/HA4IoT.Controller.Main/CatLitterBoxSender.cs +++ b/Controllers/HA4IoT.Controller.Main/CatLitterBoxSender.cs @@ -4,8 +4,9 @@ using HA4IoT.Contracts.Core; using HA4IoT.Contracts.Logging; using HA4IoT.Contracts.Sensors; -using HA4IoT.Core.Timer; +using HA4IoT.Contracts.Services.System; using HA4IoT.ExternalServices.Twitter; +using HA4IoT.Services.System; namespace HA4IoT.Controller.Main { @@ -37,11 +38,11 @@ internal class CatLitterBoxTwitterSender "Hey, this one looks like you :-)" }; - public CatLitterBoxTwitterSender(IHomeAutomationTimer timer) + public CatLitterBoxTwitterSender(ITimerService timerService) { - if (timer == null) throw new ArgumentNullException(nameof(timer)); + if (timerService == null) throw new ArgumentNullException(nameof(timerService)); - timer.Tick += Tick; + timerService.Tick += Tick; } public CatLitterBoxTwitterSender WithTrigger(IMotionDetector motionDetector) @@ -98,8 +99,8 @@ private async Task Tweet(TimeSpan timeInLitterBox) try { - TwitterService twitterService; - if (!TwitterServiceFactory.TryCreateFromDefaultConfigurationFile(out twitterService)) + TwitterClientService twitterService; + if (!TwitterClientServiceFactory.TryCreateFromDefaultConfigurationFile(out twitterService)) { Log.Verbose("Twitter API is disabled."); return; diff --git a/Controllers/HA4IoT.Controller.Main/Controller.cs b/Controllers/HA4IoT.Controller.Main/Controller.cs index 9c73e56f..6994f9ad 100644 --- a/Controllers/HA4IoT.Controller.Main/Controller.cs +++ b/Controllers/HA4IoT.Controller.Main/Controller.cs @@ -1,4 +1,5 @@ using System.Threading.Tasks; +using HA4IoT.Contracts.Core; using HA4IoT.Contracts.Hardware; using HA4IoT.Contracts.Logging; using HA4IoT.Controller.Main.Rooms; @@ -20,7 +21,6 @@ using HA4IoT.Contracts.Services.System; using HA4IoT.Contracts.Services.Weather; using HA4IoT.PersonalAgent; -using HA4IoT.Services; using HA4IoT.Services.ControllerSlave; using HA4IoT.Services.Environment; @@ -35,124 +35,9 @@ public Controller() { } - protected override async Task ConfigureAsync() + protected override async Task ConfigureAsync(IContainerService factoryService) { - AddDevice(new BuiltInI2CBus()); - - var ccToolsBoardController = new CCToolsBoardController(this, GetDevice()); - - AddDevice(new Pi2PortController()); - AddDevice(ccToolsBoardController); - AddDevice(new I2CHardwareBridge(new I2CSlaveAddress(50), GetDevice(), ServiceLocator.GetService())); - AddDevice(SetupRemoteSwitchController()); - - ServiceLocator.RegisterService(typeof(SynonymService), new SynonymService()); - - SetupOpenWeatherMapService(); - SetupTelegramBot(); - SetupTwitterClient(); - - ServiceLocator.GetService().TryLoadPersistedSynonyms(); - - ccToolsBoardController.CreateHSPE16InputOnly(InstalledDevice.Input0, new I2CSlaveAddress(42)); - ccToolsBoardController.CreateHSPE16InputOnly(InstalledDevice.Input1, new I2CSlaveAddress(43)); - ccToolsBoardController.CreateHSPE16InputOnly(InstalledDevice.Input2, new I2CSlaveAddress(47)); - ccToolsBoardController.CreateHSPE16InputOnly(InstalledDevice.Input3, new I2CSlaveAddress(45)); - ccToolsBoardController.CreateHSPE16InputOnly(InstalledDevice.Input4, new I2CSlaveAddress(46)); - ccToolsBoardController.CreateHSPE16InputOnly(InstalledDevice.Input5, new I2CSlaveAddress(44)); - - new BedroomConfiguration(this).Setup(); - new OfficeConfiguration(this).Setup(); - new UpperBathroomConfiguration(this).Setup(); - new ReadingRoomConfiguration(this).Setup(); - new ChildrensRoomRoomConfiguration(this).Setup(); - new KitchenConfiguration(this).Setup(); - new FloorConfiguration(this).Setup(); - new LowerBathroomConfiguration(this).Setup(); - new StoreroomConfiguration(this).Setup(); - new LivingRoomConfiguration(this).Setup(); - - ServiceLocator.GetService().RegisterDefaultComponentStateSynonyms(this); - - InitializeAzureCloudApiEndpoint(); - - var ioBoardsInterruptMonitor = new InterruptMonitor(GetDevice().GetInput(4)); - ioBoardsInterruptMonitor.InterruptDetected += (s, e) => ccToolsBoardController.PollInputBoardStates(); - ioBoardsInterruptMonitor.Start(); - await base.ConfigureAsync(); } - - private void SetupOpenWeatherMapService() - { - var controllerSlaveService = new ControllerSlaveService("127.0.0.1", ServiceLocator.GetService(), ServiceLocator.GetService()); - ServiceLocator.RegisterService(typeof(ControllerSlaveService), controllerSlaveService); - - var openWeatherMapService = new OpenWeatherMapService( - ServiceLocator.GetService(), - ServiceLocator.GetService(), - ServiceLocator.GetService()); - - ServiceLocator.RegisterService(typeof(IOutdoorTemperatureService), new OutdoorTemperatureService(openWeatherMapService, ServiceLocator.GetService())); - ServiceLocator.RegisterService(typeof(IOutdoorHumidityService), new OutdootHumidityService(openWeatherMapService, ServiceLocator.GetService())); - ServiceLocator.RegisterService(typeof(IDaylightService), new DaylightService(openWeatherMapService, ServiceLocator.GetService())); - ServiceLocator.RegisterService(typeof(IWeatherService), new WeatherService(openWeatherMapService, ServiceLocator.GetService())); - ServiceLocator.RegisterService(typeof(OpenWeatherMapService), openWeatherMapService); - } - - private void SetupTelegramBot() - { - TelegramBotService telegramBotService; - if (!TelegramBotServiceFactory.TryCreateFromDefaultConfigurationFile(out telegramBotService)) - { - return; - } - - Log.WarningLogged += (s, e) => - { - telegramBotService.EnqueueMessageForAdministrators($"{Emoji.WarningSign} {e.Message}\r\n{e.Exception}", TelegramMessageFormat.PlainText); - }; - - Log.ErrorLogged += (s, e) => - { - if (e.Message.StartsWith("Sending Telegram message failed")) - { - // Prevent recursive send of sending failures. - return; - } - - telegramBotService.EnqueueMessageForAdministrators($"{Emoji.HeavyExclamationMark} {e.Message}\r\n{e.Exception}", TelegramMessageFormat.PlainText); - }; - - telegramBotService.EnqueueMessageForAdministrators($"{Emoji.Bell} Das System ist gestartet."); - new PersonalAgentToTelegramBotDispatcher(this).ExposeToTelegramBot(telegramBotService); - - ServiceLocator.RegisterService(typeof(TelegramBotService), telegramBotService); - } - - private void SetupTwitterClient() - { - TwitterService twitterService; - if (!TwitterServiceFactory.TryCreateFromDefaultConfigurationFile(out twitterService)) - { - return; - } - - ServiceLocator.RegisterService(typeof(TwitterService), twitterService); - } - - private RemoteSocketController SetupRemoteSwitchController() - { - const int LDP433MhzSenderPin = 10; - - var i2cHardwareBridge = GetDevice(); - var brennenstuhl = new BrennenstuhlCodeSequenceProvider(); - var ldp433MHzSender = new LPD433MHzSignalSender(i2cHardwareBridge, LDP433MhzSenderPin, ApiController); - - var remoteSwitchController = new RemoteSocketController(ldp433MHzSender, ServiceLocator.GetService()) - .WithRemoteSocket(0, brennenstuhl.GetSequencePair(BrennenstuhlSystemCode.AllOn, BrennenstuhlUnitCode.A)); - - return remoteSwitchController; - } } } diff --git a/Controllers/HA4IoT.Controller.Main/HA4IoT.Controller.Main.csproj b/Controllers/HA4IoT.Controller.Main/HA4IoT.Controller.Main.csproj index e654035c..449bd17e 100644 --- a/Controllers/HA4IoT.Controller.Main/HA4IoT.Controller.Main.csproj +++ b/Controllers/HA4IoT.Controller.Main/HA4IoT.Controller.Main.csproj @@ -113,7 +113,6 @@ - diff --git a/Controllers/HA4IoT.Controller.Main/Rooms/BedroomConfiguration.cs b/Controllers/HA4IoT.Controller.Main/Rooms/BedroomConfiguration.cs index a518a461..afb72871 100644 --- a/Controllers/HA4IoT.Controller.Main/Rooms/BedroomConfiguration.cs +++ b/Controllers/HA4IoT.Controller.Main/Rooms/BedroomConfiguration.cs @@ -9,10 +9,8 @@ using HA4IoT.Contracts.Areas; using HA4IoT.Contracts.Components; using HA4IoT.Contracts.Hardware; -using HA4IoT.Contracts.Services; using HA4IoT.Contracts.Services.Daylight; -using HA4IoT.Core; -using HA4IoT.Hardware; +using HA4IoT.Contracts.Services.System; using HA4IoT.Hardware.CCTools; using HA4IoT.Hardware.I2CHardwareBridge; using HA4IoT.PersonalAgent; @@ -21,11 +19,19 @@ using HA4IoT.Sensors.MotionDetectors; using HA4IoT.Sensors.TemperatureSensors; using HA4IoT.Sensors.Windows; +using HA4IoT.Services.Areas; +using HA4IoT.Services.Devices; namespace HA4IoT.Controller.Main.Rooms { - internal class BedroomConfiguration : RoomConfiguration + internal class BedroomConfiguration { + private readonly IDeviceService _deviceService; + private readonly IAreaService _areaService; + private readonly IDaylightService _daylightService; + private readonly CCToolsBoardService _ccToolsBoardService; + private readonly SynonymService _synonymService; + private enum Bedroom { TemperatureSensor, @@ -70,24 +76,39 @@ private enum Bedroom WindowRight } - public BedroomConfiguration(Controller controller) - : base(controller) + public BedroomConfiguration( + IDeviceService deviceService, + IAreaService areaService, + IDaylightService daylightService, + CCToolsBoardService ccToolsBoardService, + SynonymService synonymService) { + if (deviceService == null) throw new ArgumentNullException(nameof(deviceService)); + if (areaService == null) throw new ArgumentNullException(nameof(areaService)); + if (daylightService == null) throw new ArgumentNullException(nameof(daylightService)); + if (ccToolsBoardService == null) throw new ArgumentNullException(nameof(ccToolsBoardService)); + if (synonymService == null) throw new ArgumentNullException(nameof(synonymService)); + + _deviceService = deviceService; + _areaService = areaService; + _daylightService = daylightService; + _ccToolsBoardService = ccToolsBoardService; + _synonymService = synonymService; } - public override void Setup() + public void Setup() { - var hsrel5 = CCToolsBoardController.CreateHSREL5(InstalledDevice.BedroomHSREL5, new I2CSlaveAddress(38)); - var hsrel8 = CCToolsBoardController.CreateHSREL8(InstalledDevice.BedroomHSREL8, new I2CSlaveAddress(21)); - var input5 = Controller.Device(InstalledDevice.Input5); - var input4 = Controller.Device(InstalledDevice.Input4); + var hsrel5 = _ccToolsBoardService.CreateHSREL5(InstalledDevice.BedroomHSREL5, new I2CSlaveAddress(38)); + var hsrel8 = _ccToolsBoardService.CreateHSREL8(InstalledDevice.BedroomHSREL8, new I2CSlaveAddress(21)); + var input5 = _deviceService.GetDevice(InstalledDevice.Input5); + var input4 = _deviceService.GetDevice(InstalledDevice.Input4); + var i2CHardwareBridge = _deviceService.GetDevice(); - var i2cHardwareBridge = Controller.GetDevice(); const int SensorPin = 6; - var room = Controller.CreateArea(Room.Bedroom) - .WithTemperatureSensor(Bedroom.TemperatureSensor, i2cHardwareBridge.DHT22Accessor.GetTemperatureSensor(SensorPin)) - .WithHumiditySensor(Bedroom.HumiditySensor, i2cHardwareBridge.DHT22Accessor.GetHumiditySensor(SensorPin)) + var room = _areaService.CreateArea(Room.Bedroom) + .WithTemperatureSensor(Bedroom.TemperatureSensor, i2CHardwareBridge.DHT22Accessor.GetTemperatureSensor(SensorPin)) + .WithHumiditySensor(Bedroom.HumiditySensor, i2CHardwareBridge.DHT22Accessor.GetHumiditySensor(SensorPin)) .WithMotionDetector(Bedroom.MotionDetector, input5.GetInput(12)) .WithLamp(Bedroom.LightCeiling, hsrel5.GetOutput(5).WithInvertedState()) .WithLamp(Bedroom.LightCeilingWindow, hsrel5.GetOutput(6).WithInvertedState()) @@ -144,7 +165,7 @@ public override void Setup() .WithTarget(room.GetStateMachine(Bedroom.LightCeiling)) .WithOnDuration(TimeSpan.FromSeconds(15)) .WithTurnOnIfAllRollerShuttersClosed(room.GetRollerShutter(Bedroom.RollerShutterLeft), room.GetRollerShutter(Bedroom.RollerShutterRight)) - .WithEnabledAtNight(Controller.ServiceLocator.GetService()) + .WithEnabledAtNight(_daylightService) .WithSkipIfAnyActuatorIsAlreadyOn(room.GetLamp(Bedroom.LampBedLeft), room.GetLamp(Bedroom.LampBedRight)); room.WithStateMachine(Bedroom.Fan, (s, r) => SetupFan(s, r, hsrel8)); @@ -159,7 +180,7 @@ public override void Setup() room.GetButton(Bedroom.ButtonBedRightOuter).WithPressedShortlyAction(() => room.GetStateMachine(Bedroom.Fan).SetNextState()); room.GetButton(Bedroom.ButtonBedRightOuter).WithPressedLongAction(() => room.GetStateMachine(Bedroom.Fan).TryTurnOff()); - Controller.ServiceLocator.GetService().AddSynonymsForArea(Room.Bedroom, "Schlafzimmer", "Bedroom"); + _synonymService.AddSynonymsForArea(Room.Bedroom, "Schlafzimmer", "Bedroom"); } private void SetupFan(StateMachine fan, IArea room, HSREL8 hsrel8) diff --git a/Controllers/HA4IoT.Controller.Main/Rooms/ChildrensRoomConfiguration.cs b/Controllers/HA4IoT.Controller.Main/Rooms/ChildrensRoomConfiguration.cs index 35285e30..5be24e1b 100644 --- a/Controllers/HA4IoT.Controller.Main/Rooms/ChildrensRoomConfiguration.cs +++ b/Controllers/HA4IoT.Controller.Main/Rooms/ChildrensRoomConfiguration.cs @@ -1,12 +1,12 @@ -using HA4IoT.Actuators.Connectors; +using System; +using HA4IoT.Actuators.Connectors; using HA4IoT.Actuators.Lamps; using HA4IoT.Actuators.RollerShutters; using HA4IoT.Actuators.Sockets; using HA4IoT.Automations; -using HA4IoT.Contracts.Core; +using HA4IoT.Contracts.Areas; using HA4IoT.Contracts.Hardware; -using HA4IoT.Core; -using HA4IoT.Hardware; +using HA4IoT.Contracts.Services.System; using HA4IoT.Hardware.CCTools; using HA4IoT.Hardware.I2CHardwareBridge; using HA4IoT.PersonalAgent; @@ -14,11 +14,18 @@ using HA4IoT.Sensors.HumiditySensors; using HA4IoT.Sensors.TemperatureSensors; using HA4IoT.Sensors.Windows; +using HA4IoT.Services.Areas; +using HA4IoT.Services.Devices; namespace HA4IoT.Controller.Main.Rooms { - internal class ChildrensRoomRoomConfiguration : RoomConfiguration + internal class ChildrensRoomRoomConfiguration { + private readonly IAreaService _areaService; + private readonly SynonymService _synonymService; + private readonly IDeviceService _deviceService; + private readonly CCToolsBoardService _ccToolsBoardService; + private enum ChildrensRoom { TemperatureSensor, @@ -39,23 +46,34 @@ private enum ChildrensRoom Window } - public ChildrensRoomRoomConfiguration(IController controller) - : base(controller) + public ChildrensRoomRoomConfiguration( + IAreaService areaService, + SynonymService synonymService, + IDeviceService deviceService, + CCToolsBoardService ccToolsBoardService) { + if (areaService == null) throw new ArgumentNullException(nameof(areaService)); + if (synonymService == null) throw new ArgumentNullException(nameof(synonymService)); + if (deviceService == null) throw new ArgumentNullException(nameof(deviceService)); + if (ccToolsBoardService == null) throw new ArgumentNullException(nameof(ccToolsBoardService)); + + _areaService = areaService; + _synonymService = synonymService; + _deviceService = deviceService; + _ccToolsBoardService = ccToolsBoardService; } - public override void Setup() + public void Setup() { - var hsrel5 = CCToolsBoardController.CreateHSREL5(InstalledDevice.ChildrensRoomHSREL5, new I2CSlaveAddress(63)); - var input0 = Controller.Device(InstalledDevice.Input0); - - var i2cHardwareBridge = Controller.GetDevice(); + var hsrel5 = _ccToolsBoardService.CreateHSREL5(InstalledDevice.ChildrensRoomHSREL5, new I2CSlaveAddress(63)); + var input0 = _deviceService.GetDevice(InstalledDevice.Input0); + var i2CHardwareBridge = _deviceService.GetDevice(); const int SensorPin = 7; - var room = Controller.CreateArea(Room.ChildrensRoom) - .WithTemperatureSensor(ChildrensRoom.TemperatureSensor, i2cHardwareBridge.DHT22Accessor.GetTemperatureSensor(SensorPin)) - .WithHumiditySensor(ChildrensRoom.HumiditySensor, i2cHardwareBridge.DHT22Accessor.GetHumiditySensor(SensorPin)) + var room = _areaService.CreateArea(Room.ChildrensRoom) + .WithTemperatureSensor(ChildrensRoom.TemperatureSensor, i2CHardwareBridge.DHT22Accessor.GetTemperatureSensor(SensorPin)) + .WithHumiditySensor(ChildrensRoom.HumiditySensor, i2CHardwareBridge.DHT22Accessor.GetHumiditySensor(SensorPin)) .WithLamp(ChildrensRoom.LightCeilingMiddle, hsrel5[HSREL5Pin.GPIO0]) .WithRollerShutter(ChildrensRoom.RollerShutter, hsrel5[HSREL5Pin.Relay4], hsrel5[HSREL5Pin.Relay3]) .WithSocket(ChildrensRoom.SocketWindow, hsrel5[HSREL5Pin.Relay0]) @@ -71,7 +89,7 @@ public override void Setup() room.GetRollerShutter(ChildrensRoom.RollerShutter) .ConnectWith(room.GetButton(ChildrensRoom.RollerShutterButtonUp), room.GetButton(ChildrensRoom.RollerShutterButtonDown)); - Controller.ServiceLocator.GetService().AddSynonymsForArea(Room.ChildrensRoom, "Kinderzimmer", "ChildrensRoom"); + _synonymService.AddSynonymsForArea(Room.ChildrensRoom, "Kinderzimmer", "ChildrensRoom"); } } } diff --git a/Controllers/HA4IoT.Controller.Main/Rooms/FloorConfiguration.cs b/Controllers/HA4IoT.Controller.Main/Rooms/FloorConfiguration.cs index 84315f22..2ee511eb 100644 --- a/Controllers/HA4IoT.Controller.Main/Rooms/FloorConfiguration.cs +++ b/Controllers/HA4IoT.Controller.Main/Rooms/FloorConfiguration.cs @@ -5,15 +5,12 @@ using HA4IoT.Actuators.Lamps; using HA4IoT.Actuators.RollerShutters; using HA4IoT.Actuators.StateMachines; -using HA4IoT.Actuators.Triggers; using HA4IoT.Automations; using HA4IoT.Contracts.Actuators; using HA4IoT.Contracts.Areas; -using HA4IoT.Contracts.Core; using HA4IoT.Contracts.Hardware; -using HA4IoT.Contracts.Services; using HA4IoT.Contracts.Services.Daylight; -using HA4IoT.Core; +using HA4IoT.Contracts.Services.System; using HA4IoT.Hardware; using HA4IoT.Hardware.CCTools; using HA4IoT.Hardware.I2CHardwareBridge; @@ -22,11 +19,19 @@ using HA4IoT.Sensors.HumiditySensors; using HA4IoT.Sensors.MotionDetectors; using HA4IoT.Sensors.TemperatureSensors; +using HA4IoT.Services.Areas; +using HA4IoT.Services.Devices; namespace HA4IoT.Controller.Main.Rooms { - internal class FloorConfiguration : RoomConfiguration + internal class FloorConfiguration { + private readonly IAreaService _areaService; + private readonly IDaylightService _daylightService; + private readonly IDeviceService _deviceService; + private readonly CCToolsBoardService _ccToolsBoardService; + private readonly SynonymService _synonymService; + private enum Floor { StairwayMotionDetector, @@ -62,32 +67,46 @@ private enum Floor LampStairs } - public FloorConfiguration(IController controller) - : base(controller) + public FloorConfiguration( + IAreaService areaService, + IDaylightService daylightService, + IDeviceService deviceService, + CCToolsBoardService ccToolsBoardService, + SynonymService synonymService) { + if (areaService == null) throw new ArgumentNullException(nameof(areaService)); + if (daylightService == null) throw new ArgumentNullException(nameof(daylightService)); + if (deviceService == null) throw new ArgumentNullException(nameof(deviceService)); + if (ccToolsBoardService == null) throw new ArgumentNullException(nameof(ccToolsBoardService)); + if (synonymService == null) throw new ArgumentNullException(nameof(synonymService)); + + _areaService = areaService; + _daylightService = daylightService; + _deviceService = deviceService; + _ccToolsBoardService = ccToolsBoardService; + _synonymService = synonymService; } - public override void Setup() + public void Setup() { - var hsrel5Stairway = CCToolsBoardController.CreateHSREL5(InstalledDevice.StairwayHSREL5, new I2CSlaveAddress(60)); - var hspe8UpperFloor = Controller.Device(InstalledDevice.UpperFloorAndOfficeHSPE8); - var hspe16FloorAndLowerBathroom = CCToolsBoardController.CreateHSPE16OutputOnly(InstalledDevice.LowerFloorAndLowerBathroomHSPE16, new I2CSlaveAddress(17)); - - var input1 = Controller.Device(InstalledDevice.Input1); - var input2 = Controller.Device(InstalledDevice.Input2); - var input4 = Controller.Device(InstalledDevice.Input4); + var hsrel5Stairway = _ccToolsBoardService.CreateHSREL5(InstalledDevice.StairwayHSREL5, new I2CSlaveAddress(60)); + var hspe8UpperFloor = _deviceService.GetDevice(InstalledDevice.UpperFloorAndOfficeHSPE8); + var hspe16FloorAndLowerBathroom = _ccToolsBoardService.CreateHSPE16OutputOnly(InstalledDevice.LowerFloorAndLowerBathroomHSPE16, new I2CSlaveAddress(17)); - var i2cHardwareBridge = Controller.GetDevice(); + var input1 = _deviceService.GetDevice(InstalledDevice.Input1); + var input2 = _deviceService.GetDevice(InstalledDevice.Input2); + var input4 = _deviceService.GetDevice(InstalledDevice.Input4); + var i2CHardwareBridge = _deviceService.GetDevice(); const int SensorPin = 5; - var room = Controller.CreateArea(Room.Floor) + var room = _areaService.CreateArea(Room.Floor) .WithMotionDetector(Floor.StairwayMotionDetector, input2.GetInput(1)) .WithMotionDetector(Floor.StairsLowerMotionDetector, input4.GetInput(7)) .WithMotionDetector(Floor.StairsUpperMotionDetector, input4.GetInput(6)) .WithMotionDetector(Floor.LowerFloorMotionDetector, input1.GetInput(4)) - .WithTemperatureSensor(Floor.LowerFloorTemperatureSensor, i2cHardwareBridge.DHT22Accessor.GetTemperatureSensor(SensorPin)) - .WithHumiditySensor(Floor.LowerFloorHumiditySensor, i2cHardwareBridge.DHT22Accessor.GetHumiditySensor(SensorPin)) + .WithTemperatureSensor(Floor.LowerFloorTemperatureSensor, i2CHardwareBridge.DHT22Accessor.GetTemperatureSensor(SensorPin)) + .WithHumiditySensor(Floor.LowerFloorHumiditySensor, i2CHardwareBridge.DHT22Accessor.GetHumiditySensor(SensorPin)) .WithLamp(Floor.Lamp1, hspe16FloorAndLowerBathroom.GetOutput(5).WithInvertedState()) .WithLamp(Floor.Lamp2, hspe16FloorAndLowerBathroom.GetOutput(6).WithInvertedState()) .WithLamp(Floor.Lamp3, hspe16FloorAndLowerBathroom.GetOutput(7).WithInvertedState()) @@ -120,7 +139,7 @@ public override void Setup() .WithTrigger(room.GetButton(Floor.ButtonLowerFloorAtBathroom).GetPressedShortlyTrigger()) .WithTrigger(room.GetButton(Floor.ButtonLowerFloorAtKitchen).GetPressedShortlyTrigger()) .WithTarget(room.GetActuator(Floor.CombinedLamps)) - .WithEnabledAtNight(Controller.ServiceLocator.GetService()) + .WithEnabledAtNight(_daylightService) .WithTurnOffIfButtonPressedWhileAlreadyOn() .WithOnDuration(TimeSpan.FromSeconds(20)); @@ -129,7 +148,7 @@ public override void Setup() room.SetupRollerShutterAutomation().WithRollerShutters(room.GetRollerShutter(Floor.StairwayRollerShutter)); - Controller.ServiceLocator.GetService().AddSynonymsForArea(Room.Floor, "Flur", "Floor"); + _synonymService.AddSynonymsForArea(Room.Floor, "Flur", "Floor"); } private void SetupStairwayLamps(IArea room) @@ -138,7 +157,7 @@ private void SetupStairwayLamps(IArea room) .WithTrigger(room.GetMotionDetector(Floor.StairwayMotionDetector)) .WithTrigger(room.GetButton(Floor.ButtonStairway).GetPressedShortlyTrigger()) .WithTarget(room.GetActuator(Floor.CombinedStairwayLamp)) - .WithEnabledAtNight(Controller.ServiceLocator.GetService()) + .WithEnabledAtNight(_daylightService) .WithOnDuration(TimeSpan.FromSeconds(30)); } diff --git a/Controllers/HA4IoT.Controller.Main/Rooms/KitchenConfiguration.cs b/Controllers/HA4IoT.Controller.Main/Rooms/KitchenConfiguration.cs index 59e6801b..4d549db3 100644 --- a/Controllers/HA4IoT.Controller.Main/Rooms/KitchenConfiguration.cs +++ b/Controllers/HA4IoT.Controller.Main/Rooms/KitchenConfiguration.cs @@ -1,16 +1,15 @@ -using HA4IoT.Actuators; +using System; +using HA4IoT.Actuators; using HA4IoT.Actuators.BinaryStateActuators; using HA4IoT.Actuators.Connectors; using HA4IoT.Actuators.Lamps; using HA4IoT.Actuators.RollerShutters; using HA4IoT.Actuators.Sockets; using HA4IoT.Automations; -using HA4IoT.Contracts.Core; +using HA4IoT.Contracts.Areas; using HA4IoT.Contracts.Hardware; -using HA4IoT.Contracts.Services; using HA4IoT.Contracts.Services.Daylight; -using HA4IoT.Core; -using HA4IoT.Hardware; +using HA4IoT.Contracts.Services.System; using HA4IoT.Hardware.CCTools; using HA4IoT.Hardware.I2CHardwareBridge; using HA4IoT.PersonalAgent; @@ -19,11 +18,19 @@ using HA4IoT.Sensors.MotionDetectors; using HA4IoT.Sensors.TemperatureSensors; using HA4IoT.Sensors.Windows; +using HA4IoT.Services.Areas; +using HA4IoT.Services.Devices; namespace HA4IoT.Controller.Main.Rooms { - internal class KitchenConfiguration : RoomConfiguration + internal class KitchenConfiguration { + private readonly IAreaService _areaService; + private readonly IDaylightService _daylightService; + private readonly IDeviceService _deviceService; + private readonly CCToolsBoardService _ccToolsBoardService; + private readonly SynonymService _synonymService; + public enum Kitchen { TemperatureSensor, @@ -51,27 +58,41 @@ public enum Kitchen Window } - public KitchenConfiguration(IController controller) - : base(controller) + public KitchenConfiguration( + IAreaService areaService, + IDaylightService daylightService, + IDeviceService deviceService, + CCToolsBoardService ccToolsBoardService, + SynonymService synonymService) { + if (areaService == null) throw new ArgumentNullException(nameof(areaService)); + if (daylightService == null) throw new ArgumentNullException(nameof(daylightService)); + if (deviceService == null) throw new ArgumentNullException(nameof(deviceService)); + if (ccToolsBoardService == null) throw new ArgumentNullException(nameof(ccToolsBoardService)); + if (synonymService == null) throw new ArgumentNullException(nameof(synonymService)); + + _areaService = areaService; + _daylightService = daylightService; + _deviceService = deviceService; + _ccToolsBoardService = ccToolsBoardService; + _synonymService = synonymService; } - public override void Setup() + public void Setup() { - var hsrel5 = CCToolsBoardController.CreateHSREL5(InstalledDevice.KitchenHSREL5, new I2CSlaveAddress(58)); - var hspe8 = CCToolsBoardController.CreateHSPE8OutputOnly(InstalledDevice.KitchenHSPE8, new I2CSlaveAddress(39)); - - var input0 = Controller.Device(InstalledDevice.Input0); - var input1 = Controller.Device(InstalledDevice.Input1); - var input2 = Controller.Device(InstalledDevice.Input2); + var hsrel5 = _ccToolsBoardService.CreateHSREL5(InstalledDevice.KitchenHSREL5, new I2CSlaveAddress(58)); + var hspe8 = _ccToolsBoardService.CreateHSPE8OutputOnly(InstalledDevice.KitchenHSPE8, new I2CSlaveAddress(39)); - var i2cHardwareBridge = Controller.GetDevice(); + var input0 = _deviceService.GetDevice(InstalledDevice.Input0); + var input1 = _deviceService.GetDevice(InstalledDevice.Input1); + var input2 = _deviceService.GetDevice(InstalledDevice.Input2); + var i2CHardwareBridge = _deviceService.GetDevice(); const int SensorPin = 11; - var room = Controller.CreateArea(Room.Kitchen) - .WithTemperatureSensor(Kitchen.TemperatureSensor, i2cHardwareBridge.DHT22Accessor.GetTemperatureSensor(SensorPin)) - .WithHumiditySensor(Kitchen.HumiditySensor, i2cHardwareBridge.DHT22Accessor.GetHumiditySensor(SensorPin)) + var room = _areaService.CreateArea(Room.Kitchen) + .WithTemperatureSensor(Kitchen.TemperatureSensor, i2CHardwareBridge.DHT22Accessor.GetTemperatureSensor(SensorPin)) + .WithHumiditySensor(Kitchen.HumiditySensor, i2CHardwareBridge.DHT22Accessor.GetHumiditySensor(SensorPin)) .WithMotionDetector(Kitchen.MotionDetector, input1.GetInput(8)) .WithLamp(Kitchen.LightCeilingMiddle, hsrel5.GetOutput(5).WithInvertedState()) .WithLamp(Kitchen.LightCeilingWindow, hsrel5.GetOutput(6).WithInvertedState()) @@ -102,9 +123,9 @@ public override void Setup() room.SetupTurnOnAndOffAutomation() .WithTrigger(room.GetMotionDetector(Kitchen.MotionDetector)) .WithTarget(room.GetActuator(Kitchen.CombinedAutomaticLights)) - .WithEnabledAtNight(Controller.ServiceLocator.GetService()); + .WithEnabledAtNight(_daylightService); - Controller.ServiceLocator.GetService().AddSynonymsForArea(Room.Kitchen, "Küche", "Kitchen"); + _synonymService.AddSynonymsForArea(Room.Kitchen, "Küche", "Kitchen"); } } } diff --git a/Controllers/HA4IoT.Controller.Main/Rooms/LivingRoomConfiguration.cs b/Controllers/HA4IoT.Controller.Main/Rooms/LivingRoomConfiguration.cs index 827a55bf..bf86090d 100644 --- a/Controllers/HA4IoT.Controller.Main/Rooms/LivingRoomConfiguration.cs +++ b/Controllers/HA4IoT.Controller.Main/Rooms/LivingRoomConfiguration.cs @@ -1,10 +1,9 @@ using HA4IoT.Actuators.Connectors; using HA4IoT.Actuators.Lamps; using HA4IoT.Actuators.Sockets; -using HA4IoT.Contracts.Core; +using HA4IoT.Contracts.Areas; using HA4IoT.Contracts.Hardware; -using HA4IoT.Core; -using HA4IoT.Hardware; +using HA4IoT.Contracts.Services.System; using HA4IoT.Hardware.CCTools; using HA4IoT.Hardware.I2CHardwareBridge; using HA4IoT.PersonalAgent; @@ -12,11 +11,18 @@ using HA4IoT.Sensors.HumiditySensors; using HA4IoT.Sensors.TemperatureSensors; using HA4IoT.Sensors.Windows; +using HA4IoT.Services.Areas; +using HA4IoT.Services.Devices; namespace HA4IoT.Controller.Main.Rooms { - internal class LivingRoomConfiguration : RoomConfiguration + internal class LivingRoomConfiguration { + private readonly IDeviceService _deviceService; + private readonly IAreaService _areaService; + private readonly CCToolsBoardService _ccToolsBoardService; + private readonly SynonymService _synonymService; + private enum LivingRoom { MotionDetector, @@ -51,26 +57,32 @@ private enum LivingRoom WindowRight, } - public LivingRoomConfiguration(IController controller) - : base(controller) + public LivingRoomConfiguration( + IDeviceService deviceService, + IAreaService areaService, + CCToolsBoardService ccToolsBoardService, + SynonymService synonymService) { + _deviceService = deviceService; + _areaService = areaService; + _ccToolsBoardService = ccToolsBoardService; + _synonymService = synonymService; } - public override void Setup() + public void Setup() { - var hsrel8 = CCToolsBoardController.CreateHSREL8(InstalledDevice.LivingRoomHSREL8, new I2CSlaveAddress(18)); - var hsrel5 = CCToolsBoardController.CreateHSREL5(InstalledDevice.LivingRoomHSREL5, new I2CSlaveAddress(57)); + var hsrel8 = _ccToolsBoardService.CreateHSREL8(InstalledDevice.LivingRoomHSREL8, new I2CSlaveAddress(18)); + var hsrel5 = _ccToolsBoardService.CreateHSREL5(InstalledDevice.LivingRoomHSREL5, new I2CSlaveAddress(57)); - var input0 = Controller.Device(InstalledDevice.Input0); - var input1 = Controller.Device(InstalledDevice.Input1); - - var i2cHardwareBridge = Controller.GetDevice(); + var input0 = _deviceService.GetDevice(InstalledDevice.Input0); + var input1 = _deviceService.GetDevice(InstalledDevice.Input1); + var i2CHardwareBridge = _deviceService.GetDevice(); const int SensorPin = 12; - var room = Controller.CreateArea(Room.LivingRoom) - .WithTemperatureSensor(LivingRoom.TemperatureSensor, i2cHardwareBridge.DHT22Accessor.GetTemperatureSensor(SensorPin)) - .WithHumiditySensor(LivingRoom.HumiditySensor, i2cHardwareBridge.DHT22Accessor.GetHumiditySensor(SensorPin)) + var room = _areaService.CreateArea(Room.LivingRoom) + .WithTemperatureSensor(LivingRoom.TemperatureSensor, i2CHardwareBridge.DHT22Accessor.GetTemperatureSensor(SensorPin)) + .WithHumiditySensor(LivingRoom.HumiditySensor, i2CHardwareBridge.DHT22Accessor.GetHumiditySensor(SensorPin)) .WithLamp(LivingRoom.LampCouch, hsrel8.GetOutput(8).WithInvertedState()) .WithLamp(LivingRoom.LampDiningTable, hsrel8.GetOutput(9).WithInvertedState()) .WithSocket(LivingRoom.SocketWindowLeftLower, hsrel8.GetOutput(1)) @@ -102,7 +114,7 @@ public override void Setup() room.Socket(LivingRoom.SocketWallRightEdgeRight). ConnectToggleActionWith(room.GetButton(LivingRoom.ButtonLower)); - Controller.ServiceLocator.GetService().AddSynonymsForArea(Room.LivingRoom, "Wohnzimmer", "LivingRoom"); + _synonymService.AddSynonymsForArea(Room.LivingRoom, "Wohnzimmer", "LivingRoom"); } } } diff --git a/Controllers/HA4IoT.Controller.Main/Rooms/LowerBathroomConfiguration.cs b/Controllers/HA4IoT.Controller.Main/Rooms/LowerBathroomConfiguration.cs index a34eda3e..5179577a 100644 --- a/Controllers/HA4IoT.Controller.Main/Rooms/LowerBathroomConfiguration.cs +++ b/Controllers/HA4IoT.Controller.Main/Rooms/LowerBathroomConfiguration.cs @@ -8,8 +8,7 @@ using HA4IoT.Contracts.Areas; using HA4IoT.Contracts.Core; using HA4IoT.Contracts.Services; -using HA4IoT.Core; -using HA4IoT.Hardware; +using HA4IoT.Contracts.Services.System; using HA4IoT.Hardware.CCTools; using HA4IoT.Hardware.I2CHardwareBridge; using HA4IoT.PersonalAgent; @@ -18,11 +17,17 @@ using HA4IoT.Sensors.MotionDetectors; using HA4IoT.Sensors.TemperatureSensors; using HA4IoT.Sensors.Windows; +using HA4IoT.Services.Areas; +using HA4IoT.Services.Devices; namespace HA4IoT.Controller.Main.Rooms { - internal class LowerBathroomConfiguration : RoomConfiguration + internal class LowerBathroomConfiguration { + private readonly IDeviceService _deviceService; + private readonly ISchedulerService _schedulerService; + private readonly IAreaService _areaService; + private readonly SynonymService _synonymService; private TimedAction _bathmodeResetTimer; public enum LowerBathroom @@ -43,23 +48,35 @@ public enum LowerBathroom Window } - public LowerBathroomConfiguration(IController controller) - : base(controller) + public LowerBathroomConfiguration( + IDeviceService deviceService, + ISchedulerService schedulerService, + IAreaService areaService, + SynonymService synonymService) { + if (deviceService == null) throw new ArgumentNullException(nameof(deviceService)); + if (schedulerService == null) throw new ArgumentNullException(nameof(schedulerService)); + if (areaService == null) throw new ArgumentNullException(nameof(areaService)); + if (synonymService == null) throw new ArgumentNullException(nameof(synonymService)); + + _deviceService = deviceService; + _schedulerService = schedulerService; + _areaService = areaService; + _synonymService = synonymService; } - public override void Setup() + public void Setup() { - var hspe16_FloorAndLowerBathroom = Controller.Device(InstalledDevice.LowerFloorAndLowerBathroomHSPE16); - var input3 = Controller.Device(InstalledDevice.Input3); - var i2cHardwareBridge = Controller.GetDevice(); + var hspe16_FloorAndLowerBathroom = _deviceService.GetDevice(InstalledDevice.LowerFloorAndLowerBathroomHSPE16); + var input3 = _deviceService.GetDevice(InstalledDevice.Input3); + var i2CHardwareBridge = _deviceService.GetDevice(); const int SensorPin = 3; - var room = Controller.CreateArea(Room.LowerBathroom) + var room = _areaService.CreateArea(Room.LowerBathroom) .WithMotionDetector(LowerBathroom.MotionDetector, input3.GetInput(15)) - .WithTemperatureSensor(LowerBathroom.TemperatureSensor, i2cHardwareBridge.DHT22Accessor.GetTemperatureSensor(SensorPin)) - .WithHumiditySensor(LowerBathroom.HumiditySensor, i2cHardwareBridge.DHT22Accessor.GetHumiditySensor(SensorPin)) + .WithTemperatureSensor(LowerBathroom.TemperatureSensor, i2CHardwareBridge.DHT22Accessor.GetTemperatureSensor(SensorPin)) + .WithHumiditySensor(LowerBathroom.HumiditySensor, i2CHardwareBridge.DHT22Accessor.GetHumiditySensor(SensorPin)) .WithLamp(LowerBathroom.LightCeilingDoor, hspe16_FloorAndLowerBathroom.GetOutput(0).WithInvertedState()) .WithLamp(LowerBathroom.LightCeilingMiddle, hspe16_FloorAndLowerBathroom.GetOutput(1).WithInvertedState()) .WithLamp(LowerBathroom.LightCeilingWindow, hspe16_FloorAndLowerBathroom.GetOutput(2).WithInvertedState()) @@ -78,7 +95,7 @@ public override void Setup() .WithTrigger(room.GetMotionDetector(LowerBathroom.MotionDetector)) .WithTarget(room.GetActuator(LowerBathroom.CombinedLights)); - Controller.ServiceLocator.GetService().AddSynonymsForArea(Room.LowerBathroom, "BadUnten", "LowerBathroom"); + _synonymService.AddSynonymsForArea(Room.LowerBathroom, "BadUnten", "LowerBathroom"); } private void StartBathode(IArea bathroom) @@ -91,7 +108,7 @@ private void StartBathode(IArea bathroom) bathroom.GetLamp(LowerBathroom.LampMirror).TryTurnOff(); _bathmodeResetTimer?.Cancel(); - _bathmodeResetTimer = bathroom.Controller.ServiceLocator.GetService().In(TimeSpan.FromHours(1)).Execute(() => bathroom.GetMotionDetector().Enable()); + _bathmodeResetTimer = _schedulerService.In(TimeSpan.FromHours(1)).Execute(() => bathroom.GetMotionDetector().Enable()); } } } diff --git a/Controllers/HA4IoT.Controller.Main/Rooms/OfficeConfiguration.cs b/Controllers/HA4IoT.Controller.Main/Rooms/OfficeConfiguration.cs index b7747af9..977b0d7a 100644 --- a/Controllers/HA4IoT.Controller.Main/Rooms/OfficeConfiguration.cs +++ b/Controllers/HA4IoT.Controller.Main/Rooms/OfficeConfiguration.cs @@ -1,26 +1,36 @@ -using HA4IoT.Actuators.Sockets; +using System; +using HA4IoT.Actuators.Sockets; using HA4IoT.Actuators.StateMachines; using HA4IoT.Actuators.Triggers; using HA4IoT.Contracts.Actuators; using HA4IoT.Contracts.Areas; using HA4IoT.Contracts.Components; -using HA4IoT.Contracts.Core; using HA4IoT.Contracts.Hardware; -using HA4IoT.Core; -using HA4IoT.Hardware; +using HA4IoT.Contracts.Services.Daylight; +using HA4IoT.Contracts.Services.System; using HA4IoT.Hardware.CCTools; using HA4IoT.Hardware.I2CHardwareBridge; +using HA4IoT.Hardware.RemoteSwitch; using HA4IoT.PersonalAgent; using HA4IoT.Sensors.Buttons; using HA4IoT.Sensors.HumiditySensors; using HA4IoT.Sensors.MotionDetectors; using HA4IoT.Sensors.TemperatureSensors; using HA4IoT.Sensors.Windows; +using HA4IoT.Services.Areas; +using HA4IoT.Services.Devices; namespace HA4IoT.Controller.Main.Rooms { - internal class OfficeConfiguration : RoomConfiguration + internal class OfficeConfiguration { + private readonly IDeviceService _deviceService; + private readonly IAreaService _areaService; + private readonly IDaylightService _daylightService; + private readonly CCToolsBoardService _ccToolsBoardService; + private readonly SynonymService _synonymService; + private readonly RemoteSocketService _remoteSocketService; + public enum Office { TemperatureSensor, @@ -48,26 +58,43 @@ public enum Office WindowRight } - public OfficeConfiguration(IController controller) - : base(controller) + public OfficeConfiguration( + IDeviceService deviceService, + IAreaService areaService, + IDaylightService daylightService, + CCToolsBoardService ccToolsBoardService, + SynonymService synonymService, + RemoteSocketService remoteSocketService) { + if (deviceService == null) throw new ArgumentNullException(nameof(deviceService)); + if (areaService == null) throw new ArgumentNullException(nameof(areaService)); + if (daylightService == null) throw new ArgumentNullException(nameof(daylightService)); + if (ccToolsBoardService == null) throw new ArgumentNullException(nameof(ccToolsBoardService)); + if (synonymService == null) throw new ArgumentNullException(nameof(synonymService)); + if (remoteSocketService == null) throw new ArgumentNullException(nameof(remoteSocketService)); + + _deviceService = deviceService; + _areaService = areaService; + _daylightService = daylightService; + _ccToolsBoardService = ccToolsBoardService; + _synonymService = synonymService; + _remoteSocketService = remoteSocketService; } - public override void Setup() + public void Setup() { - var hsrel8 = CCToolsBoardController.CreateHSREL8(InstalledDevice.OfficeHSREL8, new I2CSlaveAddress(20)); - var hspe8 = CCToolsBoardController.CreateHSPE8OutputOnly(InstalledDevice.UpperFloorAndOfficeHSPE8, new I2CSlaveAddress(37)); - var input4 = Controller.Device(InstalledDevice.Input4); - var input5 = Controller.Device(InstalledDevice.Input5); - - const int SensorPin = 2; + var hsrel8 = _ccToolsBoardService.CreateHSREL8(InstalledDevice.OfficeHSREL8, new I2CSlaveAddress(20)); + var hspe8 = _ccToolsBoardService.CreateHSPE8OutputOnly(InstalledDevice.UpperFloorAndOfficeHSPE8, new I2CSlaveAddress(37)); + var input4 = _deviceService.GetDevice(InstalledDevice.Input4); + var input5 = _deviceService.GetDevice(InstalledDevice.Input5); + var i2CHardwareBridge = _deviceService.GetDevice(); - var i2cHardwareBridge = Controller.GetDevice(); + const int SensorPin = 2; - var room = Controller.CreateArea(Room.Office) + var room = _areaService.CreateArea(Room.Office) .WithMotionDetector(Office.MotionDetector, input4.GetInput(13)) - .WithTemperatureSensor(Office.TemperatureSensor, i2cHardwareBridge.DHT22Accessor.GetTemperatureSensor(SensorPin)) - .WithHumiditySensor(Office.HumiditySensor, i2cHardwareBridge.DHT22Accessor.GetHumiditySensor(SensorPin)) + .WithTemperatureSensor(Office.TemperatureSensor, i2CHardwareBridge.DHT22Accessor.GetTemperatureSensor(SensorPin)) + .WithHumiditySensor(Office.HumiditySensor, i2CHardwareBridge.DHT22Accessor.GetHumiditySensor(SensorPin)) .WithSocket(Office.SocketFrontLeft, hsrel8.GetOutput(0)) .WithSocket(Office.SocketFrontRight, hsrel8.GetOutput(6)) .WithSocket(Office.SocketWindowLeft, hsrel8.GetOutput(10).WithInvertedState()) @@ -81,7 +108,7 @@ public override void Setup() .WithButton(Office.ButtonUpperRight, input4.GetInput(15)) .WithWindow(Office.WindowLeft, w => w.WithLeftCasement(input4.GetInput(11)).WithRightCasement(input4.GetInput(12), input4.GetInput(10))) .WithWindow(Office.WindowRight, w => w.WithLeftCasement(input4.GetInput(8)).WithRightCasement(input4.GetInput(9), input5.GetInput(8))) - .WithSocket(Office.RemoteSocketDesk, RemoteSocketController.GetOutput(0)) + .WithSocket(Office.RemoteSocketDesk, _remoteSocketService.GetOutput(0)) .WithStateMachine(Office.CombinedCeilingLights, (s, a) => SetupLight(s, hsrel8, hspe8, a)); room.GetButton(Office.ButtonUpperLeft).GetPressedLongTrigger().Attach(() => @@ -166,14 +193,13 @@ private void SetupLight(StateMachine light, HSREL8 hsrel8, HSPE8OutputOnly hspe8 .GetPressedShortlyTrigger() .Attach(light.GetSetStateAction(BinaryStateId.On)); - var synonymService = Controller.ServiceLocator.GetService(); - synonymService.AddSynonymsForArea(Room.Office, "Büro", "Arbeitszimmer"); + _synonymService.AddSynonymsForArea(Room.Office, "Büro", "Arbeitszimmer"); - synonymService.AddSynonymsForComponent(Room.Office, Office.CombinedCeilingLights, "Licht"); - synonymService.AddSynonymsForComponent(Room.Office, Office.SocketRearLeftEdge, "Rotlicht", "Pufflicht", "Rot"); + _synonymService.AddSynonymsForComponent(Room.Office, Office.CombinedCeilingLights, "Licht"); + _synonymService.AddSynonymsForComponent(Room.Office, Office.SocketRearLeftEdge, "Rotlicht", "Pufflicht", "Rot"); - synonymService.AddSynonymsForComponentState(deskOnlyStateId, "Schreibtisch"); - synonymService.AddSynonymsForComponentState(couchOnlyStateId, "Couch"); + _synonymService.AddSynonymsForComponentState(deskOnlyStateId, "Schreibtisch"); + _synonymService.AddSynonymsForComponentState(couchOnlyStateId, "Couch"); } } } diff --git a/Controllers/HA4IoT.Controller.Main/Rooms/ReadingRoomConfiguration.cs b/Controllers/HA4IoT.Controller.Main/Rooms/ReadingRoomConfiguration.cs index 043b8ee4..c7ccbb82 100644 --- a/Controllers/HA4IoT.Controller.Main/Rooms/ReadingRoomConfiguration.cs +++ b/Controllers/HA4IoT.Controller.Main/Rooms/ReadingRoomConfiguration.cs @@ -1,12 +1,12 @@ -using HA4IoT.Actuators.Connectors; +using System; +using HA4IoT.Actuators.Connectors; using HA4IoT.Actuators.Lamps; using HA4IoT.Actuators.RollerShutters; using HA4IoT.Actuators.Sockets; using HA4IoT.Automations; -using HA4IoT.Contracts.Core; +using HA4IoT.Contracts.Areas; using HA4IoT.Contracts.Hardware; -using HA4IoT.Core; -using HA4IoT.Hardware; +using HA4IoT.Contracts.Services.System; using HA4IoT.Hardware.CCTools; using HA4IoT.Hardware.I2CHardwareBridge; using HA4IoT.PersonalAgent; @@ -14,11 +14,18 @@ using HA4IoT.Sensors.HumiditySensors; using HA4IoT.Sensors.TemperatureSensors; using HA4IoT.Sensors.Windows; +using HA4IoT.Services.Areas; +using HA4IoT.Services.Devices; namespace HA4IoT.Controller.Main.Rooms { - internal class ReadingRoomConfiguration : RoomConfiguration + internal class ReadingRoomConfiguration { + private readonly IAreaService _areaService; + private readonly SynonymService _synonymService; + private readonly IDeviceService _deviceService; + private readonly CCToolsBoardService _ccToolsBoardService; + private enum ReadingRoom { TemperatureSensor, @@ -39,23 +46,34 @@ private enum ReadingRoom Window } - public ReadingRoomConfiguration(IController controller) - : base(controller) + public ReadingRoomConfiguration( + IAreaService areaService, + SynonymService synonymService, + IDeviceService deviceService, + CCToolsBoardService ccToolsBoardService) { + if (areaService == null) throw new ArgumentNullException(nameof(areaService)); + if (synonymService == null) throw new ArgumentNullException(nameof(synonymService)); + if (deviceService == null) throw new ArgumentNullException(nameof(deviceService)); + if (ccToolsBoardService == null) throw new ArgumentNullException(nameof(ccToolsBoardService)); + + _areaService = areaService; + _synonymService = synonymService; + _deviceService = deviceService; + _ccToolsBoardService = ccToolsBoardService; } - public override void Setup() + public void Setup() { - var hsrel5 = CCToolsBoardController.CreateHSREL5(InstalledDevice.ReadingRoomHSREL5, new I2CSlaveAddress(62)); - var input2 = Controller.Device(InstalledDevice.Input2); - - var i2cHardwareBridge = Controller.GetDevice(); + var hsrel5 = _ccToolsBoardService.CreateHSREL5(InstalledDevice.ReadingRoomHSREL5, new I2CSlaveAddress(62)); + var input2 = _deviceService.GetDevice(InstalledDevice.Input2); + var i2CHardwareBridge = _deviceService.GetDevice(); const int SensorPin = 9; - var room = Controller.CreateArea(Room.ReadingRoom) - .WithTemperatureSensor(ReadingRoom.TemperatureSensor, i2cHardwareBridge.DHT22Accessor.GetTemperatureSensor(SensorPin)) - .WithHumiditySensor(ReadingRoom.HumiditySensor, i2cHardwareBridge.DHT22Accessor.GetHumiditySensor(SensorPin)) + var room = _areaService.CreateArea(Room.ReadingRoom) + .WithTemperatureSensor(ReadingRoom.TemperatureSensor, i2CHardwareBridge.DHT22Accessor.GetTemperatureSensor(SensorPin)) + .WithHumiditySensor(ReadingRoom.HumiditySensor, i2CHardwareBridge.DHT22Accessor.GetHumiditySensor(SensorPin)) .WithLamp(ReadingRoom.LightCeilingMiddle, hsrel5[HSREL5Pin.GPIO0]) .WithRollerShutter(ReadingRoom.RollerShutter, hsrel5[HSREL5Pin.Relay4], hsrel5[HSREL5Pin.Relay3]) .WithSocket(ReadingRoom.SocketWindow, hsrel5[HSREL5Pin.Relay0]) @@ -71,7 +89,7 @@ public override void Setup() room.GetRollerShutter(ReadingRoom.RollerShutter) .ConnectWith(room.GetButton(ReadingRoom.RollerShutterButtonUp), room.GetButton(ReadingRoom.RollerShutterButtonDown)); - Controller.ServiceLocator.GetService().AddSynonymsForArea(Room.ReadingRoom, "Lesezimmer", "Gästezimmer", "ReadingRoom"); + _synonymService.AddSynonymsForArea(Room.ReadingRoom, "Lesezimmer", "Gästezimmer", "ReadingRoom"); } } } diff --git a/Controllers/HA4IoT.Controller.Main/Rooms/RoomConfiguration.cs b/Controllers/HA4IoT.Controller.Main/Rooms/RoomConfiguration.cs deleted file mode 100644 index 641205f2..00000000 --- a/Controllers/HA4IoT.Controller.Main/Rooms/RoomConfiguration.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System; -using HA4IoT.Contracts.Core; -using HA4IoT.Hardware.CCTools; -using HA4IoT.Hardware.RemoteSwitch; -using HA4IoT.Hardware.Knx; - -namespace HA4IoT.Controller.Main.Rooms -{ - internal abstract class RoomConfiguration - { - protected RoomConfiguration( - IController controller) - { - if (controller == null) throw new ArgumentNullException(nameof(controller)); - - Controller = controller; - CCToolsBoardController = controller.GetDevice(); - RemoteSocketController = controller.GetDevice(); - } - - public IController Controller { get; } - public CCToolsBoardController CCToolsBoardController { get; } - public RemoteSocketController RemoteSocketController { get; } - - public abstract void Setup(); - } -} diff --git a/Controllers/HA4IoT.Controller.Main/Rooms/StoreroomConfiguration.cs b/Controllers/HA4IoT.Controller.Main/Rooms/StoreroomConfiguration.cs index 0b2f0547..ca7052d0 100644 --- a/Controllers/HA4IoT.Controller.Main/Rooms/StoreroomConfiguration.cs +++ b/Controllers/HA4IoT.Controller.Main/Rooms/StoreroomConfiguration.cs @@ -1,22 +1,27 @@ using System; using HA4IoT.Actuators.Lamps; using HA4IoT.Actuators.Sockets; -using HA4IoT.Actuators.StateMachines; using HA4IoT.Automations; -using HA4IoT.Contracts.Core; +using HA4IoT.Contracts.Areas; using HA4IoT.Contracts.Hardware; -using HA4IoT.Contracts.Services; using HA4IoT.Contracts.Services.Daylight; -using HA4IoT.Core; -using HA4IoT.Hardware; +using HA4IoT.Contracts.Services.System; using HA4IoT.Hardware.CCTools; using HA4IoT.PersonalAgent; using HA4IoT.Sensors.MotionDetectors; +using HA4IoT.Services.Areas; +using HA4IoT.Services.Devices; namespace HA4IoT.Controller.Main.Rooms { - internal class StoreroomConfiguration : RoomConfiguration + internal class StoreroomConfiguration { + private readonly IAreaService _areaService; + private readonly SynonymService _synonymService; + private readonly IDeviceService _deviceService; + private readonly CCToolsBoardService _ccToolsBoardService; + private readonly ITimerService _timerService; + private readonly IDaylightService _daylightService; private CatLitterBoxTwitterSender _catLitterBoxTwitterSender; private enum Storeroom @@ -29,20 +34,38 @@ private enum Storeroom CirculatingPump } - public StoreroomConfiguration(IController controller) - : base(controller) + public StoreroomConfiguration( + IAreaService areaService, + SynonymService synonymService, + IDeviceService deviceService, + CCToolsBoardService ccToolsBoardService, + ITimerService timerService, + IDaylightService daylightService) { + if (areaService == null) throw new ArgumentNullException(nameof(areaService)); + if (synonymService == null) throw new ArgumentNullException(nameof(synonymService)); + if (deviceService == null) throw new ArgumentNullException(nameof(deviceService)); + if (ccToolsBoardService == null) throw new ArgumentNullException(nameof(ccToolsBoardService)); + if (timerService == null) throw new ArgumentNullException(nameof(timerService)); + if (daylightService == null) throw new ArgumentNullException(nameof(daylightService)); + + _areaService = areaService; + _synonymService = synonymService; + _deviceService = deviceService; + _ccToolsBoardService = ccToolsBoardService; + _timerService = timerService; + _daylightService = daylightService; } - public override void Setup() + public void Setup() { - var hsrel8LowerHeatingValves = CCToolsBoardController.CreateHSREL8(InstalledDevice.LowerHeatingValvesHSREL8, new I2CSlaveAddress(16)); - var hsrel5UpperHeatingValves = CCToolsBoardController.CreateHSREL5(InstalledDevice.UpperHeatingValvesHSREL5, new I2CSlaveAddress(56)); + var hsrel8LowerHeatingValves = _ccToolsBoardService.CreateHSREL8(InstalledDevice.LowerHeatingValvesHSREL8, new I2CSlaveAddress(16)); + var hsrel5UpperHeatingValves = _ccToolsBoardService.CreateHSREL5(InstalledDevice.UpperHeatingValvesHSREL5, new I2CSlaveAddress(56)); - var hsrel5Stairway = Controller.Device(InstalledDevice.StairwayHSREL5); - var input3 = Controller.Device(InstalledDevice.Input3); + var hsrel5Stairway = _deviceService.GetDevice(InstalledDevice.StairwayHSREL5); + var input3 = _deviceService.GetDevice(InstalledDevice.Input3); - var storeroom = Controller.CreateArea(Room.Storeroom) + var storeroom = _areaService.CreateArea(Room.Storeroom) .WithMotionDetector(Storeroom.MotionDetector, input3.GetInput(12)) .WithMotionDetector(Storeroom.MotionDetectorCatLitterBox, input3.GetInput(11).WithInvertedState()) .WithLamp(Storeroom.LightCeiling, hsrel5Stairway[HSREL5Pin.GPIO1]) @@ -66,18 +89,18 @@ public override void Setup() hsrel5UpperHeatingValves[HSREL5Pin.GPIO1].Write(BinaryState.Low); storeroom.SetupTurnOnAndOffAutomation() - .WithTrigger(Controller.GetArea(AreaIdFactory.Create(Room.Kitchen)).GetMotionDetector(KitchenConfiguration.Kitchen.MotionDetector)) - .WithTrigger(Controller.GetArea(AreaIdFactory.Create(Room.LowerBathroom)).GetMotionDetector(LowerBathroomConfiguration.LowerBathroom.MotionDetector)) + .WithTrigger(_areaService.GetArea(Room.Kitchen).GetMotionDetector(KitchenConfiguration.Kitchen.MotionDetector)) + .WithTrigger(_areaService.GetArea(Room.LowerBathroom).GetMotionDetector(LowerBathroomConfiguration.LowerBathroom.MotionDetector)) .WithTarget(storeroom.Socket(Storeroom.CirculatingPump)) .WithPauseAfterEveryTurnOn(TimeSpan.FromHours(1)) .WithOnDuration(TimeSpan.FromMinutes(1)) - .WithEnabledAtDay(Controller.ServiceLocator.GetService()); + .WithEnabledAtDay(_daylightService); _catLitterBoxTwitterSender = - new CatLitterBoxTwitterSender(Controller.Timer).WithTrigger( + new CatLitterBoxTwitterSender(_timerService).WithTrigger( storeroom.GetMotionDetector(Storeroom.MotionDetectorCatLitterBox)); - Controller.ServiceLocator.GetService().AddSynonymsForArea(Room.Storeroom, "Abstellkammer", "Storeroom"); + _synonymService.AddSynonymsForArea(Room.Storeroom, "Abstellkammer", "Storeroom"); } } } diff --git a/Controllers/HA4IoT.Controller.Main/Rooms/UpperBathroomConfiguration.cs b/Controllers/HA4IoT.Controller.Main/Rooms/UpperBathroomConfiguration.cs index 4e812b3f..7e78c5da 100644 --- a/Controllers/HA4IoT.Controller.Main/Rooms/UpperBathroomConfiguration.cs +++ b/Controllers/HA4IoT.Controller.Main/Rooms/UpperBathroomConfiguration.cs @@ -5,22 +5,28 @@ using HA4IoT.Automations; using HA4IoT.Contracts.Areas; using HA4IoT.Contracts.Components; -using HA4IoT.Contracts.Core; using HA4IoT.Contracts.Hardware; using HA4IoT.Contracts.Services; -using HA4IoT.Core; -using HA4IoT.Hardware; +using HA4IoT.Contracts.Services.System; using HA4IoT.Hardware.CCTools; using HA4IoT.Hardware.I2CHardwareBridge; using HA4IoT.PersonalAgent; using HA4IoT.Sensors.HumiditySensors; using HA4IoT.Sensors.MotionDetectors; using HA4IoT.Sensors.TemperatureSensors; +using HA4IoT.Services.Areas; +using HA4IoT.Services.Devices; namespace HA4IoT.Controller.Main.Rooms { - internal class UpperBathroomConfiguration : RoomConfiguration + internal class UpperBathroomConfiguration { + private readonly CCToolsBoardService _ccToolsBoardService; + private readonly IDeviceService _deviceService; + private readonly ISchedulerService _schedulerService; + private readonly IAreaService _areaService; + private readonly SynonymService _synonymService; + private enum UpperBathroom { TemperatureSensor, @@ -37,29 +43,43 @@ private enum UpperBathroom CombinedCeilingLights } - public UpperBathroomConfiguration(IController controller) - : base(controller) + public UpperBathroomConfiguration( + CCToolsBoardService ccToolsBoardService, + IDeviceService deviceService, + ISchedulerService schedulerService, + IAreaService areaService, + SynonymService synonymService) { + if (ccToolsBoardService == null) throw new ArgumentNullException(nameof(ccToolsBoardService)); + if (deviceService == null) throw new ArgumentNullException(nameof(deviceService)); + if (schedulerService == null) throw new ArgumentNullException(nameof(schedulerService)); + if (areaService == null) throw new ArgumentNullException(nameof(areaService)); + if (synonymService == null) throw new ArgumentNullException(nameof(synonymService)); + + _ccToolsBoardService = ccToolsBoardService; + _deviceService = deviceService; + _schedulerService = schedulerService; + _areaService = areaService; + _synonymService = synonymService; } - public override void Setup() + public void Setup() { - var hsrel5 = CCToolsBoardController.CreateHSREL5(InstalledDevice.UpperBathroomHSREL5, new I2CSlaveAddress(61)); - var input5 = Controller.Device(InstalledDevice.Input5); + var hsrel5 = _ccToolsBoardService.CreateHSREL5(InstalledDevice.UpperBathroomHSREL5, new I2CSlaveAddress(61)); + var input5 = _deviceService.GetDevice(InstalledDevice.Input5); + var i2CHardwareBridge = _deviceService.GetDevice(); const int SensorPin = 4; - - var i2cHardwareBridge = Controller.GetDevice(); - - var room = Controller.CreateArea(Room.UpperBathroom) - .WithTemperatureSensor(UpperBathroom.TemperatureSensor, i2cHardwareBridge.DHT22Accessor.GetTemperatureSensor(SensorPin)) - .WithHumiditySensor(UpperBathroom.HumiditySensor, i2cHardwareBridge.DHT22Accessor.GetHumiditySensor(SensorPin)) + + var room = _areaService.CreateArea(Room.UpperBathroom) + .WithTemperatureSensor(UpperBathroom.TemperatureSensor, i2CHardwareBridge.DHT22Accessor.GetTemperatureSensor(SensorPin)) + .WithHumiditySensor(UpperBathroom.HumiditySensor, i2CHardwareBridge.DHT22Accessor.GetHumiditySensor(SensorPin)) .WithMotionDetector(UpperBathroom.MotionDetector, input5.GetInput(15)) .WithLamp(UpperBathroom.LightCeilingDoor, hsrel5.GetOutput(0)) .WithLamp(UpperBathroom.LightCeilingEdge, hsrel5.GetOutput(1)) .WithLamp(UpperBathroom.LightCeilingMirrorCabinet, hsrel5.GetOutput(2)) .WithLamp(UpperBathroom.LampMirrorCabinet, hsrel5.GetOutput(3)) - .WithStateMachine(UpperBathroom.Fan, (s, r) => SetupFan(s, r, hsrel5)); + .WithStateMachine(UpperBathroom.Fan, (s, r) => SetupFan(s, hsrel5)); var combinedLights = room.CombineActuators(UpperBathroom.CombinedCeilingLights) @@ -73,16 +93,16 @@ public override void Setup() .WithTarget(combinedLights) .WithOnDuration(TimeSpan.FromMinutes(8)); - new BathroomFanAutomation(AutomationIdFactory.CreateIdFrom(room), Controller.ServiceLocator.GetService()) + new BathroomFanAutomation(AutomationIdFactory.CreateIdFrom(room), _schedulerService) .WithTrigger(room.GetMotionDetector(UpperBathroom.MotionDetector)) .WithSlowDuration(TimeSpan.FromMinutes(8)) .WithFastDuration(TimeSpan.FromMinutes(12)) .WithActuator(room.GetStateMachine(UpperBathroom.Fan)); - Controller.ServiceLocator.GetService().AddSynonymsForArea(Room.UpperBathroom, "BadOben", "UpperBathroom"); + _synonymService.AddSynonymsForArea(Room.UpperBathroom, "BadOben", "UpperBathroom"); } - private void SetupFan(StateMachine stateMachine, IArea room, HSREL5 hsrel5) + private void SetupFan(StateMachine stateMachine, HSREL5 hsrel5) { var fanPort0 = hsrel5.GetOutput(4); var fanPort1 = hsrel5.GetOutput(5); diff --git a/Controllers/HA4IoT.Controller.Main/StartupTask.cs b/Controllers/HA4IoT.Controller.Main/StartupTask.cs index 4fc0b8c2..fa583db2 100644 --- a/Controllers/HA4IoT.Controller.Main/StartupTask.cs +++ b/Controllers/HA4IoT.Controller.Main/StartupTask.cs @@ -1,4 +1,29 @@ -using Windows.ApplicationModel.Background; +using System.Threading.Tasks; +using Windows.ApplicationModel.Background; +using HA4IoT.Contracts.Api; +using HA4IoT.Contracts.Core; +using HA4IoT.Contracts.Hardware; +using HA4IoT.Contracts.Logging; +using HA4IoT.Contracts.PersonalAgent; +using HA4IoT.Contracts.Services; +using HA4IoT.Contracts.Services.Daylight; +using HA4IoT.Contracts.Services.OutdoorHumidity; +using HA4IoT.Contracts.Services.OutdoorTemperature; +using HA4IoT.Contracts.Services.System; +using HA4IoT.Contracts.Services.Weather; +using HA4IoT.Controller.Main.Rooms; +using HA4IoT.ExternalServices.OpenWeatherMap; +using HA4IoT.ExternalServices.TelegramBot; +using HA4IoT.ExternalServices.Twitter; +using HA4IoT.Hardware; +using HA4IoT.Hardware.CCTools; +using HA4IoT.Hardware.I2CHardwareBridge; +using HA4IoT.Hardware.Pi2; +using HA4IoT.Hardware.RemoteSwitch; +using HA4IoT.Hardware.RemoteSwitch.Codes; +using HA4IoT.PersonalAgent; +using HA4IoT.Services.ControllerSlave; +using HA4IoT.Services.Environment; namespace HA4IoT.Controller.Main { @@ -6,7 +31,142 @@ public sealed class StartupTask : IBackgroundTask { public void Run(IBackgroundTaskInstance taskInstance) { - new Controller().RunAsync(taskInstance); + var controller = new Controller { Initializer = new Initializer() }; + controller.RunAsync(taskInstance); + } + + private class Initializer : IInitializer + { + public void RegisterServices(IContainerService containerService) + { + RegisterI2CHardwareBridgeService(containerService); + RegisterOpenWeatherMapService(containerService); + RegisterControllerSlaveService(containerService); + RegisterTwitterClientService(containerService); + RegisterTelegramBotService(containerService); + } + + public Task Initialize(IContainerService containerService) + { + var ccToolsBoardService = containerService.GetInstance(); + var pi2GpioService = containerService.GetInstance(); + var synonymService = containerService.GetInstance(); + + synonymService.TryLoadPersistedSynonyms(); + + ccToolsBoardService.CreateHSPE16InputOnly(InstalledDevice.Input0, new I2CSlaveAddress(42)); + ccToolsBoardService.CreateHSPE16InputOnly(InstalledDevice.Input1, new I2CSlaveAddress(43)); + ccToolsBoardService.CreateHSPE16InputOnly(InstalledDevice.Input2, new I2CSlaveAddress(47)); + ccToolsBoardService.CreateHSPE16InputOnly(InstalledDevice.Input3, new I2CSlaveAddress(45)); + ccToolsBoardService.CreateHSPE16InputOnly(InstalledDevice.Input4, new I2CSlaveAddress(46)); + ccToolsBoardService.CreateHSPE16InputOnly(InstalledDevice.Input5, new I2CSlaveAddress(44)); + + containerService.GetInstance().Setup(); + containerService.GetInstance().Setup(); + containerService.GetInstance().Setup(); + containerService.GetInstance().Setup(); + containerService.GetInstance().Setup(); + containerService.GetInstance().Setup(); + containerService.GetInstance().Setup(); + containerService.GetInstance().Setup(); + containerService.GetInstance().Setup(); + containerService.GetInstance().Setup(); + + synonymService.RegisterDefaultComponentStateSynonyms(); + + InitializeAzureCloudApiEndpoint(); + + var ioBoardsInterruptMonitor = new InterruptMonitor(pi2GpioService.GetInput(4)); + ioBoardsInterruptMonitor.InterruptDetected += (s, e) => ccToolsBoardService.PollInputBoardStates(); + ioBoardsInterruptMonitor.Start(); + + return Task.FromResult(0); + } + + private void RegisterOpenWeatherMapService(IContainerService containerService) + { + var dateTimeService = containerService.GetInstance(); + var openWeatherMapService = containerService.GetInstance(); + + containerService.RegisterSingleton(() => openWeatherMapService); + containerService.RegisterSingleton(() => new OutdoorTemperatureService(openWeatherMapService, dateTimeService)); + containerService.RegisterSingleton(() => new OutdootHumidityService(openWeatherMapService, dateTimeService)); + containerService.RegisterSingleton(() => new DaylightService(openWeatherMapService, dateTimeService)); + containerService.RegisterSingleton(() => new WeatherService(openWeatherMapService, dateTimeService)); + } + + private void RegisterControllerSlaveService(IContainerService containerService) + { + var controllerSlaveServiceOptions = new ControllerSlaveServiceOptions + { + MasterControllerAddress = "127.0.0.1" + }; + + containerService.RegisterSingleton(() => controllerSlaveServiceOptions); + containerService.RegisterSingleton(); + } + + private void RegisterTelegramBotService(IContainerService containerService) + { + TelegramBotService telegramBotService; + if (!TelegramBotServiceFactory.TryCreateFromDefaultConfigurationFile(out telegramBotService)) + { + return; + } + + Log.WarningLogged += (s, e) => + { + telegramBotService.EnqueueMessageForAdministrators($"{Emoji.WarningSign} {e.Message}\r\n{e.Exception}", TelegramMessageFormat.PlainText); + }; + + Log.ErrorLogged += (s, e) => + { + if (e.Message.StartsWith("Sending Telegram message failed")) + { + // Prevent recursive send of sending failures. + return; + } + + telegramBotService.EnqueueMessageForAdministrators($"{Emoji.HeavyExclamationMark} {e.Message}\r\n{e.Exception}", TelegramMessageFormat.PlainText); + }; + + telegramBotService.EnqueueMessageForAdministrators($"{Emoji.Bell} Das System ist gestartet."); + + containerService.GetInstance().ExposeToTelegramBot(telegramBotService); + containerService.RegisterSingleton(() => telegramBotService); + } + + private void RegisterTwitterClientService(IContainerService containerService) + { + TwitterClientService twitterClientService; + if (!TwitterClientServiceFactory.TryCreateFromDefaultConfigurationFile(out twitterClientService)) + { + return; + } + + containerService.RegisterSingleton(() => twitterClientService); + } + + private void RegisterI2CHardwareBridgeService(IContainerService containerService) + { + const int LDP433MhzSenderPin = 10; + + var deviceService = containerService.GetInstance(); + var i2CBusService = containerService.GetInstance(); + var schedulerService = containerService.GetInstance(); + var apiService = containerService.GetInstance(); + + var i2CHardwareBridge = new I2CHardwareBridge(new I2CSlaveAddress(50), i2CBusService, schedulerService); + deviceService.AddDevice(i2CHardwareBridge); + + var brennenstuhl = new BrennenstuhlCodeSequenceProvider(); + var ldp433MHzSender = new LPD433MHzSignalSender(i2CHardwareBridge, LDP433MhzSenderPin, apiService); + + var remoteSwitchService = new RemoteSocketService(ldp433MHzSender, schedulerService) + .WithRemoteSocket(0, brennenstuhl.GetSequencePair(BrennenstuhlSystemCode.AllOn, BrennenstuhlUnitCode.A)); + + containerService.RegisterSingleton(() => remoteSwitchService); + } } } } \ No newline at end of file diff --git a/HA4IoT.sln b/HA4IoT.sln index c061202a..f9ee4afc 100644 --- a/HA4IoT.sln +++ b/HA4IoT.sln @@ -131,6 +131,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HA4IoT.Core.Tests", "Tests\ EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HA4IoT.Services", "SDK\HA4IoT.Services\HA4IoT.Services.csproj", "{6FD41DDA-4369-43C1-807A-B1BC43ECBDBF}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HA4IoT.Settings", "SDK\HA4IoT.Settings\HA4IoT.Settings.csproj", "{600BC3F2-2A09-4A8E-9126-1F9ACCD7D879}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|ARM (For Raspberry Pi) = Debug|ARM (For Raspberry Pi) @@ -511,12 +513,20 @@ Global {4BD2A0F3-4CFC-41EE-ACE3-BE41A4A75C48}.Release|x86 (For local).Build.0 = Release|x86 {6FD41DDA-4369-43C1-807A-B1BC43ECBDBF}.Debug|ARM (For Raspberry Pi).ActiveCfg = Debug|ARM {6FD41DDA-4369-43C1-807A-B1BC43ECBDBF}.Debug|ARM (For Raspberry Pi).Build.0 = Debug|ARM - {6FD41DDA-4369-43C1-807A-B1BC43ECBDBF}.Debug|x86 (For local).ActiveCfg = Debug|Any CPU - {6FD41DDA-4369-43C1-807A-B1BC43ECBDBF}.Debug|x86 (For local).Build.0 = Debug|Any CPU + {6FD41DDA-4369-43C1-807A-B1BC43ECBDBF}.Debug|x86 (For local).ActiveCfg = Debug|x86 + {6FD41DDA-4369-43C1-807A-B1BC43ECBDBF}.Debug|x86 (For local).Build.0 = Debug|x86 {6FD41DDA-4369-43C1-807A-B1BC43ECBDBF}.Release|ARM (For Raspberry Pi).ActiveCfg = Release|Any CPU {6FD41DDA-4369-43C1-807A-B1BC43ECBDBF}.Release|ARM (For Raspberry Pi).Build.0 = Release|Any CPU {6FD41DDA-4369-43C1-807A-B1BC43ECBDBF}.Release|x86 (For local).ActiveCfg = Release|x86 {6FD41DDA-4369-43C1-807A-B1BC43ECBDBF}.Release|x86 (For local).Build.0 = Release|x86 + {600BC3F2-2A09-4A8E-9126-1F9ACCD7D879}.Debug|ARM (For Raspberry Pi).ActiveCfg = Debug|Any CPU + {600BC3F2-2A09-4A8E-9126-1F9ACCD7D879}.Debug|ARM (For Raspberry Pi).Build.0 = Debug|Any CPU + {600BC3F2-2A09-4A8E-9126-1F9ACCD7D879}.Debug|x86 (For local).ActiveCfg = Debug|x86 + {600BC3F2-2A09-4A8E-9126-1F9ACCD7D879}.Debug|x86 (For local).Build.0 = Debug|x86 + {600BC3F2-2A09-4A8E-9126-1F9ACCD7D879}.Release|ARM (For Raspberry Pi).ActiveCfg = Release|Any CPU + {600BC3F2-2A09-4A8E-9126-1F9ACCD7D879}.Release|ARM (For Raspberry Pi).Build.0 = Release|Any CPU + {600BC3F2-2A09-4A8E-9126-1F9ACCD7D879}.Release|x86 (For local).ActiveCfg = Release|Any CPU + {600BC3F2-2A09-4A8E-9126-1F9ACCD7D879}.Release|x86 (For local).Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -577,5 +587,6 @@ Global {DF91A86C-235F-44E7-AA3C-72FA0B786250} = {C66A0C8B-0AAA-40C0-8D27-BD5B7BF1EF46} {4BD2A0F3-4CFC-41EE-ACE3-BE41A4A75C48} = {C66A0C8B-0AAA-40C0-8D27-BD5B7BF1EF46} {6FD41DDA-4369-43C1-807A-B1BC43ECBDBF} = {982ABB4E-A5DC-4C78-87A3-30BF49DD5764} + {600BC3F2-2A09-4A8E-9126-1F9ACCD7D879} = {982ABB4E-A5DC-4C78-87A3-30BF49DD5764} EndGlobalSection EndGlobal diff --git a/SDK/Api/HA4IoT.Api.LocalHttpServer/LocalHttpServerApiDispatcherEndpoint.cs b/SDK/Api/HA4IoT.Api.LocalHttpServer/LocalHttpServerApiDispatcherEndpoint.cs index 0f4851e1..ec3c2b9b 100644 --- a/SDK/Api/HA4IoT.Api.LocalHttpServer/LocalHttpServerApiDispatcherEndpoint.cs +++ b/SDK/Api/HA4IoT.Api.LocalHttpServer/LocalHttpServerApiDispatcherEndpoint.cs @@ -10,11 +10,11 @@ namespace HA4IoT.Api.LocalRestServer { public class LocalHttpServerApiDispatcherEndpoint : IApiDispatcherEndpoint { - public LocalHttpServerApiDispatcherEndpoint(HttpServer httpRequestController) + public LocalHttpServerApiDispatcherEndpoint(HttpServer httpServer) { - if (httpRequestController == null) throw new ArgumentNullException(nameof(httpRequestController)); + if (httpServer == null) throw new ArgumentNullException(nameof(httpServer)); - httpRequestController.RequestReceived += DispatchRequest; + httpServer.RequestReceived += DispatchRequest; } public event EventHandler RequestReceived; diff --git a/SDK/Api/HA4IoT.Api/ApiController.cs b/SDK/Api/HA4IoT.Api/ApiService.cs similarity index 94% rename from SDK/Api/HA4IoT.Api/ApiController.cs rename to SDK/Api/HA4IoT.Api/ApiService.cs index ceadccbb..28dfa794 100644 --- a/SDK/Api/HA4IoT.Api/ApiController.cs +++ b/SDK/Api/HA4IoT.Api/ApiService.cs @@ -1,32 +1,25 @@ using System; using System.Collections.Generic; using System.Diagnostics; -using System.Globalization; using Windows.Data.Json; using Windows.Security.Cryptography; using Windows.Security.Cryptography.Core; using Windows.Storage.Streams; -using HA4IoT.Contracts.Actuators; using HA4IoT.Contracts.Api; using HA4IoT.Contracts.Components; using HA4IoT.Networking; namespace HA4IoT.Api { - public class ApiController : IApiController + public class ApiService : IApiService { - private readonly string _name; private readonly List _endpoints = new List(); private readonly Dictionary> _requestRoutes = new Dictionary>(StringComparer.OrdinalIgnoreCase); private readonly Dictionary> _commandRoutes = new Dictionary>(StringComparer.OrdinalIgnoreCase); private readonly HashAlgorithmProvider _hashAlgorithm = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5); - public ApiController(string name) + public ApiService() { - if (name == null) throw new ArgumentNullException(nameof(name)); - - _name = name; - RouteRequest("requests", HandleRequestApiDescription); } @@ -67,7 +60,7 @@ public void RegisterEndpoint(IApiDispatcherEndpoint endpoint) private string GenerateUri(string relativePath) { - return $"/{_name}/{relativePath}".Trim(); + return $"/api/{relativePath}".Trim(); } private void RouteRequest(object sender, ApiRequestReceivedEventArgs e) diff --git a/SDK/Api/HA4IoT.Api/HA4IoT.Api.csproj b/SDK/Api/HA4IoT.Api/HA4IoT.Api.csproj index 63040caa..a9628cad 100644 --- a/SDK/Api/HA4IoT.Api/HA4IoT.Api.csproj +++ b/SDK/Api/HA4IoT.Api/HA4IoT.Api.csproj @@ -108,7 +108,7 @@ - + diff --git a/SDK/ExternalServices/HA4IoT.ExternalServices.TelegramBot/PersonalAgentToTelegramBotDispatcher.cs b/SDK/ExternalServices/HA4IoT.ExternalServices.TelegramBot/PersonalAgentToTelegramBotDispatcher.cs index a543770f..5baac257 100644 --- a/SDK/ExternalServices/HA4IoT.ExternalServices.TelegramBot/PersonalAgentToTelegramBotDispatcher.cs +++ b/SDK/ExternalServices/HA4IoT.ExternalServices.TelegramBot/PersonalAgentToTelegramBotDispatcher.cs @@ -1,18 +1,18 @@ using System; -using HA4IoT.Contracts.Core; +using HA4IoT.Contracts.Services.System; using HA4IoT.PersonalAgent; namespace HA4IoT.ExternalServices.TelegramBot { public class PersonalAgentToTelegramBotDispatcher { - private readonly IController _controller; - - public PersonalAgentToTelegramBotDispatcher(IController controller) + private readonly IContainerService _containerService; + + public PersonalAgentToTelegramBotDispatcher(IContainerService containerService) { - if (controller == null) throw new ArgumentNullException(nameof(controller)); - - _controller = controller; + if (containerService == null) throw new ArgumentNullException(nameof(containerService)); + + _containerService = containerService; } public void ExposeToTelegramBot(TelegramBotService telegramBotService) @@ -24,7 +24,7 @@ public void ExposeToTelegramBot(TelegramBotService telegramBotService) private void ProcessMessageAndSendAnswer(object sender, TelegramBotMessageReceivedEventArgs e) { - var messageProcessor = new PersonalAgentMessageProcessor(_controller); + var messageProcessor = _containerService.GetInstance(); messageProcessor.ProcessMessage(e.Message); e.EnqueueResponse(messageProcessor.Answer, TelegramMessageFormat.HTML); diff --git a/SDK/ExternalServices/HA4IoT.ExternalServices.Twitter/HA4IoT.ExternalServices.Twitter.csproj b/SDK/ExternalServices/HA4IoT.ExternalServices.Twitter/HA4IoT.ExternalServices.Twitter.csproj index 528c5cec..c3fccb68 100644 --- a/SDK/ExternalServices/HA4IoT.ExternalServices.Twitter/HA4IoT.ExternalServices.Twitter.csproj +++ b/SDK/ExternalServices/HA4IoT.ExternalServices.Twitter/HA4IoT.ExternalServices.Twitter.csproj @@ -109,8 +109,8 @@ - - + + diff --git a/SDK/ExternalServices/HA4IoT.ExternalServices.Twitter/TweetAction.cs b/SDK/ExternalServices/HA4IoT.ExternalServices.Twitter/TweetAction.cs index e22254cc..46f7a54a 100644 --- a/SDK/ExternalServices/HA4IoT.ExternalServices.Twitter/TweetAction.cs +++ b/SDK/ExternalServices/HA4IoT.ExternalServices.Twitter/TweetAction.cs @@ -7,9 +7,9 @@ namespace HA4IoT.ExternalServices.Twitter public class TweetAction : IAction { private readonly Func _messageProvider; - private readonly TwitterService _twitterService; + private readonly TwitterClientService _twitterService; - public TweetAction(Func messageProvider, TwitterService twitterService) + public TweetAction(Func messageProvider, TwitterClientService twitterService) { if (messageProvider == null) throw new ArgumentNullException(nameof(messageProvider)); if (twitterService == null) throw new ArgumentNullException(nameof(twitterService)); @@ -18,7 +18,7 @@ public TweetAction(Func messageProvider, TwitterService twitterService) _twitterService = twitterService; } - public TweetAction(string message, TwitterService twitterService) + public TweetAction(string message, TwitterClientService twitterService) { if (message == null) throw new ArgumentNullException(nameof(message)); if (twitterService == null) throw new ArgumentNullException(nameof(twitterService)); diff --git a/SDK/ExternalServices/HA4IoT.ExternalServices.Twitter/TwitterService.cs b/SDK/ExternalServices/HA4IoT.ExternalServices.Twitter/TwitterClientService.cs similarity index 98% rename from SDK/ExternalServices/HA4IoT.ExternalServices.Twitter/TwitterService.cs rename to SDK/ExternalServices/HA4IoT.ExternalServices.Twitter/TwitterClientService.cs index ce5116a4..133412c4 100644 --- a/SDK/ExternalServices/HA4IoT.ExternalServices.Twitter/TwitterService.cs +++ b/SDK/ExternalServices/HA4IoT.ExternalServices.Twitter/TwitterClientService.cs @@ -12,7 +12,7 @@ namespace HA4IoT.ExternalServices.Twitter { - public class TwitterService : ServiceBase + public class TwitterClientService : ServiceBase { private string _nonce; private string _timestamp; diff --git a/SDK/ExternalServices/HA4IoT.ExternalServices.Twitter/TwitterServiceFactory.cs b/SDK/ExternalServices/HA4IoT.ExternalServices.Twitter/TwitterClientServiceFactory.cs similarity index 88% rename from SDK/ExternalServices/HA4IoT.ExternalServices.Twitter/TwitterServiceFactory.cs rename to SDK/ExternalServices/HA4IoT.ExternalServices.Twitter/TwitterClientServiceFactory.cs index c966f529..52eb70bf 100644 --- a/SDK/ExternalServices/HA4IoT.ExternalServices.Twitter/TwitterServiceFactory.cs +++ b/SDK/ExternalServices/HA4IoT.ExternalServices.Twitter/TwitterClientServiceFactory.cs @@ -5,9 +5,9 @@ namespace HA4IoT.ExternalServices.Twitter { - public static class TwitterServiceFactory + public static class TwitterClientServiceFactory { - public static bool TryCreateFromConfigurationFile(string filename, out TwitterService twitterService) + public static bool TryCreateFromConfigurationFile(string filename, out TwitterClientService twitterService) { if (!File.Exists(filename)) { @@ -25,7 +25,7 @@ public static bool TryCreateFromConfigurationFile(string filename, out TwitterSe return false; } - twitterService = new TwitterService(); + twitterService = new TwitterClientService(); twitterService.AccessToken = configuration.GetNamedString("AccessToken"); twitterService.AccessTokenSecret = configuration.GetNamedString("AccessTokenSecret"); twitterService.CosumerSecret = configuration.GetNamedString("ConsumerSecret"); @@ -40,7 +40,7 @@ public static bool TryCreateFromConfigurationFile(string filename, out TwitterSe } } - public static bool TryCreateFromDefaultConfigurationFile(out TwitterService twitterService) + public static bool TryCreateFromDefaultConfigurationFile(out TwitterClientService twitterService) { string filename = Path.Combine(ApplicationData.Current.LocalFolder.Path, "TwitterClientConfiguration.json"); return TryCreateFromConfigurationFile(filename, out twitterService); diff --git a/SDK/HA4IoT.Actuators/ActuatorExtensions.cs b/SDK/HA4IoT.Actuators/ActuatorExtensions.cs index f040f85c..403a20fc 100644 --- a/SDK/HA4IoT.Actuators/ActuatorExtensions.cs +++ b/SDK/HA4IoT.Actuators/ActuatorExtensions.cs @@ -2,7 +2,6 @@ using HA4IoT.Contracts.Actuators; using HA4IoT.Contracts.Areas; using HA4IoT.Contracts.Components; -using HA4IoT.Contracts.Core; namespace HA4IoT.Actuators { @@ -15,14 +14,6 @@ public static IActuator GetActuator(this IArea area, Enum id) return area.GetComponent(ComponentIdFactory.Create(area.Id, id)); } - public static IActuator GetActuator(this IComponentController controller, ComponentId id) - { - if (controller == null) throw new ArgumentNullException(nameof(controller)); - if (id == null) throw new ArgumentNullException(nameof(id)); - - return controller.GetComponent(id); - } - public static bool IsOn(this IActuator actuator) { if (actuator == null) throw new ArgumentNullException(nameof(actuator)); diff --git a/SDK/HA4IoT.Actuators/Animations/Animation.cs b/SDK/HA4IoT.Actuators/Animations/Animation.cs index 0de64e4a..9ff532a0 100644 --- a/SDK/HA4IoT.Actuators/Animations/Animation.cs +++ b/SDK/HA4IoT.Actuators/Animations/Animation.cs @@ -1,23 +1,22 @@ using System; using System.Collections.Generic; using System.Linq; -using HA4IoT.Contracts; using HA4IoT.Contracts.Core; -using HA4IoT.Core.Timer; +using HA4IoT.Contracts.Services.System; namespace HA4IoT.Actuators.Animations { public class Animation { - private readonly IHomeAutomationTimer _timer; + private readonly ITimerService _timerService; private TimeSpan _position = TimeSpan.Zero; - public Animation(IHomeAutomationTimer timer) + public Animation(ITimerService timerService) { - if (timer == null) throw new ArgumentNullException(nameof(timer)); + if (timerService == null) throw new ArgumentNullException(nameof(timerService)); - _timer = timer; + _timerService = timerService; } public IList Frames { get; } = new List(); @@ -25,12 +24,12 @@ public Animation(IHomeAutomationTimer timer) public virtual void Start() { ApplyFrame(); - _timer.Tick += ApplyFrame; + _timerService.Tick += ApplyFrame; } public void Stop() { - _timer.Tick -= ApplyFrame; + _timerService.Tick -= ApplyFrame; } public Animation WithFrame(Frame frame) diff --git a/SDK/HA4IoT.Actuators/Animations/DirectionAnimation.cs b/SDK/HA4IoT.Actuators/Animations/DirectionAnimation.cs index 4c706e84..bde5a15d 100644 --- a/SDK/HA4IoT.Actuators/Animations/DirectionAnimation.cs +++ b/SDK/HA4IoT.Actuators/Animations/DirectionAnimation.cs @@ -4,6 +4,7 @@ using HA4IoT.Contracts.Actuators; using HA4IoT.Contracts.Components; using HA4IoT.Contracts.Core; +using HA4IoT.Contracts.Services.System; namespace HA4IoT.Actuators.Animations { @@ -14,7 +15,7 @@ public class DirectionAnimation : Animation private IComponentState _targetState; private TimeSpan _duration = TimeSpan.FromMilliseconds(250); - public DirectionAnimation(IHomeAutomationTimer timer) : base(timer) + public DirectionAnimation(ITimerService timerService) : base(timerService) { } diff --git a/SDK/HA4IoT.Actuators/BinaryStateActuators/LogicalBinaryStateActuator.cs b/SDK/HA4IoT.Actuators/BinaryStateActuators/LogicalBinaryStateActuator.cs index 2b123463..3baee8a9 100644 --- a/SDK/HA4IoT.Actuators/BinaryStateActuators/LogicalBinaryStateActuator.cs +++ b/SDK/HA4IoT.Actuators/BinaryStateActuators/LogicalBinaryStateActuator.cs @@ -6,21 +6,22 @@ using HA4IoT.Contracts.Core; using HA4IoT.Contracts.Hardware; using HA4IoT.Contracts.Sensors; +using HA4IoT.Contracts.Services.System; namespace HA4IoT.Actuators.BinaryStateActuators { public class LogicalBinaryStateActuator : ActuatorBase, IStateMachine { - private readonly IHomeAutomationTimer _timer; + private readonly ITimerService _timerService; private IComponentState _state = new UnknownComponentState(); - public LogicalBinaryStateActuator(ComponentId id, IHomeAutomationTimer timer) + public LogicalBinaryStateActuator(ComponentId id, ITimerService timerService) : base(id) { - if (timer == null) throw new ArgumentNullException(nameof(timer)); + if (timerService == null) throw new ArgumentNullException(nameof(timerService)); - _timer = timer; + _timerService = timerService; } public IList Actuators { get; } = new List(); diff --git a/SDK/HA4IoT.Actuators/BinaryStateActuators/LogicalBinaryStateActuatorExtensions.cs b/SDK/HA4IoT.Actuators/BinaryStateActuators/LogicalBinaryStateActuatorExtensions.cs index b219086c..fc520915 100644 --- a/SDK/HA4IoT.Actuators/BinaryStateActuators/LogicalBinaryStateActuatorExtensions.cs +++ b/SDK/HA4IoT.Actuators/BinaryStateActuators/LogicalBinaryStateActuatorExtensions.cs @@ -10,7 +10,7 @@ public static LogicalBinaryStateActuator CombineActuators(this IArea area, Enum { if (area == null) throw new ArgumentNullException(nameof(area)); - var actuator = new LogicalBinaryStateActuator(ComponentIdFactory.Create(area.Id, id), area.Controller.Timer); + var actuator = new LogicalBinaryStateActuator(ComponentIdFactory.Create(area.Id, id), area.Controller.TimerService); area.AddComponent(actuator); return actuator; } diff --git a/SDK/HA4IoT.Actuators/RollerShutters/RollerShutter.cs b/SDK/HA4IoT.Actuators/RollerShutters/RollerShutter.cs index 6346b122..69bf9de0 100644 --- a/SDK/HA4IoT.Actuators/RollerShutters/RollerShutter.cs +++ b/SDK/HA4IoT.Actuators/RollerShutters/RollerShutter.cs @@ -9,6 +9,7 @@ using HA4IoT.Contracts.Core; using HA4IoT.Contracts.Hardware; using HA4IoT.Contracts.Services; +using HA4IoT.Contracts.Services.System; using HA4IoT.Networking; using Action = HA4IoT.Actuators.Actions.Action; @@ -18,7 +19,7 @@ public class RollerShutter : ActuatorBase, IRollerShutter { private readonly Stopwatch _movingDuration = new Stopwatch(); private readonly IRollerShutterEndpoint _endpoint; - private readonly IHomeAutomationTimer _timer; + private readonly ITimerService _timerService; private readonly ISchedulerService _schedulerService; private readonly IAction _startMoveUpAction; @@ -35,7 +36,7 @@ public class RollerShutter : ActuatorBase, IRollerShutter public RollerShutter( ComponentId id, IRollerShutterEndpoint endpoint, - IHomeAutomationTimer timer, + ITimerService timerService, ISchedulerService schedulerService) : base(id) { @@ -44,10 +45,10 @@ public RollerShutter( if (schedulerService == null) throw new ArgumentNullException(nameof(schedulerService)); _endpoint = endpoint; - _timer = timer; + _timerService = timerService; _schedulerService = schedulerService; - timer.Tick += (s, e) => UpdatePosition(e); + timerService.Tick += (s, e) => UpdatePosition(e); _settings = new RollerShutterSettingsWrapper(Settings); _startMoveUpAction = new Action(() => SetState(RollerShutterStateId.MovingUp)); diff --git a/SDK/HA4IoT.Actuators/RollerShutters/RollerShutterExtensions.cs b/SDK/HA4IoT.Actuators/RollerShutters/RollerShutterExtensions.cs index dad111d7..b5e0efe9 100644 --- a/SDK/HA4IoT.Actuators/RollerShutters/RollerShutterExtensions.cs +++ b/SDK/HA4IoT.Actuators/RollerShutters/RollerShutterExtensions.cs @@ -34,7 +34,7 @@ public static IArea WithRollerShutter(this IArea area, Enum id, IBinaryOutput po var rollerShutter = new RollerShutter( ComponentIdFactory.Create(area.Id, id), new PortBasedRollerShutterEndpoint(powerOutput, directionOutput), - area.Controller.Timer, + area.Controller.TimerService, area.Controller.ServiceLocator.GetService()); area.AddComponent(rollerShutter); diff --git a/SDK/HA4IoT.Components/HA4IoT.Components.csproj b/SDK/HA4IoT.Components/HA4IoT.Components.csproj index 3208c586..8a06d053 100644 --- a/SDK/HA4IoT.Components/HA4IoT.Components.csproj +++ b/SDK/HA4IoT.Components/HA4IoT.Components.csproj @@ -118,10 +118,6 @@ {E1EDAC4B-83B9-46F4-9F6A-3BAE97D79F29} HA4IoT.Contracts - - {2BBEF090-4FEE-4FB7-9CF1-F6597F2C53EA} - HA4IoT.Core - {D4E0A3F9-6521-4AEE-815A-E2A60323FB63} HA4IoT.Networking diff --git a/SDK/HA4IoT.Configuration/ConfigurationExtenderBase.cs b/SDK/HA4IoT.Configuration/ConfigurationExtenderBase.cs deleted file mode 100644 index e7ab8760..00000000 --- a/SDK/HA4IoT.Configuration/ConfigurationExtenderBase.cs +++ /dev/null @@ -1,67 +0,0 @@ -using System; -using System.Xml.Linq; -using HA4IoT.Contracts.Components; -using HA4IoT.Contracts.Configuration; -using HA4IoT.Contracts.Core; -using HA4IoT.Contracts.Hardware; -using HA4IoT.Contracts.Sensors; -using HA4IoT.Contracts.Services; - -namespace HA4IoT.Configuration -{ - public abstract class ConfigurationExtenderBase : IConfigurationExtender - { - protected ConfigurationExtenderBase(ConfigurationParser parser, IController controller) - { - if (parser == null) throw new ArgumentNullException(nameof(parser)); - if (controller == null) throw new ArgumentNullException(nameof(controller)); - - Parser = parser; - Controller = controller; - } - - public string Namespace { get; protected set; } = string.Empty; - - public virtual IDevice ParseDevice(XElement element) - { - throw new NotSupportedException("Configuratio extender '" + Namespace + "' does not support any devices."); - } - - public virtual IService ParseService(XElement element) - { - throw new NotSupportedException("Configuratio extender '" + Namespace + "' does not support any services."); - } - - public virtual IBinaryOutput ParseBinaryOutput(XElement element) - { - throw new NotSupportedException("Configuratio extender '" + Namespace + "' does not support any binary outputs."); - } - - public virtual IBinaryInput ParseBinaryInput(XElement element) - { - throw new NotSupportedException("Configuratio extender '" + Namespace + "' does not support any binary inputs."); - } - - public virtual INumericValueSensorEndpoint ParseNumericValueSensor(XElement element) - { - throw new NotSupportedException("Configuratio extender '" + Namespace + "' does not support any single value sensors."); - } - - public virtual IComponent ParseComponent(XElement element) - { - throw new NotSupportedException("Configuratio extender '" + Namespace + "' does not support any components."); - } - - public virtual void OnConfigurationParsed() - { - } - - public virtual void OnInitializationFromCodeCompleted() - { - } - - protected ConfigurationParser Parser { get; } - - protected IController Controller { get; } - } -} diff --git a/SDK/HA4IoT.Configuration/ConfigurationExtensions.cs b/SDK/HA4IoT.Configuration/ConfigurationExtensions.cs deleted file mode 100644 index 7e111aa6..00000000 --- a/SDK/HA4IoT.Configuration/ConfigurationExtensions.cs +++ /dev/null @@ -1,154 +0,0 @@ -using System; -using System.Linq; -using System.Xml.Linq; -using HA4IoT.Contracts.Configuration; - -namespace HA4IoT.Configuration -{ - public static class ConfigurationExtensions - { - public static TValue GetGenericValueFromAttribute(this XElement element, string attributeName, TValue defaultValue, Func converter) - { - if (element == null) throw new ArgumentNullException(nameof(element)); - if (attributeName == null) throw new ArgumentNullException(nameof(attributeName)); - if (converter == null) throw new ArgumentNullException(nameof(converter)); - - var attribute = element.Attribute(attributeName); - if (attribute == null) - { - return defaultValue; - } - - return converter(attribute.Value); - } - - public static TValue GetMandatoryGenericValueFromAttribute(this XElement element, string attributeName, Func converter) - { - if (element == null) throw new ArgumentNullException(nameof(element)); - if (attributeName == null) throw new ArgumentNullException(nameof(attributeName)); - if (converter == null) throw new ArgumentNullException(nameof(converter)); - - var attribute = element.Attribute(attributeName); - if (attribute == null) - { - throw new ConfigurationInvalidException("Mandatory attribute '" + attributeName + "' missing.", element); - } - - return converter(attribute.Value); - } - - public static string GetStringFromAttribute(this XElement element, string attributeName, string defaultValue) - { - return GetGenericValueFromAttribute(element, attributeName, defaultValue, v => v); - } - - public static bool GetBoolFromAttribute(this XElement element, string attributeName, bool defaultValue) - { - return GetGenericValueFromAttribute(element, attributeName, defaultValue, Convert.ToBoolean); - } - - public static int GetIntFromAttribute(this XElement element, string attributeName, int defaultValue) - { - return GetGenericValueFromAttribute(element, attributeName, defaultValue, Convert.ToInt32); - } - - public static double GetDoubleFromAttribute(this XElement element, string attributeName, double defaultValue) - { - return GetGenericValueFromAttribute(element, attributeName, defaultValue, Convert.ToDouble); - } - - public static TimeSpan GetTimeSpanFromAttribute(this XElement element, string attributeName, TimeSpan defaultValue) - { - return GetGenericValueFromAttribute(element, attributeName, defaultValue, TimeSpan.Parse); - } - - public static string GetMandatoryStringFromAttribute(this XElement element, string attributeName) - { - if (element == null) throw new ArgumentNullException(nameof(element)); - if (attributeName == null) throw new ArgumentNullException(nameof(attributeName)); - - return element.GetMandatoryGenericValueFromAttribute(attributeName, v => v); - } - - public static TEnum GetMandatoryEnumFromAttribute(this XElement element, string attributeName) - { - if (element == null) throw new ArgumentNullException(nameof(element)); - if (attributeName == null) throw new ArgumentNullException(nameof(attributeName)); - - string value = element.GetMandatoryGenericValueFromAttribute(attributeName, v => v); - return (TEnum)Enum.Parse(typeof (TEnum), value, true); - } - - public static bool GetMandatoryBoolFromAttribute(this XElement element, string attributeName) - { - if (element == null) throw new ArgumentNullException(nameof(element)); - if (attributeName == null) throw new ArgumentNullException(nameof(attributeName)); - - return element.GetMandatoryGenericValueFromAttribute(attributeName, Convert.ToBoolean); - } - - public static int GetMandatoryIntFromAttribute(this XElement element, string attributeName) - { - if (element == null) throw new ArgumentNullException(nameof(element)); - if (attributeName == null) throw new ArgumentNullException(nameof(attributeName)); - - return element.GetMandatoryGenericValueFromAttribute(attributeName, Convert.ToInt32); - } - - public static double GetMandatoryDoubleFromAttribute(this XElement element, string attributeName) - { - if (element == null) throw new ArgumentNullException(nameof(element)); - if (attributeName == null) throw new ArgumentNullException(nameof(attributeName)); - - return element.GetMandatoryGenericValueFromAttribute(attributeName, Convert.ToDouble); - } - - public static XElement GetMandatorySingleChildFromContainer(this XElement element, string containerElementName) - { - if (element == null) throw new ArgumentNullException(nameof(element)); - if (containerElementName == null) throw new ArgumentNullException(nameof(containerElementName)); - - var containerElement = element.Element(containerElementName); - if (containerElement == null) - { - throw new ConfigurationInvalidException("Mandatory container element '" + containerElementName + "' missing.", element); - } - - var childElements = containerElement.Elements().ToList(); - - if (childElements.Count == 0) - { - throw new ConfigurationInvalidException("Mandatory container element '" + containerElementName + "' is empty.", element); - } - - if (childElements.Count > 1) - { - throw new ConfigurationInvalidException("Mandatory container element '" + containerElementName + "' contains more than one element.", element); - } - - return childElements.First(); - } - - public static XElement GetMandatorySingleChildElementOrFromContainer(this XElement element, string containerElementName) - { - if (element == null) throw new ArgumentNullException(nameof(element)); - if (containerElementName == null) throw new ArgumentNullException(nameof(containerElementName)); - - var childElements = element.Elements().ToList(); - if (childElements.Count == 1) - { - return childElements.First(); - } - - return element.GetMandatorySingleChildFromContainer(containerElementName); - } - - public static bool HasChildElement(this XElement element, string childElementName) - { - if (element == null) throw new ArgumentNullException(nameof(element)); - if (childElementName == null) throw new ArgumentNullException(nameof(childElementName)); - - return element.Element(childElementName) != null; - } - } -} diff --git a/SDK/HA4IoT.Configuration/ConfigurationParser.cs b/SDK/HA4IoT.Configuration/ConfigurationParser.cs deleted file mode 100644 index 2834e6e0..00000000 --- a/SDK/HA4IoT.Configuration/ConfigurationParser.cs +++ /dev/null @@ -1,181 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Xml.Linq; -using Windows.Storage; -using HA4IoT.Contracts.Areas; -using HA4IoT.Contracts.Configuration; -using HA4IoT.Contracts.Core; -using HA4IoT.Contracts.Hardware; -using HA4IoT.Contracts.Logging; -using HA4IoT.Contracts.Sensors; -using HA4IoT.Core; - -namespace HA4IoT.Configuration -{ - public class ConfigurationParser - { - private readonly Dictionary _configurationExtenders = new Dictionary(); - private readonly IController _controller; - - private XDocument _configuration; - - public ConfigurationParser(IController controller) - { - if (controller == null) throw new ArgumentNullException(nameof(controller)); - - _controller = controller; - } - - public void RegisterConfigurationExtender(IConfigurationExtender configurationExtender) - { - if (configurationExtender == null) throw new ArgumentNullException(nameof(configurationExtender)); - - _configurationExtenders.Add(configurationExtender.Namespace, configurationExtender); - } - - public void ParseConfiguration(XDocument configuration) - { - if (configuration == null) throw new ArgumentNullException(nameof(configuration)); - - _configuration = configuration; - - ParseServices(); - ParseDevices(); - ParseAreas(); - - TriggerOnConfigurationParsed(); - } - - public void ParseConfiguration() - { - XDocument configuration = LoadConfiguration(); - if (configuration == null) - { - return; - } - - ParseConfiguration(configuration); - } - - public IBinaryInput ParseBinaryInput(XElement element) - { - return GetConfigurationExtender(element).ParseBinaryInput(element).WithInvertedState(element.GetBoolFromAttribute("invertState", false)); - } - - public IBinaryOutput ParseBinaryOutput(XElement element) - { - return GetConfigurationExtender(element).ParseBinaryOutput(element).WithInvertedState(element.GetBoolFromAttribute("invertState", false)); - } - - public INumericValueSensorEndpoint ParseNumericValueSensor(XElement element) - { - return GetConfigurationExtender(element).ParseNumericValueSensor(element); - } - - private XDocument LoadConfiguration() - { - string filename = Path.Combine(ApplicationData.Current.LocalFolder.Path, "Configuration.xml"); - if (!File.Exists(filename)) - { - Log.Info($"Skipped loading XML configuration because file '{filename}' does not exist."); - return null; - } - - using (var fileStream = File.OpenRead(filename)) - { - return XDocument.Load(fileStream); - } - } - - private void ParseServices() - { - var servicesElement = _configuration.Root.Element("Services"); - foreach (XElement serviceElement in servicesElement.Elements()) - { - try - { - // TODO: Get the type from an attribute. - var service = GetConfigurationExtender(serviceElement).ParseService(serviceElement); - _controller.ServiceLocator.RegisterService(service.GetType(), service); - } - catch (Exception exception) - { - Log.Warning(exception, $"Unable to parse service node '{serviceElement.Name}'."); - } - } - } - - private void ParseDevices() - { - var devicesElement = _configuration.Root.Element("Devices"); - foreach (XElement deviceElement in devicesElement.Elements()) - { - try - { - var device = GetConfigurationExtender(deviceElement).ParseDevice(deviceElement); - _controller.AddDevice(device); - } - catch (Exception exception) - { - Log.Warning(exception, $"Unable to parse device node '{deviceElement.Name}'."); - } - } - } - - private void ParseAreas() - { - var roomsElement = _configuration.Root.Element("Areas"); - foreach (XElement areaElement in roomsElement.Elements()) - { - try - { - _controller.AddArea(ParseArea(areaElement)); - } - catch (Exception exception) - { - Log.Warning(exception, $"Unable to parse area node '{areaElement.Name}'."); - } - } - } - - private IArea ParseArea(XElement roomElement) - { - var area = new Area(new AreaId(roomElement.GetMandatoryStringFromAttribute("id")), _controller); - - foreach (var componentElement in roomElement.Element("Components").Elements()) - { - try - { - var component = GetConfigurationExtender(componentElement).ParseComponent(componentElement); - area.AddComponent(component); - } - catch (Exception exception) - { - Log.Warning(exception, $"Unable to parse component node '{componentElement.Name}'."); - } - } - - return area; - } - - private IConfigurationExtender GetConfigurationExtender(XElement element) - { - IConfigurationExtender extender; - if (!_configurationExtenders.TryGetValue(element.Name.NamespaceName, out extender)) - { - throw new InvalidOperationException("No configuration extender found for element with namespace '" + element.Name.NamespaceName + "'."); - } - - return extender; - } - - private void TriggerOnConfigurationParsed() - { - foreach (var configurationExtender in _configurationExtenders.Values) - { - configurationExtender.OnConfigurationParsed(); - } - } - } -} diff --git a/SDK/HA4IoT.Configuration/DefaultConfigurationExtender.cs b/SDK/HA4IoT.Configuration/DefaultConfigurationExtender.cs deleted file mode 100644 index 82097121..00000000 --- a/SDK/HA4IoT.Configuration/DefaultConfigurationExtender.cs +++ /dev/null @@ -1,239 +0,0 @@ -using System; -using System.Xml.Linq; -using HA4IoT.Actuators; -using HA4IoT.Actuators.BinaryStateActuators; -using HA4IoT.Actuators.Lamps; -using HA4IoT.Actuators.RollerShutters; -using HA4IoT.Actuators.Sockets; -using HA4IoT.Actuators.StateMachines; -using HA4IoT.Contracts.Actuators; -using HA4IoT.Contracts.Components; -using HA4IoT.Contracts.Configuration; -using HA4IoT.Contracts.Core; -using HA4IoT.Contracts.Hardware; -using HA4IoT.Contracts.Services; -using HA4IoT.Contracts.Services.System; -using HA4IoT.ExternalServices.OpenWeatherMap; -using HA4IoT.Hardware; -using HA4IoT.Sensors.Buttons; -using HA4IoT.Sensors.HumiditySensors; -using HA4IoT.Sensors.MotionDetectors; -using HA4IoT.Sensors.TemperatureSensors; -using HA4IoT.Sensors.Windows; - -namespace HA4IoT.Configuration -{ - public class DefaultConfigurationExtender : ConfigurationExtenderBase - { - public DefaultConfigurationExtender(ConfigurationParser parser, IController controller) : base(parser, controller) - { - if (parser == null) throw new ArgumentNullException(nameof(parser)); - if (controller == null) throw new ArgumentNullException(nameof(controller)); - - Namespace = string.Empty; - } - - public override IDevice ParseDevice(XElement element) - { - switch (element.Name.LocalName) - { - case "I2CBus": return ParseI2CBus(element); - - default: throw new ConfigurationInvalidException("Device not supported.", element); - } - } - - public override IService ParseService(XElement element) - { - switch (element.Name.LocalName) - { - case "OpenWeatherMapService": return ParseWeatherStation(element); - - default: throw new ConfigurationInvalidException("Service not supported.", element); - } - } - - public override IComponent ParseComponent(XElement element) - { - switch (element.Name.LocalName) - { - case "CustomBinaryStateOutputActuator": return ParseCustomBinaryStateOutputActuator(element); - case "Lamp": return ParseLamp(element); - case "Socket": return ParseSocket(element); - case "Button": return ParseButton(element); - case "RollerShutter": return ParseRollerShutter(element); - case "Window": return ParseWindow(element); - case "TemperatureSensor": return ParseTemperatureSensor(element); - case "HumiditySensor": return ParseHumiditySensor(element); - case "StateMachine": return ParseStateMachine(element); - case "MotionDetector": return ParseMotionDetector(element); - - default: throw new ConfigurationInvalidException("Component not supported.", element); - } - } - - private IDevice ParseI2CBus(XElement element) - { - return new BuiltInI2CBus(new DeviceId(element.GetMandatoryStringFromAttribute("id"))); - } - - private IService ParseWeatherStation(XElement element) - { - return new OpenWeatherMapService( - Controller.ServiceLocator.GetService(), - Controller.ServiceLocator.GetService(), - Controller.ServiceLocator.GetService()); - } - - private IComponent ParseCustomBinaryStateOutputActuator(XElement element) - { - IBinaryOutput output = Parser.ParseBinaryOutput(element.GetMandatorySingleChildElementOrFromContainer("Output")); - - return new CustomBinaryStateActuator( - new ComponentId(element.GetMandatoryStringFromAttribute("id")), - new PortBasedBinaryStateEndpoint(output)); - } - - private IComponent ParseMotionDetector(XElement element) - { - IBinaryInput input = Parser.ParseBinaryInput(element.GetMandatorySingleChildElementOrFromContainer("Input")); - - return new MotionDetector( - new ComponentId(element.GetMandatoryStringFromAttribute("id")), - new PortBasedMotionDetectorEndpoint(input), - Controller.ServiceLocator.GetService()); - } - - private IComponent ParseButton(XElement element) - { - IBinaryInput input = Parser.ParseBinaryInput(element.GetMandatorySingleChildElementOrFromContainer("Input")); - - return new Button( - new ComponentId(element.GetMandatoryStringFromAttribute("id")), - new PortBasedButtonEndpoint(input), - Controller.Timer); - } - - private IComponent ParseSocket(XElement element) - { - IBinaryOutput output = Parser.ParseBinaryOutput(element.GetMandatorySingleChildElementOrFromContainer("Output")); - - return new Socket( - new ComponentId(element.GetMandatoryStringFromAttribute("id")), - new PortBasedBinaryStateEndpoint(output)); - } - - private IComponent ParseLamp(XElement element) - { - IBinaryOutput output = Parser.ParseBinaryOutput(element.GetMandatorySingleChildElementOrFromContainer("Output")); - - return new Lamp( - new ComponentId(element.GetMandatoryStringFromAttribute("id")), - new PortBasedBinaryStateEndpoint(output)); - } - - private IComponent ParseRollerShutter(XElement element) - { - IBinaryOutput powerOutput = Parser.ParseBinaryOutput(element.GetMandatorySingleChildFromContainer("Power")); - IBinaryOutput directionOutput = Parser.ParseBinaryOutput(element.GetMandatorySingleChildFromContainer("Direction")); - - return new RollerShutter( - new ComponentId(element.GetMandatoryStringFromAttribute("id")), - new PortBasedRollerShutterEndpoint(powerOutput, directionOutput), - Controller.Timer, - Controller.ServiceLocator.GetService()); - } - - private IComponent ParseWindow(XElement element) - { - var window = new Window( - new ComponentId(element.GetMandatoryStringFromAttribute("id"))); - - var leftCasementElement = element.Element("LeftCasement"); - if (leftCasementElement != null) - { - window.WithCasement(ParseCasement(leftCasementElement, Casement.LeftCasementId)); - } - - var centerCasementElement = element.Element("CenterCasement"); - if (centerCasementElement != null) - { - window.WithCasement(ParseCasement(centerCasementElement, Casement.CenterCasementId)); - } - - var rightCasementElement = element.Element("RightCasement"); - if (rightCasementElement != null) - { - window.WithCasement(ParseCasement(rightCasementElement, Casement.RightCasementId)); - } - - return window; - } - - private Casement ParseCasement(XElement element, string defaultId) - { - IBinaryInput fullOpenInput = Parser.ParseBinaryInput(element.GetMandatorySingleChildFromContainer("FullOpen")); - - IBinaryInput tiltInput = null; - if (element.HasChildElement("Tilt")) - { - tiltInput = Parser.ParseBinaryInput(element.GetMandatorySingleChildFromContainer("Tilt")); - } - - var casement = new Casement(element.GetStringFromAttribute("id", defaultId), fullOpenInput, tiltInput); - return casement; - } - - private IComponent ParseHumiditySensor(XElement element) - { - var sensor = Parser.ParseNumericValueSensor(element.GetMandatorySingleChildElementOrFromContainer("Sensor")); - - return new HumiditySensor( - new ComponentId(element.GetMandatoryStringFromAttribute("id")), - sensor); - } - - private IComponent ParseTemperatureSensor(XElement element) - { - var sensor = Parser.ParseNumericValueSensor(element.GetMandatorySingleChildElementOrFromContainer("Sensor")); - - return new TemperatureSensor( - new ComponentId(element.GetMandatoryStringFromAttribute("id")), - sensor); - } - - private IComponent ParseStateMachine(XElement element) - { - var id = new ComponentId(element.GetMandatoryStringFromAttribute("id")); - - var stateMachine = new StateMachine(id); - - foreach (var stateElement in element.Element("States").Elements("State")) - { - var stateId = stateElement.GetMandatoryStringFromAttribute("id"); - var state = stateMachine.AddState(new NamedComponentState(stateId)); - - foreach (var lowPortElement in stateElement.Element("LowPorts").Elements()) - { - state.WithOutput(Parser.ParseBinaryOutput(lowPortElement), BinaryState.Low); - } - - foreach (var highPortElement in stateElement.Element("LowPorts").Elements()) - { - state.WithOutput(Parser.ParseBinaryOutput(highPortElement), BinaryState.High); - } - - foreach (var actuatorElement in stateElement.Element("Actuators").Elements()) - { - var targetState = actuatorElement.GetMandatoryStringFromAttribute("targetState"); - var actuatorId = new ComponentId(actuatorElement.GetMandatoryStringFromAttribute("id")); - var actuator = Controller.GetComponent(actuatorId); - - state.WithActuator(actuator, new NamedComponentState(targetState)); - } - } - - return stateMachine; - } - } -} diff --git a/SDK/HA4IoT.Configuration/HA4IoT.Configuration.csproj b/SDK/HA4IoT.Configuration/HA4IoT.Configuration.csproj index d10163d9..568f1a4d 100644 --- a/SDK/HA4IoT.Configuration/HA4IoT.Configuration.csproj +++ b/SDK/HA4IoT.Configuration/HA4IoT.Configuration.csproj @@ -107,48 +107,9 @@ - - - - - - - - {6788E4A8-580E-4C2E-9754-95229F24F217} - HA4IoT.ExternalServices.OpenWeatherMap - - - {808ABECF-D9C2-4AB2-95D8-EAF228B44576} - HA4IoT.Actuators - - - {60F9E539-3FF5-40DE-B0C4-BE99CAE57736} - HA4IoT.Components - - - {551337E7-D1EF-4145-92B4-F7086F7665A6} - HA4IoT.Contracts - - - {2BBEF090-4FEE-4FB7-9CF1-F6597F2C53EA} - HA4IoT.Core - - - {287A9BD0-4037-4ADD-986F-54056F059EAE} - HA4IoT.Hardware - - - {D4E0A3F9-6521-4AEE-815A-E2A60323FB63} - HA4IoT.Networking - - - {8892E736-CDD0-48EB-AD9E-A1C8AA230FD7} - HA4IoT.Sensors - - 14.0 diff --git a/SDK/HA4IoT.Configuration/Pi2ConfigurationExtender.cs b/SDK/HA4IoT.Configuration/Pi2ConfigurationExtender.cs deleted file mode 100644 index a1886c2d..00000000 --- a/SDK/HA4IoT.Configuration/Pi2ConfigurationExtender.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace HA4IoT.Configuration -{ - public class Pi2ConfigurationExtender - { - } -} diff --git a/SDK/HA4IoT.Contracts/Api/IApiController.cs b/SDK/HA4IoT.Contracts/Api/IApiService.cs similarity index 90% rename from SDK/HA4IoT.Contracts/Api/IApiController.cs rename to SDK/HA4IoT.Contracts/Api/IApiService.cs index c76a2806..5e8b2c78 100644 --- a/SDK/HA4IoT.Contracts/Api/IApiController.cs +++ b/SDK/HA4IoT.Contracts/Api/IApiService.cs @@ -3,7 +3,7 @@ namespace HA4IoT.Contracts.Api { - public interface IApiController + public interface IApiService { void RegisterEndpoint(IApiDispatcherEndpoint endpoint); diff --git a/SDK/HA4IoT.Core/AreaIdFactory.cs b/SDK/HA4IoT.Contracts/Areas/AreaIdFactory.cs similarity index 77% rename from SDK/HA4IoT.Core/AreaIdFactory.cs rename to SDK/HA4IoT.Contracts/Areas/AreaIdFactory.cs index bf7aa0cd..cee91672 100644 --- a/SDK/HA4IoT.Core/AreaIdFactory.cs +++ b/SDK/HA4IoT.Contracts/Areas/AreaIdFactory.cs @@ -1,7 +1,6 @@ using System; -using HA4IoT.Contracts.Areas; -namespace HA4IoT.Core +namespace HA4IoT.Contracts.Areas { public static class AreaIdFactory { diff --git a/SDK/HA4IoT.Contracts/Areas/IArea.cs b/SDK/HA4IoT.Contracts/Areas/IArea.cs index e3079c65..df689afb 100644 --- a/SDK/HA4IoT.Contracts/Areas/IArea.cs +++ b/SDK/HA4IoT.Contracts/Areas/IArea.cs @@ -1,18 +1,21 @@ using Windows.Data.Json; -using HA4IoT.Contracts.Automations; -using HA4IoT.Contracts.Core; +using HA4IoT.Contracts.Components; using HA4IoT.Contracts.Core.Settings; namespace HA4IoT.Contracts.Areas { - public interface IArea : IAutomationController, IComponentController + public interface IArea { AreaId Id { get; } ISettingsContainer Settings { get; } + + JsonObject ExportConfigurationToJsonObject(); - IController Controller { get; } + void AddComponent(IComponent component); - JsonObject ExportConfigurationToJsonObject(); + TComponent GetComponent() where TComponent : IComponent; + + TComponent GetComponent(ComponentId id) where TComponent : IComponent; } } diff --git a/SDK/HA4IoT.Contracts/Areas/IAreaService.cs b/SDK/HA4IoT.Contracts/Areas/IAreaService.cs new file mode 100644 index 00000000..ca159c17 --- /dev/null +++ b/SDK/HA4IoT.Contracts/Areas/IAreaService.cs @@ -0,0 +1,15 @@ +using System.Collections.Generic; + +namespace HA4IoT.Contracts.Areas +{ + public interface IAreaService + { + IArea CreateArea(AreaId id); + + void AddArea(IArea area); + + IArea GetArea(AreaId id); + + IList GetAreas(); + } +} diff --git a/SDK/HA4IoT.Contracts/Automations/IAutomationController.cs b/SDK/HA4IoT.Contracts/Automations/IAutomationService.cs similarity index 81% rename from SDK/HA4IoT.Contracts/Automations/IAutomationController.cs rename to SDK/HA4IoT.Contracts/Automations/IAutomationService.cs index cfe80913..d077cc62 100644 --- a/SDK/HA4IoT.Contracts/Automations/IAutomationController.cs +++ b/SDK/HA4IoT.Contracts/Automations/IAutomationService.cs @@ -1,8 +1,9 @@ using System.Collections.Generic; +using HA4IoT.Contracts.Services; namespace HA4IoT.Contracts.Automations { - public interface IAutomationController + public interface IAutomationService : IService { void AddAutomation(IAutomation automation); diff --git a/SDK/HA4IoT.Contracts/Core/IActuatorController.cs b/SDK/HA4IoT.Contracts/Components/IComponentService.cs similarity index 70% rename from SDK/HA4IoT.Contracts/Core/IActuatorController.cs rename to SDK/HA4IoT.Contracts/Components/IComponentService.cs index baea3431..851179ed 100644 --- a/SDK/HA4IoT.Contracts/Core/IActuatorController.cs +++ b/SDK/HA4IoT.Contracts/Components/IComponentService.cs @@ -1,9 +1,8 @@ using System.Collections.Generic; -using HA4IoT.Contracts.Components; -namespace HA4IoT.Contracts.Core +namespace HA4IoT.Contracts.Components { - public interface IComponentController + public interface IComponentService { void AddComponent(IComponent component); @@ -15,6 +14,6 @@ public interface IComponentController IList GetComponents(); - bool GetContainsComponent(ComponentId componentId); + bool ContainsComponent(ComponentId componentId); } } diff --git a/SDK/HA4IoT.Contracts/Core/IAreaController.cs b/SDK/HA4IoT.Contracts/Core/IAreaController.cs deleted file mode 100644 index 090db767..00000000 --- a/SDK/HA4IoT.Contracts/Core/IAreaController.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System.Collections.Generic; -using HA4IoT.Contracts.Areas; - -namespace HA4IoT.Contracts.Core -{ - public interface IAreaController - { - void AddArea(IArea room); - - IArea GetArea(AreaId id); - - IList GetAreas(); - } -} diff --git a/SDK/HA4IoT.Contracts/Core/IController.cs b/SDK/HA4IoT.Contracts/Core/IController.cs index 252082e0..a175e67d 100644 --- a/SDK/HA4IoT.Contracts/Core/IController.cs +++ b/SDK/HA4IoT.Contracts/Core/IController.cs @@ -1,14 +1,9 @@ -using HA4IoT.Contracts.Api; -using HA4IoT.Contracts.Automations; -using HA4IoT.Contracts.Core.Settings; +using HA4IoT.Contracts.Core.Settings; namespace HA4IoT.Contracts.Core { - public interface IController : IDeviceController, IComponentController, IAreaController, IAutomationController + public interface IController { - IApiController ApiController { get; } - IHomeAutomationTimer Timer { get; } - ISettingsContainer Settings { get; } - IServiceLocator ServiceLocator { get; } + ISettingsContainer Settings { get; } } } diff --git a/SDK/HA4IoT.Contracts/Core/IHomeAutomationTimer.cs b/SDK/HA4IoT.Contracts/Core/IHomeAutomationTimer.cs deleted file mode 100644 index f9be7439..00000000 --- a/SDK/HA4IoT.Contracts/Core/IHomeAutomationTimer.cs +++ /dev/null @@ -1,9 +0,0 @@ -using System; - -namespace HA4IoT.Contracts.Core -{ - public interface IHomeAutomationTimer - { - event EventHandler Tick; - } -} diff --git a/SDK/HA4IoT.Contracts/Core/IInitializer.cs b/SDK/HA4IoT.Contracts/Core/IInitializer.cs new file mode 100644 index 00000000..c5aeb851 --- /dev/null +++ b/SDK/HA4IoT.Contracts/Core/IInitializer.cs @@ -0,0 +1,12 @@ +using System.Threading.Tasks; +using HA4IoT.Contracts.Services.System; + +namespace HA4IoT.Contracts.Core +{ + public interface IInitializer + { + void RegisterServices(IContainerService containerService); + + Task Initialize(IContainerService containerService); + } +} diff --git a/SDK/HA4IoT.Contracts/Core/IServiceController.cs b/SDK/HA4IoT.Contracts/Core/IServiceController.cs deleted file mode 100644 index e22b6214..00000000 --- a/SDK/HA4IoT.Contracts/Core/IServiceController.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System; -using System.Collections.Generic; -using HA4IoT.Contracts.Services; - -namespace HA4IoT.Contracts.Core -{ - public interface IServiceLocator - { - void RegisterService(Type interfaceType, IService service); - - TService GetService() where TService : IService; - - IList GetServices(); - - bool TryGetService(out TService service) where TService : IService; - } -} diff --git a/SDK/HA4IoT.Contracts/Core/IStartupCompletedNotification.cs b/SDK/HA4IoT.Contracts/Core/IStartupCompletedNotification.cs new file mode 100644 index 00000000..0f4cea4d --- /dev/null +++ b/SDK/HA4IoT.Contracts/Core/IStartupCompletedNotification.cs @@ -0,0 +1,7 @@ +namespace HA4IoT.Contracts.Core +{ + public interface IStartupCompletedNotification + { + void OnStartupCompleted(); + } +} diff --git a/SDK/HA4IoT.Contracts/Core/ServiceAlreadyRegisteredException.cs b/SDK/HA4IoT.Contracts/Core/ServiceAlreadyRegisteredException.cs deleted file mode 100644 index ba2efe2a..00000000 --- a/SDK/HA4IoT.Contracts/Core/ServiceAlreadyRegisteredException.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; - -namespace HA4IoT.Contracts.Core -{ - public class ServiceAlreadyRegisteredException : Exception - { - public ServiceAlreadyRegisteredException(Type serviceType) - : base($"Service '{serviceType.Name}' is already registered.") - { - } - } -} diff --git a/SDK/HA4IoT.Contracts/Core/ServiceLocator.cs b/SDK/HA4IoT.Contracts/Core/ServiceLocator.cs deleted file mode 100644 index 5e67acdc..00000000 --- a/SDK/HA4IoT.Contracts/Core/ServiceLocator.cs +++ /dev/null @@ -1,79 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using HA4IoT.Contracts.Services; - -namespace HA4IoT.Contracts.Core -{ - public class ServiceLocator : IServiceLocator - { - private readonly object _syncRoot = new object(); - private readonly Dictionary _services = new Dictionary(); - - public void RegisterService(Type interfaceType, IService service) - { - if (interfaceType == null) throw new ArgumentNullException(nameof(interfaceType)); - if (service == null) throw new ArgumentNullException(nameof(service)); - - lock (_syncRoot) - { - if (!interfaceType.IsInstanceOfType(service)) - { - throw new InvalidOperationException("The service is not implementing the required interface."); - } - - if (_services.ContainsKey(interfaceType)) - { - throw new ServiceAlreadyRegisteredException(interfaceType); - } - - _services.Add(interfaceType, service); - } - - service.CompleteRegistration(this); - } - - public TService GetService() where TService : IService - { - var interfaceType = typeof(TService); - - lock (_syncRoot) - { - IService serviceBuffer; - if (_services.TryGetValue(interfaceType, out serviceBuffer)) - { - return (TService) serviceBuffer; - } - } - - throw new ServiceNotRegisteredException(typeof(TService)); - } - - public bool TryGetService(out TService service) where TService : IService - { - var interfaceType = typeof(TService); - - lock (_syncRoot) - { - IService serviceBuffer; - if (_services.TryGetValue(interfaceType, out serviceBuffer)) - { - service = (TService) serviceBuffer; - return true; - } - } - - service = default(TService); - return false; - } - - public IList GetServices() - { - lock (_syncRoot) - { - return _services.Select(s => new ServiceRegistration(s.Key, s.Value)).ToList(); - } - } - } -} diff --git a/SDK/HA4IoT.Contracts/Core/ServiceNotRegisteredException.cs b/SDK/HA4IoT.Contracts/Core/ServiceNotRegisteredException.cs deleted file mode 100644 index c51e0c98..00000000 --- a/SDK/HA4IoT.Contracts/Core/ServiceNotRegisteredException.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; - -namespace HA4IoT.Contracts.Core -{ - public class ServiceNotRegisteredException : Exception - { - public ServiceNotRegisteredException(Type serviceType) - : base($"Service '{serviceType.Name}' is not registered.") - { - } - } -} diff --git a/SDK/HA4IoT.Contracts/Core/ServiceRegistration.cs b/SDK/HA4IoT.Contracts/Core/ServiceRegistration.cs deleted file mode 100644 index 30478eef..00000000 --- a/SDK/HA4IoT.Contracts/Core/ServiceRegistration.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System; -using HA4IoT.Contracts.Services; - -namespace HA4IoT.Contracts.Core -{ - public class ServiceRegistration - { - public ServiceRegistration(Type interfaceType, IService serviceInstance) - { - if (interfaceType == null) throw new ArgumentNullException(nameof(interfaceType)); - if (serviceInstance == null) throw new ArgumentNullException(nameof(serviceInstance)); - - InterfaceType = interfaceType; - ServiceInstance = serviceInstance; - } - - public Type InterfaceType { get; } - - public IService ServiceInstance { get; } - } -} diff --git a/SDK/HA4IoT.Contracts/Core/TimedAction.cs b/SDK/HA4IoT.Contracts/Core/TimedAction.cs index 58061399..8cce0e6f 100644 --- a/SDK/HA4IoT.Contracts/Core/TimedAction.cs +++ b/SDK/HA4IoT.Contracts/Core/TimedAction.cs @@ -1,21 +1,22 @@ using System; +using HA4IoT.Contracts.Services.System; namespace HA4IoT.Contracts.Core { public class TimedAction { private readonly TimeSpan _interval; - private readonly IHomeAutomationTimer _timer; + private readonly ITimerService _timerService; private Action _action; private TimeSpan _timeout; - public TimedAction(TimeSpan dueTime, TimeSpan interval, IHomeAutomationTimer timer) + public TimedAction(TimeSpan dueTime, TimeSpan interval, ITimerService timerService) { _timeout = dueTime; _interval = interval; - _timer = timer; - _timer.Tick += CheckForTimeout; + _timerService = timerService; + _timerService.Tick += CheckForTimeout; } public TimedAction Execute(Action action) @@ -62,7 +63,7 @@ public void Cancel() _timeout = TimeSpan.Zero; _action = null; - _timer.Tick -= CheckForTimeout; + _timerService.Tick -= CheckForTimeout; } } } diff --git a/SDK/HA4IoT.Contracts/HA4IoT.Contracts.csproj b/SDK/HA4IoT.Contracts/HA4IoT.Contracts.csproj index f641af1d..6ba78b8a 100644 --- a/SDK/HA4IoT.Contracts/HA4IoT.Contracts.csproj +++ b/SDK/HA4IoT.Contracts/HA4IoT.Contracts.csproj @@ -108,6 +108,7 @@ + @@ -125,10 +126,8 @@ - - - - + + @@ -161,7 +160,7 @@ - + @@ -176,20 +175,20 @@ - + - + - + - - - + + + @@ -218,7 +217,7 @@ - + @@ -239,7 +238,7 @@ - + diff --git a/SDK/HA4IoT.Contracts/Hardware/IBinaryInputController.cs b/SDK/HA4IoT.Contracts/Hardware/IBinaryInputController.cs index 28ca1093..0b8f0afc 100644 --- a/SDK/HA4IoT.Contracts/Hardware/IBinaryInputController.cs +++ b/SDK/HA4IoT.Contracts/Hardware/IBinaryInputController.cs @@ -1,6 +1,6 @@ namespace HA4IoT.Contracts.Hardware { - public interface IBinaryInputController : IDevice + public interface IBinaryInputController { IBinaryInput GetInput(int number); } diff --git a/SDK/HA4IoT.Contracts/Hardware/IBinaryOutputController.cs b/SDK/HA4IoT.Contracts/Hardware/IBinaryOutputController.cs index 5135dace..b1a93677 100644 --- a/SDK/HA4IoT.Contracts/Hardware/IBinaryOutputController.cs +++ b/SDK/HA4IoT.Contracts/Hardware/IBinaryOutputController.cs @@ -1,6 +1,6 @@ namespace HA4IoT.Contracts.Hardware { - public interface IBinaryOutputController : IDevice + public interface IBinaryOutputController { IBinaryOutput GetOutput(int number); } diff --git a/SDK/HA4IoT.Contracts/Services/System/IContainerService.cs b/SDK/HA4IoT.Contracts/Services/System/IContainerService.cs new file mode 100644 index 00000000..2efdbb58 --- /dev/null +++ b/SDK/HA4IoT.Contracts/Services/System/IContainerService.cs @@ -0,0 +1,15 @@ +using System; + +namespace HA4IoT.Contracts.Services.System +{ + public interface IContainerService : IService + { + TService GetInstance() where TService : class; + + void RegisterSingleton() where TConcrete : class; + + void RegisterSingleton() where TService : class + where TImplementation : class, TService; + + void RegisterSingleton(Func instanceCreator) where TService : class; + } diff --git a/SDK/HA4IoT.Contracts/Services/System/DateTimeService.cs b/SDK/HA4IoT.Contracts/Services/System/IDateTimeService.cs similarity index 100% rename from SDK/HA4IoT.Contracts/Services/System/DateTimeService.cs rename to SDK/HA4IoT.Contracts/Services/System/IDateTimeService.cs diff --git a/SDK/HA4IoT.Contracts/Core/IDeviceController.cs b/SDK/HA4IoT.Contracts/Services/System/IDeviceService.cs similarity index 80% rename from SDK/HA4IoT.Contracts/Core/IDeviceController.cs rename to SDK/HA4IoT.Contracts/Services/System/IDeviceService.cs index b68d53ba..d0cd6839 100644 --- a/SDK/HA4IoT.Contracts/Core/IDeviceController.cs +++ b/SDK/HA4IoT.Contracts/Services/System/IDeviceService.cs @@ -1,9 +1,9 @@ using System.Collections.Generic; using HA4IoT.Contracts.Hardware; -namespace HA4IoT.Contracts.Core +namespace HA4IoT.Contracts.Services.System { - public interface IDeviceController + public interface IDeviceService : IService { void AddDevice(IDevice device); diff --git a/SDK/HA4IoT.Contracts/Hardware/II2CBus.cs b/SDK/HA4IoT.Contracts/Services/System/II2CBusService.cs similarity index 84% rename from SDK/HA4IoT.Contracts/Hardware/II2CBus.cs rename to SDK/HA4IoT.Contracts/Services/System/II2CBusService.cs index 8c4fb901..95fa9971 100644 --- a/SDK/HA4IoT.Contracts/Hardware/II2CBus.cs +++ b/SDK/HA4IoT.Contracts/Services/System/II2CBusService.cs @@ -1,8 +1,9 @@ using System; +using HA4IoT.Contracts.Hardware; -namespace HA4IoT.Contracts.Hardware +namespace HA4IoT.Contracts.Services.System { - public interface II2CBus : IDevice + public interface II2CBusService : IService { /// /// Executes the specified action providing the for the device with the specified address. diff --git a/SDK/HA4IoT.Contracts/Services/System/ITimerService.cs b/SDK/HA4IoT.Contracts/Services/System/ITimerService.cs new file mode 100644 index 00000000..bde94bec --- /dev/null +++ b/SDK/HA4IoT.Contracts/Services/System/ITimerService.cs @@ -0,0 +1,12 @@ +using System; +using HA4IoT.Contracts.Core; + +namespace HA4IoT.Contracts.Services.System +{ + public interface ITimerService + { + event EventHandler Tick; + + void Run(); + } +} diff --git a/SDK/HA4IoT.Core/AreaCollection.cs b/SDK/HA4IoT.Core/AreaCollection.cs deleted file mode 100644 index 68e4162b..00000000 --- a/SDK/HA4IoT.Core/AreaCollection.cs +++ /dev/null @@ -1,10 +0,0 @@ -using HA4IoT.Contracts.Configuration; -using HA4IoT.Contracts.Actuators; -using HA4IoT.Contracts.Areas; - -namespace HA4IoT.Core -{ - public class AreaCollection : GenericControllerCollection - { - } -} diff --git a/SDK/HA4IoT.Core/ControllerApiDispatcher.cs b/SDK/HA4IoT.Core/ControllerApiDispatcher.cs index 4ebfa49e..bed87bd2 100644 --- a/SDK/HA4IoT.Core/ControllerApiDispatcher.cs +++ b/SDK/HA4IoT.Core/ControllerApiDispatcher.cs @@ -2,26 +2,46 @@ using Windows.Data.Json; using HA4IoT.Contracts.Api; using HA4IoT.Contracts.Areas; -using HA4IoT.Contracts.Core; +using HA4IoT.Contracts.Automations; +using HA4IoT.Contracts.Components; +using HA4IoT.Contracts.Services.System; +using HA4IoT.Core.Settings; using HA4IoT.Networking; namespace HA4IoT.Core { public class ControllerApiDispatcher { - private readonly IController _controller; - - public ControllerApiDispatcher(IController controller) + private readonly IApiService _apiService; + private readonly IDeviceService _deviceService; + private readonly IComponentService _componentService; + private readonly IAreaService _areaService; + private readonly IAutomationService _automationService; + + public ControllerApiDispatcher( + IApiService apiService, + IDeviceService deviceService, + IComponentService componentService, + IAreaService areaService, + IAutomationService automationService) { - if (controller == null) throw new ArgumentNullException(nameof(controller)); - - _controller = controller; + if (apiService == null) throw new ArgumentNullException(nameof(apiService)); + if (deviceService == null) throw new ArgumentNullException(nameof(deviceService)); + if (componentService == null) throw new ArgumentNullException(nameof(componentService)); + if (areaService == null) throw new ArgumentNullException(nameof(areaService)); + if (automationService == null) throw new ArgumentNullException(nameof(automationService)); + + _apiService = apiService; + _deviceService = deviceService; + _componentService = componentService; + _areaService = areaService; + _automationService = automationService; } public void ExposeToApi() { - _controller.ApiController.RouteRequest("configuration", HandleApiGetConfiguration); - _controller.ApiController.RouteRequest("status", HandleApiGetStatus); + _apiService.RouteRequest("configuration", HandleApiGetConfiguration); + _apiService.RouteRequest("status", HandleApiGetStatus); ExposeServicesToApi(); } @@ -30,8 +50,32 @@ private void ExposeServicesToApi() { foreach (var service in _controller.ServiceLocator.GetServices()) { - _controller.ApiController.RouteRequest($"service/{service.InterfaceType.Name}", service.ServiceInstance.HandleApiRequest); - _controller.ApiController.RouteCommand($"service/{service.InterfaceType.Name}", service.ServiceInstance.HandleApiCommand); + _apiService.RouteRequest($"service/{service.InterfaceType.Name}", service.ServiceInstance.HandleApiRequest); + _apiService.RouteCommand($"service/{service.InterfaceType.Name}", service.ServiceInstance.HandleApiCommand); + } + + foreach (var device in _deviceService.GetDevices()) + { + _apiService.RouteRequest($"device/{device.Id}", device.HandleApiRequest); + _apiService.RouteCommand($"device/{device.Id}", device.HandleApiCommand); + } + + foreach (var area in _areaService.GetAreas()) + { + new SettingsContainerApiDispatcher(area.Settings, $"area/{area.Id}", _apiService).ExposeToApi(); + } + + foreach (var component in _componentService.GetComponents()) + { + new SettingsContainerApiDispatcher(component.Settings, $"component/{component.Id}", _apiService).ExposeToApi(); + _apiService.RouteCommand($"component/{component.Id}/status", component.HandleApiCommand); + _apiService.RouteRequest($"component/{component.Id}/status", component.HandleApiRequest); + component.StateChanged += (s, e) => _apiService.NotifyStateChanged(component); + } + + foreach (var automation in _automationService.GetAutomations()) + { + new SettingsContainerApiDispatcher(automation.Settings, $"automation/{automation.Id}", _apiService).ExposeToApi(); } } @@ -50,7 +94,7 @@ private void HandleApiGetStatus(IApiContext apiContext) result.SetNamedValue("services", services); var components = new JsonObject(); - foreach (var component in _controller.GetComponents()) + foreach (var component in _componentService.GetComponents()) { components.SetNamedValue(component.Id.Value, component.ExportStatusToJsonObject()); } @@ -58,7 +102,7 @@ private void HandleApiGetStatus(IApiContext apiContext) result.SetNamedValue("components", components); var automations = new JsonObject(); - foreach (var automation in _controller.GetAutomations()) + foreach (var automation in _automationService.GetAutomations()) { automations.SetNamedValue(automation.Id.Value, automation.ExportStatusToJsonObject()); } @@ -75,7 +119,7 @@ private void HandleApiGetConfiguration(IApiContext apiContext) configuration.SetNamedNumber("version", 1D); var areas = new JsonObject(); - foreach (var area in _controller.GetAreas()) + foreach (var area in _areaService.GetAreas()) { areas.SetNamedValue(area.Id.Value, ExportAreaConfigurationToJsonValue(area)); } diff --git a/SDK/HA4IoT.Core/ControllerBase.cs b/SDK/HA4IoT.Core/ControllerBase.cs index 37b09260..df69d78a 100644 --- a/SDK/HA4IoT.Core/ControllerBase.cs +++ b/SDK/HA4IoT.Core/ControllerBase.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; @@ -14,43 +13,62 @@ using HA4IoT.Contracts.Components; using HA4IoT.Contracts.Core; using HA4IoT.Contracts.Core.Settings; -using HA4IoT.Contracts.Hardware; using HA4IoT.Contracts.Logging; using HA4IoT.Contracts.Services; using HA4IoT.Contracts.Services.System; -using HA4IoT.Core.Discovery; -using HA4IoT.Core.Scheduling; -using HA4IoT.Core.Settings; -using HA4IoT.Core.Timer; +using HA4IoT.Hardware; +using HA4IoT.Hardware.CCTools; using HA4IoT.Hardware.Pi2; using HA4IoT.Logger; using HA4IoT.Networking; +using HA4IoT.PersonalAgent; +using HA4IoT.Services.Areas; +using HA4IoT.Services.Automations; +using HA4IoT.Services.Components; +using HA4IoT.Services.Devices; +using HA4IoT.Services.Health; +using HA4IoT.Services.Scheduling; +using HA4IoT.Services.System; using HA4IoT.Telemetry; +using SimpleInjector; namespace HA4IoT.Core { public class ControllerBase : IController { - private readonly DeviceCollection _devices = new DeviceCollection(); - private readonly AreaCollection _areas = new AreaCollection(); - private readonly ComponentCollection _components = new ComponentCollection(); - private readonly AutomationCollection _automations = new AutomationCollection(); - private readonly SystemInformationService _systemInformationService = new SystemInformationService(); - private readonly int? _statusLedNumber; + private readonly Container _container = new Container(); private BackgroundTaskDeferral _deferral; private HttpServer _httpServer; - public IApiController ApiController { get; } = new ApiController("api"); - public IServiceLocator ServiceLocator { get; } = new ServiceLocator(); - public IHomeAutomationTimer Timer { get; protected set; } public ISettingsContainer Settings { get; private set; } + public IInitializer Initializer { get; set; } + protected ControllerBase(int? statusLedNumber) { - _statusLedNumber = statusLedNumber; - } + _container.RegisterSingleton(() => new HealthServiceOptions {StatusLed = statusLedNumber}); + _container.RegisterSingleton(); + + _container.RegisterSingleton(); + _container.RegisterSingleton(); + _container.RegisterSingleton(); + + _container.RegisterSingleton(() => new ContainerService(_container)); + _container.RegisterSingleton(); + _container.RegisterSingleton(); + _container.RegisterSingleton(); + _container.RegisterSingleton(); + _container.RegisterSingleton(); + _container.RegisterSingleton(); + _container.RegisterSingleton(); + _container.RegisterSingleton(); + + _container.RegisterSingleton(); + _container.RegisterSingleton(); + } + public Task RunAsync(IBackgroundTaskInstance taskInstance) { if (taskInstance == null) throw new ArgumentNullException(nameof(taskInstance)); @@ -72,121 +90,17 @@ public Task RunAsync() return task; } - public void AddArea(IArea area) - { - _areas.AddUnique(area.Id, area); - } - - public IArea GetArea(AreaId id) - { - return _areas.Get(id); - } - - public IList GetAreas() - { - return _areas.GetAll(); - } - - public void AddComponent(IComponent component) - { - if (component == null) throw new ArgumentNullException(nameof(component)); - - _components.AddUnique(component.Id, component); - } - - public TComponent GetComponent() where TComponent : IComponent - { - return _components.Get(); - } - - public IList GetComponents() where TComponent : IComponent - { - return _components.GetAll(); - } - - public IList GetComponents() - { - return _components.GetAll(); - } - - public bool GetContainsComponent(ComponentId componentId) - { - return _components.Contains(componentId); - } - - public TComponent GetComponent(ComponentId id) where TComponent : IComponent - { - return _components.Get(id); - } - - public void AddDevice(IDevice device) - { - _devices.AddUnique(device.Id, device); - } - - public TDevice GetDevice(DeviceId id) where TDevice : IDevice - { - return _devices.Get(id); - } - - public TDevice GetDevice() where TDevice : IDevice - { - return _devices.Get(); - } - - public IList GetDevices() where TDevice : IDevice - { - return _devices.GetAll(); - } - - public IList GetDevices() - { - return _devices.GetAll(); - } - - public void AddAutomation(IAutomation automation) - { - _automations.AddOrUpdate(automation.Id, automation); - } - - public IList GetAutomations() where TAutomation : IAutomation - { - return _automations.GetAll(); - } - - public TAutomation GetAutomation(AutomationId id) where TAutomation : IAutomation - { - return _automations.Get(id); - } - - public IList GetAutomations() - { - return _automations.GetAll(); - } - - protected virtual async Task ConfigureAsync() + protected virtual async Task ConfigureAsync(IContainerService factoryService) { await Task.FromResult(0); } - - private void InitializeHealthMonitor() - { - IBinaryOutput ledPin = null; - if (_statusLedNumber.HasValue) - { - var pi2PortController = new Pi2PortController(); - ledPin = pi2PortController.GetOutput(_statusLedNumber.Value); - } - - ServiceLocator.RegisterService(typeof(HealthService), new HealthService(ledPin, Timer, ServiceLocator.GetService())); - } - + private void InitializeHttpApiEndpoint() { _httpServer = new HttpServer(); var httpApiDispatcherEndpoint = new LocalHttpServerApiDispatcherEndpoint(_httpServer); - ApiController.RegisterEndpoint(httpApiDispatcherEndpoint); + _container.GetInstance().RegisterEndpoint(httpApiDispatcherEndpoint); var httpRequestDispatcher = new HttpRequestDispatcher(_httpServer); @@ -194,34 +108,29 @@ private void InitializeHttpApiEndpoint() httpRequestDispatcher.MapFolder("Storage", StoragePath.Root); } - protected void InitializeAzureCloudApiEndpoint() + private bool TryInitializeAzureCloudApiEndpoint() { var azureCloudApiDispatcherEndpoint = new AzureCloudApiDispatcherEndpoint(); if (azureCloudApiDispatcherEndpoint.TryInitializeFromConfigurationFile( StoragePath.WithFilename("AzureCloudApiDispatcherEndpointSettings.json"))) { - ApiController.RegisterEndpoint(azureCloudApiDispatcherEndpoint); - } - } + _container.GetInstance().RegisterEndpoint(azureCloudApiDispatcherEndpoint); - private HomeAutomationTimer InitializeTimer() - { - var timer = new HomeAutomationTimer(); - Timer = timer; - ServiceLocator.RegisterService(typeof(ISchedulerService), new SchedulerService(Timer)); + return true; + } - return timer; + return false; } - private void InitializeLogging() + private void InitializeLogger() { if (Log.Instance == null) { var udpLogger = new UdpLogger(); udpLogger.Start(); - udpLogger.ExposeToApi(ApiController); + udpLogger.ExposeToApi(_container.GetInstance()); Log.Instance = udpLogger; } @@ -235,21 +144,14 @@ private void InitializeCore() { var stopwatch = Stopwatch.StartNew(); - ServiceLocator.RegisterService(typeof(IDateTimeService), new DateTimeService()); - ServiceLocator.RegisterService(typeof(ISystemInformationService), _systemInformationService); - - InitializeLogging(); + InitializeLogger(); InitializeHttpApiEndpoint(); LoadControllerSettings(); InitializeDiscovery(); - - var timer = InitializeTimer(); - InitializeHealthMonitor(); - + TryConfigure(); - CreateConfigurationStatistics(); - + LoadNonControllerSettings(); ResetActuatorStates(); @@ -259,13 +161,17 @@ private void InitializeCore() AttachComponentHistoryTracking(); + foreach (var service in _container.GetAllInstances()) + { + service.OnStartupCompleted(); + } + stopwatch.Stop(); Log.Info("Startup completed after " + stopwatch.Elapsed); - _systemInformationService.Set("Health/StartupDuration", stopwatch.Elapsed); - _systemInformationService.Set("Health/StartupTimestamp", DateTime.Now); - - timer.Run(); + _container.GetInstance().Set("Health/StartupDuration", stopwatch.Elapsed); + _container.GetInstance().Set("Health/StartupTimestamp", DateTime.Now); + _container.GetInstance().Run(); } catch (Exception exception) { @@ -286,9 +192,10 @@ private void StartHttpServer() } } + // TODO: To OnStartupCompleted private void ResetActuatorStates() { - foreach (var actuator in GetComponents()) + foreach (var actuator in _container.GetInstance().GetComponents()) { try { @@ -324,7 +231,10 @@ private void TryConfigure() try { Log.Info("Starting configuration"); - ConfigureAsync().Wait(); + Initializer?.RegisterServices(); + Initializer?.Initialize(); + + ConfigureAsync(_container.GetInstance()).Wait(); } catch (Exception exception) { @@ -334,17 +244,17 @@ private void TryConfigure() private void LoadNonControllerSettings() { - foreach (var area in _areas.GetAll()) + foreach (var area in _container.GetInstance().GetAreas()) { area.Settings.Load(); } - foreach (var component in _components.GetAll()) + foreach (var component in _container.GetInstance().GetComponents()) { component.Settings.Load(); } - foreach (var automation in _automations.GetAll()) + foreach (var automation in _container.GetInstance().GetAutomations()) { automation.Settings.Load(); } @@ -352,50 +262,30 @@ private void LoadNonControllerSettings() private void ExposeToApi() { - new ControllerApiDispatcher(this).ExposeToApi(); - - foreach (var device in GetDevices()) - { - ApiController.RouteRequest($"device/{device.Id}", device.HandleApiRequest); - ApiController.RouteCommand($"device/{device.Id}", device.HandleApiCommand); - } - - foreach (var area in _areas.GetAll()) - { - new SettingsContainerApiDispatcher(area.Settings, $"area/{area.Id}", ApiController).ExposeToApi(); - } - - foreach (var component in _components.GetAll()) - { - new SettingsContainerApiDispatcher(component.Settings, $"component/{component.Id}", ApiController).ExposeToApi(); - ApiController.RouteCommand($"component/{component.Id}/status", component.HandleApiCommand); - ApiController.RouteRequest($"component/{component.Id}/status", component.HandleApiRequest); - component.StateChanged += (s, e) => ApiController.NotifyStateChanged(component); - } + _container.GetInstance().ExposeToApi(); - foreach (var automation in _automations.GetAll()) - { - new SettingsContainerApiDispatcher(automation.Settings, $"automation/{automation.Id}", ApiController).ExposeToApi(); - } + TryInitializeAzureCloudApiEndpoint(); } private void AttachComponentHistoryTracking() { - foreach (var component in GetComponents()) + foreach (var component in _container.GetInstance().GetComponents()) { var history = new ComponentStateHistoryTracker(component); - history.ExposeToApi(ApiController); + history.ExposeToApi(_container.GetInstance()); } } - private void CreateConfigurationStatistics() - { - var systemInformationService = ServiceLocator.GetService(); - systemInformationService.Set("Components/Count", _components.GetAll().Count); - systemInformationService.Set("Areas/Count", _areas.GetAll().Count); - systemInformationService.Set("Automations/Count", _automations.GetAll().Count); + // TODO: Migrate! - systemInformationService.Set("Services/Count", ServiceLocator.GetServices().Count); - } + ////private void CreateConfigurationStatistics() + ////{ + //// var systemInformationService = ServiceLocator.GetService(); + //// systemInformationService.Set("Components/Count", _components.GetAll().Count); + //// systemInformationService.Set("Areas/Count", _areas.GetAll().Count); + //// systemInformationService.Set("Automations/Count", _automations.GetAll().Count); + + //// systemInformationService.Set("Services/Count", ServiceLocator.GetServices().Count); + ////} } } diff --git a/SDK/HA4IoT.Core/ControllerExtensions.cs b/SDK/HA4IoT.Core/ControllerExtensions.cs deleted file mode 100644 index 5c15835f..00000000 --- a/SDK/HA4IoT.Core/ControllerExtensions.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System; -using HA4IoT.Contracts.Areas; -using HA4IoT.Contracts.Core; - -namespace HA4IoT.Core -{ - public static class ControllerExtensions - { - public static IArea CreateArea(this IController controller, Enum id) - { - if (controller == null) throw new ArgumentNullException(nameof(controller)); - - var area = new Area(AreaIdFactory.Create(id), controller); - controller.AddArea(area); - - return area; - } - - public static IArea GetArea(this IController controller, Enum id) - { - if (controller == null) throw new ArgumentNullException(nameof(controller)); - - return controller.GetArea(AreaIdFactory.Create(id)); - } - } -} diff --git a/SDK/HA4IoT.Core/Discovery/DiscoveryServer.cs b/SDK/HA4IoT.Core/DiscoveryServer.cs similarity index 98% rename from SDK/HA4IoT.Core/Discovery/DiscoveryServer.cs rename to SDK/HA4IoT.Core/DiscoveryServer.cs index a3b6f4d3..f4b31c7f 100644 --- a/SDK/HA4IoT.Core/Discovery/DiscoveryServer.cs +++ b/SDK/HA4IoT.Core/DiscoveryServer.cs @@ -8,7 +8,7 @@ using HA4IoT.Contracts.Core.Discovery; using HA4IoT.Networking; -namespace HA4IoT.Core.Discovery +namespace HA4IoT.Core { public sealed class DiscoveryServer : IDisposable { diff --git a/SDK/HA4IoT.Core/HA4IoT.Core.csproj b/SDK/HA4IoT.Core/HA4IoT.Core.csproj index c7dd10e1..26507263 100644 --- a/SDK/HA4IoT.Core/HA4IoT.Core.csproj +++ b/SDK/HA4IoT.Core/HA4IoT.Core.csproj @@ -114,27 +114,9 @@ - - - - - - - - - - - - - - - - - - - + @@ -163,15 +145,32 @@ {D4E0A3F9-6521-4AEE-815A-E2A60323FB63} HA4IoT.Networking + + {A22FDA3A-B331-4399-863B-5F1B8D24BFE9} + HA4IoT.PersonalAgent + + + {6FD41DDA-4369-43C1-807A-B1BC43ECBDBF} + HA4IoT.Services + {97F3345C-33B6-4779-9212-5FFBCEEF3F96} HA4IoT.Telemetry + + {b0a7ef01-9382-422c-81af-c90dc5a7affd} + HA4IoT.Hardware.CCTools + {39819B8F-40F8-418A-AD3A-92A8C8D63268} HA4IoT.Hardware.Pi2 + + {287A9BD0-4037-4ADD-986F-54056F059EAE} + HA4IoT.Hardware + + 14.0 diff --git a/SDK/HA4IoT.Core/project.json b/SDK/HA4IoT.Core/project.json index c5949392..22d7ea45 100644 --- a/SDK/HA4IoT.Core/project.json +++ b/SDK/HA4IoT.Core/project.json @@ -1,6 +1,7 @@ { "dependencies": { - "Microsoft.NETCore.UniversalWindowsPlatform": "5.0.0" + "Microsoft.NETCore.UniversalWindowsPlatform": "5.0.0", + "SimpleInjector": "3.2.0" }, "frameworks": { "uap10.0": {} diff --git a/SDK/HA4IoT.Logger/UdpLogger.cs b/SDK/HA4IoT.Logger/UdpLogger.cs index 280c8706..19ab0af1 100644 --- a/SDK/HA4IoT.Logger/UdpLogger.cs +++ b/SDK/HA4IoT.Logger/UdpLogger.cs @@ -45,7 +45,7 @@ public void Start() _timer.Change(0, Timeout.Infinite); } - public void ExposeToApi(IApiController apiController) + public void ExposeToApi(IApiService apiController) { if (apiController == null) throw new ArgumentNullException(nameof(apiController)); diff --git a/SDK/HA4IoT.PersonalAgent/HA4IoT.PersonalAgent.csproj b/SDK/HA4IoT.PersonalAgent/HA4IoT.PersonalAgent.csproj index c0245c5a..f0b410f8 100644 --- a/SDK/HA4IoT.PersonalAgent/HA4IoT.PersonalAgent.csproj +++ b/SDK/HA4IoT.PersonalAgent/HA4IoT.PersonalAgent.csproj @@ -126,10 +126,6 @@ {E1EDAC4B-83B9-46F4-9F6A-3BAE97D79F29} HA4IoT.Contracts - - {2BBEF090-4FEE-4FB7-9CF1-F6597F2C53EA} - HA4IoT.Core - {D4E0A3F9-6521-4AEE-815A-E2A60323FB63} HA4IoT.Networking diff --git a/SDK/HA4IoT.PersonalAgent/MessageContextFactory.cs b/SDK/HA4IoT.PersonalAgent/MessageContextFactory.cs index c6b07451..964b55fa 100644 --- a/SDK/HA4IoT.PersonalAgent/MessageContextFactory.cs +++ b/SDK/HA4IoT.PersonalAgent/MessageContextFactory.cs @@ -2,7 +2,6 @@ using System.Linq; using HA4IoT.Contracts.Areas; using HA4IoT.Contracts.Components; -using HA4IoT.Contracts.Core; using HA4IoT.Contracts.PersonalAgent; namespace HA4IoT.PersonalAgent @@ -12,17 +11,17 @@ public class MessageContextFactory private static readonly char[] WordSeparator = { ' ' }; private readonly SynonymService _synonymService; - private readonly IController _controller; + private readonly IAreaService _areaService; private MessageContext _currentContext; - public MessageContextFactory(SynonymService synonymService, IController controller) + public MessageContextFactory(SynonymService synonymService, IAreaService areaService) { if (synonymService == null) throw new ArgumentNullException(nameof(synonymService)); - if (controller == null) throw new ArgumentNullException(nameof(controller)); + if (areaService == null) throw new ArgumentNullException(nameof(areaService)); _synonymService = synonymService; - _controller = controller; + _areaService = areaService; } public MessageContext Create(IInboundMessage message) @@ -105,9 +104,9 @@ private void FilterComponentIds() { foreach (var areaId in _currentContext.IdentifiedAreaIds) { - var area = _controller.GetArea(areaId); + var area = _areaService.GetArea(areaId); - if (area.GetContainsComponent(componentId)) + if (area.ContainsComponent(componentId)) { _currentContext.FilteredComponentIds.Add(componentId); break; diff --git a/SDK/HA4IoT.PersonalAgent/PersonalAgentMessageProcessor.cs b/SDK/HA4IoT.PersonalAgent/PersonalAgentMessageProcessor.cs index 633c4569..188b5697 100644 --- a/SDK/HA4IoT.PersonalAgent/PersonalAgentMessageProcessor.cs +++ b/SDK/HA4IoT.PersonalAgent/PersonalAgentMessageProcessor.cs @@ -4,12 +4,11 @@ using System.Text; using HA4IoT.Contracts.Actuators; using HA4IoT.Contracts.Components; -using HA4IoT.Contracts.Core; using HA4IoT.Contracts.PersonalAgent; using HA4IoT.Contracts.Sensors; using HA4IoT.Components; +using HA4IoT.Contracts.Areas; using HA4IoT.Contracts.Logging; -using HA4IoT.Contracts.Services; using HA4IoT.Contracts.Services.OutdoorHumidity; using HA4IoT.Contracts.Services.OutdoorTemperature; using HA4IoT.Contracts.Services.Weather; @@ -18,15 +17,35 @@ namespace HA4IoT.PersonalAgent { public class PersonalAgentMessageProcessor { - private readonly IController _controller; - + private readonly SynonymService _synonymService; + private readonly IComponentService _componentService; + private readonly IAreaService _areaService; + private readonly IWeatherService _weatherService; + private readonly IOutdoorTemperatureService _outdoorTemperatureService; + private readonly IOutdoorHumidityService _outdoorHumidityService; + private MessageContext _messageContext; - public PersonalAgentMessageProcessor(IController controller) + public PersonalAgentMessageProcessor( + SynonymService synonymService, + IComponentService componentService, + IAreaService areaService, + IWeatherService weatherService, + IOutdoorTemperatureService outdoorTemperatureService, + IOutdoorHumidityService outdoorHumidityService) { - if (controller == null) throw new ArgumentNullException(nameof(controller)); - - _controller = controller; + if (componentService == null) throw new ArgumentNullException(nameof(componentService)); + if (areaService == null) throw new ArgumentNullException(nameof(areaService)); + if (weatherService == null) throw new ArgumentNullException(nameof(weatherService)); + if (outdoorTemperatureService == null) throw new ArgumentNullException(nameof(outdoorTemperatureService)); + if (outdoorHumidityService == null) throw new ArgumentNullException(nameof(outdoorHumidityService)); + + _synonymService = synonymService; + _componentService = componentService; + _areaService = areaService; + _weatherService = weatherService; + _outdoorTemperatureService = outdoorTemperatureService; + _outdoorHumidityService = outdoorHumidityService; } public string Answer { get; private set; } @@ -35,8 +54,7 @@ public void ProcessMessage(IInboundMessage message) { if (message == null) throw new ArgumentNullException(nameof(message)); - var synonymService = _controller.ServiceLocator.GetService(); - var messageContextFactory = new MessageContextFactory(synonymService, _controller); + var messageContextFactory = new MessageContextFactory(_synonymService, _areaService); _messageContext = messageContextFactory.Create(message); try @@ -138,7 +156,7 @@ private string ProcessMessage() if (_messageContext.FilteredComponentIds.Count == 1) { - var component = _controller.GetComponent(_messageContext.IdentifiedComponentIds.First()); + var component = _componentService.GetComponent(_messageContext.IdentifiedComponentIds.First()); IActuator actuator = component as IActuator; if (actuator != null) @@ -179,22 +197,18 @@ private string UpdateActuatorState(IActuator actuator) private string GetWeatherStatus() { - var weatherService = _controller.ServiceLocator.GetService(); - var outdoorTemperatureService = _controller.ServiceLocator.GetService(); - var outdoorHumidityService = _controller.ServiceLocator.GetService(); - var response = new StringBuilder(); response.AppendLine($"{Emoji.BarChart} Das Wetter ist aktuell:"); - response.AppendLine($"Temperatur: {outdoorTemperatureService.OutdoorTemperature}°C"); - response.AppendLine($"Luftfeuchtigkeit: {outdoorHumidityService.OutdoorHumidity}%"); - response.AppendLine($"Situation: {weatherService.Weather}"); + response.AppendLine($"Temperatur: {_outdoorTemperatureService.OutdoorTemperature}°C"); + response.AppendLine($"Luftfeuchtigkeit: {_outdoorHumidityService.OutdoorHumidity}%"); + response.AppendLine($"Wetter: {_weatherService.Weather}"); return response.ToString(); } private string GetWindowStatus() { - var allWindows = _controller.GetComponents(); + var allWindows = _componentService.GetComponents(); List openWindows = allWindows.Where(w => w.Casements.Any(c => !c.GetState().Equals(CasementStateId.Closed))).ToList(); string response; diff --git a/SDK/HA4IoT.PersonalAgent/PersonalAgentToApiDispatcher.cs b/SDK/HA4IoT.PersonalAgent/PersonalAgentToApiDispatcher.cs index 4de71bf5..2a03381d 100644 --- a/SDK/HA4IoT.PersonalAgent/PersonalAgentToApiDispatcher.cs +++ b/SDK/HA4IoT.PersonalAgent/PersonalAgentToApiDispatcher.cs @@ -1,22 +1,22 @@ using System; using HA4IoT.Contracts.Api; -using HA4IoT.Contracts.Core; +using HA4IoT.Contracts.Services.System; using HA4IoT.Networking; namespace HA4IoT.PersonalAgent { public class PersonalAgentToApiDispatcher { - private readonly IController _controller; - - public PersonalAgentToApiDispatcher(IController controller) + private readonly IContainerService _factoryService; + + public PersonalAgentToApiDispatcher(IContainerService factoryService) { - if (controller == null) throw new ArgumentNullException(nameof(controller)); + if (_factoryService == null) throw new ArgumentNullException(nameof(factoryService)); - _controller = controller; + _factoryService = factoryService; } - public void ExposeToApi(IApiController apiController) + public void ExposeToApi(IApiService apiController) { if (apiController == null) throw new ArgumentNullException(nameof(apiController)); @@ -32,7 +32,7 @@ private void HandleCommand(IApiContext apiContext) return; } - var messageProcessor = new PersonalAgentMessageProcessor(_controller); + var messageProcessor = _factoryService.GetInstance(); messageProcessor.ProcessMessage(new ApiInboundMessage(DateTime.Now, message)); apiContext.Response.SetNamedString("answer", messageProcessor.Answer); diff --git a/SDK/HA4IoT.PersonalAgent/SynonymService.cs b/SDK/HA4IoT.PersonalAgent/SynonymService.cs index 2f79186f..8cef906a 100644 --- a/SDK/HA4IoT.PersonalAgent/SynonymService.cs +++ b/SDK/HA4IoT.PersonalAgent/SynonymService.cs @@ -5,24 +5,26 @@ using HA4IoT.Contracts.Api; using HA4IoT.Contracts.Areas; using HA4IoT.Contracts.Components; -using HA4IoT.Contracts.Core; using HA4IoT.Contracts.Logging; using HA4IoT.Contracts.Sensors; -using HA4IoT.Contracts.Services; -using HA4IoT.Core; using HA4IoT.Networking; +using ServiceBase = HA4IoT.Contracts.Services.ServiceBase; namespace HA4IoT.PersonalAgent { public class SynonymService : ServiceBase { + private readonly IComponentService _componentService; private readonly Dictionary> _areaSynonyms = new Dictionary>(); private readonly Dictionary> _componentSynonyms = new Dictionary>(); private readonly Dictionary> _componentStateSynonyms = new Dictionary>(); private readonly SynonymServiceStorage _storage; - public SynonymService() + public SynonymService(IComponentService componentService) { + if (componentService == null) throw new ArgumentNullException(nameof(componentService)); + + _componentService = componentService; _storage = new SynonymServiceStorage(); } @@ -130,27 +132,25 @@ public override void HandleApiRequest(IApiContext apiContext) _storage.ConvertComponentStateSynonymsToJsonArray(_componentStateSynonyms)); } - public void RegisterDefaultComponentStateSynonyms(IController controller) + public void RegisterDefaultComponentStateSynonyms() { - if (controller == null) throw new ArgumentNullException(nameof(controller)); - AddSynonymsForComponentState(BinaryStateId.Off, "aus", "ausschalten", "ab", "abschalten", "stop", "stoppe", "halt", "anhalten", "off"); AddSynonymsForComponentState(BinaryStateId.On, "an", "anschalten", "ein", "einschalten", "on"); AddSynonymsForComponentState(RollerShutterStateId.MovingUp, "rauf", "herauf", "hoch", "oben", "öffne", "öffnen", "up"); AddSynonymsForComponentState(RollerShutterStateId.MovingDown, "runter", "herunter", "unten", "schließe", "schließen", "down"); - foreach (var temperatureSensor in controller.GetComponents()) + foreach (var temperatureSensor in _componentService.GetComponents()) { AddSynonymsForComponent(temperatureSensor.Id, "Temperatur", "warm", "kalt", "temperature"); } - foreach (var humiditySensor in controller.GetComponents()) + foreach (var humiditySensor in _componentService.GetComponents()) { AddSynonymsForComponent(humiditySensor.Id, "feucht", "Feuchtigkeit", "trocken", "humidity"); } - foreach (var rollerShutter in controller.GetComponents()) + foreach (var rollerShutter in _componentService.GetComponents()) { AddSynonymsForComponent(rollerShutter.Id, "Rollo", "Rollade", "trocken"); } diff --git a/SDK/HA4IoT.PersonalAgent/SynonymServiceStorage.cs b/SDK/HA4IoT.PersonalAgent/SynonymServiceStorage.cs index 4360d23c..8b6b59c2 100644 --- a/SDK/HA4IoT.PersonalAgent/SynonymServiceStorage.cs +++ b/SDK/HA4IoT.PersonalAgent/SynonymServiceStorage.cs @@ -101,13 +101,13 @@ public void LoadAreaSynonymsTo(Dictionary> target) return; } - string fileContent = File.ReadAllText(_areaSynonymsFilename); - JsonObject _source = JsonObject.Parse(fileContent); + var fileContent = File.ReadAllText(_areaSynonymsFilename); + var source = JsonObject.Parse(fileContent); - foreach (var key in _source.Keys) + foreach (var key in source.Keys) { var areaId = new AreaId(key); - HashSet synonyms = ConvertJsonArrayToSynonyms(_source.GetNamedArray(key)); + HashSet synonyms = ConvertJsonArrayToSynonyms(source.GetNamedArray(key)); target[areaId] = synonyms; } @@ -122,13 +122,13 @@ public void LoadComponentSynonymsTo(Dictionary> tar return; } - string fileContent = File.ReadAllText(_componentSynonymsFilename); - JsonObject _source = JsonObject.Parse(fileContent); + var fileContent = File.ReadAllText(_componentSynonymsFilename); + var source = JsonObject.Parse(fileContent); - foreach (var key in _source.Keys) + foreach (var key in source.Keys) { var componentId = new ComponentId(key); - HashSet synonyms = ConvertJsonArrayToSynonyms(_source.GetNamedArray(key)); + HashSet synonyms = ConvertJsonArrayToSynonyms(source.GetNamedArray(key)); target[componentId] = synonyms; } diff --git a/SDK/HA4IoT.Sensors/Buttons/Button.cs b/SDK/HA4IoT.Sensors/Buttons/Button.cs index 8c8ffbe5..eedc3f6e 100644 --- a/SDK/HA4IoT.Sensors/Buttons/Button.cs +++ b/SDK/HA4IoT.Sensors/Buttons/Button.cs @@ -8,6 +8,7 @@ using HA4IoT.Contracts.Core; using HA4IoT.Contracts.Logging; using HA4IoT.Contracts.Sensors; +using HA4IoT.Contracts.Services.System; using HA4IoT.Contracts.Triggers; namespace HA4IoT.Sensors.Buttons @@ -19,7 +20,7 @@ public class Button : SensorBase, IButton private readonly Trigger _pressedLongTrigger = new Trigger(); private readonly ButtonSettingsWrapper _settings; - public Button(ComponentId id, IButtonEndpoint endpoint, IHomeAutomationTimer timer) + public Button(ComponentId id, IButtonEndpoint endpoint, ITimerService timerService) : base(id) { if (id == null) throw new ArgumentNullException(nameof(id)); @@ -29,7 +30,7 @@ public Button(ComponentId id, IButtonEndpoint endpoint, IHomeAutomationTimer tim SetState(ButtonStateId.Released); - timer.Tick += CheckForTimeout; + timerService.Tick += CheckForTimeout; endpoint.Pressed += (s, e) => HandleInputStateChanged(ButtonStateId.Pressed); endpoint.Released += (s, e) => HandleInputStateChanged(ButtonStateId.Released); } diff --git a/SDK/HA4IoT.Sensors/Buttons/ButtonExtensions.cs b/SDK/HA4IoT.Sensors/Buttons/ButtonExtensions.cs index 4b982971..9d945ed3 100644 --- a/SDK/HA4IoT.Sensors/Buttons/ButtonExtensions.cs +++ b/SDK/HA4IoT.Sensors/Buttons/ButtonExtensions.cs @@ -12,7 +12,7 @@ public static IArea WithVirtualButton(this IArea area, Enum id, Action { if (area == null) throw new ArgumentNullException(nameof(area)); - var virtualButton = new Button(ComponentIdFactory.Create(area.Id, id), new EmptyButtonEndpoint(), area.Controller.Timer); + var virtualButton = new Button(ComponentIdFactory.Create(area.Id, id), new EmptyButtonEndpoint(), area.Controller.TimerService); initializer?.Invoke(virtualButton); area.AddComponent(virtualButton); @@ -27,7 +27,7 @@ public static IArea WithButton(this IArea area, Enum id, IBinaryInput input, Act var button = new Button( ComponentIdFactory.Create(area.Id, id), new PortBasedButtonEndpoint(input), - area.Controller.Timer); + area.Controller.TimerService); initializer?.Invoke(button); @@ -49,14 +49,14 @@ public static IArea WithRollerShutterButtons( var upButton = new Button( ComponentIdFactory.Create(area.Id, upId), new PortBasedButtonEndpoint(upInput), - area.Controller.Timer); + area.Controller.TimerService); area.AddComponent(upButton); var downButton = new Button( ComponentIdFactory.Create(area.Id, downId), new PortBasedButtonEndpoint(downInput), - area.Controller.Timer); + area.Controller.TimerService); area.AddComponent(downButton); diff --git a/SDK/HA4IoT.Core/Area.cs b/SDK/HA4IoT.Services/Areas/Area.cs similarity index 79% rename from SDK/HA4IoT.Core/Area.cs rename to SDK/HA4IoT.Services/Areas/Area.cs index d7e8a7b0..83dc30b4 100644 --- a/SDK/HA4IoT.Core/Area.cs +++ b/SDK/HA4IoT.Services/Areas/Area.cs @@ -1,27 +1,31 @@ -using HA4IoT.Contracts.Core; -using System; +using System; using System.Collections.Generic; using Windows.Data.Json; using HA4IoT.Contracts.Areas; using HA4IoT.Contracts.Automations; using HA4IoT.Contracts.Components; +using HA4IoT.Contracts.Core; using HA4IoT.Contracts.Core.Settings; -using HA4IoT.Core.Settings; +using HA4IoT.Services.Automations; +using HA4IoT.Services.Components; -namespace HA4IoT.Core +namespace HA4IoT.Services.Areas { public class Area : IArea { private readonly ComponentCollection _components = new ComponentCollection(); private readonly AutomationCollection _automations = new AutomationCollection(); - public Area(AreaId id, IController controller) + private readonly IComponentService _componentService; + + public Area(AreaId id, IComponentService componentService) { - if (controller == null) throw new ArgumentNullException(nameof(controller)); + if (componentService == null) throw new ArgumentNullException(nameof(componentService)); - Id = id; - Controller = controller; + _componentService = componentService; + Id = id; + Settings = new SettingsContainer(StoragePath.WithFilename("Areas", id.Value, "Settings.json")); GeneralSettingsWrapper = new AreaSettingsWrapper(Settings); } @@ -32,14 +36,14 @@ public Area(AreaId id, IController controller) public IAreaSettingsWrapper GeneralSettingsWrapper { get; } - public IController Controller { get; } + public IController AreaService { get; } public void AddComponent(IComponent component) { if (component == null) throw new ArgumentNullException(nameof(component)); _components.AddUnique(component.Id, component); - Controller.AddComponent(component); + _componentService.AddComponent(component); } public TComponent GetComponent() where TComponent : IComponent @@ -57,7 +61,7 @@ public IList GetComponents() return _components.GetAll(); } - public bool GetContainsComponent(ComponentId componentId) + public bool ContainsComponent(ComponentId componentId) { if (componentId == null) throw new ArgumentNullException(nameof(componentId)); @@ -72,7 +76,7 @@ public TComponent GetComponent(ComponentId id) where TComponent : IC public void AddAutomation(IAutomation automation) { _automations.AddUnique(automation.Id, automation); - Controller.AddAutomation(automation); + AreaService.AddAutomation(automation); } public IList GetAutomations() where TAutomation : IAutomation diff --git a/SDK/HA4IoT.Services/Areas/AreaCollection.cs b/SDK/HA4IoT.Services/Areas/AreaCollection.cs new file mode 100644 index 00000000..5823047d --- /dev/null +++ b/SDK/HA4IoT.Services/Areas/AreaCollection.cs @@ -0,0 +1,8 @@ +using HA4IoT.Contracts.Areas; + +namespace HA4IoT.Services.Areas +{ + public class AreaCollection : GenericControllerCollection + { + } +} diff --git a/SDK/HA4IoT.Services/Areas/AreaService.cs b/SDK/HA4IoT.Services/Areas/AreaService.cs new file mode 100644 index 00000000..76268c89 --- /dev/null +++ b/SDK/HA4IoT.Services/Areas/AreaService.cs @@ -0,0 +1,50 @@ +using System; +using System.Collections.Generic; +using HA4IoT.Contracts.Areas; +using HA4IoT.Contracts.Components; +using HA4IoT.Contracts.Services; + +namespace HA4IoT.Services.Areas +{ + public class AreaService : ServiceBase, IAreaService + { + private readonly AreaCollection _areas = new AreaCollection(); + private readonly IComponentService _componentService; + + public AreaService(IComponentService componentService) + { + if (componentService == null) throw new ArgumentNullException(nameof(componentService)); + + _componentService = componentService; + } + + public IArea CreateArea(AreaId id) + { + if (id == null) throw new ArgumentNullException(nameof(id)); + + var area = new Area(id, _componentService); + _areas.AddUnique(id, area); + + return area; + } + + public void AddArea(IArea area) + { + if (area == null) throw new ArgumentNullException(nameof(area)); + + _areas.AddUnique(area.Id, area); + } + + public IArea GetArea(AreaId id) + { + if (id == null) throw new ArgumentNullException(nameof(id)); + + return _areas.Get(id); + } + + public IList GetAreas() + { + return _areas.GetAll(); + } + } +} diff --git a/SDK/HA4IoT.Services/Areas/AreaServiceExtensions.cs b/SDK/HA4IoT.Services/Areas/AreaServiceExtensions.cs new file mode 100644 index 00000000..a6c3c3bc --- /dev/null +++ b/SDK/HA4IoT.Services/Areas/AreaServiceExtensions.cs @@ -0,0 +1,21 @@ +using System; +using HA4IoT.Contracts.Areas; + +namespace HA4IoT.Services.Areas +{ + public static class AreaServiceExtensions + { + public static IArea CreateArea(this IAreaService areaService, Enum id) + { + if (areaService == null) throw new ArgumentNullException(nameof(areaService)); + return areaService.CreateArea(AreaIdFactory.Create(id)); + } + + public static IArea GetArea(this IAreaService areaService, Enum id) + { + if (areaService == null) throw new ArgumentNullException(nameof(areaService)); + + return areaService.GetArea(AreaIdFactory.Create(id)); + } + } +} diff --git a/SDK/HA4IoT.Core/AreaSettingsWrapper.cs b/SDK/HA4IoT.Services/Areas/AreaSettingsWrapper.cs similarity index 94% rename from SDK/HA4IoT.Core/AreaSettingsWrapper.cs rename to SDK/HA4IoT.Services/Areas/AreaSettingsWrapper.cs index 33a5d89a..c0b1dbf2 100644 --- a/SDK/HA4IoT.Core/AreaSettingsWrapper.cs +++ b/SDK/HA4IoT.Services/Areas/AreaSettingsWrapper.cs @@ -3,7 +3,7 @@ using HA4IoT.Contracts.Areas; using HA4IoT.Contracts.Core.Settings; -namespace HA4IoT.Core +namespace HA4IoT.Services.Areas { public class AreaSettingsWrapper : IAreaSettingsWrapper { diff --git a/SDK/HA4IoT.Core/AutomationCollection.cs b/SDK/HA4IoT.Services/Automations/AutomationCollection.cs similarity index 79% rename from SDK/HA4IoT.Core/AutomationCollection.cs rename to SDK/HA4IoT.Services/Automations/AutomationCollection.cs index 0fcf4be9..1d3ba7d4 100644 --- a/SDK/HA4IoT.Core/AutomationCollection.cs +++ b/SDK/HA4IoT.Services/Automations/AutomationCollection.cs @@ -1,6 +1,6 @@ using HA4IoT.Contracts.Automations; -namespace HA4IoT.Core +namespace HA4IoT.Services.Automations { public class AutomationCollection : GenericControllerCollection { diff --git a/SDK/HA4IoT.Services/Automations/AutomationService.cs b/SDK/HA4IoT.Services/Automations/AutomationService.cs new file mode 100644 index 00000000..094ddee0 --- /dev/null +++ b/SDK/HA4IoT.Services/Automations/AutomationService.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections.Generic; +using HA4IoT.Contracts.Automations; +using HA4IoT.Contracts.Services; + +namespace HA4IoT.Services.Automations +{ + public class AutomationService : ServiceBase, IAutomationService + { + private readonly AutomationCollection _automations = new AutomationCollection(); + + public void AddAutomation(IAutomation automation) + { + if (automation == null) throw new ArgumentNullException(nameof(automation)); + + _automations.AddOrUpdate(automation.Id, automation); + } + + public IList GetAutomations() where TAutomation : IAutomation + { + return _automations.GetAll(); + } + + public TAutomation GetAutomation(AutomationId id) where TAutomation : IAutomation + { + if (id == null) throw new ArgumentNullException(nameof(id)); + + return _automations.Get(id); + } + + public IList GetAutomations() + { + return _automations.GetAll(); + } + } +} diff --git a/SDK/HA4IoT.Core/ActuatorCollection.cs b/SDK/HA4IoT.Services/Components/ComponentCollection.cs similarity index 53% rename from SDK/HA4IoT.Core/ActuatorCollection.cs rename to SDK/HA4IoT.Services/Components/ComponentCollection.cs index 666d9124..3a62d80c 100644 --- a/SDK/HA4IoT.Core/ActuatorCollection.cs +++ b/SDK/HA4IoT.Services/Components/ComponentCollection.cs @@ -1,7 +1,6 @@ -using HA4IoT.Contracts.Actuators; -using HA4IoT.Contracts.Components; +using HA4IoT.Contracts.Components; -namespace HA4IoT.Core +namespace HA4IoT.Services.Components { public class ComponentCollection : GenericControllerCollection { diff --git a/SDK/HA4IoT.Services/Components/ComponentService.cs b/SDK/HA4IoT.Services/Components/ComponentService.cs new file mode 100644 index 00000000..7875a7d1 --- /dev/null +++ b/SDK/HA4IoT.Services/Components/ComponentService.cs @@ -0,0 +1,63 @@ +using System; +using System.Collections.Generic; +using HA4IoT.Contracts.Components; +using HA4IoT.Contracts.Core; +using HA4IoT.Contracts.Services; +using HA4IoT.Contracts.Services.System; + +namespace HA4IoT.Services.Components +{ + public class ComponentService : ServiceBase, IComponentService, IStartupCompletedNotification + { + private readonly ISystemInformationService _systemInformationService; + private readonly ComponentCollection _components = new ComponentCollection(); + + public ComponentService(ISystemInformationService systemInformationService) + { + if (systemInformationService == null) throw new ArgumentNullException(nameof(systemInformationService)); + + _systemInformationService = systemInformationService; + } + + public void AddComponent(IComponent component) + { + if (component == null) throw new ArgumentNullException(nameof(component)); + + _components.AddUnique(component.Id, component); + } + + public TComponent GetComponent() where TComponent : IComponent + { + return _components.Get(); + } + + public IList GetComponents() where TComponent : IComponent + { + return _components.GetAll(); + } + + public IList GetComponents() + { + return _components.GetAll(); + } + + public bool ContainsComponent(ComponentId componentId) + { + if (componentId == null) throw new ArgumentNullException(nameof(componentId)); + + return _components.Contains(componentId); + } + + public TComponent GetComponent(ComponentId id) where TComponent : IComponent + { + if (id == null) throw new ArgumentNullException(nameof(id)); + + return _components.Get(id); + } + + public void OnStartupCompleted() + { + _systemInformationService.Set("Components/Count", _components.GetAll().Count); + } + } +} diff --git a/SDK/HA4IoT.Services/ControllerSlave/ControllerSlaveService.cs b/SDK/HA4IoT.Services/ControllerSlave/ControllerSlaveService.cs index bb4cad0a..80af7f68 100644 --- a/SDK/HA4IoT.Services/ControllerSlave/ControllerSlaveService.cs +++ b/SDK/HA4IoT.Services/ControllerSlave/ControllerSlaveService.cs @@ -14,7 +14,7 @@ namespace HA4IoT.Services.ControllerSlave { public class ControllerSlaveService : ServiceBase, IOutdoorTemperatureProvider, IOutdoorHumidityProvider, IDaylightProvider, IWeatherProvider { - private readonly string _masterControllerAddress; + private readonly ControllerSlaveServiceOptions _masterControllerAddress; private readonly IDateTimeService _dateTimeService; public event EventHandler OutdoorTemperatureFetched; @@ -25,13 +25,13 @@ public class ControllerSlaveService : ServiceBase, IOutdoorTemperatureProvider, private DateTime? _lastPull; private DateTime? _lastSuccessfulPull; - public ControllerSlaveService(string masterControllerAddress, ISchedulerService scheduler, IDateTimeService dateTimeService) + public ControllerSlaveService(ControllerSlaveServiceOptions options, ISchedulerService scheduler, IDateTimeService dateTimeService) { - if (masterControllerAddress == null) throw new ArgumentNullException(nameof(masterControllerAddress)); + if (options == null) throw new ArgumentNullException(nameof(options)); if (scheduler == null) throw new ArgumentNullException(nameof(scheduler)); if (dateTimeService == null) throw new ArgumentNullException(nameof(dateTimeService)); - _masterControllerAddress = masterControllerAddress; + _masterControllerAddress = options; _dateTimeService = dateTimeService; scheduler.RegisterSchedule("ControllerSlavePolling", TimeSpan.FromMinutes(5), PullValues); @@ -98,7 +98,7 @@ private void PullOutsideHumidity() private JsonObject PullValue(string serviceName) { - var uri = new Uri($"http://{_masterControllerAddress}:80/api/service/{serviceName}"); + var uri = new Uri($"http://{_masterControllerAddress.MasterControllerAddress}:80/api/service/{serviceName}"); using (var webClient = new HttpClient()) { string body = webClient.GetStringAsync(uri).Result; diff --git a/SDK/HA4IoT.Services/ControllerSlave/ControllerSlaveServiceOptions.cs b/SDK/HA4IoT.Services/ControllerSlave/ControllerSlaveServiceOptions.cs new file mode 100644 index 00000000..fd07863a --- /dev/null +++ b/SDK/HA4IoT.Services/ControllerSlave/ControllerSlaveServiceOptions.cs @@ -0,0 +1,7 @@ +namespace HA4IoT.Services.ControllerSlave +{ + public class ControllerSlaveServiceOptions + { + public string MasterControllerAddress { get; set; } + } +} diff --git a/SDK/HA4IoT.Core/DeviceCollection.cs b/SDK/HA4IoT.Services/Devices/DeviceCollection.cs similarity index 79% rename from SDK/HA4IoT.Core/DeviceCollection.cs rename to SDK/HA4IoT.Services/Devices/DeviceCollection.cs index 85f8e5f5..e367dcc5 100644 --- a/SDK/HA4IoT.Core/DeviceCollection.cs +++ b/SDK/HA4IoT.Services/Devices/DeviceCollection.cs @@ -1,6 +1,6 @@ using HA4IoT.Contracts.Hardware; -namespace HA4IoT.Core +namespace HA4IoT.Services.Devices { public class DeviceCollection : GenericControllerCollection { diff --git a/SDK/HA4IoT.Services/Devices/DeviceService.cs b/SDK/HA4IoT.Services/Devices/DeviceService.cs new file mode 100644 index 00000000..e4c2d975 --- /dev/null +++ b/SDK/HA4IoT.Services/Devices/DeviceService.cs @@ -0,0 +1,37 @@ +using System.Collections.Generic; +using HA4IoT.Contracts.Hardware; +using HA4IoT.Contracts.Services; +using HA4IoT.Contracts.Services.System; + +namespace HA4IoT.Services.Devices +{ + public class DeviceService : ServiceBase, IDeviceService + { + private readonly DeviceCollection _devices = new DeviceCollection(); + + public void AddDevice(IDevice device) + { + _devices.AddUnique(device.Id, device); + } + + public TDevice GetDevice(DeviceId id) where TDevice : IDevice + { + return _devices.Get(id); + } + + public TDevice GetDevice() where TDevice : IDevice + { + return _devices.Get(); + } + + public IList GetDevices() where TDevice : IDevice + { + return _devices.GetAll(); + } + + public IList GetDevices() + { + return _devices.GetAll(); + } + } +} diff --git a/SDK/HA4IoT.Services/Devices/DeviceServiceExtensions.cs b/SDK/HA4IoT.Services/Devices/DeviceServiceExtensions.cs new file mode 100644 index 00000000..1ece3f66 --- /dev/null +++ b/SDK/HA4IoT.Services/Devices/DeviceServiceExtensions.cs @@ -0,0 +1,18 @@ +using System; +using HA4IoT.Contracts.Hardware; +using HA4IoT.Contracts.Services.System; +using HA4IoT.Hardware; + +namespace HA4IoT.Services.Devices +{ + public static class DeviceServiceExtensions + { + public static TDevice GetDevice(this IDeviceService deviceService, Enum id) where TDevice : IDevice + { + if (deviceService == null) throw new ArgumentNullException(nameof(deviceService)); + + var deviceId = DeviceIdFactory.CreateIdFrom(id); + return deviceService.GetDevice(deviceId); + } + } +} diff --git a/SDK/HA4IoT.Core/GenericControllerCollection.cs b/SDK/HA4IoT.Services/GenericControllerCollection.cs similarity index 98% rename from SDK/HA4IoT.Core/GenericControllerCollection.cs rename to SDK/HA4IoT.Services/GenericControllerCollection.cs index b506b347..95a68ee9 100644 --- a/SDK/HA4IoT.Core/GenericControllerCollection.cs +++ b/SDK/HA4IoT.Services/GenericControllerCollection.cs @@ -3,7 +3,7 @@ using System.Linq; using HA4IoT.Contracts.Core; -namespace HA4IoT.Core +namespace HA4IoT.Services { public class GenericControllerCollection where TId : IdBase { diff --git a/SDK/HA4IoT.Services/HA4IoT.Services.csproj b/SDK/HA4IoT.Services/HA4IoT.Services.csproj index b0066782..57931b65 100644 --- a/SDK/HA4IoT.Services/HA4IoT.Services.csproj +++ b/SDK/HA4IoT.Services/HA4IoT.Services.csproj @@ -107,12 +107,35 @@ + + + + + + + + + + + + + + + + + + + + + + + @@ -124,6 +147,19 @@ {D4E0A3F9-6521-4AEE-815A-E2A60323FB63} HA4IoT.Networking + + {39819B8F-40F8-418A-AD3A-92A8C8D63268} + HA4IoT.Hardware.Pi2 + + + {287A9BD0-4037-4ADD-986F-54056F059EAE} + HA4IoT.Hardware + + + + + ..\..\..\..\..\.nuget\packages\SimpleInjector\3.2.0\lib\portable-net4+sl4+wp8+win8+wpa81\SimpleInjector.dll + 14.0 diff --git a/SDK/HA4IoT.Core/HealthService.cs b/SDK/HA4IoT.Services/Health/HealthService.cs similarity index 78% rename from SDK/HA4IoT.Core/HealthService.cs rename to SDK/HA4IoT.Services/Health/HealthService.cs index 22c1889b..c7ddb860 100644 --- a/SDK/HA4IoT.Core/HealthService.cs +++ b/SDK/HA4IoT.Services/Health/HealthService.cs @@ -6,9 +6,10 @@ using HA4IoT.Contracts.Hardware; using HA4IoT.Contracts.Services; using HA4IoT.Contracts.Services.System; -using HA4IoT.Core.Timer; +using HA4IoT.Hardware.Pi2; +using HA4IoT.Services.System; -namespace HA4IoT.Core +namespace HA4IoT.Services.Health { public class HealthService : ServiceBase { @@ -16,7 +17,7 @@ public class HealthService : ServiceBase private readonly List _durations = new List(100); private readonly Timeout _ledTimeout = new Timeout(); - private readonly IBinaryOutput _statusLed; + private readonly IBinaryOutput _led; private float? _averageTimerDuration; private bool _ledState; @@ -24,23 +25,27 @@ public class HealthService : ServiceBase private float? _minTimerDuration; - public HealthService(IBinaryOutput statusLed, IHomeAutomationTimer timer, ISystemInformationService systemInformationService) + public HealthService( + HealthServiceOptions options, + Pi2GpioService pi2GpioService, + ITimerService timerService, + ISystemInformationService systemInformationService) { - if (timer == null) throw new ArgumentNullException(nameof(timer)); + if (options == null) throw new ArgumentNullException(nameof(options)); + if (timerService == null) throw new ArgumentNullException(nameof(timerService)); if (systemInformationService == null) throw new ArgumentNullException(nameof(systemInformationService)); - _statusLed = statusLed; _systemInformationService = systemInformationService; - if (statusLed != null) + if (options.StatusLed.HasValue) { + _led = pi2GpioService.GetOutput(options.StatusLed.Value); _ledTimeout.Start(TimeSpan.FromMilliseconds(1)); } - timer.Tick += Tick; + timerService.Tick += Tick; } - public override void HandleApiCommand(IApiContext apiContext) { ResetStatistics(); @@ -90,12 +95,12 @@ private void ToggleStatusLed() { if (_ledState) { - _statusLed.Write(BinaryState.High); + _led.Write(BinaryState.High); _ledTimeout.Start(TimeSpan.FromSeconds(5)); } else { - _statusLed.Write(BinaryState.Low); + _led.Write(BinaryState.Low); _ledTimeout.Start(TimeSpan.FromMilliseconds(200)); } diff --git a/SDK/HA4IoT.Services/Health/HealthServiceOptions.cs b/SDK/HA4IoT.Services/Health/HealthServiceOptions.cs new file mode 100644 index 00000000..07a30657 --- /dev/null +++ b/SDK/HA4IoT.Services/Health/HealthServiceOptions.cs @@ -0,0 +1,7 @@ +namespace HA4IoT.Services.Health +{ + public class HealthServiceOptions + { + public int? StatusLed { get; set; } + } +} diff --git a/SDK/HA4IoT.Core/Scheduling/Schedule.cs b/SDK/HA4IoT.Services/Scheduling/Schedule.cs similarity index 94% rename from SDK/HA4IoT.Core/Scheduling/Schedule.cs rename to SDK/HA4IoT.Services/Scheduling/Schedule.cs index 298646b2..635f40af 100644 --- a/SDK/HA4IoT.Core/Scheduling/Schedule.cs +++ b/SDK/HA4IoT.Services/Scheduling/Schedule.cs @@ -1,6 +1,6 @@ using System; -namespace HA4IoT.Core.Scheduling +namespace HA4IoT.Services.Scheduling { public class Schedule { diff --git a/SDK/HA4IoT.Core/Scheduling/SchedulerService.cs b/SDK/HA4IoT.Services/Scheduling/SchedulerService.cs similarity index 89% rename from SDK/HA4IoT.Core/Scheduling/SchedulerService.cs rename to SDK/HA4IoT.Services/Scheduling/SchedulerService.cs index f1367ff6..90be388c 100644 --- a/SDK/HA4IoT.Core/Scheduling/SchedulerService.cs +++ b/SDK/HA4IoT.Services/Scheduling/SchedulerService.cs @@ -8,27 +8,28 @@ using HA4IoT.Contracts.Core; using HA4IoT.Contracts.Logging; using HA4IoT.Contracts.Services; +using HA4IoT.Contracts.Services.System; using HA4IoT.Networking; -namespace HA4IoT.Core.Scheduling +namespace HA4IoT.Services.Scheduling { - public class SchedulerService : ServiceBase, ISchedulerService + public class SchedulerService : Contracts.Services.ServiceBase, ISchedulerService { private readonly object _syncRoot = new object(); private readonly Dictionary _schedules = new Dictionary(); private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); - private readonly IHomeAutomationTimer _timer; + private readonly ITimerService _timerService; - public SchedulerService(IHomeAutomationTimer timer) + public SchedulerService(ITimerService timerService) { - if (timer == null) throw new ArgumentNullException(nameof(timer)); + if (timerService == null) throw new ArgumentNullException(nameof(timerService)); - _timer = timer; + _timerService = timerService; } public TimedAction In(TimeSpan dueTime) { - return new TimedAction(dueTime, TimeSpan.Zero, _timer); + return new TimedAction(dueTime, TimeSpan.Zero, _timerService); } public override void HandleApiRequest(IApiContext apiContext) diff --git a/SDK/HA4IoT.Services/System/ContainerService.cs b/SDK/HA4IoT.Services/System/ContainerService.cs new file mode 100644 index 00000000..912f2f7b --- /dev/null +++ b/SDK/HA4IoT.Services/System/ContainerService.cs @@ -0,0 +1,41 @@ +using System; +using HA4IoT.Contracts.Services; +using HA4IoT.Contracts.Services.System; +using SimpleInjector; + +namespace HA4IoT.Services.System +{ + public class ContainerService : ServiceBase, IContainerService + { + private readonly Container _container; + + public ContainerService(Container container) + { + if (container == null) throw new ArgumentNullException(nameof(container)); + + _container = container; + } + + public TService GetInstance() where TService : class + { + return _container.GetInstance(); + } + + public void RegisterSingleton() where TConcrete : class + { + _container.RegisterSingleton(); + } + + public void RegisterSingleton(Func instanceCreator) where TService : class + { + if (instanceCreator == null) throw new ArgumentNullException(nameof(instanceCreator)); + + _container.RegisterSingleton(instanceCreator); + } + + public void RegisterSingleton() where TService : class where TImplementation : class, TService + { + _container.RegisterSingleton(); + } + } +} diff --git a/SDK/HA4IoT.Core/DateTimeService.cs b/SDK/HA4IoT.Services/System/DateTimeService.cs similarity index 95% rename from SDK/HA4IoT.Core/DateTimeService.cs rename to SDK/HA4IoT.Services/System/DateTimeService.cs index 0b35dd56..4a7ebdee 100644 --- a/SDK/HA4IoT.Core/DateTimeService.cs +++ b/SDK/HA4IoT.Services/System/DateTimeService.cs @@ -4,7 +4,7 @@ using HA4IoT.Contracts.Services.System; using HA4IoT.Networking; -namespace HA4IoT.Core +namespace HA4IoT.Services.System { public class DateTimeService : ServiceBase, IDateTimeService { diff --git a/SDK/HA4IoT.Core/SystemInformationService.cs b/SDK/HA4IoT.Services/System/SystemInformationService.cs similarity index 92% rename from SDK/HA4IoT.Core/SystemInformationService.cs rename to SDK/HA4IoT.Services/System/SystemInformationService.cs index 9385f401..91d991be 100644 --- a/SDK/HA4IoT.Core/SystemInformationService.cs +++ b/SDK/HA4IoT.Services/System/SystemInformationService.cs @@ -3,13 +3,12 @@ using System.Linq; using Windows.Data.Json; using HA4IoT.Contracts.Api; -using HA4IoT.Contracts.Services; using HA4IoT.Contracts.Services.System; using HA4IoT.Networking; -namespace HA4IoT.Core +namespace HA4IoT.Services.System { - public class SystemInformationService : ServiceBase, ISystemInformationService + public class SystemInformationService : Contracts.Services.ServiceBase, ISystemInformationService { private readonly Dictionary _values = new Dictionary(); diff --git a/SDK/HA4IoT.Core/Timer/Timeout.cs b/SDK/HA4IoT.Services/System/Timeout.cs similarity index 97% rename from SDK/HA4IoT.Core/Timer/Timeout.cs rename to SDK/HA4IoT.Services/System/Timeout.cs index 21d20c38..7d11633b 100644 --- a/SDK/HA4IoT.Core/Timer/Timeout.cs +++ b/SDK/HA4IoT.Services/System/Timeout.cs @@ -1,7 +1,7 @@ using System; using HA4IoT.Contracts.Core; -namespace HA4IoT.Core.Timer +namespace HA4IoT.Services.System { public class Timeout { diff --git a/SDK/HA4IoT.Core/Timer/HomeAutomationTimer.cs b/SDK/HA4IoT.Services/System/TimerService.cs similarity index 78% rename from SDK/HA4IoT.Core/Timer/HomeAutomationTimer.cs rename to SDK/HA4IoT.Services/System/TimerService.cs index d9d2d76f..f068ae2c 100644 --- a/SDK/HA4IoT.Core/Timer/HomeAutomationTimer.cs +++ b/SDK/HA4IoT.Services/System/TimerService.cs @@ -3,10 +3,11 @@ using System.Threading; using HA4IoT.Contracts.Core; using HA4IoT.Contracts.Logging; +using HA4IoT.Contracts.Services.System; -namespace HA4IoT.Core.Timer +namespace HA4IoT.Services.System { - public class HomeAutomationTimer : IHomeAutomationTimer + public class TimerService : ITimerService { private readonly Stopwatch _stopwatch = Stopwatch.StartNew(); @@ -14,7 +15,8 @@ public class HomeAutomationTimer : IHomeAutomationTimer public void Run() { - Log.Verbose($"Timer is running on thread {Environment.CurrentManagedThreadId}"); + var threadId = global::System.Environment.CurrentManagedThreadId; + Log.Verbose($"Timer is running on thread {threadId}"); while (true) { diff --git a/SDK/HA4IoT.Services/project.json b/SDK/HA4IoT.Services/project.json index 92d14561..6be7438b 100644 --- a/SDK/HA4IoT.Services/project.json +++ b/SDK/HA4IoT.Services/project.json @@ -1,6 +1,7 @@ { "dependencies": { - "Microsoft.NETCore.UniversalWindowsPlatform": "5.1.0" + "Microsoft.NETCore.UniversalWindowsPlatform": "5.1.0", + "SimpleInjector": "3.2.0" }, "frameworks": { "uap10.0": {} diff --git a/SDK/HA4IoT.Settings/HA4IoT.Settings.csproj b/SDK/HA4IoT.Settings/HA4IoT.Settings.csproj new file mode 100644 index 00000000..f9922049 --- /dev/null +++ b/SDK/HA4IoT.Settings/HA4IoT.Settings.csproj @@ -0,0 +1,126 @@ + + + + + Debug + AnyCPU + {600BC3F2-2A09-4A8E-9126-1F9ACCD7D879} + Library + Properties + HA4IoT.Settings + HA4IoT.Settings + en-US + UAP + 10.0.10586.0 + 10.0.10240.0 + 14 + 512 + {A5A43C5B-DE2A-4C0C-9213-0A381AF9435A};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE;NETFX_CORE;WINDOWS_UWP + prompt + 4 + + + x86 + true + bin\x86\Debug\ + DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP + ;2008 + full + x86 + false + prompt + + + x86 + bin\x86\Release\ + TRACE;NETFX_CORE;WINDOWS_UWP + true + ;2008 + pdbonly + x86 + false + prompt + + + ARM + true + bin\ARM\Debug\ + DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP + ;2008 + full + ARM + false + prompt + + + ARM + bin\ARM\Release\ + TRACE;NETFX_CORE;WINDOWS_UWP + true + ;2008 + pdbonly + ARM + false + prompt + + + x64 + true + bin\x64\Debug\ + DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP + ;2008 + full + x64 + false + prompt + + + x64 + bin\x64\Release\ + TRACE;NETFX_CORE;WINDOWS_UWP + true + ;2008 + pdbonly + x64 + false + prompt + + + + + + + + + + + + + 14.0 + + + + \ No newline at end of file diff --git a/SDK/HA4IoT.Settings/Properties/AssemblyInfo.cs b/SDK/HA4IoT.Settings/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..2bc5c1e2 --- /dev/null +++ b/SDK/HA4IoT.Settings/Properties/AssemblyInfo.cs @@ -0,0 +1,14 @@ +using System.Reflection; +using System.Runtime.InteropServices; + +[assembly: AssemblyTitle("HA4IoT.Settings")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Christian Kratky")] +[assembly: AssemblyProduct("HA4IoT")] +[assembly: AssemblyCopyright("Copyright © Christian Kratky 2016")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] +[assembly: ComVisible(false)] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] \ No newline at end of file diff --git a/SDK/HA4IoT.Settings/Properties/HA4IoT.Settings.rd.xml b/SDK/HA4IoT.Settings/Properties/HA4IoT.Settings.rd.xml new file mode 100644 index 00000000..9ccc7d78 --- /dev/null +++ b/SDK/HA4IoT.Settings/Properties/HA4IoT.Settings.rd.xml @@ -0,0 +1,33 @@ + + + + + + + + + diff --git a/SDK/HA4IoT.Core/Settings/SettingsContainer.cs b/SDK/HA4IoT.Settings/SettingsContainer.cs similarity index 98% rename from SDK/HA4IoT.Core/Settings/SettingsContainer.cs rename to SDK/HA4IoT.Settings/SettingsContainer.cs index 9a4f1926..0681e198 100644 --- a/SDK/HA4IoT.Core/Settings/SettingsContainer.cs +++ b/SDK/HA4IoT.Settings/SettingsContainer.cs @@ -3,10 +3,8 @@ using System.IO; using System.Text; using Windows.Data.Json; -using HA4IoT.Contracts.Core.Settings; -using HA4IoT.Contracts.Logging; -namespace HA4IoT.Core.Settings +namespace HA4IoT.Settings { public class SettingsContainer : ISettingsContainer { diff --git a/SDK/HA4IoT.Core/Settings/SettingsContainerApiDispatcher.cs b/SDK/HA4IoT.Settings/SettingsContainerApiDispatcher.cs similarity index 84% rename from SDK/HA4IoT.Core/Settings/SettingsContainerApiDispatcher.cs rename to SDK/HA4IoT.Settings/SettingsContainerApiDispatcher.cs index 535a0b7d..7b20f124 100644 --- a/SDK/HA4IoT.Core/Settings/SettingsContainerApiDispatcher.cs +++ b/SDK/HA4IoT.Settings/SettingsContainerApiDispatcher.cs @@ -1,16 +1,14 @@ using System; -using HA4IoT.Contracts.Api; -using HA4IoT.Contracts.Core.Settings; -namespace HA4IoT.Core.Settings +namespace HA4IoT.Settings { public class SettingsContainerApiDispatcher { private readonly ISettingsContainer _settingsContainer; - private readonly IApiController _apiController; + private readonly IApiService _apiController; private readonly string _relativeUri; - public SettingsContainerApiDispatcher(ISettingsContainer settingsContainer, string relativeUri, IApiController apiController) + public SettingsContainerApiDispatcher(ISettingsContainer settingsContainer, string relativeUri, IApiService apiController) { if (settingsContainer == null) throw new ArgumentNullException(nameof(settingsContainer)); if (relativeUri == null) throw new ArgumentNullException(nameof(relativeUri)); diff --git a/SDK/HA4IoT.Settings/project.json b/SDK/HA4IoT.Settings/project.json new file mode 100644 index 00000000..92d14561 --- /dev/null +++ b/SDK/HA4IoT.Settings/project.json @@ -0,0 +1,16 @@ +{ + "dependencies": { + "Microsoft.NETCore.UniversalWindowsPlatform": "5.1.0" + }, + "frameworks": { + "uap10.0": {} + }, + "runtimes": { + "win10-arm": {}, + "win10-arm-aot": {}, + "win10-x86": {}, + "win10-x86-aot": {}, + "win10-x64": {}, + "win10-x64-aot": {} + } +} \ No newline at end of file diff --git a/SDK/HA4IoT.Telemetry/ActuatorMonitor.cs b/SDK/HA4IoT.Telemetry/ActuatorMonitor.cs index 8e98064f..fcc3b726 100644 --- a/SDK/HA4IoT.Telemetry/ActuatorMonitor.cs +++ b/SDK/HA4IoT.Telemetry/ActuatorMonitor.cs @@ -1,18 +1,25 @@ using System; using HA4IoT.Contracts.Actuators; using HA4IoT.Contracts.Components; -using HA4IoT.Contracts.Core; using HA4IoT.Contracts.Sensors; +using HA4IoT.Contracts.Services.System; namespace HA4IoT.Telemetry { public abstract class ActuatorMonitor - { - public void Connect(IController controller) + { + private readonly IComponentService _componentService; + + protected ActuatorMonitor(IComponentService componentService) { - if (controller == null) throw new ArgumentNullException(nameof(controller)); + if (componentService == null) throw new ArgumentNullException(nameof(componentService)); + + _componentService = componentService; + } - foreach (var component in controller.GetComponents()) + public void Connect() + { + foreach (var component in _componentService.GetComponents()) { OnComponentConnecting(component); diff --git a/SDK/HA4IoT.Telemetry/ComponentStateHistoryTracker.cs b/SDK/HA4IoT.Telemetry/ComponentStateHistoryTracker.cs index d9232fae..0bd916c3 100644 --- a/SDK/HA4IoT.Telemetry/ComponentStateHistoryTracker.cs +++ b/SDK/HA4IoT.Telemetry/ComponentStateHistoryTracker.cs @@ -42,7 +42,7 @@ public void Reset() } } - public void ExposeToApi(IApiController apiController) + public void ExposeToApi(IApiService apiController) { if (apiController == null) throw new ArgumentNullException(nameof(apiController)); diff --git a/SDK/Hardware/HA4IoT.Hardware.CCTools/CCToolsBoardController.cs b/SDK/Hardware/HA4IoT.Hardware.CCTools/CCToolsBoardService.cs similarity index 64% rename from SDK/Hardware/HA4IoT.Hardware.CCTools/CCToolsBoardController.cs rename to SDK/Hardware/HA4IoT.Hardware.CCTools/CCToolsBoardService.cs index a2d0cd1e..16654f52 100644 --- a/SDK/Hardware/HA4IoT.Hardware.CCTools/CCToolsBoardController.cs +++ b/SDK/Hardware/HA4IoT.Hardware.CCTools/CCToolsBoardService.cs @@ -1,84 +1,82 @@ using System; using System.Diagnostics; -using HA4IoT.Contracts.Api; -using HA4IoT.Contracts.Core; using HA4IoT.Contracts.Hardware; using HA4IoT.Contracts.Logging; +using HA4IoT.Contracts.Services; +using HA4IoT.Contracts.Services.System; namespace HA4IoT.Hardware.CCTools { - public class CCToolsBoardController : IDevice + public class CCToolsBoardService : ServiceBase { - private readonly II2CBus _i2CBus; - private readonly IController _controller; + private readonly II2CBusService _i2CBusService; + private readonly IDeviceService _deviceService; - public CCToolsBoardController(IController controller, II2CBus i2cBus) + public CCToolsBoardService(IDeviceService deviceService, II2CBusService i2CBusServiceService) { - if (i2cBus == null) throw new ArgumentNullException(nameof(i2cBus)); - if (controller == null) throw new ArgumentNullException(nameof(controller)); + if (i2CBusServiceService == null) throw new ArgumentNullException(nameof(i2CBusServiceService)); + if (deviceService == null) throw new ArgumentNullException(nameof(deviceService)); - _controller = controller; - _i2CBus = i2cBus; + _deviceService = deviceService; + _i2CBusService = i2CBusServiceService; } - public DeviceId Id { get; } = new DeviceId("CCToolsBoardController"); - public HSPE16InputOnly CreateHSPE16InputOnly(Enum id, I2CSlaveAddress address) { - var device = new HSPE16InputOnly(DeviceIdFactory.CreateIdFrom(id), address, _i2CBus) + var device = new HSPE16InputOnly(DeviceIdFactory.CreateIdFrom(id), address, _i2CBusService) { AutomaticallyFetchState = true }; - _controller.AddDevice(device); + _deviceService.AddDevice(device); return device; } public HSPE16OutputOnly CreateHSPE16OutputOnly(Enum id, I2CSlaveAddress address) { - var device = new HSPE16OutputOnly(DeviceIdFactory.CreateIdFrom(id), address, _i2CBus); - _controller.AddDevice(device); + var device = new HSPE16OutputOnly(DeviceIdFactory.CreateIdFrom(id), address, _i2CBusService); + _deviceService.AddDevice(device); return device; } public HSPE8OutputOnly CreateHSPE8OutputOnly(Enum id, I2CSlaveAddress i2CAddress) { - var device = new HSPE8OutputOnly(DeviceIdFactory.CreateIdFrom(id), i2CAddress, _i2CBus); - _controller.AddDevice(device); + var device = new HSPE8OutputOnly(DeviceIdFactory.CreateIdFrom(id), i2CAddress, _i2CBusService); + _deviceService.AddDevice(device); return device; } public HSPE8InputOnly CreateHSPE8InputOnly(Enum id, I2CSlaveAddress i2CAddress) { - var device = new HSPE8InputOnly(DeviceIdFactory.CreateIdFrom(id), i2CAddress, _i2CBus); - _controller.AddDevice(device); + var device = new HSPE8InputOnly(DeviceIdFactory.CreateIdFrom(id), i2CAddress, _i2CBusService); + _deviceService.AddDevice(device); return device; } public HSREL5 CreateHSREL5(Enum id, I2CSlaveAddress i2CAddress) { - var device = new HSREL5(DeviceIdFactory.CreateIdFrom(id), i2CAddress, _i2CBus); - _controller.AddDevice(device); + var device = new HSREL5(DeviceIdFactory.CreateIdFrom(id), i2CAddress, _i2CBusService); + _deviceService.AddDevice(device); return device; } public HSREL8 CreateHSREL8(Enum id, I2CSlaveAddress i2CAddress) { - var device = new HSREL8(DeviceIdFactory.CreateIdFrom(id), i2CAddress, _i2CBus); - _controller.AddDevice(device); + var device = new HSREL8(DeviceIdFactory.CreateIdFrom(id), i2CAddress, _i2CBusService); + _deviceService.AddDevice(device); return device; } public HSRT16 CreateHSRT16(Enum id, I2CSlaveAddress address) { - var device = new HSRT16(DeviceIdFactory.CreateIdFrom(id), address, _i2CBus); - _controller.AddDevice(device); + var device = new HSRT16(DeviceIdFactory.CreateIdFrom(id), address, _i2CBusService); + _deviceService.AddDevice(device); return device; } @@ -87,7 +85,7 @@ public void PollInputBoardStates() { var stopwatch = Stopwatch.StartNew(); - var inputDevices = _controller.GetDevices(); + var inputDevices = _deviceService.GetDevices(); foreach (var portExpanderController in inputDevices) { @@ -111,13 +109,5 @@ public void PollInputBoardStates() } } } - - public void HandleApiCommand(IApiContext apiContext) - { - } - - public void HandleApiRequest(IApiContext apiContext) - { - } } } diff --git a/SDK/Hardware/HA4IoT.Hardware.CCTools/CCToolsConfigurationExtender.cs b/SDK/Hardware/HA4IoT.Hardware.CCTools/CCToolsConfigurationExtender.cs deleted file mode 100644 index 56389d55..00000000 --- a/SDK/Hardware/HA4IoT.Hardware.CCTools/CCToolsConfigurationExtender.cs +++ /dev/null @@ -1,157 +0,0 @@ -using System; -using System.Xml.Linq; -using HA4IoT.Configuration; -using HA4IoT.Contracts.Configuration; -using HA4IoT.Contracts.Core; -using HA4IoT.Contracts.Hardware; - -namespace HA4IoT.Hardware.CCTools -{ - public class CCToolsConfigurationExtender : ConfigurationExtenderBase - { - public CCToolsConfigurationExtender(ConfigurationParser parser, IController controller) - : base(parser, controller) - { - Namespace = "http://www.ha4iot.de/ConfigurationExtenders/CCTools"; - } - - public override IDevice ParseDevice(XElement element) - { - if (element == null) throw new ArgumentNullException(nameof(element)); - - switch (element.Name.LocalName) - { - case "HSPE16InputOnly": return ParseHSPE16InputOnly(element); - case "HSPE16OutputOnly": return ParseHSPE16OutputOnly(element); - - case "HSPE8InputOnly": return ParseHSPE8InputOnly(element); - case "HSPE8OutputOnly": return ParseHSPE8OutputOnly(element); - - case "HSRel5": return ParseHSRel5(element); - case "HSRel8": return ParseHSRel8(element); - - case "HSRT16": return ParseHSRT16(element); - - default: throw new ConfigurationInvalidException("Device not supported.", element); - } - } - - public override IBinaryInput ParseBinaryInput(XElement element) - { - if (element == null) throw new ArgumentNullException(nameof(element)); - - var device = Controller.GetDevice(new DeviceId(element.GetMandatoryStringFromAttribute("deviceId"))); - var port = element.GetMandatoryStringFromAttribute("port"); - - var hspe16 = device as HSPE16InputOnly; - if (hspe16 != null) - { - return hspe16[(HSPE16Pin) Enum.Parse(typeof (HSPE16Pin), port)]; - } - - var hspe8 = device as HSPE8InputOnly; - if (hspe8 != null) - { - return hspe8[(HSPE8Pin) Enum.Parse(typeof (HSPE8Pin), port)]; - } - - throw new ConfigurationInvalidException("CCTools device '" + device.GetType().FullName + "' is no input device.", element); - } - - public override IBinaryOutput ParseBinaryOutput(XElement element) - { - if (element == null) throw new ArgumentNullException(nameof(element)); - - var device = Controller.GetDevice(new DeviceId(element.GetMandatoryStringFromAttribute("deviceId"))); - var port = element.GetMandatoryStringFromAttribute("port"); - - var hspe16 = device as HSPE16OutputOnly; - if (hspe16 != null) - { - return hspe16[(HSPE16Pin)Enum.Parse(typeof(HSPE16Pin), port)]; - } - - var hspe8 = device as HSPE8OutputOnly; - if (hspe8 != null) - { - return hspe8[(HSPE8Pin)Enum.Parse(typeof(HSPE8Pin), port)]; - } - - var hsrel8 = device as HSREL8; - if (hsrel8 != null) - { - return hsrel8[(HSREL8Pin)Enum.Parse(typeof(HSREL8Pin), port)]; - } - - var hsrel5 = device as HSREL5; - if (hsrel5 != null) - { - return hsrel5[(HSREL5Pin)Enum.Parse(typeof(HSREL5Pin), port)]; - } - - var hsrt16 = device as HSRT16; - if (hsrt16 != null) - { - return hsrt16[(HSRT16Pin)Enum.Parse(typeof(HSRT16Pin), port)]; - } - - throw new ConfigurationInvalidException("CCTools device '" + device.GetType().FullName + "' is no input device.", element); - } - - private HSREL5 ParseHSRel5(XElement element) - { - return new HSREL5( - new DeviceId(element.GetMandatoryStringFromAttribute("id")), - new I2CSlaveAddress(element.GetMandatoryIntFromAttribute("i2cAddress")), - Controller.GetDevice(element.GetStringFromAttribute("i2cBus", "II2CBus.default").ToDeviceId())); - } - - private HSREL8 ParseHSRel8(XElement element) - { - return new HSREL8( - new DeviceId(element.GetMandatoryStringFromAttribute("id")), - new I2CSlaveAddress(element.GetMandatoryIntFromAttribute("i2cAddress")), - Controller.GetDevice(element.GetStringFromAttribute("i2cBus", "II2CBus.default").ToDeviceId())); - } - - private HSPE16OutputOnly ParseHSPE16OutputOnly(XElement element) - { - return new HSPE16OutputOnly( - new DeviceId(element.GetMandatoryStringFromAttribute("id")), - new I2CSlaveAddress(element.GetMandatoryIntFromAttribute("i2cAddress")), - Controller.GetDevice(element.GetStringFromAttribute("i2cBus", "II2CBus.default").ToDeviceId())); - } - - private HSPE16InputOnly ParseHSPE16InputOnly(XElement element) - { - return new HSPE16InputOnly( - new DeviceId(element.GetMandatoryStringFromAttribute("id")), - new I2CSlaveAddress(element.GetMandatoryIntFromAttribute("i2cAddress")), - Controller.GetDevice(element.GetStringFromAttribute("i2cBus", "II2CBus.default").ToDeviceId())); - } - - private HSPE8OutputOnly ParseHSPE8OutputOnly(XElement element) - { - return new HSPE8OutputOnly( - new DeviceId(element.GetMandatoryStringFromAttribute("id")), - new I2CSlaveAddress(element.GetMandatoryIntFromAttribute("i2cAddress")), - Controller.GetDevice(element.GetStringFromAttribute("i2cBus", "II2CBus.default").ToDeviceId())); - } - - private HSPE8InputOnly ParseHSPE8InputOnly(XElement element) - { - return new HSPE8InputOnly( - new DeviceId(element.GetMandatoryStringFromAttribute("id")), - new I2CSlaveAddress(element.GetMandatoryIntFromAttribute("i2cAddress")), - Controller.GetDevice(element.GetStringFromAttribute("i2cBus", "II2CBus.default").ToDeviceId())); - } - - private HSRT16 ParseHSRT16(XElement element) - { - return new HSRT16( - new DeviceId(element.GetMandatoryStringFromAttribute("id")), - new I2CSlaveAddress(element.GetMandatoryIntFromAttribute("i2cAddress")), - Controller.GetDevice(element.GetStringFromAttribute("i2cBus", "II2CBus.default").ToDeviceId())); - } - } -} diff --git a/SDK/Hardware/HA4IoT.Hardware.CCTools/HA4IoT.Hardware.CCTools.csproj b/SDK/Hardware/HA4IoT.Hardware.CCTools/HA4IoT.Hardware.CCTools.csproj index 8434a9a1..d39510d7 100644 --- a/SDK/Hardware/HA4IoT.Hardware.CCTools/HA4IoT.Hardware.CCTools.csproj +++ b/SDK/Hardware/HA4IoT.Hardware.CCTools/HA4IoT.Hardware.CCTools.csproj @@ -114,8 +114,7 @@ - - + @@ -143,10 +142,6 @@ {551337E7-D1EF-4145-92B4-F7086F7665A6} HA4IoT.Contracts - - {2BBEF090-4FEE-4FB7-9CF1-F6597F2C53EA} - HA4IoT.Core - {287A9BD0-4037-4ADD-986F-54056F059EAE} HA4IoT.Hardware diff --git a/SDK/Hardware/HA4IoT.Hardware.CCTools/HSPE16InputOnly.cs b/SDK/Hardware/HA4IoT.Hardware.CCTools/HSPE16InputOnly.cs index 7030ae93..42d072d9 100644 --- a/SDK/Hardware/HA4IoT.Hardware.CCTools/HSPE16InputOnly.cs +++ b/SDK/Hardware/HA4IoT.Hardware.CCTools/HSPE16InputOnly.cs @@ -1,11 +1,12 @@ using HA4IoT.Contracts.Hardware; +using HA4IoT.Contracts.Services.System; using HA4IoT.Hardware.PortExpanderDrivers; namespace HA4IoT.Hardware.CCTools { public class HSPE16InputOnly : CCToolsInputBoardBase, IBinaryInputController { - public HSPE16InputOnly(DeviceId id, I2CSlaveAddress address, II2CBus i2cBus) + public HSPE16InputOnly(DeviceId id, I2CSlaveAddress address, II2CBusService i2cBus) : base(id, new MAX7311Driver(address, i2cBus)) { byte[] setupAsInputs = { 0x06, 0xFF, 0xFF }; diff --git a/SDK/Hardware/HA4IoT.Hardware.CCTools/HSPE16OutputOnly.cs b/SDK/Hardware/HA4IoT.Hardware.CCTools/HSPE16OutputOnly.cs index d83b52a4..6b3cc87f 100644 --- a/SDK/Hardware/HA4IoT.Hardware.CCTools/HSPE16OutputOnly.cs +++ b/SDK/Hardware/HA4IoT.Hardware.CCTools/HSPE16OutputOnly.cs @@ -1,11 +1,12 @@ using HA4IoT.Contracts.Hardware; +using HA4IoT.Contracts.Services.System; using HA4IoT.Hardware.PortExpanderDrivers; namespace HA4IoT.Hardware.CCTools { public class HSPE16OutputOnly : CCToolsBoardBase, IBinaryOutputController { - public HSPE16OutputOnly(DeviceId id, I2CSlaveAddress address, II2CBus i2cBus) + public HSPE16OutputOnly(DeviceId id, I2CSlaveAddress address, II2CBusService i2cBus) : base(id, new MAX7311Driver(address, i2cBus)) { CommitChanges(true); diff --git a/SDK/Hardware/HA4IoT.Hardware.CCTools/HSPE8InputOnly.cs b/SDK/Hardware/HA4IoT.Hardware.CCTools/HSPE8InputOnly.cs index fe2768bb..2404d8b8 100644 --- a/SDK/Hardware/HA4IoT.Hardware.CCTools/HSPE8InputOnly.cs +++ b/SDK/Hardware/HA4IoT.Hardware.CCTools/HSPE8InputOnly.cs @@ -1,12 +1,13 @@ using System; using HA4IoT.Contracts.Hardware; +using HA4IoT.Contracts.Services.System; using HA4IoT.Hardware.PortExpanderDrivers; namespace HA4IoT.Hardware.CCTools { public class HSPE8InputOnly : CCToolsInputBoardBase, IBinaryInputController { - public HSPE8InputOnly(DeviceId id, I2CSlaveAddress address, II2CBus bus) + public HSPE8InputOnly(DeviceId id, I2CSlaveAddress address, II2CBusService bus) : base(id, new PCF8574Driver(address, bus)) { FetchState(); diff --git a/SDK/Hardware/HA4IoT.Hardware.CCTools/HSPE8OutputOnly.cs b/SDK/Hardware/HA4IoT.Hardware.CCTools/HSPE8OutputOnly.cs index 0530263c..3e26cc7e 100644 --- a/SDK/Hardware/HA4IoT.Hardware.CCTools/HSPE8OutputOnly.cs +++ b/SDK/Hardware/HA4IoT.Hardware.CCTools/HSPE8OutputOnly.cs @@ -1,12 +1,13 @@ using System; using HA4IoT.Contracts.Hardware; +using HA4IoT.Contracts.Services.System; using HA4IoT.Hardware.PortExpanderDrivers; namespace HA4IoT.Hardware.CCTools { public class HSPE8OutputOnly : CCToolsBoardBase, IBinaryOutputController { - public HSPE8OutputOnly(DeviceId id, I2CSlaveAddress address, II2CBus bus) + public HSPE8OutputOnly(DeviceId id, I2CSlaveAddress address, II2CBusService bus) : base(id, new PCF8574Driver(address, bus)) { FetchState(); diff --git a/SDK/Hardware/HA4IoT.Hardware.CCTools/HSREL5.cs b/SDK/Hardware/HA4IoT.Hardware.CCTools/HSREL5.cs index 90d4b1f1..1a69d832 100644 --- a/SDK/Hardware/HA4IoT.Hardware.CCTools/HSREL5.cs +++ b/SDK/Hardware/HA4IoT.Hardware.CCTools/HSREL5.cs @@ -1,12 +1,13 @@ using System; using HA4IoT.Contracts.Hardware; +using HA4IoT.Contracts.Services.System; using HA4IoT.Hardware.PortExpanderDrivers; namespace HA4IoT.Hardware.CCTools { public class HSREL5 : CCToolsBoardBase, IBinaryOutputController { - public HSREL5(DeviceId id, I2CSlaveAddress i2CAddress, II2CBus bus) + public HSREL5(DeviceId id, I2CSlaveAddress i2CAddress, II2CBusService bus) : base(id, new PCF8574Driver(i2CAddress, bus)) { // Ensure that all relays are off by default. The first 5 ports are hardware inverted! The other ports are not inverted but the diff --git a/SDK/Hardware/HA4IoT.Hardware.CCTools/HSREL8.cs b/SDK/Hardware/HA4IoT.Hardware.CCTools/HSREL8.cs index ffd5d2b9..65c1ac76 100644 --- a/SDK/Hardware/HA4IoT.Hardware.CCTools/HSREL8.cs +++ b/SDK/Hardware/HA4IoT.Hardware.CCTools/HSREL8.cs @@ -1,12 +1,13 @@ using System; using HA4IoT.Contracts.Hardware; +using HA4IoT.Contracts.Services.System; using HA4IoT.Hardware.PortExpanderDrivers; namespace HA4IoT.Hardware.CCTools { public class HSREL8 : CCToolsBoardBase, IBinaryOutputController { - public HSREL8(DeviceId id, I2CSlaveAddress i2CAddress, II2CBus i2CBus) + public HSREL8(DeviceId id, I2CSlaveAddress i2CAddress, II2CBusService i2CBus) : base(id, new MAX7311Driver(i2CAddress, i2CBus)) { SetState(new byte[] { 0x00, 255 }); diff --git a/SDK/Hardware/HA4IoT.Hardware.CCTools/HSRT16.cs b/SDK/Hardware/HA4IoT.Hardware.CCTools/HSRT16.cs index a822aa25..006347c1 100644 --- a/SDK/Hardware/HA4IoT.Hardware.CCTools/HSRT16.cs +++ b/SDK/Hardware/HA4IoT.Hardware.CCTools/HSRT16.cs @@ -1,12 +1,13 @@ using System; using HA4IoT.Contracts.Hardware; +using HA4IoT.Contracts.Services.System; using HA4IoT.Hardware.PortExpanderDrivers; namespace HA4IoT.Hardware.CCTools { public class HSRT16 : CCToolsBoardBase, IBinaryOutputController { - public HSRT16(DeviceId id, I2CSlaveAddress address, II2CBus i2CBus) + public HSRT16(DeviceId id, I2CSlaveAddress address, II2CBusService i2CBus) : base(id, new MAX7311Driver(address, i2CBus)) { SetState(new byte[] { 0x00, 0x00 }); diff --git a/SDK/Hardware/HA4IoT.Hardware.I2CHardwareBridge/I2CHardwareBridge.cs b/SDK/Hardware/HA4IoT.Hardware.I2CHardwareBridge/I2CHardwareBridge.cs index fa9dbab7..d2dbd09b 100644 --- a/SDK/Hardware/HA4IoT.Hardware.I2CHardwareBridge/I2CHardwareBridge.cs +++ b/SDK/Hardware/HA4IoT.Hardware.I2CHardwareBridge/I2CHardwareBridge.cs @@ -2,15 +2,16 @@ using HA4IoT.Contracts.Api; using HA4IoT.Contracts.Hardware; using HA4IoT.Contracts.Services; +using HA4IoT.Contracts.Services.System; namespace HA4IoT.Hardware.I2CHardwareBridge { public class I2CHardwareBridge : IDevice { private readonly I2CSlaveAddress _address; - private readonly II2CBus _i2CBus; + private readonly II2CBusService _i2CBus; - public I2CHardwareBridge(I2CSlaveAddress address, II2CBus i2cBus, ISchedulerService schedulerService) + public I2CHardwareBridge(I2CSlaveAddress address, II2CBusService i2cBus, ISchedulerService schedulerService) { if (i2cBus == null) throw new ArgumentNullException(nameof(i2cBus)); if (schedulerService == null) throw new ArgumentNullException(nameof(schedulerService)); diff --git a/SDK/Hardware/HA4IoT.Hardware.I2CHardwareBridge/I2CHardwareBridgeConfigurationExtender.cs b/SDK/Hardware/HA4IoT.Hardware.I2CHardwareBridge/I2CHardwareBridgeConfigurationExtender.cs index 53d67247..20062c93 100644 --- a/SDK/Hardware/HA4IoT.Hardware.I2CHardwareBridge/I2CHardwareBridgeConfigurationExtender.cs +++ b/SDK/Hardware/HA4IoT.Hardware.I2CHardwareBridge/I2CHardwareBridgeConfigurationExtender.cs @@ -6,6 +6,7 @@ using HA4IoT.Contracts.Hardware; using HA4IoT.Contracts.Sensors; using HA4IoT.Contracts.Services; +using HA4IoT.Contracts.Services.System; namespace HA4IoT.Hardware.I2CHardwareBridge { @@ -64,7 +65,7 @@ private IDevice ParseI2CHardwareBridge(XElement element) { return new I2CHardwareBridge( new I2CSlaveAddress(element.GetMandatoryIntFromAttribute("i2cAddress")), - Controller.GetDevice(new DeviceId(element.GetStringFromAttribute("i2cBus", "II2CBus.default"))), + Controller.GetDevice(new DeviceId(element.GetStringFromAttribute("i2cBus", "II2CBus.default"))), Controller.ServiceLocator.GetService()); } } diff --git a/SDK/Hardware/HA4IoT.Hardware.Pi2/HA4IoT.Hardware.Pi2.csproj b/SDK/Hardware/HA4IoT.Hardware.Pi2/HA4IoT.Hardware.Pi2.csproj index 42c5b5f1..d8b5e491 100644 --- a/SDK/Hardware/HA4IoT.Hardware.Pi2/HA4IoT.Hardware.Pi2.csproj +++ b/SDK/Hardware/HA4IoT.Hardware.Pi2/HA4IoT.Hardware.Pi2.csproj @@ -113,8 +113,8 @@ - - + + diff --git a/SDK/Hardware/HA4IoT.Hardware.Pi2/Pi2Port.cs b/SDK/Hardware/HA4IoT.Hardware.Pi2/Pi2Gpio.cs similarity index 96% rename from SDK/Hardware/HA4IoT.Hardware.Pi2/Pi2Port.cs rename to SDK/Hardware/HA4IoT.Hardware.Pi2/Pi2Gpio.cs index a395a050..e07e8d87 100644 --- a/SDK/Hardware/HA4IoT.Hardware.Pi2/Pi2Port.cs +++ b/SDK/Hardware/HA4IoT.Hardware.Pi2/Pi2Gpio.cs @@ -4,14 +4,14 @@ namespace HA4IoT.Hardware.Pi2 { - public class Pi2Port : IBinaryOutput, IBinaryInput + public class Pi2Gpio : IBinaryOutput, IBinaryInput { private readonly object _syncRoot = new object(); private bool _isStateInverted; private BinaryState _previousState; - public Pi2Port(GpioPin pin) + public Pi2Gpio(GpioPin pin) { if (pin == null) throw new ArgumentNullException(nameof(pin)); diff --git a/SDK/Hardware/HA4IoT.Hardware.Pi2/Pi2PortController.cs b/SDK/Hardware/HA4IoT.Hardware.Pi2/Pi2GpioService.cs similarity index 56% rename from SDK/Hardware/HA4IoT.Hardware.Pi2/Pi2PortController.cs rename to SDK/Hardware/HA4IoT.Hardware.Pi2/Pi2GpioService.cs index d5de5eab..10621a8e 100644 --- a/SDK/Hardware/HA4IoT.Hardware.Pi2/Pi2PortController.cs +++ b/SDK/Hardware/HA4IoT.Hardware.Pi2/Pi2GpioService.cs @@ -1,16 +1,23 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using Windows.Devices.Gpio; -using HA4IoT.Contracts.Api; using HA4IoT.Contracts.Hardware; +using HA4IoT.Contracts.Services; +using HA4IoT.Contracts.Services.System; namespace HA4IoT.Hardware.Pi2 { - public class Pi2PortController : IBinaryOutputController, IBinaryInputController + public class Pi2GpioService : ServiceBase, IBinaryOutputController, IBinaryInputController { private readonly GpioController _gpioController = GpioController.GetDefault(); - private readonly Dictionary _openPorts = new Dictionary(); + private readonly Dictionary _openPorts = new Dictionary(); - public DeviceId Id { get; } = new DeviceId("Pi2.GPIOs"); + public Pi2GpioService(ITimerService timerService) + { + if (timerService == null) throw new ArgumentNullException(nameof(timerService)); + + timerService.Tick += (s, e) => PollOpenInputPorts(); + } public IBinaryInput GetInput(int number) { @@ -22,17 +29,9 @@ public IBinaryOutput GetOutput(int number) return OpenPort(number, GpioPinDriveMode.Output); } - public void HandleApiCommand(IApiContext apiContext) - { - } - - public void HandleApiRequest(IApiContext apiContext) - { - } - - public void PollOpenInputPorts() + private void PollOpenInputPorts() { - foreach (Pi2Port port in _openPorts.Values) + foreach (Pi2Gpio port in _openPorts.Values) { if (port.Pin.GetDriveMode() == GpioPinDriveMode.Input) { @@ -41,15 +40,15 @@ public void PollOpenInputPorts() } } - private Pi2Port OpenPort(int number, GpioPinDriveMode mode) + private Pi2Gpio OpenPort(int number, GpioPinDriveMode mode) { - Pi2Port port; + Pi2Gpio port; if (!_openPorts.TryGetValue(number, out port)) { GpioPin pin = _gpioController.OpenPin(number, GpioSharingMode.Exclusive); pin.SetDriveMode(mode); - port = new Pi2Port(pin); + port = new Pi2Gpio(pin); _openPorts.Add(number, port); } diff --git a/SDK/Hardware/HA4IoT.Hardware.PortExpanderDrivers/MAX7311Driver.cs b/SDK/Hardware/HA4IoT.Hardware.PortExpanderDrivers/MAX7311Driver.cs index 84f1c8d7..721dc676 100644 --- a/SDK/Hardware/HA4IoT.Hardware.PortExpanderDrivers/MAX7311Driver.cs +++ b/SDK/Hardware/HA4IoT.Hardware.PortExpanderDrivers/MAX7311Driver.cs @@ -1,11 +1,12 @@ using System; using HA4IoT.Contracts.Hardware; +using HA4IoT.Contracts.Services.System; namespace HA4IoT.Hardware.PortExpanderDrivers { public class MAX7311Driver : IPortExpanderDriver { - private readonly II2CBus _i2CBus; + private readonly II2CBusService _i2CBus; private readonly I2CSlaveAddress _address; private const byte InputPortRegisterA = 0; @@ -13,7 +14,7 @@ public class MAX7311Driver : IPortExpanderDriver private const byte PolarityInversionRegisterA = 4; private const byte ConfigurationRegisterA = 6; - public MAX7311Driver(I2CSlaveAddress address, II2CBus i2CBus) + public MAX7311Driver(I2CSlaveAddress address, II2CBusService i2CBus) { if (address == null) throw new ArgumentNullException(nameof(address)); if (i2CBus == null) throw new ArgumentNullException(nameof(i2CBus)); diff --git a/SDK/Hardware/HA4IoT.Hardware.PortExpanderDrivers/PCA9555ADriver.cs b/SDK/Hardware/HA4IoT.Hardware.PortExpanderDrivers/PCA9555ADriver.cs index fe8fc068..df255cf7 100644 --- a/SDK/Hardware/HA4IoT.Hardware.PortExpanderDrivers/PCA9555ADriver.cs +++ b/SDK/Hardware/HA4IoT.Hardware.PortExpanderDrivers/PCA9555ADriver.cs @@ -1,10 +1,11 @@ using HA4IoT.Contracts.Hardware; +using HA4IoT.Contracts.Services.System; namespace HA4IoT.Hardware.PortExpanderDrivers { public class PCA9555ADriver : PCA9555Driver { - public PCA9555ADriver(I2CSlaveAddress address, II2CBus i2CBus) + public PCA9555ADriver(I2CSlaveAddress address, II2CBusService i2CBus) : base(address, i2CBus) { } diff --git a/SDK/Hardware/HA4IoT.Hardware.PortExpanderDrivers/PCA9555Driver.cs b/SDK/Hardware/HA4IoT.Hardware.PortExpanderDrivers/PCA9555Driver.cs index 619cdfc9..324d5c3e 100644 --- a/SDK/Hardware/HA4IoT.Hardware.PortExpanderDrivers/PCA9555Driver.cs +++ b/SDK/Hardware/HA4IoT.Hardware.PortExpanderDrivers/PCA9555Driver.cs @@ -1,10 +1,11 @@ using HA4IoT.Contracts.Hardware; +using HA4IoT.Contracts.Services.System; namespace HA4IoT.Hardware.PortExpanderDrivers { public class PCA9555Driver : MAX7311Driver { - public PCA9555Driver(I2CSlaveAddress address, II2CBus i2CBus) + public PCA9555Driver(I2CSlaveAddress address, II2CBusService i2CBus) : base(address, i2CBus) { } diff --git a/SDK/Hardware/HA4IoT.Hardware.PortExpanderDrivers/PCF8574ADriver.cs b/SDK/Hardware/HA4IoT.Hardware.PortExpanderDrivers/PCF8574ADriver.cs index 2d33baba..21f574f4 100644 --- a/SDK/Hardware/HA4IoT.Hardware.PortExpanderDrivers/PCF8574ADriver.cs +++ b/SDK/Hardware/HA4IoT.Hardware.PortExpanderDrivers/PCF8574ADriver.cs @@ -1,10 +1,11 @@ using HA4IoT.Contracts.Hardware; +using HA4IoT.Contracts.Services.System; namespace HA4IoT.Hardware.PortExpanderDrivers { public class PCF8574ADriver : PCF8574Driver { - public PCF8574ADriver(I2CSlaveAddress address, II2CBus i2CBus) + public PCF8574ADriver(I2CSlaveAddress address, II2CBusService i2CBus) : base(address, i2CBus) { } diff --git a/SDK/Hardware/HA4IoT.Hardware.PortExpanderDrivers/PCF8574Driver.cs b/SDK/Hardware/HA4IoT.Hardware.PortExpanderDrivers/PCF8574Driver.cs index 40e2141d..0e405fc3 100644 --- a/SDK/Hardware/HA4IoT.Hardware.PortExpanderDrivers/PCF8574Driver.cs +++ b/SDK/Hardware/HA4IoT.Hardware.PortExpanderDrivers/PCF8574Driver.cs @@ -1,14 +1,15 @@ using System; using HA4IoT.Contracts.Hardware; +using HA4IoT.Contracts.Services.System; namespace HA4IoT.Hardware.PortExpanderDrivers { public class PCF8574Driver : IPortExpanderDriver { - private readonly II2CBus _i2CBus; + private readonly II2CBusService _i2CBus; private readonly I2CSlaveAddress _address; - public PCF8574Driver(I2CSlaveAddress address, II2CBus i2CBus) + public PCF8574Driver(I2CSlaveAddress address, II2CBusService i2CBus) { if (address == null) throw new ArgumentNullException(nameof(address)); if (i2CBus == null) throw new ArgumentNullException(nameof(i2CBus)); diff --git a/SDK/Hardware/HA4IoT.Hardware.RemoteSwitch/HA4IoT.Hardware.RemoteSwitch.csproj b/SDK/Hardware/HA4IoT.Hardware.RemoteSwitch/HA4IoT.Hardware.RemoteSwitch.csproj index edd39e74..0834b491 100644 --- a/SDK/Hardware/HA4IoT.Hardware.RemoteSwitch/HA4IoT.Hardware.RemoteSwitch.csproj +++ b/SDK/Hardware/HA4IoT.Hardware.RemoteSwitch/HA4IoT.Hardware.RemoteSwitch.csproj @@ -126,7 +126,7 @@ - + diff --git a/SDK/Hardware/HA4IoT.Hardware.RemoteSwitch/LPD433MhzSignalSender.cs b/SDK/Hardware/HA4IoT.Hardware.RemoteSwitch/LPD433MhzSignalSender.cs index 95a6bac2..cac4ee4f 100644 --- a/SDK/Hardware/HA4IoT.Hardware.RemoteSwitch/LPD433MhzSignalSender.cs +++ b/SDK/Hardware/HA4IoT.Hardware.RemoteSwitch/LPD433MhzSignalSender.cs @@ -10,7 +10,7 @@ public class LPD433MHzSignalSender : ILPD433MHzSignalSender private readonly I2CHardwareBridge.I2CHardwareBridge _i2CHardwareBridge; private readonly byte _pin; - public LPD433MHzSignalSender(I2CHardwareBridge.I2CHardwareBridge i2CHardwareBridge, byte pin, IApiController apiController) + public LPD433MHzSignalSender(I2CHardwareBridge.I2CHardwareBridge i2CHardwareBridge, byte pin, IApiService apiController) { if (i2CHardwareBridge == null) throw new ArgumentNullException(nameof(i2CHardwareBridge)); if (apiController == null) throw new ArgumentNullException(nameof(apiController)); diff --git a/SDK/Hardware/HA4IoT.Hardware.RemoteSwitch/RemoteSocketController.cs b/SDK/Hardware/HA4IoT.Hardware.RemoteSwitch/RemoteSocketService.cs similarity index 78% rename from SDK/Hardware/HA4IoT.Hardware.RemoteSwitch/RemoteSocketController.cs rename to SDK/Hardware/HA4IoT.Hardware.RemoteSwitch/RemoteSocketService.cs index 4d8f9e3b..a69b4d72 100644 --- a/SDK/Hardware/HA4IoT.Hardware.RemoteSwitch/RemoteSocketController.cs +++ b/SDK/Hardware/HA4IoT.Hardware.RemoteSwitch/RemoteSocketService.cs @@ -1,19 +1,18 @@ using System; using System.Collections.Generic; -using HA4IoT.Contracts.Api; using HA4IoT.Contracts.Hardware; using HA4IoT.Contracts.Services; namespace HA4IoT.Hardware.RemoteSwitch { - public class RemoteSocketController : IBinaryOutputController + public class RemoteSocketService : ServiceBase, IBinaryOutputController { private readonly object _syncRoot = new object(); private readonly Dictionary _ports = new Dictionary(); private readonly LPD433MHzSignalSender _sender; - public RemoteSocketController(LPD433MHzSignalSender sender, ISchedulerService schedulerService) + public RemoteSocketService(LPD433MHzSignalSender sender, ISchedulerService schedulerService) { if (sender == null) throw new ArgumentNullException(nameof(sender)); if (schedulerService == null) throw new ArgumentNullException(nameof(schedulerService)); @@ -24,9 +23,7 @@ public RemoteSocketController(LPD433MHzSignalSender sender, ISchedulerService sc // or the switch has been removed from the socket and plugged in at another place. schedulerService.RegisterSchedule("RCSocketStateSender", TimeSpan.FromSeconds(5), RefreshStates); } - - public DeviceId Id { get; } = new DeviceId("RemoteSocketController"); - + public IBinaryOutput GetOutput(int number) { if (number < 0) throw new ArgumentOutOfRangeException(nameof(number)); @@ -43,7 +40,7 @@ public IBinaryOutput GetOutput(int number) } } - public RemoteSocketController WithRemoteSocket(int id, LPD433MHzCodeSequencePair codeSequencePair) + public RemoteSocketService WithRemoteSocket(int id, LPD433MHzCodeSequencePair codeSequencePair) { if (codeSequencePair == null) throw new ArgumentNullException(nameof(codeSequencePair)); @@ -58,14 +55,6 @@ public RemoteSocketController WithRemoteSocket(int id, LPD433MHzCodeSequencePair return this; } - public void HandleApiCommand(IApiContext apiContext) - { - } - - public void HandleApiRequest(IApiContext apiContext) - { - } - private void RefreshStates() { foreach (var port in _ports.Values) diff --git a/SDK/Hardware/HA4IoT.Hardware/BuiltInI2CBus.cs b/SDK/Hardware/HA4IoT.Hardware/BuiltInI2CBusService.cs similarity index 83% rename from SDK/Hardware/HA4IoT.Hardware/BuiltInI2CBus.cs rename to SDK/Hardware/HA4IoT.Hardware/BuiltInI2CBusService.cs index 6f8db69e..65fbf11d 100644 --- a/SDK/Hardware/HA4IoT.Hardware/BuiltInI2CBus.cs +++ b/SDK/Hardware/HA4IoT.Hardware/BuiltInI2CBusService.cs @@ -3,31 +3,21 @@ using System.Linq; using Windows.Devices.Enumeration; using Windows.Devices.I2c; -using HA4IoT.Contracts.Api; using HA4IoT.Contracts.Hardware; using HA4IoT.Contracts.Logging; +using HA4IoT.Contracts.Services; +using HA4IoT.Contracts.Services.System; namespace HA4IoT.Hardware { - public class BuiltInI2CBus : II2CBus + public class BuiltInI2CBusService : ServiceBase, II2CBusService { - public static readonly DeviceId DefaultId = new DeviceId("I2C.BuiltIn"); - private readonly object _syncRoot = new object(); private readonly Dictionary _deviceCache = new Dictionary(); private readonly string _i2CBusId; - - public BuiltInI2CBus() - : this(DefaultId) - { - } - public BuiltInI2CBus(DeviceId id) + public BuiltInI2CBusService() { - if (id == null) throw new ArgumentNullException(nameof(id)); - - Id = id; - string deviceSelector = I2cDevice.GetDeviceSelector(); DeviceInformationCollection deviceInformation = DeviceInformation.FindAllAsync(deviceSelector).AsTask().Result; @@ -38,17 +28,7 @@ public BuiltInI2CBus(DeviceId id) _i2CBusId = deviceInformation.First().Id; } - - public DeviceId Id { get; } - - public void HandleApiCommand(IApiContext apiContext) - { - } - - public void HandleApiRequest(IApiContext apiContext) - { - } - + public void Execute(I2CSlaveAddress address, Action action, bool useCache = true) { if (action == null) throw new ArgumentNullException(nameof(action)); diff --git a/SDK/Hardware/HA4IoT.Hardware/ControllerExtensions.cs b/SDK/Hardware/HA4IoT.Hardware/ControllerExtensions.cs deleted file mode 100644 index ef73f95d..00000000 --- a/SDK/Hardware/HA4IoT.Hardware/ControllerExtensions.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; -using HA4IoT.Contracts.Core; -using HA4IoT.Contracts.Hardware; - -namespace HA4IoT.Hardware -{ - public static class ControllerExtensions - { - public static TDevice Device(this IDeviceController controller, Enum id) where TDevice : IDevice - { - return controller.GetDevice(DeviceIdFactory.CreateIdFrom(id)); - } - } -} diff --git a/SDK/Hardware/HA4IoT.Hardware/HA4IoT.Hardware.csproj b/SDK/Hardware/HA4IoT.Hardware/HA4IoT.Hardware.csproj index 6f70d6d9..d093ef52 100644 --- a/SDK/Hardware/HA4IoT.Hardware/HA4IoT.Hardware.csproj +++ b/SDK/Hardware/HA4IoT.Hardware/HA4IoT.Hardware.csproj @@ -115,8 +115,7 @@ - - + diff --git a/Tests/HA4IoT.Actuators.Tests/AutomaticTurnOnAndOffAutomationTests.cs b/Tests/HA4IoT.Actuators.Tests/AutomaticTurnOnAndOffAutomationTests.cs index c40c645a..38b735a5 100644 --- a/Tests/HA4IoT.Actuators.Tests/AutomaticTurnOnAndOffAutomationTests.cs +++ b/Tests/HA4IoT.Actuators.Tests/AutomaticTurnOnAndOffAutomationTests.cs @@ -15,7 +15,7 @@ public class AutomaticTurnOnAndOffAutomationTests [TestMethod] public void Should_TurnOn_IfMotionDetected() { - var schedulerService = new SchedulerService(new TestHomeAutomationTimer()); + var schedulerService = new SchedulerService(new TestTimerService()); var motionDetectorFactory = new TestMotionDetectorFactory(schedulerService); var stateMachineFactory = new TestStateMachineFactory(); @@ -35,11 +35,11 @@ public void Should_TurnOn_IfMotionDetected() [TestMethod] public void Should_TurnOn_IfButtonPressedShort() { - var timer = new TestHomeAutomationTimer(); + var timer = new TestTimerService(); var buttonFactory = new TestButtonFactory(timer); var stateMachineFactory = new TestStateMachineFactory(); - var automation = new TurnOnAndOffAutomation(AutomationIdFactory.EmptyId, new TestDateTimeService(), new SchedulerService(new TestHomeAutomationTimer())); + var automation = new TurnOnAndOffAutomation(AutomationIdFactory.EmptyId, new TestDateTimeService(), new SchedulerService(new TestTimerService())); var button = buttonFactory.CreateTestButton(); var output = stateMachineFactory.CreateTestStateMachineWithOnOffStates(); output.GetState().ShouldBeEquivalentTo(BinaryStateId.Off); @@ -55,7 +55,7 @@ public void Should_TurnOn_IfButtonPressedShort() [TestMethod] public void Should_NotTurnOn_IfMotionDetected_AndTimeRangeConditionIs_NotFulfilled() { - var timer = new TestHomeAutomationTimer(); + var timer = new TestTimerService(); var dateTimeService = new TestDateTimeService(); dateTimeService.SetTime(TimeSpan.Parse("18:00:00")); @@ -79,7 +79,7 @@ public void Should_NotTurnOn_IfMotionDetected_AndTimeRangeConditionIs_NotFulfill [TestMethod] public void Should_TurnOn_IfButtonPressed_EvenIfTimeRangeConditionIs_NotFulfilled() { - var timer = new TestHomeAutomationTimer(); + var timer = new TestTimerService(); var dateTimeService = new TestDateTimeService(); dateTimeService.SetTime(TimeSpan.Parse("18:00:00")); @@ -103,7 +103,7 @@ public void Should_TurnOn_IfButtonPressed_EvenIfTimeRangeConditionIs_NotFulfille [TestMethod] public void Should_NotTurnOn_IfMotionDetected_AndSkipConditionIs_Fulfilled() { - var timer = new TestHomeAutomationTimer(); + var timer = new TestTimerService(); var dateTimeService = new TestDateTimeService(); dateTimeService.SetTime(TimeSpan.Parse("14:00:00")); @@ -136,7 +136,7 @@ public void Should_NotTurnOn_IfMotionDetected_AndSkipConditionIs_Fulfilled() [TestMethod] public void Should_TurnOn_IfMotionDetected_AndSkipConditionIs_NotFulfilled() { - var timer = new TestHomeAutomationTimer(); + var timer = new TestTimerService(); var dateTimeService = new TestDateTimeService(); dateTimeService.SetTime(TimeSpan.Parse("14:00:00")); @@ -168,7 +168,7 @@ public void Should_TurnOn_IfMotionDetected_AndSkipConditionIs_NotFulfilled() [TestMethod] public void Should_TurnOff_IfButtonPressed_WhileTargetIsAlreadyOn() { - var timer = new TestHomeAutomationTimer(); + var timer = new TestTimerService(); var dateTimeService = new TestDateTimeService(); dateTimeService.SetTime(TimeSpan.Parse("14:00:00")); diff --git a/Tests/HA4IoT.Actuators.Tests/LogicalBinaryStateActuatorTests.cs b/Tests/HA4IoT.Actuators.Tests/LogicalBinaryStateActuatorTests.cs index a2c25a9e..c31083e5 100644 --- a/Tests/HA4IoT.Actuators.Tests/LogicalBinaryStateActuatorTests.cs +++ b/Tests/HA4IoT.Actuators.Tests/LogicalBinaryStateActuatorTests.cs @@ -13,7 +13,7 @@ public class LogicalBinaryStateActuatorTests [TestMethod] public void TurnOn_CombinedActuators() { - var timer = new TestHomeAutomationTimer(); + var timer = new TestTimerService(); var stateMachineFactory = new TestStateMachineFactory(); var testActuator1 = stateMachineFactory.CreateTestStateMachineWithOnOffStates(); diff --git a/Tests/HA4IoT.Actuators.Tests/RollerShutterTests.cs b/Tests/HA4IoT.Actuators.Tests/RollerShutterTests.cs index e5394a87..08f81ba1 100644 --- a/Tests/HA4IoT.Actuators.Tests/RollerShutterTests.cs +++ b/Tests/HA4IoT.Actuators.Tests/RollerShutterTests.cs @@ -11,7 +11,7 @@ public class RollerShutterTests [TestMethod] public void TestRollerShutter() { - var rollerShutterFactory = new TestRollerShutterFactory(new TestHomeAutomationTimer()); + var rollerShutterFactory = new TestRollerShutterFactory(new TestTimerService()); TestRollerShutter rollerShutter = rollerShutterFactory.CreateTestRollerShutter(); rollerShutter.GetState().Equals(RollerShutterStateId.Off).ShouldBeEquivalentTo(true); diff --git a/Tests/HA4IoT.Actuators.Tests/TriggerTests.cs b/Tests/HA4IoT.Actuators.Tests/TriggerTests.cs index ac5ca1f9..4ce4246c 100644 --- a/Tests/HA4IoT.Actuators.Tests/TriggerTests.cs +++ b/Tests/HA4IoT.Actuators.Tests/TriggerTests.cs @@ -103,7 +103,7 @@ public void SensorValueUnderran_Trigger() [TestMethod] public void Associate_TriggerWithActuatorAction() { - var buttonFactory = new TestButtonFactory(new TestHomeAutomationTimer()); + var buttonFactory = new TestButtonFactory(new TestTimerService()); var stateMachineFactory = new TestStateMachineFactory(); var testButton = buttonFactory.CreateTestButton(); diff --git a/Tests/HA4IoT.Automations.Tests/AutomationTests.cs b/Tests/HA4IoT.Automations.Tests/AutomationTests.cs index c4c97527..a1c689a3 100644 --- a/Tests/HA4IoT.Automations.Tests/AutomationTests.cs +++ b/Tests/HA4IoT.Automations.Tests/AutomationTests.cs @@ -16,7 +16,7 @@ public class AutomationTests [TestMethod] public void Automation_Toggle() { - var timer = new TestHomeAutomationTimer(); + var timer = new TestTimerService(); var testButtonFactory = new TestButtonFactory(timer); var testStateMachineFactory = new TestStateMachineFactory(); @@ -42,7 +42,7 @@ public void Automation_WithCondition() var testController = new TestController(); var automation = new Automation(AutomationIdFactory.EmptyId); - var testButtonFactory = new TestButtonFactory(testController.Timer); + var testButtonFactory = new TestButtonFactory(testController.TimerService); var testStateMachineFactory = new TestStateMachineFactory(); var testButton = testButtonFactory.CreateTestButton(); diff --git a/Tests/HA4IoT.Automations.Tests/ConditionalOnAutomationTests.cs b/Tests/HA4IoT.Automations.Tests/ConditionalOnAutomationTests.cs index 65611850..1ef15967 100644 --- a/Tests/HA4IoT.Automations.Tests/ConditionalOnAutomationTests.cs +++ b/Tests/HA4IoT.Automations.Tests/ConditionalOnAutomationTests.cs @@ -20,7 +20,7 @@ public void Empty_ConditionalOnAutomation() testController.ServiceLocator.GetService(), testController.ServiceLocator.GetService()); - var testButtonFactory = new TestButtonFactory(testController.Timer); + var testButtonFactory = new TestButtonFactory(testController.TimerService); var testStateMachineFactory = new TestStateMachineFactory(); var testButton = testButtonFactory.CreateTestButton(); diff --git a/Tests/HA4IoT.Automations.Tests/RollerShutterAutomationTests.cs b/Tests/HA4IoT.Automations.Tests/RollerShutterAutomationTests.cs index 7261127c..e807a5f9 100644 --- a/Tests/HA4IoT.Automations.Tests/RollerShutterAutomationTests.cs +++ b/Tests/HA4IoT.Automations.Tests/RollerShutterAutomationTests.cs @@ -1,7 +1,6 @@ using System; using FluentAssertions; using HA4IoT.Contracts.Actuators; -using HA4IoT.Contracts.Hardware; using HA4IoT.Contracts.Services; using HA4IoT.Contracts.Services.System; using HA4IoT.Tests.Mockups; @@ -86,7 +85,7 @@ private void Setup() _controller = new TestController(); _controller.SetTime(TimeSpan.Parse("12:00")); - var testRollerShutterFactory = new TestRollerShutterFactory(_controller.Timer); + var testRollerShutterFactory = new TestRollerShutterFactory(_controller.TimerService); _weatherStation = new TestWeatherStation(); _weatherStation.OutdoorTemperature = 20; diff --git a/Tests/HA4IoT.Configuration.Tests/ConfigurationParserTests.cs b/Tests/HA4IoT.Configuration.Tests/ConfigurationParserTests.cs index 94ae43cf..f6601bfa 100644 --- a/Tests/HA4IoT.Configuration.Tests/ConfigurationParserTests.cs +++ b/Tests/HA4IoT.Configuration.Tests/ConfigurationParserTests.cs @@ -8,6 +8,7 @@ using HA4IoT.Contracts.Core; using HA4IoT.Contracts.Hardware; using HA4IoT.Contracts.Services; +using HA4IoT.Contracts.Services.System; using HA4IoT.Contracts.Services.Weather; using HA4IoT.Hardware.CCTools; using HA4IoT.Hardware.I2CHardwareBridge; @@ -26,7 +27,7 @@ public class ConfigurationParserTests [TestMethod] public void Parse_I2CBusDevice() { - GetController().GetDevices().Count.ShouldBeEquivalentTo(1); + GetController().GetDevices().Count.ShouldBeEquivalentTo(1); } [TestMethod] diff --git a/Tests/HA4IoT.Configuration.Tests/HA4IoT.Configuration.Tests.csproj b/Tests/HA4IoT.Configuration.Tests/HA4IoT.Configuration.Tests.csproj index ea302c8d..981fd51d 100644 --- a/Tests/HA4IoT.Configuration.Tests/HA4IoT.Configuration.Tests.csproj +++ b/Tests/HA4IoT.Configuration.Tests/HA4IoT.Configuration.Tests.csproj @@ -98,7 +98,6 @@ - UnitTestApp.xaml diff --git a/Tests/HA4IoT.Configuration.Tests/TestConfigurationExtender.cs b/Tests/HA4IoT.Configuration.Tests/TestConfigurationExtender.cs deleted file mode 100644 index 4eafe2f6..00000000 --- a/Tests/HA4IoT.Configuration.Tests/TestConfigurationExtender.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System; -using System.Xml.Linq; -using HA4IoT.Contracts.Configuration; -using HA4IoT.Contracts.Core; -using HA4IoT.Contracts.Hardware; -using HA4IoT.Tests.Mockups; - -namespace HA4IoT.Configuration.Tests -{ - internal class TestConfigurationExtender : ConfigurationExtenderBase - { - public TestConfigurationExtender(ConfigurationParser parser, IController controller) - : base(parser, controller) - { - Namespace = "http://www.ha4iot.de/ConfigurationExtenders/Test"; - } - - public override IDevice ParseDevice(XElement element) - { - switch (element.Name.LocalName) - { - case "I2CBus": return new TestI2CBus(new DeviceId(element.GetMandatoryStringFromAttribute("id"))); - - default: throw new ConfigurationInvalidException("Device not supported.", element); - } - } - } -} diff --git a/Tests/HA4IoT.Core.Tests/HA4IoT.Core.Tests.csproj b/Tests/HA4IoT.Core.Tests/HA4IoT.Core.Tests.csproj index eb1ffc92..6955bed0 100644 --- a/Tests/HA4IoT.Core.Tests/HA4IoT.Core.Tests.csproj +++ b/Tests/HA4IoT.Core.Tests/HA4IoT.Core.Tests.csproj @@ -99,7 +99,6 @@ UnitTestApp.xaml - diff --git a/Tests/HA4IoT.Core.Tests/ServiceLocatorTests.cs b/Tests/HA4IoT.Core.Tests/ServiceLocatorTests.cs deleted file mode 100644 index 54bf6f48..00000000 --- a/Tests/HA4IoT.Core.Tests/ServiceLocatorTests.cs +++ /dev/null @@ -1,126 +0,0 @@ -using System; -using Windows.Data.Json; -using FluentAssertions; -using HA4IoT.Contracts.Api; -using HA4IoT.Contracts.Core; -using HA4IoT.Contracts.Services; -using HA4IoT.Contracts.Services.Daylight; -using HA4IoT.Contracts.Services.System; -using HA4IoT.Tests.Mockups; -using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; - -namespace HA4IoT.Core.Tests -{ - [TestClass] - public class ServiceLocatorTests - { - [TestMethod] - public void ServiceLocator_RegisterServices() - { - var serviceLocator = new ServiceLocator(); - serviceLocator.RegisterService(typeof(IDaylightService), new TestDaylightService()); - serviceLocator.RegisterService(typeof(IDateTimeService), new TestDateTimeService()); - - serviceLocator.GetServices().Count.ShouldBeEquivalentTo(2); - } - - [TestMethod] - public void ServiceLocator_RegisterServices_Duplicate_Direct() - { - var serviceLocator = new ServiceLocator(); - serviceLocator.RegisterService(typeof(IDaylightService), new TestDaylightService()); - serviceLocator.RegisterService(typeof(IDateTimeService), new TestDateTimeService()); - - try - { - serviceLocator.RegisterService(typeof(IDateTimeService), new DateTimeService()); - - throw new Exception("Exception not thrown."); - } - catch (Exception) - { - // OK! - } - } - - [TestMethod] - public void ServiceLocator_RegisterServices_Duplicate_WithInterface() - { - var serviceLocator = new ServiceLocator(); - serviceLocator.RegisterService(typeof(IDaylightService), new TestDaylightService()); - serviceLocator.RegisterService(typeof(IDateTimeService), new TestDateTimeService()); - - try - { - serviceLocator.RegisterService(typeof(IDateTimeService), new DuplicateDateTimeService()); - - throw new Exception("Exception not thrown."); - } - catch (Exception) - { - // OK! - } - } - - [TestMethod] - public void ServiceLocator_GetServices_Direct() - { - var serviceLocator = new ServiceLocator(); - serviceLocator.RegisterService(typeof(TestDaylightService), new TestDaylightService()); - serviceLocator.RegisterService(typeof(TestDateTimeService), new TestDateTimeService()); - - TestDateTimeService dts; - serviceLocator.TryGetService(out dts).ShouldBeEquivalentTo(true); - } - - [TestMethod] - public void ServiceLocator_TryGetServices_WithInterface() - { - var serviceLocator = new ServiceLocator(); - serviceLocator.RegisterService(typeof(IDaylightService), new TestDaylightService()); - serviceLocator.RegisterService(typeof(IDateTimeService), new TestDateTimeService()); - - IDateTimeService dts; - serviceLocator.TryGetService(out dts).ShouldBeEquivalentTo(true); - } - - [TestMethod] - public void ServiceLocator_GetServices_WithInterface() - { - var serviceLocator = new ServiceLocator(); - serviceLocator.RegisterService(typeof(IDaylightService), new TestDaylightService()); - serviceLocator.RegisterService(typeof(IDateTimeService), new TestDateTimeService()); - - serviceLocator.GetService(); - } - - private class DuplicateDateTimeService : IDateTimeService - { - public JsonObject ExportStatusToJsonObject() - { - throw new NotImplementedException(); - } - - public void HandleApiCommand(IApiContext apiContext) - { - throw new NotImplementedException(); - } - - public void HandleApiRequest(IApiContext apiContext) - { - throw new NotImplementedException(); - } - - public void CompleteRegistration(IServiceLocator serviceLocator) - { - throw new NotImplementedException(); - } - - public DateTime Date { get; set; } - - public TimeSpan Time { get; set; } - - public DateTime Now { get; set; } - } - } -} diff --git a/Tests/HA4IoT.Tests.Mockups/TestButton.cs b/Tests/HA4IoT.Tests.Mockups/TestButton.cs index 77ac22e4..a04f92a1 100644 --- a/Tests/HA4IoT.Tests.Mockups/TestButton.cs +++ b/Tests/HA4IoT.Tests.Mockups/TestButton.cs @@ -1,14 +1,15 @@ using System; using HA4IoT.Contracts.Components; using HA4IoT.Contracts.Core; +using HA4IoT.Contracts.Services.System; using HA4IoT.Sensors.Buttons; namespace HA4IoT.Tests.Mockups { public class TestButton : Button { - public TestButton(ComponentId id, TestButtonEndpoint endpoint, IHomeAutomationTimer timer) - : base(id, endpoint, timer) + public TestButton(ComponentId id, TestButtonEndpoint endpoint, ITimerService timerService) + : base(id, endpoint, timerService) { if (endpoint == null) throw new ArgumentNullException(nameof(endpoint)); diff --git a/Tests/HA4IoT.Tests.Mockups/TestButtonFactory.cs b/Tests/HA4IoT.Tests.Mockups/TestButtonFactory.cs index aadfac87..59403997 100644 --- a/Tests/HA4IoT.Tests.Mockups/TestButtonFactory.cs +++ b/Tests/HA4IoT.Tests.Mockups/TestButtonFactory.cs @@ -1,23 +1,24 @@ using System; using HA4IoT.Contracts.Components; using HA4IoT.Contracts.Core; +using HA4IoT.Contracts.Services.System; namespace HA4IoT.Tests.Mockups { public class TestButtonFactory { - private readonly IHomeAutomationTimer _timer; + private readonly ITimerService _timerService; - public TestButtonFactory(IHomeAutomationTimer timer) + public TestButtonFactory(ITimerService timerService) { - if (timer == null) throw new ArgumentNullException(nameof(timer)); + if (timerService == null) throw new ArgumentNullException(nameof(timerService)); - _timer = timer; + _timerService = timerService; } public TestButton CreateTestButton() { - return new TestButton(ComponentIdFactory.EmptyId, new TestButtonEndpoint(), _timer); + return new TestButton(ComponentIdFactory.EmptyId, new TestButtonEndpoint(), _timerService); } } } \ No newline at end of file diff --git a/Tests/HA4IoT.Tests.Mockups/TestController.cs b/Tests/HA4IoT.Tests.Mockups/TestController.cs index a86b3de7..24f84673 100644 --- a/Tests/HA4IoT.Tests.Mockups/TestController.cs +++ b/Tests/HA4IoT.Tests.Mockups/TestController.cs @@ -16,12 +16,12 @@ public TestController() : base(22) { Log.Instance = new TestLogger(); - Timer = new TestHomeAutomationTimer(); + TimerService = new TestTimerService(); ServiceLocator.RegisterService(typeof(IDaylightService), new TestDaylightService()); ServiceLocator.RegisterService(typeof(IDateTimeService), _dateTimeService); ServiceLocator.RegisterService(typeof(ISystemInformationService), new SystemInformationService()); - ServiceLocator.RegisterService(typeof(ISchedulerService), new SchedulerService(Timer)); + ServiceLocator.RegisterService(typeof(ISchedulerService), new SchedulerService(TimerService)); } public void SetTime(TimeSpan value) diff --git a/Tests/HA4IoT.Tests.Mockups/TestHomeAutomationTimer.cs b/Tests/HA4IoT.Tests.Mockups/TestHomeAutomationTimer.cs index 59d8df3c..41692d15 100644 --- a/Tests/HA4IoT.Tests.Mockups/TestHomeAutomationTimer.cs +++ b/Tests/HA4IoT.Tests.Mockups/TestHomeAutomationTimer.cs @@ -1,9 +1,10 @@ using System; using HA4IoT.Contracts.Core; +using HA4IoT.Contracts.Services.System; namespace HA4IoT.Tests.Mockups { - public class TestHomeAutomationTimer : IHomeAutomationTimer + public class TestTimerService : ITimerService { public event EventHandler Tick; diff --git a/Tests/HA4IoT.Tests.Mockups/TestHttpRequestController.cs b/Tests/HA4IoT.Tests.Mockups/TestHttpRequestController.cs index 00aeb185..5dafc531 100644 --- a/Tests/HA4IoT.Tests.Mockups/TestHttpRequestController.cs +++ b/Tests/HA4IoT.Tests.Mockups/TestHttpRequestController.cs @@ -6,7 +6,7 @@ namespace HA4IoT.Tests.Mockups { - public class TestHttpRequestController : IHttpRequestController, IApiController + public class TestHttpRequestController : IHttpRequestController, IApiService { public IHttpRequestDispatcherAction HandleGet(string uri) { diff --git a/Tests/HA4IoT.Tests.Mockups/TestI2CBus.cs b/Tests/HA4IoT.Tests.Mockups/TestI2CBus.cs index bfae0975..1335f794 100644 --- a/Tests/HA4IoT.Tests.Mockups/TestI2CBus.cs +++ b/Tests/HA4IoT.Tests.Mockups/TestI2CBus.cs @@ -1,10 +1,11 @@ using System; using HA4IoT.Contracts.Api; using HA4IoT.Contracts.Hardware; +using HA4IoT.Contracts.Services.System; namespace HA4IoT.Tests.Mockups { - public class TestI2CBus : II2CBus + public class TestI2CBus : II2CBusService { public TestI2CBus(DeviceId deviceId) { diff --git a/Tests/HA4IoT.Tests.Mockups/TestRollerShutter.cs b/Tests/HA4IoT.Tests.Mockups/TestRollerShutter.cs index d9b4365b..871e43df 100644 --- a/Tests/HA4IoT.Tests.Mockups/TestRollerShutter.cs +++ b/Tests/HA4IoT.Tests.Mockups/TestRollerShutter.cs @@ -3,13 +3,14 @@ using HA4IoT.Contracts.Components; using HA4IoT.Contracts.Core; using HA4IoT.Contracts.Services; +using HA4IoT.Contracts.Services.System; namespace HA4IoT.Tests.Mockups { public class TestRollerShutter : RollerShutter { - public TestRollerShutter(ComponentId id, TestRollerShutterEndpoint endpoint, IHomeAutomationTimer timer, ISchedulerService schedulerService) - : base(id, endpoint, timer, schedulerService) + public TestRollerShutter(ComponentId id, TestRollerShutterEndpoint endpoint, ITimerService timerService, ISchedulerService schedulerService) + : base(id, endpoint, timerService, schedulerService) { if (endpoint == null) throw new ArgumentNullException(nameof(endpoint)); diff --git a/Tests/HA4IoT.Tests.Mockups/TestRollerShutterFactory.cs b/Tests/HA4IoT.Tests.Mockups/TestRollerShutterFactory.cs index e2c99f6c..f49365f1 100644 --- a/Tests/HA4IoT.Tests.Mockups/TestRollerShutterFactory.cs +++ b/Tests/HA4IoT.Tests.Mockups/TestRollerShutterFactory.cs @@ -1,6 +1,7 @@ using System; using HA4IoT.Contracts.Components; using HA4IoT.Contracts.Core; +using HA4IoT.Contracts.Services.System; using HA4IoT.Core; using HA4IoT.Core.Scheduling; @@ -8,18 +9,18 @@ namespace HA4IoT.Tests.Mockups { public class TestRollerShutterFactory { - private readonly IHomeAutomationTimer _timer; + private readonly ITimerService _timerService; - public TestRollerShutterFactory(IHomeAutomationTimer timer) + public TestRollerShutterFactory(ITimerService timerService) { - if (timer == null) throw new ArgumentNullException(nameof(timer)); + if (timerService == null) throw new ArgumentNullException(nameof(timerService)); - _timer = timer; + _timerService = timerService; } public TestRollerShutter CreateTestRollerShutter() { - return new TestRollerShutter(ComponentIdFactory.EmptyId, new TestRollerShutterEndpoint(), _timer, new SchedulerService(_timer)); + return new TestRollerShutter(ComponentIdFactory.EmptyId, new TestRollerShutterEndpoint(), _timerService, new SchedulerService(_timerService)); } } } \ No newline at end of file From ac5f24c6ffe087b2cc4a1b5d2b7af90c99b7e49c Mon Sep 17 00:00:00 2001 From: Christian Kratky Date: Sun, 14 Aug 2016 19:16:44 +0200 Subject: [PATCH 05/61] Service refactoring --- .../HA4IoT.Controller.Local.csproj | 2 +- .../{Controller.cs => Initializer.cs} | 14 +- .../HA4IoT.Controller.Local/MainPage.xaml.cs | 8 +- .../HA4IoT.Controller.Main/Controller.cs | 43 ----- .../HA4IoT.Controller.Main.csproj | 1 - .../Rooms/BedroomConfiguration.cs | 71 +++++--- .../Rooms/ChildrensRoomConfiguration.cs | 42 +++-- .../Rooms/FloorConfiguration.cs | 97 ++++++----- .../Rooms/KitchenConfiguration.cs | 41 +++-- .../Rooms/LivingRoomConfiguration.cs | 53 +++--- .../Rooms/LowerBathroomConfiguration.cs | 25 ++- .../Rooms/OfficeConfiguration.cs | 49 +++--- .../Rooms/ReadingRoomConfiguration.cs | 45 ++++-- .../Rooms/StoreroomConfiguration.cs | 49 ++++-- .../Rooms/UpperBathroomConfiguration.cs | 23 ++- .../HA4IoT.Controller.Main/StartupTask.cs | 21 ++- HA4IoT.sln | 4 +- .../OpenWeatherMapService.cs | 9 +- SDK/HA4IoT.Actuators/ActuatorFactory.cs | 66 ++++++++ .../LogicalBinaryStateActuatorExtensions.cs | 18 --- SDK/HA4IoT.Actuators/HA4IoT.Actuators.csproj | 6 +- .../RollerShutters/RollerShutter.cs | 9 +- .../RollerShutters/RollerShutterExtensions.cs | 20 +-- .../Sockets/SocketExtensions.cs | 14 +- .../StateMachines/StateMachine.cs | 7 +- SDK/HA4IoT.Automations/AutomationBase.cs | 2 +- SDK/HA4IoT.Automations/AutomationFactory.cs | 87 ++++++++++ SDK/HA4IoT.Automations/AutomationIdFactory.cs | 1 - .../ConditionalOnAutomationExtensions.cs | 27 ---- .../HA4IoT.Automations.csproj | 11 +- .../RollerShutterAutomation.cs | 26 +-- .../RollerShutterAutomationExtensions.cs | 24 --- .../TurnOnAndOffAutomationExtensions.cs | 25 --- SDK/HA4IoT.Components/ComponentBase.cs | 9 +- .../HA4IoT.Components.csproj | 4 + SDK/HA4IoT.Contracts/Areas/IArea.cs | 9 +- .../Automations/IAutomationService.cs | 2 +- SDK/HA4IoT.Contracts/Components/IComponent.cs | 4 +- .../ConfigurationInvalidException.cs | 15 -- .../HandleConfigurationNodeResult.cs | 9 -- .../Configuration/IConfigurationExtender.cs | 29 ---- SDK/HA4IoT.Contracts/Core/IController.cs | 9 -- ...{IInitializer.cs => IHA4IoTInitializer.cs} | 4 +- SDK/HA4IoT.Contracts/HA4IoT.Contracts.csproj | 13 +- SDK/HA4IoT.Contracts/Hardware/IDevice.cs | 4 +- .../Services/Daylight/IDaylightService.cs | 2 +- .../Services/IApiExposedService.cs | 12 ++ .../Services/ISchedulerService.cs | 2 +- SDK/HA4IoT.Contracts/Services/IService.cs | 17 -- .../IOutdoorHumidityService.cs | 2 +- .../IOutdoorTemperatureService.cs | 2 +- SDK/HA4IoT.Contracts/Services/ServiceBase.cs | 18 +-- .../Services/System/IContainerService.cs | 7 +- .../Services/System/IDateTimeService.cs | 2 +- .../Services/System/IDeviceService.cs | 2 +- .../Services/System/II2CBusService.cs | 2 +- .../System/ISystemInformationService.cs | 2 +- .../Services/Weather/IWeatherService.cs | 2 +- SDK/HA4IoT.Contracts/project.json | 3 +- SDK/HA4IoT.Core/ControllerApiDispatcher.cs | 59 ++++--- SDK/HA4IoT.Core/ControllerOptions.cs | 7 + SDK/HA4IoT.Core/DiscoveryServer.cs | 22 +-- SDK/HA4IoT.Core/HA4IoT.Core.csproj | 23 ++- ...{ControllerBase.cs => HA4IoTController.cs} | 152 +++++++++--------- SDK/HA4IoT.Logger/UdpLogger.cs | 6 +- SDK/HA4IoT.PersonalAgent/SynonymService.cs | 5 +- SDK/HA4IoT.Sensors/Buttons/Button.cs | 19 ++- .../Buttons/ButtonExtensions.cs | 56 ------- SDK/HA4IoT.Sensors/HA4IoT.Sensors.csproj | 5 +- .../MotionDetectors/MotionDetector.cs | 4 +- .../MotionDetectorExtensions.cs | 16 -- SDK/HA4IoT.Sensors/SensorFactory.cs | 97 +++++++++++ SDK/HA4IoT.Services/Areas/Area.cs | 22 ++- SDK/HA4IoT.Services/Areas/AreaService.cs | 11 +- .../ControllerSlave/ControllerSlaveService.cs | 4 +- .../Environment/DaylightService.cs | 4 +- .../Environment/OutdoorTemperatureService.cs | 4 +- .../Environment/OutdootHumidityService.cs | 4 +- .../Environment/WeatherService.cs | 4 +- SDK/HA4IoT.Services/HA4IoT.Services.csproj | 4 + SDK/HA4IoT.Services/Health/HealthService.cs | 4 +- .../Scheduling/SchedulerService.cs | 4 +- .../System/ContainerService.cs | 9 +- SDK/HA4IoT.Services/System/DateTimeService.cs | 2 +- .../System/SystemInformationService.cs | 2 +- SDK/HA4IoT.Settings/ControllerSettings.cs | 58 +++++++ SDK/HA4IoT.Settings/HA4IoT.Settings.csproj | 7 + SDK/HA4IoT.Settings/SettingsContainer.cs | 2 + .../SettingsContainerApiDispatcher.cs | 2 + .../CCToolsBoardBase.cs | 37 +++-- .../HA4IoT.Hardware.I2CHardwareBridge.csproj | 1 - .../I2CHardwareBridge.cs | 12 +- .../I2CHardwareBridgeConfigurationExtender.cs | 72 --------- .../HA4IoT.Hardware/BuiltInI2CBusService.cs | 3 +- .../AutomaticTurnOnAndOffAutomationTests.cs | 3 +- .../HA4IoT.Actuators.Tests.csproj | 4 + .../RollerShutterTests.cs | 5 +- .../AutomationTests.cs | 4 +- .../ConditionalOnAutomationTests.cs | 6 +- .../RollerShutterAutomationTests.cs | 15 +- .../ConfigurationParserTests.cs | 134 --------------- .../HA4IoT.Configuration.Tests.csproj | 6 +- .../SettingsTests.cs | 2 +- .../TestConfiguration.cs | 16 -- .../CCToolsTests.cs | 32 ++-- .../MessageContextTests.cs | 12 +- .../HA4IoT.Tests.Mockups.csproj | 10 +- Tests/HA4IoT.Tests.Mockups/TestController.cs | 32 ++-- .../TestDateTimeService.cs | 7 +- .../TestHomeAutomationTimer.cs | 6 +- .../{TestI2CBus.cs => TestI2CBusService.cs} | 21 +-- .../TestRollerShutterFactory.cs | 15 +- 112 files changed, 1119 insertions(+), 1080 deletions(-) rename Controllers/HA4IoT.Controller.Local/{Controller.cs => Initializer.cs} (91%) delete mode 100644 Controllers/HA4IoT.Controller.Main/Controller.cs create mode 100644 SDK/HA4IoT.Actuators/ActuatorFactory.cs delete mode 100644 SDK/HA4IoT.Actuators/BinaryStateActuators/LogicalBinaryStateActuatorExtensions.cs create mode 100644 SDK/HA4IoT.Automations/AutomationFactory.cs delete mode 100644 SDK/HA4IoT.Automations/ConditionalOnAutomationExtensions.cs delete mode 100644 SDK/HA4IoT.Automations/TurnOnAndOffAutomationExtensions.cs delete mode 100644 SDK/HA4IoT.Contracts/Configuration/ConfigurationInvalidException.cs delete mode 100644 SDK/HA4IoT.Contracts/Configuration/HandleConfigurationNodeResult.cs delete mode 100644 SDK/HA4IoT.Contracts/Configuration/IConfigurationExtender.cs delete mode 100644 SDK/HA4IoT.Contracts/Core/IController.cs rename SDK/HA4IoT.Contracts/Core/{IInitializer.cs => IHA4IoTInitializer.cs} (65%) create mode 100644 SDK/HA4IoT.Contracts/Services/IApiExposedService.cs delete mode 100644 SDK/HA4IoT.Contracts/Services/IService.cs create mode 100644 SDK/HA4IoT.Core/ControllerOptions.cs rename SDK/HA4IoT.Core/{ControllerBase.cs => HA4IoTController.cs} (79%) create mode 100644 SDK/HA4IoT.Sensors/SensorFactory.cs create mode 100644 SDK/HA4IoT.Settings/ControllerSettings.cs delete mode 100644 SDK/Hardware/HA4IoT.Hardware.I2CHardwareBridge/I2CHardwareBridgeConfigurationExtender.cs delete mode 100644 Tests/HA4IoT.Configuration.Tests/ConfigurationParserTests.cs delete mode 100644 Tests/HA4IoT.Configuration.Tests/TestConfiguration.cs rename Tests/HA4IoT.Tests.Mockups/{TestI2CBus.cs => TestI2CBusService.cs} (51%) diff --git a/Controllers/HA4IoT.Controller.Local/HA4IoT.Controller.Local.csproj b/Controllers/HA4IoT.Controller.Local/HA4IoT.Controller.Local.csproj index 624c0da5..7ca051da 100644 --- a/Controllers/HA4IoT.Controller.Local/HA4IoT.Controller.Local.csproj +++ b/Controllers/HA4IoT.Controller.Local/HA4IoT.Controller.Local.csproj @@ -96,7 +96,7 @@ App.xaml - + MainPage.xaml diff --git a/Controllers/HA4IoT.Controller.Local/Controller.cs b/Controllers/HA4IoT.Controller.Local/Initializer.cs similarity index 91% rename from Controllers/HA4IoT.Controller.Local/Controller.cs rename to Controllers/HA4IoT.Controller.Local/Initializer.cs index d22b45cb..ad93a8ab 100644 --- a/Controllers/HA4IoT.Controller.Local/Controller.cs +++ b/Controllers/HA4IoT.Controller.Local/Initializer.cs @@ -8,26 +8,30 @@ using HA4IoT.Contracts.Actuators; using HA4IoT.Contracts.Areas; using HA4IoT.Contracts.Components; +using HA4IoT.Contracts.Core; using HA4IoT.Contracts.Sensors; +using HA4IoT.Contracts.Services.Daylight; using HA4IoT.Contracts.Services.System; -using HA4IoT.Core; using HA4IoT.Hardware.Knx; namespace HA4IoT.Controller.Local { - public class Controller : ControllerBase + public class Initializer : IHA4IoTInitializer { private readonly MainPage _mainPage; - public Controller(MainPage mainPage) - : base(null) + public Initializer(MainPage mainPage) { if (mainPage == null) throw new ArgumentNullException(nameof(mainPage)); _mainPage = mainPage; } - protected override async Task ConfigureAsync(IContainerService factoryService) + public void RegisterServices(IContainerService containerService) + { + } + + public async Task Configure(IContainerService factoryService) { var areaService = factoryService.GetInstance(); var timerService = factoryService.GetInstance(); diff --git a/Controllers/HA4IoT.Controller.Local/MainPage.xaml.cs b/Controllers/HA4IoT.Controller.Local/MainPage.xaml.cs index 53e62320..dda75c64 100644 --- a/Controllers/HA4IoT.Controller.Local/MainPage.xaml.cs +++ b/Controllers/HA4IoT.Controller.Local/MainPage.xaml.cs @@ -7,12 +7,13 @@ using HA4IoT.Contracts.Core; using HA4IoT.Contracts.Logging; using HA4IoT.Contracts.Sensors; +using HA4IoT.Core; namespace HA4IoT.Controller.Local { public sealed partial class MainPage { - private readonly Controller _controller; + private readonly Core.HA4IoTController _controller; public MainPage() { @@ -20,7 +21,8 @@ public MainPage() Log.Instance = new TextBoxLogger(LogTextBox); - _controller = new Controller(this); + _controller = new Core.HA4IoTController(new ControllerOptions()); + _controller.Initializer = new Initializer(this); // The app is only available from other machines. https://msdn.microsoft.com/en-us/library/windows/apps/Hh780593.aspx StoragePathTextBox.Text = StoragePath.Root; @@ -48,7 +50,7 @@ await Dispatcher.RunAsync( return result; } - + public async Task CreateDemoButton(string caption) { IButtonEndpoint result = null; diff --git a/Controllers/HA4IoT.Controller.Main/Controller.cs b/Controllers/HA4IoT.Controller.Main/Controller.cs deleted file mode 100644 index 6994f9ad..00000000 --- a/Controllers/HA4IoT.Controller.Main/Controller.cs +++ /dev/null @@ -1,43 +0,0 @@ -using System.Threading.Tasks; -using HA4IoT.Contracts.Core; -using HA4IoT.Contracts.Hardware; -using HA4IoT.Contracts.Logging; -using HA4IoT.Controller.Main.Rooms; -using HA4IoT.Core; -using HA4IoT.ExternalServices.OpenWeatherMap; -using HA4IoT.ExternalServices.TelegramBot; -using HA4IoT.ExternalServices.Twitter; -using HA4IoT.Hardware; -using HA4IoT.Hardware.CCTools; -using HA4IoT.Hardware.I2CHardwareBridge; -using HA4IoT.Hardware.Pi2; -using HA4IoT.Hardware.RemoteSwitch; -using HA4IoT.Hardware.RemoteSwitch.Codes; -using HA4IoT.Contracts.PersonalAgent; -using HA4IoT.Contracts.Services; -using HA4IoT.Contracts.Services.Daylight; -using HA4IoT.Contracts.Services.OutdoorHumidity; -using HA4IoT.Contracts.Services.OutdoorTemperature; -using HA4IoT.Contracts.Services.System; -using HA4IoT.Contracts.Services.Weather; -using HA4IoT.PersonalAgent; -using HA4IoT.Services.ControllerSlave; -using HA4IoT.Services.Environment; - -namespace HA4IoT.Controller.Main -{ - internal class Controller : ControllerBase - { - private const int LedGpio = 22; - - public Controller() - : base(LedGpio) - { - } - - protected override async Task ConfigureAsync(IContainerService factoryService) - { - await base.ConfigureAsync(); - } - } -} diff --git a/Controllers/HA4IoT.Controller.Main/HA4IoT.Controller.Main.csproj b/Controllers/HA4IoT.Controller.Main/HA4IoT.Controller.Main.csproj index 449bd17e..436f5104 100644 --- a/Controllers/HA4IoT.Controller.Main/HA4IoT.Controller.Main.csproj +++ b/Controllers/HA4IoT.Controller.Main/HA4IoT.Controller.Main.csproj @@ -101,7 +101,6 @@ - diff --git a/Controllers/HA4IoT.Controller.Main/Rooms/BedroomConfiguration.cs b/Controllers/HA4IoT.Controller.Main/Rooms/BedroomConfiguration.cs index afb72871..dc4f9627 100644 --- a/Controllers/HA4IoT.Controller.Main/Rooms/BedroomConfiguration.cs +++ b/Controllers/HA4IoT.Controller.Main/Rooms/BedroomConfiguration.cs @@ -1,9 +1,9 @@ using System; +using HA4IoT.Actuators; using HA4IoT.Actuators.BinaryStateActuators; using HA4IoT.Actuators.Connectors; using HA4IoT.Actuators.Lamps; using HA4IoT.Actuators.RollerShutters; -using HA4IoT.Actuators.Sockets; using HA4IoT.Actuators.StateMachines; using HA4IoT.Automations; using HA4IoT.Contracts.Areas; @@ -14,6 +14,7 @@ using HA4IoT.Hardware.CCTools; using HA4IoT.Hardware.I2CHardwareBridge; using HA4IoT.PersonalAgent; +using HA4IoT.Sensors; using HA4IoT.Sensors.Buttons; using HA4IoT.Sensors.HumiditySensors; using HA4IoT.Sensors.MotionDetectors; @@ -31,6 +32,9 @@ internal class BedroomConfiguration private readonly IDaylightService _daylightService; private readonly CCToolsBoardService _ccToolsBoardService; private readonly SynonymService _synonymService; + private readonly ActuatorFactory _actuatorFactory; + private readonly SensorFactory _sensorFactory; + private readonly AutomationFactory _automationFactory; private enum Bedroom { @@ -81,19 +85,28 @@ public BedroomConfiguration( IAreaService areaService, IDaylightService daylightService, CCToolsBoardService ccToolsBoardService, - SynonymService synonymService) + SynonymService synonymService, + ActuatorFactory actuatorFactory, + SensorFactory sensorFactory, + AutomationFactory automationFactory) { if (deviceService == null) throw new ArgumentNullException(nameof(deviceService)); if (areaService == null) throw new ArgumentNullException(nameof(areaService)); if (daylightService == null) throw new ArgumentNullException(nameof(daylightService)); if (ccToolsBoardService == null) throw new ArgumentNullException(nameof(ccToolsBoardService)); if (synonymService == null) throw new ArgumentNullException(nameof(synonymService)); + if (actuatorFactory == null) throw new ArgumentNullException(nameof(actuatorFactory)); + if (sensorFactory == null) throw new ArgumentNullException(nameof(sensorFactory)); + if (automationFactory == null) throw new ArgumentNullException(nameof(automationFactory)); _deviceService = deviceService; _areaService = areaService; _daylightService = daylightService; _ccToolsBoardService = ccToolsBoardService; _synonymService = synonymService; + _actuatorFactory = actuatorFactory; + _sensorFactory = sensorFactory; + _automationFactory = automationFactory; } public void Setup() @@ -109,39 +122,47 @@ public void Setup() var room = _areaService.CreateArea(Room.Bedroom) .WithTemperatureSensor(Bedroom.TemperatureSensor, i2CHardwareBridge.DHT22Accessor.GetTemperatureSensor(SensorPin)) .WithHumiditySensor(Bedroom.HumiditySensor, i2CHardwareBridge.DHT22Accessor.GetHumiditySensor(SensorPin)) - .WithMotionDetector(Bedroom.MotionDetector, input5.GetInput(12)) .WithLamp(Bedroom.LightCeiling, hsrel5.GetOutput(5).WithInvertedState()) .WithLamp(Bedroom.LightCeilingWindow, hsrel5.GetOutput(6).WithInvertedState()) .WithLamp(Bedroom.LightCeilingWall, hsrel5.GetOutput(7).WithInvertedState()) - .WithSocket(Bedroom.SocketWindowLeft, hsrel5.GetOutput(0)) - .WithSocket(Bedroom.SocketWindowRight, hsrel5.GetOutput(1)) - .WithSocket(Bedroom.SocketWall, hsrel5.GetOutput(2)) - .WithSocket(Bedroom.SocketWallEdge, hsrel5.GetOutput(3)) - .WithSocket(Bedroom.SocketBedLeft, hsrel8.GetOutput(7)) - .WithSocket(Bedroom.SocketBedRight, hsrel8.GetOutput(9)) .WithLamp(Bedroom.LampBedLeft, hsrel5.GetOutput(4)) .WithLamp(Bedroom.LampBedRight, hsrel8.GetOutput(8).WithInvertedState()) - .WithButton(Bedroom.ButtonDoor, input5.GetInput(11)) - .WithButton(Bedroom.ButtonWindowUpper, input5.GetInput(10)) - .WithButton(Bedroom.ButtonWindowLower, input5.GetInput(13)) - .WithButton(Bedroom.ButtonBedLeftInner, input4.GetInput(2)) - .WithButton(Bedroom.ButtonBedLeftOuter, input4.GetInput(0)) - .WithButton(Bedroom.ButtonBedRightInner, input4.GetInput(1)) - .WithButton(Bedroom.ButtonBedRightOuter, input4.GetInput(3)) - .WithRollerShutter(Bedroom.RollerShutterLeft, hsrel8.GetOutput(6), hsrel8.GetOutput(5)) - .WithRollerShutter(Bedroom.RollerShutterRight, hsrel8.GetOutput(3), hsrel8.GetOutput(4)) - .WithRollerShutterButtons(Bedroom.RollerShutterButtonsUpperUp, input5.GetInput(6), Bedroom.RollerShutterButtonsUpperDown, input5.GetInput(7)) - .WithRollerShutterButtons(Bedroom.RollerShutterButtonsLowerUp, input5.GetInput(4), Bedroom.RollerShutterButtonsLowerDown, input5.GetInput(5)) .WithWindow(Bedroom.WindowLeft, w => w.WithCenterCasement(input5.GetInput(2))) .WithWindow(Bedroom.WindowRight, w => w.WithCenterCasement(input5.GetInput(3))); + _sensorFactory.RegisterMotionDetector(room, Bedroom.MotionDetector, input5.GetInput(12)); + + _sensorFactory.RegisterButton(room, Bedroom.ButtonWindowUpper, input5.GetInput(10)); + _sensorFactory.RegisterButton(room, Bedroom.ButtonWindowLower, input5.GetInput(13)); + _sensorFactory.RegisterButton(room, Bedroom.ButtonBedLeftInner, input4.GetInput(2)); + _sensorFactory.RegisterButton(room, Bedroom.ButtonBedLeftOuter, input4.GetInput(0)); + _sensorFactory.RegisterButton(room, Bedroom.ButtonBedRightInner, input4.GetInput(1)); + _sensorFactory.RegisterButton(room, Bedroom.ButtonBedRightOuter, input4.GetInput(3)); + _sensorFactory.RegisterButton(room, Bedroom.ButtonDoor, input5.GetInput(11)); + + _sensorFactory.RegisterRollerShutterButtons(room, Bedroom.RollerShutterButtonsUpperUp, input5.GetInput(6), + Bedroom.RollerShutterButtonsUpperDown, input5.GetInput(7)); + + _sensorFactory.RegisterRollerShutterButtons(room, Bedroom.RollerShutterButtonsLowerUp, input5.GetInput(4), + Bedroom.RollerShutterButtonsLowerDown, input5.GetInput(5)); + + _actuatorFactory.RegisterSocket(room, Bedroom.SocketWindowLeft, hsrel5[HSREL5Pin.Relay0]); + _actuatorFactory.RegisterSocket(room, Bedroom.SocketWindowRight, hsrel5[HSREL5Pin.Relay1]); + _actuatorFactory.RegisterSocket(room, Bedroom.SocketWall, hsrel5[HSREL5Pin.Relay2]); + _actuatorFactory.RegisterSocket(room, Bedroom.SocketWallEdge, hsrel5[HSREL5Pin.Relay3]); + _actuatorFactory.RegisterSocket(room, Bedroom.SocketBedLeft, hsrel8.GetOutput(7)); + _actuatorFactory.RegisterSocket(room, Bedroom.SocketBedRight, hsrel8.GetOutput(9)); + + _actuatorFactory.RegisterRollerShutter(room, Bedroom.RollerShutterLeft, hsrel8[HSREL8Pin.Relay6], hsrel8[HSREL8Pin.Relay5]); + _actuatorFactory.RegisterRollerShutter(room, Bedroom.RollerShutterRight, hsrel8[HSREL8Pin.Relay3], hsrel8[HSREL8Pin.Relay4]); + room.GetRollerShutter(Bedroom.RollerShutterLeft) .ConnectWith(room.GetButton(Bedroom.RollerShutterButtonsUpperUp), room.GetButton(Bedroom.RollerShutterButtonsUpperDown)); room.GetRollerShutter(Bedroom.RollerShutterRight) .ConnectWith(room.GetButton(Bedroom.RollerShutterButtonsLowerUp), room.GetButton(Bedroom.RollerShutterButtonsLowerDown)); - room.CombineActuators(Bedroom.CombinedCeilingLights) + _actuatorFactory.RegisterLogicalActuator(room, Bedroom.CombinedCeilingLights) .WithActuator(room.GetLamp(Bedroom.LightCeilingWall)) .WithActuator(room.GetLamp(Bedroom.LightCeilingWindow)) .ConnectToggleActionWith(room.GetButton(Bedroom.ButtonDoor)) @@ -154,22 +175,22 @@ public void Setup() room.GetStateMachine(Bedroom.CombinedCeilingLights).TryTurnOff(); }); - room.SetupRollerShutterAutomation() + _automationFactory.RegisterRollerShutterAutomation(room) .WithRollerShutters(room.GetRollerShutters()) .WithDoNotOpenBefore(TimeSpan.FromHours(7).Add(TimeSpan.FromMinutes(15))) .WithCloseIfOutsideTemperatureIsGreaterThan(24) .WithDoNotOpenIfOutsideTemperatureIsBelowThan(3); - room.SetupTurnOnAndOffAutomation() + _automationFactory.RegisterTurnOnAndOffAutomation(room) .WithTrigger(room.GetMotionDetector(Bedroom.MotionDetector)) .WithTarget(room.GetStateMachine(Bedroom.LightCeiling)) .WithOnDuration(TimeSpan.FromSeconds(15)) .WithTurnOnIfAllRollerShuttersClosed(room.GetRollerShutter(Bedroom.RollerShutterLeft), room.GetRollerShutter(Bedroom.RollerShutterRight)) .WithEnabledAtNight(_daylightService) .WithSkipIfAnyActuatorIsAlreadyOn(room.GetLamp(Bedroom.LampBedLeft), room.GetLamp(Bedroom.LampBedRight)); - + room.WithStateMachine(Bedroom.Fan, (s, r) => SetupFan(s, r, hsrel8)); - + room.GetButton(Bedroom.ButtonBedLeftInner).WithPressedShortlyAction(() => room.GetLamp(Bedroom.LampBedLeft).SetNextState()); room.GetButton(Bedroom.ButtonBedLeftInner).WithPressedLongAction(() => room.GetStateMachine(Bedroom.CombinedCeilingLights).SetNextState()); room.GetButton(Bedroom.ButtonBedLeftOuter).WithPressedShortlyAction(() => room.GetStateMachine(Bedroom.Fan).SetNextState()); diff --git a/Controllers/HA4IoT.Controller.Main/Rooms/ChildrensRoomConfiguration.cs b/Controllers/HA4IoT.Controller.Main/Rooms/ChildrensRoomConfiguration.cs index 5be24e1b..f799b5b6 100644 --- a/Controllers/HA4IoT.Controller.Main/Rooms/ChildrensRoomConfiguration.cs +++ b/Controllers/HA4IoT.Controller.Main/Rooms/ChildrensRoomConfiguration.cs @@ -1,8 +1,8 @@ using System; +using HA4IoT.Actuators; using HA4IoT.Actuators.Connectors; using HA4IoT.Actuators.Lamps; using HA4IoT.Actuators.RollerShutters; -using HA4IoT.Actuators.Sockets; using HA4IoT.Automations; using HA4IoT.Contracts.Areas; using HA4IoT.Contracts.Hardware; @@ -10,6 +10,7 @@ using HA4IoT.Hardware.CCTools; using HA4IoT.Hardware.I2CHardwareBridge; using HA4IoT.PersonalAgent; +using HA4IoT.Sensors; using HA4IoT.Sensors.Buttons; using HA4IoT.Sensors.HumiditySensors; using HA4IoT.Sensors.TemperatureSensors; @@ -25,6 +26,9 @@ internal class ChildrensRoomRoomConfiguration private readonly SynonymService _synonymService; private readonly IDeviceService _deviceService; private readonly CCToolsBoardService _ccToolsBoardService; + private readonly AutomationFactory _automationFactory; + private readonly ActuatorFactory _actuatorFactory; + private readonly SensorFactory _sensorFactory; private enum ChildrensRoom { @@ -47,20 +51,29 @@ private enum ChildrensRoom } public ChildrensRoomRoomConfiguration( - IAreaService areaService, + IAreaService areaService, SynonymService synonymService, - IDeviceService deviceService, - CCToolsBoardService ccToolsBoardService) + IDeviceService deviceService, + CCToolsBoardService ccToolsBoardService, + AutomationFactory automationFactory, + ActuatorFactory actuatorFactory, + SensorFactory sensorFactory) { if (areaService == null) throw new ArgumentNullException(nameof(areaService)); if (synonymService == null) throw new ArgumentNullException(nameof(synonymService)); if (deviceService == null) throw new ArgumentNullException(nameof(deviceService)); if (ccToolsBoardService == null) throw new ArgumentNullException(nameof(ccToolsBoardService)); + if (automationFactory == null) throw new ArgumentNullException(nameof(automationFactory)); + if (actuatorFactory == null) throw new ArgumentNullException(nameof(actuatorFactory)); + if (sensorFactory == null) throw new ArgumentNullException(nameof(sensorFactory)); _areaService = areaService; _synonymService = synonymService; _deviceService = deviceService; _ccToolsBoardService = ccToolsBoardService; + _automationFactory = automationFactory; + _actuatorFactory = actuatorFactory; + _sensorFactory = sensorFactory; } public void Setup() @@ -75,17 +88,22 @@ public void Setup() .WithTemperatureSensor(ChildrensRoom.TemperatureSensor, i2CHardwareBridge.DHT22Accessor.GetTemperatureSensor(SensorPin)) .WithHumiditySensor(ChildrensRoom.HumiditySensor, i2CHardwareBridge.DHT22Accessor.GetHumiditySensor(SensorPin)) .WithLamp(ChildrensRoom.LightCeilingMiddle, hsrel5[HSREL5Pin.GPIO0]) - .WithRollerShutter(ChildrensRoom.RollerShutter, hsrel5[HSREL5Pin.Relay4], hsrel5[HSREL5Pin.Relay3]) - .WithSocket(ChildrensRoom.SocketWindow, hsrel5[HSREL5Pin.Relay0]) - .WithSocket(ChildrensRoom.SocketWallLeft, hsrel5[HSREL5Pin.Relay1]) - .WithSocket(ChildrensRoom.SocketWallRight, hsrel5[HSREL5Pin.Relay2]) - .WithButton(ChildrensRoom.Button, input0.GetInput(0)) - .WithWindow(ChildrensRoom.Window, w => w.WithCenterCasement(input0.GetInput(5), input0.GetInput(4))) - .WithRollerShutterButtons(ChildrensRoom.RollerShutterButtonUp, input0.GetInput(1), ChildrensRoom.RollerShutterButtonDown, input0.GetInput(2)); + .WithWindow(ChildrensRoom.Window, w => w.WithCenterCasement(input0.GetInput(5), input0.GetInput(4))); + + _actuatorFactory.RegisterSocket(room, ChildrensRoom.SocketWindow, hsrel5[HSREL5Pin.Relay0]); + _actuatorFactory.RegisterSocket(room, ChildrensRoom.SocketWallLeft, hsrel5[HSREL5Pin.Relay1]); + _actuatorFactory.RegisterSocket(room, ChildrensRoom.SocketWallRight, hsrel5[HSREL5Pin.Relay2]); + + _sensorFactory.RegisterButton(room, ChildrensRoom.Button, input0.GetInput(0)); + + _actuatorFactory.RegisterRollerShutter(room, ChildrensRoom.RollerShutter, hsrel5[HSREL5Pin.Relay4], hsrel5[HSREL5Pin.Relay3]); + _sensorFactory.RegisterRollerShutterButtons(room, ChildrensRoom.RollerShutterButtonUp, input0.GetInput(1), ChildrensRoom.RollerShutterButtonDown, input0.GetInput(2)); room.GetLamp(ChildrensRoom.LightCeilingMiddle).ConnectToggleActionWith(room.GetButton(ChildrensRoom.Button)); - room.SetupRollerShutterAutomation().WithRollerShutters(room.GetRollerShutter(ChildrensRoom.RollerShutter)); + _automationFactory.RegisterRollerShutterAutomation(room) + .WithRollerShutters(room.GetRollerShutter(ChildrensRoom.RollerShutter)); + room.GetRollerShutter(ChildrensRoom.RollerShutter) .ConnectWith(room.GetButton(ChildrensRoom.RollerShutterButtonUp), room.GetButton(ChildrensRoom.RollerShutterButtonDown)); diff --git a/Controllers/HA4IoT.Controller.Main/Rooms/FloorConfiguration.cs b/Controllers/HA4IoT.Controller.Main/Rooms/FloorConfiguration.cs index 2ee511eb..cabca292 100644 --- a/Controllers/HA4IoT.Controller.Main/Rooms/FloorConfiguration.cs +++ b/Controllers/HA4IoT.Controller.Main/Rooms/FloorConfiguration.cs @@ -15,6 +15,7 @@ using HA4IoT.Hardware.CCTools; using HA4IoT.Hardware.I2CHardwareBridge; using HA4IoT.PersonalAgent; +using HA4IoT.Sensors; using HA4IoT.Sensors.Buttons; using HA4IoT.Sensors.HumiditySensors; using HA4IoT.Sensors.MotionDetectors; @@ -31,6 +32,9 @@ internal class FloorConfiguration private readonly IDeviceService _deviceService; private readonly CCToolsBoardService _ccToolsBoardService; private readonly SynonymService _synonymService; + private readonly AutomationFactory _automationFactory; + private readonly ActuatorFactory _actuatorFactory; + private readonly SensorFactory _sensorFactory; private enum Floor { @@ -72,19 +76,28 @@ public FloorConfiguration( IDaylightService daylightService, IDeviceService deviceService, CCToolsBoardService ccToolsBoardService, - SynonymService synonymService) + SynonymService synonymService, + AutomationFactory automationFactory, + ActuatorFactory actuatorFactory, + SensorFactory sensorFactory) { if (areaService == null) throw new ArgumentNullException(nameof(areaService)); if (daylightService == null) throw new ArgumentNullException(nameof(daylightService)); if (deviceService == null) throw new ArgumentNullException(nameof(deviceService)); if (ccToolsBoardService == null) throw new ArgumentNullException(nameof(ccToolsBoardService)); if (synonymService == null) throw new ArgumentNullException(nameof(synonymService)); + if (automationFactory == null) throw new ArgumentNullException(nameof(automationFactory)); + if (actuatorFactory == null) throw new ArgumentNullException(nameof(actuatorFactory)); + if (sensorFactory == null) throw new ArgumentNullException(nameof(sensorFactory)); _areaService = areaService; _daylightService = daylightService; _deviceService = deviceService; _ccToolsBoardService = ccToolsBoardService; _synonymService = synonymService; + _automationFactory = automationFactory; + _actuatorFactory = actuatorFactory; + _sensorFactory = sensorFactory; } public void Setup() @@ -101,39 +114,44 @@ public void Setup() const int SensorPin = 5; var room = _areaService.CreateArea(Room.Floor) - .WithMotionDetector(Floor.StairwayMotionDetector, input2.GetInput(1)) - .WithMotionDetector(Floor.StairsLowerMotionDetector, input4.GetInput(7)) - .WithMotionDetector(Floor.StairsUpperMotionDetector, input4.GetInput(6)) - .WithMotionDetector(Floor.LowerFloorMotionDetector, input1.GetInput(4)) - .WithTemperatureSensor(Floor.LowerFloorTemperatureSensor, i2CHardwareBridge.DHT22Accessor.GetTemperatureSensor(SensorPin)) - .WithHumiditySensor(Floor.LowerFloorHumiditySensor, i2CHardwareBridge.DHT22Accessor.GetHumiditySensor(SensorPin)) + .WithTemperatureSensor(Floor.LowerFloorTemperatureSensor, + i2CHardwareBridge.DHT22Accessor.GetTemperatureSensor(SensorPin)) + .WithHumiditySensor(Floor.LowerFloorHumiditySensor, + i2CHardwareBridge.DHT22Accessor.GetHumiditySensor(SensorPin)) .WithLamp(Floor.Lamp1, hspe16FloorAndLowerBathroom.GetOutput(5).WithInvertedState()) .WithLamp(Floor.Lamp2, hspe16FloorAndLowerBathroom.GetOutput(6).WithInvertedState()) .WithLamp(Floor.Lamp3, hspe16FloorAndLowerBathroom.GetOutput(7).WithInvertedState()) .WithLamp(Floor.StairwayLampCeiling, hsrel5Stairway.GetOutput(0)) - .WithLamp(Floor.StairwayLampWall, hsrel5Stairway.GetOutput(1)) - .WithRollerShutter(Floor.StairwayRollerShutter, hsrel5Stairway.GetOutput(4), hsrel5Stairway.GetOutput(3)) - .WithButton(Floor.ButtonLowerFloorUpper, input1.GetInput(0)) - .WithButton(Floor.ButtonLowerFloorLower, input1.GetInput(5)) - .WithButton(Floor.ButtonLowerFloorAtBathroom, input1.GetInput(1)) - .WithButton(Floor.ButtonLowerFloorAtKitchen, input1.GetInput(3)) - .WithButton(Floor.ButtonStairsLowerUpper, input4.GetInput(5)) - .WithButton(Floor.ButtonStairsLowerLower, input1.GetInput(2)) - .WithButton(Floor.ButtonStairsUpper, input4.GetInput(4)) - .WithButton(Floor.ButtonStairway, input1.GetInput(6)); - - room.CombineActuators(Floor.CombinedStairwayLamp) + .WithLamp(Floor.StairwayLampWall, hsrel5Stairway.GetOutput(1)); + + _sensorFactory.RegisterMotionDetector(room, Floor.StairwayMotionDetector, input2.GetInput(1)); + _sensorFactory.RegisterMotionDetector(room, Floor.StairsLowerMotionDetector, input4.GetInput(7)); + _sensorFactory.RegisterMotionDetector(room, Floor.StairsUpperMotionDetector, input4.GetInput(6)); + _sensorFactory.RegisterMotionDetector(room, Floor.LowerFloorMotionDetector, input1.GetInput(4)); + + _actuatorFactory.RegisterRollerShutter(room, Floor.StairwayRollerShutter, hsrel5Stairway.GetOutput(4), hsrel5Stairway.GetOutput(3)); + + _sensorFactory.RegisterButton(room, Floor.ButtonLowerFloorUpper, input1.GetInput(0)); + _sensorFactory.RegisterButton(room, Floor.ButtonLowerFloorLower, input1.GetInput(5)); + _sensorFactory.RegisterButton(room, Floor.ButtonLowerFloorAtBathroom, input1.GetInput(1)); + _sensorFactory.RegisterButton(room, Floor.ButtonLowerFloorAtKitchen, input1.GetInput(3)); + _sensorFactory.RegisterButton(room, Floor.ButtonStairsLowerUpper, input4.GetInput(5)); + _sensorFactory.RegisterButton(room, Floor.ButtonStairsLowerLower, input1.GetInput(2)); + _sensorFactory.RegisterButton(room, Floor.ButtonStairsUpper, input4.GetInput(4)); + _sensorFactory.RegisterButton(room, Floor.ButtonStairway, input1.GetInput(6)); + + _actuatorFactory.RegisterLogicalActuator(room, Floor.CombinedStairwayLamp) .WithActuator(room.GetLamp(Floor.StairwayLampCeiling)) .WithActuator(room.GetLamp(Floor.StairwayLampWall)); SetupStairwayLamps(room); - room.CombineActuators(Floor.CombinedLamps) + _actuatorFactory.RegisterLogicalActuator(room, Floor.CombinedLamps) .WithActuator(room.GetLamp(Floor.Lamp1)) .WithActuator(room.GetLamp(Floor.Lamp2)) .WithActuator(room.GetLamp(Floor.Lamp3)); - room.SetupTurnOnAndOffAutomation() + _automationFactory.RegisterTurnOnAndOffAutomation(room) .WithTrigger(room.GetMotionDetector(Floor.LowerFloorMotionDetector)) .WithTrigger(room.GetButton(Floor.ButtonLowerFloorUpper).GetPressedShortlyTrigger()) .WithTrigger(room.GetButton(Floor.ButtonLowerFloorAtBathroom).GetPressedShortlyTrigger()) @@ -143,17 +161,18 @@ public void Setup() .WithTurnOffIfButtonPressedWhileAlreadyOn() .WithOnDuration(TimeSpan.FromSeconds(20)); - SetupStairsCeilingLamps(room, hspe8UpperFloor); - SetupStairsLamps(room, hspe16FloorAndLowerBathroom); - - room.SetupRollerShutterAutomation().WithRollerShutters(room.GetRollerShutter(Floor.StairwayRollerShutter)); + SetupStairsCeilingLamps(_automationFactory, room, hspe8UpperFloor); + SetupStairsLamps(_automationFactory, room, hspe16FloorAndLowerBathroom); + + _automationFactory.RegisterRollerShutterAutomation(room) + .WithRollerShutters(room.GetRollerShutter(Floor.StairwayRollerShutter)); _synonymService.AddSynonymsForArea(Room.Floor, "Flur", "Floor"); } private void SetupStairwayLamps(IArea room) { - room.SetupTurnOnAndOffAutomation() + _automationFactory.RegisterTurnOnAndOffAutomation(room) .WithTrigger(room.GetMotionDetector(Floor.StairwayMotionDetector)) .WithTrigger(room.GetButton(Floor.ButtonStairway).GetPressedShortlyTrigger()) .WithTarget(room.GetActuator(Floor.CombinedStairwayLamp)) @@ -161,7 +180,7 @@ private void SetupStairwayLamps(IArea room) .WithOnDuration(TimeSpan.FromSeconds(30)); } - private void SetupStairsCeilingLamps(IArea floor, HSPE8OutputOnly hspe8UpperFloor) + private void SetupStairsCeilingLamps(AutomationFactory automationFactory, IArea room, HSPE8OutputOnly hspe8UpperFloor) { var output = new LogicalBinaryOutput() .WithOutput(hspe8UpperFloor[HSPE8Pin.GPIO4]) @@ -170,18 +189,18 @@ private void SetupStairsCeilingLamps(IArea floor, HSPE8OutputOnly hspe8UpperFloo .WithOutput(hspe8UpperFloor[HSPE8Pin.GPIO6]) .WithInvertedState(); - floor.WithLamp(Floor.LampStairsCeiling, output); + room.WithLamp(Floor.LampStairsCeiling, output); - floor.SetupTurnOnAndOffAutomation() - .WithTrigger(floor.GetMotionDetector(Floor.StairsLowerMotionDetector)) - .WithTrigger(floor.GetMotionDetector(Floor.StairsUpperMotionDetector)) + automationFactory.RegisterTurnOnAndOffAutomation(room) + .WithTrigger(room.GetMotionDetector(Floor.StairsLowerMotionDetector)) + .WithTrigger(room.GetMotionDetector(Floor.StairsUpperMotionDetector)) //.WithTrigger(floor.GetButton(Floor.ButtonStairsUpper).GetPressedShortlyTrigger()) - .WithTarget(floor.GetStateMachine(Floor.LampStairsCeiling)) + .WithTarget(room.GetStateMachine(Floor.LampStairsCeiling)) .WithOnDuration(TimeSpan.FromSeconds(10)); - var lamp = floor.GetLamp(Floor.LampStairsCeiling); + var lamp = room.GetLamp(Floor.LampStairsCeiling); - floor.GetButton(Floor.ButtonStairsUpper).GetPressedShortlyTrigger().Triggered += (s, e) => + room.GetButton(Floor.ButtonStairsUpper).GetPressedShortlyTrigger().Triggered += (s, e) => { if (lamp.GetState().Equals(BinaryStateId.On)) { @@ -193,7 +212,7 @@ private void SetupStairsCeilingLamps(IArea floor, HSPE8OutputOnly hspe8UpperFloo } }; - floor.GetButton(Floor.ButtonStairsLowerUpper).GetPressedShortlyTrigger().Triggered += (s, e) => + room.GetButton(Floor.ButtonStairsLowerUpper).GetPressedShortlyTrigger().Triggered += (s, e) => { if (lamp.GetState().Equals(BinaryStateId.On)) { @@ -206,7 +225,7 @@ private void SetupStairsCeilingLamps(IArea floor, HSPE8OutputOnly hspe8UpperFloo }; } - private void SetupStairsLamps(IArea floor, HSPE16OutputOnly hspe16FloorAndLowerBathroom) + private void SetupStairsLamps(AutomationFactory automationFactory, IArea room, HSPE16OutputOnly hspe16FloorAndLowerBathroom) { var output = new LogicalBinaryOutput() .WithOutput(hspe16FloorAndLowerBathroom[HSPE16Pin.GPIO8]) @@ -217,10 +236,10 @@ private void SetupStairsLamps(IArea floor, HSPE16OutputOnly hspe16FloorAndLowerB .WithOutput(hspe16FloorAndLowerBathroom[HSPE16Pin.GPIO12]) .WithInvertedState(); - floor.WithLamp(Floor.LampStairs, output); + room.WithLamp(Floor.LampStairs, output); - floor.SetupConditionalOnAutomation() - .WithActuator(floor.GetLamp(Floor.LampStairs)) + automationFactory.RegisterConditionalOnAutomation(room) + .WithActuator(room.GetLamp(Floor.LampStairs)) .WithOnAtNightRange() .WithOffBetweenRange(TimeSpan.FromHours(23), TimeSpan.FromHours(4)); } diff --git a/Controllers/HA4IoT.Controller.Main/Rooms/KitchenConfiguration.cs b/Controllers/HA4IoT.Controller.Main/Rooms/KitchenConfiguration.cs index 4d549db3..b36546e9 100644 --- a/Controllers/HA4IoT.Controller.Main/Rooms/KitchenConfiguration.cs +++ b/Controllers/HA4IoT.Controller.Main/Rooms/KitchenConfiguration.cs @@ -13,6 +13,7 @@ using HA4IoT.Hardware.CCTools; using HA4IoT.Hardware.I2CHardwareBridge; using HA4IoT.PersonalAgent; +using HA4IoT.Sensors; using HA4IoT.Sensors.Buttons; using HA4IoT.Sensors.HumiditySensors; using HA4IoT.Sensors.MotionDetectors; @@ -30,6 +31,9 @@ internal class KitchenConfiguration private readonly IDeviceService _deviceService; private readonly CCToolsBoardService _ccToolsBoardService; private readonly SynonymService _synonymService; + private readonly AutomationFactory _automationFactory; + private readonly ActuatorFactory _actuatorFactory; + private readonly SensorFactory _sensorFactory; public enum Kitchen { @@ -63,19 +67,28 @@ public KitchenConfiguration( IDaylightService daylightService, IDeviceService deviceService, CCToolsBoardService ccToolsBoardService, - SynonymService synonymService) + SynonymService synonymService, + AutomationFactory automationFactory, + ActuatorFactory actuatorFactory, + SensorFactory sensorFactory) { if (areaService == null) throw new ArgumentNullException(nameof(areaService)); if (daylightService == null) throw new ArgumentNullException(nameof(daylightService)); if (deviceService == null) throw new ArgumentNullException(nameof(deviceService)); if (ccToolsBoardService == null) throw new ArgumentNullException(nameof(ccToolsBoardService)); if (synonymService == null) throw new ArgumentNullException(nameof(synonymService)); + if (automationFactory == null) throw new ArgumentNullException(nameof(automationFactory)); + if (actuatorFactory == null) throw new ArgumentNullException(nameof(actuatorFactory)); + if (sensorFactory == null) throw new ArgumentNullException(nameof(sensorFactory)); _areaService = areaService; _daylightService = daylightService; _deviceService = deviceService; _ccToolsBoardService = ccToolsBoardService; _synonymService = synonymService; + _automationFactory = automationFactory; + _actuatorFactory = actuatorFactory; + _sensorFactory = sensorFactory; } public void Setup() @@ -93,34 +106,38 @@ public void Setup() var room = _areaService.CreateArea(Room.Kitchen) .WithTemperatureSensor(Kitchen.TemperatureSensor, i2CHardwareBridge.DHT22Accessor.GetTemperatureSensor(SensorPin)) .WithHumiditySensor(Kitchen.HumiditySensor, i2CHardwareBridge.DHT22Accessor.GetHumiditySensor(SensorPin)) - .WithMotionDetector(Kitchen.MotionDetector, input1.GetInput(8)) .WithLamp(Kitchen.LightCeilingMiddle, hsrel5.GetOutput(5).WithInvertedState()) .WithLamp(Kitchen.LightCeilingWindow, hsrel5.GetOutput(6).WithInvertedState()) .WithLamp(Kitchen.LightCeilingWall, hsrel5.GetOutput(7).WithInvertedState()) .WithLamp(Kitchen.LightCeilingDoor, hspe8.GetOutput(0).WithInvertedState()) .WithLamp(Kitchen.LightCeilingPassageInner, hspe8.GetOutput(1).WithInvertedState()) - .WithLamp(Kitchen.LightCeilingPassageOuter, hspe8.GetOutput(2).WithInvertedState()) - .WithSocket(Kitchen.SocketWall, hsrel5.GetOutput(2)) - .WithRollerShutter(Kitchen.RollerShutter, hsrel5.GetOutput(4), hsrel5.GetOutput(3)) - .WithButton(Kitchen.ButtonKitchenette, input1.GetInput(11)) - .WithButton(Kitchen.ButtonPassage, input1.GetInput(9)) - .WithRollerShutterButtons(Kitchen.RollerShutterButtonUp, input2.GetInput(15), Kitchen.RollerShutterButtonDown, input2.GetInput(14)) - .WithWindow(Kitchen.Window, w => w.WithCenterCasement(input0.GetInput(6), input0.GetInput(7))); + .WithWindow(Kitchen.Window, w => w.WithCenterCasement(input0.GetInput(6), input0.GetInput(7))) + .WithLamp(Kitchen.LightCeilingPassageOuter, hspe8.GetOutput(2).WithInvertedState()); + + _sensorFactory.RegisterMotionDetector(room, Kitchen.MotionDetector, input1.GetInput(8)); + + _actuatorFactory.RegisterSocket(room, Kitchen.SocketWall, hsrel5.GetOutput(2)); + _actuatorFactory.RegisterRollerShutter(room, Kitchen.RollerShutter, hsrel5.GetOutput(4), hsrel5.GetOutput(3)); + _sensorFactory.RegisterButton(room, Kitchen.ButtonKitchenette, input1.GetInput(11)); + _sensorFactory.RegisterButton(room, Kitchen.ButtonPassage, input1.GetInput(9)); + _sensorFactory.RegisterRollerShutterButtons(room, Kitchen.RollerShutterButtonUp, input2.GetInput(15), + Kitchen.RollerShutterButtonDown, input2.GetInput(14)); room.GetLamp(Kitchen.LightCeilingMiddle).ConnectToggleActionWith(room.GetButton(Kitchen.ButtonKitchenette)); room.GetLamp(Kitchen.LightCeilingMiddle).ConnectToggleActionWith(room.GetButton(Kitchen.ButtonPassage)); - room.SetupRollerShutterAutomation().WithRollerShutters(room.GetRollerShutter(Kitchen.RollerShutter)); + _automationFactory.RegisterRollerShutterAutomation(room) + .WithRollerShutters(room.GetRollerShutter(Kitchen.RollerShutter)); room.GetRollerShutter(Kitchen.RollerShutter).ConnectWith( room.GetButton(Kitchen.RollerShutterButtonUp), room.GetButton(Kitchen.RollerShutterButtonDown)); - room.CombineActuators(Kitchen.CombinedAutomaticLights) + _actuatorFactory.RegisterLogicalActuator(room, Kitchen.CombinedAutomaticLights) .WithActuator(room.GetLamp(Kitchen.LightCeilingWall)) .WithActuator(room.GetLamp(Kitchen.LightCeilingDoor)) .WithActuator(room.GetLamp(Kitchen.LightCeilingWindow)); - room.SetupTurnOnAndOffAutomation() + _automationFactory.RegisterTurnOnAndOffAutomation(room) .WithTrigger(room.GetMotionDetector(Kitchen.MotionDetector)) .WithTarget(room.GetActuator(Kitchen.CombinedAutomaticLights)) .WithEnabledAtNight(_daylightService); diff --git a/Controllers/HA4IoT.Controller.Main/Rooms/LivingRoomConfiguration.cs b/Controllers/HA4IoT.Controller.Main/Rooms/LivingRoomConfiguration.cs index bf86090d..320dccac 100644 --- a/Controllers/HA4IoT.Controller.Main/Rooms/LivingRoomConfiguration.cs +++ b/Controllers/HA4IoT.Controller.Main/Rooms/LivingRoomConfiguration.cs @@ -1,4 +1,6 @@ -using HA4IoT.Actuators.Connectors; +using System; +using HA4IoT.Actuators; +using HA4IoT.Actuators.Connectors; using HA4IoT.Actuators.Lamps; using HA4IoT.Actuators.Sockets; using HA4IoT.Contracts.Areas; @@ -7,6 +9,7 @@ using HA4IoT.Hardware.CCTools; using HA4IoT.Hardware.I2CHardwareBridge; using HA4IoT.PersonalAgent; +using HA4IoT.Sensors; using HA4IoT.Sensors.Buttons; using HA4IoT.Sensors.HumiditySensors; using HA4IoT.Sensors.TemperatureSensors; @@ -22,6 +25,8 @@ internal class LivingRoomConfiguration private readonly IAreaService _areaService; private readonly CCToolsBoardService _ccToolsBoardService; private readonly SynonymService _synonymService; + private readonly ActuatorFactory _actuatorFactory; + private readonly SensorFactory _sensorFactory; private enum LivingRoom { @@ -60,20 +65,31 @@ private enum LivingRoom public LivingRoomConfiguration( IDeviceService deviceService, IAreaService areaService, - CCToolsBoardService ccToolsBoardService, - SynonymService synonymService) + CCToolsBoardService ccToolsBoardService, + SynonymService synonymService, + ActuatorFactory actuatorFactory, + SensorFactory sensorFactory) { + if (deviceService == null) throw new ArgumentNullException(nameof(deviceService)); + if (areaService == null) throw new ArgumentNullException(nameof(areaService)); + if (ccToolsBoardService == null) throw new ArgumentNullException(nameof(ccToolsBoardService)); + if (synonymService == null) throw new ArgumentNullException(nameof(synonymService)); + if (actuatorFactory == null) throw new ArgumentNullException(nameof(actuatorFactory)); + if (sensorFactory == null) throw new ArgumentNullException(nameof(sensorFactory)); + _deviceService = deviceService; _areaService = areaService; _ccToolsBoardService = ccToolsBoardService; _synonymService = synonymService; + _actuatorFactory = actuatorFactory; + _sensorFactory = sensorFactory; } public void Setup() { var hsrel8 = _ccToolsBoardService.CreateHSREL8(InstalledDevice.LivingRoomHSREL8, new I2CSlaveAddress(18)); var hsrel5 = _ccToolsBoardService.CreateHSREL5(InstalledDevice.LivingRoomHSREL5, new I2CSlaveAddress(57)); - + var input0 = _deviceService.GetDevice(InstalledDevice.Input0); var input1 = _deviceService.GetDevice(InstalledDevice.Input1); var i2CHardwareBridge = _deviceService.GetDevice(); @@ -85,24 +101,23 @@ public void Setup() .WithHumiditySensor(LivingRoom.HumiditySensor, i2CHardwareBridge.DHT22Accessor.GetHumiditySensor(SensorPin)) .WithLamp(LivingRoom.LampCouch, hsrel8.GetOutput(8).WithInvertedState()) .WithLamp(LivingRoom.LampDiningTable, hsrel8.GetOutput(9).WithInvertedState()) - .WithSocket(LivingRoom.SocketWindowLeftLower, hsrel8.GetOutput(1)) - .WithSocket(LivingRoom.SocketWindowMiddleLower, hsrel8.GetOutput(2)) - .WithSocket(LivingRoom.SocketWindowRightLower, hsrel8.GetOutput(3)) - .WithSocket(LivingRoom.SocketWindowLeftUpper, hsrel8.GetOutput(5)) - .WithSocket(LivingRoom.SocketWindowRightUpper, hsrel8.GetOutput(7)) - - .WithSocket(LivingRoom.SocketWallRightEdgeRight, hsrel8.GetOutput(4)) - - .WithSocket(LivingRoom.SocketWallLeftEdgeLeft, hsrel8.GetOutput(0)) - - .WithButton(LivingRoom.ButtonUpper, input0.GetInput(15)) - .WithButton(LivingRoom.ButtonMiddle, input0.GetInput(14)) - .WithButton(LivingRoom.ButtonLower, input0.GetInput(13)) - .WithButton(LivingRoom.ButtonPassage, input1.GetInput(10)) .WithWindow(LivingRoom.WindowLeft, w => w.WithLeftCasement(input0.GetInput(10), input0.GetInput(11)).WithRightCasement(input0.GetInput(9), input0.GetInput(8))) .WithWindow(LivingRoom.WindowRight, w => w.WithLeftCasement(input1.GetInput(14), input1.GetInput(15)).WithRightCasement(input1.GetInput(13), input1.GetInput(12))); + + _actuatorFactory.RegisterSocket(room, LivingRoom.SocketWindowLeftLower, hsrel8.GetOutput(1)); + _actuatorFactory.RegisterSocket(room, LivingRoom.SocketWindowMiddleLower, hsrel8.GetOutput(2)); + _actuatorFactory.RegisterSocket(room, LivingRoom.SocketWindowRightLower, hsrel8.GetOutput(3)); + _actuatorFactory.RegisterSocket(room, LivingRoom.SocketWindowLeftUpper, hsrel8.GetOutput(5)); + _actuatorFactory.RegisterSocket(room, LivingRoom.SocketWindowRightUpper, hsrel8.GetOutput(7)); + _actuatorFactory.RegisterSocket(room, LivingRoom.SocketWallRightEdgeRight, hsrel8.GetOutput(4)); + _actuatorFactory.RegisterSocket(room, LivingRoom.SocketWallLeftEdgeLeft, hsrel8.GetOutput(0)); + + _sensorFactory.RegisterButton(room, LivingRoom.ButtonUpper, input0.GetInput(15)); + _sensorFactory.RegisterButton(room, LivingRoom.ButtonMiddle, input0.GetInput(14)); + _sensorFactory.RegisterButton(room, LivingRoom.ButtonLower, input0.GetInput(13)); + _sensorFactory.RegisterButton(room, LivingRoom.ButtonPassage, input1.GetInput(10)); room.GetLamp(LivingRoom.LampDiningTable) .ConnectToggleActionWith(room.GetButton(LivingRoom.ButtonUpper)) @@ -111,7 +126,7 @@ public void Setup() room.GetLamp(LivingRoom.LampCouch). ConnectToggleActionWith(room.GetButton(LivingRoom.ButtonMiddle)); - room.Socket(LivingRoom.SocketWallRightEdgeRight). + room.GetSocket(LivingRoom.SocketWallRightEdgeRight). ConnectToggleActionWith(room.GetButton(LivingRoom.ButtonLower)); _synonymService.AddSynonymsForArea(Room.LivingRoom, "Wohnzimmer", "LivingRoom"); diff --git a/Controllers/HA4IoT.Controller.Main/Rooms/LowerBathroomConfiguration.cs b/Controllers/HA4IoT.Controller.Main/Rooms/LowerBathroomConfiguration.cs index 5179577a..e090608a 100644 --- a/Controllers/HA4IoT.Controller.Main/Rooms/LowerBathroomConfiguration.cs +++ b/Controllers/HA4IoT.Controller.Main/Rooms/LowerBathroomConfiguration.cs @@ -12,7 +12,7 @@ using HA4IoT.Hardware.CCTools; using HA4IoT.Hardware.I2CHardwareBridge; using HA4IoT.PersonalAgent; -using HA4IoT.Sensors.Buttons; +using HA4IoT.Sensors; using HA4IoT.Sensors.HumiditySensors; using HA4IoT.Sensors.MotionDetectors; using HA4IoT.Sensors.TemperatureSensors; @@ -28,6 +28,9 @@ internal class LowerBathroomConfiguration private readonly ISchedulerService _schedulerService; private readonly IAreaService _areaService; private readonly SynonymService _synonymService; + private readonly AutomationFactory _automationFactory; + private readonly ActuatorFactory _actuatorFactory; + private readonly SensorFactory _sensorFactory; private TimedAction _bathmodeResetTimer; public enum LowerBathroom @@ -52,17 +55,26 @@ public LowerBathroomConfiguration( IDeviceService deviceService, ISchedulerService schedulerService, IAreaService areaService, - SynonymService synonymService) + SynonymService synonymService, + AutomationFactory automationFactory, + ActuatorFactory actuatorFactory, + SensorFactory sensorFactory) { if (deviceService == null) throw new ArgumentNullException(nameof(deviceService)); if (schedulerService == null) throw new ArgumentNullException(nameof(schedulerService)); if (areaService == null) throw new ArgumentNullException(nameof(areaService)); if (synonymService == null) throw new ArgumentNullException(nameof(synonymService)); + if (automationFactory == null) throw new ArgumentNullException(nameof(automationFactory)); + if (actuatorFactory == null) throw new ArgumentNullException(nameof(actuatorFactory)); + if (sensorFactory == null) throw new ArgumentNullException(nameof(sensorFactory)); _deviceService = deviceService; _schedulerService = schedulerService; _areaService = areaService; _synonymService = synonymService; + _automationFactory = automationFactory; + _actuatorFactory = actuatorFactory; + _sensorFactory = sensorFactory; } public void Setup() @@ -74,7 +86,6 @@ public void Setup() const int SensorPin = 3; var room = _areaService.CreateArea(Room.LowerBathroom) - .WithMotionDetector(LowerBathroom.MotionDetector, input3.GetInput(15)) .WithTemperatureSensor(LowerBathroom.TemperatureSensor, i2CHardwareBridge.DHT22Accessor.GetTemperatureSensor(SensorPin)) .WithHumiditySensor(LowerBathroom.HumiditySensor, i2CHardwareBridge.DHT22Accessor.GetHumiditySensor(SensorPin)) .WithLamp(LowerBathroom.LightCeilingDoor, hspe16_FloorAndLowerBathroom.GetOutput(0).WithInvertedState()) @@ -83,15 +94,17 @@ public void Setup() .WithLamp(LowerBathroom.LampMirror, hspe16_FloorAndLowerBathroom.GetOutput(4).WithInvertedState()) .WithWindow(LowerBathroom.Window, w => w.WithCenterCasement(input3.GetInput(13), input3.GetInput(14))); - room.WithVirtualButton(LowerBathroom.StartBathmodeButton, b => b.GetPressedShortlyTrigger().Attach(() => StartBathode(room))); + _sensorFactory.RegisterMotionDetector(room, LowerBathroom.MotionDetector, input3.GetInput(15)); - room.CombineActuators(LowerBathroom.CombinedLights) + _sensorFactory.RegisterVirtualButton(room, LowerBathroom.StartBathmodeButton, b => b.GetPressedShortlyTrigger().Attach(() => StartBathode(room))); + + _actuatorFactory.RegisterLogicalActuator(room, LowerBathroom.CombinedLights) .WithActuator(room.GetLamp(LowerBathroom.LightCeilingDoor)) .WithActuator(room.GetLamp(LowerBathroom.LightCeilingMiddle)) .WithActuator(room.GetLamp(LowerBathroom.LightCeilingWindow)) .WithActuator(room.GetLamp(LowerBathroom.LampMirror)); - room.SetupTurnOnAndOffAutomation() + _automationFactory.RegisterTurnOnAndOffAutomation(room) .WithTrigger(room.GetMotionDetector(LowerBathroom.MotionDetector)) .WithTarget(room.GetActuator(LowerBathroom.CombinedLights)); diff --git a/Controllers/HA4IoT.Controller.Main/Rooms/OfficeConfiguration.cs b/Controllers/HA4IoT.Controller.Main/Rooms/OfficeConfiguration.cs index 977b0d7a..972bfe2d 100644 --- a/Controllers/HA4IoT.Controller.Main/Rooms/OfficeConfiguration.cs +++ b/Controllers/HA4IoT.Controller.Main/Rooms/OfficeConfiguration.cs @@ -1,4 +1,5 @@ using System; +using HA4IoT.Actuators; using HA4IoT.Actuators.Sockets; using HA4IoT.Actuators.StateMachines; using HA4IoT.Actuators.Triggers; @@ -12,6 +13,7 @@ using HA4IoT.Hardware.I2CHardwareBridge; using HA4IoT.Hardware.RemoteSwitch; using HA4IoT.PersonalAgent; +using HA4IoT.Sensors; using HA4IoT.Sensors.Buttons; using HA4IoT.Sensors.HumiditySensors; using HA4IoT.Sensors.MotionDetectors; @@ -30,6 +32,8 @@ internal class OfficeConfiguration private readonly CCToolsBoardService _ccToolsBoardService; private readonly SynonymService _synonymService; private readonly RemoteSocketService _remoteSocketService; + private readonly ActuatorFactory _actuatorFactory; + private readonly SensorFactory _sensorFactory; public enum Office { @@ -64,7 +68,9 @@ public OfficeConfiguration( IDaylightService daylightService, CCToolsBoardService ccToolsBoardService, SynonymService synonymService, - RemoteSocketService remoteSocketService) + RemoteSocketService remoteSocketService, + ActuatorFactory actuatorFactory, + SensorFactory sensorFactory) { if (deviceService == null) throw new ArgumentNullException(nameof(deviceService)); if (areaService == null) throw new ArgumentNullException(nameof(areaService)); @@ -72,6 +78,8 @@ public OfficeConfiguration( if (ccToolsBoardService == null) throw new ArgumentNullException(nameof(ccToolsBoardService)); if (synonymService == null) throw new ArgumentNullException(nameof(synonymService)); if (remoteSocketService == null) throw new ArgumentNullException(nameof(remoteSocketService)); + if (actuatorFactory == null) throw new ArgumentNullException(nameof(actuatorFactory)); + if (sensorFactory == null) throw new ArgumentNullException(nameof(sensorFactory)); _deviceService = deviceService; _areaService = areaService; @@ -79,6 +87,8 @@ public OfficeConfiguration( _ccToolsBoardService = ccToolsBoardService; _synonymService = synonymService; _remoteSocketService = remoteSocketService; + _actuatorFactory = actuatorFactory; + _sensorFactory = sensorFactory; } public void Setup() @@ -92,31 +102,34 @@ public void Setup() const int SensorPin = 2; var room = _areaService.CreateArea(Room.Office) - .WithMotionDetector(Office.MotionDetector, input4.GetInput(13)) .WithTemperatureSensor(Office.TemperatureSensor, i2CHardwareBridge.DHT22Accessor.GetTemperatureSensor(SensorPin)) .WithHumiditySensor(Office.HumiditySensor, i2CHardwareBridge.DHT22Accessor.GetHumiditySensor(SensorPin)) - .WithSocket(Office.SocketFrontLeft, hsrel8.GetOutput(0)) - .WithSocket(Office.SocketFrontRight, hsrel8.GetOutput(6)) - .WithSocket(Office.SocketWindowLeft, hsrel8.GetOutput(10).WithInvertedState()) - .WithSocket(Office.SocketWindowRight, hsrel8.GetOutput(11).WithInvertedState()) - .WithSocket(Office.SocketRearLeftEdge, hsrel8.GetOutput(7)) - .WithSocket(Office.SocketRearLeft, hsrel8.GetOutput(2)) - .WithSocket(Office.SocketRearRight, hsrel8.GetOutput(1)) - .WithButton(Office.ButtonUpperLeft, input5.GetInput(0)) - .WithButton(Office.ButtonLowerLeft, input5.GetInput(1)) - .WithButton(Office.ButtonLowerRight, input4.GetInput(14)) - .WithButton(Office.ButtonUpperRight, input4.GetInput(15)) .WithWindow(Office.WindowLeft, w => w.WithLeftCasement(input4.GetInput(11)).WithRightCasement(input4.GetInput(12), input4.GetInput(10))) .WithWindow(Office.WindowRight, w => w.WithLeftCasement(input4.GetInput(8)).WithRightCasement(input4.GetInput(9), input5.GetInput(8))) - .WithSocket(Office.RemoteSocketDesk, _remoteSocketService.GetOutput(0)) .WithStateMachine(Office.CombinedCeilingLights, (s, a) => SetupLight(s, hsrel8, hspe8, a)); - + + _sensorFactory.RegisterMotionDetector(room, Office.MotionDetector, input4.GetInput(13)); + + _actuatorFactory.RegisterSocket(room, Office.SocketFrontLeft, hsrel8.GetOutput(0)); + _actuatorFactory.RegisterSocket(room, Office.SocketFrontRight, hsrel8.GetOutput(6)); + _actuatorFactory.RegisterSocket(room, Office.SocketWindowLeft, hsrel8.GetOutput(10).WithInvertedState()); + _actuatorFactory.RegisterSocket(room, Office.SocketWindowRight, hsrel8.GetOutput(11).WithInvertedState()); + _actuatorFactory.RegisterSocket(room, Office.SocketRearLeftEdge, hsrel8.GetOutput(7)); + _actuatorFactory.RegisterSocket(room, Office.SocketRearLeft, hsrel8.GetOutput(2)); + _actuatorFactory.RegisterSocket(room, Office.SocketRearRight, hsrel8.GetOutput(1)); + _actuatorFactory.RegisterSocket(room, Office.RemoteSocketDesk, _remoteSocketService.GetOutput(0)); + + _sensorFactory.RegisterButton(room, Office.ButtonUpperLeft, input5.GetInput(0)); + _sensorFactory.RegisterButton(room, Office.ButtonLowerLeft, input5.GetInput(1)); + _sensorFactory.RegisterButton(room, Office.ButtonLowerRight, input4.GetInput(14)); + _sensorFactory.RegisterButton(room, Office.ButtonUpperRight, input4.GetInput(15)); + room.GetButton(Office.ButtonUpperLeft).GetPressedLongTrigger().Attach(() => { room.GetStateMachine(Office.CombinedCeilingLights).TryTurnOff(); - room.Socket(Office.SocketRearLeftEdge).TryTurnOff(); - room.Socket(Office.SocketRearLeft).TryTurnOff(); - room.Socket(Office.SocketFrontLeft).TryTurnOff(); + room.GetSocket(Office.SocketRearLeftEdge).TryTurnOff(); + room.GetSocket(Office.SocketRearLeft).TryTurnOff(); + room.GetSocket(Office.SocketFrontLeft).TryTurnOff(); }); } diff --git a/Controllers/HA4IoT.Controller.Main/Rooms/ReadingRoomConfiguration.cs b/Controllers/HA4IoT.Controller.Main/Rooms/ReadingRoomConfiguration.cs index c7ccbb82..4b0b46a4 100644 --- a/Controllers/HA4IoT.Controller.Main/Rooms/ReadingRoomConfiguration.cs +++ b/Controllers/HA4IoT.Controller.Main/Rooms/ReadingRoomConfiguration.cs @@ -1,8 +1,8 @@ using System; +using HA4IoT.Actuators; using HA4IoT.Actuators.Connectors; using HA4IoT.Actuators.Lamps; using HA4IoT.Actuators.RollerShutters; -using HA4IoT.Actuators.Sockets; using HA4IoT.Automations; using HA4IoT.Contracts.Areas; using HA4IoT.Contracts.Hardware; @@ -10,6 +10,7 @@ using HA4IoT.Hardware.CCTools; using HA4IoT.Hardware.I2CHardwareBridge; using HA4IoT.PersonalAgent; +using HA4IoT.Sensors; using HA4IoT.Sensors.Buttons; using HA4IoT.Sensors.HumiditySensors; using HA4IoT.Sensors.TemperatureSensors; @@ -25,6 +26,9 @@ internal class ReadingRoomConfiguration private readonly SynonymService _synonymService; private readonly IDeviceService _deviceService; private readonly CCToolsBoardService _ccToolsBoardService; + private readonly AutomationFactory _automationFactory; + private readonly ActuatorFactory _actuatorFactory; + private readonly SensorFactory _sensorFactory; private enum ReadingRoom { @@ -50,17 +54,26 @@ public ReadingRoomConfiguration( IAreaService areaService, SynonymService synonymService, IDeviceService deviceService, - CCToolsBoardService ccToolsBoardService) + CCToolsBoardService ccToolsBoardService, + AutomationFactory automationFactory, + ActuatorFactory actuatorFactory, + SensorFactory sensorFactory) { if (areaService == null) throw new ArgumentNullException(nameof(areaService)); if (synonymService == null) throw new ArgumentNullException(nameof(synonymService)); if (deviceService == null) throw new ArgumentNullException(nameof(deviceService)); if (ccToolsBoardService == null) throw new ArgumentNullException(nameof(ccToolsBoardService)); + if (automationFactory == null) throw new ArgumentNullException(nameof(automationFactory)); + if (actuatorFactory == null) throw new ArgumentNullException(nameof(actuatorFactory)); + if (sensorFactory == null) throw new ArgumentNullException(nameof(sensorFactory)); _areaService = areaService; _synonymService = synonymService; _deviceService = deviceService; _ccToolsBoardService = ccToolsBoardService; + _automationFactory = automationFactory; + _actuatorFactory = actuatorFactory; + _sensorFactory = sensorFactory; } public void Setup() @@ -72,20 +85,28 @@ public void Setup() const int SensorPin = 9; var room = _areaService.CreateArea(Room.ReadingRoom) - .WithTemperatureSensor(ReadingRoom.TemperatureSensor, i2CHardwareBridge.DHT22Accessor.GetTemperatureSensor(SensorPin)) - .WithHumiditySensor(ReadingRoom.HumiditySensor, i2CHardwareBridge.DHT22Accessor.GetHumiditySensor(SensorPin)) + .WithTemperatureSensor(ReadingRoom.TemperatureSensor, + i2CHardwareBridge.DHT22Accessor.GetTemperatureSensor(SensorPin)) + .WithHumiditySensor(ReadingRoom.HumiditySensor, + i2CHardwareBridge.DHT22Accessor.GetHumiditySensor(SensorPin)) .WithLamp(ReadingRoom.LightCeilingMiddle, hsrel5[HSREL5Pin.GPIO0]) - .WithRollerShutter(ReadingRoom.RollerShutter, hsrel5[HSREL5Pin.Relay4], hsrel5[HSREL5Pin.Relay3]) - .WithSocket(ReadingRoom.SocketWindow, hsrel5[HSREL5Pin.Relay0]) - .WithSocket(ReadingRoom.SocketWallLeft, hsrel5[HSREL5Pin.Relay1]) - .WithSocket(ReadingRoom.SocketWallRight, hsrel5[HSREL5Pin.Relay2]) - .WithButton(ReadingRoom.Button, input2.GetInput(13)) - .WithWindow(ReadingRoom.Window, w => w.WithCenterCasement(input2.GetInput(8))) // Tilt = input2.GetInput(9) -- currently broken! - .WithRollerShutterButtons(ReadingRoom.RollerShutterButtonUp, input2.GetInput(12), ReadingRoom.RollerShutterButtonDown, input2.GetInput(11)); + .WithWindow(ReadingRoom.Window, w => w.WithCenterCasement(input2.GetInput(8))); // Tilt = input2.GetInput(9) -- currently broken! + + _actuatorFactory.RegisterRollerShutter(room, ReadingRoom.RollerShutter, hsrel5[HSREL5Pin.Relay4], hsrel5[HSREL5Pin.Relay3]); + _sensorFactory.RegisterRollerShutterButtons(room, ReadingRoom.RollerShutterButtonUp, input2.GetInput(12), + ReadingRoom.RollerShutterButtonDown, input2.GetInput(11)); + + _actuatorFactory.RegisterSocket(room, ReadingRoom.SocketWindow, hsrel5[HSREL5Pin.Relay0]); + _actuatorFactory.RegisterSocket(room, ReadingRoom.SocketWallLeft, hsrel5[HSREL5Pin.Relay1]); + _actuatorFactory.RegisterSocket(room, ReadingRoom.SocketWallRight, hsrel5[HSREL5Pin.Relay2]); + + _sensorFactory.RegisterButton(room, ReadingRoom.Button, input2.GetInput(13)); room.GetLamp(ReadingRoom.LightCeilingMiddle).ConnectToggleActionWith(room.GetButton(ReadingRoom.Button)); - room.SetupRollerShutterAutomation().WithRollerShutters(room.GetRollerShutter(ReadingRoom.RollerShutter)); + _automationFactory.RegisterRollerShutterAutomation(room) + .WithRollerShutters(room.GetRollerShutter(ReadingRoom.RollerShutter)); + room.GetRollerShutter(ReadingRoom.RollerShutter) .ConnectWith(room.GetButton(ReadingRoom.RollerShutterButtonUp), room.GetButton(ReadingRoom.RollerShutterButtonDown)); diff --git a/Controllers/HA4IoT.Controller.Main/Rooms/StoreroomConfiguration.cs b/Controllers/HA4IoT.Controller.Main/Rooms/StoreroomConfiguration.cs index ca7052d0..36947762 100644 --- a/Controllers/HA4IoT.Controller.Main/Rooms/StoreroomConfiguration.cs +++ b/Controllers/HA4IoT.Controller.Main/Rooms/StoreroomConfiguration.cs @@ -1,4 +1,5 @@ using System; +using HA4IoT.Actuators; using HA4IoT.Actuators.Lamps; using HA4IoT.Actuators.Sockets; using HA4IoT.Automations; @@ -8,6 +9,7 @@ using HA4IoT.Contracts.Services.System; using HA4IoT.Hardware.CCTools; using HA4IoT.PersonalAgent; +using HA4IoT.Sensors; using HA4IoT.Sensors.MotionDetectors; using HA4IoT.Services.Areas; using HA4IoT.Services.Devices; @@ -22,6 +24,9 @@ internal class StoreroomConfiguration private readonly CCToolsBoardService _ccToolsBoardService; private readonly ITimerService _timerService; private readonly IDaylightService _daylightService; + private readonly AutomationFactory _automationFactory; + private readonly ActuatorFactory _actuatorFactory; + private readonly SensorFactory _sensorFactory; private CatLitterBoxTwitterSender _catLitterBoxTwitterSender; private enum Storeroom @@ -40,7 +45,10 @@ public StoreroomConfiguration( IDeviceService deviceService, CCToolsBoardService ccToolsBoardService, ITimerService timerService, - IDaylightService daylightService) + IDaylightService daylightService, + AutomationFactory automationFactory, + ActuatorFactory actuatorFactory, + SensorFactory sensorFactory) { if (areaService == null) throw new ArgumentNullException(nameof(areaService)); if (synonymService == null) throw new ArgumentNullException(nameof(synonymService)); @@ -48,6 +56,9 @@ public StoreroomConfiguration( if (ccToolsBoardService == null) throw new ArgumentNullException(nameof(ccToolsBoardService)); if (timerService == null) throw new ArgumentNullException(nameof(timerService)); if (daylightService == null) throw new ArgumentNullException(nameof(daylightService)); + if (automationFactory == null) throw new ArgumentNullException(nameof(automationFactory)); + if (actuatorFactory == null) throw new ArgumentNullException(nameof(actuatorFactory)); + if (sensorFactory == null) throw new ArgumentNullException(nameof(sensorFactory)); _areaService = areaService; _synonymService = synonymService; @@ -55,6 +66,9 @@ public StoreroomConfiguration( _ccToolsBoardService = ccToolsBoardService; _timerService = timerService; _daylightService = daylightService; + _automationFactory = automationFactory; + _actuatorFactory = actuatorFactory; + _sensorFactory = sensorFactory; } public void Setup() @@ -65,40 +79,41 @@ public void Setup() var hsrel5Stairway = _deviceService.GetDevice(InstalledDevice.StairwayHSREL5); var input3 = _deviceService.GetDevice(InstalledDevice.Input3); - var storeroom = _areaService.CreateArea(Room.Storeroom) - .WithMotionDetector(Storeroom.MotionDetector, input3.GetInput(12)) - .WithMotionDetector(Storeroom.MotionDetectorCatLitterBox, input3.GetInput(11).WithInvertedState()) - .WithLamp(Storeroom.LightCeiling, hsrel5Stairway[HSREL5Pin.GPIO1]) - .WithSocket(Storeroom.CatLitterBoxFan, hsrel5Stairway[HSREL5Pin.GPIO2]); + var room = _areaService.CreateArea(Room.Storeroom) + .WithLamp(Storeroom.LightCeiling, hsrel5Stairway[HSREL5Pin.GPIO1]); - storeroom.SetupTurnOnAndOffAutomation() - .WithTrigger(storeroom.GetMotionDetector(Storeroom.MotionDetector)) - .WithTarget(storeroom.GetLamp(Storeroom.LightCeiling)) + _sensorFactory.RegisterMotionDetector(room, Storeroom.MotionDetector, input3.GetInput(12)); + _sensorFactory.RegisterMotionDetector(room, Storeroom.MotionDetectorCatLitterBox, input3.GetInput(11).WithInvertedState()); + + _actuatorFactory.RegisterSocket(room, Storeroom.CatLitterBoxFan, hsrel5Stairway[HSREL5Pin.GPIO2]); + _actuatorFactory.RegisterSocket(room, Storeroom.CirculatingPump, hsrel5UpperHeatingValves[HSREL5Pin.Relay3]); + + _automationFactory.RegisterTurnOnAndOffAutomation(room) + .WithTrigger(room.GetMotionDetector(Storeroom.MotionDetector)) + .WithTarget(room.GetLamp(Storeroom.LightCeiling)) .WithOnDuration(TimeSpan.FromMinutes(1)); - storeroom.SetupTurnOnAndOffAutomation() - .WithTrigger(storeroom.GetMotionDetector(Storeroom.MotionDetectorCatLitterBox)) - .WithTarget(storeroom.Socket(Storeroom.CatLitterBoxFan)) + _automationFactory.RegisterTurnOnAndOffAutomation(room) + .WithTrigger(room.GetMotionDetector(Storeroom.MotionDetectorCatLitterBox)) + .WithTarget(room.GetSocket(Storeroom.CatLitterBoxFan)) .WithOnDuration(TimeSpan.FromMinutes(2)); - storeroom.WithSocket(Storeroom.CirculatingPump, hsrel5UpperHeatingValves[HSREL5Pin.Relay3]); - // Both relays are used for water source selection (True+True = Lowerr, False+False = Upper) // Second relays is with capacitor. Disable second with delay before disable first one. hsrel5UpperHeatingValves[HSREL5Pin.GPIO0].Write(BinaryState.Low); hsrel5UpperHeatingValves[HSREL5Pin.GPIO1].Write(BinaryState.Low); - storeroom.SetupTurnOnAndOffAutomation() + _automationFactory.RegisterTurnOnAndOffAutomation(room) .WithTrigger(_areaService.GetArea(Room.Kitchen).GetMotionDetector(KitchenConfiguration.Kitchen.MotionDetector)) .WithTrigger(_areaService.GetArea(Room.LowerBathroom).GetMotionDetector(LowerBathroomConfiguration.LowerBathroom.MotionDetector)) - .WithTarget(storeroom.Socket(Storeroom.CirculatingPump)) + .WithTarget(room.GetSocket(Storeroom.CirculatingPump)) .WithPauseAfterEveryTurnOn(TimeSpan.FromHours(1)) .WithOnDuration(TimeSpan.FromMinutes(1)) .WithEnabledAtDay(_daylightService); _catLitterBoxTwitterSender = new CatLitterBoxTwitterSender(_timerService).WithTrigger( - storeroom.GetMotionDetector(Storeroom.MotionDetectorCatLitterBox)); + room.GetMotionDetector(Storeroom.MotionDetectorCatLitterBox)); _synonymService.AddSynonymsForArea(Room.Storeroom, "Abstellkammer", "Storeroom"); } diff --git a/Controllers/HA4IoT.Controller.Main/Rooms/UpperBathroomConfiguration.cs b/Controllers/HA4IoT.Controller.Main/Rooms/UpperBathroomConfiguration.cs index 7e78c5da..426bb7be 100644 --- a/Controllers/HA4IoT.Controller.Main/Rooms/UpperBathroomConfiguration.cs +++ b/Controllers/HA4IoT.Controller.Main/Rooms/UpperBathroomConfiguration.cs @@ -1,4 +1,5 @@ using System; +using HA4IoT.Actuators; using HA4IoT.Actuators.BinaryStateActuators; using HA4IoT.Actuators.Lamps; using HA4IoT.Actuators.StateMachines; @@ -11,6 +12,7 @@ using HA4IoT.Hardware.CCTools; using HA4IoT.Hardware.I2CHardwareBridge; using HA4IoT.PersonalAgent; +using HA4IoT.Sensors; using HA4IoT.Sensors.HumiditySensors; using HA4IoT.Sensors.MotionDetectors; using HA4IoT.Sensors.TemperatureSensors; @@ -26,6 +28,9 @@ internal class UpperBathroomConfiguration private readonly ISchedulerService _schedulerService; private readonly IAreaService _areaService; private readonly SynonymService _synonymService; + private readonly AutomationFactory _automationFactory; + private readonly ActuatorFactory _actuatorFactory; + private readonly SensorFactory _sensorFactory; private enum UpperBathroom { @@ -48,19 +53,28 @@ public UpperBathroomConfiguration( IDeviceService deviceService, ISchedulerService schedulerService, IAreaService areaService, - SynonymService synonymService) + SynonymService synonymService, + AutomationFactory automationFactory, + ActuatorFactory actuatorFactory, + SensorFactory sensorFactory) { if (ccToolsBoardService == null) throw new ArgumentNullException(nameof(ccToolsBoardService)); if (deviceService == null) throw new ArgumentNullException(nameof(deviceService)); if (schedulerService == null) throw new ArgumentNullException(nameof(schedulerService)); if (areaService == null) throw new ArgumentNullException(nameof(areaService)); if (synonymService == null) throw new ArgumentNullException(nameof(synonymService)); + if (automationFactory == null) throw new ArgumentNullException(nameof(automationFactory)); + if (actuatorFactory == null) throw new ArgumentNullException(nameof(actuatorFactory)); + if (sensorFactory == null) throw new ArgumentNullException(nameof(sensorFactory)); _ccToolsBoardService = ccToolsBoardService; _deviceService = deviceService; _schedulerService = schedulerService; _areaService = areaService; _synonymService = synonymService; + _automationFactory = automationFactory; + _actuatorFactory = actuatorFactory; + _sensorFactory = sensorFactory; } public void Setup() @@ -74,21 +88,22 @@ public void Setup() var room = _areaService.CreateArea(Room.UpperBathroom) .WithTemperatureSensor(UpperBathroom.TemperatureSensor, i2CHardwareBridge.DHT22Accessor.GetTemperatureSensor(SensorPin)) .WithHumiditySensor(UpperBathroom.HumiditySensor, i2CHardwareBridge.DHT22Accessor.GetHumiditySensor(SensorPin)) - .WithMotionDetector(UpperBathroom.MotionDetector, input5.GetInput(15)) .WithLamp(UpperBathroom.LightCeilingDoor, hsrel5.GetOutput(0)) .WithLamp(UpperBathroom.LightCeilingEdge, hsrel5.GetOutput(1)) .WithLamp(UpperBathroom.LightCeilingMirrorCabinet, hsrel5.GetOutput(2)) .WithLamp(UpperBathroom.LampMirrorCabinet, hsrel5.GetOutput(3)) .WithStateMachine(UpperBathroom.Fan, (s, r) => SetupFan(s, hsrel5)); + _sensorFactory.RegisterMotionDetector(room, UpperBathroom.MotionDetector, input5.GetInput(15)); + var combinedLights = - room.CombineActuators(UpperBathroom.CombinedCeilingLights) + _actuatorFactory.RegisterLogicalActuator(room, UpperBathroom.CombinedCeilingLights) .WithActuator(room.GetLamp(UpperBathroom.LightCeilingDoor)) .WithActuator(room.GetLamp(UpperBathroom.LightCeilingEdge)) .WithActuator(room.GetLamp(UpperBathroom.LightCeilingMirrorCabinet)) .WithActuator(room.GetLamp(UpperBathroom.LampMirrorCabinet)); - room.SetupTurnOnAndOffAutomation() + _automationFactory.RegisterTurnOnAndOffAutomation(room) .WithTrigger(room.GetMotionDetector(UpperBathroom.MotionDetector)) .WithTarget(combinedLights) .WithOnDuration(TimeSpan.FromMinutes(8)); diff --git a/Controllers/HA4IoT.Controller.Main/StartupTask.cs b/Controllers/HA4IoT.Controller.Main/StartupTask.cs index fa583db2..4d926042 100644 --- a/Controllers/HA4IoT.Controller.Main/StartupTask.cs +++ b/Controllers/HA4IoT.Controller.Main/StartupTask.cs @@ -12,6 +12,7 @@ using HA4IoT.Contracts.Services.System; using HA4IoT.Contracts.Services.Weather; using HA4IoT.Controller.Main.Rooms; +using HA4IoT.Core; using HA4IoT.ExternalServices.OpenWeatherMap; using HA4IoT.ExternalServices.TelegramBot; using HA4IoT.ExternalServices.Twitter; @@ -29,13 +30,19 @@ namespace HA4IoT.Controller.Main { public sealed class StartupTask : IBackgroundTask { + private const int LedGpio = 22; + public void Run(IBackgroundTaskInstance taskInstance) { - var controller = new Controller { Initializer = new Initializer() }; + var controller = new HA4IoTController(new ControllerOptions { StatusLedNumber = LedGpio }) + { + Initializer = new Initializer() + }; + controller.RunAsync(taskInstance); } - private class Initializer : IInitializer + private class Initializer : IHA4IoTInitializer { public void RegisterServices(IContainerService containerService) { @@ -45,13 +52,13 @@ public void RegisterServices(IContainerService containerService) RegisterTwitterClientService(containerService); RegisterTelegramBotService(containerService); } - - public Task Initialize(IContainerService containerService) + + public Task Configure(IContainerService containerService) { var ccToolsBoardService = containerService.GetInstance(); var pi2GpioService = containerService.GetInstance(); var synonymService = containerService.GetInstance(); - + synonymService.TryLoadPersistedSynonyms(); ccToolsBoardService.CreateHSPE16InputOnly(InstalledDevice.Input0, new I2CSlaveAddress(42)); @@ -74,8 +81,6 @@ public Task Initialize(IContainerService containerService) synonymService.RegisterDefaultComponentStateSynonyms(); - InitializeAzureCloudApiEndpoint(); - var ioBoardsInterruptMonitor = new InterruptMonitor(pi2GpioService.GetInput(4)); ioBoardsInterruptMonitor.InterruptDetected += (s, e) => ccToolsBoardService.PollInputBoardStates(); ioBoardsInterruptMonitor.Start(); @@ -158,7 +163,7 @@ private void RegisterI2CHardwareBridgeService(IContainerService containerService var i2CHardwareBridge = new I2CHardwareBridge(new I2CSlaveAddress(50), i2CBusService, schedulerService); deviceService.AddDevice(i2CHardwareBridge); - + var brennenstuhl = new BrennenstuhlCodeSequenceProvider(); var ldp433MHzSender = new LPD433MHzSignalSender(i2CHardwareBridge, LDP433MhzSenderPin, apiService); diff --git a/HA4IoT.sln b/HA4IoT.sln index f9ee4afc..3731f2b4 100644 --- a/HA4IoT.sln +++ b/HA4IoT.sln @@ -519,8 +519,8 @@ Global {6FD41DDA-4369-43C1-807A-B1BC43ECBDBF}.Release|ARM (For Raspberry Pi).Build.0 = Release|Any CPU {6FD41DDA-4369-43C1-807A-B1BC43ECBDBF}.Release|x86 (For local).ActiveCfg = Release|x86 {6FD41DDA-4369-43C1-807A-B1BC43ECBDBF}.Release|x86 (For local).Build.0 = Release|x86 - {600BC3F2-2A09-4A8E-9126-1F9ACCD7D879}.Debug|ARM (For Raspberry Pi).ActiveCfg = Debug|Any CPU - {600BC3F2-2A09-4A8E-9126-1F9ACCD7D879}.Debug|ARM (For Raspberry Pi).Build.0 = Debug|Any CPU + {600BC3F2-2A09-4A8E-9126-1F9ACCD7D879}.Debug|ARM (For Raspberry Pi).ActiveCfg = Debug|ARM + {600BC3F2-2A09-4A8E-9126-1F9ACCD7D879}.Debug|ARM (For Raspberry Pi).Build.0 = Debug|ARM {600BC3F2-2A09-4A8E-9126-1F9ACCD7D879}.Debug|x86 (For local).ActiveCfg = Debug|x86 {600BC3F2-2A09-4A8E-9126-1F9ACCD7D879}.Debug|x86 (For local).Build.0 = Debug|x86 {600BC3F2-2A09-4A8E-9126-1F9ACCD7D879}.Release|ARM (For Raspberry Pi).ActiveCfg = Release|Any CPU diff --git a/SDK/ExternalServices/HA4IoT.ExternalServices.OpenWeatherMap/OpenWeatherMapService.cs b/SDK/ExternalServices/HA4IoT.ExternalServices.OpenWeatherMap/OpenWeatherMapService.cs index d4b2e29c..14ed726c 100644 --- a/SDK/ExternalServices/HA4IoT.ExternalServices.OpenWeatherMap/OpenWeatherMapService.cs +++ b/SDK/ExternalServices/HA4IoT.ExternalServices.OpenWeatherMap/OpenWeatherMapService.cs @@ -52,7 +52,7 @@ public OpenWeatherMapService( public event EventHandler DaylightFetched; public event EventHandler WeatherFetched; - public override JsonObject ExportStatusToJsonObject() + public override JsonObject GetStatus() { var result = new JsonObject(); @@ -66,9 +66,12 @@ public override JsonObject ExportStatusToJsonObject() return result; } - public override void HandleApiCommand(IApiContext apiContext) + public override void HandleApiCall(IApiContext apiContext) { - Refresh(); + if (apiContext.CallType == ApiCallType.Command) + { + Refresh(); + } } private void PersistWeatherData(string weatherData) diff --git a/SDK/HA4IoT.Actuators/ActuatorFactory.cs b/SDK/HA4IoT.Actuators/ActuatorFactory.cs new file mode 100644 index 00000000..0bb60f37 --- /dev/null +++ b/SDK/HA4IoT.Actuators/ActuatorFactory.cs @@ -0,0 +1,66 @@ +using System; +using HA4IoT.Actuators.BinaryStateActuators; +using HA4IoT.Actuators.RollerShutters; +using HA4IoT.Actuators.Sockets; +using HA4IoT.Contracts.Actuators; +using HA4IoT.Contracts.Areas; +using HA4IoT.Contracts.Components; +using HA4IoT.Contracts.Hardware; +using HA4IoT.Contracts.Services; +using HA4IoT.Contracts.Services.System; + +namespace HA4IoT.Actuators +{ + public class ActuatorFactory + { + private readonly ITimerService _timerService; + private readonly ISchedulerService _schedulerService; + + public ActuatorFactory(ITimerService timerService, ISchedulerService schedulerService) + { + if (timerService == null) throw new ArgumentNullException(nameof(timerService)); + if (schedulerService == null) throw new ArgumentNullException(nameof(schedulerService)); + + _timerService = timerService; + _schedulerService = schedulerService; + } + + public IRollerShutter RegisterRollerShutter(IArea area, Enum id, IBinaryOutput powerOutput, IBinaryOutput directionOutput) + { + if (area == null) throw new ArgumentNullException(nameof(area)); + if (powerOutput == null) throw new ArgumentNullException(nameof(powerOutput)); + if (directionOutput == null) throw new ArgumentNullException(nameof(directionOutput)); + + var rollerShutter = new RollerShutter( + ComponentIdFactory.Create(area.Id, id), + new PortBasedRollerShutterEndpoint(powerOutput, directionOutput), + _timerService, + _schedulerService); + + area.AddComponent(rollerShutter); + + return rollerShutter; + } + + public ISocket RegisterSocket(IArea area, Enum id, IBinaryOutput output) + { + if (area == null) throw new ArgumentNullException(nameof(area)); + if (output == null) throw new ArgumentNullException(nameof(output)); + + var socket = new Socket(ComponentIdFactory.Create(area.Id, id), new PortBasedBinaryStateEndpoint(output)); + area.AddComponent(socket); + + return socket; + } + + public LogicalBinaryStateActuator RegisterLogicalActuator(IArea area, Enum id) + { + if (area == null) throw new ArgumentNullException(nameof(area)); + + var actuator = new LogicalBinaryStateActuator(ComponentIdFactory.Create(area.Id, id), _timerService); + area.AddComponent(actuator); + + return actuator; + } + } +} diff --git a/SDK/HA4IoT.Actuators/BinaryStateActuators/LogicalBinaryStateActuatorExtensions.cs b/SDK/HA4IoT.Actuators/BinaryStateActuators/LogicalBinaryStateActuatorExtensions.cs deleted file mode 100644 index fc520915..00000000 --- a/SDK/HA4IoT.Actuators/BinaryStateActuators/LogicalBinaryStateActuatorExtensions.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; -using HA4IoT.Contracts.Areas; -using HA4IoT.Contracts.Components; - -namespace HA4IoT.Actuators.BinaryStateActuators -{ - public static class LogicalBinaryStateActuatorExtensions - { - public static LogicalBinaryStateActuator CombineActuators(this IArea area, Enum id) - { - if (area == null) throw new ArgumentNullException(nameof(area)); - - var actuator = new LogicalBinaryStateActuator(ComponentIdFactory.Create(area.Id, id), area.Controller.TimerService); - area.AddComponent(actuator); - return actuator; - } - } -} diff --git a/SDK/HA4IoT.Actuators/HA4IoT.Actuators.csproj b/SDK/HA4IoT.Actuators/HA4IoT.Actuators.csproj index 1cafd4d0..143b4beb 100644 --- a/SDK/HA4IoT.Actuators/HA4IoT.Actuators.csproj +++ b/SDK/HA4IoT.Actuators/HA4IoT.Actuators.csproj @@ -120,7 +120,7 @@ - + @@ -160,10 +160,6 @@ {551337e7-d1ef-4145-92b4-f7086f7665a6} HA4IoT.Contracts - - {2BBEF090-4FEE-4FB7-9CF1-F6597F2C53EA} - HA4IoT.Core - {D4E0A3F9-6521-4AEE-815A-E2A60323FB63} HA4IoT.Networking diff --git a/SDK/HA4IoT.Actuators/RollerShutters/RollerShutter.cs b/SDK/HA4IoT.Actuators/RollerShutters/RollerShutter.cs index 69bf9de0..a837c49b 100644 --- a/SDK/HA4IoT.Actuators/RollerShutters/RollerShutter.cs +++ b/SDK/HA4IoT.Actuators/RollerShutters/RollerShutter.cs @@ -124,10 +124,13 @@ public override void SetState(IComponentState state, params IHardwareParameter[] OnActiveStateChanged(oldState, _state); } - public override void HandleApiCommand(IApiContext apiContext) + public override void HandleApiCall(IApiContext apiContext) { - var state = new NamedComponentState(apiContext.Request.GetNamedString("state")); - SetState(state); + if (apiContext.CallType == ApiCallType.Command) + { + var state = new NamedComponentState(apiContext.Request.GetNamedString("state")); + SetState(state); + } } public override IList GetSupportedStates() diff --git a/SDK/HA4IoT.Actuators/RollerShutters/RollerShutterExtensions.cs b/SDK/HA4IoT.Actuators/RollerShutters/RollerShutterExtensions.cs index b5e0efe9..75966e74 100644 --- a/SDK/HA4IoT.Actuators/RollerShutters/RollerShutterExtensions.cs +++ b/SDK/HA4IoT.Actuators/RollerShutters/RollerShutterExtensions.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Linq; using HA4IoT.Contracts.Actuators; using HA4IoT.Contracts.Areas; @@ -10,7 +11,7 @@ namespace HA4IoT.Actuators.RollerShutters { public static class RollerShutterExtensions { - public static IRollerShutter[] GetRollerShutters(this IArea area) + public static IList GetRollerShutters(this IArea area) { if (area == null) throw new ArgumentNullException(nameof(area)); @@ -23,22 +24,5 @@ public static IRollerShutter GetRollerShutter(this IArea area, Enum id) return area.GetComponent(ComponentIdFactory.Create(area.Id, id)); } - - public static IArea WithRollerShutter(this IArea area, Enum id, IBinaryOutput powerOutput, IBinaryOutput directionOutput) - { - if (area == null) throw new ArgumentNullException(nameof(area)); - - if (powerOutput == null) throw new ArgumentNullException(nameof(powerOutput)); - if (directionOutput == null) throw new ArgumentNullException(nameof(directionOutput)); - - var rollerShutter = new RollerShutter( - ComponentIdFactory.Create(area.Id, id), - new PortBasedRollerShutterEndpoint(powerOutput, directionOutput), - area.Controller.TimerService, - area.Controller.ServiceLocator.GetService()); - - area.AddComponent(rollerShutter); - return area; - } } } diff --git a/SDK/HA4IoT.Actuators/Sockets/SocketExtensions.cs b/SDK/HA4IoT.Actuators/Sockets/SocketExtensions.cs index c5f12dee..7fb49d20 100644 --- a/SDK/HA4IoT.Actuators/Sockets/SocketExtensions.cs +++ b/SDK/HA4IoT.Actuators/Sockets/SocketExtensions.cs @@ -2,24 +2,12 @@ using HA4IoT.Contracts.Actuators; using HA4IoT.Contracts.Areas; using HA4IoT.Contracts.Components; -using HA4IoT.Contracts.Hardware; namespace HA4IoT.Actuators.Sockets { public static class SocketExtensions { - public static IArea WithSocket(this IArea area, Enum id, IBinaryOutput output) - { - if (area == null) throw new ArgumentNullException(nameof(area)); - if (output == null) throw new ArgumentNullException(nameof(output)); - - var socket = new Socket(ComponentIdFactory.Create(area.Id, id), new PortBasedBinaryStateEndpoint(output)); - area.AddComponent(socket); - - return area; - } - - public static ISocket Socket(this IArea area, Enum id) + public static ISocket GetSocket(this IArea area, Enum id) { if (area == null) throw new ArgumentNullException(nameof(area)); diff --git a/SDK/HA4IoT.Actuators/StateMachines/StateMachine.cs b/SDK/HA4IoT.Actuators/StateMachines/StateMachine.cs index bfa5f63e..9a853527 100644 --- a/SDK/HA4IoT.Actuators/StateMachines/StateMachine.cs +++ b/SDK/HA4IoT.Actuators/StateMachines/StateMachine.cs @@ -141,8 +141,13 @@ public void AddState(IStateMachineState state) _states.Add(state); } - public override void HandleApiCommand(IApiContext apiContext) + public override void HandleApiCall(IApiContext apiContext) { + if (apiContext.CallType != ApiCallType.Command) + { + return; + } + if (apiContext.Request.ContainsKey("action")) { string action = apiContext.Request.GetNamedString("action", "nextState"); diff --git a/SDK/HA4IoT.Automations/AutomationBase.cs b/SDK/HA4IoT.Automations/AutomationBase.cs index 70ad4c67..8553abf3 100644 --- a/SDK/HA4IoT.Automations/AutomationBase.cs +++ b/SDK/HA4IoT.Automations/AutomationBase.cs @@ -3,8 +3,8 @@ using HA4IoT.Contracts.Automations; using HA4IoT.Contracts.Core; using HA4IoT.Contracts.Core.Settings; -using HA4IoT.Core.Settings; using HA4IoT.Networking; +using HA4IoT.Settings; namespace HA4IoT.Automations { diff --git a/SDK/HA4IoT.Automations/AutomationFactory.cs b/SDK/HA4IoT.Automations/AutomationFactory.cs new file mode 100644 index 00000000..53bb58c3 --- /dev/null +++ b/SDK/HA4IoT.Automations/AutomationFactory.cs @@ -0,0 +1,87 @@ +using System; +using HA4IoT.Contracts.Areas; +using HA4IoT.Contracts.Components; +using HA4IoT.Contracts.Services; +using HA4IoT.Contracts.Services.Daylight; +using HA4IoT.Contracts.Services.OutdoorTemperature; +using HA4IoT.Contracts.Services.System; + +namespace HA4IoT.Automations +{ + public class AutomationFactory + { + private readonly ISchedulerService _schedulerService; + private readonly IDateTimeService _dateTimeService; + private readonly IDaylightService _daylightService; + private readonly IOutdoorTemperatureService _outdoorTemperatureService; + private readonly IComponentService _componentService; + + public AutomationFactory( + ISchedulerService schedulerService, + IDateTimeService dateTimeService, + IDaylightService daylightService, + IOutdoorTemperatureService outdoorTemperatureService, + IComponentService componentService) + { + if (schedulerService == null) throw new ArgumentNullException(nameof(schedulerService)); + if (dateTimeService == null) throw new ArgumentNullException(nameof(dateTimeService)); + if (daylightService == null) throw new ArgumentNullException(nameof(daylightService)); + if (outdoorTemperatureService == null) throw new ArgumentNullException(nameof(outdoorTemperatureService)); + if (componentService == null) throw new ArgumentNullException(nameof(componentService)); + + _schedulerService = schedulerService; + _dateTimeService = dateTimeService; + _daylightService = daylightService; + _outdoorTemperatureService = outdoorTemperatureService; + _componentService = componentService; + } + + public ConditionalOnAutomation RegisterConditionalOnAutomation(IArea area) + { + if (area == null) throw new ArgumentNullException(nameof(area)); + + var automation = + new ConditionalOnAutomation( + AutomationIdFactory.CreateIdFrom(area), + _schedulerService, + _dateTimeService, + _daylightService); + + area.AddAutomation(automation); + + return automation; + } + + public RollerShutterAutomation RegisterRollerShutterAutomation(IArea area) + { + if (area == null) throw new ArgumentNullException(nameof(area)); + + var automation = new RollerShutterAutomation( + AutomationIdFactory.CreateIdFrom(area), + _schedulerService, + _dateTimeService, + _daylightService, + _outdoorTemperatureService, + _componentService); + + area.AddAutomation(automation); + + return automation; + } + + public TurnOnAndOffAutomation RegisterTurnOnAndOffAutomation(IArea area) + { + if (area == null) throw new ArgumentNullException(nameof(area)); + + var automation = + new TurnOnAndOffAutomation( + AutomationIdFactory.CreateIdFrom(area), + _dateTimeService, + _schedulerService); + + area.AddAutomation(automation); + + return automation; + } + } +} diff --git a/SDK/HA4IoT.Automations/AutomationIdFactory.cs b/SDK/HA4IoT.Automations/AutomationIdFactory.cs index e6f1e7e6..1c702076 100644 --- a/SDK/HA4IoT.Automations/AutomationIdFactory.cs +++ b/SDK/HA4IoT.Automations/AutomationIdFactory.cs @@ -1,7 +1,6 @@ using System; using HA4IoT.Contracts.Areas; using HA4IoT.Contracts.Automations; -using HA4IoT.Contracts.Configuration; namespace HA4IoT.Automations { diff --git a/SDK/HA4IoT.Automations/ConditionalOnAutomationExtensions.cs b/SDK/HA4IoT.Automations/ConditionalOnAutomationExtensions.cs deleted file mode 100644 index 280ab2e3..00000000 --- a/SDK/HA4IoT.Automations/ConditionalOnAutomationExtensions.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System; -using HA4IoT.Contracts.Areas; -using HA4IoT.Contracts.Services; -using HA4IoT.Contracts.Services.Daylight; -using HA4IoT.Contracts.Services.System; - -namespace HA4IoT.Automations -{ - public static class ConditionalOnAutomationExtensions - { - public static ConditionalOnAutomation SetupConditionalOnAutomation(this IArea area) - { - if (area == null) throw new ArgumentNullException(nameof(area)); - - var automation = - new ConditionalOnAutomation( - AutomationIdFactory.CreateIdFrom(area), - area.Controller.ServiceLocator.GetService(), - area.Controller.ServiceLocator.GetService(), - area.Controller.ServiceLocator.GetService()); - - area.AddAutomation(automation); - - return automation; - } - } -} diff --git a/SDK/HA4IoT.Automations/HA4IoT.Automations.csproj b/SDK/HA4IoT.Automations/HA4IoT.Automations.csproj index 9428c77b..7a4165ed 100644 --- a/SDK/HA4IoT.Automations/HA4IoT.Automations.csproj +++ b/SDK/HA4IoT.Automations/HA4IoT.Automations.csproj @@ -107,16 +107,15 @@ + - - @@ -137,14 +136,14 @@ {551337E7-D1EF-4145-92B4-F7086F7665A6} HA4IoT.Contracts - - {2BBEF090-4FEE-4FB7-9CF1-F6597F2C53EA} - HA4IoT.Core - {d4e0a3f9-6521-4aee-815a-e2a60323fb63} HA4IoT.Networking + + {600BC3F2-2A09-4A8E-9126-1F9ACCD7D879} + HA4IoT.Settings + 14.0 diff --git a/SDK/HA4IoT.Automations/RollerShutterAutomation.cs b/SDK/HA4IoT.Automations/RollerShutterAutomation.cs index c9bd3424..97ed7311 100644 --- a/SDK/HA4IoT.Automations/RollerShutterAutomation.cs +++ b/SDK/HA4IoT.Automations/RollerShutterAutomation.cs @@ -6,7 +6,6 @@ using HA4IoT.Contracts.Actuators; using HA4IoT.Contracts.Automations; using HA4IoT.Contracts.Components; -using HA4IoT.Contracts.Core; using HA4IoT.Contracts.Logging; using HA4IoT.Contracts.Services; using HA4IoT.Contracts.Services.Daylight; @@ -19,11 +18,10 @@ public class RollerShutterAutomation : AutomationBase { private readonly List _rollerShutters = new List(); - private readonly ISchedulerService _schedulerService; private readonly IDateTimeService _dateTimeService; private readonly IDaylightService _daylightService; private readonly IOutdoorTemperatureService _outdoorTemperatureService; - private readonly IComponentController _componentController; + private readonly IComponentService _componentService; private bool _maxOutsideTemperatureApplied; private bool _autoOpenIsApplied; @@ -35,22 +33,23 @@ public RollerShutterAutomation( IDateTimeService dateTimeService, IDaylightService daylightService, IOutdoorTemperatureService outdoorTemperatureService, - IComponentController componentController) + IComponentService componentService) : base(id) { - if (schedulerService == null) throw new ArgumentNullException(nameof(schedulerService)); if (dateTimeService == null) throw new ArgumentNullException(nameof(dateTimeService)); if (daylightService == null) throw new ArgumentNullException(nameof(daylightService)); if (outdoorTemperatureService == null) throw new ArgumentNullException(nameof(outdoorTemperatureService)); - if (componentController == null) throw new ArgumentNullException(nameof(componentController)); + if (componentService == null) throw new ArgumentNullException(nameof(componentService)); - _schedulerService = schedulerService; _dateTimeService = dateTimeService; _daylightService = daylightService; _outdoorTemperatureService = outdoorTemperatureService; - _componentController = componentController; + _componentService = componentService; + _componentService = componentService; - SpecialSettingsWrapper = new RollerShutterAutomationSettingsWrapper(Settings); + SpecialSettingsWrapper = new RollerShutterAutomationSettingsWrapper(Settings); + + schedulerService.RegisterSchedule("RollerShutterAutomation-" + Guid.NewGuid(), TimeSpan.FromSeconds(10), PerformPendingActions); } public RollerShutterAutomationSettingsWrapper SpecialSettingsWrapper { get; } @@ -63,9 +62,12 @@ public RollerShutterAutomation WithRollerShutters(params IRollerShutter[] roller return this; } - public void Activate() + public RollerShutterAutomation WithRollerShutters(IList rollerShutters) { - _schedulerService.RegisterSchedule("RollerShutterAutomation-" + Guid.NewGuid(), TimeSpan.FromSeconds(10), PerformPendingActions); + if (rollerShutters == null) throw new ArgumentNullException(nameof(rollerShutters)); + + _rollerShutters.AddRange(rollerShutters.Select(rs => rs.Id)); + return this; } public void PerformPendingActions() @@ -191,7 +193,7 @@ private void SetStates(NamedComponentState state) { foreach (var rollerShutter in _rollerShutters) { - _componentController.GetComponent(rollerShutter).SetState(state); + _componentService.GetComponent(rollerShutter).SetState(state); } } diff --git a/SDK/HA4IoT.Automations/RollerShutterAutomationExtensions.cs b/SDK/HA4IoT.Automations/RollerShutterAutomationExtensions.cs index f37768de..9e73ab11 100644 --- a/SDK/HA4IoT.Automations/RollerShutterAutomationExtensions.cs +++ b/SDK/HA4IoT.Automations/RollerShutterAutomationExtensions.cs @@ -1,33 +1,9 @@ using System; -using HA4IoT.Contracts.Areas; -using HA4IoT.Contracts.Services; -using HA4IoT.Contracts.Services.Daylight; -using HA4IoT.Contracts.Services.OutdoorTemperature; -using HA4IoT.Contracts.Services.System; namespace HA4IoT.Automations { public static class RollerShutterAutomationExtensions { - public static RollerShutterAutomation SetupRollerShutterAutomation(this IArea area) - { - if (area == null) throw new ArgumentNullException(nameof(area)); - - var automation = new RollerShutterAutomation( - AutomationIdFactory.CreateIdFrom(area), - area.Controller.ServiceLocator.GetService(), - area.Controller.ServiceLocator.GetService(), - area.Controller.ServiceLocator.GetService(), - area.Controller.ServiceLocator.GetService(), - area.Controller); - - automation.Activate(); - - area.AddAutomation(automation); - - return automation; - } - public static RollerShutterAutomation WithDoNotOpenBefore(this RollerShutterAutomation automation, TimeSpan minTime) { if (automation == null) throw new ArgumentNullException(nameof(automation)); diff --git a/SDK/HA4IoT.Automations/TurnOnAndOffAutomationExtensions.cs b/SDK/HA4IoT.Automations/TurnOnAndOffAutomationExtensions.cs deleted file mode 100644 index 8787b129..00000000 --- a/SDK/HA4IoT.Automations/TurnOnAndOffAutomationExtensions.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System; -using HA4IoT.Contracts.Areas; -using HA4IoT.Contracts.Services; -using HA4IoT.Contracts.Services.System; - -namespace HA4IoT.Automations -{ - public static class TurnOnAndOffAutomationExtensions - { - public static TurnOnAndOffAutomation SetupTurnOnAndOffAutomation(this IArea area) - { - if (area == null) throw new ArgumentNullException(nameof(area)); - - var automation = - new TurnOnAndOffAutomation( - AutomationIdFactory.CreateIdFrom(area), - area.Controller.ServiceLocator.GetService(), - area.Controller.ServiceLocator.GetService()); - - area.AddAutomation(automation); - - return automation; - } - } -} diff --git a/SDK/HA4IoT.Components/ComponentBase.cs b/SDK/HA4IoT.Components/ComponentBase.cs index 73a956f9..33a80038 100644 --- a/SDK/HA4IoT.Components/ComponentBase.cs +++ b/SDK/HA4IoT.Components/ComponentBase.cs @@ -7,8 +7,8 @@ using HA4IoT.Contracts.Core; using HA4IoT.Contracts.Core.Settings; using HA4IoT.Contracts.Logging; -using HA4IoT.Core.Settings; using HA4IoT.Networking; +using HA4IoT.Settings; namespace HA4IoT.Components { @@ -68,15 +68,10 @@ public virtual JsonObject ExportStatusToJsonObject() return status; } - public virtual void HandleApiCommand(IApiContext apiContext) + public virtual void HandleApiCall(IApiContext apiContext) { } - public virtual void HandleApiRequest(IApiContext apiContext) - { - apiContext.Response = ExportStatusToJsonObject(); - } - protected void OnActiveStateChanged(IComponentState oldState, IComponentState newState) { _stateLastChanged = DateTime.Now; diff --git a/SDK/HA4IoT.Components/HA4IoT.Components.csproj b/SDK/HA4IoT.Components/HA4IoT.Components.csproj index 8a06d053..d4de07b3 100644 --- a/SDK/HA4IoT.Components/HA4IoT.Components.csproj +++ b/SDK/HA4IoT.Components/HA4IoT.Components.csproj @@ -122,6 +122,10 @@ {D4E0A3F9-6521-4AEE-815A-E2A60323FB63} HA4IoT.Networking + + {600BC3F2-2A09-4A8E-9126-1F9ACCD7D879} + HA4IoT.Settings + 14.0 diff --git a/SDK/HA4IoT.Contracts/Areas/IArea.cs b/SDK/HA4IoT.Contracts/Areas/IArea.cs index df689afb..948e020d 100644 --- a/SDK/HA4IoT.Contracts/Areas/IArea.cs +++ b/SDK/HA4IoT.Contracts/Areas/IArea.cs @@ -1,21 +1,16 @@ using Windows.Data.Json; +using HA4IoT.Contracts.Automations; using HA4IoT.Contracts.Components; using HA4IoT.Contracts.Core.Settings; namespace HA4IoT.Contracts.Areas { - public interface IArea + public interface IArea : IComponentService, IAutomationService { AreaId Id { get; } ISettingsContainer Settings { get; } JsonObject ExportConfigurationToJsonObject(); - - void AddComponent(IComponent component); - - TComponent GetComponent() where TComponent : IComponent; - - TComponent GetComponent(ComponentId id) where TComponent : IComponent; } } diff --git a/SDK/HA4IoT.Contracts/Automations/IAutomationService.cs b/SDK/HA4IoT.Contracts/Automations/IAutomationService.cs index d077cc62..7c0397aa 100644 --- a/SDK/HA4IoT.Contracts/Automations/IAutomationService.cs +++ b/SDK/HA4IoT.Contracts/Automations/IAutomationService.cs @@ -3,7 +3,7 @@ namespace HA4IoT.Contracts.Automations { - public interface IAutomationService : IService + public interface IAutomationService : IApiExposedService { void AddAutomation(IAutomation automation); diff --git a/SDK/HA4IoT.Contracts/Components/IComponent.cs b/SDK/HA4IoT.Contracts/Components/IComponent.cs index 027cb265..d9eeaab6 100644 --- a/SDK/HA4IoT.Contracts/Components/IComponent.cs +++ b/SDK/HA4IoT.Contracts/Components/IComponent.cs @@ -21,9 +21,7 @@ public interface IComponent IList GetSupportedStates(); - void HandleApiCommand(IApiContext apiContext); - - void HandleApiRequest(IApiContext apiContext); + void HandleApiCall(IApiContext apiContext); JsonObject ExportConfigurationToJsonObject(); diff --git a/SDK/HA4IoT.Contracts/Configuration/ConfigurationInvalidException.cs b/SDK/HA4IoT.Contracts/Configuration/ConfigurationInvalidException.cs deleted file mode 100644 index 9d7fc21d..00000000 --- a/SDK/HA4IoT.Contracts/Configuration/ConfigurationInvalidException.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; -using System.Xml.Linq; - -namespace HA4IoT.Contracts.Configuration -{ - public class ConfigurationInvalidException : Exception - { - public ConfigurationInvalidException(string message, XElement affectedElement) : base(message) - { - AffectedElement = affectedElement; - } - - public XElement AffectedElement { get; private set; } - } -} diff --git a/SDK/HA4IoT.Contracts/Configuration/HandleConfigurationNodeResult.cs b/SDK/HA4IoT.Contracts/Configuration/HandleConfigurationNodeResult.cs deleted file mode 100644 index d19f3a6a..00000000 --- a/SDK/HA4IoT.Contracts/Configuration/HandleConfigurationNodeResult.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace HA4IoT.Contracts.Configuration -{ - public enum HandleConfigurationNodeResult - { - NotSupported, - - Handled - } -} diff --git a/SDK/HA4IoT.Contracts/Configuration/IConfigurationExtender.cs b/SDK/HA4IoT.Contracts/Configuration/IConfigurationExtender.cs deleted file mode 100644 index e91a0460..00000000 --- a/SDK/HA4IoT.Contracts/Configuration/IConfigurationExtender.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System.Xml.Linq; -using HA4IoT.Contracts.Components; -using HA4IoT.Contracts.Hardware; -using HA4IoT.Contracts.Sensors; -using HA4IoT.Contracts.Services; - -namespace HA4IoT.Contracts.Configuration -{ - public interface IConfigurationExtender - { - string Namespace { get; } - - IService ParseService(XElement element); - - IDevice ParseDevice(XElement element); - - IBinaryOutput ParseBinaryOutput(XElement element); - - IBinaryInput ParseBinaryInput(XElement element); - - INumericValueSensorEndpoint ParseNumericValueSensor(XElement element); - - IComponent ParseComponent(XElement element); - - void OnConfigurationParsed(); - - void OnInitializationFromCodeCompleted(); - } -} diff --git a/SDK/HA4IoT.Contracts/Core/IController.cs b/SDK/HA4IoT.Contracts/Core/IController.cs deleted file mode 100644 index a175e67d..00000000 --- a/SDK/HA4IoT.Contracts/Core/IController.cs +++ /dev/null @@ -1,9 +0,0 @@ -using HA4IoT.Contracts.Core.Settings; - -namespace HA4IoT.Contracts.Core -{ - public interface IController - { - ISettingsContainer Settings { get; } - } -} diff --git a/SDK/HA4IoT.Contracts/Core/IInitializer.cs b/SDK/HA4IoT.Contracts/Core/IHA4IoTInitializer.cs similarity index 65% rename from SDK/HA4IoT.Contracts/Core/IInitializer.cs rename to SDK/HA4IoT.Contracts/Core/IHA4IoTInitializer.cs index c5aeb851..5d72ca47 100644 --- a/SDK/HA4IoT.Contracts/Core/IInitializer.cs +++ b/SDK/HA4IoT.Contracts/Core/IHA4IoTInitializer.cs @@ -3,10 +3,10 @@ namespace HA4IoT.Contracts.Core { - public interface IInitializer + public interface IHA4IoTInitializer { void RegisterServices(IContainerService containerService); - Task Initialize(IContainerService containerService); + Task Configure(IContainerService containerService); } } diff --git a/SDK/HA4IoT.Contracts/HA4IoT.Contracts.csproj b/SDK/HA4IoT.Contracts/HA4IoT.Contracts.csproj index 6ba78b8a..177fedcc 100644 --- a/SDK/HA4IoT.Contracts/HA4IoT.Contracts.csproj +++ b/SDK/HA4IoT.Contracts/HA4IoT.Contracts.csproj @@ -126,7 +126,7 @@ - + @@ -176,16 +176,13 @@ - - - - + @@ -222,7 +219,6 @@ - @@ -245,6 +241,11 @@ + + + ..\..\..\..\..\.nuget\packages\SimpleInjector\3.2.0\lib\portable-net4+sl4+wp8+win8+wpa81\SimpleInjector.dll + + 14.0 diff --git a/SDK/HA4IoT.Contracts/Hardware/IDevice.cs b/SDK/HA4IoT.Contracts/Hardware/IDevice.cs index b4d34406..8dc97d65 100644 --- a/SDK/HA4IoT.Contracts/Hardware/IDevice.cs +++ b/SDK/HA4IoT.Contracts/Hardware/IDevice.cs @@ -6,8 +6,6 @@ public interface IDevice { DeviceId Id { get; } - void HandleApiCommand(IApiContext apiContext); - - void HandleApiRequest(IApiContext apiContext); + void HandleApiCall(IApiContext apiContext); } } diff --git a/SDK/HA4IoT.Contracts/Services/Daylight/IDaylightService.cs b/SDK/HA4IoT.Contracts/Services/Daylight/IDaylightService.cs index a6fe7979..99a59b1c 100644 --- a/SDK/HA4IoT.Contracts/Services/Daylight/IDaylightService.cs +++ b/SDK/HA4IoT.Contracts/Services/Daylight/IDaylightService.cs @@ -2,7 +2,7 @@ namespace HA4IoT.Contracts.Services.Daylight { - public interface IDaylightService : IService + public interface IDaylightService { TimeSpan Sunrise { get; } diff --git a/SDK/HA4IoT.Contracts/Services/IApiExposedService.cs b/SDK/HA4IoT.Contracts/Services/IApiExposedService.cs new file mode 100644 index 00000000..9a9cae30 --- /dev/null +++ b/SDK/HA4IoT.Contracts/Services/IApiExposedService.cs @@ -0,0 +1,12 @@ +using Windows.Data.Json; +using HA4IoT.Contracts.Api; + +namespace HA4IoT.Contracts.Services +{ + public interface IApiExposedService + { + void HandleApiCall(IApiContext apiContext); + + JsonObject GetStatus(); + } +} diff --git a/SDK/HA4IoT.Contracts/Services/ISchedulerService.cs b/SDK/HA4IoT.Contracts/Services/ISchedulerService.cs index e9b7c297..d540bdb4 100644 --- a/SDK/HA4IoT.Contracts/Services/ISchedulerService.cs +++ b/SDK/HA4IoT.Contracts/Services/ISchedulerService.cs @@ -3,7 +3,7 @@ namespace HA4IoT.Contracts.Services { - public interface ISchedulerService : IService + public interface ISchedulerService : IApiExposedService { TimedAction In(TimeSpan dueTime); diff --git a/SDK/HA4IoT.Contracts/Services/IService.cs b/SDK/HA4IoT.Contracts/Services/IService.cs deleted file mode 100644 index 7f9b7801..00000000 --- a/SDK/HA4IoT.Contracts/Services/IService.cs +++ /dev/null @@ -1,17 +0,0 @@ -using Windows.Data.Json; -using HA4IoT.Contracts.Api; -using HA4IoT.Contracts.Core; - -namespace HA4IoT.Contracts.Services -{ - public interface IService - { - JsonObject ExportStatusToJsonObject(); - - void HandleApiCommand(IApiContext apiContext); - - void HandleApiRequest(IApiContext apiContext); - - void CompleteRegistration(IServiceLocator serviceLocator); - } -} diff --git a/SDK/HA4IoT.Contracts/Services/OutdoorHumidity/IOutdoorHumidityService.cs b/SDK/HA4IoT.Contracts/Services/OutdoorHumidity/IOutdoorHumidityService.cs index 9fef9b47..8c537911 100644 --- a/SDK/HA4IoT.Contracts/Services/OutdoorHumidity/IOutdoorHumidityService.cs +++ b/SDK/HA4IoT.Contracts/Services/OutdoorHumidity/IOutdoorHumidityService.cs @@ -2,7 +2,7 @@ namespace HA4IoT.Contracts.Services.OutdoorHumidity { - public interface IOutdoorHumidityService : IService + public interface IOutdoorHumidityService : IApiExposedService { float OutdoorHumidity { get; } diff --git a/SDK/HA4IoT.Contracts/Services/OutdoorTemperature/IOutdoorTemperatureService.cs b/SDK/HA4IoT.Contracts/Services/OutdoorTemperature/IOutdoorTemperatureService.cs index c693533e..5067b519 100644 --- a/SDK/HA4IoT.Contracts/Services/OutdoorTemperature/IOutdoorTemperatureService.cs +++ b/SDK/HA4IoT.Contracts/Services/OutdoorTemperature/IOutdoorTemperatureService.cs @@ -2,7 +2,7 @@ namespace HA4IoT.Contracts.Services.OutdoorTemperature { - public interface IOutdoorTemperatureService : IService + public interface IOutdoorTemperatureService : IApiExposedService { float OutdoorTemperature { get; } diff --git a/SDK/HA4IoT.Contracts/Services/ServiceBase.cs b/SDK/HA4IoT.Contracts/Services/ServiceBase.cs index 3a8f46e1..a22ba673 100644 --- a/SDK/HA4IoT.Contracts/Services/ServiceBase.cs +++ b/SDK/HA4IoT.Contracts/Services/ServiceBase.cs @@ -1,27 +1,17 @@ using Windows.Data.Json; using HA4IoT.Contracts.Api; -using HA4IoT.Contracts.Core; namespace HA4IoT.Contracts.Services { - public abstract class ServiceBase : IService + public abstract class ServiceBase : IApiExposedService { - public virtual JsonObject ExportStatusToJsonObject() - { - return new JsonObject(); - } - - public virtual void HandleApiCommand(IApiContext apiContext) + public virtual void HandleApiCall(IApiContext apiContext) { } - public virtual void HandleApiRequest(IApiContext apiContext) - { - apiContext.Response = ExportStatusToJsonObject(); - } - - public virtual void CompleteRegistration(IServiceLocator serviceLocator) + public virtual JsonObject GetStatus() { + return new JsonObject(); } } } diff --git a/SDK/HA4IoT.Contracts/Services/System/IContainerService.cs b/SDK/HA4IoT.Contracts/Services/System/IContainerService.cs index 2efdbb58..cd7200ef 100644 --- a/SDK/HA4IoT.Contracts/Services/System/IContainerService.cs +++ b/SDK/HA4IoT.Contracts/Services/System/IContainerService.cs @@ -1,11 +1,15 @@ using System; +using System.Collections.Generic; +using SimpleInjector; namespace HA4IoT.Contracts.Services.System { - public interface IContainerService : IService + public interface IContainerService { TService GetInstance() where TService : class; + IEnumerable GetCurrentRegistrations(); + void RegisterSingleton() where TConcrete : class; void RegisterSingleton() where TService : class @@ -13,3 +17,4 @@ void RegisterSingleton() where TService : class void RegisterSingleton(Func instanceCreator) where TService : class; } +} \ No newline at end of file diff --git a/SDK/HA4IoT.Contracts/Services/System/IDateTimeService.cs b/SDK/HA4IoT.Contracts/Services/System/IDateTimeService.cs index 52d764cf..3ee819b0 100644 --- a/SDK/HA4IoT.Contracts/Services/System/IDateTimeService.cs +++ b/SDK/HA4IoT.Contracts/Services/System/IDateTimeService.cs @@ -2,7 +2,7 @@ namespace HA4IoT.Contracts.Services.System { - public interface IDateTimeService : IService + public interface IDateTimeService : IApiExposedService { DateTime Date { get; } diff --git a/SDK/HA4IoT.Contracts/Services/System/IDeviceService.cs b/SDK/HA4IoT.Contracts/Services/System/IDeviceService.cs index d0cd6839..fac1f886 100644 --- a/SDK/HA4IoT.Contracts/Services/System/IDeviceService.cs +++ b/SDK/HA4IoT.Contracts/Services/System/IDeviceService.cs @@ -3,7 +3,7 @@ namespace HA4IoT.Contracts.Services.System { - public interface IDeviceService : IService + public interface IDeviceService : IApiExposedService { void AddDevice(IDevice device); diff --git a/SDK/HA4IoT.Contracts/Services/System/II2CBusService.cs b/SDK/HA4IoT.Contracts/Services/System/II2CBusService.cs index 95fa9971..05947fb5 100644 --- a/SDK/HA4IoT.Contracts/Services/System/II2CBusService.cs +++ b/SDK/HA4IoT.Contracts/Services/System/II2CBusService.cs @@ -3,7 +3,7 @@ namespace HA4IoT.Contracts.Services.System { - public interface II2CBusService : IService + public interface II2CBusService : IApiExposedService { /// /// Executes the specified action providing the for the device with the specified address. diff --git a/SDK/HA4IoT.Contracts/Services/System/ISystemInformationService.cs b/SDK/HA4IoT.Contracts/Services/System/ISystemInformationService.cs index efa845d5..7d5571f9 100644 --- a/SDK/HA4IoT.Contracts/Services/System/ISystemInformationService.cs +++ b/SDK/HA4IoT.Contracts/Services/System/ISystemInformationService.cs @@ -2,7 +2,7 @@ namespace HA4IoT.Contracts.Services.System { - public interface ISystemInformationService : IService + public interface ISystemInformationService : IApiExposedService { void Set(string name, string value); diff --git a/SDK/HA4IoT.Contracts/Services/Weather/IWeatherService.cs b/SDK/HA4IoT.Contracts/Services/Weather/IWeatherService.cs index 608854f5..e4df7f30 100644 --- a/SDK/HA4IoT.Contracts/Services/Weather/IWeatherService.cs +++ b/SDK/HA4IoT.Contracts/Services/Weather/IWeatherService.cs @@ -2,7 +2,7 @@ namespace HA4IoT.Contracts.Services.Weather { - public interface IWeatherService : IService + public interface IWeatherService : IApiExposedService { Weather Weather { get; } diff --git a/SDK/HA4IoT.Contracts/project.json b/SDK/HA4IoT.Contracts/project.json index c5949392..22d7ea45 100644 --- a/SDK/HA4IoT.Contracts/project.json +++ b/SDK/HA4IoT.Contracts/project.json @@ -1,6 +1,7 @@ { "dependencies": { - "Microsoft.NETCore.UniversalWindowsPlatform": "5.0.0" + "Microsoft.NETCore.UniversalWindowsPlatform": "5.0.0", + "SimpleInjector": "3.2.0" }, "frameworks": { "uap10.0": {} diff --git a/SDK/HA4IoT.Core/ControllerApiDispatcher.cs b/SDK/HA4IoT.Core/ControllerApiDispatcher.cs index bed87bd2..4ac61111 100644 --- a/SDK/HA4IoT.Core/ControllerApiDispatcher.cs +++ b/SDK/HA4IoT.Core/ControllerApiDispatcher.cs @@ -1,12 +1,15 @@ using System; +using System.Reflection; using Windows.Data.Json; using HA4IoT.Contracts.Api; using HA4IoT.Contracts.Areas; using HA4IoT.Contracts.Automations; using HA4IoT.Contracts.Components; +using HA4IoT.Contracts.Core.Settings; +using HA4IoT.Contracts.Services; using HA4IoT.Contracts.Services.System; -using HA4IoT.Core.Settings; using HA4IoT.Networking; +using HA4IoT.Settings; namespace HA4IoT.Core { @@ -17,25 +20,33 @@ public class ControllerApiDispatcher private readonly IComponentService _componentService; private readonly IAreaService _areaService; private readonly IAutomationService _automationService; + private readonly IContainerService _containerService; + private readonly ControllerSettings _controllerSettings; public ControllerApiDispatcher( IApiService apiService, IDeviceService deviceService, IComponentService componentService, IAreaService areaService, - IAutomationService automationService) + IAutomationService automationService, + IContainerService containerService, + ControllerSettings controllerSettings) { if (apiService == null) throw new ArgumentNullException(nameof(apiService)); if (deviceService == null) throw new ArgumentNullException(nameof(deviceService)); if (componentService == null) throw new ArgumentNullException(nameof(componentService)); if (areaService == null) throw new ArgumentNullException(nameof(areaService)); if (automationService == null) throw new ArgumentNullException(nameof(automationService)); + if (containerService == null) throw new ArgumentNullException(nameof(containerService)); + if (controllerSettings == null) throw new ArgumentNullException(nameof(controllerSettings)); _apiService = apiService; _deviceService = deviceService; _componentService = componentService; _areaService = areaService; _automationService = automationService; + _containerService = containerService; + _controllerSettings = controllerSettings; } public void ExposeToApi() @@ -43,36 +54,36 @@ public void ExposeToApi() _apiService.RouteRequest("configuration", HandleApiGetConfiguration); _apiService.RouteRequest("status", HandleApiGetStatus); - ExposeServicesToApi(); - } - - private void ExposeServicesToApi() - { - foreach (var service in _controller.ServiceLocator.GetServices()) + foreach (var registration in _containerService.GetCurrentRegistrations()) { - _apiService.RouteRequest($"service/{service.InterfaceType.Name}", service.ServiceInstance.HandleApiRequest); - _apiService.RouteCommand($"service/{service.InterfaceType.Name}", service.ServiceInstance.HandleApiCommand); + var apiExposedService = registration.GetInstance() as IApiExposedService; + if (apiExposedService != null) + { + _apiService.RouteRequest($"service/{registration.ServiceType.Name}", apiExposedService.HandleApiCall); + _apiService.RouteCommand($"service/{registration.ServiceType.Name}", apiExposedService.HandleApiCall); + } } foreach (var device in _deviceService.GetDevices()) { - _apiService.RouteRequest($"device/{device.Id}", device.HandleApiRequest); - _apiService.RouteCommand($"device/{device.Id}", device.HandleApiCommand); - } - - foreach (var area in _areaService.GetAreas()) - { - new SettingsContainerApiDispatcher(area.Settings, $"area/{area.Id}", _apiService).ExposeToApi(); + _apiService.RouteRequest($"device/{device.Id}", device.HandleApiCall); + _apiService.RouteCommand($"device/{device.Id}", device.HandleApiCall); } foreach (var component in _componentService.GetComponents()) { + _apiService.RouteCommand($"component/{component.Id}/status", component.HandleApiCall); + _apiService.RouteRequest($"component/{component.Id}/status", component.HandleApiCall); + new SettingsContainerApiDispatcher(component.Settings, $"component/{component.Id}", _apiService).ExposeToApi(); - _apiService.RouteCommand($"component/{component.Id}/status", component.HandleApiCommand); - _apiService.RouteRequest($"component/{component.Id}/status", component.HandleApiRequest); component.StateChanged += (s, e) => _apiService.NotifyStateChanged(component); } + foreach (var area in _areaService.GetAreas()) + { + new SettingsContainerApiDispatcher(area.Settings, $"area/{area.Id}", _apiService).ExposeToApi(); + } + foreach (var automation in _automationService.GetAutomations()) { new SettingsContainerApiDispatcher(automation.Settings, $"automation/{automation.Id}", _apiService).ExposeToApi(); @@ -86,10 +97,10 @@ private void HandleApiGetStatus(IApiContext apiContext) result.SetNamedNumber("version", 1D); var services = new JsonObject(); - foreach (var service in _controller.ServiceLocator.GetServices()) - { - services.SetNamedObject(service.InterfaceType.Name, service.ServiceInstance.ExportStatusToJsonObject()); - } + ////foreach (var service in _controller.ServiceLocator.GetServices()) + ////{ + //// services.SetNamedObject(service.InterfaceType.Name, service.ServiceInstance.ExportStatusToJsonObject()); + ////} result.SetNamedValue("services", services); @@ -125,7 +136,7 @@ private void HandleApiGetConfiguration(IApiContext apiContext) } configuration.SetNamedValue("areas", areas); - configuration.SetNamedValue("controller", _controller.Settings.Export()); + configuration.SetNamedValue("controller", _controllerSettings.Export()); apiContext.Response = configuration; } diff --git a/SDK/HA4IoT.Core/ControllerOptions.cs b/SDK/HA4IoT.Core/ControllerOptions.cs new file mode 100644 index 00000000..47a3f546 --- /dev/null +++ b/SDK/HA4IoT.Core/ControllerOptions.cs @@ -0,0 +1,7 @@ +namespace HA4IoT.Core +{ + public class ControllerOptions + { + public int? StatusLedNumber { get; set; } + } +} diff --git a/SDK/HA4IoT.Core/DiscoveryServer.cs b/SDK/HA4IoT.Core/DiscoveryServer.cs index f4b31c7f..cbaed574 100644 --- a/SDK/HA4IoT.Core/DiscoveryServer.cs +++ b/SDK/HA4IoT.Core/DiscoveryServer.cs @@ -7,22 +7,23 @@ using HA4IoT.Contracts.Core; using HA4IoT.Contracts.Core.Discovery; using HA4IoT.Networking; +using HA4IoT.Settings; namespace HA4IoT.Core { - public sealed class DiscoveryServer : IDisposable + public sealed class DiscoveryServer : IDisposable, IStartupCompletedNotification { private int DEFAULT_PORT = 19228; - private readonly IController _controller; + private readonly ControllerSettings _controllerSettings; private DatagramSocket _socket; - public DiscoveryServer(IController controller) + public DiscoveryServer(ControllerSettings controllerSettings) { - if (controller == null) throw new ArgumentNullException(nameof(controller)); + if (controllerSettings == null) throw new ArgumentNullException(nameof(controllerSettings)); - _controller = controller; + _controllerSettings = controllerSettings; } public void Start() @@ -39,11 +40,7 @@ public void Start() private void SendResponse(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args) { - // TODO: Add wrapper. - var response = new DiscoveryResponse( - _controller.Settings.GetString("Name"), - _controller.Settings.GetString("Description")); - + var response = new DiscoveryResponse(_controllerSettings.Name, _controllerSettings.Description); SendResponseAsync(args.RemoteAddress, response).Wait(); } @@ -79,5 +76,10 @@ public void Dispose() { _socket?.Dispose(); } + + public void OnStartupCompleted() + { + Start(); + } } } diff --git a/SDK/HA4IoT.Core/HA4IoT.Core.csproj b/SDK/HA4IoT.Core/HA4IoT.Core.csproj index 26507263..d53f2f86 100644 --- a/SDK/HA4IoT.Core/HA4IoT.Core.csproj +++ b/SDK/HA4IoT.Core/HA4IoT.Core.csproj @@ -115,7 +115,8 @@ - + + @@ -133,6 +134,18 @@ {ED4B4304-0E5D-459D-857D-622F790C1A32} HA4IoT.Api + + {808ABECF-D9C2-4AB2-95D8-EAF228B44576} + HA4IoT.Actuators + + + {1CA64C98-210A-4015-95C6-67D591115F7B} + HA4IoT.Automations + + + {60F9E539-3FF5-40DE-B0C4-BE99CAE57736} + HA4IoT.Components + {551337E7-D1EF-4145-92B4-F7086F7665A6} HA4IoT.Contracts @@ -149,10 +162,18 @@ {A22FDA3A-B331-4399-863B-5F1B8D24BFE9} HA4IoT.PersonalAgent + + {8892E736-CDD0-48EB-AD9E-A1C8AA230FD7} + HA4IoT.Sensors + {6FD41DDA-4369-43C1-807A-B1BC43ECBDBF} HA4IoT.Services + + {600BC3F2-2A09-4A8E-9126-1F9ACCD7D879} + HA4IoT.Settings + {97F3345C-33B6-4779-9212-5FFBCEEF3F96} HA4IoT.Telemetry diff --git a/SDK/HA4IoT.Core/ControllerBase.cs b/SDK/HA4IoT.Core/HA4IoTController.cs similarity index 79% rename from SDK/HA4IoT.Core/ControllerBase.cs rename to SDK/HA4IoT.Core/HA4IoTController.cs index df69d78a..a8469ed6 100644 --- a/SDK/HA4IoT.Core/ControllerBase.cs +++ b/SDK/HA4IoT.Core/HA4IoTController.cs @@ -3,16 +3,17 @@ using System.Threading; using System.Threading.Tasks; using Windows.ApplicationModel.Background; +using HA4IoT.Actuators; using HA4IoT.Api; using HA4IoT.Api.AzureCloud; using HA4IoT.Api.LocalRestServer; +using HA4IoT.Automations; using HA4IoT.Contracts.Actuators; using HA4IoT.Contracts.Api; using HA4IoT.Contracts.Areas; using HA4IoT.Contracts.Automations; using HA4IoT.Contracts.Components; using HA4IoT.Contracts.Core; -using HA4IoT.Contracts.Core.Settings; using HA4IoT.Contracts.Logging; using HA4IoT.Contracts.Services; using HA4IoT.Contracts.Services.System; @@ -22,6 +23,7 @@ using HA4IoT.Logger; using HA4IoT.Networking; using HA4IoT.PersonalAgent; +using HA4IoT.Sensors; using HA4IoT.Services.Areas; using HA4IoT.Services.Automations; using HA4IoT.Services.Components; @@ -29,46 +31,29 @@ using HA4IoT.Services.Health; using HA4IoT.Services.Scheduling; using HA4IoT.Services.System; +using HA4IoT.Settings; using HA4IoT.Telemetry; using SimpleInjector; namespace HA4IoT.Core { - public class ControllerBase : IController + public class HA4IoTController { private readonly Container _container = new Container(); + private readonly ControllerOptions _options; private BackgroundTaskDeferral _deferral; private HttpServer _httpServer; - - public ISettingsContainer Settings { get; private set; } - public IInitializer Initializer { get; set; } - - protected ControllerBase(int? statusLedNumber) + public HA4IoTController(ControllerOptions options) { - _container.RegisterSingleton(() => new HealthServiceOptions {StatusLed = statusLedNumber}); - _container.RegisterSingleton(); + if (options == null) throw new ArgumentNullException(nameof(options)); - _container.RegisterSingleton(); - _container.RegisterSingleton(); - _container.RegisterSingleton(); - - _container.RegisterSingleton(() => new ContainerService(_container)); - _container.RegisterSingleton(); - _container.RegisterSingleton(); - _container.RegisterSingleton(); - _container.RegisterSingleton(); + _options = options; + } - _container.RegisterSingleton(); - _container.RegisterSingleton(); - _container.RegisterSingleton(); - _container.RegisterSingleton(); + public IHA4IoTInitializer Initializer { get; set; } - _container.RegisterSingleton(); - _container.RegisterSingleton(); - } - public Task RunAsync(IBackgroundTaskInstance taskInstance) { if (taskInstance == null) throw new ArgumentNullException(nameof(taskInstance)); @@ -81,7 +66,7 @@ public Task RunAsync(IBackgroundTaskInstance taskInstance) public Task RunAsync() { var task = Task.Factory.StartNew( - InitializeCore, + Startup, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); @@ -89,12 +74,7 @@ public Task RunAsync() task.ConfigureAwait(false); return task; } - - protected virtual async Task ConfigureAsync(IContainerService factoryService) - { - await Task.FromResult(0); - } - + private void InitializeHttpApiEndpoint() { _httpServer = new HttpServer(); @@ -103,7 +83,7 @@ private void InitializeHttpApiEndpoint() _container.GetInstance().RegisterEndpoint(httpApiDispatcherEndpoint); var httpRequestDispatcher = new HttpRequestDispatcher(_httpServer); - + httpRequestDispatcher.MapFolder("App", StoragePath.AppRoot); httpRequestDispatcher.MapFolder("Storage", StoragePath.Root); } @@ -123,41 +103,35 @@ private bool TryInitializeAzureCloudApiEndpoint() return false; } - private void InitializeLogger() + private void Startup() { - if (Log.Instance == null) + try { - var udpLogger = new UdpLogger(); - udpLogger.Start(); + var stopwatch = Stopwatch.StartNew(); - udpLogger.ExposeToApi(_container.GetInstance()); + UdpLogger udpLogger = null; + if (Log.Instance == null) + { + udpLogger = new UdpLogger(); + udpLogger.Start(); + Log.Instance = udpLogger; + } - Log.Instance = udpLogger; - } - - Log.Info("Starting..."); - } + Log.Info("Starting..."); + + RegisterServices(); - private void InitializeCore() - { - try - { - var stopwatch = Stopwatch.StartNew(); - - InitializeLogger(); InitializeHttpApiEndpoint(); - - LoadControllerSettings(); - InitializeDiscovery(); - + TryConfigure(); - + LoadNonControllerSettings(); ResetActuatorStates(); StartHttpServer(); ExposeToApi(); + udpLogger?.ExposeToApi(_container.GetInstance()); AttachComponentHistoryTracking(); @@ -165,10 +139,10 @@ private void InitializeCore() { service.OnStartupCompleted(); } - + stopwatch.Stop(); Log.Info("Startup completed after " + stopwatch.Elapsed); - + _container.GetInstance().Set("Health/StartupDuration", stopwatch.Elapsed); _container.GetInstance().Set("Health/StartupTimestamp", DateTime.Now); _container.GetInstance().Run(); @@ -179,6 +153,45 @@ private void InitializeCore() } } + private void RegisterServices() + { + var containerService = new ContainerService(_container); + + _container.RegisterSingleton(); + + _container.RegisterSingleton(() => new HealthServiceOptions { StatusLed = _options.StatusLedNumber }); + _container.RegisterSingleton(); + + _container.RegisterSingleton(); + + _container.RegisterSingleton(); + + _container.RegisterSingleton(); // TODO: Create interface! + _container.RegisterSingleton(); + + _container.RegisterSingleton(() => containerService); + _container.RegisterSingleton(); + _container.RegisterSingleton(); + _container.RegisterSingleton(); + _container.RegisterSingleton(); + + _container.RegisterSingleton(); + _container.RegisterSingleton(); + _container.RegisterSingleton(); + _container.RegisterSingleton(); + + _container.RegisterSingleton(); + _container.RegisterSingleton(); + _container.RegisterSingleton(); + + _container.RegisterSingleton(); + _container.RegisterSingleton(); + + Initializer?.RegisterServices(containerService); + + _container.Verify(); + } + private void StartHttpServer() { try @@ -208,33 +221,12 @@ private void ResetActuatorStates() } } - private void InitializeDiscovery() - { - var discoveryServer = new DiscoveryServer(this); - discoveryServer.Start(); - } - - private void LoadControllerSettings() - { - Settings = new SettingsContainer(StoragePath.WithFilename("ControllerConfiguration.json")); - - Settings.SetValue("Name", "HA4IoT Controller"); - Settings.SetValue("Description", "The HA4IoT controller which is responsible for this house."); - Settings.SetValue("Language", "EN"); - - Settings.Load(); - Settings.Save(); - } - private void TryConfigure() { try { Log.Info("Starting configuration"); - Initializer?.RegisterServices(); - Initializer?.Initialize(); - - ConfigureAsync(_container.GetInstance()).Wait(); + Initializer?.Configure(_container.GetInstance()).Wait(); } catch (Exception exception) { diff --git a/SDK/HA4IoT.Logger/UdpLogger.cs b/SDK/HA4IoT.Logger/UdpLogger.cs index 19ab0af1..86acfac2 100644 --- a/SDK/HA4IoT.Logger/UdpLogger.cs +++ b/SDK/HA4IoT.Logger/UdpLogger.cs @@ -45,11 +45,11 @@ public void Start() _timer.Change(0, Timeout.Infinite); } - public void ExposeToApi(IApiService apiController) + public void ExposeToApi(IApiService apiService) { - if (apiController == null) throw new ArgumentNullException(nameof(apiController)); + if (apiService == null) throw new ArgumentNullException(nameof(apiService)); - apiController.RouteRequest("trace", HandleApiGet); + apiService.RouteRequest("trace", HandleApiGet); } public void Verbose(string message) diff --git a/SDK/HA4IoT.PersonalAgent/SynonymService.cs b/SDK/HA4IoT.PersonalAgent/SynonymService.cs index 8cef906a..c0439246 100644 --- a/SDK/HA4IoT.PersonalAgent/SynonymService.cs +++ b/SDK/HA4IoT.PersonalAgent/SynonymService.cs @@ -7,12 +7,13 @@ using HA4IoT.Contracts.Components; using HA4IoT.Contracts.Logging; using HA4IoT.Contracts.Sensors; +using HA4IoT.Contracts.Services; using HA4IoT.Networking; using ServiceBase = HA4IoT.Contracts.Services.ServiceBase; namespace HA4IoT.PersonalAgent { - public class SynonymService : ServiceBase + public class SynonymService : ServiceBase, IApiExposedService { private readonly IComponentService _componentService; private readonly Dictionary> _areaSynonyms = new Dictionary>(); @@ -121,7 +122,7 @@ public IList GetComponentStatesBySynonym(string synonym) return _componentStateSynonyms.Where(i => i.Value.Any(s => s.Equals(synonym, StringComparison.CurrentCultureIgnoreCase))).Select(i => i.Key).ToList(); } - public override void HandleApiRequest(IApiContext apiContext) + public void HandleApiCall(IApiContext apiContext) { apiContext.Response.SetNamedObject("AreaSynonyms", _storage.ConvertAreaSynonymsToJsonObject(_areaSynonyms)); diff --git a/SDK/HA4IoT.Sensors/Buttons/Button.cs b/SDK/HA4IoT.Sensors/Buttons/Button.cs index eedc3f6e..79ca6a59 100644 --- a/SDK/HA4IoT.Sensors/Buttons/Button.cs +++ b/SDK/HA4IoT.Sensors/Buttons/Button.cs @@ -45,16 +45,19 @@ public ITrigger GetPressedLongTrigger() return _pressedLongTrigger; } - public override void HandleApiCommand(IApiContext apiContext) + public override void HandleApiCall(IApiContext apiContext) { - string action = apiContext.Request.GetNamedString("duration", string.Empty); - if (action.Equals(ButtonPressedDuration.Long.ToString(), StringComparison.OrdinalIgnoreCase)) + if (apiContext.CallType == ApiCallType.Command) { - OnPressedLong(); - } - else - { - OnPressedShortlyShort(); + string action = apiContext.Request.GetNamedString("duration", string.Empty); + if (action.Equals(ButtonPressedDuration.Long.ToString(), StringComparison.OrdinalIgnoreCase)) + { + OnPressedLong(); + } + else + { + OnPressedShortlyShort(); + } } } diff --git a/SDK/HA4IoT.Sensors/Buttons/ButtonExtensions.cs b/SDK/HA4IoT.Sensors/Buttons/ButtonExtensions.cs index 9d945ed3..f925ef49 100644 --- a/SDK/HA4IoT.Sensors/Buttons/ButtonExtensions.cs +++ b/SDK/HA4IoT.Sensors/Buttons/ButtonExtensions.cs @@ -1,68 +1,12 @@ using System; using HA4IoT.Contracts.Areas; using HA4IoT.Contracts.Components; -using HA4IoT.Contracts.Hardware; using HA4IoT.Contracts.Sensors; namespace HA4IoT.Sensors.Buttons { public static class ButtonExtensions { - public static IArea WithVirtualButton(this IArea area, Enum id, Action initializer = null) - { - if (area == null) throw new ArgumentNullException(nameof(area)); - - var virtualButton = new Button(ComponentIdFactory.Create(area.Id, id), new EmptyButtonEndpoint(), area.Controller.TimerService); - initializer?.Invoke(virtualButton); - - area.AddComponent(virtualButton); - return area; - } - - public static IArea WithButton(this IArea area, Enum id, IBinaryInput input, Action initializer = null) - { - if (area == null) throw new ArgumentNullException(nameof(area)); - if (input == null) throw new ArgumentNullException(nameof(input)); - - var button = new Button( - ComponentIdFactory.Create(area.Id, id), - new PortBasedButtonEndpoint(input), - area.Controller.TimerService); - - initializer?.Invoke(button); - - area.AddComponent(button); - return area; - } - - public static IArea WithRollerShutterButtons( - this IArea area, - Enum upId, - IBinaryInput upInput, - Enum downId, - IBinaryInput downInput) - { - if (area == null) throw new ArgumentNullException(nameof(area)); - if (upInput == null) throw new ArgumentNullException(nameof(upInput)); - if (downInput == null) throw new ArgumentNullException(nameof(downInput)); - - var upButton = new Button( - ComponentIdFactory.Create(area.Id, upId), - new PortBasedButtonEndpoint(upInput), - area.Controller.TimerService); - - area.AddComponent(upButton); - - var downButton = new Button( - ComponentIdFactory.Create(area.Id, downId), - new PortBasedButtonEndpoint(downInput), - area.Controller.TimerService); - - area.AddComponent(downButton); - - return area; - } - public static IButton WithPressedShortlyAction(this IButton button, Action action) { if (button == null) throw new ArgumentNullException(nameof(button)); diff --git a/SDK/HA4IoT.Sensors/HA4IoT.Sensors.csproj b/SDK/HA4IoT.Sensors/HA4IoT.Sensors.csproj index 7360bb7b..498eff7f 100644 --- a/SDK/HA4IoT.Sensors/HA4IoT.Sensors.csproj +++ b/SDK/HA4IoT.Sensors/HA4IoT.Sensors.csproj @@ -119,6 +119,7 @@ + @@ -143,10 +144,6 @@ {E1EDAC4B-83B9-46F4-9F6A-3BAE97D79F29} HA4IoT.Contracts - - {2BBEF090-4FEE-4FB7-9CF1-F6597F2C53EA} - HA4IoT.Core - {D4E0A3F9-6521-4AEE-815A-E2A60323FB63} HA4IoT.Networking diff --git a/SDK/HA4IoT.Sensors/MotionDetectors/MotionDetector.cs b/SDK/HA4IoT.Sensors/MotionDetectors/MotionDetector.cs index 3399d256..36376528 100644 --- a/SDK/HA4IoT.Sensors/MotionDetectors/MotionDetector.cs +++ b/SDK/HA4IoT.Sensors/MotionDetectors/MotionDetector.cs @@ -57,10 +57,8 @@ public override IList GetSupportedStates() return new List {MotionDetectorStateId.Idle, MotionDetectorStateId.MotionDetected}; } - public override void HandleApiCommand(IApiContext apiContext) + public override void HandleApiCall(IApiContext apiContext) { - base.HandleApiCommand(apiContext); - if (apiContext.Request.ContainsKey("action")) { string action = apiContext.Request.GetNamedString("action"); diff --git a/SDK/HA4IoT.Sensors/MotionDetectors/MotionDetectorExtensions.cs b/SDK/HA4IoT.Sensors/MotionDetectors/MotionDetectorExtensions.cs index 41df93d7..aab40899 100644 --- a/SDK/HA4IoT.Sensors/MotionDetectors/MotionDetectorExtensions.cs +++ b/SDK/HA4IoT.Sensors/MotionDetectors/MotionDetectorExtensions.cs @@ -1,28 +1,12 @@ using System; using HA4IoT.Contracts.Areas; using HA4IoT.Contracts.Components; -using HA4IoT.Contracts.Hardware; using HA4IoT.Contracts.Sensors; -using HA4IoT.Contracts.Services; namespace HA4IoT.Sensors.MotionDetectors { public static class MotionDetectorExtensions { - public static IArea WithMotionDetector(this IArea area, Enum id, IBinaryInput input) - { - if (area == null) throw new ArgumentNullException(nameof(area)); - if (input == null) throw new ArgumentNullException(nameof(input)); - - var motionDetector = new MotionDetector( - ComponentIdFactory.Create(area.Id, id), - new PortBasedMotionDetectorEndpoint(input), - area.Controller.ServiceLocator.GetService()); - - area.AddComponent(motionDetector); - return area; - } - public static IMotionDetector GetMotionDetector(this IArea area, Enum id) { if (area == null) throw new ArgumentNullException(nameof(area)); diff --git a/SDK/HA4IoT.Sensors/SensorFactory.cs b/SDK/HA4IoT.Sensors/SensorFactory.cs new file mode 100644 index 00000000..056b9ebc --- /dev/null +++ b/SDK/HA4IoT.Sensors/SensorFactory.cs @@ -0,0 +1,97 @@ +using System; +using HA4IoT.Contracts.Areas; +using HA4IoT.Contracts.Components; +using HA4IoT.Contracts.Hardware; +using HA4IoT.Contracts.Sensors; +using HA4IoT.Contracts.Services; +using HA4IoT.Contracts.Services.System; +using HA4IoT.Sensors.Buttons; +using HA4IoT.Sensors.MotionDetectors; + +namespace HA4IoT.Sensors +{ + public class SensorFactory + { + private readonly ITimerService _timerService; + private readonly ISchedulerService _schedulerService; + + public SensorFactory(ITimerService timerService, ISchedulerService schedulerService) + { + if (timerService == null) throw new ArgumentNullException(nameof(timerService)); + if (schedulerService == null) throw new ArgumentNullException(nameof(schedulerService)); + + _timerService = timerService; + _schedulerService = schedulerService; + } + + public IButton RegisterVirtualButton(IArea area, Enum id, Action initializer = null) + { + if (area == null) throw new ArgumentNullException(nameof(area)); + + var virtualButton = new Button(ComponentIdFactory.Create(area.Id, id), new EmptyButtonEndpoint(), _timerService); + initializer?.Invoke(virtualButton); + + area.AddComponent(virtualButton); + return virtualButton; + } + + public IButton RegisterButton(IArea area, Enum id, IBinaryInput input, Action initializer = null) + { + if (area == null) throw new ArgumentNullException(nameof(area)); + if (input == null) throw new ArgumentNullException(nameof(input)); + + var button = new Button( + ComponentIdFactory.Create(area.Id, id), + new PortBasedButtonEndpoint(input), + _timerService); + + initializer?.Invoke(button); + + area.AddComponent(button); + return button; + } + + public IArea RegisterRollerShutterButtons( + IArea area, + Enum upId, + IBinaryInput upInput, + Enum downId, + IBinaryInput downInput) + { + if (area == null) throw new ArgumentNullException(nameof(area)); + if (upInput == null) throw new ArgumentNullException(nameof(upInput)); + if (downInput == null) throw new ArgumentNullException(nameof(downInput)); + + var upButton = new Button( + ComponentIdFactory.Create(area.Id, upId), + new PortBasedButtonEndpoint(upInput), + _timerService); + + area.AddComponent(upButton); + + var downButton = new Button( + ComponentIdFactory.Create(area.Id, downId), + new PortBasedButtonEndpoint(downInput), + _timerService); + + area.AddComponent(downButton); + + return area; + } + + public IMotionDetector RegisterMotionDetector(IArea area, Enum id, IBinaryInput input) + { + if (area == null) throw new ArgumentNullException(nameof(area)); + if (input == null) throw new ArgumentNullException(nameof(input)); + + var motionDetector = new MotionDetector( + ComponentIdFactory.Create(area.Id, id), + new PortBasedMotionDetectorEndpoint(input), + _schedulerService); + + area.AddComponent(motionDetector); + + return motionDetector; + } + } +} diff --git a/SDK/HA4IoT.Services/Areas/Area.cs b/SDK/HA4IoT.Services/Areas/Area.cs index 83dc30b4..2389a98f 100644 --- a/SDK/HA4IoT.Services/Areas/Area.cs +++ b/SDK/HA4IoT.Services/Areas/Area.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using Windows.Data.Json; +using HA4IoT.Contracts.Api; using HA4IoT.Contracts.Areas; using HA4IoT.Contracts.Automations; using HA4IoT.Contracts.Components; @@ -8,6 +9,7 @@ using HA4IoT.Contracts.Core.Settings; using HA4IoT.Services.Automations; using HA4IoT.Services.Components; +using HA4IoT.Settings; namespace HA4IoT.Services.Areas { @@ -17,12 +19,15 @@ public class Area : IArea private readonly AutomationCollection _automations = new AutomationCollection(); private readonly IComponentService _componentService; + private readonly IAutomationService _automationService; - public Area(AreaId id, IComponentService componentService) + public Area(AreaId id, IComponentService componentService, IAutomationService automationService) { if (componentService == null) throw new ArgumentNullException(nameof(componentService)); + if (automationService == null) throw new ArgumentNullException(nameof(automationService)); _componentService = componentService; + _automationService = automationService; Id = id; @@ -35,9 +40,7 @@ public Area(AreaId id, IComponentService componentService) public ISettingsContainer Settings { get; } public IAreaSettingsWrapper GeneralSettingsWrapper { get; } - - public IController AreaService { get; } - + public void AddComponent(IComponent component) { if (component == null) throw new ArgumentNullException(nameof(component)); @@ -76,7 +79,7 @@ public TComponent GetComponent(ComponentId id) where TComponent : IC public void AddAutomation(IAutomation automation) { _automations.AddUnique(automation.Id, automation); - AreaService.AddAutomation(automation); + _automationService.AddAutomation(automation); } public IList GetAutomations() where TAutomation : IAutomation @@ -98,5 +101,14 @@ public JsonObject ExportConfigurationToJsonObject() { return Settings.Export(); } + + public JsonObject GetStatus() + { + return null; + } + + public void HandleApiCall(IApiContext apiContext) + { + } } } \ No newline at end of file diff --git a/SDK/HA4IoT.Services/Areas/AreaService.cs b/SDK/HA4IoT.Services/Areas/AreaService.cs index 76268c89..72c3ea87 100644 --- a/SDK/HA4IoT.Services/Areas/AreaService.cs +++ b/SDK/HA4IoT.Services/Areas/AreaService.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using HA4IoT.Contracts.Areas; +using HA4IoT.Contracts.Automations; using HA4IoT.Contracts.Components; using HA4IoT.Contracts.Services; @@ -9,20 +10,24 @@ namespace HA4IoT.Services.Areas public class AreaService : ServiceBase, IAreaService { private readonly AreaCollection _areas = new AreaCollection(); + private readonly IComponentService _componentService; - - public AreaService(IComponentService componentService) + private readonly IAutomationService _automationService; + + public AreaService(IComponentService componentService, IAutomationService automationService) { if (componentService == null) throw new ArgumentNullException(nameof(componentService)); + if (automationService == null) throw new ArgumentNullException(nameof(automationService)); _componentService = componentService; + _automationService = automationService; } public IArea CreateArea(AreaId id) { if (id == null) throw new ArgumentNullException(nameof(id)); - var area = new Area(id, _componentService); + var area = new Area(id, _componentService, _automationService); _areas.AddUnique(id, area); return area; diff --git a/SDK/HA4IoT.Services/ControllerSlave/ControllerSlaveService.cs b/SDK/HA4IoT.Services/ControllerSlave/ControllerSlaveService.cs index 80af7f68..52ab9c2a 100644 --- a/SDK/HA4IoT.Services/ControllerSlave/ControllerSlaveService.cs +++ b/SDK/HA4IoT.Services/ControllerSlave/ControllerSlaveService.cs @@ -37,9 +37,9 @@ public ControllerSlaveService(ControllerSlaveServiceOptions options, ISchedulerS scheduler.RegisterSchedule("ControllerSlavePolling", TimeSpan.FromMinutes(5), PullValues); } - public override JsonObject ExportStatusToJsonObject() + public override JsonObject GetStatus() { - var status = base.ExportStatusToJsonObject(); + var status = base.GetStatus(); status.SetNamedDateTime("LastPull", _lastPull); status.SetNamedDateTime("LastSuccessfulPull", _lastSuccessfulPull); diff --git a/SDK/HA4IoT.Services/Environment/DaylightService.cs b/SDK/HA4IoT.Services/Environment/DaylightService.cs index 3233ae89..e4f410a8 100644 --- a/SDK/HA4IoT.Services/Environment/DaylightService.cs +++ b/SDK/HA4IoT.Services/Environment/DaylightService.cs @@ -24,9 +24,9 @@ public DaylightService(IDaylightProvider provider, IDateTimeService dateTimeServ public TimeSpan Sunset { get; private set; } public DateTime? Timestamp { get; private set; } - public override JsonObject ExportStatusToJsonObject() + public override JsonObject GetStatus() { - var status = base.ExportStatusToJsonObject(); + var status = base.GetStatus(); status.SetNamedTimeSpan("Sunrise", Sunrise); status.SetNamedTimeSpan("Sunset", Sunset); status.SetNamedDateTime("Timestamp", Timestamp); diff --git a/SDK/HA4IoT.Services/Environment/OutdoorTemperatureService.cs b/SDK/HA4IoT.Services/Environment/OutdoorTemperatureService.cs index 1dc19607..762b8e65 100644 --- a/SDK/HA4IoT.Services/Environment/OutdoorTemperatureService.cs +++ b/SDK/HA4IoT.Services/Environment/OutdoorTemperatureService.cs @@ -31,9 +31,9 @@ private void Update(object sender, OutdoorTemperatureFetchedEventArgs e) Timestamp = _dateTimeService.Now; } - public override JsonObject ExportStatusToJsonObject() + public override JsonObject GetStatus() { - var status = base.ExportStatusToJsonObject(); + var status = base.GetStatus(); status.SetNamedNumber("OutdoorTemperature", OutdoorTemperature); status.SetNamedDateTime("Timestamp", Timestamp); diff --git a/SDK/HA4IoT.Services/Environment/OutdootHumidityService.cs b/SDK/HA4IoT.Services/Environment/OutdootHumidityService.cs index fc6a8567..dab9f935 100644 --- a/SDK/HA4IoT.Services/Environment/OutdootHumidityService.cs +++ b/SDK/HA4IoT.Services/Environment/OutdootHumidityService.cs @@ -31,9 +31,9 @@ private void Update(object sender, OutdoorHumidityFetchedEventArgs e) Timestamp = _dateTimeService.Now; } - public override JsonObject ExportStatusToJsonObject() + public override JsonObject GetStatus() { - var status = base.ExportStatusToJsonObject(); + var status = base.GetStatus(); status.SetNamedNumber("OutdoorHumidity", OutdoorHumidity); status.SetNamedDateTime("Timestamp", Timestamp); diff --git a/SDK/HA4IoT.Services/Environment/WeatherService.cs b/SDK/HA4IoT.Services/Environment/WeatherService.cs index 6681f6e7..8d19fe28 100644 --- a/SDK/HA4IoT.Services/Environment/WeatherService.cs +++ b/SDK/HA4IoT.Services/Environment/WeatherService.cs @@ -24,9 +24,9 @@ public WeatherService(IWeatherProvider provider, IDateTimeService dateTimeServic public Weather Weather { get; private set; } - public override JsonObject ExportStatusToJsonObject() + public override JsonObject GetStatus() { - var status = base.ExportStatusToJsonObject(); + var status = base.GetStatus(); status.SetNamedEnum("Weather", Weather); status.SetNamedDateTime("Timestamp", Timestamp); diff --git a/SDK/HA4IoT.Services/HA4IoT.Services.csproj b/SDK/HA4IoT.Services/HA4IoT.Services.csproj index 57931b65..76dd38f0 100644 --- a/SDK/HA4IoT.Services/HA4IoT.Services.csproj +++ b/SDK/HA4IoT.Services/HA4IoT.Services.csproj @@ -147,6 +147,10 @@ {D4E0A3F9-6521-4AEE-815A-E2A60323FB63} HA4IoT.Networking + + {600BC3F2-2A09-4A8E-9126-1F9ACCD7D879} + HA4IoT.Settings + {39819B8F-40F8-418A-AD3A-92A8C8D63268} HA4IoT.Hardware.Pi2 diff --git a/SDK/HA4IoT.Services/Health/HealthService.cs b/SDK/HA4IoT.Services/Health/HealthService.cs index c7ddb860..7ca9d0c2 100644 --- a/SDK/HA4IoT.Services/Health/HealthService.cs +++ b/SDK/HA4IoT.Services/Health/HealthService.cs @@ -11,7 +11,7 @@ namespace HA4IoT.Services.Health { - public class HealthService : ServiceBase + public class HealthService : ServiceBase, IApiExposedService { private readonly ISystemInformationService _systemInformationService; @@ -46,7 +46,7 @@ public HealthService( timerService.Tick += Tick; } - public override void HandleApiCommand(IApiContext apiContext) + public void HandleApiCall(IApiContext apiContext) { ResetStatistics(); } diff --git a/SDK/HA4IoT.Services/Scheduling/SchedulerService.cs b/SDK/HA4IoT.Services/Scheduling/SchedulerService.cs index 90be388c..917f5635 100644 --- a/SDK/HA4IoT.Services/Scheduling/SchedulerService.cs +++ b/SDK/HA4IoT.Services/Scheduling/SchedulerService.cs @@ -13,7 +13,7 @@ namespace HA4IoT.Services.Scheduling { - public class SchedulerService : Contracts.Services.ServiceBase, ISchedulerService + public class SchedulerService : ServiceBase, ISchedulerService { private readonly object _syncRoot = new object(); private readonly Dictionary _schedules = new Dictionary(); @@ -32,7 +32,7 @@ public TimedAction In(TimeSpan dueTime) return new TimedAction(dueTime, TimeSpan.Zero, _timerService); } - public override void HandleApiRequest(IApiContext apiContext) + public void HandleApiCall(IApiContext apiContext) { lock (_syncRoot) { diff --git a/SDK/HA4IoT.Services/System/ContainerService.cs b/SDK/HA4IoT.Services/System/ContainerService.cs index 912f2f7b..16d25081 100644 --- a/SDK/HA4IoT.Services/System/ContainerService.cs +++ b/SDK/HA4IoT.Services/System/ContainerService.cs @@ -1,11 +1,11 @@ using System; -using HA4IoT.Contracts.Services; +using System.Collections.Generic; using HA4IoT.Contracts.Services.System; using SimpleInjector; namespace HA4IoT.Services.System { - public class ContainerService : ServiceBase, IContainerService + public class ContainerService : IContainerService { private readonly Container _container; @@ -21,6 +21,11 @@ public TService GetInstance() where TService : class return _container.GetInstance(); } + public IEnumerable GetCurrentRegistrations() + { + return _container.GetCurrentRegistrations(); + } + public void RegisterSingleton() where TConcrete : class { _container.RegisterSingleton(); diff --git a/SDK/HA4IoT.Services/System/DateTimeService.cs b/SDK/HA4IoT.Services/System/DateTimeService.cs index 4a7ebdee..1d4e9ccf 100644 --- a/SDK/HA4IoT.Services/System/DateTimeService.cs +++ b/SDK/HA4IoT.Services/System/DateTimeService.cs @@ -14,7 +14,7 @@ public class DateTimeService : ServiceBase, IDateTimeService public DateTime Now => DateTime.Now; - public override void HandleApiRequest(IApiContext apiContext) + public void HandleApiCall(IApiContext apiContext) { apiContext.Response.SetNamedDateTime("Date", Date); apiContext.Response.SetNamedTimeSpan("Time", Time); diff --git a/SDK/HA4IoT.Services/System/SystemInformationService.cs b/SDK/HA4IoT.Services/System/SystemInformationService.cs index 91d991be..b65d26cd 100644 --- a/SDK/HA4IoT.Services/System/SystemInformationService.cs +++ b/SDK/HA4IoT.Services/System/SystemInformationService.cs @@ -47,7 +47,7 @@ public void Set(string name, DateTime? value) _values[name] = value.ToJsonValue(); } - public override void HandleApiRequest(IApiContext apiContext) + public void HandleApiCall(IApiContext apiContext) { apiContext.Response = new JsonObject(); diff --git a/SDK/HA4IoT.Settings/ControllerSettings.cs b/SDK/HA4IoT.Settings/ControllerSettings.cs new file mode 100644 index 00000000..43670f1d --- /dev/null +++ b/SDK/HA4IoT.Settings/ControllerSettings.cs @@ -0,0 +1,58 @@ +using Windows.Data.Json; +using HA4IoT.Contracts.Core; + +namespace HA4IoT.Settings +{ + public class ControllerSettings + { + private readonly SettingsContainer _settingsContainer; + + public ControllerSettings() + { + _settingsContainer = new SettingsContainer(StoragePath.WithFilename("ControllerConfiguration.json")); + + _settingsContainer.SetValue("Name", "HA4IoT Controller"); + _settingsContainer.SetValue("Description", "The HA4IoT controller which is responsible for this house."); + _settingsContainer.SetValue("Language", "EN"); + + // Ensure that the initial values are overridden with the already saved ones by loading the settings before saving. + _settingsContainer.Load(); + _settingsContainer.Save(); + } + + public string Language + { + get { return _settingsContainer.GetString(nameof(Language)); } + set + { + _settingsContainer.SetValue(nameof(Language), value); + _settingsContainer.Save(); + } + } + + public string Name + { + get { return _settingsContainer.GetString(nameof(Name)); } + set + { + _settingsContainer.SetValue(nameof(Name), value); + _settingsContainer.Save(); + } + } + + public string Description + { + get { return _settingsContainer.GetString(nameof(Description)); } + set + { + _settingsContainer.SetValue(nameof(Description), value); + _settingsContainer.Save(); + } + } + + public IJsonValue Export() + { + return _settingsContainer.Export(); + } + } +} diff --git a/SDK/HA4IoT.Settings/HA4IoT.Settings.csproj b/SDK/HA4IoT.Settings/HA4IoT.Settings.csproj index f9922049..54338772 100644 --- a/SDK/HA4IoT.Settings/HA4IoT.Settings.csproj +++ b/SDK/HA4IoT.Settings/HA4IoT.Settings.csproj @@ -107,11 +107,18 @@ + + + + {E1EDAC4B-83B9-46F4-9F6A-3BAE97D79F29} + HA4IoT.Contracts + + 14.0 diff --git a/SDK/HA4IoT.Settings/SettingsContainer.cs b/SDK/HA4IoT.Settings/SettingsContainer.cs index 0681e198..9d8f4fb5 100644 --- a/SDK/HA4IoT.Settings/SettingsContainer.cs +++ b/SDK/HA4IoT.Settings/SettingsContainer.cs @@ -3,6 +3,8 @@ using System.IO; using System.Text; using Windows.Data.Json; +using HA4IoT.Contracts.Core.Settings; +using HA4IoT.Contracts.Logging; namespace HA4IoT.Settings { diff --git a/SDK/HA4IoT.Settings/SettingsContainerApiDispatcher.cs b/SDK/HA4IoT.Settings/SettingsContainerApiDispatcher.cs index 7b20f124..7e4120f5 100644 --- a/SDK/HA4IoT.Settings/SettingsContainerApiDispatcher.cs +++ b/SDK/HA4IoT.Settings/SettingsContainerApiDispatcher.cs @@ -1,4 +1,6 @@ using System; +using HA4IoT.Contracts.Api; +using HA4IoT.Contracts.Core.Settings; namespace HA4IoT.Settings { diff --git a/SDK/Hardware/HA4IoT.Hardware.CCTools/CCToolsBoardBase.cs b/SDK/Hardware/HA4IoT.Hardware.CCTools/CCToolsBoardBase.cs index ef2515aa..d07d6e7d 100644 --- a/SDK/Hardware/HA4IoT.Hardware.CCTools/CCToolsBoardBase.cs +++ b/SDK/Hardware/HA4IoT.Hardware.CCTools/CCToolsBoardBase.cs @@ -142,29 +142,32 @@ public void FetchState() } } - public void HandleApiCommand(IApiContext apiContext) + public void HandleApiCall(IApiContext apiContext) { - JsonArray state = apiContext.Request.GetNamedArray("state", null); - if (state != null) + if (apiContext.CallType == ApiCallType.Command) { - byte[] buffer = JsonValueToByteArray(state); - SetState(buffer); - } + JsonArray state = apiContext.Request.GetNamedArray("state", null); + if (state != null) + { + byte[] buffer = JsonValueToByteArray(state); + SetState(buffer); + } - var commit = apiContext.Request.GetNamedBoolean("commit", true); - if (commit) - { - CommitChanges(); + var commit = apiContext.Request.GetNamedBoolean("commit", true); + if (commit) + { + CommitChanges(); + } } - } - public void HandleApiRequest(IApiContext apiContext) - { - var result = new JsonObject(); - result.SetNamedValue("state", GetState().ToJsonValue()); - result.SetNamedValue("committed-state", GetCommittedState().ToJsonValue()); + if (apiContext.CallType == ApiCallType.Request) + { + var result = new JsonObject(); + result.SetNamedValue("state", GetState().ToJsonValue()); + result.SetNamedValue("committed-state", GetCommittedState().ToJsonValue()); - apiContext.Response = result; + apiContext.Response = result; + } } internal BinaryState GetPortState(int pinNumber) diff --git a/SDK/Hardware/HA4IoT.Hardware.I2CHardwareBridge/HA4IoT.Hardware.I2CHardwareBridge.csproj b/SDK/Hardware/HA4IoT.Hardware.I2CHardwareBridge/HA4IoT.Hardware.I2CHardwareBridge.csproj index 9394616d..0aefd9a8 100644 --- a/SDK/Hardware/HA4IoT.Hardware.I2CHardwareBridge/HA4IoT.Hardware.I2CHardwareBridge.csproj +++ b/SDK/Hardware/HA4IoT.Hardware.I2CHardwareBridge/HA4IoT.Hardware.I2CHardwareBridge.csproj @@ -113,7 +113,6 @@ - diff --git a/SDK/Hardware/HA4IoT.Hardware.I2CHardwareBridge/I2CHardwareBridge.cs b/SDK/Hardware/HA4IoT.Hardware.I2CHardwareBridge/I2CHardwareBridge.cs index d2dbd09b..115cfa4a 100644 --- a/SDK/Hardware/HA4IoT.Hardware.I2CHardwareBridge/I2CHardwareBridge.cs +++ b/SDK/Hardware/HA4IoT.Hardware.I2CHardwareBridge/I2CHardwareBridge.cs @@ -11,13 +11,13 @@ public class I2CHardwareBridge : IDevice private readonly I2CSlaveAddress _address; private readonly II2CBusService _i2CBus; - public I2CHardwareBridge(I2CSlaveAddress address, II2CBusService i2cBus, ISchedulerService schedulerService) + public I2CHardwareBridge(I2CSlaveAddress address, II2CBusService i2CBus, ISchedulerService schedulerService) { - if (i2cBus == null) throw new ArgumentNullException(nameof(i2cBus)); + if (i2CBus == null) throw new ArgumentNullException(nameof(i2CBus)); if (schedulerService == null) throw new ArgumentNullException(nameof(schedulerService)); _address = address; - _i2CBus = i2cBus; + _i2CBus = i2CBus; DHT22Accessor = new DHT22Accessor(this, schedulerService); } @@ -26,11 +26,7 @@ public I2CHardwareBridge(I2CSlaveAddress address, II2CBusService i2cBus, ISchedu public DHT22Accessor DHT22Accessor { get; } - public void HandleApiCommand(IApiContext apiContext) - { - } - - public void HandleApiRequest(IApiContext apiContext) + public void HandleApiCall(IApiContext apiContext) { } diff --git a/SDK/Hardware/HA4IoT.Hardware.I2CHardwareBridge/I2CHardwareBridgeConfigurationExtender.cs b/SDK/Hardware/HA4IoT.Hardware.I2CHardwareBridge/I2CHardwareBridgeConfigurationExtender.cs deleted file mode 100644 index 20062c93..00000000 --- a/SDK/Hardware/HA4IoT.Hardware.I2CHardwareBridge/I2CHardwareBridgeConfigurationExtender.cs +++ /dev/null @@ -1,72 +0,0 @@ -using System; -using System.Xml.Linq; -using HA4IoT.Configuration; -using HA4IoT.Contracts.Configuration; -using HA4IoT.Contracts.Core; -using HA4IoT.Contracts.Hardware; -using HA4IoT.Contracts.Sensors; -using HA4IoT.Contracts.Services; -using HA4IoT.Contracts.Services.System; - -namespace HA4IoT.Hardware.I2CHardwareBridge -{ - public class I2CHardwareBridgeConfigurationExtender : ConfigurationExtenderBase - { - public I2CHardwareBridgeConfigurationExtender(ConfigurationParser parser, IController controller) - : base(parser, controller) - { - Namespace = "http://www.ha4iot.de/ConfigurationExtenders/I2CHardwareBridge"; - } - - public override IDevice ParseDevice(XElement element) - { - if (element == null) throw new ArgumentNullException(nameof(element)); - - switch (element.Name.LocalName) - { - case "I2CHardwareBridge": return ParseI2CHardwareBridge(element); - - default: throw new ConfigurationInvalidException("Device not supported.", element); - } - } - - public override INumericValueSensorEndpoint ParseNumericValueSensor(XElement element) - { - if (element == null) throw new ArgumentNullException(nameof(element)); - - switch (element.Name.LocalName) - { - case "TemperatureSensor": return ParseTemperatureSensor(element); - case "HumiditySensor": return ParseHumiditySensor(element); - - default: throw new ConfigurationInvalidException("Sensor not supported.", element); - } - } - - private INumericValueSensorEndpoint ParseHumiditySensor(XElement element) - { - var i2cHardwareBridge = - Controller.GetDevice( - new DeviceId(element.GetMandatoryStringFromAttribute("i2cHardwareBridgeDeviceId"))); - - return i2cHardwareBridge.DHT22Accessor.GetHumiditySensor((byte)element.GetMandatoryIntFromAttribute("sensorId")); - } - - private INumericValueSensorEndpoint ParseTemperatureSensor(XElement element) - { - var i2cHardwareBridge = - Controller.GetDevice( - new DeviceId(element.GetMandatoryStringFromAttribute("i2cHardwareBridgeDeviceId"))); - - return i2cHardwareBridge.DHT22Accessor.GetTemperatureSensor((byte)element.GetMandatoryIntFromAttribute("sensorId")); - } - - private IDevice ParseI2CHardwareBridge(XElement element) - { - return new I2CHardwareBridge( - new I2CSlaveAddress(element.GetMandatoryIntFromAttribute("i2cAddress")), - Controller.GetDevice(new DeviceId(element.GetStringFromAttribute("i2cBus", "II2CBus.default"))), - Controller.ServiceLocator.GetService()); - } - } -} diff --git a/SDK/Hardware/HA4IoT.Hardware/BuiltInI2CBusService.cs b/SDK/Hardware/HA4IoT.Hardware/BuiltInI2CBusService.cs index 65fbf11d..0594a4cb 100644 --- a/SDK/Hardware/HA4IoT.Hardware/BuiltInI2CBusService.cs +++ b/SDK/Hardware/HA4IoT.Hardware/BuiltInI2CBusService.cs @@ -23,7 +23,8 @@ public BuiltInI2CBusService() DeviceInformationCollection deviceInformation = DeviceInformation.FindAllAsync(deviceSelector).AsTask().Result; if (deviceInformation.Count == 0) { - throw new InvalidOperationException("I2C bus not found."); + //throw new InvalidOperationException("I2C bus not found."); + return; } _i2CBusId = deviceInformation.First().Id; diff --git a/Tests/HA4IoT.Actuators.Tests/AutomaticTurnOnAndOffAutomationTests.cs b/Tests/HA4IoT.Actuators.Tests/AutomaticTurnOnAndOffAutomationTests.cs index 38b735a5..e35ef142 100644 --- a/Tests/HA4IoT.Actuators.Tests/AutomaticTurnOnAndOffAutomationTests.cs +++ b/Tests/HA4IoT.Actuators.Tests/AutomaticTurnOnAndOffAutomationTests.cs @@ -2,8 +2,7 @@ using FluentAssertions; using HA4IoT.Automations; using HA4IoT.Contracts.Actuators; -using HA4IoT.Core; -using HA4IoT.Core.Scheduling; +using HA4IoT.Services.Scheduling; using HA4IoT.Tests.Mockups; using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; diff --git a/Tests/HA4IoT.Actuators.Tests/HA4IoT.Actuators.Tests.csproj b/Tests/HA4IoT.Actuators.Tests/HA4IoT.Actuators.Tests.csproj index 202c68c1..f2646afb 100644 --- a/Tests/HA4IoT.Actuators.Tests/HA4IoT.Actuators.Tests.csproj +++ b/Tests/HA4IoT.Actuators.Tests/HA4IoT.Actuators.Tests.csproj @@ -162,6 +162,10 @@ {2bbef090-4fee-4fb7-9cf1-f6597f2c53ea} HA4IoT.Core + + {6FD41DDA-4369-43C1-807A-B1BC43ECBDBF} + HA4IoT.Services + {287A9BD0-4037-4ADD-986F-54056F059EAE} HA4IoT.Hardware diff --git a/Tests/HA4IoT.Actuators.Tests/RollerShutterTests.cs b/Tests/HA4IoT.Actuators.Tests/RollerShutterTests.cs index 08f81ba1..002ccd09 100644 --- a/Tests/HA4IoT.Actuators.Tests/RollerShutterTests.cs +++ b/Tests/HA4IoT.Actuators.Tests/RollerShutterTests.cs @@ -1,5 +1,6 @@ using FluentAssertions; using HA4IoT.Contracts.Actuators; +using HA4IoT.Services.Scheduling; using HA4IoT.Tests.Mockups; using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; @@ -11,7 +12,9 @@ public class RollerShutterTests [TestMethod] public void TestRollerShutter() { - var rollerShutterFactory = new TestRollerShutterFactory(new TestTimerService()); + var timerService = new TestTimerService(); + var rollerShutterFactory = new TestRollerShutterFactory(timerService, new SchedulerService(timerService)); + TestRollerShutter rollerShutter = rollerShutterFactory.CreateTestRollerShutter(); rollerShutter.GetState().Equals(RollerShutterStateId.Off).ShouldBeEquivalentTo(true); diff --git a/Tests/HA4IoT.Automations.Tests/AutomationTests.cs b/Tests/HA4IoT.Automations.Tests/AutomationTests.cs index a1c689a3..d62f3220 100644 --- a/Tests/HA4IoT.Automations.Tests/AutomationTests.cs +++ b/Tests/HA4IoT.Automations.Tests/AutomationTests.cs @@ -4,7 +4,6 @@ using HA4IoT.Conditions; using HA4IoT.Conditions.Specialized; using HA4IoT.Contracts.Actuators; -using HA4IoT.Contracts.Services.System; using HA4IoT.Tests.Mockups; using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; @@ -39,6 +38,7 @@ public void Automation_Toggle() [TestMethod] public void Automation_WithCondition() { + var dateTimeService = new TestDateTimeService(); var testController = new TestController(); var automation = new Automation(AutomationIdFactory.EmptyId); @@ -50,7 +50,7 @@ public void Automation_WithCondition() automation .WithTrigger(testButton.GetPressedShortlyTrigger()) - .WithCondition(ConditionRelation.And, new TimeRangeCondition(testController.ServiceLocator.GetService()).WithStart(TimeSpan.FromHours(1)).WithEnd(TimeSpan.FromHours(2))) + .WithCondition(ConditionRelation.And, new TimeRangeCondition(dateTimeService).WithStart(TimeSpan.FromHours(1)).WithEnd(TimeSpan.FromHours(2))) .WithActionIfConditionsFulfilled(testOutput.GetSetNextStateAction()); testOutput.GetState().ShouldBeEquivalentTo(BinaryStateId.Off); diff --git a/Tests/HA4IoT.Automations.Tests/ConditionalOnAutomationTests.cs b/Tests/HA4IoT.Automations.Tests/ConditionalOnAutomationTests.cs index 1ef15967..cb3f154f 100644 --- a/Tests/HA4IoT.Automations.Tests/ConditionalOnAutomationTests.cs +++ b/Tests/HA4IoT.Automations.Tests/ConditionalOnAutomationTests.cs @@ -16,9 +16,9 @@ public void Empty_ConditionalOnAutomation() { var testController = new TestController(); var automation = new ConditionalOnAutomation(AutomationIdFactory.EmptyId, - testController.ServiceLocator.GetService(), - testController.ServiceLocator.GetService(), - testController.ServiceLocator.GetService()); + testController.SchedulerService, + testController.DateTimeService, + testController.DaylightService); var testButtonFactory = new TestButtonFactory(testController.TimerService); var testStateMachineFactory = new TestStateMachineFactory(); diff --git a/Tests/HA4IoT.Automations.Tests/RollerShutterAutomationTests.cs b/Tests/HA4IoT.Automations.Tests/RollerShutterAutomationTests.cs index e807a5f9..d01f07e3 100644 --- a/Tests/HA4IoT.Automations.Tests/RollerShutterAutomationTests.cs +++ b/Tests/HA4IoT.Automations.Tests/RollerShutterAutomationTests.cs @@ -1,8 +1,6 @@ using System; using FluentAssertions; using HA4IoT.Contracts.Actuators; -using HA4IoT.Contracts.Services; -using HA4IoT.Contracts.Services.System; using HA4IoT.Tests.Mockups; using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; @@ -85,23 +83,22 @@ private void Setup() _controller = new TestController(); _controller.SetTime(TimeSpan.Parse("12:00")); - var testRollerShutterFactory = new TestRollerShutterFactory(_controller.TimerService); + var testRollerShutterFactory = new TestRollerShutterFactory(_controller.TimerService, _controller.SchedulerService); _weatherStation = new TestWeatherStation(); _weatherStation.OutdoorTemperature = 20; _daylightService = new TestDaylightService(); _rollerShutter = testRollerShutterFactory.CreateTestRollerShutter(); - _controller.ServiceLocator.RegisterService(typeof(TestWeatherStation), _weatherStation); - _controller.AddComponent(_rollerShutter); + _controller.ComponentService.AddComponent(_rollerShutter); _automation = new RollerShutterAutomation( - AutomationIdFactory.EmptyId, - _controller.ServiceLocator.GetService(), - _controller.ServiceLocator.GetService(), + AutomationIdFactory.EmptyId, + _controller.SchedulerService, + _controller.DateTimeService, _daylightService, _weatherStation, - _controller); + _controller.ComponentService); _automation.WithRollerShutters(_rollerShutter); } diff --git a/Tests/HA4IoT.Configuration.Tests/ConfigurationParserTests.cs b/Tests/HA4IoT.Configuration.Tests/ConfigurationParserTests.cs deleted file mode 100644 index f6601bfa..00000000 --- a/Tests/HA4IoT.Configuration.Tests/ConfigurationParserTests.cs +++ /dev/null @@ -1,134 +0,0 @@ -using System; -using FluentAssertions; -using HA4IoT.Actuators.Lamps; -using HA4IoT.Actuators.RollerShutters; -using HA4IoT.Actuators.Sockets; -using HA4IoT.Contracts.Areas; -using HA4IoT.Contracts.Components; -using HA4IoT.Contracts.Core; -using HA4IoT.Contracts.Hardware; -using HA4IoT.Contracts.Services; -using HA4IoT.Contracts.Services.System; -using HA4IoT.Contracts.Services.Weather; -using HA4IoT.Hardware.CCTools; -using HA4IoT.Hardware.I2CHardwareBridge; -using HA4IoT.Sensors.Buttons; -using HA4IoT.Sensors.HumiditySensors; -using HA4IoT.Sensors.TemperatureSensors; -using HA4IoT.Sensors.Windows; -using HA4IoT.Tests.Mockups; -using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; - -namespace HA4IoT.Configuration.Tests -{ - [TestClass] - public class ConfigurationParserTests - { - [TestMethod] - public void Parse_I2CBusDevice() - { - GetController().GetDevices().Count.ShouldBeEquivalentTo(1); - } - - [TestMethod] - public void Parse_CCToolsDevices() - { - var controller = GetController(); - - controller.GetDevices().Count.ShouldBeEquivalentTo(1); - controller.GetDevices().Count.ShouldBeEquivalentTo(1); - } - - [TestMethod] - public void Parse_Areas() - { - var controller = GetController(); - - controller.GetAreas().Count.ShouldBeEquivalentTo(1); - } - - ////[TestMethod] - ////public void Parse_WeatherStation() - ////{ - //// var controller = GetController(); - //// controller.ServiceLocator.GetService(); - ////} - - [TestMethod] - public void Parse_Socket() - { - var controller = GetController(); - - // TODO: Check parameters (expose properties). - controller.GetArea(new AreaId("Bedroom")).GetComponent(new ComponentId("Bedroom.SocketWindowLeft")); - } - - [TestMethod] - public void Parse_Lamp() - { - var controller = GetController(); - - // TODO: Check parameters (expose properties). - controller.GetArea(new AreaId("Bedroom")).GetComponent(new ComponentId("Bedroom.LightCeiling")); - } - - [TestMethod] - public void Parse_Button() - { - var controller = GetController(); - - // TODO: Check parameters (expose properties). - controller.GetArea(new AreaId("Bedroom")).GetComponent