summaryrefslogtreecommitdiff
path: root/distfoldd/discoverer.h
blob: ae106dee1762671cb16e2d7b6faba4bb2c9974ea (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
#ifndef DISCOVERER_H
#define DISCOVERER_H

#include <QtCore/QTimer>
#include <QtCore/QUuid>
#include <QtCore/QDateTime>
#include <QtNetwork/QNetworkConfigurationManager>
#include <QtNetwork/QHostAddress>
#include <QtNetwork/QUdpSocket>
#include <QtSystemInfo/QSystemNetworkInfo>
#include <QtSystemInfo/QSystemAlignedTimer>

QTM_USE_NAMESPACE

class Discoverer : public QObject
{
	Q_OBJECT

public:
	Discoverer(const QUuid& uuid, uint port, const QString& serviceName, QObject *parent = 0);
	
	static const uint servicePort = 17451;
	static const int dateTimeCompareMinDelta = 5;

	// In seconds
	static const int idleBroadcastInterval = 15 * 60;
	static const int activeBroadcastInterval = 5;
	static const int lostHostTimeout =  idleBroadcastInterval * 1.4f;

signals:
	void foundMoreRecentHost(const QHostAddress& address, uint port, const QDateTime& dateTime);

public slots:
	void setLastModifiedTime(const QDateTime& dateTime);

private:
#pragma pack(push)
#pragma pack(1)
	struct Message {
		quint32 mtime;
		char hostUuid[38];
		quint16 port;
		char folderUuid[38];
		char name[];
	};
#pragma pack()
	struct HostInfo {
		QDateTime lastSeen;
	};

	QByteArray encodeMessage() const;

	void switchToActiveMode();

private slots:
	void broadcastMessage();
	void handleDataAvailable();
	void handleBroadcastMessage(const QHostAddress& sender, const QByteArray &data);
	void handleHostSeen(const QUuid& hostUuid);
	void handleTimerTimeout();
	void handleTimerError();
	void handleOnlineStateChanged(bool online);

private:
	QUuid _folderUuid;
	QUuid _hostUuid;
	QString _serviceName;
	uint _port;
	QDateTime _mtime;
	bool _mtimeChanged;
	QUdpSocket *_receiver;
	QUdpSocket *_sender;
	quint32 _myId;
	QNetworkConfigurationManager *_netConfig;
	QSystemNetworkInfo *_netInfo;
	QDateTime _lastBroadcast;
	QSystemAlignedTimer *_timer;
	QTimer *_fallbackTimer;
	QHash<QUuid, HostInfo> _knownHosts;
};

#endif // DISCOVERER_H