File: inquirer.cpp

package info (click to toggle)
pybluez 0.18-1
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 524 kB
  • ctags: 776
  • sloc: ansic: 4,226; python: 2,175; cpp: 1,861; makefile: 46
file content (601 lines) | stat: -rw-r--r-- 16,976 bytes parent folder | download | duplicates (5)
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
#include <windows.h>
#include <Python.h>

#include <BtIfDefinitions.h>
#include <BtIfClasses.h>
#include <com_error.h>
#include "util.h"

#include "inquirer.hpp"

static inline void
dbg (const char *fmt, ...)
{
    return;
    va_list ap;
    va_start (ap, fmt);
    vfprintf (stderr, fmt, ap);
    va_end (ap);
}

static void 
dict_set_str_pyobj(PyObject *dict, const char *key, PyObject *valobj)
{
    PyObject *keyobj;
    keyobj = PyString_FromString (key);
    PyDict_SetItem (dict, keyobj, valobj);
    Py_DECREF (keyobj);
}

static void 
dict_set_strings(PyObject *dict, const char *key, const char *val)
{
    PyObject *keyobj, *valobj;
    keyobj = PyString_FromString (key);
    valobj = PyString_FromString (val);
    PyDict_SetItem (dict, keyobj, valobj);
    Py_DECREF (keyobj);
    Py_DECREF (valobj);
}

static void 
dict_set_str_long(PyObject *dict, const char *key, long val)
{
    PyObject *keyobj, *valobj;
    keyobj = PyString_FromString (key);
    valobj = PyInt_FromLong(val);
    PyDict_SetItem (dict, keyobj, valobj);
    Py_DECREF (keyobj);
    Py_DECREF (valobj);
}

WCInquirer::WCInquirer (PyObject *wcinq) 
{
    this->wcinq = wcinq;

    this->serverfd = socket (AF_INET, SOCK_STREAM, 0);
    this->threadfd = socket (AF_INET, SOCK_STREAM, 0);

    int status = SOCKET_ERROR;

    struct sockaddr_in saddr = { 0, };

    for (int i=0; i<10; i++) {
        this->sockport = 3000 + (unsigned short) (20000 *
                    (rand () / (RAND_MAX + 1.0)));

        saddr.sin_family = AF_INET;
        saddr.sin_port = htons (this->sockport);
        saddr.sin_addr.s_addr = inet_addr ("127.0.0.1");

        status = bind (this->serverfd, (struct sockaddr*) &saddr,
                sizeof (saddr));

        if (0 == status) break;
    }

    assert (0 == status);

    // instruct server socket to accept one connection
    status = listen (this->serverfd, 1);
    // TODO error checking

//    // connect the client socket to the server socket
//    status = connect (this->threadfd, (struct sockaddr*) &saddr, 
//            sizeof (saddr));
//    // TODO error checking

}

WCInquirer::~WCInquirer () 
{
    closesocket (this->threadfd);
}

int
WCInquirer::AcceptClient () 
{
    struct sockaddr_in useless;
    int useless_sz = sizeof (useless);
    this->threadfd = 
        accept (this->serverfd, (struct sockaddr*)&useless, &useless_sz);

    if (this->threadfd >= 0) {
        // put sockets into nonblocking mode
        unsigned long nonblocking = 1;
        ioctlsocket (this->threadfd, FIONBIO, &nonblocking);

        closesocket (this->serverfd);

        return 0;
    }

    return -1;
}

#pragma pack(push)
#pragma pack(1)

typedef struct {
    int msg_type;
    unsigned char bda[6];
    unsigned char devClass[3];
    unsigned char bdName[248];
    int bConnected;
} device_responded_msg_t;

void
WCInquirer::OnDeviceResponded (BD_ADDR bda, DEV_CLASS devClass, 
                BD_NAME bdName, BOOL bConnected)
{
    dbg ("%s:%d:%s\n", __FILE__, __LINE__, __FUNCTION__);
    device_responded_msg_t msg;
    memset (&msg, 0, sizeof (msg));

    msg.msg_type = DEVICE_RESPONDED;
    memcpy (msg.bda, bda, BD_ADDR_LEN);
    memcpy (msg.devClass, devClass, sizeof (devClass));
    memcpy (msg.bdName, bdName, strlen ((char*)bdName));
    msg.bConnected = bConnected;

    send (this->threadfd, reinterpret_cast <const char *> (&msg), 
            sizeof (msg), 0);
}

