Skip to content
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

Expose moving as motion sensor #956

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

Conversation

torandreroland
Copy link

@torandreroland torandreroland commented Nov 16, 2024

Expose moving as motion sensor to enable motion sensor for SmartThings/Samjin Multipurpose sensor.

Summary by CodeRabbit

  • New Features

    • Introduced a new MovingSensorHandler to enhance motion sensor capabilities.
    • Updated the BasicSensorCreator to include the new handler in its management system.
    • Added support for a new moving sensor, allowing devices to function as motion sensors.
  • Documentation

    • Updated documentation to include details about the new moving sensor and its functionalities.
  • Tests

    • Added a new test suite for the SmartThings IM6001-MPP01 motion sensor to validate its behavior.

These changes collectively improve the system's ability to handle motion sensors effectively and enhance user experience.

Copy link

coderabbitai bot commented Nov 16, 2024

Walkthrough

The changes introduce a new sensor handler, MovingSensorHandler, to the BasicSensorCreator class in the src/converters/basic_sensors.ts file. This handler is imported from src/converters/basic_sensors/moving.ts and added to the static handlers array. The MovingSensorHandler class extends BinarySensorHandler and includes functionality for motion sensors, such as a unique identifier generation method. The existing logic for other components and configurations remains unchanged, ensuring the functionality of the BasicSensorCreator is preserved while expanding its capabilities.

Changes

File Path Change Summary
src/converters/basic_sensors.ts Added MovingSensorHandler import and included it in the BasicSensorCreator.handlers array.
src/converters/basic_sensors/moving.ts Introduced MovingSensorHandler class extending BinarySensorHandler, with a constructor and static method for identifier generation.
.gitignore Added entry to ignore .DS_Store files and updated TypeScript ignore pattern.
CHANGELOG.md Updated to include a new feature for exposing moving functionality as a motion sensor.
docs/sensors.md Added documentation for the new moving sensor, detailing its service and characteristic.
test/basic_sensors.spec.ts Introduced a new test suite for the SmartThings IM6001-MPP01 motion sensor with relevant test cases.
test/exposes/smartthings/im6001-mpp01.json Added JSON configuration for battery, moving, and linkquality entities.

Poem

In the world of sensors, we hop and play,
A new handler joins us, hip-hip-hooray! 🐇
With motion detected, we’re quick on our feet,
Creating new services, oh what a treat!
So let’s dance and twirl, in code we delight,
For the MovingSensorHandler shines ever so bright! ✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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 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

@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: 3

🧹 Outside diff range comments (1)
src/converters/basic_sensors.ts (1)

Line range hint 1-94: Consider documenting motion sensor behavior.

Since this change introduces motion sensor capabilities, it would be beneficial to document the expected behavior, especially regarding:

  • Motion detection timeout/reset behavior
  • Any specific handling for the SmartThings/Samjin Multipurpose sensor
  • Integration considerations with home automation systems

Would you like me to help draft documentation for these aspects?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Reviewing files that changed from the base of the PR and between 46dbd07 and bf4b05f.

📒 Files selected for processing (2)
  • src/converters/basic_sensors.ts (2 hunks)
  • src/converters/basic_sensors/moving.ts (1 hunks)
🧰 Additional context used
🪛 Biome
src/converters/basic_sensors/moving.ts

[error] 16-16: Template literals are preferred over string concatenation.

Unsafe fix: Use a template literal.

(lint/style/useTemplate)


[error] 24-24: Template literals are preferred over string concatenation.

Unsafe fix: Use a template literal.

(lint/style/useTemplate)


[error] 26-26: Template literals are preferred over string concatenation.

Unsafe fix: Use a template literal.

(lint/style/useTemplate)

🔇 Additional comments (4)
src/converters/basic_sensors/moving.ts (2)

1-4: LGTM! All necessary dependencies are properly imported.

The imports are well-organized and include all required dependencies for implementing the motion sensor handler.


6-7: LGTM! Class structure aligns with PR objectives.

The MovingSensorHandler correctly extends BinarySensorHandler and defines the appropriate expose name for the moving state.

src/converters/basic_sensors.ts (2)

21-21: LGTM! Import follows established patterns.

The import statement for MovingSensorHandler follows the existing convention and is properly placed with other sensor handler imports.


56-56: LGTM! Handler registration looks good.

The MovingSensorHandler is correctly added to the static handlers array, maintaining consistency with other sensor handlers.

