shelly

package module
v0.3.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: 26 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, receives webhooks and action URLs, and reads Shelly BLU and other BTHome Bluetooth sensors (package bthome, with AES-CCM). 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
Typed status and configuration: switch, cover, light/rgb/rgbw/cct, input (switch, analog, counter), em, emdata, em1, em1data, pm1, temperature, humidity, devicepower, sys, wifi yes, as views over the maps (Status, Config); unknown components and fields stay readable
Typed calls over any transport (Caller: HTTP, MQTT, BLE, your own) yes: status, config, <Type>.SetConfig, switch, cover, light, components with paging
Scripts: create, upload in chunks, read back in pages, start, stop, eval, status, config, delete yes
Schedules, webhooks (with the supported-event list), KVS (with etags, both GetMany forms), virtual components yes
Gen1 settings beyond Wi-Fi: /settings and /settings/
/, actions (/settings/actions, both URL forms)
yes
Discovery: DNS-SD (_shelly._tcp, _http._tcp) through your mDNS browser, CoIoT, a subnet scan; each confirmed with GET /shelly yes, package discover
Webhook and action URL receiver: an http.Handler for Gen2+ webhooks (with ${...} URL tokens), Gen1 actions and Gen1 sensor report URLs, with a shared token and a source check (HookHandler, HookURL, HookWebhook) yes, since v0.3.0
BTHome (Shelly BLU and other BTHome sensors): v2 and v1 decoding, AES-CCM encryption, every object id of the format, events, a packet builder, advertising data, replay guard yes, package bthome, since v0.3.0
Bluetooth through Gen2+ devices: the BTHome component (add and delete devices and sensors, discovery, object information, known objects, events, typed status), relayed advertisements (ble.scan_result, with a relay script), Shelly manufacturer data yes, since v0.3.0
Typed views of smoke, flood, illuminance, voltmeter yes, since v0.3.0
The Shelly cloud no: needs a Shelly cloud account and its auth key (see Not yet)

Left out on purpose:

  • An mDNS implementation, a Bluetooth stack and an MQTT client: they come from the application, which keeps this module free of cgo and heavy dependencies. discover.Browser takes any mDNS browser; mdns is one (below).

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 Gen2+ status and configuration of the common components, as views over the maps; Gen1 as maps yes, Gen1 and Gen2+ yes, Gen2+
Scripts, schedules, webhooks, KVS, virtual components yes yes types only
Gen1 settings and actions yes yes no
Discovery DNS-SD over your mDNS browser, CoIoT, subnet scan mDNS, CoIoT, BLE, Wi-Fi no
Webhook and action URL receiver yes (HookHandler) no (creates webhooks only) no
BTHome decoding every object id of the format, v1 and v2, AES-CCM decryption, builder; checked against bthome-ble nine object ids, no decryption no
BTHome component of Gen2+ devices calls, views and events calls and types no
Relayed advertisements (ble.scan_result) yes, with a relay script no no
Cloud API no yes 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 5,400 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, with typed views where you want them and the raw maps where a new component appears, receive webhooks, or read Shelly BLU and other BTHome sensors (through a Shelly device or your own Bluetooth scanner). Pick tj-smith47/shelly-go for the Shelly cloud, BLE scanning and Wi-Fi discovery on its own stacks, or typed models of every Gen1 endpoint and rarer Gen2+ components. 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))
}

Typed views and the newer calls take any Caller (a *Client, an MQTTDevice, a BLEDevice):

st, _ := shelly.GetStatus(ctx, c)
if sw, ok := st.Switch(0); ok && sw.APower != nil {
	fmt.Println(sw.Output, *sw.APower)
}
id, _ := shelly.CreateScript(ctx, c, "blink")
_ = shelly.PutScriptCode(ctx, c, id, code, 0) // in chunks
_, _ = shelly.StartScript(ctx, c, id)
_, _, _ = shelly.KVSSet(ctx, c, "mode", "eco", "")

Discovery with mdns as the browser:

browse := func(ctx context.Context, svc string) ([]discover.Service, error) {
	list, err := mdns.Browse(ctx, svc, mdns.Options{})
	out := make([]discover.Service, 0, len(list))
	for _, s := range list {
		out = append(out, discover.Service{Instance: s.Instance, Host: s.Host, Port: s.Port, IPs: s.IPs, TXT: s.TXT})
	}
	return out, err
}
devices, err := discover.MDNS(ctx, browse, discover.Options{})

Receiving webhooks, and BTHome sensors heard by a Gen2+ device:

http.Handle("/hooks/", &shelly.HookHandler{Prefix: "/hooks", Token: secret,
	Handle: func(h shelly.Hook) { tC, _ := h.Float("tC"); log.Println(h.Device, h.Event, tC) }})
