entity filter by integration
This commit is contained in:
1 parent
34a4bd93bd
commit
dde8d76772
15 files changed
+397
-263
No files matched your search
@@ -5,11 +5,9 @@ import {
|
||||
import { InputDevice } from "components/Inputs/InputDevice";
|
||||
import { InputDeviceCapabilties } from "components/Inputs/InputDeviceCapabilties";
|
||||
import { InputEntity } from "components/Inputs/InputEntities";
|
||||
import InputText from "components/Inputs/InputText";
|
||||
import { cleanUpUndefined } from "components/NodeEditor/OptionManager/OptionManager";
|
||||
import { DeviceBaseType, DeviceTypeCapability } from "haService/types";
|
||||
import { AutomationDeviceState } from "types/automations/common";
|
||||
import { prettyName } from "utils/formatting";
|
||||
|
||||
export type DeviceEditorProps<DBT extends DeviceBaseType> = {
|
||||
type: "action" | "condition" | "trigger";
|
||||
|
||||
@@ -1,98 +1,98 @@
|
||||
import "./InputTime.css";
|
||||
import { useState, useEffect, FC } from "react";
|
||||
import TextField from '@mui/material/TextField';
|
||||
import EditIcon from '@mui/icons-material/Edit';
|
||||
import TextField from "@mui/material/TextField";
|
||||
import EditIcon from "@mui/icons-material/Edit";
|
||||
import CloseIcon from "@mui/icons-material/Close";
|
||||
import IconButton from "@mui/material/IconButton"
|
||||
import IconButton from "@mui/material/IconButton";
|
||||
import { AutomationTime, AutomationTimeObject } from "types/automations/common";
|
||||
import { convertAutomationTimeToTimeObject, convertObjectToAutomationTimeString, milisecondsToObject } from "utils/time";
|
||||
import { convertStringToAutomationTimeObject, convertAutomationTimeToTimeString } from 'utils/time';
|
||||
import {
|
||||
convertAutomationTimeToTimeObject,
|
||||
convertObjectToAutomationTimeString,
|
||||
} from "utils/time";
|
||||
import { convertAutomationTimeToTimeString } from "utils/time";
|
||||
import { prettyName } from "utils/formatting";
|
||||
import FormControl from "@mui/material/FormControl";
|
||||
import InputLabel from '@mui/material/InputLabel';
|
||||
import Input from "@mui/material/Input";
|
||||
import FormHelperText from '@mui/material/FormHelperText';
|
||||
import InputLabel from "@mui/material/InputLabel";
|
||||
|
||||
// constants
|
||||
const fields: Array<keyof AutomationTimeObject> = [
|
||||
'hours',
|
||||
'minutes',
|
||||
'seconds',
|
||||
'milliseconds'
|
||||
]
|
||||
"hours",
|
||||
"minutes",
|
||||
"seconds",
|
||||
"milliseconds",
|
||||
];
|
||||
export interface Props {
|
||||
label: string;
|
||||
value?: AutomationTime;
|
||||
onChange: (v?: AutomationTimeObject) => void;
|
||||
}
|
||||
export const InputTime: FC<Props> = (props) => {
|
||||
|
||||
|
||||
// state
|
||||
const [disabled, setDisabled] = useState(!props.value)
|
||||
const [displayValue, setDisplayValue] = useState(convertAutomationTimeToTimeObject(props.value))
|
||||
const [disabled, setDisabled] = useState(!props.value);
|
||||
const [displayValue, setDisplayValue] = useState(
|
||||
convertAutomationTimeToTimeObject(props.value)
|
||||
);
|
||||
|
||||
// process display input
|
||||
const updateOne = (k: keyof AutomationTimeObject) => (v: string) => {
|
||||
if (Number(v) < 0) {
|
||||
setDisplayValue({
|
||||
...displayValue,
|
||||
[k]: 0
|
||||
})
|
||||
[k]: 0,
|
||||
});
|
||||
} else if (k === "hours") {
|
||||
setDisplayValue({
|
||||
...displayValue,
|
||||
[k]: Number(v)
|
||||
})
|
||||
[k]: Number(v),
|
||||
});
|
||||
} else if (k === "minutes") {
|
||||
let minutes = Number(v);
|
||||
let { hours = 0 } = displayValue
|
||||
let { hours = 0 } = displayValue;
|
||||
if (minutes > 59) {
|
||||
const additonalHours = Math.floor(minutes / 60)
|
||||
hours += additonalHours
|
||||
minutes = minutes - additonalHours * 60
|
||||
const additonalHours = Math.floor(minutes / 60);
|
||||
hours += additonalHours;
|
||||
minutes = minutes - additonalHours * 60;
|
||||
}
|
||||
setDisplayValue({
|
||||
...displayValue,
|
||||
minutes,
|
||||
hours,
|
||||
})
|
||||
});
|
||||
} else if (k === "seconds") {
|
||||
let seconds = Number(v);
|
||||
let { hours = 0, minutes = 0 } = displayValue
|
||||
let { hours = 0, minutes = 0 } = displayValue;
|
||||
if (seconds > 59) {
|
||||
const additonalHours = Math.floor(seconds / (60 * 60))
|
||||
hours += additonalHours
|
||||
seconds = seconds - additonalHours * 60
|
||||
const additonalHours = Math.floor(seconds / (60 * 60));
|
||||
hours += additonalHours;
|
||||
seconds = seconds - additonalHours * 60;
|
||||
}
|
||||
if (seconds > 59) {
|
||||
const additionalMinutes = Math.floor(seconds / 60)
|
||||
minutes += additionalMinutes
|
||||
seconds = seconds - additionalMinutes * 60
|
||||
const additionalMinutes = Math.floor(seconds / 60);
|
||||
minutes += additionalMinutes;
|
||||
seconds = seconds - additionalMinutes * 60;
|
||||
}
|
||||
setDisplayValue({
|
||||
...displayValue,
|
||||
minutes,
|
||||
hours,
|
||||
seconds,
|
||||
})
|
||||
});
|
||||
} else if (k === "milliseconds") {
|
||||
let milliseconds = Number(v);
|
||||
let { hours = 0, minutes = 0, seconds = 0 } = displayValue
|
||||
let { hours = 0, minutes = 0, seconds = 0 } = displayValue;
|
||||
if (milliseconds > 1000) {
|
||||
const additonalHours = Math.floor(milliseconds / (60 * 60 * 1000))
|
||||
hours += additonalHours
|
||||
milliseconds = milliseconds - additonalHours * 60 * 60 * 1000
|
||||
const additonalHours = Math.floor(milliseconds / (60 * 60 * 1000));
|
||||
hours += additonalHours;
|
||||
milliseconds = milliseconds - additonalHours * 60 * 60 * 1000;
|
||||
}
|
||||
if (milliseconds > 1000) {
|
||||
const additionalMinutes = Math.floor(milliseconds / (60 * 1000))
|
||||
minutes += additionalMinutes
|
||||
milliseconds = milliseconds - additionalMinutes * 60 * 1000
|
||||
const additionalMinutes = Math.floor(milliseconds / (60 * 1000));
|
||||
minutes += additionalMinutes;
|
||||
milliseconds = milliseconds - additionalMinutes * 60 * 1000;
|
||||
}
|
||||
if (milliseconds > 1000) {
|
||||
const additionalSeconds = Math.floor(milliseconds / 1000)
|
||||
seconds += additionalSeconds
|
||||
milliseconds = milliseconds - additionalSeconds * 1000
|
||||
const additionalSeconds = Math.floor(milliseconds / 1000);
|
||||
seconds += additionalSeconds;
|
||||
milliseconds = milliseconds - additionalSeconds * 1000;
|
||||
}
|
||||
setDisplayValue({
|
||||
...displayValue,
|
||||
@@ -100,49 +100,50 @@ export const InputTime: FC<Props> = (props) => {
|
||||
hours,
|
||||
seconds,
|
||||
milliseconds,
|
||||
})
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
// effect
|
||||
useEffect(() => {
|
||||
if (disabled && !props.value) {
|
||||
return
|
||||
return;
|
||||
}
|
||||
if (disabled) {
|
||||
props.onChange(undefined)
|
||||
props.onChange(undefined);
|
||||
} else {
|
||||
const pVal = convertAutomationTimeToTimeString(props.value);
|
||||
const cVal = convertObjectToAutomationTimeString(displayValue);
|
||||
if (pVal !== cVal) {
|
||||
props.onChange(displayValue)
|
||||
props.onChange(displayValue);
|
||||
}
|
||||
}
|
||||
}, [disabled, displayValue])
|
||||
// eslint-disable-next-line
|
||||
}, [disabled, displayValue]);
|
||||
|
||||
|
||||
return <div className="input-time">
|
||||
<InputLabel >{props.label}</InputLabel>
|
||||
<div className="input-time--inner">
|
||||
{fields.map(name =>
|
||||
<TextField
|
||||
key={name}
|
||||
variant="filled"
|
||||
label={prettyName(name)}
|
||||
defaultValue="00"
|
||||
InputProps={{
|
||||
disabled,
|
||||
type: "number",
|
||||
title: prettyName(name),
|
||||
}}
|
||||
value={displayValue[name] ?? 0}
|
||||
onChange={e => updateOne(name)(e.target.value)}
|
||||
/>
|
||||
)}
|
||||
<IconButton onClick={() => setDisabled(!disabled)}>
|
||||
{disabled ? <EditIcon /> : <CloseIcon />}
|
||||
</IconButton>
|
||||
return (
|
||||
<div className="input-time">
|
||||
<InputLabel>{props.label}</InputLabel>
|
||||
<div className="input-time--inner">
|
||||
{fields.map((name) => (
|
||||
<TextField
|
||||
key={name}
|
||||
variant="filled"
|
||||
label={prettyName(name)}
|
||||
defaultValue="00"
|
||||
InputProps={{
|
||||
disabled,
|
||||
type: "number",
|
||||
title: prettyName(name),
|
||||
}}
|
||||
value={displayValue[name] ?? 0}
|
||||
onChange={(e) => updateOne(name)(e.target.value)}
|
||||
/>
|
||||
))}
|
||||
<IconButton onClick={() => setDisabled(!disabled)}>
|
||||
{disabled ? <EditIcon /> : <CloseIcon />}
|
||||
</IconButton>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
);
|
||||
};
|
||||
@@ -1,5 +1,5 @@
|
||||
import { FC } from "react";
|
||||
import { useHAEntities } from "haService";
|
||||
import { useHAEntities } from "haService/HAEntities";
|
||||
import {
|
||||
InputAutoComplete,
|
||||
InputAutoCompletePropsBase,
|
||||
@@ -8,13 +8,17 @@ import { prettyName } from "utils/formatting";
|
||||
|
||||
export type InputEntityProps = InputAutoCompletePropsBase & {
|
||||
restrictToDomain?: string[];
|
||||
restrictedIntegrations?: string[];
|
||||
preSelectedEntityIds?: string[];
|
||||
};
|
||||
|
||||
export const InputEntity: FC<InputEntityProps> = (props) => {
|
||||
// state
|
||||
const entities = useHAEntities();
|
||||
let options = entities.getOptions(props.restrictToDomain);
|
||||
let options = entities.getOptions(
|
||||
props.restrictToDomain,
|
||||
props.restrictedIntegrations
|
||||
);
|
||||
if (props.preSelectedEntityIds) {
|
||||
options = options.filter((opt) =>
|
||||
props.preSelectedEntityIds?.includes(entities.getID(opt))
|
||||
@@ -29,7 +33,13 @@ export const InputEntity: FC<InputEntityProps> = (props) => {
|
||||
}
|
||||
});
|
||||
}
|
||||
errors.concat(entities.validateOptions(v, props.restrictToDomain) ?? []);
|
||||
errors.concat(
|
||||
entities.validateOptions(
|
||||
v,
|
||||
props.restrictToDomain,
|
||||
props.restrictedIntegrations
|
||||
) ?? []
|
||||
);
|
||||
if (errors.length > 0) {
|
||||
return errors;
|
||||
}
|
||||
@@ -42,7 +52,11 @@ export const InputEntity: FC<InputEntityProps> = (props) => {
|
||||
options={options}
|
||||
getID={entities.getID}
|
||||
getLabel={entities.getLabel}
|
||||
groupBy={(opt) => (typeof opt !== "string" ? prettyName(opt.domain) : "")}
|
||||
groupBy={(opt) =>
|
||||
typeof opt !== "string"
|
||||
? `${prettyName(opt.integration)}/ ${prettyName(opt.domain)}`
|
||||
: ""
|
||||
}
|
||||
/>
|
||||
);
|
||||
};
|
||||
@@ -1,7 +1,6 @@
|
||||
import "./InputYaml.css";
|
||||
import * as yaml from "js-yaml";
|
||||
import { useEffect, useState, ReactNode } from "react";
|
||||
import { useDelayEffect } from "utils/useDelay";
|
||||
|
||||
import CodeMirror from "@uiw/react-codemirror";
|
||||
import FormControl from "@mui/material/FormControl";
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { HAEntitiesState, HAService } from "haService";
|
||||
import { HAService } from "haService";
|
||||
import { HAEntitiesState } from "haService/HAEntities";
|
||||
import { FC } from "react";
|
||||
import { AutomationAction } from "types/automations/actions";
|
||||
import { AutomationCondition } from "types/automations/conditions";
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import "./ServiceEditorField.css";
|
||||
import { FC } from "react";
|
||||
import { FC, useRef } from "react";
|
||||
import { ServiceEditorOption } from "./options";
|
||||
import InputText from "components/Inputs/InputText";
|
||||
import InputNumber from "components/Inputs/InputNumber";
|
||||
@@ -10,6 +10,8 @@ import { prettyName } from "utils/formatting";
|
||||
import InputBoolean from "components/Inputs/InputBoolean";
|
||||
import { SelectorNumber, SelectorText } from "haService/fieldTypes";
|
||||
import InputYaml from "components/Inputs/InputYaml";
|
||||
import { useSnackbar } from "notistack";
|
||||
import { InputEntity } from "components/Inputs/InputEntities";
|
||||
|
||||
export type ServiceEditorFieldProps = {
|
||||
option: ServiceEditorOption;
|
||||
@@ -23,6 +25,8 @@ export const ServiceEditorField: FC<ServiceEditorFieldProps> = ({
|
||||
onChange,
|
||||
onRemove,
|
||||
}) => {
|
||||
const snackr = useSnackbar();
|
||||
const msgRef = useRef<Record<string, boolean>>({});
|
||||
const description = option.data.description ?? "";
|
||||
const isRequired = !onRemove;
|
||||
const label = option.label;
|
||||
@@ -97,6 +101,37 @@ export const ServiceEditorField: FC<ServiceEditorFieldProps> = ({
|
||||
return <InputBoolean {...prop} />;
|
||||
} else if ("object" in option.data.selector) {
|
||||
return <InputYaml {...prop} />;
|
||||
} else if ("entity" in option.data.selector) {
|
||||
const options = option.data.selector.entity ?? {};
|
||||
console.log(options);
|
||||
return (
|
||||
<InputEntity
|
||||
{...prop}
|
||||
multiple={false}
|
||||
restrictToDomain={options.domain ? [options.domain] : undefined}
|
||||
restrictedIntegrations={
|
||||
options.integration ? [options.integration] : undefined
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
if (option.data.selector) {
|
||||
if (!msgRef.current[JSON.stringify(option.data.selector)]) {
|
||||
msgRef.current[JSON.stringify(option.data.selector)] = true;
|
||||
snackr.enqueueSnackbar(
|
||||
<span>
|
||||
"{JSON.stringify(Object.keys(option.data.selector))}" is of a
|
||||
unimplemented! <br />
|
||||
Please report this to the maintainers.{" "}
|
||||
<b>For now, we leave you with a generic textbox!</b> <br />
|
||||
DEBUG="{JSON.stringify(option.data.selector)}"
|
||||
</span>,
|
||||
{
|
||||
variant: "warning",
|
||||
persist: true,
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
return <InputText {...prop} />;
|
||||
|
||||
@@ -439,6 +439,22 @@ export const LightTurnOn = makeExample({
|
||||
},
|
||||
});
|
||||
|
||||
export const ZhaLight = makeExample({
|
||||
name: "Turn Light",
|
||||
description: "",
|
||||
fields: {
|
||||
entity: {
|
||||
description: "Light Entity",
|
||||
selector: {
|
||||
entity: {
|
||||
domain: "light",
|
||||
integration: "zha",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
export const UltimateService = makeExample({
|
||||
name: "Ultimate Service",
|
||||
description: "Show a notification in the frontend.",
|
||||
|
||||
@@ -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