Let's verify the MovingSensorHandler implementation:

✅ Verification successful

MovingSensorHandler implementation is correctly structured and integrated

The verification confirms:

  • Properly extends BinarySensorHandler with correct inheritance
  • Correctly sets exposesName as 'moving'
  • Implements MotionSensor service with appropriate characteristics
  • Uses consistent identifier generation pattern
  • No conflicting usages of 'moving' property found elsewhere
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify MovingSensorHandler implementation and its base class usage

# Check if MovingSensorHandler extends BinarySensorHandler as expected
ast-grep --pattern 'class MovingSensorHandler extends BinarySensorHandler {
  $$$
}'

# Verify the exposesName is set to 'moving'
ast-grep --pattern 'static exposesName = $moving'

# Look for any existing usage of 'moving' property in the codebase
rg -l "['|\"]moving['|\"]" 

Length of output: 2126

Comment on lines +1 to +30
import { BasicAccessory } from '../interfaces';
import { ExposesEntryWithBinaryProperty, ExposesEntryWithProperty } from '../../z2mModels';
import { hap } from '../../hap';
import { BinarySensorHandler } from './binary';

export class MovingSensorHandler extends BinarySensorHandler {
public static readonly exposesName: string = 'moving';

constructor(expose: ExposesEntryWithProperty, otherExposes: ExposesEntryWithBinaryProperty[], accessory: BasicAccessory) {
super(
accessory,
expose as ExposesEntryWithBinaryProperty,
otherExposes,
MovingSensorHandler.generateIdentifier,
'Motion Sensor (moving)',
(n, t) => new hap.Service.MotionSensor(n, (MovingSensorHandler.exposesName + ' ' + (t ?? '')).trim()),
hap.Characteristic.MotionDetected,
true,
false
);
}

static generateIdentifier(endpoint: string | undefined) {
let identifier = MovingSensorHandler.exposesName + '_' + hap.Service.MotionSensor.UUID;
if (endpoint !== undefined) {
identifier += '_' + endpoint.trim();
}
return identifier;
}
}
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Implementation successfully meets PR objectives.

The MovingSensorHandler implementation effectively exposes the "moving" state as a motion sensor while following established patterns and HomeKit standards. The code is well-structured and maintainable.

Consider documenting the following in the PR description or README:

  1. The mapping between the "moving" state and motion detection
  2. Any specific behavior or limitations users should be aware of when using this with the SmartThings/Samjin Multipurpose sensor
🧰 Tools
🪛 Biome

[error] 16-16: Template literals are preferred over string concatenation.

Unsafe fix: Use a template literal.

(lint/style/useTemplate)


[error] 24-24: Template literals are preferred over string concatenation.

Unsafe fix: Use a template literal.

(lint/style/useTemplate)


[error] 26-26: Template literals are preferred over string concatenation.

Unsafe fix: Use a template literal.

(lint/style/useTemplate)

Comment on lines +9 to +21
constructor(expose: ExposesEntryWithProperty, otherExposes: ExposesEntryWithBinaryProperty[], accessory: BasicAccessory) {
super(
accessory,
expose as ExposesEntryWithBinaryProperty,
otherExposes,
MovingSensorHandler.generateIdentifier,
'Motion Sensor (moving)',
(n, t) => new hap.Service.MotionSensor(n, (MovingSensorHandler.exposesName + ' ' + (t ?? '')).trim()),
hap.Characteristic.MotionDetected,
true,
false
);
}
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

💡 Codebase verification

Refactor string concatenation to template literals across motion sensor handlers

Found similar string concatenation pattern in other motion sensor handlers. Let's update all instances for consistency:

  • src/converters/basic_sensors/moving.ts: Change to `${MovingSensorHandler.exposesName} ${t ?? ''}`.trim()
  • src/converters/basic_sensors/vibration.ts: Change to `${VibrationSensorHandler.exposesName} ${t ?? ''}`.trim()

The HomeKit service configuration is consistent across all implementations, using the correct characteristic hap.Characteristic.MotionDetected with proper initialization.

🔗 Analysis chain

Refactor string concatenation to use template literals.

The constructor implementation is correct, but we can improve readability by using template literals.

Apply this change:

-      (n, t) => new hap.Service.MotionSensor(n, (MovingSensorHandler.exposesName + ' ' + (t ?? '')).trim()),
+      (n, t) => new hap.Service.MotionSensor(n, `${MovingSensorHandler.exposesName} ${t ?? ''}`.trim()),

