shelly

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 11, 2026 License: Apache-2.0 Imports: 20 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

shelly

The local APIs of Shelly devices in pure Go, without the Shelly cloud; not affiliated with Shelly Group.

Go Reference test Go

It speaks Gen1 HTTP with basic authentication, CoIoT and MQTT, and the Gen2, Gen3 and Gen4 JSON-RPC API over HTTP with SHA-256 digest authentication, over the WebSocket notification channel, over the outbound WebSocket that sleeping devices open, over MQTT and over BLE; it also sets up a new device's Wi-Fi and updates firmware by URL. Its one dependency is coder/websocket; there is no cgo. It was written for SigmaM2M, a oneM2M platform, whose Shelly integration it serves.

Features

Feature Status
GET /shelly, generation detection (Info) yes
Gen1 HTTP with basic authentication; relay, light (white and colour mode), colour and roller requests yes; a level on a light in colour mode is sent as gain on /color/n
Gen2+ JSON-RPC over HTTP with SHA-256 digest (RFC 7616; nonce count, one re-challenge) yes
Gen2+ WebSocket channel: authentication object, status, notifications, keep-alive (WatchWS) yes
Outbound WebSocket of sleeping Gen2+ devices: server (Inbound), Ws.GetConfig and Ws.SetConfig yes
CoIoT: CoAP codec, /cit/d description (sensors in one block or several), multicast and unicast listener yes; values by the description, never by fixed sensor IDs
MQTT mode: Gen1 topics and commands, Gen2+ notifications and JSON-RPC yes, over the application's MQTT client (Publisher, Filters, Handle)
BLE RPC framing yes, over the application's Bluetooth stack (GATT)
Wi-Fi setup (Gen1 /settings/sta, Gen2+ WiFi.SetConfig), firmware update by URL yes

Left out on purpose:

  • Discovery. Gen2+ devices announce _shelly._tcp over mDNS; browse with an mDNS library such as mdns. Gen1 devices are also found by their CoIoT messages (ListenCoIoT).
  • Typed per-component models. Status and configuration stay maps by component key (switch:0), so new components and fields reach the application without a new release.
  • A Bluetooth stack and an MQTT client: they come from the application, which keeps this module free of cgo and heavy dependencies.
  • The Shelly cloud, scripts, schedules, webhooks, Gen1 settings beyond Wi-Fi.

Choosing a Go Shelly library

Compared from each library's source at the versions named, read on 2026-10-11 (not run). Check the projects themselves before relying on a row.

this module tj-smith47/shelly-go v0.14.0 jcodybaker/go-shelly (commit 6c8a73a, 2026-07-19)
Licence Apache-2.0 Apache-2.0 MIT
Gen1 HTTP with basic authentication yes yes no (Gen2+ only)
Gen1 CoIoT yes yes no
Gen1 MQTT topic model yes no (MQTT transport, topics by the caller) no
Gen2+ RPC over HTTP with SHA-256 digest yes, own code yes, own code through mongoose-os's mgrpc
Gen2+ WebSocket channel with notifications and the auth object yes yes types only; transport from mgrpc
Server for the outbound WebSocket of sleeping devices yes no (Ws.SetConfig only) no
Gen2+ RPC over MQTT yes, over your client yes, on Eclipse Paho partial (no events/rpc)
BLE RPC framing over your GATT yes, on tinygo bluetooth no
Typed component models no, maps yes, Gen1 and Gen2+ yes, Gen2+
Discovery, cloud API no mDNS, CoIoT, BLE, Wi-Fi; cloud no
Simulator for tests yes (shelly-sim) mocks and one fixture no
cgo none on macOS, through tinygo bluetooth none
Direct dependencies coder/websocket 6 (Paho, gorilla/websocket, tinygo bluetooth, gonetworkmanager, mdlayher/wifi, testcontainers-go) 4 (Paho, google/uuid, mongoose-os/mos, testify)
Size (non-test Go lines) about 1,800 about 61,600 about 6,200

