├── .gitignore
├── images
├── readme.png
├── input-stations.png
├── numberbox-images.png
└── progressbar-customization.png
├── hacs.json
├── .github
└── workflows
│ ├── build.yml
│ └── hacs.yml
├── src
├── styles.ts
├── types.ts
├── opensprinkler-state.ts
├── relative_time.ts
├── helpers.ts
├── editor.ts
├── ha_entity_registry.ts
├── opensprinkler-generic-entity-row.ts
├── ha_style.ts
├── opensprinkler-more-info-dialog.ts
├── opensprinkler-control.ts
└── opensprinkler-card.ts
├── tsconfig.json
├── CONFIGURATION.md
├── rollup.config.dev.js
├── rollup.config.js
├── package.json
├── README.md
└── LICENSE
/.gitignore:
--------------------------------------------------------------------------------
1 | /node_modules/
2 | /dist
3 |
--------------------------------------------------------------------------------
/images/readme.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rianadon/opensprinkler-card/HEAD/images/readme.png
--------------------------------------------------------------------------------
/images/input-stations.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rianadon/opensprinkler-card/HEAD/images/input-stations.png
--------------------------------------------------------------------------------
/images/numberbox-images.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rianadon/opensprinkler-card/HEAD/images/numberbox-images.png
--------------------------------------------------------------------------------
/hacs.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "OpenSprinkler Card",
3 | "render_readme": true,
4 | "filename": "opensprinkler-card.js"
5 | }
6 |
--------------------------------------------------------------------------------
/images/progressbar-customization.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rianadon/opensprinkler-card/HEAD/images/progressbar-customization.png
--------------------------------------------------------------------------------
/.github/workflows/build.yml:
--------------------------------------------------------------------------------
1 | name: 'Build'
2 |
3 | on:
4 | push:
5 | branches:
6 | - main
7 | pull_request:
8 | branches:
9 | - main
10 |
11 | jobs:
12 | build:
13 | name: Test build
14 | runs-on: ubuntu-latest
15 | steps:
16 | - uses: actions/checkout@v1
17 | - name: Build
18 | run: |
19 | npm install
20 | npm run build
21 |
--------------------------------------------------------------------------------
/.github/workflows/hacs.yml:
--------------------------------------------------------------------------------
1 | name: HACS Action
2 |
3 | on:
4 | push:
5 | pull_request:
6 | schedule:
7 | - cron: "0 0 * * *"
8 |
9 | jobs:
10 | hacs:
11 | name: HACS Action
12 | runs-on: "ubuntu-latest"
13 | steps:
14 | - uses: "actions/checkout@v2"
15 | - name: HACS Action
16 | uses: "hacs/action@main"
17 | with:
18 | category: "plugin"
19 |
--------------------------------------------------------------------------------
/src/styles.ts:
--------------------------------------------------------------------------------
1 | import { css } from 'lit';
2 |
3 | export const styles = css`
4 | opensprinkler-timer-bar-entity-row {
5 | height: var(--opensprinkler-timer-height);
6 | }
7 |
8 | opensprinkler-state {
9 | height: var(--opensprinkler-line-height);
10 | color: var(--primary-text-color);
11 | display: flex;
12 | justify-content: center;
13 | flex-direction: column;
14 | }
15 |
16 | .header {
17 | margin-left: 56px;
18 | margin-top: 16px;
19 | color: var(--secondary-text-color);
20 | }
21 | `;
22 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "es2017",
4 | "module": "esnext",
5 | "moduleResolution": "node",
6 | "lib": [
7 | "es2020",
8 | "dom",
9 | "dom.iterable"
10 | ],
11 | "noEmit": true,
12 | "noUnusedParameters": true,
13 | "noImplicitReturns": true,
14 | "noFallthroughCasesInSwitch": true,
15 | "strict": true,
16 | "noImplicitAny": false,
17 | "skipLibCheck": true,
18 | "resolveJsonModule": true,
19 | "experimentalDecorators": true
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/CONFIGURATION.md:
--------------------------------------------------------------------------------
1 | # Default Card Configuration
2 |
3 | ```yaml
4 | name: "Sprinkler"
5 | icon: "mdi:sprinkler-variant"
6 |
7 | hide_dots: false
8 | hide_disabled: false
9 |
10 | card_line_height: "small"
11 | timer_line_height: "medium"
12 | popup_line_height: "small"
13 |
14 | icons: {
15 | # If any of these icons are set to `false`,
16 | # the default entity icon will be used
17 | run_once: 'mdi:auto-fix'
18 | station: {
19 | active: 'mdi:water'
20 | active_disabled: 'mdi:water-off'
21 | idle: 'mdi:water-outline'
22 | idle_disabled: 'mdi:water-off-outline'
23 | }
24 | program: {
25 | active: 'mdi:timer'
26 | active_disabled: 'mdi:timer-off'
27 | idle: 'mdi:timer-outline'
28 | idle_disabled: 'mdi:timer-off-outline'
29 | }
30 | }
31 | ```
32 |
--------------------------------------------------------------------------------
/rollup.config.dev.js:
--------------------------------------------------------------------------------
1 | import resolve from "rollup-plugin-node-resolve";
2 | import typescript from "rollup-plugin-typescript2";
3 | import babel from "rollup-plugin-babel";
4 | import serve from "rollup-plugin-serve";
5 | import { terser } from "rollup-plugin-terser";
6 | import json from '@rollup/plugin-json';
7 |
8 | export default {
9 | input: ["src/opensprinkler-card.ts"],
10 | output: {
11 | dir: "./dist",
12 | format: "es",
13 | },
14 | plugins: [
15 | resolve(),
16 | typescript(),
17 | json(),
18 | babel({
19 | exclude: "node_modules/**",
20 | }),
21 | terser(),
22 | serve({
23 | contentBase: "./dist",
24 | host: "0.0.0.0",
25 | port: 5000,
26 | allowCrossOrigin: true,
27 | headers: {
28 | "Access-Control-Allow-Origin": "*",
29 | },
30 | }),
31 | ],
32 | };
33 |
--------------------------------------------------------------------------------
/rollup.config.js:
--------------------------------------------------------------------------------
1 | import typescript from 'rollup-plugin-typescript2';
2 | import commonjs from 'rollup-plugin-commonjs';
3 | import nodeResolve from 'rollup-plugin-node-resolve';
4 | import babel from 'rollup-plugin-babel';
5 | import { terser } from 'rollup-plugin-terser';
6 | import serve from 'rollup-plugin-serve';
7 | import json from '@rollup/plugin-json';
8 |
9 | const dev = process.env.ROLLUP_WATCH;
10 |
11 | const serveopts = {
12 | contentBase: ['./dist'],
13 | host: '0.0.0.0',
14 | port: 5000,
15 | allowCrossOrigin: true,
16 | headers: {
17 | 'Access-Control-Allow-Origin': '*',
18 | },
19 | };
20 |
21 | const plugins = [
22 | nodeResolve({}),
23 | commonjs(),
24 | typescript(),
25 | json(),
26 | babel({
27 | exclude: 'node_modules/**',
28 | }),
29 | dev && serve(serveopts),
30 | !dev && terser(),
31 | ];
32 |
33 | export default [
34 | {
35 | input: 'src/opensprinkler-card.ts',
36 | output: {
37 | dir: 'dist',
38 | format: 'es',
39 | },
40 | plugins: [...plugins],
41 | },
42 | ];
43 |
--------------------------------------------------------------------------------
/src/types.ts:
--------------------------------------------------------------------------------
1 | import { EntityConfig } from 'custom-card-helpers';
2 | import { TimerBarConfig } from 'lovelace-timer-bar-card/src/types';
3 |
4 | export declare type HassEntity = {
5 | entity_id: string;
6 | state: string;
7 | last_changed: string;
8 | last_updated: string;
9 | context: {
10 | id: string;
11 | user_id: string | null;
12 | };
13 | attributes: {
14 | [key: string]: any;
15 | };
16 | };
17 |
18 | export type LineHeight = 'small' | 'medium' | 'normal';
19 |
20 | export type IconSet = {
21 | active?: string;
22 | active_disabled?: string;
23 | idle?: string;
24 | idle_disabled?: string;
25 | }
26 |
27 | // TODO Add your configuration elements here for type-checking
28 | export interface OpensprinklerCardConfig {
29 | type: string;
30 | name?: string;
31 | icon?: string;
32 | device?: string;
33 | bars?: TimerBarConfig;
34 | extra_entities?: string[];
35 | input_number?: EntityConfig;
36 | hide_dots?: boolean;
37 | hide_disabled?: boolean;
38 | card_line_height?: LineHeight;
39 | timer_line_height?: LineHeight;
40 | popup_line_height?: LineHeight;
41 | icons: {
42 | run_once?: string;
43 | station: IconSet;
44 | program: IconSet;
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "opensprinkler-card",
3 | "version": "1.13.0",
4 | "description": "OpenSprinkler status for Home Assistant",
5 | "keywords": [
6 | "home-assistant",
7 | "homeassistant",
8 | "hass",
9 | "automation",
10 | "lovelace",
11 | "custom-cards"
12 | ],
13 | "module": "opensprinkler-card.js",
14 | "repository": "git@github.com:rianadon/opensprinkler-card.git",
15 | "license": "Apache-2.0",
16 | "dependencies": {
17 | "@formatjs/intl-utils": "^3.8.4",
18 | "@mdi/js": "^6.5.95",
19 | "custom-card-helpers": "1.8.0",
20 | "home-assistant-js-websocket": "^5.12.0",
21 | "lit": "^2.0.2",
22 | "lovelace-timer-bar-card": "^1.15.0"
23 | },
24 | "devDependencies": {
25 | "@babel/core": "^7.16.5",
26 | "@rollup/plugin-json": "^4.1.0",
27 | "prettier": "^2.5.1",
28 | "rollup": "^2.61.1",
29 | "rollup-plugin-babel": "^4.4.0",
30 | "rollup-plugin-commonjs": "^10.1.0",
31 | "rollup-plugin-node-resolve": "^5.2.0",
32 | "rollup-plugin-serve": "^1.1.0",
33 | "rollup-plugin-terser": "^7.0.2",
34 | "rollup-plugin-typescript2": "^0.31.1",
35 | "typescript": "^4.5.4"
36 | },
37 | "scripts": {
38 | "start": "rollup -c rollup.config.dev.js --watch",
39 | "build": "rollup -c"
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/opensprinkler-state.ts:
--------------------------------------------------------------------------------
1 | import { html } from "lit";
2 | import { EntityConfig, HomeAssistant } from "custom-card-helpers";
3 | import { osName } from "./helpers";
4 |
5 | export class OpensprinklerState extends HTMLElement {
6 | private element?: any;
7 |
8 | private _config?: EntityConfig;
9 | private _hass?: HomeAssistant;
10 |
11 | async connectedCallback() {
12 | const helpers = await (window as any).loadCardHelpers();
13 | this.element = helpers.createRowElement(this._config);
14 |
15 | this.element.hass = this._hass;
16 | this.appendChild(this.element);
17 | }
18 |
19 | disconnectedCallback() {
20 | this.removeChild(this.element);
21 | }
22 |
23 | set hass(hass: HomeAssistant) {
24 | this._hass = hass;
25 | if (this.element) this.element.hass = hass;
26 | }
27 |
28 | set config(config: EntityConfig) {
29 | this._config = config;
30 | if (this.element) this.element.setConfig(config);
31 | }
32 | }
33 |
34 | window.customElements.define('opensprinkler-state', OpensprinklerState);
35 |
36 | export function renderState(entity: string|EntityConfig, hass: HomeAssistant, moreInfo?: any) {
37 | let config: EntityConfig;
38 |
39 | if (!entity) return html`Entity not found`;
40 |
41 | if (typeof entity === 'string') {
42 | const state = hass.states[entity];
43 | if (!state) return html`Entity ${entity} not found`;
44 | config = { entity, name: osName(state) };
45 | } else {
46 | config = entity;
47 | }
48 |
49 | return html``;
50 | }
51 |
--------------------------------------------------------------------------------
/src/relative_time.ts:
--------------------------------------------------------------------------------
1 | //REF: https://github.com/custom-cards/custom-card-helpers/blob/master/src/datetime/relative_time.ts
2 | //REF: https://github.com/home-assistant/frontend/blob/dev/src/common/datetime/relative_time.ts
3 |
4 | import { selectUnit } from "@formatjs/intl-utils";
5 |
6 | // REF: https://github.com/custom-cards/custom-card-helpers/blob/master/src/types.ts
7 | // REF: https://github.com/home-assistant/frontend/blob/dev/src/data/translation.ts
8 | enum NumberFormat {
9 | language = "language",
10 | system = "system",
11 | comma_decimal = "comma_decimal",
12 | decimal_comma = "decimal_comma",
13 | space_comma = "space_comma",
14 | none = "none",
15 | }
16 |
17 | export enum TimeFormat {
18 | language = "language",
19 | system = "system",
20 | am_pm = "12",
21 | twenty_four = "24",
22 | }
23 |
24 | interface MinBarFrontendLocaleData {
25 | language: string;
26 | }
27 |
28 | const formatRelTimeMem =
29 | (locale: MinBarFrontendLocaleData) =>
30 | new Intl.RelativeTimeFormat(locale.language, { numeric: "auto" });
31 |
32 | /**
33 | * Calculate a string representing a date object as relative time from now.
34 | *
35 | * Example output: 5 minutes ago, in 3 days.
36 | */
37 | export const relativeTime = (
38 | from: Date,
39 | locale: MinBarFrontendLocaleData,
40 | to?: Date,
41 | includeTense = true
42 | ): string => {
43 | const diff = selectUnit(from, to);
44 | if (includeTense) {
45 | return formatRelTimeMem(locale).format(diff.value, diff.unit);
46 | }
47 | return Intl.NumberFormat(locale.language, {
48 | style: "unit",
49 | unit: diff.unit,
50 | unitDisplay: "long",
51 | }).format(Math.abs(diff.value));
52 | };
53 |
--------------------------------------------------------------------------------
/src/helpers.ts:
--------------------------------------------------------------------------------
1 | import { HassEntity, LineHeight } from "./types";
2 |
3 | export type EntitiesFunc = (predicate: (entity: HassEntity) => boolean) => HassEntity[];
4 |
5 | const MANUAL_ID = 99;
6 | const RUN_ONCE_ID = 254;
7 |
8 | const WAITING_STATES = ['waiting'];
9 | const ACTIVE_STATES = ['program', 'once_program', 'manual', 'on'];
10 | const STOPPABLE_STATES = [...ACTIVE_STATES, ...WAITING_STATES]
11 |
12 | export const isStation = (entity: HassEntity) =>
13 | entity.attributes.opensprinkler_type === 'station' &&
14 | entity.entity_id.startsWith('sensor.');
15 | export const isProgram = (entity: HassEntity) =>
16 | entity.attributes.opensprinkler_type === 'program' &&
17 | entity.entity_id.startsWith('binary_sensor.')
18 | export const isController = (entity: HassEntity) =>
19 | entity.attributes.opensprinkler_type === 'controller' &&
20 | entity.entity_id.startsWith('switch.');
21 |
22 | export const isRunOnce = (entity: HassEntity) => entity.entity_id === 'run_once';
23 | export const isState = (entity: HassEntity) => !entity.attributes?.opensprinkler_type;
24 | export const isStationProgEnable = (entity: HassEntity) =>
25 | entity.entity_id.startsWith('switch.');
26 | export const isPlayPausable = (entity: HassEntity) =>
27 | isStation(entity) || isProgram(entity) || isRunOnce(entity)
28 | export const isRainDelayActiveSensor = (entity: HassEntity) =>
29 | entity.entity_id.startsWith('binary_sensor.') &&
30 | entity.entity_id.endsWith('rain_delay_active')
31 | export const isRainDelayStopTime = (entity: HassEntity) =>
32 | entity.entity_id.startsWith('sensor.') &&
33 | entity.entity_id.endsWith('rain_delay_stop_time')
34 |
35 | export function hasRunOnce(entities: EntitiesFunc) {
36 | return entities(isStation).some(e => e.attributes.running_program_id === RUN_ONCE_ID);
37 | }
38 | export function hasManual(entities: EntitiesFunc) {
39 | return entities(isStation).some(e => e.attributes.running_program_id === MANUAL_ID);
40 | }
41 | export function hasRainDelayActive(entities: EntitiesFunc) {
42 | return entities(isRainDelayActiveSensor).some(e => e.state === 'on');
43 | }
44 |
45 | export const stateWaiting = (entity: HassEntity) => WAITING_STATES.includes(entity.state);
46 | export const stateStoppable = (entity: HassEntity) => STOPPABLE_STATES.includes(entity.state);
47 | export const stateActivated = (entity: HassEntity) => ACTIVE_STATES.includes(entity.state)
48 |
49 | export function osName(entity: HassEntity){
50 | return entity.attributes.name || entity.attributes.friendly_name
51 | .replace(/ Station Status$/, '').replace(/ Program Running$/, '').replace(/^OpenSprinkler /, '');
52 | }
53 |
54 | export function isEnabled(entity: HassEntity, func: EntitiesFunc) {
55 | return func(isStationProgEnable).find(e => (
56 | e.attributes.index == entity.attributes.index &&
57 | e.attributes.opensprinkler_type == entity.attributes.opensprinkler_type
58 | ))?.state === 'on';
59 | }
60 |
61 | export function lineHeight(size: LineHeight | undefined) {
62 | if (size === 'small') return '32px';
63 | if (size === 'medium') return '36px';
64 | return undefined
65 | }
66 |
--------------------------------------------------------------------------------
/src/editor.ts:
--------------------------------------------------------------------------------
1 | /* eslint-disable @typescript-eslint/no-explicit-any */
2 | /* eslint-disable @typescript-eslint/camelcase */
3 | import { LitElement, html, TemplateResult, CSSResultGroup, css } from 'lit';
4 | import { customElement, state, property } from "lit/decorators";
5 | import { HomeAssistant, fireEvent, LovelaceCardEditor } from 'custom-card-helpers';
6 |
7 | import { OpensprinklerCardConfig } from './types';
8 |
9 | const options = {
10 | required: {
11 | icon: 'tune',
12 | name: 'Required',
13 | secondary: 'Required options for this card to function',
14 | }
15 | };
16 |
17 | @customElement('opensprinkler-card-editor')
18 | export class BoilerplateCardEditor extends LitElement implements LovelaceCardEditor {
19 | @property({ attribute: false }) public hass?: HomeAssistant;
20 | @state() private _config?: OpensprinklerCardConfig;
21 | @state() private _helpers?: any;
22 | private _initialized = false;
23 |
24 | public setConfig(config: OpensprinklerCardConfig): void {
25 | this._config = config;
26 |
27 | this.loadCardHelpers();
28 | }
29 |
30 | protected shouldUpdate(): boolean {
31 | if (!this._initialized) {
32 | this._initialize();
33 | }
34 |
35 | return true;
36 | }
37 |
38 | private _computeLabel(schema: any) {
39 | if (schema.name == 'device') return 'Device (Required)';
40 | if (schema.name == 'name') return 'Name (Optional)';
41 | return '';
42 | }
43 |
44 | protected render(): TemplateResult | void {
45 | if (!this.hass || !this._helpers) {
46 | return html``;
47 | }
48 |
49 | const schema = [
50 | { name: 'device', selector: { device: { integration: 'opensprinkler', manufacturer: 'OpenSprinkler' } } },
51 | { name: 'name', selector: { text: {} } },
52 | ];
53 |
54 | return html`
55 |
56 |
63 |
64 | `;
65 | }
66 |
67 | private _initialize(): void {
68 | if (this.hass === undefined) return;
69 | if (this._config === undefined) return;
70 | if (this._helpers === undefined) return;
71 | this._initialized = true;
72 | }
73 |
74 | private async loadCardHelpers(): Promise {
75 | this._helpers = await (window as any).loadCardHelpers();
76 | }
77 |
78 | private _valueChanged(ev: CustomEvent): void {
79 | fireEvent(this, 'config-changed', { config: ev.detail.value });
80 |
81 | }
82 |
83 | static get styles(): CSSResultGroup {
84 | return css`
85 | .option {
86 | padding: 4px 0px;
87 | cursor: pointer;
88 | }
89 | .row {
90 | display: flex;
91 | margin-bottom: -14px;
92 | pointer-events: none;
93 | }
94 | .title {
95 | padding-left: 16px;
96 | margin-top: -6px;
97 | pointer-events: none;
98 | }
99 | .secondary {
100 | padding-left: 40px;
101 | color: var(--secondary-text-color);
102 | pointer-events: none;
103 | }
104 | .values {
105 | padding-left: 16px;
106 | background: var(--secondary-background-color);
107 | display: grid;
108 | }
109 | ha-formfield {
110 | padding-bottom: 8px;
111 | }
112 | `;
113 | }
114 | }
115 |
--------------------------------------------------------------------------------
/src/ha_entity_registry.ts:
--------------------------------------------------------------------------------
1 | /**
2 | * This file is adapted from the Home Assistant frontend.
3 | * See src/data/entity_registry.ts in the frontend repository.
4 | *
5 | * It has been modified to use public libraries rather than
6 | * the internal Home Assistant ones. Some stuff has also been removed.
7 | */
8 |
9 | import { Connection, createCollection } from "home-assistant-js-websocket";
10 | import { debounce, HomeAssistant } from "custom-card-helpers";
11 |
12 | export interface EntityRegistryEntry {
13 | entity_id: string;
14 | name: string | null;
15 | icon: string | null;
16 | platform: string;
17 | config_entry_id: string | null;
18 | device_id: string | null;
19 | area_id: string | null;
20 | disabled_by: string | null;
21 | }
22 |
23 | export interface ExtEntityRegistryEntry extends EntityRegistryEntry {
24 | unique_id: string;
25 | capabilities: Record;
26 | original_name?: string;
27 | original_icon?: string;
28 | }
29 |
30 | export interface UpdateEntityRegistryEntryResult {
31 | entity_entry: ExtEntityRegistryEntry;
32 | reload_delay?: number;
33 | require_restart?: boolean;
34 | }
35 |
36 | export interface EntityRegistryEntryUpdateParams {
37 | name?: string | null;
38 | icon?: string | null;
39 | area_id?: string | null;
40 | disabled_by?: string | null;
41 | new_entity_id?: string;
42 | }
43 |
44 | export const findBatteryEntity = (
45 | hass: HomeAssistant,
46 | entities: EntityRegistryEntry[]
47 | ): EntityRegistryEntry | undefined =>
48 | entities.find(
49 | (entity) =>
50 | hass.states[entity.entity_id] &&
51 | hass.states[entity.entity_id].attributes.device_class === "battery"
52 | );
53 |
54 | export const findBatteryChargingEntity = (
55 | hass: HomeAssistant,
56 | entities: EntityRegistryEntry[]
57 | ): EntityRegistryEntry | undefined =>
58 | entities.find(
59 | (entity) =>
60 | hass.states[entity.entity_id] &&
61 | hass.states[entity.entity_id].attributes.device_class ===
62 | "battery_charging"
63 | );
64 |
65 | export const getExtendedEntityRegistryEntry = (
66 | hass: HomeAssistant,
67 | entityId: string
68 | ): Promise =>
69 | hass.callWS({
70 | type: "config/entity_registry/get",
71 | entity_id: entityId,
72 | });
73 |
74 | export const updateEntityRegistryEntry = (
75 | hass: HomeAssistant,
76 | entityId: string,
77 | updates: Partial
78 | ): Promise =>
79 | hass.callWS({
80 | type: "config/entity_registry/update",
81 | entity_id: entityId,
82 | ...updates,
83 | });
84 |
85 | export const removeEntityRegistryEntry = (
86 | hass: HomeAssistant,
87 | entityId: string
88 | ): Promise =>
89 | hass.callWS({
90 | type: "config/entity_registry/remove",
91 | entity_id: entityId,
92 | });
93 |
94 | export const fetchEntityRegistry = (conn) =>
95 | conn.sendMessagePromise({
96 | type: "config/entity_registry/list",
97 | });
98 |
99 | const subscribeEntityRegistryUpdates = (conn, store) =>
100 | conn.subscribeEvents(
101 | debounce(
102 | () =>
103 | fetchEntityRegistry(conn).then((entities) =>
104 | store.setState(entities, true)
105 | ),
106 | 500,
107 | true
108 | ),
109 | "entity_registry_updated"
110 | );
111 |
112 | export const subscribeEntityRegistry = (
113 | conn: Connection,
114 | onChange: (entities: EntityRegistryEntry[]) => void
115 | ) =>
116 | createCollection(
117 | "_entityRegistry",
118 | fetchEntityRegistry,
119 | subscribeEntityRegistryUpdates,
120 | conn,
121 | onChange
122 | );
123 |
--------------------------------------------------------------------------------
/src/opensprinkler-generic-entity-row.ts:
--------------------------------------------------------------------------------
1 | /**
2 | * This is a modified version of hui-generic-entity-row from Home Assistant.
3 | * A more info button is added, and the code has been simplified for the limitted
4 | * needs of the OpenSprinkler card.
5 | */
6 |
7 | import { mdiDotsVertical } from "@mdi/js";
8 | import { css, CSSResultGroup, html, LitElement,
9 | PropertyValues, TemplateResult } from "lit";
10 | import { property } from "lit/decorators";
11 | import { classMap } from "lit/directives/class-map";
12 | import { ifDefined } from "lit/directives/if-defined";
13 | import { fireEvent, HomeAssistant, computeRTL } from "custom-card-helpers";
14 |
15 | class OpensprinklerGenericEntityRow extends LitElement {
16 | @property({ attribute: false }) public hass?: HomeAssistant;
17 |
18 | @property() public stateObj?: any;
19 |
20 | @property() public config?: any;
21 |
22 | @property() public secondaryText?: string;
23 |
24 | protected render(): TemplateResult {
25 | if (!this.hass || !this.config) {
26 | return html``;
27 | }
28 | const hasSecondary = this.secondaryText || this.config.secondary_info;
29 | const spanStyle = this.config.title ? "font-size: 1.1em" : "";
30 |
31 | const pointer = this.config.hide_dots;
32 |
33 | return html`
34 |
44 |
49 |
${this.config.name}
50 | ${hasSecondary
51 | ? html`
${this.secondaryText}
`
52 | : ""}
53 |
54 |
55 | ${this.config.hide_dots ? '' : html`
62 |
63 | `}
64 | `;
65 | }
66 |
67 | protected updated(changedProps: PropertyValues): void {
68 | super.updated(changedProps);
69 | if (changedProps.has("hass")) {
70 | this.toggleAttribute("rtl", computeRTL(this.hass!));
71 | }
72 | }
73 |
74 | private _handleClick() {
75 | fireEvent(this, 'hass-more-info', { entityId: this.config.entity });
76 | }
77 |
78 | static get styles(): CSSResultGroup {
79 | return css`
80 | :host {
81 | display: flex;
82 | align-items: center;
83 | flex-direction: row;
84 | --mdc-icon-button-size: 40px;
85 | }
86 | .info {
87 | margin-left: 16px;
88 | margin-right: 8px;
89 | flex: 1 1 30%;
90 | }
91 | .info,
92 | .info > * {
93 | white-space: nowrap;
94 | overflow: hidden;
95 | text-overflow: ellipsis;
96 | }
97 | .flex ::slotted(*) {
98 | margin-left: 8px;
99 | min-width: 0;
100 | }
101 | .flex ::slotted([slot="secondary"]) {
102 | margin-left: 0;
103 | }
104 | .secondary,
105 | ha-relative-time {
106 | color: var(--secondary-text-color);
107 | }
108 | state-badge {
109 | flex: 0 0 40px;
110 | }
111 | :host([rtl]) .flex {
112 | margin-left: 0;
113 | margin-right: 16px;
114 | }
115 | :host([rtl]) .flex ::slotted(*) {
116 | margin-left: 0;
117 | margin-right: 8px;
118 | }
119 | .pointer {
120 | cursor: pointer;
121 | }
122 | .more-info {
123 | color: var(--secondary-text-color);
124 | }
125 | `;
126 | }
127 | }
128 | customElements.define("opensprinkler-generic-entity-row", OpensprinklerGenericEntityRow);
129 |
--------------------------------------------------------------------------------
/src/ha_style.ts:
--------------------------------------------------------------------------------
1 | /**
2 | * Dialog styles from the Home Assistant frontend.
3 | * These are copied verbatim, but just put into their own file.
4 | */
5 |
6 | import { css } from "lit";
7 |
8 | export const haStyleDialog = css`
9 | /* prevent clipping of positioned elements */
10 | paper-dialog-scrollable {
11 | --paper-dialog-scrollable: {
12 | -webkit-overflow-scrolling: auto;
13 | }
14 | }
15 |
16 | /* force smooth scrolling for iOS 10 */
17 | paper-dialog-scrollable.can-scroll {
18 | --paper-dialog-scrollable: {
19 | -webkit-overflow-scrolling: touch;
20 | }
21 | }
22 |
23 | .paper-dialog-buttons {
24 | align-items: flex-end;
25 | padding: 8px;
26 | padding-bottom: max(env(safe-area-inset-bottom), 8px);
27 | }
28 |
29 | @media all and (min-width: 450px) and (min-height: 500px) {
30 | ha-paper-dialog {
31 | min-width: 400px;
32 | }
33 | }
34 |
35 | @media all and (max-width: 450px), all and (max-height: 500px) {
36 | paper-dialog,
37 | ha-paper-dialog {
38 | margin: 0;
39 | width: calc(
40 | 100% - env(safe-area-inset-right) - env(safe-area-inset-left)
41 | ) !important;
42 | min-width: calc(
43 | 100% - env(safe-area-inset-right) - env(safe-area-inset-left)
44 | ) !important;
45 | max-width: calc(
46 | 100% - env(safe-area-inset-right) - env(safe-area-inset-left)
47 | ) !important;
48 | max-height: calc(100% - var(--header-height));
49 |
50 | position: fixed !important;
51 | bottom: 0px;
52 | left: env(safe-area-inset-left);
53 | right: env(safe-area-inset-right);
54 | overflow: scroll;
55 | border-bottom-left-radius: 0px;
56 | border-bottom-right-radius: 0px;
57 | }
58 | }
59 |
60 | /* mwc-dialog (ha-dialog) styles */
61 | ha-dialog {
62 | --mdc-dialog-min-width: 400px;
63 | --mdc-dialog-max-width: 600px;
64 | --mdc-dialog-heading-ink-color: var(--primary-text-color);
65 | --mdc-dialog-content-ink-color: var(--primary-text-color);
66 | --justify-action-buttons: space-between;
67 | }
68 |
69 | ha-dialog .form {
70 | padding-bottom: 24px;
71 | color: var(--primary-text-color);
72 | }
73 |
74 | a {
75 | color: var(--primary-color);
76 | }
77 |
78 | /* make dialog fullscreen on small screens */
79 | @media all and (max-width: 450px), all and (max-height: 500px) {
80 | ha-dialog {
81 | --mdc-dialog-min-width: calc(
82 | 100vw - env(safe-area-inset-right) - env(safe-area-inset-left)
83 | );
84 | --mdc-dialog-max-width: calc(
85 | 100vw - env(safe-area-inset-right) - env(safe-area-inset-left)
86 | );
87 | --mdc-dialog-min-height: 100%;
88 | --mdc-dialog-max-height: 100%;
89 | --mdc-shape-medium: 0px;
90 | --vertial-align-dialog: flex-end;
91 | }
92 | }
93 | mwc-button.warning {
94 | --mdc-theme-primary: var(--error-color);
95 | }
96 | .error {
97 | color: var(--error-color);
98 | }
99 | `;
100 |
101 | export const haStyleMoreInfo = css`
102 | ha-dialog {
103 | --dialog-surface-position: static;
104 | --dialog-content-position: static;
105 | }
106 |
107 | ha-header-bar {
108 | --mdc-theme-on-primary: var(--primary-text-color);
109 | --mdc-theme-primary: var(--mdc-theme-surface);
110 | flex-shrink: 0;
111 | display: block;
112 | }
113 |
114 | @media all and (max-width: 450px), all and (max-height: 500px) {
115 | ha-header-bar {
116 | --mdc-theme-primary: var(--app-header-background-color);
117 | --mdc-theme-on-primary: var(--app-header-text-color, white);
118 | border-bottom: none;
119 | }
120 | }
121 |
122 | .heading {
123 | border-bottom: 1px solid
124 | var(--mdc-dialog-scroll-divider-color, rgba(0, 0, 0, 0.12));
125 | }
126 |
127 | @media all and (min-width: 451px) and (min-height: 501px) {
128 | ha-dialog {
129 | --mdc-dialog-max-width: 90vw;
130 | }
131 |
132 | .content {
133 | width: 352px;
134 | }
135 |
136 | ha-header-bar {
137 | width: 400px;
138 | }
139 |
140 | .main-title {
141 | overflow: hidden;
142 | text-overflow: ellipsis;
143 | cursor: default;
144 | }
145 |
146 | :host([large]) .content {
147 | width: calc(90vw - 48px);
148 | }
149 |
150 | :host([large]) ha-dialog[data-domain="camera"] .content,
151 | :host([large]) ha-header-bar {
152 | width: 90vw;
153 | }
154 | }
155 |
156 | state-card-content,
157 | ha-more-info-history,
158 | ha-more-info-logbook:not(:last-child) {
159 | display: block;
160 | margin-bottom: 16px;
161 | }
162 | `;
163 |
--------------------------------------------------------------------------------
/src/opensprinkler-more-info-dialog.ts:
--------------------------------------------------------------------------------
1 | import { mdiClose } from "@mdi/js";
2 | import { html, LitElement } from "lit";
3 | import { customElement, property, state } from "lit/decorators";
4 | import { computeRTL, fireEvent, HomeAssistant } from "custom-card-helpers";
5 | import { OpensprinklerCardConfig, HassEntity } from "./types";
6 | import { styles } from "./styles";
7 | import "./opensprinkler-state";
8 | import "./opensprinkler-control";
9 | import { OpensprinklerCard } from "./opensprinkler-card";
10 | import { haStyleDialog, haStyleMoreInfo } from "./ha_style";
11 | import { EntitiesFunc, hasRunOnce, isController, isEnabled, isProgram, isState, isStation, lineHeight } from "./helpers";
12 | import { renderState } from "./opensprinkler-state";
13 | import { styleMap } from "lit/directives/style-map";
14 |
15 | export interface MoreInfoDialogParams {
16 | config: OpensprinklerCardConfig;
17 | }
18 |
19 | @customElement("opensprinkler-more-info-dialog")
20 | export class MoreInfoDialog extends LitElement {
21 | @property({ attribute: false }) public hass!: HomeAssistant;
22 | @property({ attribute: false }) public entities!: EntitiesFunc;
23 | @property({ attribute: false }) public parent!: OpensprinklerCard;
24 |
25 | @property({ type: Boolean, reflect: true }) public large = false;
26 |
27 | @state() private _config?: OpensprinklerCardConfig | undefined;
28 |
29 | public showDialog(params: MoreInfoDialogParams) {
30 | this._config = params.config;
31 | if (!this._config) {
32 | this.closeDialog();
33 | return;
34 | }
35 | this.large = false;
36 | }
37 |
38 | public closeDialog() {
39 | this._config = undefined;
40 | // fireEvent(this, "dialog-closed", { dialog: this.localName });
41 | }
42 |
43 | protected render() {
44 | if (!this._config) {
45 | return html``;
46 | }
47 |
48 | const style = styleMap({
49 | '--opensprinkler-line-height': lineHeight(this._config.popup_line_height),
50 | direction: computeRTL(this.hass) ? 'rtl' : undefined,
51 | });
52 |
53 | return html`
54 |
62 |
63 |
64 |
71 |
72 |
73 |
74 | ${this._config.name}
75 |
76 |
77 |
78 |
79 | ${this._renderStates()}
80 | ${this._renderStations()}
81 | ${this._renderPrograms()}
82 |
83 |
84 | `;
85 | }
86 |
87 | private _renderHeading(title: string) {
88 | return html``;
89 | }
90 |
91 | private _renderState(entity: HassEntity) {
92 | return renderState(entity.entity_id, this.hass, (e:CustomEvent) => this._moreInfo(e));
93 | }
94 |
95 | private _renderControl(entity: HassEntity) {
96 | return html``;
101 | }
102 |
103 | private _renderStates() {
104 | return this.entities(isController).map(s => {
105 | return this._renderState(s);
106 | }).concat(this.entities(isState).sort((a, b) => {
107 | if (a.entity_id.includes('sensor_')) return 1
108 | if (a.entity_id.includes('rain_delay') && !b.entity_id.includes('sensor_')) return 1
109 | return -1
110 | }).map(s => {
111 | return this._renderState(s);
112 | }));
113 | }
114 |
115 | private _renderStations() {
116 | return [
117 | this._renderHeading('Stations'),
118 | this._config!.input_number ? renderState(this._config!.input_number, this.hass) : '',
119 | ].concat(this.entities(isStation).filter(s => this._shouldShowEntity(s)).map(s => {
120 | return this._renderControl(s);
121 | }));
122 | }
123 |
124 | private _renderPrograms() {
125 | const runOnceEntity = { entity_id: 'run_once', state: 'on',
126 | attributes: { name: 'Run Once' } } as any;
127 | return [
128 | this._renderHeading('Programs'),
129 | hasRunOnce(this.entities) ? this._renderControl(runOnceEntity) : html``,
130 | ].concat(this.entities(isProgram).filter(s => this._shouldShowEntity(s)).map(s => {
131 | return this._renderControl(s);
132 | }));
133 | }
134 |
135 | private _enlarge() {
136 | this.large = !this.large;
137 | }
138 |
139 | private _moreInfo(e: CustomEvent) {
140 | this.closeDialog();
141 | fireEvent(this.parent, "hass-more-info", e.detail);
142 | }
143 |
144 | private _shouldShowEntity(entity: HassEntity) {
145 | if (this._config!.hide_disabled) return isEnabled(entity, this.entities);
146 | return true;
147 | }
148 |
149 | static get styles() {
150 | return [
151 | haStyleDialog,
152 | haStyleMoreInfo,
153 | styles,
154 | ];
155 | }
156 | }
157 |
--------------------------------------------------------------------------------
/src/opensprinkler-control.ts:
--------------------------------------------------------------------------------
1 | import { mdiPlay, mdiStop } from "@mdi/js";
2 | import { LitElement, css, html, TemplateResult, PropertyValues } from 'lit';
3 | import { customElement, state, property } from "lit/decorators";
4 | import { HomeAssistant } from 'custom-card-helpers';
5 |
6 | import { localize } from 'lovelace-timer-bar-card/src/timer-bar-entity-row';
7 |
8 | import {
9 | EntitiesFunc, isController, isEnabled, isProgram, isRunOnce, isStation,
10 | osName, stateActivated, stateStoppable } from './helpers';
11 | import { HassEntity, IconSet, OpensprinklerCardConfig } from './types';
12 |
13 | @customElement('opensprinkler-control')
14 | export class OpensprinklerControl extends LitElement {
15 |
16 | @property({ attribute: false }) public hass!: HomeAssistant;
17 | @property({ attribute: false }) public entities!: EntitiesFunc;
18 | @property() public controller!: string;
19 | @property() public entity!: HassEntity;
20 | @property() public config!: OpensprinklerCardConfig;
21 |
22 | @state() private _loading = false;
23 | @state() private _stopping = false;
24 |
25 | protected updated(changedProps: PropertyValues) {
26 | super.updated(changedProps);
27 | if (changedProps.has("hass")) {
28 | this._loading = false;
29 | // Only mark a stop operation as complete when all stations have turned off
30 | if (this.entities(isStation).every(s => s.state === 'idle'))
31 | this._stopping = false;
32 | }
33 | }
34 |
35 | protected render(): TemplateResult | void {
36 | if (!this.entity) return html`Entity not found`;
37 |
38 | const loading = this._loading || this._stopping;
39 | const enabled = this._enabled();
40 | if (typeof enabled === 'undefined') return html`Enable switch for entity not found`;
41 |
42 | const config = {
43 | entity: this.entity.entity_id, name: osName(this.entity),
44 | icon: this._icon(enabled),
45 | hide_dots: this.config.hide_dots,
46 | };
47 |
48 | return html`
49 | ${this._state(enabled)}
50 | ${loading ? html``
51 | : html` this._toggleEntity(this.entity)} .disabled=${!enabled}>
52 |
53 | `}
54 | `;
55 | }
56 |
57 | private _state(enabled: boolean) {
58 | if (isRunOnce(this.entity)) return 'Running';
59 | if (isStation(this.entity)) {
60 | if (this.entity.state === 'idle' && !enabled) return 'Disabled';
61 | if (this.entity.state === 'once_program') return 'Once Program';
62 | return localize(this.hass, this.entity.state, this.entity);
63 | }
64 | if (isProgram(this.entity)) {
65 | if (status === 'off' && !enabled) return 'Disabled';
66 | return status === 'on' ? 'Running' : 'Off';
67 | }
68 | return;
69 | }
70 |
71 | private _icon(enabled: boolean) {
72 | if (isRunOnce(this.entity)) return this.config.icons.run_once;
73 | if (isStation(this.entity)) {
74 | const on = stateActivated(this.entity);
75 | return this._iconFromSet(on, enabled, this.config.icons.station);
76 | }
77 | if (isProgram(this.entity)) {
78 | const on = this.entity.state === 'on';
79 | return this._iconFromSet(on, enabled, this.config.icons.program);
80 | }
81 | return;
82 | }
83 |
84 | private _iconFromSet(on: boolean, enabled: boolean, icons: IconSet) {
85 | if (on && enabled) return icons.active;
86 | if (!on && enabled) return icons.idle;
87 | if (on && !enabled) return icons.active_disabled;
88 | if (!on && !enabled) return icons.idle_disabled;
89 | return;
90 | }
91 |
92 | private _toggleIcon() {
93 | return stateStoppable(this.entity) ? mdiStop : mdiPlay;
94 | }
95 |
96 | private _enabled(): boolean | undefined {
97 | if (isRunOnce(this.entity)) return true;
98 | return isEnabled(this.entity, this.entities);
99 | }
100 |
101 | private _toggleEntity(entity: HassEntity) {
102 | const service = stateStoppable(entity) ? 'stop' : 'run';
103 | let entity_id = entity.entity_id;
104 |
105 | const isStoppingProgram = service === 'stop' && isProgram(entity);
106 |
107 | if (entity_id === 'run_once' || isStoppingProgram) {
108 | this._stopping = true;
109 | entity_id = this.entities(isController)[0].entity_id;
110 | } else {
111 | this._loading = true;
112 | }
113 |
114 | if (service === 'run' && isStation(entity))
115 | this.hass.callService('opensprinkler', service, { entity_id, run_seconds: this._runtime() });
116 | else
117 | this.hass.callService('opensprinkler', service, { entity_id });
118 | }
119 |
120 | private _runtime() {
121 | if (!this.config.input_number?.entity) return undefined;
122 | const entity = this.hass.states[this.config.input_number.entity];
123 | if (!entity) return;
124 |
125 | return Number(entity.state) * 60;
126 | }
127 |
128 | static get styles() {
129 | return css`
130 | opensprinkler-generic-entity-row { height: var(--opensprinkler-line-height); }
131 |
132 | .button {
133 | color: var(--secondary-text-color);
134 | --mdc-icon-button-size: 40px;
135 | margin-inline-end: -8px;
136 | margin-inline-start: 4px;
137 | }
138 |
139 | mwc-circular-progress {
140 | margin-inline-start: 8px;
141 | margin-inline-end: -4px;
142 | }
143 | `;
144 | }
145 | }
146 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Lovelace OpenSprinkler Card
2 |
3 | Collect [OpenSprinkler][opensprinkler] status into a card for [Home Assistant][home-assistant].
4 |
5 | You will need the [OpenSprinkler integration][opensprinkler-integration] installed.
6 |
7 | 
8 |
9 | ## Install
10 |
11 | OpenSprinkler Card is available from [HACS][hacs] (search for "opensprinkler card"). If you don't have [HACS][hacs] installed, follow the [manual installation](#manual-installation) instructions.
12 |
13 | ## Options
14 |
15 | | Name | Type | Requirement | Description |
16 | | ----------------- | ------- | ------------ | -------------------------------------------------------------------- |
17 | | type | string | **Required** | `custom:opensprinkler-card` |
18 | | device | string | **Required** | Device id of the OpenSprinkler in Home Assistant |
19 | | name | string | **Optional** | Card title (e.g. "Sprinkler") |
20 | | icon | string | **Optional** | Card icon (e.g. "mdi:sprinkler-variant") |
21 | | bars | dict | **Optional** | Configuration for the progress bars |
22 | | extra_entities | array | **Optional** | Entities to always show in the card |
23 | | input_number | string | **Optional** | Configuration for run-duration-choosing entity |
24 | | hide_dots | bool | **Optional** | If `true`, hide the 3 dots appearing next to entities |
25 | | hide_disabled | bool | **Optional** | If `true`, hide disabled stations and programs in the popup |
26 | | icons | dict | **Optional** | Icon configuration. See the [default config][config] for an example. |
27 |
28 | Finding device ids is tricky, so I recommend using the dropdown in the visual card editor to set `device` rather than YAML.
29 |
30 | You can also set `popup_line_height`, `timer_line_height`, and `card_line_height` to [control the spacing of entities](#mobile-friendliness).
31 |
32 | ## Entity ID requirements
33 |
34 | This card locates your OpenSprinkler entities by using their entity ids. If you haven't changed these, you have nothing to worry about.
35 |
36 | Otherwise, make sure:
37 | - The ids of station status sensors end with `_status`
38 | - The ids of program running binary sensors end with `_running`
39 | - The id of the OpenSprinkler controller enabled switch ends with `_enabled`
40 | - The ids of program & station enabled switches end with `_enabled`
41 | - The id of the rain delay active binary sensor ends with `_rain_delay_active`
42 | - The id of the rain delay stop time sensor ends with `_rain_delay_stop_time`
43 |
44 | ## Extra entities and duration control
45 |
46 | By default, the only way to control stations is to first click on the 3 dots in the top-right corner of the card. If you'd like to have a few stations controls always accessible from the dashboard, you can add them to the bottom of the card with the `extra_entities` option. You can also add programs or even any entity type (`switch`es, `light`s, etc).
47 |
48 |
49 |
50 | Stations also default to a runtime of 1 minute. To extend the length they run for, make an `input_number` entity then link it to the card via the `input_number` option. The slider or box input will appear in the popup, and if you are using the `extra_entities` option, in the card as well.
51 |
52 |
53 | | Entity configuration | Home Assistant configuration.yaml |
54 |
|
55 |
56 | ```yaml
57 | type: custom:opensprinkler-card
58 | device: 3e0a97a098f4609215aed92fe19bb7fb
59 | extra_entities:
60 | - sensor.front_lawn_station_status
61 | - sensor.arbor_drip_station_status
62 | input_number:
63 | entity: input_number.slider
64 | ```
65 |
66 | |
67 |
68 |
69 | ```yaml
70 |
71 | input_number:
72 | slider:
73 | name: Station Duration
74 | initial: 5 # in minutes
75 | min: 1
76 | max: 30
77 | step: 1
78 | # You can also use mode: box
79 | ```
80 |
81 | |
82 |
83 | You can also use custom cards for the duration control, like [numberbox-card](https://github.com/htmltiger/numberbox-card). As well as headings inside the `extra_entities`! (anything without a `.` is a heading)
84 |
85 |
86 |
87 |
88 |
89 |
90 | |
91 |
92 | ```yaml
93 | ...
94 | input_number:
95 | entity: input_number.slider
96 | type: custom:numberbox-card
97 | unit: m
98 | icon: mdi:timelapse
99 | extra_entities:
100 | - Stations
101 | - sensor.front_lawn_station_status
102 | - sensor.arbor_drip_station_status
103 | - sensor.s15_station_status
104 | - Sensors
105 | - sensor.opensprinkler_water_level
106 | - sensor.upstairs_humidity
107 | ```
108 |
109 | |
110 |
111 | ## Progress bar customization
112 |
113 | The OpenSprinkler card depends on the [Timer Bar Card](https://github.com/rianadon/timer-bar-card) for rendering progress bars. You can use Timer Bar customization options inside the OpenSprinkler card by inserting your configurations under the `bars` option. You'll need to switch to the code (YAML) editor to use these options. Fields under the [Customization](https://github.com/rianadon/timer-bar-card#customization) section are supported. For an example:
114 |
115 |
116 |
117 | ```yaml
118 | type: custom:opensprinkler-card
119 | device: 3e0a97a098f4609215aed92fe19bb7fb
120 | name: Sprinkler
121 | bars:
122 | bar_foreground: pink
123 | icon: mdi:tortoise
124 | active_icon: mdi:rabbit
125 | ```
126 |
127 | ## Mobile friendliness
128 |
129 | By default, the card is optimized for use with clickers, not fingers. There are a few options you may wish to change if you are a fingerer or touchscreen user:
130 |
131 | - You can space entities further apart to make it more likeley you tap the correct one. For each of the following options, you can use `normal` (40px spacing, the default in Home Assistant), `medium` (36px spacing), or `small` (32px). They are listed with their defaults:
132 |
133 | ```yaml
134 | popup_line_height: small # Spacing between entities (sensors, stations, programs) listed in the popup
135 | timer_line_height: medium # Spacing between progress bars (running stations) in the card
136 | card_line_height: small # Spacing between extra_entities (entities in the card)
137 | ```
138 |
139 | - You can hide the 3 vertical dots that appear to the right of station controls using `hide_dots`, which should further remove some sources of accidents. You can still access entity details by clicking on the station icon (yup, that's not very obvious ... that's why I put the dots there)
140 |
141 | ## A word on design
142 |
143 | You may find some details, such as loading icons, the run-once program entry, and the layout of the card in its default configuration to be tastefully designed. You may find other details like the duration input and `extra_entities` to appear like goblin heads grafted onto puppies. I only have so much time to play around with the design, and welcome any contribution, whether code or Figma link or pencil sketch, to make the card more accessible, consistent, prettier, or whatever you strive for.
144 |
145 | ## Manual installation
146 |
147 | 1. Download `opensprinkler-card.js` from the [latest release][release] and move this file to the `config/www` folder.
148 | 2. Ensure you have advanced mode enabled (accessible via your username in the bottom left corner)
149 | 3. Go to Configuration -> Lovelace Dashboards -> Resources.
150 | 4. Add `/local/opensprinkler-card.js` with type JS module.
151 | 5. Refresh the page? Or restart Home Assistant? The card should eventually be there.
152 |
153 | [home-assistant]: https://github.com/home-assistant/home-assistant
154 | [opensprinkler]: https://opensprinkler.com
155 | [opensprinkler-integration]: https://github.com/vinteo/hass-opensprinkler
156 | [hacs]: https://hacs.xyz/
157 | [release]: https://github.com/rianadon/opensprinkler-card/releases
158 | [config]: https://github.com/rianadon/opensprinkler-card/blob/main/CONFIGURATION.md
159 |
--------------------------------------------------------------------------------
/src/opensprinkler-card.ts:
--------------------------------------------------------------------------------
1 | import { LitElement, css, html, TemplateResult } from 'lit';
2 | import { customElement, state, property } from "lit/decorators";
3 | import { HomeAssistant, LovelaceCardEditor } from 'custom-card-helpers';
4 | import { PropertyValues } from 'lit-element';
5 | import { UnsubscribeFunc } from 'home-assistant-js-websocket';
6 |
7 | import { fillConfig, TimerBarEntityRow } from 'lovelace-timer-bar-card/src/timer-bar-entity-row';
8 | import { EntityRegistryEntry, subscribeEntityRegistry } from './ha_entity_registry';
9 | import { OpensprinklerCardConfig, HassEntity } from './types';
10 | import { styles } from './styles';
11 | import "./editor";
12 | import "./opensprinkler-generic-entity-row";
13 | import "./opensprinkler-more-info-dialog";
14 | import "./opensprinkler-control";
15 | import { MoreInfoDialog } from './opensprinkler-more-info-dialog';
16 | import { EntitiesFunc, hasManual, hasRainDelayActive, hasRunOnce, isPlayPausable, isProgram, isRainDelayStopTime, isStation, lineHeight, osName, stateActivated, stateWaiting } from './helpers';
17 | import { renderState } from './opensprinkler-state';
18 | import { styleMap } from 'lit/directives/style-map';
19 | import { relativeTime } from './relative_time';
20 |
21 | // This puts your card into the UI card picker dialog
22 | (window as any).customCards = (window as any).customCards || [];
23 | (window as any).customCards.push({
24 | type: 'opensprinkler-card',
25 | name: 'Opensprinkler Card',
26 | description: 'Collect OpenSprinkler status into a card',
27 | });
28 |
29 | window.customElements.define('opensprinkler-timer-bar-entity-row', TimerBarEntityRow);
30 |
31 | @customElement('opensprinkler-card')
32 | export class OpensprinklerCard extends LitElement {
33 |
34 | @property({ attribute: false }) public hass?: HomeAssistant;
35 | @state() private config!: OpensprinklerCardConfig;
36 | @state() private entities?: EntityRegistryEntry[];
37 | @state() private unsub?: UnsubscribeFunc;
38 | @state() private dialog!: MoreInfoDialog;
39 |
40 | public static async getConfigElement(): Promise {
41 | return document.createElement('opensprinkler-card-editor') as LovelaceCardEditor;
42 | }
43 |
44 | public static getStubConfig(): object {
45 | return {};
46 | }
47 |
48 | setConfig(config: OpensprinklerCardConfig): void {
49 | if (!config) {
50 | throw new Error("Invalid configuration");
51 | }
52 | this.config = {
53 | name: "Sprinkler",
54 | icon: "mdi:sprinkler-variant",
55 | card_line_height: "small",
56 | timer_line_height: "medium",
57 | popup_line_height: "small",
58 | ...config,
59 | icons: {
60 | run_once: 'mdi:auto-fix',
61 | ...config.icons,
62 | station: {
63 | active: 'mdi:water',
64 | active_disabled: 'mdi:water-off',
65 | idle: 'mdi:water-outline',
66 | idle_disabled: 'mdi:water-off-outline',
67 | ...config.icons?.station,
68 | },
69 | program: {
70 | active: 'mdi:timer',
71 | active_disabled: 'mdi:timer-off',
72 | idle: 'mdi:timer-outline',
73 | idle_disabled: 'mdi:timer-off-outline',
74 | ...config.icons?.station,
75 | }
76 | }
77 | };
78 | }
79 |
80 | protected render(): TemplateResult | void {
81 | if (!this.config.device) return html`No device specified`;
82 | if (this.config.input_number && !this.config.input_number.entity) return html`input_number.entity must be defined`;
83 | if (!this.entities) return html``;
84 |
85 | const config = { name: this.config.name, icon: this.config.icon, title: true };
86 | const entities = this._statusEntities();
87 | const style = styleMap({
88 | '--opensprinkler-line-height': lineHeight(this.config.card_line_height),
89 | '--opensprinkler-timer-height': lineHeight(this.config.timer_line_height),
90 | });
91 |
92 | return html`
93 |
94 |
99 |
100 | ${entities.map(s => this._renderStatus(s))}
101 |
102 | ${ (this.config as any).card_stations ? html`
card_stations has been renamed to extra_entities` : ''}
103 | ${this.config.extra_entities ?.length ? html`` : ''}
107 |
108 |
109 | `;
110 | }
111 |
112 | private _moreInfo() {
113 | this.dialog.showDialog({ config: this.config });
114 | }
115 |
116 | protected shouldUpdate(changedProps: PropertyValues): boolean {
117 | if (!this.config) return false;
118 | if (changedProps.has('config')) return true;
119 |
120 | const oldHass = changedProps.get('hass') as HomeAssistant | undefined;
121 | if (!oldHass) return true;
122 |
123 | for (const entity of this._matchingEntities(() => true)) {
124 | if (oldHass.states[entity.entity_id] !== entity) return true;
125 | }
126 |
127 | const input = this.config.input_number?.entity;
128 | if (input && oldHass.states[input] !== this.hass?.states[input]) return true;
129 |
130 | return false;
131 | }
132 |
133 | public connectedCallback() {
134 | super.connectedCallback();
135 | if (this.hass) this._subscribe();
136 |
137 | this.dialog = new MoreInfoDialog();
138 | this.dialog.hass = this.hass!;
139 | this.dialog.entities = this._matchingEntities.bind(this);
140 | this.dialog.parent = this;
141 | document.body.appendChild(this.dialog);
142 | }
143 |
144 | protected updated(changedProps: PropertyValues) {
145 | super.updated(changedProps);
146 | if (!this.unsub && changedProps.has("hass")) {
147 | this._subscribe();
148 | }
149 | if (changedProps.has("hass")) this.dialog.hass = this.hass!;
150 | }
151 |
152 | public disconnectedCallback() {
153 | super.disconnectedCallback();
154 | if (this.unsub) this.unsub();
155 | this.unsub = undefined;
156 | document.body.removeChild(this.dialog);
157 | }
158 |
159 | private _subscribe() {
160 | this.unsub = subscribeEntityRegistry(this.hass!.connection, entries => {
161 | this.entities = entries;
162 | });
163 | }
164 |
165 | private _matchingEntities(predicate: (entity: any) => boolean) {
166 | if (!this.entities || !this.hass) return [];
167 | const entities = this.entities.filter(e => {
168 | const state = this.hass!.states[e.entity_id];
169 | if (!state) return;
170 | return e.device_id === this.config.device && predicate(state);
171 | });
172 | return entities.map(e => this.hass!.states[e.entity_id]);
173 | }
174 |
175 | private _statusEntities() {
176 | const status = this._matchingEntities(isStation);
177 | return status.filter(stateActivated).concat(status.filter(stateWaiting));
178 | }
179 |
180 | private _renderStatus(e: HassEntity) {
181 | const config = fillConfig({
182 | // These two properties can be overridden
183 | icon: this.config.icons.station.idle,
184 | active_icon: this.config.icons.station.active,
185 |
186 | ...this.config.bars,
187 |
188 | type: 'timer-bar-entity-row',
189 | entity: e.entity_id,
190 | name: e.attributes.name,
191 | });
192 | return html`
194 | `;
195 | }
196 |
197 | private _renderExtraEntities() {
198 | if (!this.config.extra_entities) return '';
199 | return this.config.extra_entities.map(e => {
200 | if (!e.includes('.')) return html``;
201 | if (!this.hass!.states[e]) return html`Entity ${e} not found`;
202 | if (!isPlayPausable(this.hass!.states[e])) return renderState(e, this.hass!);
203 | return html` this._matchingEntities(p)} .hass=${this.hass}
205 | .config=${this.config}
206 | >`;
207 | });
208 | }
209 |
210 | private _secondaryText() {
211 | const entities: EntitiesFunc = p => this._matchingEntities(p)
212 |
213 | if (hasRainDelayActive(entities)) {
214 | const stop_time = entities(isRainDelayStopTime).find(_ => true)?.state;
215 | return `Rain delay${ stop_time ? ` ends ${relativeTime(new Date(stop_time), this.hass!.locale!)}` : ''}`;
216 | }
217 |
218 | const programs = entities(isProgram).filter(stateActivated).map(osName);
219 | if (hasRunOnce(entities)) programs.splice(0, 0, 'Once Program');
220 | if (hasManual(entities)) programs.push('Stations Manually');
221 |
222 | if (programs.length > 0) return 'Running ' + programs.join(', ');
223 | return '';
224 | }
225 |
226 | public async getCardSize(): Promise {
227 | return 1 + this._statusEntities().length;
228 | }
229 |
230 | static styles = [styles, css`.header { margin-top: 8px; }`];
231 | }
232 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | ==============
3 |
4 | _Version 2.0, January 2004_
5 | _<>_
6 |
7 | ### Terms and Conditions for use, reproduction, and distribution
8 |
9 | #### 1. Definitions
10 |
11 | “License” shall mean the terms and conditions for use, reproduction, and
12 | distribution as defined by Sections 1 through 9 of this document.
13 |
14 | “Licensor” shall mean the copyright owner or entity authorized by the copyright
15 | owner that is granting the License.
16 |
17 | “Legal Entity” shall mean the union of the acting entity and all other entities
18 | that control, are controlled by, or are under common control with that entity.
19 | For the purposes of this definition, “control” means **(i)** the power, direct or
20 | indirect, to cause the direction or management of such entity, whether by
21 | contract or otherwise, or **(ii)** ownership of fifty percent (50%) or more of the
22 | outstanding shares, or **(iii)** beneficial ownership of such entity.
23 |
24 | “You” (or “Your”) shall mean an individual or Legal Entity exercising
25 | permissions granted by this License.
26 |
27 | “Source” form shall mean the preferred form for making modifications, including
28 | but not limited to software source code, documentation source, and configuration
29 | files.
30 |
31 | “Object” form shall mean any form resulting from mechanical transformation or
32 | translation of a Source form, including but not limited to compiled object code,
33 | generated documentation, and conversions to other media types.
34 |
35 | “Work” shall mean the work of authorship, whether in Source or Object form, made
36 | available under the License, as indicated by a copyright notice that is included
37 | in or attached to the work (an example is provided in the Appendix below).
38 |
39 | “Derivative Works” shall mean any work, whether in Source or Object form, that
40 | is based on (or derived from) the Work and for which the editorial revisions,
41 | annotations, elaborations, or other modifications represent, as a whole, an
42 | original work of authorship. For the purposes of this License, Derivative Works
43 | shall not include works that remain separable from, or merely link (or bind by
44 | name) to the interfaces of, the Work and Derivative Works thereof.
45 |
46 | “Contribution” shall mean any work of authorship, including the original version
47 | of the Work and any modifications or additions to that Work or Derivative Works
48 | thereof, that is intentionally submitted to Licensor for inclusion in the Work
49 | by the copyright owner or by an individual or Legal Entity authorized to submit
50 | on behalf of the copyright owner. For the purposes of this definition,
51 | “submitted” means any form of electronic, verbal, or written communication sent
52 | to the Licensor or its representatives, including but not limited to
53 | communication on electronic mailing lists, source code control systems, and
54 | issue tracking systems that are managed by, or on behalf of, the Licensor for
55 | the purpose of discussing and improving the Work, but excluding communication
56 | that is conspicuously marked or otherwise designated in writing by the copyright
57 | owner as “Not a Contribution.”
58 |
59 | “Contributor” shall mean Licensor and any individual or Legal Entity on behalf
60 | of whom a Contribution has been received by Licensor and subsequently
61 | incorporated within the Work.
62 |
63 | #### 2. Grant of Copyright License
64 |
65 | Subject to the terms and conditions of this License, each Contributor hereby
66 | grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
67 | irrevocable copyright license to reproduce, prepare Derivative Works of,
68 | publicly display, publicly perform, sublicense, and distribute the Work and such
69 | Derivative Works in Source or Object form.
70 |
71 | #### 3. Grant of Patent License
72 |
73 | Subject to the terms and conditions of this License, each Contributor hereby
74 | grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
75 | irrevocable (except as stated in this section) patent license to make, have
76 | made, use, offer to sell, sell, import, and otherwise transfer the Work, where
77 | such license applies only to those patent claims licensable by such Contributor
78 | that are necessarily infringed by their Contribution(s) alone or by combination
79 | of their Contribution(s) with the Work to which such Contribution(s) was
80 | submitted. If You institute patent litigation against any entity (including a
81 | cross-claim or counterclaim in a lawsuit) alleging that the Work or a
82 | Contribution incorporated within the Work constitutes direct or contributory
83 | patent infringement, then any patent licenses granted to You under this License
84 | for that Work shall terminate as of the date such litigation is filed.
85 |
86 | #### 4. Redistribution
87 |
88 | You may reproduce and distribute copies of the Work or Derivative Works thereof
89 | in any medium, with or without modifications, and in Source or Object form,
90 | provided that You meet the following conditions:
91 |
92 | * **(a)** You must give any other recipients of the Work or Derivative Works a copy of
93 | this License; and
94 | * **(b)** You must cause any modified files to carry prominent notices stating that You
95 | changed the files; and
96 | * **(c)** You must retain, in the Source form of any Derivative Works that You distribute,
97 | all copyright, patent, trademark, and attribution notices from the Source form
98 | of the Work, excluding those notices that do not pertain to any part of the
99 | Derivative Works; and
100 | * **(d)** If the Work includes a “NOTICE” text file as part of its distribution, then any
101 | Derivative Works that You distribute must include a readable copy of the
102 | attribution notices contained within such NOTICE file, excluding those notices
103 | that do not pertain to any part of the Derivative Works, in at least one of the
104 | following places: within a NOTICE text file distributed as part of the
105 | Derivative Works; within the Source form or documentation, if provided along
106 | with the Derivative Works; or, within a display generated by the Derivative
107 | Works, if and wherever such third-party notices normally appear. The contents of
108 | the NOTICE file are for informational purposes only and do not modify the
109 | License. You may add Your own attribution notices within Derivative Works that
110 | You distribute, alongside or as an addendum to the NOTICE text from the Work,
111 | provided that such additional attribution notices cannot be construed as
112 | modifying the License.
113 |
114 | You may add Your own copyright statement to Your modifications and may provide
115 | additional or different license terms and conditions for use, reproduction, or
116 | distribution of Your modifications, or for any such Derivative Works as a whole,
117 | provided Your use, reproduction, and distribution of the Work otherwise complies
118 | with the conditions stated in this License.
119 |
120 | #### 5. Submission of Contributions
121 |
122 | Unless You explicitly state otherwise, any Contribution intentionally submitted
123 | for inclusion in the Work by You to the Licensor shall be under the terms and
124 | conditions of this License, without any additional terms or conditions.
125 | Notwithstanding the above, nothing herein shall supersede or modify the terms of
126 | any separate license agreement you may have executed with Licensor regarding
127 | such Contributions.
128 |
129 | #### 6. Trademarks
130 |
131 | This License does not grant permission to use the trade names, trademarks,
132 | service marks, or product names of the Licensor, except as required for
133 | reasonable and customary use in describing the origin of the Work and
134 | reproducing the content of the NOTICE file.
135 |
136 | #### 7. Disclaimer of Warranty
137 |
138 | Unless required by applicable law or agreed to in writing, Licensor provides the
139 | Work (and each Contributor provides its Contributions) on an “AS IS” BASIS,
140 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
141 | including, without limitation, any warranties or conditions of TITLE,
142 | NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
143 | solely responsible for determining the appropriateness of using or
144 | redistributing the Work and assume any risks associated with Your exercise of
145 | permissions under this License.
146 |
147 | #### 8. Limitation of Liability
148 |
149 | In no event and under no legal theory, whether in tort (including negligence),
150 | contract, or otherwise, unless required by applicable law (such as deliberate
151 | and grossly negligent acts) or agreed to in writing, shall any Contributor be
152 | liable to You for damages, including any direct, indirect, special, incidental,
153 | or consequential damages of any character arising as a result of this License or
154 | out of the use or inability to use the Work (including but not limited to
155 | damages for loss of goodwill, work stoppage, computer failure or malfunction, or
156 | any and all other commercial damages or losses), even if such Contributor has
157 | been advised of the possibility of such damages.
158 |
159 | #### 9. Accepting Warranty or Additional Liability
160 |
161 | While redistributing the Work or Derivative Works thereof, You may choose to
162 | offer, and charge a fee for, acceptance of support, warranty, indemnity, or
163 | other liability obligations and/or rights consistent with this License. However,
164 | in accepting such obligations, You may act only on Your own behalf and on Your
165 | sole responsibility, not on behalf of any other Contributor, and only if You
166 | agree to indemnify, defend, and hold each Contributor harmless for any liability
167 | incurred by, or claims asserted against, such Contributor by reason of your
168 | accepting any such warranty or additional liability.
169 |
170 | _END OF TERMS AND CONDITIONS_
171 |
172 | ### APPENDIX: How to apply the Apache License to your work
173 |
174 | To apply the Apache License to your work, attach the following boilerplate
175 | notice, with the fields enclosed by brackets `[]` replaced with your own
176 | identifying information. (Don't include the brackets!) The text should be
177 | enclosed in the appropriate comment syntax for the file format. We also
178 | recommend that a file or class name and description of purpose be included on
179 | the same “printed page” as the copyright notice for easier identification within
180 | third-party archives.
181 |
182 | Copyright [yyyy] [name of copyright owner]
183 |
184 | Licensed under the Apache License, Version 2.0 (the "License");
185 | you may not use this file except in compliance with the License.
186 | You may obtain a copy of the License at
187 |
188 | http://www.apache.org/licenses/LICENSE-2.0
189 |
190 | Unless required by applicable law or agreed to in writing, software
191 | distributed under the License is distributed on an "AS IS" BASIS,
192 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
193 | See the License for the specific language governing permissions and
194 | limitations under the License.
195 |
--------------------------------------------------------------------------------