homebridge-lib 6.3.7 → 6.3.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,328 +0,0 @@
1
- // homebridge-lib/lib/CommandLineUtility.js
2
- //
3
- // Library for Homebridge plugins.
4
- // Copyright © 2018-2023 Erik Baauw. All rights reserved.
5
-
6
- 'use strict'
7
-
8
- const homebridgeLib = require('../index')
9
-
10
- const chalk = require('chalk')
11
- const util = require('util')
12
-
13
- // Force colors when output is re-directed.
14
- chalk.enabled = true
15
- chalk.level = 1
16
-
17
- /** Command-line tool.
18
- */
19
- class CommandLineTool {
20
- /** Make text bold.
21
- * @param {string} text - The text.
22
- * @returns {string} - The bold text.
23
- */
24
- static b (text) { return chalk.bold(text) }
25
-
26
- /** Make text underlined.
27
- * @param {string} text - The text.
28
- * @returns {string} - The underlined text.
29
- */
30
- static u (text) { return chalk.underline(text) }
31
-
32
- /** Create a new instance of a command line utility.
33
- */
34
- constructor (options = { mode: 'command' }) {
35
- // We need to handle errors here, for subtype or caller won't be able
36
- // to log the error/exception without our log functions.
37
- try {
38
- // Set program name
39
- // argv[0]: node executable, argv[1]: javascript file
40
- this.name = process.argv[1]
41
- // Use {mode: "command"} as default for logging.
42
- this._options = {
43
- chalk: false,
44
- debug: false,
45
- program: true,
46
- timestamp: false
47
- }
48
- // Set logging options.
49
- this.setOptions(options)
50
-
51
- process
52
- .on('SIGHUB', this._onSignal.bind(this))
53
- .on('SIGINT', this._onSignal.bind(this))
54
- .on('SIGTERM', this._onSignal.bind(this))
55
- .on('SIGABRT', this._onSignal.bind(this))
56
- .on('uncaughtException', async (error) => {
57
- await this.fatal('uncaught exception: %s', error.stack)
58
- })
59
- .removeAllListeners('unhandledRejection')
60
- .on('unhandledRejection', async (error) => {
61
- await this.fatal('unhandled rejection: %s', error.stack)
62
- })
63
- } catch (error) {
64
- this._log({ label: 'fatal', chalk: chalk.bold.red }, error)
65
- }
66
- }
67
-
68
- /** Set logging options.
69
- * @param {object} options - Loggin options.
70
- * @parameter {string} mode - Mode in which utlity is run:<br>
71
- * - `command` - From the command line.
72
- * - `daemon` - As a daemon.
73
- * - `service` - As a service.
74
- * @parameter {boolean} [debug=false] - Output debug messages.
75
- * @parameter {boolean} [vdebug=false] - Output verbose debug messages.
76
- * @parameter {boolean} [vvdebug=false] - Output very verbose debug messages.
77
- * @returns {object} - The old options.
78
- */
79
- setOptions (options) {
80
- if (this.optionParser == null) {
81
- this.optionParser = new homebridgeLib.OptionParser(this._options)
82
- this.optionParser
83
- .boolKey('chalk') // Use chalk to colour messages.
84
- .boolKey('debug') // Show debug messages.
85
- .boolKey('vdebug') // Show verbose debug messages.
86
- .boolKey('vvdebug') // Show very verbose debug messages.
87
- .boolKey('program') // Include program name.
88
- .boolKey('timestamp') // Include timestamp.
89
- .enumKey('mode')
90
- .enumKeyValue('mode', 'command', () => {
91
- // Command-line program.
92
- this._options.chalk = false
93
- this._options.program = true
94
- this._options.timestamp = false
95
- })
96
- .enumKeyValue('mode', 'daemon', () => {
97
- // Program runs as standalone daemon.
98
- this._options.chalk = true
99
- this._options.program = false
100
- this._options.timestamp = true
101
- })
102
- .enumKeyValue('mode', 'service', () => {
103
- // Program runs as systemctl service.
104
- this._options.chalk = true
105
- this._options.program = false
106
- this._options.timestamp = false
107
- })
108
- }
109
- const oldOptions = this._options
110
- this.optionParser.parse(options)
111
- if (this._options.debug) {
112
- this._options.chalk = true
113
- }
114
-
115
- return oldOptions
116
- }
117
-
118
- /** Do cleanup before exit.
119
- * @abstract
120
- */
121
- async destroy () {}
122
-
123
- // Signal handler.
124
- async _onSignal (signal, signalNum) {
125
- this.log('got %s - exiting', signal)
126
- try {
127
- await this.destroy()
128
- } catch (error) {
129
- this.error(error)
130
- }
131
- setImmediate(() => { process.exit(128 + signalNum) })
132
- // Prevent _onSignal() from returning.
133
- await homebridgeLib.timeout(1000)
134
- }
135
-
136
- /** Program name.
137
- * @type {string}
138
- */
139
- get name () { return this._name }
140
- set name (name) {
141
- const list = name.split('/')
142
- this._name = list[list.length - 1]
143
- process.title = this._name
144
- }
145
-
146
- /** Debug mode is enabled.
147
- * @type {boolean}
148
- */
149
- get debugEnabled () {
150
- return !!this._options.debug
151
- }
152
-
153
- /** Usage string.
154
- * @type {string}
155
- */
156
- get usage () { return this._usage }
157
- set usage (usage) {
158
- this._usage = usage
159
- }
160
-
161
- /** Verbose debug mode is enabled.
162
- * @type {boolean}
163
- */
164
- get vdebugEnabled () {
165
- return !!this._options.vdebug
166
- }
167
-
168
- // ===== Logging =============================================================
169
-
170
- /** Print debug message to stderr.
171
- * @param {string|Error} format - The printf-style message or an instance of
172
- * [Error](https://nodejs.org/dist/latest-v14.x/docs/api/errors.html#errors_class_error).
173
- * @param {...string} args - Arguments to the printf-style message.
174
- */
175
- debug (format, ...args) {
176
- if (this._options.debug) {
177
- this._log({ chalk: chalk.grey }, format, ...args)
178
- }
179
- }
180
-
181
- /** Print error message to stderr.
182
- * @param {string|Error} format - The printf-style message or an instance of
183
- * [Error](https://nodejs.org/dist/latest-v14.x/docs/api/errors.html#errors_class_error).
184
- * @param {...string} args - Arguments to the printf-style message.
185
- */
186
- error (format, ...args) {
187
- this._log({ label: 'error', chalk: chalk.bold.red }, format, ...args)
188
- }
189
-
190
- /** Print error message to stderr and abort program.
191
- * @param {string|Error} format - The printf-style message or an instance of
192
- * [Error](https://nodejs.org/dist/latest-v14.x/docs/api/errors.html#errors_class_error).
193
- * @param {...string} args - Arguments to the printf-style message.
194
- */
195
- async fatal (format, ...args) {
196
- this._log({ label: 'fatal', chalk: chalk.bold.red }, format, ...args)
197
- try {
198
- await this.destroy()
199
- } catch (error) {
200
- this.error(error)
201
- }
202
- setImmediate(() => { process.exit(-1) })
203
- // Prevent fatal() from returning.
204
- await homebridgeLib.timeout(1000)
205
- }
206
-
207
- /** Print log message to stderr.
208
- * @param {string|Error} format - The printf-style message or an instance of
209
- * [Error](https://nodejs.org/dist/latest-v14.x/docs/api/errors.html#errors_class_error).
210
- * @param {...string} args - Arguments to the printf-style message.
211
- */
212
- log (format, ...args) {
213
- this._log({}, format, ...args)
214
- }
215
-
216
- /** Print log message continuation to stderr.
217
- * @param {string|Error} format - The printf-style message or an instance of
218
- * [Error](https://nodejs.org/dist/latest-v14.x/docs/api/errors.html#errors_class_error).
219
- * @param {...string} args - Arguments to the printf-style message.
220
- */
221
- logc (format, ...args) {
222
- this._log({ noLabel: true }, format, ...args)
223
- }
224
-
225
- /** Print message to stdout.
226
- * @param {string|Error} format - The printf-style message or an instance of
227
- * [Error](https://nodejs.org/dist/latest-v14.x/docs/api/errors.html#errors_class_error).
228
- * @param {...string} args - Arguments to the printf-style message.
229
- */
230
- print (format, ...args) {
231
- this._log({ noLabel: true, stdout: true }, format, ...args)
232
- }
233
-
234
- /** Print verbose debug message to stderr.
235
- * @param {string|Error} format - The printf-style message or an instance of
236
- * [Error](https://nodejs.org/dist/latest-v14.x/docs/api/errors.html#errors_class_error).
237
- * @param {...string} args - Arguments to the printf-style message.
238
- */
239
- vdebug (format, ...args) {
240
- if (this._options.vdebug) {
241
- this._log({ chalk: chalk.grey }, format, ...args)
242
- }
243
- }
244
-
245
- /** Print very verbose debug message to stderr.
246
- * @param {string|Error} format - The printf-style message or an instance of
247
- * [Error](https://nodejs.org/dist/latest-v14.x/docs/api/errors.html#errors_class_error).
248
- * @param {...string} args - Arguments to the printf-style message.
249
- */
250
- vvdebug (format, ...args) {
251
- if (this._options.vvdebug) {
252
- this._log({ chalk: chalk.grey }, format, ...args)
253
- }
254
- }
255
-
256
- /** Print warning message to stderr.
257
- * @param {string|Error} format - The printf-style message or an instance of
258
- * [Error](https://nodejs.org/dist/latest-v14.x/docs/api/errors.html#errors_class_error).
259
- * @param {...string} args - Arguments to the printf-style message.
260
- */
261
- warn (format, ...args) {
262
- this._log({ label: 'warning', chalk: chalk.yellow }, format, ...args)
263
- }
264
-
265
- // Do the heavy lifting for debug(), error(), fatal(), log(), and warn(),
266
- // taking into account the options, and errors vs exceptions.
267
- _log (params = {}, ...args) {
268
- const output = params.stdout ? process.stdout : process.stderr
269
- let timestamp = ''
270
- let message = ''
271
- let usage
272
-
273
- // If last argument is Error convert it to string.
274
- if (args.length > 0) {
275
- let lastArg = args.pop()
276
- if (lastArg instanceof Error) {
277
- if (lastArg.constructor.name === 'UsageError') {
278
- usage = true
279
- }
280
- lastArg = homebridgeLib.formatError(lastArg, this._options.chalk)
281
- }
282
- args.push(lastArg)
283
- }
284
-
285
- // Format message.
286
- if (args[0] == null) {
287
- message = ''
288
- } else if (typeof args[0] === 'string') {
289
- message = util.format(...args)
290
- } else {
291
- message = util.format('%o', ...args)
292
- }
293
-
294
- // Handle newline.
295
- if (message.substring(message.length - 2) === '\\c') {
296
- message = message.substring(0, message.length - 2)
297
- } else {
298
- message += '\n'
299
- }
300
-
301
- // Handle labels.
302
- if (!params.noLabel) {
303
- if (params.label != null) {
304
- message = params.label + ': ' + message
305
- }
306
- if (this._options.program) {
307
- message = this._name + ': ' + message
308
- }
309
- if (this._options.timestamp) {
310
- timestamp = '[' + String(new Date()).substring(0, 24) + '] '
311
- if (this._options.chalk) {
312
- timestamp = chalk.white(timestamp)
313
- }
314
- }
315
- }
316
-
317
- // Handle colours.
318
- if (params.chalk != null && this._options.chalk) {
319
- message = params.chalk(message)
320
- }
321
- output.write(timestamp + message)
322
- if (usage && this._usage != null) {
323
- this.logc('usage: %s', this._usage)
324
- }
325
- }
326
- }
327
-
328
- module.exports = CommandLineTool
package/lib/HapTool.js DELETED
@@ -1,92 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- // homebridge-lib/lib/HapTool.js
4
- //
5
- // Library for Homebridge plugins.
6
- // Copyright © 2018-2023 Erik Baauw. All rights reserved.
7
- //
8
- // Logger for HomeKit accessory announcements.
9
-
10
- 'use strict'
11
-
12
- const homebridgeLib = require('../index')
13
-
14
- const Bonjour = require('bonjour-hap')
15
-
16
- const { b, u } = homebridgeLib.CommandLineTool
17
-
18
- const usage = `${b('hap')} [${b('-hVlrs')}] [${b('-t')} ${u('timeout')}]`
19
- const help = `Logger for HomeKit accessory announcements.
20
-
21
- Usage: ${usage}
22
-
23
- Search for HomeKit accessory announcements
24
- Parameters:
25
- ${b('-h')} Print this help and exit.
26
- ${b('-V')} Print version and exit.
27
- ${b('-d')} Listen for Bonjour alive broadcasts instead of searching.
28
- ${b('-s')} Do not output timestamps (useful when running as service).
29
- ${b('-t')} ${u('timeout')} Search for ${u('timeout')} seconds instead of default ${b('5')}.`
30
-
31
- class HapTool extends homebridgeLib.CommandLineTool {
32
- constructor () {
33
- super()
34
- this.usage = usage
35
- this.options = { timeout: 15 }
36
- }
37
-
38
- parseArguments () {
39
- const parser = new homebridgeLib.CommandLineParser()
40
- parser
41
- .help('h', 'help', help)
42
- .version('V', 'version')
43
- .flag('l', 'listen', (key) => { this.options.mode = 'daemon' })
44
- .flag('s', 'service', (key) => { this.options.mode = 'service' })
45
- .option('t', 'timeout', (value, key) => {
46
- this.options.timeout = homebridgeLib.OptionParser.toInt(
47
- 'timeout', value, 1, 60, true
48
- )
49
- })
50
- .parse()
51
- }
52
-
53
- onUp (obj) {
54
- delete obj.rawTxt
55
- this.log('found accessory: %s', obj.name, this.jsonFormatter.stringify(obj))
56
- }
57
-
58
- async main () {
59
- try {
60
- this.parseArguments()
61
- this.jsonFormatter = new homebridgeLib.JsonFormatter(
62
- this.options.mode === 'service'
63
- ? { noWhiteSpace: true, sortKeys: true }
64
- : { sortKeys: true }
65
- )
66
- if (this.options.mode) {
67
- this.setOptions({ mode: this.options.mode })
68
- } else {
69
- setTimeout(() => {
70
- this.log('search done')
71
- bonjour4.destroy()
72
- // bonjour6.destroy()
73
- }, this.options.timeout * 1000)
74
- }
75
- this.log('searching for HomeKit accessories')
76
- const bonjour4 = new Bonjour()
77
- const browser4 = bonjour4.find({ type: 'hap' })
78
- browser4.on('up', this.onUp.bind(this))
79
- // const bonjour6 = new Bonjour({
80
- // type: 'udp6',
81
- // interface: '::%en0', // TODO: how to determine the interface?!
82
- // ip: 'ff02::fb'
83
- // })
84
- // const browser6 = bonjour6.find({ type: 'hap' })
85
- // browser6.on('up', this.onUp.bind(this))
86
- } catch (error) {
87
- await this.fatal(error)
88
- }
89
- }
90
- }
91
-
92
- module.exports = HapTool