smartthings

package
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Sep 23, 2026 License: Apache-2.0 Imports: 23 Imported by: 0

Documentation

Index

Constants

View Source
const (
	InteractionDiscoveryRequest    = "discoveryRequest"
	InteractionStateRefreshRequest = "stateRefreshRequest"
	InteractionCommandRequest      = "commandRequest"
	InteractionGrantCallbackAccess = "grantCallbackAccess"
	InteractionIntegrationDeleted  = "integrationDeleted"
	InteractionInteractionResult   = "interactionResult"
)

SmartThings Schema interaction type constants

View Source
const (
	InteractionDiscoveryResponse    = "discoveryResponse"
	InteractionStateRefreshResponse = "stateRefreshResponse"
	InteractionCommandResponse      = "commandResponse"
	InteractionStateCallback        = "stateCallback"
	InteractionDiscoveryCallback    = "discoveryCallback"

	// The code exchange and the refresh post to the same oauthToken URL but are separate interaction types, each admitting exactly one grantType; SmartThings answers UNSUPPORTED-GRANT-TYPE for any other pairing.
	InteractionAccessTokenRequest  = "accessTokenRequest"
	InteractionRefreshAccessTokens = "refreshAccessTokens"
)

SmartThings Schema response interaction type constants

View Source
const (
	CommandSetHue        = "setHue"
	CommandSetSaturation = "setSaturation"
)
View Source
const (
	CapabilitySwitch                    = "st.switch"
	CapabilitySwitchLevel               = "st.switchLevel"
	CapabilityColorControl              = "st.colorControl"
	CapabilityColorTemperature          = "st.colorTemperature"
	CapabilityFanSpeed                  = "st.fanSpeed"
	CapabilityThermostatMode            = "st.thermostatMode"
	CapabilityThermostatHeatingSetpoint = "st.thermostatHeatingSetpoint"
	CapabilityHealthCheck               = "st.healthCheck"
)

SmartThings capability constants

View Source
const (
	ComponentMain = "main"

	AttributeSwitch           = "switch"
	AttributeLevel            = "level"
	AttributeHue              = "hue"
	AttributeSaturation       = "saturation"
	AttributeColorTemperature = "colorTemperature"
	AttributeFanSpeed         = "fanSpeed"
	AttributeHeatingSetpoint  = "heatingSetpoint"
	AttributeHealthStatus     = "healthStatus"
)

SmartThings component and attribute constants. Every device we expose is single-component, so states are always reported on "main".

View Source
const (
	ErrorDeviceError   = "DEVICE-ERROR"
	ErrorDeviceDeleted = "DEVICE-DELETED"
	ErrorOffline       = "OFFLINE"
)

SmartThings error enum constants

View Source
const (
	ParamTypePower               = "esp.param.power"
	ParamTypeBrightness          = "esp.param.brightness"
	ParamTypeHue                 = "esp.param.hue"
	ParamTypeSaturation          = "esp.param.saturation"
	ParamTypeCCT                 = "esp.param.cct"
	ParamTypeSpeed               = "esp.param.speed"
	ParamTypeTemperature         = "esp.param.temperature"
	ParamTypeSetpointTemperature = "esp.param.setpoint-temperature"
)

RMNG parameter type constants used for capability mapping

Variables

This section is empty.

Functions

func AuthorizeNode

func AuthorizeNode(rmngCtx *rmngctx.RmngContext, nodeGroups map[string]string, nodeID string) error

AuthorizeNode reports whether the caller may act on nodeID, loading the node's permissions into rmngCtx on success. nodeGroups comes from UserNodeGroups.

func GetDeviceID

func GetDeviceID(nodeID, deviceName string) string

GetDeviceID generates a SmartThings external device ID from a node ID and device name. Format: <nodeID>#<deviceName>

func GetSTCapabilities

func GetSTCapabilities(paramTypes []string) []string

func GetUserIDFromToken

func GetUserIDFromToken(ctx context.Context, token string) (string, error)

GetUserIDFromToken validates the access token and returns the user ID. Account linking runs against the ESP User OIDC provider, so user.GetUserIDFromToken resolves it there when ESPUSER_ISSUER is configured, falling back to the Cognito admin service otherwise.

func HueToDevice

func HueToDevice(hue float64) int

func HueToST

func HueToST(hue float64) float64

func IsSTDiscoverable

func IsSTDiscoverable(device *config.NodeCfgDevice) bool

Discovery drops any device whose params map to nothing beyond the always-present healthCheck, so nothing else may report state for one either.

func ParseDeviceID

func ParseDeviceID(externalDeviceID string) (nodeID string, deviceName string, err error)

ParseDeviceID splits a SmartThings external device ID into node ID and device name.

func STCapabilitiesForDevice

func STCapabilitiesForDevice(device *config.NodeCfgDevice) []string

func UserNodeGroups

func UserNodeGroups(rmngCtx *rmngctx.RmngContext) (map[string]string, error)

UserNodeGroups returns the nodes the caller may act on, mapped to the group each one belongs to. It walks the caller's own groups exactly as discovery does, so a node the caller has no access to is simply absent from the map.

