39 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
MasseR 05263fed2b Easier files 2026-11-03 15:05:18 +02:00
MasseR 6e35445090 Much improved hallway handling 2026-11-03 14:47:01 +02:00
MasseR 95fcc61c4f HallwaySpec: readable clock helper, fix expectations for added Tick 2026-11-02 18:41:29 +02:00
MasseR 2039d03a5e Add failing spec for hallway lights automation 2026-11-02 18:13:31 +02:00
MasseR 868a5d7e4f Refactor bedroom presence controller to parallel arrows style 2026-11-01 13:10:54 +02:00
MasseR d710251a4e Document bedroom presence and sleep mode guard behavior with tests 2026-11-01 13:05:53 +02:00
MasseR c78f5a4a6d Kids light on a transition 2026-11-01 12:48:52 +02:00
MasseR 889ad1c091 Turn on sleep mode only if there are any lights already on 2026-11-01 12:46:30 +02:00
MasseR 5f8b3cbe00 Refactor to a more arrows style syntax 2026-10-24 00:18:04 +03:00
MasseR 078f24e4b9 Fix tests and add tests for kitchen lights 2026-10-23 23:57:05 +03:00
MasseR 15e50322c4 Making the controllers more linear
Basically, the idea of `(oneBranch <> secondBranch)` instead of

