-
Notifications
You must be signed in to change notification settings - Fork 0
/
denon.go
75 lines (66 loc) · 1.61 KB
/
denon.go
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
package main
import (
"fmt"
"net/http"
"io/ioutil"
"time"
"github.com/gorilla/mux"
"log"
"encoding/json"
"golang.org/x/net/websocket"
"github.com/rs/cors"
"github.com/laurent35240/denon/device"
)
var denon = device.Denon{Host: "192.168.1.9"}
func handlePower(w http.ResponseWriter, r *http.Request) {
type PowerState struct {
State string `json:"state"`
}
var powerState PowerState
defer r.Body.Close()
body, err := ioutil.ReadAll(r.Body)
if err != nil {
panic(err)
}
fmt.Printf("Body: %s", body)
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
if err := json.Unmarshal(body, &powerState); err != nil {
w.WriteHeader(422) // unprocessable entity
if err := json.NewEncoder(w).Encode(err); err != nil {
panic(err)
}
}
fmt.Printf("Power state received: %s", powerState.State)
switch {
case powerState.State == "ON":
denon.PowerOn()
case powerState.State == "OFF":
denon.PowerOff()
}
fmt.Fprint(w, "OK")
}
func WsServer(ws *websocket.Conn) {
ws.Write([]byte("Connected"))
c:= make(chan string)
var status, oldStatus string
for {
go denon.GetStatus(c)
status = <- c
if status != oldStatus {
ws.Write([]byte(status))
fmt.Printf("Status %s sent through WS\n", status)
oldStatus = status
}
time.Sleep(100 * time.Millisecond)
}
}
func main() {
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/power", handlePower).Methods("PUT")
router.Handle("/ws", websocket.Handler(WsServer))
c := cors.New(cors.Options{
AllowedMethods: []string{"GET", "POST", "PUT"},
})
handler := c.Handler(router)
log.Fatal(http.ListenAndServe(":8080", handler))
}