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

Add default code to alarm_control_panel #20062

Merged

Conversation

gjohansson-ST
Copy link
Member

@gjohansson-ST gjohansson-ST commented Mar 11, 2024

Proposed change

Adds capabilities to add a default code to alarm_control_panel entities

Core PR: home-assistant/core#112540
Architecture decision: home-assistant/architecture#892

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

    • Introduced default_code property for alarm control panel entities, enhancing security and user control.
    • Added functionality to manage alarm modes with code protection, simplifying the process of setting alarm modes.
  • Improvements

    • Enhanced error handling and subscription management for alarm panel cards, ensuring a more robust user experience.
    • Streamlined the disarming process of alarm control panels with improved logic.
  • Refactor

    • Simplified code structure by consolidating alarm mode setting logic into a single function, improving maintainability and readability.

Copy link
Contributor

@silamon silamon left a comment

Choose a reason for hiding this comment

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

Code looks good. 👍 I've did a test and everything works as expected. Just there's a small difference in how the card behaves when a default code is correctly set:

  • In the more info dialog, you don't show the prompt anymore to enter the alarm code.
  • In the alarm card panel, you still see the code display while it's not really needed. It should be hidden there, if it's not needed to fill it in.

@silamon silamon marked this pull request as draft May 6, 2024 06:35
@gjohansson-ST gjohansson-ST force-pushed the alarm_control_panel-default-code branch from 57868d5 to b7ed985 Compare May 6, 2024 15:27
@gjohansson-ST
Copy link
Member Author

Code looks good. 👍 I've did a test and everything works as expected. Just there's a small difference in how the card behaves when a default code is correctly set:

I did an effort to try to figure it out but I hope maybe to get some help here.
getExtendedEntityRegistryEntry() is continuously loading and I think it's probably only worth to set it once when it renders first time. Any help you can offer @silamon ? Thanks

@silamon
Copy link
Contributor

silamon commented May 7, 2024

Either implement the firstUpdated or connectedCallback in the lit component:

 public async connectedCallback(): Promise<void> {
    super.connectedCallback();
    await this._loadEntityRegistryEntry();
 }
public async firstUpdated(changedProps: PropertyValues) {
    super.firstUpdated(changedProps);
    await this._loadEntityRegistryEntry();
}  

I would probably suggest to do connectedCallback, since firstUpdated is called right after the render and obviously would trigger a new render.

@gjohansson-ST gjohansson-ST marked this pull request as ready for review May 7, 2024 18:27
@gjohansson-ST
Copy link
Member Author

Thanks for the help @silamon
I had to go with firstUpdated as hass isn't available on the first pass so it seems I need that second render to get it and thereby being able to read the registry.

@gjohansson-ST
Copy link
Member Author

Core PR approved

@silamon
Copy link
Contributor

silamon commented May 24, 2024

