summaryrefslogtreecommitdiff
path: root/doc/server-tutorial.xml
blob: 1c360ce796ef962e402eb4a2697d091dff10b6c3 (plain)
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
<?xml version="1.0"?>
<!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd">

<chapter id="server-tutorial" xmlns:xi="http://www.w3.org/2001/XInclude">
  <title>Writing a UPnP Service</title>

  <simplesect>
    <title>Introduction</title>
    <para>
      This chapter explains how to implement a UPnP service using GUPnP. For
      this example we will create a virtual UPnP-enabled light bulb.
    </para>
    <para>
      Before any code can be written, the device and services that it implement
      need to be described in XML.  Although this can be frustrating, if you are
      implementing a standardised service (see <ulink
      url="http://upnp.org/sdcps-and-certification/standards/sdcps/"/> for the
      list of standard devices and services) then the service description is
      already written for you and the device description is trivial.  UPnP has
      standardised <ulink url="http://upnp.org/specs/ha/lighting/">Lighting
      Controls</ulink>, so we'll be using the device and service types defined
      there.
    </para>
  </simplesect>

  <simplesect>
    <title>Defining the Device</title>
    <para>
      The first step is to write the <firstterm>device description</firstterm>
      file.  This is a short XML document which describes the device and what
      services it provides (for more details see the <ulink
      url="http://upnp.org/specs/arch/UPnP-arch-DeviceArchitecture-v1.0.pdf">UPnP
      Device Architecture</ulink> specification, section 2.1).  We'll be using
      the <literal>BinaryLight1</literal> device type, but if none of the
      existing device types are suitable a custom device type can be created.
    </para>
    <programlisting><xi:include href="../examples/BinaryLight1.xml" parse="text"><xi:fallback /></xi:include></programlisting>
    <para>
      The <sgmltag>specVersion</sgmltag> tag defines what version of the UPnP
      Device Architecture the document conforms to.  At the time of writing the
      only version is 1.0.
    </para>
    <para>
      Next there is the root <sgmltag>device</sgmltag> tag.  This contains
      metadata about the device, lists the services it provides and any
      sub-devices present (there are none in this example).  The
      <sgmltag>deviceType</sgmltag> tag specifies the type of the device.
    </para>
    <para>
      Next we have <sgmltag>friendlyName</sgmltag>,
      <sgmltag>manufacturer</sgmltag> and <sgmltag>modelName</sgmltag>.  The
      friendly name is a human-readable name for the device, the manufacturer
      and model name are self-explanatory.
    </para>
    <para>
      Next there is the UDN, or <firstterm>Unique Device Name</firstterm>.  This
      is an identifier which is unique for each device but persistent for each
      particular device.  Although it has to start with <literal>uuid:</literal>
      note that it doesn't have to be an UUID.  There are several alternatives
      here: for example it could be computed at built-time if the software will
      only be used on a single machine, or it could be calculated using the
      device's serial number or MAC address.
    </para>
    <para>
      Finally we have the <sgmltag>serviceList</sgmltag> which describes the
      services this device provides.  Each service has a service type (again
      there are types defined for standardised services or you can create your
      own), service identifier, and three URLs.  As a service type we're using
      the standard <literal>SwitchPower1</literal> service.  The
      <sgmltag>SCPDURL</sgmltag> field specifies where the <firstterm>Service
      Control Protocol Document</firstterm> can be found, this describes the
      service in more detail and will be covered next.  Finally there are the
      control and event URLs, which need to be unique on the device and will be
      managed by GUPnP.
    </para>
  </simplesect>

  <simplesect>
    <title>Defining Services</title>
    <para>
      Because we are using a standard service we can use the service description
      from the specification.  This is the <literal>SwitchPower1</literal>
      service description file:
    </para>
    <programlisting><xi:include href="../examples/SwitchPower1.xml" parse="text"><xi:fallback /></xi:include></programlisting>
    <para>
      Again, the <sgmltag>specVersion</sgmltag> tag defines the UPnP version
      that is being used.  The rest of the document consists of an
      <sgmltag>actionList</sgmltag> defining the <glossterm
      linkend="action">actions</glossterm> available and a
      <sgmltag>serviceStateTable</sgmltag> defining the <glossterm
      linkend="state-variable">state variables</glossterm>.
    </para>
    <para>
      Every <sgmltag>action</sgmltag> has a <sgmltag>name</sgmltag> and a list
      of <sgmltag>argument</sgmltag>s.  Arguments also have a name, a direction
      (<literal>in</literal> or <literal>out</literal> for input or output
      arguments) and a related state variable.  The state variable is used to
      determine the type of the argument, and as such is a required element.
      This can lead to the creation of otherwise unused state variables to
      define the type for an argument (the <literal>WANIPConnection</literal>
      service is a good example of this), thanks to the legacy behind UPnP.
    </para>
    <para>
      <sgmltag>stateVariable</sgmltag>s need to specify their
      <sgmltag>name</sgmltag> and <sgmltag>dataType</sgmltag>.  State variables
      by default send notifications when they change, to specify that a variable
      doesn't do this set the <sgmltag>sendEvents</sgmltag> attribute to
      <literal>no</literal>.  Finally there are optional
      <sgmltag>defaultValue</sgmltag>, <sgmltag>allowedValueList</sgmltag> and
      <sgmltag>allowedValueRange</sgmltag> elements which specify what the
      default and valid values for the variable.
    </para>
    <para>
      For the full specification of the service definition file, including a
      complete list of valid <sgmltag>dataType</sgmltag>s, see section 2.3 of
      the <ulink
      url="http://upnp.org/specs/arch/UPnP-arch-DeviceArchitecture-v1.0.pdf">UPnP
      Device Architecture</ulink>.
    </para>
  </simplesect>

  <simplesect>
    <title>Implementing the Device</title>
    <para>
      Before starting to implement the device, some boilerplate code is needed
      to initialise GUPnP.  GLib types and threading needs to be initialised,
      and then a GUPnP context can be created using gupnp_context_new().
    </para>
    <programlisting>GUPnPContext *context;
