Skip to content

Tuya - Add local protocol 3.5 support - PR2#2438

Open
Terdious wants to merge 56 commits intoGladysAssistant:masterfrom
Terdious:tuya-local-protocol-3.5
Open

Tuya - Add local protocol 3.5 support - PR2#2438
Terdious wants to merge 56 commits intoGladysAssistant:masterfrom
Terdious:tuya-local-protocol-3.5

Conversation

@Terdious
Copy link
Copy Markdown
Contributor

@Terdious Terdious commented Feb 21, 2026

Pull Request check-list

To ensure your Pull Request can be accepted as fast as possible, make sure to review and check all of these items:

  • If your changes affect the code, did you write the tests?
  • Are tests passing? (npm test on both front/server)
  • Is the linter passing? (npm run eslint on both front/server)
  • Did you run prettier? (npm run prettier on both front/server)
  • If you are adding a new feature/service, did you run the integration comparator? (npm run compare-translations on front)
  • Did you test this pull request in real life? With real devices? If this development is a big feature or a new service, we recommend that you provide a Docker image to the community (forum) for testing before merging.
  • If your changes modify the API (REST or Node.js), did you modify the API documentation? (Documentation is based on comments in code)
  • If you are adding a new features/services which needs explanation, did you modify the user documentation? See the GitHub repo and the website.
  • Did you add fake requests data for the demo mode (front/src/config/demo.js) so that the demo website is working without a backend? (if needed) See https://demo.gladysassistant.com.

NOTE: these things are not required to open a PR and can be done afterwards / while the PR is open.

Description of change

Summary

  • Add full local protocol 3.5 support for Tuya devices.
  • Improve the local communication stack introduced in the baseline branch:
    • local scan
    • local poll
    • local set value
  • Keep the branch focused on protocol/runtime support rather than device-type mapping.

Details

  • Add protocol 3.5 local support using @demirdeniz/tuyapi-newgen alongside the existing Tuya stack.
  • Improve local scan behavior:
    • protocol parsing
    • timeout sanitization
    • sender IP fallback
    • persistence of local-only discovered devices
  • Improve local poll behavior:
    • timeout handling
    • retry/cleanup behavior
    • discovered-device refresh after successful local poll
  • Improve local set-value behavior:
    • protocol 3.5 support
    • command validation hardening
    • safer failure cleanup
  • Improve setup/device UX related to local mode and protocol handling.

Scope

  • Translate

    • +3 lines / -9 lines
  • Front

    • +23 lines / -29 lines
  • Server

    • +97 lines / -43 lines
  • Server Tests

    • +193 lines / -12 lines
  • Package

    • +75 lines / -0 lines

Summary by CodeRabbit

  • New Features

    • Local device polling with multi-protocol fallback, UDP local discovery, connection status, manual disconnect, reconnect logic, and cloud/local mode controls.
  • UI

    • Richer Tuya setup UI with new credential fields and connection states; device view shows masked IP, product/device identifiers, protocol/IP controls, local-poll actions, GitHub issue shortcut, and improved discovery ordering/status.
  • Localization

    • Expanded DE/EN/FR translations for setup, discovery, devices, statuses, errors, and guidance.
  • Tests

    • Extensive new and updated tests for local poll/scan, discovery, config, status, setValue, and lifecycle.

Terdious and others added 28 commits February 11, 2026 15:58
…er models

- Added support for air conditioning devices with new mappings and DPS configurations.
- Introduced local polling for Tuya devices to improve responsiveness.
- Enhanced device conversion logic to include additional parameters such as cloud IP and local override.
- Updated feature conversion to utilize advanced DPS mappings for air conditioning.
- Implemented new models for air conditioning and power meter, including specific feature mappings.
- Improved error handling and logging for local polling and device value setting.
- Added unit tests for new feature mappings and conversion logic.
… champ d'erreur dans le payload de l'événement WebSocket
…s et ajouter des tests pour la gestion des appareils locaux
…eurs de port et mise à jour des traductions
…re des liens vers la documentation et les options de connexion
…réation de rapports GitHub pour les appareils Tuya
…l disconnect features

- Added new translations for connection status messages in German, English, and French.
- Implemented API endpoints to get Tuya connection status and to manually disconnect from the Tuya cloud.
- Updated the Tuya service to handle automatic reconnection logic and manual disconnect state.
- Enhanced the SetupTab component to reflect connection status and provide a disconnect button.
- Added tests for the new functionality, including status retrieval and manual disconnect.
- Implemented device ranking and sorting in DiscoverTab for better user experience.
- Added loading indicators and improved UI feedback during device scanning.
- Refactored local polling logic to update discovered devices with local information.
- Introduced utility functions for managing device parameters, including upserting and normalizing values.
- Enhanced local scan response handling to merge existing device parameters.
- Updated tests to cover new functionality and ensure reliability of device management.
…age, ajouter des tests pour la reconnexion automatique et la découverte des appareils
… des paramètres dans le code de configuration Tuya
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Feb 21, 2026

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds local UDP scanning and multi-protocol local polling for Tuya, extends frontend cloud/local flows and connection lifecycle, exposes server endpoints (local-poll, local-scan, status, disconnect), implements auto-reconnect/manual-disconnect and device param utilities, updates tests, and adds i18n entries (de/en/fr).