typedef struct {
    int msg_type;
    int success;
    short num_responses;
} inquiry_complete_msg_t;

void
WCInquirer::OnInquiryComplete (BOOL success, short num_responses)
{
    dbg ("%s:%d:%s\n", __FILE__, __LINE__, __FUNCTION__);
    inquiry_complete_msg_t msg;
    msg.msg_type = INQUIRY_COMPLETE;
    msg.success = success;
    msg.num_responses = num_responses;

    send (this->threadfd, reinterpret_cast <const char *> (&msg),
            sizeof (msg), 0);
}

typedef struct {
    int msg_type;
} discovery_complete_msg_t;

void
WCInquirer::OnDiscoveryComplete ()
{
    dbg ("%s:%d:%s\n", __FILE__, __LINE__, __FUNCTION__);
    discovery_complete_msg_t msg;
    msg.msg_type = DISCOVERY_COMPLETE;

    send (this->threadfd, reinterpret_cast <const char *> (&msg), 
            sizeof (msg), 0);
}

typedef struct {
    int msg_type;
    CBtIf::STACK_STATUS new_status;
} stack_status_change_msg_t;

void
WCInquirer::OnStackStatusChange (STACK_STATUS new_status)
{
    dbg ("%s:%d:%s\n", __FILE__, __LINE__, __FUNCTION__);
    stack_status_change_msg_t msg;
    msg.msg_type = STACK_STATUS_CHAGE;
    msg.new_status = new_status;

    send (this->threadfd, reinterpret_cast <const char *> (&msg), 
            sizeof (msg), 0);
}

#pragma pack(pop)

// ===================

typedef struct _WCInquirerPyObject WCInquirerPyObject;

struct _WCInquirerPyObject {
    PyObject_HEAD

    WCInquirer *inq;

    int readfd;
    int writefd;
};
PyDoc_STRVAR(wcinquirer_doc, "CBtIf wrapper");

extern PyTypeObject wcinquirer_type;

static PyObject *
get_sockport (PyObject *s)
{
    WCInquirerPyObject *self = (WCInquirerPyObject*) s;
    return PyInt_FromLong (self->inq->GetSockPort ());
}

static PyObject *
accept_client (PyObject *s)
{
    WCInquirerPyObject *self = (WCInquirerPyObject*) s;
    return PyInt_FromLong (self->inq->AcceptClient ());
}

static PyObject * 
start_inquiry (PyObject *s)
{
    WCInquirerPyObject *self = (WCInquirerPyObject*) s;
    if (self->inq->StartInquiry ()) {
        Py_RETURN_TRUE;
    } else {
        Py_RETURN_FALSE;
    }
}

static PyObject *
start_discovery (PyObject *s, PyObject *args)
{
    WCInquirerPyObject *self = (WCInquirerPyObject*) s;

    dbg ("%s:%d start_discovery\n", __FILE__, __LINE__);

    char *bdaddr_in = NULL;
    int bdaddr_in_len = 0;
    char *uuid_str = NULL;
    int uuid_str_len = 0;
    BD_ADDR bdaddr;

    if (!PyArg_ParseTuple (args, "s#|s#", &bdaddr_in, &bdaddr_in_len, 
                &uuid_str, &uuid_str_len)) return 0;

    if (bdaddr_in_len != BD_ADDR_LEN) {
        PyErr_SetString (PyExc_ValueError, "invalid bdaddr");
        return NULL;
    }
    memcpy (bdaddr, bdaddr_in, BD_ADDR_LEN);

    GUID uuid = { 0 };
    GUID *puuid = NULL;
    if (uuid_str) {
        PyWidcomm::str2uuid (uuid_str, &uuid);
        puuid = &uuid;
    }

    BOOL result;
    Py_BEGIN_ALLOW_THREADS
    result = self->inq->StartDiscovery (bdaddr, puuid);
    Py_END_ALLOW_THREADS
   
    if (result) Py_RETURN_TRUE;
    else Py_RETURN_FALSE;
}

