package main import ( "errors" "flag" "fmt" "github.com/dedkovd/noolite" "net/http" "strings" "strconv" ) func sendCommand(command string, channel, value, r, g, b int) error { if channel == -1 { return errors.New("Channel was not set") } if command == "" { return errors.New("Command was not set") } n, err := noolite.DefaultNooliteAdapter() defer n.Close() if err != nil { return err } if command == "set" { if value != 0 { return n.SetBrightnesValue(channel, value) } else if r != 0 || g != 0 || b != 0 { return n.SetBrightnesValues(channel, r, g, b) } else { return errors.New("Need some value") } } else { commands := map[string]func(int) error{ "on": n.On, "off": n.Off, "switch": n.Switch, "decraseBrightnes": n.DecraseBrightnes, "incraseBrightnes": n.IncraseBrightnes, "invertBrightnes": n.InvertBrightnes, } cmd, ok := commands[command] if !ok { return errors.New("Command not found") } return cmd(channel) } } func parseParams(path string) (string, int, int, int, int, int) { params := strings.Split(path, "/")[1:] command := "" channel := -1 value := 0 r := 0 g := 0 b := 0 command = params[0] if len(params) > 1 { channel, _ = strconv.Atoi(params[1]) } if len(params) > 2 { value, _ = strconv.Atoi(params[2]) } if len(params) == 5 { value = 0 r, _ = strconv.Atoi(params[2]) g, _ = strconv.Atoi(params[3]) b, _ = strconv.Atoi(params[4]) } return command, channel, value, r, g, b } func main() { channel := flag.Int("channel", -1, "Noolite adapter channel") command := flag.String("command", "", "Command") value := flag.Int("val", 0, "Set value") red := flag.Int("r", 0, "Red channel") green := flag.Int("g", 0, "Green channel") blue := flag.Int("b", 0, "Blue channel") http_port := flag.Int("p", -1, "Http port") flag.Parse() if *http_port < 0 { err := sendCommand(*command, *channel, *value, *red, *green, *blue) if err != nil { panic(err) } } else { http.HandleFunc("/noolite/", func(w http.ResponseWriter, r *http.Request) { command, channel, value, red, green, blue := parseParams(r.URL.Path[1:]) err := sendCommand(command, channel, value, red, green, blue) if err != nil { fmt.Fprintf(w, "{\"error\": %q}", err) } else { fmt.Fprintf(w, "{\"command\": %q, \"channel\": \"%d\"}", command, channel) } }) fs := http.FileServer(http.Dir("/var/www/static")) http.Handle("/static/", http.StripPrefix("/static/", fs)) panic(http.ListenAndServe(fmt.Sprintf(":%d", *http_port), nil)) } }