1 ''' Top-level python bindings for the lircd socket interface. '''
28 from abc
import ABCMeta, abstractmethod
40 _DEFAULT_PROG =
'lircd-client'
43 def get_default_socket_path() -> str:
44 ''' Get default value for the lircd socket path, using (falling priority):
46 - The environment variable LIRC_SOCKET_PATH.
47 - The 'output' value in the lirc_options.conf file if value and the
48 corresponding file exists.
49 - A hardcoded default lirc.config.VARRUNDIR/lirc/lircd, possibly
53 if 'LIRC_SOCKET_PATH' in os.environ:
54 return os.environ[
'LIRC_SOCKET_PATH']
55 path = lirc.config.SYSCONFDIR +
'/lirc/lirc_options.conf'
56 parser = configparser.SafeConfigParser()
59 except configparser.Error:
62 if parser.has_section(
'lircd'):
64 path = str(parser.get(
'lircd',
'output'))
65 if os.path.exists(path):
67 except configparser.NoOptionError:
69 return lirc.config.VARRUNDIR +
'/lirc/lircd'
72 def get_default_lircrc_path() -> str:
73 ''' Get default path to the lircrc file according to (falling priority):
75 - $XDG_CONFIG_HOME/lircrc if environment variable and file exists.
76 - ~/.config/lircrc if it exists.
77 - ~/.lircrc if it exists
78 - A hardcoded default lirc.config.SYSCONFDIR/lirc/lircrc, whether
81 if 'XDG_CONFIG_HOME' in os.environ:
82 path = os.path.join(os.environ[
'XDG_CONFIG_HOME'],
'lircrc')
83 if os.path.exists(path):
85 path = os.path.join(os.path.expanduser(
'~'),
'.config' 'lircrc')
86 if os.path.exists(path):
88 path = os.path.join(os.path.expanduser(
'~'),
'.lircrc')
89 if os.path.exists(path):
91 return os.path.join(lirc.config.SYSCONFDIR,
'lirc',
'lircrc')
94 class BadPacketException(Exception):
95 ''' Malformed or otherwise unparsable packet received. '''
99 class TimeoutException(Exception):
100 ''' Timeout receiving data from remote host.'''
154 class AbstractConnection(metaclass=ABCMeta):
155 ''' Abstract interface for all connections. '''
160 def __exit__(self, exc_type, exc, traceback):
164 def readline(self, timeout: float =
None) -> str:
165 ''' Read a buffered line
169 - If set to 0 immediately return either a line or None.
170 - If set to None (default mode) use blocking read.
172 Returns: code string as described in lircd(8) without trailing
175 Raises: TimeoutException if timeout > 0 expires.
180 def fileno(self) -> int:
181 ''' Return the file nr used for IO, suitable for select() etc. '''
185 def has_data(self) -> bool:
186 ''' Return true if next readline(None) won't block . '''
191 ''' Close/release all resources '''
195 class RawConnection(AbstractConnection):
196 ''' Interface to receive code strings as described in lircd(8).
199 - socket_path: lircd output socket path, see get_default_socket_path()
201 - prog: Program name used in lircrc decoding, see ircat(1). Could be
202 omitted if only raw keypresses should be read.
207 def __init__(self, socket_path: str =
None, prog: str = _DEFAULT_PROG):
209 os.environ[
'LIRC_SOCKET_PATH'] = socket_path
211 os.environ[
'LIRC_SOCKET_PATH'] = get_default_socket_path()
212 _client.lirc_deinit()
213 fd = _client.lirc_init(prog)
214 self._socket = socket.fromfd(fd, socket.AF_UNIX, socket.SOCK_STREAM)
215 self._select = selectors.DefaultSelector()
216 self._select.register(self._socket, selectors.EVENT_READ)
217 self._buffer = bytearray(0)
219 def readline(self, timeout: float =
None) -> str:
220 ''' Implements AbstractConnection.readline(). '''
223 while b
'\n' not in self._buffer:
224 ready = self._select.select(
225 start + timeout - time.clock()
if timeout
else timeout)
228 raise TimeoutException(
229 "readline: no data within %f seconds" % timeout)
232 recv = self._socket.recv(4096)
234 raise ConnectionResetError(
'Connection lost')
236 line, self._buffer = self._buffer.split(b
'\n', 1)
237 return line.decode(
'ascii',
'ignore')
239 def fileno(self) -> int:
240 ''' Implements AbstractConnection.fileno(). '''
241 return self._socket.fileno()
243 def has_data(self) -> bool:
244 ''' Implements AbstractConnection.has_data() '''
245 return b
'\n' in self._buffer
248 ''' Implements AbstractConnection.close() '''
250 _client.lirc_deinit()
253 AbstractConnection.register(RawConnection)
256 class LircdConnection(AbstractConnection):
257 ''' Interface to receive lircrc-translated keypresses. This is basically
258 built on top of lirc_code2char() and as such supporting centralized
259 translations using lircrc_class. See lircrcd(8).
262 - program: string, used to identify client. See ircat(1)
263 - lircrc: lircrc file path. See get_default_lircrc_path() for defaults.
264 - socket_path: lircd output socket path, see get_default_socket_path()
269 def __init__(self, program: str,
270 lircrc_path: str =
None,
271 socket_path: str =
None):
273 lircrc_path = get_default_lircrc_path()
275 raise FileNotFoundError(
'Cannot find lircrc config file.')
276 self._connection = RawConnection(socket_path, program)
277 self._lircrc = _client.lirc_readconfig(lircrc_path)
278 self._program = program
281 def readline(self, timeout: float =
None):
282 ''' Implements AbstractConnection.readline(). '''
283 while len(self._buffer) <= 0:
284 code = self._connection.readline(timeout)
288 _client.lirc_code2char(self._lircrc, self._program, code)
289 if not strings
or len(strings) == 0:
293 self._buffer.extend(strings)
294 return self._buffer.pop(0)
296 def has_data(self) -> bool:
297 ''' Implements AbstractConnection.has_data() '''
298 return len(self._buffer) > 0
300 def fileno(self) -> int:
301 ''' Implements AbstractConnection.fileno(). '''
302 return self._connection.fileno()
305 ''' Implements AbstractConnection.close() '''
306 self._connection.close()
307 _client.lirc_freeconfig(self._lircrc)
310 AbstractConnection.register(LircdConnection)
366 class CommandConnection(RawConnection):
367 ''' Extends the parent with a send() method. '''
369 def __init__(self, socket_path: str =
None):
370 RawConnection.__init__(self, socket_path)
372 def send(self, command: (bytearray, str)):
373 ''' Send single line over socket '''
374 if not isinstance(command, bytearray):
375 command = command.encode(
'ascii')
376 while len(command) > 0:
377 sent = self._socket.send(command)
378 command = command[sent:]
382 ''' Public reply parser result, available when completed. '''
388 class Command(object):
389 ''' Command, parser and connection container with a run() method. '''
391 def __init__(self, cmd: str,
392 connection: AbstractConnection,
393 timeout: float = 0.4):
394 self._conn = connection
395 self._cmd_string = cmd
396 self._parser = ReplyParser()
398 def run(self, timeout: float =
None):
399 ''' Run the command and return a Reply. Timeout as of
400 AbstractConnection.readline()
402 self._conn.send(self._cmd_string)
403 while not self._parser.is_completed():
404 line = self._conn.readline(timeout)
406 raise TimeoutException(
'No data from lircd host.')
407 self._parser.feed(line)
412 ''' The status/result from parsing a command reply.
415 result: Enum Result, reflects parser state.
416 success: bool, reflects SUCCESS/ERROR.
417 data: List of lines, the command DATA payload.
418 sighup: bool, reflects if a SIGHUP package has been received
419 (these are otherwise ignored).
420 last_line: str, last input line (for error messages).
423 self.result = Result.INCOMPLETE
430 class ReplyParser(Reply):
431 ''' Handles the actual parsing of a command reply. '''
435 self._state = self._State.BEGIN
436 self._lines_expected =
None
437 self._buffer = bytearray(0)
439 def is_completed(self) -> bool:
440 ''' Returns true if no more reply input is required. '''
441 return self.result != Result.INCOMPLETE
443 def feed(self, line: str):
444 ''' Enter a line of data into parsing FSM, update state. '''
447 self._State.BEGIN: self._begin,
448 self._State.COMMAND: self._command,
449 self._State.RESULT: self._result,
450 self._State.DATA: self._data,
451 self._State.LINE_COUNT: self._line_count,
452 self._State.LINES: self._lines,
453 self._State.END: self._end,
454 self._State.SIGHUP_END: self._sighup_end
459 self.last_line = line
460 fsm[self._state](line)
461 if self._state == self._State.DONE:
462 self.result = Result.OK
471 ''' Internal FSM state. '''
483 def _bad_packet_exception(self, line):
484 self.result = Result.FAIL
485 raise BadPacketException(
486 'Cannot parse: %s\nat state: %s\n' % (line, self._state))
488 def _begin(self, line):
490 self._state = self._State.COMMAND
492 def _command(self, line):
494 self._bad_packet_exception(line)
495 elif line ==
'SIGHUP':
496 self._state = self._State.SIGHUP_END
499 self._state = self._State.RESULT
501 def _result(self, line):
502 if line
in [
'SUCCESS',
'ERROR']:
503 self.success = line ==
'SUCCESS'
504 self._state = self._State.DATA
506 self._bad_packet_exception(line)
508 def _data(self, line):
510 self._state = self._State.DONE
512 self._state = self._State.LINE_COUNT
514 self._bad_packet_exception(line)
516 def _line_count(self, line):
518 self._lines_expected = int(line)
520 self._bad_packet_exception(line)
521 if self._lines_expected == 0:
522 self._state = self._State.END
524 self._state = self._State.LINES
526 def _lines(self, line):
527 self.data.append(line)
528 if len(self.data) >= self._lines_expected:
529 self._state = self._State.END
531 def _end(self, line):
533 self._bad_packet_exception(line)
534 self._state = self._State.DONE
536 def _sighup_end(self, line):
538 ReplyParser.__init__(self)
541 self._bad_packet_exception(line)
558 class SimulateCommand(Command):
559 ''' Simulate a button press, see SIMULATE in lircd(8) manpage. '''
562 def __init__(self, connection: AbstractConnection,
563 remote: str, key: str, repeat: int = 1, keycode: int = 0):
564 cmd =
'SIMULATE %016d %02d %s %s\n' % \
565 (int(keycode), int(repeat), key, remote)
566 Command.__init__(self, cmd, connection)
569 class ListRemotesCommand(Command):
570 ''' List available remotes, see LIST in lircd(8) manpage. '''
572 def __init__(self, connection: AbstractConnection):
573 Command.__init__(self,
'LIST\n', connection)
576 class ListKeysCommand(Command):
577 ''' List available keys in given remote, see LIST in lircd(8) manpage. '''
579 def __init__(self, connection: AbstractConnection, remote: str):
580 Command.__init__(self,
'LIST %s\n' % remote, connection)
583 class StartRepeatCommand(Command):
584 ''' Start repeating given key, see SEND_START in lircd(8) manpage. '''
586 def __init__(self, connection: AbstractConnection,
587 remote: str, key: str):
588 cmd =
'SEND_START %s %s\n' % (remote, key)
589 Command.__init__(self, cmd, connection)
592 class StopRepeatCommand(Command):
593 ''' Stop repeating given key, see SEND_STOP in lircd(8) manpage. '''
595 def __init__(self, connection: AbstractConnection,
596 remote: str, key: str):
597 cmd =
'SEND_STOP %s %s\n' % (remote, key)
598 Command.__init__(self, cmd, connection)
601 class SendCommand(Command):
602 ''' Send given key, see SEND_ONCE in lircd(8) manpage. '''
604 def __init__(self, connection: AbstractConnection,
605 remote: str, keys: str):
607 raise ValueError(
'No keys to send given')
608 cmd =
'SEND_ONCE %s %s\n' % (remote,
' '.join(keys))
609 Command.__init__(self, cmd, connection)
612 class SetTransmittersCommand(Command):
613 ''' Set transmitters to use, see SET_TRANSMITTERS in lircd(8) manpage.
616 transmitter: Either a bitmask or a list of int describing active
620 def __init__(self, connection: AbstractConnection,
621 transmitters: (int, list)):
622 if isinstance(transmitters, list):
624 for transmitter
in transmitters:
625 mask |= (1 << (int(transmitter) - 1))
628 cmd =
'SET_TRANSMITTERS %d\n' % mask
629 Command.__init__(self, cmd, connection)
632 class VersionCommand(Command):
633 ''' Get lircd version, see VERSION in lircd(8) manpage. '''
635 def __init__(self, connection: AbstractConnection):
636 Command.__init__(self,
'VERSION\n', connection)
639 class DrvOptionCommand(Command):
640 ''' Set a driver option value, see DRV_OPTION in lircd(8) manpage. '''
642 def __init__(self, connection: AbstractConnection,
643 option: str, value: str):
644 cmd =
'DRV_OPTION %s %s\n' % (option, value)
645 Command.__init__(self, cmd, connection)
648 class SetLogCommand(Command):
649 ''' Start/stop logging lircd output , see SET_INPUTLOG in lircd(8)
653 def __init__(self, connection: AbstractConnection,
654 logfile: str =
None):
655 cmd =
'SET_INPUTLOG' + (
' ' + logfile
if logfile
else '') +
'\n'
656 Command.__init__(self, cmd, connection)
669 class IdentCommand(Command):
670 ''' Identify client using the prog token, see IDENT in lircrcd(8) '''
672 def __init__(self, connection: AbstractConnection,
675 raise ValueError(
'The prog argument cannot be None')
676 cmd =
'IDENT {}\n'.format(prog)
677 Command.__init__(self, cmd, connection)
680 class CodeCommand(Command):
681 '''Translate a keypress to application string, see CODE in lircrcd(8) '''
683 def __init__(self, connection: AbstractConnection,
686 raise ValueError(
'The prog argument cannot be None')
687 Command.__init__(self,
'CODE {}\n'.format(code), connection)
690 class GetModeCommand(Command):
691 '''Get current translation mode, see GETMODE in lircrcd(8) '''
693 def __init__(self, connection: AbstractConnection):
694 Command.__init__(self,
"GETMODE\n", connection)
697 class SetModeCommand(Command):
698 '''Set current translation mode, see SETMODE in lircrcd(8) '''
700 def __init__(self, connection: AbstractConnection,
703 raise ValueError(
'The mode argument cannot be None')
704 Command.__init__(self,
'SETMODE {}\n'.format(mode), connection)