• Stars
    star
    2,054
  • Rank 22,498 (Top 0.5 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 7 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

🌧 An easy-to-use API for devices that use Tuya's cloud services. Documentation: https://codetheweb.github.io/tuyapi.

TuyAPI 🌧 🔌

XO code style Build Status Coverage Status Node Version

A library for communicating with devices that use the Tuya cloud network. These devices are branded under many different names, but if your device works with the TuyaSmart app or port 6668 is open on your device chances are this library will work.

Installation

npm install codetheweb/tuyapi

Basic Usage

See the setup instructions for how to find the needed parameters.

These examples should report the current status, set the default property to the opposite of what it currently is, then report the changed status. They will need to be adapted if your device does not have a boolean property at index 1 (i.e. it doesn't have an on/off property). Index 20 seems to be another somewhat common on/off property.

Asynchronous (event based, recommended)

const TuyAPI = require('tuyapi');

const device = new TuyAPI({
  id: 'xxxxxxxxxxxxxxxxxxxx',
  key: 'xxxxxxxxxxxxxxxx'});

let stateHasChanged = false;

// Find device on network
device.find().then(() => {
  // Connect to device
  device.connect();
});

// Add event listeners
device.on('connected', () => {
  console.log('Connected to device!');
});

device.on('disconnected', () => {
  console.log('Disconnected from device.');
});

device.on('error', error => {
  console.log('Error!', error);
});

device.on('data', data => {
  console.log('Data from device:', data);

  console.log(`Boolean status of default property: ${data.dps['1']}.`);

  // Set default property to opposite
  if (!stateHasChanged) {
    device.set({set: !(data.dps['1'])});

    // Otherwise we'll be stuck in an endless
    // loop of toggling the state.
    stateHasChanged = true;
  }
});

// Disconnect after 10 seconds
setTimeout(() => { device.disconnect(); }, 10000);

Synchronous

const TuyAPI = require('tuyapi');

const device = new TuyAPI({
  id: 'xxxxxxxxxxxxxxxxxxxx',
  key: 'xxxxxxxxxxxxxxxx',
  issueGetOnConnect: false});

(async () => {
  await device.find();

  await device.connect();

  let status = await device.get();

  console.log(`Current status: ${status}.`);

  await device.set({set: !status});

  status = await device.get();

  console.log(`New status: ${status}.`);

  device.disconnect();
})();

Data not updating?

Some new devices don't send data updates if the app isn't open.

These devices need to be "forced" to send updates. You can do so by calling refresh() (see docs), which will emit a dp-refresh event.

const TuyAPI = require('tuyapi');

const device = new TuyAPI({
    id: 'xxxxxxxxxxxxxxxxxxxx',
    key: 'xxxxxxxxxxxxxxxx',
    ip: 'xxx.xxx.xxx.xxx',
    version: '3.3',
    issueRefreshOnConnect: true});

// Find device on network
device.find().then(() => {
    // Connect to device
    device.connect();
});

// Add event listeners
device.on('connected', () => {
    console.log('Connected to device!');
});

device.on('disconnected', () => {
    console.log('Disconnected from device.');
});

device.on('error', error => {
    console.log('Error!', error);
});

device.on('dp-refresh', data => {
    console.log('DP_REFRESH data from device: ', data);
});

device.on('data', data => {
    console.log('DATA from device: ', data);

});

// Disconnect after 10 seconds
setTimeout(() => { device.disconnect(); }, 1000);

📝 Notes

  • Only one TCP connection can be in use with a device at once. If using this, do not have the app on your phone open.
  • Some devices ship with older firmware that may not work with tuyapi. If you're experiencing issues, please try updating the device's firmware in the official app.
  • Newer firmware may use protocol 3.3. If you are not using find(), you will need to manually pass version: 3.3 to the constructor.
  • TuyAPI does not support sensors due to the fact that they only connect to the network when their state changes. There are no plans to add support as it's out of scope to intercept network requests.
  • The key parameter for devices changes every time a device is removed and re-added to the TuyaSmart app. If you're getting decrypt errors, try getting the key again - it might have changed.

📓 Documentation

See the docs.

Current State & the Future of TuyAPI

The goal of this repository specifically is to provide a bit of a middle ground between implementing everything from scratch and having everything handled for you.

I realize this is a bit wishy-washy and most users would prefer one or the other. I started a new library a while ago to address this and incorporate some of the lessons we've learned over the years: @tuyapi/driver. The intention is that this library would be fairly low-level, and then more user-friendly libraries could be built on top of it to provide common functionality for, say, setting RGB light values (probably named @tuyapi/devices).

Unfortunately, not much progress has been made in that regard for a few reasons. First, besides the occasional coffee (thank you 😀) I don't get paid for this. And it's hard to be motivated to work on it when I don't actually use it day-to-day. For lack of a beter explanation, it's just not "fun" anymore. Also: trying to play wack-a-mole with a large corporation is kinda exhausting.

TL;DR: all that to say that I personally will not be further developing Tuya-related projects for the foreseeable future besides fixing reproducable bugs. I plan to still respond to support requests and bug reports, but please be patient. 😀

Contributing

See CONTRIBUTING.

Contributors

(If you're not on the above list, open a PR.)

Related

Flash alternative firmware

  • tuya-convert a project that allows you to flash custom firmware OTA on devices

Ports

Clients for Tuya's Cloud

Projects built with TuyAPI

To add your project to either of the above lists, please open a pull request.

forthebadge forthebadge

More Repositories

1

muse

🎧 a self-hosted midwestern Discord music bot that doesn't suck
TypeScript
782
star
2

aoede

🎧 a self-hosted Spotify → Discord music bot
Rust
285
star
3

anylist

📋 a wrapper for AnyList's API (unoffical, reverse engineered)
JavaScript
85
star
4

dialogflow-to-discord

Easily add Discord bot integration to your Dialogflow project
JavaScript
18
star
5

placed

a viewer for /r/place
Rust
17
star
6

serverless-step-functions-local

Run AWS step functions offline with Serverless
JavaScript
16
star
7

homebridge-tuya-outlet

A plugin for Homebridge for Tuya-based outlets
JavaScript
15
star
8

MMM-AnyList

Magic Mirror module to display AnyList data
JavaScript
11
star
9

literature-clock

Returns a random quote containing the passed time.
JavaScript
6
star
10

Pigeon

Web interface for GRIP
JavaScript
3
star
11

mtu-webcams

📷 🚨 an easy-to-use API for downloading and streaming from public Michigan Tech webcams
JavaScript
3
star
12

librespot-node

Rust
3
star
13

portfolio

🎨 source for maxisom.me
TypeScript
3
star
14

Spong

🍴+ 🥄 + 🎵 App to show the currently playing song on Spotify. Made for big displays at parties and events.
JavaScript
2
star
15

stepfunctions-localhost

JavaScript
1
star
16

ifttt-bluetooth-proximity

A script to add Bluetooth proximity detection to IFTTT flows
JavaScript
1
star
17

buzzzer

A web buzzer (for Jeopardy, etc.). Made for Wonderhack 2019.
CSS
1
star
18

relacation

Quick demo to show seeding of the Math.random() function with a user's location
HTML
1
star
19

tothemoonbitcoin

🚀 to the 🌔!
CSS
1
star
20

substr-occurrence

A small library that counts the number of occurrences of a substring
JavaScript
1
star
21

homebridge-yamaha-scene

Turns on and off a Yamaha AV receiver and set it to a scene
JavaScript
1
star
22

codetheweb

1
star
23

dominos-api

🍕
JavaScript
1
star
24

nodesplash

🌊 port of qdm12/gosplash to TypeScript
TypeScript
1
star
25

Tradmill

A new & fresh wireless treadmill controller
CSS
1
star
26

gh-action-issue-parser

⚙️ action that runs issue-parser and provides the output
TypeScript
1
star
27

palmdoc-compression

Fast & safe implementation of Kindle/PalmDoc flavored LZ77
Rust
1
star