smarthome_sdk

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: May 6, 2022 License: GPL-2.0 Imports: 8 Imported by: 0

README

smarthome-sdk

A go package which makes communication to a smarthome server simple

Documentation

Index

Constants

View Source
const Version = "0.1.0"

Variables

View Source
var (
	ErrNotInitialized      = errors.New("action failed: initialize connection first")
	ErrInvalidURL          = errors.New("invalid url: the url could not be parsed")
	ErrConnFailed          = errors.New("connection failed: request failed due to network issues")
	ErrServiceUnavailable  = errors.New("request failed: smarthome is currently unavailable")
	ErrInternalServerError = errors.New("request failed: smarthome failed internally")
	ErrInvalidCredentials  = errors.New("authentication failed: invalid credentials")
	ErrNoCookiesSent       = errors.New("login request did not respond with an expected cookie")
	ErrAlreadyInitialized  = errors.New("cannot initialize: already initialized")
	ErrUnauthorized        = errors.New("request failed: not authorized")
	ErrReadResponseBody    = errors.New("could not read body from response")
	ErrPermissionDenied    = errors.New("no permission to access this ressource")
	ErrInvalidSwitch       = errors.New("invalid switch id: no such switch exists")
	ErrUnprocessableEntity = errors.New("unprocessable entity: invalid or conflicting data")
)

Functions

This section is empty.

Types

type AuthMethod

type AuthMethod uint8
const (
	/** No authentication will send every request without any form of user-authentication
	- Can be used in a context which does not require authentication, for example, listing the switches
	- Not reccomended in most cases due to the strict data protection of Smarthome
	*/
	AuthMethodNone AuthMethod = iota

	/** Cookie authentication relies on a cookie-store which sends a authentication cookie at every request
	- Faster response-time: The server does not need to revalidate the user's credentials on every request
	- Static: If the Smarthome server is restarted, the stored cookie becomes invalid and the communication breaks
	- Not recommended for long-running applications
	*/
	AuthMethodCookie

	/** URL-query authentication adds `?username=foo&password=bar` to every requested URL
	- Slower response-time: The server needs to revalidate the user's credentials on every request
	- Dynamic: The connection will remain in a working condition after the smarthome server has been restarted
	- Recommended for long-running applications
	*/
	AuthMethodQuery
)

Specifies how the library handles authentication

type Connection

type Connection struct {
	// The username which will be used if `AuthMethodCookie` or `AuthMethodQuery` is set
	// If `AuthMethodCookie` is used, the username will only be used in the login function
	Username string
	// The password which will be used if `AuthMethodCookie` or `AuthMethodQuery` is set
	// If `AuthMethodCookie` is used, the password will only be used in the login function
	Password string
	// The base URL which will be used to create all request
	SmarthomeURL *url.URL
	// Stores which authentication mode will be used
	AuthMethod AuthMethod
	// The cookie-store which will be used if `AuthMethodCookie` is set
	// The store is written to once in the login function
	// Every request will access the store in order to include the cookie in the request
	SessionCookie *http.Cookie
	// contains filtered or unexported fields
}

func NewConnection

func NewConnection(smarthomeURL string, authMethod AuthMethod) (*Connection, error)

Creates a new connection First argument specifies the base URL of the target Smarthome-server Second argument specifies how to handle authentication

func (*Connection) Connect

func (c *Connection) Connect(username string, password string) error

If the authentication mode is set to `AuthMethodNone`, both arguments can be set to nil Otherwise, username and password are required to login

func (*Connection) CreateHomescript added in v0.3.0

func (c *Connection) CreateHomescript(data HomescriptRequest) error

Creates a new Homescript which is owned by the current user * Errors - nil - ErrNotInitialized - ErrConnFailed - ErrReadResponseBody - ErrInvalidCredentials - ErrPermissionDenied - PrepareRequest errors - ErrUnprocessableEntity (conflicting id / invalid data) - Unknown

func (*Connection) DeleteHomescript added in v0.3.0

func (c *Connection) DeleteHomescript(id string) error

Deletes an existing Homescript which is owned by the current user * Errors - nil - ErrNotInitialized - ErrConnFailed - ErrReadResponseBody - ErrInvalidCredentials - ErrPermissionDenied - PrepareRequest errors - ErrUnprocessableEntity (invalid id) - Unknown

func (*Connection) GetAllSwitches added in v0.2.0

func (c *Connection) GetAllSwitches() (switches []Switch, err error)

Returns a list containing all switches of the target instance * Errors - nil - ErrServiceUnavailable - ErrReadResponseBody - ErrConnFailed - ErrNotInitialized - PrepareRequest errors

func (*Connection) GetDebugInfo

func (c *Connection) GetDebugInfo() (info DebugInfoData, err error)

Retrieves debugging information from the smarthome server * Errors - nil - ErrNotInitialized - ErrConnFailed - ErrReadResponseBody - ErrInvalidCredentials - ErrServiceUnavailable - PrepareRequest errors - ErrPermissionDenied

func (*Connection) GetPersonalSwitches

func (c *Connection) GetPersonalSwitches() (switches []Switch, err error)

Returns a list of switches to which the user has access to * Errors - nil - ErrInvalidCredentials - ErrServiceUnavailable - ErrReadResponseBody - ErrConnFailed - ErrNotInitialized - PrepareRequest errors

func (*Connection) HealthCheck

