shelly

package module
v0.1.5 Latest Latest
Warning

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

Go to latest
Published: Dec 13, 2025 License: MIT Imports: 0 Imported by: 0

README ยถ

shelly-go

Go Reference Coverage Go Report Card CI

A comprehensive, production-ready Go library for controlling Shelly smart home devices across all generations (Gen1, Gen2, Gen3, Gen4) and all communication protocols (HTTP, WebSocket, MQTT, CoAP/CoIoT).

Features

  • ๐ŸŽฏ Complete Device Coverage - Support for Gen1, Gen2 (Plus), Gen3, Gen4, Pro, BLU, and Wave devices
  • ๐Ÿ”Œ Multiple Protocols - HTTP, WebSocket, MQTT, CoAP/CoIoT, Matter (upcoming)
  • โ˜๏ธ Cloud API Integration - First Go library with full Cloud Control API support
  • ๐Ÿ” Auto-Discovery - mDNS, BLE, and CoIoT device discovery
  • ๐Ÿ“Š Real-Time Events - WebSocket and notification support for live device updates
  • ๐ŸŽจ Extensible Architecture - Easy to add new devices and components
  • ๐Ÿงช Thoroughly Tested - โ‰ฅ90% test coverage (non-hw) with comprehensive unit and integration tests
  • ๐Ÿ“š Well Documented - Complete godoc documentation with runnable examples
  • โšก Modern Go - Built for Go 1.25.5+ with latest features

Installation

go get github.com/tj-smith47/shelly-go

Requires Go 1.25.5 or later.

Quick Start

Gen2/Gen3/Gen4 Devices (RPC-based)
package main

import (
    "context"
    "fmt"
    "log"

    "github.com/tj-smith47/shelly-go/gen2"
    "github.com/tj-smith47/shelly-go/gen2/components"
)

func main() {
    // Create a client for your Shelly device
    client := gen2.NewClient("http://192.168.1.100")

    // Control a switch
    sw := components.NewSwitch(client, 0)
    err := sw.Set(context.Background(), true)
    if err != nil {
        log.Fatal(err)
    }

    // Get switch status
    status, err := sw.GetStatus(context.Background())
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Switch is %s\n", status.Output)
}
Gen1 Devices (REST-based)
package main

import (
    "context"
    "log"

    "github.com/tj-smith47/shelly-go/gen1"
    "github.com/tj-smith47/shelly-go/gen1/components"
)

func main() {
    client := gen1.NewClient("http://192.168.1.101")

    relay := components.NewRelay(client, 0)
    err := relay.Set(context.Background(), true)
    if err != nil {
        log.Fatal(err)
    }
}
Device Discovery
package main

import (
    "context"
    "fmt"
    "log"
    "time"

    "github.com/tj-smith47/shelly-go/discovery"
)

func main() {
    scanner := discovery.NewScanner()

    ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
    defer cancel()

    devices, err := scanner.Scan(ctx)
    if err != nil {
        log.Fatal(err)
    }

    for _, device := range devices {
        fmt.Printf("Found: %s at %s (Gen%d)\n", device.Name, device.Address, device.Generation)
    }
}
Cloud API
package main

import (
    "context"
    "log"

    "github.com/tj-smith47/shelly-go/cloud"
)

func main() {
    // Authenticate with Shelly Cloud
    client := cloud.NewClient()
    err := client.Authenticate(context.Background(), "username", "password")
    if err != nil {
        log.Fatal(err)
    }

    // List all devices
    devices, err := client.ListDevices(context.Background())
    if err != nil {
        log.Fatal(err)
    }

    // Control a device via cloud
    err = client.SetSwitch(context.Background(), devices[0].ID, 0, true)
    if err != nil {
        log.Fatal(err)
    }
}

Supported Devices

