diff --git a/cmd/lifx.go b/cmd/lifx.go new file mode 100644 index 0000000..d1ed696 --- /dev/null +++ b/cmd/lifx.go @@ -0,0 +1,24 @@ +package main + +import ( + "fmt" + "git.kill0.net/chill9/lifx" + "os" + "time" +) + +func main() { + apiToken := os.Getenv("LIFX_API_TOKEN") + if apiToken == "" { + fmt.Println("LIFX_API_TOKEN is undefined") + os.Exit(1) + } + s := &lifx.State{Power: "on", Color: "white"} + c := lifx.NewSession(apiToken) + c.SetState("group:Office", s) + time.Sleep(10) + c.SetState("all", &lifx.State{Power: "on", Color: "green"}) + time.Sleep(10) + c.SetState("all", &lifx.State{Power: "off"}) + fmt.Println(lifx.EndpointState(lifx.Endpoint)) +} diff --git a/endpoints.go b/endpoints.go new file mode 100644 index 0000000..ad2ba1a --- /dev/null +++ b/endpoints.go @@ -0,0 +1,18 @@ +package lifx + +import ( + "fmt" + "net/url" + "path" +) + +func BuildURL(rawurl, rawpath string) string { + u, _ := url.Parse(rawurl) + u.Path = path.Join(u.Path, rawpath) + return u.String() +} + +var ( + Endpoint = "https://api.lifx.com/v1" + EndpointState = func(selector string) string { return BuildURL(Endpoint, fmt.Sprintf("/lights/%s/state", selector)) } +) diff --git a/rest.go b/rest.go new file mode 100644 index 0000000..5b733fe --- /dev/null +++ b/rest.go @@ -0,0 +1,33 @@ +package lifx + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "net/http" +) + +func NewSession(token string) *Session { + return &Session{ + token: token, + Client: &http.Client{}, + } +} + +func (s *Session) NewRequest(method, url string, body io.Reader) *http.Request { + req, _ := http.NewRequest(method, url, body) + req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", s.token)) + return req +} + +func (s *Session) SetState(selector string, state *State) error { + j, _ := json.Marshal(state) + req := s.NewRequest("PUT", EndpointState(selector), bytes.NewBuffer(j)) + resp, err := s.Client.Do(req) + if err != nil { + return err + } + fmt.Println(resp) + return nil +} diff --git a/structs.go b/structs.go new file mode 100644 index 0000000..5f8d763 --- /dev/null +++ b/structs.go @@ -0,0 +1,24 @@ +package lifx + +import ( + "net/http" +) + +const API_BASE_URL = "https://api.lifx.com/v1" + +type ( + State struct { + Power string `json:"power,omitempty"` + Color string `json:"color,omitempty"` + Brightness float64 `json:"brightness,omitempty"` + Duration float64 `json:"duration,omitempty"` + Infrared float64 `json:"infrared,omitempty"` + Fast bool `json:"fast,omitempty"` + } + + Session struct { + BaseUrl string + token string + Client *http.Client + } +)