-
Notifications
You must be signed in to change notification settings - Fork 0
/
rackethue.rkt
123 lines (106 loc) · 3.28 KB
/
rackethue.rkt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
#lang racket
(require net/http-easy)
(require json)
(require dotenv)
(dotenv-load!)
(define base-url (~a "http://" (getenv "HUE_BRIDGE_IP") "/api/" (getenv "HUE_SECRET") "/"))
;; some lights are glitchy (non-responsive) so only check a few
(define light-ids-check '(|1| |7|))
(define light-ids '(|1| |2| |3| |4| |5| |7| |8| |9|))
(define req/get
(lambda (endpoint)
(string->jsexpr
(bytes->string/utf-8
(response-body
(get (~a base-url endpoint)))))))
(define req/put
(lambda (endpoint value)
(put (~a base-url endpoint)
#:data value)))
(define lights
(lambda ()
(req/get "lights")))
(define light-on?
(lambda (l id)
(hash-ref
(hash-ref
(hash-ref l id)
'state)
'on)))
(define light-reachable?
(lambda (l id)
(hash-ref
(hash-ref
(hash-ref l id)
'state)
'reachable)))
(define all-lights-on?
(lambda ()
(letrec ({l (lights)}
{alo? (lambda (lid)
(cond
[(null? lid) #t]
[else (and (light-on? l (car lid))
(light-reachable? l (car lid))
(alo? (cdr lid)))]))})
(alo? light-ids-check))))
(define all-lights-off?
(lambda ()
(letrec ({l (lights)}
{alo? (lambda (lid)
(cond
[(null? lid) #t]
[else (and (or (not (light-on? l (car lid)))
(not (light-reachable? l (car lid))))
(alo? (cdr lid)))]))})
(alo? light-ids-check))))
(define light-off
(lambda (light-id)
(req/put (~a "lights/" light-id "/state")
(jsexpr->string (hasheq 'on #f)))))
(define light-on
(lambda (light-id)
(req/put (~a "lights/" light-id "/state")
(jsexpr->string (hasheq 'on #t)))))
(define all-lights-on
(lambda ()
(letrec ({alo (lambda (lid)
(cond
[(null? lid) '()]
[else (light-on (car lid))
(sleep 0.7)
(alo (cdr lid))]))})
(alo light-ids))))
(define all-lights-off
(lambda ()
(letrec ({alo (lambda (lid)
(cond
[(null? lid) '()]
[else (light-off (car lid))
(sleep 1.0)
(alo (cdr lid))]))})
(alo light-ids))))
(define synchronize-lights
(lambda ()
(letrec ({a (lambda ()
(cond
[(all-lights-on?) (sleep 10)
(a)]
[else (all-lights-off)
(displayln "turning off")
(b)]))}
{b (lambda ()
(cond
[(all-lights-off?) (sleep 2)
(b)]
[else (all-lights-on)
(displayln "turning on")
(a)]))}
{subscribe (lambda ()
(with-handlers
([exn:fail? (lambda (v)
(displayln v)
(subscribe))])
(a)))})
(subscribe))))
(synchronize-lights)