summaryrefslogtreecommitdiffstats
path: root/lirc/client.py
blob: 0a1b7b1101f40476ba13c3c3e0e2dd0dc80a82c1 (plain) (blame)
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
from pathlib import Path
from typing import List, Union

from .connection.lircd_connection import LircdConnection
from .exceptions import LircdCommandFailureError
from .reply_packet_parser import ReplyPacketParser


class Client:
    """Communicate with the lircd daemon."""

    def __init__(self, connection: LircdConnection = None) -> None:
        """
        Initialize the client by connecting to the lircd socket.

        Args:
            connection: The connection to lircd. Created with defaults
            depending on the operating system if one is not provided.

        Raises:
            ValueError: If connection is not an instance of LircdConnection.
            LircdConnectionError: If the socket cannot connect to the address.
        """
        if not connection:
            connection = LircdConnection()

        if not isinstance(connection, LircdConnection):
            raise ValueError("`connection` must be an instance of `LircdConnection`")

        # Used for start_repeat and stop_repeat
        self.__last_send_start_remote = None
        self.__last_send_start_key = None

        self.__connection = connection
        self.__connection.connect()

    def __send_command(self, command: str) -> Union[str, List[str]]:
        """
        Send a command to lircd.

        Args:
            command: A command from the lircd socket command interface.

        Returns:
            The data from the lirc response packet.
        """
        self.__connection.send(command)

        parser = ReplyPacketParser()
        while not parser.is_finished:
            line = self.__connection.readline()
            parser.feed(line)

        parser_data = parser.data[0] if len(parser.data) == 1 else parser.data

        if not parser.success:
            raise LircdCommandFailureError(
                f"The `{command}` command sent to lircd failed: {parser_data}"
            )

        return parser_data

    def close(self) -> None:
        """Close the connection to the socket."""
        self.__connection.close()

    def send(self, remote: str, key: str, repeat_count: int = 1) -> None:
        """
        Send an lircd SEND_ONCE command.

        Args:
            key: The name of the key to send.
            remote: The remote to use keys from.
            repeat_count: The number of times to press this key.

        Raises:
            LircdCommandFailure: If the command fails.
        """
        self.__send_command(f"SEND_ONCE {remote} {key} {repeat_count}")

    def start_repeat(self, remote: str, key: str) -> None:
        """
        Send an lircd SEND_START command.

        This will repeat the given key until
        stop_repeat() is called.

        Args:
            remote: The remote to use keys from.
            key: The name of the key to start sending.

        Raises:
            LircdCommandFailure: If the command fails.
        """
        self.__last_send_start_remote = remote
        self.__last_send_start_key = key
        self.__send_command(f"SEND_START {remote} {key}")

    def stop_repeat(self, remote: str = "", key: str = "") -> None:
        """
        Send an lircd SEND_STOP command.

        The remote and key default to the remote and key
        last used with send_start if they are not specified,
        since the most likely use case is sending a send_start
        and then a send_stop.

        Args:
            remote: The remote to stop.
            key: The key to stop sending.

        Raises:
            LircdCommandFailure: If the command fails.
        """
        if not remote and self.__last_send_start_remote:
            remote = self.__last_send_start_remote

        if not key and self.__last_send_start_key:
            key = self.__last_send_start_key

        self.__send_command(f"SEND_STOP {remote} {key}")

    def list_remotes(self) -> List[str]:
        """
        List all the remotes that lirc has in
        its `lircd.conf.d` folder.

        Raises:
            LircdCommandFailure: If the command fails.

        Returns:
            The list of all remotes.
        """
        return self.__send_command("LIST")

    def list_remote_keys(self, remote: str) -> List[str]:
        """
        List all the keys for a specific remote.

        Args:
            remote: The remote to list the keys of.

        Raises:
            LircdCommandFailure: If the command fails.

        Returns:
            The list of keys from the remote.
        """
        return self.__send_command(f"LIST {remote}")

    def start_logging(self, path: Union[str, Path]) -> None:
        """
        Send a lircd SET_INPUTLOG command which sets
        the path to log all lircd received data to.

        Args:
            path: The path to start logging lircd recieved data to.

        Raises:
            LircdCommandFailure: If the command fails.
        """
        self.__send_command(f"SET_INPUTLOG {path}")

    def stop_logging(self) -> None:
        """
        Stop logging to the inputlog path from start_logging.

        Raises:
            LircdCommandFailure: If the command fails.
        """
        # When calling SET_INPUTLOG without the path argument,
        # it will stop logging and close the logfile.
        self.__send_command("SET_INPUTLOG")

    def version(self) -> str:
        """
        Retrieve the version of LIRC

        Raises:
            LircdCommandFailure: If the command fails.

        Returns:
            The version of LIRC being used.
        """
        return self.__send_command("VERSION")

    def driver_option(self, key: str, value: str) -> None:
        """
        Set driver-specific option named key to given value.

        Args:
            key: The key to set for the driver.
            value: The value for the key to set.

        Raises:
            LircdCommandFailure: If the command fails.
        """
        self.__send_command(f"DRV_OPTION {key} {value}")

    def simulate(
        self, remote: str, key: str, repeat_count: int = 1, keycode: int = 0
    ) -> None:
        """
        Simulate an IR event.

        The --allow-simulate command line option to `lircd` must be active for this
        command not to fail.

        Example Format:
            <code> <repeat count> <button name> <remote control name>

            Such as:
                0000000000f40bf0 00 KEY_UP ANIMAX

        Args:
            remote: The remote to simulate key presses from.
            key: The key on the remote to simulate.
            repeat_count: The number of times to simulate the key press.
            keycode: lircd(8) describes this option as a 16 hexadecimal digit
                number encoding of the IR signal. However, it says it is depreciated
                and should be ignored.

        Raises:
            LircdCommandFailure: If the command fails.
        """
        self.__send_command(
            "SIMULATE %016d %02d %s %s\n" % (keycode, repeat_count, key, remote)
        )

    def set_transmitters(self, transmitters: Union[int, List[int]]) -> None:
        """
        Set the active transmitters.

        Example:
            import lirc

            c = lirc.Client()

            c.set_transmitters(1)

            c.set_transmitters([1,3,5])

        Args:
            transmitters: The transmitters to set active.

        Raises:
            LircdCommandFailure: If the command fails.
        """
        mask = transmitters

        if isinstance(transmitters, List):
            mask = 0
            for transmitter in transmitters:
                mask |= 1 << (int(transmitter) - 1)

        self.__send_command(f"SET_TRANSMITTERS {mask}")