summaryrefslogtreecommitdiff
path: root/noncore/settings/networksettings2/opietooth2/OTHCISocket.cpp
blob: 1997b4478225d106d0eb1ad92bcb70c1c7dbac42 (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
//-*-c++-*-
/***************************************************************************
 *   Copyright (C) 2003 by Fred Schaettgen                                 *
 *   kdebluetooth@schaettgen.de                                            *
 *                                                                         *
 *   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 of the License, or     *
 *   (at your option) any later version.                                   *
 ***************************************************************************/

#include <qbuffer.h>
#include <qtimer.h>
#include <qdatastream.h>
#include <opie2/odebug.h>

#include <bluezlib.h>

// #include "deviceaddress.h"
#include <OTHCISocket.h>
#include <OTDriver.h>

using namespace Opietooth2;

OTHCISocket::OTHCISocket( OTDriver * D ) :
                            QObject( D, D->devname() ) {
    BStatusSet = false;
    Driver = D;
    HCIReadNotifier = 0;
}

OTHCISocket::~OTHCISocket() {
    close();
}

void OTHCISocket::close() {
    odebug << "OTHCISocket::close()" << oendl;
    if( HCIReadNotifier ) {
        delete HCIReadNotifier;
    }

    if( HCISocket.isValid() ) {
        HCISocket.close();
    }
}

bool OTHCISocket::open() {

    odebug << "OTHCISocket::open()" << oendl;
    int s;

    s = ::socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI);

    if (s < 0) {
      emit error( tr( "Error creating socket on %1 : %2 %3").
                    arg( Driver->devname() ).
                    arg( errno ).
                    arg( strerror(errno) )
                );
      return false;
    }

    /* Bind socket to the HCI device */
    struct sockaddr_hci sa;
    sa.hci_family = AF_BLUETOOTH;
    sa.hci_dev = Driver->devId();
    if (bind(s, (struct sockaddr *)&sa, sizeof(sa)) < 0) {
      ::close(s);
      emit error( tr( "Error binding to socket to %1 : %2 %3").
                    arg( Driver->devname() ).
                    arg( errno ).
                    arg( strerror(errno) )
                );
      return false;
    }

    struct hci_filter flt;
    hci_filter_clear(&flt);
    hci_filter_set_ptype(HCI_EVENT_PKT, &flt);
    hci_filter_all_events(&flt);
    if( setsockopt(s, SOL_HCI, HCI_FILTER, &flt, sizeof(flt)) < 0 ) {
      ::close(s);
      emit error( tr( "HCI filter setup failed on %1 : %2 %3").
                    arg( Driver->devname() ).
                    arg( errno ).
                    arg( strerror(errno) )
                );
      return false;
    }

    if( HCIReadNotifier ) {
      delete HCIReadNotifier;
    }

    HCISocket.setSocket(s, QSocketDevice::Datagram);
    HCIReadNotifier = new QSocketNotifier(
                  s, QSocketNotifier::Read, this);

    connect( HCIReadNotifier, 
             SIGNAL(activated(int)),
             this, 
             SLOT(slotSocketActivated())
           );

    //connect(hciSocket, SIGNAL(error(int)),
    //    this, SLOT(slotSocketError(int)));
    //connect(hciSocket, SIGNAL(connectionClosed()),
    //    this, SLOT(slotConnectionClosed()));
    //hciSocket->setSocket(s);

    return true;
}

void OTHCISocket::slotSocketError(int e) {
    close();
    emit error( tr( "HCI socket error 0x%1 on %1 : %2 %3").
                    arg(e,2,16).
                    arg( Driver->devname() ).
                    arg( errno ).
                    arg( strerror(errno) )
                );
}