commandRequest and stateRefreshRequest act on an externalDeviceId supplied by the request rather than on anything the caller proved ownership of, so every such id must be checked against this map (and then through user.LoadNodePermissions) before the node is touched. Discovery does not need it: it only ever enumerates the caller's groups.

Types

type STAuthentication

type STAuthentication struct {
	TokenType string `json:"tokenType"`
	Token     string `json:"token"`
}

STAuthentication contains the user's OAuth token

type STCallbackAuth

type STCallbackAuth struct {
	GrantType    string `json:"grantType"`
	Scope        string `json:"scope"`
	Code         string `json:"code,omitempty"`
	ClientID     string `json:"clientId"`
	ClientSecret string `json:"clientSecret,omitempty"`
	AccessToken  string `json:"accessToken,omitempty"`
	RefreshToken string `json:"refreshToken,omitempty"`
	ExpiresIn    int    `json:"expiresIn,omitempty"`
}

STCallbackAuth contains callback OAuth credentials provided by SmartThings

type STCallbackURLs

type STCallbackURLs struct {
	OAuthToken    string `json:"oauthToken"`
	StateCallback string `json:"stateCallback"`
}

STCallbackURLs contains the SmartThings callback endpoints

type STCommand

type STCommand struct {
	Component  string        `json:"component"`
	Capability string        `json:"capability"`
	Command    string        `json:"command"`
	Arguments  []interface{} `json:"arguments,omitempty"`
}

STCommand represents a single command to execute on a device

type STCommandDevice

type STCommandDevice struct {
	ExternalDeviceID string            `json:"externalDeviceId"`
	DeviceCookie     map[string]string `json:"deviceCookie,omitempty"`
	Commands         []STCommand       `json:"commands,omitempty"`
}

STCommandDevice identifies a device in requests. For stateRefresh, only ExternalDeviceID is populated. For commandRequest, Commands contains the commands to execute.

type STDeviceContext

type STDeviceContext struct {
	RoomName   string   `json:"roomName,omitempty"`
	Groups     []string `json:"groups,omitempty"`
	Categories []string `json:"categories,omitempty"`
}

STDeviceContext provides additional context about a device

type STDeviceError

type STDeviceError struct {
	ErrorEnum string `json:"errorEnum"`
	Detail    string `json:"detail,omitempty"`
}

STDeviceError represents an error for a specific device

type STDeviceState

type STDeviceState struct {
	ExternalDeviceID string          `json:"externalDeviceId"`
	States           []STState       `json:"states"`
	DeviceError      []STDeviceError `json:"deviceError,omitempty"`
}

STDeviceState represents device state in stateRefresh/command responses

type STDiscoveryCallbackPayload

type STDiscoveryCallbackPayload struct {
	Headers        STHeaders           `json:"headers"`
	Authentication STAuthentication    `json:"authentication"`
	Devices        []STDiscoveryDevice `json:"devices"`
}

STDiscoveryCallbackPayload is the payload sent when devices become available to a user outside a discoveryRequest. SmartThings only rebuilds its device list from a discovery it initiates, so a node added to a group stays invisible until we push this.

type STDiscoveryDevice

type STDiscoveryDevice struct {
	ExternalDeviceID  string              `json:"externalDeviceId"`
	DeviceCookie      map[string]string   `json:"deviceCookie,omitempty"`
	FriendlyName      string              `json:"friendlyName"`
	DeviceHandlerType string              `json:"deviceHandlerType"`
	ManufacturerInfo  *STManufacturerInfo `json:"manufacturerInfo,omitempty"`
	DeviceContext     *STDeviceContext    `json:"deviceContext,omitempty"`
}

STDiscoveryDevice represents a device in the discovery response

type STError

type STError struct {
	ErrorEnum string `json:"errorEnum"`
	Detail    string `json:"detail,omitempty"`
}

STError represents an error in an interaction result

type STHeaders

type STHeaders struct {
	Schema          string `json:"schema"`
	Version         string `json:"version"`
	InteractionType string `json:"interactionType"`
	RequestID       string `json:"requestId"`
}

STHeaders contains metadata about the Schema interaction

type STInteractionResult

type STInteractionResult struct {
	InteractionType string   `json:"interactionType"`
	RequestID       string   `json:"requestId"`
	Error           *STError `json:"error,omitempty"`
}

STInteractionResult contains the result of a previous interaction

type STManufacturerInfo

type STManufacturerInfo struct {
	ManufacturerName string `json:"manufacturerName"`
	ModelName        string `json:"modelName"`
	SwVersion        string `json:"swVersion,omitempty"`
}

STManufacturerInfo contains manufacturer metadata for a device

type STNotification

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

STNotification implements the NotificationService interface for SmartThings state callbacks.

func NewSTNotification

func NewSTNotification(ctx context.Context, baseURL string) *STNotification

NewSTNotification creates a new SmartThings notification service instance. A non-empty baseURL switches the adapter into mock mode, routing state callbacks to the test webhook instead of the per-user callback URL.

func (*STNotification) GetName

