openhab

package
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Feb 14, 2024 License: Apache-2.0 Imports: 24 Imported by: 0

Documentation

Index

Constants

View Source
const (
	StateNULL = "NULL"
	StateOFF  = "OFF"
	StateON   = "ON"
)
View Source
const (
	MetricItemName         = "item_name"
	MetricRuleID           = "rule_id"
	MetricItemCacheHit     = "item.cache_hit"
	MetricItemLoad         = "item.load"
	MetricItemLoadState    = "item.load_state"
	MetricItemSetState     = "item.set_state"
	MetricItemNotFound     = "item.not_found"
	MetricItemStateUpdated = "item.state_updated"
	MetricItemsCacheSize   = "items.cache_size"
	MetricRuleAdded        = "rule.added"
	MetricRuleDeleted      = "rule.deleted"
	MetricRulesCount       = "rules.count"
)
View Source
const DateTimeFormat = "2006-01-02T15:04:05.999-0700"

Variables

View Source
var (
	ErrorNotFound           = errors.New("not found")
	ErrRuleAlreadyActivated = errors.New("rule already activated")
)

Functions

func Debounce

func Debounce(after time.Duration, triggers ...Trigger) *triggerDebounce

Debounce will trigger the event after some time, in case the subscription is triggered multiple times in a row. Typically this is the case of Connection and Disconnection system events when openHAB is starting

func OnAlive added in v0.7.0

func OnAlive() *systemEventTrigger

OnAlive is a trigger activated when the client receives an ALIVE event from the server. This event is sent by OpenHAB version 3.4+ (API v5+)

func OnConnect

func OnConnect() *systemEventTrigger

OnConnect is a trigger activated when successfully connected (or reconnected) to openHAB.

This event is only activated the first time openHAB sends any data to the event bus API

Please note when openHAB is starting, the event may be triggered many times: you might want to look at Debounce to avoid too many triggers.

On my setup, a Debounce of 1 minute works well and the event gets triggered only once during a restart

func OnDateTime added in v0.6.0

func OnDateTime(dateTime time.Time) *dateTimeTrigger

OnDateTime will trigger the event only once: at the exact time.Time passed in argument. If the time argument is in the past, no trigger will ever run.

func OnDisconnect

func OnDisconnect() *systemEventTrigger

OnDisconnect is a trigger activated when the connection to openHAB is lost

func OnError added in v0.3.0

func OnError() *systemEventTrigger

OnError is a trigger activated when the client wasn't able to contact openHAB server

func OnItemReceivedCommand

func OnItemReceivedCommand(item string, state State) *itemReceivedCommandTrigger

OnItemReceivedCommand triggers the rule when the item received a command equal to state. Use a nil state to receive ANY command sent to the item This is an equivalent of the DSL rule:

Item <item> received command [<command>]

func OnItemReceivedState

func OnItemReceivedState(item string, state State) *itemReceivedStateTrigger

OnItemReceivedState triggers the rule when the item received an update equal to state. pass nil to state to receive ANY update of the state This is an equivalent of the DSL rule:

Item <item> received update [<state>]

func OnItemStateChanged

func OnItemStateChanged(item string) *itemStateChangedTrigger

OnItemStateChanged triggers the rule when the item received an update with a different state This is an equivalent of the DSL rule:

Item <item> changed

func OnItemStateChangedFrom

func OnItemStateChangedFrom(item string, from State) *itemStateChangedTrigger

OnItemStateChangedFrom triggers the rule when the item received an update with a different state This is an equivalent of the DSL rule:

Item <item> changed from <state>

func OnItemStateChangedFromTo

func OnItemStateChangedFromTo(item string, from, to State) *itemStateChangedTrigger

OnItemStateChangedFromTo triggers the rule when the item received an update with a different state This is an equivalent of the DSL rule:

Item <item> changed from <state> to <state>

func OnItemStateChangedTo

func OnItemStateChangedTo(item string, to State) *itemStateChangedTrigger

OnItemStateChangedTo triggers the rule when the item received an update with a different state This is an equivalent of the DSL rule:

Item <item> changed to <state>

func OnStableConnection added in v0.6.0

func OnStableConnection() *systemEventTrigger

