miio

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 11, 2026 License: Apache-2.0 Imports: 26 Imported by: 0

README

miio

Clients for Xiaomi Mi Home Wi-Fi devices in pure Go: the miIO local protocol, MIoT requests, specifications from miot-spec.org and the Mi account device list; not affiliated with Xiaomi.

Go Reference test Go

It talks miIO on UDP 54321 (token-encrypted JSON-RPC, the hello handshake and discovery), sends MIoT get_properties, set_properties and action requests, fetches a model's MIoT specification, and signs in to a Mi account to list its devices with their tokens and local addresses, so tokens need not be extracted by hand. Standard library and lanbcast only, no cgo. It was written for SigmaM2M, a oneM2M platform, whose Xiaomi adapter is built on it.

Features

Feature Status
miIO packets, hello handshake, stamps, JSON-RPC with random request IDs and one retry yes
Hello discovery (broadcast to every LAN interface through lanbcast) yes
MIoT get_properties (batched by 15), set_properties, action, with per-property codes yes
MIoT specifications from miot-spec.org (newest released version per model) yes; none bundled
Mi account sign-in, homes, shared homes and device lists in every region yes
Mi account identity verification (e-mail or SMS ticket, captcha) reported as ErrCloudVerify, not completed
Mapping specifications to a device model, legacy per-model methods no; that is the caller's
Bluetooth and Zigbee sub-devices of gateways, firmware update, the Mi account's other APIs no

Choosing a Go miIO library

Compared from each project's source at the version named, on 2026-10-11. Check the projects themselves before relying on a row.

this module mberatsanli/miio (2026-09-01) vkorn/go-miio (2023-03-16) nickw444/miio-go (2019-08-25) python-miio master 9a00e08 (Python)
miIO packets, handshake, discovery yes yes yes yes yes
MIoT get/set properties, actions yes yes no no yes
MIoT specifications from miot-spec.org yes no (a written-up spec for one model) no no yes
Mi account device and token list yes yes no no through micloud
Mi account e-mail verification completed no (reported) yes no no no
Per-model helpers (vacuums, gateways, lights...) no one Roborock model Aqara gateway, sensors, vacuum Yeelight, plugs very many
Device, account and specification simulators yes, separate module no no a device simulator miio and MIoT device simulators
Interop evidence against python-miio both ways (below) none stated none stated none stated the reference
Go version, dependencies 1.22; lanbcast 1.25; cobra, x/term (CLI) dep era, no go.mod 1.12; several n/a
Licence Apache-2.0 MIT MIT MIT GPL-3.0

Pick this module when you want a small protocol layer with MIoT and the account's token list under your own device model, with simulators for your tests. Pick mberatsanli/miio when your account asks for e-mail verification and you want the library to complete it, or for its Roborock driver. Use python-miio outside Go, or when you need its many per-model integrations.

Install

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

Requires Go 1.22 or later.

Quick start

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

cloud := &miio.Cloud{Username: email, Password: password}
devs, err := cloud.Devices(ctx, []string{"i2"}) // India; miio.Regions lists all
tok, _ := hex.DecodeString(devs[0].Token)
c := &miio.Client{Addr: devs[0].LocalIP + ":54321", Token: tok, Timeout: 5 * time.Second}
info, err := c.Call(ctx, "miIO.info", nil)

// A MIoT device: read power (service 2, property 2) and switch it off.
res, err := miio.GetProperties(ctx, c, []miio.PropRef{{DID: devs[0].DID, SIID: 2, PIID: 2}})
_, err = miio.SetProperties(ctx, c, []miio.PropRef{{DID: devs[0].DID, SIID: 2, PIID: 2, Value: false}})

Example and ExampleGetProperties in example_test.go show the same (they need an account and a device, so they are not run); ExampleKeys runs. miio-sim runs them against simulated devices and a simulated account.

Documentation

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

Package What it does
miio (module root) miIO: Client (Call, DeviceID), Discover, Hello, Packet, Open, Keys. MIoT: GetProperties, SetProperties, DoAction, PropRef, PropResult, PropError; specifications: Spec, HTTPSpecs, SpecSource, URNName. Mi account: Cloud (Login, Devices), CloudDevice, Regions
interop (nested module, tests only) this client against python-miio's miio and MIoT device simulators, in a container

Changes per version are in CHANGELOG.md.

Testing

go test -race ./...
cd interop && SIGMA_MIIO_INTEROP=1 go test -v ./...   # needs Docker