func (c *Connection) HealthCheck() (status HealthStatus, err error)

Can be used in order to check if the Smarthome server is reachable and responds Returns an ENUM type indicating the overall health status of the server

func (*Connection) ModifyHomescript added in v0.3.0

func (c *Connection) ModifyHomescript(data HomescriptRequest) error

Modifies an existing Homescript which is owned by the current user * Errors - nil - ErrNotInitialized - ErrConnFailed - ErrReadResponseBody - ErrInvalidCredentials - ErrPermissionDenied - PrepareRequest errors - ErrUnprocessableEntity (invalid id / in valid data) - Unknown

func (*Connection) RunHomescript

func (c *Connection) RunHomescript(code string, timeout time.Duration) (response HomescriptResponse, err error)

Executes a string of homescript code on the Smarthome-server Returns a Homescript-response and an error The error is meant to indicate a failure of communication, not a failure of execution Normally, a `ErrConnFailed` indicates that the server is not reachable, however if other requests work a `ErrConnFailed` could indicate a request-timeout. In this case, check if you need to increase the timeout * Errors - nil - ErrNotInitialized - ErrConnFailed - ErrReadResponseBody - ErrInvalidCredentials - ErrPermissionDenied - PrepareRequest errors - Unknown

func (*Connection) SetPower

func (c *Connection) SetPower(switchId string, powerOn bool) error

Sends a power request to Smarthome Only switch to which the user has permission to will work * Errors - nil - ErrNotInitialized - ErrConnFailed - ErrServiceUnavailable - ErrInvalidSwitch - ErrPermissionDenied - PrepareRequest errors - Unknown

type DBStatus

type DBStatus struct {
	OpenConnections int `json:"openConnections"`
	InUse           int `json:""`
	Idle            int `json:""`
}

type DebugInfoData

type DebugInfoData struct {
	ServerVersion          string      `json:"version"`
	DatabaseOnline         bool        `json:"databaseOnline"`
	DatabaseStats          DBStatus    `json:"databaseStats"`
	CpuCores               uint8       `json:"cpuCores"`
	Goroutines             uint16      `json:"goroutines"`
	GoVersion              string      `json:"goVersion"`
	MemoryUsage            uint16      `json:"memoryUsage"`
	PowerJobCount          uint16      `json:"powerJobCount"`
	PowerJobWithErrorCount uint16      `json:"lastPowerJobErrorCount"`
	PowerJobs              []PowerJob  `json:"powerJobs"`
	PowerJobResults        []JobResult `json:"powerJobResults"`
}

Is returned when the debug information is requested

type ErrorLocation

type ErrorLocation struct {
	Filename string `json:"filename"`
	Line     uint   `json:"line"`
	Column   uint   `json:"column"`
	Index    uint   `json:"index"`
}

Specifies where the Homescript error occurred

type HTTPMethod

type HTTPMethod string
const (
	Get    HTTPMethod = "GET"
	Post   HTTPMethod = "POST"
	Put    HTTPMethod = "PUT"
	Delete HTTPMethod = "DELETE"
)

type HealthStatus

type HealthStatus uint
const (
	StatusUnknown           HealthStatus = iota //Default return value if a request error occurs
	StatusHealthy                               // All systems are in a operational state
	StatusPartiallyDegraded                     // Some systems are degraded, for example one out of more Hardware nodes have failed recently
	StatusDegraded                              // The database connection has failed, Smarthome cannot be used in this state
)

type Homescript added in v0.3.0

type Homescript struct {
	Id                  string `json:"id"`
	Owner               string `json:"owner"`
	Name                string `json:"name"`
	Description         string `json:"description"`
	QuickActionsEnabled bool   `json:"quickActionsEnabled"`
	SchedulerEnabled    bool   `json:"schedulerEnabled"`
	Code                string `json:"code"`
}

Represents a Homescript entity

type HomescriptError

type HomescriptError struct {
	ErrorType string        `json:"errorType"`
	Location  ErrorLocation `json:"location"`
	Message   string        `json:"message"`
}

Contains information about why a Homescript terminated

type HomescriptRequest added in v0.3.0

type HomescriptRequest struct {
	Id                  string `json:"id"`
	Name                string `json:"name"`
	Description         string `json:"description"`
	QuickActionsEnabled bool   `json:"quickActionsEnabled"`
	SchedulerEnabled    bool   `json:"schedulerEnabled"`
	Code                string `json:"code"`
}

Used for creating a new script or modifying an existing one

type HomescriptResponse

type HomescriptResponse struct {
	Success  bool              `json:"success"`
	Exitcode int               `json:"exitCode"`
	Message  string            `json:"message"`
	Output   string            `json:"output"`
	Errors   []HomescriptError `json:"error"`
}

Under normal conditions, Smarthome will return such a response

type JobResult

type JobResult struct {
	Id    int64 `json:"id"`
	Error error `json:"error"`
}

type PowerJob

type PowerJob struct {
	Id         int64  `json:"id"`
	SwitchName string `json:"switchName"`
	Power      bool   `json:"power"`
}

type Switch

type Switch struct {
	Id      string `json:"id"`
	Name    string `json:"name"`
	RoomId  string `json:"roomId"`
	PowerOn bool   `json:"powerOn"`
	Watts   uint16 `json:"watts"`
}

Switch Response from Smarthome Id is a unique identifier used for many actions regarding switches

Jump to

Keyboard shortcuts

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