go_ha_client

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 2, 2023 License: MIT Imports: 14 Imported by: 2

README

go-ha-client

Go client for home-assistant REST API. Tested with home-assistant core-2021.7.2

Basic usage

Change Token and Host to your actual home-assistant bearer token and address Check home-assistant documentation how get access token.

package main

import (
	"context"
	"fmt"
	ha "github.com/mkelcik/go-ha-client"
	"net/http"
	"time"
)

func main() {
	client := ha.NewClient(ha.ClientConfig{Token: "mytoken", Host: "http://my-ha.home"}, &http.Client{
		Timeout: 30 * time.Second,
	})
    
	// ping instance
	if err := client.Ping(context.Background()); err != nil {
		fmt.Println("connection error", err)
	} else {
		fmt.Println("connection ok")
	}

	// example of home-assistant instance info
	discoverInfo, err := client.GetDiscoverInfo(context.Background())
	if err != nil {
		panic(err)
	}
	fmt.Printf("%+v", discoverInfo)
}
Examples

To turn light with entity id light.light_1 on, we can use NewTurnLightOnCmd helper, to create command and call service.

// turn light on
if _, err := client.CallService(context.Background(), ha.NewTurnLightOnCmd("light.light_1")); err != nil {
	panic(err)
}

// turn light off 
if _, err := client.CallService(context.Background(), ha.NewTurnLightOffCmd("light.light_1")); err != nil {
	panic(err)
}

or turn switch.switch_1 off without helper

if _, err := client.CallService(context.Background(), DefaultServiceCmd{
    Service:  "turn_off",
    Domain:   "switch", 
    EntityId: "switch.switch_1",
}); err != nil {
	panic(err)
}

Take and save picture from camera

camImg, err := client.GetCameraJpeg(context.Background(), "camera.my_camera")
if err != nil {
	panic(err)
}

f, err := os.Create("camera.jpg")
if err != nil {
	panic(err)
}
defer f.Close()

