# Cling Core

## User Manual

### Authors:

Christian Bauer

### Table Of Contents:

1. A first UPnP service and control point

The most basic UPnP service imaginable is the binary light. This device has one service, the power switch, turning the light on and off. In fact, the SwitchPower:1 service and the BinaryLight:1 device are standardized templates you can download here.

In the following sections we'll implement this UPnP service and device with the Cling Core library as a simple Java console application.

1.1. The SwitchPower service implementation

This is the source of the SwitchPower:1 service - note that although there are many annotations in the source, no runtime dependency on Cling exists:

    package example.binarylight;

    import org.teleal.cling.binding.annotations.*;

    @UpnpService(
            serviceId = @UpnpServiceId("SwitchPower"),
            serviceType = @UpnpServiceType(value = "SwitchPower", version = 1)
    )
    public class SwitchPower {

        @UpnpStateVariable(defaultValue = "0", sendEvents = false)
        private boolean target = false;

        @UpnpStateVariable(defaultValue = "0")
        private boolean status = false;

        @UpnpAction
        public void setTarget(@UpnpInputArgument(name = "NewTargetValue") boolean newTargetValue) {
            target = newTargetValue;
            status = newTargetValue;
            System.out.println("Switch is: " + status);
        }

        @UpnpAction(out = @UpnpOutputArgument(name = "RetTargetValue"))
        public boolean getTarget() {
            return target;
        }

        @UpnpAction(out = @UpnpOutputArgument(name = "ResultStatus"))
        public boolean getStatus() {
            return status;
        }

    }

To compile this class the Cling Core library has to be available on your classpath. However, once compiled this class can be instantiated and executed in any environment, there are no dependencies on any framework or library code.

The annotations are used by Cling to read the metadata that describes your service, what UPnP state variables it has, how they are accessed, and what methods should be exposed as UPnP actions. You can also provide Cling metadata in an XML file or programmatically through Java code - both options are discussed later in this manual. Source code annotations are usually the best choice.

You might have expected something even simpler: After all, a binary light only needs a single boolean state, it is either on or off. The designers of this service also considered that there might be a difference between switching the light on, and actually seeing the result of that action. Imagine what happens if the light bulb is broken: The target state of the light is set to true but the status is still false, because the SetTarget action could not make the switch. Obviously this won't be a problem with this simple demonstration because it only prints the status to standard console output.

1.2. Binding a UPnP device

Devices (and embedded devices) are created programmatically in Cling, with plain Java code that instantiates an immutable graph of objects. The following method creates such a device graph and binds the service from the previous section to the root device:

    LocalDevice createDevice()
            throws ValidationException, LocalServiceBindingException, IOException {

        DeviceIdentity identity =
                new DeviceIdentity(
                        UDN.uniqueSystemIdentifier("Demo Binary Light")
                );

        DeviceType type =
                new UDADeviceType("BinaryLight", 1);

        DeviceDetails details =
                new DeviceDetails(
                        "Friendly Binary Light",
                        new ManufacturerDetails("ACME"),
                        new ModelDetails("BinLight2000", "A demo light with on/off switch.", "v1")
                );

        Icon icon =
                new Icon(
                        "image/png", 48, 48, 8,
                        getClass().getResource("icon.png")
                );

        DeviceService<LocalService> deviceService =
                new AnnotationLocalServiceBinder().read(SwitchPower.class);

        deviceService.getService().setManager(
                new DefaultServiceManager(deviceService.getService(), SwitchPower.class)
        );

        return new LocalDevice(
                identity,
                type,
                details,
                new Icon[]{icon}, // Or 'null' for no icons
                new DeviceService[]{deviceService}
        );
    }

Let's step through this code. As you can see, all arguments that make up the device's metadata have to be provided through constructors, because the metadata classes are immutable and hence thread-safe.

DeviceIdentity

  Every device, no matter if it is a root device or an embedded device of a root device, requires a unique device name (UDN). This UDN should be stable, that is, it should not change when the device is restarted. When you physically unplug a UPnP appliance from the network (or when you simply turn it off or put it into standby mode), and when you make it available later on, it should expose the same UDN so that clients know they are dealing with the same device. The `UDN.uniqueSystemIdentifier()` method provides exactly that: A unique identifier that is the same every time this method is called on the same computer system. It hashes the network cards hardware address and a few other elements to guarantee uniqueness and stability.

DeviceType

  The type of a device also includes its version, a plain integer. In this case the BinaryLight:1 is a standardized device template which adheres to the UDA (UPnP Device Architecture) specification.

DeviceDetails

  This detailed information about the device's "friendly name", as well as model and manufacturer information is optional. You should at least provide a friendly name value, this is what UPnP applications will display primarily.