Tests carry // Covers: SIG-... comments: requirement IDs of the SigmaM2M project's compliance report, with no meaning outside it. The client, MIoT, account and specification tests against the simulators are in miio-sim.

interop/ is a nested module with its own go.mod. Its tests build an image from interop/peer (python:3.12-slim with python-miio from a fixed commit, 9a00e08, of its master branch: its simulators are not in a PyPI release yet) and are skipped unless SIGMA_MIIO_INTEROP=1 is set and Docker answers.

Interop tested against
  • python-miio's device simulators (master 9a00e08, 2026-10-11, Docker Desktop on arm64; interop):
    • miiocli devtools miio-simulator with the zhimi.fan file python-miio ships: hello handshake (device ID as python-miio derives it), miIO.info, get_prop, set_power and the changed value, an unknown method refused, a wrong token unanswered, discovery by hello. Passed.
    • miiocli devtools miot-simulator with a made-up specification (interop/peer/spec.json): get_properties with codes (an unknown property refused), set_properties and the values read back, a read-only property refused, an action. Passed.
    • The first run found that the simulator answers miIO.info without a "result" member; Client.Call now returns such an answer whole, as python-miio does (TestAnswerWithoutResult).
  • python-miio's client against the simulators, in miio-sim.
  • Not yet: a real Xiaomi device, a real Mi account, the live miot-spec.org service.
  • miio-sim: simulated miIO and MIoT devices, a simulated Mi account and specification service, as a Go package and a command.
  • lanbcast: the broadcast helper discovery uses.

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. Xiaomi, Mi, Mi Home and MIoT are trademarks of their owner; the names are used only to say which devices and services this module talks to.

Documentation

Overview

Package miio speaks the local protocol of Xiaomi Mi Home Wi-Fi devices: miIO packets on UDP port 54321 with the token-derived encryption (Client, Discover), the legacy JSON-RPC methods, the MIoT property and action requests (GetProperties, SetProperties, DoAction) with the models' MIoT specifications (HTTPSpecs), and the Mi account client that lists an account's devices with their tokens (Cloud), so tokens need not be extracted by hand.

Xiaomi does not document the local protocol or the account API; this package follows public descriptions (see PROVENANCE.md). The sim package simulates devices, the account and the specification service for tests.

Example

List the account's devices with their tokens, then switch a plug on its LAN. It needs a Mi account and a device, so it is not run; github.com/cB-Sigma/miio-sim runs the same steps against a simulated account and plug.

package main

import (
	"context"
	"encoding/hex"
	"fmt"
	"time"

	"github.com/cB-Sigma/miio"
)

func main() {
	ctx := context.Background()
	cloud := &miio.Cloud{Username: "user@example.invalid", Password: "secret"}
	devs, err := cloud.Devices(ctx, []string{"i2"}) // India; miio.Regions lists all
	if err != nil || len(devs) == 0 {
		fmt.Println(devs, err)
		return
	}
	tok, _ := hex.DecodeString(devs[0].Token)
	c := &miio.Client{Addr: devs[0].LocalIP + ":54321", Token: tok, Timeout: 3 * time.Second}
	_, err = c.Call(ctx, "set_power", []any{"on"})
	fmt.Println(devs[0].Model, err)
}

Index

Examples

Constants

View Source
const DefaultSpecURL = "https://miot-spec.org/miot-spec-v2"

DefaultSpecURL is miot-spec.org's specification service.

View Source
const Port = 54321

Port is miIO's UDP port.

Variables

View Source
var (
	// ErrCloudAuth: the account refused the user name or password.
	ErrCloudAuth = errors.New("the Mi account refused the user name or password")
	// ErrCloudVerify: Xiaomi asks for a captcha or an e-mail or SMS code,
	// which a server cannot give.
	ErrCloudVerify = errors.New("the Mi account asks for a verification a server cannot give (a captcha or a code sent by e-mail or SMS)")
)

Errors of the sign-in.

View Source
var ErrNoSpec = errors.New("no MIoT specification of the model")

ErrNoSpec means no specification of the model could be found.

View Source
var ErrToken = errors.New("the device's answer does not open with the token")

ErrToken means the device's answer could not be opened with the token.

View Source
var Regions = []string{"cn", "de", "us", "ru", "tw", "sg", "in", "i2"}

Regions are the Mi account's server regions (cn has no prefix; i2 is India's).

Functions

func CheckAction

func CheckAction(raw json.RawMessage) error