_, _, _ = shelly.CreateWebhook(ctx, c, shelly.HookWebhook("http://192.168.1.10:8080/hooks", id,
	"temperature.change", 0, map[string]string{"tC": "${ev.tC}"}, secret))

_, devID, _ := shelly.BTHomeAddDevice(ctx, c, shelly.BTHomeDeviceConfig{Addr: "3c:2e:f5:71:d5:2a", Key: bindKey}, 0)
st, _ := shelly.GetStatus(ctx, c)
d, _ := st.BTHomeDevice(devID) // battery, RSSI, packet id

// Or decode advertisements yourself (relayed by BLERelayScript, or from your scanner):
p, err := bthome.DecodeAdvertising(adv, "3C:2E:F5:71:D5:2A", key)

The runnable examples are Example, ExampleGen1Level and ExampleParseCoAP in example_test.go, and ExampleDecode in bthome/; 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
shelly, typed views and calls Status and Config (ParseStatus, ParseConfig, Switch, Cover, Light, Input, EM, EMData, EM1, EM1Data, PM1, Temperature, Humidity, DevicePower, Sys, WiFi, Keys, Decode); Caller, CallerFunc, MQTTDevice, BLEDevice, IsRPCError; GetStatus, GetConfig, GetDeviceInfo, GetComponents, SetConfig, SetSwitch, ToggleSwitch, GetSwitch, GetCover, MoveCover, CoverToPosition, SetLight; scripts (ListScripts, CreateScript, PutScriptCode, GetScriptCode, StartScript, StopScript, EvalScript, GetScriptStatus, SetScriptConfig, DeleteScript), schedules (CreateSchedule, UpdateSchedule, ListSchedules, DeleteSchedule, DeleteAllSchedules), webhooks (CreateWebhook, UpdateWebhook, ListWebhooks, DeleteWebhook, DeleteAllWebhooks, WebhookEvents), KVS (KVSSet, KVSGet, KVSGetMany, KVSList, KVSDelete), virtual components (AddVirtual, DeleteVirtual, SetVirtual); Gen1 Gen1Settings, Client.Settings1, Client.Gen1Actions, Gen1SetAction, Gen1ActionNames
shelly, receiving and Bluetooth (v0.3.0) HookHandler, Hook, HookURL, HookWebhook, the Gen1 action names; BTHomeAddDevice, BTHomeAddSensor, BTHomeDeleteDevice, BTHomeDeleteSensor, BTHomeStartDiscovery, BTHomeObjectInfos, BTHomeKnownObjects, BTHomeResetEncryptionCounter, Status.BTHomeDevice/BTHomeSensor, Config.BTHomeDevice/BTHomeSensor, ParseBTHomeDiscovered, ParseBTHomeDeviceEvent, ParseBLEScanResult, ParseBLEScanEvent, ScanResultData, BLEAdvert, BLERelayScript, ParseBLEMfData; Status.Smoke, Flood, Illuminance, Voltmeter
bthome Decode, DecodeAdvertising, Packet, Object, Info, Objects, Builder (Add, Button, Dimmer, Command, Text, Raw, Firmware, ServiceData, Seal), ParseAD, ServiceData16, Manufacturer, LocalName, Advertising, Guard, ParseMAC
discover MDNS over a Browser, Scan, ListenCoIoT, Probe, FromService, FromCoIoT
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. The typed views are tested against status and configuration documents in the shape devices send, and the newer calls against a recording Caller; discover against test servers on loopback and a CoIoT socket. 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, including, for v0.2.0, scripts, KVS, virtual components, schedules, webhooks, per-component configuration, Gen3 and Gen4 devices, a Pro 3EM and a timed cover: checks the simulator this module's integration tests use. The same simulator behaviours are then driven by this module's typed calls in shelly-sim's tests, so the two clients agree on them.
  • bthome-ble 3.24.0 (MIT; the BTHome parser Home Assistant uses), in python:3.12.10-slim in Docker (interop, 2026-10-12): package bthome built a packet for every object id it knows (91), for every button, dimmer and command event (14) and one encrypted packet with several objects and one with the address in the payload; bthome-ble decoded all 106 and every value, event and argument agreed with package bthome's own decoding; bthome-ble verified both bind keys. The worked examples of the format's description and RFC 3610's CCM vector are unit tests.
  • aioshelly 13.34.1 with bthome-ble 3.24.0 against a simulated Gen3 device (shelly-sim's interop, 2026-10-12): aioshelly installed its own Bluetooth relay script, the device relayed a simulated BLU door sensor's advertisement as ble.scan_result events, aioshelly parsed them and read the Shelly manufacturer data, bthome-ble decoded the BTHome data, and aioshelly added a BTHomeDevice and BTHomeSensor through call_rpc and saw the sensor's value in its status. This module's calls drive the same simulated BTHome component in shelly-sim's tests.
  • The webhook receiver ran against shelly-sim's devices calling their Gen2+ webhooks (URL tokens replaced by the simulator) and Gen1 action and report URLs; no independent device calls webhooks, so that is our own reading of the documents on both ends.
  • shelly-sim's tests also run this module's MQTT type against simulated devices connected to a real broker (mochi-mqtt v2.7.9, embedded), and discover.MDNS against the devices' DNS-SD records announced over real multicast by mdns (shelly-sim's interop, 2026-10-11).
  • Not yet, needing hardware: a real device on a network (each generation), BLE RPC against a device, CoIoT multicast from a device, MQTT with real devices on a broker, a script actually run by a device's script engine (including BLERelayScript), a real Shelly BLU sensor's advertisements, webhooks called by a real device.
  • Not yet, needing a vendor account: the Shelly cloud API (its server-side endpoints need an account's auth key and server name, so there is nothing to test against without one).
  • 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).
  • 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

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 (
	BLEFlagDiscoverable = 1 << 0
	BLEFlagAuth         = 1 << 1
	BLEFlagRPC          = 1 << 2 // RPC over Bluetooth is on
	BLEFlagBuzzer       = 1 << 3
	BLEFlagPairing      = 1 << 4
)