func (s *STNotification) GetName() string

func (*STNotification) GetType

func (*STNotification) Marshal

func (s *STNotification) Marshal(notif *notification.Notification) (interface{}, error)

Marshal converts a shadow update notification to a SmartThings state callback payload.

func (*STNotification) NotifyOnConnectivityChange

func (s *STNotification) NotifyOnConnectivityChange() bool

st.healthCheck is the only thing that tells SmartThings a device is reachable, and without opting in the dispatcher skips this service before Marshal runs.

func (*STNotification) Send

func (s *STNotification) Send(notif interface{}) error

func (*STNotification) SendTo

func (s *STNotification) SendTo(notif interface{}, userIDs []string) error

SendTo retrieves stored callback tokens for each user, refreshes if expired, and sends the state callback payload to the SmartThings callback URL.

type STRequest

type STRequest struct {
	Headers                STHeaders            `json:"headers"`
	Authentication         STAuthentication     `json:"authentication"`
	Devices                []STCommandDevice    `json:"devices,omitempty"`
	CallbackAuthentication *STCallbackAuth      `json:"callbackAuthentication,omitempty"`
	CallbackURLs           *STCallbackURLs      `json:"callbackUrls,omitempty"`
	InteractionResult      *STInteractionResult `json:"interactionResult,omitempty"`
	// interactionResult fields are sent by SmartThings at the TOP LEVEL of the request (not nested):
	// originatingInteractionType identifies which response failed, globalError carries response-wide
	// errors, and deviceState[].deviceError carries per-device errors.
	OriginatingInteractionType string          `json:"originatingInteractionType,omitempty"`
	GlobalError                *STError        `json:"globalError,omitempty"`
	DeviceState                []STDeviceState `json:"deviceState,omitempty"`
}

STRequest is the top-level SmartThings Schema request envelope

type STResponse

type STResponse struct {
	Headers         STHeaders           `json:"headers"`
	IsAuthenticated *bool               `json:"isAuthenticated,omitempty"`
	Devices         []STDiscoveryDevice `json:"devices,omitempty"`
	DeviceState     []STDeviceState     `json:"deviceState,omitempty"`
	// RequestGrantCallbackAccess, when true on a discoveryResponse, asks SmartThings to send a
	// grantCallbackAccess interaction so we can obtain (or refresh) the callback tokens needed
	// for proactive state callbacks. Without it, SmartThings never grants callback access.
	RequestGrantCallbackAccess bool `json:"requestGrantCallbackAccess,omitempty"`
}

STResponse is the top-level SmartThings Schema response envelope

func HandleCommand

func HandleCommand(ctx context.Context, request STRequest) (STResponse, error)

HandleCommand processes a SmartThings commandRequest and publishes commands to devices via IoT Core MQTT, returning the commanded device state.

func HandleDiscovery

func HandleDiscovery(ctx context.Context, request STRequest) (STResponse, error)

func HandleGrantCallbackAccess

func HandleGrantCallbackAccess(ctx context.Context, request STRequest) (STResponse, error)

HandleGrantCallbackAccess processes a grantCallbackAccess interaction from SmartThings. It exchanges the authorization code for actual tokens via the SmartThings token endpoint, then stores the tokens in the Users DynamoDB table keyed by user ID.

func HandleIntegrationDeleted

func HandleIntegrationDeleted(ctx context.Context, request STRequest) (STResponse, error)

HandleIntegrationDeleted removes the user's stored SmartThings endpoint rows when SmartThings sends an integrationDeleted interaction. If no rows exist, the operation succeeds silently.

func HandleInteractionResult

func HandleInteractionResult(ctx context.Context, request STRequest) (STResponse, error)

HandleInteractionResult processes interactionResult interactions from SmartThings. SmartThings reports the outcome of a prior response here: a response-wide globalError and/or per-device deviceError, tagged with originatingInteractionType. We log every error so failures (e.g. a rejected commandResponse) are visible.

func HandleStateRefresh

func HandleStateRefresh(ctx context.Context, request STRequest) (STResponse, error)

HandleStateRefresh processes a SmartThings stateRefreshRequest and returns the current state of the requested devices including st.healthCheck capability.

type STState

type STState struct {
	Component  string      `json:"component"`
	Capability string      `json:"capability"`
	Attribute  string      `json:"attribute"`
	Value      interface{} `json:"value"`
	Unit       string      `json:"unit,omitempty"`
}

STState represents a single capability attribute state

type STStateCallbackPayload

type STStateCallbackPayload struct {
	Headers        STHeaders        `json:"headers"`
	Authentication STAuthentication `json:"authentication"`
	DeviceState    []STDeviceState  `json:"deviceState"`
}

STStateCallbackPayload is the payload sent to the SmartThings state callback endpoint. It must be a full ST Schema envelope: headers (with schema/version/interactionType) and authentication (the per-user callback access token), plus the device states. Omitting the headers causes SmartThings to reject the callback with "Invalid or unspecified schema".

Directories

Path Synopsis
handlers
st_action command
st_cfg command

Jump to

Keyboard shortcuts

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