```
do
x <- foo
case x of
  ...
```
2026-10-23 22:55:06 +03:00
MasseR 617bd255ff Diagrams 2026-10-23 16:00:19 +03:00
MasseR 022342af32 Make the type variable 2026-10-22 12:17:58 +03:00
MasseR 6caa2acafb Merge pull request 'Statistics page' (#7) from statistics-page into main
Reviewed-on: #7
2026-10-12 16:06:16 +03:00
MasseR 7d5103ac90 Pretty 2026-10-12 16:05:32 +03:00
MasseR 3a6fe26d0c List of ranges 2026-10-12 15:17:07 +03:00
MasseR 45277e02da htmx flags 2026-10-12 14:55:30 +03:00
MasseR 87dda96e7e Simple HTML responses 2026-10-12 13:28:54 +03:00
MasseR 55855db55b Try a separate holdKnown primitive 2026-10-12 11:11:37 +03:00
MasseR 8a4a5aef33 Filter setup 2026-10-09 14:50:15 +03:00
MasseR d33c2cf268 Reads better 2026-10-08 13:45:12 +03:00
MasseR 7bd0a652cb Clean hlint and cabal warnings 2026-10-02 15:42:12 +03:00
MasseR 449f404464 Review notes docs tweaks 2026-10-02 15:13:54 +03:00
MasseR 0e5d76901d Bound note header parsing 2026-10-02 15:13:04 +03:00
MasseR 773f3b550f Review notes docs 2026-10-02 14:47:46 +03:00
MasseR 4664e71493 Review note push 2026-10-02 14:45:17 +03:00
MasseR e7adb3e88b Latest review note 2026-10-02 14:41:26 +03:00
MasseR 2e2960c159 Review note script 2026-10-02 14:36:46 +03:00
MasseR 627f813859 Spec: verification wording matches scan-based latest 2026-10-02 14:31:49 +03:00
MasseR e750e0e687 Spec: latest scans notes by branch and round 2026-10-02 14:29:56 +03:00
MasseR 63210afc7b Track superpowers specs, ignore plans 2026-10-02 14:23:40 +03:00
MasseR 7ec491d383 Review notes protocol design 2026-10-02 14:22:24 +03:00
MasseR 4f1277aa45 Worktrees 2026-10-02 12:29:56 +03:00
MasseR 3908d5a3a6 REVIEW guidelines 2026-10-02 12:28:23 +03:00
MasseR 5416e9b708 Safer default 2026-10-01 21:57:47 +03:00
MasseR 38d575d716 I don't need these log lines anymore 2026-10-01 21:16:23 +03:00
44 changed files with 1591 additions and 250 deletions

No files matched your search

+3 -1
View File
@@ -4,8 +4,10 @@ dist-newstyle
.worktrees/
docs/superpowers
docs/superpowers/plans
*.dat
handlers.json
*.hp
*.eventlog
*.eventlog.html
+10
View File
@@ -5,6 +5,11 @@
A sidecar for Home Assistant that runs automations using arrowized functional
reactive programming (AFRP). Haskell, built with cabal.
## Working style
- When doing any non-trivial work, always work in a worktree on a feature branch
- Feature branches should be named as the topic of the change
## Code style
- Vertical modules: split by feature/concept, not by layer.
@@ -25,3 +30,8 @@ reactive programming (AFRP). Haskell, built with cabal.
- hspec for unit tests, hedgehog for property tests.
- Run with `nix develop -c cabal test`.
## Reviewing
Reviews are recorded in git notes under `refs/notes/review`; read the latest
note before reviewing. See [[REVIEW.md]].
+49
View File
@@ -0,0 +1,49 @@
# Code Review Guidelines
- Each MR should be focused, changing only one concept at a time
- Keep MRs small - aim for under 500 lines of diff. There can be some wiggle room for cases that are hard to split
- When reviewing code, check for test coverage and suggest tests if missing
- Go through tests and think hard to see if any unit tests or group of unit tests can be replaced with a property test
- When suggesting a property test, consider cases that the property needs to falsify and whether it needs its own generator
- Business logic stays pure
## Comments
- Less is more
- If there's comments for a function, verify they're proper haddock style
- If there's comments for a function, they must only be about the contract and use instructions
- If there's comments for implementation, they should only be for exceptional cases, cases where the reader would question why something is implemented like that
- Comment style should follow minimalistic writing style
## Recording reviews
Reviews are stored as git notes under `refs/notes/review`, one note per
reviewed commit. The note header carries `branch`, `round`, `verdict`
(`approve` or `request-changes`), `previous` (sha of the last reviewed tip),
and a findings list with stable IDs (`F1`, `F2`, ...) whose `status` is
`open`, `resolved`, or `wontfix`. The body is free markdown prose.
Protocol:
1. Fetch prior results:
`git fetch origin "refs/notes/review:refs/notes/review"`
Ignore the failure on the first-ever review (origin has no notes ref yet);
if the fetch is rejected as non-fast-forward, your local notes are ahead —
push instead.
2. Read the latest verdict and open findings for the branch:
`scripts/review-note latest [branch]`
3. Review the branch tip per this document.
4. Write the note (header + markdown) to a file and attach it to the tip:
`scripts/review-note write <file>`. Use `--force` only to replace a note
on the same commit deliberately.
5. Publish: `scripts/review-note push` (plain `git push` does not push
notes).
On a re-review after fixes: new tip, new note, `round`+1, `previous` set to
the last reviewed sha, open findings carried forward by ID, resolved ones
marked `resolved`.
On a branch rename: update the note's `branch:` header to the new name and
mention the old name in the body, so `latest <new-name>` chains and history
stays findable.
+6 -6
View File
@@ -2,9 +2,9 @@
, cereal, cereal-conduit, cereal-text, conduit, containers
, data-default, directory, ekg-core, exceptions, filepath, hedgehog
, hspec, hspec-hedgehog, http-media, http-types, katip, lens
, lens-aeson, lib, libsystemd-journal, network, process, retry
, servant, servant-server, stm, temporary, text, time, unliftio
, unordered-containers, uuid, wai, warp, websockets
, lens-aeson, lib, libsystemd-journal, lucid2, network, process
, retry, servant, servant-server, stm, temporary, text, time
, unliftio, unordered-containers, uuid, wai, warp, websockets
}:
mkDerivation {
pname = "home-assistant-controller";
@@ -16,9 +16,9 @@ mkDerivation {
aeson annotated-exception async base bytestring cereal
cereal-conduit cereal-text conduit containers data-default
directory ekg-core exceptions filepath http-media http-types katip
lens lens-aeson libsystemd-journal network process retry servant
servant-server stm text time unliftio unordered-containers uuid wai
warp websockets
lens lens-aeson libsystemd-journal lucid2 network process retry
servant servant-server stm text time unliftio unordered-containers
uuid wai warp websockets
];
executableHaskellDepends = [ base ];
testHaskellDepends = [
@@ -0,0 +1,113 @@
# Review notes protocol
Date: 2026-10-02
Status: approved
## Purpose
Record code-review results as git notes under `refs/notes/review` so that the
next reviewer — human or AI — can read the current verdict, see open findings
with stable IDs, and continue from where the last review stopped. This
replaces a CI reviewer: reviews happen locally, results travel with the
commits they judged.
## Storage model
- One note per reviewed commit, in the `review` notes ref.
- The tip of a reviewed branch always carries the latest verdict.
- Re-reviewing after fixes writes a **new** note on the **new** tip commit.
Old notes stay attached to old commits as history.
- Each note links to the previously reviewed commit via `previous`, forming a
walkable chain of review rounds per branch.
- Merging to main needs no special handling: the `approve` note on the final
tip is the record.
## Note format
Line-based header, then a blank line, then free markdown body:
branch: <branch name>
round: <integer, starting at 1>
verdict: approve | request-changes
previous: none | <sha of previously reviewed tip>
findings:
- id: F<N>
severity: blocker | major | minor
file: <path>:<line>
title: <one line>
status: open | resolved | wontfix
## Details
<markdown prose>
Rules:
- Finding IDs are unique within a note and carry forward across rounds: a
finding resolved since the last note keeps its ID and moves to
`status: resolved`; an unfixed finding keeps its ID and `status: open`.
New findings get fresh IDs that do not collide with carried-forward ones.
- The body is free markdown; the `## Details` heading in the example is
illustrative, not required.
- Headers are plain `key: value` lines so the helper script can parse them
with sed/awk.
## Helper script: `scripts/review-note`
Bash, git plumbing only. Subcommands:
- `review-note show [commit]` — print the note for a commit (default: current
tip). Exit 1 with a message on stderr if there is no note.
- `review-note write <file>` — attach the note in `<file>` to the current tip
commit. Refuses to replace an existing note unless `--force` is given; a
proper re-review targets a new commit, so overwriting is always deliberate.
Validates that `branch`, `round`, and `verdict` are present and that
`verdict` uses the vocabulary above. No other validation.
- `review-note latest [branch]` — print the note with the highest `round` for
a branch (default: current branch), scanning the notes ref and matching
notes on their `branch:` header. Exit 1 if there is no note for the branch.
(A `previous`-chain walk cannot bootstrap from an unreviewed tip, so the
scan uses the `branch:` header as the index instead.)
- `review-note push` — `git push origin refs/notes/review`. Plain `git push`
ignores notes, so this is the only way results travel.
`push` pushes without force; if the remote rejects, report the failure and let
the user decide.
## Lifecycle
1. Reviewer reads `review-note latest <branch>` (exit 1 means first review).
2. Reviewer reviews the branch tip per `REVIEW.md`.
3. Reviewer writes the note with `review-note write` and runs
`review-note push`.
4. If the verdict is `request-changes`, the author pushes fixes as new
commits. The next review round starts at the new tip with `round`+1,
`previous` set to the last reviewed tip, and carried-forward findings.
5. When the verdict is `approve` and the branch merges, the notes remain on
the branch commits as the review record.
## Documentation integration
- `REVIEW.md` gains a "Recording reviews" section describing the protocol and
the four script commands. This is the single source of truth for the
protocol.
- `AGENTS.md` "Reviewing" section gains one line pointing at the section, so
any AI session picks up the flow automatically.
## Seeding the experiment
The failing review of `home_assistant_controller_cleanup` (commit `ba6e0e8`)
becomes note round 1, with these findings:
- F1 (blocker, src/AFRP.hs:273): hlint's `\_ -> x` → `const x` rewrites break
the rank-2 `Mealy` type; library does not compile.
- F2 (blocker, test/AFRPLawsSpec.hs:98): seven law tests reduced to
tautologies by hlint rewrites; see :103, :212, :221, :228, :235, :256.
- F3 (minor, test/AFRPLawsSpec.hs:241): the interchange and composition laws
were reshaped to `<$>` forms; fold them into the same hlint suppression.
## Verification
The script is verified by round-trip checks in a throwaway temp clone: write,
show, latest (two rounds, branch filtering), force-overwrite refusal and
acceptance, and push. No Haskell or cabal changes, so no
cabal2nix regeneration.
+9 -2
View File
@@ -52,7 +52,7 @@ extra-doc-files: CHANGELOG.md
-- extra-source-files:
common warnings
ghc-options: -Wall
ghc-options: -Wall -Werror
library
-- Import common warning flags.
@@ -60,6 +60,7 @@ library
-- Modules exported by the library.
exposed-modules: AFRP
, AFRP.Diagram
, HomeAssistant.Controller
, HomeAssistant.Controller.Bedroom
, HomeAssistant.Controller.Children
@@ -132,6 +133,8 @@ library
, wai
, retry
, libsystemd-journal
, lucid2
, http-api-data
-- Directories containing source files.
hs-source-dirs: src
@@ -179,12 +182,15 @@ test-suite home-assistant-controller-test
, ConnectionSpec
, FlagsSpec
, GraphingSpec
, HallwaySpec
, HttpServerSpec
, KitchenSpec
, LivingroomSpec
, MetricsSpec
, RuntimeSpec
, Support
, ControllerSpec
, PresenceSpec
-- LANGUAGE extensions used by modules in this package.
-- other-extensions:
@@ -222,4 +228,5 @@ test-suite home-assistant-controller-test
unordered-containers,
process,
directory,
temporary
temporary,
lucid2
+95
View File
@@ -0,0 +1,95 @@
#!/usr/bin/env bash
# review-note: manage code-review notes under refs/notes/review.
# The protocol lives in REVIEW.md.
set -euo pipefail
NOTES_REF=refs/notes/review
REMOTE=origin
die() { echo "review-note: $*" >&2; exit 1; }
usage() {
cat >&2 <<'EOF'
usage:
review-note show [commit]
review-note write <file> [--force]
review-note latest [branch]
review-note push
EOF
exit 1
}
validate() {
local file="$1"
grep -q '^branch: .\+' "$file" || die "missing or empty 'branch:' header"
grep -Eq '^round: [0-9]+$' "$file" || die "missing or invalid 'round:' header"
grep -Eq '^verdict: (approve|request-changes)$' "$file" \
|| die "verdict must be 'approve' or 'request-changes'"
}
cmd_show() {
local commit="${1:-HEAD}"
git notes --ref="$NOTES_REF" show "$commit" 2>/dev/null \
|| die "no review note for $commit"
}
cmd_write() {
local force="" file=""
local arg
for arg in "$@"; do
case "$arg" in
--force) force=1 ;;
*) file="$arg" ;;
esac
done
[ -n "$file" ] || usage
[ -f "$file" ] || die "no such file: $file"
local tip
tip=$(git rev-parse HEAD)
if [ -z "$force" ] && git notes --ref="$NOTES_REF" show "$tip" >/dev/null 2>&1; then
die "tip $tip already has a review note; pass --force to replace"
fi
validate "$file"
if [ -n "$force" ]; then
git notes --ref="$NOTES_REF" add -f -F "$file" "$tip"
else
git notes --ref="$NOTES_REF" add -F "$file" "$tip"
fi
}
cmd_latest() {
local branch="${1:-$(git branch --show-current)}"
local blob obj note br rnd best="" best_round=-1
while read -r blob obj; do
note=$(git notes --ref="$NOTES_REF" show "$obj") || continue
br=$(sed -n '/^$/q; s/^branch: //p' <<<"$note")
[ "$br" = "$branch" ] || continue
rnd=$(sed -n '/^$/q; s/^round: //p' <<<"$note")
[[ "$rnd" =~ ^[0-9]+$ ]] || continue
if [ "$rnd" -gt "$best_round" ]; then
best_round=$rnd
best=$note
fi
done < <(git notes --ref="$NOTES_REF" list)
[ -n "$best" ] || die "no review notes for branch: $branch"
printf '%s\n' "$best"
}
cmd_push() {
git rev-parse -q --verify "$NOTES_REF" >/dev/null || die "no review notes to push"
git push "$REMOTE" "$NOTES_REF"
}
main() {
local cmd="${1:-}"
if [ $# -gt 0 ]; then shift; fi
case "$cmd" in
show) cmd_show "$@" ;;
write) cmd_write "$@" ;;
latest) cmd_latest "$@" ;;
push) cmd_push "$@" ;;
*) usage ;;
esac
}
main "$@"
+82
View File
@@ -0,0 +1,82 @@
#!/usr/bin/env bash
# Round-trip checks for scripts/review-note, in a throwaway temp repo.
set -euo pipefail
root=$(cd "$(dirname "$0")/.." && pwd -P)
rn="$root/scripts/review-note"
fail() { echo "FAIL: $*" >&2; exit 1; }
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
git init -q --bare "$tmp/remote.git"
git init -q -b main "$tmp/repo"
cd "$tmp/repo"
git config user.email test@example.com
git config user.name test
echo one > a.txt && git add a.txt && git commit -qm one
echo two > b.txt && git add b.txt && git commit -qm two
note="$tmp/note1"
cat > "$note" <<'EOF'
branch: main
round: 1
verdict: request-changes
previous: none
findings:
- id: F1
severity: blocker
file: a.txt:1
title: fix me
status: open
## Details
Fix it.
EOF
if "$rn" show >/dev/null 2>&1; then fail "show should exit 1 without a note"; fi
sed '/^verdict:/d' "$note" > "$tmp/no-verdict"
if "$rn" write "$tmp/no-verdict" >/dev/null 2>&1; then fail "write should refuse a missing verdict"; fi
sed 's/^verdict: request-changes/verdict: maybe/' "$note" > "$tmp/bad-verdict"
if "$rn" write "$tmp/bad-verdict" >/dev/null 2>&1; then fail "write should refuse a bad verdict"; fi
"$rn" write "$note"
"$rn" show | grep -q '^verdict: request-changes$' || fail "show should print the note"
if "$rn" write "$note" >/dev/null 2>&1; then fail "write should refuse an existing note"; fi
sed 's/^verdict: request-changes/verdict: approve/' "$note" > "$tmp/note1b"
"$rn" write "$tmp/note1b" --force
"$rn" show | grep -q '^verdict: approve$' || fail "show should print the replaced note"
"$rn" show | diff -u "$tmp/note1b" - || fail "show should print the note verbatim"
# latest finds the note by branch, even from a newer unreviewed tip
echo three > c.txt && git add c.txt && git commit -qm three
"$rn" latest main | grep -q '^verdict: approve$' || fail "latest should find the round 1 note"
# a note for another branch must not leak into the result
sed -e 's/^branch: main/branch: other/' -e 's/^round: 1/round: 9/' "$tmp/note1b" > "$tmp/other"
"$rn" write "$tmp/other"
"$rn" latest main | grep -q '^verdict: approve$' || fail "latest should ignore other branches"
# round 2 on the new tip wins and carries previous (replaces the
# other-branch note on the same commit, so --force)
PREV=$(git rev-parse HEAD~1)
sed -e 's/^round: 1/round: 2/' -e "s/^previous: none/previous: $PREV/" "$tmp/note1b" > "$tmp/note2"
"$rn" write "$tmp/note2" --force
"$rn" latest main | grep -q '^round: 2$' || fail "latest should pick the highest round"
"$rn" latest main | grep -q "^previous: $PREV$" || fail "round 2 should carry previous"
if "$rn" latest nosuch >/dev/null 2>&1; then fail "latest should exit 1 for an unknown branch"; fi
# push publishes notes to origin; a fresh clone picks them up
git remote add origin "$tmp/remote.git"
git push -q origin main
"$rn" push
git clone -q "$tmp/remote.git" "$tmp/clone"
cd "$tmp/clone"
git fetch -q origin "refs/notes/review:refs/notes/review"
"$rn" latest main | grep -q '^round: 2$' || fail "clone should see the round 2 note"
echo "ok: show/write/latest/push"
+65 -29
View File
@@ -1,14 +1,16 @@
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE Arrows #-}
{-# LANGUAGE TypeOperators #-}
module AFRP
( Mealy(..)
, Auto(..)
, DecodedAuto(..)
, eff
, withEntities
, named
, Event(..)
, hold
, holdKnown
, events
-- , switch
, preMapAccum
@@ -18,8 +20,10 @@ module AFRP
, changes
, whenA
, filterA
, filterEvent
, thenA
, (>>|)
, (>>||)
, toEvent
, lMerge
, Pair(..)
@@ -27,6 +31,7 @@ module AFRP
, SerializeUTCTime(..)
, SerializeLocalTime(..)
, edge
, edgeFrom
, waitFor
, duration
, tag
@@ -67,6 +72,8 @@ import qualified Data.Conduit.Cereal as CC
import qualified Conduit as C
import Control.Monad.Catch (MonadCatch, handle)
import Control.Exception.Annotated (throw)
import AFRP.Diagram
import Data.Text (Text)
data Codec s = Codec { getter :: !(Get s), putter :: !(Putter s) }
@@ -129,7 +136,7 @@ instance Monad m => Applicative (Auto m a) where
pure a = Fun (\_req -> const a)
fa <*> fb =
case (fa,fb) of
(Fun af, Fun bf) -> Fun $ \req -> (af req <*> bf req)
(Fun af, Fun bf) -> Fun $ \req -> af req <*> bf req
(Stateful codec s af, Fun bf) -> Stateful codec s
(\s' req x -> do
let a = bf req x
@@ -179,7 +186,7 @@ instance (Monad m, Monoid b) => Monoid (Auto m a b) where
instance Monad m => Category (Auto m) where
id = Fun $ \_ -> id
id = Fun $ const id
af . ag =
case (af, ag) of
(Fun f, Fun g) -> Fun (\req -> f req . g req)
@@ -257,55 +264,58 @@ load path a = handle defaultOnMissingFile (flip deserialize a <$> liftIO (B.read
| isDoesNotExistError e = pure $ FailDecode "State doesn't exist yet" a
| otherwise = throw e
-- | The set of entity ids an arrow subscribes to. Static: it does not
-- change as the machine steps, so the runtime can read it once to build
-- trigger subscriptions.
data Mealy eff a b = Mealy
{ entities :: S.Set T.Text
, runDiagramC :: forall x. (DiagramF x -> x) -> x
, runMealy :: forall m. Monad m => (forall x. eff x -> m x) -> Auto m a b
}
-- Provide a name
named :: Text -> Mealy eff a b -> Mealy eff a b
named n f = f{runDiagramC = \run -> run (Step n (runDiagramC f run))}
instance Semigroup b => Semigroup (Mealy eff a b) where
Mealy ast af <> Mealy bst bf = Mealy (ast <> bst) $ \nt -> af nt <> bf nt
Mealy ast ad af <> Mealy bst bd bf = Mealy (ast <> bst) (combineDiagram Merge ad bd) $ \nt -> af nt <> bf nt
instance Monoid b => Monoid (Mealy eff a b) where
mempty = Mealy mempty $ \_nt -> mempty
-- where
-- m = Mealy mempty $ \_ _ _ -> pure (Pair mempty m)
mempty = Mealy mempty emptyDiagram $ \_nt -> mempty
eff :: (Request -> a -> eff b) -> Mealy eff a b
eff f = Mealy mempty $ \nt -> do
eff f = Mealy mempty emptyDiagram $ \nt -> do
Stateful (Codec get put) (State () False) $ \s req a -> do
b <- nt (f req a)
pure (b, s)
-- | Override the static entity set of an arrow. Use when a combinator
-- (e.g. 'switch') hides continuation entities from the runtime's
-- startup subscription scan.
withEntities :: S.Set T.Text -> Mealy eff a b -> Mealy eff a b
withEntities es (Mealy _ f) = Mealy es f
instance Category (Mealy eff) where
id = Mealy mempty (\_ -> id)
(Mealy ast f) . (Mealy bst g) = Mealy (ast <> bst) $ \nt -> do
{- HLINT ignore "Use const" -}
id = Mealy mempty emptyDiagram $ \_nt -> id
(Mealy ast ad f) . (Mealy bst bd g) = Mealy (ast <> bst) (combineDiagram Then bd ad) $ \nt -> do
f nt . g nt
instance Arrow (Mealy eff) where
arr f = Mealy mempty $ \_nt -> arr f
first (Mealy st f) = Mealy st $ \nt -> first (f nt)
arr f = Mealy mempty emptyDiagram $ \_nt -> arr f
first (Mealy st d f) = Mealy st d $ \nt -> first (f nt)
(Mealy ast ad f) &&& (Mealy bst bd g) = Mealy (ast <> bst) (combineDiagram Both ad bd) $ \nt -> do
f nt &&& g nt
instance ArrowChoice (Mealy eff) where
left (Mealy st f) = Mealy st $ \nt -> left (f nt)
left (Mealy st d f) = Mealy st d $ \nt -> left (f nt)
(Mealy ast ad f) +++ (Mealy bst bd g) = Mealy (ast <> bst) (combineDiagram Branch ad bd) $ \nt -> do
f nt +++ g nt
instance Functor (Mealy eff a) where
fmap f (Mealy st g) = Mealy st $ \nt -> fmap f (g nt)
fmap f (Mealy st d g) = Mealy st d $ \nt -> fmap f (g nt)
instance Applicative (Mealy eff a) where
pure b = Mealy mempty $ \_ -> pure b
Mealy ast f <*> Mealy bst x = Mealy (ast <> bst) $ \nt ->
pure b = Mealy mempty emptyDiagram $ \_ -> pure b
Mealy ast ad f <*> Mealy bst bd x = Mealy (ast <> bst) (combineDiagram Compose ad bd) $ \nt ->
f nt <*> x nt
data Event a
@@ -328,7 +338,12 @@ hold def = mapAccum step def id
Tick -> prev
Event new -> new
snapshot :: (Serialize a, Eq a) => a -> Mealy m (Event (), a) a
-- A variant of 'hold' which makes it explicit whether we have a previous value
holdKnown :: (Serialize a, Eq a) => Mealy m (Event a) (Maybe a)
holdKnown = arr (fmap Just) >>> hold Nothing
snapshot :: (Serialize a, Eq a) => a -> Mealy m (Event x, a) a
snapshot def = mapAccum step def id
where
step prev (Tick, _) = prev
@@ -365,10 +380,10 @@ preMapAccum' f x extract = Stateful (Codec get put) (pure x) (\s _req a -> pure
mapAccum :: (Eq x, Serialize x) => (x -> a -> x) -> x -> (x -> b) -> Mealy eff a b
mapAccum step x extract = Mealy mempty $ \_nt -> mapAccum' step x extract
mapAccum step x extract = Mealy mempty emptyDiagram $ \_nt -> mapAccum' step x extract
preMapAccum :: (Eq x, Serialize x) => (x -> a -> x) -> x -> (x -> b) -> Mealy eff a b
preMapAccum step x extract = Mealy mempty $ \_nt -> preMapAccum' step x extract
preMapAccum step x extract = Mealy mempty emptyDiagram $ \_nt -> preMapAccum' step x extract
mapAccum' :: forall m x a b. (Monad m, Eq x, Serialize x) => (x -> a -> x) -> x -> (x -> b) -> Auto m a b
mapAccum' f x extract = Stateful (Codec get put) (pure x) (\s _req a -> pure $ step s a)
@@ -377,7 +392,7 @@ mapAccum' f x extract = Stateful (Codec get put) (pure x) (\s _req a -> pure $ s
step s a = let s' = f (state s) a in (extract s', State s' (dirty s || state s /= s'))
preMapAccumRequest :: (Serialize x, Eq x) => (Request -> x -> a -> x) -> x -> (x -> b) -> Mealy eff a b
preMapAccumRequest step x extract = Mealy mempty $ \_ -> preMapAccumRequest' step x extract
preMapAccumRequest step x extract = Mealy mempty emptyDiagram $ \_ -> preMapAccumRequest' step x extract
preMapAccumRequest' :: forall m x a b. (Serialize x, Eq x, Monad m) => (Request -> x -> a -> x) -> x -> (x -> b) -> Auto m a b
preMapAccumRequest' f x extract = Stateful (Codec get put) (State x False) (\s req a -> pure $ step s req a)
@@ -386,7 +401,7 @@ preMapAccumRequest' f x extract = Stateful (Codec get put) (State x False) (\s r
step s req a = let s' = f req (state s) a in (extract (state s), State s' (dirty s || state s /= s'))
mapAccumRequest :: (Serialize x, Eq x) => (Request -> x -> a -> x) -> x -> (x -> b) -> Mealy eff a b
mapAccumRequest step x extract = Mealy mempty $ \_ -> mapAccumRequest' step x extract
mapAccumRequest step x extract = Mealy mempty emptyDiagram $ \_ -> mapAccumRequest' step x extract
mapAccumRequest' :: forall m x a b. (Monad m, Serialize x, Eq x) => (Request -> x -> a -> x) -> x -> (x -> b) -> Auto m a b
mapAccumRequest' f x extract = Stateful (Codec get put) (State x False) (\s req a -> pure $ step s req a)
@@ -480,6 +495,13 @@ whenA predicate auto = arr (\a -> if predicate a then Left a else Right ()) >>>
filterA :: (a -> Bool) -> Mealy eff a (Either () a)
filterA f = arr $ \a -> bool (Left ()) (Right a) (f a)
-- filters events through if they match the predicate
filterEvent :: (ArrowChoice cat, Arrow cat) => (a -> Bool) -> Event a `cat` Event a
filterEvent predicate = proc ev -> do
case ev of
Event a | predicate a -> id -< ev
_ -> arr (const Tick) -< ()
thenA :: (ArrowChoice cat, Arrow cat) => cat a (Either b1 c) -> cat c (Either b1 b2) -> cat a (Either b1 b2)
thenA f g = f >>> arr Left ||| g
@@ -488,6 +510,15 @@ thenA f g = f >>> arr Left ||| g
infixl 2 >>|
(>>||) :: (ArrowChoice cat, Arrow cat) => cat a (Event b) -> cat b c -> cat a (Event c)
f >>|| g = proc x -> do
e <- f -< x
case e of
Event e' -> g >>> arr Event -< e'
Tick -> arr (const Tick) -< ()
infixr 1 >>||
toEvent :: Mealy eff (Either () a) (Event a)
toEvent = arr (either (const Tick) Event)
@@ -498,10 +529,15 @@ lMerge (Event a) _ = Event a
lMerge Tick (Event a) = Event a
edge :: Mealy eff Bool (Event ())
edge =
edge = edgeFrom False
-- | Edge that behaves as if the input has been `start` forever, so the first
-- True input does not fire when `start` is already True (no transition).
edgeFrom :: Bool -> Mealy eff Bool (Event ())
edgeFrom start =
mapAccum
(\(_, current) new -> (current, new))
(False, False)
(start, start)
(\(old, current) ->
if not old && current
then Event ()
@@ -602,7 +638,7 @@ requestLocalTime :: Request -> LocalTime
requestLocalTime Request{requestTime, requestTimeZone} = utcToLocalTime requestTimeZone requestTime
currentTime :: Mealy eff a LocalTime
currentTime = Mealy mempty $ \_nt -> Fun $ \req _ ->
currentTime = Mealy mempty emptyDiagram $ \_nt -> Fun $ \req _ ->
requestLocalTime req
+49
View File
@@ -0,0 +1,49 @@
{-# LANGUAGE OverloadedStrings #-}
module AFRP.Diagram where
import Data.Text (Text)
import qualified Text.Printf as Text
import qualified Data.Text as T
-- For rendering the arrows
data DiagramF f
= Empty
| Step Text f -- Named step
| Then f f -- >>>
| Both f f -- &&&
| Branch f f -- |||
| Merge f f -- <>
| Compose f f -- <*>
type DiagramAlgebra a = DiagramF a -> a
type DiagramC= forall a. DiagramAlgebra a -> a
combineDiagram :: (forall a. a -> a -> DiagramF a) -> DiagramC -> DiagramC -> DiagramC
combineDiagram constructor a b r = r (constructor (a r) (b r))
emptyDiagram :: DiagramC
emptyDiagram r = r Empty
renderF :: DiagramF (Maybe T.Text) -> Maybe T.Text
renderF = \case
Empty -> Nothing
Step n x -> Just $ n <> T.pack (maybe "" (Text.printf "( %s )") x)
Then (Just a) (Just b) -> Just $ a <> " -> " <> b
Then (Just a) _ -> Just a
Then _ b -> b
Both (Just a) (Just b) -> Just $ T.pack $ Text.printf "(%s, %s)" a b
Both (Just a) _ -> Just a
Both _ b -> b
Branch (Just a) (Just b) -> Just $ T.pack $ Text.printf "(%s || %s)" a b
-- I'm leaving this here. This would be technically more correct (showing
-- the empty branch, ie. the full if-then-else, but often we care about a
-- more simplistic `when` style structure
-- Branch (Just a) Nothing -> Just $ T.pack $ Text.printf "(%s || <skip>)" a
Branch (Just a) Nothing -> Just $ T.pack $ Text.printf "%s" a
Branch _ b -> b
Merge (Just a) (Just b) -> Just $ T.pack $ Text.printf "(%s, %s)" a b
Merge (Just a) _ -> Just a
Merge _ b -> b
Compose (Just a) (Just b) -> Just $ T.pack $ Text.printf "(%s, %s)" a b
Compose (Just a) _ -> Just a
Compose _ b -> b
+80 -63
View File
@@ -1,21 +1,18 @@
{-# LANGUAGE Arrows #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DerivingVia #-}
module HomeAssistant.Controller.Bedroom where
import HomeAssistant.Controller
import qualified Data.Text as T
import AFRP (Event (..), lMerge, duration, edge)
import AFRP (Event (..), edge, filterEvent, hold, named, snapshot, tag, waitFor, (>>||))
import Data.Aeson (Value, object, (.=))
import Control.Arrow ((>>>), returnA, arr, Arrow (..))
import Data.Bool (bool)
import Data.Time (NominalDiffTime)
import qualified AFRP
import Data.Map (Map)
import qualified Data.Map.Strict as M
import Data.Serialize.Text ()
import Data.Default (def)
import Data.Serialize (Serialize)
@@ -31,66 +28,80 @@ createBedroomScene = Service
, "snapshot_entities" .= [l | EntityId l <- bedroomLightTargets]
]
, serviceTarget= []
, serviceExclusions= []
}
-- Bedroom presence
bedroomPresence :: HASS (Event Value) (Event Presence)
bedroomPresence = presence "binary_sensor.presence_sensor_bedroom_occupancy"
presenceLightEvents :: HASS (Event Value) (Event LightingMode)
presenceLightEvents =
bedroomPresence >>> AFRP.hold Unoccupied
>>> arr lightWanted
>>> (sleepEvent &&& offEvent &&& onEvent)
>>> arr (\(s,(o,n)) -> s `AFRP.lMerge` o `AFRP.lMerge` n)
where
lightWanted o = o == Occupied
sleepEvent = arr not >>> AFRP.edge >>> arr (AFRP.tag LightingSleep)
onEvent = AFRP.edge >>> arr (AFRP.tag LightingOn)
offEvent = arr not >>> AFRP.waitFor 300 >>> arr (AFRP.tag LightingOff)
bedroomPresenceOccupied :: HASS (Event Value) Bool
bedroomPresenceOccupied = bedroomPresence >>> hold Unoccupied >>> arr (== Occupied)
bedroomLightStatus :: HASS (Event Value) (Map T.Text LightObservation)
bedroomLightStatus = M.fromList <$> traverse (\e -> (e,) <$> observedLight e) [e | EntityId e <- bedroomLightTargets]
newtype Snapshot = Snapshot { getSnapshot :: Map T.Text LightObservation }
deriving (Show, Eq)
deriving Serialize via (Map T.Text LightObservation)
-- 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 = entityRead "sensor.presence_sensor_bedroom_light_level" >>> AFRP.hold 15
lightLevel = entityRead "sensor.presence_sensor_bedroom_light_level" >>> AFRP.hold 1
-- Snapshot the light status when leaving (presence turning unoccupied),
-- restored on the next entry.
snapshotOnLeaving :: HASS (Event Value) (Map T.Text LightObservation)
snapshotOnLeaving =
(bedroomPresenceOccupied &&& bedroomLightStatus)
>>> first (arr not >>> edge)
>>> snapshot M.empty
-- The light reactions run "in parallel"; there is a chance that two
-- services are called in one go
bedroomPresenceController :: HASS (Event Value) ()
bedroomPresenceController = proc x -> do
p <- presenceLightEvents >>> traceEvent -< x
capped <- lightLevel >>> arr (< 4) -< x
-- mode <- AFRP.hold LightingOff -< p
-- This line is just for debugging purposes
_ <- bedroomLightStatus >>> AFRP.changes >>> traceEvent -< x
_ <- lightLevel >>> AFRP.changes >>> traceEvent -< x
snap <- (doSnapshot &&& bedroomLightStatus) >>> AFRP.snapshot M.empty >>> arr Snapshot -< x
-- This line is just for debugging
_ <- AFRP.changes >>> traceEvent -< snap
case p of
Event LightingOff -> do
callService (light bedroomLightTargets Off) -< ()
Event LightingOn -> do
callServicesDyn (\(c,xs) -> concatMap (uncurry (toLight c)) xs) -< (capped, M.toList (getSnapshot snap))
returnA -< ()
Event LightingSleep -> do
callService (activateScene "scene.makuuhuone_lepotila") -< ()
_ -> returnA -< ()
bedroomPresenceController =
((,,,) <$> bedroomPresenceOccupied <*> cappedLightLevel <*> bedroomLightStatus <*> snapshotOnLeaving)
>>> mconcat
[ AFRP.named "Lights on" lightsOn
, AFRP.named "Lights sleep" lightsSleep
, AFRP.named "Lights off" lightsOff
]
>>> arr (const ()) -- I don't like this extra arr here
where
cappedLightLevel :: HASS (Event Value) Bool
cappedLightLevel = lightLevel >>> arr (< 4)
lightsOn =
arr (\(o, capped, _, snap) -> (o, (capped, M.toList snap)))
>>> first edge
>>> arr (\(ev, p) -> tag p ev)
>>|| callServicesDyn "Turn on lights (capped)" (\(c,xs) -> concatMap (uncurry (toLight c)) xs)
lightsSleep =
arr (\(o, _, st, _) -> (not o, st))
>>> first edge
>>> arr (\(ev, st) -> tag st ev)
>>> filterEvent anyLightsAreOn
>>|| callService "Turn on sleep" (activateScene "scene.makuuhuone_lepotila")
lightsOff =
arr (\(o, _, _, _) -> not o)
>>> waitFor 300
>>|| callService "Turn off lights" (light bedroomLightTargets [] Off)
anyLightsAreOn :: Foldable f => f LightObservation -> Bool
anyLightsAreOn = any observedOn
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} =
[ light [EntityId entityId] (On def
[ light [EntityId entityId] [] (On def
{lightBrightness = fmap (\b' -> BrightnessAbsolute $ if capped then 140 `min` b' else b') b
, lightColorTemperature = t
})
]
doSnapshot = presenceLightEvents
>>> arr (\ev -> if ev == Event LightingSleep then Event () else Tick)
data BedroomControls
@@ -102,7 +113,7 @@ data BedroomControls
bedroomButton :: HASS (Event Value) (Event BedroomControls)
bedroomButton = (masseButton &&& enishenButton &&& centralButton)
>>> arr (\(a,(b,c)) -> a `lMerge` b `lMerge` c)
>>> arr (\(a,(b,c)) -> a <> b <> c)
where
masseButton = fmap Masse <$> ikeaQuickButton "event.bedroom_quick_remote_masse_action"
enishenButton = fmap Enishen <$> ikeaQuickButton "event.bedroom_quick_jemina_action"
@@ -114,21 +125,27 @@ bedroomButtonController = proc x -> do
-- Any event will cause the sleep mode to be turned off
case ev of
Event (Masse (OnButton ShortRelease)) -> do
callService (activateScene "scene.makuuhuone_masse") -< ()
callService "scene.makuuhuone_masse" (activateScene "scene.makuuhuone_masse") -< ()
Event (Masse (OnButton DoubleClick)) -> do
callService (activateScene "scene.makuuhuone_keski") -< ()
callService "scene.makuuhuone_keski" (activateScene "scene.makuuhuone_keski") -< ()
Event (Masse (OnButton LongClick)) -> do
callService (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
callService (light [AreaId "makuuhuone"] Off) -< ()
callService "Lights off" (light [AreaId "makuuhuone"] [] Off) -< ()
Event (Enishen (OnButton ShortRelease)) -> do
callService (activateScene "scene.makuuhuone_jemina") -< ()
callService "scene.makuuhuone_jemina" (activateScene "scene.makuuhuone_jemina") -< ()
Event (Enishen (OnButton DoubleClick)) -> do
callService (activateScene "scene.makuuhuone_keski") -< ()
callService "scene.makuuhuone_keski" (activateScene "scene.makuuhuone_keski") -< ()
Event (Enishen (OnButton LongClick)) -> do
callService (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
callService (light [AreaId "makuuhuone"] Off) -< ()
callService "Lights off" (light [AreaId "makuuhuone"] [] Off) -< ()
_ -> returnA -< ()
@@ -138,22 +155,21 @@ drawer = entityBool "binary_sensor.bedroom_nightstand_drawer_sensor_masse_contac
>>> arr (fmap (bool Closed Open))
bedroomDrawerController :: HASS (Event Value) ()
bedroomDrawerController = proc x -> do
st <- drawer >>> traceEvent -< x
case st of
Event Open -> callService (switchService [entity] True) -< ()
Event Closed -> callService (switchService [entity] False) -< ()
_ -> returnA -< ()
bedroomDrawerController =
drawer >>>
(named "Drawer opened" lightOn <> named "Drawer closed" lightOff)
>>> arr (const ())
where
entity = EntityId "switch.bedroom_drawer_light_masse"
lightOff = filterEvent (== Closed)
>>|| callService "drawer light off" (switchService [entity] [] False)
lightOn = filterEvent (== Open)
>>|| callService "drawer light on" (switchService [entity] [] True)
door :: HASS (Event Value) (Event DoorState)
door = entityBool "binary_sensor.makuuhuone_ovi_contact"
>>> arr (fmap (bool Closed Open))
waitFor :: NominalDiffTime -> HASS a (Event ())
waitFor n = duration >>> arr (> n) >>> edge
delayedDoor :: HASS (Event Value) (Event DoorState)
delayedDoor = door
@@ -167,8 +183,8 @@ humidifierController = proc x -> do
case st of
-- Turn the humidifier on when the door is closed
-- the humidifier is low-powered, no point in losing all the humidity
Event Open -> callService (humidifier False) -< ()
Event Closed -> callService (humidifier True) -< ()
Event Open -> callService "Humidifier off" (humidifier False) -< ()
Event Closed -> callService "Humidifier on" (humidifier True) -< ()
_ -> returnA -< ()
where
humidifier state = Service
@@ -176,4 +192,5 @@ humidifierController = proc x -> do
, serviceName= bool "turn_off" "turn_on" state
, serviceData= Nothing
, serviceTarget= [EntityId "humidifier.makuuhuone_ilmankostutin"]
, serviceExclusions= []
}
+80 -8
View File
@@ -1,15 +1,25 @@
{-# LANGUAGE Arrows #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DerivingVia #-}
module HomeAssistant.Controller.Children where
import HomeAssistant.Controller (HASS, callService, Target (AreaId), light, LightCommand(..), ikeaQuickButton, IkeaGesture (..), IkeaButton (..), traceEvent, activateScene, LightAttributes (..), Brightness (..))
import HomeAssistant.Controller (HASS, callService, light, LightCommand(..), ikeaQuickButton, IkeaGesture (..), IkeaButton (..), traceEvent, activateScene, LightAttributes (..), Brightness (..), entityRead, entityChangeEvent)
import AFRP (Event (..))
import qualified AFRP
import Control.Arrow (Arrow(..), (>>>), returnA)
import Data.Time (Day, TimeOfDay (..), localDay, LocalTime (..))
import Data.Time.Calendar.OrdinalDate (WeekOfYear, mondayStartWeek)
import Data.Functor.Contravariant (Predicate (..), (>$<))
import Data.Aeson (Value)
import Data.Aeson (Value, object, (.=))
import Data.Default (Default(..))
import Data.Serialize (Serialize)
import Data.Serialize.Text ()
import GHC.Generics (Generic)
import HomeAssistant.Controller.Service (Service(..), Target(..))
import Data.Aeson.Types (ToJSON (..))
import Data.Aeson.Lens (key, _String)
import Control.Lens ((^?), to)
import Data.Text (Text)
import Control.Monad (join)
-- Let's see building some reasonable interface for utctime
dow :: Day -> (WeekOfYear, Int)
@@ -75,11 +85,13 @@ schoolLightController = lightsOn <> lightsOff
lightsOn :: HASS a ()
lightsOn = foldMap atTime timersOn
>>> AFRP.onEvent (callService (light [AreaId "lasten_makuuhuone"] (On def{lightBrightness=Just $ BrightnessPercent 100} )))
>>> AFRP.onEvent (callService "Lights on" lights)
where
lights = light [AreaId "lasten_makuuhuone"] [] (On def{lightBrightness=Just (BrightnessPercent 100), lightTransition = Just 5} )
lightsOff :: HASS a ()
lightsOff = foldMap atTime timersOff
>>> AFRP.onEvent (callService (light [AreaId "lasten_makuuhuone"] Off))
>>> AFRP.onEvent (callService "Lights off" (light [AreaId "lasten_makuuhuone"] [LabelId "decoration"] Off))
childrenBedroomButton :: HASS (Event Value) (Event (IkeaButton IkeaGesture))
@@ -89,8 +101,68 @@ childrenBedroomButtonController :: HASS (Event Value) ()
childrenBedroomButtonController = proc x -> do
ev <- childrenBedroomButton >>> traceEvent -< x
case ev of
Event (OnButton ShortRelease) -> callService (activateScene "scene.lasten_nukkuvalmistelu") -< ()
Event (OnButton DoubleClick) -> callService (activateScene "scene.lasten_luku") -< ()
Event (OnButton LongClick) -> callService (activateScene "scene.lasten_kirkas") -< ()
Event (OffButton _) -> callService (light [AreaId "lasten_makuuhuone"] Off) -< ()
Event (OnButton ShortRelease) -> callService "scene.lasten_nukkuvalmistelu" (activateScene "scene.lasten_nukkuvalmistelu") -< ()
Event (OnButton DoubleClick) -> callService "scene.lasten_luku" (activateScene "scene.lasten_luku") -< ()
Event (OnButton LongClick) -> callService "scene.lasten_kirkas" (activateScene "scene.lasten_kirkas") -< ()
Event (OffButton _) -> callService "Lights off" (light [AreaId "lasten_makuuhuone"] [LabelId "decoration"] Off) -< ()
_ -> returnA -< ()
newtype PM25 = PM25 Float
deriving (Serialize, Eq, Ord) via Float
deriving Show
data PM25Level = PM25High | PM25Low
deriving (Eq, Generic, Show)
instance Serialize PM25Level
pm25 :: HASS (Event Value) PM25
pm25 = fmap PM25 (entityRead "sensor.children_temp_pm25" >>> AFRP.hold 0)
pm25Level :: HASS PM25 PM25Level
pm25Level = (tagHigh &&& tagLow) >>> arr (uncurry AFRP.lMerge) >>> AFRP.hold PM25Low
where
-- Band between 8 and 12 to avoid oscillation near the ~10 mark
tagHigh = arr (> PM25 12) >>> AFRP.edge >>> arr (AFRP.tag PM25High)
tagLow = arr (< PM25 8) >>> AFRP.edge >>> arr (AFRP.tag PM25Low)
data HumidifierAction
= Idle
| Humidifying
| Other Text
deriving (Show, Eq, Generic)
instance Serialize HumidifierAction
-- what is the humidifer doing right now?
humidifierOperatingState :: HASS (Event Value) (Event (Maybe HumidifierAction))
humidifierOperatingState = entityChangeEvent "humidifier.lapset_ilmankostutin"
>>> arr (fmap entityAction)
where
entityAction v = v ^? key "event" . key "variables" . key "trigger" . key "to_state" . key "attributes" . key "action" . _String . to humidifierAction
humidifierAction = \case
"idle" -> Idle
"humidifying" -> Humidifying
other -> Other other
-- TODO: There's some other percentages elsewhere that could be replaced with this
newtype Percentage = Percentage Int
instance ToJSON Percentage where
toJSON (Percentage p) = object ["percentage" .= p]
childrenAirFilterController :: HASS (Event Value) ()
childrenAirFilterController = proc ev -> do
level <- pm25 >>> pm25Level >>> AFRP.changes >>> traceEvent -< ev
humidifier <- humidifierOperatingState >>> AFRP.holdKnown >>> arr join -< ev
case level of
Event PM25High ->
AFRP.whenA (== Just Idle) (callService "Fan strong" (fanOnTo (Percentage 80))) -< humidifier
Event PM25Low -> callService "Fan low" (fanOnTo (Percentage 20)) -< ()
_ -> returnA -< ()
where
fanOnTo percentage = Service
{ serviceDomain = "fan"
, serviceName = "set_percentage"
, serviceTarget = [EntityId "fan.children_fan"]
, serviceExclusions = []
, serviceData = Just $ toJSON percentage
}
+10 -1
View File
@@ -1,9 +1,18 @@
module HomeAssistant.Controller.Door (DoorState(..)) where
module HomeAssistant.Controller.Door (DoorState(..), doorState) where
import GHC.Generics (Generic)
import Data.Serialize (Serialize)
import AFRP (Mealy, Event)
import Data.Aeson (Value)
import Data.Text (Text)
import HomeAssistant.Controller.Entity (entityBool)
import Control.Arrow ((>>>), arr)
import Data.Bool (bool)
data DoorState = Open | Closed
deriving (Show, Eq, Generic)
instance Serialize DoorState
doorState :: Text -> Mealy eff (Event Value) (Event DoorState)
doorState entity = entityBool entity >>> arr (fmap (bool Closed Open))
+15 -10
View File
@@ -1,5 +1,6 @@
{-# LANGUAGE Arrows #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
module HomeAssistant.Controller.Effect
( HASSEff(..)
@@ -13,9 +14,10 @@ module HomeAssistant.Controller.Effect
, traceValue
) where
import AFRP (Mealy, eff, Event (..), Request)
import AFRP (Mealy, eff, Event (..), Request, named)
import Control.Arrow (returnA)
import HomeAssistant.Controller.Service (Service)
import HomeAssistant.Controller.Service (Service (..))
import qualified Data.Text as T
data HASSEff a where
CallService :: Request -> Service -> HASSEff ()
@@ -25,17 +27,20 @@ data HASSEff a where
type HASS a b = Mealy HASSEff a b
callService :: Service -> HASS a ()
callService service = eff (\req _ -> CallService req service)
serviceLabel :: T.Text -> HASS a b -> HASS a b
serviceLabel lbl = named ("Service: " <> lbl)
callServices :: [Service] -> HASS a ()
callServices service = eff (\req _ -> CallServices req service)
callService :: T.Text -> Service -> HASS a ()
callService lbl service = serviceLabel lbl $ eff (\req _ -> CallService req service)
callServiceDyn :: (a -> Service) -> HASS a ()
callServiceDyn mkService = eff (\req a -> CallService req (mkService a))
callServices :: T.Text -> [Service] -> HASS a ()
callServices lbl service = serviceLabel lbl $ eff (\req _ -> CallServices req service)
callServicesDyn :: (a -> [Service]) -> HASS a ()
callServicesDyn mkService = eff (\req a -> CallServices req (mkService a))
callServiceDyn :: T.Text -> (a -> Service) -> HASS a ()
callServiceDyn lbl mkService = serviceLabel lbl $ eff (\req a -> CallService req (mkService a))
callServicesDyn :: T.Text -> (a -> [Service]) -> HASS a ()
callServicesDyn lbl mkService = serviceLabel lbl $ eff (\req a -> CallServices req (mkService a))
debug :: Show a => HASS a a
debug = proc x -> do
+3 -2
View File
@@ -10,7 +10,7 @@ module HomeAssistant.Controller.Entity
, entityBool'
) where
import AFRP (Mealy (..), Event, events, filterA, (>>|), toEvent)
import AFRP (Mealy (..), Event, events, filterA, (>>|), toEvent, named)
import Control.Arrow (arr)
import Control.Category ((>>>))
import Data.Aeson (Value)
@@ -19,12 +19,13 @@ import qualified Data.Text as T
import qualified Data.Set as S
import Control.Lens (has, only, (^?), to)
import qualified Data.Text.Lens as TL
import AFRP.Diagram (emptyDiagram)
entityChangeEvent :: T.Text -> Mealy eff (Event Value) (Event Value)
entityChangeEvent entityId = entityChangeEvent' entityId >>> toEvent
entityChangeEvent' :: T.Text -> Mealy eff (Event Value) (Either () Value)
entityChangeEvent' entityId = Mealy (S.singleton entityId) $ runMealy (events >>| filterA isEntity)
entityChangeEvent' entityId = named entityId $ Mealy (S.singleton entityId) emptyDiagram $ runMealy (events >>| filterA isEntity)
where
isEntity :: Value -> Bool
isEntity = has (key "event" . key "variables" . key "trigger" . key "entity_id" . _String . only entityId)
+84 -15
View File
@@ -1,31 +1,100 @@
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE Arrows #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE RecordWildCards #-}
module HomeAssistant.Controller.Hallway where
import HomeAssistant.Controller (Presence, HASS, motion, motionToPresence, traceEvent, callServiceDyn, light, Target (..), LightCommand (..))
import HomeAssistant.Controller.Light.Mode (LightingMode (..), lightingModeEvents)
import HomeAssistant.Controller (Presence (..), HASS, motion, motionToPresence, callServiceDyn, light, Target (..), LightCommand (..), doorState, DoorState (..), callService)
import HomeAssistant.Controller.Bedroom (readyForSleep)
import AFRP (Event (..))
import qualified AFRP
import Data.Aeson (Value)
import Control.Arrow ((>>>), returnA)
import Control.Arrow ((>>>), arr, returnA)
import Data.Time (LocalTime(..), TimeOfDay (..))
import Data.Default (def)
import Data.Serialize (Serialize)
import GHC.Generics (Generic)
data Mode
= Quiet -- ^ Possibly sleep time, doors are open, minimize light leakage
| Regular -- ^ Doors are closed, light leakage is not a concern
deriving (Generic, Eq, Show)
instance Serialize Mode
data ModeInput = ModeInput
{ roomTimeOfDay :: TimeOfDay
, bedroomDoor :: Maybe DoorState
, childrenBedroomDoor :: Maybe DoorState
, bedroomReadyForSleep :: Bool
}
mode :: HASS (Event Value) Mode
mode = roomState >>> arr sleepMode
where
sleepMode :: ModeInput -> Mode
sleepMode ModeInput{..} = sleep
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
| otherwise = Regular
roomState = ModeInput <$> timeOfDay <*> masterBedroom <*> childrenBedroom <*> readyForSleep
timeOfDay = fmap localTimeOfDay AFRP.currentTime
masterBedroom = doorState "binary_sensor.makuuhuone_ovi_contact" >>> AFRP.holdKnown
childrenBedroom = doorState "binary_sensor.lasten_makuuhuone_ovi_contact" >>> AFRP.holdKnown
hallwayPresence :: HASS (Event Value) Presence
hallwayPresence = motion "binary_sensor.hallway_movement_occupancy" >>> motionToPresence 500
hallwayLightsController :: HASS (Event Value) ()
hallwayLightsController = proc x -> do
now <- AFRP.currentTime -< ()
p <- hallwayPresence -< x
ev <- lightingModeEvents -< p
traceEvent -< ev
case ev of
-- The lights entity is a "group of lights" in hass
Event LightingOn | lightsAllowed now -> callServiceDyn (light [EntityId "light.hallway_lights"]) -< On def
Event LightingOff -> callServiceDyn (light [EntityId "light.hallway_lights"]) -< Off
_ -> returnA -< ()
lightsOnTrigger :: HASS (Event Value) (Event ())
lightsOnTrigger = hallwayPresence >>> arr (== Occupied) >>> AFRP.edge
modeTrigger :: HASS (Event Value) (Event Mode)
modeTrigger = ((,) <$> hallwayPresence <*> (mode >>> AFRP.changes)) >>> arr go
where
lightsAllowed (LocalTime _ tod) = not (tod > TimeOfDay 1 45 0 && tod < TimeOfDay 5 0 0)
go (Unoccupied, _) = Tick
go (Occupied, e) = e
modeC :: HASS (Event Value) ()
modeC = modeTrigger >>> mconcat
[ AFRP.filterEvent (== Quiet) AFRP.>>|| lightOff
, AFRP.filterEvent (== Regular) AFRP.>>|| lightOn
] >>>
arr (const ())
where
lightOff = callService "Lower light off" (light [EntityId "light.hallway_ceiling"] [] Off)
lightOn = callService "Lower light back on" (light [EntityId "light.hallway_ceiling"] [] (On def))
onC :: HASS (Event Value) ()
onC = proc ev -> do
trigger <- lightsOnTrigger -< ev
m <- mode -< ev
let entities = case m of
Quiet -> [EntityId "light.hallway_ceiling_2"]
Regular -> [EntityId "light.hallway_lights"]
case trigger of
Event _ -> lightsOn -< entities
Tick -> returnA -< ()
where
lightsOn = callServiceDyn "Lights on" (\es -> light es [] (On def))
lightsOffTrigger :: HASS (Event Value) (Event ())
lightsOffTrigger = hallwayPresence >>> arr (== Unoccupied) >>>
AFRP.edgeFrom True -- we start from 'edgeFrom True' because the initial state is to be unoccupied
offC :: HASS (Event Value) ()
offC = (lightsOffTrigger AFRP.>>|| lightsOff) >>>
arr (const ())
where
lightsOff = callService "Lights off" (light [EntityId "light.hallway_lights"] [] Off)
hallwayLightsController :: HASS (Event Value) ()
hallwayLightsController = onC <> offC <> modeC
+23 -28
View File
@@ -2,7 +2,7 @@
{-# LANGUAGE Arrows #-}
module HomeAssistant.Controller.Kitchen where
import HomeAssistant.Controller
import AFRP (Event (..))
import AFRP (Event (..), (>>||))
import qualified AFRP
import Data.Aeson (Value)
import Control.Arrow ((>>>), Arrow (..), returnA)
@@ -23,8 +23,8 @@ kitchenCeilingController = proc x -> do
ev <- lightingModeEvents -< p
traceEvent -< ev
case ev of
Event LightingOn | lightsAllowed now -> callServiceDyn (light [EntityId "light.kitchen_ceiling"]) -< On def
Event LightingOff -> callServiceDyn (light [EntityId "light.kitchen_ceiling"]) -< Off
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
_ -> returnA -< ()
where
lightsAllowed (LocalTime _ tod) = not (tod > TimeOfDay 1 45 0 && tod < TimeOfDay 5 0 0)
@@ -36,44 +36,39 @@ dinnerLightLevel = entityRead "sensor.sijainti_keittio_light_level" >>> AFRP.hol
dinnerPresence :: HASS (Event Value) Presence
dinnerPresence = presence "binary_sensor.sijainti_keittio_occupancy" >>> AFRP.hold Unoccupied
dinnerLightEvents :: HASS (Event Value) (Event LightingMode)
dinnerLightEvents =
dinnerTableController :: HASS (Event Value) ()
dinnerTableController =
((,) <$> dinnerLightLevel <*> dinnerPresence)
>>> arr lightWanted
>>> (sleepEvent &&& offEvent &&& onEvent)
>>> arr (\(s, (o, n)) -> s `AFRP.lMerge` o `AFRP.lMerge` n)
-- These are done "in parallel", there is a chance that two services are called in one go
>>> mconcat
[ AFRP.named "Lights on" lightsOn
, AFRP.named "Lights sleep" lightsSleep
, AFRP.named "Lights off" lightsOff ]
>>> arr (const ()) -- I don't like this extra arr here
where
lightWanted (lightLevel, occ) = occ == Occupied && lightLevel < 13
onEvent =
lightsOn =
AFRP.edge
>>> arr (fmap (const LightingOn))
>>|| sleep "sleep off" False
>>> callService "Dining light on" (light [EntityId "light.kitchen_dining_large"] [] $ On def)
sleepEvent =
lightsSleep =
arr not
>>> AFRP.edge
>>> arr (fmap (const LightingSleep))
>>|| sleep "sleep on" True
offEvent =
lightsOff =
arr not
>>> AFRP.waitFor 300
>>> arr (fmap (const LightingOff))
>>|| sleep "sleep off" False
>>> 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)
dinnerTableController :: HASS (Event Value) ()
dinnerTableController = proc x -> do
ev <- dinnerLightEvents -< x
case ev of
Event LightingOn -> do
sleep -< False
callServiceDyn (light [EntityId "light.kitchen_dining_large"]) -< On def
Event LightingOff -> do
sleep -< False
callServiceDyn (light [EntityId "light.kitchen_dining_large"]) -< Off
Event LightingSleep -> do
sleep -< True
_ -> returnA -< ()
where
sleep = callServiceDyn (switchService [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"])
kitchenMotionController :: HASS (Event Value) ()
kitchenMotionController = kitchenCeilingController <> dinnerTableController
@@ -47,16 +47,19 @@ data LightCommand
= Off
| On LightAttributes
light :: [Target] -> LightCommand -> Service
light targets (On settings) = Service
light :: [Target] -> [Target] -> LightCommand -> Service
light targets exclusions = \case
(On settings) -> Service
{ serviceDomain="light"
, serviceName= "turn_on"
, serviceData= formatLightAttributes settings
, serviceTarget=targets
, serviceExclusions = exclusions
}
light targets Off = Service
Off -> Service
{ serviceDomain="light"
, serviceName= "turn_off"
, serviceData=Nothing
, serviceTarget=targets
, serviceExclusions = exclusions
}
+4 -4
View File
@@ -39,8 +39,8 @@ livingroomPresenceController = proc x -> do
ev <- lightingModeEvents . livingroomPresence -< x
traceEvent -< ev
case ev of
AFRP.Event LightingOn -> callServiceDyn (light livingroomLightTargets) -< On def
AFRP.Event LightingOff -> callServiceDyn (light livingroomLightTargets) -< Off
AFRP.Event LightingOn -> callServiceDyn "Lights on" (light livingroomLightTargets []) -< On def
AFRP.Event LightingOff -> callServiceDyn "Lights off" (light livingroomLightTargets []) -< Off
_ -> returnA -< ()
returnA -< ()
@@ -88,6 +88,6 @@ livingroomPlantLights = (season &&& tod)
where
setLights = proc mode -> do
case mode of
AFRP.Event Growth -> callService (activateScene "scene.olohuoneen_kasvivalo") -< ()
AFRP.Event Ambience -> callService (activateScene "scene.kasvivalo_iltatila") -< ()
AFRP.Event Growth -> callService "scene.olohuoneen_kasvivalo" (activateScene "scene.olohuoneen_kasvivalo") -< ()
AFRP.Event Ambience -> callService "scene.kasvivalo_iltatila" (activateScene "scene.kasvivalo_iltatila") -< ()
_ -> returnA -< ()
+14 -9
View File
@@ -3,10 +3,11 @@ module HomeAssistant.Controller.Presence
, presence
, Motion(..)
, motion
, motionEvent
, motionToPresence
) where
import AFRP (Event, hold, lMerge, waitFor, tag, edge)
import AFRP (Event, hold, lMerge, waitFor, tag, edge, holdKnown)
import Control.Arrow (arr, (&&&))
import Control.Category ((>>>))
import Data.Aeson (Value)
@@ -28,28 +29,32 @@ presence entityId = entityBool entityId
>>> arr (fmap (bool Unoccupied Occupied))
data Motion = MotionDetected | MotionNotDetected | MotionUnknown
data Motion = MotionDetected | MotionNotDetected
deriving (Show, Eq, Generic)
motion :: T.Text -> HASS (Event Value) Motion
motionEvent :: T.Text -> HASS (Event Value) (Event Motion)
motionEvent entityId = entityBool entityId
>>> arr (fmap (bool MotionNotDetected MotionDetected))
motion :: T.Text -> HASS (Event Value) (Maybe Motion)
motion entityId = entityBool entityId
>>> arr (fmap (bool MotionNotDetected MotionDetected))
>>> hold MotionUnknown
>>> holdKnown
-- Convert a motion status into a simulated presence
--
-- A motion tracker detects _motion_, but if you are still, it can't detect you.
-- A simple and cheap heuristic is to assume the person is a bit longer there
motionToPresence :: NominalDiffTime -> HASS Motion Presence
motionToPresence :: NominalDiffTime -> HASS (Maybe Motion) Presence
motionToPresence delay = (eventOccupied &&& eventUnoccupied)
>>> arr (uncurry lMerge)
>>> AFRP.hold Unoccupied
where
eventOccupied :: HASS Motion (Event Presence)
eventOccupied = arr (== MotionDetected) >>> edge >>> arr (fmap (const Occupied))
eventUnoccupied :: HASS Motion (Event Presence)
eventUnoccupied = arr (== MotionNotDetected) >>> waitFor delay >>> arr (tag Unoccupied)
eventOccupied :: HASS (Maybe Motion) (Event Presence)
eventOccupied = arr (== Just MotionDetected) >>> edge >>> arr (fmap (const Occupied))
eventUnoccupied :: HASS (Maybe Motion) (Event Presence)
eventUnoccupied = arr (== Just MotionNotDetected) >>> waitFor delay >>> arr (tag Unoccupied)
instance Serialize Motion
-1
View File
@@ -1,4 +1,3 @@
{-# LANGUAGE Arrows #-}
{-# LANGUAGE OverloadedStrings #-}
module HomeAssistant.Controller.Ruuvi
( Ruuvi(..)
+1
View File
@@ -18,4 +18,5 @@ activateSceneWith sceneId d = Service
, serviceName= "turn_on"
, serviceTarget= [EntityId sceneId]
, serviceData = d
, serviceExclusions = []
}
+5 -1
View File
@@ -6,7 +6,10 @@ module HomeAssistant.Controller.Service
import Data.Aeson (Value)
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)
data Service = Service
@@ -14,5 +17,6 @@ data Service = Service
, serviceName :: T.Text
, serviceData :: Maybe Value
, serviceTarget :: [Target]
, serviceExclusions :: [Target]
}
deriving (Show, Eq)
+3 -2
View File
@@ -5,10 +5,11 @@ module HomeAssistant.Controller.Switch (switchService) where
import Data.Bool (bool)
import HomeAssistant.Controller.Service (Service (..), Target)
switchService :: [Target] -> Bool -> Service
switchService targets b = Service
switchService :: [Target] -> [Target] -> Bool -> Service
switchService targets exclusions b = Service
{ serviceDomain="switch"
, serviceName= bool "turn_off" "turn_on" b
, serviceData=Nothing
, serviceTarget=targets
, serviceExclusions=exclusions
}
+8 -4
View File
@@ -28,7 +28,7 @@ import Data.Void (Void)
import GHC.Stack (HasCallStack)
import HomeAssistant.Controller (HASS, HASSEff (..))
import HomeAssistant.Controller.Bedroom (bedroomButtonController, bedroomDrawerController, bedroomPresenceController, humidifierController)
import HomeAssistant.Controller.Children (childrenBedroomButtonController, schoolLightController)
import HomeAssistant.Controller.Children (childrenBedroomButtonController, schoolLightController, childrenAirFilterController)
import HomeAssistant.Controller.Hallway (hallwayLightsController)
import HomeAssistant.Controller.Kitchen (kitchenMotionController)
import HomeAssistant.Controller.Livingroom (livingroomPlantLights, livingroomPresenceController)
@@ -42,12 +42,13 @@ import HttpServer qualified
import Katip (KatipContext, Namespace (Namespace), Severity (..), logF, logLocM, ls, runKatipContextT, runKatipT, sl, katipAddNamespace)
import Network.Socket (withSocketsDo)
import System.Environment (getEnv, lookupEnv)
import System.FilePath ((</>))
import System.FilePath ((</>), (<.>))
import System.Metrics qualified
import Text.Read (readMaybe)
import UnliftIO.Async
import Control.Monad.Catch (MonadCatch)
import Control.Exception.Annotated (checkpoint, Annotation (..))
import AFRP.Diagram (renderF)
step :: (MonadIO m) => FilePath -> T.Text -> UUID -> Auto m a b -> a -> m (b, Auto m a b)
step path name trace st a = do
@@ -69,7 +70,8 @@ controllers =
Controller "livingroom-presence" livingroomPresenceController,
Controller "hallway-motion-controller" hallwayLightsController,
Controller "children-button" childrenBedroomButtonController,
Controller "livingroom-plants" livingroomPlantLights
Controller "livingroom-plants" livingroomPlantLights,
Controller "children-filter" childrenAirFilterController
]
-- | Steps the machine for every inbound message; service calls go to the
@@ -79,7 +81,7 @@ runController :: forall m. (HasCallStack, MonadCatch m, KatipContext m, MonadIO
runController rootDir bus (Controller name machine) = checkpoint (Annotation name) $ katipAddNamespace ns $ do
inbound <- liftIO $ atomically (dupTChan (busInbound bus))
let workerDefinition = runMealy machine (channelHassEval @m bus)
let path = rootDir </> T.unpack name
let path = rootDir </> T.unpack name <.> "dat"
worker <-
load path workerDefinition >>= \case
Decoded a -> pure a
@@ -121,6 +123,8 @@ defaultMain =
rrdtool <- fromMaybe "rrdtool" <$> liftIO (lookupEnv "HA_RRDTOOL")
metricsPort <- lookupPort
writerLimiter <- slidingWindowLimiter rateLimitMetrics 10 20
forM_ controllers $ \(Controller n m) ->
logLocM InfoS $ ls $ n <> ": " <> fromMaybe "" (runDiagramC m renderF)
let ents = foldMap (\(Controller _ m) -> entities m) controllers
workers =
[ ("reader", readerAction host 8123 token ents bus),
+11 -8
View File
@@ -36,10 +36,9 @@ import Data.UUID (toText)
import AFRP (Request(..), Event(..))
import Control.Monad.IO.Class (liftIO, MonadIO)
import HomeAssistant.Runtime.RateLimit (RateLimited, RateLimiter, runRateLimited)
import Control.Monad.Catch (MonadCatch)
import GHC.Stack (HasCallStack)
import UnliftIO (MonadUnliftIO, race, withRunInIO)
import Control.Monad.Catch (onException)
import Control.Monad.Catch (MonadCatch, onException)
-- | Connect, authenticate, subscribe, then receive and broadcast forever.
-- Restarting this action reconnects. All setup sends happen before the
@@ -147,17 +146,21 @@ encodeService callId Service{..} = object $
, "type" .= ("call_service" :: T.Text)
, "domain" .= serviceDomain
, "service" .= serviceName
, "target" .= targetObject serviceTarget
, "target" .= targetObject serviceTarget serviceExclusions
] <> maybe [] (\d -> ["service_data" .= d]) serviceData
-- | A single target encodes as a scalar; multiple encode as a list. Empty
-- lists are omitted so Home Assistant receives only populated keys.
targetObject :: [Target] -> Value
targetObject targets = object $ entityPart <> areaPart
-- lists are omitted so Home Assistant receives only populated keys. Exclusions
-- nest under "exclude".
targetObject :: [Target] -> [Target] -> Value
targetObject targets exclusions = object $
targetKeys targets
<> [ "exclude" .= object (targetKeys exclusions) | not (null exclusions) ]
where
entityPart = emit "entity_id" [e | EntityId e <- targets]
areaPart = emit "area_id" [a | AreaId a <- targets]
targetKeys ts = emit "entity_id" [e | EntityId e <- ts]
<> emit "area_id" [a | AreaId a <- ts]
<> emit "label_id" [l | LabelId l <- ts]
emit _ [] = []
emit k [x] = [k .= x]
emit k many = [k .= many]
+1 -1
View File
@@ -44,7 +44,7 @@ loadFlags rootPath allNames = do
let path = rootPath </> "handlers.json"
fileMap <- readFlagsFile path
let defaults = M.fromList [(n, True) | n <- allNames]
initial = M.unionWith (\fileVal -> const fileVal) fileMap defaults
initial = M.unionWith const fileMap defaults
tv <- liftIO $ newTVarIO initial
lock <- liftIO $ newMVar ()
pure Flags
+4 -3
View File
@@ -13,6 +13,7 @@ module HomeAssistant.Runtime.Graphing
, readProcessBytes
, Graph(..)
, renderGraph
, rangeSuffix
) where
import Control.Exception (evaluate)
@@ -190,10 +191,10 @@ cfName = \case
defArgs :: FilePath -> Series -> [String]
defArgs rrdPath series =
[ "DEF:" ++ rawF ++ "=" ++ rrdPath ++ ":"
( "DEF:" ++ rawF ++ "=" ++ rrdPath ++ ":"
++ srcDs source ++ ":" ++ cfName (srcCF source)
]
++ transformArgs
)
: transformArgs
where
source = serSource series
alias = serAlias series
+173 -18
View File
@@ -7,71 +7,225 @@ import Control.Monad.IO.Class (liftIO, MonadIO)
import qualified Data.ByteString as BS
import Data.Void (Void)
import Network.Wai.Handler.Warp (run)
import Servant.API ((:>), Capture, Get, QueryParam, (:-), MimeRender (..), Accept (..), NamedRoutes, JSON, ReqBody, Put)
import Servant.API ((:>), Capture, Get, QueryParam, (:-), MimeRender (..), Accept (..), NamedRoutes, JSON, ReqBody, Put, Post, FormUrlEncoded, Header)
import Data.ByteString (ByteString)
import GHC.Generics (Generic)
import Servant (Handler, err404)
import Servant (Handler, err404, fieldLink, toUrlPiece)
import Control.Monad.Catch (throwM, catch, MonadCatch, MonadThrow, SomeException)
import Servant.Server (err500, ServerT)
import Data.Maybe (fromMaybe)
import Data.Map.Strict (Map)
import qualified Data.Set as S
import Data.Text (Text)
import HomeAssistant.Runtime.Flags (Flags, allFlags, setEnabled, validNames)
import HomeAssistant.Runtime.Flags (Flags, allFlags, setEnabled, validNames, isEnabled)
import Control.Exception.Annotated (checkpoint, Annotation (Annotation))
import Servant.Server.Generic (genericServeT)
import Network.Wai (Application)
import Network.HTTP.Media ((//))
import HomeAssistant.Runtime.Graphing (Graph, Range (..), lookupGraph, graphs, renderGraph)
import Katip (KatipContextT, Katip, runKatipContextT, LogEnv, KatipContext, ls, Severity (..), logFM)
import HomeAssistant.Runtime.Graphing (Graph (..), Range (..), lookupGraph, graphs, renderGraph, rangeSuffix)
import Katip (KatipContextT, Katip, runKatipContextT, LogEnv, KatipContext, ls, Severity (..), logFM, katipAddContext, sl)
import Data.Aeson (ToJSON (toJSON), FromJSON, object, (.=))
import Lucid (ToHtml, toHtml, renderBS, toHtmlRaw, HtmlT, Attributes)
import qualified Lucid.Html5 as H5
import qualified Data.Map.Strict as M
import Data.Foldable (for_)
import qualified Data.Text as T
import Web.FormUrlEncoded (FromForm, fromForm, parseUnique)
import Lucid.Base (makeAttributes)
import Data.Aeson.Key (fromText)
data ImagePng
instance MimeRender ImagePng ByteString where
mimeRender _ = BS.fromStrict
instance MimeRender ImagePng GraphPng where
mimeRender _ (GraphPng bs) = BS.fromStrict bs
instance Accept ImagePng where
contentType _ = "image" // "png"
-- `servant-lucid` package would provide this and the instance for the original lucid(1) package
-- but we have lucid2
data HTML
instance Accept HTML where
contentType _ = "text" // "html"
instance ToHtml a => MimeRender HTML a where
mimeRender _ = renderBS . toHtml
newtype StatsPage = StatsPage (forall m. Monad m => HtmlT m ())
instance ToHtml StatsPage where
toHtml (StatsPage inner) = inner
toHtmlRaw = toHtml
page_ :: Monad m => HtmlT m () -> HtmlT m ()
page_ inner = H5.doctypehtml_ $ do
H5.head_ $ do
H5.script_
[ H5.src_ "https://cdn.jsdelivr.net/npm/htmx.org@2.0.11/dist/htmx.min.js"
, H5.integrity_ "sha384-2OatzQy1H+Zd/IIrjr1TcuDGqLXeHhbooAyJY1KdQMKnr4LZ22k31GBLdYKHmVjg"
, H5.crossorigin_ "anonymous"
]
("" :: Text)
H5.style_ css
H5.body_ inner
css :: Text
css = T.unlines
[ "body { font-family: system-ui, sans-serif; margin: 1rem auto; max-width: 40rem; padding: 0 1rem; }"
, "table { border-collapse: collapse; }"
, "th, td { padding: 0.4rem 0.75rem; border-bottom: 1px solid #ddd; text-align: left; }"
, "input[type=submit] { padding: 0.25rem 0.75rem; cursor: pointer; }"
, "img { max-width: 100%; }"
]
type HxRequest = Header "HX-Request" Bool
data API mode = API
{ getMetrics :: mode :- "metrics" :> Capture "graph" Graph :> QueryParam "range" Range :> Get '[ImagePng] ByteString
, getFlags :: mode :- "flags" :> Get '[JSON] (Map Text Bool)
, putFlag :: mode :- "flags" :> Capture "name" Text :> ReqBody '[JSON] Bool :> Put '[JSON] (Map Text Bool)
{ getMetrics :: mode :- "metrics" :> Capture "graph" Graph :> QueryParam "range" Range :> Get '[ImagePng] GraphPng
, getStats :: mode :- "stats" :> HxRequest :> QueryParam "range" Range :> Get '[HTML] StatsPage
, getFlags :: mode :- "flags" :> Get '[JSON, HTML] FlagsResponse
, putFlag :: mode :- "flags" :> Capture "name" Text :> ReqBody '[JSON, FormUrlEncoded] FlagValue :> Put '[HTML, JSON] FlagResponse
, postFlag :: mode :- "flags" :> Capture "name" Text :> ReqBody '[JSON, FormUrlEncoded] FlagValue :> Post '[JSON, HTML] FlagResponse
}
deriving Generic
newtype GraphPng = GraphPng ByteString
getFlagsHandler :: Flags -> LoggingHandler (Map Text Bool)
getFlagsHandler flags = allFlags flags
newtype FlagValue = FlagValue Bool
deriving FromJSON via Bool
putFlagHandler :: Flags -> Text -> Bool -> LoggingHandler (Map Text Bool)
putFlagHandler flags name val
instance FromForm FlagValue where
fromForm f = FlagValue <$> parseUnique "flag-value" f
newtype FlagsResponse = FlagsResponse (Map Text Bool)
deriving (ToJSON) via (Map Text Bool)
data FlagResponse = FlagResponse Text Bool
instance ToHtml FlagResponse where
toHtml (FlagResponse name value) = flagRow name value
toHtmlRaw = toHtml
instance ToJSON FlagResponse where
toJSON (FlagResponse k v) = object [fromText k .= v]
flagsPage :: Monad m => FlagsResponse -> HtmlT m ()
flagsPage (FlagsResponse f) = page_ $
H5.table_ $ do
H5.tr_ $ do
H5.th_ "Name"
H5.th_ "Value"
H5.th_ ""
for_ (M.toList f) $ uncurry flagRow
flagRow :: Monad m => Text -> Bool -> HtmlT m ()
flagRow name value = H5.tr_ [H5.id_ (rowId name)] $ do
H5.td_ (toHtml name)
H5.td_ (toHtml (if value then "on" else "off" :: Text))
H5.td_ (toggle name value)
where
toggle :: Monad m => Text -> Bool -> HtmlT m ()
toggle key current = H5.form_ [H5.method_ "post", H5.action_ (postFlagsLink key)] $ do
H5.input_ [H5.name_ "flag-value", H5.type_ "hidden", H5.value_ (T.pack (show (not current)))]
H5.input_
[ H5.type_ "submit"
, H5.value_ (if current then "Disable" else "Enable")
, hxTrigger "click"
, hxTarget ("#" <> rowId key)
, hxPut (postFlagsLink key)
, hxSwap "outerHTML"
]
postFlagsLink k = "/" <> toUrlPiece (fieldLink putFlag k)
rowId :: Text -> Text
rowId = ("status-" <>)
hxTrigger :: Text -> Attributes
hxTrigger = makeAttributes "hx-trigger"
hxTarget :: Text -> Attributes
hxTarget = makeAttributes "hx-target"
hxPut :: Text -> Attributes
hxPut = makeAttributes "hx-put"
hxGet :: Text -> Attributes
hxGet = makeAttributes "hx-get"
hxPushUrl :: Text -> Attributes
hxPushUrl = makeAttributes "hx-push-url"
hxSwap :: Text -> Attributes
hxSwap = makeAttributes "hx-swap"
instance ToHtml FlagsResponse where
toHtml = flagsPage
toHtmlRaw = toHtml
getFlagsHandler :: Flags -> LoggingHandler FlagsResponse
getFlagsHandler = fmap FlagsResponse . allFlags
putFlagHandler :: Flags -> Text -> FlagValue -> LoggingHandler FlagResponse
putFlagHandler flags name (FlagValue val)
| name `S.notMember` validNames flags = throwM err404
| otherwise = do
| otherwise = checkpoint (Annotation (name, val)) $ katipAddContext (sl "flag" (name, val)) $ do
setEnabled flags name val `catch` \e -> do
logFM ErrorS (ls ("failed to persist handler flag: " <> show (e :: SomeException)))
throwM err500
allFlags flags
FlagResponse name <$> isEnabled flags name
getMetricsHandler :: FilePath -> FilePath -> Graph -> Maybe Range -> LoggingHandler ByteString
getMetricsHandler :: FilePath -> FilePath -> Graph -> Maybe Range -> LoggingHandler GraphPng
getMetricsHandler rrdPath rrdtool graphMode mRange = checkpoint (Annotation (graphMode, mRange)) $ do
case lookupGraph graphs graphMode of
Nothing -> throwM err404
Just spec -> do
let range = fromMaybe OneDay mRange
g <- renderGraph rrdPath rrdtool spec range
either (\e -> logFM ErrorS (ls e) >> throwM err500) pure g
either (\e -> logFM ErrorS (ls e) >> throwM err500) (pure . GraphPng) g
-- server :: FilePath -> FilePath -> API AsServer
server :: FilePath -> FilePath -> Flags -> ServerT (NamedRoutes API) LoggingHandler
server rrdPath rrdtool flags = API
{ getMetrics = getMetricsHandler rrdPath rrdtool
, getStats = getStatsHandler
, getFlags = getFlagsHandler flags
, putFlag = putFlagHandler flags
, postFlag = putFlagHandler flags -- This exists only for html forms
}
statsPage :: Maybe Bool -> Maybe Range -> StatsPage
statsPage hx r = StatsPage $
if hx == Just True
then statsContent r
else page_ (statsContent r)
statsContent :: Monad m => Maybe Range -> HtmlT m ()
statsContent r = H5.div_ [H5.id_ "stats"] $ do
H5.ul_ $ for_ [minBound..maxBound] $ \range ->
H5.li_ $ H5.a_ (link range) $ toHtml $ rangeSuffix range
H5.h2_ "Traffic"
H5.img_ [H5.src_ (src Traffic)]
H5.h2_ "Memory"
H5.img_ [H5.src_ (src Memory)]
H5.h2_ "Ratelimit"
H5.img_ [H5.src_ (src RateLimit)]
where
src m = "/" <> toUrlPiece (fieldLink getMetrics m r)
link range =
let url = "/" <> toUrlPiece (fieldLink getStats (Just range))
in [ H5.href_ url
, hxGet url
, hxTarget "#stats"
, hxSwap "outerHTML"
, hxPushUrl "true"
]
getStatsHandler :: Maybe Bool -> Maybe Range -> LoggingHandler StatsPage
getStatsHandler hx r = pure (statsPage hx r)
servantApp :: LogEnv -> FilePath -> FilePath -> Flags -> Application
servantApp le rrdPath rrdtool flags = genericServeT (toHandler le) (server rrdPath rrdtool flags)
@@ -85,3 +239,4 @@ toHandler :: LogEnv -> (forall a. LoggingHandler a -> Handler a)
toHandler le (LoggingHandler k) = runKatipContextT le () "http" k
+4
View File
@@ -12,6 +12,10 @@ import Support (fakeRequest)
import Test.Hspec (Spec, describe, it)
import Test.Hspec.Hedgehog (forAll, forAllWith, hedgehog, (===))
-- We are testing laws -> hlint warns about not using laws
{-# ANN module "Hlint: ignore" #-}
-- | Law tests for the Mealy instances. Two machines count as equal when
-- they emit equal outputs on every input sequence, so each law runs both
-- sides on generated inputs.
+6 -4
View File
@@ -19,6 +19,8 @@ import qualified Hedgehog.Gen as Gen
import qualified Hedgehog.Range as Range
import Test.Hspec
import Test.Hspec.Hedgehog
import Data.Maybe (listToMaybe)
import AFRP.Diagram (emptyDiagram)
fakeRequest :: Request
fakeRequest = Request (sec 0) utc nil "test"
@@ -52,7 +54,7 @@ instance Functor St where
fmap f (St g) = St $ \s -> let (a, s') = g s in (f a, s')
instance Applicative St where
pure a = St (\s -> (a, s))
pure a = St (a,)
St f <*> St x = St $ \s -> let (f', s') = f s; (a, s'') = x s' in (f' a, s'')
instance Monad St where
@@ -165,7 +167,7 @@ lMergeSpec = describe "lMerge" $ do
changesSpec :: Spec
changesSpec = describe "changes" $ do
it "first output is always Tick" $
runPure changes "hello" !! 0 `shouldBe` Tick
listToMaybe (runPure changes "hello") `shouldBe` Just Tick
it "outputs Event only on value change" $
runPure changes "aaaabbbcca"
@@ -535,11 +537,11 @@ sampleSpec = describe "sample" $ do
-- | A stateless arrow carrying a fixed entity set, for testing propagation.
subscribed :: S.Set T.Text -> Mealy Identity Int Int
subscribed ents = Mealy ents $ \_ -> Fun $ \_ a -> a
subscribed ents = Mealy ents emptyDiagram $ \_ -> Fun $ \_ a -> a
-- | Same as 'subscribed' but yields a function, for testing '<*>'.
subscribedF :: S.Set T.Text -> Mealy Identity Int (Int -> Int)
subscribedF ents = Mealy ents $ \_ -> Fun $ \_ a -> (a +)
subscribedF ents = Mealy ents emptyDiagram $ \_ -> Fun $ \_ a -> (a +)
entitiesSpec :: Spec
entitiesSpec = describe "entities" $ do
+110 -8
View File
@@ -5,7 +5,10 @@ module BedroomSpec (spec) where
import AFRP (Event (..), entities)
import qualified Data.Set as S
import qualified Data.Text as T
import Data.Aeson (Value)
import Data.Aeson (Value, object, (.=))
import qualified Data.Aeson.Key as Key
import Data.Default (def)
import Data.Time (getCurrentTime, addUTCTime)
import HomeAssistant.Controller
import HomeAssistant.Controller.Bedroom
import Support
@@ -20,11 +23,31 @@ enishenButton = Event . buttonEvent "event.bedroom_quick_jemina_action"
drawerState :: T.Text -> Event Value
drawerState = Event . stateEvent "binary_sensor.bedroom_nightstand_drawer_sensor_masse_contact"
presenceSensor :: T.Text -> Event Value
presenceSensor = Event . stateEvent "binary_sensor.presence_sensor_bedroom_occupancy"
-- Light state event with observed attributes
masseLight :: T.Text -> [(T.Text, Int)] -> Event Value
masseLight state attrs = Event $ object
[ "event" .= object
[ "variables" .= object
[ "trigger" .= object
[ "entity_id" .= ("light.bedroom_masse" :: T.Text)
, "to_state" .= object
[ "state" .= state
, "attributes" .= object [ Key.fromString (T.unpack k) .= v | (k, v) <- attrs ]
]
]
]
]
]
spec :: Spec
spec = describe "Bedroom" $ do
entitySpec
drawerSpec
buttonSpec
presenceSpec
entitySpec :: Spec
entitySpec = describe "entities" $ do
@@ -62,18 +85,18 @@ drawerSpec = describe "bedroomDrawerController" $ do
it "turns the drawer light on when the drawer opens" $
services (runHASS bedroomDrawerController [drawerState "on"])
`shouldBe` [[switchService [entity] True]]
`shouldBe` [[switchService [entity] [] True]]
it "turns the drawer light off when the drawer closes" $
services (runHASS bedroomDrawerController [drawerState "off"])
`shouldBe` [[switchService [entity] False]]
`shouldBe` [[switchService [entity] [] False]]
it "toggles the light as the drawer opens and closes" $
services (runHASS bedroomDrawerController
[ drawerState "on", drawerState "off", drawerState "on" ])
`shouldBe` [ [switchService [entity] True]
, [switchService [entity] False]
, [switchService [entity] True]
`shouldBe` [ [switchService [entity] [] True]
, [switchService [entity] [] False]
, [switchService [entity] [] True]
]
it "ignores state events for other entities" $
@@ -85,6 +108,73 @@ drawerSpec = describe "bedroomDrawerController" $ do
services (runHASS bedroomDrawerController [Tick])
`shouldBe` [[]]
presenceSpec :: Spec
presenceSpec = describe "bedroomPresenceController" $ do
let sleepScene = activateScene "scene.makuuhuone_lepotila"
it "subscribes to presence, light level and the bedroom lights" $
entities bedroomPresenceController
`shouldBe` S.fromList
[ "binary_sensor.presence_sensor_bedroom_occupancy"
, "sensor.presence_sensor_bedroom_light_level"
, "light.bedroom_ceiling"
, "light.bedroom_jemina"
, "light.bedroom_led_switch"
, "light.bedroom_masse"
]
it "does nothing on Tick" $
services (runHASS bedroomPresenceController [Tick])
`shouldBe` [[]]
it "does nothing when entering for the first time (no snapshot yet)" $
services (runHASS bedroomPresenceController [presenceSensor "on"])
`shouldBe` [[]]
it "activates the sleep scene when leaving with the lights on" $
services (runHASS bedroomPresenceController
[ presenceSensor "on", masseLight "on" [], presenceSensor "off" ])
`shouldBe` [ [], [], [sleepScene] ]
it "does not activate the sleep scene when the lights are off" $
services (runHASS bedroomPresenceController
[ presenceSensor "on", masseLight "on" [], masseLight "off" [], presenceSensor "off" ])
`shouldBe` [ [], [], [], [] ]
it "turns the lights off 300s after leaving" $ do
now <- getCurrentTime
let later = 305 `addUTCTime` now
services (runHASSTimed bedroomPresenceController
[ (now, presenceSensor "on"), (now, presenceSensor "off"), (later, Tick) ])
`shouldBe` [ [], [], [light bedroomLightTargets [] Off] ]
it "restores the last snapshot when re-entering after sleep" $ do
now <- getCurrentTime
let later = 350 `addUTCTime` now
let masseRestored = light [EntityId "light.bedroom_masse"] [] (On def
{ lightBrightness = Just (BrightnessAbsolute 140)
, lightColorTemperature = Just 2700
})
services (runHASSTimed bedroomPresenceController
[ (now, presenceSensor "on")
, (now, masseLight "on" [("brightness", 255), ("color_temp_kelvin", 2700)])
, (now, presenceSensor "off")
, (now, Tick)
, (later, presenceSensor "on")
, (later, Tick)
])
`shouldBe` [ []
, []
, [sleepScene]
, []
, [ light [EntityId "light.bedroom_ceiling"] [] Off
, light [EntityId "light.bedroom_jemina"] [] Off
, light [EntityId "light.bedroom_led_switch"] [] Off
, masseRestored
]
, []
]
buttonSpec :: Spec
buttonSpec = describe "bedroomButtonController" $ do
let area = AreaId "makuuhuone"
@@ -103,7 +193,15 @@ buttonSpec = describe "bedroomButtonController" $ do
it "Masse off click turns the bedroom lights off" $
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)" $
concat (services (runHASS bedroomButtonController [enishenButton "1_short_release"]))
@@ -119,7 +217,11 @@ buttonSpec = describe "bedroomButtonController" $ do
it "Enishen off click turns the bedroom lights off" $
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)" $
services (runHASS bedroomButtonController [masseButton "1_initial_press"])
+3 -4
View File
@@ -6,7 +6,7 @@ import AFRP (Request (..), Event (..))
import Control.Concurrent.STM
( atomically
, dupTChan
, isEmptyTChan
, readTChan
, writeTChan
)
@@ -18,7 +18,6 @@ import HomeAssistant.Controller (HASSEff (..), Service (..), Target(..))
import HomeAssistant.Runtime.Bus
import HomeAssistant.Runtime.Flags (loadFlags, setEnabled)
import HomeAssistant.Runtime.Metrics (registerAppMetrics)
import Control.Monad.IO.Class (liftIO)
import Katip (Namespace (Namespace), runKatipContextT)
import Katip.Monadic (runNoLoggingT)
import Support (withTestLogEnv)
@@ -41,7 +40,7 @@ spec = describe "Bus" $ do
it "channelHassEval writes CallService to the outbound channel" $ withTestBus $ \bus -> do
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"]) $
channelHassEval bus (CallService req svc)
(_, svc') <- atomically $ readTChan (busOutbound bus)
@@ -51,7 +50,7 @@ spec = describe "Bus" $ do
withTestFlagsBus $ \bus -> do
setEnabled (busFlags bus) "test-handler" False
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"]) $
channelHassEval bus (CallService req svc)
result <- timeout 1000000 $ atomically $ readTChan (busOutbound bus)
+16 -5
View File
@@ -27,7 +27,7 @@ spec :: Spec
spec = do
describe "encodeService" $ do
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
[ "id" .= (7 :: Int)
, "type" .= ("call_service" :: Text)
@@ -37,7 +37,7 @@ spec = do
]
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
[ "id" .= (8 :: Int)
, "type" .= ("call_service" :: Text)
@@ -47,6 +47,19 @@ spec = do
, "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
it "is true for event frames" $
isTriggerEvent (object ["type" .= ("event" :: Text)]) `shouldBe` True
@@ -80,7 +93,5 @@ req n = Request (UTCTime (toEnum 0) (fromIntegral (0 :: Int))) utc
uuid = "00000000-0000-0000-0000-" <> pad n
lightOn :: [Target] -> Service
lightOn targets = Service "light" "turn_on" Nothing targets
lightOn targets = Service "light" "turn_on" Nothing targets []
lightOff :: [Target] -> Service
lightOff targets = Service "light" "turn_off" Nothing targets
-1
View File
@@ -4,7 +4,6 @@ import Test.Hspec
import Data.Default (def)
import HomeAssistant.Controller (Brightness(..), formatLightAttributes, LightAttributes(..))
import Data.Aeson (object, (.=))
import HomeAssistant.Controller ()
spec :: Spec
+1 -1
View File
@@ -70,7 +70,7 @@ spec = describe "Flags" $ do
n <- forAll $ Gen.int (Range.linear 1 50)
liftIO $ withTempDirectory "/tmp" "flags-spec" $ \dir -> do
flags <- runNoLoggingT (loadFlags dir ["x"])
mapConcurrently_ (\i -> setEnabled flags "x" (even i)) [1 .. n]
mapConcurrently_ (setEnabled flags "x" . even) [1 .. n]
m <- allFlags flags
decoded <- decodeFileStrict (dir <> "/handlers.json")
(decoded :: Maybe (Map Text Bool)) `shouldBe` Just m
+1 -1
View File
@@ -7,6 +7,7 @@ import qualified Data.ByteString as BS
import HomeAssistant.Runtime.Graphing
( GraphSpec (..)
, Range (..)
, Graph(..)
, buildGraphArgs
, graphs
, lookupGraph
@@ -21,7 +22,6 @@ import System.Exit (ExitCode (..))
import System.Process (readProcessWithExitCode)
import Test.Hspec
import Servant.API (FromHttpApiData(..), ToHttpApiData (..))
import HomeAssistant.Runtime.Graphing (Graph(..))
traffic :: GraphSpec
traffic = case lookupGraph graphs Traffic of
+291
View File
@@ -0,0 +1,291 @@
{-# LANGUAGE OverloadedStrings #-}
module HallwaySpec (spec) where
import AFRP (Event (..))
import qualified Data.Text as T
import Data.Aeson (Value, object, (.=))
import Data.Bool (bool)
import Data.Default (def)
import Data.List (scanl')
import Data.Time (UTCTime, addUTCTime)
import HomeAssistant.Controller
import HomeAssistant.Controller.Hallway
import Support
import Test.Hspec
import Test.Hspec.Hedgehog
import qualified Hedgehog.Gen as Gen
import qualified Hedgehog.Range as Range
day, night :: UTCTime
day = clock 10 0 -- 10:00, outside sleep hours
night = clock 21 0 -- 21:00, inside sleep hours (20:30 - 07:30)
motionSensor :: T.Text -> Event Value
motionSensor = Event . stateEvent "binary_sensor.hallway_movement_occupancy"
masterDoor :: T.Text -> Event Value
masterDoor = Event . stateEvent "binary_sensor.makuuhuone_ovi_contact"
childrenDoor :: T.Text -> Event Value
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
-- timeout), occasionally a 600s gap so presence can expire and the room can
-- become unoccupied again.
data TestEvent = TestEvent Int (Event Bool)
deriving Show
genTestEvent :: Gen TestEvent
genTestEvent = TestEvent
<$> Gen.frequency [(8, Gen.integral (Range.linear 0 20)), (2, pure 600)]
<*> Gen.frequency [(3, pure Tick), (1, Event <$> Gen.bool)]
-- | Presence and both of its presence-derived triggers, observed in lock-step
-- over the same motion stream, so the triggers can be judged against the
-- intermediate presence value at each step.
presenceProbe :: HASS (Event Value) (Presence, Event (), Event ())
presenceProbe = (,,) <$> hallwayPresence <*> lightsOnTrigger <*> lightsOffTrigger
-- | Expected firing steps: every step that *enters* `target`. The implicit
-- state before the first step is Unoccupied — the room starts unoccupied —
-- so an Unoccupied-trigger never fires at the first step.
edgeSteps :: Presence -> [Presence] -> [Int]
edgeSteps target ps =
[ i
| (i, (prev, p)) <- zip [0 ..] (zip (Unoccupied : ps) ps)
, prev /= target
, p == target
]
spec :: Spec
spec = describe "Hallway" $ do
lightsSpec
presenceTransitionSpec
modeTriggerSpec
presenceTransitionSpec :: Spec
presenceTransitionSpec = describe "presenceTriggers" $
it "fires exactly on the corresponding presence transitions" $ hedgehog $ do
events <- forAll $ Gen.list (Range.linear 0 100) genTestEvent
let steps = drop 1 $ scanl' (flip addUTCTime) day [fromIntegral t | TestEvent t _ <- events]
timed = values (runHASSTimed presenceProbe
(zipWith (\t (TestEvent _ e) ->
(t, stateEvent "binary_sensor.hallway_movement_occupancy" . bool "off" "on" <$> e))
steps events))
presences = [p | (p, _, _) <- timed]
onSteps = [i | (i, (_, Event (), _)) <- zip [0 ..] timed]
offSteps = [i | (i, (_, _, Event ())) <- zip [0 ..] timed]
onSteps === edgeSteps Occupied presences
offSteps === edgeSteps Unoccupied presences
cover 30 "at least one unoccupied -> occupied transition" (not (null onSteps))
cover 30 "at least one occupied -> unoccupied transition" (not (null offSteps))
-- | Presence, the chosen mode and the mode-adjustment trigger observed in
-- lock-step over the same event stream.
modeProbe :: HASS (Event Value) (Presence, Mode, Event Mode)
modeProbe = (,,) <$> hallwayPresence <*> mode <*> modeTrigger
data ModeAction
= Motion Bool -- ^ @True@ is motion detected
| MasterDoor 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
deriving Show
data ModeEvent = ModeEvent Int ModeAction
deriving Show
genModeEvent :: Gen ModeEvent
genModeEvent = ModeEvent
<$> Gen.frequency [(6, Gen.integral (Range.linear 0 15)), (1, pure 900)]
<*> Gen.frequency [(4, Motion <$> Gen.bool)
,(2, MasterDoor <$> 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)
]
modeEventValue :: ModeAction -> Event Value
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 (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
-- | The mode-adjustment trigger: the presence-based lights are already on
-- (room occupied), the world changed which lights should be on, so adjust.
-- The first observed mode is the baseline the lights-on trigger already
-- acted on, so it is not an adjustment.
modeTriggerSpec :: Spec
modeTriggerSpec = describe "modeTrigger" $
it "fires exactly on occupied steps that change the mode, tagged with the new mode" $ hedgehog $ do
events <- forAll $ Gen.list (Range.linear 0 100) genModeEvent
let steps = drop 1 $ scanl' (flip addUTCTime) (clock 20 0) [fromIntegral t | ModeEvent t _ <- events]
timed = values (runHASSTimed modeProbe
(zipWith (\t (ModeEvent _ a) -> (t, modeEventValue a)) steps events))
modes = [m | (_, m, _) <- timed]
-- The previous mode; at the first step it is the mode itself, since
-- the first observed mode is the baseline the lights-on trigger
-- already acted on, not an adjustment.
prior = case modes of [] -> []; m0 : _ -> m0 : init modes
expected =
[ i
| (i, (prevM, (p, m, _))) <- zip [0 ..] (zip prior timed)
, prevM /= m
, p == Occupied
]
suppressed =
[ () | (prevM, (p, m, _)) <- zip prior timed
, p == Unoccupied
, prevM /= m
]
fired = [i | (i, (_, _, Event _)) <- zip [0 ..] timed]
tags = [(i, tag) | (i, (_, _, Event tag)) <- zip [0 ..] timed]
fired === expected
tags === [(i, m) | i <- expected, let m = modes !! i]
cover 25 "fires at least once" (not (null fired))
cover 25 "suppressed a mode change while unoccupied" (not (null suppressed))
cover 25 "reaches quiet mode" (Quiet `elem` modes)
lightsSpec :: Spec
lightsSpec = do
describe "hallwayLightsController" $ do
it "turns the full lights on when someone enters during daytime" $
services (runHASSTimed hallwayLightsController [(day, motionSensor "on")])
`shouldBe` [[light [EntityId "light.hallway_lights"] [] (On def)]]
it "turns the full lights on when someone enters during daytime preceding tick" $
services (runHASSTimed hallwayLightsController [(day, Tick), (day, motionSensor "on")])
`shouldBe` [[], [light [EntityId "light.hallway_lights"] [] (On def)]]
it "turns the lights off when everyone leaves, without sleep mode" $
let later = 505 `addUTCTime` day
in services (runHASSTimed hallwayLightsController
[ (day, Tick)
, (day, motionSensor "on")
, (day, motionSensor "off")
, (later, Tick)
])
`shouldBe` [ []
, [light [EntityId "light.hallway_lights"] [] (On def)]
, []
, [light [EntityId "light.hallway_lights"] [] Off]
]
it "turns on only the ceiling light when entering during sleep hours with a door open" $
services (runHASSTimed hallwayLightsController
[ (night, Tick)
, (night, masterDoor "on")
, (night, motionSensor "on")
])
`shouldBe` [ []
, []
, [light [EntityId "light.hallway_ceiling_2"] [] (On def)]
]
it "leaves the lights unchanged when an empty bedroom door opens during sleep hours" $
services (runHASSTimed hallwayLightsController
[ (night, masterDoor "off") -- closed
, (night, childrenDoor "off") -- closed
, (night, motionSensor "on")
, (night, masterDoor "on") -- opens, but nobody is ready to sleep there
])
`shouldBe` [ []
, []
, [light [EntityId "light.hallway_lights"] [] (On def)]
, []
]
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" $
services (runHASSTimed hallwayLightsController
[ (night, masterDoor "on")
, (night, motionSensor "on")
, (night, masterDoor "off")
, (night, childrenDoor "off")
])
`shouldBe` [ []
, [light [EntityId "light.hallway_ceiling_2"] [] (On def)]
, []
, [light [EntityId "light.hallway_ceiling"] [] (On def)]
]
+64
View File
@@ -0,0 +1,64 @@
{-# LANGUAGE OverloadedStrings #-}
module HttpServerSpec (spec) where
import qualified Data.Map.Strict as M
import Data.Text (Text)
import qualified Data.Text as T
import Data.Text.Lazy.Encoding (decodeUtf8)
import qualified Data.Text.Lazy as TL
import Lucid (Html, renderBS, toHtml)
import Test.Hspec
import HomeAssistant.Runtime.Graphing (Range (..))
import HttpServer
render :: Html () -> String
render = TL.unpack . decodeUtf8 . renderBS
spec :: Spec
spec = describe "HttpServer" $ do
describe "flagRow" $ do
it "renders the whole row so htmx can outerHTML-swap it" $
render (flagRow "tea" True) `shouldContain` "<tr id=\"status-tea\">"
it "requests an outerHTML swap (htmx casing)" $
render (flagRow "tea" True) `shouldContain` "hx-swap=\"outerHTML\""
it "displays on with a Disable button when enabled" $ do
let html = render (flagRow "tea" True)
html `shouldContain` "<td>on</td>"
html `shouldContain` "value=\"Disable\""
it "displays off with an Enable button when disabled" $ do
let html = render (flagRow "tea" False)
html `shouldContain` "<td>off</td>"
html `shouldContain` "value=\"Enable\""
describe "flagsPage" $ do
let page = flagsPage (FlagsResponse (M.fromList [("tea" :: Text, True)]))
it "uses the shared page shell with a style block" $
render page `shouldContain` "<style"
it "has a header row" $ do
let html = render page
html `shouldContain` "<th>Name</th>"
html `shouldContain` "<th>Value</th>"
it "carries each row id exactly once" $
T.count "id=\"status-tea\"" (T.pack (render page)) `shouldBe` 1
describe "statsPage" $ do
it "uses the shared page shell with a style block (full page)" $
render (toHtml (statsPage Nothing Nothing)) `shouldContain` "<style"
it "serves a bare fragment for htmx requests" $ do
let html = render (toHtml (statsPage (Just True) (Just OneDay)))
html `shouldNotContain` "DOCTYPE"
html `shouldContain` "<div id=\"stats\">"
it "range links swap the stats fragment in place" $ do
let html = render (toHtml (statsPage Nothing (Just OneDay)))
html `shouldContain` "hx-get=\"/stats?range=24h\""
html `shouldContain` "hx-target=\"#stats\""
html `shouldContain` "hx-push-url=\"true\""
+12 -5
View File
@@ -11,6 +11,7 @@ import HomeAssistant.Controller.Kitchen
import Support
import Test.Hspec
import Data.Default (def)
import Data.Time (getCurrentTime, addUTCTime)
-- Helper functions for creating test events
testDinnerLightLevel :: Int -> Event Value
@@ -35,12 +36,18 @@ dinnerTableSpec = describe "dinnerTableController" $ do
it "turns lights on when presence is occupied and light level is low" $ do
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 off when presence is unoccupied" $ do
services (runHASS dinnerTableController [testDinnerLightLevel 10, testDinnerPresence "off"])
`shouldBe` [[switchService [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] True], []]
it "turns lights to sleep when presence is unoccupied" $ do
now <- getCurrentTime
services (runHASSTimed dinnerTableController [(now, testDinnerLightLevel 10), (now, testDinnerPresence "off")])
`shouldBe` [[switchService [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] [] True], []]
it "turns lights off when no presence for 300 seconds" $ do
now <- getCurrentTime
let later = 305 `addUTCTime` now
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]]
it "does nothing on Tick" $ do
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]]
+6
View File
@@ -8,11 +8,14 @@ import qualified BusSpec
import qualified ConnectionSpec
import qualified FlagsSpec
import qualified GraphingSpec
import qualified HallwaySpec
import qualified HttpServerSpec
import qualified KitchenSpec
import qualified LivingroomSpec
import qualified MetricsSpec
import qualified RuntimeSpec
import qualified ControllerSpec
import qualified PresenceSpec
main :: IO ()
main = hspec $ do
@@ -23,8 +26,11 @@ main = hspec $ do
ConnectionSpec.spec
FlagsSpec.spec
GraphingSpec.spec
HallwaySpec.spec
HttpServerSpec.spec
KitchenSpec.spec
LivingroomSpec.spec
MetricsSpec.spec
RuntimeSpec.spec
ControllerSpec.spec
PresenceSpec.spec
+1 -1
View File
@@ -147,7 +147,7 @@ spec = do
parseInfoDs "step = 10\nrra[0].cf = \"AVERAGE\"\n" `shouldBe` []
describe "schemaMatches" $ do
let ds name ty = DsSpec (T.pack name) name ty
let ds name = DsSpec (T.pack name) name
it "is true for identical schemas regardless of order" $
schemaMatches [ds "b" Gauge, ds "a" Derive] [("a", Derive), ("b", Gauge)]
`shouldBe` True
+53
View File
@@ -0,0 +1,53 @@
{-# LANGUAGE OverloadedStrings #-}
module PresenceSpec where
import Test.Hspec (Spec, describe, shouldBe, it)
import HomeAssistant.Controller (motion, motionToPresence, HASS, Presence(..))
import Control.Arrow ((>>>))
import Data.Aeson (Value)
import Support
import Data.Time (UTCTime)
import AFRP (Event(..))
import qualified Data.Text as T
import Test.Hspec.Hedgehog
import qualified Hedgehog.Gen as Gen
import qualified Hedgehog.Range as Range
import Data.Time.Clock (addUTCTime, diffUTCTime)
import Data.List (scanl')
import Data.Bool (bool)
motionSensor :: T.Text -> Event Value
motionSensor = Event . stateEvent "sensor.foo"
day :: UTCTime
day = clock 10 0 -- 10:00, outside sleep hours
sut :: HASS (Event Value) Presence
sut = motion "sensor.foo" >>> motionToPresence 500
data TestEvent = TestEvent Int (Event Bool)
deriving Show
genTestEvent :: Gen TestEvent
genTestEvent = TestEvent
<$> Gen.frequency [(8, Gen.integral (Range.linear 0 20)), (2, pure 600)]
<*> Gen.frequency [(3, pure Tick), (1, Event <$> Gen.bool)]
spec :: Spec
spec = describe "Presence" $ do
it "Starts as unoccupied" $
values (runHASSTimed sut [(day, Tick)]) `shouldBe` [Unoccupied]
it "Detection motion means presence" $ do
values (runHASSTimed sut [(day, motionSensor "on")]) `shouldBe` [Occupied]
values (runHASSTimed sut [(day, Tick), (day, motionSensor "on")]) `shouldBe` [Unoccupied, Occupied]
it "Leaving doesn't mean immediately unoccupied room" $ do
values (runHASSTimed sut [(day, motionSensor "on"), (day, motionSensor "off")]) `shouldBe` [Occupied, Occupied]
it "re-detects occupancy only after the timeout since the previous detection" $ hedgehog $ do
events <- forAll $ Gen.list (Range.linear 0 100) genTestEvent
let steps = drop 1 $ scanl' (flip addUTCTime) day [fromIntegral t | TestEvent t _ <- events]
length steps === length events
let timed = zip steps (values (runHASSTimed sut (zipWith (\t (TestEvent _ e) -> (t, stateEvent "sensor.foo" . bool "off" "on" <$> e)) steps events)))
let transitions = [() | ((_, Occupied), (_, Unoccupied)) <- zip timed (drop 1 timed)]
cover 20 "occupied -> unoccupied transition" (not (null transitions))
let starts = [t | (Unoccupied, (t, Occupied)) <- zip (Unoccupied : map snd timed) timed]
let deltas = zipWith (\a b -> b `diffUTCTime` a) starts (drop 1 starts)
(null deltas || minimum deltas > 500) === True
+17 -1
View File
@@ -6,11 +6,13 @@ module Support
, runHASS
, runHASSTimed
, services
, values
, fakeRequest
, sec
, stateEvent
, buttonEvent
, withTestLogEnv
, clock
) where
import Control.Exception (bracket)
@@ -36,7 +38,7 @@ instance Functor Acc where
fmap f (Acc g) = Acc $ \s -> let (a, s') = g s in (f a, s')
instance Applicative Acc where
pure a = Acc (\s -> (a, s))
pure a = Acc (a,)
Acc f <*> Acc x = Acc $ \s -> let (f', s') = f s; (a, s'') = x s' in (f' a, s'')
instance Monad Acc where
@@ -52,6 +54,7 @@ withTestLogEnv = bracket (initLogEnv "test" "test") closeScribes
-- | Interpret `HASSEff` in `Acc`: record `CallService`, drop tracing/debug.
interp :: HASSEff a -> Acc a
interp (CallService _ svc) = Acc $ \s -> ((), s ++ [svc])
interp (CallServices _ svc) = Acc $ \s -> ((), s ++ svc)
interp (Debug _) = pure ()
interp (Trace _ _) = pure ()
@@ -74,9 +77,14 @@ runHASSTimed m = go (runMealy m interp)
case runAcc (stepAuto w (Request t utc nil "test") a) [] of
((b, w'), svcs) -> (b, svcs) : go w' as
-- To observe external effects
services :: [(b, [Service])] -> [[Service]]
services = map snd
-- To observe intermediary steps
values :: [(b, [Service])] -> [b]
values = map fst
-- | Build a state-trigger payload matching `entityChangeEvent'` / `entityBool'`
-- lenses. The subscribe_trigger websocket event wraps the trigger datum under
-- `event.variables.trigger`, with `entity_id` and `to_state.state` fields.
@@ -105,3 +113,11 @@ buttonEvent entityId eventType = object
]
]
]
-- runHASSTimed builds its request with the UTC zone, so a UTCTime given as
-- seconds-of-day reads back as exactly that local time of day
clock :: Int -> Int -> UTCTime
clock h m = sec (fromIntegral (h * 60 + m) * 60)