Pick this module for a gateway or integration that has to reach every generation, take pushes by every route (CoIoT, the WebSocket channel, sleeping devices' outbound WebSocket, MQTT) and stay small and free of cgo, and that is happy with status as maps. Pick tj-smith47/shelly-go for typed models of each component, discovery and the Shelly cloud in one package. Pick jcodybaker/go-shelly if you build on mongoose-os's RPC tooling and need only Gen2+ devices.

Install

go get github.com/cB-Sigma/shelly@latest

Requires Go 1.24 or later.

Quick start

import "github.com/cB-Sigma/shelly"

base, _ := shelly.BaseURL("192.168.1.50")
c := &shelly.Client{Base: base, Password: pw, HTTP: &http.Client{Timeout: 5 * time.Second}}
info, err := c.Shelly(ctx)
if info.Generation() >= 2 {
	_, err = c.RPC(ctx, "Switch.Set", map[string]any{"id": 0, "on": true})
	err = shelly.WatchWS(ctx, base, shelly.WSOptions{Src: "my-app", Password: pw,
		Notify: func(method string, params json.RawMessage) error { /* ... */ return nil }})
} else {
	_, err = c.Get1(ctx, shelly.Gen1Level(0, 40, colourMode, nil))
}

The runnable examples are Example, ExampleGen1Level and ExampleParseCoAP in example_test.go; go test runs them.

Documentation

API reference: https://pkg.go.dev/github.com/cB-Sigma/shelly

Package What it does
shelly (module root) Client (Shelly, Get1, Get, RPC, SetWiFi, Update, WaitVersion, OutboundWS, SetOutboundWS, Reboot, CitDescription), Info, RPCError, ErrAuth, DigestResponse, WSAuth, BaseURL. Push: WatchWS and Events (Gen2+ WebSocket), Inbound and ServeInbound (outbound WebSocket), ParseCoAP, EncodeCoIoT, CitDesc.Decode, ListenCoIoT (CoIoT), MQTT with Publisher, ParseGen1Report, Gen1MQTT (MQTT mode). Requests: Gen1Turn, Gen1Level, Gen1Colour, Gen1Roller, Gen1RollerPos, MethodPrefix, SplitKey. Setup: BLERPC over a GATT, WiFiConfig
interop (nested module, tests only) the client against payloads recorded from real devices (see below)

Changes per version are in CHANGELOG.md.

Testing

go test -race ./...

The tests here use a small fake device written in the test (fake_test.go) and the RFC 7616 SHA-256 example. The tests that drive the full simulator (every request, CoIoT, MQTT, the WebSocket channel, the outbound WebSocket, BLE, Wi-Fi setup and firmware updates) are in shelly-sim, so this module does not depend on its simulator. Two tests carry // Covers: SIG-... comments: these are requirement IDs of the SigmaM2M project's compliance report and have no meaning outside it.

interop/ is a nested module with its own go.mod. Its tests fetch the recorded payloads from GitHub at fixed revisions and are skipped unless SIGMA_SHELLY_INTEROP=1 is set:

cd interop && SIGMA_SHELLY_INTEROP=1 go test -v ./...
Interop tested against
  • Payloads recorded from real devices (interop, 2026-10-11): the four Gen1 devices (Shelly Air, Gas, Plug S, Vintage) and nine Gen2 devices (BLU Gateway at two firmware versions, Plus 1PM, Plus Plug IT, Plus Plug S, Pro 3EM, Pro 3, Pro 4PM, Wall Display) of aioshelly 13.34.1's fixtures, its Plus 2PM device info with authentication on and the WebSocket 401 frame that device sent, and the twelve Gen2, Gen3 and Gen4 devices of Home Assistant core's Shelly test fixtures (commit e8c451ce3967; among them a 2PM Gen3 as switches and as a cover, a Pro 3EM, a Duo Bulb Gen3, a Gen4 power strip, a Wall Display XL). A test server answers with the recorded payloads; Shelly, Get1, RPC, OutboundWS, SplitKey, MethodPrefix and WSAuth read them correctly. The dumps are anonymised recordings made by those projects' contributors; the serving is ours.
  • aioshelly 13.34.1 against the simulator in shelly-sim: checks the simulator this module's integration tests use, not this module.
  • Not yet: a real device on a network, BLE RPC against a device, MQTT against a broker with devices, CoIoT multicast from a device.
  • shelly-sim: simulated Gen1 and Gen2+ devices on their local APIs, as a Go package and a command, with this module's integration tests.

Status

v0.x: the API may change before v1.

Contributing

See CONTRIBUTING.md.

Security

See SECURITY.md to report a vulnerability privately.

Licence

Apache-2.0 (see LICENSE and NOTICE). Copyright 2026 Abhinav Gautam. Shelly is a trademark of Shelly Group; the name is used only to say which devices this module talks to.

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

Examples

Constants

View Source
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.

View Source
const (
	CoIoTGroup = "224.0.1.187"
	CoIoTPort  = 5683
)

CoIoT defaults: the multicast group and UDP port devices send to.

View Source
const DefaultAPAddress = "192.168.33.1"

DefaultAPAddress is a Shelly device's address on its own hotspot.

View Source
const DefaultMQTTPrefix = "shellies"

DefaultMQTTPrefix is the Gen1 topic root devices use unless set.

View Source
const User = "admin"

User is the user name of Gen2+ authentication (fixed by the API).

Variables

View Source
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

func BaseURL(addr string) (string, error)

BaseURL turns an address (host, host:port, http://host:port or https://host:port) into the Base of a Client.

func DigestResponse

func DigestResponse(user, realm, password, method, uri, nonce, nc, cnonce string) string

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

func EncodeCoIoT(devType, devID string, serial int, payload []byte) []byte

EncodeCoIoT builds a CoIoT status message to /cit/s with serial and payload, as a device sends it (for simulators and tests).

func Gen1Colour

func Gen1Colour(n int, r, g, b uint8, gain *float64) string

Gen1Colour turns colour output n on with red, green and blue, and gain (percent) when set.

func Gen1Event

func Gen1Event(e string) string

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

func Gen1Level(n int, level float64, colourMode bool, transition *float64) string

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

func Gen1MQTT(pathQuery string) (string, string, error)

Gen1MQTT turns a Gen1 GET into the MQTT command topic (under shellies/<id>/) and payload.

func Gen1Roller

func Gen1Roller(n int, move string) string

Gen1Roller moves roller n: open, close or stop.

func Gen1RollerPos

func Gen1RollerPos(n int, pos float64) string

Gen1RollerPos moves roller n to pos percent (100 open).

func Gen1Turn

func Gen1Turn(kind string, n int, turn string) string

Gen1Turn switches output n of kind relay or light: turn is on, off or toggle.

func MACOfID

func MACOfID(id string) string

MACOfID is the MAC part of a Gen1 id in lower case (shelly1-A4CF12F45B2E → a4cf12f45b2e); "" when the id has none.

func MethodPrefix

func MethodPrefix(typ string) string

MethodPrefix is the RPC namespace of a Gen2+ component type: switch → Switch, light → Light, rgb → RGB, rgbw → RGBW, cct → CCT, cover → Cover.

func SHA256Hex

func SHA256Hex(s string) string

SHA256Hex is the hexadecimal SHA-256 of s.

func ServeInbound

func ServeInbound(ctx context.Context, ln net.Listener, path string, in *Inbound) error

ServeInbound serves in at path on ln until ctx ends, which also ends the open channels; it closes ln.

func SplitKey

func SplitKey(k string) (typ string, id int, ok bool)

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

func WSAuth(challengeJSON, password string) (map[string]any, error)

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

func WSURL(base string) string

WSURL is the WebSocket address of a device's RPC channel for a Client Base (http://host → ws://host/rpc, https → wss).

func WatchWS

func WatchWS(ctx context.Context, base string, o WSOptions) error

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

func WiFiConfig(ssid, password string) map[string]any

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

func (c CitDesc) BlockIndex(s CitSensor) (n int, ok bool)

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).

func (CitDesc) Decode

func (c CitDesc) Decode(payload []byte) []CitValue

Decode reads a status payload ({"G": [[channel, sensor ID, value], …]}) with the description, in the payload's order. Triples of sensors the description does not list are left out; a payload that is not JSON gives nothing.

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

func (s *CitSensor) UnmarshalJSON(b []byte) error

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

func (c *Client) CitDescription(ctx context.Context) (CitDesc, error)

CitDescription reads a Gen1 device's CoIoT description (GET /cit/d).

func (*Client) Get

func (c *Client) Get(ctx context.Context, pathQuery string) ([]byte, error)

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

func (c *Client) Get1(ctx context.Context, pathQuery string) (map[string]any, error)

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) Reboot