if err := jpeg.Encode(f, camImg, nil); err != nil {
	panic(err)
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var NotFoundError = errors.New("not found")
View Source
var UnAuthorizedError = errors.New("unauthorized")

Functions

This section is empty.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

func NewClient

func NewClient(config ClientConfig, client *http.Client) *Client

func (*Client) CallService

func (c *Client) CallService(ctx context.Context, cmd DefaultServiceCmd) (StateEntities, error)

func (*Client) CreateState

func (c *Client) CreateState(ctx context.Context, entityId string, newState State) (StateResponse, error)

func (*Client) FireEvent

func (c *Client) FireEvent(ctx context.Context, eventType string, atTime *time.Time) (bool, error)

func (*Client) GetCameraJpeg

func (c *Client) GetCameraJpeg(ctx context.Context, cameraEntityId string) (image.Image, error)

func (*Client) GetConfig

func (c *Client) GetConfig(ctx context.Context) (Config, error)

func (*Client) GetDiscoverInfo

func (c *Client) GetDiscoverInfo(ctx context.Context) (DiscoveryInfo, error)

func (*Client) GetEvents

func (c *Client) GetEvents(ctx context.Context) (Events, error)

func (*Client) GetLogbook

func (c *Client) GetLogbook(ctx context.Context, filter *LogbookFilter) (LogbookRecords, error)

func (*Client) GetPlainErrorLog

func (c *Client) GetPlainErrorLog(ctx context.Context) (PlainText, error)

func (*Client) GetServices

func (c *Client) GetServices(ctx context.Context) (Services, error)

func (*Client) GetStateChangesHistory

func (c *Client) GetStateChangesHistory(ctx context.Context, filter *StateChangesFilter) (StateChanges, error)

func (*Client) GetStateForEntity

func (c *Client) GetStateForEntity(ctx context.Context, entityId string) (StateEntity, error)

func (*Client) GetStates

func (c *Client) GetStates(ctx context.Context) (StateEntities, error)

func (*Client) Ping

func (c *Client) Ping(ctx context.Context) error

func (*Client) RenderTemplate

func (c *Client) RenderTemplate(ctx context.Context, template string) (string, error)

func (*Client) TriggerConfigCheck

func (c *Client) TriggerConfigCheck(ctx context.Context) (ConfigurationCheckResult, error)

type ClientConfig

type ClientConfig struct {
	Debug bool
	Token string
	Host  string
}

type Config

type Config struct {
	Components   []string `json:"components"`
	ConfigDir    string   `json:"config_dir"`
	Elevation    int      `json:"elevation"`
	Latitude     float64  `json:"latitude"`
	LocationName string   `json:"location_name"`
	Longitude    float64  `json:"longitude"`
	TimeZone     string   `json:"time_zone"`
	UnitSystem   struct {
		Length      string `json:"length"`
		Mass        string `json:"mass"`
		Temperature string `json:"temperature"`
		Volume      string `json:"volume"`
	} `json:"unit_system"`
	Version               string   `json:"version"`
	WhitelistExternalDirs []string `json:"whitelist_external_dirs"`
}

type ConfigurationCheckResult

type ConfigurationCheckResult struct {
	Errors *string `json:"errors"`
	Result string  `json:"result"`
}

type DefaultServiceCmd

type DefaultServiceCmd struct {
	Service  string `json:"-"`
	Domain   string `json:"-"`
	EntityId string `json:"entity_id"`
}

func NewToggleLightTCmd added in v0.4.0

func NewToggleLightTCmd(entityId string) DefaultServiceCmd

NewToggleLightTCmd is helper for turning light off

func NewTurnLightOffCmd

func NewTurnLightOffCmd(entityId string) DefaultServiceCmd

NewTurnLightOffCmd is helper for turning light off

func NewTurnLightOnCmd

func NewTurnLightOnCmd(entityId string) DefaultServiceCmd

NewTurnLightOnCmd is helper for turning light on

func (DefaultServiceCmd) Reader

func (c DefaultServiceCmd) Reader() io.Reader

type DiscoveryInfo

type DiscoveryInfo struct {
	BaseUrl             string `json:"base_url"`
	LocationName        string `json:"location_name"`
	RequiresApiPassword bool   `json:"requires_api_password"`
	Version             string `json:"version"`
}

type EntityChange

type EntityChange struct {
	EntityId    string                 `json:"entity_id"`
	State       string                 `json:"state"`
	Attributes  map[string]interface{} `json:"attributes"`
	LastChanged time.Time              `json:"last_changed"`
	LastUpdated time.Time              `json:"last_updated"`
}

func (*EntityChange) GetFriendlyName

func (e *EntityChange) GetFriendlyName() string

type Event

type Event struct {
	Event         string `json:"event"`
	ListenerCount int    `json:"listener_count"`
}

type Events

type Events []Event

type LogbookFilter

type LogbookFilter struct {
	StartTime time.Time
	EndTime   time.Time `json:"end_time"`
	EntityId  string    `json:"entity"`
}

func (*LogbookFilter) String

func (f *LogbookFilter) String() string

type LogbookRecord

type LogbookRecord struct {
	When     time.Time `json:"when"`
	Name     string    `json:"name"`
	State    string    `json:"state"`
	EntityId string    `json:"entity_id"`
	Icon     string    `json:"icon"`
}

type LogbookRecords

type LogbookRecords []LogbookRecord

type PlainText

type PlainText string

type Service

type Service struct {
	Name        string                  `json:"name"`
	Description string                  `json:"description"`
	Fields      map[string]ServiceField `json:"fields"`
	Target      struct {
		Entity []map[string]interface{} `json:"entity"`
	} `json:"target"`
}

type ServiceDomain

type ServiceDomain struct {
	Domain   string             `json:"domain"`
	Services map[string]Service `json:"services"`
}

type ServiceField

type ServiceField struct {
	Advanced    bool                              `json:"advanced"`
	Name        string                            `json:"name"`
	Description string                            `json:"description"`
	Required    bool                              `json:"required"`
	Example     interface{}                       `json:"example"`
	Selector    map[string]map[string]interface{} `json:"selector"`
}

type Services

type Services []ServiceDomain

type State

type State struct {
	State      string                 `json:"state"`
	Attributes map[string]interface{} `json:"attributes"`
}

type StateChanges

type StateChanges [][]EntityChange

type StateChangesFilter

type StateChangesFilter struct {
	StartTime              time.Time
	EndTime                time.Time `json:"end_time"`
	FilterEntityId         string    `json:"filter_entity_id"`
	MinimalResponse        bool      `json:"minimal_response"`
	SignificantChangesOnly bool      `json:"significant_changes_only"`
}

StateChangesFilter use json tags to construct queryParams

func (*StateChangesFilter) String

func (f *StateChangesFilter) String() string

type StateEntities

type StateEntities []StateEntity

type StateEntity

type StateEntity struct {
	EntityId    string                 `json:"entity_id"`
	State       string                 `json:"state"`
	Attributes  map[string]interface{} `json:"attributes"`
	LastChanged time.Time              `json:"last_changed"`
	LastUpdated time.Time              `json:"last_updated"`
	Context     struct {
		Id       string `json:"id"`
		ParentId string `json:"parent_id"`
		UserId   string `json:"user_id"`
	} `json:"context"`
}

type StateResponse

type StateResponse struct {
	State
	CreateCode  int       `json:"-"`
	EntityId    string    `json:"entity_id"`
	LastChanged time.Time `json:"last_changed"`
	LastUpdated time.Time `json:"last_updated"`
}

func (StateResponse) Created added in v0.4.0

func (s StateResponse) Created() bool

func (StateResponse) Updated added in v0.4.0

func (s StateResponse) Updated() bool

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL