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)
}
Output:
Index ¶
- Constants
- Variables
- func CheckAction(raw json.RawMessage) error
- func Decrypt(token, ct []byte) ([]byte, error)
- func DefaultAPIBase(region string) string
- func Discover(ctx context.Context, bcast string, wait time.Duration) (map[uint32]string, error)
- func DoAction(ctx context.Context, c *Client, did string, siid, aiid int, in []any) error
- func EncSignature(method, path string, params [][2]string, signedNonce string) string
- func Encrypt(token, plain []byte) []byte
- func Hello() []byte
- func Keys(token []byte) (key, iv []byte)
- func Packet(token []byte, deviceID, stamp uint32, plain []byte) []byte
- func RC4Decrypt(signedNonce, v string) ([]byte, error)
- func RC4Encrypt(signedNonce, v string) string
- func SignedNonce(ssecurity, nonce string) string
- func URNName(urn string) (string, bool)
- type Action
- type Client
- type Cloud
- type CloudDevice
- type HTTPSpecs
- type Header
- type PropError
- type PropRef
- type PropResult
- type Property
- type Service
- type Spec
- type SpecSource
- type ValueItem
Examples ¶
Constants ¶
const DefaultSpecURL = "https://miot-spec.org/miot-spec-v2"
DefaultSpecURL is miot-spec.org's specification service.
const Port = 54321
Port is miIO's UDP port.
Variables ¶
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.
var ErrNoSpec = errors.New("no MIoT specification of the model")
ErrNoSpec means no specification of the model could be found.
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.
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 DefaultAPIBase ¶
DefaultAPIBase is the Mi account's API address of a region.
func EncSignature ¶
EncSignature is the SHA-1 signature over the method, the path, the parameters in order and the signed nonce.
func Keys ¶
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 RC4Decrypt ¶
RC4Decrypt reverses RC4Encrypt.
func RC4Encrypt ¶
RC4Encrypt encrypts a value with a signed nonce (base64 in and out).
func SignedNonce ¶
SignedNonce is the per-call key: SHA-256(ssecurity ‖ nonce), base64.
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 ¶
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.
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.
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 Header ¶
Header is a parsed packet header.
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 ¶
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)
}
}
Output:
func SetProperties ¶
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.
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 ¶
SpecSource gives a model's MIoT specification.