-
Notifications
You must be signed in to change notification settings - Fork 0
/
Homebridge.js
98 lines (84 loc) · 2.35 KB
/
Homebridge.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
'use strict'
const path = require('path')
const childProcess = require('child_process')
const { trim } = require('lodash')
const kill = require('tree-kill')
const fsExtra = require('fs-extra')
const {
HOMEBRIDGE_LOG,
HOMEBRIDGE_EXITED,
HOMEBRIDGE_STOPPING,
HOMEBRIDGE_STARTING,
PACKAGE_PATH,
HOMEBRIDGE_PATH
} = require('./statics')
class HomeBridge {
constructor (dpmcPlugin) {
this.plugin = dpmcPlugin
this.tracer = dpmcPlugin.tracer
this.process = null
this.binPath = path.resolve(PACKAGE_PATH, 'node_modules', '.bin', 'homebridge')
this.libPath = path.resolve(__dirname)
this.pluginPath = path.resolve(PACKAGE_PATH, 'plugin')
this.pluginPackageJsonOrigin = path.resolve(this.libPath, 'plugin-package.json')
this.pluginPackageJsonDest = path.resolve(this.pluginPath, 'package.json')
this.start = this.start.bind(this)
}
log (data, method) {
let cleanData = trim(data.toString())
if (cleanData.length) {
if (cleanData.split('\n').length > 1) {
cleanData = `\n${cleanData}`
}
this.tracer[method](`${HOMEBRIDGE_LOG} ${cleanData}`)
}
}
async writePackageJson () {
await fsExtra.copy(this.pluginPackageJsonOrigin, this.pluginPackageJsonDest)
}
async start () {
await this.tracer.info(HOMEBRIDGE_STARTING)
await this.writePackageJson()
const homebridgePath = path.resolve(await this.plugin.storage.getPath(), HOMEBRIDGE_PATH)
this.process = childProcess.spawn(this.binPath, [
'-U',
homebridgePath,
'-P',
this.pluginPath
], {
cwd: PACKAGE_PATH,
encoding: 'utf8'
})
this.process.stdout.on('data', data => {
this.log(data, 'info')
})
this.process.stderr.on('data', data => {
this.log(data, 'error')
})
this.process.on('close', code => {
this.log(`${HOMEBRIDGE_EXITED} ${code}`, 'info')
this.process = null
})
}
async stop () {
if (this.process) {
await this.tracer.info(HOMEBRIDGE_STOPPING)
return new Promise((resolve, reject) => {
kill(this.process.pid, error => {
if (error) {
reject(error)
} else {
this.process = null
resolve()
}
})
})
}
return Promise.resolve()
}
async restart () {
await this.stop()
return this.start()
}
}
module.exports = HomeBridge