2 <!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" "http://www.oasis-open.org/docbook/xml/4.4/docbookx.dtd">
4 <chapter id="server-tutorial" xmlns:xi="http://www.w3.org/2001/XInclude">
5 <title>Writing a UPnP Service</title>
8 <title>Introduction</title>
10 This chapter explains how to implement a UPnP service using GUPnP. For
11 this example we will create a virtual UPnP-enabled light bulb.
14 Before any code can be written, the device and services that it implement
15 need to be described in XML. Although this can be frustrating, if you are
16 implementing a standardised service (see <ulink
17 url="http://upnp.org/standardizeddcps/"/> for the list of standard devices
18 and services) then the service description is already written for you and
19 the device description is trivial. UPnP has standardised <ulink
20 url="http://upnp.org/standardizeddcps/lighting.asp">Lighting
21 Controls</ulink>, so we'll be using the device and service types defined
27 <title>Defining the Device</title>
29 The first step is to write the <firstterm>device description</firstterm>
30 file. This is a short XML document which describes the device and what
31 services it provides (for more details see the <ulink
32 url="http://upnp.org/specs/arch/UPnP-DeviceArchitecture-v1.0.pdf">UPnP
33 Device Architecture</ulink> specification, section 2.1). We'll be using
34 the <literal>BinaryLight1</literal> device type, but if none of the
35 existing device types are suitable a custom device type can be created.
37 <programlisting><xi:include href="../../examples/BinaryLight1.xml" parse="text"/></programlisting>
39 The <sgmltag>specVersion</sgmltag> tag defines what version of the UPnP
40 Device Architecture the document conforms to. At the time of writing the
44 Next there is the root <sgmltag>device</sgmltag> tag. This contains
45 metadata about the device, lists the services it provides and any
46 sub-devices present (there are none in this example). The
47 <sgmltag>deviceType</sgmltag> tag specifies the type of the device.
50 Next we have <sgmltag>friendlyName</sgmltag>,
51 <sgmltag>manufacturer</sgmltag> and <sgmltag>modelName</sgmltag>. The
52 friendly name is a human-readable name for the device, the manufacturer
53 and model name are self-explanatory.
56 Next there is the UDN, or <firstterm>Unique Device Name</firstterm>. This
57 is an identifier which is unique for each device but persistent for each
58 particular device. Although it has to start with <literal>uuid:</literal>
59 note that it doesn't have to be an UUID. There are several alternatives
60 here: for example it could be computed at built-time if the software will
61 only be used on a single machine, or it could be calculated using the
62 device's serial number or MAC address.
65 Finally we have the <sgmltag>serviceList</sgmltag> which describes the
66 services this device provides. Each service has a service type (again
67 there are types defined for standardised services or you can create your
68 own), service identifier, and three URLs. As a service type we're using
69 the standard <literal>SwitchPower1</literal> service. The
70 <sgmltag>SCPDURL</sgmltag> field specifies where the <firstterm>Service
71 Control Protocol Document</firstterm> can be found, this describes the
72 service in more detail and will be covered next. Finally there are the
73 control and event URLs, which need to be unique on the device and will be
79 <title>Defining Services</title>
81 Becase we are using a standard service we can use the service description
82 from the specification. This is the <literal>SwitchPower1</literal>
83 service description file:
85 <programlisting><xi:include href="../../examples/SwitchPower1.xml" parse="text"/></programlisting>
87 Again, the <sgmltag>specVersion</sgmltag> tag defines the UPnP version
88 that is being used. The rest of the document consists of an
89 <sgmltag>actionList</sgmltag> defining the <glossterm
90 linkend="action">actions</glossterm> available and a
91 <sgmltag>serviceStateTable</sgmltag> defining the <glossterm
92 linkend="state-variable">state variables</glossterm>.
95 Every <sgmltag>action</sgmltag> has a <sgmltag>name</sgmltag> and a list
96 of <sgmltag>argument</sgmltag>s. Arguments also have a name, a direction
97 (<literal>in</literal> or <literal>out</literal> for input or output
98 arguments) and a related state variable. The state variable is used to
99 determine the type of the argument, and as such is a required element.
100 This can lead to the creation of otherwise unused state variables to
101 define the type for an argument (the <literal>WANIPConnection</literal>
102 service is a good example of this), thanks to the legacy behind UPnP.
105 <sgmltag>stateVariable</sgmltag>s need to specify their
106 <sgmltag>name</sgmltag> and <sgmltag>dataType</sgmltag>. State variables
107 by default send notifications when they change, to specify that a variable
108 doesn't do this set the <sgmltag>sendEvents</sgmltag> attribute to
109 <literal>no</literal>. Finally there are optional
110 <sgmltag>defaultValue</sgmltag>, <sgmltag>allowedValueList</sgmltag> and
111 <sgmltag>allowedValueRange</sgmltag> elements which specify what the
112 default and valid values for the variable.
115 For the full specification of the service definition file, including a
116 complete list of valid <sgmltag>dataType</sgmltag>s, see section 2.3 of
118 url="http://upnp.org/specs/arch/UPnP-DeviceArchitecture-v1.0.pdf">UPnP
119 Device Architecture</ulink>.
124 <title>Implementing the Device</title>
126 Before starting to implement the device, some boilerplate code is needed
127 to initialise GUPnP. GLib types and threading needs to be initialised,
128 and then a GUPnP context can be created using gupnp_context_new().
130 <programlisting>GUPnPContext *context;
131 /* Initialize required subsystems */
132 g_thread_init (NULL);
134 /* Create the GUPnP context with default host and port */
135 context = gupnp_context_new (NULL, NULL, 0, NULL);</programlisting>
137 UPnP uses HTTP to provide the device and service description files, so
138 next we tell GUPnP to publish them. This is done with
139 gupnp_context_host_path() which takes a local filename to send when a
140 certain server path is requested.
142 <programlisting>gupnp_context_host_path (context, "BinaryLight1.xml", "/BinaryLight1.xml");
143 gupnp_context_host_path (context, "SwitchPower1.xml", "/SwitchPower1.xml");</programlisting>
145 Next the root device can be created.
147 <programlisting>GUPnPRootDevice *dev;
148 /* Create the root device object */
149 dev = gupnp_root_device_new (context, "/BinaryLight1.xml");
150 /* Activate the root device, so that it announces itself */
151 gupnp_root_device_set_available (dev, TRUE);</programlisting>
153 GUPnP scans the device description and any service description files it
154 refers to, so if the main loop was entered now the device and service
155 would be available on the network, albeit with no functionality. The
156 remaining task is to implement the services.
161 <title>Implementing a Service</title>
163 To implement a service we first fetch the #GUPnPService from the root
164 device using gupnp_device_info_get_service() (#GUPnPRootDevice is a
165 subclass of #GUPnPDevice, which implements #GUPnPDeviceInfo). This
166 returns a #GUPnPServiceInfo which again is an interface, implemented by
167 #GUPnPService (on the server) and #GUPnPServiceProxy (on the client).
169 <programlisting>GUPnPServiceInfo *service;
170 service = gupnp_device_info_get_service
171 (GUPNP_DEVICE_INFO (dev), "urn:schemas-upnp-org:service:SwitchPower:1");</programlisting>
173 #GUPnPService handles interacting with the network itself, leaving the
174 implementation of the service itself to signal handlers that we need to
175 connect. There are two signals: #GUPnPService::action-invoked and
176 #GUPnPService::query-variable. #GUPnPService::action-invoked is emitted
177 when a client invokes an action: the handler is passed a
178 #GUPnPServiceAction object that identifies which action was invoked, and
179 is used to return values using gupnp_service_action_set().
180 #GUPnPService::query-variable is emitted for evented variables when a
181 control point subscribes to the service (to announce the initial value),
182 or whenever a client queries the value of a state variable (note that this
183 is now deprecated behaviour for UPnP control points): the handler is
184 passed the variable name and a #GValue which should be set to the current
185 value of the variable.
188 There are two approaches that clients can take to handle these signals.
189 They can either connect a single handler to #GUPnPService::action-invoked
190 or #GUPnPService::query-variable and examine the arguments to decide what
191 action to take. Alternatively, handlers can be targetted at specific
192 actions or variables by using the <firstterm>signal detail</firstterm>
193 when connecting. For example, this causes
194 <function>on_get_status_action</function> to be called when the
195 <function>GetStatus</function> action is invoked:
197 <programlisting>static void on_get_status_action (GUPnPService *service, GUPnPServiceAction *action, gpointer user_data);
199 g_signal_connect (service, "action-invoked::GetStatus", G_CALLBACK (on_get_status_action), NULL);</programlisting>
201 The implementation of action handlers is quite simple. The handler is
202 passed a #GUPnPServiceAction object which represents the in-progress
203 action. If required it can be queried using
204 gupnp_service_action_get_name() to identify the action (this isn't
205 required if detailed signals were connected). Any
206 <firstterm>in</firstterm> arguments can be retrieving using
207 gupnp_service_action_get(), and then return values can be set using
208 gupnp_service_action_set(). Once the action has been performed, either
209 gupnp_service_action_return() or gupnp_service_action_return_error()
210 should be called to either return successfully or return an error code.
211 If any evented state variables were modified during the action then a
212 notification should be emitted using gupnp_service_notify(). This is an
213 example implementation of <function>GetStatus</function> and
214 <function>SetTarget</function>:
216 <programlisting>static gboolean status;
219 get_status_cb (GUPnPService *service, GUPnPServiceAction *action, gpointer user_data)
221 gupnp_service_action_set (action,
222 "ResultStatus", G_TYPE_BOOLEAN, status,
224 gupnp_service_action_return (action);
228 set_target_cb (GUPnPService *service, GUPnPServiceAction *action, gpointer user_data)
230 gupnp_service_action_get (action,
231 "NewTargetValue", G_TYPE_BOOLEAN, &status,
233 gupnp_service_action_return (action);
234 gupnp_service_notify (service, "Status", G_TYPE_STRING, status, NULL);
237 g_signal_connect (service, "action-invoked::GetStatus", G_CALLBACK (get_status_cb), NULL);
238 g_signal_connect (service, "action-invoked::SetTarget", G_CALLBACK (set_target_cb), NULL);</programlisting>
240 State variable query handlers are called with the name of the variable and
241 a #GValue. This value should be initialized with the relevant type and
242 then set to the current value. Again signal detail can be used to connect
243 handlers to specific state variable callbacks.
245 <programlisting>static gboolean status;
248 query_status_cb (GUPnPService *service, char *variable, GValue *value, gpointer user_data)
250 g_value_init (value, G_TYPE_BOOLEAN);
251 g_value_set_boolean (value, status);
254 g_signal_connect (service, "query-variable::Status", G_CALLBACK (query_status_cb), NULL);</programlisting>
256 The service is now fully implemented. To complete it, enter a GLib main
257 loop and wait for a client to connect. The complete source code for this
258 example is available as <filename>examples/light-server.c</filename> in
262 For services which have many actions and variables there is a convenience
263 method gupnp_service_signals_autoconnect() which will automatically
264 connect specially named handlers to signals. See the documentation for
265 full details on how it works.
269 <title>Generating Service-specific Wrappers</title>
271 Using service-specific wrappers can simplify the implementation of a service.
272 Wrappers can be generated with <xref linkend="gupnp-binding-tool"/>
273 using the option <literal>--mode server</literal>.
276 In the following examples the wrapper has been created with <literal>--mode server --prefix switch</literal>.
278 <programlisting>static gboolean status;
281 get_status_cb (GUPnPService *service,
282 GUPnPServiceAction *action,
285 switch_get_status_action_set (action, status);
287 gupnp_service_action_return (action);
291 set_target_cb (GUPnPService *service,
292 GUPnPServiceAction *action,
295 switch_set_target_action_get (action, &status);
296 switch_status_variable_notify (service, status);
298 gupnp_service_action_return (action);
303 switch_get_status_action_connect (service, G_CALLBACK(get_status_cb), NULL);
304 switch_set_target_action_connect (service, G_CALLBACK(set_target_cb), NULL);</programlisting>
306 Note how many possible problem situations that were run-time errors are
307 actually compile-time errors when wrappers are used: Action names,
308 argument names and argument types are easier to get correct (and available
309 in editor autocompletion).
312 State variable query handlers are implemented in a similar manner, but
313 they are even simpler as the return value of the handler is the state
316 <programlisting>static gboolean
317 query_status_cb (GUPnPService *service,
325 switch_status_query_connect (service, query_status_cb, NULL);</programlisting>