Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

8 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

yolink-api

A Go library for the YoLink smart home API. Supports HTTP and MQTT transports, strongly-typed controllers for every supported device, real-time event subscriptions, and a CLI tool for shell scripting.

Installation

go get github.com/tyandl/yolink-api

Requires Go 1.21+.

Credentials

Authenticate with a YoLink User Access Credential (UAC). Create one in the YoLink mobile app:

Settings → Account → Advanced Settings → User Access Credentials → Create

This yields a UAID (client ID) and a Secret Key (client secret).

Library usage

Connect and list devices

import (
    "github.com/tyandl/yolink-api/pkg/controller"
    _ "github.com/tyandl/yolink-api/pkg/devices" // registers typed device controllers
)

home, err := controller.NewHome(
    "https://api.yosmart.com",
    func() string { return os.Getenv("YOLINK_CLIENT_ID") },
    func() string { return os.Getenv("YOLINK_CLIENT_SECRET") },
)

devices, err := home.GetDeviceList()
for _, device := range devices {
    fmt.Printf("%s\t%s\t%s\n", device.GetName(), device.GetType(), device.GetId())
}

Importing pkg/devices (even as _) registers the typed controllers, so GetDeviceList and GetDeviceByName return concrete types you can type-assert:

device, err := home.GetDeviceByName("Front Door")
if sensor, ok := device.(*devices.DoorSensor); ok {
    state, err := sensor.GetState()
    fmt.Printf("state=%s battery=%s\n", state.State.State, state.State.Battery)
}

Devices without a registered type fall back to the untyped controller.Device.

Send a command

if lamp, ok := device.(*devices.Switch); ok {
    _, err := lamp.SetState(devices.SwitchSetStateParams{State: types.SwitchCommandOpen})
}

Subscribe to real-time reports (MQTT)

if err := home.InitializeMqtt("tcp://mqtt.api.yosmart.com:8003"); err != nil {
    log.Fatal(err)
}
defer home.CloseMqtt()

reports, stop, err := home.Subscribe() // whole home; or device.Subscribe() for one device
defer stop()

for report := range reports {
    fmt.Printf("%s: %s %v\n", report.Device.GetName(), report.Event, report.Data)
}

Note: the YoLink MQTT broker is plaintext TCP on port 8003 — no TLS endpoint is available. The access token travels as the MQTT username. Use the local hub broker on a trusted LAN if you need transport encryption.

Async calls over MQTT

ch := sensor.GetStateAsync()
result := <-ch
if result.Err != nil {
    log.Fatal(result.Err)
}
fmt.Println(result.Response)

Save and restore a home

Home.Save serializes the host, home info, and device list to JSON. Credentials are never written to the blob and must be supplied again at restore time:

blob, err := home.Save()

// later:
home, err = controller.RestoreHome(idFn, secretFn, blob)

CLI

The cmd/yolink program is a full-featured CLI for interacting with the YoLink API from the shell.

go build ./cmd/yolink

export YOLINK_CLIENT_ID=<UAID>
export YOLINK_CLIENT_SECRET=<secret>

Commands

# List all devices: name<TAB>type<TAB>id
./yolink ls

# Stream real-time reports as newline-delimited JSON
./yolink listen
./yolink listen --on "Front Door"

# Call a typed method on a device
./yolink do getState --on "Front Door"
./yolink do setState --on "Kitchen Light" --state open

Global flags

Flag Default Description
--log warn Log verbosity: debug, info, warn, error
--output json Output format: json or go
--client-id env Override YOLINK_CLIENT_ID
--client-secret env Override YOLINK_CLIENT_SECRET

Supported devices

Category Devices
Sensors DoorSensor, MotionSensor, LeakSensor, VibrationalSensor, ThSensor, SoilThcSensor, WaterDepthSensor, CoSmokeSensor, PowerFailureAlarm, IpCamera
Controls Switch, MultiOutlet, Outlet, Dimmer, Siren, GarageDoor, Lock, LockV2, Manipulator, Sprinkler, SprinklerV2, Thermostat
Hubs Hub, CellularHub, SpeakerHub
Metering WaterMeterController, WaterLeakController
Other Finger, SmartRemoter, InfraredRemoter, CsDevice, Debugger

Code generation

Typed device controllers are generated from JSON definitions in pkg/devices/. Each .json file describes a device's methods and events; the generator produces a *_gen.go file with typed request/response structs, sync and async method receivers, and an MQTT event parser.

After adding or editing a device definition:

python3 scripts/gen_device_types.py
go build ./...   # verify the generated code compiles

Do not edit *_gen.go files directly.

Project layout

pkg/controller/     HTTP + MQTT transports, Home, device registry, save/restore
pkg/devices/        typed device controllers (*_gen.go) and their JSON definitions
pkg/types/          shared types: enums, timestamps, temperature, status codes
cmd/yolink/         CLI tool
scripts/            code generators

API reference

Full go doc output for each package is saved in docs/:

License

Released under the MIT License.

About

A Go library for the YoLink smart home API. Supports HTTP and MQTT transports, strongly-typed controllers for every supported device, real-time event subscriptions, and a CLI tool for shell scripting.

Topics

Resources

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages