Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

wled-client

ShiftLimits410MIT0.22.1TypeScript support: included

A friendly JS interface for controlling your WLED devices from Node.js or the browser.

wled, client, isomorphic, led

readme

WLED Client

A friendly JS interface for controlling your WLED devices from Node.js or the browser.

Note: This is under early active development and may be subject to breaking changes until it reaches a stable version 1.0.0.

About

This is a JS/TS client library for the control of WLED devices. It offers a friendly simplified interface to send commands and receive data from your device, either piecemeal via WLED's JSON API or in real time via the WebSocket API. The full power of WLED's JSON API can also be harnessed through WLED Client by using updateState.

Installation

WLED Client is isomorphic, meaning it will behave identically in both the browser and Node.js.

Browser

For a fast and traditional start, you can include the CDN script for WLED Client in your HTML:

<script src="https://unpkg.com/wled-client/dist/browser/wled-client.js"></script>

Or you can also download this script directly to use it locally where you please. Either way, the WLEDClient class will now be available globally.

For a more modern approach, you can use the ES Module version of WLED Client provided by the CDN:

<script src="https://unpkg.com/wled-client/dist/browser/wled-client.mjs" type="module"></script>

See usage for next steps.

Node

Install with your favorite Node.js package manager:

# NPM
$ npm install wled-client

# Yarn
$ yarn add wled-client

Then you can require or import WLED Client:

import { WLEDClient } from 'wled-client'
const { WLEDClient } = require('wled-client')

See usage for next steps.

Other Environments

Under the hood, WLED Client uses the fetch, WebSocket, and EventTarget APIs to achieve the desired behavior. WLED Client is primarily meant to be used in the browser where these APIs are provided by the browser's execution environment. In order to work on node, each API has been polyfilled.

If your execution environment includes these APIs, you can use the browser script out of the box. Otherwise you'll need to add your own polyfills to make WLED Client work in your desired environment.

Usage

Create a new instance of the WLEDClient class and pass in the IP of your WLED device:

const wled = new WLEDClient('192.168.0.123')

Once the class is constructed, WLED Client will immediately try to fetch the full device context (state, info, effects, and palettes) via the JSON API. If WebSocket is enabled, then at the same time WLED Client will also try to establish a connection via the WebSocket API.

When WLED Client has successfully fetched the device context, the promise at wled.isReady will resolve. Then the device's state, info, effects, and palettes will be accessible. As long as the WebSocket API is connected updates to the device context will be received asynchronously, so changes made from outside WLED Client (like the WLED App) will be automatically applied to the client instance. You can always manually refetch the context using the wled.refreshContext() method.

async function init() {
    const wled = new WLEDClient('192.168.0.123')
    await wled.init()

    console.log(wled.info.version) // 0.12.0
}
init().catch(console.error)

If you're familiar with WLED's JSON API, you can make an update to the device state in a similar way using the wled.updateState() method. This method accepts an object with a friendly (verbose) interface that matches 1:1 with the WLED JSON API.

async function init() {
    const wled = new WLEDClient('192.168.0.123')
    await wled.init()

    console.log(wled.state.brightness) // 255
    await wled.updateState({
        brightness: 128
    })
    console.log(wled.state.brightness) // 128
}
init().catch(console.error)

If you'd rather be more direct, WLED Client offers simple methods to execute common commands as well.

async function init() {
    const wled = new WLEDClient('192.168.0.123')
    await wled.init()

    console.log(wled.state.brightness) // 255
    await wled.setBrightness(128)
    console.log(wled.state.brightness) // 128
}
init().catch(console.error)

See the WLEDClient class page for a list of methods. At any point you can run any method that updates the device's state, regardless of WLED Client's ready state. If the WebSocket is not connected, state updates will be sent via the JSON API over HTTP.

Examples

Twitch integration example using tmi.js. Contains detailed instructions if you're new to Node.js.

To see how WLED Client handles various use cases, there are several example scripts in the official examples repository.

Documentation

There is a wonderfully done documentation for the WLED JSON API to be found at the WLED knowledge base. WLED Client implements this with only slightly more verbose key names.

See the API documentation page for a detailed run down of WLED Client's structure. The WLEDClient class docs has a quick list of properties and methods you can use. It may also help to check out the type definitions for WLED Client and compare them to the type definitions for WLED itself.