This library supports all Shelly devices across all generations:

  • โœ… Gen1 - Shelly 1/1PM/2.5/4Pro/Plug/Bulb/RGBW2/Dimmer/EM/3EM/H&T/Smoke/Flood/Door/Window/Motion/etc.
  • โœ… Gen2 (Plus) - Shelly Plus 1/1PM/2PM/i4/Plug S/H&T/Smoke/Wall Dimmer/RGBW PM/UNI/etc.
  • โœ… Pro - Shelly Pro 1/1PM/2/2PM/3/3EM/4PM/Dimmer/Dual Cover/EM-50/etc.
  • โœ… Gen3 - Shelly 1/1PM/2PM/1L/2L/PM Mini/Plug S/i4/H&T/EM/Dimmer/Wall Display/etc.
  • โœ… Gen4 - Shelly 1/1PM (and future Gen4 devices)
  • โœ… BLU (Bluetooth) - Shelly BLU Button/Door/Motion/H&T/TRV/Gateway/etc.
  • โœ… Wave (Z-Wave) - Shelly Wave 1/1PM/2PM/Plug/Shutter/etc.

See DEVICES.md for complete device matrix.

Architecture

The library is organized into focused packages:

shelly-go/
โ”œโ”€โ”€ types/          Core interfaces and types
โ”œโ”€โ”€ transport/      Communication layer (HTTP, WebSocket, MQTT, CoAP)
โ”œโ”€โ”€ rpc/            RPC framework for Gen2+ devices
โ”œโ”€โ”€ gen1/           Gen1 device support
โ”œโ”€โ”€ gen2/           Gen2+ device support (Plus, Pro, Gen3, Gen4)
โ”œโ”€โ”€ cloud/          Shelly Cloud API
โ”œโ”€โ”€ discovery/      Device discovery (mDNS, BLE, CoIoT)
โ”œโ”€โ”€ events/         Event bus and notification system
โ”œโ”€โ”€ helpers/        Convenience utilities (batch, groups, scenes)
โ”œโ”€โ”€ profiles/       Device profiles and capabilities
โ””โ”€โ”€ examples/       Runnable examples

See ARCHITECTURE.md for design decisions and patterns.

Key Concepts

Transports

All communication goes through transport implementations:

import "github.com/tj-smith47/shelly-go/transport"

// HTTP transport (most common)
http := transport.NewHTTP("http://192.168.1.100",
    transport.WithTimeout(30*time.Second),
    transport.WithAuth("admin", "password"))

// WebSocket transport (real-time)
ws := transport.NewWebSocket("ws://192.168.1.100/rpc",
    transport.WithReconnect(true))

// MQTT transport
mqtt := transport.NewMQTT("mqtt://192.168.1.10:1883",
    transport.WithMQTTTopic("shellies/shellyplus1-abc123"))
Components

Devices are composed of components (switches, covers, lights, sensors, etc.):

// Each component has GetConfig, SetConfig, and GetStatus
config, err := sw.GetConfig(ctx)
config.Name = "Living Room Light"
err = sw.SetConfig(ctx, config)

status, err := sw.GetStatus(ctx)
fmt.Printf("Power: %.2fW\n", status.APower)
Events

Subscribe to real-time device events:

import "github.com/tj-smith47/shelly-go/events"

bus := events.NewBus()

// Subscribe to switch events
bus.Subscribe(events.FilterByComponent("switch:0"), func(e events.Event) {
    fmt.Printf("Switch changed: %+v\n", e)
})

// Connect device to event bus
device.AttachEventBus(bus)
Batch Operations

Control multiple devices at once:

import "github.com/tj-smith47/shelly-go/helpers"

// Turn off all switches
err := helpers.BatchSet(ctx, devices, false)

// Create a scene
scene := helpers.NewScene("Movie Time")
scene.Add(livingRoomLight, helpers.WithBrightness(20))
scene.Add(tvBacklight, helpers.WithRGB(255, 0, 0))
scene.Activate(ctx)

Documentation

Examples

