summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorEugene Triguba <eugenetriguba@gmail.com>2020-07-15 23:08:11 -0500
committerEugene Triguba <eugenetriguba@gmail.com>2020-07-15 23:08:11 -0500
commit705a84f5b8908b462a0c0c98b64d5d111ec20d17 (patch)
treeff58948fd2b3f6b287dc0c36e170e0159b3c3430
parentRun CI on macos, windows, and ubuntu (diff)
downloadlirc-705a84f5b8908b462a0c0c98b64d5d111ec20d17.zip
Change how address and socket are determined in Lirc
This is to help with making this package cross-platform.
-rw-r--r--CHANGELOG.rst36
-rw-r--r--docs/source/usage.rst57
-rw-r--r--lirc/lirc.py76
-rw-r--r--tests/test_lirc.py18
4 files changed, 150 insertions, 37 deletions
diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index dac2803..52b74d6 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -8,6 +8,42 @@ Changelog <https://keepachangelog.com/en/1.0.0/>`_, and this project
adheres to `Semantic Versioning <https://semver.org/spec/v2.0.0.html>`_.
+Unreleased
+------------------
+
+**Changed**
+
+ - ``socket_path`` in ``Lirc``'s constructor is now called ``address`` to better signify
+ what is it for (the address to reach lircd). This allows it to make more sense in a
+ cross-platform context such as with WinLIRC since TCP is used there and not a socket.
+
+ - ``address`` in ``Lirc``'s constructor is now type hinted to be a tuple or a string.
+ A tuple is used for a TCP connection since you'd specify it as such: ("localhost", 8765).
+
+ - ``socket_timeout`` has been renamed to just ``timeout`` in ``Lirc``'s constructor to clarify
+ that it may not necessarily be a socket (in the case of being on Windows).
+
+ - ``socket_timeout`` in ``Lirc``'s constructor is now type hinted as a float instead of an int.
+ This is the type that the socket will change it to anyway, and it makes more sense with time.
+
+ - ``socket`` and ``address`` in ``Lirc``'s constructor is now defaulted to ``None`` in the ``__init__``
+ method, but it does some calculations to determine the operating system that it is being run on and
+ sets up sensible defaults for them based on that.
+
+ - On Linux, it is "/var/run/lirc/lircd" as the address.
+ 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.
+
+ - On Linux and macOS, the socket would end up being socket.socket(socket.AF_UNIX, socket.SOCK_STREAM).
+ On Windows, the socket would end up being socket.socket(socket.AF_INET, socket.SOCK_STREAM) since it is
+ connected over TCP with WinLIRC.
+
+**Removed**
+
+ - ``DEFAULT_SOCKET_PATH`` constant on ``Lirc``. It no longer makes sense with cross-platform support.
+ - ``ENCODING`` constant on ``Lirc``. It is now a private part of the class.
+
+
0.1.0 - 2020-07-13
------------------
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/lirc.py b/lirc/lirc.py
index a60c869..3671c3c 100644
--- a/lirc/lirc.py
+++ b/lirc/lirc.py
@@ -1,6 +1,7 @@
import socket
import threading
from itertools import islice
+from platform import system
from typing import List, Union
from lirc.exceptions import (
@@ -10,34 +11,69 @@ from lirc.exceptions import (
)
from lirc.response import LircResponse
+DEFAULT_ADDRESS_LINUX = "/var/run/lirc/lircd"
+DEFAULT_ADDRESS_WINDOWS = ("localhost", 8765)
+DEFAULT_ADDRESS_DARWIN = "/opt/run/var/run/lirc/lircd"
+
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,
+ address: Union[str, tuple] = None,
+ socket: socket.socket = None,
+ timeout: float = 5.0,
) -> None:
"""
Initialize Lirc by connecting to the lircd socket.
- :param socket_path: The path to the lircd socket.
+ :param address: The address to lircd. 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.
+
: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.
+ :param timeout: The amount of time in seconds to wait before timing out when
+ receiving data from the lirc server.
+
+ :raises FileNotFoundError: If the socket cannot connect to the address.
"""
self.__lock = threading.Lock()
- self.__socket = socket
- self.__socket_timeout = socket_timeout
- self.__socket.settimeout(self.__socket_timeout)
- self.__socket.connect(socket_path)
+ self.__encoding = "utf-8"
+ self.__timeout = timeout
+ self.__socket = self.__determine_socket(socket)
+ self.__address = (
+ address
+ if address is not None
+ else globals()[f"DEFAULT_ADDRESS_{system().upper()}"]
+ )
+
+ self.__socket.settimeout(self.__timeout)
+ self.__socket.connect(self.__address)
+
+ @staticmethod
+ def __determine_socket(lircd_socket: Union[socket.socket, None]) -> socket.socket:
+ """
+ Determines the default socket type to be used based on the
+ operating system of the host if no socket to use is provided.
+
+ It will use a socket configured for TCP on Windows (since
+ that is how WinLIRC works), and it will default to a socket
+ configured for unix sockets otherwise (Darwin & Linux).
+
+ :param lircd_socket: The socket passed in to the Lirc constructor.
+ """
+ if isinstance(lircd_socket, socket.socket):
+ return lircd_socket
+
+ if system() == "Windows":
+ return socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ else:
+ return socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
def __send_command(self, command: str) -> LircResponse:
"""
@@ -55,7 +91,7 @@ class Lirc:
try:
self.__lock.acquire()
- self.__socket.sendall(command.encode(self.ENCODING))
+ self.__socket.sendall(command.encode(self.__encoding))
reply_packet = self.__read_reply_packet()
return self.__parse_reply_packet(reply_packet)
@@ -79,7 +115,7 @@ class Lirc:
: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.
+ the specified timeout amount of seconds.
:raises LircSocketError: If something else went wrong with the socket.
"""
try:
@@ -88,14 +124,14 @@ class Lirc:
data = self.__socket.recv(BUFFER_LENGTH)
# Ignore recieve requests that the socket caches
- while "BEGIN" not in data.decode(self.ENCODING):
+ while "BEGIN" not in data.decode(self.__encoding):
data = self.__socket.recv(BUFFER_LENGTH)
- buffer += data.decode(self.ENCODING)
+ buffer += data.decode(self.__encoding)
while not buffer.endswith("END\n"):
data = self.__socket.recv(BUFFER_LENGTH)
- buffer += data.decode(self.ENCODING)
+ buffer += data.decode(self.__encoding)
return buffer
except (socket.timeout, socket.error) as e:
@@ -103,7 +139,7 @@ class Lirc:
if err == "timed out":
raise LircSocketTimeoutError(
f"could not find any data on the socket after "
- f"{self.__socket_timeout} seconds, socket timed out."
+ f"{self.__timeout} seconds, socket timed out."
)
else:
raise LircSocketError(e)
diff --git a/tests/test_lirc.py b/tests/test_lirc.py
index 348e785..4c69ac6 100644
--- a/tests/test_lirc.py
+++ b/tests/test_lirc.py
@@ -10,24 +10,24 @@ from lirc import (
)
+# TODO: test this per OS!
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)
+ Lirc(socket=mock_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)
+ Lirc(socket=mock_socket, address=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)
+ Lirc(socket=mock_socket, address=TEST_SOCKET_PATH)
mock_socket.connect.assert_called_with(TEST_SOCKET_PATH)
@@ -38,7 +38,7 @@ 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)
+ assert reply_packet == retrieved_packet.encode(mock_lirc._Lirc__encoding)
@pytest.mark.skipif(
@@ -108,12 +108,14 @@ 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
+ SUCCESS = (
+ True if "SUCCESS" in reply_packet.decode(mock_lirc._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)
+ (COMMAND + "\n").encode(mock_lirc._Lirc__encoding)
)
if repeat_count > 1: