noolite-web.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package main
  2. import (
  3. "errors"
  4. "flag"
  5. "fmt"
  6. "github.com/dedkovd/noolite"
  7. "net/http"
  8. "strconv"
  9. "strings"
  10. )
  11. func sendCommand(n *noolite.NooliteAdapter, command string, channel, value, r, g, b int) error {
  12. if channel == -1 {
  13. return errors.New("Channel was not set")
  14. }
  15. if command == "" {
  16. return errors.New("Command was not set")
  17. }
  18. if command == "set" {
  19. if value != 0 {
  20. return n.SetBrightnesValue(channel, value)
  21. } else if r != 0 || g != 0 || b != 0 {
  22. return n.SetBrightnesValues(channel, r, g, b)
  23. } else {
  24. return errors.New("Need some value")
  25. }
  26. } else {
  27. cmd, ok := n.FindCommand(command)
  28. if !ok {
  29. return errors.New("Command not found")
  30. }
  31. return cmd(channel)
  32. }
  33. }
  34. func parseParams(path string) (string, int, int, int, int, int) {
  35. params := strings.Split(path, "/")[1:]
  36. command := ""
  37. channel := -1
  38. value := 0
  39. r := 0
  40. g := 0
  41. b := 0
  42. command = params[0]
  43. if len(params) > 1 {
  44. channel, _ = strconv.Atoi(params[1])
  45. }
  46. if len(params) > 2 {
  47. value, _ = strconv.Atoi(params[2])
  48. }
  49. if len(params) == 5 {
  50. value = 0
  51. r, _ = strconv.Atoi(params[2])
  52. g, _ = strconv.Atoi(params[3])
  53. b, _ = strconv.Atoi(params[4])
  54. }
  55. return command, channel, value, r, g, b
  56. }
  57. func main() {
  58. binding := *flag.String("bind", ":8080", "Address binding")
  59. static_dir := *flag.String("static", "/var/www/static", "Static directory")
  60. flag.Parse()
  61. n, err := noolite.DefaultNooliteAdapter()
  62. if err != nil {
  63. panic(err)
  64. }
  65. defer n.Close()
  66. http.HandleFunc("/noolite/", func(w http.ResponseWriter, r *http.Request) {
  67. command, channel, value, red, green, blue := parseParams(r.URL.Path[1:])
  68. err := sendCommand(n, command, channel, value, red, green, blue)
  69. if err != nil {
  70. fmt.Fprintf(w, "{\"error\": %q}", err)
  71. } else {
  72. fmt.Fprintf(w, "{\"command\": %q, \"channel\": \"%d\"}", command, channel)
  73. }
  74. })
  75. fs := http.FileServer(http.Dir(static_dir))
  76. http.Handle("/static/", http.StripPrefix("/static/", fs))
  77. panic(http.ListenAndServe(binding, nil))
  78. }