entity filter by integration
This commit is contained in:
1 parent
34a4bd93bd
commit
dde8d76772
15 files changed
+397
-263
No files matched your search
@@ -1,21 +0,0 @@
|
||||
import { Connection, getCollection } from "home-assistant-js-websocket";
|
||||
import { DeviceRegistryItem, HassDevices } from './types';
|
||||
|
||||
|
||||
export const fetchDeviceRegistry = (conn: Connection): Promise<Record<string, DeviceRegistryItem>> =>
|
||||
conn.sendMessagePromise<HassDevices>({
|
||||
"type": "config/device_registry/list"
|
||||
}).then(
|
||||
data =>
|
||||
data.filter(
|
||||
({ disabled_by }) => !disabled_by
|
||||
).reduce<Record<string, DeviceRegistryItem>>((all, n) => {
|
||||
all[n.id] = n
|
||||
return all
|
||||
}, {}
|
||||
))
|
||||
export const deviceRegistryColl = (conn: Connection) => getCollection<Record<string, DeviceRegistryItem>>(
|
||||
conn,
|
||||
"_$drc",
|
||||
fetchDeviceRegistry
|
||||
)
|
||||
@@ -1,9 +0,0 @@
|
||||
import { Connection, getCollection } from "home-assistant-js-websocket";
|
||||
import { HassEntitiesRegistry } from './types';
|
||||
|
||||
|
||||
export const fetchEntityRegistry = (conn: Connection) => conn.sendMessagePromise<HassEntitiesRegistry>({
|
||||
"type": "config/entity_registry/list"
|
||||
}).then(data => data.filter(({ disabled_by }) => !disabled_by))
|
||||
export const entityRegistryColl = (conn: Connection) => getCollection<HassEntitiesRegistry>(conn, "_$erc", fetchEntityRegistry)
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
import { Option } from "components/Inputs/InputAutoComplete";
|
||||
import { useHassCollection } from "./useHassCollection";
|
||||
import { entitiesColl } from "home-assistant-js-websocket";
|
||||
import { useHAConnection } from "./connection";
|
||||
import { entitySourceColl } from "./additionalCollections";
|
||||
|
||||
export type EntityOption = Option<{ domain: string; integration: string }>;
|
||||
export type HAEntitiesState = ReturnType<typeof useHAEntities>;
|
||||
export const useHAEntities = () => {
|
||||
const entities = useHassCollection(entitiesColl, (state) => ({
|
||||
domains: Array.from(
|
||||
new Set(Object.keys(state).map((x) => x.split(".")[0])).keys()
|
||||
).sort(),
|
||||
}));
|
||||
const entitySource = useHassCollection(entitySourceColl);
|
||||
const methods = {
|
||||
getStates(inp: string[] | string, attribute?: string): string[] {
|
||||
if (!entities.ready) {
|
||||
return [];
|
||||
}
|
||||
let entityIds: string[] = [];
|
||||
if (typeof inp === "string") {
|
||||
entityIds = [inp];
|
||||
} else if (Array.isArray(inp)) {
|
||||
entityIds = inp;
|
||||
}
|
||||
let state: Set<string> = new Set();
|
||||
entityIds.forEach((entityId) => {
|
||||
if (entities.collection.state[entityId]) {
|
||||
if (!attribute) {
|
||||
state.add(entities.collection.state[entityId].state);
|
||||
} else {
|
||||
const val = (entities.collection.state[entityId]?.attributes ?? {})[
|
||||
attribute
|
||||
];
|
||||
if (val) {
|
||||
state.add(val);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
return Array.from(state.keys());
|
||||
},
|
||||
getAttributes(inp: string[] | string): string[] {
|
||||
if (!entities.ready) {
|
||||
return [];
|
||||
}
|
||||
let entityIds: string[] = [];
|
||||
if (typeof inp === "string") {
|
||||
entityIds = [inp];
|
||||
} else if (Array.isArray(inp)) {
|
||||
entityIds = inp;
|
||||
}
|
||||
let attributes: Set<string> = new Set();
|
||||
entityIds.forEach((entityId) => {
|
||||
const thisAttrs = new Set(
|
||||
Object.keys(entities.collection.state[entityId]?.attributes ?? {})
|
||||
);
|
||||
if (attributes.size === 0) {
|
||||
attributes = thisAttrs;
|
||||
} else {
|
||||
attributes = new Set([...attributes].filter((a) => thisAttrs.has(a)));
|
||||
}
|
||||
});
|
||||
return Array.from(attributes.keys());
|
||||
},
|
||||
getDomainList(): string[] {
|
||||
return entities.additional?.domains ?? [];
|
||||
},
|
||||
validateOptions(
|
||||
options: string[],
|
||||
restrictedDomains?: string[],
|
||||
restrictedIntegrations?: string[]
|
||||
): null | string[] {
|
||||
let out = options;
|
||||
if (restrictedDomains) {
|
||||
const domains = restrictedDomains.map((x) => x.toLowerCase());
|
||||
const domainsStr =
|
||||
domains.length > 1
|
||||
? `one of "${domains.join(", ")}"`
|
||||
: `"${domains[0]}"`;
|
||||
out = out.reduce<string[]>((all = [], key) => {
|
||||
if (!domains.includes(key.toLowerCase().split(".")[0])) {
|
||||
return [...all, `${methods.getLabel(key)} is not ${domainsStr}`];
|
||||
}
|
||||
return all;
|
||||
}, []);
|
||||
}
|
||||
if (restrictedIntegrations && entitySource.ready) {
|
||||
const domains = restrictedIntegrations.map((x) => x.toLowerCase());
|
||||
const domainsStr =
|
||||
domains.length > 1
|
||||
? `one of "${domains.join(", ")}"`
|
||||
: `"${domains[0]}"`;
|
||||
out = out.reduce<string[]>((all = [], key) => {
|
||||
const integration = entitySource.collection.state[key].domain;
|
||||
if (!domains.includes(integration.toLowerCase())) {
|
||||
return [...all, `${methods.getLabel(key)} is not ${domainsStr}`];
|
||||
}
|
||||
return all;
|
||||
}, []);
|
||||
}
|
||||
if (out.length > 0) {
|
||||
return out;
|
||||
}
|
||||
return null;
|
||||
},
|
||||
getOptions(
|
||||
restrictToDomain?: string[],
|
||||
restrictedIntegrations?: string[]
|
||||
): EntityOption[] {
|
||||
if (!entities.ready) {
|
||||
return [];
|
||||
}
|
||||
let keys = Object.keys(entities.collection.state);
|
||||
if (restrictToDomain) {
|
||||
const domains = restrictToDomain.map((x) => x.toLowerCase());
|
||||
keys = keys.filter((key) =>
|
||||
domains.includes(key.toLowerCase().split(".")[0])
|
||||
);
|
||||
}
|
||||
if (restrictedIntegrations && entitySource.ready) {
|
||||
const integrations = restrictedIntegrations.map((x) => x.toLowerCase());
|
||||
console.log(entitySource);
|
||||
keys = keys.filter((key) => {
|
||||
const integration = (
|
||||
entitySource.collection.state[key]?.domain ?? ""
|
||||
).toLowerCase();
|
||||
console.log({
|
||||
[key]: integration,
|
||||
domain: integrations[0],
|
||||
include: integrations.includes(integration),
|
||||
});
|
||||
return integrations.includes(integration);
|
||||
});
|
||||
}
|
||||
return keys.map((key) => ({
|
||||
id: key,
|
||||
label: entities.collection.state[key].attributes.friendly_name ?? key,
|
||||
domain: key.split(".")[0] ?? "n/a",
|
||||
integration: entitySource.ready
|
||||
? entitySource.collection.state[key].domain ?? "n/a"
|
||||
: "...",
|
||||
}));
|
||||
},
|
||||
getLabel: (opt: EntityOption): string => {
|
||||
if (typeof opt === "string") {
|
||||
if (entities.ready) {
|
||||
return (
|
||||
entities.collection.state[opt]?.attributes.friendly_name ?? opt
|
||||
);
|
||||
}
|
||||
return opt;
|
||||
}
|
||||
return opt.label ?? opt.id;
|
||||
},
|
||||
getID: (opt: EntityOption): string => {
|
||||
if (typeof opt === "string") {
|
||||
return opt;
|
||||
}
|
||||
return opt.id;
|
||||
},
|
||||
};
|
||||
return {
|
||||
...entities,
|
||||
...methods,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,45 @@
|
||||
import { Connection, getCollection } from "home-assistant-js-websocket";
|
||||
import {
|
||||
DeviceRegistryItem,
|
||||
EntitySource,
|
||||
HassDevices,
|
||||
HassEntitiesRegistry,
|
||||
} from "./types";
|
||||
|
||||
export const fetchDeviceRegistry = (
|
||||
conn: Connection
|
||||
): Promise<Record<string, DeviceRegistryItem>> =>
|
||||
conn
|
||||
.sendMessagePromise<HassDevices>({
|
||||
type: "config/device_registry/list",
|
||||
})
|
||||
.then((data) =>
|
||||
data
|
||||
.filter(({ disabled_by }) => !disabled_by)
|
||||
.reduce<Record<string, DeviceRegistryItem>>((all, n) => {
|
||||
all[n.id] = n;
|
||||
return all;
|
||||
}, {})
|
||||
);
|
||||
export const deviceRegistryColl = (conn: Connection) =>
|
||||
getCollection<Record<string, DeviceRegistryItem>>(
|
||||
conn,
|
||||
"_$drc",
|
||||
fetchDeviceRegistry
|
||||
);
|
||||
|
||||
export const fetchEntityRegistry = (conn: Connection) =>
|
||||
conn
|
||||
.sendMessagePromise<HassEntitiesRegistry>({
|
||||
type: "config/entity_registry/list",
|
||||
})
|
||||
.then((data) => data.filter(({ disabled_by }) => !disabled_by));
|
||||
export const entityRegistryColl = (conn: Connection) =>
|
||||
getCollection<HassEntitiesRegistry>(conn, "_$erc", fetchEntityRegistry);
|
||||
|
||||
export const fetchEntitySource = (conn: Connection) =>
|
||||
conn.sendMessagePromise<Record<string, EntitySource>>({
|
||||
type: "entity/source",
|
||||
});
|
||||
export const entitySourceColl = (conn: Connection) =>
|
||||
getCollection<Record<string, EntitySource>>(conn, "_$esc", fetchEntitySource);
|
||||
@@ -1,26 +1,25 @@
|
||||
import React, { FC } from "react";
|
||||
import { ComponentMeta, ComponentStory } from '@storybook/react';
|
||||
import { ComponentMeta, ComponentStory } from "@storybook/react";
|
||||
import { Page } from "components/Page";
|
||||
import { useHAEntities } from "haService";
|
||||
import { useHAEntities } from "haService/HAEntities";
|
||||
|
||||
const Test: FC<{ onRender: () => void }> = ({ onRender }) => {
|
||||
const conn = useHAEntities();
|
||||
onRender && onRender()
|
||||
return <code>
|
||||
{JSON.stringify(conn, null, 4)}
|
||||
</code>
|
||||
}
|
||||
const conn = useHAEntities();
|
||||
onRender && onRender();
|
||||
return <code>{JSON.stringify(conn, null, 4)}</code>;
|
||||
};
|
||||
|
||||
export default {
|
||||
title: 'Services/HA Entities',
|
||||
component: Test,
|
||||
parameters: { actions: { argTypesRegex: '^on.*' } },
|
||||
args: {}
|
||||
} as ComponentMeta<typeof Test>
|
||||
title: "Services/HA Entities",
|
||||
component: Test,
|
||||
parameters: { actions: { argTypesRegex: "^on.*" } },
|
||||
args: {},
|
||||
} as ComponentMeta<typeof Test>;
|
||||
|
||||
export const Base: ComponentStory<typeof Test> = props => {
|
||||
|
||||
return <Page>
|
||||
<Test {...props} />
|
||||
export const Base: ComponentStory<typeof Test> = (props) => {
|
||||
return (
|
||||
<Page>
|
||||
<Test {...props} />
|
||||
</Page>
|
||||
};
|
||||
);
|
||||
};
|
||||
@@ -10,8 +10,8 @@ import {
|
||||
HASendMessage,
|
||||
} from "./types";
|
||||
|
||||
export const getDeviceExtraWsCalls = (callHA: HASendMessage) => {
|
||||
const createUseThing = function <Args, HAData, STData>(
|
||||
export const makeCreateUseThing = (callHA: HASendMessage) =>
|
||||
function <Args, HAData, STData>(
|
||||
convertArgsToMessage: (a: Args) => MessageBase,
|
||||
transformHAData: (ha: HAData) => STData,
|
||||
defaultSTData: STData
|
||||
@@ -41,6 +41,9 @@ export const getDeviceExtraWsCalls = (callHA: HASendMessage) => {
|
||||
return stData;
|
||||
};
|
||||
};
|
||||
|
||||
export const getDeviceExtraWsCalls = (callHA: HASendMessage) => {
|
||||
const createUseThing = makeCreateUseThing(callHA);
|
||||
const reduceDeviceThings = function <
|
||||
Raw extends { type: string; subtype?: string; entity_id?: string }
|
||||
>(raw: Raw[]) {
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { entitiesColl, servicesColl } from "home-assistant-js-websocket";
|
||||
import { servicesColl } from "home-assistant-js-websocket";
|
||||
import { Namer } from "utils/formatting";
|
||||
import { deviceRegistryColl } from "./DeviceRegistry";
|
||||
import { entityRegistryColl } from "./EntityRegistry";
|
||||
import {
|
||||
deviceRegistryColl,
|
||||
entityRegistryColl,
|
||||
} from "./additionalCollections";
|
||||
import { DeviceRegistryItem, HASendMessage } from "./types";
|
||||
import { useHassCollection } from "./useHassCollection";
|
||||
import { useHAConnection } from "./connection";
|
||||
@@ -9,131 +11,7 @@ import { useSnackbar } from "notistack";
|
||||
import { TypedHassService } from "./fieldTypes";
|
||||
import { Option } from "components/Inputs/InputAutoComplete";
|
||||
import { getDeviceExtraWsCalls } from "./extras";
|
||||
|
||||
export type EntityOption = Option<{ domain: string }>;
|
||||
export type HAEntitiesState = ReturnType<typeof useHAEntities>;
|
||||
export const useHAEntities = () => {
|
||||
const entities = useHassCollection(entitiesColl, (state) => ({
|
||||
domains: Array.from(
|
||||
new Set(Object.keys(state).map((x) => x.split(".")[0])).keys()
|
||||
).sort(),
|
||||
}));
|
||||
const methods = {
|
||||
getStates(inp: string[] | string, attribute?: string): string[] {
|
||||
if (!entities.ready) {
|
||||
return [];
|
||||
}
|
||||
let entityIds: string[] = [];
|
||||
if (typeof inp === "string") {
|
||||
entityIds = [inp];
|
||||
} else if (Array.isArray(inp)) {
|
||||
entityIds = inp;
|
||||
}
|
||||
let state: Set<string> = new Set();
|
||||
entityIds.forEach((entityId) => {
|
||||
if (entities.collection.state[entityId]) {
|
||||
if (!attribute) {
|
||||
state.add(entities.collection.state[entityId].state);
|
||||
} else {
|
||||
const val = (entities.collection.state[entityId]?.attributes ?? {})[
|
||||
attribute
|
||||
];
|
||||
if (val) {
|
||||
state.add(val);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
return Array.from(state.keys());
|
||||
},
|
||||
getAttributes(inp: string[] | string): string[] {
|
||||
if (!entities.ready) {
|
||||
return [];
|
||||
}
|
||||
let entityIds: string[] = [];
|
||||
if (typeof inp === "string") {
|
||||
entityIds = [inp];
|
||||
} else if (Array.isArray(inp)) {
|
||||
entityIds = inp;
|
||||
}
|
||||
let attributes: Set<string> = new Set();
|
||||
entityIds.forEach((entityId) => {
|
||||
const thisAttrs = new Set(
|
||||
Object.keys(entities.collection.state[entityId]?.attributes ?? {})
|
||||
);
|
||||
if (attributes.size === 0) {
|
||||
attributes = thisAttrs;
|
||||
} else {
|
||||
attributes = new Set([...attributes].filter((a) => thisAttrs.has(a)));
|
||||
}
|
||||
});
|
||||
return Array.from(attributes.keys());
|
||||
},
|
||||
getDomainList(): string[] {
|
||||
return entities.additional?.domains ?? [];
|
||||
},
|
||||
validateOptions(
|
||||
options: string[],
|
||||
restrictedDomains?: string[]
|
||||
): null | string[] {
|
||||
if (restrictedDomains) {
|
||||
const domains = restrictedDomains.map((x) => x.toLowerCase());
|
||||
const domainsStr =
|
||||
domains.length > 1
|
||||
? `one of "${domains.join(", ")}"`
|
||||
: `"${domains[0]}"`;
|
||||
const out = options.reduce<string[]>((all = [], key) => {
|
||||
if (!domains.includes(key.toLowerCase().split(".")[0])) {
|
||||
return [...all, `${methods.getLabel(key)} is not ${domainsStr}`];
|
||||
}
|
||||
return all;
|
||||
}, []);
|
||||
if (out.length > 0) {
|
||||
return out;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
},
|
||||
getOptions(restrictToDomain?: string[]): EntityOption[] {
|
||||
if (!entities.ready) {
|
||||
return [];
|
||||
}
|
||||
let keys = Object.keys(entities.collection.state);
|
||||
if (restrictToDomain) {
|
||||
const domains = restrictToDomain.map((x) => x.toLowerCase());
|
||||
keys = keys.filter((key) =>
|
||||
domains.includes(key.toLowerCase().split(".")[0])
|
||||
);
|
||||
}
|
||||
return keys.map((key) => ({
|
||||
id: key,
|
||||
label: entities.collection.state[key].attributes.friendly_name ?? key,
|
||||
domain: key.split(".")[0] ?? "n/a",
|
||||
}));
|
||||
},
|
||||
getLabel: (opt: EntityOption): string => {
|
||||
if (typeof opt === "string") {
|
||||
if (entities.ready) {
|
||||
return (
|
||||
entities.collection.state[opt]?.attributes.friendly_name ?? opt
|
||||
);
|
||||
}
|
||||
return opt;
|
||||
}
|
||||
return opt.label ?? opt.id;
|
||||
},
|
||||
getID: (opt: EntityOption): string => {
|
||||
if (typeof opt === "string") {
|
||||
return opt;
|
||||
}
|
||||
return opt.id;
|
||||
},
|
||||
};
|
||||
return {
|
||||
...entities,
|
||||
...methods,
|
||||
};
|
||||
};
|
||||
import { useHAEntities } from "./HAEntities";
|
||||
|
||||
export type ServiceOption = Option<{
|
||||
domain: string;
|
||||
|
||||
@@ -107,3 +107,10 @@ export interface HaFormBooleanSchema extends HaFormBaseSchema {
|
||||
export interface HaFormTimeSchema extends HaFormBaseSchema {
|
||||
type: "positive_time_period_dict";
|
||||
}
|
||||
|
||||
export interface EntitySource {
|
||||
domain: string;
|
||||
custom_component: boolean;
|
||||
source: "config_entry" | "platform_config";
|
||||
config_entry?: string;
|
||||
}
|
||||
Reference in new issue
Block a user