See the examples/ directory for complete, runnable examples:

  • Basic Control - Switch, cover, and light control
  • Discovery - mDNS, BLE, and CoIoT discovery
  • Cloud API - Authentication and remote control
  • Real-Time Events - WebSocket event handling
  • Energy Monitoring - Historical energy data retrieval and analysis
  • Batch Operations - Controlling multiple devices
  • Scenes - Creating and managing scenes
  • Provisioning - WiFi and BLE device setup
  • Firmware Updates - OTA update management

Testing

Run tests:

# Unit tests
go test ./...

# With coverage
go test -cover ./...

# Integration tests (requires devices)
go test -tags=integration ./...

Contributing

Contributions are welcome! Please read CONTRIBUTING.md for guidelines.

Comparison with Other Libraries

Feature shelly-go jcodybaker/go-shelly jojomi/go-shelly
Gen1 Support โœ… Full โŒ โœ… Limited
Gen2+ Support โœ… Full โœ… โŒ
Gen3/Gen4 โœ… โœ… โŒ
Cloud API โœ… โŒ โŒ
Discovery โœ… All protocols โŒ โŒ
WebSocket โœ… Bidirectional โœ… โŒ
MQTT โœ… โŒ โŒ
CoAP/CoIoT โœ… โŒ โŒ
Test Coverage โ‰ฅ90% ~60% <20%
Documentation Complete Good Minimal

Roadmap

  • Gen1 support (HTTP, CoIoT)
  • Gen2/Gen3/Gen4 support (RPC)
  • Cloud API integration
  • Device discovery (mDNS, CoIoT, WiFi AP, BLE)
  • Event system
  • WiFi provisioning (platform-specific: Linux/macOS/Windows)
  • BLE discovery (TinyGo implementation for Linux/macOS; see examples/discovery/ble)
  • BLE provisioning (TinyGo implementation for Linux/macOS; see examples/provisioning/ble)
  • Backup/restore functionality
  • Firmware update management
  • Batch operations and device groups
  • Scene management
  • Matter protocol support (RPC control of Matter-enabled Shelly devices)
  • Zigbee support (RPC control of Zigbee-enabled Gen4 devices)
  • Z-Wave support (Wave device profiles; IP-enabled Wave devices use Gen2 RPC)
  • LoRa add-on support (full RPC implementation)
  • Integrator API (B2B fleet management, analytics, provisioning)

Known Limitations

Bluetooth (BLE)

BLE discovery and provisioning are fully implemented using the TinyGo bluetooth library:

  • Linux: Works with BlueZ (requires bluez package)
  • macOS: Works with CoreBluetooth
  • Windows: Not supported (returns ErrBLETransmitterNotSupported)

Requirements:

  • Bluetooth adapter must be available and enabled
  • Appropriate OS permissions (may need root/sudo on Linux)
  • No other application should be blocking the bluetooth adapter

Features:

  • Discover Shelly devices in BLE provisioning mode (Gen2+)
  • Parse BTHome sensor data from Shelly BLU devices (buttons, sensors, etc.)
  • Connect to devices and send RPC commands over BLE GATT
  • Provision WiFi credentials to unprovisioned devices

See the examples at examples/discovery/ble and examples/provisioning/ble.

Integration Tests

Integration tests exist but require real Shelly devices at specific IP addresses. They are skipped in CI environments (SHELLY_CI=1).

License

MIT License - see LICENSE for details.

Credits

Generated by Claude Opus 4.5 over many iterations ๐Ÿค–

Shellyยฎ is a registered trademark of Allterco Robotics. This project is not affiliated with or endorsed by Allterco Robotics.

Support

Acknowledgments

Thanks to the Shelly community and other library authors for inspiration and testing.

Documentation ยถ

Overview ยถ

Package shelly provides a comprehensive Go library for controlling Shelly smart home devices across all device generations (Gen1, Gen2, Gen3, Gen4) and communication protocols (HTTP, WebSocket, MQTT, CoAP/CoIoT).

Overview ยถ

This library provides a unified interface for interacting with Shelly devices, whether you're controlling them locally via HTTP/WebSocket, discovering them on your network, or managing them through the Shelly Cloud API.

Quick Start ยถ

