device.cpp 9.58 KB
Newer Older
Jean-Francois Dockes's avatar
Jean-Francois Dockes committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/* Copyright (C) 2029 J.F.Dockes
 *
 * License: GPL 2.1
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include "myvdir.h"
Jean-Francois Dockes's avatar
Jean-Francois Dockes committed
22
#include "utils.h"
Jean-Francois Dockes's avatar
Jean-Francois Dockes committed
23
24
25
26
27
28
29
30
31
32
33
34
35

#include <iostream>
#include <sstream>
#include <string>

#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <signal.h>

36
37
38
#include <upnp.h>
#include <upnpdebug.h>
#include <upnptools.h>
Jean-Francois Dockes's avatar
Jean-Francois Dockes committed
39
40
41
42
43
44

void sigcatcher(int)
{
    return;
}

Jean-Francois Dockes's avatar
Jean-Francois Dockes committed
45
static std::string deviceDescription {
Jean-Francois Dockes's avatar
Jean-Francois Dockes committed
46
47
48
49
50
51
52
53
54
55
56
    "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
    "<root xmlns=\"urn:schemas-upnp-org:device-1-0\">"
    "  <specVersion>"
    "    <major>1</major>"
    "    <minor>1</minor>"
    "  </specVersion>"
    "  <device>"
    "    <deviceType>urn:jfd:testdevice:1</deviceType>"
    "    <friendlyName>npupnp-test-device</friendlyName>"
    "    <manufacturer>jfd</manufacturer>"
    "    <modelName>jfd-webserver</modelName>"
Jean-Francois Dockes's avatar
Jean-Francois Dockes committed
57
    "    <UDN>@UDN@</UDN>"
Jean-Francois Dockes's avatar
Jean-Francois Dockes committed
58
59
60
61
    "    <serviceList>"
    "      <service>"
    "        <serviceType>urn:jfd:service:MyService:1</serviceType>"
    "        <serviceId>urn:jfd:serviceId:MyService</serviceId>"
Jean-Francois Dockes's avatar
Jean-Francois Dockes committed
62
    "        <SCPDURL>@SCPDURL@</SCPDURL>"
Jean-Francois Dockes's avatar
Jean-Francois Dockes committed
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
    "        <controlURL>/ctl/MyService</controlURL>"
    "        <eventSubURL>/evt/MyService</eventSubURL>"
    "      </service>"
    "    </serviceList>"
    "  </device>"
    "</root>"
};

// Our service has two actions, to set and retrieve a value. Who needs more?
const static std::string serviceDescription {
    "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
    "<scpd xmlns=\"urn:schemas-upnp-org:service-1-0\">"
    "  <specVersion>"
    "    <major>1</major>"
    "    <minor>1</minor>"
    "  </specVersion>"
    "  <actionList>"
    "    <action>"
    "      <name>GetValue</name>"
    "      <argumentList>"
    "        <argument>"
    "          <name>Value</name>"
    "          <direction>out</direction>"
    "          <relatedStateVariable>Value</relatedStateVariable>"
    "        </argument>"
    "      </argumentList>"
    "    </action>"
    "    <action>"
    "      <name>SetValue</name>"
    "      <argumentList>"
    "        <argument>"
    "          <name>Value</name>"
    "          <direction>in</direction>"
    "          <relatedStateVariable>Value</relatedStateVariable>"
    "        </argument>"
    "      </argumentList>"
    "    </action>"
    "  </actionList>"
    "  <serviceStateTable>"
    "    <stateVariable sendEvents=\"yes\">"
    "      <name>Value</name>"
    "      <dataType>ui4</dataType>"
    "    </stateVariable>"
    "  </serviceStateTable>"
    "</scpd>"
};

void callfailed(const char *call, int code)
{
    std::cerr << call << " failed. code " << code << ": " <<
		UpnpGetErrorMessage(code) << "\n";
}


// Our device handle. Need this in several places. Of course, in a
// real implementation, this would be stored in a data structure
// pointed to by the cookie argument which we set when registering the
// device, and receive in the callbacks.
static UpnpDevice_Handle the_handle;

// Because we share a virtualdir implementation with the webserver
// test program, and because this is actually file-system-based, we
// use a temporary directory to store the HTTP-downloadable
Jean-Francois Dockes's avatar
none    
Jean-Francois Dockes committed
126
127
// description files. We do not use the local file serving capability from
// the WEB server (see smallsamps/upnp_fsdevice for this).
Jean-Francois Dockes's avatar
Jean-Francois Dockes committed
128
129
130
static const char *cdirtemplate{"/tmp/npupnpXXXXXX"};
static char *vdirnm;

Jean-Francois Dockes's avatar
Jean-Francois Dockes committed
131
132
static const std::string myudn{"uuid:jfd-npupnp-test-on-y"};

Jean-Francois Dockes's avatar
Jean-Francois Dockes committed
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
// Service description XML path (this points inside the temp dir above).
static std::string sdpath;

static void cleanup()
{
    if (vdirnm) {
        if (!sdpath.empty()) {
            unlink(sdpath.c_str());
        }
        rmdir(vdirnm);
    }
}

static int theValue = 42;

static std::string thevalueasstr()
{
    std::ostringstream ostr;
    ostr << theValue;
    return ostr.str();
}
    
static int runaction(Upnp_Action_Request *arp)
{
    std::cerr << "Action request: action " << arp->ActionName << " UDN " <<
        arp->DevUDN << " ServiceID " << arp->ServiceID << " arg cnt " <<
        arp->args.size() << "\n";

    if (!strcmp("GetValue", arp->ActionName)) {
        if (arp->args.size() != 0) {
            std::cerr << "'Value' action should have no args\n";
            return UPNP_E_INVALID_PARAM;
        }
        arp->resdata.push_back(
        std::pair<std::string, std::string>("Value", thevalueasstr()));

    } else if (!strcmp("SetValue", arp->ActionName)) {
        if (arp->args.size() != 1) {
            std::cerr << "'Value' action should have no args\n";
            return UPNP_E_INVALID_PARAM;
        }
        if (arp->args[0].first != "Value") {
175
            std::cerr << "'Value' action bad arg name [" << arp->args[0].first << "]\n";
Jean-Francois Dockes's avatar
Jean-Francois Dockes committed
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
            return UPNP_E_INVALID_PARAM;
        }
        theValue = atoi(arp->args[0].second.c_str());

        // We just presumably changed the value of our variable, so
        // generate an event.
        const char *names[]{"Value"};
        const char *values[]{thevalueasstr().c_str()};
        UpnpNotify(the_handle, arp->DevUDN, arp->ServiceID, names, values, 1);

    } else {
        std::cerr << "BAD ACTION NAME [" << arp->ActionName << "]\n";
        return UPNP_E_INVALID_PARAM;
    }
    return UPNP_E_SUCCESS;
}

// Process subscription request. We send all the state variable values
// through the UpnpAcceptSubscription function.
static int subscriptionrequest(struct Upnp_Subscription_Request *srp)
{
    std::cerr << "Subscription request: UDN " << srp->UDN << " serviceId " <<
        srp->ServiceId << " Subscription ID " << srp->Sid << "\n";

    const char *names[]{"Value"};
    const char *values[]{thevalueasstr().c_str()};
    return UpnpAcceptSubscription(the_handle, srp->UDN, srp->ServiceId, names,
                                  values, 1, srp->Sid);
}    

// This gets called every time something happens in the lib.
static int g_lib_callback(
    Upnp_EventType evttype, const void *event, void *cookie)
{
    std::cerr << "g_lib_callback. evttype " << evttype <<
		" event " << (void*)event << " cookie " << cookie << "\n";

    switch (evttype) {

    case UPNP_CONTROL_ACTION_REQUEST:
    {
        struct Upnp_Action_Request *arp = (struct Upnp_Action_Request *)event;
        return runaction(arp);
    }
    break;

    case UPNP_EVENT_SUBSCRIPTION_REQUEST:
    {
        struct Upnp_Subscription_Request *srp =
            (struct Upnp_Subscription_Request *)event;
        return subscriptionrequest(srp);
    }

    default:
        std::cerr << "Got event type " << evttype << "\n";
    }

    return 0;
}

static char *thisprog;
static char usage[] =
"[no arguments] : test device\n"
;
static void
Usage(void)
{
    fprintf(stderr, "Usage: %s %s", thisprog, usage);
    exit(1);
}

bool storeDescription()
{
    vdirnm = strdup(cdirtemplate);
    if (nullptr == mkdtemp(vdirnm)) {
        perror("mkdtemp");
        return false;
    }
    sdpath = std::string(vdirnm) + '/' + "MyService.xml";
    int fd = open(sdpath.c_str(), O_WRONLY|O_CREAT, 0444);
    if (fd < 0) {
        std::cerr << " Error opening " << sdpath << " : ";
        perror("open");
        return false;
    }
    if (write(fd, serviceDescription.c_str(), serviceDescription.size()) !=
        int(serviceDescription.size())) {
        perror("write");
        close(fd);
        return false;
    }
    close(fd);
    return true;
}

int main(int argc, char **argv)
{
    thisprog = *argv++;
    argc--;
    if (argc != 0) {
        Usage();
    }

    atexit(cleanup);
    signal(SIGINT, sigcatcher);
    signal(SIGTERM, sigcatcher);

    // Store the service description so that it can be downloaded through the
    // web server.
    if (!storeDescription()) {
        return 1;
    }

    // Initialize library. This starts the web server.
    int errcode = UpnpInit2(nullptr, 0);
    if (errcode != UPNP_E_SUCCESS) {
        callfailed("UpnpInit2", errcode);
        return 1;
    }
295
    UpnpSetLogLevel(UPNP_DEBUG);
Jean-Francois Dockes's avatar
Jean-Francois Dockes committed
296
297
298
    UpnpInitLog();

    std::cerr << "IP " << UpnpGetServerIpAddress() << " port " <<
Jean-Francois Dockes's avatar
Jean-Francois Dockes committed
299
        UpnpGetServerPort() << " UDN " << myudn << "\n";
Jean-Francois Dockes's avatar
Jean-Francois Dockes committed
300
301
302
303
304
305
306
307
308
309

	errcode = UpnpSetVirtualDirCallbacks(&mycallbacks);
    if (errcode != UPNP_E_SUCCESS) {
        callfailed("UpnpSetVirtualDirCallbacks", errcode);
        return 1;
    }
	errcode = UpnpAddVirtualDir(vdirnm, nullptr, nullptr);

    // Declare our device. The device description includes the URL for
    // the service description of our one and only service.
Jean-Francois Dockes's avatar
Jean-Francois Dockes committed
310
311
    str_replace1(deviceDescription, "@UDN@", myudn);
    str_replace1(deviceDescription, "@SCPDURL@", sdpath);
Jean-Francois Dockes's avatar
Jean-Francois Dockes committed
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
    errcode = UpnpRegisterRootDevice2(
        UPNPREG_BUF_DESC, deviceDescription.c_str(), deviceDescription.size(), 
        0, g_lib_callback, nullptr, &the_handle);
    if (errcode != UPNP_E_SUCCESS) {
        callfailed("UpnpRegisterRootDevice2", errcode);
        return 1;
    }

    // And just let the lib work.
    pause();

    errcode = UpnpFinish();
    if (errcode != UPNP_E_SUCCESS) {
        callfailed("UpnpFinish", errcode);
        return 1;
    }
    
    return 0;
}