Author SHA1 Message Date
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
MasseR 6bcab1a0d8 Update tests 2026-09-30 15:01:17 +03:00
MasseR cceddad037 Capped based on light level 2026-09-30 14:27:50 +03:00
MasseR c75fc1a7b9 Logging and really not working light restoration 2026-09-30 13:46:16 +03:00
MasseR 1098be227d Push to journalctl 2026-09-30 12:33:31 +03:00
MasseR a427acd6ed Fix warnings 2026-09-30 09:05:48 +03:00
MasseR aee34f4e14 Make flag-decision tests fail fast and assert the outbound metric 2026-09-30 08:57:40 +03:00
MasseR 526710ef71 Simplify channelHassEval now that the writer owns the flag decision 2026-09-30 08:56:07 +03:00
MasseR c2425e8fb0 Move handler flag check from bus to writer with skip logging 2026-09-30 08:06:59 +03:00
MasseR a7a11e96b7 Complete rename vocabulary (childrenBedroomButton, toIkeaRemoteAction) 2026-09-30 00:21:24 +03:00
MasseR adce7c8427 Split Controller.hs into vertical submodules behind umbrella re-export 2026-09-30 00:07:31 +03:00
MasseR 9e00aeb6a2 Rename entity-list and snapshot helpers for consistency 2026-09-29 23:52:46 +03:00
MasseR b643fe55b1 Rename switch to switchService to avoid AFRP name conflict 2026-09-29 23:47:58 +03:00
MasseR 138b62c54a Rename IkeaController to IkeaRemoteAction, fix brightness typo 2026-09-29 23:44:56 +03:00
MasseR 889091d321 Regenerate default.nix (data-default was missing from the derivation) 2026-09-29 23:40:20 +03:00
MasseR c2426dec3d Unify per-room Lights enums into shared LightingMode 2026-09-29 23:38:43 +03:00
MasseR ad023a1ba2 Rename light observation layer (LightStatus, lightSignal, brightness, temperature) 2026-09-29 23:19:34 +03:00
MasseR 7ce994e814 Rename light command layer (Light, LightSettings, BrightnessSettings) 2026-09-29 23:14:07 +03:00
MasseR fefeae6301 Store a custom snapshot of lights 2026-09-29 22:51:37 +03:00
MasseR fcaccfdeb0 Faster transition 2026-09-29 20:42:14 +03:00
50 changed files with 1792 additions and 646 deletions

No files matched your search