For Gen2/Gen3/Gen4 devices (RPC-based):

client := gen2.NewClient("http://192.168.1.100")
sw := components.NewSwitch(client, 0)
err := sw.Set(context.Background(), true)

For Gen1 devices (REST-based):

client := gen1.NewClient("http://192.168.1.101")
relay := components.NewRelay(client, 0)
err := relay.Set(context.Background(), true)

Package Organization ยถ

The library is organized into several focused packages:

  • types: Core interfaces and type definitions
  • transport: Communication layer implementations (HTTP, WebSocket, MQTT, CoAP)
  • rpc: RPC framework for Gen2+ devices
  • gen1: Support for Gen1 devices
  • gen2: Support for Gen2+ devices (Plus, Pro, Gen3, Gen4)
  • cloud: Shelly Cloud API integration
  • discovery: Device discovery via mDNS, BLE, and CoIoT
  • events: Event bus and real-time notifications
  • helpers: Convenience utilities for batch operations, groups, and scenes
  • profiles: Device profiles and capability detection

Device Generations ยถ

Shelly devices come in multiple generations with different protocols:

Gen1: REST API over HTTP, CoIoT for real-time updates

  • Examples: Shelly 1, 1PM, 2.5, Plug, Bulb, RGBW2, Dimmer, EM, H&T

Gen2 (Plus): RPC over HTTP/WebSocket, MQTT support

  • Examples: Shelly Plus 1, 1PM, 2PM, i4, Plug S, H&T

Pro: Enhanced Gen2 with Ethernet, ModBus, additional I/O

  • Examples: Shelly Pro 1, 1PM, 2PM, 3, 3EM, 4PM, Dimmer

Gen3: Latest generation with improved hardware and features

  • Examples: Shelly 1 Gen3, 1PM Gen3, 2PM Gen3, Wall Display

Gen4: Future-ready devices (as released by Allterco)

  • Examples: Shelly 1 Gen4, 1PM Gen4

BLU: Bluetooth Low Energy devices

  • Examples: BLU Button, Door/Window, Motion, H&T, TRV

Wave: Z-Wave devices

  • Examples: Wave 1, 1PM, 2PM, Plug, Shutter

Components ยถ

Devices are composed of components that provide specific functionality:

  • Switch: On/off control with power monitoring
  • Cover: Roller shutter/blind control with position
  • Light: Dimming and color control
  • Input: Button and sensor inputs
  • PM/EM: Power and energy monitoring
  • WiFi/Ethernet/BLE: Network configuration
  • Cloud/MQTT/Webhook: Integration services
  • Script: JavaScript automation
  • Temperature/Humidity/Smoke: Environmental sensors
  • Thermostat: Climate control

Each component implements standard methods:

  • GetConfig: Retrieve component configuration
  • SetConfig: Update component configuration
  • GetStatus: Get current component status

Transports ยถ

Communication with devices uses pluggable transports:

// HTTP transport (most common)
http := transport.NewHTTP("http://192.168.1.100",
    transport.WithTimeout(30*time.Second),
    transport.WithAuth("admin", "password"))

// WebSocket transport for real-time communication
ws := transport.NewWebSocket("ws://192.168.1.100/rpc")

// MQTT transport
mqtt := transport.NewMQTT("mqtt://broker:1883",
    transport.WithMQTTTopic("shellies/device-id"))

Discovery ยถ

Devices can be discovered automatically using multiple methods:

scanner := discovery.NewScanner()
devices, err := scanner.Scan(ctx)
for _, device := range devices {
    fmt.Printf("Found %s at %s\n", device.Name, device.Address)
}

Cloud API ยถ

Control devices remotely via Shelly Cloud:

client := cloud.NewClient()
err := client.Authenticate(ctx, "username", "password")
devices, err := client.ListDevices(ctx)
err = client.SetSwitch(ctx, devices[0].ID, 0, true)

Events ยถ

Subscribe to real-time device events:

