TinyTuya
Python module to interface with Tuya WiFi smart devices
Description
This python module controls and reads state of Tuya compatible WiFi Smart Devices (Plugs, Switches, Lights, Window Covers, etc.) using the local area network (LAN) or the cloud (TuyaCloud API). This is a compatible replacement for the pytuya
PyPI module and currently supports Tuya Protocols 3.1, 3.2, 3.3, 3.4 and 3.5.
Tuya devices are designed to communicate with the TuyaCloud but most also expose a local area network API. This allows us to directly control the devices without using the cloud. This python module provides a way to poll status and issue commands to these devices.
TinyTuya can also connect to the Tuya Cloud to poll status and issue commands to Tuya devices.
# Example Usage of TinyTuya
import tinytuya
d = tinytuya.Device('DEVICE_ID_HERE', 'IP_ADDRESS_HERE', 'LOCAL_KEY_HERE', version=3.3)
data = d.status()
print('Device status: %r' % data)
NOTE: Devices need to be activated by Smart Life App.
TinyTuya Installation
# Install TinyTuya Library
python -m pip install tinytuya
# Optional: Install Command Line Tool
pipx install tinytuya
Pip will attempt to install cryptography
, requests
and colorama
if not already installed.
Tuya Device Preparation
Controlling and monitoring Tuya devices on your network requires the following:
- Address - Network address (IPv4) of the device e.g. 10.0.1.100
- Device ID - Unique identifier for the Tuya device
- Version - Tuya protocol version used (3.1, 3.2, 3.3, 3.4 or 3.5)
- Local_Key - Security key needed to access the Tuya device. See Setup Wizard to get these keys.
Network Scanner
TinyTuya has a built in network scanner that can be used to find Tuya Devices on your local network. It will show Address, Device ID and Version for each device. Your LAN and firewall will need to allow UDP (6666, 6667 and 7000) and TCP (6668) traffic.
python -m tinytuya scan
Setup Wizard - Getting Local Keys
TinyTuya has a built-in setup Wizard that uses the Tuya IoT Cloud Platform to generate a JSON list (devices.json) of all your registered devices, including secret Local_Key and Name of your devices. Follow the steps below:
-
PAIR - Download the Smart Life App or Tuya Smart App, available for iPhone or Android. Set up your SmartLife account and pair all of your Tuya devices (this is important as you cannot access a device that has not been paired). Do not use a 'guest' account, otherwise it will get deleted without confirmation at step 3.
-
SCAN (Optional) - Run the TinyTuya scan to get a list of Tuya devices on your network. It will show device Address, Device ID and Version number (3.x):
python -m tinytuya scan
NOTE: You will need to use one of the displayed Device IDs for step 4.
-
TUYA ACCOUNT - Set up a Tuya Account (see PDF Instructions):
- NOTE: Tuya often changes their portal and services. Please open an issue with screenshots if we need to update these instructions.
- Create a Tuya Developer account on iot.tuya.com. When it asks for the "Account Type", select "Skip this step..." (see screenshot).
- Click on "Cloud" icon -> "Create Cloud Project"
- Pick the correct Data Center "Region" for your location (check HERE to find your Region). This will be used by TinyTuya Wizard (screenshot).
- Skip the configuration wizard but remember the Authorization Key: API ID and Secret for below (screenshot).
- Click on "Cloud" icon -> Select your project -> Devices -> Link Tuya App Account (see screenshot)
- Click Add App Account (screenshot) and it will pop-up a "Link Tuya App Account" dialog, chose "Automatic" and "Read Only Status" (it will still alow commands). Click OK and it will display a QR code. Scan the QR code with the Smart Life app on your Phone (see step 1 above) by going to the "Me" tab in the Smart Life app and clicking on the QR code button
[..]
in the upper right hand corner of the app. When you scan the QR code, it will link all of the devices registered in your Smart Life app into your Tuya IoT project. If the QR code will not scan then make sure to disable any browser theming plug-ins (such as Dark Reader) and try again. - NO DEVICES? If no devices show up after scanning the QR code, you will need to select a different data center and edit your project (or create a new one) until you see your paired devices from the Smart Life App show up. (screenshot). The data center may not be the most logical. As an example, some in the UK have reported needing to select "Central Europe" instead of "Western Europe".
- SERVICE API: Under "Service API" ensure these APIs are listed:
IoT Core
andAuthorization
. To be sure, click subscribe again on every service. Very important: disable popup blockers otherwise subscribing won't work without providing any indication of a failure. Make sure you authorize your Project to use those APIs:- Click "Service API" tab
- Click "Go to Authorize" button
- Select the API Groups from the dropdown and click
Subscribe
(screenshot)
-
WIZARD - Run Setup Wizard:
- From your Linux/Mac/Win PC run the TinyTuya Setup Wizard to fetch the Local_Keys for all of your registered devices:
python -m tinytuya wizard # use -nocolor for non-ANSI-color terminals
- The Wizard will prompt you for the API ID key, API Secret, API Region (cn, us, us-e, eu, eu-w, or in) from your Tuya IoT project as set in Step 3 above.
- To find those again, go to iot.tuya.com, choose your project and click
Overview
- API Key: Access ID/Client ID
- API Secret: Access Secret/Client Secret
- To find those again, go to iot.tuya.com, choose your project and click
- It will also ask for a sample Device ID. You can have the wizard scan for one (enter
scan
), use one from step 2 above or in the Device List on your Tuya IoT project. - The Wizard will poll the Tuya IoT Cloud Platform and print a JSON list of all your registered devices with the "name", "id" and "key" of your registered device(s). The "key"s in this list are the Devices' Local_Key you will use to access your device.
- In addition to displaying the list of devices, Wizard will create a local file
devices.json
that TinyTuya will use to provide additional details for scan results fromtinytuya.deviceScan()
or when runningpython -m tinytuya scan
. The wizard also creates a local filetuya-raw.json
that contains the entire payload from Tuya Cloud. - The Wizard will ask if you want to poll all the devices. If you do, it will display the status of all devices on record and create a
snapshot.json
file with these results. Make sure your LAN and firewall permit UDP (6666, 6667 and 7000) and TCP (6668) traffic.
- From your Linux/Mac/Win PC run the TinyTuya Setup Wizard to fetch the Local_Keys for all of your registered devices:
Notes:
- If you ever reset or re-pair your smart devices, the Local_Key will be reset and you will need to repeat the steps above.
- The TinyTuya Wizard was inspired by the TuyAPI CLI which is an alternative way to fetch the Local_Keys:
npm i @tuyapi/cli -g
and runtuya-cli wizard
Programming with TinyTuya
After importing tinytuya, you create a device handle for the device you want to read or control. Here is an example for a Tuya smart switch or plug:
import tinytuya
# Connect to Device
d = tinytuya.OutletDevice(
dev_id='DEVICE_ID_HERE',
address='IP_ADDRESS_HERE', # Or set to 'Auto' to auto-discover IP address
local_key='LOCAL_KEY_HERE',
version=3.3)
# Get Status
data = d.status()
print('set_status() result %r' % data)
# Turn On
d.turn_on()
# Turn Off
d.turn_off()
TinyTuya Module Classes and Functions
Classes
AESCipher - Cryptography Helpers
XenonDevice(args...) - Base Class
Device(args...) - Tuya Class for Devices
OutletDevice(args...)
CoverDevice(args...)
BulbDevice(args...)
Where args:
dev_id (str): Device ID e.g. 01234567891234567890
address (str): Device Network IP Address e.g. 10.0.1.99 or "Auto" to auto-find
local_key (str): The encryption key
dev_type (str): Device type for payload options (see below)
version = 3.1 (float): Tuya Protocol (e.g. 3.1, 3.2, 3.3, 3.4, 3.5)
persist = False (bool): Keep TCP link open
cid = None (str): Optional sub device id
node_id = None (str): Alias for cid
parent = None (object): Gateway device object this is a child of
port = TCPPORT (int): The port to connect to device
connection_timeout = 5 (int): Timeout in seconds
connection_retry_limit = 5 (int)
connection_retry_delay = 5 (int)
Total timeout = (connection_timeout * connection_retry_limit) +
(connection_retry_delay * (connection_retry_limit - 1))
Defaults: (5 * 5) + (5 * (5 - 1)) = 45 seconds
Cloud(apiRegion, apiKey, apiSecret, apiDeviceID, new_sign_algorithm)
TinyTuya Base Functions
devices = deviceScan() # Returns dictionary of devices found on local network
scan() # Interactive scan of local network
wizard() # Interactive setup wizard
set_debug(toggle, color) # Activate verbose debugging output
pack_message(msg, hmac_key) # Packs a TuyaMessage(), encrypting or adding a CRC if required
unpack_message(data, hmac_key, header,
no_retcode) # Unpacks a TuyaMessage()
parse_header(data) # Unpacks just the header part of a message into a TuyaHeader()
find_device(dev_id, address) # Scans network for Tuya devices with either ID = dev_id or IP = address
device_info(dev_id) # Searches DEVICEFILE (usually devices.json) for device with ID
assign_dp_mappings(tuyadevices, mappings) # Adds mappings to all the devices in the tuyadevices list
decrypt_udp(msg) # Decrypts a UDP network broadcast packet
Device Functions (All Devices)
json = status() # returns json payload
subdev_query(nowait) # query sub-device status (only for gateway devices)
set_version(version) # 3.1 [default], 3.2, 3.3 or 3.4
set_socketPersistent(False/True) # False [default] or True
set_socketNODELAY(False/True) # False or True [default]
set_socketRetryLimit(integer) # retry count limit [default 5]
set_socketRetryDelay(integer) # retry delay [default 5]
set_socketTimeout(timeout) # set connection timeout in seconds [default 5]
set_dpsUsed(dps_to_request) # add data points (DPS) to request
add_dps_to_request(index) # add data point (DPS) index set to None
set_retry(retry=True) # retry if response payload is truncated
set_status(on, switch=1, nowait) # Set status of switch to 'on' or 'off' (bool)
set_value(index, value, nowait) # Set int value of any index.
set_multiple_values(index_value_dict, nowait) # Set multiple values with a single request
heartbeat(nowait) # Send heartbeat to device
updatedps(index=[1], nowait) # Send updatedps command to device
turn_on(switch=1, nowait) # Turn on device / switch #
turn_off(switch=1, nowait) # Turn off
set_timer(num_secs, nowait) # Set timer for num_secs
set_sendWait(num_secs) # Time to wait after sending commands before pulling response
detect_available_dps() # Return list of DPS available from device
generate_payload(command, data,... # Generate TuyaMessage payload for command with data
send(payload) # Send payload to device (do not wait for response)
receive() # Receive payload from device
OutletDevice Additional Functions
set_dimmer(percentage):
BulbDevice Additional Functions
set_colour(r, g, b, nowait):
set_hsv(h, s, v, nowait):
set_white(brightness, colourtemp, nowait):
set_white_percentage(brightness=100, colourtemp=0, nowait):
set_brightness(brightness, nowait):
set_brightness_percentage(brightness=100, nowait):
set_colourtemp(colourtemp, nowait):
set_colourtemp_percentage(colourtemp=100, nowait):
set_scene(scene, nowait): # 1=nature, 3=rave, 4=rainbow
set_mode(mode='white', nowait): # white, colour, scene, music
result = brightness():
result = colourtemp():
(r, g, b) = colour_rgb():
(h,s,v) = colour_hsv()
result = state():
CoverDevice Additional Functions
open_cover(switch=1):
close_cover(switch=1):
stop_cover(switch=1):
Cloud Functions
setregion(apiRegion)
cloudrequest(url, action=[POST if post else GET], post={}, query={})
getdevices(verbose=False)
getstatus(deviceid)
getfunctions(deviceid)
getproperties(deviceid)
getdps(deviceid)