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

Use extended address in WS API calls #21172

Open
wants to merge 6 commits into
base: dev
Choose a base branch
from

Conversation

agners
Copy link
Member

@agners agners commented Jun 26, 2024

Breaking change

Proposed change

This follows the HA Core change and passes the extended address to the OTBR WS API calls where necessary. It also follows the new OTBR info format which potentially includes multiple OTBRs.

This allows to support multiple OTBR managed by a single system.

Note: There is one corner case when none of the OTBR is found via discovery. In this case we offer to reset the OTBR. Currently we simply offer this for the primary or first one found.

Related Core PR: home-assistant/core#108282

Type of change

  • Dependency upgrade
  • Bugfix (non-breaking change which fixes an issue)
  • New feature (thank you!)
  • Breaking change (fix/feature causing existing functionality to break)
  • Code quality improvements to existing code or addition of tests

Example configuration

Additional information

  • This PR fixes or closes issue: fixes #
  • This PR is related to issue or discussion:
  • Link to documentation pull request:

Checklist

  • The code change is tested and works locally.
  • There is no commented out code in this PR.
  • Tests have been added to verify that the new code works.

If user exposed functionality or configuration variables are added/changed:

Summary by CodeRabbit

  • New Features

    • Enhanced Thread network management with added extended_pan_id support and extended address parameters in network functions.
  • Bug Fixes

    • Improved handling of OTBR information for network actions.
  • Translation

    • Added new language support for Thread network information and credential deletion messages.

This follows the HA Core change and passes the extended address to the
OTBR WS API calls where necessary. It also follows the new OTBR info
format which potentially includes multiple OTBRs.

This allows to support multiple OTBR managed by a single system.

Note: There is one corner case when none of the OTBR is found via
discovery. In this case we offer to reset the OTBR. Currently we simply
offer this for the primary or first one found.
@agners agners added the Feature PRs that are adding a new feature label Jun 26, 2024
@agners agners requested a review from bramkragten June 26, 2024 13:01
Copy link
Contributor

coderabbitai bot commented Jun 26, 2024

Walkthrough

Walkthrough

This update enhances the OTBRInfo functionalities within the otbr.ts file by adding an extended_pan_id property and incorporating an extended_address parameter in several OTBR functions. Additionally, type changes and functionality adjustments were made to the thread-config-panel.ts to handle these new properties. The en.json translations file was updated with new keys related to Thread network information and credential management.

Changes

Files/Groups Change Summary
src/data/otbr.ts - Added extended_pan_id property to OTBRInfo interface.
- Modified functions to use extended_address parameter.
- getOTBRInfo function now returns OTBRInfoDict type instead of OTBRInfo.
src/panels/config/integrations/.../thread-config-panel.ts - Updated _otbrInfo property type to OTBRInfoDict.
- Enhanced functions to utilize otbr information.
- Added/modified methods to handle OTBR actions with the new type and properties.
src/translations/en.json - Added new keys for "thread_network_info" and "thread_network_delete_credentials" under the "change_channel_text" section.

Sequence Diagram(s)

Updated OTBRInfo Retrieval and Use

sequenceDiagram
    participant User
    participant ThreadConfigPanel
    participant OTBRService
    participant HomeAssistant

    User->>ThreadConfigPanel: Navigate to Thread Config
    ThreadConfigPanel->>OTBRService: getOTBRInfo()
    OTBRService->>HomeAssistant: Request OTBRInfo
    HomeAssistant->>OTBRService: Return OTBRInfo including extended_pan_id
    OTBRService->>ThreadConfigPanel: Return OTBRInfoDict with extended_pan_id

    User->>ThreadConfigPanel: Perform Network Action (e.g., Create Network)
    ThreadConfigPanel->>OTBRService: OTBRCreateNetwork(extended_address)
    OTBRService->>HomeAssistant: Create Network with extended_address
    HomeAssistant->>OTBRService: Network Created
    OTBRService->>ThreadConfigPanel: Confirm Network Creation
