forked from Phylock/sonos-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.gradle
More file actions
331 lines (299 loc) · 11.7 KB
/
build.gradle
File metadata and controls
331 lines (299 loc) · 11.7 KB
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
import com.google.common.base.CaseFormat
import groovy.io.FileType
apply plugin: 'java'
apply plugin: 'maven'
archivesBaseName = "sonos-api"
group = 'org.rattigan.sonos'
version = '1.5'
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.google.guava:guava:17.+'
}
}
repositories {
mavenCentral()
//mavenLocal()
// cling
maven { url "http://4thline.org/m2" }
maven { url "http://repo.maven.apache.org/maven2" }
}
dependencies {
compile group: 'com.google.guava', name: 'guava', version: '13.0.1'
compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.1'
compile(group: 'org.simpleframework', name: 'simple-xml', version: '2.7') {
exclude(module: 'stax-api')
exclude(module: 'stax')
}
compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.2'
compile group: 'joda-time', name: 'joda-time', version: '2.1'
compile(group: 'org.fourthline.cling', name: 'cling-core', version: '2.0.1') {
exclude(module: 'tools')
}
testCompile group: 'ch.qos.logback', name: 'logback-classic', version: '1.0.9'
testCompile group: 'junit', name: 'junit', version: '4.11'
}
task generateServiceWrappers {
generateServiceWrappers()
}
void generateServiceWrappers() {
def services = [:]
def serviceDescriptors = []
new File(projectDir, 'descriptors').eachFileRecurse(FileType.FILES) { file ->
if (!file.name == 'device_description.xml')
return;
def xml = new XmlSlurper().parseText(file.text)
def serviceXmls = xml.depthFirst().findAll{it.name() == 'serviceList'}*.service
serviceXmls.each{ serviceList ->
serviceList.each {
serviceDescriptors << [filename: it.SCPDURL, id: it.serviceId]
}
}
}
serviceDescriptors.each { descriptor ->
String filename = descriptor.filename
String id = descriptor.id
def file = new File(new File(projectDir, 'descriptors'), filename);
if (!file.name.endsWith('xml'))
return;
def service = [id: id]
def serviceName = id.substring(id.lastIndexOf(':') + 1)
services[serviceName] = service
service.name = serviceName
def xml = new XmlSlurper().parseText(file.text)
def vars = [:]
service.vars = vars
xml.serviceStateTable.stateVariable.each { varXml ->
def var = [:]
def stateName = varXml.name.text()
vars[stateName] = var
var.name = stateName
var.argType = stateName.startsWith('A_ARG_TYPE_')
var.events = varXml.@sendEvents == 'yes'
if (varXml.allowedValueList.size()) {
def allowed = varXml.allowedValueList.allowedValue*.text()
if (!allowed.equals(["1"]))
var.enumValues = allowed
}
var.type = varXml.dataType.text()
}
def actions = []
service.actions = actions
xml.actionList.action.each { actionXml ->
def action = [:]
def name = actionXml.name.text()
actions << action
action.name = name
def args = []
actionXml.argumentList.argument.each { argXml ->
def arg = [:]
def argName = argXml.name.text()
args << arg
arg.name = argName
arg.in = argXml.direction.text() == 'in'
arg.var = vars[argXml.relatedStateVariable.text()]
assert arg.var
}
action.in = args.findAll{it.in}
action.out = args.findAll{!it.in}
}
}
services.each { name, service ->
File output = new File(projectDir, "src/main/java/org/tensin/sonos/gen/${name}.java")
def enumTexts = []
def requestTexts = []
def responseTexts = []
def actionTexts = []
for (entry in service.vars) {
def var = entry.value
if (!var.enumValues)
continue;
assert var.type == 'string'
// prefix numeric constants with _
def enumValues = var.enumValues.collect{it ==~ /[0-9].*/ ? '_'+it : it}
// flag for later use
var.numeric = enumValues != var.enumValues
def enumName = getJavaType(var)
def enumText = """
public enum $enumName {${enumValues.join(', ')}}
"""
enumTexts << enumText
}
for (action in service.actions) {
String actionName = action.name
String actionRequestClassName = action.name + 'Request'
String actionResponseClassName = action.name + 'Response'
if (!action.out)
actionResponseClassName = 'void'
String actionMethodName = fixAcronyms(CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, action.name))
String parameterList = []
def actionText = """
public $actionRequestClassName $actionMethodName(${parameterList.join(',')}) {
return new $actionRequestClassName();
}
"""
actionTexts << actionText
def requestFields = []
def requestSetters = []
def setInputParameters = []
for (arg in action.in) {
def javaType = getJavaType(arg.var)
def javaParamName = fixAcronyms(CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, arg.name))
def requestField = """
private $javaType $javaParamName;
"""
requestFields << requestField
def requestSetter = """
public $actionRequestClassName $javaParamName($javaType $javaParamName) {
this.$javaParamName = $javaParamName;
return this;
}
"""
requestSetters << requestSetter
def wrapExpression = getWrapExpression(arg.var, "this.$javaParamName")
def setInputParameter = """
invocation.setInput("$arg.name", $wrapExpression);
"""
setInputParameters << setInputParameter
}
def responseFields = []
def responseGetters = []
def getOutputParameters = []
for (arg in action.out) {
def javaType = getJavaType(arg.var)
def javaParamName = fixAcronyms(CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, arg.name))
def responseField = """
private $javaType $javaParamName;
"""
responseFields << responseField;
def responseGetter = """
public $javaType $javaParamName() {
return $javaParamName;
}
"""
responseGetters << responseGetter
def getOutputParameter = """
response.$javaParamName = ServiceHelper._$arg.var.type(invocation, "$arg.name");
"""
if (arg.var.enumValues) {
getOutputParameter = """
response.$javaParamName = ServiceHelper._$arg.var.type(invocation, "$arg.name", ${javaType}.class);
"""
}
getOutputParameters << getOutputParameter
}
def returnValue = """
$actionResponseClassName response = new $actionResponseClassName();
${getOutputParameters.join()}
return response;
"""
if (!action.out)
returnValue = ''
def requestText = """
public class $actionRequestClassName {
${requestFields.join()}
${requestSetters.join()}
public $actionResponseClassName execute() {
Action action = service.getAction("$actionName");
ActionInvocation invocation = new ActionInvocation(action);
${setInputParameters.join()}
new ActionCallback.Default(invocation, upnpService.getControlPoint()).run();
if (invocation.getFailure() != null)
throw new SonosException("" + invocation.getFailure().getErrorCode(), invocation.getFailure());
$returnValue
}
}
"""
requestTexts << requestText
def responseText = """
public class $actionResponseClassName {
${responseFields.join()}
${responseGetters.join()}
}
"""
if (action.out)
responseTexts << responseText
}
String serviceId = service.id
String text = """package org.tensin.sonos.gen;
import org.fourthline.cling.model.meta.Service;
import org.fourthline.cling.model.meta.Action;
import org.fourthline.cling.model.action.ActionInvocation;
import org.fourthline.cling.controlpoint.ActionCallback;
import org.fourthline.cling.UpnpService;
import org.fourthline.cling.model.meta.RemoteDevice;
import org.tensin.sonos.helpers.RemoteDeviceHelper;
import org.tensin.sonos.helpers.ServiceHelper;
import org.fourthline.cling.model.types.UnsignedIntegerFourBytes;
import org.fourthline.cling.model.types.UnsignedIntegerTwoBytes;
import org.tensin.sonos.SonosException;
public class $name {
private Service service;
private UpnpService upnpService;
public $name(UpnpService upnpService, RemoteDevice device) {
this.upnpService = upnpService;
this.service = RemoteDeviceHelper.findService(device, "$serviceId");
}
${enumTexts.join()}
${actionTexts.join()}
${requestTexts.join()}
${responseTexts.join()}
}
"""
output.setText(text, 'UTF-8');
}
}
String getJavaType(Map var) {
if (var.enumValues)
return var.name.replace('A_ARG_TYPE_', '');
switch (var.type) {
case 'string': return 'String'
case 'i4': return 'int'
case 'ui4': return 'int'
case 'i2': return 'int'
case 'ui2': return 'int'
case 'boolean': return 'boolean'
default: throw new RuntimeException(var.type)
}
}
String getWrapExpression(Map var, String expression) {
switch (var.type) {
case 'string':
if (!var.enumValues)
return expression
// remove underscore prefix for numeric enums
if (var.numeric)
return "(${expression}).toString().substring(1)"
return expression
case 'i4': return expression
case 'ui4': return "new UnsignedIntegerFourBytes($expression)"
case 'i2': return expression
case 'ui2': return "new UnsignedIntegerTwoBytes($expression)"
case 'boolean': return expression
default: println "Unsupported type: $var.type"; throw new RuntimeException(var.type)
}
}
String getUnwrapExpression(Map arg) {
return
switch (arg.var.type) {
case 'string': return "getString(String)invocation.getOutput(\"$arg.name\").getValue()"
case 'i4': return "(Integer)invocation.getOutput(\"$arg.name\").getValue().getValue()"
case 'ui4': return "(Integer)invocation.getOutput(\"$arg.name\").getValue().getValue()"
case 'i2': return "(Integer)invocation.getOutput(\"$arg.name\").getValue().getValue()"
case 'ui2': return "(Integer)invocation.getOutput(\"$arg.name\").getValue().getValue()"
case 'boolean': "(Boolean)invocation.getOutput(\"$arg.name\").getValue()"
default: println "Unsupported type: $var.type"; throw new RuntimeException(var.type)
}
}
String getCastType(String javaType) {
switch (javaType) {
case 'int': return 'Integer'
case 'boolean': return 'Boolean'
default: return javaType
}
}
String fixAcronyms(String str) {
str.replaceAll('(\\p{Upper}+)((?=\\p{Upper}\\p{Lower})?)', '$1$2')
}