~xdavidwu/motion-control

34f15598ea9f67f87cf82c7cfd9316fdefdef381 — xdavidwu 2 years ago c3747eb
tools: add buttonc: send key events from stdin
3 files changed, 92 insertions(+), 2 deletions(-)

M .gitignore
M Makefile
A tools/buttonc/main.ha
M .gitignore => .gitignore +1 -0
@@ 4,3 4,4 @@
/pointerc
/pointerd
/motion-control
/buttonc

M Makefile => Makefile +2 -2
@@ 1,4 1,4 @@
evdev-dump-events uinput-pointer pointerc:
evdev-dump-events uinput-pointer pointerc buttonc:
	hare build -levdev -o $@ tools/$@/
gy-801-dump:
	hare build -o $@ tools/$@/


@@ 6,4 6,4 @@ pointerd:
	hare build -levdev -o $@ cmd/$@/
motion-control:
	hare build -o $@ cmd/$@/
.PHONY: evdev-dump-events uinput-pointer gy-801-dump pointerd pointerc motion-control
.PHONY: evdev-dump-events uinput-pointer gy-801-dump pointerd pointerc motion-control buttonc

A tools/buttonc/main.ha => tools/buttonc/main.ha +89 -0
@@ 0,0 1,89 @@
use fmt;
use io;
use net;
use net::ip;
use net::udp;
use os;
use proto::control;
use strconv;
use unix::tty;

fn send(sock: io::file, bytes: []u8) void = {
	match (udp::send(sock, bytes)) {
	case let err: net::error =>
		fmt::fatalf("Cannot send(): {}", net::strerror(err));
	case size =>
		yield;
	};
};

export fn main() int = {
	if (len(os::args) != 3) {
		fmt::fatalf("Usage: {} addr port", os::args[0]);
	};
	const addr = match (ip::parse(os::args[1])) {
	case let addr: ip::addr =>
		yield addr;
	case ip::invalid =>
		fmt::fatalf("Invalid address {}", os::args[1]);
	};
	const port = match (strconv::stou16(os::args[2])) {
	case let port: u16 =>
		yield port;
	case =>
		fmt::fatalf("Invalid port {}", os::args[2]);
	};

	const sock = match (udp::connect(addr, port)) {
	case let s: io::file =>
		yield s;
	case let err: net::error =>
		fmt::fatalf("Cannot connect() {}:{}: {}", ip::string(addr), port, net::strerror(err));
	};
	defer io::close(sock)!;

	let buf = control::request {...};

	const tty = tty::isatty(os::stdin_file);
	let termios: *tty::termios = &tty::termios {...};

	if (tty) {
		termios = &tty::termios_query(os::stdin_file)!;
		tty::makeraw(termios)!;
	};
	if (tty) defer tty::termios_restore(termios);

	for (true) {
		let i: []u8 = [0];
		match (io::read(os::stdin_file, i)) {
		case size =>
			yield;
		case io::EOF =>
			break;
		case let err: io::error =>
			fmt::fatalf("Cannot read(): {}", io::strerror(err));
		};
		switch (i[0]) {
		case 'A' =>
			buf.code = control::code::KEY_PRESSED;
			buf.key = control::key::BTN_LEFT;
			send(sock, buf.bytes);
		case 'a' =>
			buf.code = control::code::KEY_RELEASED;
			buf.key = control::key::BTN_LEFT;
			send(sock, buf.bytes);
		case 'B' =>
			buf.code = control::code::KEY_PRESSED;
			buf.key = control::key::BTN_RIGHT;
			send(sock, buf.bytes);
		case 'b' =>
			buf.code = control::code::KEY_RELEASED;
			buf.key = control::key::BTN_RIGHT;
			send(sock, buf.bytes);
		case 4 => // EOT
			break;
		};
	};

	return 0;
};