Loading

Recent review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

Commits

Files that changed from the base of the PR and between be7956c and db091aa.

Files selected for processing (3)
  • src/data/otbr.ts (1 hunks)
  • src/panels/config/integrations/integration-panels/thread/thread-config-panel.ts (15 hunks)
  • src/translations/en.json (1 hunks)
Additional context used
Biome
src/panels/config/integrations/integration-panels/thread/thread-config-panel.ts

[error] 170-170: Forbidden non-null assertion.

Unsafe fix: Replace with optional chain operator ?. This operator includes runtime checks, so it is safer than the compile-only non-null assertion operator

(lint/style/noNonNullAssertion)


[error] 212-212: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 210-210: Excessive complexity detected.

Please refactor this function to reduce its complexity score from 31 to the max allowed complexity 15.

(lint/complexity/noExcessiveCognitiveComplexity)


[error] 337-337: Unexpected any. Specify a different type.

any disables many type checking rules. Its use should be avoided.

(lint/suspicious/noExplicitAny)


[error] 341-341: Forbidden non-null assertion.

Unsafe fix: Replace with optional chain operator ?. This operator includes runtime checks, so it is safer than the compile-only non-null assertion operator

(lint/style/noNonNullAssertion)


[error] 352-352: Unexpected any. Specify a different type.

any disables many type checking rules. Its use should be avoided.

(lint/suspicious/noExplicitAny)


[error] 353-353: Unexpected any. Specify a different type.

any disables many type checking rules. Its use should be avoided.

(lint/suspicious/noExplicitAny)


[error] 358-358: Forbidden non-null assertion.

Unsafe fix: Replace with optional chain operator ?. This operator includes runtime checks, so it is safer than the compile-only non-null assertion operator

(lint/style/noNonNullAssertion)


[error] 397-397: Forbidden non-null assertion.

Unsafe fix: Replace with optional chain operator ?. This operator includes runtime checks, so it is safer than the compile-only non-null assertion operator

(lint/style/noNonNullAssertion)


[error] 469-469: Unexpected any. Specify a different type.

any disables many type checking rules. Its use should be avoided.

(lint/suspicious/noExplicitAny)


[error] 470-470: Unexpected any. Specify a different type.

any disables many type checking rules. Its use should be avoided.

(lint/suspicious/noExplicitAny)


[error] 471-471: Unexpected any. Specify a different type.

any disables many type checking rules. Its use should be avoided.

(lint/suspicious/noExplicitAny)


[error] 478-478: Forbidden non-null assertion.

(lint/style/noNonNullAssertion)


[error] 493-493: Unexpected any. Specify a different type.

any disables many type checking rules. Its use should be avoided.

(lint/suspicious/noExplicitAny)


[error] 511-511: Unexpected any. Specify a different type.

any disables many type checking rules. Its use should be avoided.

(lint/suspicious/noExplicitAny)


[error] 539-539: Unexpected any. Specify a different type.

any disables many type checking rules. Its use should be avoided.

(lint/suspicious/noExplicitAny)


[error] 582-582: Unexpected any. Specify a different type.

any disables many type checking rules. Its use should be avoided.

(lint/suspicious/noExplicitAny)


[error] 592-592: Unexpected any. Specify a different type.

any disables many type checking rules. Its use should be avoided.

(lint/suspicious/noExplicitAny)


[error] 609-609: Unexpected any. Specify a different type.

any disables many type checking rules. Its use should be avoided.

(lint/suspicious/noExplicitAny)


[error] 660-660: Unexpected any. Specify a different type.

any disables many type checking rules. Its use should be avoided.

(lint/suspicious/noExplicitAny)

Gitleaks
src/translations/en.json

6537-6538: Identified a HashiCorp Terraform password field, risking unauthorized infrastructure configuration and security breaches.

(hashicorp-tf-password)

Additional comments not posted (8)
src/data/otbr.ts (5)

8-8: Added extended_pan_id to OTBRInfo.

This addition aligns with the PR's objectives to support extended addresses.


