Automate Home Assistant with Deno scripts

Deno is a new JavaScript and TypeScript runtime. It runs on Windows/Mac/Linux and is easy to install because it is just a single executable.

I wrote some helper methods to make it easy to connect to Home Assistant, stream the latest state and use that to automate things. It is available at balloob/home-assistant-deno.

To give a taste of how scripts can look, here is an example script to keep one entity in the opposite state of another:

import { parse } from "https://deno.land/[email protected]/flags/mod.ts";
import {
  getConnection,
  subscribeEntities,
  callService,
  HassEntities,
  HassEntity,
} from "https://raw.githubusercontent.com/balloob/home-assistant-deno/master/mod.ts";

const args = parse(Deno.args);

if (!args.from || !args.to) {
  console.error("Specify both --from <entity_id> and --to <entity_id>");
  Deno.exit(1);
}

const conn = await getConnection();

// light.kitchen -> light
const serviceDomain = args.to.split(".", 1)[0];

let lastState: HassEntity;

subscribeEntities(conn, async (entities: HassEntities) => {
  const fromState = entities[args.from];

  if (fromState === lastState) {
    return;
  }

  lastState = fromState;
  const serviceName = fromState.state === "on" ? "turn_off" : "turn_on";
  await callService(conn, serviceDomain, serviceName, { entity_id: args.to });
});

Since you write just JavaScript, you can make your scripts as simple or complex as you want.

3 Likes

As usual it will be fantastic. Of course, another thing to support :slight_smile: