ó
Ý¹‚Yc           @` sÚ   d  Z  d d l m Z m Z m Z m Z d d l Z d d l Z d d l Z d d l	 m
 Z
 d d l m Z d d l m Z m Z m Z m Z d d l m Z d d	 g Z d
 e f d „  ƒ  YZ d e
 f d „  ƒ  YZ d S(   uŠ   
    pyudev.monitor
    ==============

    Monitor implementation.

    .. moduleauthor::  Sebastian Wiesner  <lunaryorn@googlemail.com>
i    (   t   print_functiont   divisiont   unicode_literalst   absolute_importN(   t   Thread(   t   closing(   t   ensure_byte_stringt   ensure_unicode_stringt   reraiset   eintr_retry_call(   t   Deviceu   Monitoru   MonitorObservert   Monitorc           B` sž   e  Z d  Z d d „ Z d „  Z d „  Z e d d „ ƒ Z e d „  ƒ Z	 d „  Z
 d d „ Z d	 „  Z d
 „  Z d „  Z e Z d „  Z d „  Z d „  Z RS(   u  
    Monitor udev events:

    >>> context = pyudev.Context()
    >>> monitor = pyudev.Monitor.from_netlink(context)
    >>> monitor.filter_by(subsystem='input')
    >>> for action, device in monitor:
    ...     print('{0}: {1}'.format(action, device))
    ...

    A :class:`Monitor` objects connects to the udev daemon and listens for
    changes to the device list.  A monitor is created by connecting to the
    kernel daemon through netlink (see :meth:`from_netlink`).
    Alternatively, connections to arbitrary daemons can be made using
    :meth:`from_socket`, which is however only seldom of use.

    Once the monitor is created, you can add a filter using :meth:`filter_by()`
    or :meth:`filter_by_tag()` to drop incoming events in subsystems, which are
    not of interest to the application.

    If the monitor is eventually set up, you can either iterate over the
    :class:`Monitor` object to synchronously receive events (see
    :meth:`__iter__()`) or use a :class:`MonitorObserver` to asynchronously
    react on events.  Moreover the monitor provides a real file descriptor (see
    :meth:`fileno()`), which is :func:`selectable <select.select>`, so you can
    also plug the monitor into custom notification mechanisms.  Do *not* read
    or write on this file descriptor.

    Instances of this class can directly be given as ``udev_monitor *`` to
    functions wrapped through :mod:`ctypes`.
    c         C` s+   | |  _  | |  _ | |  _ | j |  _ d  S(   N(   t   contextt   _as_parameter_t   _socket_patht   _libudev(   t   selfR   t	   monitor_pt   socket_path(    (    s2   /usr/lib/python2.7/site-packages/pyudev/monitor.pyt   __init__P   s    			c         C` s2   t  j ƒ  \ } } } |  j | _ t | | ƒ d  S(   N(   t   syst   exc_infoR   t   filenameR   (   R   t   _t	   exc_valuet	   traceback(    (    s2   /usr/lib/python2.7/site-packages/pyudev/monitor.pyt   _reraise_with_socket_pathV   s    c         C` s   |  j  j |  ƒ d  S(   N(   R   t   udev_monitor_unref(   R   (    (    s2   /usr/lib/python2.7/site-packages/pyudev/monitor.pyt   __del__[   s    u   udevc         C` sa   | d k r$ t  d j | ƒ ƒ ‚ n  | j j | t | ƒ ƒ } | sT t d ƒ ‚ n  |  | | ƒ S(   u®  
        Create a monitor by connecting to the kernel daemon through netlink.

        ``context`` is the :class:`Context` to use.  ``source`` is a string,
        describing the event source.  Two sources are available:

        ``'udev'`` (the default)
          Events emitted after udev as registered and configured the device.
          This is the absolutely recommended source for applications.

        ``'kernel'``
          Events emitted directly after the kernel has seen the device.  The
          device has not yet been configured by udev and might not be usable
          at all.  **Never** use this, unless you know what you are doing.

        Return a new :class:`Monitor` object, which is connected to the
        given source.  Raise :exc:`~exceptions.ValueError`, if an invalid
        source has been specified.  Raise
        :exc:`~exceptions.EnvironmentError`, if the creation of the monitor
        failed.
        u   kernelu   udevu8   Invalid source: {0!r}. Must be one of "udev" or "kernel"u   Could not create udev monitor(   u   kernelu   udev(   t
   ValueErrort   formatR   t   udev_monitor_new_from_netlinkR   t   EnvironmentError(   t   clsR   t   sourcet   monitor(    (    s2   /usr/lib/python2.7/site-packages/pyudev/monitor.pyt   from_netlink^   s    		c         C` sL   | j  j | t | ƒ ƒ } | s9 t d j | ƒ ƒ ‚ n  |  | | d | ƒS(   u˜  
        Connect to an arbitrary udev daemon using the given ``socket_path``.

        ``context`` is the :class:`Context` to use. ``socket_path`` is a byte
        or unicode string, pointing to an existing socket.  If the path starts
        with a ``@``, use an abstract namespace socket.  If ``socket_path``
        does not exist, fall back to an abstract namespace socket.

        The caller is responsible for permissions and cleanup of the socket
        file.

        Return a new :class:`Monitor` object, which is connected to the given
        socket.  Raise :exc:`~exceptions.EnvironmentError`, if the creation of
        the monitor failed.
        u*   Could not create monitor for socket: {0!r}R   (   R   t   udev_monitor_new_from_socketR   R    R   (   R!   R   R   R#   (    (    s2   /usr/lib/python2.7/site-packages/pyudev/monitor.pyt   from_socket~   s    		c         C` s   |  j  j |  ƒ S(   uÅ   
        Return the file description associated with this monitor as integer.

        This is really a real file descriptor ;), which can be watched and
        :func:`select.select`\ ed.
        (   R   t   udev_monitor_get_fd(   R   (    (    s2   /usr/lib/python2.7/site-packages/pyudev/monitor.pyt   fileno–   s    c         C` sK   t  | ƒ } | r! t  | ƒ } n  |  j j |  | | ƒ |  j j |  ƒ d S(   u'  
        Filter incoming events.

        ``subsystem`` is a byte or unicode string with the name of a
        subsystem (e.g. ``'input'``).  Only events originating from the
        given subsystem pass the filter and are handed to the caller.

        If given, ``device_type`` is a byte or unicode string specifying the
        device type.  Only devices with the given device type are propagated
        to the caller.  If ``device_type`` is not given, no additional
        filter for a specific device type is installed.

        These filters are executed inside the kernel, and client processes
        will usually not be woken up for device, that do not match these
        filters.

        .. versionchanged:: 0.15
           This method can also be after :meth:`enable_receiving()` now
        N(   R   R   t/   udev_monitor_filter_add_match_subsystem_devtypet   udev_monitor_filter_update(   R   t	   subsystemt   device_type(    (    s2   /usr/lib/python2.7/site-packages/pyudev/monitor.pyt	   filter_byŸ   s    	c         C` s-   |  j  j |  t | ƒ ƒ |  j  j |  ƒ d S(   u\  
        Filter incoming events by the given ``tag``.

        ``tag`` is a byte or unicode string with the name of a tag.  Only
        events for devices which have this tag attached pass the filter and are
        handed to the caller.

        Like with :meth:`filter_by` this filter is also executed inside the
        kernel, so that client processes are usually not woken up for devices
        without the given ``tag``.

        .. udevversion:: 154

        .. versionadded:: 0.9

        .. versionchanged:: 0.15
           This method can also be after :meth:`enable_receiving()` now
        N(   R   t!   udev_monitor_filter_add_match_tagR   R*   (   R   t   tag(    (    s2   /usr/lib/python2.7/site-packages/pyudev/monitor.pyt   filter_by_tagº   s    	c         C` s$   |  j  j |  ƒ |  j  j |  ƒ d S(   u  
        Remove any filters installed with :meth:`filter_by()` or
        :meth:`filter_by_tag()` from this monitor.

        .. warning::

           Up to udev 181 (and possibly even later versions) the underlying
           ``udev_monitor_filter_remove()`` seems to be broken.  If used with
           affected versions this method always raises
           :exc:`~exceptions.ValueError`.

        Raise :exc:`~exceptions.EnvironmentError` if removal of installed
        filters failed.

        .. versionadded:: 0.15
        N(   R   t   udev_monitor_filter_removeR*   (   R   (    (    s2   /usr/lib/python2.7/site-packages/pyudev/monitor.pyt   remove_filterÑ   s    c         C` s6   y |  j  j |  ƒ Wn t k
 r1 |  j ƒ  n Xd S(   u„  
        Switch the monitor into listing mode.

        Connect to the event source and receive incoming events.  Only after
        calling this method, the monitor listens for incoming events.

        .. note::

           This method is implicitly called by :meth:`__iter__`.  You don't
           need to call it explicitly, if you are iterating over the
           monitor.
        N(   R   t   udev_monitor_enable_receivingR    R   (   R   (    (    s2   /usr/lib/python2.7/site-packages/pyudev/monitor.pyt   enable_receivingå   s    c         C` s9   y |  j  j |  | ƒ Wn t k
 r4 |  j ƒ  n Xd S(   uN  
        Set the receive buffer ``size``.

        ``size`` is the requested buffer size in bytes, as integer.

        .. note::

           The CAP_NET_ADMIN capability must be contained in the effective
           capability set of the caller for this method to succeed.  Otherwise
           :exc:`~exceptions.EnvironmentError` will be raised, with ``errno``
           set to :data:`~errno.EPERM`.  Unprivileged processes typically lack
           this capability.  You can check the capabilities of the current
           process with the python-prctl_ module:

           >>> import prctl
           >>> prctl.cap_effective.net_admin

        Raise :exc:`~exceptions.EnvironmentError`, if the buffer size could not
        bet set.

        .. versionadded:: 0.13

        .. _python-prctl: http://packages.python.org/python-prctl
        N(   R   t$   udev_monitor_set_receive_buffer_sizeR    R   (   R   t   size(    (    s2   /usr/lib/python2.7/site-packages/pyudev/monitor.pyt   set_receive_buffer_sizeù   s    c         C` sw   y |  j  j |  ƒ } Wn t k
 r3 |  j ƒ  n X| sI t d ƒ ‚ n  t |  j  j | ƒ ƒ } | t |  j | ƒ f S(   uo  
        Receive a single device from the monitor.

        The caller must make sure, that there are events available in the
        event queue.  The call blocks, until a device is available.

        If a device was available, return ``(action, device)``.  ``device``
        is the :class:`Device` object describing the device.  ``action`` is
        a string describing the action.  udev informs about the following
        actions:

        ``'add'``
          A device has been added (e.g. a USB device was plugged in)
        ``'remove'``
          A device has been removed (e.g. a USB device was unplugged)
        ``'change'``
          Something about the device changed (e.g. a device property)
        ``'move'``
          The device was renamed, moved, or re-parented

        Raise :exc:`~exceptions.EnvironmentError`, if no device could be
        read.
        u   Could not receive device(   R   t   udev_monitor_receive_deviceR    R   R   t   udev_device_get_actionR
   R   (   R   t   device_pt   action(    (    s2   /usr/lib/python2.7/site-packages/pyudev/monitor.pyt   receive_device  s    c         c` st   |  j  ƒ  t t j ƒ  ƒ R } | j |  t j ƒ x5 t ri t | j ƒ } x | D] } |  j	 ƒ  VqQ Wq5 WWd QXd S(   uð  
        Wait for incoming events and receive them upon arrival.

        This methods implicitly calls :meth:`enable_receiving`, and starts
        polling the :meth:`fileno` of this monitor.  If a event comes in, it
        receives the corresponding device and yields it to the caller.

        The returned iterator is endless, and continues receiving devices
        without ever stopping.

        Yields ``(action, device)`` (see :meth:`receive_device` for a
        description).
        N(
   R4   R   t   selectt   epollt   registert   EPOLLINt   TrueR	   t   pollR<   (   R   t   notifiert   eventst   event(    (    s2   /usr/lib/python2.7/site-packages/pyudev/monitor.pyt   __iter__9  s    
	N(   t   __name__t
   __module__t   __doc__t   NoneR   R   R   t   classmethodR$   R&   R(   R-   R0   R2   R4   t   startR7   R<   RF   (    (    (    s2   /usr/lib/python2.7/site-packages/pyudev/monitor.pyR   /   s    									"t   MonitorObserverc           B` s2   e  Z d  Z d „  Z d „  Z d „  Z d „  Z RS(   u$  
    A :class:`~threading.Thread` class to observe a :class:`Monitor` in background:

    >>> context = pyudev.Context()
    >>> monitor = pyudev.Monitor.from_netlink(context)
    >>> monitor.filter_by(subsystem='input')
    >>> def print_device_event(action, device):
    ...     print('background event {0}: {1}'.format(action, device))
    >>> observer = MonitorObserver(monitor, print_device_event, name='monitor-observer')
    >>> observer.daemon
    True
    >>> observer.start()

    In the above example, input device events will be printed in background,
    until :meth:`stop()` is called on ``observer``.

    .. note::

       Instances of this class are always created as daemon thread.  If you do
       not want to use daemon threads for monitoring, you need explicitly set
       :attr:`~threading.Thread.daemon` to ``False`` before invoking
       :meth:`~threading.Thread.start()`.

    .. versionadded:: 0.14

    .. versionchanged:: 0.15
       :meth:`Monitor.enable_receiving()` is implicitly called when the thread
       is started.
    c         O` sJ   t  j |  | | Ž | |  _ t |  _ t j ƒ  \ |  _ |  _ | |  _	 d S(   uê  
        Create a new observer for the given ``monitor``.

        ``monitor`` is the :class:`Monitor` to observe.  ``event_handler`` is a
        callable with the signature ``event_handler(action, device)``, where
        ``action`` is a string describing the event (see
        :meth:`Monitor.receive_device`), and ``device`` is the :class:`Device`
        object that caused this event.  This callable is invoked for every
        device event received through ``monitor``.

        .. warning::

           ``event_handler`` is always invoked in this background thread, and
           *not* in the calling thread.

        ``args`` and ``kwargs`` are passed unchanged to the parent constructor
        of :class:`~threading.Thread`.
        N(
   R   R   R#   RA   t   daemont   ost   pipet   _stop_event_sourcet   _stop_event_sinkt   _handle_event(   R   R#   t   event_handlert   argst   kwargs(    (    s2   /usr/lib/python2.7/site-packages/pyudev/monitor.pyR   o  s
    		c         C` sÜ   |  j  j ƒ  t t j ƒ  ƒ · } | j |  j t j ƒ | j |  j  t j ƒ x t rÑ xt t	 | j
 ƒ D]c \ } } | |  j k r– t j |  j ƒ d  S|  j  j ƒ  } | rg | \ } } |  j | | ƒ qg qg WqQ WWd  QXd  S(   N(   R#   R4   R   R=   R>   R?   RQ   R@   RA   R	   RB   RO   t   closeR<   RS   (   R   RC   t   fdR   RE   R;   t   device(    (    s2   /usr/lib/python2.7/site-packages/pyudev/monitor.pyt   runŠ  s    	c         C` sK   |  j  d k r d Sz t j |  j  d ƒ Wd t j |  j  ƒ d |  _  Xd S(   uT  
        Send a stop signal to the background thread.

        The background thread will eventually exit, but it may still be running
        when this method returns.  This method is essentially the asynchronous
        equivalent to :meth:`stop()`.

        .. note::

           The underlying :attr:`monitor` is *not* stopped.
        Ns   (   RR   RJ   RO   t   writeRW   (   R   (    (    s2   /usr/lib/python2.7/site-packages/pyudev/monitor.pyt	   send_stopž  s    c         C` s   |  j  ƒ  |  j ƒ  d S(   u  
        Stop the background thread.

        .. warning::

           Calling this method from the ``event_handler`` results in a dead
           lock.  If you need to stop the observer from ``event_handler``, use
           :meth:`send_stop`, and be prepared to get some more events before
           the observer actually exits.

        Send a stop signal to the backgroud (see :meth:`send_stop`) and waits
        for the background thread to exit (see :meth:`~threading.Thread.join`).
        After this method returns, it is guaranteed that the ``event_handler``
        passed to :meth:`MonitorObserver.__init__()` is not longer called for
        any event from :attr:`monitor`.

        .. note::

           The underlying :attr:`monitor` is *not* stopped.
        N(   R\   t   join(   R   (    (    s2   /usr/lib/python2.7/site-packages/pyudev/monitor.pyt   stop´  s    
(   RG   RH   RI   R   RZ   R\   R^   (    (    (    s2   /usr/lib/python2.7/site-packages/pyudev/monitor.pyRM   P  s
   			(   RI   t
   __future__R    R   R   R   RO   R   R=   t	   threadingR   t
   contextlibR   t   pyudev._utilR   R   R   R	   t   pyudev.coreR
   t   __all__t   objectR   RM   (    (    (    s2   /usr/lib/python2.7/site-packages/pyudev/monitor.pyt   <module>   s   ""ÿ "