14-14: Updated return type of getOTBRInfo.

The function now returns OTBRInfoDict to handle multiple OTBRs, aligning with the new requirements.


19-25: Updated OTBRCreateNetwork to accept extended_address.

The addition of the extended_address parameter allows specifying the network to create, which is crucial for the new functionality.


30-35: Updated OTBRSetNetwork to include extended_address.

This update is necessary to specify the network based on the extended address, enhancing the functionality to manage multiple networks.


41-46: Updated OTBRSetChannel to include extended_address.

This change allows setting the channel for a specific network, which is essential for managing multiple networks.

src/panels/config/integrations/integration-panels/thread/thread-config-panel.ts (2)

31-31: Updated imports to include OTBRInfoDict.

This change is necessary to support the handling of multiple OTBRs in the configuration panel.


79-79: Added _otbrInfo state to store OTBR information.

This addition is crucial for managing state related to multiple OTBRs, aligning with the new functionality.

src/translations/en.json (1)

4553-4555: Translation additions are appropriate and clear.

The added translations for "Thread network information" and "Delete Thread network credentials" are clear and seem to align well with the rest of the application's terminology. These additions will help users understand their actions within the Home Assistant interface regarding Thread network management.


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration 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: 1

Outside diff range comments (1)
src/panels/config/integrations/integration-panels/thread/thread-config-panel.ts (1)

Line range hint 463-481: Specify a more accurate type than any for otbr.

Using any reduces type safety. Consider specifying a more accurate type for better type checking and maintainability.

- const otbr = (ev.currentTarget as any).otbr as OTBRInfo;
+ const otbr = (ev.currentTarget as HTMLElement).otbr as OTBRInfo;
Tools
Biome

[error] 472-472: Forbidden non-null assertion. (lint/style/noNonNullAssertion)


[error] 487-487: Unexpected any. Specify a different type. (lint/suspicious/noExplicitAny)

any disables many type checking rules. Its use should be avoided.

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: 2

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

Outside diff range comments (4)
src/panels/config/integrations/integration-panels/thread/thread-config-panel.ts (4)

Line range hint 491-504: Improve error handling in _resetBorderRouter.

The method uses any for error handling, which reduces type safety. Consider specifying a more accurate type for the error and enhance error handling to manage specific error cases.

try {
  await OTBRCreateNetwork(this.hass, otbr.extended_address);
} catch (err: unknown) {
  showAlertDialog(this, {
    title: this.hass.localize("ui.panel.config.thread.otbr_config_failed"),
    text: (err as Error).message,
  });
  // Log error or handle specific error cases here
}
Tools
Biome

[error] 472-472: Forbidden non-null assertion. (lint/style/noNonNullAssertion)


[error] 487-487: Unexpected any. Specify a different type. (lint/suspicious/noExplicitAny)

any disables many type checking rules. Its use should be avoided.


Line range hint 612-644: Improve error handling in _changeChannel.

The method uses any for error handling, which reduces type safety. Consider specifying a more accurate type for the error and enhance error handling to manage specific error cases.

try {
  const result = await OTBRSetChannel(this.hass, otbr.extended_address, channel);
  showAlertDialog(this, {
    title: this.hass.localize("ui.panel.config.thread.change_channel_initiated_title"),
    text: this.hass.localize("ui.panel.config.thread.change_channel_initiated_text", { delay: Math.floor(result.delay / 60) }),
  });
} catch (err: unknown) {
  if (err instanceof CustomError) { // Assume CustomError is a more specific error type you might expect
    showAlertDialog(this, {
      title: "Specific Error",
      text: err.message,
    });
  } else {
    showAlertDialog(this, {
      title: "Error",
      text: (err as Error).message,
    });
  }
}

Line range hint 514-533: Improve error handling in _setDataset.

The method uses any for error handling, which reduces type safety. Consider specifying a more accurate type for the error and enhance error handling to manage specific error cases.