static PyObject *
is_device_ready (PyObject *s)
{
    WCInquirerPyObject *self = (WCInquirerPyObject*) s;
    dbg ("IsDeviceReady: %d\n", (self->inq->IsDeviceReady ()));
    if (self->inq->IsDeviceReady ()) Py_RETURN_TRUE;
    else Py_RETURN_FALSE;
}

static PyObject *
is_stack_server_up (PyObject *s)
{
    WCInquirerPyObject *self = (WCInquirerPyObject*) s;
    if (self->inq->IsStackServerUp ()) Py_RETURN_TRUE;
    else Py_RETURN_FALSE;
}

static PyObject * 
get_local_device_name (PyObject *s)
{
    WCInquirerPyObject *self = (WCInquirerPyObject*) s;
    BD_NAME name;
    if (self->inq->GetLocalDeviceName (&name)) {
        return PyString_FromString ( (const char *)name);
    } else {
        Py_RETURN_NONE;
    }
}

static PyObject *
get_local_device_version_info (PyObject *s)
{
    WCInquirerPyObject *self = (WCInquirerPyObject*) s;
    Py_RETURN_NONE;
//    DEV_VER_INFO info;
//    BOOL success = self->inq->GetLocalDeviceVersionInfo (&info);
//    if (success) {
//        return Py_BuildValue ("s#BHBHH", 
//                info.bd_addr, 6, 
//                info.hci_version,
//                info.hci_revision,
//                info.lmp_version,
//                info.manufacturer,
//                info.lmp_sub_version);
//    } else {
//        Py_RETURN_NONE;
//    }
}

#define MAX_SDP_DISCOVERY_RECORDS 2000

