initial commit

This commit is contained in:
Ryan Cavicchioni 2020-02-23 21:01:12 -06:00
parent 25fd03b1b1
commit 7358c00200
Signed by: ryanc
GPG Key ID: 877EEDAF9245103D
4 changed files with 99 additions and 0 deletions

24
cmd/lifx.go Normal file
View File

@ -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))
}

18
endpoints.go Normal file
View File

@ -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)) }
)

33
rest.go Normal file
View File

@ -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
}

24
structs.go Normal file
View File

@ -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
}
)