-
Notifications
You must be signed in to change notification settings - Fork 11
/
index.js
182 lines (142 loc) · 4.09 KB
/
index.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
const EventEmitter = require('events')
const Websocket = require('ws')
const defaultConfig = {
host: 'localhost',
protocol: 'ws',
retryTimeout: 5000,
timeout: 5000,
retryCount: 10,
port: 8123,
password: '',
token: ''
}
class Homeassistant extends EventEmitter {
constructor(options) {
super()
this.config = Object.assign(defaultConfig, options)
this.url = `${this.config.protocol}://${this.config.host}:${this.config.port}/api/websocket`
this.retriesLeft = this.config.retryCount
this.promises = {}
this.states = []
this.id = 1
}
connect() {
this.ws = new Websocket(this.url)
this.ws.on('message', data => {
data = JSON.parse(data)
if (data.type == 'auth_ok') {
this.emit('connection', 'authenticated')
}
if (data.type == 'auth_required') {
if (!this.config.password && !this.config.token) throw new Error('Password required')
if (this.config.token)
return this.send({type: 'auth', access_token: this.config.token}, false)
return this.send({type: 'auth', api_password: this.config.password}, false)
}
if (data.type == 'auth_invalid') {
throw new Error('Invalid password')
}
let p = this.promises[data.id]
if (!p) return false;
if (p.timeout) {
clearTimeout(p.timeout)
}
if (p.callback) {
p.callback(data)
}
})
this.ws.on('open', () => {
this.emit('connection', 'connected')
if(this.retry) {
clearTimeout(this.retry)
this.retry = null
}
this.retriesLeft = this.config.retryCount
})
this.ws.on('error', () => {
this.emit('connection', 'connection_error')
this.reconnect()
})
this.ws.on('close', () => {
this.emit('connection', 'connection_closed')
this.reconnect()
})
return new Promise((resolve, reject) => {
this.on('connection', info => {
if (info == 'authenticated') resolve(this)
})
}).then(() => {
return this.send({
type: 'get_states'
})
}).then(states => {
this.states = states.result
return this.subscribe({
callback: this.updateState.bind(this)
})
})
}
reconnect() {
if (this.retry) return true
this.retry = setInterval(() => {
if(this.retriesLeft === 0) {
clearTimeout(this.retry)
throw new Error('home-assistant connection closed')
}
if(this.retriesLeft > 0) this.retriesLeft--
try {
this.emit('connection', 'reconnecting')
this.connect()
} catch (error) { }
}, this.config.retryTimeout)
}
send(data, addId = true) {
if (addId) {
data.id = this.id
this.id++
}
return new Promise((resolve, reject) => {
this.promises[data.id] = {
timeout: setTimeout(() => {
return reject(new Error('No response received from home-assistant'))
}, this.config.timeout),
callback: resolve
}
this.ws.send(JSON.stringify(data))
})
}
call(options) {
return this.send(Object.assign({type: 'call_service'}, options))
}
subscribe(options) {
if(!options.callback) throw new Error('Callback function is required')
let data = { type: 'subscribe_events' }
if(options.event) data.event_type = event
return this.send(data)
.then((data) => {
if(!data.success) return Promise.reject(new Error(data))
this.promises[data.id].callback = options.callback
return Promise.resolve(data)
})
}
unsubscribe(subscription) {
return this.send({
type: 'unsubscribe_events',
subscription
})
}
findEntity(id) {
return this.states.findIndex(state => state.entity_id === id)
}
updateState(change) {
let data = change.event.data
if (change.event.event_type !== 'state_changed') return true
let changeIndex = this.findEntity(data.entity_id)
this.states[changeIndex] = data.new_state
this.emit(`state:${data.entity_id}`, data)
}
state(entity) {
return this.states[this.findEntity(entity)]
}
}
module.exports = Homeassistant