Flags of the Shelly manufacturer data.

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

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

View Source
const (
	Gen1OutputOn     = "out_on_url"
	Gen1OutputOff    = "out_off_url"
	Gen1ButtonOn     = "btn_on_url"
	Gen1ButtonOff    = "btn_off_url"
	Gen1ShortPush    = "shortpush_url"
	Gen1LongPush     = "longpush_url"
	Gen1RollerOpen   = "roller_open_url"
	Gen1RollerClose  = "roller_close_url"
	Gen1RollerStop   = "roller_stop_url"
	Gen1SensorReport = "report_url"
)

Gen1 action names for the common Gen1 events, for Gen1SetAction.

View Source
const BLEScanResultEvent = "ble.scan_result"

BLEScanResultEvent is the event name a relay script emits for the advertisements it hears; BLERelayScript and the Home Assistant script use it.

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 DefaultScriptChunk = 1024

DefaultScriptChunk is how many octets of code ScriptPutCode sends per request when no size is given.

View Source
const ShellyCompanyID = 0x0BA9

ShellyCompanyID is the Bluetooth company identifier in Shelly devices' manufacturer data.

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 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 BLERelayScript added in v0.3.0

func BLERelayScript(active bool) string

BLERelayScript returns the code of a script that passes every advertisement the device hears to the application as a version 2 "ble.scan_result" event (on the WebSocket channel, MQTT or the outbound WebSocket), batching up to 16 per event. active asks for scan responses too (active scanning uses more battery on the senders). Install it with CreateScript, PutScriptCode, SetScriptConfig (enable) and StartScript; Bluetooth must be on (BLE.SetConfig).

func BTHomeAddDevice added in v0.3.0

func BTHomeAddDevice(ctx context.Context, c Caller, cfg BTHomeDeviceConfig, id int) (string, int, error)

BTHomeAddDevice adds a BTHomeDevice for the sensor at cfg.Addr (BTHome.AddDevice). id 0 lets the device choose (200 to 299). It returns the new component's key and id.

func BTHomeAddSensor added in v0.3.0

func BTHomeAddSensor(ctx context.Context, c Caller, cfg BTHomeSensorConfig, id int) (string, int, error)

BTHomeAddSensor adds a BTHomeSensor for one object of a device already added (BTHome.AddSensor). id 0 lets the device choose.

func BTHomeDeleteDevice added in v0.3.0

func BTHomeDeleteDevice(ctx context.Context, c Caller, id int) error

BTHomeDeleteDevice removes bthomedevice:id (BTHome.DeleteDevice).

func BTHomeDeleteSensor added in v0.3.0

func BTHomeDeleteSensor(ctx context.Context, c Caller, id int) error

BTHomeDeleteSensor removes bthomesensor:id (BTHome.DeleteSensor).

func BTHomeResetEncryptionCounter added in v0.3.0

func BTHomeResetEncryptionCounter(ctx context.Context, c Caller) error

BTHomeResetEncryptionCounter resets the device's counter for encrypted BTHome it sends (BTHome.ResetEncryptionCounter); change the keys too.

func BTHomeStartDiscovery added in v0.3.0

func BTHomeStartDiscovery(ctx context.Context, c Caller, seconds int) error

BTHomeStartDiscovery starts an active scan for BTHome devices (BTHome.StartDeviceDiscovery); seconds 0 keeps the device's default. Found devices come as "device_discovered" events of component "bthome" (ParseBTHomeDiscovered), and "discovery_done" ends the scan.

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 CoverToPosition added in v0.2.0

func CoverToPosition(ctx context.Context, c Caller, id int, pos float64) error

