ewelink-api

repository·master·Indexed 43 days ago

https://github.com/skydiver/ewelink-api

A JavaScript library for interacting with eWeLink-compatible smart devices in Node.js, browsers, and serverless environments. Version 3.1.1 supports cloud-based and local LAN-based (zeroconf) control, providing methods for authentication, device discovery, power state control, and telemetry monitoring for devices such as Sonoff POW.

Tokens
12.5K
Snippets
58
Records
66
Agent score
50%

What's inside ewelink-api

  1. Overview of ewelink-api features

    master

    The ewelink-api library provides a JavaScript interface for interacting with eWeLink devices. Key capabilities include:

    • Environment Compatibility: Can run in browsers, Node.js scripts, or serverless environments.
    • Device Control: Ability to set on/off states for compatible devices.
    • Power Monitoring: Retrieve power consumption data from devices such as Sonoff POW.
    • Event Listening: Listen for real-time device events.
    • LAN Mode: Supports zeroconf for local network communication, allowing control without an active internet connection.
  2. Explore available methods in ewelink-api

    master

    The ewelink-api package provides a variety of methods to interact with eWelink devices, including credential management, WebSocket connections, device status retrieval, and power state control.

    Important: You must instantiate the class before attempting to use any of these methods.

    Available method categories include:

    • Authentication & Connection: getCredentials, openWebSocket
    • Device Discovery & Info: getDevice, getDevices, getRegion, getFirmwareVersion, getDeviceChannelCount
    • Power Control: getDevicePowerState, setDevicePowerState, getWSDevicePowerState, setWSDevicePowerState, toggleDevice
    • Telemetry & Monitoring: getDevicePowerUsage, getDeviceCurrentTH, getDeviceCurrentTemperature, getDeviceCurrentHumidity
    • Data Management: saveDevicesCache

    For implementation patterns, refer to the provided demos for Node.js and Serverless environments.

  3. Specify the correct ewelink region

    master

    The default region for this library is us. If your account is registered in a different region, you must specify the region parameter during instantiation. Failure to provide the correct region will result in 400 or 401 errors.

    If you are unsure of your region, use the getRegion method to identify it.

  4. Quickstart with ewelink-api

    master

    To start using ewelink-api, instantiate the ewelink class with your credentials and a specific region. Note that the default region is us; if your account is in a different region, you must specify the region parameter to avoid 400/401 errors. Once instantiated, you can call methods like getDevices() to interact with your smart home devices.

    const ewelink = require('ewelink-api');
    
    /* instantiate class */
    const connection = new ewelink({
      email: '<your ewelink email>',
      password: '<your ewelink password>',
      region: '<your ewelink region>',
    });
    
    /* get all devices */
    const devices = await connection.getDevices();
    console.log(devices);
  5. Implement ewelink-api in serverless environments

    master

    In serverless environments (like AWS Lambda or Google Cloud Functions), you must instantiate the ewelink class on every request because the execution context is ephemeral.

    To avoid performing a full login (email/password) on every single request, follow this pattern:

    1. First Request: Use email, password, and region to call getCredentials(). This returns an access token (at), an apikey, and the region.
    2. Subsequent Requests: Store the at and region in a persistent store (like a database or cache). For future requests, instantiate ewelink using only the at and region parameters to bypass the login step.
    /* first request: get access token and api key */
    (async () => {
      const connection = new ewelink({
        email: '<your ewelink email>',
        password: '<your ewelink password>',
        region: '<your ewelink region>',
      });
    
      const credentials = await connection.getCredentials();
    
      const accessToken = credentials.at;
      const apiKey = credentials.user.apikey;
      const region = credentials.region;
    })();
    
    /* subsequent request: use access token */
    (async () => {
      const newConnection = new ewelink({
        at: accessToken,
        region: region
      });
    
      const devices = await newConnection.getDevices();
    })();
  6. Integrate ewelink-api in serverless environments

    master
    If you are deploying your logic to a serverless platform (such as AWS Lambda), follow the serverless integration guide. This guide provides instructions on how to correctly package and execute the library within a stateless, event-driven environment.
  7. Toggle device power state via Zeroconf (LAN mode)

    master

    Once the cache files (devices-cache.json and arp-table.json) are generated, you can control devices locally without an internet connection.

    1. Load the caches using Zeroconf.loadCachedDevices() and Zeroconf.loadArpTable().
    2. Initialize the ewelink connection by passing the loaded devicesCache and arpTable in the options object.
    3. Use connection.setDevicePowerState(deviceId, state) to turn devices on or off.

    Supported actions: Only 'on' and 'off' are currently available.

    const ewelink = require('ewelink-api');
    const Zeroconf = require('ewelink-api/src/classes/Zeroconf');
    
    /* load cache files */
    const devicesCache = await Zeroconf.loadCachedDevices();
    const arpTable = await Zeroconf.loadArpTable();
    
    /* create the connection using cache files */
    const connection = new ewelink({ devicesCache, arpTable });
    
    /* turn device on */
    await connection.setDevicePowerState('<your device id>', 'on');
    
    /* turn device off */
    await connection.setDevicePowerState('<your device id>', 'off');
  8. Run the test suite or coverage reports

    master

    You can execute the tests using npm scripts.

    Important: Tests must be performed serially to avoid flooding eWeLink servers. If you are running Jest manually instead of through npm, you must include the --runInBand flag.

    npm run test
    # or
    npm run coverage
    
    # If running jest manually:
    jest --runInBand
  9. Generate an ARP table cache file for Zeroconf

    master

    To enable LAN mode, you must generate an arp-table.json file which contains information about the devices connected to your network. Use the Zeroconf.saveArpTable method, providing your network's IP address (e.g., 192.168.5.1).

    const Zeroconf = require('ewelink-api/src/classes/Zeroconf');
    
    await Zeroconf.saveArpTable({
      ip: '<your network addres, ex: 192.168.5.1>'
    });
  10. Set up the test suite environment

    master

    Before running tests, you must configure your credentials. Copy the example configuration file to the active configuration path and update it with your actual eWeLink credentials.

    Prerequisites:

    • All devices must be connected before running the test suite.
    • Ensure you have updated test/_setup/config/credentials.js with your parameters.
    cp test/_setup/config/credentials.example.js test/_setup/config/credentials.js