summaryrefslogtreecommitdiff
path: root/saltoqd/toqconnection.cpp
blob: b5265da9348ddc6791662b3ab6b9f689b7bd24b8 (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
275
276
#include <zlib.h>
#include <QtCore/QtEndian>
#include <QtCore/QMetaEnum>
#include <QtDebug>

#include "toqconnection.h"

static const QBluetoothUuid LISTEN_UUID(QLatin1String("00000001-476D-42C4-BD11-9D377C45694F"));
static const int HEADER_LENGTH = 10;
static const int FIRST_CONNECTION_INTERVAL = 10 * 1000;
// Because the watch will actually try to reconnect to us frequently,
// we can afford to set a relaxed interval here.
static const int RETRY_CONNECTION_INTERVAL = 10 * 60 * 1000;

ToqConnection::ToqConnection(QObject *parent) :
	QObject(parent),
	_server(new QBluetoothServer(QBluetoothServiceInfo::RfcommProtocol, this)),
	_socket(0),
	_reconnectTimer(new QTimer(this)),
	_lastTransactionId(0)
{
	connect(_reconnectTimer, &QTimer::timeout,
			this, &ToqConnection::tryConnect);

	_reconnectTimer->setTimerType(Qt::VeryCoarseTimer);
	_reconnectTimer->setSingleShot(true);

	connect(_server, &QBluetoothServer::newConnection,
			this, &ToqConnection::handleServerConnection);

	QBluetoothServiceInfo service = _server->listen(LISTEN_UUID, "PHubCommServer");
	if (service.isValid()) {
		qDebug() << "Started listening on channel" << service.serverChannel();
	} else {
		qWarning() << "Could not register the server service";
	}
}

ToqConnection::Message::Message(Endpoint source, Endpoint destination, quint16 transactionId, quint32 type, const QJsonDocument &payload)
	: source(source), destination(destination), transactionId(transactionId), type(type),
	  payload(payload.toJson(QJsonDocument::Compact))
{

}

QJsonDocument ToqConnection::Message::toJson() const
{
	QJsonDocument doc;
	QJsonParseError error;

	doc = QJsonDocument::fromJson(payload, &error);
	if (error.error) {
		qWarning() << "Failure while parsing message JSON payload: " << error.errorString();
	}

	return doc;
}

QString ToqConnection::nameOfEndpoint(Endpoint ep)
{
	int index = staticMetaObject.indexOfEnumerator("CoreEndpoints");
	QMetaEnum epEnum = staticMetaObject.enumerator(index);
	const char * ret = epEnum.valueToKey(ep);
	if (ret) {
		return QString::fromLatin1(ret);
	} else {
		return QString::number(ep);
	}
}

quint32 ToqConnection::checksum(const QByteArray &data)
{
	uLong crc = crc32(0L, Z_NULL, 0);
	crc = crc32(crc, reinterpret_cast<const Bytef*>(data.constData()), data.size());
	return crc;
}

quint32 ToqConnection::checksum(QIODevice *dev)
{
	uLong crc = crc32(0L, Z_NULL, 0);
	char buffer[4 * 1024];
	qint64 read;
	while ((read = dev->read(buffer, sizeof(buffer))) > 0) {
		crc = crc32(crc, reinterpret_cast<const Bytef*>(&buffer[0]), read);
	}
	return crc;
}

void ToqConnection::setAddress(const QBluetoothAddress &address)
{
	if (address != _address) {
		_address = address;
		if (isConnected()) {
			_socket->disconnectFromService();
		} else {
			_reconnectTimer->start(FIRST_CONNECTION_INTERVAL);
		}
	}
}

quint16 ToqConnection::newTransactionId()
{
	if (_lastTransactionId >= 0xFFFA) {
		// The last transaction ids (as well as 0) seem to be reserved
		// Avoid using them
		_lastTransactionId = 0;
	}

	return ++_lastTransactionId;
}

void ToqConnection::sendMessage(const Message &msg)
{
	if (_socket) {
		_socket->write(packMessage(msg));
	} else {
		qWarning() << "Discarding message because connection is broken";
	}
}

void ToqConnection::disconnectFromDevice()
{
	if (_socket) {
		_socket->disconnectFromService();
	} else {
		qWarning() << "Not connected";
	}
}

ToqConnection::Message ToqConnection::unpackMessage(const QByteArray &data)
{
	Message msg;

	Q_ASSERT(data.length() >= HEADER_LENGTH);
	const uchar *header = reinterpret_cast<const uchar*>(data.constData());

	quint16 message_length = qFromBigEndian<quint16>(&header[2]);
	Q_ASSERT(data.length() == message_length + HEADER_LENGTH - 4);
	msg.source = header[0];
	msg.destination = header[1];
	msg.transactionId = qFromBigEndian<quint16>(&header[4]);
	msg.type = qFromBigEndian<quint32>(&header[6]);
	msg.payload = data.mid(HEADER_LENGTH);

	return msg;
}

QByteArray ToqConnection::packMessage(const Message &msg)
{
	uchar header[HEADER_LENGTH];

	header[0] = msg.source;
	header[1] = msg.destination;
	qToBigEndian<quint16>(msg.payload.length() + 4, &header[2]);
	qToBigEndian<quint16>(msg.transactionId, &header[4]);
	qToBigEndian<quint32>(msg.type, &header[6]);

	QByteArray data;
	data.reserve(HEADER_LENGTH + msg.payload.length());
	data.append(reinterpret_cast<char*>(&header[0]), HEADER_LENGTH);
	data.append(msg.payload);

	return data;
}

void ToqConnection::setSocket(QBluetoothSocket *socket)
{
	Q_ASSERT(!_socket);
	_socket = socket;
	connect(_socket, &QBluetoothSocket::connected,
			this, &ToqConnection::handleSocketConnected);
	connect(_socket, &QBluetoothSocket::disconnected,
			this, &ToqConnection::handleSocketDisconnected);
	connect(_socket, (void (QBluetoothSocket::*)(QBluetoothSocket::SocketError))&QBluetoothSocket::error,
			this, &ToqConnection::handleSocketError);
	connect(_socket, &QBluetoothSocket::readyRead,
			this, &ToqConnection::handleSocketData);
	if (_socket->state() == QBluetoothSocket::ConnectedState) {
		handleSocketConnected();
	}
}

void ToqConnection::tryConnect()
{
	Q_ASSERT(!_socket);

	QBluetoothSocket *socket =
			new QBluetoothSocket(QBluetoothServiceInfo::RfcommProtocol, this);
	setSocket(socket);

	qDebug() << "Connecting to" << _address.toString();

	socket->connectToService(_address, 1);
}

void ToqConnection::handleServerConnection()
{
	qDebug() << "Got a connection from the server";
	QBluetoothSocket *socket = _server->nextPendingConnection();
	if (_socket) {
		// If we have an existing socket, give priority to the received one.
		qDebug() << "Terminating current connection first";
		_socket->disconnectFromService();
		if (_socket) {
			_socket->deleteLater();
			_socket = 0;
		}
	}
	setSocket(socket);
}

void ToqConnection::handleSocketConnected()
{
	qDebug() << "Connected";
	Q_ASSERT(_socket);
	_reconnectTimer->stop();
	emit connected();
	emit connectedChanged();
}

void ToqConnection::handleSocketDisconnected()
{
	if (_socket) {
		qDebug() << "Disconnected";
		Q_ASSERT(_socket->state() == QBluetoothSocket::UnconnectedState ||
				 _socket->state() == QBluetoothSocket::ClosingState);
		_socket->deleteLater();
		_socket = 0;
		if (!_address.isNull()) {
			_reconnectTimer->start(RETRY_CONNECTION_INTERVAL);
		}
		emit disconnected();
		emit connectedChanged();
	}
}

void ToqConnection::handleSocketError(QBluetoothSocket::SocketError error)
{
	if (_socket) {
		qWarning() << error << _socket->errorString();
		_socket->disconnectFromService();
	}
}

void ToqConnection::handleSocketData()
{
	// Keep attempting to read messages as long as at least a header is present
	while (_socket->bytesAvailable() >= HEADER_LENGTH) {
		// Take a look at the header, but do not remove it from the socket input buffer.
		// We will only remove it once we're sure the entire packet is in the buffer.
		uchar header[HEADER_LENGTH];
		_socket->peek(reinterpret_cast<char*>(header), HEADER_LENGTH);

		quint16 message_length = qFromBigEndian<quint16>(&header[2]);

		// Sanity checks on the message_length
		if (message_length == 0) {
			qWarning() << "received empty message";
			_socket->read(HEADER_LENGTH); // skip this header
			continue; // check if there are additional headers.
		}

		// Now wait for the entire message
		if (_socket->bytesAvailable() < HEADER_LENGTH + message_length - 4) {
			qDebug() << "incomplete msg body in read buffer";
			return; // try again once more data comes in
		}

		// We can now safely remove the message from the input buffer,
		// as we know the entire message is in the input buffer.
		QByteArray data = _socket->read(HEADER_LENGTH + message_length - 4);
		Message msg = unpackMessage(data);
		if (msg.transactionId > _lastTransactionId) _lastTransactionId = msg.transactionId;
		emit messageReceived(msg);
	}
}