src/SimulatorSocketServer.cpp
author František Kučera <franta-hg@frantovo.cz>
Thu, 24 Oct 2019 21:51:08 +0200
branchv_0
changeset 10 da93f3667a52
parent 7 b355abd4b887
permissions -rw-r--r--
fix license version: GNU GPLv3

/**
 * Spacenav Simulator Qt
 * Copyright © 2019 František Kučera (Frantovo.cz, GlobalCode.info)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, version 3 of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

#include <iostream>

#include "SimulatorSocketServer.h"
#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;
		std::wcout << L"To allow client connections do:" << std::endl;
		std::wcout << L"ln -s " << path.toStdWString() << " /var/run/spnav.sock" << 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) {
}

SimulatorSocketServer::~SimulatorSocketServer() {
}

void SimulatorSocketServer::publishButtonEvent(const ButtonEvent e) {
	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::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
		}
	}
}