bus := events.NewBus()
bus.Subscribe(events.FilterByDevice(deviceID), func(e events.Event) {
    fmt.Printf("Event: %+v\n", e)
})
device.AttachEventBus(bus)

Error Handling ยถ

The library defines standard error types:

  • ErrNotFound: Resource not found
  • ErrAuth: Authentication failed
  • ErrTimeout: Operation timed out
  • ErrNotSupported: Feature not supported by device

All errors are wrapped with context using fmt.Errorf with %w.

Context Support ยถ

All operations accept context.Context for cancellation and timeout:

ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
status, err := sw.GetStatus(ctx)

Thread Safety ยถ

All client and device implementations are safe for concurrent use unless otherwise documented. Components share the underlying client and can be used from multiple goroutines.

Extensibility ยถ

The library is designed to be extensible for new devices and firmware features:

  • All structs include RawFields map[string]json.RawMessage for unknown fields
  • Component interface allows custom implementations
  • Transport interface supports new protocols

Testing ยถ

The library includes comprehensive testing utilities:

import "github.com/tj-smith47/shelly-go/internal/testutil"

mock := testutil.NewMockTransport()
mock.AddResponse("Shelly.GetDeviceInfo", testutil.LoadFixture("device.json"))
client := gen2.NewClient(mock)

Examples ยถ

See the examples/ directory for complete, runnable examples covering:

  • Basic device control
  • Device discovery
  • Cloud API usage
  • Real-time events
  • Batch operations
  • Scene management
  • Device provisioning
  • Firmware updates

Official Documentation ยถ

For more information about Shelly devices and protocols, see:

License ยถ

Shellyยฎ is a registered trademark of Allterco Robotics. This project is not affiliated with or endorsed by Allterco Robotics.

Directories ยถ