Icon

  Every device can have a bunch of icons associated with it which similar to the friendly name are shown to users when appropriate. You do not have to provide any icons if you don't want to, in that case just create an empty `Icon[]` or use `null` instead.

DeviceService

  Finally, the most important part of the device are its services. Each `DeviceService` encapsulates a particular `Service`. Here we use the Cling annotation binder to instantiate a `DeviceService`, reading the annotation metadata of the `SwitchPower` class.

A `Service` instance is only metadata that describes the service, to actually do some work you have to set a `ServiceManager`. The `DefaultServiceManager` will instantiate the given `SwitchPower` class when an action which operates on the service has to be executed (this happens lazily, as late as possible). The manager will hold on to the instance and always re-use it as long as the service is registered with the UPnP stack. In other words, the service manager is the factory that instantiates your actual implementation of a UPnP service.

Also note that `LocalDevice` is the interface that represents a UPnP device which is "local" to the running UPnP stack on the host. Any device that has been discovered through the network will be a `RemoteDevice`, you typically do not instantiate these directly.

A `ValidationException` will be thrown when the device graph you instantiated was invaild, you can call `getErrors()` on the exception to find out which property value of which class failed an integrity rule. The local service annotation binder will provide a `LocalServiceBindingException` if something is wrong with your annotation metadata on your service implementation class. An `IOException` can only by thrown by this particular `Icon` constructor, when it reads the resource file.

1.3. Running the server

The Cling Core main API entry point is a thread-safe and typically single shared instance of `UpnpService`:

    package example.binarylight;

    import org.teleal.cling.UpnpService;
    import org.teleal.cling.UpnpServiceImpl;
    import org.teleal.cling.binding.*;
    import org.teleal.cling.binding.annotations.*;
    import org.teleal.cling.model.*;
    import org.teleal.cling.model.meta.*;
    import org.teleal.cling.model.types.*;

    import java.io.IOException;

    public class BinaryLightServer implements Runnable {

        public static void main(String[] args) throws Exception {
            // Start a user thread that runs the UPnP stack until the application quits
            Thread serverThread = new Thread(new BinaryLightServer());
            serverThread.setDaemon(false);
            serverThread.start();
        }

        public void run() {
            try {

                final UpnpService upnpService = new UpnpServiceImpl();

                Runtime.getRuntime().addShutdownHook(new Thread() {
                    @Override
                    public void run() {
                        upnpService.shutdown();
                    }
                });

                // Add the bound local device to the registry
                upnpService.getRegistry().addDevice(
                        createDevice()
                );

            } catch (Exception ex) {
                System.err.println("Exception occured: " + ex);
                ex.printStackTrace(System.err);
                System.exit(1);
            }
        }

    }

(The `createDevice()` method from the previous section should be added to this class.)

As soon as the `UPnPServiceImpl` is created, the stack is up and running. You always have to create a `UPnPService` instance, no matter if you write a client or a server. The `UpnpService` maintains a registry of all the discovered remote device on the network, and all the bound local devices. It manages advertisements for discovery and event handling in the background.

You should shut down the UPnP service properly when your application quits, so that all other UPnP systems on your network will be notified that bound devices which are local to your application are no longer available. If you do not shut down the `UpnpService` when your application quits, other UPnP control points on your network might still show devices as available when they are in fact already gone.

The `createDevice()` method from the previous section is called here, as soon as the `Registry` of the local UPnP service stack is available.

You can now compile and start this server, it should print some informational messages to your console and then wait for connections from UPnP control points. It will listen for TCP requests on port 8081. Use the Cling Workbench if you want to test your server immediately.

1.4. Creating a control point

The client application has the same basic scaffolding as the server, it also uses a shared single instance of `UpnpService`:

    package example.binarylight;

    import org.teleal.cling.DefaultUpnpServiceConfiguration;
    import org.teleal.cling.UpnpService;
    import org.teleal.cling.UpnpServiceImpl;
    import org.teleal.cling.controlpoint.*;
    import org.teleal.cling.model.action.*;
    import org.teleal.cling.model.message.*;
    import org.teleal.cling.model.message.header.*;
    import org.teleal.cling.model.meta.*;
    import org.teleal.cling.model.types.*;
    import org.teleal.cling.registry.*;

    public class BinaryLightClient implements Runnable {

        public static void main(String[] args) throws Exception {
            // Start a user thread that runs the UPnP stack until the application quits
            Thread clientThread = new Thread(new BinaryLightClient());
            clientThread.setDaemon(false);
            clientThread.start();

        }

        public void run() {
            try {

                UpnpService upnpService = new UpnpServiceImpl(
                        new DefaultUpnpServiceConfiguration(8082)
                );

                // Add a listener for device registration events
                upnpService.getRegistry().addListener(
                        createRegistryListener(upnpService)
                );

                // Broadcast a search message for all devices
                upnpService.getControlPoint().search(
                        new STAllHeader()
                );

            } catch (Exception ex) {
                System.err.println("Exception occured: " + ex);
                System.exit(1);
            }
        }

    }