Still a few things to decide on in my opinion:

  • While the keypad is gone now, most of the card is also gone.. I think it will need a UX review before approval
    image
  • When you entered a default code in the settings, you need to refresh the dashboard (note that we don't have an event now to catch an updated entry in a lovelace card)
  • When you have a wrong default code and click an alarm card panel action, it shows "invalid alarm code provided". In this case the user didn't provide anything and it might be unclear that it was entered it the settings.

@silamon
Copy link
Contributor

silamon commented May 24, 2024

I'm also adding the label back to indicate we should "wait for backend" before we can merge.

@gjohansson-ST
Copy link
Member Author

gjohansson-ST commented May 24, 2024

  • While the keypad is gone now, most of the card is also gone.. I think it will need a UX review before approval

I guess that makes sense. The card is a bit odd without anything really in it.

  • When you entered a default code in the settings, you need to refresh the dashboard (note that we don't have an event now to catch an updated entry in a lovelace card)

Can you provide some guidance how to fix that. As I have no clue otherwise.

  • When you have a wrong default code and click an alarm card panel action, it shows "invalid alarm code provided". In this case the user didn't provide anything and it might be unclear that it was entered it the settings.

Isn't that an error coming from the respective integration?

I'm also adding the label back to indicate we should "wait for backend" before we can merge.

That label is very confusing as the core PR is done and ready to merge, we are waiting for the frontend PR

@piitaya
Copy link
Member

piitaya commented May 24, 2024

Still a few things to decide on in my opinion:

  • While the keypad is gone now, most of the card is also gone.. I think it will need a UX review before approval

The design is ok. User can use other card if they don't have code (e.g. tile card)

  • When you entered a default code in the settings, you need to refresh the dashboard (note that we don't have an event now to catch an updated entry in a lovelace card)

We should be able to detect the changes using this code:

protected updated(changedProps: PropertyValues<typeof this>): void {
    super.updated(changedProps);

    if (changedProps.has("hass")) {
      const oldHass = changedProps.get("hass");
      const entityId = this._config?.entity;
      if (entityId) {
        if (oldHass?.entities[entityId] !== this.hass?.entities[entityId]) {
          this._loadEntityRegistryEntry();
        }
      }
    }
  }

@silamon
Copy link
Contributor

silamon commented May 25, 2024

  • When you have a wrong default code and click an alarm card panel action, it shows "invalid alarm code provided". In this case the user didn't provide anything and it might be unclear that it was entered it the settings.

Isn't that an error coming from the respective integration?

I just checked and yes, it's an error coming from the implementing integration.
Other questions have been answered by Paul. Thank you, Paul!

@gjohansson-ST gjohansson-ST force-pushed the alarm_control_panel-default-code branch from 63f941b to 3121f26 Compare May 26, 2024 14:29
Copy link
Contributor

coderabbitai bot commented May 26, 2024

Walkthrough

Walkthrough

The updates introduce AlarmControlPanelEntityOptions and enhance alarm control panel functionality across multiple components. This includes setting alarm modes with code protection, subscribing to entity registry updates, and improving error handling. The changes simplify the logic for setting alarm modes and managing default alarm codes, making the system more robust and user-friendly.

Changes

File Path Change Summary
src/data/entity_registry.ts Added AlarmControlPanelEntityOptions interface and integrated it into EntityRegistryOptions and EntityRegistryEntryUpdateParams.
src/panels/config/entities/entity-registry-settings-editor.ts Added logic to handle alarm_control_panel settings, including default_code property.
src/panels/lovelace/cards/hui-alarm-panel-card.ts Enhanced to manage default alarm codes, subscribe to entity registry updates, and improve error handling.
src/data/alarm_control_panel.ts Added setProtectedAlarmControlPanelMode function for setting alarm modes with code protection.
src/dialogs/more-info/controls/more-info-alarm_control_panel.ts Refactored _disarm() method to use setProtectedAlarmControlPanelMode.
src/panels/lovelace/card-features/hui-alarm-modes-card-feature.ts Simplified setting alarm modes by using setProtectedAlarmControlPanelMode.
src/state-control/alarm_control_panel/ha-state-control-alarm_control_panel-modes.ts Updated to use setProtectedAlarmControlPanelMode for setting alarm modes.

Sequence Diagram(s) (Beta)

Setting Alarm Mode with Code Protection

sequenceDiagram
    participant User
    participant UI as User Interface
    participant AlarmPanel as Alarm Control Panel
    participant Backend as Backend Service

    User ->> UI: Select Alarm Mode
    UI ->> AlarmPanel: Request to set mode with code
    AlarmPanel ->> UI: Prompt for code
    User ->> UI: Enter code
    UI ->> AlarmPanel: Send code and mode
    AlarmPanel ->> Backend: Validate code and set mode
    Backend -->> AlarmPanel: Mode set confirmation
    AlarmPanel -->> UI: Update UI with new mode
    UI -->> User: Display mode set confirmation
Loading

Recent Review Details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

Commits Files that changed from the base of the PR and between db434f6 and 120283d.
Files selected for processing (5)
  • src/data/alarm_control_panel.ts (2 hunks)
  • src/dialogs/more-info/controls/more-info-alarm_control_panel.ts (2 hunks)
  • src/panels/lovelace/card-features/hui-alarm-modes-card-feature.ts (2 hunks)
  • src/panels/lovelace/cards/hui-alarm-panel-card.ts (8 hunks)
  • src/state-control/alarm_control_panel/ha-state-control-alarm_control_panel-modes.ts (2 hunks)
Additional Context Used
Biome (49)
src/data/alarm_control_panel.ts (4)

21-28: The enum declaration should not be const


52-52: Forbidden non-null assertion.


8-12: All these imports are only used as types.


14-15: All these imports are only used as types.

src/dialogs/more-info/controls/more-info-alarm_control_panel.ts (3)

26-26: Forbidden non-null assertion.


1-1: Some named imports are only used as types.


6-10: Some named imports are only used as types.

src/panels/lovelace/card-features/hui-alarm-modes-card-feature.ts (13)

99-99: Unexpected any. Specify a different type.


101-101: Forbidden non-null assertion.


103-103: Forbidden non-null assertion.


118-118: Forbidden non-null assertion.


118-118: Forbidden non-null assertion.


140-140: Forbidden non-null assertion.


170-170: Forbidden non-null assertion.


1-2: All these imports are only used as types.


2-3: Some named imports are only used as types.


14-21: Some named imports are only used as types.


22-23: All these imports are only used as types.


23-24: All these imports are only used as types.


25-26: All these imports are only used as types.

src/panels/lovelace/cards/hui-alarm-panel-card.ts (20)

177-177: Forbidden non-null assertion.


178-178: Forbidden non-null assertion.


183-183: Forbidden non-null assertion.


184-184: Forbidden non-null assertion.


184-184: Forbidden non-null assertion.


201-201: Forbidden non-null assertion.


204-204: Forbidden non-null assertion.


207-207: Forbidden non-null assertion.


208-208: Forbidden non-null assertion.


306-306: Forbidden non-null assertion.


307-307: Do not use template literals if interpolation and special-character handling are not needed.


322-322: Forbidden non-null assertion.


327-327: Forbidden non-null assertion.


328-328: Forbidden non-null assertion.


334-334: Forbidden non-null assertion.


334-334: Unexpected any. Specify a different type.


335-335: Forbidden non-null assertion.


335-335: Forbidden non-null assertion.


341-341: Forbidden non-null assertion.


342-342: Forbidden non-null assertion.

src/state-control/alarm_control_panel/ha-state-control-alarm_control_panel-modes.ts (9)

47-47: Forbidden non-null assertion.


47-47: Forbidden non-null assertion.


51-51: Unexpected any. Specify a different type.


53-53: Forbidden non-null assertion.


55-55: Forbidden non-null assertion.


89-89: Forbidden non-null assertion.


1-1: Some named imports are only used as types.


9-15: Some named imports are only used as types.


16-17: All these imports are only used as types.


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

Outside diff range and nitpick comments (7)
src/state-control/alarm_control_panel/ha-state-control-alarm_control_panel-modes.ts (2)

Line range hint 54-54: Consider removing the non-null assertion operators (!) where possible to enhance code safety by handling potential null or undefined values explicitly.

Also applies to: 55-55, 56-56, 71-71, 72-72, 75-75, 86-86, 87-87, 95-95, 97-97, 131-131


Line range hint 93-93: Specify a more explicit type instead of using any to improve type safety and maintainability.

-    const mode = (ev.detail as any).value as AlarmMode;
+    const mode = (ev.detail as CustomEventDetail).value as AlarmMode;
src/panels/lovelace/cards/hui-alarm-panel-card.ts (2)

Line range hint 163-163: Multiple non-null assertions are used throughout the file. Consider validating these values before use to prevent runtime errors.

Also applies to: 164-164, 169-169, 170-170, 175-175, 180-180, 181-181, 281-281, 297-297, 302-302, 303-303, 309-309, 310-310, 316-316, 317-317, 318-318


Line range hint 282-282: Avoid using template literals when not necessary as it can lead to performance overhead.

-          ? this.hass!.localize(`ui.card.alarm_control_panel.clear_code`)
+          ? this.hass!.localize("ui.card.alarm_control_panel.clear_code")
src/panels/config/entities/entity-registry-settings-editor.ts (3)

Line range hint 283-283: Avoid using non-null assertions.

- this.hass.connection._entityRegistry?.refresh();
+ this.hass.connection._entityRegistry.refresh();

Non-null assertions can lead to runtime errors if the object is actually null. It's safer to handle potential nulls explicitly or ensure that the object is always defined.


Line range hint 757-757: Use template literals for string concatenation.

- "ui.dialogs.entity_registry.editor.stream.stream_orientation_" + num.toString();
+ `ui.dialogs.entity_registry.editor.stream.stream_orientation_${num}`;

- this.hass.localize("ui.dialogs.entity_registry.editor.change_device_area_link") + ")";
+ `${this.hass.localize("ui.dialogs.entity_registry.editor.change_device_area_link")})`;

Template literals provide a more readable and concise way to handle string concatenation, especially when variables are involved.

Also applies to: 833-834


Line range hint 845-846: Use optional chaining to safely access properties.

- this.hass.devices[this.entry.device_id].area_id
+ this.hass.devices[this.entry.device_id]?.area_id

Optional chaining is a safer way to access nested properties, especially when there's a possibility that an intermediate property could be undefined.

@silamon
Copy link
Contributor

silamon commented May 26, 2024

Retested, but it keeps reloading the registry again right now, eventually slowing down the frontend.

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

src/panels/lovelace/cards/hui-alarm-panel-card.ts Outdated Show resolved Hide resolved
@gjohansson-ST
Copy link
Member Author

Retested, but it keeps reloading the registry again right now, eventually slowing down the frontend.

I changed it again but I guess you tested it before.
With @piitaya suggestion it doesn't work as there is nothing triggering the update function at the moment.
I guess I need to modify shouldUpdate somehow but not sure how to only update when the default code is updated.

@silamon
Copy link
Contributor

silamon commented May 26, 2024

Retested, but it keeps reloading the registry again right now, eventually slowing down the frontend.

I changed it again but I guess you tested it before. With @piitaya suggestion it doesn't work as there is nothing triggering the update function at the moment. I guess I need to modify shouldUpdate somehow but not sure how to only update when the default code is updated.

No, I see. There's nothing that triggers the update and it's impossible from the more-info dialog to retrigger a card update at this time. Using a subscription on the entity does the trick, but I'm unsure if it would be accepted and the most performable solution for this case:

diff --git a/src/panels/lovelace/cards/hui-alarm-panel-card.ts b/src/panels/lovelace/cards/hui-alarm-panel-card.ts
index c5b11775b..e29cd5684 100644
--- a/src/panels/lovelace/cards/hui-alarm-panel-card.ts
+++ b/src/panels/lovelace/cards/hui-alarm-panel-card.ts
@@ -1,4 +1,4 @@
-import { HassEntity } from "home-assistant-js-websocket";
+import { HassEntity, UnsubscribeFunc } from "home-assistant-js-websocket";
 import {
   CSSResultGroup,
   LitElement,
@@ -33,6 +33,7 @@ import type { LovelaceCard } from "../types";
 import {
   ExtEntityRegistryEntry,
   getExtendedEntityRegistryEntry,
+  subscribeEntityRegistry,
 } from "../../../data/entity_registry";
 import { AlarmPanelCardConfig, AlarmPanelCardConfigState } from "./types";
 
@@ -107,6 +108,20 @@ class HuiAlarmPanelCard extends LitElement implements LovelaceCard {
 
   @query("#alarmCode") private _input?: HaTextField;
 
+  private _unsubEntityRegistry?: UnsubscribeFunc;
+
+  public connectedCallback() {
+    super.connectedCallback();
+  }
+
+  public disconnectedCallback() {
+    super.disconnectedCallback();
+    if (this._unsubEntityRegistry) {
+      this._unsubEntityRegistry();
+      this._unsubEntityRegistry = undefined;
+    }
+  }
+
   public async getCardSize(): Promise<number> {
     if (!this._config || !this.hass) {
       return 9;
@@ -136,18 +151,12 @@ class HuiAlarmPanelCard extends LitElement implements LovelaceCard {
     if (!this._config || !this.hass) {
       return;
     }
+
     const oldHass = changedProps.get("hass") as HomeAssistant | undefined;
     const oldConfig = changedProps.get("_config") as
       | AlarmPanelCardConfig
       | undefined;
-    if (changedProps.has("hass")) {
-      const entityId = this._config?.entity;
-      if (entityId) {
-        if (oldHass?.entities[entityId] !== this.hass?.entities[entityId]) {
-          this._loadEntityRegistryEntry();
-        }
-      }
-    }
+
     if (
       !oldHass ||
       !oldConfig ||
@@ -183,9 +192,18 @@ class HuiAlarmPanelCard extends LitElement implements LovelaceCard {
       return;
     }
     try {
-      this._entry = await getExtendedEntityRegistryEntry(
-        this.hass!,
-        this._config!.entity
+      this._unsubEntityRegistry = subscribeEntityRegistry(
+        this.hass!.connection,
+        async (entries) => {
+          if (
+            entries.some((entry) => entry.entity_id === this._config!.entity)
+          ) {
+            this._entry = await getExtendedEntityRegistryEntry(
+              this.hass!,
+              this._config!.entity
+            );
+          }
+        }
       );
     } catch (e) {
       this._entry = null;

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

Outside diff range and nitpick comments (2)
src/panels/lovelace/cards/hui-alarm-panel-card.ts (2)

Line range hint 178-178: Avoid using non-null assertions without checks.

Consider adding checks before non-null assertions or handling potential nulls to prevent runtime errors.

Also applies to: 179-179, 184-184, 185-185, 190-190, 195-195, 198-198, 201-201, 202-202, 305-305, 321-321, 326-326, 327-327, 333-333, 334-334, 340-340


Line range hint 306-306: Avoid unnecessary template literals.

- return this.hass!.localize(`component.alarm_control_panel.entity_component._.state.${entityState}`) || entityState;
+ return this.hass!.localize("component.alarm_control_panel.entity_component._.state." + entityState) || entityState;

@gjohansson-ST
Copy link
Member Author

No, I see. There's nothing that triggers the update and it's impossible from the more-info dialog to retrigger a card update at this time. Using a subscription on the entity does the trick, but I'm unsure if it would be accepted and the most performable solution for this case:

I adapted the code to your proposal and it works like a charm.
I noticed it's only the area card which already has this subscription but then it sort of confirms it's the only only way to handle it right now.

@bramkragten bramkragten requested a review from piitaya May 29, 2024 07:16
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: 3

Outside diff range comments (7)
src/state-control/alarm_control_panel/ha-state-control-alarm_control_panel-modes.ts (2)

Line range hint 51-51: Specify a type for ev.detail to avoid using any.

-    const mode = (ev.detail as any).value as AlarmMode;
+    interface Detail {
+        value: AlarmMode;
+    }
+    const mode = ((ev.detail as Detail).value);

Line range hint 53-53: Avoid using non-null assertions. Instead, ensure that the variables are defined before use.

-    if (mode === this.stateObj!.state) return;
+    if (this.stateObj && mode === this.stateObj.state) return;

-    const oldMode = this._getCurrentMode(this.stateObj!);
+    if (this.stateObj) {
+        const oldMode = this._getCurrentMode(this.stateObj);
+    }

-        .disabled=${this.stateObj!.state === UNAVAILABLE}
+    if (this.stateObj) {
+        .disabled=${this.stateObj.state === UNAVAILABLE}
+    }

Also applies to: 55-55, 89-89

src/data/alarm_control_panel.ts (2)

Line range hint 21-28: The enum declaration should not be const as it is not a constant value but a type that can be extended or implemented.

- export const enum AlarmControlPanelEntityFeature {
+ export enum AlarmControlPanelEntityFeature {

Line range hint 52-52: Avoid using non-null assertions. Instead, ensure that the variables are defined before use.

-  hass!.callService("alarm_control_panel", `alarm_${action}`, {
+  if (hass) {
+      hass.callService("alarm_control_panel", `alarm_${action}`, {
+          entity_id: entity,
+          code,
+      });
+  } else {
+      console.error("Hass is undefined");
+  }
src/panels/lovelace/card-features/hui-alarm-modes-card-feature.ts (2)

Line range hint 99-99: Specify a type for ev.detail to avoid using any.

-    const mode = (ev.detail as any).value as AlarmMode;
+    interface Detail {
+        value: AlarmMode;
+    }
+    const mode = ((ev.detail as Detail).value);

Line range hint 101-101: Avoid using non-null assertions. Instead, ensure that the variables are defined before use.

-    if (mode === this.stateObj!.state) return;
+    if (this.stateObj && mode === this.stateObj.state) return;

-    const oldMode = this._getCurrentMode(this.stateObj!);
+    if (this.stateObj) {
+        const oldMode = this._getCurrentMode(this.stateObj);
+    }

-    setProtectedAlarmControlPanelMode(this, this.hass!, this.stateObj!, mode);
+    if (this.hass && this.stateObj) {
+        setProtectedAlarmControlPanelMode(this, this.hass, this.stateObj, mode);
+    } else {
+        console.error("Hass or StateObj is undefined");
+    }

-        .label=${this.hass.localize("ui.card.alarm_control_panel.disarm")}
+    if (this.hass) {
+        .label=${this.hass.localize("ui.card.alarm_control_panel.disarm")}
+    }

-        .disabled=${this.stateObj!.state === UNAVAILABLE}
+    if (this.stateObj) {
+        .disabled=${this.stateObj.state === UNAVAILABLE}
+    }

Also applies to: 103-103, 118-118, 140-140, 170-170

src/panels/lovelace/cards/hui-alarm-panel-card.ts (1)

Line range hint 177-177: Avoid using non-null assertions and template literals unnecessarily. Instead, ensure that the variables are defined before use and use string concatenation where interpolation is not needed.

-      this.hass!.localize("state.default.unavailable")
+    if (this.hass) {
+        this.hass.localize("state.default.unavailable")
+    }

-      this.hass!.localize(
+    if (this.hass) {
+        this.hass.localize(
          `component.alarm_control_panel.entity_component._.state.${entityState}`
        ) || entityState;
+    }

-    const val = (e.currentTarget! as any).value;
+    if (e.currentTarget) {
+        const val = (e.currentTarget as HTMLButtonElement).value;
+    }

-    callAlarmAction(
-      this.hass!,
-      this._config!.entity,
-      (e.currentTarget! as any).action,
-      input?.value || undefined
-    );
+    if (this.hass && this._config && e.currentTarget) {
+        callAlarmAction(
+            this.hass,
+            this._config.entity,
+            (e.currentTarget as HTMLButtonElement).action,
+            input?.value || undefined
+        );
+    }

Also applies to: 178-178, 183-183, 184-184, 184-184, 201-201, 204-204, 207-207, 208-208, 306-306, 307-307, 322-322, 327-327, 328-328, 334-334, 334-334, 335-335, 335-335, 341-341, 342-342

@piitaya
Copy link
Member

piitaya commented May 29, 2024

@gjohansson-ST I updated the PR to have it ready for today's beta.
Here's the fixes :

  • check for default code for every alarm call (It was missing for card features and disarm in more info)
  • fix subscription to entity registry

@frenck frenck merged commit 91e5fca into home-assistant:dev May 29, 2024
13 checks passed
@gjohansson-ST gjohansson-ST deleted the alarm_control_panel-default-code branch May 29, 2024 11:19
@gjohansson-ST
Copy link
Member Author

@gjohansson-ST I updated the PR to have it ready for today's beta. Here's the fixes :

Thanks @piitaya 👍

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

Successfully merging this pull request may close these issues.

None yet

4 participants