Initial Commit

This commit is contained in:
btowles
2021-08-16 02:36:15 +00:00
commit 392ef6ccc0
20 changed files with 893 additions and 0 deletions

View File

@@ -0,0 +1,30 @@
// For format details, see https://aka.ms/devcontainer.json. For config options, see the README at:
// https://github.com/microsoft/vscode-dev-containers/tree/v0.183.0/containers/javascript-node
{
"name": "Node.js",
"build": {
"dockerfile": "../Dockerfile.dev",
// Update 'VARIANT' to pick a Node version: 12, 14, 16
"args": { "VARIANT": "14" }
},
// Set *default* container specific settings.json values on container create.
"settings": {},
// Add the IDs of extensions you want installed when the container is created.
"extensions": [
"dbaeumer.vscode-eslint"
],
// Use 'forwardPorts' to make a list of ports inside the container available locally.
// "forwardPorts": [],
// Use 'postCreateCommand' to run commands after the container is created.
// "postCreateCommand": "yarn install",
// Comment out connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root.
"remoteUser": "node",
"workspaceMount": "source=${localWorkspaceFolder},target=/workspaces/MagicMirror/modules/${localWorkspaceFolderBasename},type=bind,consistency=delegated",
"workspaceFolder": "/workspaces/MagicMirror/modules/${localWorkspaceFolderBasename}"
}

16
.eslintrc.json Normal file
View File

@@ -0,0 +1,16 @@
{
"rules": {
"indent": ["error", "tab"],
"quotes": ["error", "double"],
"max-len": ["error", 250],
"curly": "error",
"camelcase": ["error", {"properties": "never"}],
"no-trailing-spaces": ["error"],
"no-irregular-whitespace": ["error"]
},
"env": {
"browser": true,
"node": true,
"es6": true
}
}

6
.gitignore vendored Normal file
View File

