Skip to content

New Components - philips_hue #16456

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

Merged
merged 2 commits into from
Apr 30, 2025
Merged

New Components - philips_hue #16456

merged 2 commits into from
Apr 30, 2025

Conversation

michelle0927
Copy link
Collaborator

@michelle0927 michelle0927 commented Apr 25, 2025

Resolves #15146

@vunguyenhung

Copy link

vercel bot commented Apr 25, 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) Apr 25, 2025 5:55pm
pipedream-docs ⬜️ Ignored (Inspect) Apr 25, 2025 5:55pm
pipedream-docs-redirect-do-not-edit ⬜️ Ignored (Inspect) Apr 25, 2025 5:55pm

Copy link
Contributor

coderabbitai bot commented Apr 25, 2025

Walkthrough

This update introduces a comprehensive Philips Hue integration, adding new actions and polling sources for the Hue API v2. The Philips Hue app component is expanded with dynamic property definitions and resource methods for lights, groups, scenes, and sensors. Three new actions—turning lights on, setting light color, and activating scenes—are implemented, each supporting both individual lights and groups. Three new event sources are added to emit events on light state changes, scene activations, and sensor updates, with robust state management and deduplication. Supporting base modules and test event fixtures are also included, and the package version is incremented.

Changes

Files/Group Change Summary
components/philips_hue/philips_hue.app.mjs Major expansion: Adds dynamic prop definitions and resource methods for Hue API v2 (CRUD for lights, groups, scenes, sensors). Centralizes API requests and authentication.
components/philips_hue/actions/activate-scene/activate-scene.mjs New action: Activates a specified Philips Hue scene using the API, with dynamic scene selection.
components/philips_hue/actions/set-light-color/set-light-color.mjs New action: Sets the color of a light or group using a HEX code, converting to CIE xy and updating via API.
components/philips_hue/actions/turn-light-on/turn-light-on.mjs New action: Turns a light or group on (or off), enforcing that exactly one target is specified.
components/philips_hue/sources/common/base.mjs New base module: Provides state management, event emission, and meta generation for polling sources.
components/philips_hue/sources/new-light-state/new-light-state.mjs New source: Emits events when a light or group's state changes (on/off, brightness, color), using previous state comparison.
components/philips_hue/sources/new-light-state/test-event.mjs New test fixture: Sample Philips Hue light state event for testing the new-light-state source.
components/philips_hue/sources/new-scene-activated/new-scene-activated.mjs New source: Emits events when a specific scene is activated, comparing activation state with previous data.
components/philips_hue/sources/new-scene-activated/test-event.mjs New test fixture: Sample scene activation event for testing the new-scene-activated source.
components/philips_hue/sources/new-sensor-update/new-sensor-update.mjs New source: Emits events when a specified Hue sensor (motion, temperature, light level) updates, deduplicated by timestamp.
components/philips_hue/package.json Version bump to 0.7.0; updates @pipedream/platform dependency.

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant PD_Component as Philips Hue Component
  participant HueAPI as Philips Hue API

  User->>PD_Component: Configure action/source (select light/group/scene/sensor)
  PD_Component->>HueAPI: Authenticate and fetch options (e.g., list lights/scenes)
  User->>PD_Component: Trigger action or polling interval fires
  alt Action: Turn Light On / Set Color / Activate Scene
    PD_Component->>HueAPI: Send API request (PUT) to update light/group/scene
    HueAPI-->>PD_Component: Response (success/failure)
    PD_Component-->>User: Return result/summary
  else Source: Polling Event (light state, scene, sensor)
    PD_Component->>HueAPI: Fetch current state(s)
    PD_Component->>PD_Component: Compare with previous state
    alt State Changed/Update Detected
      PD_Component-->>User: Emit event with summary/meta
      PD_Component->>PD_Component: Update stored state
    end
  end
Loading

Assessment against linked issues

