forked from SmartThingsUle/DLNA-PLAYER
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MediaRenderer_Connect_Beta.groovy
453 lines (384 loc) · 13.5 KB
/
MediaRenderer_Connect_Beta.groovy
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
/**
* MediaRenderer Service Manager v 2.0.3 Beta Chromcast Audio Bubble Server
*
* Author: SmartThings - Ulises Mujica
*/
definition(
name: "MediaRenderer (Connect)",
namespace: "mujica",
author: "SmartThings - Ulises Mujica",
description: "Allows you to control your Media Renderer from the SmartThings app. Perform basic functions like play, pause, stop, change track, and check artist and song name from the Things screen.",
category: "SmartThings Labs",
singleInstance: true,
iconUrl: "https://graph.api.smartthings.com/api/devices/icons/st.secondary.smartapps-tile?displaySize=2x",
iconX2Url: "https://graph.api.smartthings.com/api/devices/icons/st.secondary.smartapps-tile?displaySize=2x"
)
preferences {
page(name: "MainPage", title: "Search and config your Media Renderers", install:true, uninstall: true){
section("") {
href(name: "discover",title: "Discovery process",required: false,page: "mediaRendererDiscovery",description: "tap to start searching")
}
section("Options", hideable: true, hidden: true) {
input("refreshMRInterval", "number", title:"Enter refresh players interval (min)",defaultValue:"15", required:false)
}
}
page(name: "mediaRendererDiscovery", title:"Discovery Started!")
}
def mediaRendererDiscovery()
{
log.trace "mediaRendererDiscovery() state.subscribe ${state.subscribe}"
if(canInstallLabs())
{
int mediaRendererRefreshCount = !state.mediaRendererRefreshCount ? 0 : state.mediaRendererRefreshCount as int
state.mediaRendererRefreshCount = mediaRendererRefreshCount + 1
def refreshInterval = 5
def options = mediaRenderersDiscovered() ?: []
def numFound = options.size() ?: 0
if(!state.subscribe) {
subscribe(location, null, locationHandler, [filterEvents:false])
state.subscribe = true
}
//mediaRenderer discovery request every 5 //25 seconds
if((mediaRendererRefreshCount % 8) == 0) {
discoverMediaRenderers()
}
//setup.xml request every 3 seconds except on discoveries
if(((mediaRendererRefreshCount % 1) == 0) && ((mediaRendererRefreshCount % 8) != 0)) {
verifyMediaRendererPlayer()
}
return dynamicPage(name:"mediaRendererDiscovery", title:"Discovery Started!", nextPage:"", refreshInterval:refreshInterval) {
section("Please wait while we discover your MediaRenderer. Discovery can take five minutes or more, so sit back and relax! Select your device below once discovered.") {
input "selectedMediaRenderer", "enum", required:false, title:"Select Media Renderer (${numFound} found)", multiple:true, options:options
}
}
}
else
{
def upgradeNeeded = """To use SmartThings Labs, your Hub should be completely up to date.
To update your Hub, access Location Settings in the Main Menu (tap the gear next to your location name), select your Hub, and choose "Update Hub"."""
return dynamicPage(name:"mediaRendererDiscovery", title:"Upgrade needed!", nextPage:"", install:false, uninstall: true) {
section("Upgrade") {
paragraph "$upgradeNeeded"
}
}
}
}
private discoverMediaRenderers()
{
sendHubCommand(new physicalgraph.device.HubAction("lan discovery urn:schemas-upnp-org:device:MediaRenderer:1", physicalgraph.device.Protocol.LAN))
}
private verifyMediaRendererPlayer() {
def devices = getMediaRendererPlayer().findAll { it?.value?.verified != true }
devices.each {
verifyMediaRenderer((it?.value?.ip + ":" + it?.value?.port), it?.value?.ssdpPath)
}
}
private verifyMediaRenderer(String deviceNetworkId, String ssdpPath) {
String ip = getHostAddress(deviceNetworkId)
if(!ssdpPath){
ssdpPath = "/"
}
log.trace "verifyMediaRenderer($deviceNetworkId, $ssdpPath, $ip)"
sendHubCommand(new physicalgraph.device.HubAction("""GET $ssdpPath HTTP/1.1\r\nHOST: $ip\r\n\r\n""", physicalgraph.device.Protocol.LAN, "${deviceNetworkId}"))
}
Map mediaRenderersDiscovered() {
def vmediaRenderers = getVerifiedMediaRendererPlayer()
def map = [:]
vmediaRenderers.each {
def value = "${it.value.name}"
def key = it.value.ip + ":" + it.value.port + ":" + getUUID(it.value.ssdpUSN)
map["${key}"] = value
}
map
}
def getMediaRendererPlayer()
{
state.mediaRenderers = state.mediaRenderers ?: [:]
}
def getVerifiedMediaRendererPlayer()
{
getMediaRendererPlayer().findAll{ it?.value?.verified == true }
}
def installed() {
log.trace "installed()"
//initialize()
}
def updated() {
log.trace "updated()"
if (selectedMediaRenderer) {
addMediaRenderer()
}
unsubscribe()
state.subscribe = false
unschedule()
scheduleTimer()
scheduleActions()
refreshAll()
syncDevices()
}
def uninstalled() {
def devices = getChildDevices()
devices.each {
deleteChildDevice(it.deviceNetworkId)
}
}
def initialize() {
// remove location subscription aftwards
log.trace "initialize()"
//scheduledRefreshHandler()
}
def scheduledRefreshHandler(){
}
def scheduledTimerHandler() {
timerAll()
}
def scheduledActionsHandler() {
syncDevices()
//runIn(60, scheduledRefreshHandler)
}
private scheduleTimer() {
def cron = "0 0/3 * * * ?"
schedule(cron, scheduledTimerHandler)
}
private scheduleActions() {
def minutes = Math.max(settings.refreshMRInterval.toInteger(),1)
def cron = "0 0/${minutes} * * * ?"
schedule(cron, scheduledActionsHandler)
}
private syncDevices() {
log.debug "syncDevices()"
if(!state.subscribe) {
subscribe(location, null, locationHandler, [filterEvents:false])
log.trace "subscribe($location, null, locationHandler, [filterEvents:false])"
state.subscribe = true
}
discoverMediaRenderers()
}
private timerAll(){
childDevices*.poll()
}
private refreshAll(){
childDevices*.refresh()
}
def addMediaRenderer() {
def players = getVerifiedMediaRendererPlayer()
def runSubscribe = false
selectedMediaRenderer.each { dni ->
def d = getChildDevice(dni)
if(!d) {
def newPlayer = players.find { (it.value.ip + ":" + it.value.port + ":" + getUUID(it.value.ssdpUSN) ) == dni }
if (newPlayer){
d = addChildDevice("mujica", "DLNA Player", dni, newPlayer?.value.hub, [label:"${newPlayer?.value.name} Speaker","data":["model":newPlayer?.value.model,"avtcurl":newPlayer?.value.avtcurl,"avteurl":newPlayer?.value.avteurl,"rccurl":newPlayer?.value.rccurl,"rceurl":newPlayer?.value.rceurl,"udn":newPlayer?.value.udn,"dni":dni]])
}
runSubscribe = true
}
}
}
def locationHandler(evt) {
def description = evt.description
def hub = evt?.hubId
def parsedEvent = parseEventMessage(description)
def msg = parseLanMessage(description)
if (msg?.headers?.sid)
{
childDevices*.each { childDevice ->
if(childDevice.getDataValue('subscriptionId') == ((msg?.headers?.sid ?:"") - "uuid:")|| childDevice.getDataValue('subscriptionId1') == ((msg?.headers?.sid ?:"") - "uuid:")){
childDevice.parse(description)
}
}
}
parsedEvent << ["hub":hub]
if (parsedEvent?.ssdpTerm?.contains("urn:schemas-upnp-org:device:MediaRenderer:1"))
{ //SSDP DISCOVERY EVENTS
log.debug "MediaRenderer device found" + parsedEvent
def mediaRenderers = getMediaRendererPlayer()
if (!(mediaRenderers."${parsedEvent.ssdpUSN.toString()}"))
{ //mediaRenderer does not exist
mediaRenderers << ["${parsedEvent.ssdpUSN.toString()}":parsedEvent]
}
else
{ // update the values
def d = mediaRenderers."${parsedEvent.ssdpUSN.toString()}"
boolean deviceChangedValues = false
if(d.ip != parsedEvent.ip || d.port != parsedEvent.port) {
d.ip = parsedEvent.ip
d.port = parsedEvent.port
deviceChangedValues = true
}
if (deviceChangedValues) {
def children = getChildDevices()
children.each {
if (parsedEvent.ssdpUSN.toString().contains(it.getDataValue("udn"))) {
it.setDeviceNetworkId((parsedEvent.ip + ":" + parsedEvent.port + ":" + getUUID(parsedEvent.ssdpUSN.toString()))) //could error if device with same dni already exists
it.updateDataValue("dni", (parsedEvent.ip + ":" + parsedEvent.port + ":" + getUUID(parsedEvent.ssdpUSN.toString())))
it.refresh()
log.trace "Updated Device IP"
}
}
}
}
}
else if (parsedEvent.headers && parsedEvent.body)
{ // MEDIARENDER RESPONSES
def headerString = new String(parsedEvent?.headers?.decodeBase64())
def bodyString = new String(parsedEvent.body.decodeBase64())
def type = (headerString =~ /Content-Type:.*/) ? (headerString =~ /Content-Type:.*/)[0] : null
def body
def device
if (bodyString?.contains("xml"))
{ // description.xml response (application/xml)
body = new XmlSlurper().parseText(bodyString)
// Avoid add sonos devices
device = body?.device
body?.device?.deviceList?.device?.each{
if (it?.deviceType?.text().contains("urn:schemas-upnp-org:device:MediaRenderer:1")) {
device = it
}
}
if ( device?.deviceType?.text().contains("urn:schemas-upnp-org:device:MediaRenderer:1"))
{
def avtcurl = ""
def avteurl = ""
def rccurl = ""
def rceurl = ""
device?.serviceList?.service?.each{
if (it?.serviceType?.text().contains("AVTransport")) {
avtcurl = it?.controlURL?.text().startsWith("/")? it?.controlURL.text() : "/" + it?.controlURL.text()
avteurl = it?.eventSubURL?.text().startsWith("/")? it?.eventSubURL.text() : "/" + it?.eventSubURL.text()
}
else if (it?.serviceType?.text().contains("RenderingControl")) {
rccurl = it?.controlURL?.text().startsWith("/")? it?.controlURL?.text() : "/" + it?.controlURL?.text()
rceurl = it?.eventSubURL?.text().startsWith("/")? it?.eventSubURL?.text() : "/" + it?.eventSubURL?.text()
}
}
def mediaRenderers = getMediaRendererPlayer()
def player = mediaRenderers.find {it?.key?.contains(device?.UDN?.text())}
if (player)
{
player.value << [name:device?.friendlyName?.text(),model:device?.modelName?.text(), serialNumber:device?.UDN?.text(), verified: true,avtcurl:avtcurl,avteurl:avteurl,rccurl:rccurl,rceurl:rceurl,udn:device?.UDN?.text()]
}
}
}
else if(type?.contains("json"))
{ //(application/json)
body = new groovy.json.JsonSlurper().parseText(bodyString)
}
}
}
private def parseEventMessage(Map event) {
//handles mediaRenderer attribute events
return event
}
private def parseEventMessage(String description) {
def event = [:]
def parts = description.split(',')
parts.each { part ->
part = part.trim()
if (part.startsWith('devicetype:')) {
def valueString = part.split(":")[1].trim()
event.devicetype = valueString
}
else if (part.startsWith('mac:')) {
def valueString = part.split(":")[1].trim()
if (valueString) {
event.mac = valueString
}
}
else if (part.startsWith('networkAddress:')) {
def valueString = part.split(":")[1].trim()
if (valueString) {
event.ip = valueString
}
}
else if (part.startsWith('deviceAddress:')) {
def valueString = part.split(":")[1].trim()
if (valueString) {
event.port = valueString
}
}
else if (part.startsWith('ssdpPath:')) {
def valueString = part.split(":")[1].trim()
if (valueString) {
event.ssdpPath = valueString
}
}
else if (part.startsWith('ssdpUSN:')) {
part -= "ssdpUSN:"
def valueString = part.trim()
if (valueString) {
event.ssdpUSN = valueString
}
}
else if (part.startsWith('ssdpTerm:')) {
part -= "ssdpTerm:"
def valueString = part.trim()
if (valueString) {
event.ssdpTerm = valueString
}
}
else if (part.startsWith('headers')) {
part -= "headers:"
def valueString = part.trim()
if (valueString) {
event.headers = valueString
}
}
else if (part.startsWith('body')) {
part -= "body:"
def valueString = part.trim()
if (valueString) {
event.body = valueString
}
}
}
if (event.devicetype == "04" && event.ssdpPath =~ /[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}/ && !event.ssdpUSN && !event.ssdpTerm){
def matcher = event.ssdpPath =~ /[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}/
def ssdpUSN = matcher[0]
event.ssdpUSN = "uuid:$ssdpUSN::urn:schemas-upnp-org:device:MediaRenderer:1"
event.ssdpTerm = "urn:schemas-upnp-org:device:MediaRenderer:1"
}
event
}
/////////CHILD DEVICE METHODS
def parse(childDevice, description) {
def parsedEvent = parseEventMessage(description)
if (parsedEvent.headers && parsedEvent.body) {
def headerString = new String(parsedEvent.headers.decodeBase64())
def bodyString = new String(parsedEvent.body.decodeBase64())
def body = new groovy.json.JsonSlurper().parseText(bodyString)
} else {
return []
}
}
private Integer convertHexToInt(hex) {
Integer.parseInt(hex,16)
}
private String convertHexToIP(hex) {
[convertHexToInt(hex[0..1]),convertHexToInt(hex[2..3]),convertHexToInt(hex[4..5]),convertHexToInt(hex[6..7])].join(".")
}
private getHostAddress(d) {
def parts = d.split(":")
def ip = convertHexToIP(parts[0])
def port = convertHexToInt(parts[1])
return ip + ":" + port
}
private getUUID(d) {
if (d =~ /[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}/ ){
def matcher = d =~ /[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}/
matcher[0]
}else{
"ffffffff-fffffffff-ffff-ffffffffffff"
}
}
private Boolean canInstallLabs()
{
return hasAllHubsOver("000.011.00603")
}
private Boolean hasAllHubsOver(String desiredFirmware)
{
return realHubFirmwareVersions.every { fw -> fw >= desiredFirmware }
}
private List getRealHubFirmwareVersions()
{
return location.hubs*.firmwareVersionString.findAll { it }
}