Documentation
¶
Overview ¶
Package shelly speaks the local APIs of Shelly devices, without the Shelly cloud:
- GET /shelly (no login) tells what a device is and its generation (Info).
- Gen1: HTTP GET with basic authentication (Client.Get1); the request builders Gen1Turn, Gen1Level, Gen1Colour, Gen1Roller and Gen1RollerPos; CoIoT, the CoAP status messages Gen1 devices multicast (ParseCoAP, CitDesc, ListenCoIoT).
- Gen2, Gen3 and Gen4 (the RPC API): JSON-RPC over HTTP with SHA-256 digest authentication (Client.RPC), the WebSocket RPC channel with its notifications (WatchWS, WSAuth), and a server for the outbound WebSocket that sleeping devices open themselves (Inbound).
- MQTT mode for both, over the application's MQTT client (MQTT).
- First-time setup: the site's Wi-Fi from the device's hotspot (Client.SetWiFi) or over BLE RPC (BLERPC, over the application's Bluetooth stack through GATT); firmware updates by URL (Client.Update, Client.WaitVersion).
- Typed views of Gen2+ status and configuration (Status, Config) and typed calls over any transport (Caller): outputs, scripts, schedules, webhooks, the key-value store and virtual components; Gen1 settings and actions (Gen1Settings, Client.Gen1Actions). Package discover finds devices by DNS-SD, CoIoT or a scan.
The package logs nothing and keeps no state beyond a Client's digest challenge and an MQTT's pending requests. Networking goes through the *http.Client, Publisher and GATT the application gives it, except the UDP and TCP listeners it is asked to open. Simulated devices of each generation are in the module github.com/cB-Sigma/shelly-sim.
Example ¶
Ask a device what it is, then switch a Gen2+ output with JSON-RPC. (github.com/cB-Sigma/shelly-sim has simulated devices of every kind.)
srv := (&fakeDevice{gen: 2, password: "secret"}).start() // stands in for a device on the LAN
defer srv.Close()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
base, _ := shelly.BaseURL(srv.URL)
c := &shelly.Client{Base: base, Password: "secret", HTTP: &http.Client{Timeout: 5 * time.Second}}
info, err := c.Shelly(ctx)
if err != nil {
panic(err)
}
fmt.Println(info.DefaultID(), "gen", info.Generation(), info.ModelName())
if _, err := c.RPC(ctx, "Switch.Set", map[string]any{"id": 0, "on": true}); err != nil {
panic(err)
}
raw, _ := c.RPC(ctx, "Shelly.GetStatus", nil)
var st map[string]map[string]any
_ = json.Unmarshal(raw, &st)
fmt.Println("output:", st["switch:0"]["output"])
// Output:
// shellyplus1-a8032ab1f001 gen 2 SNSW-001X16EU
Output: shellyplus1-a8032ab1f001 gen 2 SNSW-001X16EU output: true
Index ¶
- Constants
- Variables
- func AddVirtual(ctx context.Context, c Caller, typ string, config map[string]any, id int) (int, error)
- func BLERPC(ctx context.Context, g GATT, src string, id int, method string, ...) (json.RawMessage, error)
- func BaseURL(addr string) (string, error)
- func CoverToPosition(ctx context.Context, c Caller, id int, pos float64) error
- func CreateSchedule(ctx context.Context, c Caller, j ScheduleJob) (id, rev int, err error)
- func CreateScript(ctx context.Context, c Caller, name string) (int, error)
- func CreateWebhook(ctx context.Context, c Caller, h Webhook) (id, rev int, err error)
- func DeleteAllSchedules(ctx context.Context, c Caller) (rev int, err error)
- func DeleteAllWebhooks(ctx context.Context, c Caller) (rev int, err error)
- func DeleteSchedule(ctx context.Context, c Caller, id int) (rev int, err error)
- func DeleteScript(ctx context.Context, c Caller, id int) error
- func DeleteVirtual(ctx context.Context, c Caller, key string) error
- func DeleteWebhook(ctx context.Context, c Caller, id int) (rev int, err error)
- func DigestResponse(user, realm, password, method, uri, nonce, nc, cnonce string) string
- func EncodeCoIoT(devType, devID string, serial int, payload []byte) []byte
- func EvalScript(ctx context.Context, c Caller, id int, code string) (string, error)
- func Gen1ActionNames(actions map[string][]Gen1Action) []string
- func Gen1Colour(n int, r, g, b uint8, gain *float64) string
- func Gen1Event(e string) string
- func Gen1Level(n int, level float64, colourMode bool, transition *float64) string
- func Gen1MQTT(pathQuery string) (string, string, error)
- func Gen1Roller(n int, move string) string
- func Gen1RollerPos(n int, pos float64) string
- func Gen1SetAction(name string, index int, enabled bool, urls ...string) string
- func Gen1Settings(section string, n int, values url.Values) string
- func Gen1Turn(kind string, n int, turn string) string
- func GetScriptCode(ctx context.Context, c Caller, id int) (string, error)
- func IsRPCError(err error, code int) bool
- func KVSDelete(ctx context.Context, c Caller, key, etag string) (rev int, err error)
- func KVSList(ctx context.Context, c Caller, match string) (map[string]string, int, error)
- func KVSSet(ctx context.Context, c Caller, key string, value any, etag string) (newEtag string, rev int, err error)
- func MACOfID(id string) string
- func MethodPrefix(typ string) string
- func MoveCover(ctx context.Context, c Caller, id int, move string, duration float64) error
- func PutScriptCode(ctx context.Context, c Caller, id int, code string, chunk int) error
- func SHA256Hex(s string) string
- func ServeInbound(ctx context.Context, ln net.Listener, path string, in *Inbound) error
- func SetConfig(ctx context.Context, c Caller, key string, config map[string]any) (restartRequired bool, err error)
- func SetLight(ctx context.Context, c Caller, typ string, id int, s LightSet) error
- func SetScriptConfig(ctx context.Context, c Caller, id int, name *string, enable *bool) error
- func SetSwitch(ctx context.Context, c Caller, id int, on bool, toggleAfter float64) (wasOn bool, err error)
- func SetVirtual(ctx context.Context, c Caller, key string, value any) error
- func SplitKey(k string) (typ string, id int, ok bool)
- func StartScript(ctx context.Context, c Caller, id int) (wasRunning bool, err error)
- func StopScript(ctx context.Context, c Caller, id int) (wasRunning bool, err error)
- func ToggleSwitch(ctx context.Context, c Caller, id int) (wasOn bool, err error)
- func UpdateSchedule(ctx context.Context, c Caller, j ScheduleJob) (rev int, err error)
- func UpdateWebhook(ctx context.Context, c Caller, h Webhook) (rev int, err error)
- func WSAuth(challengeJSON, password string) (map[string]any, error)
- func WSURL(base string) string
- func WatchWS(ctx context.Context, base string, o WSOptions) error
- func WebhookEvents(ctx context.Context, c Caller) ([]string, error)
- func WiFiConfig(ssid, password string) map[string]any
- type Announce
- type BLEDevice
- type BLEDialer
- type Caller
- type CallerFunc
- type CitBlock
- type CitDesc
- type CitSensor
- type CitValue
- type Client
- func (c *Client) CitDescription(ctx context.Context) (CitDesc, error)
- func (c *Client) Gen1Actions(ctx context.Context) (map[string][]Gen1Action, error)
- func (c *Client) Get(ctx context.Context, pathQuery string) ([]byte, error)
- func (c *Client) Get1(ctx context.Context, pathQuery string) (map[string]any, error)
- func (c *Client) OutboundWS(ctx context.Context) (OutboundWS, error)
- func (c *Client) RPC(ctx context.Context, method string, params map[string]any) (json.RawMessage, error)
- func (c *Client) Reboot(ctx context.Context) error
- func (c *Client) SetOutboundWS(ctx context.Context, server string) (restart bool, err error)
- func (c *Client) SetWiFi(ctx context.Context, gen int, ssid, password string) error
- func (c *Client) Settings1(ctx context.Context, section string, n int, values url.Values) (map[string]any, error)
- func (c *Client) Shelly(ctx context.Context) (Info, error)
- func (c *Client) Update(ctx context.Context, gen int, imageURL string) error
- func (c *Client) WaitVersion(ctx context.Context, before, want string, every time.Duration) (Info, error)
- type CoIoTListener
- type CoIoTMessage
- type Component
- type Config
- func (c Config) Cover(id int) (v CoverConfig, ok bool)
- func (c Config) Decode(key string, v any) bool
- func (c Config) Input(id int) (v InputConfig, ok bool)
- func (c Config) Keys(typ string) []string
- func (c Config) Light(typ string, id int) (v LightConfig, ok bool)
- func (c Config) Name() string
- func (c Config) Switch(id int) (v SwitchConfig, ok bool)
- func (c Config) Sys() (v SysConfig, ok bool)
- func (c Config) WiFi() (v WiFiConfigView, ok bool)
- type CoverConfig
- type CoverStatus
- type DevicePowerStatus
- type EM1DataStatus
- type EM1Status
- type EMDataStatus
- type EMPhase
- type EMStatus
- type Energy
- type Event
- type Frame
- type GATT
- type Gen1Action
- type Gen1ActionURL
- type Gen1Report
- type Gen1TopicKind
- type HumidityStatus
- type Inbound
- type InboundChannel
- type Info
- type InputConfig
- type InputCounts
- type InputStatus
- type KVSItem
- type LightConfig
- type LightSet
- type LightStatus
- type MQTT
- type MQTTDevice
- type MQTTKind
- type MQTTMessage
- type Meter
- type OutboundWS
- type PM1Status
- type Publisher
- type RPCError
- type ScheduleCall
- type ScheduleJob
- type Script
- type ScriptStatus
- type Status
- func (s Status) Cover(id int) (v CoverStatus, ok bool)
- func (s Status) Decode(key string, v any) bool
- func (s Status) DevicePower(id int) (v DevicePowerStatus, ok bool)
- func (s Status) EM(id int) (v EMStatus, ok bool)
- func (s Status) EM1(id int) (v EM1Status, ok bool)
- func (s Status) EM1Data(id int) (v EM1DataStatus, ok bool)
- func (s Status) EMData(id int) (v EMDataStatus, ok bool)
- func (s Status) Humidity(id int) (v HumidityStatus, ok bool)
- func (s Status) Input(id int) (v InputStatus, ok bool)
- func (s Status) Keys(typ string) []string
- func (s Status) Light(typ string, id int) (v LightStatus, ok bool)
- func (s Status) PM1(id int) (v PM1Status, ok bool)
- func (s Status) Switch(id int) (v SwitchStatus, ok bool)
- func (s Status) Sys() (v SysStatus, ok bool)
- func (s Status) Temperature(id int) (v TemperatureStatus, ok bool)
- func (s Status) WiFi() (v WiFiStatus, ok bool)
- type SwitchConfig
- type SwitchStatus
- type SysConfig
- type SysStatus
- type Temperature
- type TemperatureStatus
- type WSOptions
- type Webhook
- type WiFiConfigView
- type WiFiStatus
Examples ¶
Constants ¶
const ( BLEService = "5f6d4f53-5f52-5043-5f53-56435f49445f" BLEData = "5f6d4f53-5f52-5043-5f64-6174615f5f5f" BLETxControl = "5f6d4f53-5f52-5043-5f74-785f63746c5f" BLERxControl = "5f6d4f53-5f52-5043-5f72-785f63746c5f" // BLENamePrefix starts the advertised name of Shelly devices // ("ShellyPlus1PM-…"); compare without case. BLENamePrefix = "Shelly" )
Shelly BLE RPC (Gen2+): the GATT service and its characteristics. A request is sent by writing its length (4 octets, big-endian) to TX control and the JSON to data; the answer's length is read from RX control and the answer from data until that many octets came.
const ( CoIoTGroup = "224.0.1.187" CoIoTPort = 5683 )
CoIoT defaults: the multicast group and UDP port devices send to.
const DefaultAPAddress = "192.168.33.1"
DefaultAPAddress is a Shelly device's address on its own hotspot.
const DefaultMQTTPrefix = "shellies"
DefaultMQTTPrefix is the Gen1 topic root devices use unless set.
const DefaultScriptChunk = 1024
DefaultScriptChunk is how many octets of code ScriptPutCode sends per request when no size is given.
const User = "admin"
User is the user name of Gen2+ authentication (fixed by the API).
Variables ¶
var ErrAuth = errors.New("the device refused the password")
ErrAuth is wrapped when the device refuses the credentials.
Functions ¶
func AddVirtual ¶ added in v0.2.0
func AddVirtual(ctx context.Context, c Caller, typ string, config map[string]any, id int) (int, error)
AddVirtual creates a dynamic (virtual) component (Virtual.Add): typ is boolean, number, text, enum, group or button; id 0 lets the device pick one (from 200). It returns the new component's id.
func BLERPC ¶
func BLERPC(ctx context.Context, g GATT, src string, id int, method string, params map[string]any) (json.RawMessage, error)
BLERPC sends one JSON-RPC request (with src as its "src") over Shelly's BLE RPC framing and returns its result.
func BaseURL ¶
BaseURL turns an address (host, host:port, http://host:port or https://host:port) into the Base of a Client.
func CoverToPosition ¶ added in v0.2.0
CoverToPosition moves cover id to pos percent open (Cover.GoToPosition).
func CreateSchedule ¶ added in v0.2.0
CreateSchedule adds a job (Schedule.Create) and returns its id and the schedules' new revision.
func CreateScript ¶ added in v0.2.0
CreateScript makes an empty script named name (Script.Create).
func CreateWebhook ¶ added in v0.2.0
CreateWebhook adds a webhook (Webhook.Create).
func DeleteAllSchedules ¶ added in v0.2.0
DeleteAllSchedules removes every job (Schedule.DeleteAll).
func DeleteAllWebhooks ¶ added in v0.2.0
DeleteAllWebhooks removes every webhook (Webhook.DeleteAll).
func DeleteSchedule ¶ added in v0.2.0
DeleteSchedule removes job id (Schedule.Delete).
func DeleteScript ¶ added in v0.2.0
DeleteScript removes script id (Script.Delete).
func DeleteVirtual ¶ added in v0.2.0
DeleteVirtual removes a dynamic component by key ("number:200").
func DeleteWebhook ¶ added in v0.2.0
DeleteWebhook removes webhook id (Webhook.Delete).
func DigestResponse ¶
DigestResponse is the RFC 7616 response with SHA-256 and qop auth: H(H(user:realm:password):nonce:nc:cnonce:auth:H(method:uri)).
func EncodeCoIoT ¶
EncodeCoIoT builds a CoIoT status message to /cit/s with serial and payload, as a device sends it (for simulators and tests).
func EvalScript ¶ added in v0.2.0
EvalScript evaluates code in running script id's context (Script.Eval) and returns the result as the device printed it.
func Gen1ActionNames ¶ added in v0.2.0
func Gen1ActionNames(actions map[string][]Gen1Action) []string
Gen1ActionNames lists the action names of a /settings/actions answer, sorted.
func Gen1Colour ¶
Gen1Colour turns colour output n on with red, green and blue, and gain (percent) when set.
func Gen1Event ¶
Gen1Event names a Gen1 input event the way Gen2 devices name theirs: S single_push, L long_push, SS double_push, SSS triple_push, SL short_long (other codes as sent, lower case).
func Gen1Level ¶
Gen1Level dims light output n to level percent (0 turns it off). A light in colour mode (a Bulb or RGBW2 with mode color in its status) dims with gain on /color/n, since /light/n's brightness applies to white mode only; colourMode selects that form.
Example ¶
Dim a Gen1 light. A Bulb or RGBW2 in colour mode takes the level as the gain of /color/n.
package main
import (
"fmt"
"github.com/cB-Sigma/shelly"
)
func main() {
fmt.Println(shelly.Gen1Level(0, 40, false, nil))
fmt.Println(shelly.Gen1Level(0, 40, true, nil))
}
Output: /light/0?brightness=40&turn=on /color/0?gain=40&turn=on
func Gen1MQTT ¶
Gen1MQTT turns a Gen1 GET into the MQTT command topic (under shellies/<id>/) and payload.
func Gen1Roller ¶
Gen1Roller moves roller n: open, close or stop.
func Gen1RollerPos ¶
Gen1RollerPos moves roller n to pos percent (100 open).
func Gen1SetAction ¶ added in v0.2.0
Gen1SetAction is the path with query that sets slot index of action name: enabled, and the URLs to call (an empty list clears them). Firmware that takes time windows reads urls[] as plain URLs too.
func Gen1Settings ¶ added in v0.2.0
Gen1Settings is the path with query that changes settings: section "" for /settings, else /settings/<section>/<n> (n < 0 leaves the index out, for sections such as cloud, mqtt, coiot or login).
func GetScriptCode ¶ added in v0.2.0
GetScriptCode reads script id's code whole, page by page (Script.GetCode with offset).
func IsRPCError ¶ added in v0.2.0
IsRPCError reports whether err carries a device error with code.
func KVSDelete ¶ added in v0.2.0
KVSDelete removes key (KVS.Delete); with etag set only if it still matches.
func KVSSet ¶ added in v0.2.0
func KVSSet(ctx context.Context, c Caller, key string, value any, etag string) (newEtag string, rev int, err error)
KVSSet stores value (any JSON value) under key (KVS.Set). With etag set, the device refuses the write unless the stored entry still has that etag.
func MACOfID ¶
MACOfID is the MAC part of a Gen1 id in lower case (shelly1-A4CF12F45B2E → a4cf12f45b2e); "" when the id has none.
func MethodPrefix ¶
MethodPrefix is the RPC namespace of a Gen2+ component type: switch → Switch, light → Light, rgb → RGB, rgbw → RGBW, cct → CCT, cover → Cover; the namespaces spelled otherwise (WiFi, KVS, BLE, MQTT, EM, EMData, EM1, EM1Data, PM1, DevicePower) as the device names them.
func MoveCover ¶ added in v0.2.0
MoveCover runs Cover.Open, Cover.Close or Cover.Stop (move is open, close or stop); with duration > 0 an open or close runs for that many seconds.
func PutScriptCode ¶ added in v0.2.0
PutScriptCode replaces script id's code with code, sent in chunks of at most chunk octets (DefaultScriptChunk when 0), split between UTF-8 characters: the first replaces, the rest append (Script.PutCode).
func ServeInbound ¶
ServeInbound serves in at path on ln until ctx ends, which also ends the open channels; it closes ln.
func SetConfig ¶ added in v0.2.0
func SetConfig(ctx context.Context, c Caller, key string, config map[string]any) (restartRequired bool, err error)
SetConfig sets part of a component's configuration with <Type>.SetConfig (key "switch:0", or "sys", "wifi" without an id) and returns whether the device must restart for it.
func SetLight ¶ added in v0.2.0
SetLight sets a light-like component (typ light, rgb, rgbw or cct) with <Type>.Set.
func SetScriptConfig ¶ added in v0.2.0
SetScriptConfig renames script id or sets whether it runs at boot (Script.SetConfig); nil fields are left as they are.
func SetSwitch ¶ added in v0.2.0
func SetSwitch(ctx context.Context, c Caller, id int, on bool, toggleAfter float64) (wasOn bool, err error)
SetSwitch turns switch id on or off (Switch.Set); with toggleAfter > 0 the device flips it back after that many seconds. It returns whether the switch was on.
func SetVirtual ¶ added in v0.2.0
SetVirtual sets a dynamic component's value (<Type>.Set with id and value), key as "boolean:200".
func SplitKey ¶
SplitKey splits a Gen2+ component key ("switch:1") into its type and id; ok is false for a key without a numeric id ("sys").
func StartScript ¶ added in v0.2.0
StartScript runs script id (Script.Start); wasRunning says whether it already ran.
func StopScript ¶ added in v0.2.0
StopScript stops script id (Script.Stop).
func ToggleSwitch ¶ added in v0.2.0
ToggleSwitch flips switch id (Switch.Toggle).
func UpdateSchedule ¶ added in v0.2.0
UpdateSchedule replaces job j.ID (Schedule.Update).
func UpdateWebhook ¶ added in v0.2.0
UpdateWebhook replaces webhook h.ID (Webhook.Update).
func WSAuth ¶
WSAuth builds the authentication object of a JSON-RPC request over WebSocket from a 401 challenge (the error message is the challenge as JSON). The second hash is over the fixed "dummy_method:dummy_uri". The nonce and nonce count are echoed in the form the device sent them (a number on older firmware); without a count in the challenge it starts at 1.
func WSURL ¶
WSURL is the WebSocket address of a device's RPC channel for a Client Base (http://host → ws://host/rpc, https → wss).
func WatchWS ¶
WatchWS opens the WebSocket RPC channel of a Gen2+ device at base (http://host[:port]), asks for Shelly.GetStatus, authenticates when the device asks (WSAuth), and hands the status and every notification to the options' functions until ctx ends, the channel fails or a function returns an error, which WatchWS then returns. A refused password is ErrAuth.
func WebhookEvents ¶ added in v0.2.0
WebhookEvents lists the events webhooks can be made for (Webhook.ListSupported), sorted. Firmware before 1.0 answered a list under hook_types; later firmware answers an object under types.
func WiFiConfig ¶
WiFiConfig is the WiFi.SetConfig params that make a Gen2+ device join a network as a station.
Types ¶
type Announce ¶
type Announce struct {
ID string // the device id (shellyplug-s-98CDAC1F0A0A)
Model string // the type code (SHPLG-S)
MAC string // 12 hexadecimal digits
IP string // the device's address
}
Announce is a Gen1 device's announcement on <prefix>/announce.
type BLEDevice ¶ added in v0.2.0
BLEDevice is one Gen2+ device over BLE RPC through the application's GATT peer. Src is the "src" of requests; ids count up from 1.
type BLEDialer ¶
type BLEDialer func(ctx context.Context, adapter, target string) (g GATT, name string, closeFn func(), err error)
BLEDialer connects to a device over an adapter: target is its BLE address or advertised name, or "" for the first Shelly device found. It returns the peer, its advertised name and a close function.
type Caller ¶ added in v0.2.0
type Caller interface {
RPC(ctx context.Context, method string, params map[string]any) (json.RawMessage, error)
}
Caller sends one Gen2+ JSON-RPC request and returns its result. A *Client is one (HTTP); MQTTDevice and BLEDevice put the other transports behind it, and a WebSocket channel the application keeps can be wrapped the same way. The typed helpers below take a Caller, so they work over every transport.
type CallerFunc ¶ added in v0.2.0
type CallerFunc func(ctx context.Context, method string, params map[string]any) (json.RawMessage, error)
CallerFunc adapts a function to Caller.
type CitBlock ¶
type CitBlock struct {
// I is the block ID sensors name in L.
I int `json:"I"`
// D is the block's description.
D string `json:"D"`
}
CitBlock is one block of a /cit/d description: a part of the device ("relay_0", "input_1", "device").
type CitDesc ¶
type CitDesc struct {
// Blk are the device's blocks.
Blk []CitBlock `json:"blk"`
// Sen are its sensors.
Sen []CitSensor `json:"sen"`
}
CitDesc is a device's /cit/d description.
func (CitDesc) BlockIndex ¶
BlockIndex is the index of a sensor's block among the device's blocks of the same kind, from the number after the last "_" of the block's description (relay_0 → 0, relay_1 → 1); ok is false when the block has none (the "device" block).
type CitSensor ¶
type CitSensor struct {
// I is the sensor ID the status triples refer to.
I int `json:"I"`
// T is the sensor type (S state, P power, E energy, T temperature,
// EV event, EVC event count, …).
T string `json:"T"`
// D is the description ("output", "power", "inputEvent", …).
D string `json:"D"`
// U is the unit (W, Wmin, C, %), when it has one.
U string `json:"U"`
// L is the ID of the block the sensor belongs to; for a sensor the
// description gives several blocks, the first of them.
L int `json:"L"`
// Blocks are all the block IDs of a sensor whose L is a list in the
// description; nil when L is a single number.
Blocks []int `json:"-"`
}
CitSensor is one sensor of a /cit/d description.
func (*CitSensor) UnmarshalJSON ¶
UnmarshalJSON reads a sensor whose L is a block ID or a list of them.
type CitValue ¶
type CitValue struct {
// Sensor is the sensor it belongs to.
Sensor CitSensor
// Index is the sensor's block index (BlockIndex); HasIndex is false
// for a block without one.
Index int
HasIndex bool
// Value is the value as sent: a float64, a string, or another JSON
// value.
Value any
}
CitValue is one value of a status message.
type Client ¶
type Client struct {
// Base is http://host[:port] (BaseURL makes one from an address).
Base string
// Username is the Gen1 basic-authentication user (default admin);
// Gen2+ devices always use User.
Username string
// Password is the device's login password; empty when it has none.
Password string
// HTTP sends the requests. The application sets its timeouts, proxy
// and dialer here.
HTTP *http.Client
// contains filtered or unexported fields
}
Client talks HTTP to one device. It is safe for concurrent use.
func (*Client) CitDescription ¶
CitDescription reads a Gen1 device's CoIoT description (GET /cit/d).
func (*Client) Gen1Actions ¶ added in v0.2.0
Gen1Actions reads GET /settings/actions: the slots of each action by its name.
func (*Client) Get ¶
Get is a Gen1 GET of path (with query), returning the body as it came: with basic authentication when a password is set. GET /cit/d (the CoIoT description) is one use.
func (*Client) Get1 ¶
Get1 is a Gen1 GET of path (with query) as JSON, with basic authentication when a password is set.
func (*Client) OutboundWS ¶
func (c *Client) OutboundWS(ctx context.Context) (OutboundWS, error)
OutboundWS reads the device's outbound WebSocket setting; an error when the device has no Ws component (older firmware).
func (*Client) RPC ¶
func (c *Client) RPC(ctx context.Context, method string, params map[string]any) (json.RawMessage, error)
RPC calls a Gen2+ method over HTTP (POST /rpc), answering a digest challenge when the device has authentication on.
func (*Client) SetOutboundWS ¶
SetOutboundWS tells the device to open its outbound WebSocket to server (any certificate authority for wss). restart is true when the device takes the setting only after a restart (Reboot).
func (*Client) SetWiFi ¶
SetWiFi tells the device to join a network: WiFi.SetConfig for gen 2 and later, GET /settings/sta for Gen1.
func (*Client) Settings1 ¶ added in v0.2.0
func (c *Client) Settings1(ctx context.Context, section string, n int, values url.Values) (map[string]any, error)
Settings1 reads or changes Gen1 settings (see Gen1Settings) and returns the endpoint's answer.
func (*Client) Update ¶
Update tells the device to fetch and install the firmware image at imageURL: Shelly.Update with a url for gen 2 and later, GET /ota?url= for Gen1. The device restarts when it is done; WaitVersion follows it.
func (*Client) WaitVersion ¶
func (c *Client) WaitVersion(ctx context.Context, before, want string, every time.Duration) (Info, error)
WaitVersion reads GET /shelly every interval until the device reports a firmware version other than before (and containing want, when want is set), and returns what it read. Failed reads are skipped: the device is restarting. It returns ctx's error when ctx ends first.
type CoIoTListener ¶
type CoIoTListener struct {
// contains filtered or unexported fields
}
CoIoTListener receives CoIoT messages on UDP.
func ListenCoIoT ¶
func ListenCoIoT(addr *net.UDPAddr, group string) (*CoIoTListener, error)
ListenCoIoT opens a CoIoT listener on addr (":5683" when nil). With a group ("" means CoIoTGroup) it joins that multicast group on addr's port; "none" listens for unicast only, for devices given this host as their CoIoT peer. When the group cannot be joined it falls back to unicast on addr.
func (*CoIoTListener) Addr ¶
func (l *CoIoTListener) Addr() string
Addr is the address the listener is bound to.
func (*CoIoTListener) Serve ¶
func (l *CoIoTListener) Serve(ctx context.Context, fn func(m CoIoTMessage, from *net.UDPAddr)) error
Serve calls fn for each status message (a /cit/s path and a device id) with its sender until ctx ends or the listener is closed; it closes the listener when it returns.
type CoIoTMessage ¶
type CoIoTMessage struct {
// Code is the CoAP code (30, that is 0.30, for a status message).
Code byte
// Path is the URI path (/cit/s).
Path string
// DevType is the device's type (SHSW-25).
DevType string
// DevID is its id, the MAC's hexadecimal digits (A4CF12F45B2E).
DevID string
// Version is the CoIoT version the device names.
Version string
// Serial changes when the device's state changes.
Serial int
// Payload is the JSON status ({"G": [...]}).
Payload []byte
}
CoIoTMessage is one received CoIoT message.
func ParseCoAP ¶
func ParseCoAP(b []byte) (CoIoTMessage, error)
ParseCoAP reads a CoAP message as CoIoT carries it.
Example ¶
Read a CoIoT status message (what Gen1 devices multicast on UDP 5683).
package main
import (
"fmt"
"github.com/cB-Sigma/shelly"
)
func main() {
b := shelly.EncodeCoIoT("SHSW-1", "98CDAC1F0005", 7, []byte(`{"G":[[0,1101,1]]}`))
m, err := shelly.ParseCoAP(b)
if err != nil {
panic(err)
}
desc := shelly.CitDesc{Blk: []shelly.CitBlock{{I: 1, D: "relay_0"}}, Sen: []shelly.CitSensor{{I: 1101, T: "S", D: "output", L: 1}}}
for _, v := range desc.Decode(m.Payload) {
fmt.Println(m.DevType, m.DevID, m.Path, v.Sensor.D, v.Index, v.Value)
}
}
Output: SHSW-1 98CDAC1F0005 /cit/s output 0 1
type Component ¶ added in v0.2.0
type Component struct {
Key string `json:"key"`
Status json.RawMessage `json:"status,omitempty"`
Config json.RawMessage `json:"config,omitempty"`
Attrs json.RawMessage `json:"attrs,omitempty"`
}
Component is one entry of Shelly.GetComponents: its key, and its status and configuration as the device sent them.
func GetComponents ¶ added in v0.2.0
GetComponents lists the device's components (Shelly.GetComponents), reading every page; dynamicOnly lists only dynamic (virtual) components. It returns the configuration revision with them.
type Config ¶ added in v0.2.0
type Config map[string]json.RawMessage
Config is a Gen2+ device's configuration (Shelly.GetConfig) by component key.
func ParseConfig ¶ added in v0.2.0
ParseConfig reads a Shelly.GetConfig result.
func (Config) Cover ¶ added in v0.2.0
func (c Config) Cover(id int) (v CoverConfig, ok bool)
Cover reads cover:id's configuration.
func (Config) Input ¶ added in v0.2.0
func (c Config) Input(id int) (v InputConfig, ok bool)
Input reads input:id's configuration.
func (Config) Light ¶ added in v0.2.0
func (c Config) Light(typ string, id int) (v LightConfig, ok bool)
Light reads a light-like component's configuration (typ light, rgb, rgbw or cct).
func (Config) Name ¶ added in v0.2.0
Name is the device name in sys's configuration ("" when none is set).
func (Config) Switch ¶ added in v0.2.0
func (c Config) Switch(id int) (v SwitchConfig, ok bool)
Switch reads switch:id's configuration.
func (Config) WiFi ¶ added in v0.2.0
func (c Config) WiFi() (v WiFiConfigView, ok bool)
WiFi reads wifi's configuration.
type CoverConfig ¶ added in v0.2.0
type CoverConfig struct {
ID int `json:"id"`
Name *string `json:"name"`
InMode string `json:"in_mode,omitempty"`
InitialState string `json:"initial_state,omitempty"`
InvertDirection bool `json:"invert_directions"`
SwapInputs bool `json:"swap_inputs"`
MaxtimeOpen *float64 `json:"maxtime_open,omitempty"`
MaxtimeClose *float64 `json:"maxtime_close,omitempty"`
PowerLimit *float64 `json:"power_limit,omitempty"`
}
CoverConfig is a cover component's configuration (the common fields).
type CoverStatus ¶ added in v0.2.0
type CoverStatus struct {
ID int `json:"id"`
Source string `json:"source,omitempty"`
State string `json:"state"`
CurrentPos *float64 `json:"current_pos,omitempty"`
TargetPos *float64 `json:"target_pos,omitempty"`
SlatPos *float64 `json:"slat_pos,omitempty"`
MoveTimeout *float64 `json:"move_timeout,omitempty"`
MoveStartedAt *float64 `json:"move_started_at,omitempty"`
PosControl bool `json:"pos_control,omitempty"`
LastDirection string `json:"last_direction,omitempty"`
Errors []string `json:"errors,omitempty"`
Meter
}
CoverStatus is a cover component's status. State is open, closed, opening, closing, stopped or calibrating; positions are percent open and nil when the cover is not calibrated.
type DevicePowerStatus ¶ added in v0.2.0
type DevicePowerStatus struct {
ID int `json:"id"`
Battery struct {
V *float64 `json:"V"`
Percent *float64 `json:"percent"`
} `json:"battery"`
External *struct {
Present bool `json:"present"`
} `json:"external,omitempty"`
Errors []string `json:"errors,omitempty"`
}
DevicePowerStatus is a battery device's power status.
type EM1DataStatus ¶ added in v0.2.0
type EM1DataStatus struct {
ID int `json:"id"`
TotalActEnergy *float64 `json:"total_act_energy,omitempty"`
TotalActRetEnergy *float64 `json:"total_act_ret_energy,omitempty"`
}
EM1DataStatus is a single-phase channel's energy totals (em1data).
type EMDataStatus ¶ added in v0.2.0
type EMDataStatus struct {
ID int `json:"id"`
ATotalActEnergy *float64 `json:"a_total_act_energy,omitempty"`
ATotalActRetEnergy *float64 `json:"a_total_act_ret_energy,omitempty"`
BTotalActEnergy *float64 `json:"b_total_act_energy,omitempty"`
BTotalActRetEnergy *float64 `json:"b_total_act_ret_energy,omitempty"`
CTotalActEnergy *float64 `json:"c_total_act_energy,omitempty"`
CTotalActRetEnergy *float64 `json:"c_total_act_ret_energy,omitempty"`
TotalAct *float64 `json:"total_act,omitempty"`
TotalActRet *float64 `json:"total_act_ret,omitempty"`
}
EMDataStatus is a three-phase meter's energy totals (emdata), in watt-hours.
type EMPhase ¶ added in v0.2.0
type EMPhase struct {
Current *float64 `json:"current,omitempty"`
Voltage *float64 `json:"voltage,omitempty"`
ActPower *float64 `json:"act_power,omitempty"`
AprtPower *float64 `json:"aprt_power,omitempty"`
PF *float64 `json:"pf,omitempty"`
Freq *float64 `json:"freq,omitempty"`
}
EMPhase is one phase of a three-phase energy meter.
type EMStatus ¶ added in v0.2.0
type EMStatus struct {
ID int `json:"id"`
A, B, C EMPhase `json:"-"`
NCurrent *float64 `json:"n_current,omitempty"`
TotalCurrent *float64 `json:"total_current,omitempty"`
TotalActPower *float64 `json:"total_act_power,omitempty"`
TotalAprtPower *float64 `json:"total_aprt_power,omitempty"`
Errors []string `json:"errors,omitempty"`
}
EMStatus is a three-phase energy meter's status (em). The phases are read from the a_, b_ and c_ prefixed fields.
func (*EMStatus) UnmarshalJSON ¶ added in v0.2.0
UnmarshalJSON reads the phase-prefixed fields into A, B and C.
type Energy ¶ added in v0.2.0
type Energy struct {
Total float64 `json:"total"`
ByMinute []float64 `json:"by_minute,omitempty"`
MinuteTS int64 `json:"minute_ts,omitempty"`
}
Energy is an energy counter: Total in watt-hours, and the last three whole minutes in milliwatt-hours with the Unix time of the minute they end at.
type Event ¶
type Event struct {
// Component is the component that raised it ("input:0").
Component string
// Name is the event (single_push, long_push, …).
Name string
// TS is the device's time stamp in seconds since 1970; 0 when absent.
TS float64
// Fields are all the entry's fields.
Fields map[string]any
}
Event is one entry of a NotifyEvent's events list.
type Frame ¶
type Frame struct {
// Src is the device's id.
Src string
// Method is NotifyFullStatus, NotifyStatus or NotifyEvent.
Method string
// Params are the notification's params as sent.
Params json.RawMessage
}
Frame is one notification a device sent on its outbound WebSocket.
type GATT ¶
type GATT interface {
Write(ctx context.Context, char string, b []byte) error
Read(ctx context.Context, char string) ([]byte, error)
}
GATT is a connected Bluetooth LE peer: characteristic writes (with response) and reads, by UUID. The application brings the Bluetooth stack; this package only frames the RPC.
type Gen1Action ¶ added in v0.2.0
type Gen1Action struct {
Index int `json:"index"`
Enabled bool `json:"enabled"`
URLs []Gen1ActionURL `json:"urls"`
}
Gen1Action is one slot of a Gen1 action (an event such as out_on_url or btn1_shortpush_url).
func (*Gen1Action) UnmarshalJSON ¶ added in v0.2.0
func (a *Gen1Action) UnmarshalJSON(b []byte) error
UnmarshalJSON reads URLs given as strings (older firmware) or as objects with url and int (firmware 1.10 and later).
type Gen1ActionURL ¶ added in v0.2.0
Gen1ActionURL is one URL of a Gen1 action. Int is the time window of firmware that has one ("0000-0000": always).
type Gen1Report ¶
type Gen1Report struct {
// Kind says which fields are set.
Kind Gen1TopicKind
// Index is the output or input number; 0 when the topic has none.
Index int
// Text is the payload as sent.
Text string
// On is the state of relay/<n> and light/<n> ("on").
On bool
// Online is the state of online ("true").
Online bool
// Num is a number payload; IsNum is false when it was not a number.
Num float64
IsNum bool
// Light is light/<n>/status (ison, brightness, mode, …).
Light map[string]any
// Event and EventCnt are an input_event's ("S", "L", "SS"; Gen1Event
// names them).
Event string
EventCnt float64
// Name is a sensor's name (temperature, humidity, battery, lux).
Name string
}
Gen1Report is what one Gen1 topic says.
func ParseGen1Report ¶
func ParseGen1Report(rest []string, payload string) Gen1Report
ParseGen1Report reads a Gen1 topic below shellies/<id>/ (split at "/") and its payload. An input_event without an event, and a sensor or meter that is not a number, keep their Kind with the fields unset.
type Gen1TopicKind ¶
type Gen1TopicKind int
Gen1TopicKind says what a Gen1 status topic reports.
const ( // TopicOther is a topic not listed here (info, announce, …). TopicOther Gen1TopicKind = iota // TopicOnline is online: Online. TopicOnline // TopicRelay is relay/<n>: On. TopicRelay // TopicRelayPower is relay/<n>/power in W: Num. TopicRelayPower // TopicRelayEnergy is relay/<n>/energy in watt-minutes: Num. TopicRelayEnergy // TopicLight is light/<n>: On. TopicLight // TopicLightStatus is light/<n>/status: Light (nil when not JSON). TopicLightStatus // TopicRoller is roller/<n>: Text, the direction of travel (open, // close, stop). TopicRoller // TopicRollerPos is roller/<n>/pos in percent: Num (-1 while not // calibrated). TopicRollerPos // TopicInputEvent is input_event/<n>: Event and EventCnt. TopicInputEvent // TopicSensor is sensor/<name>: Name and Num. TopicSensor )
The Gen1 status topics.
type HumidityStatus ¶ added in v0.2.0
type HumidityStatus struct {
ID int `json:"id"`
RH *float64 `json:"rh"`
Errors []string `json:"errors,omitempty"`
}
HumidityStatus is a humidity sensor's status (relative humidity in percent).
type Inbound ¶
type Inbound struct {
// Frame is called for each frame that has a src and a method, in the
// order the channel's frames arrive.
Frame func(ctx context.Context, ch *InboundChannel, f Frame)
// Closed, when set, is called once a channel has ended.
Closed func(ch *InboundChannel)
}
Inbound is an http.Handler that accepts devices' outbound WebSockets. Mount it at the path devices are told (Ws.SetConfig's server), or run it with ServeInbound.
type InboundChannel ¶
type InboundChannel struct {
// RemoteIP is the device's address.
RemoteIP string
// Value is the application's own state for the channel (the device
// it belongs to, once known); Inbound does not touch it.
Value any
}
InboundChannel is one device's outbound WebSocket.
type Info ¶
type Info struct {
// Gen is the generation (2, 3, 4); Gen1 devices leave it out.
Gen int `json:"gen"`
// ID is the Gen2+ device id (shellyplus2pm-a8032ab12345).
ID string `json:"id"`
// Name is the name the owner gave the device.
Name string `json:"name"`
// MAC is the MAC address as 12 hexadecimal digits.
MAC string `json:"mac"`
// Model is the Gen2+ model code (SNSW-102P16EU).
Model string `json:"model"`
// App is the Gen2+ application name (Plus2PM).
App string `json:"app"`
// Ver is the Gen2+ firmware version.
Ver string `json:"ver"`
// AuthEn is true when a Gen2+ device has a login.
AuthEn bool `json:"auth_en"`
// Type is the Gen1 type code (SHSW-25).
Type string `json:"type"`
// Auth is true when a Gen1 device has a login.
Auth bool `json:"auth"`
// FW is the Gen1 firmware version.
FW string `json:"fw"`
}
Info is what GET /shelly tells without authentication: Gen1 carries type and auth, Gen2+ gen, id, model, app, ver and auth_en.
func GetDeviceInfo ¶ added in v0.2.0
GetDeviceInfo reads Shelly.GetDeviceInfo (the same fields as GET /shelly).
func (Info) DefaultID ¶
DefaultID is a device's identifier: the Gen2+ id in lower case, or shelly-<mac> for Gen1 (which reports none).
func (Info) Generation ¶
Generation is 1 for Gen1 devices, else the gen the device reports.
type InputConfig ¶ added in v0.2.0
type InputConfig struct {
ID int `json:"id"`
Name *string `json:"name"`
Type string `json:"type"`
Enable *bool `json:"enable,omitempty"`
Invert bool `json:"invert"`
FactoryReset *bool `json:"factory_reset,omitempty"`
}
InputConfig is an input component's configuration. Type is switch, button, analog or count.
type InputCounts ¶ added in v0.2.0
type InputCounts struct {
Total float64 `json:"total"`
XTotal *float64 `json:"xtotal,omitempty"`
ByMinute []float64 `json:"by_minute,omitempty"`
MinuteTS int64 `json:"minute_ts,omitempty"`
}
InputCounts is a counter input's pulse counts.
type InputStatus ¶ added in v0.2.0
type InputStatus struct {
ID int `json:"id"`
State *bool `json:"state,omitempty"`
Percent *float64 `json:"percent,omitempty"`
Counts *InputCounts `json:"counts,omitempty"`
Freq *float64 `json:"freq,omitempty"`
Errors []string `json:"errors,omitempty"`
}
InputStatus is an input component's status: State for a switch or button input (nil while unknown), Percent for an analog input, Counts and Freq for a counter input.
type KVSItem ¶ added in v0.2.0
type KVSItem struct {
Key string `json:"key"`
Etag string `json:"etag"`
Value json.RawMessage `json:"value"`
}
KVSItem is one entry of the key-value store.
func KVSGetMany ¶ added in v0.2.0
KVSGetMany reads the entries whose keys match (KVS.GetMany; "*" is a wildcard, "" all), every page. Firmware before 1.5 answers an object by key, later firmware a list with offset and total; both are read.
type LightConfig ¶ added in v0.2.0
type LightConfig struct {
ID int `json:"id"`
Name *string `json:"name"`
InMode string `json:"in_mode,omitempty"`
InitialState string `json:"initial_state,omitempty"`
AutoOn bool `json:"auto_on"`
AutoOnDelay float64 `json:"auto_on_delay,omitempty"`
AutoOff bool `json:"auto_off"`
AutoOffDelay float64 `json:"auto_off_delay,omitempty"`
TransitionDur *float64 `json:"transition_duration,omitempty"`
Default *struct {
Brightness *float64 `json:"brightness"`
} `json:"default,omitempty"`
NightMode *struct {
Enable bool `json:"enable"`
Brightness *float64 `json:"brightness"`
} `json:"night_mode,omitempty"`
}
LightConfig is the configuration of a light, rgb, rgbw or cct component (the common fields).
type LightSet ¶ added in v0.2.0
type LightSet struct {
On *bool
Brightness *float64 // percent
RGB []int // red, green, blue 0-255 (rgb, rgbw)
White *float64 // 0-255 (rgbw)
CT *float64 // kelvin (cct)
Transition *float64 // seconds
ToggleAft *float64 // seconds
}
LightSet is what LightSetParams sends; nil fields are left as they are.
type LightStatus ¶ added in v0.2.0
type LightStatus struct {
ID int `json:"id"`
Source string `json:"source,omitempty"`
Output bool `json:"output"`
Brightness *float64 `json:"brightness,omitempty"`
RGB []int `json:"rgb,omitempty"`
White *float64 `json:"white,omitempty"`
CT *float64 `json:"ct,omitempty"`
TimerStartedAt *float64 `json:"timer_started_at,omitempty"`
TimerDuration *float64 `json:"timer_duration,omitempty"`
Errors []string `json:"errors,omitempty"`
Meter
}
LightStatus is the status of a light, rgb, rgbw or cct component. Brightness is percent; RGB is red, green and blue 0-255; White is the white channel 0-255 (rgbw); CT is the colour temperature in kelvin (cct).
type MQTT ¶
type MQTT struct {
// Prefix is the Gen1 topic root (default DefaultMQTTPrefix).
Prefix string
// Src is the JSON-RPC "src" of requests; devices answer on <Src>/rpc.
Src string
// Timeout bounds the wait for a Gen2+ answer (default 5 s).
Timeout time.Duration
// Pub sends the requests and commands.
Pub Publisher
// contains filtered or unexported fields
}
MQTT reads and commands devices in MQTT mode over an application's MQTT client. Set the fields before use; it is safe for concurrent use after.
func (*MQTT) Command1 ¶
Command1 sends a Gen1 GET (path with query, as the Gen1* request builders make it) as the MQTT command under root (<prefix>/<id>). Gen1 devices do not answer commands; their next state message confirms.
func (*MQTT) Filters ¶
Filters are the topic filters to subscribe to: everything under the Gen1 root, Gen2+ notifications and online states, and the answers to this client's requests.
func (*MQTT) Handle ¶
func (m *MQTT) Handle(topic string, payload []byte) MQTTMessage
Handle reads one received message. Answers to RPC requests are delivered to the waiting call and come back as MQTTNone.
func (*MQTT) RPC ¶
func (m *MQTT) RPC(ctx context.Context, root, method string, params map[string]any) (json.RawMessage, error)
RPC calls a Gen2+ method over the broker: the request goes to <root>/rpc and the answer comes back through Handle. An error object in the answer is an error naming the method.
type MQTTDevice ¶ added in v0.2.0
MQTTDevice is one Gen2+ device over MQTT: Root is its topic prefix (the device id unless its MQTT topic_prefix was changed).
type MQTTKind ¶
type MQTTKind int
MQTTKind says what an MQTT message is.
const ( // MQTTNone is a message that is not for the application: an answer // to a request (delivered to RPC), or one Handle cannot read. MQTTNone MQTTKind = iota // MQTTNotification is a Gen2+ JSON-RPC notification. MQTTNotification // MQTTAnnounce is a Gen1 device's announcement. MQTTAnnounce // MQTTGen1 is a Gen1 device's topic. MQTTGen1 )
The kinds of message Handle returns.
type MQTTMessage ¶
type MQTTMessage struct {
// Kind says which of the fields below are set.
Kind MQTTKind
// Root is the device's topic root: the Gen2+ prefix before
// /events/rpc, or <Prefix>/<id> for Gen1 and announcements.
Root string
// Src, Method and Params are a Gen2+ notification's.
Src, Method string
Params json.RawMessage
// Announce is a Gen1 announcement.
Announce Announce
// Device is a Gen1 device's id, Topic its topic below <Prefix>/<id>/
// (split at "/") and Report what that topic says.
Device string
Topic []string
Report Gen1Report
}
MQTTMessage is a message Handle read.
type Meter ¶ added in v0.2.0
type Meter struct {
APower *float64 `json:"apower,omitempty"`
Voltage *float64 `json:"voltage,omitempty"`
Current *float64 `json:"current,omitempty"`
PF *float64 `json:"pf,omitempty"`
Freq *float64 `json:"freq,omitempty"`
AEnergy *Energy `json:"aenergy,omitempty"`
RetAEnergy *Energy `json:"ret_aenergy,omitempty"`
Temp *Temperature `json:"temperature,omitempty"`
}
Meter holds the readings a metering output reports.
type OutboundWS ¶
type OutboundWS struct {
// Enable is true when the device opens the channel.
Enable bool `json:"enable"`
// Server is the ws:// or wss:// address it connects to.
Server string `json:"server"`
}
OutboundWS is a Gen2+ device's outbound WebSocket setting (Ws.GetConfig).
type Publisher ¶
type Publisher interface {
Publish(ctx context.Context, topic string, payload []byte, retain bool) error
}
Publisher publishes MQTT messages: the application's MQTT client.
type RPCError ¶
type RPCError struct {
// Code is the error code (401 asks for authentication; Shelly's own
// codes are negative).
Code int `json:"code"`
// Message is the device's text (for a 401 over WebSocket, the
// authentication challenge as JSON).
Message string `json:"message"`
}
RPCError is an error object of a JSON-RPC answer.
type ScheduleCall ¶ added in v0.2.0
type ScheduleCall struct {
Method string `json:"method"`
Params map[string]any `json:"params,omitempty"`
}
ScheduleCall is one RPC call a schedule job makes.
type ScheduleJob ¶ added in v0.2.0
type ScheduleJob struct {
ID int `json:"id,omitempty"`
Enable bool `json:"enable"`
Timespec string `json:"timespec"`
Calls []ScheduleCall `json:"calls"`
}
ScheduleJob is a schedule job. Timespec has six space-separated fields (seconds, minutes, hours, day of month, month, day of week) in the cron style the device documents, or starts with @sunrise or @sunset with an optional offset. ID is set by the device.
func ListSchedules ¶ added in v0.2.0
ListSchedules lists the jobs (Schedule.List).
type Script ¶ added in v0.2.0
type Script struct {
ID int `json:"id"`
Name string `json:"name"`
Enable bool `json:"enable"`
Running bool `json:"running"`
}
Script is an entry of Script.List.
type ScriptStatus ¶ added in v0.2.0
type ScriptStatus struct {
ID int `json:"id"`
Running bool `json:"running"`
MemUsed int `json:"mem_used,omitempty"`
MemPeak int `json:"mem_peak,omitempty"`
MemFree int `json:"mem_free,omitempty"`
Errors []string `json:"errors,omitempty"`
}
ScriptStatus is Script.GetStatus.
func GetScriptStatus ¶ added in v0.2.0
GetScriptStatus reads Script.GetStatus.
type Status ¶ added in v0.2.0
type Status map[string]json.RawMessage
Status is a Gen2+ device's status (Shelly.GetStatus, NotifyFullStatus) by component key ("switch:0", "sys").
func ParseStatus ¶ added in v0.2.0
ParseStatus reads a Shelly.GetStatus result.
Example ¶
ExampleParseStatus reads a switch's output and power from a status.
package main
import (
"fmt"
"github.com/cB-Sigma/shelly"
)
func main() {
st, _ := shelly.ParseStatus([]byte(`{"switch:0":{"id":0,"output":true,"apower":42.5,"aenergy":{"total":1200}},"sys":{"uptime":60}}`))
if sw, ok := st.Switch(0); ok {
fmt.Println(sw.Output, *sw.APower, sw.AEnergy.Total)
}
}
Output: true 42.5 1200
func (Status) Cover ¶ added in v0.2.0
func (s Status) Cover(id int) (v CoverStatus, ok bool)
Cover reads cover:id.
func (Status) Decode ¶ added in v0.2.0
Decode reads one component's status into v; false when the device has no such component or it does not fit v.
func (Status) DevicePower ¶ added in v0.2.0
func (s Status) DevicePower(id int) (v DevicePowerStatus, ok bool)
DevicePower reads devicepower:id.
func (Status) EM1Data ¶ added in v0.2.0
func (s Status) EM1Data(id int) (v EM1DataStatus, ok bool)
EM1Data reads em1data:id.
func (Status) EMData ¶ added in v0.2.0
func (s Status) EMData(id int) (v EMDataStatus, ok bool)
EMData reads emdata:id.
func (Status) Humidity ¶ added in v0.2.0
func (s Status) Humidity(id int) (v HumidityStatus, ok bool)
Humidity reads humidity:id.
func (Status) Input ¶ added in v0.2.0
func (s Status) Input(id int) (v InputStatus, ok bool)
Input reads input:id.
func (Status) Light ¶ added in v0.2.0
func (s Status) Light(typ string, id int) (v LightStatus, ok bool)
Light reads a light-like component: typ is light, rgb, rgbw or cct.
func (Status) Switch ¶ added in v0.2.0
func (s Status) Switch(id int) (v SwitchStatus, ok bool)
Switch reads switch:id.
func (Status) Temperature ¶ added in v0.2.0
func (s Status) Temperature(id int) (v TemperatureStatus, ok bool)
Temperature reads temperature:id.
func (Status) WiFi ¶ added in v0.2.0
func (s Status) WiFi() (v WiFiStatus, ok bool)
WiFi reads wifi.
type SwitchConfig ¶ added in v0.2.0
type SwitchConfig struct {
ID int `json:"id"`
Name *string `json:"name"`
InMode string `json:"in_mode,omitempty"`
InitialState string `json:"initial_state,omitempty"`
AutoOn bool `json:"auto_on"`
AutoOnDelay float64 `json:"auto_on_delay,omitempty"`
AutoOff bool `json:"auto_off"`
AutoOffDelay float64 `json:"auto_off_delay,omitempty"`
PowerLimit *float64 `json:"power_limit,omitempty"`
VoltageLimit *float64 `json:"voltage_limit,omitempty"`
CurrentLimit *float64 `json:"current_limit,omitempty"`
AutorecoverVolts *bool `json:"autorecover_voltage_errors,omitempty"`
}
SwitchConfig is a switch component's configuration. InMode is how the input drives it (momentary, follow, flip, detached, cycle, activate); InitialState is on, off, restore_last or match_input.
type SwitchStatus ¶ added in v0.2.0
type SwitchStatus struct {
ID int `json:"id"`
Source string `json:"source,omitempty"`
Output bool `json:"output"`
TimerStartedAt *float64 `json:"timer_started_at,omitempty"`
TimerDuration *float64 `json:"timer_duration,omitempty"`
Errors []string `json:"errors,omitempty"`
Meter
}
SwitchStatus is a switch component's status.
type SysConfig ¶ added in v0.2.0
type SysConfig struct {
Device struct {
Name *string `json:"name"`
MAC string `json:"mac"`
FWID string `json:"fw_id"`
Discoverable bool `json:"discoverable"`
EcoMode bool `json:"eco_mode"`
Profile string `json:"profile,omitempty"`
} `json:"device"`
Location struct {
TZ *string `json:"tz"`
Lat *float64 `json:"lat"`
Lon *float64 `json:"lon"`
} `json:"location"`
CfgRev int `json:"cfg_rev"`
}
SysConfig is the sys component's configuration: the device block (name, MAC, firmware id, discoverability), location and revision.
type SysStatus ¶ added in v0.2.0
type SysStatus struct {
MAC string `json:"mac"`
RestartRequired bool `json:"restart_required"`
Time string `json:"time,omitempty"`
UnixTime int64 `json:"unixtime,omitempty"`
Uptime float64 `json:"uptime"`
RAMSize int `json:"ram_size,omitempty"`
RAMFree int `json:"ram_free,omitempty"`
FSSize int `json:"fs_size,omitempty"`
FSFree int `json:"fs_free,omitempty"`
CfgRev int `json:"cfg_rev,omitempty"`
KVSRev int `json:"kvs_rev,omitempty"`
ScheduleRev int `json:"schedule_rev,omitempty"`
WebhookRev int `json:"webhook_rev,omitempty"`
WakeupPeriod int `json:"wakeup_period,omitempty"`
ResetReason int `json:"reset_reason,omitempty"`
AvailableUpdates map[string]struct {
Version string `json:"version"`
} `json:"available_updates,omitempty"`
}
SysStatus is the sys component's status.
type Temperature ¶ added in v0.2.0
Temperature is a temperature in Celsius and Fahrenheit (nil when the sensor has no reading).
type TemperatureStatus ¶ added in v0.2.0
type TemperatureStatus struct {
ID int `json:"id"`
C *float64 `json:"tC"`
F *float64 `json:"tF"`
Errors []string `json:"errors,omitempty"`
}
TemperatureStatus is a temperature sensor's status.
type WSOptions ¶
type WSOptions struct {
// Src is the "src" of the requests: the name the device answers to.
Src string
// Password answers the device's authentication challenge; with none,
// a device that asks fails with ErrAuth.
Password string
// Timeout bounds the dial, each write and each ping (default 5 s).
Timeout time.Duration
// Ping is how often the channel is pinged to notice one that died
// without a close (default a minute).
Ping time.Duration
// Status receives the result of the Shelly.GetStatus request the
// channel opens with: the device's complete status, by component.
Status func(status map[string]any) error
// Notify receives each notification (NotifyStatus, NotifyFullStatus,
// NotifyEvent) with its params as sent.
Notify func(method string, params json.RawMessage) error
}
WSOptions configure WatchWS.
type Webhook ¶ added in v0.2.0
type Webhook struct {
ID int `json:"id,omitempty"`
CID int `json:"cid"`
Enable bool `json:"enable"`
Event string `json:"event"`
Name string `json:"name,omitempty"`
URLs []string `json:"urls"`
Condition string `json:"condition,omitempty"`
RepeatPeriod int `json:"repeat_period,omitempty"`
ActiveBetween []string `json:"active_between,omitempty"`
SSLCA string `json:"ssl_ca,omitempty"`
}
Webhook is a webhook (an action): when Event happens on component instance CID, the device calls URLs. Condition, RepeatPeriod and ActiveBetween are optional.
type WiFiConfigView ¶ added in v0.2.0
type WiFiConfigView struct {
AP struct {
SSID *string `json:"ssid"`
Enable bool `json:"enable"`
IsOpen bool `json:"is_open"`
} `json:"ap"`
STA struct {
SSID *string `json:"ssid"`
Enable bool `json:"enable"`
IsOpen bool `json:"is_open"`
IPv4 string `json:"ipv4mode,omitempty"`
} `json:"sta"`
STA1 struct {
SSID *string `json:"ssid"`
Enable bool `json:"enable"`
} `json:"sta1"`
}
WiFiConfigView is the wifi component's configuration (passwords are never returned by devices).