ݹYc@`sdZddlmZmZmZmZddlZddlZddlZddl m Z ddl m Z ddl mZmZmZmZddlmZdd gZd efd YZd e fd YZdS(u pyudev.monitor ============== Monitor implementation. .. moduleauthor:: Sebastian Wiesner i(tprint_functiontdivisiontunicode_literalstabsolute_importN(tThread(tclosing(tensure_byte_stringtensure_unicode_stringtreraiseteintr_retry_call(tDeviceuMonitoruMonitorObservertMonitorcB`seZdZddZdZdZeddZedZ dZ ddZ d Z d Z d ZeZd Zd ZdZRS(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 `, 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`. cC`s+||_||_||_|j|_dS(N(tcontextt_as_parameter_t _socket_patht_libudev(tselfR t monitor_pt socket_path((s2/usr/lib/python2.7/site-packages/pyudev/monitor.pyt__init__Ps   cC`s2tj\}}}|j|_t||dS(N(tsystexc_infoRtfilenameR(Rt_t exc_valuet traceback((s2/usr/lib/python2.7/site-packages/pyudev/monitor.pyt_reraise_with_socket_pathVs cC`s|jj|dS(N(Rtudev_monitor_unref(R((s2/usr/lib/python2.7/site-packages/pyudev/monitor.pyt__del__[suudevcC`sa|dkr$tdj|n|jj|t|}|sTtdn|||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. ukerneluudevu8Invalid source: {0!r}. Must be one of "udev" or "kernel"uCould not create udev monitor(ukerneluudev(t ValueErrortformatRtudev_monitor_new_from_netlinkRtEnvironmentError(tclsR tsourcetmonitor((s2/usr/lib/python2.7/site-packages/pyudev/monitor.pyt from_netlink^s   cC`sL|jj|t|}|s9tdj|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(Rtudev_monitor_new_from_socketRR R(R!R RR#((s2/usr/lib/python2.7/site-packages/pyudev/monitor.pyt from_socket~s   cC`s|jj|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. (Rtudev_monitor_get_fd(R((s2/usr/lib/python2.7/site-packages/pyudev/monitor.pytfilenoscC`sKt|}|r!t|}n|jj||||jj|dS(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(RRt/udev_monitor_filter_add_match_subsystem_devtypetudev_monitor_filter_update(Rt subsystemt device_type((s2/usr/lib/python2.7/site-packages/pyudev/monitor.pyt filter_bys    cC`s-|jj|t||jj|dS(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(Rt!udev_monitor_filter_add_match_tagRR*(Rttag((s2/usr/lib/python2.7/site-packages/pyudev/monitor.pyt filter_by_tags cC`s$|jj||jj|dS(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(Rtudev_monitor_filter_removeR*(R((s2/usr/lib/python2.7/site-packages/pyudev/monitor.pyt remove_filterscC`s6y|jj|Wntk r1|jnXdS(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(Rtudev_monitor_enable_receivingR R(R((s2/usr/lib/python2.7/site-packages/pyudev/monitor.pytenable_receivings  cC`s9y|jj||Wntk r4|jnXdS(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(Rt$udev_monitor_set_receive_buffer_sizeR R(Rtsize((s2/usr/lib/python2.7/site-packages/pyudev/monitor.pytset_receive_buffer_sizes cC`swy|jj|}Wntk r3|jnX|sItdnt|jj|}|t|j|fS(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. uCould not receive device(Rtudev_monitor_receive_deviceR RRtudev_device_get_actionR R (Rtdevice_ptaction((s2/usr/lib/python2.7/site-packages/pyudev/monitor.pytreceive_devices cc`st|jttjR}|j|tjx5trit|j}x|D]}|j VqQWq5WWdQXdS(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( R4RtselecttepolltregistertEPOLLINtTrueR tpollR<(Rtnotifierteventstevent((s2/usr/lib/python2.7/site-packages/pyudev/monitor.pyt__iter__9s   N(t__name__t __module__t__doc__tNoneRRRt classmethodR$R&R(R-R0R2R4tstartR7R<RF(((s2/usr/lib/python2.7/site-packages/pyudev/monitor.pyR /s          "tMonitorObservercB`s2eZdZdZdZdZdZRS(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. cO`sJtj|||||_t|_tj\|_|_||_ dS(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( RRR#RAtdaemontostpipet_stop_event_sourcet_stop_event_sinkt _handle_event(RR#t event_handlertargstkwargs((s2/usr/lib/python2.7/site-packages/pyudev/monitor.pyRos   cC`s|jjttj}|j|jtj|j|jtjxtrxtt |j D]c\}}||jkrt j |jdS|jj }|rg|\}}|j||qgqgWqQWWdQXdS(N(R#R4RR=R>R?RQR@RAR RBROtcloseR<RS(RRCtfdRRER;tdevice((s2/usr/lib/python2.7/site-packages/pyudev/monitor.pytruns   cC`sK|jdkrdSztj|jdWdtj|jd|_XdS(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(RRRJROtwriteRW(R((s2/usr/lib/python2.7/site-packages/pyudev/monitor.pyt send_stops cC`s|j|jdS(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\tjoin(R((s2/usr/lib/python2.7/site-packages/pyudev/monitor.pytstops (RGRHRIRRZR\R^(((s2/usr/lib/python2.7/site-packages/pyudev/monitor.pyRMPs    (RIt __future__RRRRRORR=t threadingRt contextlibRt pyudev._utilRRRR t pyudev.coreR t__all__tobjectR RM(((s2/usr/lib/python2.7/site-packages/pyudev/monitor.pyts"   " "