-
Notifications
You must be signed in to change notification settings - Fork 1
/
sound.js
91 lines (75 loc) · 2.26 KB
/
sound.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
// On/Off MQTT<->Websocket proxy
const yargs = require('yargs');
const mqtt = require('mqtt');
const WebSocket = require('ws');
const argv = yargs
.option('mqttHost', {
description: 'Hostname of MQTT broker',
alias: 'mqtt',
type: 'string'
})
.option('wsURL', {
description: 'URL for WebSocket server. Full URL include wss://',
alias: 'ws',
type: 'string'
})
.option('mqttLightName', {
description: 'Name of the light that will precede / commands',
type: 'string'
})
.option('wsKey', {
description: 'In websocket message, the key the light represents. Ex: {"$key": { power: true|false } }',
type: 'string'
})
.option('wsOnAction', {
description: 'In websocket message, the key that will be sent as the action. ex: {"action": "$wsOnAction"}',
type: 'string'
})
.help()
.alias('help', 'h')
.argv;
// CONFIG
const mqqtHost = (argv.mqttHost) ? argv.mqttHost : 'o.xrho.com';
const mqttLightName = (argv.mqttLightName) ? argv.mqttLightName : 'soundLight';
const wsURL = (argv.wsURL) ? argv.wsURL : 'wss://cloud.xrho.com:443';
// key the light represents. {"$key": { power: true|false } }
const wsKey = (argv.wsKey) ? argv.wsKey : 'soundLight';
const wsOnAction = (argv.wsOnAction) ? argv.wsOnAction : 'sound';
const client = mqtt.connect(`mqtt://${mqqtHost}`);
const ws = new WebSocket(`${wsURL}`);
console.log('sound led proxy starting');
client.on('connect', () => {
console.log('mqtt connected');
client.publish(`${mqttLightName}/connected`, 'true');
client.subscribe(`${mqttLightName}/setOn`);
});
client.on('message', (topic, message) => {
if (topic === `${wsKey}/setOn`) {
console.log(`mqtt: ${message.toString()}`);
if (message.toString() === 'true') {
ws.send(JSON.stringify({
'action': wsOnAction
}));
} else {
ws.send(JSON.stringify({
'action': 'off'
}));
}
}
});
ws.onopen = () => {
console.log('webocket connection opened');
};
ws.onerror = (error) => {
console.error(`websocket error: ${error}`);
};
ws.onclose = (event) => {
console.log('websocket connection closed');
process.exit();
};
ws.onmessage = (event) => {
let json = JSON.parse(event.data);
console.log(`ws: ${json[wsKey]['power'].toString()}`);
// publish the light status
client.publish(`${mqttLightName}/getOn`, json[wsKey]['power'].toString());
};