func (c *Client) Reboot(ctx context.Context) error

Reboot restarts a Gen2+ device (Shelly.Reboot).

func (*Client) SetOutboundWS

func (c *Client) SetOutboundWS(ctx context.Context, server string) (restart bool, err error)

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

func (c *Client) SetWiFi(ctx context.Context, gen int, ssid, password string) error

SetWiFi tells the device to join a network: WiFi.SetConfig for gen 2 and later, GET /settings/sta for Gen1.

func (*Client) Shelly

func (c *Client) Shelly(ctx context.Context) (Info, error)

Shelly reads GET /shelly.

func (*Client) Update

func (c *Client) Update(ctx context.Context, gen int, imageURL string) error

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) Close

func (l *CoIoTListener) Close() error

Close stops the listener.

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.

func Events

func Events(params map[string]any) []Event

Events reads the events of a NotifyEvent's params.

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.

func (*Inbound) ServeHTTP

func (in *Inbound) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP accepts one channel and reads its frames until it closes or the request's context ends.

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

func (i Info) DefaultID() string

DefaultID is a device's identifier: the Gen2+ id in lower case, or shelly-<mac> for Gen1 (which reports none).

func (Info) Firmware

func (i Info) Firmware() string

Firmware is the version to show.

func (Info) Generation

func (i Info) Generation() int

Generation is 1 for Gen1 devices, else the gen the device reports.

func (Info) ModelName

func (i Info) ModelName() string

ModelName is the model to show.

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

func (m *MQTT) Command1(ctx context.Context, root, pathQuery string) error

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

func (m *MQTT) Filters() []string

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.

func (*RPCError) Error

func (e *RPCError) Error() string

Error is "RPC error <code>: <message>".

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.

Jump to

Keyboard shortcuts

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