forked from matthinc/HomeAssistantElectron
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtray.js
98 lines (83 loc) · 2.94 KB
/
tray.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
const Client = require('node-rest-client').Client
const { app, BrowserWindow, Menu, dialog, shell, Tray } = require('electron')
var client = new Client()
/**
* Calls a home assistant service
* @param {*} hass
* @param {*} password
* @param {*} domain
* @param {*} service
* @param {*} entity_id
*/
function hassService(hass, password, domain, service, entity_id) {
client.post(`${hass}/api/services/${domain}/${service}`,
{ headers: { 'x-ha-access': password, 'Content-Type': 'application/json' }, data: { entity_id: entity_id, } },
(data, res) => { })
}
/**
* get single domain and create best label
* @param {*} states
* @param {*} domain
* @param {*} sensor if true, label contains state and unit
*/
function filterDomain(states, domain, sensor = false) {
return states
.filter(state => state.entity_id.startsWith(domain + '.'))
.map(item => {
let label = item.attributes.friendly_name
if (!label) {
label = item.entity_id
}
if (sensor) {
label += ': ' + item.state
}
if (item.attributes.unit_of_measurement) {
label += item.attributes.unit_of_measurement
}
item.label = label
return item
})
}
function createTray(hass, password) {
let tray = new Tray('assets/tray.png')
client.get(hass + `/api/states?api_password=${password}`, (data, res) => {
if (data instanceof Buffer) {
dialog.showErrorBox('Tray error', `Unable to connect to ${hass}/apis/states?api_password=${password}`)
return
}
let switches = filterDomain(data, 'switch').map(item => {
return {
label: item.label,
click() { hassService(hass, password, 'switch', 'toggle', item.entity_id) }
}
})
let lights = filterDomain(data, 'light').map(item => {
return {
label: item.label,
click() { hassService(hass, password, 'light', 'toggle', item.entity_id) }
}
})
let scenes = filterDomain(data, 'scene').map(item => {
return {
label: item.label,
click() { hassService(hass, password, 'scene', 'turn_on', item.entity_id) }
}
})
let sensors = filterDomain(data, 'sensor', true).map(item => {
return { label: item.label, enabled: false }
})
let bins = filterDomain(data, 'binary_sensor', true).map(item => {
return { label: item.label, enabled: false }
})
let items = [
...sensors,
...bins,
{ label: 'Switches', submenu: switches },
{ label: 'Lights', submenu: lights },
{ label: 'Scenes', submenu: scenes }
]
let menu = Menu.buildFromTemplate(items)
tray.setContextMenu(menu)
})
}
module.exports = createTray