summaryrefslogtreecommitdiff
path: root/rcm-server-lirc.c
blob: 3abcc3205cf6f2ffa126168a5471071510cceb17 (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 rc_device *rcdev = userdata;
	uint8_t buf[100];
	ssize_t bytes_read;

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

	if (revents & EPOLLHUP) {
		fprintf(stderr, "lirc connection closed!\n");
		lirc_close(rcdev);
		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 rc_device *rcdev, const char *path)
{
	int r;

	if (!rcdev)
		return -EINVAL;

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

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

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

	return 0;
}

void
lirc_close(struct rc_device *rcdev)
{
	if (!rcdev)
		return;

	if (rcdev->lirc_fd < 0)
		return;

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