Skip to content

Usage and examples

faustyn-p edited this page Aug 30, 2020 · 2 revisions

Import YeelightService

import { YeelightService } from 'yeelight-service';
const yeelightService = new YeelightService();

Subscribing to devices

This function subscribes to all devices connected to current WiFi. Event will be executed each time, a new device is connected.

yeelightService.devices.subscribe((devices) => {
    // executed each time device is connected
    // do something with devices
});

Get device by name

This function gets device by name. If there are multiple devices with given name, only the first one will be returned.

yeelightService.getDeviceByName('deviceName').subscribe((device) => {
    // executed when device will be found
    // do something with device
});

Get device by model

This function gets device by model. If there are multiple devices with given model, only the first one will be returned.

yeelightService.getDeviceByModel('lamp1').subscribe((device) => {
    // executed when device will be found
    // do something with device
});

Subscribing to device property

You can subscribe to device property (e.g. subscribe to power state)

yeelightService.getDeviceByModel('lamp1').subscribe((device) => {
    device.power.subscribe((powerState) => {
        // executed each time power state change
        // do something with power state
    });
});

Or you can get power state just once

yeelightService.getDeviceByModel('lamp1').subscribe((device) => {
    const power = device.power.value;
    // do something with power state
});

If you want to observe more than one property, do it in RXJS-way. For example, if you want to be notified each time when connection status, power state OR brightness change, you can use RXJS combineLatest.

yeelightService.getDeviceByModel('lamp1').subscribe((device) => {
    combineLatest(
        device.connected,
        device.power,
        device.brightness
    ).pipe(
        map(([connected, power, brightness]) => {
            return { connected, power, brightness };
        })
    ).subscribe((data) => {
        // executed each time `connected`, `power` or `brightness` change
        // do something with data
    });
});

Changing property of device

Every function changing any device property returns promise object with operation status.

yeelightService.getDeviceByModel('lamp1').subscribe((device) => {
    device.setPower('on').then((result) => {
        // do something with result
    });
});