mirror of
https://github.com/ajnart/homarr.git
synced 2025-11-13 08:55:48 +01:00
feature: trigger automations (#1799)
This commit is contained in:
@@ -9,6 +9,10 @@
|
||||
"label": "Entity ID",
|
||||
"info": "Unique entity ID in Home Assistant. Copy by clicking on entity > Click on cog icon > Click on copy button at 'Entity ID'. Some custom entities may not be supported."
|
||||
},
|
||||
"automationId": {
|
||||
"label": "Optional automation ID",
|
||||
"info": "Your unique automation ID. Always starts with automation.XXXXX. If not set, widget will not be clickable and only display state. After click, entity state will be refreshed."
|
||||
},
|
||||
"displayName": {
|
||||
"label": "Display name"
|
||||
}
|
||||
|
||||
16
public/locales/en/modules/smart-home/trigger-automation.json
Normal file
16
public/locales/en/modules/smart-home/trigger-automation.json
Normal file
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"descriptor": {
|
||||
"name": "Home Assistant automation",
|
||||
"description": "Execute an automation",
|
||||
"settings": {
|
||||
"title": "Execute an automation",
|
||||
"automationId": {
|
||||
"label": "Automation ID",
|
||||
"info": "Your unique automation ID. Always starts with automation.XXXXX."
|
||||
},
|
||||
"displayName": {
|
||||
"label": "Display name"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { TRPCError } from '@trpc/server';
|
||||
|
||||
import Consola from 'consola';
|
||||
import { ZodError, z } from 'zod';
|
||||
|
||||
|
||||
@@ -8,21 +8,23 @@ import { createTRPCRouter, protectedProcedure } from '../../trpc';
|
||||
import { findAppProperty } from '~/tools/client/app-properties';
|
||||
import { getConfig } from '~/tools/config/getConfig';
|
||||
import { HomeAssistantSingleton } from '~/tools/singleton/HomeAssistantSingleton';
|
||||
import { ISmartHomeEntityStateWidget } from '~/widgets/smart-home/entity-state/entity-state.widget';
|
||||
|
||||
export const smartHomeEntityStateRouter = createTRPCRouter({
|
||||
retrieveStatus: protectedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
configName: z.string(),
|
||||
entityId: z.string().regex(/^[A-Za-z0-9-_\.]+$/)
|
||||
})
|
||||
// TODO: passing entity ID directly can be unsafe
|
||||
entityId: z.string().regex(/^[A-Za-z0-9-_\.]+$/),
|
||||
}),
|
||||
)
|
||||
.query(async ({ input }) => {
|
||||
const config = getConfig(input.configName);
|
||||
|
||||
const instances = config.apps.filter((app) => app.integration?.type == 'homeAssistant');
|
||||
|
||||
for (var instance of instances) {
|
||||
for (const instance of instances) {
|
||||
const url = new URL(instance.url);
|
||||
const client = HomeAssistantSingleton.getOrSet(url, findAppProperty(instance, 'apiKey'));
|
||||
const state = await client.getEntityState(input.entityId);
|
||||
@@ -31,17 +33,17 @@ export const smartHomeEntityStateRouter = createTRPCRouter({
|
||||
if (!(state.error instanceof ZodError)) {
|
||||
continue;
|
||||
}
|
||||
// Consola.error('Unable to handle entity state: ', state.error);
|
||||
|
||||
throw new TRPCError({
|
||||
code: 'NOT_IMPLEMENTED',
|
||||
message: `Unable to handle Home Assistant entity state. This may be due to malformed response or unknown entity type. Check log for details`
|
||||
message: `Unable to handle Home Assistant entity state. This may be due to malformed response or unknown entity type. Check log for details`,
|
||||
});
|
||||
}
|
||||
|
||||
if (!state.data) {
|
||||
throw new TRPCError({
|
||||
code: 'INTERNAL_SERVER_ERROR',
|
||||
message: `Home Assistant: Unable to connect to app '${instance.id}'. Check logs for details`
|
||||
message: `Home Assistant: Unable to connect to app '${instance.id}'. Check logs for details`,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -50,4 +52,42 @@ export const smartHomeEntityStateRouter = createTRPCRouter({
|
||||
|
||||
return null;
|
||||
}),
|
||||
triggerAutomation: protectedProcedure
|
||||
.input(z.object({
|
||||
widgetId: z.string(),
|
||||
configName: z.string(),
|
||||
})).mutation(async ({ input }) => {
|
||||
const config = getConfig(input.configName);
|
||||
const widget = config.widgets.find(widget => widget.id === input.widgetId) as ISmartHomeEntityStateWidget | null;
|
||||
|
||||
if (!widget) {
|
||||
Consola.error(`Referenced widget ${input.widgetId} does not exist on backend.`);
|
||||
throw new TRPCError({
|
||||
code: 'CONFLICT',
|
||||
message: 'Referenced widget does not exist on backend',
|
||||
});
|
||||
}
|
||||
|
||||
if (!widget.properties.automationId || widget.properties.automationId.length < 1) {
|
||||
Consola.error(`Referenced widget ${input.widgetId} does not have the required property set.`);
|
||||
throw new TRPCError({
|
||||
code: 'CONFLICT',
|
||||
message: 'Referenced widget does not have the required property',
|
||||
});
|
||||
}
|
||||
|
||||
const instances = config.apps.filter((app) => app.integration?.type == 'homeAssistant');
|
||||
|
||||
for (const instance of instances) {
|
||||
const url = new URL(instance.url);
|
||||
const client = HomeAssistantSingleton.getOrSet(url, findAppProperty(instance, 'apiKey'));
|
||||
const state = await client.triggerAutomation(widget.properties.automationId);
|
||||
|
||||
if (state) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -8,7 +8,7 @@ export class HomeAssistant {
|
||||
|
||||
constructor(url: URL, token: string) {
|
||||
if (!url.pathname.endsWith('/')) {
|
||||
url.pathname += "/";
|
||||
url.pathname += '/';
|
||||
}
|
||||
url.pathname += 'api';
|
||||
this.basePath = url;
|
||||
@@ -19,14 +19,14 @@ export class HomeAssistant {
|
||||
try {
|
||||
const response = await fetch(appendPath(this.basePath, `/states/${entityId}`), {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${this.token}`
|
||||
}
|
||||
'Authorization': `Bearer ${this.token}`,
|
||||
},
|
||||
});
|
||||
const body = await response.json();
|
||||
if (!response.ok) {
|
||||
return {
|
||||
success: false as const,
|
||||
error: body
|
||||
error: body,
|
||||
};
|
||||
}
|
||||
return entityStateSchema.safeParseAsync(body);
|
||||
@@ -34,8 +34,26 @@ export class HomeAssistant {
|
||||
Consola.error(`Failed to fetch from '${this.basePath}': ${err}`);
|
||||
return {
|
||||
success: false as const,
|
||||
error: err
|
||||
error: err,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async triggerAutomation(entityId: string) {
|
||||
try {
|
||||
const response = await fetch(appendPath(this.basePath, `/services/automation/trigger`), {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${this.token}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
'entity_id': entityId,
|
||||
}),
|
||||
method: 'POST'
|
||||
});
|
||||
return response.ok;
|
||||
} catch (err) {
|
||||
Consola.error(`Failed to fetch from '${this.basePath}': ${err}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,6 +31,7 @@ export const boardNamespaces = [
|
||||
'modules/bookmark',
|
||||
'modules/notebook',
|
||||
'modules/smart-home/entity-state',
|
||||
'modules/smart-home/trigger-automation',
|
||||
'widgets/error-boundary',
|
||||
'widgets/draggable-list',
|
||||
'widgets/location',
|
||||
|
||||
@@ -12,6 +12,7 @@ import mediaServer from './media-server/MediaServerTile';
|
||||
import notebook from './notebook/NotebookWidgetTile';
|
||||
import rss from './rss/RssWidgetTile';
|
||||
import smartHomeEntityState from './smart-home/entity-state/entity-state.widget';
|
||||
import smartHomeTriggerAutomation from './smart-home/trigger-automation/trigger-automation.widget';
|
||||
import torrent from './torrent/TorrentTile';
|
||||
import usenet from './useNet/UseNetTile';
|
||||
import videoStream from './video/VideoStreamTile';
|
||||
@@ -35,5 +36,6 @@ export default {
|
||||
'dns-hole-controls': dnsHoleControls,
|
||||
bookmark,
|
||||
notebook,
|
||||
'smart-home/entity-state': smartHomeEntityState
|
||||
'smart-home/entity-state': smartHomeEntityState,
|
||||
'smart-home/trigger-automation': smartHomeTriggerAutomation,
|
||||
};
|
||||
|
||||
@@ -16,6 +16,11 @@ const definition = defineWidget({
|
||||
defaultValue: 'sun.sun',
|
||||
info: true,
|
||||
},
|
||||
automationId: {
|
||||
type: 'text',
|
||||
info: true,
|
||||
defaultValue: '',
|
||||
},
|
||||
displayName: {
|
||||
type: 'text',
|
||||
defaultValue: 'Sun',
|
||||
@@ -39,6 +44,7 @@ interface SmartHomeEntityStateWidgetProps {
|
||||
function EntityStateTile({ widget }: SmartHomeEntityStateWidgetProps) {
|
||||
const { t } = useTranslation('modules/smart-home/entity-state');
|
||||
const { name: configName } = useConfigContext();
|
||||
const utils = api.useUtils();
|
||||
|
||||
const { data, isInitialLoading, isLoading, isError, error } =
|
||||
api.smartHomeEntityState.retrieveStatus.useQuery(
|
||||
@@ -48,10 +54,27 @@ function EntityStateTile({ widget }: SmartHomeEntityStateWidgetProps) {
|
||||
},
|
||||
{
|
||||
enabled: !!configName,
|
||||
refetchInterval: 2 * 60 * 1000
|
||||
}
|
||||
refetchInterval: 2 * 60 * 1000,
|
||||
},
|
||||
);
|
||||
|
||||
const { mutateAsync: mutateTriggerAutomationAsync } = api.smartHomeEntityState.triggerAutomation.useMutation({
|
||||
onSuccess: () => {
|
||||
void utils.smartHomeEntityState.invalidate();
|
||||
},
|
||||
});
|
||||
|
||||
const handleClick = async () => {
|
||||
if (!widget.properties.automationId) {
|
||||
return;
|
||||
}
|
||||
|
||||
await mutateTriggerAutomationAsync({
|
||||
configName: configName as string,
|
||||
widgetId: widget.id,
|
||||
});
|
||||
};
|
||||
|
||||
let dataComponent = null;
|
||||
|
||||
if (isError) {
|
||||
@@ -84,7 +107,15 @@ function EntityStateTile({ widget }: SmartHomeEntityStateWidgetProps) {
|
||||
}
|
||||
|
||||
return (
|
||||
<Center h="100%" w="100%">
|
||||
<Center
|
||||
onClick={handleClick}
|
||||
sx={() => {
|
||||
return {
|
||||
cursor: widget.properties.automationId?.length > 0 ? 'pointer' : undefined,
|
||||
};
|
||||
}}
|
||||
h="100%"
|
||||
w="100%">
|
||||
<Stack align="center" spacing={3}>
|
||||
<Text align="center" weight="bold" size="lg">
|
||||
{widget.properties.displayName}
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import { defineWidget } from '~/widgets/helper';
|
||||
import { IconSettingsAutomation } from '@tabler/icons-react';
|
||||
import { IWidget } from '~/widgets/widgets';
|
||||
import { useConfigContext } from '~/config/provider';
|
||||
import { api } from '~/utils/api';
|
||||
import { Center, Stack, Text } from '@mantine/core';
|
||||
|
||||
const definition = defineWidget({
|
||||
id: 'smart-home/trigger-automation',
|
||||
icon: IconSettingsAutomation,
|
||||
options: {
|
||||
automationId: {
|
||||
type: 'text',
|
||||
info: true,
|
||||
defaultValue: ''
|
||||
},
|
||||
displayName: {
|
||||
type: 'text',
|
||||
defaultValue: 'Sun',
|
||||
},
|
||||
},
|
||||
gridstack: {
|
||||
minWidth: 1,
|
||||
minHeight: 1,
|
||||
maxWidth: 12,
|
||||
maxHeight: 12,
|
||||
},
|
||||
component: TriggerAutomationTile,
|
||||
});
|
||||
|
||||
export type ISmartHomeTriggerAutomationWidget = IWidget<(typeof definition)['id'], typeof definition>;
|
||||
|
||||
interface SmartHomeTriggerAutomationWidgetProps {
|
||||
widget: ISmartHomeTriggerAutomationWidget;
|
||||
}
|
||||
|
||||
function TriggerAutomationTile({ widget }: SmartHomeTriggerAutomationWidgetProps) {
|
||||
const { name: configName } = useConfigContext();
|
||||
const utils = api.useUtils();
|
||||
|
||||
const { mutateAsync: mutateTriggerAutomationAsync } = api.smartHomeEntityState.triggerAutomation.useMutation({
|
||||
onSuccess: () => {
|
||||
void utils.smartHomeEntityState.invalidate();
|
||||
}
|
||||
});
|
||||
|
||||
const handleClick = async () => {
|
||||
await mutateTriggerAutomationAsync({
|
||||
configName: configName as string,
|
||||
widgetId: widget.id
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<Center onClick={handleClick} style={{ cursor: 'pointer' }} h="100%" w="100%">
|
||||
<Stack align="center" spacing={3}>
|
||||
<Text align="center" weight="bold" size="lg">
|
||||
{widget.properties.displayName}
|
||||
</Text>
|
||||
</Stack>
|
||||
</Center>
|
||||
);
|
||||
}
|
||||
|
||||
export default definition;
|
||||
Reference in New Issue
Block a user