summaryrefslogtreecommitdiff
path: root/saltoqd/toqconnection.h
blob: 0d295e29bba286099d83f128afc2f1ee22bcc53a (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
#ifndef TOQCONNECTION_H
#define TOQCONNECTION_H

#include <QtCore/QTimer>
#include <QtBluetooth/QBluetoothSocket>
#include <QtCore/QJsonDocument>
#include <QtCore/QJsonObject>

class ToqConnection : public QObject
{
	Q_OBJECT
	Q_ENUMS(CoreEndpoints)
	Q_PROPERTY(bool connected READ isConnected NOTIFY connectedChanged)
	Q_PROPERTY(QBluetoothAddress address READ address CONSTANT)

public:
	explicit ToqConnection(const QBluetoothAddress &address, QObject *parent = 0);

	typedef quint8 Endpoint;

	enum CoreEndpoints
	{
		VersionEndpoint = 0,
		VoiceCallEndpoint = 1,
		SMSEndpoint = 3,
		SystemEndpoint = 5,
		PopUpEndpoint = 7,
		StorageServiceEndpoint = 9,
		TFTPEndpoint = 15,
		FMSEndpoint = 17,
		EPCommunicationEndpoint = 19,
		MusicEndpoint = 24,
		AppMessagingEndpoint = 26,
		SpeechEndpoint = 28,
		ActivityMonitoringEndpoint = 30,
		FTSEndpoint = 32,
		AppLoggingEndpoint = 34
	};

	struct Message
	{
		Message();
		Message(Endpoint source, Endpoint destination, quint16 transactionId, quint32 type, QJsonDocument payload);

		Endpoint source;
		Endpoint destination;
		quint16 transactionId;
		quint32 type;
		QJsonDocument payload;
	};

	static QString nameOfEndpoint(Endpoint ep);

	static quint32 checksum(const QByteArray &data);
	static quint32 checksum(QIODevice *dev);

	bool isConnected() const;
	QBluetoothAddress address() const;

	quint16 newTransactionId();

public slots:
	void sendMessage(const Message &msg);

signals:
	void connected();
	void disconnected();
	void messageReceived(const Message &msg);
	void connectedChanged();

private:
	Message unpackMessage(const QByteArray &data);
	QByteArray packMessage(const Message &msg);

private slots:
	void tryConnect();
	void handleSocketConnected();
	void handleSocketDisconnected();
	void handleSocketError(QBluetoothSocket::SocketError error);
	void handleSocketData();

private:
	QBluetoothAddress _address;
	QBluetoothSocket *_socket;
	QTimer *_reconnectTimer;
	quint16 _lastTransactionId;
};

inline ToqConnection::Message::Message()
{
}

inline ToqConnection::Message::Message(Endpoint source, Endpoint destination, quint16 transactionId, quint32 type, QJsonDocument payload)
	: source(source), destination(destination), transactionId(transactionId), type(type), payload(payload)
{
}

inline bool ToqConnection::isConnected() const
{
	return _socket && _socket->state() == QBluetoothSocket::ConnectedState;
}

inline QBluetoothAddress ToqConnection::address() const
{
	return _address;
}

#endif // TOQCONNECTION_H