summaryrefslogtreecommitdiff
path: root/rcm-server-lirc.c
blob: 4342cc17d804f79cc6210e98f02e9b579729fcd3 (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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <systemd/sd-bus.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include "utils.h"
#include "shared.h"
#include "rcm-server-main.h"
#include "rcm-server-lirc.h"

void
lirc_write(int fd, const uint32_t *v, unsigned count)
{
	unsigned nv[count];
	unsigned i;
	size_t l = count * sizeof(uint32_t);

	for (i = 0; i < count; i++)
		nv[i] = v[i];

	printf("Write to lirc fd of %zu bytes returned %zi errno is %i aka %s\n",
	       l, write(fd, nv, l), errno, strerror(errno));
}

static int
lirc_read(sd_event_source *s, int fd, uint32_t revents, void *userdata)
{
	struct device *device = userdata;
	uint8_t buf[100];
	ssize_t bytes_read;

	if (fd != device->lirc_fd)
		fprintf(stderr, "lirc fd mismatch: %i != %i\n", device->lirc_fd, fd);

	if (revents & EPOLLHUP) {
		fprintf(stderr, "lirc connection closed!\n");
		lirc_close(device);
		return 0;
	}

	if (!(revents & EPOLLIN)) {
		fprintf(stderr, "unexpected lirc event: %" PRIu32 "\n", revents);
		return 0;
	}

	while ((bytes_read = read(fd, buf, sizeof(buf))) > 0)
		printf("Read %zi bytes from lirc dev\n", bytes_read);

	return 0;
}

int
lirc_setup(struct device *device, const char *path)
{
	int r;

	if (!device)
		return -EINVAL;

	if (device->lirc_fd >= 0) {
		printf("Multiple lirc devices!?\n");
		return 0;
	}

	device->lirc_fd = open(path, O_RDWR | O_NONBLOCK);
	if (device->lirc_fd < 0) {
		printf("Failed to open lirc device %s: %s\n", path, strerror(errno));
		return -errno;
	}

	if (sd_event_add_io(device->mgr->event, &device->lirc_ev,
			    device->lirc_fd, EPOLLIN, lirc_read, device) < 0) {
		printf("Failed to add event source for lirc device %s: %s\n",
		       path, strerror(errno));
		r = -errno;
		lirc_close(device);
		return r;
	}

	return 0;
}

void
lirc_close(struct device *device)
{
	if (!device)
		return;

	if (device->lirc_fd < 0)
		return;

	close(device->lirc_fd);
	device->lirc_fd = -1;
}