-
Notifications
You must be signed in to change notification settings - Fork 0
/
read-sound-sensor.js
40 lines (33 loc) · 1.07 KB
/
read-sound-sensor.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
const { Board, Pin, Sensor } = require("johnny-five");
const { WebSocket, WebSocketServer } = require("ws");
const board = new Board();
const DEBUG = false;
let sensor = null;
const wss = new WebSocketServer({ port: 3000 });
function sendSoundTriggerEvent(client, value) {
if (value !== null) {
console.log('SOUND_TRIGGER_DETECTED');
client.send('SOUND_TRIGGER_DETECTED');
}
if (DEBUG) {
client.send(JSON.stringify({ 'debug-sound': value }));
console.log("debug-sound : ", value);
}
}
board.on("ready", function () {
sensor = new Sensor.Digital(8);
});
wss.on('connection', function connection(ws) {
ws.on('error', console.error);
wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN && board.isReady) {
console.log('open!');
sensor.on("change", () => {
sendSoundTriggerEvent(client, sensor.value)
});
client.on('close', function close() {
console.log('disconnected');
});
}
});
});