Objective Addressed Explanation
new-light-state: Emit event on light state change (light/group ID required) (#15146)
new-scene-activated: Emit event when a specific scene is activated (scene name/ID required) (#15146)
new-sensor-update: Emit event on sensor update (motion/temperature/light sensor ID required) (#15146)
turn-light-on: Turn on light/group (ID required); set-light-color: Set color by ID and spec (#15146)
activate-scene: Activate scene by ID (room/zone info) (#15146)

Suggested labels

User submitted

Poem

In the land of glowing Hue,
New actions and sources now debut!
Lights turn on, colors bloom bright,
Scenes awaken in the night.
Sensors whisper, states are seen,
All managed by code—so clean!
🐇✨ The future’s lit, thanks to this commit!

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/philips_hue/actions/activate-scene/activate-scene.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)

components/philips_hue/actions/set-light-color/set-light-color.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)

components/philips_hue/actions/turn-light-on/turn-light-on.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)

  • 7 others
✨ 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: 8

🧹 Nitpick comments (14)
components/philips_hue/actions/set-light-color/set-light-color.mjs (4)

39-43: Add hex color format validation

Consider adding validation for the hex color format to avoid potential errors in the color conversion process.

 color: {
   type: "string",
   label: "Color",
   description: "A hexidecimal color value to set the light(s) to. E.g. `#800080`",
+  pattern: "^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$",
+  errorMessage: "Please enter a valid hexadecimal color (e.g., #800080)",
 },

42-42: Fix typo in description

There's a typo in the description: "hexidecimal" should be "hexadecimal".

-  description: "A hexidecimal color value to set the light(s) to. E.g. `#800080`",
+  description: "A hexadecimal color value to set the light(s) to. E.g. `#800080`",

46-55: Add error handling for color conversion

The color conversion could fail if an invalid hex color is provided. Consider adding try/catch to handle potential errors.

 hexToCIE(hex) {
+  try {
+    // Remove '#' if present
+    const hexColor = hex.startsWith('#') ? hex.substring(1) : hex;
-    const rgb = convert.hex.rgb(hex);
+    const rgb = convert.hex.rgb(hexColor);
     const xyz = convert.rgb.xyz(rgb);
     const x = xyz[0] / (xyz[0] + xyz[1] + xyz[2]);
     const y = xyz[1] / (xyz[0] + xyz[1] + xyz[2]);
     return {
       x,
       y,
     };
+  } catch (error) {
+    throw new ConfigurationError(`Invalid hex color format: ${hex}. Please provide a valid hex color (e.g., #800080).`);
+  }
 },

8-8: Specify API version in description

Update the description to explicitly mention that this action uses the Hue API v2.

-  description: "Sets the light color of a Philips Hue light. [See the documentation](https://developers.meethue.com/develop/hue-api-v2/api-reference/#resource_light__id__put)",
+  description: "Sets the light color of a Philips Hue light using API v2. [See the documentation](https://developers.meethue.com/develop/hue-api-v2/api-reference/#resource_light__id__put)",
components/philips_hue/sources/new-scene-activated/test-event.mjs (2)

89-89: Update future timestamp in test event

The test event contains a timestamp set in the future (2025-04-25). Consider using a past or present date for more realistic testing.

-    "last_recall": "2025-04-25T17:06:00.896Z"
+    "last_recall": "2023-04-25T17:06:00.896Z"

1-92: Enhance test coverage with more action types

Consider adding examples of other action types (like xy color coordinates or hue/saturation) to provide more comprehensive test coverage for different scene types.

components/philips_hue/actions/turn-light-on/turn-light-on.mjs (3)

5-7: Consider renaming for clarity

Since this action can both turn lights on and off, consider renaming it to something more descriptive like "Toggle Light" or "Control Light Power".

-  key: "philips_hue-turn-light-on",
-  name: "Turn Light On",
-  description: "Turns on or off a Philips Hue light or group of lights. [See the documentation](https://developers.meethue.com/develop/hue-api-v2/api-reference/#resource_light__id__put)",
+  key: "philips_hue-control-light-power",
+  name: "Control Light Power",
+  description: "Turns on or off a Philips Hue light or group of lights using API v2. [See the documentation](https://developers.meethue.com/develop/hue-api-v2/api-reference/#resource_light__id__put)",

70-73: Improve summary formatting

The summary message formatting breaks across multiple lines, which reduces readability. Consider reformatting to keep it on a single line.

-    $.export("$summary", `Successfully turned ${this.turnLightOff
-      ? "off"
-      : "on"} light(s)`);
+    $.export("$summary", `Successfully turned ${this.turnLightOff ? "off" : "on"} light(s)`);

45-74: Add error handling for API responses

Consider adding specific error handling for API failures to provide clearer error messages to users.

 async run({ $ }) {
   if ((!this.lightId && !this.groupId) || (this.lightId && this.groupId)) {
     throw new ConfigurationError("Must specify exactly one of Light ID or GroupID");
   }

   const opts = {
     $,
     username: this.username,
     data: {
       on: {
         on: !this.turnLightOff,
       },
     },
   };

+  try {
     const response = this.lightId
       ? await this.philipsHue.updateLight({
         lightId: this.lightId,
         ...opts,
       })
       : await this.philipsHue.updateGroup({
         groupId: this.groupId,
         ...opts,
       });

     $.export("$summary", `Successfully turned ${this.turnLightOff ? "off" : "on"} light(s)`);
     return response;
+  } catch (error) {
+    throw new Error(`Failed to control light power: ${error.message}`);
+  }
 },
components/philips_hue/actions/activate-scene/activate-scene.mjs (1)

1-8: Documentation URL doesn't match the action type.

The description points to the light API reference, but this is a scene activation action.

  key: "philips_hue-activate-scene",
  name: "Activate Scene",
- description: "Activates a Philips Hue light scene. [See the documentation](https://developers.meethue.com/develop/hue-api-v2/api-reference/#resource_light__id__put)",
+ description: "Activates a Philips Hue light scene. [See the documentation](https://developers.meethue.com/develop/hue-api-v2/api-reference/#resource_scene__id__put)",
  version: "0.0.1",
  type: "action",
components/philips_hue/sources/common/base.mjs (1)

32-39: Enhance event ID generation for better uniqueness.

The current ID generation combines item.id with timestamp, which could potentially cause collisions if multiple items are processed in the same millisecond.

    generateMeta(item) {
      const ts = Date.now();
+     // Using a random component to further ensure uniqueness
+     const randomSuffix = Math.random().toString(36).substring(2, 10);
      return {
-       id: `${item.id}${ts}`,
+       id: `${item.id}_${ts}_${randomSuffix}`,
        summary: this.getSummary(item),
        ts,
      };
    },
components/philips_hue/sources/new-sensor-update/new-sensor-update.mjs (1)

46-55: Edge-case: string-typed empty props may bypass the “exactly one” validation

deploy() currently counts only undefined values, so a prop supplied as an empty string ("") will still be considered “defined”, causing definedCount to be 1 and letting the deployment succeed with an invalid ID.
A quick tweak makes the intent explicit:

-].filter((x) => x !== undefined).length;
+].filter(Boolean).length;   // filters out: undefined, null, "", 0, false

