Skip to content

New Components - tuya #16474

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open

New Components - tuya #16474

wants to merge 3 commits into from

Conversation

michelle0927
Copy link
Collaborator

@michelle0927 michelle0927 commented Apr 29, 2025

Resolves #9874

Summary by CodeRabbit

  • New Features
    • Added actions to list Tuya devices and homes, and to send instructions to a Tuya device.
    • Introduced a new event source that emits notifications when a new Tuya device is activated.
    • Enhanced integration with Tuya, including dynamic selection of users, homes, devices, and device functions.
  • Chores
    • Updated package dependencies and version for improved compatibility and stability.

Copy link

vercel bot commented Apr 29, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

3 Skipped Deployments
Name Status Preview Comments Updated (UTC)
docs-v2 ⬜️ Ignored (Inspect) Visit Preview Apr 29, 2025 8:39pm
pipedream-docs ⬜️ Ignored (Inspect) Apr 29, 2025 8:39pm
pipedream-docs-redirect-do-not-edit ⬜️ Ignored (Inspect) Apr 29, 2025 8:39pm

Copy link
Contributor

coderabbitai bot commented Apr 29, 2025

Walkthrough

This update introduces a new integration with Tuya Cloud Services, providing actions and a trigger for interacting with Tuya devices and homes. The changes add modules for listing homes, listing devices (by user or home), sending instructions to devices, and a polling-based source for detecting new device activations. The Tuya app module is significantly extended to support dynamic property definitions and robust API client initialization, including methods for listing users, homes, devices, device functions, and sending device instructions. The package metadata is updated to include required dependencies and versioning.

Changes

Files/Paths Change Summary
components/tuya/actions/list-homes/list-homes.mjs, components/tuya/actions/list-devices/list-devices.mjs Added new actions for listing homes and devices associated with a user or home, including Tuya API calls and summary exports.
components/tuya/actions/send-instructions-to-device/send-instructions-to-device.mjs Added action to send instructions to a specific Tuya device, with dynamic property loading and API interaction.
components/tuya/sources/new-device-activated/new-device-activated.mjs Added polling source to emit events when a new device is activated, with deduplication and persistent timestamp tracking.
components/tuya/tuya.app.mjs Major update: Added dynamic prop definitions, API client setup, error handling, and methods for all Tuya API interactions.
components/tuya/package.json Updated package version to 0.1.0 and added dependencies for Tuya SDK and platform support.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Action/Source
    participant TuyaApp
    participant TuyaAPI

    User->>Action/Source: Provide userId/homeId/deviceId/instruction
    Action/Source->>TuyaApp: Call method (listHomes/listDevices/sendInstructions)
    TuyaApp->>TuyaAPI: Make authenticated API request
    TuyaAPI-->>TuyaApp: Return response data
    TuyaApp-->>Action/Source: Return processed result
    Action/Source-->>User: Output summary/result or emit event
Loading

Assessment against linked issues