void OTHCISocket::slotSocketActivated() {

    QSocketDevice::Error err = HCISocket.error();

    if( (err == QSocketDevice::NoError ) && 
        ( HCISocket.isValid() ) ) {
      //kdDebug() << "HCI socket ready read." << endl;

      unsigned char buf[512];
      int psize = HCISocket.readBlock((char*)buf, 512);

      if (psize <= 0) {
        slotSocketError(HCISocket.error());
        HCISocket.close();
        return;
      }

      //unsigned char packetType = buf[0];
      unsigned char eventCode = buf[1];
      unsigned char len = buf[2];

      if (psize-3 == len) {

        QByteArray databuf;
        databuf.duplicate((char*)(buf+3), len);
        emit event(eventCode, databuf);
        if (eventCode == EVT_CMD_STATUS) {
          updateStatus( databuf );
        }
      } else {
        odebug << "Error reading hci packet: packetSize("
              << psize
              << ")-3 != dataSize("
              << len
              << ")" 
              << oendl;
      }
    } else if (err == QSocketDevice::NoError) {
      slotConnectionClosed();
    } else {
        HCISocket.close();
        slotSocketError(err);
    }
}

void OTHCISocket::updateStatus(const QByteArray& data) {

    QDataStream stream(data, IO_ReadOnly);
    stream.setByteOrder(QDataStream::LittleEndian);
    Q_UINT8 status, dummy;
    Q_UINT16 opcode;

    BStatusSet = true;

    stream >> status >> dummy >> opcode;
    //kdDebug() << "updatestatus opcode=" << uint32_t(opcode) << endl;
    LastStatus = status;
    LastStatusOgf = cmd_opcode_ogf(opcode);
    LastStatusOcf = cmd_opcode_ocf(opcode);
}

void OTHCISocket::slotConnectionClosed() {
    odebug << "HCI connection closed." << oendl;
    emit connectionClosed();
}

void OTHCISocket::readEvent() {

    if (HCIReadNotifier) {
        slotSocketActivated();
    }
}

bool OTHCISocket::sendCommand( unsigned char ogf,
                               unsigned short ocf, 
                               QByteArray buf
                             ) {
    QBuffer packet;
    QDataStream stream(&packet);

    stream.setByteOrder(QDataStream::LittleEndian);
    packet.open(IO_WriteOnly);

    if (buf.size() > 255) return false;

    //kdDebug() << "sendCommand. ogf=" << ogf << " ocf=" << ocf << endl;
    Q_UINT16 opcode = cmd_opcode_pack(ogf, ocf);
    Q_UINT8 pType = HCI_COMMAND_PKT;
    Q_UINT8 buflen = buf.size();

    stream << pType << opcode << buflen;
    stream.writeRawBytes(buf.data(), buflen);
    packet.close();
    HCISocket.writeBlock((const char*)packet.buffer(), 
                         packet.buffer().size());
    return true;
}

bool OTHCISocket::readStatus( unsigned char ogf, 
                              unsigned short ocf, 
                              int *status, 
                              int timeout_ms) {
    QTimer timer;

    timer.start(timeout_ms, true);
    BStatusSet = false;

    while (timer.isActive() && HCISocket.isValid()) {

        odebug << "OTHCISocket::readStatus()" << oendl;
        bool timeout = false;

        if( HCISocket.bytesAvailable() == 0) {
          int rv = HCISocket.waitForMore(timeout_ms);
          timeout = (rv == 0);
        }

        if (!timeout) {
          slotSocketActivated();
        }

        if( BStatusSet == true && 
            ogf == LastStatusOgf && 
            ocf == LastStatusOcf) {
            *status = LastStatus;
            odebug << "OTHCISocket::readStatus(ogf="
                  << ogf
                  << ",ocf="
                  << ocf
                  << ",timeout="
                  << LastStatus
                  << ")"
                  << oendl;
            return true;
        }
    }

    odebug << "OTHCISocket::readStatus(ogf="
          << ogf
          << ",ocf="
          << ocf
          << ",timeout="
          << LastStatus
          << ") : timeout "
          << oendl;
    return false;
}

int OTHCISocket::socket() {
    return HCISocket.socket();
}