forked from zeroflag/punyforth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example-philips-hue.forth
102 lines (87 loc) · 2.87 KB
/
example-philips-hue.forth
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
NETCON load
\ HUE Bridge local IP and port
"192.168.0.12" constant: BRIDGE_IP
80 constant: BRIDGE_PORT
\ Base URL containing the HUE API key
"/api/<YOUR_HUE_API_KEY>/lights/" constant: BASE_URL
\ Light bulb ids for each room
"1" constant: HALL
"2" constant: BEDROOM
1024 constant: buffer-len
buffer-len buffer: buffer
: parse-http-code ( buffer -- code | throws:ECONVERT )
9 + 3 >number invert if
ECONVERT throw
then ;
exception: EHTTP
: read-http-code ( netconn -- http-code | throws:EHTTP )
buffer-len buffer netcon-readln
0 <= if EHTTP throw then
buffer "HTTP/" str-starts? if
buffer parse-http-code
else
EHTTP throw
then ;
: skip-http-headers ( netconn -- netconn )
begin
dup buffer-len buffer netcon-readln -1 <>
while
\ print: 'skipping header: ' buffer type cr
buffer strlen 0= if
\ println: 'end of header detected'
exit
then
repeat
EHTTP throw ;
: read-http-resp ( netconn -- response-code )
dup read-http-code
swap skip-http-headers
buffer-len buffer netcon-readln
print: 'body len=' . cr ;
: log-http-resp ( response-code -- response-code )
dup print: 'HTTP:' . space buffer type cr ;
: consume&dispose ( netcon -- )
dup read-http-resp log-http-resp
swap netcon-dispose
200 <> if EHTTP throw then ;
: bridge ( -- netconn )
BRIDGE_PORT BRIDGE_IP TCP netcon-connect ;
: on? ( bulb -- bool )
bridge
dup "GET " netcon-write
dup BASE_URL netcon-write
dup rot netcon-write
dup "\r\n\r\n" netcon-write
consume&dispose
buffer "\"on\":true" str-in? ;
: request-change-state ( bulb netconn -- )
dup "PUT " netcon-write
dup BASE_URL netcon-write
dup rot netcon-write
dup "/state HTTP/1.1\r\n" netcon-write
dup "Content-Type: application/json\r\n" netcon-write
dup "Accept: */*\r\n" netcon-write
dup "Connection: Close\r\n" netcon-write
drop ;
: on ( bulb -- )
bridge
tuck request-change-state
dup "Content-length: 22\r\n\r\n" netcon-write
dup "{\"on\":true,\"bri\": 255}\r\n" netcon-write
netcon-dispose ;
: off ( bulb -- )
bridge
tuck request-change-state
dup "Content-length: 12\r\n\r\n" netcon-write
dup "{\"on\":false}\r\n" netcon-write
netcon-dispose ;
: toggle ( bulb -- )
dup ['] on? catch ?dup if
print: 'Error checking light. ' ex-type cr
2drop
exit
then
{ if off else on then } catch ?dup if
print: 'Error toggling light. ' ex-type cr
2drop
then ;