OnStableConnection is a trigger activated when the connection has been stable for some time. When openHAB restarts, a connection to the API could be disconnected many times until openHAB finished all its initialization process.

func OnStart

func OnStart() *systemEventTrigger

OnStart is a trigger activated when the client has started. At this stage, the client may be connected to the openHAB event bus.

func OnStartlevel added in v0.8.0

func OnStartlevel() *systemEventTrigger

OnStartlevel is a trigger activated when the server sends Startlevel events during startup.

func OnStop

func OnStop() *systemEventTrigger

OnStop is a trigger activated when the client is about to stop. There's no guarantee it is going to be the last running event, some other queued events may still run after.

func OnThingReceivedStatusInfo added in v0.7.0

func OnThingReceivedStatusInfo(thing string, status ThingStatus) *thingReceivedStatusInfoTrigger

OnThingReceivedStatusInfo triggers the rule when the thing received a status update equal to status. pass ThingStatusAny or "" to status to receive ANY update of the status This is an equivalent of the DSL rule:

Thing <thingUID> received update [<status>] Thing <thingUID> changed [from <status>] [to <status>]

func OnThingReceivedStatusInfoChanged added in v0.7.0

func OnThingReceivedStatusInfoChanged(thing string) *thingReceivedStatusInfoChangedTrigger

OnThingReceivedStatusInfoChanged triggers the rule when the thing status changed. This is an equivalent of the DSL rule:

Thing <thingUID> changed

func OnThingReceivedStatusInfoChangedFrom added in v0.7.0

func OnThingReceivedStatusInfoChangedFrom(thing string, from ThingStatus) *thingReceivedStatusInfoChangedTrigger

OnThingReceivedStatusInfoChanged triggers the rule when the thing status changed from a value. pass ThingStatusAny or "" to status to receive ANY update of the status This is an equivalent of the DSL rule:

Thing <thingUID> changed from <status>

func OnThingReceivedStatusInfoChangedFromTo added in v0.7.0

func OnThingReceivedStatusInfoChangedFromTo(thing string, from, to ThingStatus) *thingReceivedStatusInfoChangedTrigger

OnThingReceivedStatusInfoChanged triggers the rule when the thing status changed from a value to another value. This is an equivalent of the DSL rule:

Thing <thingUID> changed from <status> to <status>

func OnThingReceivedStatusInfoChangedTo added in v0.7.0

func OnThingReceivedStatusInfoChangedTo(thing string, to ThingStatus) *thingReceivedStatusInfoChangedTrigger

OnThingReceivedStatusInfoChanged triggers the rule when the thing status changed to a value. pass ThingStatusAny or "" to status to receive ANY update of the status This is an equivalent of the DSL rule:

Thing <thingUID> changed to <status>

func OnTimeCron

func OnTimeCron(spec string) *timeCronTrigger

OnTimeCron creates a trigger from a cron entry. Please note the YEAR field is NOT supported. The 6 fields are: "second minute hour dayOfMonth month dayOfWeek" For more information, see the quartz format: http://www.quartz-scheduler.org/documentation/quartz-2.3.0/tutorials/crontrigger.html

func SetDebugLog

func SetDebugLog(logger Logger)

func SetErrorLog

func SetErrorLog(logger Logger)

Types

type Client

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

Client for openHAB. It's using openHAB REST API internally.

func NewClient

func NewClient(config Config) *Client

NewClient creates a new client to connect to a openHAB instance

func (*Client) AddRule

func (c *Client) AddRule(ruleData RuleData, run Runner, triggers ...Trigger) (ruleID string)

AddRule adds a rule definition.

  • ruleData: all fields are optional.
  • run: runner function that will be called when the rule is triggered.
  • triggers: these are the triggers that will activate the rule.

func (*Client) DeleteRule added in v0.6.0

func (c *Client) DeleteRule(ruleID string) int

DeleteRule deletes all the rule definition using their ruleID (it could be 0 to many) and returns the number of rules deleted

func (*Client) GetItem added in v0.2.0

func (c *Client) GetItem(name string) (*Item, error)

GetItem returns an openHAB item from its name. The very first call of GetItem will try to load the items collection from openHAB. If not found, returns an openhab.ErrorNotFound error.