Path Synopsis
Package backup provides device configuration backup and restore functionality.
Package backup provides device configuration backup and restore functionality.
Package cloud provides a client for the Shelly Cloud Control API.
Package cloud provides a client for the Shelly Cloud Control API.
Package discovery provides device discovery functionality for Shelly devices.
Package discovery provides device discovery functionality for Shelly devices.
Package events provides a typed event system for Shelly device notifications.
Package events provides a typed event system for Shelly device notifications.
examples
advanced/batch_operations command
Example: batch_operations demonstrates batch operations across multiple Shelly devices.
Example: batch_operations demonstrates batch operations across multiple Shelly devices.
advanced/custom_component command
Example: custom_component demonstrates creating custom component types.
Example: custom_component demonstrates creating custom component types.
advanced/scenes command
Example: scenes demonstrates scene management for coordinated device control.
Example: scenes demonstrates scene management for coordinated device control.
basic/cover_control command
Example: cover_control demonstrates controlling a Shelly Gen2+ cover (roller shutter).
Example: cover_control demonstrates controlling a Shelly Gen2+ cover (roller shutter).
basic/light_control command
Example: light_control demonstrates controlling a Shelly Gen2+ light/dimmer.
Example: light_control demonstrates controlling a Shelly Gen2+ light/dimmer.
basic/switch_control command
Example: switch_control demonstrates controlling a Shelly Gen2+ switch.
Example: switch_control demonstrates controlling a Shelly Gen2+ switch.
cloud/auth command
Example: cloud/auth demonstrates authenticating with the Shelly Cloud API.
Example: cloud/auth demonstrates authenticating with the Shelly Cloud API.
cloud/realtime command
Example: cloud/realtime demonstrates real-time events from Shelly Cloud WebSocket.
Example: cloud/realtime demonstrates real-time events from Shelly Cloud WebSocket.
discovery/ble command
Package main demonstrates BLE discovery for Shelly devices.
Package main demonstrates BLE discovery for Shelly devices.
discovery/mdns command
Example: mdns demonstrates discovering Shelly devices on the local network via mDNS.
Example: mdns demonstrates discovering Shelly devices on the local network via mDNS.
energy command
Package main demonstrates how to retrieve and analyze historical energy data from Shelly Pro 3EM and Pro EM devices using the EMData and EM1Data components.
Package main demonstrates how to retrieve and analyze historical energy data from Shelly Pro 3EM and Pro EM devices using the EMData and EM1Data components.
provisioning/ble command
Package main demonstrates BLE provisioning for Shelly devices.
Package main demonstrates BLE provisioning for Shelly devices.
Package factory provides device creation utilities.
Package factory provides device creation utilities.
Package firmware provides OTA (Over-The-Air) firmware management for Shelly devices.
Package firmware provides OTA (Over-The-Air) firmware management for Shelly devices.
Package gen1 provides support for Shelly Gen1 devices.
Package gen1 provides support for Shelly Gen1 devices.
components
Package components provides Gen1 Shelly device components.
Package components provides Gen1 Shelly device components.
Package gen2 provides support for Gen2+ Shelly devices (Plus, Pro, Gen3, Gen4).
Package gen2 provides support for Gen2+ Shelly devices (Plus, Pro, Gen3, Gen4).
Package helpers provides convenience utilities for working with Shelly devices.
Package helpers provides convenience utilities for working with Shelly devices.
Package integrator provides a client for the Shelly Integrator API.
Package integrator provides a client for the Shelly Integrator API.
internal
testutil
Package testutil provides testing utilities for the shelly-go library.
Package testutil provides testing utilities for the shelly-go library.
testutil/integration
Package integration provides integration test utilities for testing against real Shelly devices and the Shelly Cloud API.
Package integration provides integration test utilities for testing against real Shelly devices and the Shelly Cloud API.
Package lora provides support for the Shelly LoRa Add-On.
Package lora provides support for the Shelly LoRa Add-On.
Package matter provides Matter protocol support for Shelly Gen4+ devices.
Package matter provides Matter protocol support for Shelly Gen4+ devices.
Package notifications provides a unified interface for receiving real-time events from Shelly devices across all generations and connection methods.
Package notifications provides a unified interface for receiving real-time events from Shelly devices across all generations and connection methods.
Package profiles provides device profile definitions for all Shelly devices.
Package profiles provides device profile definitions for all Shelly devices.
blu
Package blu provides device profiles for Shelly BLU Bluetooth devices.
Package blu provides device profiles for Shelly BLU Bluetooth devices.
gen1
Package gen1 provides device profiles for Shelly Gen1 devices.
Package gen1 provides device profiles for Shelly Gen1 devices.
gen2
Package gen2 provides device profiles for Shelly Gen2 Plus and Pro devices.
Package gen2 provides device profiles for Shelly Gen2 Plus and Pro devices.
gen3
Package gen3 provides device profiles for Shelly Gen3 devices.
Package gen3 provides device profiles for Shelly Gen3 devices.
gen4
Package gen4 provides device profiles for Shelly Gen4 devices.
Package gen4 provides device profiles for Shelly Gen4 devices.
wave
Package wave provides device profiles for Shelly Wave Z-Wave devices.
Package wave provides device profiles for Shelly Wave Z-Wave devices.
Package provisioning provides utilities for initial setup and configuration of Shelly devices.
Package provisioning provides utilities for initial setup and configuration of Shelly devices.
Package rpc provides a JSON-RPC 2.0 framework for Shelly device communication.
Package rpc provides a JSON-RPC 2.0 framework for Shelly device communication.
tools
discover command
Standalone Shelly device discovery tool.
Standalone Shelly device discovery tool.
Package transport provides communication layer implementations for Shelly devices.
Package transport provides communication layer implementations for Shelly devices.
Package types provides core interfaces and type definitions used throughout the shelly-go library.
Package types provides core interfaces and type definitions used throughout the shelly-go library.
Package zigbee provides support for Shelly Gen2+ Zigbee component.
Package zigbee provides support for Shelly Gen2+ Zigbee component.
Package zwave provides utilities for working with Shelly Wave Z-Wave devices.
Package zwave provides utilities for working with Shelly Wave Z-Wave devices.

Jump to

Keyboard shortcuts

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