comparison service/pilight/pilight.go @ 152:2a38f2620e5b

try to read current led setting at page load. sometimes fails, sometimes readss an old value Ignore-this: 406031419412f0674bb7019f19e3c39f
author drewp@bigasterisk.com
date Wed, 16 Jul 2014 22:58:58 -0700
parents 2e4a9204f23b
children
comparison
equal deleted inserted replaced
151:4de6c7e5e959 152:2a38f2620e5b
10 import "strconv" 10 import "strconv"
11 import "time" 11 import "time"
12 import "net/textproto" 12 import "net/textproto"
13 import "bufio" 13 import "bufio"
14 import "errors" 14 import "errors"
15 import "encoding/json"
15 16
16 const ledCount = 3 17 const ledCount = 3
17 18
18 type Board struct { 19 type Board struct {
19 ser io.ReadWriteCloser 20 ser io.ReadWriteCloser
77 return json, nil 78 return json, nil
78 } 79 }
79 return "", errors.New("failed after all retries") 80 return "", errors.New("failed after all retries")
80 } 81 }
81 82
83
84 func (b *Board) ReadLeds() (colors []color.Color, err error) {
85 err = b.Write(0x3, make([]byte, 0))
86 if err != nil {
87 return
88 }
89 reader := textproto.NewReader(bufio.NewReader(b.ser))
90 line, err := reader.ReadLineBytes()
91 if err != nil {
92 return
93 }
94
95 type LedsMessage struct {
96 Leds []string
97 }
98 var ret LedsMessage
99 err = json.Unmarshal(line, &ret)
100 if err != nil {
101 return
102 }
103
104 colors = make([]color.Color, len(ret.Leds))
105 for i, c := range ret.Leds {
106 r, g, b := hex.HexToRGB(hex.Hex(c))
107 colors[i] = color.RGBA{r, g, b, 0}
108 }
109
110 return colors, nil
111 }
112
82 func getBodyStringColor(req *http.Request) (c color.Color, err error) { 113 func getBodyStringColor(req *http.Request) (c color.Color, err error) {
83 bytes := make([]byte, 1024) 114 bytes := make([]byte, 1024)
84 n, err := req.Body.Read(bytes) 115 n, err := req.Body.Read(bytes)
85 body := hex.Hex(string(bytes[:n])) 116 body := hex.Hex(string(bytes[:n]))
86 if err != nil { 117 if err != nil {
115 return 500, "" 146 return 500, ""
116 } 147 }
117 148
118 return 200, "ok" 149 return 200, "ok"
119 }) 150 })
120 m.Get("/led", func() string { 151 m.Get("/led", func() (int, string) {
121 return "['#ff0000', '#ff0000']" 152
153 colors, err := board.ReadLeds()
154 if err != nil {
155 return 500, ""
156 }
157 hexColors := make([]hex.Hex, len(colors))
158 for i, c := range colors {
159 // hex.HexModel.Convert(c) seems like the
160 // right call, but fails because it returns
161 // Color not string
162 r, g, b, _ := c.RGBA()
163 hexColors[i] = hex.RGBToHex(uint8(r), uint8(g), uint8(b))
164 }
165
166 // content-type json
167 j, err := json.Marshal(hexColors)
168 if err != nil {
169 return 500, ""
170 }
171 return 200, string(j)
122 }) 172 })
123 m.Put("/led", func(req *http.Request) (int, string) { 173 m.Put("/led", func(req *http.Request) (int, string) {
124 color, err := getBodyStringColor(req) 174 color, err := getBodyStringColor(req)
125 if err != nil { 175 if err != nil {
126 return 400, "" 176 return 400, ""