func (*Client) GetItemState added in v0.6.0

func (c *Client) GetItemState(name string) (State, error)

GetItemState returns an openHAB item state from its name. It's a shortcut of GetItem() => State(). The very first call of GetItemState will try to load the items collection from openHAB.

func (*Client) GetMembersOf added in v0.2.0

func (c *Client) GetMembersOf(groupName string) ([]*Item, error)

GetMembersOf returns a list of items member of the group

func (*Client) GetRulesData added in v0.8.0

func (c *Client) GetRulesData() []RuleData

GetRulesData returns the list of rules definition

func (*Client) RefreshCache added in v0.10.0

func (c *Client) RefreshCache() error

RefreshCache will force a reload of all the items from openHAB. You shouldn't need to call this method, as the items are loaded on demand. I've only experienced the need to call this method when the openHAB server was restarted, as the cache was loaded before openHAB finished its initialization.

func (*Client) SendCommand added in v0.6.0

func (c *Client) SendCommand(itemName string, command State) error

SendCommand sends a command to an item. It's a shortcut for GetItem() => SendCommand().

func (*Client) SendCommandWait added in v0.6.0

func (c *Client) SendCommandWait(itemName string, command State, timeout time.Duration) (bool, error)

SendCommandWait sends a command to an item and wait until the event bus acknowledge receiving the state, or after a timeout It returns true if openHAB acknowledge it's setting the desired state to the item (even if it's the same value as before). It returns false in case the acknowledged value is different than the command, or after timeout. It's a shortcut for GetItem() => SendCommandWait().

func (*Client) Start

func (c *Client) Start()

Start the handling of the defined rules. The function will return after the process received a Terminate, Abort or Interrupt signal, and after all the currently running rules have finished

Please note a client can only be started once. Any other call to this method will be ignored.

func (*Client) Stop

func (c *Client) Stop()

Stop will send a ClientStopped event, let all the currently running rules finish, close the client, then return. Stop can only be called once, any subsequent call will be ignored.

type ClientState added in v0.7.0

type ClientState int
const (
	StateStarting ClientState = iota
	StateConnecting
	StateConnected
	StateDisconnected
)

type Config

type Config struct {
	// URL of you openHAB instance. It should detect automatically the REST API URL from the main URL.
	URL      string
	User     string
	Password string
	// APIToken takes precedence over User/Password authentication
	APIToken string
	// Client is optional. You can specify a custom *http.Client if you need, otherwise it's going to use the http.DefaultClient
	Client *http.Client
	// TimeoutHTTP is the maximum time allowed to send or receive commands through the openHAB API. Default is 5 seconds.
	TimeoutHTTP time.Duration
	// ReconnectionInitialBackoff represents how long to wait after the first failure before retrying.
	// If undefined, it defaults to 1 second
	ReconnectionInitialBackoff time.Duration
	// ReconnectionMultiplier is the factor with which to multiply backoff after a failed retry.
	// If undefined, it defaults to 2.0
	ReconnectionMultiplier float64
	// ReconnectionJitter represents by how much to randomize backoffs (+/-).
	// If undefined, it defaults to 0 (linear backoff)
	ReconnectionJitter time.Duration
	// ReconnectionMaxBackoff is the upper bound on backoff.
	// If undefined, it defaults to 1 minute
	ReconnectionMaxBackoff time.Duration
	// StableConnectionDuration is the time after which we consider the connection to openHAB to be stable (and resets the backoff timer).
	// If undefined, it defaults to 1 minute
	StableConnectionDuration time.Duration
	// CancellationTimeout is the time to wait for a rule to finish before sending a cancellation to its context.
	// This timeout is only used when the client is closing down.
	// If undefined, it defaults to 5 seconds
	CancellationTimeout time.Duration
	// Telemetry is used to send metrics to a monitoring system.
	// If undefined, it defaults to a no-op implementation.
	Telemetry Telemetry
}

type DateTimeState added in v0.6.0

type DateTimeState time.Time

func MustParseDateTimeState added in v0.6.0

func MustParseDateTimeState(value string) DateTimeState

MustParseDateTimeState does not panic if the string is not a number, it returns 0 instead

func NewDateTimeState added in v0.6.0

