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).
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 BLERPC(ctx context.Context, g GATT, src string, id int, method string, ...) (json.RawMessage, error)
- func BaseURL(addr string) (string, error)
- func DigestResponse(user, realm, password, method, uri, nonce, nc, cnonce string) string
- func EncodeCoIoT(devType, devID string, serial int, payload []byte) []byte
- 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 Gen1Turn(kind string, n int, turn string) string
- func MACOfID(id string) string
- func MethodPrefix(typ string) string
- func SHA256Hex(s string) string
- func ServeInbound(ctx context.Context, ln net.Listener, path string, in *Inbound) error
- func SplitKey(k string) (typ string, id int, ok bool)
- 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 WiFiConfig(ssid, password string) map[string]any
- type Announce
- type BLEDialer
- type CitBlock
- type CitDesc
- type CitSensor
- type CitValue
- type Client
- func (c *Client) CitDescription(ctx context.Context) (CitDesc, 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) 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 Event
- type Frame
- type GATT
- type Gen1Report
- type Gen1TopicKind
- type Inbound
- type InboundChannel
- type Info
- type MQTT
- type MQTTKind
- type MQTTMessage
- type OutboundWS
- type Publisher
- type RPCError
- type WSOptions
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 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 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 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 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 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.
func ServeInbound ¶
ServeInbound serves in at path on ln until ctx ends, which also ends the open channels; it closes ln.
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 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 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 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 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) 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) 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 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 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 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 (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 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 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 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 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.