Initial commit.
[qzeecontrol] / btconnector.h
1 #ifndef BTCONNECTOR_H
2 #define BTCONNECTOR_H
3
4 #include <QObject>
5 #include <QtConnectivity/QBluetoothAddress>
6 #include <QtConnectivity/QBluetoothSocket>
7
8 QTM_USE_NAMESPACE
9 class BtConnector : public QObject
10 {
11     Q_OBJECT
12 public:
13     explicit BtConnector(QObject *parent = 0){qDebug("BtConnector Constructor");}
14     ~BtConnector(){if(socket != NULL) delete socket;}
15
16     Q_INVOKABLE void connect(QString address, int port){
17         qDebug("Trying to connect to: %s--%d", address.toUtf8().constData(), port);
18
19         if(socket != NULL)
20             delete socket;
21         socket = new QBluetoothSocket(QBluetoothSocket::RfcommSocket);
22         QObject::connect(socket, SIGNAL(connected()), this, SIGNAL(connected()));
23         QObject::connect(socket, SIGNAL(disconnected()), this, SIGNAL(disconnected()));
24         QObject::connect(socket, SIGNAL(error(QBluetoothSocket::SocketError)), this, SIGNAL(error(QBluetoothSocket::SocketError)));
25
26         qDebug("Connecting...");
27         socket->connectToService(QBluetoothAddress(address), port);
28         qDebug("Connected.");
29
30         QObject::connect(socket, SIGNAL(readyRead()), this, SLOT(readData()));
31     }
32
33 public slots:
34     void disconnect(){
35         if(socket == NULL)
36             return;
37
38         if(socket->isOpen())
39             socket->close();
40
41         delete socket;
42     }
43
44 signals:
45     void connected();
46     void disconnected();
47     void error(QBluetoothSocket::SocketError errorCode);
48
49     void stickMoved(int x, int y);
50
51 private slots:
52     void readData(){
53         qDebug("readData...");
54         QByteArray data = socket->readAll();
55         qDebug("read %d bytes.", data.size());
56
57         for(int i=0; i < data.size(); i++){
58             qDebug("%d: %d", i, ((signed char)data.at(i)));
59         }
60     }
61
62 private:
63     QBluetoothSocket *socket;
64
65 };
66
67 #endif // BTCONNECTOR_H