File: rfcommport.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 (414 lines) | stat: -rw-r--r-- 11,824 bytes parent folder | download | duplicates (4)
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
#include <windows.h>
#include <Python.h>

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

#include "rfcommport.hpp"

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

WCRfCommPort::WCRfCommPort (PyObject *pyobj) 
    : CRfCommPort () 
{
    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);
}

WCRfCommPort::~WCRfCommPort () 
{
    dbg ("%s:%d:%s\n", __FILE__, __LINE__, __FUNCTION__);
    closesocket (this->threadfd);
}

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

void
WCRfCommPort::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);
}

typedef struct {
    int msg_type;
    unsigned int event_code;
} event_received_msg_t;

void
WCRfCommPort::OnEventReceived (UINT32 event_code)
{
    dbg ("%s:%d event %u received\n", __FILE__, __LINE__, event_code);

    event_received_msg_t msg;
    msg.msg_type = EVENT_RECEIVED;
    msg.event_code = event_code;

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

#pragma pack(pop)

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

typedef struct _WCRfCommPortPyObject WCRfCommPortPyObject;

struct _WCRfCommPortPyObject {
    PyObject_HEAD

    WCRfCommPort *rfcp;
};
PyDoc_STRVAR(wcrfcommport_doc, "CRfCommPort wrapper");

extern PyTypeObject wcrfcommport_type;

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

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

static PyObject *
wc_open_server (PyObject *s, PyObject *args)
{
    WCRfCommPortPyObject *self = (WCRfCommPortPyObject*) s;

    UINT8 scn;
    UINT16 desired_mtu = RFCOMM_DEFAULT_MTU;
    if (!PyArg_ParseTuple (args, "B|H", &scn, &desired_mtu)) return NULL;

    CRfCommPort::PORT_RETURN_CODE result = 
        self->rfcp->OpenServer (scn, desired_mtu);

    return PyInt_FromLong (result);
}

static PyObject *
wc_open_client (PyObject *s, PyObject *args)
{
    UINT8 scn;
    char *bdaddr_in = NULL;
    int bdaddr_in_len;
    UINT16 desired_mtu = RFCOMM_DEFAULT_MTU;

    if(!PyArg_ParseTuple (args, "Bs#|H", &scn, &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);

    _WCRfCommPortPyObject *self = (_WCRfCommPortPyObject*) s;

    CRfCommPort::PORT_RETURN_CODE result;
    Py_BEGIN_ALLOW_THREADS;
    result = self->rfcp->OpenClient (scn, bdaddr, desired_mtu);
    Py_END_ALLOW_THREADS;

    return PyInt_FromLong (result);
}

static PyObject *
wc_is_connected (PyObject *s)
{
    _WCRfCommPortPyObject *self = (_WCRfCommPortPyObject*) s;
    BD_ADDR remote_addr;
    if (self->rfcp->IsConnected (&remote_addr)) {
        return Py_BuildValue ("s#", &remote_addr, BD_ADDR_LEN);
    } else {
        Py_RETURN_NONE;
    }
}

static PyObject *
wc_close (PyObject *s)
{
    dbg ("%s:%d:%s\n", __FILE__, __LINE__, __FUNCTION__);
    _WCRfCommPortPyObject *self = (_WCRfCommPortPyObject*) s;
    self->rfcp->Close ();
    Py_RETURN_NONE;
}

static PyObject *
wc_set_flow_enabled (PyObject *s, PyObject *arg)
{
    _WCRfCommPortPyObject *self = (_WCRfCommPortPyObject*) s;
    int enable = PyInt_AsLong (arg);
    CRfCommPort::PORT_RETURN_CODE result = self->rfcp->SetFlowEnabled (enable);
    return PyInt_FromLong (result);
}

static PyObject *
wc_set_modem_signal (PyObject *s, PyObject *arg)
{
    _WCRfCommPortPyObject *self = (_WCRfCommPortPyObject*) s;
    UINT8 signal = static_cast <UINT8> (PyInt_AsLong (arg));
    CRfCommPort::PORT_RETURN_CODE result = self->rfcp->SetModemSignal (signal);
    return PyInt_FromLong (result);
}

static PyObject *
wc_get_modem_status (PyObject *s)
{
    _WCRfCommPortPyObject *self = (_WCRfCommPortPyObject*) s;
    UINT8 signal;
    CRfCommPort::PORT_RETURN_CODE result = self->rfcp->GetModemStatus (&signal);
    return Py_BuildValue ("ii", result, signal);
}

static PyObject *
wc_send_error (PyObject *s, PyObject *arg)
{
    _WCRfCommPortPyObject *self = (_WCRfCommPortPyObject*) s;
    UINT8 errors = static_cast <UINT8> (PyInt_AsLong (arg));
    CRfCommPort::PORT_RETURN_CODE result = self->rfcp->SendError (errors);
    return PyInt_FromLong (result);
}

static PyObject *
wc_purge (PyObject *s, PyObject *arg)
{
    _WCRfCommPortPyObject *self = (_WCRfCommPortPyObject*) s;
    UINT8 purge_flags = static_cast <UINT8> (PyInt_AsLong (arg));
    CRfCommPort::PORT_RETURN_CODE result = self->rfcp->Purge (purge_flags);
    return PyInt_FromLong (result);
}

static PyObject *
wc_write (PyObject *s, PyObject *args)
{
    _WCRfCommPortPyObject *self = (_WCRfCommPortPyObject*) s;

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

    UINT16 written = 0;
    CRfCommPort::PORT_RETURN_CODE status;

    Py_BEGIN_ALLOW_THREADS;
    status = self->rfcp->Write (data, datalen, &written);
    Py_END_ALLOW_THREADS;

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

static PyObject *
wc_get_connection_stats (PyObject *s)
{
    _WCRfCommPortPyObject *self = (_WCRfCommPortPyObject*) s;
    tBT_CONN_STATS stats;
    memset (&stats, 0, sizeof (stats));
    CRfCommPort::PORT_RETURN_CODE result = 
        self->rfcp->GetConnectionStats (&stats);

    return Py_BuildValue ("iIiIII", result, 
            stats.bIsConnected,
            stats.Rssi,
            stats.BytesSent,
            stats.BytesRcvd,
            stats.Duration);
}

static PyObject *
wc_switch_role (PyObject *s, PyObject *arg)
{
    _WCRfCommPortPyObject *self = (_WCRfCommPortPyObject*) s;
    MASTER_SLAVE_ROLE new_role = 
        static_cast <MASTER_SLAVE_ROLE> (PyInt_AsLong (arg));
    BOOL result = self->rfcp->SwitchRole (new_role);
    return PyInt_FromLong (result);
}

static PyObject *
wc_set_link_supervision_timeout (PyObject *s, PyObject *arg)
{
    _WCRfCommPortPyObject *self = (_WCRfCommPortPyObject*) s;
    UINT16 timeoutSlot = static_cast <UINT16> (PyInt_AsLong (arg));
    CRfCommPort::PORT_RETURN_CODE result = 
        self->rfcp->SetLinkSupervisionTimeOut (timeoutSlot);
    return PyInt_FromLong (result);
}

static PyMethodDef wcrfcommport_methods[] = {
    { "get_sockport", (PyCFunction) get_sockport, METH_NOARGS, "" },
    { "accept_client", (PyCFunction) accept_client, METH_NOARGS, "" },
    { "open_server", (PyCFunction)wc_open_server, METH_VARARGS, "" },
    { "open_client", (PyCFunction)wc_open_client, METH_VARARGS, "" },
    { "close", (PyCFunction)wc_close, METH_NOARGS, "" },
    { "is_connected", (PyCFunction)wc_is_connected, METH_NOARGS, "" },
    { "set_flow_enabled", (PyCFunction)wc_set_flow_enabled, METH_O, "" },
    { "set_modem_signal", (PyCFunction)wc_set_modem_signal, METH_O, "" },
    { "get_modem_status", (PyCFunction)wc_get_modem_status, METH_NOARGS, "" },
    { "send_error", (PyCFunction)wc_send_error, METH_O, "" },
    { "purge", (PyCFunction)wc_purge, METH_O, "" },
    { "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 *
wcrfcommport_repr(WCRfCommPortPyObject *s)
{
    return PyString_FromString("_WCRfCommPort object");
}

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

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

static void
wcrfcommport_dealloc(WCRfCommPortPyObject *self)
{
    dbg ("%s:%d:%s\n", __FILE__, __LINE__, __FUNCTION__);
    if (self->rfcp) {
        delete self->rfcp;
        self->rfcp = NULL;
    }
    self->ob_type->tp_free((PyObject*)self);
}

int
wcrfcommport_initobj(PyObject *s, PyObject *args, PyObject *kwds)
{
    WCRfCommPortPyObject *self = (WCRfCommPortPyObject *)s;
    self->rfcp = new WCRfCommPort (s);
    return 0;
}

/* Type object for socket objects. */
PyTypeObject wcrfcommport_type = {
    PyObject_HEAD_INIT(0)   /* Must fill in type value later */
    0,                  /* ob_size */
    "_widcomm._WCRfCommPort",            /* tp_name */
    sizeof(WCRfCommPortPyObject),     /* tp_basicsize */
    0,                  /* tp_itemsize */
    (destructor)wcrfcommport_dealloc,     /* tp_dealloc */
    0,                  /* tp_print */
    0,                  /* tp_getattr */
    0,                  /* tp_setattr */
    0,                  /* tp_compare */
    (reprfunc)wcrfcommport_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 */
    wcrfcommport_doc,               /* tp_doc */
    0,                  /* tp_traverse */
    0,                  /* tp_clear */
    0,                  /* tp_richcompare */
    0,                  /* tp_weaklistoffset */
    0,                  /* tp_iter */
    0,                  /* tp_iternext */
    wcrfcommport_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 */
    wcrfcommport_initobj,             /* tp_init */
    PyType_GenericAlloc,            /* tp_alloc */
    wcrfcommport_new,             /* tp_new */
    PyObject_Del,               /* tp_free */
};