led_brightness_by_time.sh 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #!/usr/bin/env bash
  2. # Set DW LED brightness based on time of day.
  3. # Intended to be run from cron every minute, e.g.:
  4. # * * * * * /Volumes/4TB\ SSD/projects/dune-weaver/scripts/led_brightness_by_time.sh >> /tmp/dw-led-brightness.log 2>&1
  5. #
  6. # Anchors below are (HH:MM, brightness 0-100). Brightness is linearly
  7. # interpolated between consecutive anchors, so the LEDs ramp smoothly.
  8. set -euo pipefail
  9. API="${DW_API:-http://localhost:8080}"
  10. ENDPOINT="$API/api/dw_leds/brightness"
  11. # Edit these to taste. Must be sorted by time. First and last bracket midnight.
  12. ANCHORS=(
  13. "00:00 5" # deep night: dim glow
  14. "06:30 15" # pre-dawn: warm wake-up level
  15. "08:00 60" # morning: full ambient
  16. "12:00 90" # midday peak
  17. "18:00 70" # evening
  18. "21:30 30" # wind-down
  19. "23:30 5" # back to deep night
  20. )
  21. now_minutes() {
  22. local h m
  23. h=$(date +%H)
  24. m=$(date +%M)
  25. # base-10 force avoids "08" being parsed as octal
  26. echo $(( 10#$h * 60 + 10#$m ))
  27. }
  28. anchor_minutes() { # "HH:MM <bri>" -> minutes
  29. local t=${1%% *}
  30. local h=${t%%:*}
  31. local m=${t##*:}
  32. echo $(( 10#$h * 60 + 10#$m ))
  33. }
  34. anchor_value() { echo "${1##* }"; }
  35. compute_brightness() {
  36. local now=$1 prev_t prev_v next_t next_v
  37. for ((i = 0; i < ${#ANCHORS[@]} - 1; i++)); do
  38. prev_t=$(anchor_minutes "${ANCHORS[i]}")
  39. next_t=$(anchor_minutes "${ANCHORS[i+1]}")
  40. if (( now >= prev_t && now <= next_t )); then
  41. prev_v=$(anchor_value "${ANCHORS[i]}")
  42. next_v=$(anchor_value "${ANCHORS[i+1]}")
  43. # linear interpolation, integer math
  44. echo $(( prev_v + (next_v - prev_v) * (now - prev_t) / (next_t - prev_t) ))
  45. return
  46. fi
  47. done
  48. # fallback: last anchor's value
  49. anchor_value "${ANCHORS[-1]}"
  50. }
  51. main() {
  52. local now bri
  53. now=$(now_minutes)
  54. bri=$(compute_brightness "$now")
  55. echo "[$(date -Iseconds)] minute=$now brightness=$bri"
  56. curl -fsS -X POST "$ENDPOINT" \
  57. -H 'Content-Type: application/json' \
  58. -d "{\"value\": $bri}"
  59. echo
  60. }
  61. main "$@"