Objective Addressed Explanation
a) Login (username/password) (#9874) No explicit login action with username/password is implemented; integration uses API keys.
b) Get a list of "Homes" associated (#9874)
c) Get a list of devices (all or by home) (#9874)
d) Set a hook to fire when a particular device event happens (e.g. "switch 1: ON") (#9874) Only "new device activated" trigger is implemented, not arbitrary device event hooks.
e) Set a device parameter (e.g. switch 2 ON) (#9874)

Suggested labels

ai-assisted

Poem

In Tuya's cloud, new features bloom,
Homes and devices, found in every room.
With actions and triggers, the code’s now complete,
Devices obey with a tap or a tweet.
🐇 From my burrow, I cheer with delight—
Smarthomes and rabbits, both hopping to new heights!

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

components/tuya/tuya.app.mjs

Oops! Something went wrong! :(

ESLint: 8.57.1

Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'jsonc-eslint-parser' imported from /eslint.config.mjs
at packageResolve (node:internal/modules/esm/resolve:839:9)
at moduleResolve (node:internal/modules/esm/resolve:908:18)
at defaultResolve (node:internal/modules/esm/resolve:1038:11)
at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:557:12)
at ModuleLoader.resolve (node:internal/modules/esm/loader:525:25)
at ModuleLoader.getModuleJob (node:internal/modules/esm/loader:246:38)
at ModuleJob._link (node:internal/modules/esm/module_job:126:49)

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

🧹 Nitpick comments (3)
components/tuya/actions/list-devices/list-devices.mjs (2)

4-8: Update description to reflect dual functionality.

The description only mentions listing devices associated with a home, but the action actually supports listing devices for both a home and a user.

-  description: "Get a list of devices associated with a home. [See the documentation](https://developer.tuya.com/en/docs/cloud/d7ee73aadb?id=Kawfjer0wkt2a)",
+  description: "Get a list of devices associated with a home or user. [See the documentation](https://developer.tuya.com/en/docs/cloud/d7ee73aadb?id=Kawfjer0wkt2a)",

36-40: Improve handling of empty results.

The code only sets a summary when devices are found, but should also provide feedback when no devices are found.

    if (response?.result?.length) {
      $.export("$summary", `Found ${response.result.length} device${response.result.length === 1
        ? ""
        : "s"}`);
+   } else {
+     $.export("$summary", "No devices found");
    }
components/tuya/tuya.app.mjs (1)

90-94: Pass data only for non-GET requests

Some HTTP clients treat a body on GET as invalid.
A quick guard avoids surprises:

 const response = await this._getClient().request({
   method,
   path,
-  body: data,
+  ...(method === "GET" ? {} : { body: data }),
 });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 556dc7b and 912d22a.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (6)
  • components/tuya/actions/list-devices/list-devices.mjs (1 hunks)
  • components/tuya/actions/list-homes/list-homes.mjs (1 hunks)
  • components/tuya/actions/send-instructions-to-device/send-instructions-to-device.mjs (1 hunks)
  • components/tuya/package.json (2 hunks)
  • components/tuya/sources/new-device-activated/new-device-activated.mjs (1 hunks)
  • components/tuya/tuya.app.mjs (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: pnpm publish
  • GitHub Check: Verify TypeScript components
  • GitHub Check: Lint Code Base
  • GitHub Check: Publish TypeScript components
🔇 Additional comments (7)
components/tuya/package.json (2)

3-3: Version increment looks appropriate.

The version update from 0.0.1 to 0.1.0 follows semantic versioning principles, correctly indicating significant new functionality being added to the package.


15-18:

✅ Verification successful

Dependencies section looks good, but verify Tuya connector version.

The dependencies are properly structured with appropriate version ranges. Make sure that "@tuya/tuya-connector-nodejs" v2.1.2 is the latest stable version to ensure access to all necessary API features and security fixes.


🏁 Script executed:

#!/bin/bash
# Check if there are newer versions of the Tuya connector package
npm view @tuya/tuya-connector-nodejs versions --json | jq 'if type=="array" then .[-5:] else . end'

# Check for any security advisories
npm audit @tuya/tuya-connector-nodejs || echo "No direct vulnerability info available"

Length of output: 2468


Confirmed Tuya connector version is up to date

Verified that @tuya/tuya-connector-nodejs@2.1.2 is the latest stable release and there are no direct vulnerabilities reported against it. The dependencies section is good to merge.

components/tuya/actions/send-instructions-to-device/send-instructions-to-device.mjs (1)

3-69: Well-structured action component with good organization.

The component properly implements the Pipedream action architecture with appropriate props, dynamic loading, and API interaction.

components/tuya/sources/new-device-activated/new-device-activated.mjs (2)

4-43: Well-implemented polling source with proper deduplication and state management.

The component correctly implements a polling-based source with dedupe settings, database persistence, and appropriate prop definitions.


38-50:

✅ Verification successful

Verify timestamp format and comparison.

The code assumes device.active_time and the stored lastTs use the same format and are directly comparable. If these are in different formats or time zones, it could cause issues with event detection.

Verify that the timestamps are in the same format and are correctly comparable:


🏁 Script executed:

#!/bin/bash
# Find and display examples of the active_time format from the Tuya API documentation
echo "Searching for active_time in Tuya API docs..."
rg -A 2 -B 2 "active_time" --json

Length of output: 4335


🏁 Script executed:

#!/bin/bash
# Display the beginning of the source file to inspect how `devices` and `active_time` are obtained
sed -n '1,120p' components/tuya/sources/new-device-activated/new-device-activated.mjs

Length of output: 1913


Active_time is a numeric epoch timestamp and directly comparable

I’ve confirmed that device.active_time is returned by the Tuya Cloud API as a UNIX‐epoch number (seconds since 1970), and lastTs is stored and retrieved as the same numeric value via this.db. The direct >= and Math.max comparisons are therefore safe—no format or timezone conversions are needed.

components/tuya/tuya.app.mjs (1)

78-84: Consider memoising the Tuya client

_getClient() instantiates a new TuyaContext on every request.
If the SDK performs auth handshakes or creates sockets, this can be wasteful.
Storing a single instance (e.g. in this._client) would cut overhead.

[ suggest_optional_refactor ]

components/tuya/actions/list-homes/list-homes.mjs (1)

18-27: Action depends on fixed helpers — verify once _makeRequest is returned

With the bug in _makeRequest corrected, ensure this action still handles
cases where response.result is undefined (e.g. no homes found).

-const response = await this.tuya.listHomes({ userId: this.userId });
-if (response?.result?.length) {
-  $.export("$summary", `Found ${response.result.length} home${response.result.length === 1 ? "" : "s"}`);
-}
-return response;
+const response = await this.tuya.listHomes({ userId: this.userId });
+const homes = response?.result ?? [];
+$.export("$summary", `Found ${homes.length} home${homes.length === 1 ? "" : "s"}`);
+return response;

This keeps the summary logic robust even when the API legitimately returns an empty array.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

♻️ Duplicate comments (3)
components/tuya/tuya.app.mjs (3)

85-99: ⚠️ Potential issue

_makeRequest() still returns undefined on the happy-path

This was flagged in the previous review but hasn’t been addressed.
Because the function never returns a value when the request is successful, every wrapper (listHomes, listUserDevices, …) resolves to undefined, breaking dynamic props and any consumer relying on the data.

       if (!response.success) {
         console.log(response);
         throw new ConfigurationError(`${response.msg}`);
       }
+      // Return the full response (or `response.result` if callers only need the
+      // payload) so that helpers receive actual data
+      return response;

12-19: ⚠️ Potential issue

Unsafe nested-destructuring can crash option loading

If listUsers() fails or returns an unexpected payload,
const { result: { list } } = … throws a TypeError, preventing the UI from loading the prop options.

-const { result: { list } } = await this.listUsers();
-return list?.map(({ user_id: value, user_name: label }) => ({ label, value })) || [];
+const { result } = await this.listUsers();
+const list = result?.list ?? [];
+return list.map(({ user_id: value, user_name: label }) => ({ label, value }));

123-130: 🛠️ Refactor suggestion

sendInstructionsToDevice() still accepts arbitrary data, no validation

The Tuya API expects a JSON body { "commands": [...] }.
Allowing any payload without validation can lead to silent no-ops or malformed requests.
Please validate the input and make the signature clearer.

-sendInstructionsToDevice({
-  deviceId, data,
-}) {
-  return this._makeRequest({
-    method: "POST",
-    path: `/v1.0/devices/${deviceId}/commands`,
-    data,
-  });
+sendInstructionsToDevice({ deviceId, commands }) {
+  if (!Array.isArray(commands) || !commands.length) {
+    throw new ConfigurationError("`commands` must be a non-empty array");
+  }
+  return this._makeRequest({
+    method: "POST",
+    path: `/v1.0/devices/${deviceId}/commands`,
+    data: { commands },
+  });
 }
🧹 Nitpick comments (1)
components/tuya/tuya.app.mjs (1)

78-84: Consider caching the Tuya client instance

_getClient() instantiates TuyaContext on every call, adding unnecessary overhead and preventing connection pooling.
Storing the client in this after first creation is a low-effort optimisation.

-_getClient() {
-  return new TuyaContext({
-    baseUrl: this.$auth.base_url,
-    accessKey: this.$auth.client_id,
-    secretKey: this.$auth.client_secret,
-  });
+_getClient() {
+  if (!this._client) {
+    this._client = new TuyaContext({
+      baseUrl: this.$auth.base_url,
+      accessKey: this.$auth.client_id,
+      secretKey: this.$auth.client_secret,
+    });
+  }
+  return this._client;
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 912d22a and 3759c3b.

📒 Files selected for processing (1)
  • components/tuya/tuya.app.mjs (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: pnpm publish
  • GitHub Check: Verify TypeScript components
  • GitHub Check: Publish TypeScript components

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Smarlife / Tuya Cloud Services
2 participants