1 package example.binarylight;
2
3 import org.fourthline.cling.UpnpService;
4 import org.fourthline.cling.UpnpServiceImpl;
5 import org.fourthline.cling.controlpoint.*;
6 import org.fourthline.cling.model.action.*;
7 import org.fourthline.cling.model.message.*;
8 import org.fourthline.cling.model.message.header.*;
9 import org.fourthline.cling.model.meta.*;
10 import org.fourthline.cling.model.types.*;
11 import org.fourthline.cling.registry.*;
12
13 public class BinaryLightClient implements Runnable {
14
15 public static void main(String[] args) throws Exception {
16
17 Thread clientThread = new Thread(new BinaryLightClient());
18 clientThread.setDaemon(false);
19 clientThread.start();
20
21 }
22
23 public void run() {
24 try {
25
26 UpnpService upnpService = new UpnpServiceImpl();
27
28
29 upnpService.getRegistry().addListener(
30 createRegistryListener(upnpService)
31 );
32
33
34 upnpService.getControlPoint().search(
35 new STAllHeader()
36 );
37
38 } catch (Exception ex) {
39 System.err.println("Exception occured: " + ex);
40 System.exit(1);
41 }
42 }
43
44
45 RegistryListener createRegistryListener(final UpnpService upnpService) {
46 return new DefaultRegistryListener() {
47
48 ServiceId serviceId = new UDAServiceId("SwitchPower");
49
50 @Override
51 public void remoteDeviceAdded(Registry registry, RemoteDevice device) {
52
53 Service switchPower;
54 if ((switchPower = device.findService(serviceId)) != null) {
55
56 System.out.println("Service discovered: " + switchPower);
57 executeAction(upnpService, switchPower);
58
59 }
60
61 }
62
63 @Override
64 public void remoteDeviceRemoved(Registry registry, RemoteDevice device) {
65 Service switchPower;
66 if ((switchPower = device.findService(serviceId)) != null) {
67 System.out.println("Service disappeared: " + switchPower);
68 }
69 }
70
71 };
72 }
73
74
75 void executeAction(UpnpService upnpService, Service switchPowerService) {
76
77 ActionInvocation setTargetInvocation =
78 new SetTargetActionInvocation(switchPowerService);
79
80
81 upnpService.getControlPoint().execute(
82 new ActionCallback(setTargetInvocation) {
83
84 @Override
85 public void success(ActionInvocation invocation) {
86 assert invocation.getOutput().length == 0;
87 System.out.println("Successfully called action!");
88 }
89
90 @Override
91 public void failure(ActionInvocation invocation,
92 UpnpResponse operation,
93 String defaultMsg) {
94 System.err.println(defaultMsg);
95 }
96 }
97 );
98
99 }
100
101 class SetTargetActionInvocation extends ActionInvocation {
102
103 SetTargetActionInvocation(Service service) {
104 super(service.getAction("SetTarget"));
105 try {
106
107
108 setInput("NewTargetValue", true);
109
110 } catch (InvalidValueException ex) {
111 System.err.println(ex.getMessage());
112 System.exit(1);
113 }
114 }
115 }
116
117 }