4066bccd65f1a998e3d3b3ec960554a298a523ee
[profile/ivi/GUPnP.git] / doc / server-tutorial.xml
1 <?xml version="1.0"?>
2 <!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" "http://www.oasis-open.org/docbook/xml/4.4/docbookx.dtd">
3
4 <chapter id="server-tutorial" xmlns:xi="http://www.w3.org/2001/XInclude">
5   <title>Writing a UPnP Service</title>
6
7   <simplesect>
8     <title>Introduction</title>
9     <para>
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.
12     </para>
13     <para>
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/sdcps-and-certification/standards/sdcps/"/> for the
18       list of standard devices and services) then the service description is
19       already written for you and the device description is trivial.  UPnP has
20       standardised <ulink url="http://upnp.org/specs/ha/lighting/">Lighting
21       Controls</ulink>, so we'll be using the device and service types defined
22       there.
23     </para>
24   </simplesect>
25
26   <simplesect>
27     <title>Defining the Device</title>
28     <para>
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-arch-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.
36     </para>
37     <programlisting><xi:include href="../../examples/BinaryLight1.xml" parse="text"/></programlisting>
38     <para>
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
41       only version is 1.0.
42     </para>
43     <para>
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.
48     </para>
49     <para>
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.
54     </para>
55     <para>
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.
63     </para>
64     <para>
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
74       managed by GUPnP.
75     </para>
76   </simplesect>
77
78   <simplesect>
79     <title>Defining Services</title>
80     <para>
81       Because 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:
84     </para>
85     <programlisting><xi:include href="../../examples/SwitchPower1.xml" parse="text"/></programlisting>
86     <para>
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>.
93     </para>
94     <para>
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.
103     </para>
104     <para>
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.
113     </para>
114     <para>
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
117       the <ulink
118       url="http://upnp.org/specs/arch/UPnP-arch-DeviceArchitecture-v1.0.pdf">UPnP
119       Device Architecture</ulink>.
120     </para>
121   </simplesect>
122
123   <simplesect>
124     <title>Implementing the Device</title>
125     <para>
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().
129     </para>
130     <programlisting>GUPnPContext *context;
131 /* Initialize required subsystems */
132 g_type_init ();
133 /* Create the GUPnP context with default host and port */
134 context = gupnp_context_new (NULL, NULL, 0, NULL);</programlisting>
135     <para>
136       UPnP uses HTTP to provide the device and service description files, so
137       next we tell GUPnP to publish them.  This is done with
138       gupnp_context_host_path() which takes a local filename to send when a
139       certain server path is requested.
140     </para>
141 <programlisting>gupnp_context_host_path (context, "BinaryLight1.xml", "/BinaryLight1.xml");
142 gupnp_context_host_path (context, "SwitchPower1.xml", "/SwitchPower1.xml");</programlisting>
143     <para>
144       Next the root device can be created. 
145     </para>
146     <programlisting>GUPnPRootDevice *dev;
147 /* Create the root device object */
148 dev = gupnp_root_device_new (context, "/BinaryLight1.xml");
149 /* Activate the root device, so that it announces itself */
150 gupnp_root_device_set_available (dev, TRUE);</programlisting>
151     <para>
152       GUPnP scans the device description and any service description files it
153       refers to, so if the main loop was entered now the device and service
154       would be available on the network, albeit with no functionality.  The
155       remaining task is to implement the services.
156     </para>
157   </simplesect>
158
159   <simplesect>
160     <title>Implementing a Service</title>
161     <para>
162       To implement a service we first fetch the #GUPnPService from the root
163       device using gupnp_device_info_get_service() (#GUPnPRootDevice is a
164       subclass of #GUPnPDevice, which implements #GUPnPDeviceInfo).  This
165       returns a #GUPnPServiceInfo which again is an interface, implemented by
166       #GUPnPService (on the server) and #GUPnPServiceProxy (on the client).
167     </para>
168     <programlisting>GUPnPServiceInfo *service;
169 service = gupnp_device_info_get_service
170   (GUPNP_DEVICE_INFO (dev), "urn:schemas-upnp-org:service:SwitchPower:1");</programlisting>
171     <para>
172       #GUPnPService handles interacting with the network itself, leaving the
173       implementation of the service itself to signal handlers that we need to
174       connect.  There are two signals: #GUPnPService::action-invoked and
175       #GUPnPService::query-variable.  #GUPnPService::action-invoked is emitted
176       when a client invokes an action: the handler is passed a
177       #GUPnPServiceAction object that identifies which action was invoked, and
178       is used to return values using gupnp_service_action_set().
179       #GUPnPService::query-variable is emitted for evented variables when a
180       control point subscribes to the service (to announce the initial value),
181       or whenever a client queries the value of a state variable (note that this
182       is now deprecated behaviour for UPnP control points): the handler is
183       passed the variable name and a #GValue which should be set to the current
184       value of the variable.
185     </para>
186     <para>
187       There are two approaches that clients can take to handle these signals.
188       They can either connect a single handler to #GUPnPService::action-invoked
189       or #GUPnPService::query-variable and examine the arguments to decide what
190       action to take.  Alternatively, handlers can be targetted at specific
191       actions or variables by using the <firstterm>signal detail</firstterm>
192       when connecting.  For example, this causes
193       <function>on_get_status_action</function> to be called when the
194       <function>GetStatus</function> action is invoked:
195     </para>
196     <programlisting>static void on_get_status_action (GUPnPService *service, GUPnPServiceAction *action, gpointer user_data);
197 &hellip;
198 g_signal_connect (service, "action-invoked::GetStatus", G_CALLBACK (on_get_status_action), NULL);</programlisting>
199     <para>
200       The implementation of action handlers is quite simple.  The handler is
201       passed a #GUPnPServiceAction object which represents the in-progress
202       action.  If required it can be queried using
203       gupnp_service_action_get_name() to identify the action (this isn't
204       required if detailed signals were connected).  Any
205       <firstterm>in</firstterm> arguments can be retrieving using
206       gupnp_service_action_get(), and then return values can be set using
207       gupnp_service_action_set().  Once the action has been performed, either
208       gupnp_service_action_return() or gupnp_service_action_return_error()
209       should be called to either return successfully or return an error code.
210       If any evented state variables were modified during the action then a
211       notification should be emitted using gupnp_service_notify().  This is an
212       example implementation of <function>GetStatus</function> and
213       <function>SetTarget</function>:
214     </para>
215     <programlisting>static gboolean status;
216
217 static void
218 get_status_cb (GUPnPService *service, GUPnPServiceAction *action, gpointer user_data)
219 {
220   gupnp_service_action_set (action,
221                             "ResultStatus", G_TYPE_BOOLEAN, status,
222                             NULL);
223   gupnp_service_action_return (action);
224 }
225
226 void
227 set_target_cb (GUPnPService *service, GUPnPServiceAction *action, gpointer user_data)
228 {
229   gupnp_service_action_get (action,
230                             "NewTargetValue", G_TYPE_BOOLEAN, &amp;status,
231                             NULL);
232   gupnp_service_action_return (action);
233   gupnp_service_notify (service, "Status", G_TYPE_STRING, status, NULL);
234 }
235 &hellip;
236 g_signal_connect (service, "action-invoked::GetStatus", G_CALLBACK (get_status_cb), NULL);
237 g_signal_connect (service, "action-invoked::SetTarget", G_CALLBACK (set_target_cb), NULL);</programlisting>
238     <para>
239       State variable query handlers are called with the name of the variable and
240       a #GValue.  This value should be initialized with the relevant type and
241       then set to the current value.  Again signal detail can be used to connect
242       handlers to specific state variable callbacks.
243     </para>
244     <programlisting>static gboolean status;
245
246 static void
247 query_status_cb (GUPnPService *service, char *variable, GValue *value, gpointer user_data)
248 {
249   g_value_init (value, G_TYPE_BOOLEAN);
250   g_value_set_boolean (value, status);
251 }
252 &hellip;
253 g_signal_connect (service, "query-variable::Status", G_CALLBACK (query_status_cb), NULL);</programlisting>
254     <para>
255       The service is now fully implemented.  To complete it, enter a GLib main
256       loop and wait for a client to connect.  The complete source code for this
257       example is available as <filename>examples/light-server.c</filename> in
258       the GUPnP sources.
259     </para>
260     <para>
261       For services which have many actions and variables there is a convenience
262       method gupnp_service_signals_autoconnect() which will automatically
263       connect specially named handlers to signals.  See the documentation for
264       full details on how it works.
265     </para>
266   </simplesect>
267   <simplesect>
268     <title>Generating Service-specific Wrappers</title>
269     <para>
270       Using service-specific wrappers can simplify the implementation of a service.
271       Wrappers can be generated with <xref linkend="gupnp-binding-tool"/>
272       using the option <literal>--mode server</literal>. 
273     </para>
274     <para>
275       In the following examples the wrapper has been created with
276       <literal>--mode server --prefix switch</literal>. Please note that the callback handlers
277       (<literal>get_status_cb</literal> and <literal>set_target_cb</literal>) are not automatically
278       generated by <xref linkend="gupnp-binding-tool"/> for you.
279     </para>
280     <programlisting>static gboolean status;
281
282 static void
283 get_status_cb (GUPnPService *service,
284                GUPnPServiceAction *action,
285                gpointer user_data)
286 {
287   switch_get_status_action_set (action, status);
288   
289   gupnp_service_action_return (action);
290 }
291
292 static void
293 set_target_cb (GUPnPService *service,
294                GUPnPServiceAction *action,
295                gpointer user_data)
296 {
297   switch_set_target_action_get (action, &amp;status);
298   switch_status_variable_notify (service, status);
299   
300   gupnp_service_action_return (action);
301 }
302
303 &hellip;
304
305 switch_get_status_action_connect (service, G_CALLBACK(get_status_cb), NULL);
306 switch_set_target_action_connect (service, G_CALLBACK(set_target_cb), NULL);</programlisting>
307     <para>
308       Note how many possible problem situations that were run-time errors are 
309       actually compile-time errors when wrappers are used: Action names, 
310       argument names and argument types are easier to get correct (and available
311       in editor autocompletion).
312     </para>
313     <para>
314       State variable query handlers are implemented in a similar manner, but 
315       they are even simpler as the return value of the handler is the state 
316       variable value.
317     </para>
318     <programlisting>static gboolean
319 query_status_cb (GUPnPService *service, 
320                  gpointer user_data)
321 {
322   return status;
323 }
324
325 &hellip;
326
327 switch_status_query_connect (service, query_status_cb, NULL);</programlisting>
328   </simplesect>
329 </chapter>