summaryrefslogtreecommitdiff
path: root/libsowatchbt/bluetoothwatch.cpp
blob: d977b677a2139d7c426d1f7c127646114c4a721b (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
#include "bluetoothwatch.h"

using namespace sowatch;
QTM_USE_NAMESPACE

const int BluetoothWatch::connectRetryTimes[] = {
	5, 10, 30, 60, 120, 300
};

BluetoothWatch::BluetoothWatch(const QBluetoothAddress& address, QObject *parent)
	: Watch(parent),
      _localDev(new QBluetoothLocalDevice(this)),
      _address(address),
	  _socket(0),
      _connected(false),
      _connectRetries(0),
	  _connectTimer(new QTimer(this)),
	  _connectAlignedTimer(new QSystemAlignedTimer(this))
{
	_connectTimer->setSingleShot(true);
	_connectAlignedTimer->setSingleShot(true);

	connect(_connectTimer, SIGNAL(timeout()), SLOT(handleConnectTimer()));
	connect(_connectAlignedTimer, SIGNAL(timeout()), SLOT(handleConnectTimer()));
	connect(_localDev, SIGNAL(hostModeStateChanged(QBluetoothLocalDevice::HostMode)),
	        SLOT(handleLocalDevModeChanged(QBluetoothLocalDevice::HostMode)));

	// Check to see if we can connect right away
	if (_localDev->isValid() &&
	        _localDev->hostMode() != QBluetoothLocalDevice::HostPoweredOff) {
		// Do an initial connection attempt after a short delay
		// (To give time for other plugins to initialize, etc.)
		scheduleConnect();
	} else {
		qDebug() << "Not starting MetaWatch connection because BT is off";
	}
}

BluetoothWatch::~BluetoothWatch()
{
	if (_socket) {
		_socket->close();
		delete _socket;
	}
}

bool BluetoothWatch::isConnected() const
{
	return _connected;
}

void BluetoothWatch::scheduleConnect()
{
	if (_connected ||
	        _connectAlignedTimer->isActive() || _connectTimer->isActive()) {
		// Already connected or already scheduled to connect.
		return;
	}

	_connectRetries = 0;
	_connectTimer->start(100);
}

void BluetoothWatch::scheduleRetryConnect()
{
	if (_connected ||
	        _connectAlignedTimer->isActive() || _connectTimer->isActive()) {
		// Already connected or already scheduled to connect.
		return;
	}

	int timeToNextRetry;
	if (_connectRetries >= connectRetryTimesSize) {
		timeToNextRetry = connectRetryTimes[connectRetryTimesSize - 1];
	} else {
		timeToNextRetry = connectRetryTimes[_connectRetries];
		_connectRetries++; // Increase the number of connection attemps
	}

	qDebug() << "Backing off for" << timeToNextRetry << "seconds for next retry";
	_connectAlignedTimer->start(timeToNextRetry / 2, timeToNextRetry * 2);
	if (_connectAlignedTimer->lastError() != QSystemAlignedTimer::NoError) {
		// Hopefully a future version of QSystemAlignedTimer implements this fallback
		// For now, we have to do it ourselves.
		qDebug() << "Note: using plain QTimer for retry";
		_connectTimer->start(timeToNextRetry * 1000);
	}
}

void BluetoothWatch::unscheduleConnect()
{
	_connectAlignedTimer->stop();
	_connectTimer->stop();
}

void BluetoothWatch::connectToWatch()
{
	delete _socket; //Delete socket from previous connect if any.
	_socket = new QBluetoothSocket(QBluetoothSocket::RfcommSocket);

	connect(_socket, SIGNAL(connected()), SLOT(handleSocketConnected()));
	connect(_socket, SIGNAL(disconnected()), SLOT(handleSocketDisconnected()));
	connect(_socket, SIGNAL(readyRead()), SLOT(handleSocketData()));
	connect(_socket, SIGNAL(error(QBluetoothSocket::SocketError)),
			SLOT(handleSocketError(QBluetoothSocket::SocketError)));
	connect(_socket, SIGNAL(stateChanged(QBluetoothSocket::SocketState)),
			SLOT(handleSocketState(QBluetoothSocket::SocketState)));

	_socket->connectToService(_address, 1, QIODevice::ReadWrite | QIODevice::Unbuffered);
}

void BluetoothWatch::handleConnectTimer()
{
	connectToWatch();
}

void BluetoothWatch::handleLocalDevModeChanged(QBluetoothLocalDevice::HostMode state)
{
	qDebug() << "Local bluetooth device mode changed to" << state;
	if (state == QBluetoothLocalDevice::HostPoweredOff) {
		// Host bluetooth was powered down
		// Assume the socket has been disconnected
		handleSocketDisconnected();
		// Cancel any pending connection attempts
		unscheduleConnect();
	} else {
		// Host bluetooth might have been powered up
		if (!_connected) {
			scheduleConnect();
		}
	}
}

void BluetoothWatch::handleSocketConnected()
{
	if (!_connected) {
		qDebug() << "connected";

		_connected = true;
		_connectRetries = 0;

		setupBluetoothWatch();

		emit connected();
	}
}

void BluetoothWatch::handleSocketDisconnected()
{
	// Signal disconnection if necessary
	if (_connected) {
		qDebug() << "disconnected";

		_connected = false;
		desetupBluetoothWatch();

		emit disconnected();
	}

	// Setup reconnection attempt if necessary
	if (_localDev->hostMode() != QBluetoothLocalDevice::HostPoweredOff) {
		scheduleRetryConnect();
	}
}

void BluetoothWatch::handleSocketError(QBluetoothSocket::SocketError error)
{
	qWarning() << "Socket error:" << error;
	// Seems that sometimes a disconnection event may not be generated.
	handleSocketDisconnected();
}

void BluetoothWatch::handleSocketState(QBluetoothSocket::SocketState state)
{
	qDebug() << "socket is in" << state;
}