3 Commits
Author SHA1 Message Date
MasseR 9c89504399 Add target exclusions to service calls
Services can now carry excluded targets, encoded as target.exclude in
the WebSocket payload. The children's bedroom lights-off calls skip
lights labelled 'decoration'.
2026-11-14 19:36:46 +02:00
MasseR 383143024a Bedroom buttons: long off press turns the hallway lights off too 2026-11-09 12:11:34 +02:00
MasseR c5c11fe8d3 Hallway: only dim for an open bedroom door while it is ready to sleep
The parents' bedroom door is open at night for the cats, so the door
state says nothing about whoever sleeps in it. The doorway now leaks
into no one's sleep unless the bedroom reports someone present with the
lights off or dimmed far down (mmWave presence sensor); when it does,
the open door is protected like before.
2026-11-03 21:08:44 +02:00
15 changed files with 216 additions and 72 deletions

No files matched your search

+22 -7
View File
@@ -28,6 +28,7 @@ createBedroomScene = Service
, "snapshot_entities" .= [l | EntityId l <- bedroomLightTargets] , "snapshot_entities" .= [l | EntityId l <- bedroomLightTargets]
] ]
, serviceTarget= [] , serviceTarget= []
, serviceExclusions= []
} }
-- Bedroom presence -- Bedroom presence
@@ -40,6 +41,13 @@ bedroomPresenceOccupied = bedroomPresence >>> hold Unoccupied >>> arr (== Occupi
bedroomLightStatus :: HASS (Event Value) (Map T.Text LightObservation) bedroomLightStatus :: HASS (Event Value) (Map T.Text LightObservation)
bedroomLightStatus = M.fromList <$> traverse (\e -> (e,) <$> observedLight e) [e | EntityId e <- bedroomLightTargets] bedroomLightStatus = M.fromList <$> traverse (\e -> (e,) <$> observedLight e) [e | EntityId e <- bedroomLightTargets]
-- Ready to sleep: someone detected and every light off or dimmed far down
readyForSleep :: HASS (Event Value) Bool
readyForSleep = (&&) <$> bedroomPresenceOccupied <*> (all sleepLight . M.elems <$> bedroomLightStatus)
where
-- ~10% of the 0-255 brightness range
sleepLight o = not (observedOn o) || maybe False (<= 25) (observedBrightness o)
lightLevel :: HASS (Event Value) Int lightLevel :: HASS (Event Value) Int
lightLevel = entityRead "sensor.presence_sensor_bedroom_light_level" >>> AFRP.hold 1 lightLevel = entityRead "sensor.presence_sensor_bedroom_light_level" >>> AFRP.hold 1
@@ -82,14 +90,14 @@ bedroomPresenceController =
lightsOff = lightsOff =
arr (\(o, _, _, _) -> not o) arr (\(o, _, _, _) -> not o)
>>> waitFor 300 >>> waitFor 300
>>|| callService "Turn off lights" (light bedroomLightTargets Off) >>|| callService "Turn off lights" (light bedroomLightTargets [] Off)
anyLightsAreOn :: Foldable f => f LightObservation -> Bool anyLightsAreOn :: Foldable f => f LightObservation -> Bool
anyLightsAreOn = any observedOn anyLightsAreOn = any observedOn
toLight :: Bool -> T.Text -> LightObservation -> [Service] toLight :: Bool -> T.Text -> LightObservation -> [Service]
toLight _ entityId LightObservation{observedOn=False} = [light [EntityId entityId] Off] toLight _ entityId LightObservation{observedOn=False} = [light [EntityId entityId] [] Off]
toLight capped entityId LightObservation{observedOn=True, observedTemperature=t, observedBrightness=b} = toLight capped entityId LightObservation{observedOn=True, observedTemperature=t, observedBrightness=b} =
[ light [EntityId entityId] (On def [ light [EntityId entityId] [] (On def
{lightBrightness = fmap (\b' -> BrightnessAbsolute $ if capped then 140 `min` b' else b') b {lightBrightness = fmap (\b' -> BrightnessAbsolute $ if capped then 140 `min` b' else b') b
, lightColorTemperature = t , lightColorTemperature = t
}) })
@@ -122,16 +130,22 @@ bedroomButtonController = proc x -> do
callService "scene.makuuhuone_keski" (activateScene "scene.makuuhuone_keski") -< () callService "scene.makuuhuone_keski" (activateScene "scene.makuuhuone_keski") -< ()
Event (Masse (OnButton LongClick)) -> do Event (Masse (OnButton LongClick)) -> do
callService "scene.makuuhuone_kirkas" (activateScene "scene.makuuhuone_kirkas") -< () callService "scene.makuuhuone_kirkas" (activateScene "scene.makuuhuone_kirkas") -< ()
Event (Masse (OffButton LongClick)) -> do
callService "Lights off" (light [AreaId "makuuhuone"] [] Off) -< ()
callService "Hallway lights off" (light [EntityId "light.hallway_lights"] [] Off) -< ()
Event (Masse (OffButton _)) -> do Event (Masse (OffButton _)) -> do
callService "Lights off" (light [AreaId "makuuhuone"] Off) -< () callService "Lights off" (light [AreaId "makuuhuone"] [] Off) -< ()
Event (Enishen (OnButton ShortRelease)) -> do Event (Enishen (OnButton ShortRelease)) -> do
callService "scene.makuuhuone_jemina" (activateScene "scene.makuuhuone_jemina") -< () callService "scene.makuuhuone_jemina" (activateScene "scene.makuuhuone_jemina") -< ()
Event (Enishen (OnButton DoubleClick)) -> do Event (Enishen (OnButton DoubleClick)) -> do
callService "scene.makuuhuone_keski" (activateScene "scene.makuuhuone_keski") -< () callService "scene.makuuhuone_keski" (activateScene "scene.makuuhuone_keski") -< ()
Event (Enishen (OnButton LongClick)) -> do Event (Enishen (OnButton LongClick)) -> do
callService "scene.makuuhuone_kirkas" (activateScene "scene.makuuhuone_kirkas") -< () callService "scene.makuuhuone_kirkas" (activateScene "scene.makuuhuone_kirkas") -< ()
Event (Enishen (OffButton LongClick)) -> do
callService "Lights off" (light [AreaId "makuuhuone"] [] Off) -< ()
callService "Hallway lights off" (light [EntityId "light.hallway_lights"] [] Off) -< ()
Event (Enishen (OffButton _)) -> do Event (Enishen (OffButton _)) -> do
callService "Lights off" (light [AreaId "makuuhuone"] Off) -< () callService "Lights off" (light [AreaId "makuuhuone"] [] Off) -< ()
_ -> returnA -< () _ -> returnA -< ()
@@ -148,9 +162,9 @@ bedroomDrawerController =
where where
entity = EntityId "switch.bedroom_drawer_light_masse" entity = EntityId "switch.bedroom_drawer_light_masse"
lightOff = filterEvent (== Closed) lightOff = filterEvent (== Closed)
>>|| callService "drawer light off" (switchService [entity] False) >>|| callService "drawer light off" (switchService [entity] [] False)
lightOn = filterEvent (== Open) lightOn = filterEvent (== Open)
>>|| callService "drawer light on" (switchService [entity] True) >>|| callService "drawer light on" (switchService [entity] [] True)
door :: HASS (Event Value) (Event DoorState) door :: HASS (Event Value) (Event DoorState)
door = entityBool "binary_sensor.makuuhuone_ovi_contact" door = entityBool "binary_sensor.makuuhuone_ovi_contact"
@@ -178,4 +192,5 @@ humidifierController = proc x -> do
, serviceName= bool "turn_off" "turn_on" state , serviceName= bool "turn_off" "turn_on" state
, serviceData= Nothing , serviceData= Nothing
, serviceTarget= [EntityId "humidifier.makuuhuone_ilmankostutin"] , serviceTarget= [EntityId "humidifier.makuuhuone_ilmankostutin"]
, serviceExclusions= []
} }
+4 -3
View File
@@ -87,11 +87,11 @@ lightsOn :: HASS a ()
lightsOn = foldMap atTime timersOn lightsOn = foldMap atTime timersOn
>>> AFRP.onEvent (callService "Lights on" lights) >>> AFRP.onEvent (callService "Lights on" lights)
where where
lights = light [AreaId "lasten_makuuhuone"] (On def{lightBrightness=Just (BrightnessPercent 100), lightTransition = Just 5} ) lights = light [AreaId "lasten_makuuhuone"] [] (On def{lightBrightness=Just (BrightnessPercent 100), lightTransition = Just 5} )
lightsOff :: HASS a () lightsOff :: HASS a ()
lightsOff = foldMap atTime timersOff lightsOff = foldMap atTime timersOff
>>> AFRP.onEvent (callService "Lights off" (light [AreaId "lasten_makuuhuone"] Off)) >>> AFRP.onEvent (callService "Lights off" (light [AreaId "lasten_makuuhuone"] [LabelId "decoration"] Off))
childrenBedroomButton :: HASS (Event Value) (Event (IkeaButton IkeaGesture)) childrenBedroomButton :: HASS (Event Value) (Event (IkeaButton IkeaGesture))
@@ -104,7 +104,7 @@ childrenBedroomButtonController = proc x -> do
Event (OnButton ShortRelease) -> callService "scene.lasten_nukkuvalmistelu" (activateScene "scene.lasten_nukkuvalmistelu") -< () Event (OnButton ShortRelease) -> callService "scene.lasten_nukkuvalmistelu" (activateScene "scene.lasten_nukkuvalmistelu") -< ()
Event (OnButton DoubleClick) -> callService "scene.lasten_luku" (activateScene "scene.lasten_luku") -< () Event (OnButton DoubleClick) -> callService "scene.lasten_luku" (activateScene "scene.lasten_luku") -< ()
Event (OnButton LongClick) -> callService "scene.lasten_kirkas" (activateScene "scene.lasten_kirkas") -< () Event (OnButton LongClick) -> callService "scene.lasten_kirkas" (activateScene "scene.lasten_kirkas") -< ()
Event (OffButton _) -> callService "Lights off" (light [AreaId "lasten_makuuhuone"] Off) -< () Event (OffButton _) -> callService "Lights off" (light [AreaId "lasten_makuuhuone"] [LabelId "decoration"] Off) -< ()
_ -> returnA -< () _ -> returnA -< ()
newtype PM25 = PM25 Float newtype PM25 = PM25 Float
@@ -163,5 +163,6 @@ childrenAirFilterController = proc ev -> do
{ serviceDomain = "fan" { serviceDomain = "fan"
, serviceName = "set_percentage" , serviceName = "set_percentage"
, serviceTarget = [EntityId "fan.children_fan"] , serviceTarget = [EntityId "fan.children_fan"]
, serviceExclusions = []
, serviceData = Just $ toJSON percentage , serviceData = Just $ toJSON percentage
} }
+18 -8
View File
@@ -4,7 +4,8 @@
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE RecordWildCards #-}
module HomeAssistant.Controller.Hallway where module HomeAssistant.Controller.Hallway where
import HomeAssistant.Controller (Presence (..), HASS, motion, motionToPresence, callServiceDyn, light, Target (..), LightCommand (..), doorState, DoorState (Closed), callService) import HomeAssistant.Controller (Presence (..), HASS, motion, motionToPresence, callServiceDyn, light, Target (..), LightCommand (..), doorState, DoorState (..), callService)
import HomeAssistant.Controller.Bedroom (readyForSleep)
import AFRP (Event (..)) import AFRP (Event (..))
import qualified AFRP import qualified AFRP
import Data.Aeson (Value) import Data.Aeson (Value)
@@ -25,17 +26,26 @@ data ModeInput = ModeInput
{ roomTimeOfDay :: TimeOfDay { roomTimeOfDay :: TimeOfDay
, bedroomDoor :: Maybe DoorState , bedroomDoor :: Maybe DoorState
, childrenBedroomDoor :: Maybe DoorState , childrenBedroomDoor :: Maybe DoorState
, bedroomReadyForSleep :: Bool
} }
mode :: HASS (Event Value) Mode mode :: HASS (Event Value) Mode
mode = roomState >>> arr sleepMode mode = roomState >>> arr sleepMode
where where
sleepMode :: ModeInput -> Mode sleepMode :: ModeInput -> Mode
sleepMode ModeInput{bedroomDoor = Just Closed, childrenBedroomDoor = Just Closed} = Regular sleepMode ModeInput{..} = sleep
sleepMode ModeInput{..} where
-- An open parents' bedroom door only leaks into someone's sleep while
-- that someone is actually ready to sleep; an open door into an
-- empty or awake room does not need the hallway dimmed.
bedroomForLeakage = case bedroomDoor of
Just Open | not bedroomReadyForSleep -> Just Closed
door -> door
sleep
| Just Closed <- bedroomForLeakage, Just Closed <- childrenBedroomDoor = Regular
| roomTimeOfDay > TimeOfDay 20 30 0 || roomTimeOfDay < TimeOfDay 7 30 0 = Quiet | roomTimeOfDay > TimeOfDay 20 30 0 || roomTimeOfDay < TimeOfDay 7 30 0 = Quiet
| otherwise = Regular | otherwise = Regular
roomState = ModeInput <$> timeOfDay <*> masterBedroom <*> childrenBedroom roomState = ModeInput <$> timeOfDay <*> masterBedroom <*> childrenBedroom <*> readyForSleep
timeOfDay = fmap localTimeOfDay AFRP.currentTime timeOfDay = fmap localTimeOfDay AFRP.currentTime
masterBedroom = doorState "binary_sensor.makuuhuone_ovi_contact" >>> AFRP.holdKnown masterBedroom = doorState "binary_sensor.makuuhuone_ovi_contact" >>> AFRP.holdKnown
childrenBedroom = doorState "binary_sensor.lasten_makuuhuone_ovi_contact" >>> AFRP.holdKnown childrenBedroom = doorState "binary_sensor.lasten_makuuhuone_ovi_contact" >>> AFRP.holdKnown
@@ -60,8 +70,8 @@ modeC = modeTrigger >>> mconcat
] >>> ] >>>
arr (const ()) arr (const ())
where where
lightOff = callService "Lower light off" (light [EntityId "light.hallway_ceiling"] Off) lightOff = callService "Lower light off" (light [EntityId "light.hallway_ceiling"] [] Off)
lightOn = callService "Lower light back on" (light [EntityId "light.hallway_ceiling"] (On def)) lightOn = callService "Lower light back on" (light [EntityId "light.hallway_ceiling"] [] (On def))
onC :: HASS (Event Value) () onC :: HASS (Event Value) ()
onC = proc ev -> do onC = proc ev -> do
@@ -74,7 +84,7 @@ onC = proc ev -> do
Event _ -> lightsOn -< entities Event _ -> lightsOn -< entities
Tick -> returnA -< () Tick -> returnA -< ()
where where
lightsOn = callServiceDyn "Lights on" (\es -> light es (On def)) lightsOn = callServiceDyn "Lights on" (\es -> light es [] (On def))
lightsOffTrigger :: HASS (Event Value) (Event ()) lightsOffTrigger :: HASS (Event Value) (Event ())
lightsOffTrigger = hallwayPresence >>> arr (== Unoccupied) >>> lightsOffTrigger = hallwayPresence >>> arr (== Unoccupied) >>>
@@ -84,7 +94,7 @@ offC :: HASS (Event Value) ()
offC = (lightsOffTrigger AFRP.>>|| lightsOff) >>> offC = (lightsOffTrigger AFRP.>>|| lightsOff) >>>
arr (const ()) arr (const ())
where where
lightsOff = callService "Lights off" (light [EntityId "light.hallway_lights"] Off) lightsOff = callService "Lights off" (light [EntityId "light.hallway_lights"] [] Off)
hallwayLightsController :: HASS (Event Value) () hallwayLightsController :: HASS (Event Value) ()
hallwayLightsController = onC <> offC <> modeC hallwayLightsController = onC <> offC <> modeC
+5 -5
View File
@@ -23,8 +23,8 @@ kitchenCeilingController = proc x -> do
ev <- lightingModeEvents -< p ev <- lightingModeEvents -< p
traceEvent -< ev traceEvent -< ev
case ev of case ev of
Event LightingOn | lightsAllowed now -> callServiceDyn "light.kitchen_ceiling on" (light [EntityId "light.kitchen_ceiling"]) -< On def Event LightingOn | lightsAllowed now -> callServiceDyn "light.kitchen_ceiling on" (light [EntityId "light.kitchen_ceiling"] []) -< On def
Event LightingOff -> callServiceDyn "light.kitchen_ceiling off" (light [EntityId "light.kitchen_ceiling"]) -< Off Event LightingOff -> callServiceDyn "light.kitchen_ceiling off" (light [EntityId "light.kitchen_ceiling"] []) -< Off
_ -> returnA -< () _ -> returnA -< ()
where where
lightsAllowed (LocalTime _ tod) = not (tod > TimeOfDay 1 45 0 && tod < TimeOfDay 5 0 0) lightsAllowed (LocalTime _ tod) = not (tod > TimeOfDay 1 45 0 && tod < TimeOfDay 5 0 0)
@@ -53,7 +53,7 @@ dinnerTableController =
lightsOn = lightsOn =
AFRP.edge AFRP.edge
>>|| sleep "sleep off" False >>|| sleep "sleep off" False
>>> callService "Dining light on" (light [EntityId "light.kitchen_dining_large"] $ On def) >>> callService "Dining light on" (light [EntityId "light.kitchen_dining_large"] [] $ On def)
lightsSleep = lightsSleep =
arr not arr not
@@ -64,10 +64,10 @@ dinnerTableController =
arr not arr not
>>> AFRP.waitFor 300 >>> AFRP.waitFor 300
>>|| sleep "sleep off" False >>|| sleep "sleep off" False
>>> callService "Dining light on" (light [EntityId "light.kitchen_dining_large"] Off) >>> callService "Dining light on" (light [EntityId "light.kitchen_dining_large"] [] Off)
sleep lbl b = callService lbl (switchService [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] b) sleep lbl b = callService lbl (switchService [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] [] b)
kitchenMotionController :: HASS (Event Value) () kitchenMotionController :: HASS (Event Value) ()
@@ -47,16 +47,19 @@ data LightCommand
= Off = Off
| On LightAttributes | On LightAttributes
light :: [Target] -> LightCommand -> Service light :: [Target] -> [Target] -> LightCommand -> Service
light targets (On settings) = Service light targets exclusions = \case
(On settings) -> Service
{ serviceDomain="light" { serviceDomain="light"
, serviceName= "turn_on" , serviceName= "turn_on"
, serviceData= formatLightAttributes settings , serviceData= formatLightAttributes settings
, serviceTarget=targets , serviceTarget=targets
, serviceExclusions = exclusions
} }
light targets Off = Service Off -> Service
{ serviceDomain="light" { serviceDomain="light"
, serviceName= "turn_off" , serviceName= "turn_off"
, serviceData=Nothing , serviceData=Nothing
, serviceTarget=targets , serviceTarget=targets
, serviceExclusions = exclusions
} }
+2 -2
View File
@@ -39,8 +39,8 @@ livingroomPresenceController = proc x -> do
ev <- lightingModeEvents . livingroomPresence -< x ev <- lightingModeEvents . livingroomPresence -< x
traceEvent -< ev traceEvent -< ev
case ev of case ev of
AFRP.Event LightingOn -> callServiceDyn "Lights on" (light livingroomLightTargets) -< On def AFRP.Event LightingOn -> callServiceDyn "Lights on" (light livingroomLightTargets []) -< On def
AFRP.Event LightingOff -> callServiceDyn "Lights off" (light livingroomLightTargets) -< Off AFRP.Event LightingOff -> callServiceDyn "Lights off" (light livingroomLightTargets []) -< Off
_ -> returnA -< () _ -> returnA -< ()
returnA -< () returnA -< ()
+1
View File
@@ -18,4 +18,5 @@ activateSceneWith sceneId d = Service
, serviceName= "turn_on" , serviceName= "turn_on"
, serviceTarget= [EntityId sceneId] , serviceTarget= [EntityId sceneId]
, serviceData = d , serviceData = d
, serviceExclusions = []
} }
+5 -1
View File
@@ -6,7 +6,10 @@ module HomeAssistant.Controller.Service
import Data.Aeson (Value) import Data.Aeson (Value)
import qualified Data.Text as T import qualified Data.Text as T
data Target = EntityId !T.Text | AreaId !T.Text data Target
= EntityId !T.Text
| AreaId !T.Text
| LabelId !T.Text
deriving (Show,Eq,Ord) deriving (Show,Eq,Ord)
data Service = Service data Service = Service
@@ -14,5 +17,6 @@ data Service = Service
, serviceName :: T.Text , serviceName :: T.Text
, serviceData :: Maybe Value , serviceData :: Maybe Value
, serviceTarget :: [Target] , serviceTarget :: [Target]
, serviceExclusions :: [Target]
} }
deriving (Show, Eq) deriving (Show, Eq)
+3 -2
View File
@@ -5,10 +5,11 @@ module HomeAssistant.Controller.Switch (switchService) where
import Data.Bool (bool) import Data.Bool (bool)
import HomeAssistant.Controller.Service (Service (..), Target) import HomeAssistant.Controller.Service (Service (..), Target)
switchService :: [Target] -> Bool -> Service switchService :: [Target] -> [Target] -> Bool -> Service
switchService targets b = Service switchService targets exclusions b = Service
{ serviceDomain="switch" { serviceDomain="switch"
, serviceName= bool "turn_off" "turn_on" b , serviceName= bool "turn_off" "turn_on" b
, serviceData=Nothing , serviceData=Nothing
, serviceTarget=targets , serviceTarget=targets
, serviceExclusions=exclusions
} }
+10 -6
View File
@@ -146,17 +146,21 @@ encodeService callId Service{..} = object $
, "type" .= ("call_service" :: T.Text) , "type" .= ("call_service" :: T.Text)
, "domain" .= serviceDomain , "domain" .= serviceDomain
, "service" .= serviceName , "service" .= serviceName
, "target" .= targetObject serviceTarget , "target" .= targetObject serviceTarget serviceExclusions
] <> maybe [] (\d -> ["service_data" .= d]) serviceData ] <> maybe [] (\d -> ["service_data" .= d]) serviceData
-- | A single target encodes as a scalar; multiple encode as a list. Empty -- | A single target encodes as a scalar; multiple encode as a list. Empty
-- lists are omitted so Home Assistant receives only populated keys. -- lists are omitted so Home Assistant receives only populated keys. Exclusions
targetObject :: [Target] -> Value -- nest under "exclude".
targetObject targets = object $ entityPart <> areaPart targetObject :: [Target] -> [Target] -> Value
targetObject targets exclusions = object $
targetKeys targets
<> [ "exclude" .= object (targetKeys exclusions) | not (null exclusions) ]
where where
entityPart = emit "entity_id" [e | EntityId e <- targets] targetKeys ts = emit "entity_id" [e | EntityId e <- ts]
areaPart = emit "area_id" [a | AreaId a <- targets] <> emit "area_id" [a | AreaId a <- ts]
<> emit "label_id" [l | LabelId l <- ts]
emit _ [] = [] emit _ [] = []
emit k [x] = [k .= x] emit k [x] = [k .= x]
emit k many = [k .= many] emit k many = [k .= many]
+24 -12
View File
@@ -85,18 +85,18 @@ drawerSpec = describe "bedroomDrawerController" $ do
it "turns the drawer light on when the drawer opens" $ it "turns the drawer light on when the drawer opens" $
services (runHASS bedroomDrawerController [drawerState "on"]) services (runHASS bedroomDrawerController [drawerState "on"])
`shouldBe` [[switchService [entity] True]] `shouldBe` [[switchService [entity] [] True]]
it "turns the drawer light off when the drawer closes" $ it "turns the drawer light off when the drawer closes" $
services (runHASS bedroomDrawerController [drawerState "off"]) services (runHASS bedroomDrawerController [drawerState "off"])
`shouldBe` [[switchService [entity] False]] `shouldBe` [[switchService [entity] [] False]]
it "toggles the light as the drawer opens and closes" $ it "toggles the light as the drawer opens and closes" $
services (runHASS bedroomDrawerController services (runHASS bedroomDrawerController
[ drawerState "on", drawerState "off", drawerState "on" ]) [ drawerState "on", drawerState "off", drawerState "on" ])
`shouldBe` [ [switchService [entity] True] `shouldBe` [ [switchService [entity] [] True]
, [switchService [entity] False] , [switchService [entity] [] False]
, [switchService [entity] True] , [switchService [entity] [] True]
] ]
it "ignores state events for other entities" $ it "ignores state events for other entities" $
@@ -146,12 +146,12 @@ presenceSpec = describe "bedroomPresenceController" $ do
let later = 305 `addUTCTime` now let later = 305 `addUTCTime` now
services (runHASSTimed bedroomPresenceController services (runHASSTimed bedroomPresenceController
[ (now, presenceSensor "on"), (now, presenceSensor "off"), (later, Tick) ]) [ (now, presenceSensor "on"), (now, presenceSensor "off"), (later, Tick) ])
`shouldBe` [ [], [], [light bedroomLightTargets Off] ] `shouldBe` [ [], [], [light bedroomLightTargets [] Off] ]
it "restores the last snapshot when re-entering after sleep" $ do it "restores the last snapshot when re-entering after sleep" $ do
now <- getCurrentTime now <- getCurrentTime
let later = 350 `addUTCTime` now let later = 350 `addUTCTime` now
let masseRestored = light [EntityId "light.bedroom_masse"] (On def let masseRestored = light [EntityId "light.bedroom_masse"] [] (On def
{ lightBrightness = Just (BrightnessAbsolute 140) { lightBrightness = Just (BrightnessAbsolute 140)
, lightColorTemperature = Just 2700 , lightColorTemperature = Just 2700
}) })
@@ -167,9 +167,9 @@ presenceSpec = describe "bedroomPresenceController" $ do
, [] , []
, [sleepScene] , [sleepScene]
, [] , []
, [ light [EntityId "light.bedroom_ceiling"] Off , [ light [EntityId "light.bedroom_ceiling"] [] Off
, light [EntityId "light.bedroom_jemina"] Off , light [EntityId "light.bedroom_jemina"] [] Off
, light [EntityId "light.bedroom_led_switch"] Off , light [EntityId "light.bedroom_led_switch"] [] Off
, masseRestored , masseRestored
] ]
, [] , []
@@ -193,7 +193,15 @@ buttonSpec = describe "bedroomButtonController" $ do
it "Masse off click turns the bedroom lights off" $ it "Masse off click turns the bedroom lights off" $
concat (services (runHASS bedroomButtonController [masseButton "2_short_release"])) concat (services (runHASS bedroomButtonController [masseButton "2_short_release"]))
`shouldContain` [light [area] Off] `shouldContain` [light [area] [] Off]
it "Masse long off click also turns the hallway lights off" $
concat (services (runHASS bedroomButtonController [masseButton "2_long_press"]))
`shouldContain` [light [EntityId "light.hallway_lights"] [] Off]
it "Masse short off click leaves the hallway lights alone" $
concat (services (runHASS bedroomButtonController [masseButton "2_short_release"]))
`shouldNotContain` [light [EntityId "light.hallway_lights"] [] Off]
it "Enishen single click turns on her nightstand scene (lowest)" $ it "Enishen single click turns on her nightstand scene (lowest)" $
concat (services (runHASS bedroomButtonController [enishenButton "1_short_release"])) concat (services (runHASS bedroomButtonController [enishenButton "1_short_release"]))
@@ -209,7 +217,11 @@ buttonSpec = describe "bedroomButtonController" $ do
it "Enishen off click turns the bedroom lights off" $ it "Enishen off click turns the bedroom lights off" $
concat (services (runHASS bedroomButtonController [enishenButton "2_short_release"])) concat (services (runHASS bedroomButtonController [enishenButton "2_short_release"]))
`shouldContain` [light [area] Off] `shouldContain` [light [area] [] Off]
it "Enishen long off click also turns the hallway lights off" $
concat (services (runHASS bedroomButtonController [enishenButton "2_long_press"]))
`shouldContain` [light [EntityId "light.hallway_lights"] [] Off]
it "ignores the initial press (scene only fires on release)" $ it "ignores the initial press (scene only fires on release)" $
services (runHASS bedroomButtonController [masseButton "1_initial_press"]) services (runHASS bedroomButtonController [masseButton "1_initial_press"])
+2 -2
View File
@@ -40,7 +40,7 @@ spec = describe "Bus" $ do
it "channelHassEval writes CallService to the outbound channel" $ withTestBus $ \bus -> do it "channelHassEval writes CallService to the outbound channel" $ withTestBus $ \bus -> do
let req = Request (UTCTime (toEnum 0) 0) utc nil "test" let req = Request (UTCTime (toEnum 0) 0) utc nil "test"
svc = Service "light" "turn_on" Nothing [EntityId "light.bedroom_masse"] svc = Service "light" "turn_on" Nothing [EntityId "light.bedroom_masse"] []
runKatipContextT (busLogEnv bus) () (Namespace ["test"]) $ runKatipContextT (busLogEnv bus) () (Namespace ["test"]) $
channelHassEval bus (CallService req svc) channelHassEval bus (CallService req svc)
(_, svc') <- atomically $ readTChan (busOutbound bus) (_, svc') <- atomically $ readTChan (busOutbound bus)
@@ -50,7 +50,7 @@ spec = describe "Bus" $ do
withTestFlagsBus $ \bus -> do withTestFlagsBus $ \bus -> do
setEnabled (busFlags bus) "test-handler" False setEnabled (busFlags bus) "test-handler" False
let req = Request (UTCTime (toEnum 0) 0) utc nil "test-handler" let req = Request (UTCTime (toEnum 0) 0) utc nil "test-handler"
svc = Service "light" "turn_on" Nothing [EntityId "light.test"] svc = Service "light" "turn_on" Nothing [EntityId "light.test"] []
runKatipContextT (busLogEnv bus) () (Namespace ["test"]) $ runKatipContextT (busLogEnv bus) () (Namespace ["test"]) $
channelHassEval bus (CallService req svc) channelHassEval bus (CallService req svc)
result <- timeout 1000000 $ atomically $ readTChan (busOutbound bus) result <- timeout 1000000 $ atomically $ readTChan (busOutbound bus)
+16 -3
View File
@@ -27,7 +27,7 @@ spec :: Spec
spec = do spec = do
describe "encodeService" $ do describe "encodeService" $ do
it "encodes a call_service message" $ it "encodes a call_service message" $
encodeService 7 (Service "light" "turn_on" Nothing [EntityId "light.bedroom_masse"]) encodeService 7 (Service "light" "turn_on" Nothing [EntityId "light.bedroom_masse"] [])
`shouldBe` object `shouldBe` object
[ "id" .= (7 :: Int) [ "id" .= (7 :: Int)
, "type" .= ("call_service" :: Text) , "type" .= ("call_service" :: Text)
@@ -37,7 +37,7 @@ spec = do
] ]
it "includes service_data when present" $ it "includes service_data when present" $
encodeService 8 (Service "light" "turn_on" (Just (object ["brightness" .= (200 :: Int)])) [EntityId "light.bedroom_masse"]) encodeService 8 (Service "light" "turn_on" (Just (object ["brightness" .= (200 :: Int)])) [EntityId "light.bedroom_masse"] [])
`shouldBe` object `shouldBe` object
[ "id" .= (8 :: Int) [ "id" .= (8 :: Int)
, "type" .= ("call_service" :: Text) , "type" .= ("call_service" :: Text)
@@ -47,6 +47,19 @@ spec = do
, "service_data" .= object ["brightness" .= (200 :: Int)] , "service_data" .= object ["brightness" .= (200 :: Int)]
] ]
it "encodes target exclusions" $
encodeService 9 (Service "light" "turn_off" Nothing [AreaId "lasten_makuuhuone"] [LabelId "decoration"])
`shouldBe` object
[ "id" .= (9 :: Int)
, "type" .= ("call_service" :: Text)
, "domain" .= ("light" :: Text)
, "service" .= ("turn_off" :: Text)
, "target" .= object
[ "area_id" .= ("lasten_makuuhuone" :: Text)
, "exclude" .= object ["label_id" .= ("decoration" :: Text)]
]
]
describe "isTriggerEvent" $ do describe "isTriggerEvent" $ do
it "is true for event frames" $ it "is true for event frames" $
isTriggerEvent (object ["type" .= ("event" :: Text)]) `shouldBe` True isTriggerEvent (object ["type" .= ("event" :: Text)]) `shouldBe` True
@@ -80,5 +93,5 @@ req n = Request (UTCTime (toEnum 0) (fromIntegral (0 :: Int))) utc
uuid = "00000000-0000-0000-0000-" <> pad n uuid = "00000000-0000-0000-0000-" <> pad n
lightOn :: [Target] -> Service lightOn :: [Target] -> Service
lightOn = Service "light" "turn_on" Nothing lightOn targets = Service "light" "turn_on" Nothing targets []
+94 -14
View File
@@ -4,7 +4,7 @@ module HallwaySpec (spec) where
import AFRP (Event (..)) import AFRP (Event (..))
import qualified Data.Text as T import qualified Data.Text as T
import Data.Aeson (Value) import Data.Aeson (Value, object, (.=))
import Data.Bool (bool) import Data.Bool (bool)
import Data.Default (def) import Data.Default (def)
import Data.List (scanl') import Data.List (scanl')
@@ -30,6 +30,25 @@ masterDoor = Event . stateEvent "binary_sensor.makuuhuone_ovi_contact"
childrenDoor :: T.Text -> Event Value childrenDoor :: T.Text -> Event Value
childrenDoor = Event . stateEvent "binary_sensor.lasten_makuuhuone_ovi_contact" childrenDoor = Event . stateEvent "binary_sensor.lasten_makuuhuone_ovi_contact"
bedroomPresenceSensor :: T.Text -> Event Value
bedroomPresenceSensor = Event . stateEvent "binary_sensor.presence_sensor_bedroom_occupancy"
-- A light turning on with a raw brightness value (0-255)
bedroomLightEvent :: T.Text -> Int -> Event Value
bedroomLightEvent entityId brightness = Event . object $
[ "event" .= object
[ "variables" .= object
[ "trigger" .= object
[ "entity_id" .= (entityId :: T.Text)
, "to_state" .= object
[ "state" .= ("on" :: T.Text)
, "attributes" .= object [ "brightness" .= brightness ]
]
]
]
]
]
-- Same shape as the generator in PresenceSpec: mostly short gaps (< 500s -- Same shape as the generator in PresenceSpec: mostly short gaps (< 500s
-- timeout), occasionally a 600s gap so presence can expire and the room can -- timeout), occasionally a 600s gap so presence can expire and the room can
-- become unoccupied again. -- become unoccupied again.
@@ -91,6 +110,8 @@ data ModeAction
= Motion Bool -- ^ @True@ is motion detected = Motion Bool -- ^ @True@ is motion detected
| MasterDoor Bool -- ^ @True@ is closed | MasterDoor Bool -- ^ @True@ is closed
| ChildrenDoor Bool -- ^ @True@ is closed | ChildrenDoor Bool -- ^ @True@ is closed
| BedroomPresence Bool -- ^ @True@ is someone in the parents' bedroom
| BedroomLight (Maybe Int) -- ^ @Nothing@ is off, otherwise the brightness
| Idle | Idle
deriving Show deriving Show
@@ -103,6 +124,8 @@ genModeEvent = ModeEvent
<*> Gen.frequency [(4, Motion <$> Gen.bool) <*> Gen.frequency [(4, Motion <$> Gen.bool)
,(2, MasterDoor <$> Gen.bool) ,(2, MasterDoor <$> Gen.bool)
,(2, ChildrenDoor <$> Gen.bool) ,(2, ChildrenDoor <$> Gen.bool)
,(1, BedroomPresence <$> Gen.bool)
,(1, BedroomLight <$> Gen.choice [pure Nothing, pure (Just 25), pure (Just 230)])
,(2, pure Idle) ,(2, pure Idle)
] ]
@@ -110,6 +133,10 @@ modeEventValue :: ModeAction -> Event Value
modeEventValue (Motion b) = Event $ stateEvent "binary_sensor.hallway_movement_occupancy" (bool "off" "on" b) modeEventValue (Motion b) = Event $ stateEvent "binary_sensor.hallway_movement_occupancy" (bool "off" "on" b)
modeEventValue (MasterDoor b) = Event $ stateEvent "binary_sensor.makuuhuone_ovi_contact" (bool "off" "on" b) modeEventValue (MasterDoor b) = Event $ stateEvent "binary_sensor.makuuhuone_ovi_contact" (bool "off" "on" b)
modeEventValue (ChildrenDoor b) = Event $ stateEvent "binary_sensor.lasten_makuuhuone_ovi_contact" (bool "off" "on" b) modeEventValue (ChildrenDoor b) = Event $ stateEvent "binary_sensor.lasten_makuuhuone_ovi_contact" (bool "off" "on" b)
modeEventValue (BedroomPresence b) = Event $ stateEvent "binary_sensor.presence_sensor_bedroom_occupancy" (bool "off" "on" b)
modeEventValue (BedroomLight b) = case b of
Nothing -> Event $ stateEvent "light.bedroom_ceiling" "off"
Just n -> bedroomLightEvent "light.bedroom_ceiling" n
modeEventValue Idle = Tick modeEventValue Idle = Tick
-- | The mode-adjustment trigger: the presence-based lights are already on -- | The mode-adjustment trigger: the presence-based lights are already on
@@ -153,11 +180,11 @@ lightsSpec = do
describe "hallwayLightsController" $ do describe "hallwayLightsController" $ do
it "turns the full lights on when someone enters during daytime" $ it "turns the full lights on when someone enters during daytime" $
services (runHASSTimed hallwayLightsController [(day, motionSensor "on")]) services (runHASSTimed hallwayLightsController [(day, motionSensor "on")])
`shouldBe` [[light [EntityId "light.hallway_lights"] (On def)]] `shouldBe` [[light [EntityId "light.hallway_lights"] [] (On def)]]
it "turns the full lights on when someone enters during daytime preceding tick" $ it "turns the full lights on when someone enters during daytime preceding tick" $
services (runHASSTimed hallwayLightsController [(day, Tick), (day, motionSensor "on")]) services (runHASSTimed hallwayLightsController [(day, Tick), (day, motionSensor "on")])
`shouldBe` [[], [light [EntityId "light.hallway_lights"] (On def)]] `shouldBe` [[], [light [EntityId "light.hallway_lights"] [] (On def)]]
it "turns the lights off when everyone leaves, without sleep mode" $ it "turns the lights off when everyone leaves, without sleep mode" $
let later = 505 `addUTCTime` day let later = 505 `addUTCTime` day
@@ -168,9 +195,9 @@ lightsSpec = do
, (later, Tick) , (later, Tick)
]) ])
`shouldBe` [ [] `shouldBe` [ []
, [light [EntityId "light.hallway_lights"] (On def)] , [light [EntityId "light.hallway_lights"] [] (On def)]
, [] , []
, [light [EntityId "light.hallway_lights"] Off] , [light [EntityId "light.hallway_lights"] [] Off]
] ]
it "turns on only the ceiling light when entering during sleep hours with a door open" $ it "turns on only the ceiling light when entering during sleep hours with a door open" $
@@ -181,20 +208,73 @@ lightsSpec = do
]) ])
`shouldBe` [ [] `shouldBe` [ []
, [] , []
, [light [EntityId "light.hallway_ceiling_2"] (On def)] , [light [EntityId "light.hallway_ceiling_2"] [] (On def)]
] ]
it "sets the lower hallway light off when a door is opened during sleep hours" $ it "leaves the lights unchanged when an empty bedroom door opens during sleep hours" $
services (runHASSTimed hallwayLightsController services (runHASSTimed hallwayLightsController
[ (night, masterDoor "off") [ (night, masterDoor "off") -- closed
, (night, childrenDoor "off") , (night, childrenDoor "off") -- closed
, (night, motionSensor "on") , (night, motionSensor "on")
, (night, masterDoor "on") , (night, masterDoor "on") -- opens, but nobody is ready to sleep there
]) ])
`shouldBe` [ [] `shouldBe` [ []
, [] , []
, [light [EntityId "light.hallway_lights"] (On def)] , [light [EntityId "light.hallway_lights"] [] (On def)]
, [light [EntityId "light.hallway_ceiling"] Off] , []
]
it "keeps the full lights when an awake bedroom sits behind an open door" $
services (runHASSTimed hallwayLightsController
[ (night, masterDoor "on") -- open for the cats
, (night, childrenDoor "off") -- closed
, (night, bedroomPresenceSensor "on")
, (night, bedroomLightEvent "light.bedroom_ceiling" 230)
, (night, motionSensor "on")
])
`shouldBe` [ [], [], [], []
, [light [EntityId "light.hallway_lights"] [] (On def)]
]
it "protects an open bedroom door as soon as its light is dimmed down" $
services (runHASSTimed hallwayLightsController
[ (night, masterDoor "on") -- open for the cats
, (night, childrenDoor "off") -- closed
, (night, bedroomLightEvent "light.bedroom_ceiling" 230) -- still bright
, (night, bedroomPresenceSensor "on")
, (night, motionSensor "on")
, (night, bedroomLightEvent "light.bedroom_ceiling" 25)
])
`shouldBe` [ [], [], [], []
, [light [EntityId "light.hallway_lights"] [] (On def)]
, [light [EntityId "light.hallway_ceiling"] [] Off]
]
it "counts a barely lit bedroom as ready to sleep" $
services (runHASSTimed hallwayLightsController
[ (night, masterDoor "off") -- closed
, (night, childrenDoor "off") -- closed
, (night, bedroomPresenceSensor "on")
, (night, bedroomLightEvent "light.bedroom_ceiling" 25)
, (night, motionSensor "on")
, (night, masterDoor "on") -- opens for the cats, someone ready to sleep
])
`shouldBe` [ [], [], [], []
, [light [EntityId "light.hallway_lights"] [] (On def)]
, [light [EntityId "light.hallway_ceiling"] [] Off]
]
it "dims the lower light when an occupied bedroom door opens during sleep hours" $
services (runHASSTimed hallwayLightsController
[ (night, masterDoor "off") -- closed
, (night, childrenDoor "off") -- closed
, (night, bedroomPresenceSensor "on")
, (night, motionSensor "on")
, (night, masterDoor "on") -- opens for the cats, someone ready to sleep
])
`shouldBe` [ [], [], []
, [light [EntityId "light.hallway_lights"] [] (On def)]
, [light [EntityId "light.hallway_ceiling"] [] Off]
] ]
it "turns the lower hallway light on when the doors close while presence is active" $ it "turns the lower hallway light on when the doors close while presence is active" $
@@ -205,7 +285,7 @@ lightsSpec = do
, (night, childrenDoor "off") , (night, childrenDoor "off")
]) ])
`shouldBe` [ [] `shouldBe` [ []
, [light [EntityId "light.hallway_ceiling_2"] (On def)] , [light [EntityId "light.hallway_ceiling_2"] [] (On def)]
, [] , []
, [light [EntityId "light.hallway_ceiling"] (On def)] , [light [EntityId "light.hallway_ceiling"] [] (On def)]
] ]
+4 -4
View File
@@ -36,18 +36,18 @@ dinnerTableSpec = describe "dinnerTableController" $ do
it "turns lights on when presence is occupied and light level is low" $ do it "turns lights on when presence is occupied and light level is low" $ do
services (runHASS dinnerTableController [testDinnerLightLevel 10, testDinnerPresence "on"]) services (runHASS dinnerTableController [testDinnerLightLevel 10, testDinnerPresence "on"])
`shouldBe` [[switchService [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] True], [switchService [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] False, light [EntityId "light.kitchen_dining_large"] (On def)]] `shouldBe` [[switchService [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] [] True], [switchService [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] [] False, light [EntityId "light.kitchen_dining_large"] [] (On def)]]
it "turns lights to sleep when presence is unoccupied" $ do it "turns lights to sleep when presence is unoccupied" $ do
now <- getCurrentTime now <- getCurrentTime
services (runHASSTimed dinnerTableController [(now, testDinnerLightLevel 10), (now, testDinnerPresence "off")]) services (runHASSTimed dinnerTableController [(now, testDinnerLightLevel 10), (now, testDinnerPresence "off")])
`shouldBe` [[switchService [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] True], []] `shouldBe` [[switchService [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] [] True], []]
it "turns lights off when no presence for 300 seconds" $ do it "turns lights off when no presence for 300 seconds" $ do
now <- getCurrentTime now <- getCurrentTime
let later = 305 `addUTCTime` now let later = 305 `addUTCTime` now
services (runHASSTimed dinnerTableController [(now, testDinnerLightLevel 10), (now, testDinnerPresence "off"), (later, Tick)]) services (runHASSTimed dinnerTableController [(now, testDinnerLightLevel 10), (now, testDinnerPresence "off"), (later, Tick)])
`shouldBe` [[switchService [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] True], [], [switchService [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] False, light [EntityId "light.kitchen_dining_large"] Off]] `shouldBe` [[switchService [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] [] True], [], [switchService [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] [] False, light [EntityId "light.kitchen_dining_large"] [] Off]]
it "does nothing on Tick" $ do it "does nothing on Tick" $ do
services (runHASS dinnerTableController [Tick]) services (runHASS dinnerTableController [Tick])
`shouldBe` [[switchService [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] True]] `shouldBe` [[switchService [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] [] True]]