CoverToPosition moves cover id to pos percent open (Cover.GoToPosition).

func CreateSchedule added in v0.2.0

func CreateSchedule(ctx context.Context, c Caller, j ScheduleJob) (id, rev int, err error)

CreateSchedule adds a job (Schedule.Create) and returns its id and the schedules' new revision.

func CreateScript added in v0.2.0

func CreateScript(ctx context.Context, c Caller, name string) (int, error)

CreateScript makes an empty script named name (Script.Create).

func CreateWebhook added in v0.2.0

func CreateWebhook(ctx context.Context, c Caller, h Webhook) (id, rev int, err error)

CreateWebhook adds a webhook (Webhook.Create).

func DeleteAllSchedules added in v0.2.0

func DeleteAllSchedules(ctx context.Context, c Caller) (rev int, err error)

DeleteAllSchedules removes every job (Schedule.DeleteAll).

func DeleteAllWebhooks added in v0.2.0

func DeleteAllWebhooks(ctx context.Context, c Caller) (rev int, err error)

DeleteAllWebhooks removes every webhook (Webhook.DeleteAll).

func DeleteSchedule added in v0.2.0

func DeleteSchedule(ctx context.Context, c Caller, id int) (rev int, err error)

DeleteSchedule removes job id (Schedule.Delete).

func DeleteScript added in v0.2.0

func DeleteScript(ctx context.Context, c Caller, id int) error

DeleteScript removes script id (Script.Delete).

func DeleteVirtual added in v0.2.0

func DeleteVirtual(ctx context.Context, c Caller, key string) error

DeleteVirtual removes a dynamic component by key ("number:200").

func DeleteWebhook added in v0.2.0

func DeleteWebhook(ctx context.Context, c Caller, id int) (rev int, err error)

DeleteWebhook removes webhook id (Webhook.Delete).

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 EvalScript added in v0.2.0

func EvalScript(ctx context.Context, c Caller, id int, code string) (string, error)

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

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 Gen1SetAction added in v0.2.0

func Gen1SetAction(name string, index int, enabled bool, urls ...string) string

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

func Gen1Settings(section string, n int, values url.Values) string

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 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 GetScriptCode added in v0.2.0

func GetScriptCode(ctx context.Context, c Caller, id int) (string, error)

GetScriptCode reads script id's code whole, page by page (Script.GetCode with offset).

func HookURL added in v0.3.0

func HookURL(base, device, event string, fields map[string]string, token string) string

HookURL builds a URL for a device to call: base, then the device and the event as path segments, then fields as query parameters. Values may hold Gen2+ URL tokens (such as "${ev.tC}"); the token characters are kept as they are so that the device can replace them. token, when not empty, is added as the "token" parameter for HookHandler.Token.

HookURL("http://192.168.1.10:8080/hooks", "shellyplus1-a8032ab1e001", "switch.on",
	map[string]string{"apower": `${status["switch:0"].apower}`}, "s3cret")

func IsRPCError added in v0.2.0

func IsRPCError(err error, code int) bool

IsRPCError reports whether err carries a device error with code.

func KVSDelete added in v0.2.0

func KVSDelete(ctx context.Context, c Caller, key, etag string) (rev int, err error)

KVSDelete removes key (KVS.Delete); with etag set only if it still matches.

func KVSList added in v0.2.0

func KVSList(ctx context.Context, c Caller, match string) (map[string]string, int, error)

KVSList lists the keys that match (KVS.List) with their etags.

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

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; 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

func MoveCover(ctx context.Context, c Caller, id int, move string, duration float64) error

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

func PutScriptCode(ctx context.Context, c Caller, id int, code string, chunk int) error

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 SHA256Hex

func SHA256Hex(s string) string

SHA256Hex is the hexadecimal SHA-256 of s.

func ScanResultData added in v0.3.0

func ScanResultData(adverts []BLEAdvert) json.RawMessage

ScanResultData builds the data of a version 2 "ble.scan_result" event, for simulators and tests.

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

func SetLight(ctx context.Context, c Caller, typ string, id int, s LightSet) error

SetLight sets a light-like component (typ light, rgb, rgbw or cct) with <Type>.Set.

func SetScriptConfig added in v0.2.0

func SetScriptConfig(ctx context.Context, c Caller, id int, name *string, enable *bool) error

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

func SetVirtual(ctx context.Context, c Caller, key string, value any) error

SetVirtual sets a dynamic component's value (<Type>.Set with id and value), key as "boolean:200".

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 StartScript added in v0.2.0

func StartScript(ctx context.Context, c Caller, id int) (wasRunning bool, err error)

StartScript runs script id (Script.Start); wasRunning says whether it already ran.

func StopScript added in v0.2.0

func StopScript(ctx context.Context, c Caller, id int) (wasRunning bool, err error)