CheckAction reads an action answer and returns a *PropError when its code is not 0.

func Decrypt

func Decrypt(token, ct []byte) ([]byte, error)

Decrypt reverses Encrypt.

func DefaultAPIBase

func DefaultAPIBase(region string) string

DefaultAPIBase is the Mi account's API address of a region.

func Discover

func Discover(ctx context.Context, bcast string, wait time.Duration) (map[uint32]string, error)

Discover broadcasts a hello and returns device ID → address.

func DoAction

func DoAction(ctx context.Context, c *Client, did string, siid, aiid int, in []any) error

DoAction runs an action of a service with its input values.

func EncSignature

func EncSignature(method, path string, params [][2]string, signedNonce string) string

EncSignature is the SHA-1 signature over the method, the path, the parameters in order and the signed nonce.

func Encrypt

func Encrypt(token, plain []byte) []byte

Encrypt encrypts data for a token.

func Hello

func Hello() []byte

Hello is the discovery and handshake packet.

func Keys

func Keys(token []byte) (key, iv []byte)

Keys derives the AES key and IV from a 16-byte token.

Example
package main

import (
	"encoding/hex"
	"fmt"

	"github.com/cB-Sigma/miio"
)

func main() {
	tok, _ := hex.DecodeString("00112233445566778899aabbccddeeff")
	key, iv := miio.Keys(tok)
	fmt.Println(len(key), len(iv))
}
Output:
16 16

func Packet

func Packet(token []byte, deviceID, stamp uint32, plain []byte) []byte

Packet builds a packet with encrypted data.

func RC4Decrypt

func RC4Decrypt(signedNonce, v string) ([]byte, error)

RC4Decrypt reverses RC4Encrypt.

func RC4Encrypt

func RC4Encrypt(signedNonce, v string) string

RC4Encrypt encrypts a value with a signed nonce (base64 in and out).

func SignedNonce

func SignedNonce(ssecurity, nonce string) string

SignedNonce is the per-call key: SHA-256(ssecurity ‖ nonce), base64.

func URNName

func URNName(urn string) (string, bool)

URNName is the name part of a MIoT type URN ("urn:miot-spec-v2:property:on:00000006:..." gives "on") and whether it is a standard (miot-spec-v2) one.

Types

type Action

type Action struct {
	IID  int    `json:"iid"`
	Type string `json:"type"`
	In   []int  `json:"in,omitempty"`
}

Action is one action of a service.

type Client

type Client struct {
	Addr    string // host:port
	Token   []byte
	Timeout time.Duration
	// contains filtered or unexported fields
}

Client talks to one device.

func (*Client) Call

func (c *Client) Call(ctx context.Context, method string, params any) (json.RawMessage, error)

Call sends a JSON-RPC request and returns its result, or the whole answer when it has neither "result" nor "error". Request IDs start at a random value (devices ignore an ID they answered recently, so a restarted client must not begin at 1 again); when a request is not answered, the IDs move on by 100 and it is asked once more.

func (*Client) DeviceID

func (c *Client) DeviceID() uint32

DeviceID is the ID the device gave in its last answer.

type Cloud

type Cloud struct {
	Username, Password string
	// AccountBase is https://account.xiaomi.com (tests change it).
	AccountBase string
	// APIBase gives a region's API address
	// (https://<region>.api.io.mi.com/app).
	APIBase func(region string) string
	HTTP    *http.Client
	// contains filtered or unexported fields
}

Cloud signs in to a Mi account and lists its devices.

func (*Cloud) Devices

func (c *Cloud) Devices(ctx context.Context, regions []string) ([]CloudDevice, error)

Devices signs in when needed and lists the account's devices in the regions (every region when empty), with the homes shared with it.

func (*Cloud) Login

func (c *Cloud) Login(ctx context.Context) error

Login signs in (steps 1 to 3).

type CloudDevice

type CloudDevice struct {
	DID     string `json:"did"`
	Token   string `json:"token"`
	Name    string `json:"name"`
	Model   string `json:"model"`
	LocalIP string `json:"localip"`
	MAC     string `json:"mac"`
	Online  bool   `json:"isOnline"`
	Region  string `json:"region,omitempty"`
}

CloudDevice is one device of the account.

type HTTPSpecs

type HTTPSpecs struct {
	Base string
	HTTP *http.Client
	// contains filtered or unexported fields
}

HTTPSpecs fetches specifications from a specification service.

func (*HTTPSpecs) Spec

