ConnectionChecker.cpp 1.66 KB
Newer Older
legoc's avatar
legoc committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/*
 * Copyright 2015 Institut Laue-Langevin
 *
 * Licensed under the EUPL, Version 1.1 only (the "License");
 * You may not use this work except in compliance with the Licence.
 * You may obtain a copy of the Licence at:
 *
 * http://joinup.ec.europa.eu/software/page/eupl
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the Licence is distributed on an "AS IS" basis,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the Licence for the specific language governing permissions and
 * limitations under the Licence.
 */

17
18
#include "ConnectionChecker.h"
#include "Server.h"
legoc's avatar
legoc committed
19
#include "TimeCondition.h"
legoc's avatar
legoc committed
20
21
22
23
24

using namespace std;

namespace cameo {

25
ConnectionChecker::ConnectionChecker(Server * server, ConnectionChecker::FunctionType handler) : m_server(server), m_function(handler) {
26
	m_waitCondition.reset(new TimeCondition());
legoc's avatar
legoc committed
27
28
}

29
ConnectionChecker::~ConnectionChecker() {
legoc's avatar
legoc committed
30
31
32
	stopThread();
}

33
void ConnectionChecker::loop(int timeoutMs, int pollingTimeMs) {
legoc's avatar
legoc committed
34
35
36

	// Loop until the condition is notified.
	while (true) {
37
		bool stopped = m_waitCondition->wait(pollingTimeMs);
legoc's avatar
legoc committed
38
39
40
41
42
43
44
		if (stopped) {
			return;
		}

		// Check the server.
		bool available = (m_server->isAvailable(timeoutMs));

45
46
		// Apply the handler.
		m_function(available);
legoc's avatar
legoc committed
47
48
49
	}
}

50
void ConnectionChecker::startThread(int timeoutMs, int pollingTimeMs) {
legoc's avatar
legoc committed
51
52
53
54
55

	// Stop the thread if it exists.
	stopThread();

	// Start the thread.
legoc's avatar
legoc committed
56
	m_thread = unique_ptr<thread>(new thread(bind(&ConnectionChecker::loop, this, timeoutMs, pollingTimeMs)));
legoc's avatar
legoc committed
57
58
}

59
void ConnectionChecker::stopThread() {
legoc's avatar
legoc committed
60

legoc's avatar
legoc committed
61
	if (m_thread.get() != nullptr) {
62
		m_waitCondition->notify();
legoc's avatar
legoc committed
63
64
65
66
67
		m_thread->join();
	}
}

}