def queryWirelessDevice(self,iface):
try:
from pythonwifi.iwlibs import Wireless
import errno
except ImportError:
return False
else:
try:
ifobj = Wireless(iface) # a Wireless NIC Object
wlanresponse = ifobj.getAPaddr()
except IOError, (error_no, error_str):
if error_no in (errno.EOPNOTSUPP, errno.ENODEV, errno.EPERM):
return False
else:
print "error: ",error_no,error_str
return True
else:
return True
python类ENODEV的实例源码
def queryWirelessDevice(self,iface):
try:
from pythonwifi.iwlibs import Wireless
import errno
except ImportError:
return False
else:
try:
ifobj = Wireless(iface) # a Wireless NIC Object
wlanresponse = ifobj.getAPaddr()
except IOError, (error_no, error_str):
if error_no in (errno.EOPNOTSUPP, errno.ENODEV, errno.EPERM):
return False
else:
print "error: ",error_no,error_str
return True
else:
return True
def test_init_linux_version_ack_err(self, mocker, transport): # noqa: F811
mocker.patch('nfc.clf.pn532.Device.__init__').return_value = None
mocker.patch('nfc.clf.pn532.open').return_value = ["cpuinfo"]
mocker.patch('os.system').return_value = -1
sys.platform = "linux"
transport.write.return_value = None
transport.read.side_effect = [
ERR(), # GetFirmwareVersion
]
with pytest.raises(IOError) as excinfo:
nfc.clf.pn532.init(transport)
assert excinfo.value.errno == errno.ENODEV
assert transport.write.mock_calls == [call(_) for _ in [
HEX(10 * '00') + CMD('02'), # GetFirmwareVersion
]]
def test_init_linux_version_rsp_err(self, mocker, transport): # noqa: F811
mocker.patch('nfc.clf.pn532.Device.__init__').return_value = None
mocker.patch('nfc.clf.pn532.open').return_value = ["cpuinfo"]
mocker.patch('os.system').return_value = -1
sys.platform = "linux"
transport.write.return_value = None
transport.read.side_effect = [
ACK(), ERR(), # GetFirmwareVersion
]
with pytest.raises(IOError) as excinfo:
nfc.clf.pn532.init(transport)
assert excinfo.value.errno == errno.ENODEV
assert transport.write.mock_calls == [call(_) for _ in [
HEX(10 * '00') + CMD('02'), # GetFirmwareVersion
]]
def test_init_linux_sam_cfg_ack_err(self, mocker, transport): # noqa: F811
mocker.patch('nfc.clf.pn532.Device.__init__').return_value = None
mocker.patch('nfc.clf.pn532.open').return_value = ["cpuinfo"]
mocker.patch('os.system').return_value = -1
sys.platform = "linux"
transport.write.return_value = None
transport.read.side_effect = [
ACK(), RSP('03 32010607'), # GetFirmwareVersion
ERR(), # SAMConfiguration
]
with pytest.raises(IOError) as excinfo:
nfc.clf.pn532.init(transport)
assert excinfo.value.errno == errno.ENODEV
assert transport.write.mock_calls == [call(_) for _ in [
HEX(10 * '00') + CMD('02'), # GetFirmwareVersion
HEX(10 * '00') + CMD('14 010000'), # SAMConfiguration
]]
def queryWirelessDevice(self,iface):
try:
from pythonwifi.iwlibs import Wireless
import errno
except ImportError:
return False
else:
try:
ifobj = Wireless(iface) # a Wireless NIC Object
wlanresponse = ifobj.getAPaddr()
except IOError, (error_no, error_str):
if error_no in (errno.EOPNOTSUPP, errno.ENODEV, errno.EPERM):
return False
else:
print "error: ",error_no,error_str
return True
else:
return True
def rfkill_block(idx):
"""
blocks the device at index
:param idx: rkill index
"""
if not os.path.exists(os.path.join(spath,"rfkill{0}".format(idx))):
raise pyric.error(errno.ENODEV,"No device at {0}".format(idx))
fout = None
try:
rfke = rfkh.rfkill_event(idx,rfkh.RFKILL_TYPE_ALL,rfkh.RFKILL_OP_CHANGE,1,0)
if _PY3_: rfke = rfke.decode('ascii')
fout = open(dpath, 'w')
fout.write(rfke)
except struct.error as e:
raise pyric.error(pyric.EUNDEF,"Error packing rfkill event {0}".format(e))
except IOError as e:
raise pyric.error(e.errno,e.message)
finally:
if fout: fout.close()
def rfkill_unblock(idx):
"""
unblocks the device at index
:param idx: rkill index
"""
if not os.path.exists(os.path.join(spath, "rfkill{0}".format(idx))):
raise pyric.error(errno.ENODEV, "No device at {0}".format(idx))
fout = None
try:
rfke = rfkh.rfkill_event(idx,rfkh.RFKILL_TYPE_ALL,rfkh.RFKILL_OP_CHANGE,0,0)
fout = open(dpath, 'w')
fout.write(rfke)
except struct.error as e:
raise pyric.error(pyric.EUNDEF,"Error packing rfkill event {0}".format(e))
except IOError as e:
raise pyric.error(e.errno,e.message)
finally:
if fout: fout.close()
def soft_blocked(idx):
"""
determines soft block state of device
:param idx: rkill index
:returns: True if device at idx is soft blocked, False otherwise
"""
if not os.path.exists(os.path.join(spath,"rfkill{0}".format(idx))):
raise pyric.error(errno.ENODEV,"No device at {0}".format(idx))
fin = None
try:
fin = open(os.path.join(spath,"rfkill{0}".format(idx),'soft'),'r')
return int(fin.read().strip()) == 1
except IOError:
raise pyric.error(errno.ENODEV,"No device at {0}".format(idx))
except ValueError:
raise pyric.error(pyric.EUNDEF,"Unexpected error")
finally:
if fin: fin.close()
def hard_blocked(idx):
"""
determines hard block state of device
:param idx: rkill index
:returns: True if device at idx is hard blocked, False otherwise
"""
if not os.path.exists(os.path.join(spath,"rfkill{0}".format(idx))):
raise pyric.error(errno.ENODEV,"No device at {0}".format(idx))
fin = None
try:
fin = open(os.path.join(spath,"rfkill{0}".format(idx),'hard'),'r')
return int(fin.read().strip()) == 1
except IOError:
raise pyric.error(errno.ENODEV,"No device at {0}".format(idx))
except ValueError:
raise pyric.error(pyric.EUNDEF,"Unexpected error")
finally:
if fin: fin.close()
def sense(self, targets, **kwargs):
"""Send discovery and activation requests to find a
target. Targets is a list of target specifications (TTA, TTB,
TTF). Not all readers may support all possible target
types. The return value is an activated target with a possibly
updated specification (bitrate) or None.
Additional keyword arguments are driver specific.
.. note:: This is a direct interface to the
driver and not needed if :meth:`connect` is used.
"""
if self.dev is None:
raise IOError(errno.ENODEV, os.strerror(errno.ENODEV))
with self.lock:
return self.dev.sense(targets, **kwargs)
def exchange(self, send_data, timeout):
"""Exchange data with an activated target (data is a command
frame) or as an activated target (data is a response
frame). Returns a target response frame (if data is send to an
activated target) or a next command frame (if data is send
from an activated target). Returns None if the communication
link broke during exchange (if data is sent as a target). The
timeout is the number of seconds to wait for data to return,
if the timeout expires an nfc.clf.TimeoutException is
raised. Other nfc.clf.DigitalProtocolExceptions may be raised
if an error is detected during communication.
.. note:: This is a direct interface to the
driver and not needed if :meth:`connect` is used.
"""
if self.dev is None:
raise IOError(errno.ENODEV, os.strerror(errno.ENODEV))
with self.lock:
return self.dev.exchange(send_data, timeout)
def set_communication_mode(self, brm, **kwargs):
"""Set the hardware communication mode. The effect of calling
this method depends on the hardware support, some drivers may
purposely ignore this function. If supported, the parameter
*brm* specifies the communication mode to choose as a string
composed of the bitrate and modulation type, for example
'212F' shall switch to 212 kbps Type F communication. Other
communication parameters may be changed with optional keyword
arguments. Currently implemented by the RC-S380 driver are the
parameters 'add-crc' and 'check-crc' when running as
initator. It is possible to set *brm* to an empty string if
bitrate and modulation shall not be changed but only optional
parameters executed.
.. note:: This is a direct interface to the
driver and not needed if :meth:`connect` is used.
"""
if self.dev is None:
raise IOError(errno.ENODEV, os.strerror(errno.ENODEV))
with self.lock:
self.dev.set_communication_mode(brm, **kwargs)
def queryWirelessDevice(self,iface):
try:
from pythonwifi.iwlibs import Wireless
import errno
except ImportError:
return False
else:
try:
ifobj = Wireless(iface) # a Wireless NIC Object
wlanresponse = ifobj.getAPaddr()
except IOError, (error_no, error_str):
if error_no in (errno.EOPNOTSUPP, errno.ENODEV, errno.EPERM):
return False
else:
print "[AdapterSetupConfiguration] error: ",error_no,error_str
return True
else:
return True
def get_interface_mac(sock: socket.socket, ifname: str) -> str:
"""Obtain a network interface's MAC address, as a string."""
ifreq = struct.pack(b'256s', ifname.encode('utf-8')[:15])
try:
info = fcntl.ioctl(sock.fileno(), SIOCGIFHWADDR, ifreq)
except OSError as e:
if e.errno is not None and e.errno == errno.ENODEV:
raise InterfaceNotFound(
"Interface not found: '%s'." % ifname)
else:
raise MACAddressNotAvailable(
"Failed to get MAC address for '%s': %s." % (
ifname, strerror(e.errno)))
else:
# Of course we're sure these are the correct indexes into the `ifreq`.
# Also, your lack of faith is disturbing.
mac = ''.join('%02x:' % char for char in info[18:24])[:-1]
return mac
def queryWirelessDevice(self,iface):
try:
from pythonwifi.iwlibs import Wireless
import errno
except ImportError:
return False
else:
try:
ifobj = Wireless(iface) # a Wireless NIC Object
wlanresponse = ifobj.getAPaddr()
except IOError, (error_no, error_str):
if error_no in (errno.EOPNOTSUPP, errno.ENODEV, errno.EPERM):
return False
else:
print "error: ",error_no,error_str
return True
else:
return True
def test_read(self, usb):
usb.usb_dev.bulkRead.side_effect = [
b'12',
b'34',
nfc.clf.transport.libusb.USBErrorTimeout,
nfc.clf.transport.libusb.USBErrorNoDevice,
nfc.clf.transport.libusb.USBError,
b'',
]
assert usb.read() == b'12'
usb.usb_dev.bulkRead.assert_called_with(0x84, 300, 0)
assert usb.read(100) == b'34'
usb.usb_dev.bulkRead.assert_called_with(0x84, 300, 100)
with pytest.raises(IOError) as excinfo:
usb.read()
assert excinfo.value.errno == errno.ETIMEDOUT
with pytest.raises(IOError) as excinfo:
usb.read()
assert excinfo.value.errno == errno.ENODEV
with pytest.raises(IOError) as excinfo:
usb.read()
assert excinfo.value.errno == errno.EIO
with pytest.raises(IOError) as excinfo:
usb.read()
assert excinfo.value.errno == errno.EIO
usb.usb_inp = None
assert usb.read() is None
def test_write(self, usb):
usb.write(b'12')
usb.usb_dev.bulkWrite.assert_called_with(0x04, b'12', 0)
usb.write(b'12', 100)
usb.usb_dev.bulkWrite.assert_called_with(0x04, b'12', 100)
usb.write(64 * b'1', 100)
usb.usb_dev.bulkWrite.assert_has_calls([
call(0x04, 64 * b'1', 100),
call(0x04, b'', 100),
])
usb.usb_dev.bulkWrite.side_effect = [
nfc.clf.transport.libusb.USBErrorTimeout,
nfc.clf.transport.libusb.USBErrorNoDevice,
nfc.clf.transport.libusb.USBError,
]
with pytest.raises(IOError) as excinfo:
usb.write(b'12')
assert excinfo.value.errno == errno.ETIMEDOUT
with pytest.raises(IOError) as excinfo:
usb.write(b'12')
assert excinfo.value.errno == errno.ENODEV
with pytest.raises(IOError) as excinfo:
usb.write(b'12')
assert excinfo.value.errno == errno.EIO
usb.usb_out = None
assert usb.write(b'12') is None
def test_init_linux_setbaud_ack_err(self, mocker, transport): # noqa: F811
mocker.patch('nfc.clf.pn532.Device.__init__').return_value = None
mocker.patch('nfc.clf.pn532.open').return_value = ["cpuinfo"]
stty = mocker.patch('os.system')
stty.side_effect = [-1, 0, None]
sys.platform = "linux"
transport.write.return_value = None
transport.read.side_effect = [
ACK(), RSP('03 32010607'), # GetFirmwareVersion
ACK(), RSP('15'), # SAMConfiguration
ERR(), # SetSerialBaudrate
]
with pytest.raises(IOError) as excinfo:
nfc.clf.pn532.init(transport)
assert excinfo.value.errno == errno.ENODEV
assert stty.mock_calls == [
call('stty -F /dev/ttyS0 921600 2> /dev/null'),
call('stty -F /dev/ttyS0 460800 2> /dev/null'),
call('stty -F /dev/ttyS0 115200 2> /dev/null'),
]
assert transport.write.mock_calls == [call(_) for _ in [
HEX(10 * '00') + CMD('02'), # GetFirmwareVersion
HEX(10 * '00') + CMD('14 010000'), # SAMConfiguration
HEX(10 * '00') + CMD('10 06'), # SetSerialBaudrate
]]
def test_init_linux_setbaud_rsp_err(self, mocker, transport): # noqa: F811
mocker.patch('nfc.clf.pn532.Device.__init__').return_value = None
mocker.patch('nfc.clf.pn532.open').return_value = ["cpuinfo"]
stty = mocker.patch('os.system')
stty.side_effect = [-1, 0, None]
sys.platform = "linux"
transport.write.return_value = None
transport.read.side_effect = [
ACK(), RSP('03 32010607'), # GetFirmwareVersion
ACK(), RSP('15'), # SAMConfiguration
ACK(), ERR(), # SetSerialBaudrate
]
with pytest.raises(IOError) as excinfo:
nfc.clf.pn532.init(transport)
assert excinfo.value.errno == errno.ENODEV
assert stty.mock_calls == [
call('stty -F /dev/ttyS0 921600 2> /dev/null'),
call('stty -F /dev/ttyS0 460800 2> /dev/null'),
call('stty -F /dev/ttyS0 115200 2> /dev/null'),
]
assert transport.write.mock_calls == [call(_) for _ in [
HEX(10 * '00') + CMD('02'), # GetFirmwareVersion
HEX(10 * '00') + CMD('14 010000'), # SAMConfiguration
HEX(10 * '00') + CMD('10 06'), # SetSerialBaudrate
]]
def __init__(self, transport):
self.transport = transport
# read ACR122U firmware version string
reader_version = self.ccid_xfr_block(bytearray.fromhex("FF00480000"))
if not reader_version.startswith("ACR122U"):
log.error("failed to retrieve ACR122U version string")
raise IOError(errno.ENODEV, os.strerror(errno.ENODEV))
if int(chr(reader_version[7])) < 2:
log.error("{0} not supported, need 2.x".format(reader_version[7:]))
raise IOError(errno.ENODEV, os.strerror(errno.ENODEV))
log.debug("initialize " + str(reader_version))
# set icc power on
log.debug("CCID ICC-POWER-ON")
frame = bytearray.fromhex("62000000000000000000")
transport.write(frame)
transport.read(100)
# disable autodetection
log.debug("Set PICC Operating Parameters")
self.ccid_xfr_block(bytearray.fromhex("FF00517F00"))
# switch red/green led off/on
log.debug("Configure Buzzer and LED")
self.set_buzzer_and_led_to_default()
super(Chipset, self).__init__(transport, logger=log)
def write(self, frame, timeout=0):
if self.usb_out is not None:
log.log(logging.DEBUG-1, ">>> %s", hexlify(frame))
try:
ep_addr = self.usb_out.getAddress()
self.usb_dev.bulkWrite(ep_addr, bytes(frame), timeout)
if len(frame) % self.usb_out.getMaxPacketSize() == 0:
self.usb_dev.bulkWrite(ep_addr, b'', timeout)
except libusb.USBErrorTimeout:
raise IOError(errno.ETIMEDOUT, os.strerror(errno.ETIMEDOUT))
except libusb.USBErrorNoDevice:
raise IOError(errno.ENODEV, os.strerror(errno.ENODEV))
except libusb.USBError as error:
log.error("%r", error)
raise IOError(errno.EIO, os.strerror(errno.EIO))
def __init__(self, path=None):
self.device = None
self.target = None
self.lock = threading.Lock()
if path and not self.open(path):
raise IOError(errno.ENODEV, os.strerror(errno.ENODEV))
def exchange(self, send_data, timeout):
"""Exchange data with an activated target (*send_data* is a command
frame) or as an activated target (*send_data* is a response
frame). Returns a target response frame (if data is send to an
activated target) or a next command frame (if data is send
from an activated target). Returns None if the communication
link broke during exchange (if data is sent as a target). The
timeout is the number of seconds to wait for data to return,
if the timeout expires an nfc.clf.TimeoutException is
raised. Other nfc.clf.CommunicationError exceptions may be raised if
an error is detected during communication.
"""
with self.lock:
if self.device is None:
raise IOError(errno.ENODEV, os.strerror(errno.ENODEV))
log.debug(">>> %s timeout=%s", print_data(send_data), str(timeout))
if isinstance(self.target, RemoteTarget):
exchange = self.device.send_cmd_recv_rsp
elif isinstance(self.target, LocalTarget):
exchange = self.device.send_rsp_recv_cmd
else:
log.error("no target for data exchange")
return None
send_time = time.time()
rcvd_data = exchange(self.target, send_data, timeout)
recv_time = time.time() - send_time
log.debug("<<< %s %.3fs", print_data(rcvd_data), recv_time)
return rcvd_data
def max_send_data_size(self):
"""The maximum number of octets that can be send with the
:meth:`exchange` method in the established operating mode.
"""
with self.lock:
if self.device is None:
raise IOError(errno.ENODEV, os.strerror(errno.ENODEV))
else:
return self.device.get_max_send_data_size(self.target)
def max_recv_data_size(self):
"""The maximum number of octets that can be received with the
:meth:`exchange` method in the established operating mode.
"""
with self.lock:
if self.device is None:
raise IOError(errno.ENODEV, os.strerror(errno.ENODEV))
else:
return self.device.get_max_recv_data_size(self.target)
def test_main():
try:
dsp = ossaudiodev.open('w')
except (ossaudiodev.error, IOError) as msg:
if msg.args[0] in (errno.EACCES, errno.ENOENT,
errno.ENODEV, errno.EBUSY):
raise unittest.SkipTest(msg)
raise
dsp.close()
support.run_unittest(__name__)
def test_main():
try:
dsp = linuxaudiodev.open('w')
except linuxaudiodev.error, msg:
if msg.args[0] in (errno.EACCES, errno.ENOENT, errno.ENODEV, errno.EBUSY):
raise unittest.SkipTest(msg)
raise
dsp.close()
run_unittest(LinuxAudioDevTests)
def test_main():
try:
dsp = ossaudiodev.open('w')
except (ossaudiodev.error, IOError), msg:
if msg.args[0] in (errno.EACCES, errno.ENOENT,
errno.ENODEV, errno.EBUSY):
raise unittest.SkipTest(msg)
raise
dsp.close()
test_support.run_unittest(__name__)
def test_main():
try:
dsp = linuxaudiodev.open('w')
except linuxaudiodev.error, msg:
if msg.args[0] in (errno.EACCES, errno.ENOENT, errno.ENODEV, errno.EBUSY):
raise unittest.SkipTest(msg)
raise
dsp.close()
run_unittest(LinuxAudioDevTests)