forked from zwave-js/zwave-js-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
328 lines (273 loc) · 8.07 KB
/
app.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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
const express = require('express')
const reqlib = require('app-root-path').require
const logger = require('morgan')
const cookieParser = require('cookie-parser')
const bodyParser = require('body-parser')
const app = express()
const SerialPort = require('serialport')
const jsonStore = reqlib('/lib/jsonStore.js')
const cors = require('cors')
const ZWaveClient = reqlib('/lib/ZwaveClient')
const MqttClient = reqlib('/lib/MqttClient')
const Gateway = reqlib('/lib/Gateway')
const store = reqlib('config/store.js')
const debug = reqlib('/lib/debug')('App')
const history = require('connect-history-api-fallback')
const SocketManager = reqlib('/lib/SocketManager')
const { inboundEvents, socketEvents } = reqlib('/lib/SocketManager.js')
const utils = reqlib('/lib/utils.js')
const renderIndex = reqlib('/lib/renderIndex')
const socketManager = new SocketManager()
let gw // the gateway instance
// flag used to prevent multiple restarts while one is already in progress
let restarting = false
// ### UTILS
function hasProperty (obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop)
}
function start (server) {
setupSocket(server)
setupInterceptor()
startGateway()
}
function startGateway () {
const settings = jsonStore.get(store.settings)
let mqtt
let zwave
if (settings.mqtt) {
mqtt = new MqttClient(settings.mqtt)
}
if (settings.zwave) {
zwave = new ZWaveClient(settings.zwave, socketManager.io)
}
gw = new Gateway(settings.gateway, zwave, mqtt)
gw.start()
restarting = false
}
function setupInterceptor () {
// intercept logs and redirect them to socket
const interceptor = function (write) {
return function (...args) {
socketManager.io.emit('DEBUG', args[0].toString())
write.apply(process.stdout, args)
}
}
process.stdout.write = interceptor(process.stdout.write)
process.stderr.write = interceptor(process.stderr.write)
}
// print actual application version (with git short sha is git is installed)
function printVersion () {
let rev
try {
rev = require('child_process')
.execSync('git rev-parse --short HEAD')
.toString()
.trim()
} catch (error) {
// git not installed
}
debug(`Version: ${require('./package.json').version}${rev ? '.' + rev : ''}`)
}
// ### EXPRESS SETUP
printVersion()
debug('Application path:' + utils.getPath(true))
// view engine setup
app.set('views', utils.joinPath(false, 'views'))
app.set('view engine', 'ejs')
app.use(logger('dev', { stream: { write: msg => debug(msg.trimEnd()) } }))
app.use(bodyParser.json({ limit: '50mb' }))
app.use(
bodyParser.urlencoded({
limit: '50mb',
extended: true,
parameterLimit: 50000
})
)
app.use(cookieParser())
app.use(
history({
index: '/'
})
)
app.get('/', renderIndex)
app.use('/', express.static(utils.joinPath(false, 'dist')))
app.use(cors())
// ### SOCKET SETUP
/**
* Binds socketManager to `server`
*
* @param {HttpServer} server
*/
function setupSocket (server) {
server.on('listening', function () {
const addr = server.address()
const bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port
debug('Listening on', bind)
})
socketManager.bindServer(server)
socketManager.on(inboundEvents.init, function (socket) {
if (gw.zwave) {
socket.emit(socketEvents.init, {
nodes: gw.zwave.nodes,
info: gw.zwave.ozwConfig,
error: gw.zwave.error,
cntStatus: gw.zwave.cntStatus
})
}
})
socketManager.on(inboundEvents.zwave, async function (socket, data) {
debug('Zwave api call:', data.api, data.args)
if (gw.zwave) {
const result = await gw.zwave.callApi(data.api, ...data.args)
result.api = data.api
socket.emit(socketEvents.api, result)
}
})
socketManager.on(inboundEvents.hass, async function (socket, data) {
debug('Hass api call:', data.apiName)
switch (data.apiName) {
case 'delete':
gw.publishDiscovery(data.device, data.nodeId, true, true)
break
case 'discover':
gw.publishDiscovery(data.device, data.nodeId, false, true)
break
case 'rediscoverNode':
gw.rediscoverNode(data.nodeId)
break
case 'disableDiscovery':
gw.disableDiscovery(data.nodeId)
break
case 'update':
gw.zwave.updateDevice(data.device, data.nodeId)
break
case 'add':
gw.zwave.addDevice(data.device, data.nodeId)
break
case 'store':
await gw.zwave.storeDevices(data.devices, data.nodeId, data.remove)
break
}
})
}
// ### APIs
app.get('/health', async function (req, res) {
let mqtt = false
let zwave = false
if (gw) {
mqtt = gw.mqtt ? gw.mqtt.getStatus().status : false
zwave = gw.zwave ? gw.zwave.getStatus().status : false
}
const status = mqtt && zwave
res.status(status ? 200 : 500).send(status ? 'Ok' : 'Error')
})
app.get('/health/:client', async function (req, res) {
const client = req.params.client
let status
if (client !== 'zwave' && client !== 'mqtt') {
res.status(500).send("Requested client doesn 't exist")
} else {
status = gw && gw[client] ? gw[client].getStatus().status : false
}
res.status(status ? 200 : 500).send(status ? 'Ok' : 'Error')
})
// get settings
app.get('/api/settings', async function (req, res) {
const data = {
success: true,
settings: jsonStore.get(store.settings),
devices: gw.zwave ? gw.zwave.devices : {},
serial_ports: []
}
let ports
if (process.platform !== 'sunos') {
try {
ports = await SerialPort.list()
} catch (error) {
debug(error)
}
data.serial_ports = ports ? ports.map(p => p.path) : []
res.json(data)
} else res.json(data)
})
// get config
app.get('/api/exportConfig', function (req, res) {
return res.json({
success: true,
data: jsonStore.get(store.nodes),
message: 'Successfully exported nodes JSON configuration'
})
})
// import config
app.post('/api/importConfig', async function (req, res) {
const config = req.body.data
try {
if (!gw.zwave) throw Error('Zwave client not inited')
if (!Array.isArray(config)) throw Error('Configuration not valid')
else {
for (let i = 0; i < config.length; i++) {
const e = config[i]
if (e && (!hasProperty(e, 'name') || !hasProperty(e, 'loc'))) {
throw Error('Configuration not valid')
} else if (e) {
await gw.zwave.callApi('_setNodeName', i, e.name || '')
await gw.zwave.callApi('_setNodeLocation', i, e.loc || '')
if (e.hassDevices) {
await gw.zwave.storeDevices(e.hassDevices, i, false)
}
}
}
}
res.json({ success: true, message: 'Configuration imported successfully' })
} catch (error) {
debug(error.message)
return res.json({ success: false, message: error.message })
}
})
// update settings
app.post('/api/settings', async function (req, res) {
try {
if (restarting) {
throw Error(
'Gateway is restarting, wait a moment before doing another request'
)
}
restarting = true
await jsonStore.put(store.settings, req.body)
await gw.close()
startGateway()
res.json({ success: true, message: 'Configuration updated successfully' })
} catch (error) {
debug(error)
res.json({ success: false, message: error.message })
}
})
// ### ERROR HANDLERS
// catch 404 and forward to error handler
app.use(function (req, res, next) {
const err = new Error('Not Found')
err.status = 404
next(err)
})
// error handler
app.use(function (err, req, res) {
// set locals, only providing error in development
res.locals.message = err.message
res.locals.error = req.app.get('env') === 'development' ? err : {}
debug(`${req.method} ${req.url} ${err.status} - Error: ${err.message}`)
// render the error page
res.status(err.status || 500)
res.redirect('/')
})
process.removeAllListeners('SIGINT')
process.on('SIGINT', function () {
debug('Closing clients...')
gw.close()
.catch(err => {
debug('Error while closing clients', err)
})
.finally(() => {
process.exit()
})
})
module.exports = { app, start }