StopScript stops script id (Script.Stop).

func ToggleSwitch added in v0.2.0

func ToggleSwitch(ctx context.Context, c Caller, id int) (wasOn bool, err error)

ToggleSwitch flips switch id (Switch.Toggle).

func UpdateSchedule added in v0.2.0

func UpdateSchedule(ctx context.Context, c Caller, j ScheduleJob) (rev int, err error)

UpdateSchedule replaces job j.ID (Schedule.Update).

func UpdateWebhook added in v0.2.0

func UpdateWebhook(ctx context.Context, c Caller, h Webhook) (rev int, err error)

UpdateWebhook replaces webhook h.ID (Webhook.Update).

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 WebhookEvents added in v0.2.0

func WebhookEvents(ctx context.Context, c Caller) ([]string, error)

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

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 AlarmStatus added in v0.3.0

type AlarmStatus struct {
	ID     int      `json:"id"`
	Alarm  bool     `json:"alarm"`
	Mute   bool     `json:"mute"`
	Errors []string `json:"errors,omitempty"`
}

AlarmStatus is a smoke or flood component's status: the alarm and whether it was muted.

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 BLEAdvert added in v0.3.0

type BLEAdvert struct {
	Addr string // the sender's address, upper case with colons
	RSSI int
	Data []byte // the advertising data, then the scan response
}

BLEAdvert is one advertisement a device relayed.

func ParseBLEScanEvent added in v0.3.0

func ParseBLEScanEvent(e Event) ([]BLEAdvert, bool, error)

ParseBLEScanEvent reads the advertisements of a "ble.scan_result" event (an Event from Events, raised by a script component); ok is false for other events.

func ParseBLEScanResult added in v0.3.0

func ParseBLEScanResult(data json.RawMessage) ([]BLEAdvert, error)

ParseBLEScanResult reads the data of a "ble.scan_result" event: version 1 is one advertisement [1, addr, rssi, adv, scan response] and version 2 a list [2, [[addr, rssi, adv, scan response], ...]], with the data in base64.

func (BLEAdvert) BTHome added in v0.3.0

func (a BLEAdvert) BTHome(key []byte) (*bthome.Packet, error)

BTHome decodes the advertisement's BTHome service data (key is the sender's bind key, or nil).

func (BLEAdvert) Shelly added in v0.3.0

func (a BLEAdvert) Shelly() (BLEMfData, bool)

Shelly reads the Shelly manufacturer data of the advertisement, if any.

type BLEDevice added in v0.2.0

type BLEDevice struct {
	G   GATT
	Src string
	// contains filtered or unexported fields
}

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.

func (*BLEDevice) RPC added in v0.2.0

func (d *BLEDevice) RPC(ctx context.Context, method string, params map[string]any) (json.RawMessage, error)

RPC calls method on the device over Bluetooth, one request at a time.

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 BLEMfData added in v0.3.0

type BLEMfData struct {
	Flags   int    `json:"flags"`
	ModelID int    `json:"model_id"`
	MAC     string `json:"mac"`
}

BLEMfData is the Shelly manufacturer data of an advertisement: flags, the device's Wi-Fi MAC and a model id.

func ParseBLEMfData added in v0.3.0

func ParseBLEMfData(d []byte) (BLEMfData, bool)

ParseBLEMfData reads Shelly manufacturer data (after the company id): blocks of a type byte and a fixed size (flags 2 bytes, MAC 6 bytes sent last byte first, model id 2 bytes). It stops at a block type it does not know.

type BTHomeDeviceConfig added in v0.3.0

type BTHomeDeviceConfig struct {
	ID   int            `json:"id,omitempty"`
	Name *string        `json:"name"`
	Addr string         `json:"addr"`
	Key  string         `json:"key,omitempty"`
	Meta map[string]any `json:"meta,omitempty"`
}

BTHomeDeviceConfig is a BTHomeDevice's configuration. Key (the sensor's AES key, 32 hexadecimal digits) can be set but is never read back.

type BTHomeDeviceEvent added in v0.3.0

type BTHomeDeviceEvent struct {
	Component string                          `json:"component"`
	ID        int                             `json:"id"`
	Event     string                          `json:"event"`
	Idx       int                             `json:"idx"`
	Channel   int                             `json:"channel"`
	Sensors   map[string][]BTHomeSensorStatus `json:"sensors"`
	TS        float64                         `json:"ts"`
}

BTHomeDeviceEvent is a button or dimmer event of a BTHomeDevice ("single_push", "double_push", "long_push", "rotate_left", ...): which object occurrence sent it, the remote's channel (-1 when it has none) and the device's sensor statuses by object id.

func ParseBTHomeDeviceEvent added in v0.3.0

func ParseBTHomeDeviceEvent(e Event) (BTHomeDeviceEvent, bool)

