logo elektroda
logo elektroda
X
logo elektroda

How to Perform HTTP Requests on Tuya Devices

User question

how do http request on tuya device

Artificial Intelligence Response

Direct answer to the question

• Tuya products do not expose a public REST server on the LAN.
• To “do HTTP requests on a Tuya device” you therefore have three practical options:

  1. Use the Tuya Cloud OpenAPI (official / supported) – you send signed HTTPS requests to Tuya’s regional cloud; the cloud relays commands to the device.
  2. Use reverse-engineered local control – obtain the device’s _localkey and talk to it over TCP port 6668 with AES encryption (libraries such as tinytuya, tuyapi, localtuya wrap the protocol; you still do not use plain HTTP).
  3. Replace the Tuya firmware with open-source firmware (Tasmota, ESPHome, OpenBeken). After flashing, the module does offer a real HTTP/REST interface on the LAN.

Plain, unauthenticated HTTP to a stock Tuya device is therefore not possible; you either go through the cloud or change the firmware.


Detailed problem analysis

  1. Tuya communication architecture
    • Device boots → establishes an MQTT/TCP session to Tuya’s regional cloud (UDP 6669 during pairing, then TCP 6668/8886).
    • Mobile app / your server → HTTPS REST (OpenAPI) → Tuya cloud → encrypted MQTT → device.
    • There is no built-in web server in factory firmware.

  2. Official Tuya Cloud OpenAPI workflow (HTTP to the cloud)

    a. Create Developer Account → Cloud Project (https://iot.tuya.com).
    b. Note Access ID (client_id) & Access Secret (client_secret); bind your end-user account (QR-scan) so your devices appear in the project.
    c. Authentication – get OAuth2 token (grant_type = 1):

     POST https://openapi.tuya{region}.com/v1.0/token?grant_type=1
    Headers:
    client_id: <ID>
    sign: <HMAC-SHA256>
    t: <milliseconds>
    sign_method: HMAC-SHA256

    Response ⇒ access_token (≈2 h) + refresh_token (≈30 d).

    d. Send device command (example: turn switch_1 ON):

     POST /v1.0/devices/{device_id}/commands
    Body:
    {
    "commands":[{"code":"switch_1","value":true}]
    }

    Required headers: client_id, access_token, t, sign, sign_method.
    Signature string (v1.0):

     sign = HMAC_SHA256(
    client_id + access_token + t + // header part
    HTTP_METHOD + // "POST"
    SHA256(JSON_body) + // lowercase hex
    URL // full path incl. query
    , client_secret)

    e. Region base URLs
    • China: openapi.tuyacn.com
    • West US: openapi.tuyaus.com
    • East US (data-center-us-e): openapi-us-e.tuyaus.com
    • Europe: openapi.tuyaeu.com
    • India: openapi-in.tuyacn.com

  3. Local (LAN) control without flashing

    a. Requirements
    – Device must use “old” Tuya Wi-Fi module (BK7231T/N, ESP8266-based TYWE3S etc.) and allow retrieval of _localkey (via Tuya IoT Portal → “Device Details” → “Key” or Cloud API query).
    – Firmware ≥3.4 still supports LAN protocol 3.3/3.5. Tuya has begun disabling it on brand-new releases, so YMMV.

    b. Protocol specifics
    • Unicast TCP 6668 (JSON payload encrypted with AES-ECB / PKCS7 using local_key)
    • Message = 4-byte header + length + command ID (0x07=control, 0x0a=status) + encrypted JSON.
    • Not RESTful; no HTTP headers.

    c. Helpful libraries / tools
    • Python tinytuya, Node @codetheweb/tuyapi, Home-Assistant localtuya.
    • Sample Python snippet (tinytuya):

     import tinytuya
    d = tinytuya.Device(DEVICE_ID, DEVICE_IP, LOCAL_KEY)
    d.set_version(3.3)
    d.set_socketPersistent(True)
    d.set_socketRetryLimit(3)
    print(d.status()) # query
    d.set_value('switch_1', True) # turn on

    • Traffic stays on your LAN; no Tuya cloud needed once key is known.

  4. Flashing custom firmware (HTTP truly “on device”)

    • If you absolutely need straight HTTP/REST, re-flash.
    tuya-convert (OTA exploit) rarely works since 2021; today you often must open the device and use a 3.3 V USB-TTL to flash.
    • After flashing Tasmota:

     # Turn relay ON
    GET http://<ip>/cm?cmnd=Power%20On
    # Query status
    GET http://<ip>/cm?cmnd=Status%200

    • ESPHome exposes REST and native Home-Assistant API as well.
    • Firmware replacement voids warranty and can brick the product if done improperly.


Current information and trends

• 2023-24: Tuya released OpenAPI v2.0 (RESTful + WebSocket). SDKs (tuya-iot-py-sdk, tuya-iot-cpp-sdk) now abstract signing and token handling.
• LAN protocol 3.3 is being phased out on some new “cube” modules; Tuya encourages edge-gateway or Matter/Wi-Fi modules.
• Matter-over-Wi-Fi/Tuya has appeared; those devices expose standard Matter clusters locally (but not HTTP).
• Rate limits: free Cloud Project ⇒ 1 000 req/day, 10 QPS burst. Paid tiers increase this.


Supporting explanations and details

• Why no HTTP on stock firmware?
– Code space is minimal (BK7231 ~2 MB flash). MQTT over TLS is lighter than embedding an HTTP server with TLS stack, and central cloud control simplifies OEM management.

• Signature rationale: avoids sending client_secret over the wire; prevents replay (timestamp) and substitution (HMAC).

• Error codes (Cloud): 1010 wrong sign, 1011 token expired, 2406 permission deny, 28841005 rate limit, 5000 system busy.


Ethical and legal aspects

• Cloud API use is covered by Tuya IoT Platform ToS – commercial deployments require paid plan/licence.
• Reverse-engineering LAN protocol is tolerated by Tuya but not officially supported. Ensure GDPR/CCPA compliance if you store user tokens/keys.
• Flashing firmware voids CE/FCC conformity; ensure the modified device remains electrically safe.


Practical guidelines / best practices

  1. Use official Cloud API when: you need remote access, firmware updates, guaranteed compatibility.
  2. Cache access_token, refresh proactively (≈1 h before expiry).
  3. Batch commands when possible (/commands supports up to 10 DPs) to stay below rate limits.
  4. For LAN control: reserve static DHCP IPs; monitor TCP 6668 availability; fall back to cloud if LAN offline.
  5. Secure secrets – store local_key and client_secret in an encrypted vault (e.g., HashiCorp Vault, AWS KMS).
  6. Testing: Tuya Developer Platform offers a built-in API Explorer and Postman environment JSON; use these to validate signatures.

Possible disclaimers / additional notes

• Not every device exposes its _localkey in the portal— some OEM-bound devices hide it.
• Tuya can disable LAN control in future firmware; plan for graceful degradation.
• Edge cases (battery devices, BLE-Wi-Fi gateways) use different transport; approach differs.


Suggestions for further research

• Investigate Tuya Edge Gateway SDK – allows LAN control via WebSocket without cloud round-trip.
• Monitor Tuya’s Matter roadmap; Matter may provide a standard local API.
• Explore OTA patching methods for new BK7231N/BK7231Z devices (OpenBeken).
• Compare with other ecosystems (Shelly, Aqara) for local HTTP vs. cloud trade-offs.


Brief summary

A stock Tuya device cannot be driven by simple LAN HTTP calls. You either:

  1. Send authenticated HTTPS requests to Tuya Cloud (official, secure, but cloud-dependent).
  2. Use the reverse-engineered LAN protocol with the device’s _localkey (no HTTP, but fully local).
  3. Flash alternative firmware (Tasmota/ESPHome) to gain a true REST interface.

Choose the route that best matches your reliability, latency, security, and maintenance requirements.

Ask additional question

Wait...(2min)
Disclaimer: The responses provided by artificial intelligence (language model) may be inaccurate and misleading. Elektroda is not responsible for the accuracy, reliability, or completeness of the presented information. All responses should be verified by the user.