eWeLink API Client for Node.js

3.1.1 · active · verified Tue Apr 21

The ewelink-api library provides a programmatic interface for interacting with eWeLink-compatible smart home devices, such as Sonoff products, from Node.js environments. It supports both cloud-based interaction (requiring internet access) and ZeroConf (LAN mode) for local control without an internet connection. The current stable version is 3.1.1, with releases occurring on a moderate, irregular cadence, focusing on bug fixes, dependency updates, and feature enhancements like improved error handling and new device control methods. Key differentiators include its multi-environment compatibility (Node.js, browsers, serverless), robust device state management, and power consumption monitoring for compatible devices.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates initializing the API, logging in, finding a specific device, and toggling its power state using the recommended WebSocket method.

import EwelinkApi from 'ewelink-api';

const EMAIL = process.env.EWELINK_EMAIL ?? '';
const PASSWORD = process.env.EWELINK_PASSWORD ?? '';
const REGION = process.env.EWELINK_REGION ?? 'us'; // e.g., 'us', 'eu', 'as'
const DEVICE_ID = process.env.EWELINK_DEVICE_ID ?? '';

async function controlDevice() {
  if (!EMAIL || !PASSWORD || !DEVICE_ID) {
    console.error('Please set EWELINK_EMAIL, EWELINK_PASSWORD, and EWELINK_DEVICE_ID environment variables.');
    process.exit(1);
  }

  try {
    const connection = new EwelinkApi({ email: EMAIL, password: PASSWORD, region: REGION });
    await connection.get and set things
    const devices = await connection.getDevices();
    const targetDevice = devices.find(d => d.deviceid === DEVICE_ID);

    if (targetDevice) {
      console.log(`Found device: ${targetDevice.name} (ID: ${targetDevice.deviceid})`);
      
      // Toggle power state using the newer WebSocket method (v3.1.0+)
      console.log('Toggling device power state via WebSocket...');
      const currentState = targetDevice.params.switch === 'on' ? 'off' : 'on';
      await connection.setWSDevicePowerState(DEVICE_ID, currentState);
      console.log(`Device state toggled to ${currentState}.`);

      // Or using the standard HTTP method
      // console.log('Toggling device power state via HTTP...');
      // await connection.setDevicePowerState(DEVICE_ID, currentState);
      // console.log(`Device state toggled to ${currentState}.`);

      const status = await connection.getDevicePowerState(DEVICE_ID);
      console.log(`Device new power state: ${status.state}`);
    } else {
      console.log(`Device with ID ${DEVICE_ID} not found.`);
    }

  } catch (error) {
    console.error('An error occurred:', error.message);
  }
}

controlDevice();

view raw JSON →