add more methods

This commit is contained in:
Ryan Cavicchioni 2020-02-28 19:34:59 -06:00
parent 584c2b2ec5
commit 76cdfd3de3
Signed by: ryanc
GPG Key ID: 877EEDAF9245103D
2 changed files with 45 additions and 11 deletions

View File

@ -14,5 +14,10 @@ func BuildURL(rawurl, rawpath string) string {
var (
Endpoint = "https://api.lifx.com/v1"
EndpointState = func(selector string) string { return BuildURL(Endpoint, fmt.Sprintf("/lights/%s/state", selector)) }
EndpointState = func(selector string) string {
return BuildURL(Endpoint, fmt.Sprintf("/lights/%s/state", selector))
}
EndpointToggle = func(selector string) string {
return BuildURL(Endpoint, fmt.Sprintf("/lights/%s/toggle", selector))
}
)

49
rest.go
View File

@ -28,48 +28,77 @@ func (s *Session) NewRequest(method, url string, body io.Reader) (req *http.Requ
func (s *Session) Request(method, url string, body io.Reader) ([]Result, error) {
req, err := s.NewRequest(method, url, body)
if err != nil {
return []Result{}, err
return nil, err
}
resp, err := s.Client.Do(req)
if err != nil {
return []Result{}, err
return nil, err
}
switch resp.StatusCode {
case http.StatusAccepted:
return []Result{}, nil
return nil, nil
case http.StatusMultiStatus:
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return []Result{}, err
return nil, err
}
r := Results{}
err = json.Unmarshal(body, &r)
if err != nil {
return []Result{}, err
return nil, err
}
return r.Results, nil
}
return []Result{}, nil
return nil, nil
}
func (s *Session) SetState(selector string, state *State) ([]Result, error) {
j, err := json.Marshal(state)
if err != nil {
return []Result{}, err
return nil, err
}
res, err := s.Request("PUT", EndpointState(selector), bytes.NewBuffer(j))
if err != nil {
return []Result{}, err
return nil, err
}
return res, nil
}
func (s *Session) PowerOff(selector string) {
s.SetState(selector, &State{Power: "off"})
func (s *Session) Toggle(selector string, duration float64) ([]Result, error) {
m := make(map[string]interface{})
m["duration"] = duration
j, err := json.Marshal(m)
if err != nil {
return nil, err
}
res, err := s.Request("POST", EndpointToggle(selector), bytes.NewBuffer(j))
if err != nil {
return nil, err
}
return res, nil
}
func (s *Session) PowerOff(selector string) ([]Result, error) {
return s.SetState(selector, &State{Power: "off"})
}
func (s *Session) FastPowerOff(selector string) {
s.SetState(selector, &State{Power: "off", Fast: true})
}
func (s *Session) PowerOn(selector string) ([]Result, error) {
return s.SetState(selector, &State{Power: "on"})
}
func (s *Session) FastPowerOn(selector string) {
s.SetState(selector, &State{Power: "on", Fast: true})
}