-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
MMM-Hotword2.js
249 lines (212 loc) · 7.57 KB
/
MMM-Hotword2.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
class HotwordHelper {
#_callbacks = null
constructor(callbacks) {
this.#_callbacks = callbacks
}
sendNotification(notification, payload) {
this.#_callbacks.sendNotification(notification, payload)
}
async shellExec(scr) {
return this.#_callbacks.shellExec(scr)
}
getModules() {
return this.#_callbacks.getModules()
}
getModule(name) {
const modules = this.getModules()
return modules.find(m => m.name === name)
}
}
Module.register("MMM-Hotword2", {
defaults: {
verbose: false,
//stealth: false,
startOnBoot: true,
device: -1, // default device: -1. Index or mic name
sensitivity: 0.5,
continuousRecording: false,
restart: false,
restartDelay: 1000,
onDetect: async ({ helper, result, error, payload }) => { // helper, result, error, payload
if (error) return
console.log('[HOT2] Detected:', result)
helper.sendNotification('SHOW_ALERT', { title: 'Hotword Detected', message: `Hotword: ${result?.hotword}` })
},
languageModel: null, // For english, just leave as null, or 'porcupine_params_ko.pv' for Korean.
hotwords: [
{ hotword: 'COMPUTER' },
{ hotword: 'JARVIS' },
],
/* Advanced settings */
recorderFrameLength: 512,
recorderBufferedFramesCount: 50, // 50 * 512 / 16000 = 1.6 sec. Higher value is more smooth but memory consuming.
tooShortRecording: 1000 * 1, // 1 sec
tooLongRecording: 1000 * 60, // 60 sec
soundThreshold: 0.1, // 0 ~ 1. Ideally, 0 is silent and your voice will increase the number. Lower value is more sensitive. In noisy environment, set higher value.
silentFrames : 100, // accumulated soundThreshold for silent detection. (soundThreshold 0.1 to 100 accumulated frames would be around 1.5 sec)
waitTimeout: 1000 * 30, // 30 sec
},
getStyles: function () {
return ['MMM-Hotword2.css']
},
regularizeHotwords: function (hotwords) {
return hotwords.map(h => {
return {
...h,
onDetect: (typeof h.onDetect === 'function') ? h.onDetect : this.config.onDetect,
restart: h.restart ?? this.config.restart,
restartDelay: h.restartDelay ?? this.config.restartDelay,
continuousRecording: h.continuousRecording ?? this.config.continuousRecording,
sensitivity: h.sensitivity ?? this.config.sensitivity,
}
})
},
start: function () {
this.requested = new Map()
this.shellJobs = new Map()
this.config.hotwords = this.regularizeHotwords(this.config.hotwords)
this.sendSocketNotification('INIT', this.config)
this.helper = new HotwordHelper({
sendNotification: (noti, payload) => {
this.sendNotification(noti, payload)
},
shellExec: (script) => {
const { resolve, promise } = Promise.withResolvers()
const resolver = (shellId, result) => {
resolve(result)
this.shellJobs.delete(shellId)
}
const shellId = new Date().getTime() + Math.random().toString(36).substring(7)
this.shellJobs.set(shellId, resolver)
this.sendSocketNotification("SHELL_EXEC", { shellId, script })
return promise
},
getModules: () => {
return MM.getModules()
},
})
},
onDeactivated: async function (payload) {
this.onStatus({ status: '' })
//setTimeout(async () => {
await this.flushRequestedMap()
this.sendNotification('HOTWORD_DEACTIVATED')
//}, 1000)
},
onResult: async function ({ notificationId, result, error, payload }) {
const { sender, payload: original } = this.consumeRequestedMap(notificationId)
if (!original) return
let { callback = async () => { return }, ...rest } = original
if (typeof callback !== 'function') return
await callback({ error, result, payload: rest })
const { hotwords = [] } = original?.config ?? this.config
if (Array.isArray(hotwords) && hotwords.length > 0) {
let found = hotwords.find(h => h.hotword === result?.hotword)
let onDetect = (typeof found?.onDetect === 'function') ? found.onDetect : this.config.onDetect
const ret = await onDetect({
helper: this.helper,
result,
error,
payload: rest
})
if (found?.restart) {
setTimeout(() => {
console.log('[HOT2] Restarting detector...')
this.notificationReceived('HOTWORD_ACTIVATE', original, sender)
}, found?.restartDelay ?? 1000)
} else {
setTimeout(() => {
const status = document.getElementById('HOT2_' + this.identifier)
if (status.dataset.status === 'detected') {
console.log('[HOT2] Finished...')
status.dataset.status = ''
status.innerHTML = ''
}
}, 3000)
}
}
},
onInitialized: function () {
this.sendNotification('HOTWORD_READY')
if (this.config.startOnBoot) {
Log.log('[HOT2] Starting on Boot...')
this.notificationReceived('HOTWORD_ACTIVATE', this.config, { name: 'MMM-Hotword2' })
}
},
onStatus: function ({ status = '', content = '' }) {
const dom = document.getElementById('HOT2_' + this.identifier)
if (!dom) return
dom.dataset.status = status
dom.innerHTML = content || ''
},
onShellResult: function ({ shellId, result }) {
if (!this.shellJobs.has(shellId)) return
const resolver = this.shellJobs.get(shellId)
resolver(shellId, result)
},
socketNotificationReceived: function (notification, payload) {
const job = {
'INITIALIZED': 'onInitialized',
//'RESULT': 'onResult',
'DEACTIVATED': 'onDeactivated',
'RESULT': 'onResult',
'STATUS': 'onStatus',
'SHELL_RESULT': 'onShellResult',
}
if (job[ notification ] && typeof this[ job[ notification ] ] === 'function') {
this[ job[ notification ] ](payload)
return
}
},
notificationReceived: function (notification, payload, sender) {
const job = {
'DOM_OBJECTS_CREATED': 'onDomCreated',
'HOTWORD_ACTIVATE': 'activate',
'HOTWORD_DEACTIVATE': 'deactivate',
}
if (job[ notification ] && typeof this[ job[ notification ] ] === 'function') {
this[ job[ notification ] ](payload, sender)
return
}
},
flushRequestedMap: async function () {
for (const [ notificationId, { sender, payload: original } ] of this.requested) {
const { callback, ...payload } = original
if (typeof payload.callback === 'function') {
payload.callback({ error: 'Flushed forcely', result: null, payload })
}
}
this.requested.clear()
},
setRequestedMap: function (payload, sender) {
const notificationId = new Date().getTime() + Math.random().toString(36).substring(7)
this.requested.set(notificationId, { payload, sender })
return notificationId
},
consumeRequestedMap: function (notificationId) {
if (!this.requested.has(notificationId)) return null
const payload = this.requested.get(notificationId)
//this.requested.delete(notificationId)
return payload
},
activate: function (delivered = {}, sender = { name: 'unknown' }) {
const payload = { ...this.config, ...delivered }
const notificationId = this.setRequestedMap(payload, sender)
this.sendSocketNotification('ACTIVATE', { notificationId, ...payload })
},
onDomCreated: function () {
//this.sendSocketNotification('INIT', this.config)
},
stop: function () {
this.deactivate()
},
deactivate: function () {
this.sendSocketNotification('DEACTIVATE')
},
getDom: function () {
const wrapper = document.createElement("div")
wrapper.className = "HOT2"
wrapper.id = 'HOT2_' + this.identifier
return wrapper
},
})