Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

logging: Simplify imports and initialization #2257

Merged
merged 4 commits into from
Feb 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 7 additions & 8 deletions lib/hidapi/hidapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,15 @@
"""
import atexit
import ctypes
import logging
import platform as _platform

from collections import namedtuple
from logging import INFO as _INFO
from logging import getLogger
from threading import Thread
from time import sleep

_log = getLogger(__name__)
del getLogger
logger = logging.getLogger(__name__)

native_implementation = 'hidapi'

# Device info as expected by Solaar
Expand Down Expand Up @@ -257,14 +256,14 @@ def _match(action, device, filterfn):
if len(report) == 1 + 19 and report[0] == 0x11:
device['hidpp_long'] = True
except HIDError as e: # noqa: F841
if _log.isEnabledFor(_INFO):
_log.info(f"Error opening device {device['path']} ({bus_id}/{vid:04X}/{pid:04X}) for hidpp check: {e}")
if logger.isEnabledFor(logging.INFO):
logger.info(f"Error opening device {device['path']} ({bus_id}/{vid:04X}/{pid:04X}) for hidpp check: {e}")
finally:
if device_handle:
close(device_handle)

if _log.isEnabledFor(_INFO):
_log.info(
if logger.isEnabledFor(logging.INFO):
logger.info(
'Found device BID %s VID %04X PID %04X HID++ %s %s', bus_id, vid, pid, device['hidpp_short'], device['hidpp_long']
)

Expand Down
17 changes: 8 additions & 9 deletions lib/hidapi/udev.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,12 @@
"""

import errno as _errno
import logging
import os as _os
import warnings as _warnings

# the tuple object we'll expose when enumerating devices
from collections import namedtuple
from logging import INFO as _INFO
from logging import getLogger
from select import select as _select
from time import sleep
from time import time as _timestamp
Expand All @@ -42,8 +41,8 @@
from pyudev import Devices as _Devices
from pyudev import Monitor as _Monitor

_log = getLogger(__name__)
del getLogger
logger = logging.getLogger(__name__)

native_implementation = 'udev'
fileopen = open

