src/SimulatorSocketServer.cpp
branchv_0
changeset 5 980a27d138f7
parent 3 42d64bd73232
child 7 b355abd4b887
--- a/src/SimulatorSocketServer.cpp	Thu Mar 14 17:41:43 2019 +0100
+++ b/src/SimulatorSocketServer.cpp	Thu Mar 14 20:39:34 2019 +0100
@@ -22,7 +22,28 @@
 #include "ButtonEvent.h"
 #include "MotionEvent.h"
 
+enum SocketEventType : int32_t {
+	Motion,
+	ButtonPress,
+	ButtonRelease
+};
+
 SimulatorSocketServer::SimulatorSocketServer() {
+	QString path = "/tmp/spacenav-simulator.sock";
+
+	bool listnening = server->listen(path);
+
+	if (listnening) {
+		std::wcout << L"Listening on: " << path.toStdWString() << std::endl;
+
+		connect(server, &QLocalServer::newConnection, [path, this]() {
+			std::wcout << L"New connection on: " << path.toStdWString() << std::endl;
+			connections.push_back(server->nextPendingConnection());
+		});
+
+	} else {
+		std::wcout << L"Unable to listen on: " << path.toStdWString() << std::endl; // TODO: throw exception
+	}
 }
 
 SimulatorSocketServer::SimulatorSocketServer(const SimulatorSocketServer& orig) {
@@ -32,19 +53,36 @@
 }
 
 void SimulatorSocketServer::publishButtonEvent(const ButtonEvent e) {
-	std::wcout << L"buttonEvent(" << e.number << L", " << (e.pressed ? L"pressed" : L"released") << L")" << std::endl;
+	std::array<int32_t, 8> data = {0};
+	data[0] = e.pressed ? SocketEventType::ButtonPress : SocketEventType::ButtonRelease;
+	data[1] = e.number;
+	publish(data);
+
+
 }
 
 void SimulatorSocketServer::publishMotionEvent(const MotionEvent e) {
-	std::wcout << L"motionEvent( m = ["
-			<< e.x << L", "
-			<< e.y << L", "
-			<< e.z << L"], "
-			<< L"r = ["
-			<< e.rx << L", "
-			<< e.ry << L", "
-			<< e.rz << L"], "
-			<< L"period = " << e.period
-			<< L")" << std::endl;
+	std::array<int32_t, 8> data = {0};
+	int i = 0;
+	data[i++] = SocketEventType::Motion;
+	data[i++] = e.x;
+	data[i++] = e.y;
+	data[i++] = e.z;
+	data[i++] = e.rx;
+	data[i++] = e.ry;
+	data[i++] = e.rz;
+	data[i++] = e.period;
+	publish(data);
+	// TODO: custom sensitivity for each connection
+}
 
+void SimulatorSocketServer::publish(const std::array<int32_t, 8> &data) {
+	for (QLocalSocket* socket : connections) {
+		if (socket->isValid()) {
+			socket->write((char*) &data, sizeof data);
+			socket->flush();
+		} else {
+			// TODO: remove invalid socket
+		}
+	}
 }