Search code examples
pythonsdkiottuya

Tuya python script doesn't connect. Error 501


When I'm trying to connect to tuya api using tuya_iot library, I get a generic error that says nothing.

I tried this:

from tuya_iot import TuyaOpenAPI, TUYA_LOGGER
import logging

TUYA_LOGGER.setLevel(logging.DEBUG)

# Cloud project authorization info
ACCESS_ID = 'mysuperID'
ACCESS_KEY = 'mysuperSecretKey'

# For more info, refer to: https://developer.tuya.com/en/docs/iot/api-request?id=Ka4a8uuo1j4t4
ENDPOINT = "https://openapi.tuyaus.com" # Western America Data Center

# Project configuration
USERNAME = '[email protected]'
PASSWORD = 'thePassword of Tuya'

# Initialization of tuya openapi
openapi = TuyaOpenAPI(ENDPOINT, ACCESS_ID, ACCESS_KEY)
openapi.connect(USERNAME, PASSWORD)

And I got this:

[2023-11-13 18:44:47,778] [tuya-openapi] Request: method = POST,                 url = https://openapi.tuyaus.com/v1.0/iot-01/associated-users/actions/authorized-login,                params = None,                body = {'username': '[email protected]', 'password': '***', 'country_code': '', 'schema': ''},                t = 1699911887778
[2023-11-13 18:44:48,694] [tuya-openapi] Response: {
  "code": 501,
  "msg": "request fail with unkown error",
  "success": false,
  "t": 1699911889502,
  "tid": "debb0af0826d11ee8088063dea7c5c23"
}

But I was hoping to get a successful connection.


Solution

  • After some more research I find out this library which is simpler to use and easier overall. TinyTuya

    import tinytuya
    
    # Tuya connection
    tuya_api_endpoint = os.getenv('TUYA_API_ENDPOINT')
    tuya_access_id = os.getenv('TUYA_ACCESS_ID')
    tuya_access_key = os.getenv('TUYA_ACCESS_KEY')
    
    # Connecto to Tuya API
    tuya_cloud = tinytuya.Cloud(apiRegion = tuya_api_endpoint, apiKey = tuya_access_id, apiSecret = tuya_access_key)
    # API_ENDPOINT: cn, us, us-e, eu, eu-w, or in. Options based on tinytuya python library
    

    And using this one is easier to connect to the Tuya API, as the functions are really straight forward and have great documentation.