static PyObject *
read_discovery_records (PyObject *s, PyObject *args)
{
    WCInquirerPyObject *self = (WCInquirerPyObject*) s;

    UINT8 *bdaddr_in = NULL;
    int bdaddr_in_len = 0;
    char *uuid_str = NULL;
    int uuid_str_len = 0;
    BD_ADDR bdaddr;

    if (!PyArg_ParseTuple (args, "s#|s#", &bdaddr_in, &bdaddr_in_len, 
                &uuid_str, &uuid_str_len)) return 0;

    if (bdaddr_in_len != BD_ADDR_LEN) {
        PyErr_SetString (PyExc_ValueError, "invalid bdaddr");
        return NULL;
    }
    memcpy (bdaddr, bdaddr_in, BD_ADDR_LEN);

    int nrecords = 0;

    CSdpDiscoveryRec *records = new CSdpDiscoveryRec[MAX_SDP_DISCOVERY_RECORDS];

    if (uuid_str) {
        dbg ("filtering by uuid %s\n", uuid_str);
        GUID uuid = { 0 };
        PyWidcomm::str2uuid (uuid_str, &uuid);

        nrecords = self->inq->ReadDiscoveryRecords (bdaddr, 
                MAX_SDP_DISCOVERY_RECORDS,
                records,
                &uuid);
    } else {
        dbg ("no uuid specified.\n");
        nrecords = self->inq->ReadDiscoveryRecords (bdaddr, 
                MAX_SDP_DISCOVERY_RECORDS,
                records);
        dbg ("nrecords: %d\n", nrecords);
    }

    char bdaddr_str[18];
    sprintf (bdaddr_str, "%02X:%02X:%02X:%02X:%02X:%02X", 
            bdaddr_in[0], bdaddr_in[1], bdaddr_in[2], 
            bdaddr_in[3], bdaddr_in[4], bdaddr_in[5]);

    PyObject *result = PyList_New (nrecords);
    for (int i=0; i<nrecords; i++) {
        PyObject *dict = PyDict_New ();

        // host name offering the service
        dict_set_strings (dict, "host", bdaddr_str);

        // service name
        dict_set_strings (dict, "name", records[i].m_service_name);

        // protocol and port number
        UINT8 scn;
        UINT16 psm;
        if (records[i].FindRFCommScn (&scn)) {
            dict_set_strings (dict, "protocol", "RFCOMM");
            dict_set_str_long (dict, "port", scn);
        } else if (records[i].FindL2CapPsm (&psm)) {
            dict_set_strings (dict, "protocol", "L2CAP");
            dict_set_str_long (dict, "port", psm);
        } else {
            dict_set_strings (dict, "protocol", "UNKNOWN");
            dict_set_str_pyobj (dict, "port", Py_None);
        }

        // service description
        SDP_DISC_ATTTR_VAL desc;
        if (records[i].FindAttribute (0x0101, &desc) &&
            desc.num_elem > 0 && 
            desc.elem[0].type == ATTR_TYPE_ARRAY) {
            dict_set_strings (dict, "description", 
                    (char*)desc.elem[0].val.array);
        } else {
            dict_set_strings (dict, "description", "");
        }

        dict_set_strings (dict, "provider", "");

        PyObject *profiles_list = PyList_New (0);
        dict_set_str_pyobj (dict, "profiles", profiles_list);
        Py_DECREF (profiles_list);

        dict_set_strings (dict, "service-id", "");

        // service class list
        PyObject *uuid_list = PyList_New (0);
//        SDP_DISC_ATTTR_VAL service_classes;
//        if (records[i].FindAttribute (0x0001, &service_classes)) {
//
//            printf ("service-classes: %d\n", desc.num_elem);
//            for (int j=0; j<desc.num_elem; j++) {
//                if (desc.elem[j].type == ATTR_TYPE_UUID ||
//                    desc.elem[j].type == ATTR_TYPE_ARRAY) {
//                    printf ("   array len: %d\n", desc.elem[j].len);
//                    unsigned char *u = desc.elem[j].val.array;
//                    char buf[255];
//                    memset (buf, 0, sizeof (buf));
//                    memcpy (buf, desc.elem[j].val.array, desc.elem[j].len);
//                    sprintf (buf, 
//        "%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X",
//                            u[0], u[1], u[2], u[3],
//                            u[4], u[5], u[6], u[7],
//                            u[8], u[9], u[10], u[11],
//                            u[12], u[13], u[14], u[15]);
//                    printf ("%s\n", buf);
//                    PyObject *uuid_pyobj = PyString_FromString (buf);
//                    PyList_Append (uuid_list, uuid_pyobj);
//                    Py_DECREF (uuid_pyobj);
//                } else {
//                    printf ("     elem type: %d\n", desc.elem[j].type);
//                }
//            }
//        }
        dict_set_str_pyobj (dict, "service-classes", uuid_list);
        Py_DECREF (uuid_list);
        
        PyList_SetItem (result, i, dict);
    }

    delete [] records;

    return result;
}

static PyObject *
get_remote_device_info (PyObject *s, PyObject *args)
{
    // TODO
    Py_RETURN_NONE;
}

static PyObject *
get_next_remote_device_info (PyObject *s, PyObject *args)
{
    // TODO
    Py_RETURN_NONE;
}

static PyObject *
get_local_device_address (PyObject *s)
{
    WCInquirerPyObject *self = (WCInquirerPyObject*) s;
    BOOL result = self->inq->GetLocalDeviceInfo ();
    if (result) {
        return Py_BuildValue ("s", self->inq->m_BdName);
    } else {
        Py_RETURN_NONE;
    }
}

static PyObject *
get_btw_version_info (PyObject *s)
{
    WCInquirerPyObject *self = (WCInquirerPyObject*) s;
    char buf[MAX_PATH];
    BOOL result = self->inq->GetBTWVersionInfo (buf, MAX_PATH);
    if (result) {
        return PyString_FromString (buf);
    } else {
        Py_RETURN_NONE;
    }
}