Expand Down Expand Up @@ -123,7 +122,7 @@ def _match(action, device, filterfn):
return
except Exception as e: # if can't process report descriptor fall back to old scheme
hidpp_short = hidpp_long = None
_log.warn(
logger.warning(
'Report Descriptor not processed for DEVICE %s BID %s VID %s PID %s: %s', device.device_node, bid, vid, pid, e
)

Expand All @@ -147,8 +146,8 @@ def _match(action, device, filterfn):
intf_device = device.find_parent('usb', 'usb_interface')
usb_interface = None if intf_device is None else intf_device.attributes.asint('bInterfaceNumber')
# print('*** usb interface', action, device, 'usb_interface:', intf_device, usb_interface, interface_number)
if _log.isEnabledFor(_INFO):
_log.info(
if logger.isEnabledFor(logging.INFO):
logger.info(
'Found device %s BID %s VID %s PID %s HID++ %s %s USB %s %s', device.device_node, bid, vid, pid, hidpp_short,
hidpp_long, usb_interface, interface_number
)
Expand Down Expand Up @@ -325,14 +324,14 @@ def open_path(device_path):
assert device_path
assert device_path.startswith('/dev/hidraw')

_log.info('OPEN PATH %s', device_path)
logger.info('OPEN PATH %s', device_path)
retrycount = 0
while (retrycount < 3):
retrycount += 1
try:
return _os.open(device_path, _os.O_RDWR | _os.O_SYNC)
except OSError as e:
_log.info('OPEN PATH FAILED %s ERROR %s %s', device_path, e.errno, e)
logger.info('OPEN PATH FAILED %s ERROR %s %s', device_path, e.errno, e)
if e.errno == _errno.EACCES:
sleep(0.1)
else:
Expand Down
9 changes: 4 additions & 5 deletions lib/logitech_receiver/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,11 @@
from .hidpp20 import FeatureCallError, FeatureNotSupported # noqa: F401
from .receiver import Receiver # noqa: F401

_DEBUG = logging.DEBUG
_log = logging.getLogger(__name__)
_log.setLevel(logging.root.level)
logger = logging.getLogger(__name__)
logger.setLevel(logging.root.level)
# if logging.root.level > logging.DEBUG:
# _log.addHandler(logging.NullHandler())
# _log.propagate = 0
# logger.addHandler(logging.NullHandler())
# logger.propagate = 0

del logging

Expand Down
74 changes: 36 additions & 38 deletions lib/logitech_receiver/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,11 @@
# Base low-level functions used by the API proper.
# Unlikely to be used directly unless you're expanding the API.

import logging
import threading as _threading

from collections import namedtuple
from contextlib import contextmanager
from logging import DEBUG as _DEBUG
from logging import INFO as _INFO
from logging import getLogger
from random import getrandbits as _random_bits
from struct import pack as _pack
from time import time as _timestamp
Expand All @@ -40,8 +38,7 @@
from .common import KwException as _KwException
from .common import strhex as _strhex

_log = getLogger(__name__)
del getLogger
logger = logging.getLogger(__name__)

#
#
Expand Down Expand Up @@ -184,10 +181,10 @@ def close(handle):
_hid.close(handle)
else:
handle.close()
# _log.info("closed receiver handle %r", handle)
# logger.info("closed receiver handle %r", handle)
return True
except Exception:
# _log.exception("closing receiver handle %r", handle)
# logger.exception("closing receiver handle %r", handle)
pass

return False
Expand All @@ -214,13 +211,13 @@ def write(handle, devnumber, data, long_message=False):
wdata = _pack('!BB18s', HIDPP_LONG_MESSAGE_ID, devnumber, data)
else:
wdata = _pack('!BB5s', HIDPP_SHORT_MESSAGE_ID, devnumber, data)
if _log.isEnabledFor(_DEBUG):
_log.debug('(%s) <= w[%02X %02X %s %s]', handle, ord(wdata[:1]), devnumber, _strhex(wdata[2:4]), _strhex(wdata[4:]))
if logger.isEnabledFor(logging.DEBUG):
logger.debug('(%s) <= w[%02X %02X %s %s]', handle, ord(wdata[:1]), devnumber, _strhex(wdata[2:4]), _strhex(wdata[4:]))

try:
_hid.write(int(handle), wdata)
except Exception as reason:
_log.error('write failed, assuming handle %r no longer available', handle)
logger.error('write failed, assuming handle %r no longer available', handle)
close(handle)
raise NoReceiver(reason=reason)

Expand Down Expand Up @@ -251,7 +248,7 @@ def check_message(data):
if report_lengths.get(report_id) == len(data):
return True
else:
_log.warn('unexpected message size: report_id %02X message %s' % (report_id, _strhex(data)))
logger.warning('unexpected message size: report_id %02X message %s' % (report_id, _strhex(data)))
return False


Expand All @@ -269,16 +266,17 @@ def _read(handle, timeout):
timeout = int(timeout * 1000)
data = _hid.read(int(handle), _MAX_READ_SIZE, timeout)
except Exception as reason:
_log.warn('read failed, assuming handle %r no longer available', handle)
logger.warning('read failed, assuming handle %r no longer available', handle)
close(handle)
raise NoReceiver(reason=reason)

if data and check_message(data): # ignore messages that fail check
report_id = ord(data[:1])
devnumber = ord(data[1:2])

if _log.isEnabledFor(_DEBUG) and (report_id != DJ_MESSAGE_ID or ord(data[2:3]) > 0x10): # ignore DJ input messages
_log.debug('(%s) => r[%02X %02X %s %s]', handle, report_id, devnumber, _strhex(data[2:4]), _strhex(data[4:]))
if logger.isEnabledFor(logging.DEBUG
) and (report_id != DJ_MESSAGE_ID or ord(data[2:3]) > 0x10): # ignore DJ input messages
logger.debug('(%s) => r[%02X %02X %s %s]', handle, report_id, devnumber, _strhex(data[2:4]), _strhex(data[4:]))

return report_id, devnumber, data[2:]

Expand All @@ -299,7 +297,7 @@ def _skip_incoming(handle, ihandle, notifications_hook):
# read whatever is already in the buffer, if any
data = _hid.read(ihandle, _MAX_READ_SIZE, 0)
except Exception as reason:
_log.error('read failed, assuming receiver %s no longer available', handle)
logger.error('read failed, assuming receiver %s no longer available', handle)
close(handle)
raise NoReceiver(reason=reason)

Expand Down Expand Up @@ -363,8 +361,8 @@ def make_notification(report_id, devnumber, data):
def handle_lock(handle):
with request_lock:
if handles_lock.get(handle) is None:
if _log.isEnabledFor(_INFO):
_log.info('New lock %s', repr(handle))
if logger.isEnabledFor(logging.INFO):
logger.info('New lock %s', repr(handle))
handles_lock[handle] = _threading.Lock() # Serialize requests on the handle
return handles_lock[handle]

Expand All @@ -375,7 +373,7 @@ def acquire_timeout(lock, handle, timeout):
result = lock.acquire(timeout=timeout)
try:
if not result:
_log.error('lock on handle %d not acquired, probably due to timeout', int(handle))
logger.error('lock on handle %d not acquired, probably due to timeout', int(handle))
yield result
finally:
if result:
Expand Down Expand Up @@ -414,16 +412,16 @@ def request(handle, devnumber, request_id, *params, no_reply=False, return_error
params = b''.join(_pack('B', p) if isinstance(p, int) else p for p in params)
else:
params = b''
# if _log.isEnabledFor(_DEBUG):
# _log.debug("(%s) device %d request_id {%04X} params [%s]", handle, devnumber, request_id, _strhex(params))
# if logger.isEnabledFor(logging.DEBUG):
# logger.debug("(%s) device %d request_id {%04X} params [%s]", handle, devnumber, request_id, _strhex(params))
request_data = _pack('!H', request_id) + params

ihandle = int(handle)
notifications_hook = getattr(handle, 'notifications_hook', None)
try:
_skip_incoming(handle, ihandle, notifications_hook)
except NoReceiver:
_log.warn('device or receiver disconnected')
logger.warning('device or receiver disconnected')
return None
write(ihandle, devnumber, request_data, long_message)

Expand All @@ -444,16 +442,16 @@ def request(handle, devnumber, request_id, *params, no_reply=False, return_error
]:
error = ord(reply_data[3:4])

if _log.isEnabledFor(_DEBUG):
_log.debug(
if logger.isEnabledFor(logging.DEBUG):
logger.debug(
'(%s) device 0x%02X error on request {%04X}: %d = %s', handle, devnumber, request_id, error,
_hidpp10.ERROR[error]
)
return _hidpp10.ERROR[error] if return_error else None
if reply_data[:1] == b'\xFF' and reply_data[1:3] == request_data[:2]:
# a HID++ 2.0 feature call returned with an error
error = ord(reply_data[3:4])
_log.error(
logger.error(
'(%s) device %d error on feature request {%04X}: %d = %s', handle, devnumber, request_id, error,
_hidpp20.ERROR[error]
)
Expand Down Expand Up @@ -481,16 +479,16 @@ def request(handle, devnumber, request_id, *params, no_reply=False, return_error
n = make_notification(report_id, reply_devnumber, reply_data)
if n:
notifications_hook(n)
# elif _log.isEnabledFor(_DEBUG):
# _log.debug("(%s) ignoring reply %02X [%s]", handle, reply_devnumber, _strhex(reply_data))
# elif _log.isEnabledFor(_DEBUG):
# _log.debug("(%s) ignoring reply %02X [%s]", handle, reply_devnumber, _strhex(reply_data))
# elif logger.isEnabledFor(logging.DEBUG):
# logger.debug("(%s) ignoring reply %02X [%s]", handle, reply_devnumber, _strhex(reply_data))
# elif logger.isEnabledFor(logging.DEBUG):
# logger.debug("(%s) ignoring reply %02X [%s]", handle, reply_devnumber, _strhex(reply_data))

delta = _timestamp() - request_started
# if _log.isEnabledFor(_DEBUG):
# _log.debug("(%s) still waiting for reply, delta %f", handle, delta)
# if logger.isEnabledFor(logging.DEBUG):
# logger.debug("(%s) still waiting for reply, delta %f", handle, delta)

_log.warn(
logger.warning(
'timeout (%0.2f/%0.2f) on device %d request {%04X} params [%s]', delta, timeout, devnumber, request_id,
_strhex(params)
)
Expand All @@ -501,14 +499,14 @@ def ping(handle, devnumber, long_message=False):
"""Check if a device is connected to the receiver.
:returns: The HID protocol supported by the device, as a floating point number, if the device is active.
"""
if _log.isEnabledFor(_DEBUG):
_log.debug('(%s) pinging device %d', handle, devnumber)
if logger.isEnabledFor(logging.DEBUG):
logger.debug('(%s) pinging device %d', handle, devnumber)
with acquire_timeout(handle_lock(handle), handle, 10.):
notifications_hook = getattr(handle, 'notifications_hook', None)
try:
_skip_incoming(handle, int(handle), notifications_hook)
except NoReceiver:
_log.warn('device or receiver disconnected')
logger.warning('device or receiver disconnected')
return

# randomize the SoftwareId and mark byte to be able to identify the ping
Expand Down Expand Up @@ -537,16 +535,16 @@ def ping(handle, devnumber, long_message=False):
if error == _hidpp10.ERROR.resource_error or error == _hidpp10.ERROR.connection_request_failed:
return # device unreachable
if error == _hidpp10.ERROR.unknown_device: # no paired device with that number
_log.error('(%s) device %d error on ping request: unknown device', handle, devnumber)
logger.error('(%s) device %d error on ping request: unknown device', handle, devnumber)
raise NoSuchDevice(number=devnumber, request=request_id)

if notifications_hook:
n = make_notification(report_id, reply_devnumber, reply_data)
if n:
notifications_hook(n)
# elif _log.isEnabledFor(_DEBUG):
# _log.debug("(%s) ignoring reply %02X [%s]", handle, reply_devnumber, _strhex(reply_data))
# elif logger.isEnabledFor(logging.DEBUG):
# logger.debug("(%s) ignoring reply %02X [%s]", handle, reply_devnumber, _strhex(reply_data))

delta = _timestamp() - request_started

_log.warn('(%s) timeout (%0.2f/%0.2f) on device %d ping', handle, delta, _PING_TIMEOUT, devnumber)
logger.warning('(%s) timeout (%0.2f/%0.2f) on device %d ping', handle, delta, _PING_TIMEOUT, devnumber)
Loading
Loading