Documentation
¶
Overview ¶
Package sim simulates Shelly devices on their local APIs for tests and demonstrations: Gen1 devices on the HTTP API (/shelly, /status, /settings, /relay, /light, /roller, basic authentication) and Gen2+ devices on JSON-RPC over HTTP (POST /rpc, digest authentication with SHA-256) and over WebSocket (ws://host/rpc, with the JSON-RPC authentication object and NotifyStatus / NotifyEvent notifications). Each device is its own HTTP server on 127.0.0.1, or on the address given to NewHost. Built from Shelly's public API documentation; not a Shelly product.
Example ¶
Start the demo devices and read one.
package main
import (
"encoding/json"
"fmt"
"net/http"
"github.com/cB-Sigma/shelly-sim/sim"
)
func main() {
s := sim.NewDemo()
defer s.Close()
resp, err := http.Get("http://" + s.Addr("98CDAC1F0006") + "/status")
if err != nil {
panic(err)
}
defer resp.Body.Close()
var st struct {
Lights []struct {
IsOn bool `json:"ison"`
Brightness int `json:"brightness"`
} `json:"lights"`
}
_ = json.NewDecoder(resp.Body).Decode(&st)
fmt.Println(st.Lights[0].IsOn, st.Lights[0].Brightness)
}
Output: true 65
Index ¶
- func Gen1MQTTID(model, mac string) string
- type BLEPeer
- type Device
- type Input1
- type Light1
- type MQTTOptions
- type Relay1
- type Roller1
- type STA
- type Service
- type Sim
- func (s *Sim) Add(d Device) string
- func (s *Sim) Addr(key string) string
- func (s *Sim) AuthFailures() int
- func (s *Sim) BLE(key string) *BLEPeer
- func (s *Sim) Calls(what string) int
- func (s *Sim) Close()
- func (s *Sim) Component(key, comp string) map[string]any
- func (s *Sim) ConnectMQTT(key, addr string, o MQTTOptions) (func(), error)
- func (s *Sim) DialOutbound(key, url string) (func(), error)
- func (s *Sim) DropWS(key string)
- func (s *Sim) Event(key, comp, event string)
- func (s *Sim) Gen1(key string) Device
- func (s *Sim) Gen1Topics(key string) map[string]string
- func (s *Sim) Hear(key, addr string, rssi int, adv []byte)
- func (s *Sim) Hooks(key string) []string
- func (s *Sim) KVS(key string) map[string]any
- func (s *Sim) Keys() []string
- func (s *Sim) MQTTCommand(key, topic, payload string) bool
- func (s *Sim) Press1(key string, input int, event string)
- func (s *Sim) RPC(key, method string, params map[string]any) (any, map[string]any)
- func (s *Sim) Reboots() int
- func (s *Sim) Report1(key string)
- func (s *Sim) Requests() []string
- func (s *Sim) RunSchedule(key string, id int) int
- func (s *Sim) ScriptCode(key string, id int) (code string, running bool)
- func (s *Sim) SendCoIoT(key, addr string) error
- func (s *Sim) Services() []Service
- func (s *Sim) SetComponent(key, comp string, fields map[string]any)
- func (s *Sim) SetGen1(key string, fn func(*Device))
- func (s *Sim) SetOffline(key string, off bool)
- func (s *Sim) SetUpdate(key, v string)
- func (s *Sim) UpdateURL(key string) string
- func (s *Sim) WSClients(key string) int
- func (s *Sim) WiFi(key string) STA
- func (s *Sim) WsConfig(key string) map[string]any
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Gen1MQTTID ¶ added in v0.2.0
Gen1MQTTID is a Gen1 device's MQTT id: shelly<kind>-<MAC>.
Types ¶
type BLEPeer ¶
type BLEPeer struct {
Writes int // characteristic writes, for tests
// contains filtered or unexported fields
}
BLEPeer is a device's Bluetooth RPC service as a GATT peer: a request's length is written to TX control (4 octets, big-endian), the request to data; the answer's length is read from RX control and the answer from data in chunks of at most 20 octets.
type Device ¶
type Device struct {
Gen int // 1 or 2 (2 covers Gen2, Gen3 and Gen4, which share the RPC API)
ID string // Gen2: device id such as shellyplus2pm-a8032ab12345
MAC string // 12 upper-case hexadecimal digits
Model string // Gen2: SNSW-102P16EU; Gen1: type such as SHSW-PM
App string // Gen2: Plus2PM
FW string
Name string
Password string // empty: no authentication
// Gen2 state: component key ("switch:0") → status object.
Components map[string]map[string]any
// Gen1 state.
Mode string // relay or roller
Relays []Relay1
Lights []Light1
Rollers []Roller1
TempC *float64
Hum *float64
// Inputs are Gen1 inputs (buttons): the last event and its count.
Inputs []Input1
// Battery is a Gen1 battery device's charge (nil: mains powered).
Battery *float64
// Gen2: Ws is the outbound WebSocket configuration (Ws.GetConfig).
Ws map[string]any
// CoverTravel is how long a Gen2+ cover takes from closed to open;
// zero moves it at once.
CoverTravel time.Duration
}
Device configures a simulated device.
type Input1 ¶
Input1 is a Gen1 input: the last event (S, L, SS …) and a count that goes up with each.
type Light1 ¶
Light1 is a Gen1 dimmer output. With Color set it is a Bulb or RGBW2 in colour mode: it dims with gain on /color/n, and a brightness on /light/n is ignored there.
type MQTTOptions ¶ added in v0.2.0
type MQTTOptions struct {
// User and Password log in to the broker when set.
User, Password string
// Prefix is a Gen1 device's topic root (shellies when empty).
Prefix string
// StatusNotify makes a Gen2+ device also publish each changed
// component's whole status on <id>/status/<component>, as its
// status_ntf setting does.
StatusNotify bool
// KeepAlive is the keep-alive sent to the broker (30 s when 0).
KeepAlive time.Duration
}
MQTTOptions configure ConnectMQTT.
type Service ¶ added in v0.2.0
type Service struct {
Instance string
Service string // _shelly._tcp or _http._tcp
Host string // host label, without .local
Port int
TXT map[string]string
IP net.IP
}
Service is a DNS-SD service a device announces on the network.
type Sim ¶
type Sim struct {
// contains filtered or unexported fields
}
Sim is a set of simulated devices.
func NewDemo ¶
func NewDemo() *Sim
NewDemo returns a simulator with a Shelly Plus 2PM as two switches, a Plus 2PM on a curtain (cover mode), a Plus Plug S, a Plus H&T, a Gen1 Shelly 1PM and a Gen1 Dimmer 2.
func NewFullDemo ¶ added in v0.2.0
func NewFullDemo() *Sim
NewFullDemo returns NewDemo's six devices and, after them, one of each later kind: a Shelly 1PM Gen3, a Plug S Gen3, a 1PM Gen4, a Pro 3EM (three-phase meter), a PM Mini Gen3 (pm1), an EM Gen3 (two em1 channels), a Plus i4 (four inputs), a Plus RGBW PM in rgbw mode and a Plus 2PM cover with a 15 s travel time. NewDemo stays as it was so tests that count its devices keep working.
func NewHost ¶
NewHost returns an empty simulator whose devices listen on host (an IP address such as 0.0.0.0, for peers in containers or on other machines). Addr then gives host:port.
func (*Sim) AuthFailures ¶
AuthFailures counts requests refused for authentication after a credential was offered.
func (*Sim) ConnectMQTT ¶ added in v0.2.0
func (s *Sim) ConnectMQTT(key, addr string, o MQTTOptions) (func(), error)
ConnectMQTT connects device key to the MQTT broker at addr (host:port) as a device in MQTT mode does. A Gen2+ device announces <id>/online, answers JSON-RPC requests on <id>/rpc to <src>/rpc and publishes its notifications on <id>/events/rpc. A Gen1 device publishes <prefix>/announce and its state topics under <prefix>/<id>/, takes relay commands on <prefix>/<id>/relay/<n>/command (and republishes its state) and answers <prefix>/command "announce". The returned function disconnects.
func (*Sim) DialOutbound ¶
DialOutbound opens the device's outbound WebSocket to url, as a sleeping Gen2+ device does when it wakes: NotifyFullStatus first, then the notifications of its changes while the channel is open. It returns a function that closes the channel (the device sleeps again).
func (*Sim) Gen1Topics ¶
Gen1Topics are the MQTT messages a Gen1 device publishes for its state (topic under shellies/<id>/ → payload).
func (*Sim) Hear ¶ added in v0.3.0
Hear makes Gen2+ device key receive a Bluetooth advertisement (the advertising data, then any scan response) from addr: running scripts that relay advertisements emit it as a "ble.scan_result" event; a BTHomeDevice added for addr decodes it, updates its status and its sensors, and raises button and dimmer events and their webhooks.
func (*Sim) Keys ¶
Keys lists the devices' keys (the Gen2 id, or the Gen1 MAC) in the order they were added.
func (*Sim) MQTTCommand ¶
MQTTCommand applies a Gen1 MQTT command (topic under shellies/<id>/) as the device does; false when the device does not take it.
func (*Sim) RPC ¶
RPC runs a Gen2+ method as the device does (for its MQTT RPC); it returns the result or the error object.
func (*Sim) Report1 ¶ added in v0.3.0
Report1 makes a Gen1 sensor call its report URL (report_url) with its readings and id, as an H&T does when it wakes: hum and temp, plus batV for a battery device.
func (*Sim) Requests ¶
Requests lists the control requests received ("<id> Switch.Set {...}", "<mac> /relay/0?turn=off").
func (*Sim) RunSchedule ¶ added in v0.2.0
RunSchedule runs schedule job id's calls now, as the device does when its time comes, and returns how many calls failed.
func (*Sim) ScriptCode ¶ added in v0.2.0
ScriptCode returns the code of a device's script, and whether it runs.
func (*Sim) SendCoIoT ¶
SendCoIoT sends the device's CoIoT status message to addr (the listener under test; real devices multicast it). The serial changes with the state.
func (*Sim) Services ¶ added in v0.2.0
Services lists what each device announces over mDNS: Gen2 and later devices _shelly._tcp (gen, app and ver in TXT) and _http._tcp with their id as the instance; Gen1 devices _http._tcp as shelly<type>-<MAC>. The port is the device's port here (80 on a real device). The module does not announce them itself, so that it keeps no mDNS dependency; hand them to an mDNS responder such as github.com/cB-Sigma/mdns (the interop module does this).
func (*Sim) SetComponent ¶
SetComponent merges fields into a Gen2 component (as a button press or a load change would) and notifies the device's channels.
func (*Sim) SetOffline ¶
SetOffline makes a device answer 503 and drop its channels.
func (*Sim) SetUpdate ¶
SetUpdate makes an update of the device (Gen2+ Shelly.Update, Gen1 /ota) install version v a moment later; with v empty an update is refused.