ParseBTHomeDeviceEvent reads an event of a bthomedevice component.

type BTHomeDeviceStatus added in v0.3.0

type BTHomeDeviceStatus struct {
	ID          int      `json:"id"`
	RSSI        *float64 `json:"rssi"`
	Battery     *float64 `json:"battery"`
	PacketID    *float64 `json:"packet_id"`
	LastUpdated float64  `json:"last_updated_ts"`
	Key         *bool    `json:"key,omitempty"`
	Paired      *bool    `json:"paired,omitempty"`
	RPC         *bool    `json:"rpc,omitempty"`
	FWVer       string   `json:"fw_ver,omitempty"`
	Errors      []string `json:"errors,omitempty"`
}

BTHomeDeviceStatus is a BTHomeDevice's status.

type BTHomeDiscovered added in v0.3.0

type BTHomeDiscovered struct {
	Addr      string     `json:"addr"`
	LocalName string     `json:"local_name"`
	RSSI      float64    `json:"rssi"`
	Encrypted bool       `json:"encrypted"`
	Shelly    *BLEMfData `json:"shelly_mfdata,omitempty"`
}

BTHomeDiscovered is one "device_discovered" event of a discovery scan.

func ParseBTHomeDiscovered added in v0.3.0

func ParseBTHomeDiscovered(e Event) (BTHomeDiscovered, bool)

ParseBTHomeDiscovered reads a "device_discovered" event (an Event from Events, component "bthome").

type BTHomeKnownObject added in v0.3.0

type BTHomeKnownObject struct {
	ObjID     int     `json:"obj_id"`
	Idx       int     `json:"idx"`
	Component *string `json:"component"`
}

BTHomeKnownObject is an object id a BTHomeDevice has seen, with the sensor component that shows it ("" when none does).

func BTHomeKnownObjects added in v0.3.0

func BTHomeKnownObjects(ctx context.Context, c Caller, id int) ([]BTHomeKnownObject, error)

BTHomeKnownObjects lists the objects bthomedevice:id has seen (BTHomeDevice.GetKnownObjects).

type BTHomeObjectInfo added in v0.3.0

type BTHomeObjectInfo struct {
	ObjID int    `json:"obj_id"`
	Name  string `json:"obj_name"`
	Type  string `json:"type"` // "sensor", "binary_sensor", ...
	Unit  string `json:"unit,omitempty"`
}

BTHomeObjectInfo is the device's description of an object id.

func BTHomeObjectInfos added in v0.3.0

func BTHomeObjectInfos(ctx context.Context, c Caller, ids []int) ([]BTHomeObjectInfo, error)

BTHomeObjectInfos asks the device to describe object ids (BTHome.GetObjectInfos), every page.

type BTHomeSensorConfig added in v0.3.0

type BTHomeSensorConfig struct {
	ID    int            `json:"id,omitempty"`
	Name  *string        `json:"name"`
	Addr  string         `json:"addr"`
	ObjID int            `json:"obj_id"`
	Idx   int            `json:"idx"`
	Meta  map[string]any `json:"meta,omitempty"`
}

BTHomeSensorConfig is a BTHomeSensor's configuration: which object id and which occurrence (Idx, from 0) of the device's packets it shows.

type BTHomeSensorStatus added in v0.3.0

type BTHomeSensorStatus struct {
	ID          int     `json:"id"`
	Value       any     `json:"value"`
	LastUpdated float64 `json:"last_updated_ts"`
}

BTHomeSensorStatus is a BTHomeSensor's status: the latest value (a number, a string or a bool) and when it came.

func (BTHomeSensorStatus) Float added in v0.3.0

func (s BTHomeSensorStatus) Float() (float64, bool)

Float returns the value as a number (a bool as 0 or 1).

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.

func (CallerFunc) RPC added in v0.2.0

func (f CallerFunc) RPC(ctx context.Context, method string, params map[string]any) (json.RawMessage, error)

RPC calls f.

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) Gen1Actions added in v0.2.0

func (c *Client) Gen1Actions(ctx context.Context) (map[string][]Gen1Action, error)

Gen1Actions reads GET /settings/actions: the slots of each action by its name.

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

func GetComponents(ctx context.Context, c Caller, dynamicOnly bool) ([]Component, int, error)

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 GetConfig added in v0.2.0

func GetConfig(ctx context.Context, c Caller) (Config, error)

GetConfig reads the whole configuration (Shelly.GetConfig).

func ParseConfig added in v0.2.0

func ParseConfig(b []byte) (Config, error)

ParseConfig reads a Shelly.GetConfig result.

func (Config) BTHomeDevice added in v0.3.0

func (c Config) BTHomeDevice(id int) (v BTHomeDeviceConfig, ok bool)

BTHomeDevice returns the configuration of bthomedevice:id.