func (s *HTTPSpecs) Spec(ctx context.Context, model string) (*Spec, error)

Spec implements SpecSource.

type Header struct {
	Length   uint16
	Unknown  uint32
	DeviceID uint32
	Stamp    uint32
	Checksum []byte
}

Header is a parsed packet header.

func Open

func Open(token, b []byte) (Header, []byte, error)

Open checks a packet's checksum and decrypts its data.

func ParseHeader

func ParseHeader(b []byte) (Header, error)

ParseHeader reads a packet's header.

type PropError

type PropError struct {
	SIID, IID int // IID is the property or action ID
	Code      int
	Action    bool
}

PropError is a set_properties or action answer with a non-zero code.

func (*PropError) Error

func (e *PropError) Error() string

Error tells which property or action was refused and the code.

type PropRef

type PropRef struct {
	DID   string `json:"did"`
	SIID  int    `json:"siid"`
	PIID  int    `json:"piid"`
	Value any    `json:"value,omitempty"`
	Code  int    `json:"code,omitempty"`
}

PropRef names one property in a MIoT request.

type PropResult

type PropResult struct {
	DID   string `json:"did"`
	SIID  int    `json:"siid"`
	PIID  int    `json:"piid"`
	Code  int    `json:"code"`
	Value any    `json:"value"`
}

PropResult is one property of a get_properties or set_properties answer, or the answer to an action. Code 0 is success; devices answer -4001 to -4005 and others for a property they lack, cannot write or cannot take the value of.

func CheckSet

func CheckSet(raw json.RawMessage) ([]PropResult, error)

CheckSet reads a set_properties answer and returns a *PropError for the first property answered with a non-zero code.

func GetProperties

func GetProperties(ctx context.Context, c *Client, refs []PropRef) ([]PropResult, error)

GetProperties reads properties, in requests of at most 15, and returns one result per property in order. A property the device lacks has a non-zero Code.

Example

Read a MIoT device's properties by service and property ID. It needs a device, so it is not run.

package main

import (
	"context"
	"encoding/hex"
	"fmt"
	"time"

	"github.com/cB-Sigma/miio"
)

func main() {
	tok, _ := hex.DecodeString("0f1e2d3c4b5a69788796a5b4c3d2e1f0")
	c := &miio.Client{Addr: "192.168.1.70:54321", Token: tok, Timeout: 3 * time.Second}
	res, err := miio.GetProperties(context.Background(), c, []miio.PropRef{
		{DID: "purifier", SIID: 2, PIID: 2}, // power
		{DID: "purifier", SIID: 3, PIID: 6}, // PM2.5
	})
	if err != nil {
		fmt.Println(err)
		return
	}
	for _, r := range res {
		fmt.Println(r.SIID, r.PIID, r.Code, r.Value)
	}
}

func SetProperties

func SetProperties(ctx context.Context, c *Client, refs []PropRef) ([]PropResult, error)

SetProperties writes properties (each PropRef with its Value) in one request. It returns the results, and a *PropError for the first property answered with a non-zero code.

type Property

type Property struct {
	IID         int         `json:"iid"`
	Type        string      `json:"type"`
	Description string      `json:"description,omitempty"`
	Format      string      `json:"format,omitempty"`
	Access      []string    `json:"access,omitempty"`
	Unit        string      `json:"unit,omitempty"`
	ValueRange  []float64   `json:"value-range,omitempty"`
	ValueList   []ValueItem `json:"value-list,omitempty"`
}

Property is one property of a service.

func (Property) Can

func (p Property) Can(a string) bool

Can reports whether the property allows an access: "read", "write" or "notify".

type Service

type Service struct {
	IID         int        `json:"iid"`
	Type        string     `json:"type"`
	Description string     `json:"description,omitempty"`
	Properties  []Property `json:"properties,omitempty"`
	Actions     []Action   `json:"actions,omitempty"`
}

Service is one service of a specification.

type Spec

type Spec struct {
	Type        string    `json:"type"`
	Description string    `json:"description,omitempty"`
	Services    []Service `json:"services"`
}

Spec is a model's MIoT specification, as miot-spec.org serves it.

type SpecSource

type SpecSource interface {
	Spec(ctx context.Context, model string) (*Spec, error)
}

SpecSource gives a model's MIoT specification.

type ValueItem

type ValueItem struct {
	Value       int    `json:"value"`
	Description string `json:"description"`
}

ValueItem is one allowed value of an enumerated property.

Jump to

Keyboard shortcuts

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