Let's verify the HomeKit service configuration:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for consistent motion sensor service usage across the codebase
rg -A 2 "new hap\.Service\.MotionSensor"

Length of output: 861

🧰 Tools
🪛 Biome

[error] 16-16: Template literals are preferred over string concatenation.

Unsafe fix: Use a template literal.

(lint/style/useTemplate)

Comment on lines +23 to +29
static generateIdentifier(endpoint: string | undefined) {
let identifier = MovingSensorHandler.exposesName + '_' + hap.Service.MotionSensor.UUID;
if (endpoint !== undefined) {
identifier += '_' + endpoint.trim();
}
return identifier;
}
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Refactor identifier generation to use template literals.

The identifier generation logic is correct, but we can improve readability by using template literals.

Apply these changes:

-    let identifier = MovingSensorHandler.exposesName + '_' + hap.Service.MotionSensor.UUID;
+    let identifier = `${MovingSensorHandler.exposesName}_${hap.Service.MotionSensor.UUID}`;
     if (endpoint !== undefined) {
-      identifier += '_' + endpoint.trim();
+      identifier = `${identifier}_${endpoint.trim()}`;
     }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
static generateIdentifier(endpoint: string | undefined) {
let identifier = MovingSensorHandler.exposesName + '_' + hap.Service.MotionSensor.UUID;
if (endpoint !== undefined) {
identifier += '_' + endpoint.trim();
}
return identifier;
}
static generateIdentifier(endpoint: string | undefined) {
let identifier = `${MovingSensorHandler.exposesName}_${hap.Service.MotionSensor.UUID}`;
if (endpoint !== undefined) {
identifier = `${identifier}_${endpoint.trim()}`;
}
return identifier;
}
🧰 Tools
🪛 Biome

[error] 24-24: Template literals are preferred over string concatenation.

Unsafe fix: Use a template literal.

(lint/style/useTemplate)


[error] 26-26: Template literals are preferred over string concatenation.

Unsafe fix: Use a template literal.

(lint/style/useTemplate)

@itavero
Copy link
Owner

itavero commented Nov 17, 2024

To do:

  • Update docs
  • Update change log
  • Add tests

@torandreroland
Copy link
Author

I've updated docs, added test and created changelog entry. OK?

Copy link

@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: 5

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Reviewing files that changed from the base of the PR and between bf4b05f and a117ab6.

📒 Files selected for processing (5)
  • .gitignore (1 hunks)
  • CHANGELOG.md (1 hunks)
  • docs/sensors.md (1 hunks)
  • test/basic_sensors.spec.ts (1 hunks)
  • test/exposes/smartthings/im6001-mpp01.json (1 hunks)
🧰 Additional context used
🪛 Biome
test/basic_sensors.spec.ts

[error] 664-664: Template literals are preferred over string concatenation.

Unsafe fix: Use a template literal.

(lint/style/useTemplate)

🔇 Additional comments (6)
test/exposes/smartthings/im6001-mpp01.json (3)

2-13: LGTM: Battery configuration is well-defined

The battery sensor configuration includes all necessary attributes and follows standard patterns. The description helpfully notes the potential 24-hour reporting delay.


24-35: LGTM: Linkquality configuration is complete

The link quality sensor configuration includes all necessary attributes and follows standard patterns with correct LQI range (0-255).


1-36: Verify configuration against similar devices

Let's ensure this configuration is consistent with other SmartThings/Samjin sensor configurations in the codebase.

✅ Verification successful

Let me gather more information about the overall structure and attributes of similar SmartThings devices.


Configuration is consistent with other SmartThings devices

The configuration follows the same structure and attribute patterns as other SmartThings devices in the codebase:

  • Identical structure for common attributes (battery, linkquality)
  • Consistent attribute ordering and formatting
  • Similar binary state definition pattern (value_on/value_off)
  • Proper categorization of diagnostic attributes
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Find and compare with other SmartThings sensor configurations
echo "Searching for similar SmartThings sensor configurations..."
fd -e json -p "test/exposes/**/smartthings" --exec cat {} \; | jq -c '.[] | select(.name == "moving" or .type == "binary")'

Length of output: 611


Script:

#!/bin/bash
# Compare full configuration structure with other SmartThings devices
echo "Checking other SmartThings device configurations..."
fd -e json -p "test/exposes/**/smartthings" --exec sh -c 'echo "=== $1 ==="; cat "$1"' sh {} \;

