File: l2capconn.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 (423 lines) | stat: -rw-r--r-- 11,674 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
#include <windows.h>
#include <Python.h>

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

#include "l2capconn.hpp"
#include "l2capif.hpp"

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

WCL2CapConn::WCL2CapConn (PyObject *pyobj) 
    : CL2CapConn () 
{
    this->pyobj = pyobj;
    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);
}

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

int
WCL2CapConn::AcceptClient () 
{
    dbg ("%s:%d:%s\n", __FILE__, __LINE__, __FUNCTION__);

    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;
    int len;
} data_received_t;

void
WCL2CapConn::OnDataReceived (void *p_data, UINT16 len)
{
    dbg ("%s:%d:%s\n", __FILE__, __LINE__, __FUNCTION__);

    data_received_t msg;
    msg.msg_type = DATA_RECEIVED;
    msg.len = len;

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

void 
WCL2CapConn::OnIncomingConnection () 
{
    dbg ("%s:%d:%s\n", __FILE__, __LINE__, __FUNCTION__);
    int msg = INCOMING_CONNECTION;
    send (this->threadfd, reinterpret_cast <char *> (&msg), sizeof (msg), 0);
}

void 
WCL2CapConn::OnConnectPendingReceived () 
{
    dbg ("%s:%d:%s\n", __FILE__, __LINE__, __FUNCTION__);
    // TODO
}
void 
WCL2CapConn::OnConnected () 
{
    dbg ("%s:%d:%s\n", __FILE__, __LINE__, __FUNCTION__);
    int msg = CONNECTED;
    send (this->threadfd, reinterpret_cast <char *> (&msg), sizeof (msg), 0);
}
void 
WCL2CapConn::OnCongestionStatus (BOOL is_congested) 
{
    dbg ("%s:%d:%s\n", __FILE__, __LINE__, __FUNCTION__);
    // TODO
}
void 
WCL2CapConn::OnRemoteDisconnected (UINT16 reason) 
{
    dbg ("%s:%d:%s\n", __FILE__, __LINE__, __FUNCTION__);

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

#pragma pack(pop)

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

typedef struct _WCL2CapConnPyObject WCL2CapConnPyObject;

struct _WCL2CapConnPyObject {
    PyObject_HEAD

    WCL2CapConn *l2cap;
};
PyDoc_STRVAR(wcl2capconn_doc, "CL2CapConn wrapper");

extern PyTypeObject wcl2capconn_type;

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

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

static PyObject *
wc_listen (PyObject *s, PyObject *a)
{
    WCL2CapConnPyObject *self = (WCL2CapConnPyObject*) s;
    dbg ("%s:%d:%s\n", __FILE__, __LINE__, __FUNCTION__);

    if (! PyObject_IsInstance (a, (PyObject*)&wcl2capif_type)) {
        return NULL;
    }
    WCL2CapIfPyObject *l2cap_if = (WCL2CapIfPyObject*) a;
    BOOL result;
    Py_BEGIN_ALLOW_THREADS;
    result = self->l2cap->Listen (l2cap_if->l2capif);
    Py_END_ALLOW_THREADS;
    dbg ("    listen: %d\n", result);
    if (result) {
        Py_RETURN_TRUE;
    } else {
        Py_RETURN_FALSE;
    }
}

static PyObject *
wc_accept (PyObject *s, PyObject *args)
{
    WCL2CapConnPyObject *self = (WCL2CapConnPyObject*) s;
    dbg ("%s:%d:%s\n", __FILE__, __LINE__, __FUNCTION__);

    UINT16 desired_mtu = L2CAP_DEFAULT_MTU;
    if (!PyArg_ParseTuple (args, "|H", &desired_mtu)) return NULL;
    BOOL result;
    Py_BEGIN_ALLOW_THREADS;
    dbg ("   calling accept (%p)\n", self->l2cap);
    result = self->l2cap->Accept ();
    dbg ("   accept: %d\n", result);
    Py_END_ALLOW_THREADS;
    if (result) {
        Py_RETURN_TRUE;
    } else {
        Py_RETURN_FALSE;
    }
}

static PyObject *
wc_connect (PyObject *s, PyObject *args)
{
    WCL2CapConnPyObject *self = (WCL2CapConnPyObject*) s;
    WCL2CapIfPyObject *l2cap_if = NULL;

    char *bdaddr_in = NULL;
    int bdaddr_in_len;
    UINT16 desired_mtu = L2CAP_DEFAULT_MTU;;

    if(!PyArg_ParseTuple (args, "O!s#|H", 
                &wcl2capif_type, &l2cap_if,
                &bdaddr_in, &bdaddr_in_len,
                &desired_mtu)) 
        return NULL;

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

    BD_ADDR bdaddr;
    memcpy (bdaddr, bdaddr_in, BD_ADDR_LEN);

    BOOL result;
    Py_BEGIN_ALLOW_THREADS;
    result = self->l2cap->Connect (l2cap_if->l2capif, bdaddr, desired_mtu);
    Py_END_ALLOW_THREADS;

    return PyInt_FromLong (result);
}

static PyObject *
wc_disconnect (PyObject *s)
{
    WCL2CapConnPyObject *self = (WCL2CapConnPyObject*) s;
    dbg ("%s:%d:%s\n", __FILE__, __LINE__, __FUNCTION__);
    Py_BEGIN_ALLOW_THREADS;
    self->l2cap->Disconnect ();
    Py_END_ALLOW_THREADS;
    Py_RETURN_NONE;
}

static PyObject *
wc_remote_bd_addr (PyObject *s)
{
    WCL2CapConnPyObject *self = (WCL2CapConnPyObject*) s;
    dbg ("%s:%d:%s\n", __FILE__, __LINE__, __FUNCTION__);

    tBT_CONN_STATS connstats;
    if (!self->l2cap->GetConnectionStats (&connstats)) {
        Py_RETURN_NONE;
    }
    if (!connstats.bIsConnected) Py_RETURN_NONE;
    return Py_BuildValue ("s#", &self->l2cap->m_RemoteBdAddr, BD_ADDR_LEN);
}

static PyObject *
wc_write (PyObject *s, PyObject *args)
{
    _WCL2CapConnPyObject *self = (_WCL2CapConnPyObject*) s;
    dbg ("%s:%d:%s\n", __FILE__, __LINE__, __FUNCTION__);

    char *data = NULL;
    int datalen;
    if (!PyArg_ParseTuple (args, "s#", &data, &datalen)) return NULL;

    UINT16 written = 0;
    BOOL result;

    Py_BEGIN_ALLOW_THREADS;
    result = self->l2cap->Write (data, datalen, &written);
    Py_END_ALLOW_THREADS;

    return Py_BuildValue ("II", result, written);
}

static PyObject *
wc_get_connection_stats (PyObject *s)
{
    _WCL2CapConnPyObject *self = (_WCL2CapConnPyObject*) s;
    dbg ("%s:%d:%s\n", __FILE__, __LINE__, __FUNCTION__);

    tBT_CONN_STATS stats;
    memset (&stats, 0, sizeof (stats));
    BOOL result;
    Py_BEGIN_ALLOW_THREADS;
    result = self->l2cap->GetConnectionStats (&stats);
    Py_END_ALLOW_THREADS;
    return Py_BuildValue ("iIiIII", result, 
            stats.bIsConnected, stats.Rssi, stats.BytesSent,
            stats.BytesRcvd, stats.Duration);
}

static PyObject *
wc_switch_role (PyObject *s, PyObject *arg)
{
    _WCL2CapConnPyObject *self = (_WCL2CapConnPyObject*) s;
    dbg ("%s:%d:%s\n", __FILE__, __LINE__, __FUNCTION__);

    MASTER_SLAVE_ROLE new_role = 
        static_cast <MASTER_SLAVE_ROLE> (PyInt_AsLong (arg));
    BOOL result = self->l2cap->SwitchRole (new_role);
    return PyInt_FromLong (result);
}

static PyObject *
wc_set_link_supervision_timeout (PyObject *s, PyObject *arg)
{
    _WCL2CapConnPyObject *self = (_WCL2CapConnPyObject*) s;
    dbg ("%s:%d:%s\n", __FILE__, __LINE__, __FUNCTION__);

    UINT16 timeoutSlot = static_cast <UINT16> (PyInt_AsLong (arg));
    BOOL result = self->l2cap->SetLinkSupervisionTimeOut (timeoutSlot);
    return PyInt_FromLong (result);
}

static PyMethodDef wcl2capconn_methods[] = {
    { "get_sockport", (PyCFunction) get_sockport, METH_NOARGS, "" },
    { "accept_client", (PyCFunction) accept_client, METH_NOARGS, "" },
    { "listen", (PyCFunction) wc_listen, METH_O, "" },
    { "accept", (PyCFunction) wc_accept, METH_VARARGS, "" },
    { "connect", (PyCFunction) wc_connect, METH_VARARGS, "" },
    { "disconnect", (PyCFunction) wc_disconnect, METH_NOARGS, "" },
    { "remote_bd_addr", (PyCFunction) wc_remote_bd_addr, METH_NOARGS, "" },
    { "write", (PyCFunction)wc_write, METH_VARARGS, "" },
    { "get_connection_stats", (PyCFunction)wc_get_connection_stats, 
        METH_NOARGS, "" },
    { "switch_role", (PyCFunction)wc_switch_role, METH_O, "" },
    { "set_link_supervision_timeout", 
        (PyCFunction)wc_set_link_supervision_timeout, METH_O, "" },
    { NULL, NULL }
};

static PyObject *
wcl2capconn_repr(WCL2CapConnPyObject *s)
{
    return PyString_FromString("_WCL2CapConn object");
}

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

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

static void
wcl2capconn_dealloc(WCL2CapConnPyObject *self)
{
    if (self->l2cap) {
        delete self->l2cap;
        self->l2cap = NULL;
    }
    self->ob_type->tp_free((PyObject*)self);
}

int
wcl2capconn_initobj(PyObject *s, PyObject *args, PyObject *kwds)
{
    WCL2CapConnPyObject *self = (WCL2CapConnPyObject *)s;
    self->l2cap = new WCL2CapConn (s);
    return 0;
}

/* Type object for socket objects. */
PyTypeObject wcl2capconn_type = {
    PyObject_HEAD_INIT(0)   /* Must fill in type value later */
    0,                  /* ob_size */
    "_widcomm._WCL2CapConn",            /* tp_name */
    sizeof(WCL2CapConnPyObject),     /* tp_basicsize */
    0,                  /* tp_itemsize */
    (destructor)wcl2capconn_dealloc,     /* tp_dealloc */
    0,                  /* tp_print */
    0,                  /* tp_getattr */
    0,                  /* tp_setattr */
    0,                  /* tp_compare */
    (reprfunc)wcl2capconn_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 */
    wcl2capconn_doc,               /* tp_doc */
    0,                  /* tp_traverse */
    0,                  /* tp_clear */
    0,                  /* tp_richcompare */
    0,                  /* tp_weaklistoffset */
    0,                  /* tp_iter */
    0,                  /* tp_iternext */
    wcl2capconn_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 */
    wcl2capconn_initobj,             /* tp_init */
    PyType_GenericAlloc,            /* tp_alloc */
    wcl2capconn_new,             /* tp_new */
    PyObject_Del,               /* tp_free */
};