+1 -1
View File
@@ -4,7 +4,7 @@ dist-newstyle
.worktrees/ .worktrees/
docs/superpowers docs/superpowers/plans
*.hp *.hp
*.eventlog *.eventlog
+11
View File
@@ -5,11 +5,17 @@
A sidecar for Home Assistant that runs automations using arrowized functional A sidecar for Home Assistant that runs automations using arrowized functional
reactive programming (AFRP). Haskell, built with cabal. 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 ## Code style
- Vertical modules: split by feature/concept, not by layer. - Vertical modules: split by feature/concept, not by layer.
- Comments are minimal. They describe the contract, not the implementation, - Comments are minimal. They describe the contract, not the implementation,
and should stay stable as the implementation changes. and should stay stable as the implementation changes.
- Never ever log directly to stdout via `putStr` and friends. Always use proper logging functions
## Build ## Build
@@ -24,3 +30,8 @@ reactive programming (AFRP). Haskell, built with cabal.
- hspec for unit tests, hedgehog for property tests. - hspec for unit tests, hedgehog for property tests.
- Run with `nix develop -c cabal test`. - 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.
-1
View File
@@ -4,5 +4,4 @@ import qualified HomeAssistant.Runtime (defaultMain)
main :: IO () main :: IO ()
main = do main = do
putStrLn "Hello, Haskell!"
HomeAssistant.Runtime.defaultMain HomeAssistant.Runtime.defaultMain
+13 -11
View File
@@ -1,9 +1,10 @@
{ mkDerivation, aeson, annotated-exception, async, base, bytestring { mkDerivation, aeson, annotated-exception, async, base, bytestring
, cereal, cereal-conduit, conduit, containers, directory, ekg-core , cereal, cereal-conduit, cereal-text, conduit, containers
, exceptions, filepath, hedgehog, hspec, hspec-hedgehog, http-media , data-default, directory, ekg-core, exceptions, filepath, hedgehog
, http-types, katip, lens, lens-aeson, lib, network, process, retry , hspec, hspec-hedgehog, http-media, http-types, katip, lens
, servant, servant-server, stm, temporary, text, time, unliftio , lens-aeson, lib, libsystemd-journal, lucid2, network, process
, unordered-containers, uuid, wai, warp, websockets , retry, servant, servant-server, stm, temporary, text, time
, unliftio, unordered-containers, uuid, wai, warp, websockets
}: }:
mkDerivation { mkDerivation {
pname = "home-assistant-controller"; pname = "home-assistant-controller";
@@ -13,16 +14,17 @@ mkDerivation {
isExecutable = true; isExecutable = true;
libraryHaskellDepends = [ libraryHaskellDepends = [
aeson annotated-exception async base bytestring cereal aeson annotated-exception async base bytestring cereal
cereal-conduit conduit containers directory ekg-core exceptions cereal-conduit cereal-text conduit containers data-default
filepath http-media http-types katip lens lens-aeson network directory ekg-core exceptions filepath http-media http-types katip
process retry servant servant-server stm text time unliftio lens lens-aeson libsystemd-journal lucid2 network process retry
unordered-containers uuid wai warp websockets servant servant-server stm text time unliftio unordered-containers
uuid wai warp websockets
]; ];
executableHaskellDepends = [ base ]; executableHaskellDepends = [ base ];
testHaskellDepends = [ testHaskellDepends = [
aeson annotated-exception async base bytestring cereal containers aeson annotated-exception async base bytestring cereal containers
directory ekg-core hedgehog hspec hspec-hedgehog katip process data-default directory ekg-core hedgehog hspec hspec-hedgehog katip
servant stm temporary text time unordered-containers uuid process servant stm temporary text time unordered-containers uuid
]; ];
license = lib.meta.getLicenseFromSpdxId "BSD-3-Clause"; license = lib.meta.getLicenseFromSpdxId "BSD-3-Clause";
mainProgram = "home-assistant-controller"; mainProgram = "home-assistant-controller";
@@ -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.
+26 -4
View File
@@ -52,7 +52,7 @@ extra-doc-files: CHANGELOG.md
-- extra-source-files: -- extra-source-files:
common warnings common warnings
ghc-options: -Wall ghc-options: -Wall -Werror
library library
-- Import common warning flags. -- Import common warning flags.
@@ -60,13 +60,25 @@ library
-- Modules exported by the library. -- Modules exported by the library.
exposed-modules: AFRP exposed-modules: AFRP
, AFRP.Diagram
, HomeAssistant.Controller , HomeAssistant.Controller
, HomeAssistant.Controller.Bedroom , HomeAssistant.Controller.Bedroom
, HomeAssistant.Controller.Hallway
, HomeAssistant.Controller.Kitchen
, HomeAssistant.Controller.Children , HomeAssistant.Controller.Children
, HomeAssistant.Controller.Door
, HomeAssistant.Controller.Effect
, HomeAssistant.Controller.Entity
, HomeAssistant.Controller.Hallway
, HomeAssistant.Controller.Ikea
, HomeAssistant.Controller.Kitchen
, HomeAssistant.Controller.Light.Command
, HomeAssistant.Controller.Light.Mode
, HomeAssistant.Controller.Light.Observation
, HomeAssistant.Controller.Livingroom , HomeAssistant.Controller.Livingroom
, HomeAssistant.Controller.Presence
, HomeAssistant.Controller.Ruuvi , HomeAssistant.Controller.Ruuvi
, HomeAssistant.Controller.Scene
, HomeAssistant.Controller.Service
, HomeAssistant.Controller.Switch
, HomeAssistant.Runtime , HomeAssistant.Runtime
, HomeAssistant.Runtime.Bus , HomeAssistant.Runtime.Bus
, HomeAssistant.Runtime.Connection , HomeAssistant.Runtime.Connection
@@ -76,6 +88,7 @@ library
, HomeAssistant.Runtime.Supervisor , HomeAssistant.Runtime.Supervisor
, HomeAssistant.Runtime.RateLimit , HomeAssistant.Runtime.RateLimit
, HttpServer , HttpServer
, Katip.Scribes.Journal
-- Modules included in this library but not exported. -- Modules included in this library but not exported.
-- other-modules: -- other-modules:
@@ -107,7 +120,9 @@ library
, process , process
, directory , directory
, cereal , cereal
, cereal-text
, containers , containers
, data-default
, filepath , filepath
, conduit , conduit
, cereal-conduit , cereal-conduit
@@ -117,6 +132,9 @@ library
, warp , warp
, wai , wai
, retry , retry
, libsystemd-journal
, lucid2
, http-api-data
-- Directories containing source files. -- Directories containing source files.
hs-source-dirs: src hs-source-dirs: src
@@ -164,11 +182,13 @@ test-suite home-assistant-controller-test
, ConnectionSpec , ConnectionSpec
, FlagsSpec , FlagsSpec
, GraphingSpec , GraphingSpec
, HttpServerSpec
, KitchenSpec , KitchenSpec
, LivingroomSpec , LivingroomSpec
, MetricsSpec , MetricsSpec
, RuntimeSpec , RuntimeSpec
, Support , Support
, ControllerSpec
-- LANGUAGE extensions used by modules in this package. -- LANGUAGE extensions used by modules in this package.
-- other-extensions: -- other-extensions:
@@ -187,6 +207,7 @@ test-suite home-assistant-controller-test
base ^>=4.20.2.0, base ^>=4.20.2.0,
home-assistant-controller, home-assistant-controller,
bytestring, bytestring,
data-default,
hspec, hspec,
stm, stm,
servant, servant,
@@ -205,4 +226,5 @@ test-suite home-assistant-controller-test
unordered-containers, unordered-containers,
process, process,
directory, 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"
+69 -31
View File
@@ -1,14 +1,16 @@
{-# LANGUAGE LambdaCase #-} {-# LANGUAGE LambdaCase #-}
{-# LANGUAGE Arrows #-} {-# LANGUAGE Arrows #-}
{-# LANGUAGE TypeOperators #-}
module AFRP module AFRP
( Mealy(..) ( Mealy(..)
, Auto(..) , Auto(..)
, DecodedAuto(..) , DecodedAuto(..)
, eff , eff
, withEntities , named
, Event(..) , Event(..)
, hold , hold
, holdKnown
, events , events
-- , switch -- , switch
, preMapAccum , preMapAccum
@@ -18,8 +20,10 @@ module AFRP
, changes , changes
, whenA , whenA
, filterA , filterA
, filterEvent
, thenA , thenA
, (>>|) , (>>|)
, (>>||)
, toEvent , toEvent
, lMerge , lMerge
, Pair(..) , Pair(..)
@@ -42,6 +46,7 @@ module AFRP
, load , load
, stepAuto , stepAuto
, stepAutoSerializing , stepAutoSerializing
, snapshot
) where ) where
import Control.Category (Category(..), (>>>)) import Control.Category (Category(..), (>>>))
@@ -55,7 +60,7 @@ import qualified Data.Set as S
import qualified Data.Text as T import qualified Data.Text as T
import Data.Serialize (Get, Putter, Serialize (put), runGet, get) import Data.Serialize (Get, Putter, Serialize (put), runGet, get)
import qualified Data.ByteString as B import qualified Data.ByteString as B
import Control.Exception (IOException, handle, throwIO) import Control.Exception (IOException)
import System.IO.Error (isDoesNotExistError) import System.IO.Error (isDoesNotExistError)
import GHC.Generics (Generic) import GHC.Generics (Generic)
import Data.Sequence (Seq, (|>)) import Data.Sequence (Seq, (|>))
@@ -64,6 +69,10 @@ import Control.Monad.IO.Class (MonadIO, liftIO)
import Conduit (ConduitT, (.|)) import Conduit (ConduitT, (.|))
import qualified Data.Conduit.Cereal as CC import qualified Data.Conduit.Cereal as CC
import qualified Conduit as C 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) } data Codec s = Codec { getter :: !(Get s), putter :: !(Putter s) }
@@ -126,7 +135,7 @@ instance Monad m => Applicative (Auto m a) where
pure a = Fun (\_req -> const a) pure a = Fun (\_req -> const a)
fa <*> fb = fa <*> fb =
case (fa,fb) of 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 (Stateful codec s af, Fun bf) -> Stateful codec s
(\s' req x -> do (\s' req x -> do
let a = bf req x let a = bf req x
@@ -176,7 +185,7 @@ instance (Monad m, Monoid b) => Monoid (Auto m a b) where
instance Monad m => Category (Auto m) where instance Monad m => Category (Auto m) where
id = Fun $ \_ -> id id = Fun $ const id
af . ag = af . ag =
case (af, ag) of case (af, ag) of
(Fun f, Fun g) -> Fun (\req -> f req . g req) (Fun f, Fun g) -> Fun (\req -> f req . g req)
@@ -246,63 +255,66 @@ save path s
isDirty _ = False isDirty _ = False
load :: forall m a b. FilePath -> Auto m a b -> IO (DecodedAuto m a b) load :: forall eff a b m. (MonadCatch m, MonadIO m) => FilePath -> Auto eff a b -> m (DecodedAuto eff a b)
load path a = handle defaultOnMissingFile (flip deserialize a <$> B.readFile path) load path a = handle defaultOnMissingFile (flip deserialize a <$> liftIO (B.readFile path))
where where
defaultOnMissingFile :: IOException -> IO (DecodedAuto m a b) defaultOnMissingFile :: IOException -> m (DecodedAuto eff a b)
defaultOnMissingFile e defaultOnMissingFile e
| isDoesNotExistError e = pure $ FailDecode "State doesn't exist yet" a | isDoesNotExistError e = pure $ FailDecode "State doesn't exist yet" a
| otherwise = throwIO e | otherwise = throw e
-- | The set of entity ids an arrow subscribes to. Static: it does not -- | 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 -- change as the machine steps, so the runtime can read it once to build
-- trigger subscriptions. -- trigger subscriptions.
data Mealy eff a b = Mealy data Mealy eff a b = Mealy
{ entities :: S.Set T.Text { 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 , 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 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 instance Monoid b => Monoid (Mealy eff a b) where
mempty = Mealy mempty $ \_nt -> mempty mempty = Mealy mempty emptyDiagram $ \_nt -> mempty
-- where
-- m = Mealy mempty $ \_ _ _ -> pure (Pair mempty m)
eff :: (Request -> a -> eff b) -> Mealy eff a b 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 Stateful (Codec get put) (State () False) $ \s req a -> do
b <- nt (f req a) b <- nt (f req a)
pure (b, s) 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 instance Category (Mealy eff) where
id = Mealy mempty (\_ -> id) {- HLINT ignore "Use const" -}
(Mealy ast f) . (Mealy bst g) = Mealy (ast <> bst) $ \nt -> do 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 f nt . g nt
instance Arrow (Mealy eff) where instance Arrow (Mealy eff) where
arr f = Mealy mempty $ \_nt -> arr f arr f = Mealy mempty emptyDiagram $ \_nt -> arr f
first (Mealy st f) = Mealy st $ \nt -> first (f nt) 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 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 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 instance Applicative (Mealy eff a) where
pure b = Mealy mempty $ \_ -> pure b pure b = Mealy mempty emptyDiagram $ \_ -> pure b
Mealy ast f <*> Mealy bst x = Mealy (ast <> bst) $ \nt -> Mealy ast ad f <*> Mealy bst bd x = Mealy (ast <> bst) (combineDiagram Compose ad bd) $ \nt ->
f nt <*> x nt f nt <*> x nt
data Event a data Event a
@@ -326,6 +338,16 @@ hold def = mapAccum step def id
Event new -> new Event new -> new
-- 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
step _prev (Event _, a) = a
events :: Mealy eff (Event a) (Either () a) events :: Mealy eff (Event a) (Either () a)
events = arr $ \case events = arr $ \case
Tick -> Left () Tick -> Left ()
@@ -357,10 +379,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 :: (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 :: (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' :: 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) mapAccum' f x extract = Stateful (Codec get put) (pure x) (\s _req a -> pure $ step s a)
@@ -369,7 +391,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')) 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 :: (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' :: 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) preMapAccumRequest' f x extract = Stateful (Codec get put) (State x False) (\s req a -> pure $ step s req a)
@@ -378,7 +400,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')) 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 :: (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' :: 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) mapAccumRequest' f x extract = Stateful (Codec get put) (State x False) (\s req a -> pure $ step s req a)
@@ -472,6 +494,13 @@ whenA predicate auto = arr (\a -> if predicate a then Left a else Right ()) >>>
filterA :: (a -> Bool) -> Mealy eff a (Either () a) filterA :: (a -> Bool) -> Mealy eff a (Either () a)
filterA f = arr $ \a -> bool (Left ()) (Right a) (f 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 :: (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 thenA f g = f >>> arr Left ||| g
@@ -480,6 +509,15 @@ thenA f g = f >>> arr Left ||| g
infixl 2 >>| 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 :: Mealy eff (Either () a) (Event a)
toEvent = arr (either (const Tick) Event) toEvent = arr (either (const Tick) Event)
@@ -594,7 +632,7 @@ requestLocalTime :: Request -> LocalTime
requestLocalTime Request{requestTime, requestTimeZone} = utcToLocalTime requestTimeZone requestTime requestLocalTime Request{requestTime, requestTimeZone} = utcToLocalTime requestTimeZone requestTime
currentTime :: Mealy eff a LocalTime currentTime :: Mealy eff a LocalTime
currentTime = Mealy mempty $ \_nt -> Fun $ \req _ -> currentTime = Mealy mempty emptyDiagram $ \_nt -> Fun $ \req _ ->
requestLocalTime 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
+12 -268
View File
@@ -1,271 +1,15 @@
{-# LANGUAGE Arrows #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE GADTs #-}
module HomeAssistant.Controller module HomeAssistant.Controller
( Service(..) ( module Export
, HASSEff(..)
, HASS
, callService
, callServiceDyn
, entityChangeEvent
, entityChangeEvent'
, entityRead
, entityRead'
, entityBool
, entityBool'
, DoorState(..)
, light
, Presence(..)
, presence
, motion
, motionToPresence
, debug
, traceEvent
, traceValue
, switch
, Target(..)
, brightness
, Light(..)
, ikeaQuickButton
, IkeaButton(..)
, IkeaGesture(..)
, activateScene
, activateSceneWith
, ikeaBoxRemote
, IkeaController(..)
) where ) where
import AFRP (Mealy (..), eff, Event(..), events, filterA, (>>|), toEvent, Request, hold, lMerge, waitFor, tag, edge) import HomeAssistant.Controller.Service as Export
import Control.Arrow (Arrow(..), returnA) import HomeAssistant.Controller.Effect as Export
import Control.Category ((>>>)) import HomeAssistant.Controller.Entity as Export
import Data.Aeson (Value, object, (.=)) import HomeAssistant.Controller.Presence as Export
import qualified Data.Text as T import HomeAssistant.Controller.Door as Export
import qualified Data.Set as S import HomeAssistant.Controller.Switch as Export
import Control.Lens (has, only, (^?), to, traversed) import HomeAssistant.Controller.Scene as Export
import Data.Aeson.Lens (key, _String, _Integral) import HomeAssistant.Controller.Ikea as Export
import qualified Data.Text.Lens as TL import HomeAssistant.Controller.Light.Command as Export
import Data.Bool (bool) import HomeAssistant.Controller.Light.Observation as Export
import Data.Serialize (Serialize) import HomeAssistant.Controller.Light.Mode as Export
import GHC.Generics (Generic)
import Data.Time (NominalDiffTime)
data Target = EntityId !T.Text | AreaId !T.Text
deriving (Show,Eq,Ord)
data Service = Service
{ serviceDomain :: T.Text
, serviceName :: T.Text
, serviceData :: Maybe Value
, serviceTarget :: [Target]
}
deriving (Show, Eq)
data HASSEff a where
CallService :: Request -> Service -> HASSEff ()
Debug :: Show a => a -> HASSEff ()
Trace :: Show a => Request -> a -> HASSEff ()
type HASS a b = Mealy HASSEff a b
callService :: Service -> HASS a ()
callService service = eff (\req _ -> CallService req service)
callServiceDyn :: (a -> Service) -> HASS a ()
callServiceDyn mkService = eff (\req a -> CallService req (mkService a))
debug :: Show a => HASS a a
debug = proc x -> do
eff (const Debug) -< x
returnA -< x
traceEvent :: Show a => HASS (Event a) (Event a)
traceEvent = proc ev -> do
case ev of
Event a -> eff Trace -< a
Tick -> returnA -< ()
returnA -< ev
traceValue :: Show a => HASS a a
traceValue = proc x -> do
eff Trace -< x
returnA -< x
data DoorState = Open | Closed
deriving (Show, Eq, Generic)
instance Serialize DoorState
data Presence = Occupied | Unoccupied
deriving (Show, Eq, Generic)
instance Serialize Presence
presence :: T.Text -> HASS (Event Value) (Event Presence)
presence entityId = entityBool entityId
>>> arr (fmap (bool Unoccupied Occupied))
data Motion = MotionDetected | MotionNotDetected | MotionUnknown
deriving (Show, Eq, Generic)
motion :: T.Text -> HASS (Event Value) Motion
motion entityId = entityBool entityId
>>> arr (fmap (bool MotionNotDetected MotionDetected))
>>> hold MotionUnknown
-- 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 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)
instance Serialize Motion
data Light
= Off
| On { brightnessPercentage :: Maybe Double }
-- Turn off lights when door is closed
light :: [Target] -> Light -> Service
light targets (On {brightnessPercentage}) = Service
{ serviceDomain="light"
, serviceName= "turn_on"
, serviceData=fmap (\pct -> object ["brightness_pct" .= pct]) brightnessPercentage
, serviceTarget=targets
}
light targets Off = Service
{ serviceDomain="light"
, serviceName= "turn_off"
, serviceData=Nothing
, serviceTarget=targets
}
-- Name conflict with AFRP
switch :: [Target] -> Bool -> Service
switch targets b = Service
{ serviceDomain="switch"
, serviceName= bool "turn_off" "turn_on" b
, serviceData=Nothing
, serviceTarget=targets
}
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)
where
isEntity :: Value -> Bool
isEntity = has (key "event" . key "variables" . key "trigger" . key "entity_id" . _String . only entityId)
entityRead' :: (Read a) => T.Text -> Mealy eff (Event Value) (Either () a)
entityRead' entityId = entityChangeEvent' entityId >>| (arr state >>> arr (maybe (Left ()) Right))
where
state v = v ^? key "event" . key "variables" . key "trigger" . key "to_state" . key "state" . _String . TL.unpacked . to read
entityBool' :: T.Text -> Mealy eff (Event Value) (Either () Bool)
entityBool' entityId = entityChangeEvent' entityId >>| (arr state >>> arr (maybe (Left ()) Right))
where
state v = v ^? key "event" . key "variables" . key "trigger" . key "to_state" . key "state" . _String . TL.unpacked . to toBool
toBool = \case
"on" -> True
"off" -> False
_ -> False
entityRead :: (Read a) => T.Text -> Mealy eff (Event Value) (Event a)
entityRead entityId = entityRead' entityId >>> toEvent
entityBool :: T.Text -> Mealy eff (Event Value) (Event Bool)
entityBool entityId = entityBool' entityId >>> toEvent
brightness :: T.Text -> HASS (Event Value) (Event Int)
brightness entityId =
entityChangeEvent' entityId
>>| arr (maybe (Left ()) Right . eventBrightness)
>>> AFRP.toEvent
where
eventBrightness v = v ^? key "event" . key "variables" . key "trigger" . key "to_state" . key "attributes" . key "brightness" . _Integral
data IkeaGesture
= ShortClick
| ShortRelease
| DoubleClick
| LongClick
deriving Show
data IkeaButton a = OnButton !a | OffButton !a
deriving Show
toIkeaQuickButton :: T.Text -> Maybe (IkeaButton IkeaGesture)
toIkeaQuickButton = \case
-- 1 is on, 2 is off side of the button
"1_initial_press" -> Just $ OnButton ShortClick
"1_short_release" -> Just $ OnButton ShortRelease
"1_double_press" -> Just $ OnButton DoubleClick
"1_long_press" -> Just $ OnButton LongClick
"2_initial_press" -> Just $ OffButton ShortClick
"2_short_release" -> Just $ OffButton ShortRelease
"2_double_press" -> Just $ OffButton DoubleClick
"2_long_press" -> Just $ OffButton LongClick
_ -> Nothing
ikeaQuickButton :: T.Text -> HASS (Event Value) (Event (IkeaButton IkeaGesture))
ikeaQuickButton entityId =
entityChangeEvent' entityId
>>| arr (maybe (Left ()) Right . eventType)
>>> toEvent
where
eventType v = v ^? key "event" . key "variables" . key "trigger" . key "to_state" . key "attributes" . key "event_type" . _String . to toIkeaQuickButton . traversed
data IkeaController
= ControllerOn -- Short press on
| ControllerOff -- Short press off
| ControllerBrighnessUp -- Turn brightness up
| ControllerBrighnessDown -- Turn brighness down
| ControllerArrowRight -- Turn brighness down
| ControllerArrowLeft -- Turn brighness down
| ControllerBrighnessStop
deriving Show
toIkeaController :: T.Text -> Maybe IkeaController
toIkeaController = \case
"on" -> Just ControllerOn
"off" -> Just ControllerOff
"brightness_move_up" -> Just ControllerBrighnessUp
"brightness_move_down" -> Just ControllerBrighnessDown
"brightness_stop" -> Just ControllerBrighnessStop
"arrow_right_click" -> Just ControllerArrowRight
"arrow_left_click" -> Just ControllerArrowLeft
_ -> Nothing
ikeaBoxRemote :: T.Text -> HASS (Event Value) (Event IkeaController)
ikeaBoxRemote entityId = entityChangeEvent' entityId
>>| arr (maybe (Left ()) Right . eventType)
>>> toEvent
where
eventType v = v ^? key "event" . key "variables" . key "trigger" . key "to_state" . key "attributes" . key "event_type" . _String . to toIkeaController . traversed
activateScene :: T.Text -> Service
activateScene sceneId = activateSceneWith sceneId Nothing
activateSceneWith :: T.Text -> Maybe Value -> Service
activateSceneWith sceneId d = Service
{ serviceDomain="scene"
, serviceName= "turn_on"
, serviceTarget= [EntityId sceneId]
, serviceData = d
}
+66 -42
View File
@@ -1,20 +1,26 @@
{-# LANGUAGE Arrows #-} {-# LANGUAGE Arrows #-}
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DerivingVia #-}
module HomeAssistant.Controller.Bedroom where module HomeAssistant.Controller.Bedroom where
import HomeAssistant.Controller import HomeAssistant.Controller
import qualified Data.Text as T import qualified Data.Text as T
import AFRP (Event (..), lMerge, duration, edge) import AFRP (Event (..), lMerge, duration, edge, filterEvent, named, (>>||))
import Data.Aeson (Value, object, (.=)) import Data.Aeson (Value, object, (.=))
import Control.Arrow ((>>>), returnA, arr, Arrow (..)) import Control.Arrow ((>>>), returnA, arr, Arrow (..))
import Data.Bool (bool) import Data.Bool (bool)
import Data.Time (NominalDiffTime) import Data.Time (NominalDiffTime)
import qualified AFRP 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)
bedroomLights :: [Target] bedroomLightTargets :: [Target]
bedroomLights = map EntityId ["light.bedroom_masse","light.bedroom_jemina","light.bedroom_ceiling","light.bedroom_led_switch"] bedroomLightTargets = map EntityId ["light.bedroom_masse","light.bedroom_jemina","light.bedroom_ceiling","light.bedroom_led_switch"]
createBedroomScene :: Service createBedroomScene :: Service
createBedroomScene = Service createBedroomScene = Service
@@ -22,22 +28,16 @@ createBedroomScene = Service
, serviceName= "create" , serviceName= "create"
, serviceData= Just $ object , serviceData= Just $ object
[ "scene_id" .= ("makuuhuone_lights_snapshot" :: T.Text) [ "scene_id" .= ("makuuhuone_lights_snapshot" :: T.Text)
, "snapshot_entities" .= [l | EntityId l <- bedroomLights] , "snapshot_entities" .= [l | EntityId l <- bedroomLightTargets]
] ]
, serviceTarget= [] , serviceTarget= []
} }
data PresenceLights
= LightsOn -- Restore lights
| LightsOff -- Timer expired, darkness
| LightsSleep -- No presence detected, sleep mode
deriving Show
-- Bedroom presence -- Bedroom presence
bedroomPresence :: HASS (Event Value) (Event Presence) bedroomPresence :: HASS (Event Value) (Event Presence)
bedroomPresence = presence "binary_sensor.presence_sensor_bedroom_occupancy" bedroomPresence = presence "binary_sensor.presence_sensor_bedroom_occupancy"
presenceLightEvents :: HASS (Event Value) (Event PresenceLights) presenceLightEvents :: HASS (Event Value) (Event LightingMode)
presenceLightEvents = presenceLightEvents =
bedroomPresence >>> AFRP.hold Unoccupied bedroomPresence >>> AFRP.hold Unoccupied
>>> arr lightWanted >>> arr lightWanted
@@ -45,36 +45,60 @@ presenceLightEvents =
>>> arr (\(s,(o,n)) -> s `AFRP.lMerge` o `AFRP.lMerge` n) >>> arr (\(s,(o,n)) -> s `AFRP.lMerge` o `AFRP.lMerge` n)
where where
lightWanted o = o == Occupied lightWanted o = o == Occupied
sleepEvent = arr not >>> AFRP.edge >>> arr (AFRP.tag LightsSleep) sleepEvent = arr not >>> AFRP.edge >>> arr (AFRP.tag LightingSleep)
onEvent = AFRP.edge >>> arr (AFRP.tag LightsOn) onEvent = AFRP.edge >>> arr (AFRP.tag LightingOn)
offEvent = arr not >>> AFRP.waitFor 300 >>> arr (AFRP.tag LightsOff) offEvent = arr not >>> AFRP.waitFor 300 >>> arr (AFRP.tag LightingOff)
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)
lightLevel :: HASS (Event Value) Int
lightLevel = entityRead "sensor.presence_sensor_bedroom_light_level" >>> AFRP.hold 1
bedroomPresenceController :: HASS (Event Value) () bedroomPresenceController :: HASS (Event Value) ()
bedroomPresenceController = proc x -> do bedroomPresenceController = proc x -> do
p <- presenceLightEvents >>> traceEvent -< x p <- presenceLightEvents >>> traceEvent -< x
capped <- lightLevel >>> arr (< 4) -< x
snap <- (doSnapshot &&& bedroomLightStatus) >>> AFRP.snapshot M.empty >>> arr Snapshot -< x
-- This line is just for debugging
_ <- AFRP.changes >>> traceEvent -< snap
case p of case p of
Event LightsOff -> do Event LightingOff -> do
callService (light bedroomLights Off) -< () callService "Turn off lights" (light bedroomLightTargets Off) -< ()
Event LightsOn -> do Event LightingOn -> do
callService (activateSceneWith "scene.makuuhuone_lights_snapshot" transition) -< () callServicesDyn "Turn on lights (capped)" (\(c,xs) -> concatMap (uncurry (toLight c)) xs) -< (capped, M.toList (getSnapshot snap))
Event LightsSleep -> do returnA -< ()
callService createBedroomScene -< () Event LightingSleep -> do
callService (activateSceneWith "scene.makuuhuone_lepotila" transition) -< () callService "Turn on sleep" (activateScene "scene.makuuhuone_lepotila") -< ()
_ -> returnA -< () _ -> returnA -< ()
where where
transition = Just $ object ["transition" .= (10 :: Int)] toLight :: Bool -> T.Text -> LightObservation -> [Service]
toLight _ entityId LightObservation{observedOn=False} = [light [EntityId entityId] Off]
toLight capped entityId LightObservation{observedOn=True, observedTemperature=t, observedBrightness=b} =
[ 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 data BedroomControls
= Masse (IkeaButton IkeaGesture) = Masse (IkeaButton IkeaGesture)
| Enishen (IkeaButton IkeaGesture) | Enishen (IkeaButton IkeaGesture)
| Central IkeaController | Central IkeaRemoteAction
deriving Show deriving Show
bedroomButton :: HASS (Event Value) (Event BedroomControls) bedroomButton :: HASS (Event Value) (Event BedroomControls)
bedroomButton = (masseButton &&& enishenButton &&& centralButton) bedroomButton = (masseButton &&& enishenButton &&& centralButton)
>>> arr (\(a,(b,c)) -> a `lMerge` b `lMerge` c) >>> arr (\(a,(b,c)) -> a <> b <> c)
where where
masseButton = fmap Masse <$> ikeaQuickButton "event.bedroom_quick_remote_masse_action" masseButton = fmap Masse <$> ikeaQuickButton "event.bedroom_quick_remote_masse_action"
enishenButton = fmap Enishen <$> ikeaQuickButton "event.bedroom_quick_jemina_action" enishenButton = fmap Enishen <$> ikeaQuickButton "event.bedroom_quick_jemina_action"
@@ -86,24 +110,22 @@ bedroomButtonController = proc x -> do
-- Any event will cause the sleep mode to be turned off -- Any event will cause the sleep mode to be turned off
case ev of case ev of
Event (Masse (OnButton ShortRelease)) -> do Event (Masse (OnButton ShortRelease)) -> do
callService (activateSceneWith "scene.makuuhuone_masse" transition) -< () callService "scene.makuuhuone_masse" (activateScene "scene.makuuhuone_masse") -< ()
Event (Masse (OnButton DoubleClick)) -> do Event (Masse (OnButton DoubleClick)) -> do
callService (activateSceneWith "scene.makuuhuone_keski" transition) -< () callService "scene.makuuhuone_keski" (activateScene "scene.makuuhuone_keski") -< ()
Event (Masse (OnButton LongClick)) -> do Event (Masse (OnButton LongClick)) -> do
callService (activateSceneWith "scene.makuuhuone_kirkas" transition) -< () callService "scene.makuuhuone_kirkas" (activateScene "scene.makuuhuone_kirkas") -< ()
Event (Masse (OffButton _)) -> do Event (Masse (OffButton _)) -> do
callService (light [AreaId "makuuhuone"] Off) -< () callService "Lights off" (light [AreaId "makuuhuone"] Off) -< ()
Event (Enishen (OnButton ShortRelease)) -> do Event (Enishen (OnButton ShortRelease)) -> do
callService (activateSceneWith "scene.makuuhuone_jemina" transition) -< () callService "scene.makuuhuone_jemina" (activateScene "scene.makuuhuone_jemina") -< ()
Event (Enishen (OnButton DoubleClick)) -> do Event (Enishen (OnButton DoubleClick)) -> do
callService (activateSceneWith "scene.makuuhuone_keski" transition) -< () callService "scene.makuuhuone_keski" (activateScene "scene.makuuhuone_keski") -< ()
Event (Enishen (OnButton LongClick)) -> do Event (Enishen (OnButton LongClick)) -> do
callService (activateSceneWith "scene.makuuhuone_kirkas" transition) -< () callService "scene.makuuhuone_kirkas" (activateScene "scene.makuuhuone_kirkas") -< ()
Event (Enishen (OffButton _)) -> do Event (Enishen (OffButton _)) -> do
callService (light [AreaId "makuuhuone"] Off) -< () callService "Lights off" (light [AreaId "makuuhuone"] Off) -< ()
_ -> returnA -< () _ -> returnA -< ()
where
transition = Just $ object ["transition" .= (5 :: Int)]
@@ -112,14 +134,16 @@ drawer = entityBool "binary_sensor.bedroom_nightstand_drawer_sensor_masse_contac
>>> arr (fmap (bool Closed Open)) >>> arr (fmap (bool Closed Open))
bedroomDrawerController :: HASS (Event Value) () bedroomDrawerController :: HASS (Event Value) ()
bedroomDrawerController = proc x -> do bedroomDrawerController =
st <- drawer >>> traceEvent -< x drawer >>>
case st of (named "Drawer opened" lightOn <> named "Drawer closed" lightOff)
Event Open -> callService (switch [entity] True) -< () >>> arr (const ())
Event Closed -> callService (switch [entity] False) -< ()
_ -> returnA -< ()
where where
entity = EntityId "switch.bedroom_drawer_light_masse" 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 :: HASS (Event Value) (Event DoorState)
door = entityBool "binary_sensor.makuuhuone_ovi_contact" door = entityBool "binary_sensor.makuuhuone_ovi_contact"
@@ -141,8 +165,8 @@ humidifierController = proc x -> do
case st of case st of
-- Turn the humidifier on when the door is closed -- Turn the humidifier on when the door is closed
-- the humidifier is low-powered, no point in losing all the humidity -- the humidifier is low-powered, no point in losing all the humidity
Event Open -> callService (humidifier False) -< () Event Open -> callService "Humidifier off" (humidifier False) -< ()
Event Closed -> callService (humidifier True) -< () Event Closed -> callService "Humidifier on" (humidifier True) -< ()
_ -> returnA -< () _ -> returnA -< ()
where where
humidifier state = Service humidifier state = Service
+81 -11
View File
@@ -1,14 +1,25 @@
{-# LANGUAGE Arrows #-} {-# LANGUAGE Arrows #-}
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DerivingVia #-}
module HomeAssistant.Controller.Children where module HomeAssistant.Controller.Children where
import HomeAssistant.Controller (HASS, callService, Target (AreaId), light, Light(..), ikeaQuickButton, IkeaGesture (..), IkeaButton (..), traceEvent, activateScene) import HomeAssistant.Controller (HASS, callService, light, LightCommand(..), ikeaQuickButton, IkeaGesture (..), IkeaButton (..), traceEvent, activateScene, LightAttributes (..), Brightness (..), entityRead, entityChangeEvent)
import AFRP (Event (..)) import AFRP (Event (..))
import qualified AFRP import qualified AFRP
import Control.Arrow (Arrow(..), (>>>), returnA) import Control.Arrow (Arrow(..), (>>>), returnA)
import Data.Time (Day, TimeOfDay (..), localDay, LocalTime (..)) import Data.Time (Day, TimeOfDay (..), localDay, LocalTime (..))
import Data.Time.Calendar.OrdinalDate (WeekOfYear, mondayStartWeek) import Data.Time.Calendar.OrdinalDate (WeekOfYear, mondayStartWeek)
import Data.Functor.Contravariant (Predicate (..), (>$<)) 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 -- Let's see building some reasonable interface for utctime
dow :: Day -> (WeekOfYear, Int) dow :: Day -> (WeekOfYear, Int)
@@ -74,22 +85,81 @@ schoolLightController = lightsOn <> lightsOff
lightsOn :: HASS a () lightsOn :: HASS a ()
lightsOn = foldMap atTime timersOn lightsOn = foldMap atTime timersOn
>>> AFRP.onEvent (callService (light [AreaId "lasten_makuuhuone"] On{brightnessPercentage = Just 100})) >>> AFRP.onEvent (callService "Lights on" (light [AreaId "lasten_makuuhuone"] (On def{lightBrightness=Just $ BrightnessPercent 100} )))
lightsOff :: HASS a () lightsOff :: HASS a ()
lightsOff = foldMap atTime timersOff lightsOff = foldMap atTime timersOff
>>> AFRP.onEvent (callService (light [AreaId "lasten_makuuhuone"] Off)) >>> AFRP.onEvent (callService "Lights off" (light [AreaId "lasten_makuuhuone"] Off))
bedroomButton :: HASS (Event Value) (Event (IkeaButton IkeaGesture)) childrenBedroomButton :: HASS (Event Value) (Event (IkeaButton IkeaGesture))
bedroomButton = ikeaQuickButton "event.children_quick_remote_action" childrenBedroomButton = ikeaQuickButton "event.children_quick_remote_action"
childrenBedroomButtonController :: HASS (Event Value) () childrenBedroomButtonController :: HASS (Event Value) ()
childrenBedroomButtonController = proc x -> do childrenBedroomButtonController = proc x -> do
ev <- bedroomButton >>> traceEvent -< x ev <- childrenBedroomButton >>> traceEvent -< x
case ev of case ev of
Event (OnButton ShortRelease) -> callService (activateScene "scene.lasten_nukkuvalmistelu") -< () Event (OnButton ShortRelease) -> callService "scene.lasten_nukkuvalmistelu" (activateScene "scene.lasten_nukkuvalmistelu") -< ()
Event (OnButton DoubleClick) -> callService (activateScene "scene.lasten_luku") -< () Event (OnButton DoubleClick) -> callService "scene.lasten_luku" (activateScene "scene.lasten_luku") -< ()
Event (OnButton LongClick) -> callService (activateScene "scene.lasten_kirkas") -< () Event (OnButton LongClick) -> callService "scene.lasten_kirkas" (activateScene "scene.lasten_kirkas") -< ()
Event (OffButton _) -> callService (light [AreaId "lasten_makuuhuone"] Off) -< () Event (OffButton _) -> callService "Lights off" (light [AreaId "lasten_makuuhuone"] Off) -< ()
_ -> returnA -< () _ -> 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"]
, serviceData = Just $ toJSON percentage
}
+9
View File
@@ -0,0 +1,9 @@
module HomeAssistant.Controller.Door (DoorState(..)) where
import GHC.Generics (Generic)
import Data.Serialize (Serialize)
data DoorState = Open | Closed
deriving (Show, Eq, Generic)
instance Serialize DoorState
+60
View File
@@ -0,0 +1,60 @@
{-# LANGUAGE Arrows #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
module HomeAssistant.Controller.Effect
( HASSEff(..)
, HASS
, callService
, callServices
, callServiceDyn
, callServicesDyn
, debug
, traceEvent
, traceValue
) where
import AFRP (Mealy, eff, Event (..), Request, named)
import Control.Arrow (returnA)
import HomeAssistant.Controller.Service (Service (..))
import qualified Data.Text as T
data HASSEff a where
CallService :: Request -> Service -> HASSEff ()
CallServices :: Request -> [Service] -> HASSEff ()
Debug :: Show a => a -> HASSEff ()
Trace :: Show a => Request -> a -> HASSEff ()
type HASS a b = Mealy HASSEff a b
serviceLabel :: T.Text -> HASS a b -> HASS a b
serviceLabel lbl = named ("Service: " <> lbl)
callService :: T.Text -> Service -> HASS a ()
callService lbl service = serviceLabel lbl $ eff (\req _ -> CallService req service)
callServices :: T.Text -> [Service] -> HASS a ()
callServices lbl service = serviceLabel lbl $ eff (\req _ -> CallServices req service)
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
eff (const Debug) -< x
returnA -< x
traceEvent :: Show a => HASS (Event a) (Event a)
traceEvent = proc ev -> do
case ev of
Event a -> eff Trace -< a
Tick -> returnA -< ()
returnA -< ev
traceValue :: Show a => HASS a a
traceValue = proc x -> do
eff Trace -< x
returnA -< x
+51
View File
@@ -0,0 +1,51 @@
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
module HomeAssistant.Controller.Entity
( entityChangeEvent
, entityChangeEvent'
, entityRead
, entityRead'
, entityBool
, entityBool'
) where
import AFRP (Mealy (..), Event, events, filterA, (>>|), toEvent, named)
import Control.Arrow (arr)
import Control.Category ((>>>))
import Data.Aeson (Value)
import Data.Aeson.Lens (key, _String)
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 = 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)
entityRead' :: (Read a) => T.Text -> Mealy eff (Event Value) (Either () a)
entityRead' entityId = entityChangeEvent' entityId >>| (arr state >>> arr (maybe (Left ()) Right))
where
state v = v ^? key "event" . key "variables" . key "trigger" . key "to_state" . key "state" . _String . TL.unpacked . to read
entityBool' :: T.Text -> Mealy eff (Event Value) (Either () Bool)
entityBool' entityId = entityChangeEvent' entityId >>| (arr state >>> arr (maybe (Left ()) Right))
where
state v = v ^? key "event" . key "variables" . key "trigger" . key "to_state" . key "state" . _String . TL.unpacked . to toBool
toBool = \case
"on" -> True
"off" -> False
_ -> False
entityRead :: (Read a) => T.Text -> Mealy eff (Event Value) (Event a)
entityRead entityId = entityRead' entityId >>> toEvent
entityBool :: T.Text -> Mealy eff (Event Value) (Event Bool)
entityBool entityId = entityBool' entityId >>> toEvent
+7 -14
View File
@@ -2,37 +2,30 @@
{-# LANGUAGE Arrows #-} {-# LANGUAGE Arrows #-}
module HomeAssistant.Controller.Hallway where module HomeAssistant.Controller.Hallway where
import HomeAssistant.Controller (Presence (..), HASS, motion, motionToPresence, traceEvent, callServiceDyn, light, Target (..), Light (..)) import HomeAssistant.Controller (Presence, HASS, motion, motionToPresence, traceEvent, callServiceDyn, light, Target (..), LightCommand (..))
import HomeAssistant.Controller.Light.Mode (LightingMode (..), lightingModeEvents)
import AFRP (Event (..)) import AFRP (Event (..))
import qualified AFRP import qualified AFRP
import Data.Aeson (Value) import Data.Aeson (Value)
import Control.Arrow ((>>>), Arrow (..), returnA) import Control.Arrow ((>>>), returnA)
import Data.Time (LocalTime(..), TimeOfDay (..)) import Data.Time (LocalTime(..), TimeOfDay (..))
import Data.Default (def)
hallwayPresence :: HASS (Event Value) Presence hallwayPresence :: HASS (Event Value) Presence
hallwayPresence = motion "binary_sensor.hallway_movement_occupancy" >>> motionToPresence 500 hallwayPresence = motion "binary_sensor.hallway_movement_occupancy" >>> motionToPresence 500
data Lights = LightsOn | LightsOff
deriving (Show)
eventLights :: HASS Presence (Event Lights)
eventLights = AFRP.changes >>> arr (fmap presenceLights)
where
presenceLights Occupied = LightsOn
presenceLights Unoccupied = LightsOff
hallwayLightsController :: HASS (Event Value) () hallwayLightsController :: HASS (Event Value) ()
hallwayLightsController = proc x -> do hallwayLightsController = proc x -> do
now <- AFRP.currentTime -< () now <- AFRP.currentTime -< ()
p <- hallwayPresence -< x p <- hallwayPresence -< x
ev <- eventLights -< p ev <- lightingModeEvents -< p
traceEvent -< ev traceEvent -< ev
case ev of case ev of
-- The lights entity is a "group of lights" in hass -- The lights entity is a "group of lights" in hass
Event LightsOn | lightsAllowed now -> callServiceDyn (light [EntityId "light.hallway_lights"]) -< On Nothing Event LightingOn | lightsAllowed now -> callServiceDyn "Lights on" (light [EntityId "light.hallway_lights"]) -< On def
Event LightsOff -> callServiceDyn (light [EntityId "light.hallway_lights"]) -< Off Event LightingOff -> callServiceDyn "Lights off" (light [EntityId "light.hallway_lights"]) -< Off
_ -> returnA -< () _ -> returnA -< ()
where where
lightsAllowed (LocalTime _ tod) = not (tod > TimeOfDay 1 45 0 && tod < TimeOfDay 5 0 0) lightsAllowed (LocalTime _ tod) = not (tod > TimeOfDay 1 45 0 && tod < TimeOfDay 5 0 0)
+80
View File
@@ -0,0 +1,80 @@
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
module HomeAssistant.Controller.Ikea
( IkeaGesture(..)
, IkeaButton(..)
, IkeaRemoteAction(..)
, ikeaQuickButton
, ikeaBoxRemote
) where
import AFRP (Event, toEvent, (>>|))
import Control.Arrow (arr)
import Control.Category ((>>>))
import Control.Lens ((^?), to, traversed)
import Data.Aeson (Value)
import Data.Aeson.Lens (key, _String)
import qualified Data.Text as T
import HomeAssistant.Controller.Entity (entityChangeEvent')
import HomeAssistant.Controller.Effect (HASS)
data IkeaGesture
= ShortClick
| ShortRelease
| DoubleClick
| LongClick
deriving Show
data IkeaButton a = OnButton !a | OffButton !a
deriving Show
toIkeaQuickButton :: T.Text -> Maybe (IkeaButton IkeaGesture)
toIkeaQuickButton = \case
-- 1 is on, 2 is off side of the button
"1_initial_press" -> Just $ OnButton ShortClick
"1_short_release" -> Just $ OnButton ShortRelease
"1_double_press" -> Just $ OnButton DoubleClick
"1_long_press" -> Just $ OnButton LongClick
"2_initial_press" -> Just $ OffButton ShortClick
"2_short_release" -> Just $ OffButton ShortRelease
"2_double_press" -> Just $ OffButton DoubleClick
"2_long_press" -> Just $ OffButton LongClick
_ -> Nothing
ikeaQuickButton :: T.Text -> HASS (Event Value) (Event (IkeaButton IkeaGesture))
ikeaQuickButton entityId =
entityChangeEvent' entityId
>>| arr (maybe (Left ()) Right . eventType)
>>> toEvent
where
eventType v = v ^? key "event" . key "variables" . key "trigger" . key "to_state" . key "attributes" . key "event_type" . _String . to toIkeaQuickButton . traversed
data IkeaRemoteAction
= RemoteOn -- Short press on
| RemoteOff -- Short press off
| RemoteBrightnessUp -- Turn brightness up
| RemoteBrightnessDown -- Turn brightness down
| RemoteArrowRight -- Arrow right
| RemoteArrowLeft -- Arrow left
| RemoteBrightnessStop
deriving Show
toIkeaRemoteAction :: T.Text -> Maybe IkeaRemoteAction
toIkeaRemoteAction = \case
"on" -> Just RemoteOn
"off" -> Just RemoteOff
"brightness_move_up" -> Just RemoteBrightnessUp
"brightness_move_down" -> Just RemoteBrightnessDown
"brightness_stop" -> Just RemoteBrightnessStop
"arrow_right_click" -> Just RemoteArrowRight
"arrow_left_click" -> Just RemoteArrowLeft
_ -> Nothing
ikeaBoxRemote :: T.Text -> HASS (Event Value) (Event IkeaRemoteAction)
ikeaBoxRemote entityId = entityChangeEvent' entityId
>>| arr (maybe (Left ()) Right . eventType)
>>> toEvent
where
eventType v = v ^? key "event" . key "variables" . key "trigger" . key "to_state" . key "attributes" . key "event_type" . _String . to toIkeaRemoteAction . traversed
+25 -38
View File
@@ -2,37 +2,29 @@
{-# LANGUAGE Arrows #-} {-# LANGUAGE Arrows #-}
module HomeAssistant.Controller.Kitchen where module HomeAssistant.Controller.Kitchen where
import HomeAssistant.Controller import HomeAssistant.Controller
import AFRP (Event (..)) import AFRP (Event (..), (>>||))
import qualified AFRP import qualified AFRP
import Data.Aeson (Value) import Data.Aeson (Value)
import Control.Arrow ((>>>), Arrow (..), returnA) import Control.Arrow ((>>>), Arrow (..), returnA)
import Prelude hiding (id) import Prelude hiding (id)
import Data.Time (LocalTime(..), TimeOfDay (..)) import Data.Time (LocalTime(..), TimeOfDay (..))
import Data.Default (def)
-- Kitchen has two "presence" sensors. One IKEA motion sensor and one SwitchBot presence sensor -- Kitchen has two "presence" sensors. One IKEA motion sensor and one SwitchBot presence sensor
data Lights = LightsOn | LightsOff | LightsSleep
deriving (Show)
kitchenPresence :: HASS (Event Value) Presence kitchenPresence :: HASS (Event Value) Presence
kitchenPresence = motion "binary_sensor.kitchen_movement_occupancy" >>> motionToPresence 500 kitchenPresence = motion "binary_sensor.kitchen_movement_occupancy" >>> motionToPresence 500
eventLights :: HASS Presence (Event Lights)
eventLights = AFRP.changes >>> arr (fmap presenceLights)
where
presenceLights Occupied = LightsOn
presenceLights Unoccupied = LightsOff
kitchenCeilingController :: HASS (Event Value) () kitchenCeilingController :: HASS (Event Value) ()
kitchenCeilingController = proc x -> do kitchenCeilingController = proc x -> do
now <- AFRP.currentTime -< () now <- AFRP.currentTime -< ()
p <- kitchenPresence -< x p <- kitchenPresence -< x
ev <- eventLights -< p ev <- lightingModeEvents -< p
traceEvent -< ev traceEvent -< ev
case ev of case ev of
Event LightsOn | lightsAllowed now -> callServiceDyn (light [EntityId "light.kitchen_ceiling"]) -< On Nothing Event LightingOn | lightsAllowed now -> callServiceDyn "light.kitchen_ceiling on" (light [EntityId "light.kitchen_ceiling"]) -< On def
Event LightsOff -> callServiceDyn (light [EntityId "light.kitchen_ceiling"]) -< Off Event LightingOff -> callServiceDyn "light.kitchen_ceiling off" (light [EntityId "light.kitchen_ceiling"]) -< Off
_ -> returnA -< () _ -> returnA -< ()
where where
lightsAllowed (LocalTime _ tod) = not (tod > TimeOfDay 1 45 0 && tod < TimeOfDay 5 0 0) lightsAllowed (LocalTime _ tod) = not (tod > TimeOfDay 1 45 0 && tod < TimeOfDay 5 0 0)
@@ -44,44 +36,39 @@ dinnerLightLevel = entityRead "sensor.sijainti_keittio_light_level" >>> AFRP.hol
dinnerPresence :: HASS (Event Value) Presence dinnerPresence :: HASS (Event Value) Presence
dinnerPresence = presence "binary_sensor.sijainti_keittio_occupancy" >>> AFRP.hold Unoccupied dinnerPresence = presence "binary_sensor.sijainti_keittio_occupancy" >>> AFRP.hold Unoccupied
dinnerLightEvents :: HASS (Event Value) (Event Lights)
dinnerLightEvents = dinnerTableController :: HASS (Event Value) ()
dinnerTableController =
((,) <$> dinnerLightLevel <*> dinnerPresence) ((,) <$> dinnerLightLevel <*> dinnerPresence)
>>> arr lightWanted >>> arr lightWanted
>>> (sleepEvent &&& offEvent &&& onEvent) -- These are done "in parallel", there is a chance that two services are called in one go
>>> arr (\(s, (o, n)) -> s `AFRP.lMerge` o `AFRP.lMerge` n) >>> 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 where
lightWanted (lightLevel, occ) = occ == Occupied && lightLevel < 13 lightWanted (lightLevel, occ) = occ == Occupied && lightLevel < 13
onEvent = lightsOn =
AFRP.edge AFRP.edge
>>> arr (fmap (const LightsOn)) >>|| sleep "sleep off" False
>>> callService "Dining light on" (light [EntityId "light.kitchen_dining_large"] $ On def)
sleepEvent = lightsSleep =
arr not arr not
>>> AFRP.edge >>> AFRP.edge
>>> arr (fmap (const LightsSleep)) >>|| sleep "sleep on" True
offEvent = lightsOff =
arr not arr not
>>> AFRP.waitFor 300 >>> AFRP.waitFor 300
>>> arr (fmap (const LightsOff)) >>|| 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 LightsOn -> do
sleep -< False
callServiceDyn (light [EntityId "light.kitchen_dining_large"]) -< On Nothing
Event LightsOff -> do
sleep -< False
callServiceDyn (light [EntityId "light.kitchen_dining_large"]) -< Off
Event LightsSleep -> do
sleep -< True
_ -> returnA -< ()
where
sleep = callServiceDyn (switch [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"])
kitchenMotionController :: HASS (Event Value) () kitchenMotionController :: HASS (Event Value) ()
kitchenMotionController = kitchenCeilingController <> dinnerTableController kitchenMotionController = kitchenCeilingController <> dinnerTableController
@@ -0,0 +1,62 @@
{-# LANGUAGE MonadComprehensions #-}
{-# LANGUAGE OverloadedStrings #-}
module HomeAssistant.Controller.Light.Command
( LightCommand(..)
, LightAttributes(..)
, Brightness(..)
, light
, formatLightAttributes
) where
import Data.Aeson (Value, object, (.=))
import Data.Aeson.Types (Pair)
import Data.Default (Default)
import Data.Maybe (catMaybes)
import GHC.Generics (Generic)
import HomeAssistant.Controller.Service (Service (..), Target)
data Brightness = BrightnessPercent Double | BrightnessAbsolute Int
deriving (Show, Generic)
instance Default Brightness where
data LightAttributes = LightAttributes
{ lightBrightness :: Maybe Brightness
, lightColorTemperature :: Maybe Int
, lightTransition :: Maybe Double
}
deriving (Show, Generic)
instance Default LightAttributes where
formatLightAttributes :: LightAttributes -> Maybe Value
formatLightAttributes s = toObject $ catMaybes
[ ["transition" .= x | x <- lightTransition s]
, ["color_temp_kelvin" .= k | k <- lightColorTemperature s]
, ["brightness" .= b | BrightnessAbsolute b <- lightBrightness s]
, ["brightness_pct" .= b | BrightnessPercent b <- lightBrightness s]
]
where
toObject :: [Pair] -> Maybe Value
toObject [] = Nothing
toObject xs = Just $ object xs
data LightCommand
= Off
| On LightAttributes
light :: [Target] -> LightCommand -> Service
light targets (On settings) = Service
{ serviceDomain="light"
, serviceName= "turn_on"
, serviceData= formatLightAttributes settings
, serviceTarget=targets
}
light targets Off = Service
{ serviceDomain="light"
, serviceName= "turn_off"
, serviceData=Nothing
, serviceTarget=targets
}
@@ -0,0 +1,23 @@
module HomeAssistant.Controller.Light.Mode
( LightingMode(..)
, toLightingMode
, lightingModeEvents
) where
import HomeAssistant.Controller.Effect (HASS)
import HomeAssistant.Controller.Presence (Presence (..))
import qualified AFRP
import Control.Arrow (Arrow(..), (>>>))
import GHC.Generics (Generic)
import Data.Serialize (Serialize)
data LightingMode = LightingOn | LightingOff | LightingSleep
deriving (Eq, Show, Generic)
instance Serialize LightingMode
toLightingMode :: Presence -> LightingMode
toLightingMode Occupied = LightingOn
toLightingMode Unoccupied = LightingOff
lightingModeEvents :: HASS Presence (AFRP.Event LightingMode)
lightingModeEvents = AFRP.changes >>> arr (fmap toLightingMode)
@@ -0,0 +1,52 @@
{-# LANGUAGE Arrows #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE StrictData #-}
module HomeAssistant.Controller.Light.Observation
( LightObservation(..)
, observedLight
, lightBrightnessEvent
, lightTemperatureEvent
) where
import AFRP (Event, hold)
import Control.Arrow (arr, returnA)
import Control.Category ((>>>), (.))
import Control.Lens ((^?))
import Data.Aeson (Value)
import Data.Aeson.Lens (key, _Integral)
import qualified Data.Text as T
import GHC.Generics (Generic)
import Data.Serialize (Serialize)
import HomeAssistant.Controller.Entity (entityBool, entityChangeEvent)
import HomeAssistant.Controller.Effect (HASS)
import Prelude hiding ((.))
lightBrightnessEvent :: T.Text -> HASS (Event Value) (Event (Maybe Int))
lightBrightnessEvent entityId =
entityChangeEvent entityId
>>> arr (fmap eventBrightness)
where
eventBrightness v = v ^? key "event" . key "variables" . key "trigger" . key "to_state" . key "attributes" . key "brightness" . _Integral
lightTemperatureEvent :: T.Text -> HASS (Event Value) (Event (Maybe Int))
lightTemperatureEvent entityId =
entityChangeEvent entityId
>>> arr (fmap eventTemperature)
where
eventTemperature v = v ^? key "event" . key "variables" . key "trigger" . key "to_state" . key "attributes" . key "color_temp_kelvin" . _Integral
data LightObservation = LightObservation
{ observedOn :: Bool
, observedBrightness :: Maybe Int
, observedTemperature :: Maybe Int
}
deriving (Show, Generic, Eq)
instance Serialize LightObservation
observedLight :: T.Text -> HASS (Event Value) LightObservation
observedLight entityId = proc ev -> do
e <- hold False . entityBool entityId -< ev
b <- hold Nothing . lightBrightnessEvent entityId -< ev
t <- hold Nothing . lightTemperatureEvent entityId -< ev
returnA -< LightObservation e b t
+10 -17
View File
@@ -2,26 +2,19 @@
{-# LANGUAGE Arrows #-} {-# LANGUAGE Arrows #-}
module HomeAssistant.Controller.Livingroom where module HomeAssistant.Controller.Livingroom where
import HomeAssistant.Controller (HASS, Presence (..), Target (..), presence, callServiceDyn, light, Light (..), traceEvent, callService, activateScene) import HomeAssistant.Controller (HASS, Presence (..), Target (..), presence, callServiceDyn, light, LightCommand (..), traceEvent, callService, activateScene)
import HomeAssistant.Controller.Light.Mode (LightingMode (..), lightingModeEvents)
import qualified AFRP import qualified AFRP
import Control.Arrow ((>>>), Arrow (..), returnA) import Control.Arrow ((>>>), Arrow (..), returnA)
import Data.Aeson (Value) import Data.Aeson (Value)
import Prelude hiding ((.)) import Prelude hiding ((.))
import Control.Category ((.)) import Control.Category ((.))
import Data.Time (LocalTime(..), toGregorian, TimeOfDay (..)) import Data.Time (LocalTime(..), toGregorian, TimeOfDay (..))
import Data.Default (def)
data Lights = LightsOn | LightsOff
deriving (Show)
livingroomPresence :: HASS (AFRP.Event Value) Presence livingroomPresence :: HASS (AFRP.Event Value) Presence
livingroomPresence = presence "binary_sensor.occupancy_olohuone_derived" >>> AFRP.hold Unoccupied livingroomPresence = presence "binary_sensor.occupancy_olohuone_derived" >>> AFRP.hold Unoccupied
eventLights :: HASS Presence (AFRP.Event Lights)
eventLights = AFRP.changes >>> arr (fmap presenceLights)
where
presenceLights Occupied = LightsOn
presenceLights Unoccupied = LightsOff
-- There's a small race condition / corner case bug in the og implementation -- There's a small race condition / corner case bug in the og implementation
-- I have a couple of lights in the Livingroom -- I have a couple of lights in the Livingroom
@@ -38,16 +31,16 @@ eventLights = AFRP.changes >>> arr (fmap presenceLights)
-- With that in mind, I'll be explicitly controlling the two lights, without any scene shenanigans -- With that in mind, I'll be explicitly controlling the two lights, without any scene shenanigans
lights :: [Target] livingroomLightTargets :: [Target]
lights = [EntityId "light.livingroom_ceiling", EntityId "light.livingroom_sofa"] livingroomLightTargets = [EntityId "light.livingroom_ceiling", EntityId "light.livingroom_sofa"]
livingroomPresenceController :: HASS (AFRP.Event Value) () livingroomPresenceController :: HASS (AFRP.Event Value) ()
livingroomPresenceController = proc x -> do livingroomPresenceController = proc x -> do
ev <- eventLights . livingroomPresence -< x ev <- lightingModeEvents . livingroomPresence -< x
traceEvent -< ev traceEvent -< ev
case ev of case ev of
AFRP.Event LightsOn -> callServiceDyn (light lights) -< On Nothing AFRP.Event LightingOn -> callServiceDyn "Lights on" (light livingroomLightTargets) -< On def
AFRP.Event LightsOff -> callServiceDyn (light lights) -< Off AFRP.Event LightingOff -> callServiceDyn "Lights off" (light livingroomLightTargets) -< Off
_ -> returnA -< () _ -> returnA -< ()
returnA -< () returnA -< ()
@@ -95,6 +88,6 @@ livingroomPlantLights = (season &&& tod)
where where
setLights = proc mode -> do setLights = proc mode -> do
case mode of case mode of
AFRP.Event Growth -> callService (activateScene "scene.olohuoneen_kasvivalo") -< () AFRP.Event Growth -> callService "scene.olohuoneen_kasvivalo" (activateScene "scene.olohuoneen_kasvivalo") -< ()
AFRP.Event Ambience -> callService (activateScene "scene.kasvivalo_iltatila") -< () AFRP.Event Ambience -> callService "scene.kasvivalo_iltatila" (activateScene "scene.kasvivalo_iltatila") -< ()
_ -> returnA -< () _ -> returnA -< ()
+55
View File
@@ -0,0 +1,55 @@
module HomeAssistant.Controller.Presence
( Presence(..)
, presence
, Motion(..)
, motion
, motionToPresence
) where
import AFRP (Event, hold, lMerge, waitFor, tag, edge)
import Control.Arrow (arr, (&&&))
import Control.Category ((>>>))
import Data.Aeson (Value)
import qualified Data.Text as T
import Data.Bool (bool)
import Data.Serialize (Serialize)
import GHC.Generics (Generic)
import Data.Time (NominalDiffTime)
import HomeAssistant.Controller.Entity (entityBool)
import HomeAssistant.Controller.Effect (HASS)
data Presence = Occupied | Unoccupied
deriving (Show, Eq, Generic)
instance Serialize Presence
presence :: T.Text -> HASS (Event Value) (Event Presence)
presence entityId = entityBool entityId
>>> arr (fmap (bool Unoccupied Occupied))
data Motion = MotionDetected | MotionNotDetected | MotionUnknown
deriving (Show, Eq, Generic)
motion :: T.Text -> HASS (Event Value) Motion
motion entityId = entityBool entityId
>>> arr (fmap (bool MotionNotDetected MotionDetected))
>>> hold MotionUnknown
-- 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 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)
instance Serialize Motion
-1
View File
@@ -1,4 +1,3 @@
{-# LANGUAGE Arrows #-}
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE OverloadedStrings #-}
module HomeAssistant.Controller.Ruuvi module HomeAssistant.Controller.Ruuvi
( Ruuvi(..) ( Ruuvi(..)
+21
View File
@@ -0,0 +1,21 @@
{-# LANGUAGE OverloadedStrings #-}
module HomeAssistant.Controller.Scene
( activateScene
, activateSceneWith
) where
import Data.Aeson (Value)
import qualified Data.Text as T
import HomeAssistant.Controller.Service (Service (..), Target (..))
activateScene :: T.Text -> Service
activateScene sceneId = activateSceneWith sceneId Nothing
activateSceneWith :: T.Text -> Maybe Value -> Service
activateSceneWith sceneId d = Service
{ serviceDomain="scene"
, serviceName= "turn_on"
, serviceTarget= [EntityId sceneId]
, serviceData = d
}
+18
View File
@@ -0,0 +1,18 @@
module HomeAssistant.Controller.Service
( Service(..)
, Target(..)
) where
import Data.Aeson (Value)
import qualified Data.Text as T
data Target = EntityId !T.Text | AreaId !T.Text
deriving (Show,Eq,Ord)
data Service = Service
{ serviceDomain :: T.Text
, serviceName :: T.Text
, serviceData :: Maybe Value
, serviceTarget :: [Target]
}
deriving (Show, Eq)
+14
View File
@@ -0,0 +1,14 @@
{-# LANGUAGE OverloadedStrings #-}
module HomeAssistant.Controller.Switch (switchService) where
import Data.Bool (bool)
import HomeAssistant.Controller.Service (Service (..), Target)
switchService :: [Target] -> Bool -> Service
switchService targets b = Service
{ serviceDomain="switch"
, serviceName= bool "turn_off" "turn_on" b
, serviceData=Nothing
, serviceTarget=targets
}
+93 -75
View File
@@ -4,45 +4,51 @@
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE OverloadedStrings #-}
module HomeAssistant.Runtime module HomeAssistant.Runtime
( defaultMain ( defaultMain,
, step step,
, CallIdGen CallIdGen,
, mkCallIdGen mkCallIdGen,
, dryRunHassEval dryRunHassEval,
, Controller(..) Controller (..),
, runController runController,
) where )
where
import AFRP (Event (..), Mealy (..), Request (..), Auto, stepAutoSerializing, load, DecodedAuto (..)) import AFRP (Auto, DecodedAuto (..), Event (..), Mealy (..), Request (..), load, stepAutoSerializing)
import Control.Concurrent.STM (atomically, dupTChan, readTChan) import Control.Concurrent.STM (atomically, dupTChan, readTChan)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Data.Aeson (Value) import Data.Aeson (Value)
import qualified Data.Text as T import Data.Foldable (forM_)
import Data.Maybe (fromMaybe)
import Data.Text qualified as T
import Data.Time (getCurrentTime, getCurrentTimeZone) import Data.Time (getCurrentTime, getCurrentTimeZone)
import Data.UUID (UUID, toText)
import Data.UUID.V4 qualified as UUID.V4
import Data.Void (Void) import Data.Void (Void)
import GHC.Stack (HasCallStack)
import HomeAssistant.Controller (HASS, HASSEff (..)) import HomeAssistant.Controller (HASS, HASSEff (..))
import HomeAssistant.Controller.Bedroom (bedroomButtonController, bedroomDrawerController, bedroomPresenceController, humidifierController)
import HomeAssistant.Controller.Children (childrenBedroomButtonController, schoolLightController, childrenAirFilterController)
import HomeAssistant.Controller.Hallway (hallwayLightsController)
import HomeAssistant.Controller.Kitchen (kitchenMotionController)
import HomeAssistant.Controller.Livingroom (livingroomPlantLights, livingroomPresenceController)
import HomeAssistant.Runtime.Bus import HomeAssistant.Runtime.Bus
import HomeAssistant.Runtime.Connection (readerAction, writerAction)
import HomeAssistant.Runtime.Flags (loadFlags) import HomeAssistant.Runtime.Flags (loadFlags)
import HomeAssistant.Runtime.Connection (writerAction, readerAction) import HomeAssistant.Runtime.Metrics qualified
import HomeAssistant.Runtime.RateLimit (registerRateLimitMetrics, slidingWindowLimiter)
import HomeAssistant.Runtime.Supervisor (supervised)
import HttpServer qualified
import Katip (KatipContext, Namespace (Namespace), Severity (..), logF, logLocM, ls, runKatipContextT, runKatipT, sl, katipAddNamespace)
import Network.Socket (withSocketsDo) import Network.Socket (withSocketsDo)
import System.Environment (getEnv, lookupEnv) import System.Environment (getEnv, lookupEnv)
import HomeAssistant.Controller.Bedroom (bedroomPresenceController, bedroomButtonController, bedroomDrawerController, humidifierController)
import Data.UUID (UUID, toText)
import qualified Data.UUID.V4 as UUID.V4
import Katip (runKatipT, logF, sl, Severity (..), ls, Namespace (Namespace), runKatipContextT)
import Control.Monad.IO.Class (liftIO, MonadIO)
import HomeAssistant.Controller.Children (schoolLightController, childrenBedroomButtonController)
import Data.Maybe (fromMaybe)
import qualified System.Metrics
import qualified HomeAssistant.Runtime.Metrics
import System.FilePath ((</>)) import System.FilePath ((</>))
import System.Metrics qualified
import Text.Read (readMaybe) import Text.Read (readMaybe)
import HomeAssistant.Controller.Kitchen (kitchenMotionController)
import HomeAssistant.Controller.Livingroom (livingroomPresenceController, livingroomPlantLights)
import HomeAssistant.Runtime.RateLimit (slidingWindowLimiter, registerRateLimitMetrics)
import UnliftIO.Async import UnliftIO.Async
import HomeAssistant.Runtime.Supervisor (supervised) import Control.Monad.Catch (MonadCatch)
import HomeAssistant.Controller.Hallway (hallwayLightsController) import Control.Exception.Annotated (checkpoint, Annotation (..))
import qualified HttpServer import AFRP.Diagram (renderF)
step :: (MonadIO m) => FilePath -> T.Text -> UUID -> Auto m a b -> a -> m (b, Auto m a b) 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 step path name trace st a = do
@@ -55,79 +61,91 @@ data Controller = forall b. Controller T.Text (HASS (Event Value) b)
controllers :: [Controller] controllers :: [Controller]
controllers = controllers =
[ Controller "bedroom-presence" bedroomPresenceController [ Controller "bedroom-presence" bedroomPresenceController,
, Controller "bedroom-button" bedroomButtonController Controller "bedroom-button" bedroomButtonController,
, Controller "bedroom-drawer" bedroomDrawerController Controller "bedroom-drawer" bedroomDrawerController,
, Controller "bedroom-humidifier" humidifierController Controller "bedroom-humidifier" humidifierController,
, Controller "school-light-controller" schoolLightController Controller "school-light-controller" schoolLightController,
, Controller "kitchen-motion-controller" kitchenMotionController Controller "kitchen-motion-controller" kitchenMotionController,
, Controller "livingroom-presence" livingroomPresenceController Controller "livingroom-presence" livingroomPresenceController,
, Controller "hallway-motion-controller" hallwayLightsController Controller "hallway-motion-controller" hallwayLightsController,
, Controller "children-button" childrenBedroomButtonController 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 -- | Steps the machine for every inbound message; service calls go to the
-- bus. A restart re-dups the inbound channel and starts from the machine's -- bus. A restart re-dups the inbound channel and starts from the machine's
-- initial state; messages broadcast during the restart window are lost. -- initial state; messages broadcast during the restart window are lost.
runController :: MonadIO m => FilePath -> Bus -> Controller -> m Void runController :: forall m. (HasCallStack, MonadCatch m, KatipContext m, MonadIO m) => FilePath -> Bus -> Controller -> m Void
runController rootDir bus (Controller name machine ) = liftIO $ do runController rootDir bus (Controller name machine) = checkpoint (Annotation name) $ katipAddNamespace ns $ do
inbound <- atomically (dupTChan (busInbound bus)) inbound <- liftIO $ atomically (dupTChan (busInbound bus))
let ns = Namespace [name] let workerDefinition = runMealy machine (channelHassEval @m bus)
let workerDefinition = runMealy machine (runKatipContextT (busLogEnv bus) () ns . channelHassEval bus) let path = rootDir </> T.unpack name
let path = rootDir </> T.unpack name worker <-
worker <- load path workerDefinition >>= \case load path workerDefinition >>= \case
Decoded a -> pure a Decoded a -> pure a
FailDecode err a -> a <$ putStrLn ("Failed to load (" <> T.unpack name <> "): " <> err) FailDecode err a -> a <$ logLocM WarningS (ls ("Failed to load (" <> T.unpack name <> "): " <> err))
go path inbound worker go path inbound worker
where where
ns = Namespace [name]
go path inbound f = do go path inbound f = do
msg <- atomically (readTChan inbound) msg <- liftIO $ atomically (readTChan inbound)
uuid <- UUID.V4.nextRandom uuid <- liftIO UUID.V4.nextRandom
(_, next) <- step path name uuid f msg (_, next) <- step path name uuid f msg
go path inbound next go path inbound next
lookupPort :: IO Int lookupPort :: (MonadFail m, MonadIO m) => m Int
lookupPort = do lookupPort = do
m <- lookupEnv "HA_METRICS_PORT" m <- liftIO (lookupEnv "HA_METRICS_PORT")
case m of case m of
Nothing -> pure 8124 Nothing -> pure 8124
Just s -> case readMaybe s of Just s -> case readMaybe s of
Just p | p >= 1 && p <= 65535 -> pure p Just p | p >= 1 && p <= 65535 -> pure p
_ -> fail ("HA_METRICS_PORT must be a port in 1..65535: " <> s) _ -> fail ("HA_METRICS_PORT must be a port in 1..65535: " <> s)
defaultMain :: IO () defaultMain :: IO ()
defaultMain = withSocketsDo $ do defaultMain =
severity <- maybe InfoS (const DebugS) <$> lookupEnv "HA_DEBUG" withSocketsDo $
store <- System.Metrics.newStore getSeverity >>= \s -> withLogEnv s $ \le -> runKatipContextT le () mempty $ do
System.Metrics.registerGcMetrics store logLocM InfoS "Hello world"
appMetrics <- HomeAssistant.Runtime.Metrics.registerAppMetrics store store <- liftIO System.Metrics.newStore
rateLimitMetrics <- registerRateLimitMetrics store liftIO $ System.Metrics.registerGcMetrics store
rootPath <- fromMaybe "/tmp/" <$> lookupEnv "HA_LIB_DIR" appMetrics <- liftIO $ HomeAssistant.Runtime.Metrics.registerAppMetrics store
let allNames = map (\(Controller n _) -> n) controllers rateLimitMetrics <- registerRateLimitMetrics store
flags <- loadFlags rootPath allNames rootPath <- fromMaybe "/tmp/" <$> liftIO (lookupEnv "HA_LIB_DIR")
withBus severity appMetrics flags $ \bus -> do let allNames = map (\(Controller n _) -> n) controllers
token <- getEnv "HA_TOKEN" flags <- loadFlags rootPath allNames
host <- getEnv "HA_HOST" withBus le appMetrics flags $ \bus -> do
let rrdPath = rootPath </> "hass-controller.rrd" token <- liftIO $ getEnv "HA_TOKEN"
rrdtool <- fromMaybe "rrdtool" <$> lookupEnv "HA_RRDTOOL" host <- liftIO $ getEnv "HA_HOST"
metricsPort <- lookupPort let rrdPath = rootPath </> "hass-controller.rrd"
writerLimiter <- slidingWindowLimiter rateLimitMetrics 10 20 rrdtool <- fromMaybe "rrdtool" <$> liftIO (lookupEnv "HA_RRDTOOL")
let ents = foldMap (\(Controller _ m) -> entities m) controllers metricsPort <- lookupPort
workers = writerLimiter <- slidingWindowLimiter rateLimitMetrics 10 20
[ ("reader", readerAction host 8123 token ents bus) forM_ controllers $ \(Controller n m) ->
, ("writer", writerAction writerLimiter bus) logLocM InfoS $ ls $ n <> ": " <> fromMaybe "" (runDiagramC m renderF)
, ("metrics", HomeAssistant.Runtime.Metrics.metricsAction store rrdPath rrdtool) let ents = foldMap (\(Controller _ m) -> entities m) controllers
, ("metrics-http", HttpServer.runHttpServer (busLogEnv bus) rrdPath rrdtool (busFlags bus) metricsPort) workers =
] ++ [ (name, runController rootPath bus c) | c@(Controller name _) <- controllers ] [ ("reader", readerAction host 8123 token ents bus),
runKatipContextT (busLogEnv bus) () mempty $ ("writer", writerAction writerLimiter bus),
mapConcurrently_ (uncurry supervised) workers ("metrics", HomeAssistant.Runtime.Metrics.metricsAction store rrdPath rrdtool),
("metrics-http", HttpServer.runHttpServer (busLogEnv bus) rrdPath rrdtool (busFlags bus) metricsPort)
]
++ [(name, runController rootPath bus c) | c@(Controller name _) <- controllers]
runKatipContextT (busLogEnv bus) () mempty $
mapConcurrently_ (uncurry supervised) workers
where
getSeverity = maybe InfoS (const DebugS) <$> lookupEnv "HA_DEBUG"
dryRunHassEval :: Namespace -> Bus -> HASSEff a -> IO a dryRunHassEval :: Namespace -> Bus -> HASSEff a -> IO a
dryRunHassEval ns bus = \case dryRunHassEval ns bus = \case
CallService req x -> runKatipT (busLogEnv bus) $ do CallService req x -> runKatipT (busLogEnv bus) $ do
callId <- liftIO $ generateCallId (busGen bus) callId <- liftIO $ generateCallId (busGen bus)
logF (sl "traceId" (toText (requestTraceId req))) ns DebugS (ls $ show (callId, x)) logF (sl "traceId" (toText (requestTraceId req))) ns DebugS (ls $ show (callId, x))
CallServices req xs -> runKatipT (busLogEnv bus) $ forM_ xs $ \x -> do
callId <- liftIO $ generateCallId (busGen bus)
logF (sl "traceId" (toText (requestTraceId req))) ns DebugS (ls $ show (callId, x))
Debug x -> runKatipT (busLogEnv bus) $ do Debug x -> runKatipT (busLogEnv bus) $ do
logF () ns DebugS (ls $ show x) logF () ns DebugS (ls $ show x)
Trace req x -> runKatipT (busLogEnv bus) $ do Trace req x -> runKatipT (busLogEnv bus) $ do
+40 -21
View File
@@ -1,5 +1,6 @@
{-# LANGUAGE LambdaCase #-} {-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
module HomeAssistant.Runtime.Bus module HomeAssistant.Runtime.Bus
( Bus(..) ( Bus(..)
@@ -9,6 +10,7 @@ module HomeAssistant.Runtime.Bus
, recordInbound , recordInbound
, recordOutbound , recordOutbound
, channelHassEval , channelHassEval
, withLogEnv
) where ) where
import Control.Concurrent.STM import Control.Concurrent.STM
@@ -31,9 +33,11 @@ import System.IO (stdout)
import System.Metrics.Counter (inc) import System.Metrics.Counter (inc)
import Data.UUID (toText) import Data.UUID (toText)
import AFRP (Request(..), Event(..)) import AFRP (Request(..), Event(..))
import Control.Monad (when)
import Control.Monad.IO.Class (MonadIO, liftIO) import Control.Monad.IO.Class (MonadIO, liftIO)
import HomeAssistant.Runtime.Flags (Flags, isEnabled) import HomeAssistant.Runtime.Flags (Flags)
import Katip.Scribes.Journal (mkJournalScribe)
import System.Environment (lookupEnv)
import Data.Maybe (isJust)
-- | Shared runtime state: inbound is a broadcast channel (controllers -- | Shared runtime state: inbound is a broadcast channel (controllers
-- read from 'dupTChan' copies), outbound queues service calls for the -- read from 'dupTChan' copies), outbound queues service calls for the
@@ -48,21 +52,35 @@ data Bus = Bus
, busFlags :: Flags , busFlags :: Flags
} }
withBus :: Severity -> AppMetrics -> Flags -> (Bus -> IO a) -> IO a withLogEnv :: Severity -> (LogEnv -> IO a) -> IO a
withBus severity metrics flags callback = do withLogEnv severity f = do
handleScribe <- mkHandleScribe ColorIfTerminal stdout (permitItem severity) V2 let makeLogEnv = registerJournalScribe =<< registerHandleScribe =<< initLogEnv "hass-controller" "production"
let makeLogEnv = registerScribe "stdout" handleScribe defaultScribeSettings =<< initLogEnv "hass-controller" "production"
-- closeScribes will stop accepting new logs, flush existing ones and clean up resources -- closeScribes will stop accepting new logs, flush existing ones and clean up resources
bracket makeLogEnv closeScribes $ \le -> do bracket makeLogEnv closeScribes $ \le -> f le
bus <- Bus where
<$> newBroadcastTChanIO registerJournalScribe :: LogEnv -> IO LogEnv
<*> newTChanIO registerJournalScribe le = do
<*> newTVarIO Nothing journalScribe <- mkJournalScribe (permitItem severity) V2
<*> mkCallIdGen 0 registerScribe "journalctl" journalScribe defaultScribeSettings le
<*> pure le registerHandleScribe le = do
<*> pure metrics systemdUnit <- isJust <$> lookupEnv "HA_CONTROLLER_SYSTEMD"
<*> pure flags if systemdUnit
callback bus then pure le -- ignore stdout when running in systemd
else do
handleScribe <- mkHandleScribe ColorIfTerminal stdout (permitItem severity) V2
registerScribe "stdout" handleScribe defaultScribeSettings le
withBus :: MonadIO m => LogEnv -> AppMetrics -> Flags -> (Bus -> m a) -> m a
withBus le metrics flags callback = do
bus <- Bus
<$> liftIO newBroadcastTChanIO
<*> liftIO newTChanIO
<*> liftIO (newTVarIO Nothing)
<*> liftIO (mkCallIdGen 0)
<*> pure le
<*> pure metrics
<*> pure flags
callback bus
recordInbound :: Bus -> IO () recordInbound :: Bus -> IO ()
recordInbound bus = inc (amTriggersIn (busMetrics bus)) recordInbound bus = inc (amTriggersIn (busMetrics bus))
@@ -70,15 +88,16 @@ recordInbound bus = inc (amTriggersIn (busMetrics bus))
recordOutbound :: Bus -> IO () recordOutbound :: Bus -> IO ()
recordOutbound bus = inc (amServicesOut (busMetrics bus)) recordOutbound bus = inc (amServicesOut (busMetrics bus))
channelHassEval :: (MonadIO m, KatipContext m) => Bus -> HASSEff a -> m a channelHassEval :: forall m a. (MonadIO m, KatipContext m) => Bus -> HASSEff a -> m a
channelHassEval bus = \case channelHassEval bus = \case
CallService req svc -> katipAddContext (sl "traceId" (toText (requestTraceId req))) $ do CallService req svc -> emit req svc
logFM DebugS (ls $ show svc) CallServices req svcs -> mapM_ (emit req) svcs
enabled <- isEnabled (busFlags bus) (requestHandler req)
when enabled $ liftIO $ atomically $ writeTChan (busOutbound bus) (req, svc)
Debug x -> logFM DebugS (ls $ show x) Debug x -> logFM DebugS (ls $ show x)
Trace req x -> katipAddContext (sl "traceId" (toText (requestTraceId req))) $ Trace req x -> katipAddContext (sl "traceId" (toText (requestTraceId req))) $
logFM InfoS (ls $ show x) logFM InfoS (ls $ show x)
where
emit :: Request -> Service -> m ()
emit req svc = liftIO $ atomically $ writeTChan (busOutbound bus) (req, svc)
newtype CallIdGen = CallIdGen { generateCallId :: IO Int } newtype CallIdGen = CallIdGen { generateCallId :: IO Int }
+35 -22
View File
@@ -4,6 +4,7 @@
module HomeAssistant.Runtime.Connection module HomeAssistant.Runtime.Connection
( readerAction ( readerAction
, writerAction , writerAction
, dispatchService
, encodeService , encodeService
, isTriggerEvent , isTriggerEvent
) where ) where
@@ -16,9 +17,7 @@ import Control.Concurrent.STM
, writeTChan , writeTChan
, writeTVar , writeTVar
) )
import Control.Concurrent.Async (race)
import Control.Concurrent (threadDelay) import Control.Concurrent (threadDelay)
import Control.Exception (onException)
import Control.Exception.Annotated (throw) import Control.Exception.Annotated (throw)
import Control.Lens ((^?)) import Control.Lens ((^?))
import Control.Monad (forever, forM_, when) import Control.Monad (forever, forM_, when)
@@ -29,27 +28,30 @@ import qualified Data.Text as T
import Data.Void (Void) import Data.Void (Void)
import HomeAssistant.Controller (Service (..), Target (..)) import HomeAssistant.Controller (Service (..), Target (..))
import HomeAssistant.Runtime.Bus import HomeAssistant.Runtime.Bus
import HomeAssistant.Runtime.Flags (isEnabled)
import HomeAssistant.Runtime.Supervisor (Fatal (..)) import HomeAssistant.Runtime.Supervisor (Fatal (..))
import qualified Network.WebSockets as WS import qualified Network.WebSockets as WS
import Katip (sl, logFM, Severity (..), ls, KatipContext, katipAddNamespace, katipAddContext) import Katip (sl, logFM, Severity (..), ls, Namespace (Namespace), KatipContext, katipAddNamespace, katipAddContext, logLocM)
import Data.UUID (toText) import Data.UUID (toText)
import AFRP (Request(..), Event(..)) import AFRP (Request(..), Event(..))
import Control.Monad.IO.Class (liftIO, MonadIO) import Control.Monad.IO.Class (liftIO, MonadIO)
import HomeAssistant.Runtime.RateLimit (RateLimited, RateLimiter, runRateLimited) 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 (MonadCatch, onException)
-- | Connect, authenticate, subscribe, then receive and broadcast forever. -- | Connect, authenticate, subscribe, then receive and broadcast forever.
-- Restarting this action reconnects. All setup sends happen before the -- Restarting this action reconnects. All setup sends happen before the
-- connection is published in the bus, so only the writer sends afterwards. -- connection is published in the bus, so only the writer sends afterwards.
readerAction :: MonadIO m => String -> Int -> String -> S.Set T.Text -> Bus -> m Void readerAction :: (MonadCatch m, HasCallStack, KatipContext m, MonadUnliftIO m, MonadIO m) => String -> Int -> String -> S.Set T.Text -> Bus -> m Void
readerAction host port token ents bus = liftIO $ readerAction host port token ents bus = katipAddNamespace "receiver" $ withRunInIO $ \rio ->
WS.runClient host port "/api/websocket" $ \conn -> do WS.runClient host port "/api/websocket" $ \conn -> rio $ do
handshake conn token liftIO $ handshake conn token
subscribe bus conn ents subscribe bus conn ents
atomically $ writeTVar (busConn bus) (Just conn) liftIO $ atomically $ writeTVar (busConn bus) (Just conn)
putStrLn "[reader] connected" logLocM InfoS "connected"
-- Unpublish on exit so the writer blocks and the backlog survives the outage. -- Unpublish on exit so the writer blocks and the backlog survives the outage.
receiveLoop bus conn `onException` atomically (writeTVar (busConn bus) Nothing) receiveLoop bus conn `onException` liftIO (atomically (writeTVar (busConn bus) Nothing))
handshake :: WS.Connection -> String -> IO () handshake :: WS.Connection -> String -> IO ()
handshake conn token = do handshake conn token = do
@@ -71,12 +73,12 @@ expectType expected msg =
isTriggerEvent :: Value -> Bool isTriggerEvent :: Value -> Bool
isTriggerEvent v = v ^? key "type" . _String == Just "event" isTriggerEvent v = v ^? key "type" . _String == Just "event"
subscribe :: Bus -> WS.Connection -> S.Set T.Text -> IO () subscribe :: HasCallStack => KatipContext m => Bus -> WS.Connection -> S.Set T.Text -> m ()
subscribe bus conn ents = subscribe bus conn ents =
forM_ (S.toList ents) $ \entityId -> do forM_ (S.toList ents) $ \entityId -> do
print entityId logLocM InfoS $ ls entityId
sid <- generateCallId (busGen bus) sid <- liftIO $ generateCallId (busGen bus)
WS.sendTextData conn $ encode $ object liftIO $ WS.sendTextData conn $ encode $ object
[ "id" .= sid [ "id" .= sid
, "type" .= ("subscribe_trigger" :: T.Text) , "type" .= ("subscribe_trigger" :: T.Text)
, "trigger" .= object , "trigger" .= object
@@ -91,14 +93,14 @@ subscribe bus conn ents =
-- Each read races a one-second timeout: a timeout broadcasts 'Tick' so -- Each read races a one-second timeout: a timeout broadcasts 'Tick' so
-- time-based primitives (debounce, rollup, fixed, ...) keep advancing -- time-based primitives (debounce, rollup, fixed, ...) keep advancing
-- even when no state changes arrive. -- even when no state changes arrive.
receiveLoop :: Bus -> WS.Connection -> IO Void receiveLoop :: (HasCallStack, MonadUnliftIO m, KatipContext m) => Bus -> WS.Connection -> m Void
receiveLoop bus conn = forever $ do receiveLoop bus conn = forever $ do
winner <- race (threadDelay 1_000_000) (WS.receiveData conn) winner <- race (liftIO $ threadDelay 1_000_000) (liftIO $ WS.receiveData conn)
case winner of case winner of
Left () -> atomically $ writeTChan (busInbound bus) Tick Left () -> liftIO $ atomically $ writeTChan (busInbound bus) Tick
Right msg -> case eitherDecode msg of Right msg -> case eitherDecode msg of
Left err -> putStrLn $ "[reader] skipping undecodable message: " <> err Left err -> logLocM WarningS $ ls $ "skipping undecodable message: " <> err
Right v -> do Right v -> liftIO $ do
when (isTriggerEvent v) (recordInbound bus) when (isTriggerEvent v) (recordInbound bus)
atomically $ writeTChan (busInbound bus) (Event v) atomically $ writeTChan (busInbound bus) (Event v)
@@ -122,9 +124,20 @@ sendWithId bus conn svc = katipAddNamespace "connection" $ do
writerAction :: (MonadIO m, KatipContext m, MonadCatch m) => RateLimiter -> Bus -> m Void writerAction :: (MonadIO m, KatipContext m, MonadCatch m) => RateLimiter -> Bus -> m Void
writerAction rateLimiter bus = forever $ do writerAction rateLimiter bus = forever $ do
(request, svc) <- liftIO $ atomically $ readTChan (busOutbound bus) (request, svc) <- liftIO $ atomically $ readTChan (busOutbound bus)
katipAddContext (sl "traceId" (toText (requestTraceId request))) $ do katipAddContext (sl "traceId" (toText (requestTraceId request))) $
katipAddNamespace (Namespace [requestHandler request]) $
dispatchService rateLimiter bus request svc
-- | Sends the service call, or logs and drops it when its handler is disabled.
dispatchService
:: (MonadIO m, KatipContext m, MonadCatch m)
=> RateLimiter -> Bus -> Request -> Service -> m ()
dispatchService rateLimiter bus request svc = do
enabled <- isEnabled (busFlags bus) (requestHandler request)
let logPrefix = if enabled then "Calling: " else "Skipping: "
logFM InfoS (ls $ logPrefix <> show svc)
when enabled $ do
conn <- liftIO $ atomically $ readTVar (busConn bus) >>= maybe retry pure conn <- liftIO $ atomically $ readTVar (busConn bus) >>= maybe retry pure
-- runRateLimited rateLimiter $ sendWithId bus conn request svc
runRateLimited rateLimiter $ sendWithId bus conn svc runRateLimited rateLimiter $ sendWithId bus conn svc
encodeService :: Int -> Service -> Value encodeService :: Int -> Service -> Value
+16 -13
View File
@@ -12,7 +12,6 @@ module HomeAssistant.Runtime.Flags
import Control.Concurrent.MVar (MVar, newMVar, withMVar) import Control.Concurrent.MVar (MVar, newMVar, withMVar)
import Control.Concurrent.STM (TVar, atomically, newTVarIO, readTVarIO, stateTVar) import Control.Concurrent.STM (TVar, atomically, newTVarIO, readTVarIO, stateTVar)
import Control.Exception (IOException, handle)
import Control.Monad.IO.Class (MonadIO, liftIO) import Control.Monad.IO.Class (MonadIO, liftIO)
import qualified Conduit as C import qualified Conduit as C
import Conduit ((.|)) import Conduit ((.|))
@@ -24,8 +23,12 @@ import Data.Set (Set)
import qualified Data.Set as S import qualified Data.Set as S
import Data.Text (Text) import Data.Text (Text)
import System.FilePath ((</>)) import System.FilePath ((</>))
import System.IO (hPutStrLn, stderr)
import System.IO.Error (isDoesNotExistError) import System.IO.Error (isDoesNotExistError)
import GHC.Stack (HasCallStack)
import Katip (KatipContext, logLocM, Severity (..), ls)
import Control.Monad.Catch (MonadCatch, handle)
import Control.Exception (IOException)
import Data.Maybe (fromMaybe)
type Name = Text type Name = Text
@@ -36,14 +39,14 @@ data Flags = Flags
, flagsValidNames :: Set Text , flagsValidNames :: Set Text
} }
loadFlags :: MonadIO m => FilePath -> [Name] -> m Flags loadFlags :: (KatipContext m, MonadCatch m, MonadIO m) => FilePath -> [Name] -> m Flags
loadFlags rootPath allNames = liftIO $ do loadFlags rootPath allNames = do
let path = rootPath </> "handlers.json" let path = rootPath </> "handlers.json"
fileMap <- readFlagsFile path fileMap <- readFlagsFile path
let defaults = M.fromList [(n, True) | n <- allNames] let defaults = M.fromList [(n, True) | n <- allNames]
initial = M.unionWith (\fileVal _default -> fileVal) fileMap defaults initial = M.unionWith const fileMap defaults
tv <- newTVarIO initial tv <- liftIO $ newTVarIO initial
lock <- newMVar () lock <- liftIO $ newMVar ()
pure Flags pure Flags
{ flagsState = tv { flagsState = tv
, flagsLock = lock , flagsLock = lock
@@ -51,21 +54,21 @@ loadFlags rootPath allNames = liftIO $ do
, flagsValidNames = S.fromList allNames , flagsValidNames = S.fromList allNames
} }
readFlagsFile :: FilePath -> IO (Map Name Bool) readFlagsFile :: forall m. (HasCallStack, KatipContext m, MonadCatch m) => FilePath -> m (Map Name Bool)
readFlagsFile path = readFlagsFile path =
handle onMissingOrUnreadable $ do handle onMissingOrUnreadable $ do
decoded <- decodeFileStrict' path decoded <- liftIO $ decodeFileStrict' path
case decoded of case decoded of
Nothing -> do Nothing -> do
hPutStrLn stderr ("handlers.json is unparseable; treating all handlers as enabled: " <> path) logLocM WarningS $ ls ("handlers.json is unparseable; treating all handlers as enabled: " <> path)
pure mempty pure mempty
Just m -> pure (maybe mempty id m) Just m -> pure (fromMaybe mempty m)
where where
onMissingOrUnreadable :: IOException -> IO (Map Name Bool) onMissingOrUnreadable :: HasCallStack => IOException -> m (Map Name Bool)
onMissingOrUnreadable e onMissingOrUnreadable e
| isDoesNotExistError e = pure mempty | isDoesNotExistError e = pure mempty
| otherwise = do | otherwise = do
hPutStrLn stderr ("could not read handlers.json (" <> show e <> "); treating all handlers as enabled") logLocM WarningS $ ls ("could not read handlers.json (" <> show e <> "); treating all handlers as enabled")
pure mempty pure mempty
isEnabled :: MonadIO m => Flags -> Name -> m Bool isEnabled :: MonadIO m => Flags -> Name -> m Bool
+4 -3
View File
@@ -13,6 +13,7 @@ module HomeAssistant.Runtime.Graphing
, readProcessBytes , readProcessBytes
, Graph(..) , Graph(..)
, renderGraph , renderGraph
, rangeSuffix
) where ) where
import Control.Exception (evaluate) import Control.Exception (evaluate)
@@ -190,10 +191,10 @@ cfName = \case
defArgs :: FilePath -> Series -> [String] defArgs :: FilePath -> Series -> [String]
defArgs rrdPath series = defArgs rrdPath series =
[ "DEF:" ++ rawF ++ "=" ++ rrdPath ++ ":" ( "DEF:" ++ rawF ++ "=" ++ rrdPath ++ ":"
++ srcDs source ++ ":" ++ cfName (srcCF source) ++ srcDs source ++ ":" ++ cfName (srcCF source)
] )
++ transformArgs : transformArgs
where where
source = serSource series source = serSource series
alias = serAlias series alias = serAlias series
+4 -3
View File
@@ -38,12 +38,13 @@ data RateLimiter = RateLimiter
slidingWindowLimiter slidingWindowLimiter
:: RateLimitMetrics :: MonadIO m
=> RateLimitMetrics
-> NominalDiffTime -- ^ Within how many seconds -> NominalDiffTime -- ^ Within how many seconds
-> Int -- ^ How many requests we can make -> Int -- ^ How many requests we can make
-> IO RateLimiter -> m RateLimiter
slidingWindowLimiter metrics timeWindow size = do slidingWindowLimiter metrics timeWindow size = do
window <- newTVarIO [] window <- liftIO $ newTVarIO []
return $ RateLimiter metrics $ \(RateLimited action) -> do return $ RateLimiter metrics $ \(RateLimited action) -> do
now <- liftIO getPOSIXTime now <- liftIO getPOSIXTime
allowed <- liftIO $ atomically $ do allowed <- liftIO $ atomically $ do
+173 -18
View File
@@ -7,71 +7,225 @@ import Control.Monad.IO.Class (liftIO, MonadIO)
import qualified Data.ByteString as BS import qualified Data.ByteString as BS
import Data.Void (Void) import Data.Void (Void)
import Network.Wai.Handler.Warp (run) 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 Data.ByteString (ByteString)
import GHC.Generics (Generic) import GHC.Generics (Generic)
import Servant (Handler, err404) import Servant (Handler, err404, fieldLink, toUrlPiece)
import Control.Monad.Catch (throwM, catch, MonadCatch, MonadThrow, SomeException) import Control.Monad.Catch (throwM, catch, MonadCatch, MonadThrow, SomeException)
import Servant.Server (err500, ServerT) import Servant.Server (err500, ServerT)
import Data.Maybe (fromMaybe) import Data.Maybe (fromMaybe)
import Data.Map.Strict (Map) import Data.Map.Strict (Map)
import qualified Data.Set as S import qualified Data.Set as S
import Data.Text (Text) 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 Control.Exception.Annotated (checkpoint, Annotation (Annotation))
import Servant.Server.Generic (genericServeT) import Servant.Server.Generic (genericServeT)
import Network.Wai (Application) import Network.Wai (Application)
import Network.HTTP.Media ((//)) import Network.HTTP.Media ((//))
import HomeAssistant.Runtime.Graphing (Graph, Range (..), lookupGraph, graphs, renderGraph) import HomeAssistant.Runtime.Graphing (Graph (..), Range (..), lookupGraph, graphs, renderGraph, rangeSuffix)
import Katip (KatipContextT, Katip, runKatipContextT, LogEnv, KatipContext, ls, Severity (..), logFM) 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 data ImagePng
instance MimeRender ImagePng ByteString where instance MimeRender ImagePng GraphPng where
mimeRender _ = BS.fromStrict mimeRender _ (GraphPng bs) = BS.fromStrict bs
instance Accept ImagePng where instance Accept ImagePng where
contentType _ = "image" // "png" 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 data API mode = API
{ getMetrics :: mode :- "metrics" :> Capture "graph" Graph :> QueryParam "range" Range :> Get '[ImagePng] ByteString { getMetrics :: mode :- "metrics" :> Capture "graph" Graph :> QueryParam "range" Range :> Get '[ImagePng] GraphPng
, getFlags :: mode :- "flags" :> Get '[JSON] (Map Text Bool) , getStats :: mode :- "stats" :> HxRequest :> QueryParam "range" Range :> Get '[HTML] StatsPage
, putFlag :: mode :- "flags" :> Capture "name" Text :> ReqBody '[JSON] Bool :> Put '[JSON] (Map Text Bool) , 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 deriving Generic
newtype GraphPng = GraphPng ByteString
getFlagsHandler :: Flags -> LoggingHandler (Map Text Bool) newtype FlagValue = FlagValue Bool
getFlagsHandler flags = allFlags flags deriving FromJSON via Bool
putFlagHandler :: Flags -> Text -> Bool -> LoggingHandler (Map Text Bool) instance FromForm FlagValue where
putFlagHandler flags name val 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 | 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 setEnabled flags name val `catch` \e -> do
logFM ErrorS (ls ("failed to persist handler flag: " <> show (e :: SomeException))) logFM ErrorS (ls ("failed to persist handler flag: " <> show (e :: SomeException)))
throwM err500 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 getMetricsHandler rrdPath rrdtool graphMode mRange = checkpoint (Annotation (graphMode, mRange)) $ do
case lookupGraph graphs graphMode of case lookupGraph graphs graphMode of
Nothing -> throwM err404 Nothing -> throwM err404
Just spec -> do Just spec -> do
let range = fromMaybe OneDay mRange let range = fromMaybe OneDay mRange
g <- renderGraph rrdPath rrdtool spec range 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 -> API AsServer
server :: FilePath -> FilePath -> Flags -> ServerT (NamedRoutes API) LoggingHandler server :: FilePath -> FilePath -> Flags -> ServerT (NamedRoutes API) LoggingHandler
server rrdPath rrdtool flags = API server rrdPath rrdtool flags = API
{ getMetrics = getMetricsHandler rrdPath rrdtool { getMetrics = getMetricsHandler rrdPath rrdtool
, getStats = getStatsHandler
, getFlags = getFlagsHandler flags , getFlags = getFlagsHandler flags
, putFlag = putFlagHandler 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 :: LogEnv -> FilePath -> FilePath -> Flags -> Application
servantApp le rrdPath rrdtool flags = genericServeT (toHandler le) (server rrdPath rrdtool flags) 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 toHandler le (LoggingHandler k) = runKatipContextT le () "http" k
+70
View File
@@ -0,0 +1,70 @@
{-# LANGUAGE OverloadedStrings #-}
module Katip.Scribes.Journal where
import Data.Text.Lazy qualified as TL
import Data.Text.Lazy.Builder qualified as Builder
import Katip (Item (..), LogStr (..), PermitFunc, Scribe (..), Verbosity (..), permitItem, Severity (..), registerScribe, defaultScribeSettings, initLogEnv, closeScribes, runKatipContextT, logLocM, LogItem, Namespace (..), getThreadIdText, payloadObject, katipAddContext, sl, getEnvironment)
import Systemd.Journal qualified as J
import Control.Exception (bracket)
import GHC.Stack (HasCallStack)
import qualified Data.Text as T
import qualified Data.HashMap.Strict as HashMap
import qualified Data.Text.Encoding as TE
import qualified Data.Aeson as A
import qualified Data.ByteString.Lazy as BL
import qualified Data.Aeson.KeyMap as KeyMap
import qualified Data.Aeson.Key as Key
import qualified Data.ByteString as B
mkJournalScribe :: PermitFunc -> Verbosity -> IO Scribe
mkJournalScribe permitFunc verbosity =
pure $
Scribe
{ liPush = \i ->
J.sendMessageWith (TL.toStrict $ Builder.toLazyText $ unLogStr $ _itemMessage i) (itemToJournalFields verbosity i),
scribeFinalizer = pure (), -- no cleanup?
scribePermitItem = permitFunc
}
itemToJournalFields :: forall a. LogItem a => Verbosity -> Item a -> J.JournalFields
itemToJournalFields verbosity item = mconcat
[ J.syslogIdentifier (unNS item)
, J.priority (mapPriority item)
, thread item
, payload item
, environment item
]
where
mapPriority i =
case _itemSeverity i of
DebugS -> J.Debug
InfoS -> J.Info
NoticeS -> J.Notice
WarningS -> J.Warning
ErrorS -> J.Error
CriticalS -> J.Critical
AlertS -> J.Alert
EmergencyS -> J.Emergency
unNS = T.intercalate "." . unNamespace . _itemNamespace
thread i = HashMap.singleton (katipField "thread") (TE.encodeUtf8 $ getThreadIdText $ _itemThread i)
environment i = HashMap.singleton (katipField "environment") (TE.encodeUtf8 $ getEnvironment $ _itemEnv i)
payload :: Item a -> J.JournalFields
payload i = -- HashMap.singleton (J.mkJournalField "payload") (BL.toStrict $ A.encode $ payloadObject verbosity $ _itemPayload i)
HashMap.fromList $ map (\(k,v) -> (katipField (Key.toText k), encodeValue v)) $ KeyMap.toList $ payloadObject verbosity $ _itemPayload i
-- The upstream doesn't handle '-'
katipField = J.mkJournalField . T.replace "-" "_" . ("KATIP_" <>)
encodeValue :: A.Value -> B.ByteString
encodeValue = \case
-- Handle simple scalar values as is
A.String t -> TE.encodeUtf8 t
x -> BL.toStrict $ A.encode x
test :: HasCallStack => IO ()
test = do
scribe <- mkJournalScribe (permitItem InfoS) V2
let makeLogEnv = registerScribe "journald" scribe defaultScribeSettings =<< initLogEnv "hass-controller" "dev"
bracket makeLogEnv closeScribes $ \le -> do
runKatipContextT le () "findme-context" $
katipAddContext (sl "trace-id" ("abcdefg" :: String)) $
logLocM InfoS "Hello world"
pure ()
+4
View File
@@ -12,6 +12,10 @@ import Support (fakeRequest)
import Test.Hspec (Spec, describe, it) import Test.Hspec (Spec, describe, it)
import Test.Hspec.Hedgehog (forAll, forAllWith, hedgehog, (===)) 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 -- | 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 -- they emit equal outputs on every input sequence, so each law runs both
-- sides on generated inputs. -- 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 qualified Hedgehog.Range as Range
import Test.Hspec import Test.Hspec
import Test.Hspec.Hedgehog import Test.Hspec.Hedgehog
import Data.Maybe (listToMaybe)
import AFRP.Diagram (emptyDiagram)
fakeRequest :: Request fakeRequest :: Request
fakeRequest = Request (sec 0) utc nil "test" 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') fmap f (St g) = St $ \s -> let (a, s') = g s in (f a, s')
instance Applicative St where 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'') St f <*> St x = St $ \s -> let (f', s') = f s; (a, s'') = x s' in (f' a, s'')
instance Monad St where instance Monad St where
@@ -165,7 +167,7 @@ lMergeSpec = describe "lMerge" $ do
changesSpec :: Spec changesSpec :: Spec
changesSpec = describe "changes" $ do changesSpec = describe "changes" $ do
it "first output is always Tick" $ 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" $ it "outputs Event only on value change" $
runPure changes "aaaabbbcca" runPure changes "aaaabbbcca"
@@ -535,11 +537,11 @@ sampleSpec = describe "sample" $ do
-- | A stateless arrow carrying a fixed entity set, for testing propagation. -- | A stateless arrow carrying a fixed entity set, for testing propagation.
subscribed :: S.Set T.Text -> Mealy Identity Int Int 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 '<*>'. -- | Same as 'subscribed' but yields a function, for testing '<*>'.
subscribedF :: S.Set T.Text -> Mealy Identity Int (Int -> Int) 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 :: Spec
entitiesSpec = describe "entities" $ do entitiesSpec = describe "entities" $ do
+14 -14
View File
@@ -5,7 +5,7 @@ module BedroomSpec (spec) where
import AFRP (Event (..), entities) import AFRP (Event (..), entities)
import qualified Data.Set as S import qualified Data.Set as S
import qualified Data.Text as T import qualified Data.Text as T
import Data.Aeson (Value, object, (.=)) import Data.Aeson (Value)
import HomeAssistant.Controller import HomeAssistant.Controller
import HomeAssistant.Controller.Bedroom import HomeAssistant.Controller.Bedroom
import Support import Support
@@ -49,8 +49,8 @@ entitySpec = describe "entities" $ do
] ]
it "bedroomPresenceController subscribes to the presence sensor" $ it "bedroomPresenceController subscribes to the presence sensor" $
entities bedroomPresenceController S.toList (entities bedroomPresenceController)
`shouldBe` S.singleton "binary_sensor.presence_sensor_bedroom_occupancy" `shouldContain` [ "binary_sensor.presence_sensor_bedroom_occupancy" ]
it "humidifierController subscribes to the door sensor" $ it "humidifierController subscribes to the door sensor" $
entities humidifierController entities humidifierController
@@ -62,18 +62,18 @@ drawerSpec = describe "bedroomDrawerController" $ do
it "turns the drawer light on when the drawer opens" $ it "turns the drawer light on when the drawer opens" $
services (runHASS bedroomDrawerController [drawerState "on"]) services (runHASS bedroomDrawerController [drawerState "on"])
`shouldBe` [[switch [entity] True]] `shouldBe` [[switchService [entity] True]]
it "turns the drawer light off when the drawer closes" $ it "turns the drawer light off when the drawer closes" $
services (runHASS bedroomDrawerController [drawerState "off"]) services (runHASS bedroomDrawerController [drawerState "off"])
`shouldBe` [[switch [entity] False]] `shouldBe` [[switchService [entity] False]]
it "toggles the light as the drawer opens and closes" $ it "toggles the light as the drawer opens and closes" $
services (runHASS bedroomDrawerController services (runHASS bedroomDrawerController
[ drawerState "on", drawerState "off", drawerState "on" ]) [ drawerState "on", drawerState "off", drawerState "on" ])
`shouldBe` [ [switch [entity] True] `shouldBe` [ [switchService [entity] True]
, [switch [entity] False] , [switchService [entity] False]
, [switch [entity] True] , [switchService [entity] True]
] ]
it "ignores state events for other entities" $ it "ignores state events for other entities" $
@@ -91,15 +91,15 @@ buttonSpec = describe "bedroomButtonController" $ do
it "Masse single click turns on his nightstand scene (lowest)" $ it "Masse single click turns on his nightstand scene (lowest)" $
concat (services (runHASS bedroomButtonController [masseButton "1_short_release"])) concat (services (runHASS bedroomButtonController [masseButton "1_short_release"]))
`shouldContain` [activateSceneWith "scene.makuuhuone_masse" (Just $ object ["transition" .= (5 :: Int)])] `shouldContain` [activateScene "scene.makuuhuone_masse"]
it "Masse double click turns on the middle scene" $ it "Masse double click turns on the middle scene" $
concat (services (runHASS bedroomButtonController [masseButton "1_double_press"])) concat (services (runHASS bedroomButtonController [masseButton "1_double_press"]))
`shouldContain` [activateSceneWith "scene.makuuhuone_keski" (Just $ object ["transition" .= (5 :: Int)])] `shouldContain` [activateScene "scene.makuuhuone_keski"]
it "Masse long click turns on the bright scene" $ it "Masse long click turns on the bright scene" $
concat (services (runHASS bedroomButtonController [masseButton "1_long_press"])) concat (services (runHASS bedroomButtonController [masseButton "1_long_press"]))
`shouldContain` [activateSceneWith "scene.makuuhuone_kirkas" (Just $ object ["transition" .= (5 :: Int)])] `shouldContain` [activateScene "scene.makuuhuone_kirkas"]
it "Masse off click turns the bedroom lights off" $ it "Masse off click turns the bedroom lights off" $
concat (services (runHASS bedroomButtonController [masseButton "2_short_release"])) concat (services (runHASS bedroomButtonController [masseButton "2_short_release"]))
@@ -107,15 +107,15 @@ buttonSpec = describe "bedroomButtonController" $ do
it "Enishen single click turns on her nightstand scene (lowest)" $ it "Enishen single click turns on her nightstand scene (lowest)" $
concat (services (runHASS bedroomButtonController [enishenButton "1_short_release"])) concat (services (runHASS bedroomButtonController [enishenButton "1_short_release"]))
`shouldContain` [activateSceneWith "scene.makuuhuone_jemina" (Just $ object ["transition" .= (5 :: Int)])] `shouldContain` [activateScene "scene.makuuhuone_jemina"]
it "Enishen double click turns on the middle scene" $ it "Enishen double click turns on the middle scene" $
concat (services (runHASS bedroomButtonController [enishenButton "1_double_press"])) concat (services (runHASS bedroomButtonController [enishenButton "1_double_press"]))
`shouldContain` [activateSceneWith "scene.makuuhuone_keski" (Just $ object ["transition" .= (5 :: Int)])] `shouldContain` [activateScene "scene.makuuhuone_keski"]
it "Enishen long click turns on the bright scene" $ it "Enishen long click turns on the bright scene" $
concat (services (runHASS bedroomButtonController [enishenButton "1_long_press"])) concat (services (runHASS bedroomButtonController [enishenButton "1_long_press"]))
`shouldContain` [activateSceneWith "scene.makuuhuone_kirkas" (Just $ object ["transition" .= (5 :: Int)])] `shouldContain` [activateScene "scene.makuuhuone_kirkas"]
it "Enishen off click turns the bedroom lights off" $ it "Enishen off click turns the bedroom lights off" $
concat (services (runHASS bedroomButtonController [enishenButton "2_short_release"])) concat (services (runHASS bedroomButtonController [enishenButton "2_short_release"]))
+20 -13
View File
@@ -6,7 +6,7 @@ import AFRP (Request (..), Event (..))
import Control.Concurrent.STM import Control.Concurrent.STM
( atomically ( atomically
, dupTChan , dupTChan
, isEmptyTChan
, readTChan , readTChan
, writeTChan , writeTChan
) )
@@ -18,9 +18,12 @@ import HomeAssistant.Controller (HASSEff (..), Service (..), Target(..))
import HomeAssistant.Runtime.Bus import HomeAssistant.Runtime.Bus
import HomeAssistant.Runtime.Flags (loadFlags, setEnabled) import HomeAssistant.Runtime.Flags (loadFlags, setEnabled)
import HomeAssistant.Runtime.Metrics (registerAppMetrics) import HomeAssistant.Runtime.Metrics (registerAppMetrics)
import Katip (Namespace (Namespace), runKatipContextT, Severity (..)) import Katip (Namespace (Namespace), runKatipContextT)
import Katip.Monadic (runNoLoggingT)
import Support (withTestLogEnv)
import qualified System.Metrics as Metrics import qualified System.Metrics as Metrics
import System.IO.Temp (withTempDirectory) import System.IO.Temp (withTempDirectory)
import System.Timeout (timeout)
import Test.Hspec import Test.Hspec
spec :: Spec spec :: Spec
@@ -43,15 +46,17 @@ spec = describe "Bus" $ do
(_, svc') <- atomically $ readTChan (busOutbound bus) (_, svc') <- atomically $ readTChan (busOutbound bus)
svc' `shouldBe` svc svc' `shouldBe` svc
it "channelHassEval drops CallService when the handler is disabled" $ it "channelHassEval writes CallService to the outbound channel even when the handler is disabled" $
withTestFlagsBus $ \bus -> do withTestFlagsBus $ \bus -> do
setEnabled (busFlags bus) "test-handler" False setEnabled (busFlags bus) "test-handler" False
let req = Request (UTCTime (toEnum 0) 0) utc nil "test-handler" let req = Request (UTCTime (toEnum 0) 0) utc nil "test-handler"
svc = Service "light" "turn_on" Nothing [EntityId "light.test"] svc = Service "light" "turn_on" Nothing [EntityId "light.test"]
runKatipContextT (busLogEnv bus) () (Namespace ["test"]) $ runKatipContextT (busLogEnv bus) () (Namespace ["test"]) $
channelHassEval bus (CallService req svc) channelHassEval bus (CallService req svc)
atomically (isEmptyTChan (busOutbound bus)) `shouldReturn` True result <- timeout 1000000 $ atomically $ readTChan (busOutbound bus)
case result of
Nothing -> expectationFailure "expected a write to the outbound channel"
Just (_, svc') -> svc' `shouldBe` svc
it "generates unique sequential call ids" $ do it "generates unique sequential call ids" $ do
gen <- mkCallIdGen 0 gen <- mkCallIdGen 0
@@ -64,8 +69,8 @@ spec = describe "Bus" $ do
store <- Metrics.newStore store <- Metrics.newStore
m <- registerAppMetrics store m <- registerAppMetrics store
withTempDirectory "/tmp" "bus-spec" $ \dir -> do withTempDirectory "/tmp" "bus-spec" $ \dir -> do
flags <- loadFlags dir [] flags <- runNoLoggingT (loadFlags dir [])
withBus InfoS m flags $ \bus -> do withTestLogEnv $ \le -> withBus le m flags $ \bus -> do
recordInbound bus recordInbound bus
recordInbound bus recordInbound bus
recordOutbound bus recordOutbound bus
@@ -77,14 +82,16 @@ withTestBus :: (Bus -> IO a) -> IO a
withTestBus action = do withTestBus action = do
store <- Metrics.newStore store <- Metrics.newStore
m <- registerAppMetrics store m <- registerAppMetrics store
withTempDirectory "/tmp" "bus-spec" $ \dir -> do withTestLogEnv $ \le ->
flags <- loadFlags dir [] withTempDirectory "/tmp" "bus-spec" $ \dir -> do
withBus InfoS m flags action flags <- runNoLoggingT (loadFlags dir [])
withBus le m flags action
withTestFlagsBus :: (Bus -> IO a) -> IO a withTestFlagsBus :: (Bus -> IO a) -> IO a
withTestFlagsBus action = do withTestFlagsBus action = do
store <- Metrics.newStore store <- Metrics.newStore
m <- registerAppMetrics store m <- registerAppMetrics store
withTempDirectory "/tmp" "bus-spec" $ \dir -> do withTestLogEnv $ \le ->
flags <- loadFlags dir ["test-handler"] withTempDirectory "/tmp" "bus-spec" $ \dir -> do
withBus InfoS m flags action flags <- runNoLoggingT (loadFlags dir ["test-handler"])
withBus le m flags action
+29 -4
View File
@@ -4,12 +4,23 @@ module ConnectionSpec (spec) where
import AFRP (Request(..)) import AFRP (Request(..))
import Data.Aeson (object, (.=)) import Data.Aeson (object, (.=))
import qualified Data.HashMap.Strict as HM
import Data.Maybe (fromJust) import Data.Maybe (fromJust)
import Data.Text (Text) import Data.Text (Text)
import Data.Time (UTCTime (..), utc) import Data.Time (UTCTime (..), utc)
import Data.UUID (fromString) import Data.UUID (fromString)
import HomeAssistant.Controller (Service (..), Target(..)) import HomeAssistant.Controller (Service (..), Target(..))
import HomeAssistant.Runtime.Connection (encodeService, isTriggerEvent) import HomeAssistant.Runtime.Bus
import HomeAssistant.Runtime.Flags (loadFlags, setEnabled)
import HomeAssistant.Runtime.Metrics (registerAppMetrics)
import HomeAssistant.Runtime.RateLimit (registerRateLimitMetrics, slidingWindowLimiter)
import HomeAssistant.Runtime.Connection (dispatchService, encodeService, isTriggerEvent)
import Katip (Namespace (Namespace), runKatipContextT)
import Katip.Monadic (runNoLoggingT)
import Support (withTestLogEnv)
import System.IO.Temp (withTempDirectory)
import qualified System.Metrics as Metrics
import System.Timeout (timeout)
import Test.Hspec import Test.Hspec
spec :: Spec spec :: Spec
@@ -44,6 +55,22 @@ spec = do
it "is false when there is no type" $ it "is false when there is no type" $
isTriggerEvent (object ["id" .= (1 :: Int)]) `shouldBe` False isTriggerEvent (object ["id" .= (1 :: Int)]) `shouldBe` False
describe "dispatchService" $ do
it "skips disabled handlers without consuming a call id" $ do
store <- Metrics.newStore
m <- registerAppMetrics store
rlMetrics <- registerRateLimitMetrics store
limiter <- slidingWindowLimiter rlMetrics 10 20
withTempDirectory "/tmp" "connection-spec" $ \dir -> do
flags <- runNoLoggingT (loadFlags dir ["test"])
setEnabled flags "test" False
withTestLogEnv $ \le -> withBus le m flags $ \bus -> do
timeout 1000000 (do
runKatipContextT (busLogEnv bus) () (Namespace ["connection"]) $
dispatchService limiter bus (req 1) (lightOn [EntityId "light.test"])
generateCallId (busGen bus)) `shouldReturn` Just 1
sample <- Metrics.sampleAll store
HM.lookup "hass.service.out" sample `shouldBe` Just (Metrics.Counter 0)
req :: Int -> Request req :: Int -> Request
req n = Request (UTCTime (toEnum 0) (fromIntegral (0 :: Int))) utc req n = Request (UTCTime (toEnum 0) (fromIntegral (0 :: Int))) utc
@@ -53,7 +80,5 @@ req n = Request (UTCTime (toEnum 0) (fromIntegral (0 :: Int))) utc
uuid = "00000000-0000-0000-0000-" <> pad n uuid = "00000000-0000-0000-0000-" <> pad n
lightOn :: [Target] -> Service lightOn :: [Target] -> Service
lightOn targets = Service "light" "turn_on" Nothing targets lightOn = Service "light" "turn_on" Nothing
lightOff :: [Target] -> Service
lightOff targets = Service "light" "turn_off" Nothing targets
+28
View File
@@ -0,0 +1,28 @@
{-# LANGUAGE OverloadedStrings #-}
module ControllerSpec where
import Test.Hspec
import Data.Default (def)
import HomeAssistant.Controller (Brightness(..), formatLightAttributes, LightAttributes(..))
import Data.Aeson (object, (.=))
spec :: Spec
spec = describe "Generic controller" $
describe "Light settings" $ do
it "formats the default as empty" $
formatLightAttributes def `shouldBe` Nothing
it "formats the transition" $
formatLightAttributes def{lightTransition=Just 5} `shouldBe`
Just (object ["transition" .= (5 :: Int)])
it "formats the temperature" $
formatLightAttributes def{lightColorTemperature=Just 5} `shouldBe`
Just (object ["color_temp_kelvin" .= (5 :: Int)])
it "formats the brightness as percentage" $
formatLightAttributes def{lightBrightness=Just (BrightnessPercent 100)} `shouldBe`
Just (object ["brightness_pct" .= (100 :: Int)])
it "formats the brightness as absolute" $
formatLightAttributes def{lightBrightness=Just (BrightnessAbsolute 200)} `shouldBe`
Just (object ["brightness" .= (200 :: Int)])
it "formats multiple values" $
formatLightAttributes def{lightTransition = Just 5, lightBrightness=Just (BrightnessAbsolute 200)} `shouldBe`
Just (object ["brightness" .= (200 :: Int), "transition" .= (5 :: Int)])
+10 -9
View File
@@ -10,6 +10,7 @@ import qualified Data.Map.Strict as M
import Data.Text (Text) import Data.Text (Text)
import qualified Hedgehog.Gen as Gen import qualified Hedgehog.Gen as Gen
import qualified Hedgehog.Range as Range import qualified Hedgehog.Range as Range
import Katip.Monadic (runNoLoggingT)
import System.IO.Temp (withTempDirectory) import System.IO.Temp (withTempDirectory)
import Test.Hspec import Test.Hspec
import Test.Hspec.Hedgehog import Test.Hspec.Hedgehog
@@ -21,7 +22,7 @@ spec = describe "Flags" $ do
describe "loadFlags" $ do describe "loadFlags" $ do
it "defaults all names to True when the file is missing (opt-out)" $ it "defaults all names to True when the file is missing (opt-out)" $
withTempDirectory "/tmp" "flags-spec" $ \dir -> do withTempDirectory "/tmp" "flags-spec" $ \dir -> do
flags <- loadFlags dir ["a", "b"] flags <- runNoLoggingT (loadFlags dir ["a", "b"])
m <- allFlags flags m <- allFlags flags
m `shouldBe` M.fromList [("a" :: Text, True), ("b", True)] m `shouldBe` M.fromList [("a" :: Text, True), ("b", True)]
@@ -29,7 +30,7 @@ spec = describe "Flags" $ do
withTempDirectory "/tmp" "flags-spec" $ \dir -> do withTempDirectory "/tmp" "flags-spec" $ \dir -> do
let path = dir <> "/handlers.json" let path = dir <> "/handlers.json"
writeFile path "{\"b\": false}" writeFile path "{\"b\": false}"
flags <- loadFlags dir ["a", "b"] flags <- runNoLoggingT (loadFlags dir ["a", "b"])
m <- allFlags flags m <- allFlags flags
m `shouldBe` M.fromList [("a" :: Text, True), ("b" :: Text, False)] m `shouldBe` M.fromList [("a" :: Text, True), ("b" :: Text, False)]
@@ -37,7 +38,7 @@ spec = describe "Flags" $ do
withTempDirectory "/tmp" "flags-spec" $ \dir -> do withTempDirectory "/tmp" "flags-spec" $ \dir -> do
let path = dir <> "/handlers.json" let path = dir <> "/handlers.json"
writeFile path "not json at all" writeFile path "not json at all"
flags <- loadFlags dir ["a"] flags <- runNoLoggingT (loadFlags dir ["a"])
m <- allFlags flags m <- allFlags flags
m `shouldBe` M.fromList [("a" :: Text, True)] m `shouldBe` M.fromList [("a" :: Text, True)]
@@ -46,30 +47,30 @@ spec = describe "Flags" $ do
withTempDirectory "/tmp" "flags-spec" $ \dir -> do withTempDirectory "/tmp" "flags-spec" $ \dir -> do
let path = dir <> "/handlers.json" let path = dir <> "/handlers.json"
writeFile path "{\"a\": false}" writeFile path "{\"a\": false}"
flags <- loadFlags dir ["a"] flags <- runNoLoggingT (loadFlags dir ["a"])
isEnabled flags "a" `shouldReturn` False isEnabled flags "a" `shouldReturn` False
it "defaults unknown names to True" $ it "defaults unknown names to True" $
withTempDirectory "/tmp" "flags-spec" $ \dir -> do withTempDirectory "/tmp" "flags-spec" $ \dir -> do
flags <- loadFlags dir [] flags <- runNoLoggingT (loadFlags dir [])
isEnabled flags "unknown" `shouldReturn` True isEnabled flags "unknown" `shouldReturn` True
describe "setEnabled" $ do describe "setEnabled" $ do
it "updates the in-memory map and persists to disk" $ it "updates the in-memory map and persists to disk" $
withTempDirectory "/tmp" "flags-spec" $ \dir -> do withTempDirectory "/tmp" "flags-spec" $ \dir -> do
flags <- loadFlags dir ["a"] flags <- runNoLoggingT (loadFlags dir ["a"])
setEnabled flags "a" False setEnabled flags "a" False
isEnabled flags "a" `shouldReturn` False isEnabled flags "a" `shouldReturn` False
-- reload from disk to confirm persistence -- reload from disk to confirm persistence
flags' <- loadFlags dir ["a"] flags' <- runNoLoggingT (loadFlags dir ["a"])
isEnabled flags' "a" `shouldReturn` False isEnabled flags' "a" `shouldReturn` False
it "concurrent writes leave the file consistent with the TVar" $ it "concurrent writes leave the file consistent with the TVar" $
hedgehog $ do hedgehog $ do
n <- forAll $ Gen.int (Range.linear 1 50) n <- forAll $ Gen.int (Range.linear 1 50)
liftIO $ withTempDirectory "/tmp" "flags-spec" $ \dir -> do liftIO $ withTempDirectory "/tmp" "flags-spec" $ \dir -> do
flags <- loadFlags dir ["x"] flags <- runNoLoggingT (loadFlags dir ["x"])
mapConcurrently_ (\i -> setEnabled flags "x" (even i)) [1 .. n] mapConcurrently_ (setEnabled flags "x" . even) [1 .. n]
m <- allFlags flags m <- allFlags flags
decoded <- decodeFileStrict (dir <> "/handlers.json") decoded <- decodeFileStrict (dir <> "/handlers.json")
(decoded :: Maybe (Map Text Bool)) `shouldBe` Just m (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 import HomeAssistant.Runtime.Graphing
( GraphSpec (..) ( GraphSpec (..)
, Range (..) , Range (..)
, Graph(..)
, buildGraphArgs , buildGraphArgs
, graphs , graphs
, lookupGraph , lookupGraph
@@ -21,7 +22,6 @@ import System.Exit (ExitCode (..))
import System.Process (readProcessWithExitCode) import System.Process (readProcessWithExitCode)
import Test.Hspec import Test.Hspec
import Servant.API (FromHttpApiData(..), ToHttpApiData (..)) import Servant.API (FromHttpApiData(..), ToHttpApiData (..))
import HomeAssistant.Runtime.Graphing (Graph(..))
traffic :: GraphSpec traffic :: GraphSpec
traffic = case lookupGraph graphs Traffic of traffic = case lookupGraph graphs Traffic of
+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\""
+13 -5
View File
@@ -10,6 +10,8 @@ import HomeAssistant.Controller
import HomeAssistant.Controller.Kitchen import HomeAssistant.Controller.Kitchen
import Support import Support
import Test.Hspec import Test.Hspec
import Data.Default (def)
import Data.Time (getCurrentTime, addUTCTime)
-- Helper functions for creating test events -- Helper functions for creating test events
testDinnerLightLevel :: Int -> Event Value testDinnerLightLevel :: Int -> Event Value
@@ -34,12 +36,18 @@ dinnerTableSpec = describe "dinnerTableController" $ do
it "turns lights on when presence is occupied and light level is low" $ do it "turns lights on when presence is occupied and light level is low" $ do
services (runHASS dinnerTableController [testDinnerLightLevel 10, testDinnerPresence "on"]) services (runHASS dinnerTableController [testDinnerLightLevel 10, testDinnerPresence "on"])
`shouldBe` [[switch [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] True], [switch [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] False, light [EntityId "light.kitchen_dining_large"] (On Nothing)]] `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 it "turns lights to sleep when presence is unoccupied" $ do
services (runHASS dinnerTableController [testDinnerLightLevel 10, testDinnerPresence "off"]) now <- getCurrentTime
`shouldBe` [[switch [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] True], []] 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 it "does nothing on Tick" $ do
services (runHASS dinnerTableController [Tick]) services (runHASS dinnerTableController [Tick])
`shouldBe` [[switch [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] True]] `shouldBe` [[switchService [EntityId "switch.adaptive_lighting_ruokapoydan_valot_sleep_mode"] True]]
+4
View File
@@ -8,10 +8,12 @@ import qualified BusSpec
import qualified ConnectionSpec import qualified ConnectionSpec
import qualified FlagsSpec import qualified FlagsSpec
import qualified GraphingSpec import qualified GraphingSpec
import qualified HttpServerSpec
import qualified KitchenSpec import qualified KitchenSpec
import qualified LivingroomSpec import qualified LivingroomSpec
import qualified MetricsSpec import qualified MetricsSpec
import qualified RuntimeSpec import qualified RuntimeSpec
import qualified ControllerSpec
main :: IO () main :: IO ()
main = hspec $ do main = hspec $ do
@@ -22,7 +24,9 @@ main = hspec $ do
ConnectionSpec.spec ConnectionSpec.spec
FlagsSpec.spec FlagsSpec.spec
GraphingSpec.spec GraphingSpec.spec
HttpServerSpec.spec
KitchenSpec.spec KitchenSpec.spec
LivingroomSpec.spec LivingroomSpec.spec
MetricsSpec.spec MetricsSpec.spec
RuntimeSpec.spec RuntimeSpec.spec
ControllerSpec.spec
+1 -1
View File
@@ -147,7 +147,7 @@ spec = do
parseInfoDs "step = 10\nrra[0].cf = \"AVERAGE\"\n" `shouldBe` [] parseInfoDs "step = 10\nrra[0].cf = \"AVERAGE\"\n" `shouldBe` []
describe "schemaMatches" $ do 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" $ it "is true for identical schemas regardless of order" $
schemaMatches [ds "b" Gauge, ds "a" Derive] [("a", Derive), ("b", Gauge)] schemaMatches [ds "b" Gauge, ds "a" Derive] [("a", Derive), ("b", Gauge)]
`shouldBe` True `shouldBe` True
+9 -1
View File
@@ -10,10 +10,13 @@ module Support
, sec , sec
, stateEvent , stateEvent
, buttonEvent , buttonEvent
, withTestLogEnv
) where ) where
import Control.Exception (bracket)
import Control.Monad.Fix (MonadFix (..)) import Control.Monad.Fix (MonadFix (..))
import Data.Aeson (Value, object, (.=)) import Data.Aeson (Value, object, (.=))
import Katip (LogEnv, closeScribes, initLogEnv)
import qualified Data.Text as T import qualified Data.Text as T
import Data.Time (UTCTime (..), utc) import Data.Time (UTCTime (..), utc)
import Data.UUID (nil) import Data.UUID (nil)
@@ -33,7 +36,7 @@ instance Functor Acc where
fmap f (Acc g) = Acc $ \s -> let (a, s') = g s in (f a, s') fmap f (Acc g) = Acc $ \s -> let (a, s') = g s in (f a, s')
instance Applicative Acc where 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'') Acc f <*> Acc x = Acc $ \s -> let (f', s') = f s; (a, s'') = x s' in (f' a, s'')
instance Monad Acc where instance Monad Acc where
@@ -42,9 +45,14 @@ instance Monad Acc where
instance MonadFix Acc where instance MonadFix Acc where
mfix f = Acc $ \s -> let (a, s') = runAcc (f a) s in (a, s') mfix f = Acc $ \s -> let (a, s') = runAcc (f a) s in (a, s')
-- | A silent LogEnv: no scribes registered, so nothing is written anywhere.
withTestLogEnv :: (LogEnv -> IO a) -> IO a
withTestLogEnv = bracket (initLogEnv "test" "test") closeScribes
-- | Interpret `HASSEff` in `Acc`: record `CallService`, drop tracing/debug. -- | Interpret `HASSEff` in `Acc`: record `CallService`, drop tracing/debug.
interp :: HASSEff a -> Acc a interp :: HASSEff a -> Acc a
interp (CallService _ svc) = Acc $ \s -> ((), s ++ [svc]) interp (CallService _ svc) = Acc $ \s -> ((), s ++ [svc])
interp (CallServices _ svc) = Acc $ \s -> ((), s ++ svc)
interp (Debug _) = pure () interp (Debug _) = pure ()
interp (Trace _ _) = pure () interp (Trace _ _) = pure ()