This prevents mis-configuration at deploy time.

components/philips_hue/philips_hue.app.mjs (2)

32-37: Expose readable labels for groups (consistency with lights & scenes)

lightId and sceneId option loaders return { label, value }, but groupId, motionId, etc. return plain strings.
Returning objects with labels greatly improves the UI in the Pipedream step-builder.

return data?.map(({ id, metadata }) => ({
-  id
+  label: metadata?.name || id,
+  value: id,
})) || [];

Applying this pattern across all option loaders keeps the UX consistent.


90-107: Minor: $ default parameter shadows the framework-supplied $

_makeRequest({ $ = this, path, username,})

Using $ as a parameter here shadows the special $ object that Pipedream injects with logging & fetch helpers. While it works, it can confuse readers and makes the method signature harder to grasp.

Consider renaming to pd or simply removing the default and passing this explicitly where needed.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7e4c00d and 4ea3a4d.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (11)
  • components/philips_hue/actions/activate-scene/activate-scene.mjs (1 hunks)
  • components/philips_hue/actions/set-light-color/set-light-color.mjs (1 hunks)
  • components/philips_hue/actions/turn-light-on/turn-light-on.mjs (1 hunks)
  • components/philips_hue/package.json (2 hunks)
  • components/philips_hue/philips_hue.app.mjs (1 hunks)
  • components/philips_hue/sources/common/base.mjs (1 hunks)
  • components/philips_hue/sources/new-light-state/new-light-state.mjs (1 hunks)
  • components/philips_hue/sources/new-light-state/test-event.mjs (1 hunks)
  • components/philips_hue/sources/new-scene-activated/new-scene-activated.mjs (1 hunks)
  • components/philips_hue/sources/new-scene-activated/test-event.mjs (1 hunks)
  • components/philips_hue/sources/new-sensor-update/new-sensor-update.mjs (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Publish TypeScript components
  • GitHub Check: pnpm publish
  • GitHub Check: Verify TypeScript components
  • GitHub Check: Lint Code Base
🔇 Additional comments (13)
components/philips_hue/package.json (1)

3-3: Version updates look appropriate

The minor version increment (0.6.0 → 0.7.0) properly reflects the addition of new Philips Hue integration features, and the platform dependency update ensures compatibility with the latest Pipedream platform.

Also applies to: 16-16

components/philips_hue/actions/set-light-color/set-light-color.mjs (1)

1-92: Overall implementation looks solid

The action has a good structure and correctly handles the color conversion from hex to CIE coordinates. The validation to ensure exactly one target (light or group) is provided is a good practice.

components/philips_hue/sources/new-scene-activated/test-event.mjs (1)

1-92: Test event structure looks comprehensive

The test event provides a good representation of a scene activation event with detailed properties for actions, palette, metadata, and status.

components/philips_hue/actions/turn-light-on/turn-light-on.mjs (1)

1-75: Implementation looks clean and effective

The action correctly handles both turning lights on and off, with appropriate validation for target selection (light or group).

components/philips_hue/sources/new-light-state/new-light-state.mjs (4)

1-4: Clean imports and good organization.

The imports are well-structured, pulling in the common base module, platform error handling, and test event sample. This promotes maintainability and code reuse.


5-12: Component metadata is well-defined.

The metadata provides clear identification and description of the component's purpose with appropriate documentation link. Starting with version 0.0.1 is appropriate for a new component, and "dedupe: unique" ensures no duplicate events.


13-35: Props structure allows flexible configuration.

The props extend the common base and properly set up two optional properties (lightId and groupId) with dynamic dependency handling based on username. This flexibility allows users to monitor either individual lights or groups.


36-42: Good validation in deploy hook.

The deploy hook ensures exactly one of lightId or groupId is provided, preventing invalid configurations.

components/philips_hue/actions/activate-scene/activate-scene.mjs (1)

9-26: Props are well structured with clean dependencies.

The properties are logically organized, with the scene ID dynamically dependent on the username property. This ensures proper data loading and validation.

components/philips_hue/sources/common/base.mjs (3)

1-20: Well-structured base component with essential properties.

The base component defines common properties needed across Philips Hue sources, including the app interface, database access, timer configuration with sensible defaults, and username authentication.


22-27: Simple and effective data persistence methods.

The methods for getting and setting previous data are straightforward and work well for state management across polling intervals.


40-44: Good base method pattern requiring implementation.

The getSummary method with an error throw ensures that derived components must implement this method, which is a good pattern for enforcing contract requirements.

components/philips_hue/sources/new-light-state/test-event.mjs (1)

1-169: Comprehensive sample data for light state testing.

The test event provides detailed and realistic sample data, covering all aspects of a Philips Hue light state including identification, metadata, on/off status, dimming capabilities, color properties, effects, and power-up behavior. This ensures thorough testing of the event source component.

Copy link
Collaborator

@luancazarine luancazarine left a comment

Choose a reason for hiding this comment

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

Hi @michelle0927, LGTM! Ready for QA!

@michelle0927 michelle0927 merged commit 582ff70 into master Apr 30, 2025
11 checks passed
@michelle0927 michelle0927 deleted the issue-15146 branch April 30, 2025 16:37
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.

[Components] philips_hue
2 participants