try {
  await OTBRSetNetwork(this.hass, otbr.extended_address, preferedDatasetId);
} catch (err: unknown) {
  showAlertDialog(this, {
    title: this.hass.localize("ui.panel.config.thread.otbr_config_failed"),
    text: (err as Error).message,
  });
  // Log error or handle specific error cases here
}
Tools
Biome

[error] 533-533: Unexpected any. Specify a different type. (lint/suspicious/noExplicitAny)

any disables many type checking rules. Its use should be avoided.


Line range hint 654-654: Specify a more accurate type than any for ev.

Using any reduces type safety. Consider specifying a more accurate type for better type checking and maintainability.

- const dataset = (ev.currentTarget as any).networkDataset as ThreadDataSet;
+ const dataset = (ev.currentTarget as HTMLElement).networkDataset as ThreadDataSet;

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: 2

Outside diff range comments (2)
src/panels/config/integrations/integration-panels/thread/thread-config-panel.ts (2)

Line range hint 211-254: Complex logic in _renderNetwork needs refactoring.

The function _renderNetwork contains complex logic to determine the OTBR for a network. Consider refactoring to reduce complexity and improve maintainability.

- const otbr = this._otbrInfo && this._otbrInfo[router.extended_address];
- const showOverflow = ("dataset" in network && router.border_agent_id) || otbr;
+ const otbr = this._otbrInfo?.[router.extended_address];
+ const showOverflow = network.dataset && router.border_agent_id || otbr;
Tools
Biome

[error] 212-212: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 210-210: Excessive complexity detected.

Please refactor this function to reduce its complexity score from 31 to the max allowed complexity 15.

(lint/complexity/noExcessiveCognitiveComplexity)


Line range hint 471-497: Specify a more accurate type than any for event handling and improve error handling in border router methods.

Using any reduces type safety. Consider specifying a more accurate type for better type checking and maintainability. Also, add specific error handling for the API call in _resetBorderRouter.

- const otbr = (ev.currentTarget as any).otbr as OTBRInfo;
+ const otbr = (ev.currentTarget as HTMLElement).otbr as OTBRInfo || null;
if (!otbr) {
  return;
}
try {
  await OTBRCreateNetwork(this.hass, otbr.extended_address);
} catch (err: any) {
  showAlertDialog(this, {
    title: this.hass.localize("ui.panel.config.thread.otbr_config_failed"),
    text: err.message,
  });
  // Log error or handle specific error cases here
}
Tools
Biome

[error] 478-478: Forbidden non-null assertion.

(lint/style/noNonNullAssertion)


[error] 493-493: Unexpected any. Specify a different type.

any disables many type checking rules. Its use should be avoided.

(lint/suspicious/noExplicitAny)

Comment on lines +164 to +171
const otbrForNetwork =
this._otbrInfo &&
network.dataset &&
((network.dataset.preferred_extended_address &&
this._otbrInfo[network.dataset.preferred_extended_address]) ||
Object.values(this._otbrInfo).find(
(otbr) => otbr.extended_pan_id === network.dataset!.extended_pan_id
));
Copy link
Contributor

Choose a reason for hiding this comment

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

Refactor suggestion: Use optional chaining to simplify access.

The current implementation uses a complex chain of conditions. Simplifying this with optional chaining can enhance readability and safety.

- ((network.dataset.preferred_extended_address && this._otbrInfo[network.dataset.preferred_extended_address]) || Object.values(this._otbrInfo).find((otbr) => otbr.extended_pan_id === network.dataset!.extended_pan_id));
+ network.dataset?.preferred_extended_address ? this._otbrInfo?.[network.dataset.preferred_extended_address] : Object.values(this._otbrInfo ?? {}).find((otbr) => otbr.extended_pan_id === network.dataset?.extended_pan_id);
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
const otbrForNetwork =
this._otbrInfo &&
network.dataset &&
((network.dataset.preferred_extended_address &&
this._otbrInfo[network.dataset.preferred_extended_address]) ||
Object.values(this._otbrInfo).find(
(otbr) => otbr.extended_pan_id === network.dataset!.extended_pan_id
));
const otbrForNetwork =
this._otbrInfo &&
network.dataset &&
(network.dataset?.preferred_extended_address
? this._otbrInfo?.[network.dataset.preferred_extended_address]
: Object.values(this._otbrInfo ?? {}).find(
(otbr) => otbr.extended_pan_id === network.dataset?.extended_pan_id
));
Tools
Biome