Changes

Cohort / File(s) Summary
Internationalization
front/src/config/i18n/de.json, front/src/config/i18n/en.json, front/src/config/i18n/fr.json
Added 50+ Tuya translation keys for device metadata, local/cloud modes, discovery/poll statuses, setup texts, and connection lifecycle messages.
Frontend — Device UI
front/src/routes/integration/all/tuya/TuyaDeviceBox.jsx
Added local-poll flow, IP mode toggle, protocol selector, IP masking/GitHub-issue helpers, baseline device tracking, new methods (toggleIpMode,updateProtocol,pollLocal,updateIpAddress) and state for poll validation/status; UI updates for identifiers and poll controls.
Frontend — Discovery & Styles
front/src/routes/integration/all/tuya/discover-page/DiscoverTab.jsx, front/src/routes/integration/all/tuya/discover-page/style.css
Deterministic sorting and ordered rendering, local UDP scan flow (runLocalScan), port error handling, scan loaders/alerts, on-device-saved merge handler; added .scanLoader CSS.
Frontend — Setup
front/src/routes/integration/all/tuya/setup-page/SetupTab.jsx
Connection lifecycle UI: fetch config/status, WebSocket listeners (TUYA.STATUS/TUYA.ERROR), save/disconnect flows, app username field, secret visibility toggle, and updated connect export.
Backend — Controller Endpoints
server/services/tuya/api/tuya.controller.js
Added handlers and routes: POST /api/v1/service/tuya/local-poll, POST /api/v1/service/tuya/local-scan, GET /api/v1/service/tuya/status, POST /api/v1/service/tuya/disconnect.
Backend — Service lifecycle & reconnect
server/services/tuya/index.js
Added reconnect constants, quick/interval reconnect scheduling, tryReconnect flow, and conditional device loading only when CONNECTED; integrated reconnect on start/stop.
Backend — Connect/Init/Disconnect
server/services/tuya/lib/tuya.connect.js, .../tuya.init.js, .../tuya.disconnect.js
Connect validates app account, maps connection errors, sets LAST_CONNECTED_CONFIG_HASH and auto-reconnect flags; init respects MANUAL_DISCONNECT; disconnect accepts options/manual, resets state and emits websocket status (includes manual flag).
Backend — Local poll & scan
server/services/tuya/lib/tuya.localPoll.js, server/services/tuya/lib/tuya.localScan.js
Implemented localPoll (multi-protocol attempts, timeouts, socket error handling) and localScan (UDP scanning on ports 6666/6667/7000), plus builders to merge results with discovered devices.
Backend — Device params & utils
server/services/tuya/lib/utils/tuya.deviceParams.js, .../tuya.normalize.js, .../tuya.constants.js, .../tuya.config.js
New utilities: param upsert/merge/normalize, normalizeBoolean, DEVICE_PARAM_NAME constants, GLADYS variable keys (APP_USERNAME, MANUAL_DISCONNECT, LAST_CONNECTED_CONFIG_HASH), PUBLIC_VERSION_1_0, and buildConfigHash for stable config hashing.
Backend — Command execution
server/services/tuya/lib/tuya.setValue.js
Attempt local command execution using device params (IP/localKey/protocol/local_override) via TuyAPI or tuyapi-newgen; fall back to cloud on failure; added DPS mapping helpers.
Backend — Device conversion & discovery
server/services/tuya/lib/device/tuya.convertDevice.js, .../tuya.discoverDevices.js
convertDevice surfaces product fields and params array; discovery now merges existing devices, applies local params, and preserves updatable flags.
Backend — Loading & details
server/services/tuya/lib/tuya.loadDevices.js, .../tuya.loadDeviceDetails.js, .../tuya.getConfiguration.js
Switched to pageNo/pageSize pagination and PUBLIC_VERSION_1_0 endpoints, parallel spec/detail fetch with Promise.allSettled, and include appUsername/appAccountId in configuration.
Backend — Public API additions
server/services/tuya/lib/index.js, server/services/tuya/lib/tuya.getStatus.js, server/services/tuya/lib/tuya.manualDisconnect.js, server/services/tuya/lib/tuya.saveConfiguration.js
Exported new handler methods (localScan/localPoll/getStatus/manualDisconnect), added getStatus to report configured/connected/manual_disconnect, manualDisconnect persists MANUAL_DISCONNECT, saveConfiguration persists APP_USERNAME and resets related vars.
Dependencies / Manifests
server/package.json, server/services/tuya/package.json
Added tuyapi, @demirdeniz/tuyapi-newgen and updated package manifests to support local protocol variants.
Tests
server/test/services/tuya/**, server/test/services/tuya/lib/**
Extensive new/updated tests covering reconnect logic, local-poll/scan endpoints, setValue local/cloud paths, device param utilities, convertDevice, loadDevices/details, init/status/disconnect flows, and many edge cases.
WebSocket constants
server/utils/constants.js
Added WEBSOCKET_MESSAGE_TYPES.TUYA.ERROR for explicit Tuya error events.

Sequence Diagram(s)

sequenceDiagram
    participant Client as Web Client
    participant Server as Gladys Server
    participant WebSocket as WebSocket
    participant TuyaCloud as Tuya Cloud API
    participant LocalDevice as Local Tuya Device

    Client->>Server: POST /api/v1/service/tuya/local-poll (device params)
    activate Server
    Server->>LocalDevice: Connect via TuyAPI / tuyapi-newgen (protocol attempts)
    LocalDevice-->>Server: DPS response / error
    Server->>Server: updateDiscoveredDeviceAfterLocalPoll -> persist params
    Server->>WebSocket: Emit TUYA.STATUS / TUYA.ERROR
    Server-->>Client: { dps, device? }
    deactivate Server

    Client->>Server: POST /api/v1/service/tuya/local-scan (timeout)
    activate Server
    Server->>LocalDevice: UDP scan on ports 6666/6667/7000
    LocalDevice-->>Server: discovery packets
    Server->>Server: buildLocalScanResponse (merge with discoveredDevices/state)
    Server-->>Client: { devices, local_devices, port_errors }
    deactivate Server

    Client->>Server: GET /api/v1/service/tuya/status
    activate Server
    Server->>Server: getStatus (reads MANUAL_DISCONNECT, lastError, status)
    Server-->>Client: { status, connected, configured, manual_disconnect, error }
    deactivate Server

    Client->>Server: POST /api/v1/service/tuya/disconnect
    activate Server
    Server->>Server: manualDisconnect -> set MANUAL_DISCONNECT = true -> disconnect({ manual: true })
    Server->>WebSocket: Emit TUYA.STATUS (manual_disconnect: true)
    Server-->>Client: { success: true }
    deactivate Server

    Note over Server: Background auto-reconnect loop (RECONNECT_INTERVAL_MS)
    Server->>TuyaCloud: fetch config & attempt connect when not manual_disconnect
    TuyaCloud-->>Server: connected / error
    Server->>WebSocket: Emit TUYA.STATUS / TUYA.ERROR accordingly
Loading

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Suggested reviewers

  • Pierre-Gilles

Poem

🐰 I hopped through ports and packets bright,

Local scans beneath the moonlit night,
Cloud and rabbit, side by side,
Params tucked safe — no secret to hide,
Reconnect hums, devices glow with light.

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 61.90% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main feature: adding local protocol 3.5 support for Tuya devices, which aligns with the primary objective and changes throughout the PR.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Comment @coderabbitai help to get the list of available commands and usage tips.

@relativeci
Copy link
Copy Markdown

relativeci Bot commented Feb 21, 2026

#3945 Bundle Size — 11.46MiB (+0.62%).

4a5ec79(current) vs 8db6b0d master#3902(baseline)

Warning

Bundle contains 2 duplicate packages – View duplicate packages

Bundle metrics  Change 3 changes Regression 2 regressions
                 Current
#3945
     Baseline
#3902
Regression  Initial JS 6.46MiB(+1.11%) 6.38MiB
Regression  Initial CSS 310.24KiB(+0.02%) 310.18KiB
Change  Cache Invalidation 58.6% 0%
No change  Chunks 51 51
No change  Assets 179 179
No change  Modules 1643 1643
No change  Duplicate Modules 21 21
No change  Duplicate Code 0.94% 0.94%
No change  Packages 136 136
No change  Duplicate Packages 2 2
Bundle size by type  Change 2 changes Regression 2 regressions
                 Current
#3945
     Baseline
#3902
Regression  JS 8.35MiB (+0.85%) 8.28MiB
No change  IMG 2.66MiB 2.66MiB
Regression  CSS 328.09KiB (+0.02%) 328.03KiB
No change  Fonts 93.55KiB 93.55KiB
No change  Other 18.82KiB 18.82KiB
No change  HTML 13.58KiB 13.58KiB

Bundle analysis reportBranch Terdious:tuya-local-protocol-3.5Project dashboard


Generated by RelativeCIDocumentationReport issue

@Terdious Terdious force-pushed the tuya-local-protocol-3.5 branch from e7959c6 to 74b081e Compare February 27, 2026 11:42
@Terdious Terdious changed the title Add Tuya local protocol 3.5 support Add Tuya local protocol 3.5 support - PR2 Feb 27, 2026
@Terdious Terdious removed the request for review from Pierre-Gilles February 27, 2026 12:40
@Terdious Terdious closed this Feb 27, 2026
@Terdious Terdious reopened this Feb 27, 2026
@Terdious Terdious changed the title Add Tuya local protocol 3.5 support - PR2 Tuya - Add local protocol 3.5 support - PR2 Feb 27, 2026
@stale
Copy link
Copy Markdown

stale Bot commented May 1, 2026

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

@stale stale Bot added the stale label May 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant