### TuyAPI Instance Parameters Source: https://github.com/codetheweb/tuyapi/blob/master/docs/SETUP_DEPRECATED.md Extracts the necessary parameters (id, uid, key) from a captured HTTPS request for constructing a TuyAPI instance. ```json { "id": "uuid", "uid": "productId", "key": "localKey" } ``` -------------------------------- ### Install and Run AnyProxy Source: https://github.com/codetheweb/tuyapi/blob/master/docs/SETUP.md Installs AnyProxy globally using npm and then runs the AnyProxy certificate authority tool to generate a root certificate for MITM proxying. ```bash npm i anyproxy -g anyproxy-ca ``` -------------------------------- ### Install TuyAPI CLI Source: https://github.com/codetheweb/tuyapi/blob/master/docs/SETUP.md Installs the TuyAPI command-line interface globally. This tool is required for most operations with TuyAPI. ```bash npm i @tuyapi/cli -g ``` -------------------------------- ### Install Dependencies Source: https://github.com/codetheweb/tuyapi/blob/master/CONTRIBUTING.md Installs the necessary dependencies for the TuyAPI project using npm. ```bash npm i ``` -------------------------------- ### List Tuya Devices Source: https://github.com/codetheweb/tuyapi/blob/master/docs/SETUP.md Lists available Tuya devices, typically outputting a QR code for certificate installation and device ID/key pairs. ```bash tuya-cli list-app ``` -------------------------------- ### Extract Jinvoo Device Data (Python) Source: https://github.com/codetheweb/tuyapi/blob/master/docs/SETUP_DEPRECATED.md A Python script to parse the `gw_storage.xml` file from the Jinvoo Smart app on Android. It extracts device details like name, localKey, and schema, after HTML entity decoding and JSON parsing. ```python #!/usr/bin/env python # -*- coding: us-ascii -*- # vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab # import codecs import os import json import xml.etree.ElementTree as ET try: # Python 2.6-2.7 from HTMLParser import HTMLParser except ImportError: # Python 3 from html.parser import HTMLParser ## FIXME use html.unescape()? xml_in_filename = 'com.xenon.jinvoo/shared_prefs/gw_storage.xml' h = open(xml_in_filename, 'r') xml = h.read() h.close() builder = ET.XMLTreeBuilder() builder.feed(xml) tree = builder.close() h = HTMLParser() for entry in tree.findall('string'): if entry.get('name') == 'gw_dev': # found it, need content config = entry.text s = h.unescape(config) config_dict = json.loads(s) #print(config_dict) print(len(config_dict)) for device in config_dict: #print(device) for key in ['name', 'localKey', 'uuid', 'gwType', 'verSw', 'iconUrl']: # and/or 'gwId', 'devId' print('%s = %r' % (key, device[key])) # there is a bunch of interesting meta data about the device print('schema =\') schema = device['devices'][0]['schema'] # NOTE I've only seen single entries schema = h.unescape(schema) schema_dict = json.loads(schema) print(json.dumps(schema_dict, indent=4)) print('') print(json.dumps(config_dict, indent=4)) ``` -------------------------------- ### TuyaDevice Instance Methods Source: https://github.com/codetheweb/tuyapi/blob/master/docs/index.html Provides methods for interacting with a Tuya device after initialization. Includes functions to get the device's status and refresh its state. ```APIDOC get(options = {}) Gets a device's current status. Defaults to returning only the value of the first DPS index. Parameters: options (Object, optional): options.schema (Boolean, optional): If true, returns the entire list of properties from the device. options.dps (Number, optional, default: 1): DPS index to return. options.cid (String, optional): If specified, use the device ID of the zigbee gateway and the cid of the subdevice to get its status. Returns: Promise<(Boolean | Object)>: Returns a boolean if a single property is requested, otherwise returns an object of results. Example: // get first, default property from device tuya.get().then(status => console.log(status)) // get second property from device tuya.get({dps: 2}).then(status => console.log(status)) // get all available data from device tuya.get({schema: true}).then(data => console.log(data)) refresh(options = {}) Refresh a device's current status. Defaults to returning all values. Parameters: options (Object, optional): No specific options detailed in the provided text. Returns: Promise: Returns an object containing the refreshed device status. ``` -------------------------------- ### Configuring Proxy on iPhone Source: https://github.com/codetheweb/tuyapi/blob/master/docs/SETUP.md Guides users on how to configure proxy settings on an iPhone to route traffic through a local MITM proxy server. ```APIDOC Configuring Proxy on iPhone: 1. Go to Settings > Wi-Fi. 2. Tap the 'i' icon next to your connected Wi-Fi network. 3. Scroll down to the HTTP PROXY section and select 'Configure Proxy'. 4. Choose 'Manual'. 5. Enter the Server address and Port provided by your MITM proxy tool (e.g., AnyProxy). 6. Save the settings. ``` -------------------------------- ### Link Tuya Device with Smart Link Source: https://github.com/codetheweb/tuyapi/blob/master/docs/SETUP.md Links a Tuya device to your TuyAPI setup using the Smart Link method. This requires obtaining API credentials from the Tuya IoT platform and providing WiFi network details. ```bash tuya-cli link --api-key --api-secret --schema --ssid --password --region us ``` -------------------------------- ### Synchronous Device Control with TuyAPI Source: https://github.com/codetheweb/tuyapi/blob/master/README.md Illustrates the synchronous, promise-based method for controlling Tuya devices. This approach involves using `async/await` to manage device operations like finding, connecting, getting status, setting state, and disconnecting. ```javascript 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(); })(); ``` -------------------------------- ### TuyaDevice Methods Source: https://github.com/codetheweb/tuyapi/blob/master/docs/index.html Provides methods for interacting with Tuya devices, including getting and setting device states, managing connections, and resolving device IDs. ```javascript class TuyaDevice { // Connect to the device connect(): Promise; // Disconnect from the device disconnect(): Promise; // Check if the device is connected isConnected(): boolean; // Get the current state of the device get(dps: string | string[]): Promise; // Set the state of a device's datapoint set(dps: string | any, value: any): Promise; // Refresh the device's state refresh(): Promise; // Resolve the device ID resolveId(): Promise; // Find devices on the network find(): Promise; // Toggle a device's state (e.g., on/off) toggle(): Promise; } ``` -------------------------------- ### Get Current Device Status (Command 0a) Source: https://github.com/codetheweb/tuyapi/wiki/TUYA-Commands This command retrieves the current operational status of the Tuya device. ```hex 000055aa000000000000000a0000000c00000000000000000000aa55 ``` -------------------------------- ### Tuya Get Device State Source: https://github.com/codetheweb/tuyapi/wiki/Communication-Details To retrieve the current state of a Tuya device, a specific payload structure must be sent, including the gateway and device IDs. ```javascript { gwId: '', devId: '' } ``` -------------------------------- ### TuyaDevice Constructor Source: https://github.com/codetheweb/tuyapi/blob/master/docs/index.html Initializes a new TuyaDevice instance. Requires either the device's IP address or ID. Optional parameters include port, gateway ID, encryption key, product key, protocol version, and flags for handling JSON errors and connection issues. ```APIDOC TuyaDevice(options) Parameters: options.ip (String, optional): IP address of the device. options.port (Number, optional, default: 6668): Port of the device. options.id (String, optional): ID of the device (also known as devId). options.gwID (String, optional, default: ''): Gateway ID (not needed for most devices). options.key (String): Encryption key of the device (also known as localKey). options.productKey (String, optional): Product key of the device (currently unused). options.version (Number, optional, default: 3.1): Protocol version. options.nullPayloadOnJSONError (Boolean, optional, default: false): If true, emits a data event with null values for on-device JSON parsing errors. options.issueGetOnConnect (Boolean, optional, default: true): If true, sends a GET request after connection is established. options.issueRefreshOnConnect (Boolean, optional, default: false): If true, sends DP_REFRESH request after connection is established. options.issueRefreshOnPing (Boolean, optional, default: false): If true, sends DP_REFRESH and GET request after every ping. Example: const tuya = new TuyaDevice({ id: 'xxxxxxxxxxxxxxxxxxxx', key: 'xxxxxxxxxxxxxxxx' }); ``` -------------------------------- ### TuyAPI Constructor Options Source: https://github.com/codetheweb/tuyapi/blob/master/README.md Details the various options available when initializing the TuyAPI constructor. These options allow for customization of device connection, including specifying ID, key, IP address, protocol version, and refresh behavior. ```APIDOC TuyAPI(options) options: Object id: String - Required. The Device ID. key: String - Required. The Device Key. ip: String - Optional. The Device IP address. If not provided, the library will attempt to find the device on the network. port: Number - Optional. The Device port. Defaults to 6668. version: String - Optional. The Tuya protocol version. Defaults to '3.1'. Use '3.3' for newer devices. issueGetOnConnect: Boolean - Optional. Whether to issue a GET command upon connection. Defaults to true. issueRefreshOnConnect: Boolean - Optional. Whether to issue a refresh command upon connection. Defaults to false. disableDeviceDiscovery: Boolean - Optional. Disables device discovery. Defaults to false. connectionTimeout: Number - Optional. Timeout in milliseconds for device connection. Defaults to 5000. requestAckTimeout: Number - Optional. Timeout in milliseconds for ACK response. Defaults to 1000. requestAckMaxRetries: Number - Optional. Maximum retries for ACK response. Defaults to 3. keepAlive: Boolean - Optional. Whether to keep the connection alive. Defaults to true. keepAliveTimeout: Number - Optional. Timeout in milliseconds for keep-alive packets. Defaults to 30000. ``` -------------------------------- ### List Tuya Devices using CLI Wizard Source: https://github.com/codetheweb/tuyapi/blob/master/docs/SETUP.md Runs the TuyAPI CLI wizard to discover and list all Tuya devices linked to your Tuya IoT account. This command prompts for necessary information and outputs device names, IDs, and keys. ```bash tuya-cli wizard ``` -------------------------------- ### CLI Interface for Tuya Devices Source: https://github.com/codetheweb/tuyapi/blob/master/README.md A command-line interface tool for interacting with Tuya devices, built using TuyAPI. ```javascript const cli = require('tuya-cli'); // Example usage: // cli.listDevices().then(devices => console.log(devices)); ``` -------------------------------- ### Go API for Tuya Devices Source: https://github.com/codetheweb/tuyapi/blob/master/README.md An easy-to-use API written in Go for controlling Tuya devices on the local network. ```go package main import ( "fmt" "github.com/Binozo/GoTuya" ) func main() { // Example: Connect to a device and turn it on // device := GoTuya.NewDevice("YOUR_DEVICE_ID", "YOUR_DEVICE_IP", "YOUR_DEVICE_LOCAL_KEY") // err := device.SetStatus(true) // if err != nil { // fmt.Println("Error:", err) // } fmt.Println("GoTuya example...") } ``` -------------------------------- ### Related Projects: Flash Alternative Firmware Source: https://github.com/codetheweb/tuyapi/blob/master/README.md This section highlights projects related to flashing alternative firmware onto Tuya devices, enabling greater customization and control over device behavior. The primary project mentioned facilitates Over-The-Air (OTA) firmware flashing. ```APIDOC tuya-convert: Description: A project that allows flashing custom firmware OTA on devices. Language: Shell/Various Repository: https://github.com/ct-Open-Source/tuya-convert ``` -------------------------------- ### Smart Home Panel Frontend Source: https://github.com/codetheweb/tuyapi/blob/master/README.md A frontend web application for controlling smart home devices, potentially using TuyAPI. ```javascript // This would typically involve a frontend framework like React, Vue, or Angular // interacting with a backend that uses TuyAPI. // Example API call (conceptual): // fetch('/api/devices/control', { // method: 'POST', // headers: { 'Content-Type': 'application/json' }, // body: JSON.stringify({ deviceId: '...', command: 'set', payload: { switch: false } }) // }); ``` -------------------------------- ### TuyAPI Device Control Methods Source: https://github.com/codetheweb/tuyapi/blob/master/README.md Outlines the core methods for interacting with Tuya devices. These include finding the device, establishing a connection, retrieving the current status, setting device properties, and disconnecting the session. ```APIDOC device.find(options) Finds the device on the network. Returns a Promise. device.connect(options) Connects to the device. Returns a Promise. device.get(options) Retrieves the current status of the device. Returns a Promise that resolves with the device status object. device.set(payload) Sets one or more properties (DPs) of the device. payload: Object - An object containing the properties to set. Example: { set: true, '101': 'white' } Returns a Promise. device.disconnect() Disconnects the current session with the device. ``` -------------------------------- ### Go Project for Decoding Tuya Device Traffic Source: https://github.com/codetheweb/tuyapi/blob/master/README.md A Go project designed to decode Tuya device traffic in real-time. ```go package main import ( "fmt" "github.com/py60800/tuyadump" ) func main() { // Example: Capture and decode traffic // tuyadump.CaptureTraffic() fmt.Println("Tuyadump started...") } ``` -------------------------------- ### Web Interface for Tuya Devices Source: https://github.com/codetheweb/tuyapi/blob/master/README.md A web-based interface for controlling Tuya devices, developed using TuyAPI. ```javascript const tuyaweb = require('tuyaweb'); // Usage would involve setting up a web server and integrating tuyaweb. ``` -------------------------------- ### Asynchronous Device Control with TuyAPI Source: https://github.com/codetheweb/tuyapi/blob/master/README.md Demonstrates the asynchronous, event-based approach to controlling Tuya devices. It covers finding the device, connecting, handling connection/disconnection events, errors, and receiving/sending data. This method is recommended for most use cases. ```javascript 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); ``` -------------------------------- ### Run Tests Source: https://github.com/codetheweb/tuyapi/blob/master/CONTRIBUTING.md Executes all tests for the TuyAPI project to ensure code quality and functionality. ```bash npm test ``` -------------------------------- ### Related Projects: Tuya Cloud Clients Source: https://github.com/codetheweb/tuyapi/blob/master/README.md This entry details projects that provide clients for interacting with Tuya's cloud services, allowing developers to manage Tuya devices and data through the cloud API. These clients abstract the complexities of cloud communication. ```APIDOC cloudtuya: Description: A client for Tuya's Cloud by unparagoned. Language: Python Repository: https://github.com/unparagoned/cloudtuya ``` -------------------------------- ### Node-RED Node for Tuya Smart Devices Source: https://github.com/codetheweb/tuyapi/blob/master/README.md A Node-RED node that provides extensive options for controlling Tuya devices, based on TuyAPI. ```javascript // Example flow configuration in Node-RED: // [{"id":"...","type":"tuya-smart-device","z":"...","name":"My Tuya Device","deviceid":"YOUR_DEVICE_ID","localKey":"YOUR_DEVICE_KEY","command":"set","payload":{"switch":true},"wires":[[...]]}] ``` -------------------------------- ### MQTT Interface for TuyAPI Source: https://github.com/codetheweb/tuyapi/blob/master/README.md A simple MQTT interface that utilizes TuyAPI for communication with Tuya devices. ```javascript const tuyaMqtt = require('tuya-mqtt'); // Example: Connect to MQTT and control a device // const mqttClient = tuyaMqtt.connect({ // mqttHost: 'localhost', // tuyaHost: 'YOUR_TUYA_HOST', // tuyaKey: 'YOUR_TUYA_KEY', // tuyaID: 'YOUR_TUYA_ID' // }); // mqttClient.publish('topic', JSON.stringify({ command: 'set', data: { switch: true } })); ``` -------------------------------- ### Luminea2MQTT Bridge Source: https://github.com/codetheweb/tuyapi/blob/master/README.md An expandable bridge for Luminea devices with Home Assistant Autodiscover, likely using TuyAPI. ```javascript // This project integrates Luminea devices with MQTT and Home Assistant. // Configuration would involve setting up MQTT connection details and device mappings. // Example configuration snippet (conceptual): // { // "mqtt": { // "url": "mqtt://localhost:1883", // "topicPrefix": "luminea" // }, // "devices": [ // { // "id": "YOUR_DEVICE_ID", // "key": "YOUR_DEVICE_KEY", // "name": "My Luminea Light" // } // ] // } ``` -------------------------------- ### Homebridge Plugin for Tuya Devices Source: https://github.com/codetheweb/tuyapi/blob/master/README.md A Homebridge plugin that enables control of Tuya devices within the HomeKit ecosystem. ```javascript const tuyaPlatform = require('homebridge-tuya'); // Configuration example in Homebridge config.json: // { // "platforms": [ // { // "platform": "TuyaPlatform", // "devices": [ // { // "name": "My Light", // "id": "YOUR_DEVICE_ID", // "key": "YOUR_DEVICE_KEY" // } // ] // } // ] // } ``` -------------------------------- ### Forcing Data Updates with TuyAPI Source: https://github.com/codetheweb/tuyapi/blob/master/README.md Shows how to handle devices that require explicit data refresh requests. The `issueRefreshOnConnect: true` option and the `dp-refresh` event listener are used to ensure data is updated, especially for newer firmware versions. ```javascript 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); ``` -------------------------------- ### Tuya API Reference Source: https://github.com/codetheweb/tuyapi/blob/master/docs/index.html API documentation for the Tuya library, detailing methods for device interaction and management. ```APIDOC refresh(options = {}): Promise Description: Refreshes the status of a Tuya device. Parameters: options (Object): Optional. Configuration for the refresh operation. schema (Boolean): If true, returns the entire list of properties from the device. dps (Number): DPS index to return. Defaults to 1. cid (String): If specified, use the device ID of the zigbee gateway and cid of the subdevice to refresh its status. requestedDPS (Array): Only set this if you know what you're doing. Defaults to [4,5,6,18,19,20]. Returns: Promise: An object containing the device status or data. set(options: Object): Promise Description: Sets a property on a Tuya device. Parameters: options (Object): Required. Options for setting the property. dps (Number): DPS index to set. Defaults to 1. set (any): The value to set for the property. cid (String): If specified, use the device ID of the zigbee gateway and cid of the subdevice to set its property. multiple (Boolean): Whether or not multiple properties should be set with options.data. Defaults to false. data (Object): Multiple properties to set at once. See options.multiple. shouldWaitForResponse (Boolean): Whether to wait for a response from the device. Defaults to true. Returns: Promise: The response from the device. connect(): Promise Description: Connects to the device. Can be called even if the device is already connected. Returns: Promise: true if the connection succeeds, false otherwise. disconnect(): void Description: Disconnects from the device, closing the socket and exiting gracefully. isConnected(): Boolean Description: Returns the current connection status to the device. Returns: Boolean: true if connected, false otherwise. find(options = {}): any Description: Finds an ID or IP, depending on what's missing. If you didn't pass an ID or IP to the constructor, you must call this before anything else. Parameters: options (Object): Optional. Parameters for finding the device. resolveId(options: any): any Description: Deprecated: since v3.0.0. Will be removed in v4.0.0. Use find() instead. ``` -------------------------------- ### TuyAPI Event Listeners Source: https://github.com/codetheweb/tuyapi/blob/master/README.md Describes the various events that can be listened to for managing device communication. These events provide feedback on connection status, data reception, errors, and specific device state changes like DP refreshes. ```APIDOC device.on(event, listener) Events: 'connected': Emitted when the device successfully connects. 'disconnected': Emitted when the device disconnects. 'error': Emitted when an error occurs during communication. 'data': Emitted when new data is received from the device. The data object contains the device's current state. 'dp-refresh': Emitted when a device explicitly refreshes its Data Points (DPs), often required for newer firmware. 'raw data': Emitted with the raw buffer data received from the device. ``` -------------------------------- ### Commit Changes Source: https://github.com/codetheweb/tuyapi/blob/master/CONTRIBUTING.md Stages and commits all changes with a descriptive message. ```bash git commit -a ``` -------------------------------- ### Related Projects: Tuya API Ports Source: https://github.com/codetheweb/tuyapi/blob/master/README.md This section lists various ports of the Tuya API to different programming languages, enabling developers to interact with Tuya devices using their preferred technology stack. These ports offer alternative implementations for functionalities provided by the original Tuya API. ```APIDOC TinyTuya: Description: A Python port by jasonacox and uzlonewolf. Language: Python Repository: https://github.com/jasonacox/tinytuya aiotuya: Description: A Python port by frawau. Language: Python Repository: https://github.com/frawau/aiotuya m4rcus.TuyaCore: Description: A .NET port by Marcus-L. Language: .NET Repository: https://github.com/Marcus-L/m4rcus.TuyaCore TuyaKit: Description: A .NET port by eppz. Language: .NET Repository: https://github.com/eppz/.NET.Library.TuyaKit py60800/tuya: Description: A Go port by py60800. Language: Go Repository: https://github.com/py60800/tuya rust-tuyapi: Description: A Rust port by EmilSodergren. Language: Rust Repository: https://github.com/EmilSodergren/rust-tuyapi GoTuya: Description: A Go port by Binozo. Language: Go Repository: https://github.com/Binozo/GoTuya ``` -------------------------------- ### Create a New Branch Source: https://github.com/codetheweb/tuyapi/blob/master/CONTRIBUTING.md Creates a new Git branch for development. Prefixes are recommended for feature or bugfix branches. ```bash git branch feature-contributing ``` -------------------------------- ### Trusting Root Certificate (iOS) Source: https://github.com/codetheweb/tuyapi/blob/master/docs/SETUP.md Instructions for trusting a root certificate on iOS devices, a necessary step for MITM proxying to capture traffic. ```APIDOC Trusting Root Certificate on iOS: 1. Install the root certificate provided by the proxy tool (e.g., AnyProxy). 2. Navigate to Settings > General > About > Certificate Trust Settings. 3. Enable full trust for the installed root certificate by toggling the switch next to its name. ``` -------------------------------- ### MessageParser API Documentation Source: https://github.com/codetheweb/tuyapi/blob/master/docs/index.html Documentation for the MessageParser class, including its constructor and instance methods for packet parsing and encoding. ```APIDOC MessageParser: __constructor(options?: object) Parses low-level packets for Tuya devices. Parameters: options (object, optional): Configuration options for the parser. key (string): The localKey for cipher operations. version (number, optional): The protocol version. Defaults to 3.1. Example: const parser = new MessageParser({key: 'xxxxxxxxxxxxxxxx', version: 3.1}) parsePacket(buffer: Buffer): Packet Parses a Buffer containing at least one complete packet at the beginning. Can return multiple packets if present. Parameters: buffer (Buffer): The data buffer to parse. Returns: Packet: The parsed packet data. getPayload(data: Buffer): object | string Attempts to decode a given payload into an object (if JSON) or a string. Parameters: data (Buffer): The payload buffer to decode. Returns: object | string: The decoded payload as an object or string. parse(buffer: Buffer): Array Parses a buffer that may contain multiple packets and returns all of them. Parameters: buffer (Buffer): The buffer containing potentially multiple packets. Returns: Array: An array of parsed packets. encode(options: object): Buffer Encodes a payload into a Tuya-protocol-compliant packet. Parameters: options (object): The data and settings for encoding. data (Buffer | string | object): The data to encode. encrypted (boolean): Whether to encrypt the data. commandByte (number): The command byte for the packet (use CommandType definitions). sequenceN (number, optional): The sequence number for the packet. Returns: Buffer: The encoded packet as a Buffer. ``` -------------------------------- ### Dimmer Light Switch Configuration Source: https://github.com/codetheweb/tuyapi/wiki/Device-Details Sample JSON configuration for a dimmer light switch. Replace placeholder values (XXXX, XXXXX, ) with actual device-specific information obtained from the device's data points (DPS). ```javascript { "name": "Outside Office", "id": "XXXX", "key": "XXXXX", "type": "dimmer", "options": { "dpsOn": , "dpsBright": , "minVal": , "maxVal": } } ``` -------------------------------- ### Fix Code Style Source: https://github.com/codetheweb/tuyapi/blob/master/CONTRIBUTING.md Automatically fixes most code style issues using the XO linter. ```bash npx xo --fix ``` -------------------------------- ### SIL Open Font License Version 1.1 Source: https://github.com/codetheweb/tuyapi/blob/master/docs/assets/fonts/LICENSE.txt The SIL Open Font License (OFL) allows free use, study, modification, and redistribution of font software, provided certain conditions are met. This includes not selling the font software by itself and retaining copyright notices and the license text. ```APIDOC SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 PREAMBLE The goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others. DEFINITIONS "Font Software" refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation. "Reserved Font Name" refers to any names specified as such after the copyright statement(s). "Original Version" refers to the collection of Font Software components as distributed by the Copyright Holder(s). "Modified Version" refers to any derivative made by adding to, deleting, or substituting -- in part or in whole -- any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment. "Author" refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software. PERMISSION & CONDITIONS Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions: 1) Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself. 2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user. 3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users. 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission. 5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software. TERMINATION This license becomes null and void if any of the above conditions are not met. DISCLAIMER THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE. ``` -------------------------------- ### Tuya Device Discovery Source: https://github.com/codetheweb/tuyapi/blob/master/docs/index.html Provides methods for discovering Tuya devices. `find()` is used to locate device IDs or IPs, especially when they are not provided during initialization. The `resolveId()` method is deprecated and should be replaced by `find()`. ```javascript // Find device details tuya.find({ /* options */ }).then(deviceInfo => console.log(deviceInfo)) // Deprecated: Resolve device ID // tuya.resolveId({ /* options */ }) ``` -------------------------------- ### Local Development Playground Source: https://github.com/codetheweb/tuyapi/blob/master/CONTRIBUTING.md A local file ignored by Git, useful for testing new code snippets during development. ```javascript // dev.js // Place your test code here ``` -------------------------------- ### Tuya Connection Management Source: https://github.com/codetheweb/tuyapi/blob/master/docs/index.html Manages the connection to a Tuya device. The `connect()` method establishes a connection, `disconnect()` closes it, and `isConnected()` checks the current connection status. `connect()` returns a Promise resolving to a boolean indicating success. ```javascript // Connect to the device tuya.connect().then(success => console.log('Connected:', success)) // Disconnect from the device tuya.disconnect() // Check connection status const connected = tuya.isConnected() console.log('Is connected:', connected) ``` -------------------------------- ### Find Tuya Devices Source: https://github.com/codetheweb/tuyapi/blob/master/docs/index.html Discovers Tuya devices on the network. It can be configured with a timeout and an option to return all found devices. Returns a Promise that resolves to a boolean or an array of devices. ```javascript tuya.find().then(() => console.log('ready!')) ``` -------------------------------- ### Create Pull Request Source: https://github.com/codetheweb/tuyapi/blob/master/CONTRIBUTING.md Opens a pull request to merge changes into the base master branch. This command is typically executed via the GitHub interface. ```bash https://github.com/codetheweb/tuyapi/compare ``` -------------------------------- ### Tuya Device Set Properties Source: https://github.com/codetheweb/tuyapi/blob/master/docs/index.html Sets properties on a Tuya device. This function can set a single property or multiple properties at once. It returns a Promise that resolves with the response from the device. Options include the DPS index, the value to set, and whether to wait for a response. ```javascript // set default property tuya.set({set: true}).then(() => console.log('device was turned on')) // set custom property tuya.set({dps: 2, set: false}).then(() => console.log('device was turned off')) // set multiple properties tuya.set({ multiple: true, data: { '1': true, '2': 'white' }}).then(() => console.log('device was changed')) // set custom property for a specific (virtual) deviceId tuya.set({ dps: 2, set: false, devId: '04314116cc50e346566e' }).then(() => console.log('device was turned off')) ``` -------------------------------- ### MessageParser Methods Source: https://github.com/codetheweb/tuyapi/blob/master/docs/index.html Utilities for parsing and encoding communication packets with Tuya devices. ```javascript class MessageParser { // Parse a raw packet parsePacket(packet: Buffer): any; // Get the payload from a parsed packet getPayload(parsedPacket: any): Buffer; // Parse a message parse(message: Buffer): any; // Encode a message encode(message: any): Buffer; } ``` -------------------------------- ### Dehumidifier Device Properties (DPS Mapping) Source: https://github.com/codetheweb/tuyapi/wiki/Device-Details Mapping of device properties to Data Point (DP) IDs for Eurom Drybest 30/40 dehumidifiers. This table helps in controlling and reading device states via the Tuya API. ```APIDOC Dehumidifier Properties (Eurom Drybest 30/40): - Model/Manufacturer: Eurom Drybest 30/40 - On/Off DPS: 1 - Mode DPS: 2 (1: dehumidify, 2: laundry, 3: fan) - Humidity measurement DPS: 3 - Humidity setting DPS: 4 (Range: >= 30, <= 80, Step: 5) - Fan speed DPS: 6 (1: low, 2: high) - Child lock DPS: 7 - Fan swing DPS: 8 - Water tank status DPS: 11 (0: ok, 1: tank full, 2: tank removed) - Timer DPS: 106 (Range: >= 0, <= 24, Step: 1) - Pump DPS: 107 - Defrosting DPS: 108 - Temperature measurement DPS: 110 ``` -------------------------------- ### Push Changes Source: https://github.com/codetheweb/tuyapi/blob/master/CONTRIBUTING.md Pushes the committed changes to the master branch of the remote repository. ```bash git push origin master ``` -------------------------------- ### Echo Request (Command 09) Source: https://github.com/codetheweb/tuyapi/wiki/TUYA-Commands An echo request command to test device communication. The device should echo the sent payload back. ```hex 000055aa00000000000000090000000c00000000b051ab030000aa55 ``` -------------------------------- ### Device Status Query (Command 08) Source: https://github.com/codetheweb/tuyapi/wiki/TUYA-Commands This command is used to query the current status of the Tuya device. No response is expected for this command. ```hex 000055aa00000000000000080000000c00000000000000000000aa55 ``` -------------------------------- ### TuyaDevice Events and Packet Structure Source: https://github.com/codetheweb/tuyapi/blob/master/docs/index.html Details the events emitted by a TuyaDevice instance and the structure of a received packet. Events include errors, connection status, heartbeats, data refreshes, and general data. The Packet structure includes payload, leftover bytes, command byte, and sequence number. ```APIDOC TuyaDevice#error Emitted on socket error, usually a result of a connection timeout. Also emitted on parsing errors. Properties: error (Error): error event TuyaDevice#connected Emitted when socket is connected to device. This event may be emitted multiple times within the same script, so don't use this as a trigger for your initialization code. TuyaDevice#heartbeat Emitted when a heartbeat ping is returned. TuyaDevice#dp-refresh Emitted when dp_refresh data is proactive returned from device, omitting dps 1 Only changed dps are returned. Properties: data (Object): received data commandByte (Number): commandByte of result( 8=proactive update from device) sequenceN (Number): the packet sequence number TuyaDevice#data Emitted when data is returned from device. Properties: data (Object): received data commandByte (Number): commandByte of result (e.g. 7=requested response, 8=proactive update from device) sequenceN (Number): the packet sequence number TuyaDevice#disconnected Emitted when a socket is disconnected from device. Not an exclusive event: `error` and `disconnected` may be emitted at the same time if, for example, the device goes off the network. Packet A complete packet. Type: Object Properties: payload (Buffer | Object | String): Buffer if hasn't been decoded, object or string if it has been leftover (Buffer): bytes adjacent to the parsed packet commandByte (Number) sequenceN (Number) ``` -------------------------------- ### TuyaCipher Methods Source: https://github.com/codetheweb/tuyapi/blob/master/docs/index.html Provides cryptographic functions for encrypting and decrypting data, including MD5 hashing. ```javascript class TuyaCipher { // Encrypt data using Tuya's algorithm encrypt(data: Buffer, key: Buffer): Buffer; // Decrypt data using Tuya's algorithm decrypt(data: Buffer, key: Buffer): Buffer; // Calculate the MD5 hash of data md5(data: string | Buffer): string; } ``` -------------------------------- ### SSID List Source: https://github.com/codetheweb/tuyapi/wiki/TUYA-Commands This command requests a list of available Wi-Fi network SSIDs detected by the device. ```json { ssid_list: [ 'TP-LINK_7F840E', 'BELL392', 'orangeblossom23_RE', 'Euvalyn', 'HP-Print-F4-Photosmart 6520', 'BELL674', 'killer' ] } ``` -------------------------------- ### Tuya Device Refresh Source: https://github.com/codetheweb/tuyapi/blob/master/docs/index.html Refreshes the status of a Tuya device. You can specify options to retrieve specific properties or the entire schema. Returns a Promise that resolves with the device status object. ```javascript // get first, default property from device tuya.refresh().then(status => console.log(status)) // get second property from device tuya.refresh({dps: 2}).then(status => console.log(status)) // get all available data from device tuya.refresh({schema: true}).then(data => console.log(data)) ``` -------------------------------- ### TuyaDevice Events Source: https://github.com/codetheweb/tuyapi/blob/master/docs/index.html Defines events emitted by the TuyaDevice class to signal various states and data changes. ```javascript enum TuyaDeviceEvents { ERROR = 'error', CONNECTED = 'connected', HEARTBEAT = 'heartbeat', DP_REFRESH = 'dp-refresh', DATA = 'data', DISCONNECTED = 'disconnected' } ``` -------------------------------- ### Tuya Device Properties Source: https://github.com/codetheweb/tuyapi/wiki/Communication-Details Devices have unique IDs (devId, gwId) and a JSON interface for managing properties via the 'dps' object. This object contains key-value pairs representing the device's state. ```javascript { dps: { '1': true, '2': 0 } } ``` -------------------------------- ### Toggle Device Property Source: https://github.com/codetheweb/tuyapi/blob/master/docs/index.html Toggles a boolean property of a Tuya device. It accepts an optional property number, defaulting to 1. Returns a Promise that resolves to a boolean indicating the new state. ```javascript toggle(property: Number = 1): Promise ``` -------------------------------- ### Tuya Network Packet Structure Source: https://github.com/codetheweb/tuyapi/wiki/Communication-Details Defines the structure of network packets used for communication with Tuya devices. Includes fields for prefix, sequence number, command, payload size, payload (containing return code for responses), CRC, and suffix. ```c { int32_t prefix; int32_t sequence; // pass a unique number to the device and it will be included in the response int32_t command; int32_t payloadSize; // byte count from this point forward char[] payload; // if receiving from the device, the first four bytes are the return code int32_t crc; // everything through the payload, be sure to include the prefix int32_t suffix; // essentially the marker to know that we can consider parsing another message } ``` -------------------------------- ### TuyaCipher Class Source: https://github.com/codetheweb/tuyapi/blob/master/docs/index.html Provides low-level encryption and decryption capabilities for Tuya payloads. It supports encrypting data to Buffer or Base64 string and decrypting data which can be returned as an object or string. It also includes a method for MD5 hashing. ```APIDOC TuyaCipher: __init__(options: {key: String, version: Number}) Initializes the TuyaCipher with a key and protocol version. - options.key: The localKey for the cipher. - options.version: The protocol version (e.g., 3.1). encrypt(options: {data: String, base64?: Boolean}): Buffer | String Encrypts the provided data. - options.data: The string data to encrypt. - options.base64: If true (default), returns a Base64 encoded string; otherwise, returns a Buffer. - Returns: Encrypted data as a Buffer or Base64 string. decrypt(data: String | Buffer): Object | String Decrypts the provided data. - data: The string or Buffer data to decrypt. - Returns: The decrypted data, as an object if it's JSON, otherwise as a string. md5(data: String): String Calculates the MD5 hash of the provided data. - data: The string to hash. - Returns: The middle 8 characters (8th to 16th) of the MD5 hash. ```