11# encoding: utf-8
22
33import os
4+ import fcntl
45from select import select
56from collections import namedtuple
67
78from evdev import _input , _uinput , ecodes , util
89from evdev .events import InputEvent
910
1011
12+ #--------------------------------------------------------------------------
13+ class EvdevError (Exception ):
14+ pass
15+
1116#--------------------------------------------------------------------------
1217_AbsInfo = namedtuple ('AbsInfo' , ['value' , 'min' , 'max' , 'fuzz' , 'flat' , 'resolution' ])
1318_KbdInfo = namedtuple ('KbdInfo' , ['repeat' , 'delay' ])
@@ -89,8 +94,15 @@ def __init__(self, dev):
8994 #: Path to input device.
9095 self .fn = dev
9196
97+ # Certain operations are possible only when the device is opened in
98+ # read-write mode.
99+ try :
100+ fd = os .open (dev , os .O_RDWR | os .O_NONBLOCK )
101+ except OSError :
102+ fd = os .open (dev , os .O_RDONLY | os .O_NONBLOCK )
103+
92104 #: A non-blocking file descriptor to the device file.
93- self .fd = os . open ( dev , os . O_RDWR | os . O_NONBLOCK )
105+ self .fd = fd
94106
95107 # Returns (bustype, vendor, product, version, name, phys, capabilities).
96108 info_res = _input .ioctl_devinfo (self .fd )
@@ -177,6 +189,19 @@ def capabilities(self, verbose=False, absinfo=True):
177189 else :
178190 return self ._capabilities (absinfo )
179191
192+ def need_write (func ):
193+ '''
194+ Decorator that raises EvdevError() if there is no write access to the
195+ input device.
196+ '''
197+ def wrapper (* args ):
198+ fd = args [0 ].fd
199+ if fcntl .fcntl (fd , fcntl .F_GETFL ) & os .O_RDWR :
200+ return func (* args )
201+ msg = 'no write access to device "%s"' % args [0 ].fn
202+ raise EvdevError (msg )
203+ return wrapper
204+
180205 def leds (self , verbose = False ):
181206 '''
182207 Return currently set LED keys. For example::
@@ -195,6 +220,7 @@ def leds(self, verbose=False):
195220
196221 return leds
197222
223+ @need_write
198224 def set_led (self , led_num , value ):
199225 '''
200226 Set the state of the selected LED. For example::
0 commit comments