func NewDateTimeState(value time.Time) DateTimeState

NewDateTimeState creates a DateState

func ParseDateTimeState added in v0.6.0

func ParseDateTimeState(value string) (DateTimeState, error)

ParseDateTimeState converts a string to a DateState

func (DateTimeState) Equal added in v0.6.0

func (s DateTimeState) Equal(other string) bool

func (DateTimeState) Raw added in v0.6.0

func (s DateTimeState) Raw() interface{}

func (DateTimeState) String added in v0.6.0

func (s DateTimeState) String() string

func (DateTimeState) Time added in v0.6.0

func (s DateTimeState) Time() time.Time

type DecimalState

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

func MustParseDecimalState

func MustParseDecimalState(value string) DecimalState

MustParseDecimalState does not panic if the string is not a number, it returns 0 instead

func NewDecimalState

func NewDecimalState(value float64, unit string) DecimalState

NewDecimalState creates a DecimalState with a unit

func ParseDecimalState

func ParseDecimalState(value string) (DecimalState, error)

ParseDecimalState converts a string to a DecimalState

func (DecimalState) Equal added in v0.6.0

func (s DecimalState) Equal(other string) bool

func (DecimalState) Float64 added in v0.4.0

func (s DecimalState) Float64() float64

func (DecimalState) Raw added in v0.6.0

func (s DecimalState) Raw() interface{}

func (DecimalState) String

func (s DecimalState) String() string

func (DecimalState) Unit added in v0.4.0

func (s DecimalState) Unit() string

type Item

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

Item represents an item in openHAB

func (*Item) IsGroup

func (i *Item) IsGroup() bool

IsGroup returns true if the item is a group of items

func (*Item) IsMemberOf

func (i *Item) IsMemberOf(groupName string) bool

IsMemberOf returns true if the item is a member of the group

func (*Item) Name

func (i *Item) Name() string

Name returns the name of the item (an item name is unique in openHAB)

func (*Item) SendCommand

func (i *Item) SendCommand(command State) error

SendCommand sends a command to an item

func (*Item) SendCommandWait

func (i *Item) SendCommandWait(command State, timeout time.Duration) (bool, error)

SendCommandWait sends a command to an item and wait until the event bus acknowledge receiving the state, or after a timeout It returns true if openHAB acknowledge it's setting the desired state to the item (even if it's the same value as before). It returns false in case the acknowledged value is different than the command, or after timeout

func (*Item) State

func (i *Item) State() (State, error)

State returns an internal cached value if available, or calls the api to return a fresh value from openHAB if not

State value is automatically refreshed from openHAB events, so you should always get an accurate value.

Please note if you just sent a state change command, the new value might not be reflected instantly, but only after openHAB sent a state changed event back.

func (*Item) Type

func (i *Item) Type() ItemType

Type return the item type

func (*Item) Updated

func (i *Item) Updated() time.Time