static PyMethodDef wcinquirer_methods[] = {
    { "get_sockport", (PyCFunction) get_sockport, METH_NOARGS, "" },
    { "accept_client", (PyCFunction) accept_client, METH_NOARGS, "" },
    { "start_inquiry", (PyCFunction)start_inquiry, METH_NOARGS, "" },
    { "start_discovery", (PyCFunction)start_discovery, METH_VARARGS, "" },
    { "is_device_ready", (PyCFunction)is_device_ready, METH_NOARGS, "" },
    { "is_stack_server_up", (PyCFunction)is_stack_server_up, METH_NOARGS, "" },
    { "get_local_device_name", 
        (PyCFunction)get_local_device_name, METH_NOARGS, "" },
    { "get_local_device_version_info", 
        (PyCFunction)get_local_device_version_info, METH_NOARGS, ""},
    { "read_discovery_records",
        (PyCFunction)read_discovery_records, METH_VARARGS, "" },
    { "get_remote_device_info",
        (PyCFunction)get_remote_device_info, METH_VARARGS, "" },
    { "get_next_remote_device_info",
        (PyCFunction)get_next_remote_device_info, METH_VARARGS, "" },
    { "get_local_device_address",
        (PyCFunction)get_local_device_address, METH_NOARGS, "" },
    { "get_btw_version_info",
        (PyCFunction)get_btw_version_info, METH_NOARGS, "" },
    { NULL, NULL }
};

static PyObject *
wcinquirer_repr(WCInquirerPyObject *s)
{
    return PyString_FromString("_WCInquirer object");
}

static PyObject *
wcinquirer_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
    PyObject *newobj;

    newobj = type->tp_alloc(type, 0);
    if (newobj != NULL) {
        WCInquirerPyObject *self = (WCInquirerPyObject *)newobj;
        self->inq = NULL;
    }
    return newobj;
}

static void
wcinquirer_dealloc(WCInquirerPyObject *self)
{
    if (self->inq) {
        delete self->inq;
        self->inq = NULL;
    }
    self->ob_type->tp_free((PyObject*)self);
}

int
wcinquirer_initobj(PyObject *s, PyObject *args, PyObject *kwds)
{
    WCInquirerPyObject *self = (WCInquirerPyObject *)s;

    self->inq = new WCInquirer (s);

    return 0;
}

/* Type object for socket objects. */
PyTypeObject wcinquirer_type = {
    PyObject_HEAD_INIT(0)   /* Must fill in type value later */
    0,                  /* ob_size */
    "_widcomm._WCInquirer",            /* tp_name */
    sizeof(WCInquirerPyObject),     /* tp_basicsize */
    0,                  /* tp_itemsize */
    (destructor)wcinquirer_dealloc,     /* tp_dealloc */
    0,                  /* tp_print */
    0,                  /* tp_getattr */
    0,                  /* tp_setattr */
    0,                  /* tp_compare */
    (reprfunc)wcinquirer_repr,          /* tp_repr */
    0,                  /* tp_as_number */
    0,                  /* tp_as_sequence */
    0,                  /* tp_as_mapping */
    0,                  /* tp_hash */
    0,                  /* tp_call */
    0,                  /* tp_str */
    PyObject_GenericGetAttr,        /* tp_getattro */
    0,                  /* tp_setattro */
    0,                  /* tp_as_buffer */
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
    wcinquirer_doc,               /* tp_doc */
    0,                  /* tp_traverse */
    0,                  /* tp_clear */
    0,                  /* tp_richcompare */
    0,                  /* tp_weaklistoffset */
    0,                  /* tp_iter */
    0,                  /* tp_iternext */
    wcinquirer_methods,               /* tp_methods */
    0,                  /* tp_members */
    0,                  /* tp_getset */
    0,                  /* tp_base */
    0,                  /* tp_dict */
    0,                  /* tp_descr_get */
    0,                  /* tp_descr_set */
    0,                  /* tp_dictoffset */
    wcinquirer_initobj,             /* tp_init */
    PyType_GenericAlloc,            /* tp_alloc */
    wcinquirer_new,             /* tp_new */
    PyObject_Del,               /* tp_free */
};