@@ -0,0 +1,6 @@
node_modules/*
uploads
npm-debug.log
package-lock.json
pm2.json
workspace.code-workspace

5
.stylelintrc Normal file
View File

@@ -0,0 +1,5 @@
{
"extends": "stylelint-config-standard",
"font-family-name-quotes": "double-where-recommended",
"block-no-empty": false
}

18
.vscode/launch.json vendored Normal file
View File

@@ -0,0 +1,18 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "pwa-node",
"request": "launch",
"name": "Run MagicMirror",
"skipFiles": [
"<node_internals>/**"
],
"program": "/workspaces/MagicMirror/serveronly/index.js",
"cwd": "/workspaces/MagicMirror",
},
]
}

16
Dockerfile.dev Normal file
View File

@@ -0,0 +1,16 @@
# See here for image contents: https://github.com/microsoft/vscode-dev-containers/tree/v0.183.0/containers/javascript-node/.devcontainer/base.Dockerfile
# [Choice] Node.js version: 16, 14, 12
ARG VARIANT="16-buster"
FROM mcr.microsoft.com/vscode/devcontainers/javascript-node:0-${VARIANT}
# [Optional] Uncomment this section to install additional OS packages.
RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \
&& apt-get -y install --no-install-recommends \
git \
&& mkdir -p /workspaces \
&& chown node /workspaces \
&& su node -c "cd /workspaces && git clone https://github.com/MichMich/MagicMirror" \
&& su node -c "cd /workspaces/MagicMirror && npm install" \
&& su node -c "cd /workspaces/MagicMirror && cp config/config.js.sample config/config.js" \
&& su node -c "cd /workspaces/MagicMirror && npm install pm2 -g"

66
Gruntfile.js Normal file
View File

@@ -0,0 +1,66 @@
module.exports = function(grunt) {
require("time-grunt")(grunt);
grunt.initConfig({
pkg: grunt.file.readJSON("package.json"),
eslint: {
options: {
configFile: ".eslintrc.json"
},
target: ["*.js"]
},
stylelint: {
simple: {
options: {
configFile: ".stylelintrc"
},
src: ["*.css"]
}
},
jsonlint: {
main: {
src: ["package.json", "translations/*.json"],
options: {
reporter: "jshint"
}
}
},
markdownlint: {
all: {
options: {
config: {
"default": true,
"line-length": false,
"blanks-around-headers": false,
"no-duplicate-header": false,
"no-inline-html": false,
"MD010": false,
"MD001": false,
"MD031": false,
"MD040": false,
"MD002": false,
"MD029": false,
"MD041": false,
"MD032": false,
"MD036": false,
"MD037": false,
"MD009": false,
"MD018": false,
"MD012": false,
"MD026": false,
"MD038": false
}
},
src: ["README.md", "CHANGELOG.md", "LICENSE.txt"]
}
},
yamllint: {
all: [".travis.yml"]
}
});
grunt.loadNpmTasks("grunt-eslint");
grunt.loadNpmTasks("grunt-stylelint");
grunt.loadNpmTasks("grunt-jsonlint");
grunt.loadNpmTasks("grunt-yamllint");
grunt.loadNpmTasks("grunt-markdownlint");
grunt.registerTask("default", ["eslint", "stylelint", "jsonlint", "markdownlint", "yamllint"]);
};

21
LICENSE Normal file
View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2021 Brian Towles
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

162
MMM-HomeAssistantDisplay.js Executable file
View File

@@ -0,0 +1,162 @@
/* Magic Mirror
* Module: MMM-HomeAssistantDisplay
*
* By Brian Towles <brian@towles.com>
* MIT Licensed.
*/
Module.register("MMM-HomeAssistantDisplay", {
result: {},
defaults: {
title: "Home Assistant",
host: "hassio.local",
port: "8123",
useTLS: false,
ignoreCert: true,
token: "",
debuglogging: false,
useModuleTigger: false,
moduleTriggerTemplate: "",
moduleTriggerEntities: false,
animationSpeed: 3000,
sections: [],
class: ""
},
requiresVersion: "2.1.0", // Required version of MagicMirror
start: function () {
var self = this;
//Flag for check if module is loaded
this.loaded = false;
this.displayModule = false;
this.config.identifier = this.identifier;
this.sendSocketNotification("CONNECT", this.config);
// Setup the watched entity for the module display
if (this.config.useModuleTigger && this.config.moduleTriggerEntities) {
for (const entity in this.config.moduleTriggerEntities) {
this.sendSocketNotification("SET_WATCHED_ENTITY", {
identifier: this.identifier,
entity: this.config.moduleTriggerEntities[entity]
});
}
} else {
this.displayModule = true;
}
if (this.config.sections) {
for (const sectioid in this.config.sections) {
const section = this.config.sections[sectioid];
for (const entity in section.triggerEntities) {
this.sendSocketNotification("SET_WATCHED_ENTITY", {
identifier: this.identifier,
entity: section.triggerEntities[entity]
});
}
}
}
this.renderTemplates("foo");
self.updateDom(self.config.animationSpeed);
},
isEmpty: function (obj) {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
return false;
}
}
return true;
},
getDom: function () {
var self = this;
var wrapper = document.createElement("div");
if (this.config.class) {
wrapper.className += this.config.class;
}
if (!this.displayModule) {
this.hide();
return wrapper;
}
this.show();
for (const section in this.config.sections) {
if (this.config.sections[section].render) {
var sectionWrapper = document.createElement("div");
sectionWrapper.className += " section_" + section;
if (this.config.sections[section].class) {
sectionWrapper.className += " " + this.config.sections[section].class;
}
sectionWrapper.innerHTML = this.config.sections[section].render;
wrapper.appendChild(sectionWrapper);
}
}
return wrapper;
},
getHeader: function () {
return this.config.title;
},
getScripts: function () {
return [];
},
getStyles: function () {
return ["modules/MMM-HomeAssistantDisplay/node_modules/@mdi/font/css/materialdesignicons.min.css"];
},
// Load translations files
getTranslations: function () {
//FIXME: This can be load a one file javascript definition
return {
en: "translations/en.json",
es: "translations/es.json"
};
},
updateState: function (state) {
if (this.entities.hasOwnProperty(state.entity_id)) {
this.entities[state.entity_id].updateState(state);
}
},
renderTemplates: function (causingEntity) {
if (this.config.useModuleTigger && this.config.moduleTriggerTemplate) {
this.sendSocketNotification("RENDER_MODULE_DISPLAY_TEMPLATE", {
identifier: this.identifier,
template: this.config.moduleTriggerTemplate
});
}
for (const sectionId in this.config.sections) {
this.sendSocketNotification("RENDER_SECTION_DISPLAY_TEMPLATE", {
identifier: this.identifier,
section: sectionId,
template: this.config.sections[sectionId].displayTemplate
});
}
},
// socketNotificationReceived from helper
socketNotificationReceived: function (notification, payload) {
if (payload.identifier === this.identifier) {
switch (notification) {
case "MODULE_DISPLAY_RENDERED":
this.displayModule = payload.render.toLowerCase() === "true" || payload.render.toLowerCase() === "on";
this.updateDom();
break;
case "CHANGED_STATE":
this.renderTemplates(payload.cause);
this.updateDom();
break;
case "SECTION_DISPLAY_RENDERED":
this.config.sections[payload.section].render = payload.render;
this.updateDom();
break;
case "HASSWS_DISCONNECTED":
this.sendSocketNotification("RECONNECT_WS", this.config);
break;
default:
break;
}
}
}
});

