input area

This commit is contained in:
ari committed 2022-06-16 17:24:31 -04:00
1 parent 0fc3ea6146
commit 15c97b81b4
16 files changed
+699 -416

No files matched your search

+142
View File
@@ -0,0 +1,142 @@
import { Connection, getCollection } from "home-assistant-js-websocket";
import { useHassCollection } from "./useHassCollection";
import { Option, BaseOption } from "components/Inputs/InputAutoComplete";
import { EntityRegisteryItem, HassEntitiesRegistry } from "./types";
import { prettyName } from "utils/formatting";
export interface AreaRegistryItem {
area_id: string;
name: string;
picture: null | string;
}
export type AreaDB = Record<
string,
AreaRegistryItem & {
entity: Partial<EntityRegisteryItem>;
}
>;
export const fetchAreaRegistry = (conn: Connection) =>
Promise.all([
conn.sendMessagePromise<AreaRegistryItem[]>({
type: "config/area_registry/list",
}),
conn.sendMessagePromise<HassEntitiesRegistry>({
type: "config/entity_registry/list",
}),
]).then(([areas, er]) => {
const areaDB = areas.reduce<AreaDB>((all, item) => {
return {
...all,
[item.area_id]: {
...item,
entity: {},
},
};
}, {});
er.forEach((eri) => {
if (eri.area_id) {
areaDB[eri.area_id].entity = eri;
}
});
return areaDB;
});
export const areaRegistryColl = (conn: Connection) =>
getCollection<AreaDB>(conn, "_$earg", fetchAreaRegistry);
export type AreaOptionData = {
data: Partial<EntityRegisteryItem>;
};
export type AreaBaseOption = BaseOption<AreaOptionData>;
export type AreaOption = Option<AreaOptionData>;
export const useHAAreas = () => {
const areas = useHassCollection(areaRegistryColl);
const methods = {
getAreaEntityDomain(areaId: string): null | string {
if (!areas.ready) {
return null;
}
const entityId = areas.collection.state[areaId].entity.entity_id;
if (entityId) {
return entityId.toLowerCase().split(".")[0] ?? null;
}
return null;
},
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 = [], areaId) => {
const domain = methods.getAreaEntityDomain(areaId) ?? "";
if (!domains.includes(domain)) {
return [...all, `${methods.getLabel(areaId)} is not ${domainsStr}`];
}
return all;
}, []);
if (out.length > 0) {
return out;
}
}
return null;
},
getBaseOption(opt: AreaOption): AreaBaseOption {
if (!areas.ready) {
throw new Error("Not Ready!");
}
if (typeof opt === "string") {
return {
id: opt,
label: areas.collection.state[opt].name ?? prettyName(opt),
data: areas.collection.state[opt],
};
}
return opt;
},
getOptions(restrictToDomain?: string[]): AreaOption[] {
if (!areas.ready) {
return [];
}
let keys = Object.keys(areas.collection.state);
if (restrictToDomain) {
const domains = restrictToDomain.map((x) => x.toLowerCase());
keys = keys.filter((key) => {
const domain = methods.getAreaEntityDomain(key);
if (domain) {
return domains.includes(domain);
}
return false;
});
}
return keys.map((key) => ({
id: key,
label: areas.collection.state[key].name ?? prettyName(key),
data: areas.collection.state[key].entity,
}));
},
getLabel: (opt: AreaOption): string => {
if (typeof opt === "string") {
if (areas.ready) {
return areas.collection.state[opt].name ?? prettyName(opt);
}
return opt;
}
return opt.label ?? opt.id;
},
getID: (opt: AreaOption): string => {
if (typeof opt === "string") {
return opt;
}
return opt.id;
},
};
return methods;
};
+2 -1
View File
@@ -5,4 +5,5 @@ 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)
export const entityRegistryColl = (conn: Connection) => getCollection<HassEntitiesRegistry>(conn, "_$erc", fetchEntityRegistry)
+266 -238
View File
@@ -1,267 +1,295 @@
import { entitiesColl, servicesColl } from "home-assistant-js-websocket"
import { entitiesColl, servicesColl } from "home-assistant-js-websocket";
import { Namer } from "utils/formatting";
import { deviceRegistryColl } from "./DeviceRegistry";
import { entityRegistryColl } from "./EntityRegistry";
import { DeviceRegistryItem } from "./types";
import { useHassCollection } from "./useHassCollection"
import { useHAConnection } from './connection';
import { useHassCollection } from "./useHassCollection";
import { useHAConnection } from "./connection";
import { useSnackbar } from "notistack";
import { TypedHassService } from "./fieldTypes";
import { Option } from "components/Inputs/InputAutoComplete";
export type BaseOption<T = {}> = {
id: string,
label: string,
} & T
export type Option<T = {}> = string | BaseOption<T>;
export type EntityOption = Option<{ domain: string; }>
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 = {
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]}"`
return options.reduce<string[]>((all = [], key) => {
if (!domains.includes(key.toLowerCase().split('.')[0])) {
return [
...all,
`${methods.getLabel(key)} is not ${domainsStr}`
]
}
return all
}, [])
}
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
const entities = useHassCollection(entitiesColl, (state) => ({
domains: Array.from(
new Set(Object.keys(state).map((x) => x.split(".")[0])).keys()
).sort(),
}));
const methods = {
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 {
...entities,
...methods
}
}
}
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,
};
};
export type ServiceOption = Option<{
domain: string,
action: string,
description: string,
data: TypedHassService,
export type ServiceOption = Option<{
domain: string;
action: string;
description: string;
data: TypedHassService;
}>;
export type HAServicesState = ReturnType<typeof useHAServices>;
export const useHAServices = () => {
const services = useHassCollection(servicesColl);
const methods = {
getOption(name: string): TypedHassService | null {
if (!services.ready) {
return null;
}
try {
const [domain, action] = name.split('.');
return {
name: services.collection.state[domain][action].name ?? `${domain}.${action}`,
description: services.collection.state[domain][action].description ?? "",
target: services.collection.state[domain][action].target,
fields: services.collection.state[domain][action].fields,
}
}catch(err: any) {
console.warn(err)
return null
}
const services = useHassCollection(servicesColl);
const methods = {
getOption(name: string): TypedHassService | null {
if (!services.ready) {
return null;
}
try {
const [domain, action] = name.split(".");
return {
name:
services.collection.state[domain][action].name ??
`${domain}.${action}`,
description:
services.collection.state[domain][action].description ?? "",
target: services.collection.state[domain][action].target,
fields: services.collection.state[domain][action].fields,
};
} catch (err: any) {
console.warn(err);
return null;
}
},
getOptions(): ServiceOption[] {
if (!services.ready) {
return [];
}
return Object.keys(services.collection.state).reduce<ServiceOption[]>(
(all, domain) => {
const opts = Object.keys(
services.collection.state[domain]
).map<ServiceOption>((action) => ({
id: `${domain}.${action}`,
label:
services.collection.state[domain][action].name ??
`${domain}.${action}`,
description:
services.collection.state[domain][action].description ?? "",
domain,
action,
data: {
name:
services.collection.state[domain][action].name ??
`${domain}.${action}`,
description:
services.collection.state[domain][action].description ?? "",
target: services.collection.state[domain][action].target,
fields: services.collection.state[domain][action].fields,
},
}));
return all.concat(opts);
},
getOptions(): ServiceOption[] {
if (!services.ready) {
return []
}
return Object.keys(services.collection.state).reduce<ServiceOption[]>((all, domain) => {
const opts = Object.keys(services.collection.state[domain]).map<ServiceOption>(
action => ({
id: `${domain}.${action}`,
label: services.collection.state[domain][action].name ?? `${domain}.${action}`,
description: services.collection.state[domain][action].description ?? "",
domain,
action,
data: {
name: services.collection.state[domain][action].name ?? `${domain}.${action}`,
description: services.collection.state[domain][action].description ?? "",
target: services.collection.state[domain][action].target,
fields: services.collection.state[domain][action].fields,
}
})
)
return all.concat(opts);
}, [])
},
getLabel: (opt: ServiceOption): string => {
if (typeof opt === 'string') {
if (services.ready) {
try {
const [domain, action] = opt.split('.');
return services.collection.state[domain][action].name ?? opt;
} catch (_) { }
}
return opt
}
return opt.label ?? opt.id
},
getID: (opt: ServiceOption): string => {
if (typeof opt === 'string') {
return opt
}
return opt.id
[]
);
},
getLabel: (opt: ServiceOption): string => {
if (typeof opt === "string") {
if (services.ready) {
try {
const [domain, action] = opt.split(".");
return services.collection.state[domain][action].name ?? opt;
} catch (_) {}
}
}
return opt;
}
return opt.label ?? opt.id;
},
getID: (opt: ServiceOption): string => {
if (typeof opt === "string") {
return opt;
}
return opt.id;
},
};
return { ...services, ...methods }
}
return { ...services, ...methods };
};
export type DeviceRegistryOption = Option<{ manufacturer: string }>;
export const useHADeviceRegistry = () => {
const dr = useHassCollection(deviceRegistryColl)
const getLabelForItem = (item: DeviceRegistryItem) => item ? item.name_by_user ??
item.name ??
item.id :
"";
const methods = {
getOptions(): DeviceRegistryOption[] {
if (!dr.ready) {
return []
}
const keys = Object.keys(dr.collection.state);
return keys.map(key => ({
id: key,
label: getLabelForItem(dr.collection.state[key]) ?? key,
manufacturer: dr.collection.state[key].manufacturer ?? "",
}))
},
getLabel: (opt: DeviceRegistryOption): string => {
if (typeof opt === 'string') {
if (dr.ready) {
return getLabelForItem(dr.collection.state[opt]) ?? opt
}
return opt
}
return opt.label ?? opt.id
},
getID: (opt: DeviceRegistryOption): string => {
if (typeof opt === 'string') {
return opt
}
return opt.id
const dr = useHassCollection(deviceRegistryColl);
const getLabelForItem = (item: DeviceRegistryItem) =>
item ? item.name_by_user ?? item.name ?? item.id : "";
const methods = {
getOptions(): DeviceRegistryOption[] {
if (!dr.ready) {
return [];
}
const keys = Object.keys(dr.collection.state);
return keys.map((key) => ({
id: key,
label: getLabelForItem(dr.collection.state[key]) ?? key,
manufacturer: dr.collection.state[key].manufacturer ?? "",
}));
},
getLabel: (opt: DeviceRegistryOption): string => {
if (typeof opt === "string") {
if (dr.ready) {
return getLabelForItem(dr.collection.state[opt]) ?? opt;
}
}
return { ...dr, ...methods }
}
return opt;
}
return opt.label ?? opt.id;
},
getID: (opt: DeviceRegistryOption): string => {
if (typeof opt === "string") {
return opt;
}
return opt.id;
},
};
return { ...dr, ...methods };
};
export const useHAEntityRegistry = () => {
const dr = useHassCollection(entityRegistryColl)
return dr
}
const dr = useHassCollection(entityRegistryColl);
return dr;
};
export const useHA = () => {
const entities = useHAEntities();
const devices = useHADeviceRegistry();
const services = useHAServices();
const conn = useHAConnection();
const { enqueueSnackbar } = useSnackbar();
const entities = useHAEntities();
const devices = useHADeviceRegistry();
const services = useHAServices();
const conn = useHAConnection();
const { enqueueSnackbar } = useSnackbar();
const callService = async (
domain: string,
service: string,
data: any = {},
target: any = {},
) => {
if (conn.status === 'loaded') {
try {
const result = await conn.connection.sendMessagePromise({
"type": "call_service",
domain,
service,
target,
service_data: data
})
enqueueSnackbar(`Successfully called ${domain}.${service}`, {
"variant": "success",
})
return result
} catch (err: any) {
let msg = JSON.stringify(err)
if ('message' in err) {
msg = err.message
}
enqueueSnackbar(`Failed to call ${domain}.${service} because '${msg}'`, {
"variant": "error",
})
return
}
} if (conn.status === 'error') {
enqueueSnackbar(`Failed to call service because connection is '${conn.status}' -- ${conn.error}`, {
"variant": "error"
})
} else {
enqueueSnackbar(`Failed to call service because connection is '${conn.status}'`, {
"variant": "error"
})
const callService = async (
domain: string,
service: string,
data: any = {},
target: any = {}
) => {
if (conn.status === "loaded") {
try {
const result = await conn.connection.sendMessagePromise({
type: "call_service",
domain,
service,
target,
service_data: data,
});
enqueueSnackbar(`Successfully called ${domain}.${service}`, {
variant: "success",
});
return result;
} catch (err: any) {
let msg = JSON.stringify(err);
if ("message" in err) {
msg = err.message;
}
enqueueSnackbar(
`Failed to call ${domain}.${service} because '${msg}'`,
{
variant: "error",
}
);
return;
}
}
if (conn.status === "error") {
enqueueSnackbar(
`Failed to call service because connection is '${conn.status}' -- ${conn.error}`,
{
variant: "error",
}
);
} else {
enqueueSnackbar(
`Failed to call service because connection is '${conn.status}'`,
{
variant: "error",
}
);
}
};
const namer: Namer = {
getDeviceName(device_id) {
return devices.getLabel(device_id)
},
getEntityName(entity_id, maxEntities = 1) {
if (Array.isArray(entity_id)) {
return entity_id.slice(0, maxEntities).map(entities.getLabel).join(', ')
}
return entities.getLabel(entity_id)
},
getServiceName(service) {
return services.getLabel(service)
},
}
const namer: Namer = {
getDeviceName(device_id) {
return devices.getLabel(device_id);
},
getEntityName(entity_id, maxEntities = 1) {
if (Array.isArray(entity_id)) {
return entity_id
.slice(0, maxEntities)
.map(entities.getLabel)
.join(", ");
}
return entities.getLabel(entity_id);
},
getServiceName(service) {
return services.getLabel(service);
},
};
return {
entities,
devices,
services,
namer,
callService,
reloadAutomations: () => callService("automation", "reload")
}
}
return {
entities,
devices,
services,
namer,
callService,
reloadAutomations: () => callService("automation", "reload"),
};
};
+8 -7
View File
@@ -1,8 +1,8 @@
export type EntityRegisteryItem = {
area_id: string | null;
config_entry_id: string | null;
device_id: string | null;
disabled_by:
area_id: null | string;
config_entry_id: null | string;
device_id: null | string;
disabled_by:
| "integration"
| "user"
| "config_entry"
@@ -21,9 +21,10 @@ export type EntityRegisteryItem = {
| string
| null
;
icon: string | null;
name: string | null;
platform: string | null;
entity_id: string;
icon: null | string;
name: null | string;
platform: string;
}
export type DeviceRegistryItem = {