Versioning

In order to adhere to the NPM ecosystem, WLED Client follows semantic versioning. WLED Client will bump major versions when there is a breaking change in the API that you consume in your projects. This may happen when WLED introduces a breaking change in its API, or if there comes a need to restructure parts of WLED Client.

Otherwise, we will bump minor versions every time we introduce support for new WLED features as the WLED project progresses. WLED Client aims to support whatever the latest stable version of WLED is.

License

WLED Client is MIT licensed.

changelog

Changelog

All notable changes to this project will be documented in this file.

The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.

[Unreleased]

Nothing yet.

[0.22.1]- 2022-10-30

Fixed

  • Fix syntax error when using require in Node, caused by minifying during build
  • Ensure Node uses the correct entry point when importing from an ES module (fixes #4)

[0.22.0]- 2022-06-12

Added

  • Add init object to client options for disabling the fetching of some device information on client initialize (can help with lower power devices)
  • Add timeout to client options for any fetch request to JSON API, requests now timeout after 5 seconds by default
  • Expose open event from WebSocket
  • Add events reporting the progress of a state update
    • Add error event when JSON API fails
    • Add loading event when a state update request is sent to an available transport
    • Add success event when a state update request is successful on any transport, with a payload of { transport: 'ws'|'http' }
    • Add success:http when a state update request is successful on the HTTP transport
    • Add success:ws when a state update request is successful on the WebSocket transport

Fixed

  • Fix live LEDs type not updated to new Uint8Array format

[0.21.0]- 2022-06-05

WLED 0.13.1 compatibility update.

Added

  • Add repeat property to segments
  • Add freeze property to segments
  • Add support for reading segment light capabilities via info.leds.segmentLightCapabilities and info.leds.lightCapabilities
  • Add lightCapabilities object to main client class which holds the parsed values for rgb, white, and cct from the info

Changed

  • Breaking Peek feature now uses a binary format and the live:leds event will now return an array of RGB values for LED data instead of the original object { n, leds }
  • Breaking Cronixie is now supported via usermod so references to Cronixie have been removed with the exception of the device option, which has been renamed to USERMOD_CRONIXIE

Deprecated

  • Deprecated rgbw, whiteValueInput, and cct properties from info.leds, use the new lightCapabilities object on the client instance eg. const client = new WLEDClient('x.x.x.x'), console.log(client.lightCapabilities)

[0.20.0]- 2022-01-29

After some further consideration, I have decided to decouple this project's versioning from WLED in order to better adhere to the expected behavior of a package in the NPM ecosystem. As of this release, WLED Client has been bumped up to 0.20.0 and further releases will update the version number according to standard Semantic Versioning. We moved up to 0.20 to help avoid confusing the client's version with WLED's version.

Starting with this version (0.20.0) WLED Client will target WLED 0.13.0 for API compatibility. Moving forward, WLED Client will bump major versions when there is a breaking change in the API that you consume in your projects. This may happen when WLED introduces a breaking change, or if there comes a need to restructure WLED Client.

Added

  • Add major support for getting and setting config values
  • Add setCCT method for setting the correlated color temperature of the white channel
  • Add id and name property to segments
  • Add ability to stop the client from initializing the connection, allowing for the client to be initialized but will not fetch the context or connect to the WebSocket until wled.init() is called

Changed

  • Breaking: The isReady promise is now private and should no longer be used
    • Use wled.init() which will return a promise with the same behavior
  • Breaking: Remove deprecated info.leds.pins property as it is no longer available in WLED 0.13.0
  • Breaking: Remove deprecated state.nightlight.fade property as it is no longer available in WLED 0.13.0
  • Breaking: Remove deprecated state.presetCycle property as it is no longer available in WLED 0.13.0
  • If null is returned when trying to fetch palette data WLED Client will retry instead of bailing out

[0.12.0-0.4]- 2021-11-29

The concept of "live data" in WLED Client is now generic and encompasses any possible live data instead of just LED state. LED state has been implemented into this generic concept.

Some better error handling has been implemented as well, with the error event now being utilized. Additionally most of the main methods can now optionally target one or more segments.

Otherwise filling in the client API more and improving dev experience. First implementation of support for fetching palette data as well!

Added

  • Add getPalettesData method for getting all color palette data, or optionally a specific page of palette data
  • Add setEffectSpeed and setEffectIntensity methods
  • Add enableUDPSync and disableUDPSync methods
  • Add reboot method
  • Add live property to WLED Context containing booleans indicating what live data is being sent over WebSocket, such as the current state of the device's LEDs indicated by live.leds and received by the live:leds event
  • Add wsReadyState property to return the WebSocket instance's ready state
  • Add buildStateWithSegments function to help build an updatable state object to be applied to all desired segments, or to be applied per desired segment if a function is passed
  • Add defaults for all nested objects or arrays in WLED Client's context

Changed

  • Breaking: Rename live event to live:leds to be more specific with what exactly the live data is
  • Breaking: Rename startLiveStream and stopLiveStream to startLEDStream and stopLEDStream respectively
  • Update turnOn, turnOff, toggle, setBrightness, set[Ordinal]Color, setEffect, and setPalette to support specifically targeting one or more segments
  • Update initialization procedure to properly emit errors and reject the isReady promise when a problem was encountered
  • Update updateState method to properly emit and throw errors encountered when attempting the operation
  • Update JSON API to be an event emitter and set WLED Client to relay error events
  • Update JSON API to throw and emit a Fetch Response object if the response is not OK, allowing for fetch errors to be handled as you please
  • Reconnect time for WS API is now 1 second
  • Centralize client context updates
  • WLED and WLED Client interfaces now match their defaults, so keys will be properly typed as possibly undefined while the device context has yet to be fetched
  • Made examples easily executable and moved them to their own repository so as not to pollute dependencies
  • Fix info.syncToggleReceive not being set correctly

[0.12.0-0.3]- 2021-11-22

Getting close to feature parity with the 0.12.0 API.

Added

  • Add support for fetching presets to the JSON API
  • Add getPreset, savePreset, saveStateAsPreset, and deletePreset methods for working with WLED presets
  • Add 7-presets example to demonstrate preset methods usage
  • Add deviceOptions property which shows the info.options bit field value as a friendly object of booleans
  • Add support for debug-only info properties which are filled in if your device is in debug mode
  • Add reconnection logic for the websocket connection, controlled by passing { websocket: { reconnect: [true|false] }} using client options
  • Add ESM export for the browser environment so you can use it with the modern modules system now in most browsers

Changed

  • Breaking: Move WLEDClient from default export to a named export. This breaks import or require statements. Please change import WLEDClient from 'wled-client' to import { WLEDClient } from 'wled-client' and change const WLEDClient = require('wled-client') to const { WLEDClient } = require('wled-client')
  • Update turnOn, turnOff, toggle, setBrightness, set[Ordinal]Color, updateState, and updateSegment methods to support some one-time state change properties, such as transition or noSync, which control the transition for the current method - for example turn on the lights over 100 seconds - or preventing the method from syncing to other devices respectively
  • Key transforming between WLED and WLED Client APIs now uses wildcard to support transforming presets
  • Device context properties (state, info, effects, and palettes) will now initialize with empty objects/arrays for better dev experience before context is loaded
  • Follow exports package spec to properly target different environments
  • Default export for browser environment is now in UMD format, allowing for it to be used in CJS-like module systems

[0.12.0-0.2] - 2021-11-17

Continuing to flesh out the interface and patch bugs.

Added

  • Add nightlight object to client instance containing methods for controlling the nightlight feature
  • Add 6-nightlight example to demonstrate nightlight feature usage
  • Add setTransitionTime method for control over the crossfade time between effects or colors
  • Add setMainSegmentId method to change which segment is considered the main segment
  • Add ignoreLiveData and allowLiveData methods to override when live display data is output by the device

Changed

  • Fix update:context event emitting WLED context instead of WLED Client context
  • Fix update:state event emitting WLED state instead of WLED Client state
  • Fix update:info event emitting WLED info instead of WLED Client info
  • Use Omit instead of Exclude to remove keys from a type as expected

[0.12.0-0.1] - 2021-11-16

Initial release!

Added

  • Add fully documented WLED JSON API typings
  • Add fully documented WLED Client API typings
  • Add WLED JSON API class for control of the device specifically via JSON over HTTP
  • Add WLED WebSocket API class for realtime control and feedback of the device via WebSockets
  • Add WLED Client class which offers simplified commands and a friendly interface equivalent to WLED's JSON API