Skip to content

Commit

Permalink
Merge pull request #672 from maxwroc/FixFormtting
Browse files Browse the repository at this point in the history
Fixed HA formatted state parsing
  • Loading branch information
maxwroc authored Feb 9, 2024
2 parents c76defb + 3ccc244 commit 9324646
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 4 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "battery-state-card",
"version": "3.1.5",
"version": "3.1.6",
"description": "Battery State card for Home Assistant",
"main": "dist/battery-state-card.js",
"author": "Max Chodorowski",
Expand Down
14 changes: 11 additions & 3 deletions src/entity-fields/battery-level.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ import { isNumber, log, toNumber } from "../utils";
*/
const stringValuePattern = /\b([0-9]{1,3})\s?%/;


/**
* HA formatted state pattern
*/
const formattedStatePattern = /(-?[0-9,.]+)\s?(.*)/;

/**
* Getts battery level/state
* @param config Entity config
Expand Down Expand Up @@ -100,9 +106,11 @@ export const getBatteryLevel = (config: IBatteryEntityConfig, hass?: HomeAssista
if (config.default_state_formatting !== false && !displayValue && state === entityData.state) {
const formattedState = hass.formatEntityState(entityData);

// assuming it is a number followed by unit
[state, unit] = formattedState.split(" ", 2);
unit = unit;
const matches = formattedState.match(formattedStatePattern);
if (matches != null) {
state = matches[1];
unit = matches[2] || unit;
}
}

return {
Expand Down
20 changes: 20 additions & 0 deletions test/other/entity-fields/battery-level.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -261,4 +261,24 @@ describe("Battery level", () => {

expect(state).toBe("2");
})

test.each([
["55 %", { state: "55", level: 55, unit: "%" }],
["66%", { state: "66", level: 66, unit: "%" }],
["-77lqi", { state: "-77", level: -77, unit: "lqi" }],
["-88.8lqi", { state: "-88.8", level: -88.8, unit: "lqi" }],
["99", { state: "99", level: 99, unit: "%" }],
])
("default HA formatting - various formatted states", (formattedResult: string, expected: { state: string, level: number, unit?: string }) => {

const hassMock = new HomeAssistantMock(true);
hassMock.addEntity("Mocked entity", "45");
hassMock.mockFunc("formatEntityState", () => formattedResult);

const { state, level, unit } = getBatteryLevel({ entity: "mocked_entity" }, hassMock.hass);

expect(level).toBe(expected.level);
expect(state).toBe(expected.state);
expect(unit).toBe(expected.unit);
});
});

0 comments on commit 9324646

Please sign in to comment.