Typically a control point sleeps until a device with a specific type of service becomes available on the network. The `RegistryListener` is called by Cling when a remote device has been discovered - or when it announced itself automatically. Because you usually do not want to wait for the periodic announcements of devices, a control point can also execute a search for all devices (or devices with certain service types or UDN), which will trigger an immediate discovery announcement from those devices that match the search query.

You can already see the `ControlPoint` API here with its `search(...)` method, this is one of the main interfaces you interact with when writing a UPnP client with Cling.

If you compare this code with the server code from the previous section you can see that we are not shutting down the `UpnpService` when the application quits. This is not an issue here, because this application does not have any local devices or service event listeners (not the same as registry listeners) bound and registered. Hence, we do not have to announce their departure on application shutdown and can keep the code simple for the sake of the example.

We override the default UPnP service configuration with network port `8082`, the default being `8081`. This is a required if you start the `BinaryLightServer` and this `BinaryLightClient` on the same host, when testing this example. If you are going to deploy the client and the server on two different machines (or virtual machines), you wouldn't have to override the network port.

Let's focus on the registry listener implementation and what happens when a UPnP device has been discovered on the network.

1.5. Executing an action

The control point we are creating here is only interested in services that implement SwitchPower. According to its template definition this service has the `SwitchPower` service identifier, so when a device has been discovered we can check if it offers that service:

    RegistryListener createRegistryListener(final UpnpService upnpService) {
        return new DefaultRegistryListener() {

            ServiceId serviceId = new UDAServiceId("SwitchPower");

            @Override
            public void remoteDeviceAdded(Registry registry, RemoteDevice device) {

                DeviceService switchPower;
                if ((switchPower = device.getDeviceService(serviceId)) != null) {

                    System.out.println("Service discovered: " + switchPower);
                    executeAction(upnpService, switchPower.getService());

                }

            }

            @Override
            public void remoteDeviceRemoved(Registry registry, RemoteDevice device) {
                DeviceService switchPower;
                if ((switchPower = device.getDeviceService(serviceId)) != null) {
                    System.out.println("Service disappeared: " + switchPower);
                }
            }

        };
    }

If a service becomes available we immediately execute an action on that service. When a `SwitchPower` device disappears from the network a log message is printed. Remember that this is a very trivial control point, it executes a single a fire-and-forget operation when a service becomes available:

    void executeAction(UpnpService upnpService, Service switchPowerService) {

            ActionInvocation setTargetInvocation =
                    new SetTargetActionInvocation(switchPowerService);

            // Executes asynchronous in the background
            upnpService.getControlPoint().execute(
                    new ActionCallback(setTargetInvocation) {

                        @Override
                        public void success(ActionInvocation actionInvocation) {
                            assert actionInvocation.getOutput().getValues().length == 0;
                            System.out.println("Successfully called action!");
                        }

                        @Override
                        public void failure(ActionInvocation actionInvocation, UpnpResponse operation) {
                            System.err.println(createDefaultFailureMessage(actionInvocation, operation));
                        }
                    }
            );

    }

    class SetTargetActionInvocation extends ActionInvocation {

        SetTargetActionInvocation(Service service) {
            super(service.getAction("SetTarget"));
            try {

                // This might throw an ActionException if the value is of wrong type
                getInput().addValue(true);

            } catch (ActionException ex) {
                System.err.println(ex.getMessage());
            }
        }
    }

The `Action` (metadata) and the `ActionInvocation` (actual call data) APIs allow very fine-grained control of how an invocation is prepared, how input values are set, how the action is executed, and how the output and outcome is handled. UPnP is inherently asynchronous, so just like the registry listener, executing an action is exposed to you as a callback-style API.

It is recommended that you encapsulate specific action invocations within a subclass of `ActionInvocation`, which gives you an opportunity to further abstract the input and output values of an invocation. Note however that an instance of `ActionInvocation` is not thread-safe and should not be executed in parallel by two threads.

The `ActionCallback` has two main methods you have to implement, one is called when the execution was successful, the other when it failed. There are many reasons why an action execution might fail, read the API documentation for all possible combinations. The `createDefaultFailureMessage()` method is a convenient way to create a user-friendly error message quickly.

1.6. Starting the application

Compile the binary light demo application:

Don't forget to copy your `icon.png` file into the `classes` output directory as well, into the right package from which it is loaded as a reasource (the `example.binarylight` package if you followed the previous sections verbatim).

You can start the server or client first, which one doesn't matter as they will discover each other automatically:

You should see discovery and action executiom messages on each console. You can stop and restart the applications individually (press CTRL+C on the console).