Updated returns the last time the item state was updated (doesn't necessarily mean the state was changed)

type ItemType

type ItemType string
const (
	ItemTypeUnknown       ItemType = "Unknown"
	ItemTypeContact       ItemType = "Contact"
	ItemTypeColor         ItemType = "Color"
	ItemTypeDateTime      ItemType = "DateTime"
	ItemTypeDimmer        ItemType = "Dimmer"
	ItemTypeGroup         ItemType = "Group"
	ItemTypeImage         ItemType = "Image"
	ItemTypeLocation      ItemType = "Location"
	ItemTypeNumber        ItemType = "Number"
	ItemTypeRollershutter ItemType = "Rollershutter"
	ItemTypeString        ItemType = "String"
	ItemTypeSwitch        ItemType = "Switch"
)

type Logger

type Logger interface {
	Printf(format string, v ...interface{})
}

Logger interface used by gopenhab so you can bring your own logger

type Metric added in v0.9.0

type Metric struct {
	Name        string
	Description string
	Type        MetricType
	Tags        []string
}

Metric used by gopenhab telemetry

type MetricType added in v0.9.0

type MetricType int

MetricType is the type of metric

const (
	MetricTypeGauge MetricType = iota
	MetricTypeCounter
)

type RuleData

type RuleData struct {
	// ID doesn't need to be unique. It will be autogenerated if empty.
	ID string
	// Friendly name for the rule (optional)
	Name string
	// Description of the rule (optional)
	Description string
	// Context can contain anything you need to access inside the rule (database connection, etc)
	Context interface{}
	// Timeout after which the rule will be sent a cancellation through the context (optional)
	Timeout time.Duration
}

type Runner

type Runner func(ctx context.Context, client *Client, ruleData RuleData, e event.Event)

Runner is the function that will be called when the rule is triggered

  • ctx is the context of the rule. Please note the context is cancellable. It will be cancelled when the service is stopped.
  • client is the openHAB client
  • ruleData is the original data passed to the rule
  • e is the event that triggered the rule

type State added in v0.6.0

type State interface {
	String() string
	Raw() interface{}
	Equal(other string) bool
}

type StringState

type StringState string

func (StringState) Equal added in v0.6.0

func (s StringState) Equal(other string) bool

func (StringState) Raw added in v0.6.0

func (s StringState) Raw() interface{}

func (StringState) String

func (s StringState) String() string

type SwitchState

type SwitchState string
const (
	SwitchON  SwitchState = "ON"
	SwitchOFF SwitchState = "OFF"
)

func (SwitchState) Equal added in v0.6.0

func (s SwitchState) Equal(other string) bool

func (SwitchState) Raw added in v0.6.0

func (s SwitchState) Raw() interface{}

func (SwitchState) String

func (s SwitchState) String() string

type Telemetry added in v0.8.0

type Telemetry interface {
	// RegisterMetrics sends the list of metrics used by gopenhab.
	// This is needed to initialize prometheus metrics for example
	RegisterMetrics(metrics []Metric)
	Close()
	// SetGauge sets the value of a gauge. The callback runs inside its own goroutine
	SetGauge(name string, value int64, tags map[string]string)
	// AddGauge adds the value to a gauge. The callback runs inside its own goroutine
	// AddGauge(name string, value int64, tags map[string]string)
	// SubGauge subtracts the value from a gauge. The callback runs inside its own goroutine
	// SubGauge(name string, value int64, tags map[string]string)
	// AddCounter adds the value to a counter. The callback runs inside its own goroutine
	AddCounter(name string, value int64, tags map[string]string)
}

Telemetry interface to send metrics. Two metrics are available: Gauge and Counter.

Gauge is a Metric that represents a single numerical value that can arbitrarily go up and down. A Gauge is typically used for measured values like temperatures or current memory usage, but also "counts" that can go up and down, like the number of running goroutines.

Counter is a Metric that represents a single numerical value that only ever goes up. That implies that it cannot be used to count items whose number can also go down, e.g. the number of currently running goroutines. Those "counters" are represented by Gauges. A Counter is typically used to count requests served, tasks completed, errors occurred, etc.

type TelemetryLogger added in v0.8.0

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

func NewTelemetryLogger added in v0.8.0

func NewTelemetryLogger(writer io.Writer) *TelemetryLogger

func (*TelemetryLogger) AddCounter added in v0.8.0

func (t *TelemetryLogger) AddCounter(name string, value int64, tags map[string]string)

func (*TelemetryLogger) Close added in v0.8.0

func (t *TelemetryLogger) Close()

func (*TelemetryLogger) RegisterMetrics added in v0.9.0

func (t *TelemetryLogger) RegisterMetrics(metrics []Metric)

func (*TelemetryLogger) SetGauge added in v0.8.0

func (t *TelemetryLogger) SetGauge(name string, value int64, tags map[string]string)

type Thing added in v0.7.0

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

type ThingStatus added in v0.7.0

type ThingStatus string

see openhab documentation: https://www.openhab.org/docs/concepts/things.html#thing-status

const (
	ThingStatusAny           ThingStatus = ""              // Trigger an event for any status
	ThingStatusUninitialized ThingStatus = "UNINITIALIZED" // This is the initial status of a Thing when it is added or the framework is being started. This status is also assigned if the initializing process failed or the binding is not available. Commands sent to Channels will not be processed.
	ThingStatusInitializing  ThingStatus = "INITIALIZING"  // This status is assigned while the binding initializes the Thing. It depends on the binding how long the initializing process takes. Commands sent to Channels will not be processed.
	ThingStatusUnknown       ThingStatus = "UNKNOWN"       // The handler is fully initialized but due to the nature of the represented device/service it cannot really tell yet whether the Thing is ONLINE or OFFLINE. Therefore the Thing potentially might be working correctly already and may or may not process commands. But the framework is allowed to send commands, because some radio-based devices may go ONLINE if a command is sent to them. The handler should take care to switch the Thing to ONLINE or OFFLINE as soon as possible.
	ThingStatusOnline        ThingStatus = "ONLINE"        // The device/service represented by a Thing is assumed to be working correctly and can process commands.
	ThingStatusOffline       ThingStatus = "OFFLINE"       // The device/service represented by a Thing is assumed to be not working correctly and may not process commands. But the framework is allowed to send commands, because some radio-based devices may go back to ONLINE if a command is sent to them.
	ThingStatusRemoving      ThingStatus = "REMOVING"      // The device/service represented by a Thing should be removed, but the binding has not confirmed the deletion yet. Some bindings need to communicate with the device to unpair it from the system. Thing is probably not working and commands cannot be processed.
	ThingStatusRemoved       ThingStatus = "REMOVED"       // This status indicates that the device/service represented by a Thing was removed from the external system after the REMOVING was initiated by the framework. Usually this status is an intermediate status because the Thing gets removed from the database after this status was assigned.
)

type ThingStatusDetail added in v0.7.0

type ThingStatusDetail string

see openhab documentation https://www.openhab.org/docs/concepts/things.html#status-details

const (
	ThingStatusDetailNone                        ThingStatusDetail = "NONE"                          // No further status details available.
	ThingStatusDetailHandlerMissingError         ThingStatusDetail = "HANDLER_MISSING_ERROR"         // The handler cannot be initialized because the responsible binding is not available or started.
	ThingStatusDetailHandlerRegisteringError     ThingStatusDetail = "HANDLER_REGISTERING_ERROR"     // The handler failed in the service registration phase.
	ThingStatusDetailHandlerConfigurationPending ThingStatusDetail = "HANDLER_CONFIGURATION_PENDING" // The handler is registered but cannot be initialized because of missing configuration parameters.
	ThingStatusDetailHandlerInitializingError    ThingStatusDetail = "HANDLER_INITIALIZING_ERROR"    // The handler failed in the initialization phase.
	ThingStatusDetailBridgeUninitialized         ThingStatusDetail = "BRIDGE_UNINITIALIZED"          // The bridge associated with this Thing is not initialized.
	ThingStatusDetailDisabled                    ThingStatusDetail = "DISABLED"                      // The thing was explicitly disabled.
	ThingStatusDetailConfigurationPending        ThingStatusDetail = "CONFIGURATION_PENDING"         // The Thing is waiting to transfer configuration information to a device. Some bindings need to communicate with the device to make sure the configuration is accepted.
	ThingStatusDetailCommunicationError          ThingStatusDetail = "COMMUNICATION_ERROR"           // Error communicating with the device. This may be only a temporary error.
	ThingStatusDetailConfigurationError          ThingStatusDetail = "CONFIGURATION_ERROR"           // An issue with the configuration of a Thing prevents communication with the represented device or service. This issue might be solved by reconfiguring the Thing.
	ThingStatusDetailBridgeOffline               ThingStatusDetail = "BRIDGE_OFFLINE"                // Assuming the Thing to be offline because the corresponding bridge is offline.
	ThingStatusDetailFirmwareUpdating            ThingStatusDetail = "FIRMWARE_UPDATING"             // The Thing is currently undergoing a firmware update.
	ThingStatusDetailDutyCycle                   ThingStatusDetail = "DUTY_CYCLE"                    // The Thing is currently in DUTY_CYCLE state, which means it is blocked for further usage.
	ThingStatusDetailGone                        ThingStatusDetail = "GONE"                          // The Thing has been removed from the bridge or the network to which it belongs and is no longer available for use. The user can now remove the Thing from the system.
)

type Trigger

type Trigger interface {
	// contains filtered or unexported methods
}

Trigger is a generic interface for catching incoming messages on the event bus

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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