func (Config) BTHomeSensor added in v0.3.0

func (c Config) BTHomeSensor(id int) (v BTHomeSensorConfig, ok bool)

BTHomeSensor returns the configuration of bthomesensor:id.

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) Decode added in v0.2.0

func (c Config) Decode(key string, v any) bool

Decode reads one component's configuration into v.

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) Keys added in v0.2.0

func (c Config) Keys(typ string) []string

Keys lists the keys of one component type by id.

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

func (c Config) Name() string

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) Sys added in v0.2.0

func (c Config) Sys() (v SysConfig, ok bool)

Sys reads sys'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.

func GetCover added in v0.2.0

func GetCover(ctx context.Context, c Caller, id int) (CoverStatus, error)

GetCover reads cover id's status (Cover.GetStatus).

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 EM1Status added in v0.2.0

type EM1Status struct {
	ID int `json:"id"`
	EMPhase
	Errors []string `json:"errors,omitempty"`
}

EM1Status is a single-phase energy meter channel's status (em1).

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

func (e *EMStatus) UnmarshalJSON(b []byte) error

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.

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

type Gen1ActionURL struct {
	URL string `json:"url"`
	Int string `json:"int,omitempty"`
}

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 Hook added in v0.3.0

type Hook struct {
	Device string     // the device named in the path, or the id a Gen1 sensor sent
	Event  string     // the event named in the path, or the "event" parameter
	Fields url.Values // the other query (and form) parameters
	Remote netip.Addr // the address the call came from
	Method string     // the HTTP method (devices send GET)
	Path   string     // the request path
	Time   time.Time  // when it was received
}

Hook is one call a device made to a webhook or action URL.

func (Hook) Bool added in v0.3.0

func (h Hook) Bool(name string) (bool, bool)

Bool reads field name as true or false (also 1 and 0, on and off, open and close).

func (Hook) Float added in v0.3.0

func (h Hook) Float(name string) (float64, bool)

Float reads field name as a number (a device sends "null" for a missing value; that, an empty value or a token the device did not replace give false).

type HookHandler added in v0.3.0

type HookHandler struct {
	Prefix  string                // path prefix the handler is mounted at, such as "/hooks"
	Token   string                // shared secret expected as ?token=; empty: none
	Allow   func(netip.Addr) bool // source address check; nil: any
	Handle  func(Hook)            // called for each accepted call, on the request's goroutine
	MaxBody int64                 // form bodies above this are refused (default 64 KiB)
}

HookHandler receives webhook and action URL calls. Mount it under Prefix (for example with http.Handle(Prefix+"/", h)); a call to Prefix/<device>/<event>?... becomes a Hook with Device and Event set, and a call to Prefix?... (as a Gen1 sensor's report URL) a Hook whose Device is its "id" parameter.

Devices cannot sign their calls: Token, when set, must arrive as the "token" parameter (put it in the URL with HookURL), and Allow, when set, decides which source addresses are accepted. Refused calls get 403 and are not handed on.

func (*HookHandler) ServeHTTP added in v0.3.0

func (h *HookHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler. It answers 200 with an empty body, which is all devices look at.

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 IlluminanceStatus added in v0.3.0

type IlluminanceStatus struct {
	ID           int      `json:"id"`
	Lux          *float64 `json:"lux"`
	Illumination string   `json:"illumination,omitempty"`
	Errors       []string `json:"errors,omitempty"`
}

IlluminanceStatus is an illuminance component's status: lux and the device's level (dark, twilight, bright).

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 GetDeviceInfo added in v0.2.0

func GetDeviceInfo(ctx context.Context, c Caller) (Info, error)

GetDeviceInfo reads Shelly.GetDeviceInfo (the same fields as GET /shelly).

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 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 KVSGet added in v0.2.0

func KVSGet(ctx context.Context, c Caller, key string) (KVSItem, error)

KVSGet reads key (KVS.Get).

func KVSGetMany added in v0.2.0

func KVSGetMany(ctx context.Context, c Caller, match string) ([]KVSItem, error)

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

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 MQTTDevice added in v0.2.0

type MQTTDevice struct {
	M    *MQTT
	Root string
}

MQTTDevice is one Gen2+ device over MQTT: Root is its topic prefix (the device id unless its MQTT topic_prefix was changed).

func (MQTTDevice) RPC added in v0.2.0

func (d MQTTDevice) RPC(ctx context.Context, method string, params map[string]any) (json.RawMessage, error)

RPC calls method on the device over the broker.

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 PM1Status added in v0.2.0

type PM1Status struct {
	ID     int      `json:"id"`
	Errors []string `json:"errors,omitempty"`
	Meter
}

PM1Status is a power meter's status (pm1).

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

func ListSchedules(ctx context.Context, c Caller) ([]ScheduleJob, int, error)

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.

func ListScripts added in v0.2.0

func ListScripts(ctx context.Context, c Caller) ([]Script, error)

ListScripts lists the device's scripts (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

func GetScriptStatus(ctx context.Context, c Caller, id int) (ScriptStatus, error)

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 GetStatus added in v0.2.0

func GetStatus(ctx context.Context, c Caller) (Status, error)

GetStatus reads the whole status (Shelly.GetStatus).

func ParseStatus added in v0.2.0

func ParseStatus(b []byte) (Status, error)

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) BTHomeDevice added in v0.3.0

func (s Status) BTHomeDevice(id int) (v BTHomeDeviceStatus, ok bool)

BTHomeDevice returns the status of bthomedevice:id.

func (Status) BTHomeSensor added in v0.3.0

func (s Status) BTHomeSensor(id int) (v BTHomeSensorStatus, ok bool)

BTHomeSensor returns the status of bthomesensor:id.

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

func (s Status) Decode(key string, v any) bool

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) EM added in v0.2.0

