sim

package
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: 27 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.

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

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Gen1MQTTID added in v0.2.0

func Gen1MQTTID(model, mac string) string

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.

func (*BLEPeer) Name

func (p *BLEPeer) Name() string

Name is the device's advertised name.

func (*BLEPeer) Read

func (p *BLEPeer) Read(_ context.Context, char string) ([]byte, error)

Read reads a characteristic.

func (*BLEPeer) Write

func (p *BLEPeer) Write(_ context.Context, char string, b []byte) error

Write writes a characteristic.

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

type Input1 struct {
	Event string
	Cnt   int
}

Input1 is a Gen1 input: the last event (S, L, SS …) and a count that goes up with each.

type Light1

type Light1 struct {
	On               bool
	Brightness       int
	Color            bool
	Red, Green, Blue int
	Gain             int
}

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 Relay1

type Relay1 struct {
	On      bool
	Power   float64 // W
	TotalWm float64 // watt-minutes, as Gen1 counts
}

Relay1 is a Gen1 relay output with its meter.

type Roller1

type Roller1 struct {
	State string // open, close or stop (the direction of travel)
	Pos   int
}

Roller1 is a Gen1 roller (cover) output.

type STA

type STA struct {
	SSID, Password string
	Enabled        bool
}

STA is the Wi-Fi a device was told to join.

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 New

func New() *Sim

New returns an empty simulator whose devices listen on 127.0.0.1.

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

func NewHost(host string) *Sim

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

func (s *Sim) Add(d Device) string

Add starts a device and returns its address (127.0.0.1:port).

func (*Sim) Addr

func (s *Sim) Addr(key string) string

Addr returns a device's address by Gen2 id or MAC.

func (*Sim) AuthFailures

func (s *Sim) AuthFailures() int

AuthFailures counts requests refused for authentication after a credential was offered.

func (*Sim) BLE

func (s *Sim) BLE(key string) *BLEPeer

BLE returns a device's Bluetooth peer, nil for a Gen1 device.

func (*Sim) Calls

func (s *Sim) Calls(what string) int

Calls counts requests by method (Gen2) or path (Gen1).

func (*Sim) Close

func (s *Sim) Close()

Close stops every device.

func (*Sim) Component

func (s *Sim) Component(key, comp string) map[string]any

Component returns a copy of a Gen2 component's state.

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

func (s *Sim) DialOutbound(key, url string) (func(), error)

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

func (s *Sim) DropWS(key string)

DropWS closes a device's WebSocket channels (a Wi-Fi drop).

func (*Sim) Event

func (s *Sim) Event(key, comp, event string)

Event sends a NotifyEvent for a component ("input:0", "single_push").

func (*Sim) Gen1

func (s *Sim) Gen1(key string) Device

Gen1 returns a copy of a Gen1 device's configuration and state.

func (*Sim) Gen1Topics

func (s *Sim) Gen1Topics(key string) map[string]string

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

func (s *Sim) Hear(key, addr string, rssi int, adv []byte)

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

func (s *Sim) Hooks(key string) []string

Hooks lists the URLs the device's webhooks called, in order.

func (*Sim) KVS added in v0.2.0

func (s *Sim) KVS(key string) map[string]any

KVS returns a copy of a Gen2+ device's key-value store.

func (*Sim) Keys

func (s *Sim) Keys() []string

Keys lists the devices' keys (the Gen2 id, or the Gen1 MAC) in the order they were added.

func (*Sim) MQTTCommand

func (s *Sim) MQTTCommand(key, topic, payload string) bool

MQTTCommand applies a Gen1 MQTT command (topic under shellies/<id>/) as the device does; false when the device does not take it.

func (*Sim) Press1

func (s *Sim) Press1(key string, input int, event string)

Press1 presses a Gen1 input (event S, L, SS …).

func (*Sim) RPC

func (s *Sim) RPC(key, method string, params map[string]any) (any, map[string]any)

RPC runs a Gen2+ method as the device does (for its MQTT RPC); it returns the result or the error object.

func (*Sim) Reboots

func (s *Sim) Reboots() int

Reboots counts Shelly.Reboot calls and Gen1 /reboot requests.

func (*Sim) Report1 added in v0.3.0

func (s *Sim) Report1(key string)

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

func (s *Sim) Requests() []string

Requests lists the control requests received ("<id> Switch.Set {...}", "<mac> /relay/0?turn=off").

func (*Sim) RunSchedule added in v0.2.0

func (s *Sim) RunSchedule(key string, id int) int

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

func (s *Sim) ScriptCode(key string, id int) (code string, running bool)

ScriptCode returns the code of a device's script, and whether it runs.

func (*Sim) SendCoIoT

func (s *Sim) SendCoIoT(key, addr string) error

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

func (s *Sim) Services() []Service

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

func (s *Sim) SetComponent(key, comp string, fields map[string]any)

SetComponent merges fields into a Gen2 component (as a button press or a load change would) and notifies the device's channels.

func (*Sim) SetGen1

func (s *Sim) SetGen1(key string, fn func(*Device))

SetGen1 changes a Gen1 device's state.

func (*Sim) SetOffline

func (s *Sim) SetOffline(key string, off bool)

SetOffline makes a device answer 503 and drop its channels.

func (*Sim) SetUpdate

func (s *Sim) SetUpdate(key, v string)

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.

func (*Sim) UpdateURL

func (s *Sim) UpdateURL(key string) string

UpdateURL returns the URL of the last update the device was asked for.

func (*Sim) WSClients

func (s *Sim) WSClients(key string) int

WSClients counts authenticated WebSocket channels of a device.

func (*Sim) WiFi

func (s *Sim) WiFi(key string) STA

WiFi returns the Wi-Fi a device was given (first-time setup).

func (*Sim) WsConfig

func (s *Sim) WsConfig(key string) map[string]any

WsConfig is a Gen2+ device's outbound WebSocket configuration.

Jump to

Keyboard shortcuts

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