This repository has been archived by the owner on Jan 8, 2020. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
148 lines (112 loc) · 3.85 KB
/
index.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
const SonosSystem = require('sonos-discovery')
const SonosHttpAPI = require('sonos-http-api/lib/sonos-http-api.js')
const settings = require('sonos-http-api/settings')
const nodeStatic = require('node-static')
const http = require('http')
const requireDir = require('sonos-http-api/lib/helpers/require-dir')
const path = require('path')
const mqtt = require('mqtt')
const {MQTT_HOST, MQTT_USER, MQTT_PASS, MQTT_PREFIX} = process.env
const client = mqtt.connect(MQTT_HOST, {
username: MQTT_USER,
password: MQTT_PASS,
clean: false,
clientId: "sonos"
})
client.on('connect', () => console.log("mqtt - connected"))
client.on('error', (error) => console.error('mqtt - error', error))
client.on('close', () => console.error("mqtt - connection close"))
client.on('offline', () => console.log("mqtt - offline"))
const discovery = new SonosSystem(settings)
function SonosMQTTAPI(discovery, settings) {
const port = settings.port
const webroot = settings.webroot
const actions = {}
this.getWebRoot = () => webroot
this.getPort = () => port
this.discovery = discovery
const player_related_events = [
'group-mute',
'transport-state',
'group-volume',
'volume-change',
'mute-change',
]
const system_related_events = [
'list-change',
'initialized',
'topology-change',
]
player_related_events.forEach(action =>
discovery.on(action, player => {
let topic = `${MQTT_PREFIX}${player.roomName.toLowerCase().replace(" ", "-")}/${action}`
client.publish(topic.toLowerCase(), JSON.stringify(player))
})
)
system_related_events.forEach(action =>
discovery.on(action, system => {
let topic = `${MQTT_PREFIX}system/${action}`
client.publish(topic.toLowerCase(), JSON.stringify(system))
})
)
// this handles registering of all actions
this.registerAction = (action, handler) => {
client.subscribe(`${MQTT_PREFIX}${action}`, {qos: 1})
client.subscribe(`${MQTT_PREFIX}${action}/#`, {qos: 1})
actions[action] = handler
}
//load modularized actions
requireDir(path.join(__dirname, './node_modules/sonos-http-api/lib/actions'), (registerAction) => {
registerAction(this)
})
this.requestHandler = (topic, message) => {
if (discovery.zones.length === 0) {
console.error('System has yet to be discovered')
return
}
const params = topic.replace(MQTT_PREFIX, "").split('/')
const opt = {}
opt.player = discovery.getPlayer(params.pop())
try {
opt.values = JSON.parse(message.toString())
}
catch (e) {
opt.values = [message.toString()]
}
opt.action = params[0]
if (!opt.player) {
opt.player = discovery.getAnyPlayer()
}
handleAction(opt)
.then((response) => {
if (!response || response.constructor.name === 'IncomingMessage') {
response = {status: 'success'}
} else if (Array.isArray(response) && response.length > 0 && response[0].constructor.name === 'IncomingMessage') {
response = {status: 'success'}
}
sendResponse(response)
}).catch((error) => {
console.error(error)
sendResponse({status: 'error', error: error.message, stack: error.stack})
})
}
function handleAction(options) {
let player = options.player
if (!actions[options.action]) {
return Promise.reject({error: 'action \'' + options.action + '\' not found'})
}
return actions[options.action](player, options.values)
}
}
const sendResponse = body => {
client.publish(`${MQTT_PREFIX}out`, JSON.stringify(body), {qos: 1})
console.log(body)
}
const api = new SonosMQTTAPI(discovery, settings)
const file = new nodeStatic.Server(settings.webroot)
http.createServer((request, response) =>
request.addListener('end', () => file.serve(request, response)
).resume()
).listen(settings.port)
client.on('message', api.requestHandler)
module.exports = api