func (s Status) EM(id int) (v EMStatus, ok bool)

EM reads em:id.

func (Status) EM1 added in v0.2.0

func (s Status) EM1(id int) (v EM1Status, ok bool)

EM1 reads em1: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) Flood added in v0.3.0

func (s Status) Flood(id int) (v AlarmStatus, ok bool)

Flood reads flood: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) Illuminance added in v0.3.0

func (s Status) Illuminance(id int) (v IlluminanceStatus, ok bool)

Illuminance reads illuminance: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) Keys added in v0.2.0

func (s Status) Keys(typ string) []string

Keys lists the keys of one component type ("switch") by 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) PM1 added in v0.2.0

func (s Status) PM1(id int) (v PM1Status, ok bool)

PM1 reads pm1:id.

func (Status) Smoke added in v0.3.0

func (s Status) Smoke(id int) (v AlarmStatus, ok bool)

Smoke reads smoke:id.

func (Status) Switch added in v0.2.0

func (s Status) Switch(id int) (v SwitchStatus, ok bool)

Switch reads switch:id.

func (Status) Sys added in v0.2.0

func (s Status) Sys() (v SysStatus, ok bool)

Sys reads sys.

func (Status) Temperature added in v0.2.0

func (s Status) Temperature(id int) (v TemperatureStatus, ok bool)

Temperature reads temperature:id.

func (Status) Voltmeter added in v0.3.0

func (s Status) Voltmeter(id int) (v VoltmeterStatus, ok bool)

Voltmeter reads voltmeter: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.

func GetSwitch added in v0.2.0

func GetSwitch(ctx context.Context, c Caller, id int) (SwitchStatus, error)

GetSwitch reads switch id's status (Switch.GetStatus).

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

type Temperature struct {
	C *float64 `json:"tC"`
	F *float64 `json:"tF"`
}

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 VoltmeterStatus added in v0.3.0

type VoltmeterStatus struct {
	ID       int      `json:"id"`
	Voltage  *float64 `json:"voltage"`
	XVoltage *float64 `json:"xvoltage,omitempty"`
	Errors   []string `json:"errors,omitempty"`
}

VoltmeterStatus is a voltmeter component's status (add-on analog input); XVoltage is the value after the configured transformation.

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.

func HookWebhook added in v0.3.0

func HookWebhook(base, device, event string, cid int, fields map[string]string, token string) Webhook

HookWebhook returns a Gen2+ webhook that calls a HookHandler at base for event on component instance cid, carrying fields (values may be URL tokens) and token. Name it, add a Condition, and create it with CreateWebhook.

func ListWebhooks added in v0.2.0

func ListWebhooks(ctx context.Context, c Caller) ([]Webhook, int, error)

ListWebhooks lists the webhooks (Webhook.List).

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

type WiFiStatus added in v0.2.0

type WiFiStatus struct {
	StaIP         *string  `json:"sta_ip"`
	Status        string   `json:"status"`
	SSID          *string  `json:"ssid"`
	RSSI          *float64 `json:"rssi"`
	APClientCount *int     `json:"ap_client_count,omitempty"`
}

WiFiStatus is the wifi component's status.

Directories

Path Synopsis
Package bthome reads and writes BTHome advertisements: the open Bluetooth LE sensor format that Shelly BLU devices (buttons, door and window, motion, H&T, remote, wall switch, distance) and many DIY sensors send.
Package bthome reads and writes BTHome advertisements: the open Bluetooth LE sensor format that Shelly BLU devices (buttons, door and window, motion, H&T, remote, wall switch, distance) and many DIY sensors send.
Package discover finds Shelly devices on a network in three ways, each confirmed with the device's GET /shelly:
Package discover finds Shelly devices on a network in three ways, each confirmed with the device's GET /shelly:

Jump to

Keyboard shortcuts

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