AUDIO

Listen to this page

0:00
Chapters

    tuya — smart devices from the Tuya ecosystem

    A pre-built plugin that connects Tuya ecosystem devices (Tuya Smart / Smart Life app: lights, sockets, switches, blinds/curtains, fans, air conditioners, locks, sirens, purifiers …) to holai: the Tuya IoT cloud is the brains, and the plugin speaks both of Tuya's channels — the signed OpenAPI (project credentials) and the sharing app-link channel (QR bind via the Tuya app). It ships a DP-code mapper, a device cache, scene links and a status poller.

    Single house account

    This is a house-level integration: after the bind, one Tuya app account is linked and every device of that account is visible to whoever passes the tool's role/scope gate. There is no per-person identity layer — the app account owns the whole home.

    Two ways in

    • QR app linking — enter the user code of your Tuya Smart / Smart Life app (app → Me → ⚙ → Account and Security → User Code, at the bottom), press Generate QR, and scan the code with the app (+ → Scan). Behind this is Tuya's shared login channel (client HA_3y9q4ak7g4ephrvke, schema haauthorize, overridable through the TUYA_QR_CLIENT_ID / TUYA_QR_SCHEMA env variables): the scan returns uid, endpoint and a sharing token set, and the plugin then speaks Tuya's sharing transport (AES-GCM-encrypted payloads with HMAC header signing) — no IoT project on iot.tuya.com is needed at all. Devices that support LAN control can additionally be switched to direct local-network control (see "Local LAN mode" below), so they keep working without internet.
    • Project credentials — access id + secret from your own cloud project plus the linked app account's uid (the classic route below). One reason to prefer it: full raw DP access may differ between the channels, and only project credentials pair with your own API keys.

    The active mode appears on the plugin page ({mode: 'qr' | 'project'}); a QR unlink restores project credentials as the data path.

    Local LAN mode (tinytuya-style)

    Devices that support LAN control can be driven directly over the local network — the same tinytuya/tuya-local approach: TCP port 6668, AES-ECB (protocol 3.1–3.4) or AES-GCM (3.5) with the device's local_key, the 3.4/3.5 session-key handshake and CRC32/HMAC/GCM integrity per protocol revision. What each device needs:

    • local_key — comes from the cloud device list (project mode carries it; the QR sharing channel usually does not, so local mode is a project-credentials feature unless the key was stored earlier).
    • The device on the same network as the server and LAN control enabled in the Tuya app (device settings → Device Update / LAN control). Protocol 3.5 devices that need a 3.5 handshake are supported; battery-only Zigbee end devices behind a hub are not.
    • Which devices qualify — the catalog at make-all/tuya-local DEVICES.md (~1500 models: heaters, ACs, thermostats, fans, purifiers, appliances, meters/breakers, plugs, wall switches, lighting, covers, vacuums, locks, sirens, doorbells, alarm panels, valves …) is the reference; holai decides per device by actually probing it (the dry run), so anything that answers over the LAN works, list or no list.

    Per-device flow on the plugin page (dry run → toggle, fully reversible):

    1. Scan LAN — UDP broadcasts (6666/6667) plus a TCP sweep of the local /24 on port 6668; the sweep is what works from a Docker bridge (broadcasts from the LAN never arrive there). Candidates come from the cloud device list; the found IP + protocol version are stored.
    2. Test (dry run) — reads the device's status over the LAN with the stored local_key and builds the DP map (cloud DP code → local numeric dp id) from the cloud specifications (v1.1 …/specifications carries dp_id); when it doesn't, an exact value match between the cloud status and the live local status resolves unambiguous codes (multi-relay strips with equal values may stay cloud-only).
    3. Use LAN / Back to cloud — the toggle. Enabling re-probes the device first; the device then gets the green LAN chip and all of its control/status/value/history traffic goes local-first with the cloud as automatic fallback on any LAN failure. Forget removes the stored configuration.

    Availability: the device cache is kept when the cloud is unreachable, so LAN-mode devices stay controllable and their status/history keeps sampling without internet; everything (including the LAN toggle and the consent gate for actuation) is unchanged for the voice assistant — control simply answers faster and works offline.

    Routes (admin): GET /local (per-device state + detected subnets), POST /local/scan ({subnet?} — default LAN_SUBNET env, else the server's own /24), POST /local/test ({id, ip?} — the dry run), PUT /local/:id ({enabled}), DELETE /local/:id.

    How it works

    • Credentials: accessId/accessSecret/uid/region (project mode) live in ctx.sqlStore, env vars TUYA_ACCESS_ID, TUYA_ACCESS_SECRET, TUYA_USER_ID, TUYA_REGION work as defaults (store wins); TUYA_BASE_URL and TUYA_QR_BASE override the endpoints (used by the offline test).
    • Tokens: GET /v1.0/token?grant_type=1, refreshed via grant_type=3
      • refresh token before expiry, re-requested on a cloud 401. Request signing follows the OpenAPI rules: HMAC-SHA256 over client_id + access_token + t (+ MD5 of the JSON body for POST/PUT).
    • Refresh loop: every 60 s the token and the device cache are refreshed; anything changed by holai publishes tuya.device to the event bus.
    • Device data: project mode GET /v1.0/users/{uid}/devices; QR mode the sharing SDK paths (/v1.0/m/life/users/homes → /v1.0/m/life/ha/home/devices, per-device /v1.1/m/life/:id/specifications fetched lazily for control). Both are cached (status flattened to DP codes); control posts mapped DP commands (/v1.0/devices/:id/commands / /v1.1/m/thing/:id/commands).
    • Scenes: the home's GET /v1.0/homes/{home_id}/scenes (the first home of the account unless homeId is configured in the UI) with POST .../trigger.

    Setup

    1. Install the plugin (local folder server/plugins/tuya/; restart the core so the loader picks it up).
    2. Preferred, QR: on the plugin page enter the app user code (see "Two ways in") → Generate QR → scan with the app → the page switches to linked state, list and control go live. The scan token lives for ~24 h and is refreshed by the plugin automatically.
    3. Alternative, project credentials: register on iot.tuya.com (free tier is enough for personal homes), create a Cloud project (any name, industry "Smart Home"), note the Client ID and Client secret; in the project open Devices → Linked Tuya-App Accounts and link the account of your "Tuya Smart"/"Smart Life" app (scan the generated QR with your app, or copy the Member/uid value); fill the credentials panel and press Test.
    4. Without any link the everything degrades to actionable hints with the exact missing step, instead of failing.

    Admin page (#/pui/tuya)

    • QR app linking (the primary panel) — user code input, Generate QR renders the tuyaSmart--qrLogin code, an automatic poll switches to "linked as ..." once the app confirmed; Unlink expires the sharing terminal and returns to project mode.
    • Credentials (admin) — collapsed by default for the QR-first flow (experts unfold it): client id, client secret (write-only, stored masked afterwards), uid, region select + optional custom endpoint + preferred home; Test verifies the sign/token path and counts reachable devices. A project-mode-only install unfolds the panel automatically.
    • Devices — a grid of cards (rooms-wide filter box + a "show offline" toggle): a real on/off switch for every switchable device (switch_led/switch_1..6/power), brightness and blind-position sliders, open/close + lock/unlock buttons, fan speed buttons, ±1° temperature controls, live sensor readouts (temperature, humidity, power, voltage, battery, …) as card lines, a per-device raw-DP details view and a global refresh; auto-refresh every 15 s. DP codes render with human-readable labels (switch, brightness, colour temperature, energy meters, calibration coefficients, ambient sensors …) following Tuya's standard DP-code sets; codes without a mapping stay raw. Clicking a card name renames the device inline (✓ saves the local alias, ✕/Esc cancels; an empty input resets to the app's own name) — the alias is what the voice assistant and the search match on. The card's chart icon opens the history chart (see below). Devices with a local-mode configuration show a LAN chip on the card (green = LAN mode active) that opens the local-mode modal: dry run (optionally with a manually entered IP), Use LAN / Back to cloud, Forget. Below the device grid sits the Local LAN mode panel (admin only) with the Scan LAN button and an optional subnet input.

    History and charts

    Every 5 minutes the plugin samples the fresh numeric DP values of every online device (project and QR modes alike) into the central db — one plugin store row per device and day, pruned after 370 days (a year of charts). Calibration-style DPs land there too (voltage_coe, electric_coe, power_coe, electricity_coe — the meters' own constants, handy to interpret the raw readings of e.g. a 63 A smart circuit breaker).

    Each card's chart icon opens a modal for that device:

    • Data point — any numeric DP the device reported (power, add_ele, coefficients, …; power is the default pick).
    • Predefined periods — 7 days / last month / 3 months / 6 months / last year, or a custom date range.
    • Interval — auto (15 min → 1 day depending on the span) or fixed 5 / 15 / 30 / 60 minutes, 1 day, 1 month.
    • The chart draws the averaged series plus a dashed cumulative line: for power-type DPs it integrates the buckets into energy (kWh shown as period total), for accumulating meters (add_ele, …) it clamps meter resets and sums the deltas, for plain sensors it shows a running sum. Min/avg/max of the period stand in the header row.

    History route: GET /device/:id/history?from=&to=&bucket=&code= returns {code, kind (power|counter|sensor), series, cumulative, total, min, avg, max, bucketMs, sampleCount, codes} — empty: true with the known codes once nothing landed in the window yet (e.g. right after installing the plugin: the sampler fills from now on).

    • Scenes — scene links of the configured home with a trigger button.

    The tuya tool

    POST /api/v1/tools/tuya (roles user+; scopes devices:tuya:read / devices:tuya:write; guests cannot use the tool — as in holai's other device scopes, kid tokens need the admin's scope grant):

    action args what
    devices optional query list of devices with type, online state and flattened status (filtered by name when query given)
    value device, optional reading (temperature/humidity/voltage/current/power/energy/illuminance/battery), dpCode read the sensor values of one device and answer in plain words — "what is the temperature in the kitchen?" style questions: the assistant matches the device (room) name, the readings are spoken in real units (°C/%RH, V/A/W; scaled sensor ints already converted). power answers the consumption right now (W, scaled by the device spec); energy answers the accumulated meter counter (raw — converting it to kWh needs the device's own _coe calibration coefficients); when one of the two families is missing the tool answers from the other with honest wording instead of inventing a unit
    control device, command, optional value, outlet (multi-socket strips 1–6) switch a device by (fuzzy-matched) name: on, off, toggle, brightness (0–100), color_temp (0–100), color ("h,s,v"), position (0–100, covers), speed (fan: low/medium/high), temp (°C, air), mode (air/fan mode), lock/unlock, open/close
    status device full device detail incl. raw DP code/value list
    scenes — scene links of the home (name + enabled)
    trigger sceneId run a scene link
    dp device, dpCode, dpValue raw DP-code write for unmapped devices (admin-only)

    The agent's typical flow: devices {query:"bedroom"} → control {device:"bedroom light", command:"off"}. Ambiguous names return the closest device names in the error so the voice follow-up question works. For sensor questions the flow is simply value {device:"kitchen"} — the reply text is what the assistant speaks; the Ollama provider answers this with the same one-tool decision as the other providers, and the keyword matcher falls back to value automatically when a device name is present without an explicit action.

    Devices without a recognized DP set are still listed (type other) — status shows their raw codes for the dp action.

    Routes (plugin page backend)

    Method/Path Role What
    GET /api/v1/plugins/tuya/config admin masked credentials + resolved endpoint/home
    PUT /api/v1/plugins/tuya/config admin save {accessId, accessSecret, uid, region, baseUrl?, homeId?} — empty accessSecret keeps the stored one
    DELETE /api/v1/plugins/tuya/config admin remove stored credentials
    POST /api/v1/plugins/tuya/qr-link admin {userCode} → create a pending QR binding (login channel token)
    GET /api/v1/plugins/tuya/qr-svg admin the pending QR as SVG (tuyaSmart--qrLogin?token=…)
    GET /api/v1/plugins/tuya/qr-status admin poll the pending binding; once the app scanned it, stores the sharing token info and reports bound
    DELETE /api/v1/plugins/tuya/qr-link admin expire the sharing terminal and unlink
    GET /api/v1/plugins/tuya/test admin real auth + device-list probe (counts devices, reports mistakes)
    GET /api/v1/plugins/tuya/devices user fresh device list with flattened status
    GET /api/v1/plugins/tuya/device/:id user detail incl. raw DP codes
    GET /api/v1/plugins/tuya/device/:id/history user chart series: from/to/bucket/code, aggregated + cumulative + period total
    POST /api/v1/plugins/tuya/control user mapped control {device, command, value?, outlet?} (the same path the quick buttons use)
    PUT /api/v1/plugins/tuya/device/:id/name user store/remove the local alias for a device ({name}; empty = back to the app's own name)
    POST /api/v1/plugins/tuya/refresh user drop the cache and refetch
    POST /api/v1/plugins/tuya/device/:id/commands admin raw DP commands [{code,value}]
    GET /api/v1/plugins/tuya/scenes user scenes of the home
    POST /api/v1/plugins/tuya/scene/:id/trigger user run a scene (publishes tuya.scene)
    GET /api/v1/plugins/tuya/local admin per-device local-mode state + detected subnets
    POST /api/v1/plugins/tuya/local/scan admin discover LAN devices ({subnet?}) — UDP broadcast + TCP sweep of the /24
    POST /api/v1/plugins/tuya/local/test admin dry run {id, ip?} — probe the device over the LAN and build the DP map
    PUT /api/v1/plugins/tuya/local/:id admin toggle {enabled} (re-probes before enabling)
    DELETE /api/v1/plugins/tuya/local/:id admin forget the stored local configuration

    Testing

    server/tests/tuya.js runs fully offline against a fake Tuya OpenAPI and a fake sharing channel (node tests/tuya.js): 67 checks — it verifies request signing on both transports (the fakes recompute every HMAC/X-sign and the AES-GCM envelope), token expiry/refresh paths, the device cache, command mapping for lights/switches/covers/fans, fuzzy name matching with closest-match hints, the scene list/trigger, config routes (masked secret, write-only), the QR bind flow end to end and role gating. TUYA_BASE_URL

    • TUYA_QR_BASE point the plugin at the fakes.

    server/tests/tuya-local.js (node tests/tuya-local.js) covers the local LAN mode against mock devices that speak the real wire protocol (3.3, 3.4 with the session-key handshake, 3.5 with GCM, and the device22 "data unvalid" override): codec round-trips, discovery broadcast decryption (all three formats), the DP mapping (spec dp_id and the value-match fallback), protocol auto-detection (probeVersion incl. wrong-key rejection), and the plugin-level flow end to end — dry-run test, enable, LAN-first control (no cloud call), status read, cloud fallback when the device drops off the LAN, disable and forget.

    Troubleshooting

    • token failed (status 100/...) — wrong access id/secret pair or the project was never activated; the status code is Tuya's own.
    • "QR code not scanned yet" — the QR was not scanned in time. Generate a new one; the scan must happen within minutes.
    • nickname/username empty after a scan — the app account confirmed but the sharing channel responded without the user profile; press Unlink and bind again (the token set is still valid, but the page needs the profile switch).
    • QR scan lands "device not found" — the user code belonged to another Tuya app region than the plugin endpoint; there is nothing to fix server-side — the QR carries its own channel.
    • uid ... has no devices — the app account is not linked to the cloud project (step 3 of Setup); link it in the IoT platform, then refresh.
    • Tuya request failed (status 1106) — the uid belongs to another app region than the configured endpoint (e.g. a "server near Europe / China mainland" mismatch).
    • Device does nothing — it is online, but its DP codes are not recognized (type other); open status and use dp with the exact code/value for category-specific toys, or check the device category in the Tuya platform.
    • Hero devices with countdown/humidity DPs ignore control — only the core codes are mapped; raw codes always work via dp.
    • Scenes empty — the linked account has no home with scene links, or the configured homeId points somewhere else.
    • Local scan finds nothing — the server's container only reaches the LAN through NAT: broadcasts never arrive there, so the scan uses the TCP sweep of the configured subnet (default the LAN_SUBNET env, else the server's own /24 — inside Docker that is the bridge network; set LAN_SUBNET=192.168.1.0/24 in the compose env or enter your home subnet in the panel). Also check that the devices are online and LAN control is enabled in the app.
    • Local test fails for one device — wrong/missing local_key (re-pairing the device invalidates it: refetch the device list), LAN control disabled in the app, or a protocol the device does not speak.
    • Device in LAN mode stopped answering — holai automatically falls back to the cloud for control and status; the green LAN chip stays but the log shows the fallback. Move the device back into Wi-Fi range or disable LAN mode for it.

    Last updated: November 2026