diff options
| -rw-r--r-- | .github/workflows/python-package-ci.yml | 22 | ||||
| -rw-r--r-- | CHANGELOG.rst | 27 | ||||
| -rw-r--r-- | README.rst | 104 | ||||
| -rw-r--r-- | docs/source/installation.rst | 9 | ||||
| -rw-r--r-- | docs/source/usage.rst | 57 | ||||
| -rw-r--r-- | lirc/__init__.py | 19 | ||||
| -rw-r--r-- | lirc/client.py | 192 | ||||
| -rw-r--r-- | lirc/connection/__init__.py | 0 | ||||
| -rw-r--r-- | lirc/connection/abstract_connection.py | 33 | ||||
| -rw-r--r-- | lirc/connection/default_address.py | 12 | ||||
| -rw-r--r-- | lirc/connection/default_socket.py | 13 | ||||
| -rw-r--r-- | lirc/connection/lircd_connection.py | 116 | ||||
| -rw-r--r-- | lirc/exceptions.py | 28 | ||||
| -rw-r--r-- | lirc/lirc.py | 252 | ||||
| -rw-r--r-- | lirc/reply_packet_parser.py | 168 | ||||
| -rw-r--r-- | lirc/response.py | 18 | ||||
| -rw-r--r-- | pyproject.toml | 6 | ||||
| -rw-r--r-- | tests/conftest.py | 6 | ||||
| -rw-r--r-- | tests/test_lirc.py | 204 | ||||
| -rw-r--r-- | tests/test_reply_packet.py | 66 |
20 files changed, 871 insertions, 481 deletions
diff --git a/.github/workflows/python-package-ci.yml b/.github/workflows/python-package-ci.yml index 0ffbee7..4979242 100644 --- a/.github/workflows/python-package-ci.yml +++ b/.github/workflows/python-package-ci.yml @@ -2,17 +2,22 @@ name: python package ci on: push: - branches: [ master, dev, test-ci ] + paths: + - "lirc/**" + - "tests/**" pull_request: - branches: [ master, dev, test-ci ] + paths: + - "lirc/**" + - "tests/**" jobs: build: - runs-on: ubuntu-latest + runs-on: ${{ matrix.os }} strategy: matrix: python-version: [3.6, 3.7, 3.8] + os: [macos-latest, ubuntu-latest, windows-latest] steps: - uses: actions/checkout@v2 @@ -26,10 +31,9 @@ jobs: run: | python -m pip install --upgrade pip pip install poetry - poetry install -vvv + poetry install -v - name: Run tests - run: | - poetry run task test_ci + run: poetry run task test_ci - name: Upload coverage to Codecov uses: codecov/codecov-action@v1 @@ -41,5 +45,7 @@ jobs: fail_ci_if_error: true - name: Build Package - run: | - poetry build
\ No newline at end of file + run: poetry build + + - name: Security Checks + uses: tonybaloney/pycharm-security@master
\ No newline at end of file diff --git a/CHANGELOG.rst b/CHANGELOG.rst index dac2803..58b5e31 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -8,7 +8,32 @@ Changelog <https://keepachangelog.com/en/1.0.0/>`_, and this project adheres to `Semantic Versioning <https://semver.org/spec/v2.0.0.html>`_. +Unreleased +------------------ + +**Added** + +- ``LircdConnection`` to handle configuring the connection on ``Client``. + +**Changed** + +- ``Lirc`` is now named ``Client``. + +- ``Client`` now takes in a ``connection`` as the optional argument + to configure it's connection. That ``connection`` must be a ``LircdConnection`` + class if you would like to customize the connection. The ``LircdConnection`` takes + in an ``address``, ``socket``, and ``timeout`` with optional keyword arguments. + Anything not specified with use the defaults for that operating system. + +**Removed** + +- ``DEFAULT_SOCKET_PATH`` constant on ``Client``. It no longer makes sense with cross-platform support. + +- ``ENCODING`` constant on ``Client``. + +- ``socket_path`` and ``socket_timeout`` on the ``Lirc`` constructor. + 0.1.0 - 2020-07-13 ------------------ -- Initial Release
\ No newline at end of file +- Initial Release @@ -30,8 +30,9 @@ LIRC Python Package :alt: License This is a python package that allows you to interact with the daemon in the -`Linux Infrared Remote Control <https://lirc.org>`_ package. Interacting with -the daemon allows you to send IR signals from a computer. +`Linux Infrared Remote Control <https://lirc.org>`_ package. By interacting +with the daemon, it allows you to programmatically send IR signals from a +computer. More information on the lircd daemon, socket interface, reply packet format, etc. can be found at https://www.lirc.org/html/lircd.html @@ -53,42 +54,87 @@ system as well. More information on that can be found in the `installation <https://lirc.readthedocs.io/en/latest/installation.html>`_ portion of the documentation. -Using the Lirc Package ----------------------- +Usage Quick Start +----------------- + +Customizing the Client +^^^^^^^^^^^^^^^^^^^^^^ + +.. code-block:: python + + import lirc + + client = lirc.Client() + + print(client.version()) + >>> '0.10.1' + +To use this package, we instantiate a ``Client``. When we initialize +the ``Client`` in the example above, we use the defaults by passing +it no arguments. + +The defaults use the ``LircdConnection`` class. These defaults depend +on your operating system and can be looked up in the full documentation. +However, we can customize these defaults if desired. + +.. code-block:: python + + import socket + import lirc + + client = lirc.Client( + connection=lirc.LircdConnection( + address="/var/run/lirc/lircd", + socket=socket.socket(socket.AF_UNIX, socket.SOCK_STREAM), + timeout = 5.0 + ) + ) + +The address specifies how to reach the lircd daemon. On Windows, we pass +a (hostname, port) tuple since we connect over TCP. However on Linux and +macOS, we pass in the socket path. For the client in the example above, we +set it up using the defaults for a Linux machine. While it illustrates what +is customizable, it is not a practical example since you could just call +``Client()`` then if you're on Linux and achieve the same outcome. + +Sending IR +^^^^^^^^^^ .. code-block:: python - from lirc import Lirc + import lirc + + client = lirc.Client() + client.send("my-remote-name", "KEY_POWER") + client.send("my-remote-name", "KEY_3", repeat_count=2) + + +With sending IR, we can use the `send` method and optionally, +send multiple by using the `repeat_count` keyword argument. + +Handling Errors +^^^^^^^^^^^^^^^ + +.. code-block:: python - lirc = Lirc() - response = lirc.version() + import lirc - print(response.command) - >>> 'VERSION' - print(response.success) - >>> True - print(response.data) - >>> ['0.10.1'] + client = lirc.Client() -To get started with the package, we import ``Lirc`` and can -initialize it with the defaults by passing it no arguments. + try: + client.send('some-remote', 'key_power') + except lirc.LircdCommandFailureError as error: + print('The command we sent failed! Check the error message') + print(error) -This will assume a socket path of ``/var/run/lirc/lircd``. -Furthermore, this will also then assume a socket connection -using ``AF_UNIX`` and ``SOCK_STREAM``. These are both the defaults -that should work on a Linux system. There are ports of LIRC -to Windows and macOS but using the package there is far less -common. However, both of these are configurable through options -passed to ``Lirc`` to allow it to be used on those operating systems -as well. +If the command was not successful, a ``LircdCommandFailureError`` exception will be thrown. +There are other errors that may be raised, which can be looked up in the full documentation, +but this is the most likely when sending commands. -After sending any command to the LIRC daemon, this package will create -a ``LircResponse`` for us that it returns. That response contains the -command we sent to LIRC, whether it was successful, and any data that -was returned back to us. Further Documentation --------------------- -More information on how to setup the system installed LIRC, how to use this python library, -and a full API specification can be found at https://lirc.readthedocs.io/ +More information on how to setup the system installed LIRC, how to use +this python library, and a full API specification can be found at +https://lirc.readthedocs.io/ diff --git a/docs/source/installation.rst b/docs/source/installation.rst index 3f74864..9a5b120 100644 --- a/docs/source/installation.rst +++ b/docs/source/installation.rst @@ -19,9 +19,12 @@ through pip. System LIRC Package ------------------- -While there are ports of LIRC to macOS and Windows, -the original Linux version is generally easier to -get working and install. +While LIRC was originally created for Linux, there +are ports of LIRC to macOS and Windows which this +python package is compatibile with. However, I would +still recommend using the original Linux version if +you can, as it generally has better maintanence, +hardware support, etc. Linux: diff --git a/docs/source/usage.rst b/docs/source/usage.rst index 588d2f7..ef9aa96 100644 --- a/docs/source/usage.rst +++ b/docs/source/usage.rst @@ -16,16 +16,16 @@ of things you can now import from it to get started. ) The most relevant of these is ``Lirc``, since this is the main class -you will be using. +you will be using. ``LircResponse`` is the response object that is returned +when you send a command. All the others are just errors. Initializing Lirc ----------------- -The ``Lirc`` class takes in three separate options, which all have default -values, that we may pass into it to construct it and override those default -values. - -The simplest way to construct ``Lirc`` is with no arguments at all. +The ``Lirc`` class takes in three separate options: ``address``, ``socket``, +and ``timeout``. These all have default values that depend on the operating +system you are on. So the simplest way to construct ``Lirc`` is with no +arguments at all. .. code-block:: python @@ -33,6 +33,45 @@ The simplest way to construct ``Lirc`` is with no arguments at all. lirc = Lirc() -This will attempt to connect to the lircd socket at "/var/run/lirc/lircd" on -your system, create a socket using ``AF_UNIX`` and ``SOCK_STREAM``, and sets -a socket timeout of 5 seconds.
\ No newline at end of file +Overriding LIRC Defaults on Initialization +------------------------------------------ + +However, if we the defaults don't work for us? Let's say we're on Windows +and we want to connect over TCP to a remote LIRC server on another Windows +machine. So we've passed in an ``address`` to override the default so it doesn't +look for the daemon on the localhost. ``socket`` and ``timeout`` are passed in +just to show that we can, these are already the defaults on Windows. + +.. code-block:: python + + import socket + from lirc import Lirc + + lirc = Lirc( + address=("10.16.30.2", 8765), + socket=socket.socket(socket.AF_INET, socket.SOCK_STREAM), + timeout=5 + ) + +LIRC Initialization Defaults per Operating System +----------------------------------------------- + +From the options we may pass into ``Lirc``, ``address`` and ``socket`` will +change depending on the operating system you are using. The ``timeout`` always +defaults to 5 (seconds). + +On Linux, this will attempt to connect to the lircd socket at +``/var/run/lirc/lircd`` and create a socket using ``AF_UNIX`` and +``SOCK_STREAM``. + +On macOS, it will be almost identical to Linux except that all the paths +on macOS will be prefixed by ``/opt/local/`` so the connection to the lircd +socket will instead be at ``/opt/local/var/run/lirc/lircd``. The socket that +is created will be the same. + +However if we are on Windows, we can't use unix domain sockets. So instead, +WinLIRC uses TCP to communicate with the lirc daemon. So instead of a string +for the address, it defaults to a tuple of ("localhost", 8765), the default on +WinLIRC. The first part contains the address whereas the second is the port. +Furthermore, the socket that is created uses ``AF_INET`` and ``SOCK_STREAM`` +instead now. diff --git a/lirc/__init__.py b/lirc/__init__.py index fe8e829..a8dd85b 100644 --- a/lirc/__init__.py +++ b/lirc/__init__.py @@ -1,19 +1,6 @@ -from .exceptions import ( - InvalidReplyPacketFormatError, - LircError, - LircSocketError, - LircSocketTimeoutError, -) -from .lirc import Lirc -from .response import LircResponse +from lirc.client import Client +from lirc.connection.lircd_connection import LircdConnection __version__ = "0.1.0" -__all__ = [ - "Lirc", - "LircResponse", - "LircError", - "LircSocketError", - "LircSocketTimeoutError", - "InvalidReplyPacketFormatError", -] +__all__ = ["Client", "LircdConnection"] diff --git a/lirc/client.py b/lirc/client.py new file mode 100644 index 0000000..9c32ea3 --- /dev/null +++ b/lirc/client.py @@ -0,0 +1,192 @@ +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: + LircConnectionError: If the socket cannot connect to the address. + """ + # Used for start_repeat and stop_repeat + self.__last_send_start_remote = None + self.__last_send_start_key = None + + self.__connection = LircdConnection() if connection is None else connection() + + 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: + A response object containing information on the command sent. + """ + 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): + self.__connection.close() + + def send(self, key: str, remote: 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: + LircCommandFailure + """ + 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. + + Returns: + The response of the command. + """ + self.__send_command(f"SEND_START {remote} {key}") + + def stop_repeat(self, remote: str = None, key: str = None) -> None: + """ + Send an lircd SEND_STOP command. + + Args: + remote: The remote to stop. + key: The key to stop sending. + + These default to the remote and key + last used with send_start if not specified, + since the most likely use case is sending a + send_start and then a send_stop. + + Returns: + The response of the command. + """ + if remote: + remote_to_stop = remote + elif self.__last_send_start_remote: + remote_to_stop = self.__last_send_start_remote + else: + remote_to_stop = "" + + if key: + key_to_stop = key + elif self.__last_send_start_key: + key_to_stop = self.__last_send_start_key + else: + key_to_stop = "" + + self.__send_command("SEND_STOP " f"{remote_to_stop} {key_to_stop}") + + def list_remotes(self) -> List[str]: + """ + List all the remotes that lirc has in + its `lircd.conf.d` folder. + + Returns: + The response of the command. + """ + 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. + + Returns: + The response of the command. + """ + return self.__send_command(f"LIST {remote}") + + def start_logging(self, path: str) -> None: + """ + Send a lircd SET_INPUTLOG command which sets + the path to log all lircd received data to. + + Returns: + The response of the command. + """ + self.__send_command(f"SET_INPUTLOG {path}") + + def stop_logging(self) -> None: + """ + Stop logging to the inputlog path from start_logging. + + Returns: + The response of the command. + """ + # 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 + + Returns: + The response of the command with + the version in the data field. + """ + return self.__send_command("VERSION") + + def driver_option(self, key: str, value: str) -> None: + """ + Set driver-specific option named key to given value. + """ + self.__send_command(f"DRV_OPTION {key} {value}") + + def simulate_keypress( + self, remote: str, key: str, repeat_count: int = 1, keycode: int = 0 + ) -> None: + self.__send_command( + "SIMULATE %016d %02d %s %s\n" % (keycode, repeat_count, key, remote) + ) + + def set_transmitters(self, transmitters: Union[int, List[int]]) -> None: + mask = transmitters + + if isinstance(transmitters, List): + for transmitter in transmitters: + mask |= 1 << (int(transmitter) - 1) + + self.__send_command(f"SET_TRANSMITTERS {mask}") diff --git a/lirc/connection/__init__.py b/lirc/connection/__init__.py new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/lirc/connection/__init__.py diff --git a/lirc/connection/abstract_connection.py b/lirc/connection/abstract_connection.py new file mode 100644 index 0000000..a515fd1 --- /dev/null +++ b/lirc/connection/abstract_connection.py @@ -0,0 +1,33 @@ +import socket +from abc import ABC, abstractmethod +from typing import Union + + +class AbstractConnection(ABC): + @abstractmethod + def readline(self) -> str: + pass + + @abstractmethod + def send(self, data: str): + pass + + @abstractmethod + def close(self) -> None: + pass + + @property + @abstractmethod + def socket(self) -> socket.socket: + pass + + @property + @abstractmethod + def address(self) -> Union[str, tuple]: + pass + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + return self.close() diff --git a/lirc/connection/default_address.py b/lirc/connection/default_address.py new file mode 100644 index 0000000..4d87703 --- /dev/null +++ b/lirc/connection/default_address.py @@ -0,0 +1,12 @@ +from enum import Enum + + +class DefaultAddress(Enum): + """ + Default addresses to use for connecting to the + lircd daemon, depending on the operating system. + """ + + LINUX = "/var/run/lirc/lircd" + WINDOWS = ("localhost", 8765) + DARWIN = "/opt/run/var/run/lirc/lircd" diff --git a/lirc/connection/default_socket.py b/lirc/connection/default_socket.py new file mode 100644 index 0000000..ee95529 --- /dev/null +++ b/lirc/connection/default_socket.py @@ -0,0 +1,13 @@ +import socket +from enum import Enum + + +class DefaultSocket(Enum): + """ + Default socket to use for the lircd socket, depending + on the operating system. + """ + + LINUX = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + DARWIN = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + WINDOWS = socket.socket(socket.AF_INET, socket.SOCK_STREAM) diff --git a/lirc/connection/lircd_connection.py b/lirc/connection/lircd_connection.py new file mode 100644 index 0000000..f4aa572 --- /dev/null +++ b/lirc/connection/lircd_connection.py @@ -0,0 +1,116 @@ +import platform +import socket as system_socket +from collections import deque +from typing import Union + +from ..exceptions import LircdConnectionError, LircdSocketError, LircdSocketTimeoutError +from .abstract_connection import AbstractConnection +from .default_address import DefaultAddress +from .default_socket import DefaultSocket + + +class LircdConnection(AbstractConnection): + def __init__( + self, + address: Union[str, tuple] = None, + socket: system_socket.socket = None, + timeout: float = 5.0, + ): + """ + Initialize the connection by connecting to the lircd socket. + + The default address depends on the operating system + you are using. On Linux, it is "/var/run/lirc/lircd". + On macOS, it is "/opt/run/var/run/lirc/lircd". And on + Windows, it is ("localhost", 8765) to connect to localhost:8765, + which is the default address for WinLIRC. + + The socket is also determined for you if one is not provided. A unix + domain socket is connected to on macOS and Linux. A TCP socket + is used for Windows. + + Args: + address: The address to lircd, determined for you if + one is not provided. + + socket: The socket.socket used to connect to the lircd socket. + + timeout: The amount of time in seconds to wait before timing out when + receiving data from lircd + + Raises: + LircConnectionError: If the socket cannot connect to the address. + """ + operating_system = platform.system().upper() + + self.__buffer = deque() + self.__buffer_size = 4096 + self.__socket = ( + socket if socket is not None else DefaultSocket[operating_system].value + ) + self.__address = ( + address if address is not None else DefaultAddress[operating_system].value + ) + + self.__socket.settimeout(timeout) + + try: + self.__socket.connect(self.__address) + except FileNotFoundError: + raise LircdConnectionError( + f"Could not connect to lircd at {self.__address} with socket " + f"{self.__socket}. Did you start the `lircd` daemon?" + ) + + @property + def socket(self) -> system_socket.socket: + return self.__socket + + @property + def address(self) -> str: + return self.__address + + def close(self): + self.__socket.close() + + def send(self, data: str): + if not data.endswith("\n"): + data += "\n" + + self.__socket.sendall(data.encode("utf-8")) + + def readline(self) -> str: + """ + Read the reply packet that is on the socket after a + command is sent to lircd. + + Raises: + LircdSocketTimeoutError: If recv does not find any data after + the specified timeout amount of seconds (called without a command + being sent?). + + LircdSocketError: If something else went wrong with the socket. + """ + if len(self.__buffer) >= 1: + return self.__buffer.popleft() + + try: + packet = self.__socket.recv(self.__buffer_size) + + if b"\n" in packet: + for line in packet.split(b"\n"): + self.__buffer.append(line.decode("utf-8")) + else: + self.__buffer.append(packet.decode("utf-8")) + + return self.__buffer.popleft() + + except system_socket.timeout: + raise LircdSocketTimeoutError( + "could not find any data on the socket after " + f"{self.__socket.gettimeout()} seconds, socket timed out." + ) + except system_socket.error as error: + raise LircdSocketError( + f"An error occurred while reading from the lircd socket: {error}" + ) diff --git a/lirc/exceptions.py b/lirc/exceptions.py index 063ca27..56753b9 100644 --- a/lirc/exceptions.py +++ b/lirc/exceptions.py @@ -1,18 +1,34 @@ class LircError(Exception): - """A generic error that comes from this package.""" - + """ + A generic error that comes from this package. -class InvalidReplyPacketFormatError(LircError): - """The reply packet from LIRC was in an invalid format.""" + All errors are subclasses of this error so you + could catch all lirc errors by catching this one. + """ -class LircSocketError(LircError): +class LircdSocketError(LircError): """For when a generic error occurs with the lircd socket""" -class LircSocketTimeoutError(LircSocketError): +class LircdSocketTimeoutError(LircdSocketError): """ For when a timeout error occurs with the socket. This can happen when recv does not find any data for a given amount of time. """ + + +class LircdConnectionError(LircError): + """For when we are unable to connect to lircd.""" + + +class LircdInvalidReplyPacketError(LircError): + """The reply packet from lircd was in an invalid format.""" + + +class LircdCommandFailureError(LircError): + """ + For when we send a command to the LIRC server + and that command fails to send, for whatever reason. + """ diff --git a/lirc/lirc.py b/lirc/lirc.py deleted file mode 100644 index a60c869..0000000 --- a/lirc/lirc.py +++ /dev/null @@ -1,252 +0,0 @@ -import socket -import threading -from itertools import islice -from typing import List, Union - -from lirc.exceptions import ( - InvalidReplyPacketFormatError, - LircSocketError, - LircSocketTimeoutError, -) -from lirc.response import LircResponse - - -class Lirc: - """Communicate with the lircd daemon.""" - - DEFAULT_SOCKET_PATH = "/var/run/lirc/lircd" - ENCODING = "utf-8" - - def __init__( - self, - socket_path: str = DEFAULT_SOCKET_PATH, - socket: socket.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM), - socket_timeout: int = 5, - ) -> None: - """ - Initialize Lirc by connecting to the lircd socket. - - :param socket_path: The path to the lircd socket. - :param socket: The socket.socket used to connect to the lircd socket. - :param socket_timeout: The amount of time to wait before timing out when - receiving data. - - :raises FileNotFoundError: If the socket path is not found. - """ - self.__lock = threading.Lock() - self.__socket = socket - self.__socket_timeout = socket_timeout - self.__socket.settimeout(self.__socket_timeout) - self.__socket.connect(socket_path) - - def __send_command(self, command: str) -> LircResponse: - """ - Send a command to lircd. - - :param command: A command from the lircd socket command interface. - See SOCKET COMMAND INTERFACE in https://www.lirc.org/html/lircd.html - for more information. - - :return: A LircResponse containing information on the command sent, - whether it was successful, and any other data, if any was sent. - """ - if not command.endswith("\n"): - command += "\n" - - try: - self.__lock.acquire() - self.__socket.sendall(command.encode(self.ENCODING)) - - reply_packet = self.__read_reply_packet() - return self.__parse_reply_packet(reply_packet) - finally: - self.__lock.release() - - def __read_reply_packet(self) -> str: - """ - Read the reply packet that lircd sends after a sent command. - - Reply packet format: - - BEGIN - <command> - [SUCCESS|ERROR] - [DATA - n - n lines of data] - END - - :return: The contents of the reply packet from BEGIN to END. - - :raises LircSocketTimeoutError: If recv does not find any data after - self.socket_timeout amount of seconds. - :raises LircSocketError: If something else went wrong with the socket. - """ - try: - BUFFER_LENGTH = 256 - buffer = "" - data = self.__socket.recv(BUFFER_LENGTH) - - # Ignore recieve requests that the socket caches - while "BEGIN" not in data.decode(self.ENCODING): - data = self.__socket.recv(BUFFER_LENGTH) - - buffer += data.decode(self.ENCODING) - - while not buffer.endswith("END\n"): - data = self.__socket.recv(BUFFER_LENGTH) - buffer += data.decode(self.ENCODING) - - return buffer - except (socket.timeout, socket.error) as e: - err = e.args[0] - if err == "timed out": - raise LircSocketTimeoutError( - f"could not find any data on the socket after " - f"{self.__socket_timeout} seconds, socket timed out." - ) - else: - raise LircSocketError(e) - - def __parse_reply_packet(self, packet: str) -> LircResponse: - """ - Parse the reply packet from lircd. - - :param packet: The reply packet from lirc. - - :return: An LircResponse containing the command sent, - whether it was successful, and any other data, if any was sent. - """ - lines = packet.split("\n") - current_index = 0 - response = LircResponse("", False, []) - - if lines[current_index] == "BEGIN": - current_index += 1 - else: - return response - - response.command = lines[current_index] - current_index += 1 - - response.success = True if lines[current_index] == "SUCCESS" else False - current_index += 1 - - if lines[current_index] == "END": - return response - elif lines[current_index] == "DATA": - current_index += 1 - data_length = int(lines[current_index]) - current_index += 1 - else: - raise InvalidReplyPacketFormatError( - f"Unknown format for reply packet: \n{lines}" - ) - - for line in islice(lines, current_index, current_index + data_length): - response.data.append(line) - - return response - - def send_once( - self, key: str, remote: str, repeat_count: int = 1 - ) -> Union[LircResponse, List[LircResponse]]: - """ - Send an LIRC SEND_ONCE command. - - Structure of the command: - * SEND_ONCE <remote-name> <key-name-from-remote-file> [repeat-count] - - :param key: The name of the key to send. - :param remote: The remote to use keys from. - :param repeat_count: The number of times to press this key. - - :return: a response from the command or a list of those responses - if repeat_count > 1. - """ - # The reason the optional repeat-count parameter isn't used in this - # implementaiton is because we want to be able to store all the - # responses from each command. - if repeat_count > 1: - responses = [] - - while repeat_count > 0: - responses.append(self.__send_command(f"SEND_ONCE {remote} {key}")) - repeat_count -= 1 - - return responses - - return self.__send_command(f"SEND_ONCE {remote} {key}") - - def send_start(self, key: str, remote: str) -> LircResponse: - """ - Send an LIRC SEND_START command. - - Structure of the command: - * SEND_START <remote-name> <key-name-from-remote-file> - - :param key: The name of the key to start sending. - :param remote: The remote to use keys from. - - :return: The response of the command. - """ - return self.__send_command(f"SEND_START {remote} {key}") - - def send_stop(self, key: str, remote: str) -> LircResponse: - """ - Send an LIRC SEND_STOP command. - - Structure of the command: - * SEND_STOP <remote-name> <key-name-from-remote-file> - - :param key: The name of the key to start sending. - :param remote: The remote to use keys from. - - :return: The response of the command. - """ - return self.__send_command(f"SEND_STOP") - - def list_remotes(self) -> LircResponse: - """ - List all the remotes in LIRC - - :return: The response of the command. - """ - return self.__send_command("LIST") - - def list_remote_keys(self, remote: str) -> LircResponse: - """ - List all the keys for a specific remote. - - :param remote: The remote to list the keys of. - - :return: The response of the command. - """ - return self.__send_command(f"LIST {remote}") - - def set_inputlog(self, path: str) -> LircResponse: - """ - Set the path to log all lircd received data to. - - :return: The response of the command. - """ - return self.__send_command(f"SET_INPUTLOG {path}") - - def stop_inputlog(self) -> LircResponse: - """ - Stop logging to the inputlog path from set_inputlog. - - :return: The response of the command. - """ - # When calling SET_INPUTLOG without the path argument, - # it will stop logging and close the logfile. - return self.__send_command("SET_INPUTLOG") - - def version(self) -> LircResponse: - """ - Retrieve the version of LIRC - - :return: The response of the command with - the version in the data field. - """ - return self.__send_command("VERSION") diff --git a/lirc/reply_packet_parser.py b/lirc/reply_packet_parser.py new file mode 100644 index 0000000..1db2527 --- /dev/null +++ b/lirc/reply_packet_parser.py @@ -0,0 +1,168 @@ +from enum import IntEnum, auto +from typing import List + +from .exceptions import LircdInvalidReplyPacketError + + +class ReplyPacketParser: + """ + Reads and parses reply packets sent from lircd. + + The reply packet is parsed by setting up a fsm + (finite state machine) and using an internal state + to keep track of where we are in the process. + + Reply packet format: + + BEGIN + <command> + [SUCCESS|ERROR] + [DATA + n + n lines of data] + END + + SIGHUP Format: + + BEGIN + SIGHUP + END + + The only other situation when lircd broadcasts to all + clients is when it receives the SIGHUP signal and + successfully re-reads its config file. Then it will + send a SIGHUP packet to its clients indicating that + its configuration might have changed. If we receive + this signal, we'll need to read in another packet. + """ + + class State(IntEnum): + BEGIN = auto() + COMMAND = auto() + RESULT = auto() + DATA = auto() + LINE_COUNT_LEFT = auto() + DATA_BODY = auto() + SIGHUP_END = auto() + END = auto() + FINISHED = auto() + + class Result(IntEnum): + SUCCESS = auto() + FAIL = auto() + UNDETERMINED = auto() + + def __init__(self): + self.__fsm = { + self.State.BEGIN: self.__begin, + self.State.COMMAND: self.__command, + self.State.RESULT: self.__result, + self.State.DATA: self.__data, + self.State.LINE_COUNT_LEFT: self.__line_count_left, + self.State.DATA_BODY: self.__data_body, + self.State.SIGHUP_END: self.__sighup_end, + self.State.END: self.__end, + } + self.__state = self.State.BEGIN + self.__command_result = self.Result.UNDETERMINED + self.__data_response = [] + self.__lines_left = None + + @property + def data(self) -> List: + return self.__data_response + + @property + def is_finished(self) -> bool: + return self.__state == self.State.FINISHED + + @property + def success(self) -> bool: + return self.__command_result == self.Result.SUCCESS + + def __begin(self, line: str) -> None: + if line == "BEGIN": + self.__state = self.State.COMMAND + else: + raise LircdInvalidReplyPacketError( + f"Expected a BEGIN line from lircd, got `{line}`." + ) + + def __command(self, line: str) -> None: + if line == "SIGHUP": + self.__state = self.State.SIGHUP_END + elif line: + self.__state = self.State.RESULT + else: + raise LircdInvalidReplyPacketError( + f"Expected a command line from lircd, got `{line}`." + ) + + def __result(self, line: str) -> None: + if line in ["SUCCESS", "ERROR"]: + self.__state = self.State.DATA + self.__command_result = ( + self.Result.SUCCESS if line == "SUCCESS" else self.Result.FAIL + ) + else: + raise LircdInvalidReplyPacketError( + f"Expected a result line from lircd, got `{line}`." + ) + + def __data(self, line: str) -> None: + if line == "END": + self.__state = self.State.FINISHED + elif line == "DATA": + self.__state = self.State.LINE_COUNT_LEFT + else: + raise LircdInvalidReplyPacketError( + f"Expected an END or DATA line from lircd, got `{line}`." + ) + + def __line_count_left(self, line: str) -> None: + try: + self.__lines_left = int(line) + except ValueError: + raise LircdInvalidReplyPacketError( + f"Expected a remaining line count line from lircd, got `{line}`." + ) + + self.__state = ( + self.State.END if self.__lines_left == 0 else self.State.DATA_BODY + ) + + def __data_body(self, line: str) -> None: + self.__data_response.append(line) + if len(self.__data_response) >= self.__lines_left: + self.__state = self.State.END + + def __sighup_end(self, line: str) -> None: + """ + SIGHUP packages may appear just after a command has been sent + to lircd, so this is to make sure they are not confused with + replies. If we encounter it, we reset and read in another packet. + """ + if line == "END": + self.__init__() + else: + raise LircdInvalidReplyPacketError( + "Expected an END line with the received SIGHUP packet from " + f"lircd, got `{line}` instead." + ) + + def __end(self, line: str) -> None: + if line == "END": + self.__state = self.State.FINISHED + else: + raise LircdInvalidReplyPacketError( + "Expected an END line from lircd's reply packet, " + f"got `{line}` instead." + ) + + def feed(self, line: str) -> None: + line = line.strip() + + if not line: + return + + self.__fsm[self.__state](line) diff --git a/lirc/response.py b/lirc/response.py deleted file mode 100644 index 3491037..0000000 --- a/lirc/response.py +++ /dev/null @@ -1,18 +0,0 @@ -class LircResponse: - """ - A response from the LIRC daemon. Stores the command that had - been sent, whether or not it was successful, and the parsed - reply packet data. - """ - - def __init__(self, command: str, success: bool, data: list) -> None: - self.command = command - self.success = success - self.data = data - - def __repr__(self) -> str: - return ( - f"LircResponse(command={self.command}, " - f"success={self.success}, " - f"data={self.data})" - ) diff --git a/pyproject.toml b/pyproject.toml index d5eacfe..89051dd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -20,6 +20,11 @@ classifiers = [ "Topic :: Software Development :: Libraries :: Python Modules", ] +packages = [ + { include = "lirc" }, + { include = "tests", format = "sdist" } +] + [tool.taskipy.tasks] lint = "poetry run pre-commit run --all" test = "task test_cov_missing" @@ -27,7 +32,6 @@ test_unit = "poetry run pytest tests/" test_cov = "task test_unit -- --cov=lirc/" test_cov_missing = "task test_cov -- -v --cov-report term-missing" test_ci = "task test_cov -- --cov-report=xml" -test_all = "export LIRC_RUN_LONG_TESTS=true && poetry run task test && unset LIRC_RUN_LONG_TESTS" [tool.poetry.dependencies] python = "^3.6" diff --git a/tests/conftest.py b/tests/conftest.py index 01e2460..3788b68 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -3,14 +3,14 @@ from unittest import mock import pytest -from lirc import Lirc +from lirc import Client, LircdConnection @pytest.fixture def mock_socket(): - return mock.Mock(spec=socket.socket) + return mock.MagicMock(spec=socket.socket) @pytest.fixture def mock_lirc(mock_socket): - return Lirc(socket=mock_socket) + return Client(connection=LircdConnection(socket=mock_socket)) diff --git a/tests/test_lirc.py b/tests/test_lirc.py index 348e785..4253bf0 100644 --- a/tests/test_lirc.py +++ b/tests/test_lirc.py @@ -1,135 +1,69 @@ -import os - -import pytest - -from lirc import ( - InvalidReplyPacketFormatError, - Lirc, - LircResponse, - LircSocketTimeoutError, -) - - -def test_default_lirc_init(mock_socket): - TIMEOUT = 5 - mock_lirc = Lirc(socket=mock_socket, socket_timeout=TIMEOUT) - - mock_socket.connect.assert_called_with(mock_lirc.DEFAULT_SOCKET_PATH) - mock_socket.settimeout.assert_called_with(TIMEOUT) - - -def test_lirc_custom_path(mock_socket): - CUSTOM_PATH = "CUSTOM" - Lirc(socket=mock_socket, socket_path=CUSTOM_PATH) - - mock_socket.connect.assert_called_with(CUSTOM_PATH) - - -def test_custom_path_lirc_init(mock_socket): - TEST_SOCKET_PATH = "test_path" - Lirc(socket=mock_socket, socket_path=TEST_SOCKET_PATH) - mock_socket.connect.assert_called_with(TEST_SOCKET_PATH) - - -@pytest.mark.parametrize( - "reply_packet", [b"BEGIN\nSEND_ONCE remote key\nSUCCESS\nEND\n"] -) -def test_read_reply_packet(mock_lirc, reply_packet): - mock_lirc._Lirc__socket.recv.return_value = reply_packet - retrieved_packet = mock_lirc._Lirc__read_reply_packet() - mock_lirc._Lirc__socket.recv.assert_called_with(256) - assert reply_packet == retrieved_packet.encode(mock_lirc.ENCODING) - - -@pytest.mark.skipif( - os.environ.get("LIRC_RUN_LONG_TESTS") is None, reason="Test takes too long" -) -@pytest.mark.parametrize("reply_packet", [b"INVALID PACKET"]) -def test_read_reply_packet_socket_timeout(mock_lirc, reply_packet): - with pytest.raises(LircSocketTimeoutError): - mock_lirc._Lirc__socket.recv.return_value = reply_packet - mock_lirc._Lirc__read_reply_packet() - - -@pytest.mark.parametrize( - "reply_packet, command, success, data, exception", - [ - ( - "BEGIN\nSEND_ONCE remote key\nSUCCESS\nEND\n", - "SEND_ONCE remote key", - True, - [], - None, - ), - ("INVALID PACKET", "", False, [], None), - ( - "BEGIN\nSEND_ONCE remote key\nERROR\nINVALID\n", - "SEND_ONCE remote key", - False, - [], - InvalidReplyPacketFormatError, - ), - ( - "BEGIN\nSEND_ONCE remote key\nERROR\nDATA\n1\nunknown remote: remote\n", - "SEND_ONCE remote key", - False, - ["unknown remote: remote"], - None, - ), - ( - "BEGIN\nSEND_ONCE remote key\nSUCCESS\nDATA\n3\nraa\nblah\nbhal\n", - "SEND_ONCE remote key", - True, - ["raa", "blah", "bhal"], - None, - ), - ], -) -def test_parse_reply_packet(mock_lirc, reply_packet, command, success, data, exception): - if exception: - with pytest.raises(exception): - mock_lirc._Lirc__parse_reply_packet(reply_packet) - else: - response = mock_lirc._Lirc__parse_reply_packet(reply_packet) - assert response.success == success - assert response.command == command - assert response.data == data - - -@pytest.mark.parametrize( - "reply_packet, repeat_count", - [ - (b"BEGIN\nSEND_ONCE remote key\nSUCCESS\nEND\n", 1), - (b"BEGIN\nSEND_ONCE remote key\nERROR\nEND\n", 1), - (b"BEGIN\nSEND_ONCE remote key\nSUCCESS\nEND\n", 5), - ], -) -def test_send_once(mock_lirc, reply_packet, repeat_count): - REMOTE = "remote" - KEY = "key" - COMMAND = f"SEND_ONCE {REMOTE} {KEY}" - SUCCESS = True if "SUCCESS" in reply_packet.decode(mock_lirc.ENCODING) else False - - mock_lirc._Lirc__socket.recv.return_value = reply_packet - response = mock_lirc.send_once(KEY, REMOTE, repeat_count=repeat_count) - mock_lirc._Lirc__socket.sendall.assert_called_with( - (COMMAND + "\n").encode(mock_lirc.ENCODING) - ) - - if repeat_count > 1: - assert type(response) == list - assert len(response) == repeat_count - - for r in response: - _ensure_lirc_response(r, COMMAND, SUCCESS) - else: - _ensure_lirc_response(response, COMMAND, SUCCESS) - - -def _ensure_lirc_response( - response: LircResponse, command: str, success: bool, data: list = [] -): - assert type(response) == LircResponse - assert response.command == command - assert response.success == success - assert response.data == data +# from unittest import mock +# +# import pytest +# +# from lirc import Client +# from lirc.connection.default_address import DefaultAddress +# from lirc.connection.default_socket import DefaultSocket + + +# @mock.patch("socket.socket") +# @mock.patch("platform.system") +# @pytest.mark.parametrize("os_name", ["WINDOWS", "DARWIN", "LINUX"]) +# def test_default_lirc_initialization(mocked_system, mocked_socket, os_name): +# mocked_system.return_value = os_name +# expected_socket = DefaultSocket[os_name].value +# expected_address = DefaultAddress[os_name].value +# +# Client() +# # lirc_socket = lirc.socket +# +# assert mocked_socket.family == expected_socket.family +# assert mocked_socket.type == expected_socket.type +# mocked_socket.connect.assert_called_with(expected_address) +# mocked_socket.settimeout.assert_called_with(5.0) +# +# +# def test_custom_lirc_initialization(mock_socket): +# CUSTOM_ADDRESS = "CUSTOM" +# CUSTOM_TIMEOUT = 10.0 +# +# Client(socket=mock_socket, address=CUSTOM_ADDRESS, timeout=CUSTOM_TIMEOUT) +# +# mock_socket.connect.assert_called_with(CUSTOM_ADDRESS) +# mock_socket.settimeout.assert_called_with(CUSTOM_TIMEOUT) + + +# @pytest.mark.parametrize( +# "reply_packet, repeat_count", +# [ +# (b"BEGIN\nSEND_ONCE remote key\nSUCCESS\nEND\n", 1), +# # (b"BEGIN\nSEND_ONCE remote key\nERROR\nEND\n", 1), +# # (b"BEGIN\nSEND_ONCE remote key\nSUCCESS\nEND\n", 5), +# ], +# ) +# def test_send_once(mock_lirc, reply_packet, repeat_count): +# REMOTE = "remote" +# KEY = "key" +# COMMAND = f"SEND_ONCE {REMOTE} {KEY}" +# mock_lirc.socket.recv.return_value = reply_packet +# +# response = mock_lirc.send(KEY, REMOTE, repeat_count=repeat_count) +# +# mock_lirc.socket.sendall.assert_called_with((COMMAND + "\n").encode(ENCODING)) +# +# +# if repeat_count > 1: +# assert type(response) == list +# assert len(response) == repeat_count +# +# for r in response: +# _ensure_lirc_response(r, COMMAND) +# else: +# _ensure_lirc_response(response, COMMAND) +# +# +# def _ensure_lirc_response(response: LircResponse, command: str, data: list = []): +# assert type(response) == LircResponse +# assert response.command == command +# assert response.data == data diff --git a/tests/test_reply_packet.py b/tests/test_reply_packet.py new file mode 100644 index 0000000..86ae311 --- /dev/null +++ b/tests/test_reply_packet.py @@ -0,0 +1,66 @@ +# import pytest +# +# from lirc import ( +# LircdCommandFailureError, +# LircdInvalidReplyPacketError, +# LircdSocketTimeoutError, +# ) +# from lirc.reply_packet_parser import ReplyPacketParser +# from lirc.utils import ENCODING +# +# +# @pytest.mark.parametrize( +# "reply_packet", [b"BEGIN\nSEND_ONCE remote key\nSUCCESS\nEND\n"] +# ) +# def test_read_reply_packet(mock_socket, reply_packet): +# mock_socket.recv.return_value = reply_packet +# parser = ReplyPacketParser(mock_socket) +# parser.read() +# +# retrieved_packet = parser.feed() +# +# mock_socket.recv.assert_called_with(ReplyPacketParser.BUFFER_LENGTH) +# assert reply_packet == retrieved_packet.encode(ENCODING) +# +# +# @pytest.mark.skip(reason="Not working") +# @pytest.mark.parametrize("reply_packet", [b"INVALID PACKET"]) +# def test_read_reply_packet_socket_timeout(mock_lirc, reply_packet): +# with pytest.raises(LircdSocketTimeoutError): +# mock_lirc.socket.recv.return_value = reply_packet +# ReplyPacketParser.read(mock_lirc.socket) +# +# +# @pytest.mark.parametrize( +# "reply_packet, data, exception", +# [ +# (b"BEGIN\nSEND_ONCE remote key\nSUCCESS\nEND\n", [], None,), +# # ("INVALID PACKET", [], LircdInvalidReplyPacketError), +# ( +# b"BEGIN\nSEND_ONCE remote key\nERROR\nINVALID\n", +# [], +# LircdInvalidReplyPacketError, +# ), +# ( +# b"BEGIN\nSEND_ONCE remote key\nERROR\nDATA\n1\nunknown remote: remote\n", +# ["unknown remote: remote"], +# LircdCommandFailureError, +# ), +# ( +# b"BEGIN\nSEND_ONCE remote key\nSUCCESS\nDATA\n3\nraa\nblah\nbhal\n", +# ["raa", "blah", "bhal"], +# None, +# ), +# ], +# ) +# def test_parse_reply_packet(mock_socket, reply_packet, data, exception): +# mock_socket.recv.return_value = reply_packet +# parser = ReplyPacketParser(mock_socket) +# +# if exception: +# with pytest.raises(exception): +# parser.read() +# parser.feed() +# else: +# parser.read() +# assert parser.feed() == data |