269
README.md Normal file
View File

@@ -0,0 +1,269 @@
# Home Assistant Display Magic Mirror Module
## MMM-HomeAssistantDisplay
This is a module to display [Home Assistant](https://www.home-assistant.io/) information in the form of [Templates](https://www.home-assistant.io/docs/configuration/templating/) that are processed by Home Assistant ifself and then display the results on your Magic Mirror.
Templates allow you to output virtually any HTML you want to in the contents of the module. It allows you to use the standard Jinja2 templating engine along with all of the Home Assistant custom template functions to be able to format the output of the module in whatever way you want to display it.
# Table of Contents
* [Features](#features)
* [Configuration Options](#configuration-options)
* [Module Configuration Options](#module-configuration-options)
* [Section Configuration Options](#section-configuration-options)
* [Examples](#examples)
* [Simple Hiding](#simple-hiding)
* [Media Info when Playing](#media-info-when-playing)
* [Always Displayed with Complex Template](#always-displayed-with-complex-template)
* [Programatic Sections](#programatic-sections)
* [License](#license)
### Features:
* Template rendering directly in Home Assistant.
* Hiding or displaying module based on Home Assistant entity state or template render.
* Websocket connection to Home Assistant for fast response to state changes.
* Auto reconnect to Home Assistant when connection is lost.
* Custom CSS classes added to the module and every section.
* Targeted rerender of templates only on state change of watched entity.
* Material Design icons embeded in module to use with output.
### Configuration Options
#### Module Configuration Options
| Option | Description |
|---|---|
| title | Title to display at the top of the module. <br><br> **Default:** `Home Assistant` |
| host | The hostname or ip address of the Home Assistant instance. <br><br> **Default:** `REQUIRED hassio.local` |
| port | The port that Home Assistant is listening on. <br><br> **Default:** `8321` |
| useTLS | To use TLS (SSL) for the connections to Home Assistant. <br><br> **Default:** false |
| ignoreCert | Check the validity of the TLS (SSL) cert when using TLS. <br><br> **Default:** true |
| token | The long lived token. <br><br> **Default:** `REQUIRED` |
| useModuleTigger | Use a module trigger to determine if the module should be shown. <br><br> **Default:** false |
| moduleTriggerTemplate | The template to render when using the Module Trigger. Must return **true** or **on** |
| moduleTriggerEntities | The array of entities to watch for state changes to determine if the moduleTriggerTemplate should be re-rendered. |
| animationSpeed | The animation speed to use when updating the display of the module. <br><br>**Default:** 3000 |
| class | The CSS class to add to the module `<div>` to allow for easier CSS selection. |
| sections | The array sections of the module will try to render templates for. See the sections config. <br><br> **Default:** [] |
#### Section Configuration Options
| Option | Description |
|---|---|
| triggerEntities | The array of entities to watch for state changes to determine if this sections displayTemplate should be re-rendered. |
| displayTemplate | The template to send to Home Assistant to render. The results of the render will be displayed as the contents of this section in the module. |
| class | The CSS class name to add to the `<div>` surrounding this section of the module. |
###Examples
#### Simple Hiding
A Simple hiding module only displayed on Module Trigger:
This sets up a simple module that only displays the module when the binary_sensor.put_trash_out entity is set to **on**. It will then display if the trash and/or the recycle icons need to be displayed based on the *displayTemplate*.
![Trash and Recycle](images/trash_and_recycle.png)
```javascript
{
module: 'MMM-HomeAssistantDisplay',
position: 'top_left',
config: {
host: "YOUR_HOME_ASSISTANT_HOST",
token: "YOUR_HOME_ASSISTANT_TOKEN",
port: 8123
useTLS: true,
title: "To the Curb",
useModuleTigger: true,
moduleTriggerTemplate: `{{ states.binary_sensor.put_trash_out.state == "on"}}`,
moduleTriggerEntities: ["binary_sensor.put_trash_out"],
class: "to-the-curb",
sections: [{
triggerEntities: [
"binary_sensor.put_recycle_out",
"binary_sensor.put_trash_out"
],
displayTemplate: `
{% if states.binary_sensor.put_trash_out.state == "on" %}<i class='mdi mdi-trash-can'></i>{% endif %}
{% if states.binary_sensor.put_recycle_out.state == "on" %}<i class='mdi mdi-recycle'></i>{% endif %}
`,
class: "put-outs"
}]
},
},
```
#### Media Info when Playing
Showing playing media info only when actually playing:
This example pulls the info from a media player entity in Home Assistant. It only shows the module when its playing and grabs the title and image url from the attributes of the media player.
![Media](images/now_playing.png)
```javascript
{
module: 'MMM-HomeAssistantDisplay',
position: 'top_right',
config: {
host: "YOUR_HOME_ASSISTANT_HOST",
token: "YOUR_HOME_ASSISTANT_TOKEN",
port: 8123
useTLS: true,
title: "Playing in Master Bedroom",
useModuleTigger: true,
moduleTriggerTemplate: `{{ states.media_player.master_bedroom_echo_show.state == "playing"}}`,
moduleTriggerEntities: [
"media_player.master_bedroom_echo_show"
],
class: "playing_in_master",
sections: [
{
triggerEntities: [
"media_player.master_bedroom_echo_show"
],
displayTemplate: `
<div class="image"><img src="YOUR_HOME_ASSISTANT_BASE_URL{{ states.media_player.master_bedroom_echo_show.attributes.entity_picture_local }}" height="200"/></div>
<div class="title">{{ states.media_player.master_bedroom_echo_show.attributes.media_title }}</div>
`,
class: "playing_info"
}
]
},
},
```
#### Always Displayed with Complex Template
Always displayed module with complex display template:
This example will show a complex template logic that is always displayed because it does not use the module trigger.
![Security](images/security_states.gif)
```javascript
{
module: 'MMM-HomeAssistantDisplay',
position: 'top_left',
config: {
host: "YOUR_HOME_ASSISTANT_HOST",
token: "YOUR_HOME_ASSISTANT_TOKEN",
port: 8123
useTLS: true,
title: "Security",
class: "security",
sections: [{
triggerEntities: [
"alarm_control_panel.outside_perimeter"
],
displayTemplate: `
{%- if states.alarm_control_panel.outside_perimeter.state == "disarmed" -%}
{%- set icon = "shield-check" -%}
{%- set stateText = "Disarmed" -%}
{%- elif states.alarm_control_panel.outside_perimeter.state == "armed_night" -%}
{%- set icon = "shield-home" -%}
{%- set stateText = "Armed" -%}
{%- elif states.alarm_control_panel.outside_perimeter.state == "armed_away" -%}
{%- set icon = "shield-lock" -%}
{%- set stateText = "Armed" -%}
{%- elif states.alarm_control_panel.outside_perimeter.state == "triggered" -%}
{%- set icon = "bell-ring blink" -%}
{%- set stateText = "Triggered" -%}
{%- endif -%}
<i class='mdi mdi-{{icon}}'></i> Perimeter - {{stateText}}
`,
class: "perimeter"
},
]
},
},
```
#### Programatic Sections
Programatic setting of sections from long list for always displayed module:
This shows how you can use code to set the configuration for the module. It takes a long list of entities to watch and sets each of them as a section of the module to display only when opened.
![Trash and Recycle](images/windows_open.png)
```javascript
// Top of config.js
let perimeterWindows = [
{
entity: "binary_sensor.front_office_window",
name: "Front Office Window"
},
{
entity: "binary_sensor.garage_window",
name: "Garage Window"
},
{
entity: "binary_sensor.dining_room_window",
name: "Dining Room Window"
},
{
entity: "binary_sensor.master_bedroom_left_window",
name: "Master Left Window"
},
{
entity: "binary_sensor.master_bedroom_center_window",
name: "Master Center Window"
},
{
entity: "binary_sensor.master_bedroom_right_window",
name: "Master Right Window"
},
{
entity: "binary_sensor.guest_room_window",
name: "Guest Room Window"
},
];
let perimeterWindowSections = [];
perimeterWindows.forEach((item, i) => {
perimeterWindowSections.push({
triggerEntities: [
item.entity
],
displayTemplate: `
{% if states.${item.entity}.state == "on" %}<i class='mdi mdi-window-open'></i> ${item.name}{% endif %}
`,
class: "window"
})
....
// The module entry
{
module: 'MMM-HomeAssistantDisplay',
position: 'top_right',
config: {
host: "YOUR_HOME_ASSISTANT_HOST",
token: "YOUR_HOME_ASSISTANT_TOKEN",
port: 8123
useTLS: true,
title: "Open Windows",
useModuleTigger: false,
class: "windows",
sections: [
...perimeterWindowSections,
]
},
},
```
### License
The MIT License (MIT)
=====================
Copyright © 2016 PtrBld
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the “Software”), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
**The software is provided “as is”, without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. In no event shall the authors or copyright holders be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the software or the use or other dealings in the software.**

19
helpers/Logger.js Normal file
View File

@@ -0,0 +1,19 @@
class Logger {
constructor(name) {
this.name = name;
}
info(...message) {
console.info(`[${this.name}]`, message);
}
error(...message) {
console.error(`[${this.name}]`, message);
}
debug(...message) {
console.debug(`[${this.name}]`, message);
}
}
module.exports = Logger

BIN
images/now_playing.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

BIN
images/security_states.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 144 KiB

BIN
images/security_states2.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 156 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

BIN
images/windows_open.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.2 KiB

217
node_helper.js Normal file
View File

@@ -0,0 +1,217 @@
/* Magic Mirror
* Node Helper: MMM-HomeAssistantDisplay
*
* By Brian Towles
* MIT Licensed.
*/
var backoff = require('backoff')
const NodeHelper = require("node_helper");
const HomeAssistant = require("homeassistant");
const HomeAssistantWS = require("homeassistant-ws");
const Logger = require("./helpers/Logger");
util = require('util'),
module.exports = NodeHelper.create({
start,
stop,
socketNotificationReceived,
connect,
reconnectWebsocket,
connectWebsocket,
buildHttpUrl,
onStateChangedEvent,
evaluateTemplate,
onWebsocketCloseEvent,
backoffWSConnection,
});
function start() {
this.logger = new Logger(this.name);
if (config.debuglogging) {
this.logger.debug("MMM-HomeAssistantDisplay helper started...");
}
this.connections = {};
}
function stop() {
for (const connection in this.connections) {
this.connections[connection].websocket.unsubscribeFromEvent("state_changed");
}
}
function socketNotificationReceived(notification, payload) {
if (config.debuglogging) {
this.logger.debug(`Recieved notification ${notification}`, payload);
}
if (notification !== "CONNECT" && (!payload.identifier || !this.connections[payload.identifier])) {
this.logger.error(`No connection for ${payload.identifier} found`);
return;
}
switch (notification) {
case "CONNECT":
this.connect(payload);
break;
case "RECONNECT_WS":
this.reconnectWebsocket(payload);
break;
case "SET_WATCHED_ENTITY":
if (!this.connections[payload.identifier].entities.includes(payload.entity)) {
if (config.debuglogging) {
this.logger.debug(`Registering entity ${payload.entity}`);
}
this.connections[payload.identifier].entities.push(payload.entity);
}
break;
case "RENDER_MODULE_DISPLAY_TEMPLATE":
this.evaluateTemplate(payload).then((ret) => {
this.sendSocketNotification("MODULE_DISPLAY_RENDERED", ret);
}).catch((err) => {
this.logger.error(
"Unable to evaluate template",
err
);
});
break;
case "RENDER_SECTION_DISPLAY_TEMPLATE":
this.evaluateTemplate(payload).then((ret) => {
this.sendSocketNotification("SECTION_DISPLAY_RENDERED", {
...ret,
section: payload.section
});
}).catch((err) => {
this.logger.error(
"unable to evaluate section template",
err
);
});
break;
}
}
async function evaluateTemplate(payload) {
if (config.debuglogging) {
this.logger.debug(`Evaluating template for ${payload.template}`);
}
const hass = this.connections[payload.identifier].hass;
const response = await hass.templates.render(payload.template);
return {
identifier: payload.identifier,
render: response
}
}
function buildHttpUrl(config) {
if (config.useTLS){
schema = "https"
}
else {
schema = "http"
}
var url = `${schema}://${config.host}`;
return url;
}
async function connect(payload) {
const connectionConfig = {
host: payload.host,
port: payload.port,
token: payload.token,
ignoreCert: payload.ignoreCert,
useTLS: payload.useTLS,
};
const hass = new HomeAssistant({...connectionConfig, host: this.buildHttpUrl(connectionConfig)});
this.logger.info(`HomeAssistant connected for ${payload.identifier}`);
this.connections[payload.identifier] = {
hass,
entities: []
};
await this.backoffWSConnection(payload.identifier, connectionConfig)
}
async function backoffWSConnection(identifier, connectionConfig) {
self = this;
var call = backoff.call(this.connectWebsocket, this, identifier, connectionConfig, function(err, res) {
if (err) {
self.logger.info(`Unable to connect to Home Assistant for ${identifier}: ` + err.message);
} else {
self.logger.info(`Conected to Home Assistant for ${identifier} after ${call.getNumRetries()} retries`);
}
});
call.retryIf(function(err) {
return err.error.code == 'ECONNREFUSED';
});
call.setStrategy(new backoff.ExponentialStrategy({
initialDelay: 10,
maxDelay: 10000
}));
call.start();
}
function connectWebsocket(obj, identifier, connectionConfig, callback) {
var self = obj;
HomeAssistantWS.default({
...connectionConfig,
protocol: ((connectionConfig.useTLS) ? "wss" : "ws")
})
.then((hassWs) => {
self.connections[identifier].websocket = hassWs;
hassWs.on("state_changed", onStateChangedEvent.bind(self));
hassWs.on("ws_close", onWebsocketCloseEvent.bind(self));
callback(null, hassWs);
})
.catch((err) => {
self.logger.error(
`Unable to connect to Home Assistant for module ${identifier} failed with message: `,
err.message
);
callback(err, null);
});
return;
}
async function reconnectWebsocket(payload) {
const connectionConfig = {
host: payload.host,
port: payload.port,
token: payload.token,
ignoreCert: payload.ignoreCert
};
for (const connection in this.connections) {
if (connection == payload.identifier){
this.logger.info(`Reconnecting to Home Assistant websocket for ${payload.identifier}`);
await this.backoffWSConnection(payload.identifier, connectionConfig)
}
}
}
function onStateChangedEvent(event) {
if (config.debuglogging) {
this.logger.debug(`Got state change for ${event.data.entity_id}`);
}
for (const connection in this.connections) {
if (this.connections[connection].entities.includes(event.data.entity_id)) {
this.logger.debug(`Found listening connection (${connection}) for entity ${event.data.entity_id}`);
this.sendSocketNotification("CHANGED_STATE", {
identifier: connection,
cause: event.data.entity_id,
});
}
}
}
function onWebsocketCloseEvent(event) {
for (const connection in this.connections) {
if (event.target == this.connections[connection].websocket.rawClient.ws) {
this.logger.debug(`Hass WS Disconnected (${connection})`);
this.sendSocketNotification("HASSWS_DISCONNECTED", {
identifier: connection,
});
}
}
}

40
package.json Normal file
View File

@@ -0,0 +1,40 @@
{
"name": "MMM-HomeAssistantDisplay",
"version": "1.0.0",
"description": "Module Base template for create new modules for MagicMirror",
"scripts": {
"test": "./node_modules/grunt/bin/grunt"
},
"repository": {
"type": "git",
"url": "https://github.com/wonderslug/MMM-HomeAssistantDisplay.git"
},
"keywords": [
"magic mirror",
"home assistant",
"module"
],
"author": "Brian Towles",
"license": "MIT",
"bugs": {
"url": "https://github.com/wonderslug/MMM-HomeAssistantDisplay/issues"
},
"homepage": "https://github.com/wonderslug/MMM-HomeAssistantDisplay",
"dependencies": {
"@mdi/font": "latest",
"backoff": "^2.5.0",
"homeassistant": "^0.2.0",
"homeassistant-ws": "^0.2.1"
},
"devDependencies": {
"grunt": "latest",
"grunt-eslint": "latest",
"grunt-jsonlint": "latest",
"grunt-markdownlint": "latest",
"grunt-stylelint": "latest",
"grunt-yamllint": "latest",
"stylelint": "latest",
"stylelint-config-standard": "latest",
"time-grunt": "latest"
}
}

4
translations/en.json Normal file
View File

@@ -0,0 +1,4 @@
{
"TITLE": "Title",
"UPDATE": "Update"
}

4
translations/es.json Normal file
View File

@@ -0,0 +1,4 @@
{
"TITLE": "Titulo",
"UPDATE": "Actualización"
}