Project Icon

tinytuya

实现Tuya智能设备本地和云端控制的Python模块

TinyTuya是一个功能强大的Python模块,支持通过本地网络(LAN)或云端(TuyaCloud API)控制Tuya兼容的WiFi智能设备。该模块兼容Tuya协议3.1至3.5版本,能够直接操控设备而无需依赖云服务。TinyTuya集成了网络扫描和设置向导功能,简化了设备信息和本地密钥的获取过程。它适用于多种智能设备,包括插座、开关和灯泡等,并为开发者提供了丰富的编程接口。

TinyTuya

License PyPI version Build Test Contrib Test PyPI - Python Version PyPI Downloads

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.

TinyTuya Diagram

# 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:

  1. 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.

  2. 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.

  3. 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"
      1. Pick the correct Data Center "Region" for your location (check HERE to find your Region). This will be used by TinyTuya Wizard (screenshot).
      2. 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 and Authorization. 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)
  4. 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
    • 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 from tinytuya.deviceScan() or when running python -m tinytuya scan. The wizard also creates a local file tuya-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.

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 run tuya-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)
  
项目侧边栏1项目侧边栏2
推荐项目
Project Cover

豆包MarsCode

豆包 MarsCode 是一款革命性的编程助手,通过AI技术提供代码补全、单测生成、代码解释和智能问答等功能,支持100+编程语言,与主流编辑器无缝集成,显著提升开发效率和代码质量。

Project Cover

AI写歌

Suno AI是一个革命性的AI音乐创作平台,能在短短30秒内帮助用户创作出一首完整的歌曲。无论是寻找创作灵感还是需要快速制作音乐,Suno AI都是音乐爱好者和专业人士的理想选择。

Project Cover

有言AI

有言平台提供一站式AIGC视频创作解决方案,通过智能技术简化视频制作流程。无论是企业宣传还是个人分享,有言都能帮助用户快速、轻松地制作出专业级别的视频内容。

Project Cover

Kimi

Kimi AI助手提供多语言对话支持,能够阅读和理解用户上传的文件内容,解析网页信息,并结合搜索结果为用户提供详尽的答案。无论是日常咨询还是专业问题,Kimi都能以友好、专业的方式提供帮助。

Project Cover

阿里绘蛙

绘蛙是阿里巴巴集团推出的革命性AI电商营销平台。利用尖端人工智能技术,为商家提供一键生成商品图和营销文案的服务,显著提升内容创作效率和营销效果。适用于淘宝、天猫等电商平台,让商品第一时间被种草。

Project Cover

吐司

探索Tensor.Art平台的独特AI模型,免费访问各种图像生成与AI训练工具,从Stable Diffusion等基础模型开始,轻松实现创新图像生成。体验前沿的AI技术,推动个人和企业的创新发展。

Project Cover

SubCat字幕猫

SubCat字幕猫APP是一款创新的视频播放器,它将改变您观看视频的方式!SubCat结合了先进的人工智能技术,为您提供即时视频字幕翻译,无论是本地视频还是网络流媒体,让您轻松享受各种语言的内容。

Project Cover

美间AI

美间AI创意设计平台,利用前沿AI技术,为设计师和营销人员提供一站式设计解决方案。从智能海报到3D效果图,再到文案生成,美间让创意设计更简单、更高效。

Project Cover

AIWritePaper论文写作

AIWritePaper论文写作是一站式AI论文写作辅助工具,简化了选题、文献检索至论文撰写的整个过程。通过简单设定,平台可快速生成高质量论文大纲和全文,配合图表、参考文献等一应俱全,同时提供开题报告和答辩PPT等增值服务,保障数据安全,有效提升写作效率和论文质量。

投诉举报邮箱: service@vectorlightyear.com
@2024 懂AI·鲁ICP备2024100362号-6·鲁公网安备37021002001498号