[error] 170-170: Forbidden non-null assertion.

Unsafe fix: Replace with optional chain operator ?. This operator includes runtime checks, so it is safer than the compile-only non-null assertion operator

(lint/style/noNonNullAssertion)

Comment on lines +336 to +346
private _sendCredentials(ev) {
const otbr = (ev.currentTarget as any).otbr as OTBRInfo;
if (!otbr) {
return;
}
this.hass.auth.external!.fireMessage({
type: "thread/store_in_platform_keychain",
payload: {
mac_extended_address: this._otbrInfo.extended_address,
border_agent_id: this._otbrInfo.border_agent_id ?? "",
active_operational_dataset: this._otbrInfo.active_dataset_tlvs ?? "",
mac_extended_address: otbr.extended_address,
border_agent_id: otbr.border_agent_id ?? "",
active_operational_dataset: otbr.active_dataset_tlvs ?? "",
Copy link
Contributor

Choose a reason for hiding this comment

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

Use more specific types instead of any and add null checks.

Using any reduces type safety. Consider specifying a more accurate type and adding null checks for better error handling.

- const otbr = (ev.currentTarget as any).otbr as OTBRInfo;
+ const otbr = (ev.currentTarget as HTMLElement).otbr as OTBRInfo || null;
if (!otbr) {
  return;
}
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
private _sendCredentials(ev) {
const otbr = (ev.currentTarget as any).otbr as OTBRInfo;
if (!otbr) {
return;
}
this.hass.auth.external!.fireMessage({
type: "thread/store_in_platform_keychain",
payload: {
mac_extended_address: this._otbrInfo.extended_address,
border_agent_id: this._otbrInfo.border_agent_id ?? "",
active_operational_dataset: this._otbrInfo.active_dataset_tlvs ?? "",
mac_extended_address: otbr.extended_address,
border_agent_id: otbr.border_agent_id ?? "",
active_operational_dataset: otbr.active_dataset_tlvs ?? "",
private _sendCredentials(ev) {
const otbr = (ev.currentTarget as HTMLElement).otbr as OTBRInfo || null;
if (!otbr) {
return;
}
this.hass.auth.external!.fireMessage({
type: "thread/store_in_platform_keychain",
payload: {
mac_extended_address: otbr.extended_address,
border_agent_id: otbr.border_agent_id ?? "",
active_operational_dataset: otbr.active_dataset_tlvs ?? "",
Tools
Biome

[error] 337-337: Unexpected any. Specify a different type.

any disables many type checking rules. Its use should be avoided.

(lint/suspicious/noExplicitAny)


[error] 341-341: Forbidden non-null assertion.

Unsafe fix: Replace with optional chain operator ?. This operator includes runtime checks, so it is safer than the compile-only non-null assertion operator

(lint/style/noNonNullAssertion)

.network=${network}
.path=${mdiInformationOutline}
@click=${this._showDatasetInfo}
></ha-icon-button
>${!network.dataset.preferred && !network.routers?.length
? html`<ha-icon-button
label=${this.hass.localize(
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
label=${this.hass.localize(
.label=${this.hass.localize(


return html`<ha-card>
<div class="card-header">
${network.name}${network.dataset
? html`<div>
<ha-icon-button
label=${this.hass.localize(
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
label=${this.hass.localize(
.label=${this.hass.localize(

@frenck frenck added the smash Indicator this PR is close to finish for merging or closing label Jul 4, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
cla-signed Feature PRs that are adding a new feature smash Indicator this PR is close to finish for merging or closing wait for backend
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

4 participants