Length of output: 1939

.gitignore (1)

142-142: LGTM!

Adding .DS_Store to .gitignore is a good practice as these are macOS system files that should not be tracked in version control.

docs/sensors.md (1)

24-24: LGTM! Documentation format and technical mapping are accurate.

The new entry for the moving sensor maintains consistent formatting and correctly maps to the Motion Sensor service and Motion Detected characteristic.

test/basic_sensors.spec.ts (1)

649-691: LGTM! Well-structured test suite for the motion sensor.

The test suite follows the established patterns, properly tests both states of the motion sensor, and includes appropriate setup/teardown logic.

🧰 Tools
🪛 Biome

[error] 664-664: Template literals are preferred over string concatenation.

Unsafe fix: Use a template literal.

(lint/style/useTemplate)

test/exposes/smartthings/im6001-mpp01.json Show resolved Hide resolved
.gitignore Show resolved Hide resolved
docs/sensors.md Show resolved Hide resolved
@@ -6,6 +6,10 @@ Since version 1.0.0, we try to follow the [Semantic Versioning](https://semver.o

## [Unreleased]

### Added

- Expose moving as motion sensor.
Copy link

@coderabbitai coderabbitai bot Nov 20, 2024

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Enhance the changelog entry with more details.

The current entry could be more descriptive. Consider expanding it to match the style of other entries in the changelog by:

  1. Adding the PR reference
  2. Specifying which devices are affected
  3. Including any configuration requirements
-Expose moving as motion sensor.
+Expose moving state as motion sensor for SmartThings/Samjin Multipurpose sensors (see [#956](https://github.com/itavero/homebridge-z2m/pull/956))
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
- Expose moving as motion sensor.
- Expose moving state as motion sensor for SmartThings/Samjin Multipurpose sensors (see [#956](https://github.com/itavero/homebridge-z2m/pull/956))

Copy link
Owner

Choose a reason for hiding this comment

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

Still need to add a link to this PR at the end of this line (as I usually do for lines in the changelog, so people can find more information if they want it).

Copy link

Choose a reason for hiding this comment

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

@itavero, you can simply append the link to PR #956 at the end of the line, similar to how you usually reference other PRs in the changelog. For instance:

Expose moving state as motion sensor for SmartThings/Samjin Multipurpose sensors (see #956)

Copy link
Owner

Choose a reason for hiding this comment

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

I would not add the details you suggested (as there probably more devices that use this same property). The link seems fine.

Copy link

Choose a reason for hiding this comment

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

@itavero Understood! We'll keep it concise and just include the link. Thank you for clarifying.

(_/)
(·_·) …
/ \ … (sigh)

const newHarness = new ServiceHandlersTestHarness();

// Check service creation
movingSensorId = 'moving_' + hap.Service.MotionSensor.UUID;
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Use template literals for string concatenation

Consider using template literals for better readability.

-movingSensorId = 'moving_' + hap.Service.MotionSensor.UUID;
+movingSensorId = `moving_${hap.Service.MotionSensor.UUID}`;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
movingSensorId = 'moving_' + hap.Service.MotionSensor.UUID;
movingSensorId = `moving_${hap.Service.MotionSensor.UUID}`;
🧰 Tools
🪛 Biome

[error] 664-664: Template literals are preferred over string concatenation.

Unsafe fix: Use a template literal.

(lint/style/useTemplate)

Copy link
Contributor

🆗 Published SonarCloud and code coverage data.

@torandreroland
Copy link
Author

@itavero: Can this be merged now?

src/converters/basic_sensors/moving.ts Show resolved Hide resolved
test/exposes/smartthings/im6001-mpp01.json Show resolved Hide resolved
@@ -6,6 +6,10 @@ Since version 1.0.0, we try to follow the [Semantic Versioning](https://semver.o

## [Unreleased]

### Added

- Expose moving as motion sensor.
Copy link
Owner

Choose a reason for hiding this comment

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

Still need to add a link to this PR at the end of this line (as I usually do for lines in the changelog, so people can find more information if they want it).

@itavero
Copy link
Owner

itavero commented Dec 19, 2024

@itavero: Can this be merged now?

Sorry. Didn't notice that my few remarks were still pending to be published. Most of the time I use GitLab, so still have to get used to doing code reviews on GitHub.

@torandreroland
Copy link
Author

All right. Please let me know if there is something I should do.

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.

2 participants