/* Initialize required subsystems */
#if !GLIB_CHECK_VERSION(2,35,0)
  g_type_init ();
#endif
/* Create the GUPnP context with default host and port */
context = gupnp_context_new (NULL, NULL, 0, NULL);</programlisting>
    <para>
      Next the root device can be created. The name of the device description
      file can be passed as an absolute file path or a relative path to the
      second parameter of gupnp_root_device_new(). The service description
      files referenced in the device description are expected to be at the path
      given there as well.
    </para>
    <programlisting>GUPnPRootDevice *dev;
/* Create the root device object */
dev = gupnp_root_device_new (context, "BinaryLight1.xml", ".");
/* Activate the root device, so that it announces itself */
gupnp_root_device_set_available (dev, TRUE);</programlisting>
    <para>
      GUPnP scans the device description and any service description files it
      refers to, so if the main loop was entered now the device and service
      would be available on the network, albeit with no functionality.  The
      remaining task is to implement the services.
    </para>
  </simplesect>

  <simplesect>
    <title>Implementing a Service</title>
    <para>
      To implement a service we first fetch the #GUPnPService from the root
      device using gupnp_device_info_get_service() (#GUPnPRootDevice is a
      subclass of #GUPnPDevice, which implements #GUPnPDeviceInfo).  This
      returns a #GUPnPServiceInfo which again is an interface, implemented by
      #GUPnPService (on the server) and #GUPnPServiceProxy (on the client).
    </para>
    <programlisting>GUPnPServiceInfo *service;
service = gupnp_device_info_get_service
  (GUPNP_DEVICE_INFO (dev), "urn:schemas-upnp-org:service:SwitchPower:1");</programlisting>
    <para>
      #GUPnPService handles interacting with the network itself, leaving the
      implementation of the service itself to signal handlers that we need to
      connect.  There are two signals: #GUPnPService::action-invoked and
      #GUPnPService::query-variable.  #GUPnPService::action-invoked is emitted
      when a client invokes an action: the handler is passed a
      #GUPnPServiceAction object that identifies which action was invoked, and
      is used to return values using gupnp_service_action_set().
      #GUPnPService::query-variable is emitted for evented variables when a
      control point subscribes to the service (to announce the initial value),
      or whenever a client queries the value of a state variable (note that this
      is now deprecated behaviour for UPnP control points): the handler is
      passed the variable name and a #GValue which should be set to the current
      value of the variable.
    </para>
    <para>
      Handlers should be targetted at specific actions or variables by using
      the <firstterm>signal detail</firstterm> when connecting. For example,
      this causes <function>on_get_status_action</function> to be called when
      the <function>GetStatus</function> action is invoked:
    </para>
    <programlisting>static void on_get_status_action (GUPnPService *service, GUPnPServiceAction *action, gpointer user_data);
&hellip;
g_signal_connect (service, "action-invoked::GetStatus", G_CALLBACK (on_get_status_action), NULL);</programlisting>
    <para>
      The implementation of action handlers is quite simple.  The handler is
      passed a #GUPnPServiceAction object which represents the in-progress
      action.  If required it can be queried using
      gupnp_service_action_get_name() to identify the action (this isn't
      required if detailed signals were connected).  Any
      <firstterm>in</firstterm> arguments can be retrieving using
      gupnp_service_action_get(), and then return values can be set using
      gupnp_service_action_set().  Once the action has been performed, either
      gupnp_service_action_return() or gupnp_service_action_return_error()
      should be called to either return successfully or return an error code.
      If any evented state variables were modified during the action then a
      notification should be emitted using gupnp_service_notify().  This is an
      example implementation of <function>GetStatus</function> and
      <function>SetTarget</function>:
    </para>
    <programlisting>static gboolean status;

static void
get_status_cb (GUPnPService *service, GUPnPServiceAction *action, gpointer user_data)
{
  gupnp_service_action_set (action,
                            "ResultStatus", G_TYPE_BOOLEAN, status,
                            NULL);
  gupnp_service_action_return (action);
}

void
set_target_cb (GUPnPService *service, GUPnPServiceAction *action, gpointer user_data)
{
  gupnp_service_action_get (action,
                            "NewTargetValue", G_TYPE_BOOLEAN, &amp;status,
                            NULL);
  gupnp_service_action_return (action);
  gupnp_service_notify (service, "Status", G_TYPE_STRING, status, NULL);
}
&hellip;
g_signal_connect (service, "action-invoked::GetStatus", G_CALLBACK (get_status_cb), NULL);
g_signal_connect (service, "action-invoked::SetTarget", G_CALLBACK (set_target_cb), NULL);</programlisting>
    <para>
      State variable query handlers are called with the name of the variable and
      a #GValue.  This value should be initialized with the relevant type and
      then set to the current value.  Again signal detail can be used to connect
      handlers to specific state variable callbacks.
    </para>
    <programlisting>static gboolean status;

static void
query_status_cb (GUPnPService *service, char *variable, GValue *value, gpointer user_data)
{
  g_value_init (value, G_TYPE_BOOLEAN);
  g_value_set_boolean (value, status);
}
&hellip;
g_signal_connect (service, "query-variable::Status", G_CALLBACK (query_status_cb), NULL);</programlisting>
    <para>
      The service is now fully implemented.  To complete it, enter a GLib main
      loop and wait for a client to connect.  The complete source code for this
      example is available as <filename>examples/light-server.c</filename> in
      the GUPnP sources.
    </para>
    <para>
      For services which have many actions and variables there is a convenience
      method gupnp_service_signals_autoconnect() which will automatically
      connect specially named handlers to signals.  See the documentation for
      full details on how it works.
    </para>
  </simplesect>
  <simplesect>
    <title>Generating Service-specific Wrappers</title>
    <para>
      Using service-specific wrappers can simplify the implementation of a service.
      Wrappers can be generated with <xref linkend="gupnp-binding-tool"/>
      using the option <literal>--mode server</literal>. 
    </para>
    <para>
      In the following examples the wrapper has been created with
      <literal>--mode server --prefix switch</literal>. Please note that the callback handlers
      (<literal>get_status_cb</literal> and <literal>set_target_cb</literal>) are not automatically
      generated by <xref linkend="gupnp-binding-tool"/> for you.
    </para>
    <programlisting>static gboolean status;

static void
get_status_cb (GUPnPService *service,
               GUPnPServiceAction *action,
               gpointer user_data)
{
  switch_get_status_action_set (action, status);
  
  gupnp_service_action_return (action);
}

static void
set_target_cb (GUPnPService *service,
               GUPnPServiceAction *action,
               gpointer user_data)
{
  switch_set_target_action_get (action, &amp;status);
  switch_status_variable_notify (service, status);
  
  gupnp_service_action_return (action);
}

&hellip;

switch_get_status_action_connect (service, G_CALLBACK(get_status_cb), NULL);
switch_set_target_action_connect (service, G_CALLBACK(set_target_cb), NULL);</programlisting>
    <para>
      Note how many possible problem situations that were run-time errors are 
      actually compile-time errors when wrappers are used: Action names, 
      argument names and argument types are easier to get correct (and available
      in editor autocompletion).
    </para>
    <para>
      State variable query handlers are implemented in a similar manner, but 
      they are even simpler as the return value of the handler is the state 
      variable value.
    </para>
    <programlisting>static gboolean
query_status_cb (GUPnPService *service, 
                 gpointer user_data)
{
  return status;
}

&hellip;

switch_status_query_connect (service, query_status_cb, NULL);</programlisting>
  </simplesect>
</chapter>