├── LICENSE ├── README.md ├── actions.go ├── device.go ├── events.go ├── light.go ├── lock.go ├── request.go └── switch.go /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 Jason Chu 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # go-hass 2 | Incomplete API for interfacing with Home Assistant in Go. 3 | 4 | ## Example use 5 | ```go 6 | package main 7 | 8 | import ( 9 | "fmt" 10 | 11 | "github.com/pawal/go-hass" 12 | ) 13 | 14 | func main() { 15 | h := hass.NewAccess("http://localhost:8123", "") 16 | err := h.CheckAPI() 17 | if err != nil { 18 | panic(err) 19 | } 20 | fmt.Println("API ok") 21 | 22 | // Get a filtered list of devices 23 | list, err := h.FilterStates("switch", "lock", "light") 24 | if err != nil { 25 | panic(err) 26 | } 27 | // Print that list of devices 28 | for d := range list { 29 | fmt.Printf("%s (%s): %s\n", list[d].EntityID, 30 | list[d].Attributes.FriendlyName, 31 | list[d].State) 32 | } 33 | 34 | // Get the state of a device 35 | s, err := h.GetState("group.kitchen") 36 | if err != nil { 37 | panic(err) 38 | } 39 | fmt.Printf("Group kitchen state: %s\n", s.State) 40 | 41 | // Create and interact with a device object 42 | dev := h.GetDevice(s) 43 | fmt.Println("DEV: " + dev.EntityID()) 44 | dev.On() 45 | } 46 | ``` 47 | 48 | ## License 49 | MIT. 50 | -------------------------------------------------------------------------------- /actions.go: -------------------------------------------------------------------------------- 1 | package hass 2 | 3 | import ( 4 | "errors" 5 | "strings" 6 | "time" 7 | ) 8 | 9 | // CheckAPI checks whether or not the API is running. It returns an error 10 | // if it is not running. 11 | func (a *Access) CheckAPI() error { 12 | response := struct { 13 | Message string `json:"message"` 14 | }{} 15 | err := a.httpGet("/api/", &response) 16 | if err != nil { 17 | return err 18 | } 19 | 20 | if response.Message == "" { 21 | return errors.New("hass: API is not running") 22 | } 23 | 24 | return nil 25 | } 26 | 27 | // Bootstrap is an obsolete hass struct, seems to be removed 28 | type Bootstrap struct { 29 | Config struct { 30 | Components []string `json:"components"` 31 | Latitude float64 `json:"latitude"` 32 | Longitude float64 `json:"longitude"` 33 | LocationName string `json:"location_name"` 34 | TemperatureUnit string `json:"temperature_unit"` 35 | Timezone string `json:"time_zone"` 36 | Version string `json:"version"` 37 | } `json:"config"` 38 | Events []struct { 39 | Event string `json:"event"` 40 | ListenerCount int `json:"listener_count"` 41 | } `json:"events"` 42 | Services []struct { 43 | Domain string `json:"domain"` 44 | Services map[string]struct { 45 | Description string `json:"description"` 46 | Fields interface{} `json:"fields"` 47 | } `json:"services"` 48 | } `json:"services"` 49 | States []struct { 50 | Attributes struct { 51 | Auto bool `json:"auto"` 52 | EntityID []string `json:"entity_id"` 53 | FriendlyName string `json:"friendly_name"` 54 | Hidden bool `json:"hidden"` 55 | Order int `json:"order"` 56 | } `json:"attributes"` 57 | EntityID string `json:"entity_id"` 58 | LastChanged time.Time `json:"last_changed"` 59 | LastUpdated time.Time `json:"last_updated"` 60 | State string `json:"state"` 61 | } `json:"states"` 62 | } 63 | 64 | // State is the struct for an object state 65 | type State struct { 66 | Attributes struct { 67 | Auto bool `json:"auto"` 68 | FriendlyName string `json:"friendly_name"` 69 | Hidden bool `json:"hidden"` 70 | Order int `json:"order"` 71 | AssumedState bool `json:"assumed_state"` 72 | } `json:"attributes"` 73 | EntityID string `json:"entity_id"` 74 | LastChanged time.Time `json:"last_changed"` 75 | LastUpdated time.Time `json:"last_updated"` 76 | State string `json:"state"` 77 | } 78 | 79 | // States is an array of State objects 80 | type States []State 81 | 82 | // StateChange is used for changing state on an entity 83 | type StateChange struct { 84 | EntityID string `json:"entityid"` 85 | State string `json:"state"` 86 | } 87 | 88 | // Bootstrap returns the bootstrap information of the system (obsolete) 89 | func (a *Access) Bootstrap() (Bootstrap, error) { 90 | var bootstrap Bootstrap 91 | err := a.httpGet("/api/bootstrap", &bootstrap) 92 | if err != nil { 93 | return Bootstrap{}, err 94 | } 95 | 96 | return bootstrap, nil 97 | } 98 | 99 | // FireEvent fires an event. 100 | func (a *Access) FireEvent(eventType string, eventData interface{}) error { 101 | return a.httpPost("/api/events/"+eventType, eventData) 102 | } 103 | 104 | // CallService calls a service with a domain, service, and entity id. 105 | func (a *Access) CallService(domain, service string, entityID string) error { 106 | serviceData := struct { 107 | EntityID string `json:"entity_id"` 108 | }{entityID} 109 | 110 | return a.httpPost("/api/services/"+domain+"/"+service, serviceData) 111 | } 112 | 113 | // ListStates gets an array of state objects 114 | func (a *Access) ListStates() (s States, err error) { 115 | var list States 116 | err = a.httpGet("/api/states", &list) 117 | if err != nil { 118 | return States{}, err 119 | } 120 | return list, nil 121 | } 122 | 123 | // GetState retrieves one stateobject for the entity id 124 | func (a *Access) GetState(id string) (s State, err error) { 125 | var state State 126 | err = a.httpGet("/api/states/"+id, &state) 127 | if err != nil { 128 | return State{}, err 129 | } 130 | return state, nil 131 | } 132 | 133 | // FilterStates returns a list of states filtered by the list of domains 134 | func (a *Access) FilterStates(domains ...string) (s States, err error) { 135 | list, err := a.ListStates() 136 | if err != nil { 137 | return States{}, err 138 | } 139 | for d := range list { 140 | dom := strings.TrimSuffix(strings.SplitAfter(list[d].EntityID, ".")[0], ".") 141 | for _, fdom := range domains { 142 | if fdom == dom { 143 | s = append(s, list[d]) 144 | } 145 | } 146 | if err != nil { 147 | panic(err) 148 | } 149 | } 150 | 151 | return s, err 152 | } 153 | 154 | // ChangeState changes the state of a device 155 | func (a *Access) ChangeState(id, state string) (s State, err error) { 156 | s.EntityID = id 157 | s.State = state 158 | err = a.httpPost("/api/states/"+id, s) 159 | return State{}, err 160 | } 161 | -------------------------------------------------------------------------------- /device.go: -------------------------------------------------------------------------------- 1 | package hass 2 | 3 | import "strings" 4 | 5 | // Device is a generic interface for interacting with devices 6 | type Device interface { 7 | On() error 8 | Off() error 9 | Toggle() error 10 | EntityID() string 11 | Domain() string 12 | } 13 | 14 | // GetDevice returns a Device object from an State object 15 | func (a *Access) GetDevice(state State) Device { 16 | dom := strings.TrimSuffix(strings.SplitAfter(state.EntityID, ".")[0], ".") 17 | switch dom { 18 | case "light": 19 | return a.NewLight(state.EntityID) 20 | case "switch": 21 | return a.NewSwitch(state.EntityID) 22 | case "lock": 23 | return a.NewLock(state.EntityID) 24 | } 25 | return nil 26 | } 27 | -------------------------------------------------------------------------------- /events.go: -------------------------------------------------------------------------------- 1 | package hass 2 | 3 | import ( 4 | "bufio" 5 | "encoding/json" 6 | "io" 7 | "net/http" 8 | "time" 9 | ) 10 | 11 | type EventListener struct { 12 | reader io.ReadCloser 13 | buffer *bufio.Reader 14 | } 15 | 16 | func (a *Access) ListenEvents() (*EventListener, error) { 17 | client := &http.Client{ 18 | Timeout: time.Second * 10, 19 | } 20 | 21 | req, err := http.NewRequest("GET", a.host+"/api/stream", nil) 22 | if err != nil { 23 | return nil, err 24 | } 25 | 26 | req.Header.Set("x-ha-access", a.password) 27 | 28 | resp, err := client.Do(req) 29 | if err != nil { 30 | return nil, err 31 | } 32 | 33 | return &EventListener{ 34 | reader: resp.Body, 35 | buffer: bufio.NewReader(resp.Body), 36 | }, nil 37 | } 38 | 39 | type StateChangedEvent struct { 40 | Origin string `json:"origin"` 41 | EventType string `json:"event_type"` 42 | TimeFired time.Time `json:"time_fired"` 43 | Data struct { 44 | OldState struct { 45 | EntityID string `json:"entity_id"` 46 | State string `json:"state"` 47 | LastChanged time.Time `json:"last_changed"` 48 | LastUpdated time.Time `json:"last_updated"` 49 | Attributes struct { 50 | EntityID []string `json:"entity_id"` 51 | Order int `json:"order"` 52 | Hidden bool `json:"hidden"` 53 | FriendlyName string `json:"friendly_name"` 54 | Auto bool `json:"auto"` 55 | } `json:"attributes"` 56 | } `json:"old_state"` 57 | EntityID string `json:"entity_id"` 58 | NewState struct { 59 | EntityID string `json:"entity_id"` 60 | State string `json:"state"` 61 | LastChanged time.Time `json:"last_changed"` 62 | LastUpdated time.Time `json:"last_updated"` 63 | Attributes struct { 64 | EntityID []string `json:"entity_id"` 65 | Order int `json:"order"` 66 | Hidden bool `json:"hidden"` 67 | FriendlyName string `json:"friendly_name"` 68 | Auto bool `json:"auto"` 69 | } `json:"attributes"` 70 | } `json:"new_state"` 71 | } `json:"data"` 72 | } 73 | 74 | // NextStateChanged waits and returns for the next state_changed event. 75 | func (e *EventListener) NextStateChanged() (StateChangedEvent, error) { 76 | for { 77 | line, err := e.buffer.ReadBytes('\n') 78 | if err != nil { 79 | return StateChangedEvent{}, err 80 | } 81 | 82 | if len(line) > 6 && string(line[:6]) == "data: " { 83 | jsonData := line[6:] 84 | 85 | var eventTypeFinder struct { 86 | EventType string `json:"event_type"` 87 | } 88 | 89 | err := json.Unmarshal(jsonData, &eventTypeFinder) 90 | if err != nil { 91 | return StateChangedEvent{}, err 92 | } 93 | 94 | if eventTypeFinder.EventType != "state_changed" { 95 | continue 96 | } 97 | 98 | var stateChanged StateChangedEvent 99 | err = json.Unmarshal(jsonData, &stateChanged) 100 | if err != nil { 101 | return StateChangedEvent{}, err 102 | } 103 | 104 | return stateChanged, nil 105 | } 106 | } 107 | } 108 | 109 | // Close closes the event listener library 110 | func (e *EventListener) Close() error { 111 | return e.reader.Close() 112 | } 113 | -------------------------------------------------------------------------------- /light.go: -------------------------------------------------------------------------------- 1 | package hass 2 | 3 | // Light describes a Light class 4 | type Light struct { 5 | id string 6 | state string 7 | access *Access 8 | } 9 | 10 | // NewLight creates a new Light instance 11 | func (a *Access) NewLight(id string) (light *Light) { 12 | return &Light{ 13 | id: id, 14 | access: a, 15 | } 16 | } 17 | 18 | // On turns on a light 19 | func (l *Light) On() (err error) { 20 | return l.access.CallService("light", "turn_on", l.id) 21 | } 22 | 23 | // Off turns off a light 24 | func (l *Light) Off() (err error) { 25 | return l.access.CallService("light", "turn_off", l.id) 26 | } 27 | 28 | // Toggle toggles a switch 29 | func (l *Light) Toggle() (err error) { 30 | return l.access.CallService("light", "toggle", l.id) 31 | } 32 | 33 | // EntityID returns the id of the device object 34 | func (l *Light) EntityID() string { 35 | return l.id 36 | } 37 | 38 | // Domain returns the Home Assistant domain for the device 39 | func (l *Light) Domain() string { 40 | return "light" 41 | } 42 | -------------------------------------------------------------------------------- /lock.go: -------------------------------------------------------------------------------- 1 | package hass 2 | 3 | import "errors" 4 | 5 | // Lock describes a Lock class 6 | type Lock struct { 7 | id string 8 | state string 9 | access *Access 10 | } 11 | 12 | // NewLock creates a new Lock instance 13 | func (a *Access) NewLock(id string) (lock *Lock) { 14 | return &Lock{ 15 | id: id, 16 | access: a, 17 | } 18 | } 19 | 20 | // On locks a lock 21 | func (l *Lock) On() (err error) { 22 | return l.access.CallService("lock", "lock", l.id) 23 | } 24 | 25 | // Off unlocks a lock 26 | func (l *Lock) Off() (err error) { 27 | return l.access.CallService("lock", "unlock", l.id) 28 | } 29 | 30 | // Toggle is supposed to toggle the lock, but is not implemented 31 | func (l *Lock) Toggle() (err error) { 32 | return errors.New("The command 'toggle' is not implemented for locks") 33 | } 34 | 35 | // EntityID returns the id of the device object 36 | func (l *Lock) EntityID() string { 37 | return l.id 38 | } 39 | 40 | // Domain returns the Home Assistant domain for the device 41 | func (l *Lock) Domain() string { 42 | return "lock" 43 | } 44 | -------------------------------------------------------------------------------- /request.go: -------------------------------------------------------------------------------- 1 | package hass 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "errors" 7 | "net/http" 8 | "time" 9 | ) 10 | 11 | type Access struct { 12 | host string 13 | password string 14 | } 15 | 16 | // NewAccess returns a new *Access to be used to interface with the 17 | // Home Assistant system. 18 | func NewAccess(host, password string) *Access { 19 | return &Access{host, password} 20 | } 21 | 22 | func (a *Access) httpGet(path string, v interface{}) error { 23 | client := &http.Client{ 24 | Timeout: time.Second * 10, 25 | } 26 | 27 | req, err := http.NewRequest("GET", a.host+path, nil) 28 | if err != nil { 29 | return err 30 | } 31 | req.Header.Set("x-ha-access", a.password) 32 | 33 | success := false 34 | for i := 0; i < 3; i++ { 35 | func() { 36 | var resp *http.Response 37 | resp, err = client.Do(req) 38 | if err != nil { 39 | return 40 | } 41 | 42 | defer resp.Body.Close() 43 | 44 | if resp.StatusCode != http.StatusOK { 45 | err = errors.New("hass: status not OK: " + resp.Status) 46 | return 47 | } 48 | 49 | dec := json.NewDecoder(resp.Body) 50 | err = dec.Decode(v) 51 | success = true 52 | }() 53 | 54 | if success { 55 | break 56 | } 57 | } 58 | 59 | return err 60 | } 61 | 62 | func (a *Access) httpPost(path string, v interface{}) error { 63 | var req *http.Request 64 | 65 | if v != nil { 66 | data, err := json.Marshal(v) 67 | if err != nil { 68 | return err 69 | } 70 | 71 | req, err = http.NewRequest("POST", a.host+path, bytes.NewReader(data)) 72 | if err != nil { 73 | return err 74 | } 75 | 76 | req.Header.Set("Content-Type", "application/json") 77 | } else { 78 | var err error 79 | req, err = http.NewRequest("POST", a.host+path, nil) 80 | if err != nil { 81 | return err 82 | } 83 | } 84 | 85 | client := &http.Client{ 86 | Timeout: time.Second * 10, 87 | } 88 | 89 | req.Header.Set("x-ha-access", a.password) 90 | 91 | var err error 92 | success := false 93 | for i := 0; i < 3; i++ { 94 | func() { 95 | var resp *http.Response 96 | resp, err = client.Do(req) 97 | if err != nil { 98 | return 99 | } 100 | 101 | defer resp.Body.Close() 102 | 103 | success = true 104 | }() 105 | 106 | if success { 107 | break 108 | } 109 | } 110 | 111 | return err 112 | } 113 | -------------------------------------------------------------------------------- /switch.go: -------------------------------------------------------------------------------- 1 | package hass 2 | 3 | // Switch describes a Switch class 4 | type Switch struct { 5 | id string 6 | state string 7 | access *Access 8 | } 9 | 10 | // NewSwitch creates a new Switch instance 11 | func (a *Access) NewSwitch(id string) (s *Switch) { 12 | // d := strings.SplitAfter(id, ".")[0] 13 | return &Switch{ 14 | id: id, 15 | access: a, 16 | } 17 | } 18 | 19 | // On turns on a switch 20 | func (s *Switch) On() (err error) { 21 | return s.access.CallService("switch", "turn_on", s.id) 22 | } 23 | 24 | // Off turns off a switch 25 | func (s *Switch) Off() (err error) { 26 | return s.access.CallService("switch", "turn_off", s.id) 27 | } 28 | 29 | // Toggle toggles a switch 30 | func (s *Switch) Toggle() (err error) { 31 | return s.access.CallService("switch", "toggle", s.id) 32 | } 33 | 34 | // EntityID returns the id of the device object 35 | func (s *Switch) EntityID() string { 36 | return s.id 37 | } 38 | 39 | // Domain returns the Home Assistant domain for the device 40 | func (s *Switch) Domain() string { 41 | return "switch" 42 | } 43 | --------------------------------------------------------------------------------