Skip to content

Commit

Permalink
cleanup (WIP)
Browse files Browse the repository at this point in the history
  • Loading branch information
eblot committed Apr 6, 2024
1 parent 5ca35f4 commit 1001c46
Show file tree
Hide file tree
Showing 29 changed files with 336 additions and 342 deletions.
8 changes: 7 additions & 1 deletion .pylintrc
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
[MASTER]

init-hook='import sys; sys.path.append(".")'

[MESSAGES CONTROL]

disable=
Expand All @@ -9,4 +13,6 @@ disable=
too-many-locals,
too-many-nested-blocks,
too-many-public-methods,
too-many-statements
too-many-return-statements,
too-many-statements,
unspecified-encoding
25 changes: 12 additions & 13 deletions pyftdi/bin/ftconf.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@
"""Simple FTDI EEPROM configurator.
"""

# Copyright (c) 2019-2022, Emmanuel Blot <emmanuel.blot@free.fr>
# Copyright (c) 2019-2024, Emmanuel Blot <emmanuel.blot@free.fr>
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause

from argparse import ArgumentParser, FileType
from io import StringIO
from logging import Formatter, StreamHandler, DEBUG, ERROR
from sys import modules, stderr, stdout
from sys import exit as sys_exit, modules, stderr, stdout
from textwrap import fill
from traceback import format_exc
from pyftdi import FtdiLogger
Expand Down Expand Up @@ -86,9 +86,9 @@ def main():

extra = argparser.add_argument_group(title='Extras')
extra.add_argument('-v', '--verbose', action='count', default=0,
help='increase verbosity')
help='increase verbosity')
extra.add_argument('-d', '--debug', action='store_true',
help='enable debug mode')
help='enable debug mode')
args = argparser.parse_args()
debug = args.debug

Expand Down Expand Up @@ -138,13 +138,12 @@ def main():
helpstr = ', '.join(sorted(eeprom.properties))
print(fill(helpstr, initial_indent=' ',
subsequent_indent=' '))
exit(1)
sys_exit(1)
for sep in ':=':
if sep in conf:
name, value = conf.split(sep, 1)
if not value:
argparser.error('Configuration %s without value' %
conf)
argparser.error(f'Configuration {conf} without value')
if value == 'help':
value = '?'
helpio = StringIO()
Expand All @@ -153,10 +152,10 @@ def main():
if helpstr:
print(fill(helpstr, initial_indent=' ',
subsequent_indent=' '))
exit(1)
sys_exit(1)
break
else:
argparser.error('Missing name:value separator in %s' % conf)
argparser.error(f'Missing name:value separator in {conf}')
if args.vid:
eeprom.set_property('vendor_id', args.vid)
if args.pid:
Expand All @@ -166,7 +165,7 @@ def main():
if args.hexblock is not None:
indent = ' ' * args.hexblock
for pos in range(0, len(eeprom.data), 16):
hexa = ' '.join(['%02x' % x for x in eeprom.data[pos:pos+16]])
hexa = ' '.join([f'{x:02x}' for x in eeprom.data[pos:pos+16]])
print(indent, hexa, sep='')
if args.update:
if eeprom.commit(False, no_crc=args.full_erase):
Expand All @@ -181,12 +180,12 @@ def main():
eeprom.save_config(ofp)

except (ImportError, IOError, NotImplementedError, ValueError) as exc:
print('\nError: %s' % exc, file=stderr)
print(f'\nError: {exc}', file=stderr)
if debug:
print(format_exc(chain=False), file=stderr)
exit(1)
sys_exit(1)
except KeyboardInterrupt:
exit(2)
sys_exit(2)


if __name__ == '__main__':
Expand Down
10 changes: 5 additions & 5 deletions pyftdi/bin/ftdi_urls.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#!/usr/bin/env python3

# Copyright (c) 2019-2022, Emmanuel Blot <emmanuel.blot@free.fr>
# Copyright (c) 2019-2024, Emmanuel Blot <emmanuel.blot@free.fr>
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
Expand All @@ -9,7 +9,7 @@

from argparse import ArgumentParser, FileType
from logging import Formatter, StreamHandler, DEBUG, ERROR
from sys import modules, stderr
from sys import exit as sys_exit, modules, stderr
from traceback import format_exc
from pyftdi import FtdiLogger
from pyftdi.ftdi import Ftdi
Expand Down Expand Up @@ -62,12 +62,12 @@ def main():
Ftdi.show_devices()

except (ImportError, IOError, NotImplementedError, ValueError) as exc:
print('\nError: %s' % exc, file=stderr)
print(f'\nError: {exc}', file=stderr)
if debug:
print(format_exc(chain=False), file=stderr)
exit(1)
sys_exit(1)
except KeyboardInterrupt:
exit(2)
sys_exit(2)


if __name__ == '__main__':
Expand Down
16 changes: 8 additions & 8 deletions pyftdi/bin/i2cscan.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

from argparse import ArgumentParser, FileType
from logging import Formatter, StreamHandler, getLogger, DEBUG, ERROR
from sys import modules, stderr
from sys import exit as sys_exit, modules, stderr
from traceback import format_exc
from pyftdi import FtdiLogger
from pyftdi.ftdi import Ftdi
Expand Down Expand Up @@ -75,12 +75,12 @@ def scan(cls, url: str, smb_mode: bool = True, force: bool = False) \
i2c.terminate()
columns = 16
row = 0
print(' %s' % ''.join(' %01X ' % col for col in range(columns)))
print(' ', ''.join(f' {col:01X} ' for col in range(columns)))
while True:
chunk = slaves[row:row+columns]
if not chunk:
break
print(' %1X:' % (row//columns), ' '.join(chunk))
print(f' {row//columns:01X}:', ' '.join(chunk))
row += columns


Expand Down Expand Up @@ -140,16 +140,16 @@ def main():
I2cBusScanner.scan(args.device, not args.no_smb, args.force)

except (ImportError, IOError, NotImplementedError, ValueError) as exc:
print('\nError: %s' % exc, file=stderr)
print(f'\nError: {exc}', file=stderr)
if debug:
print(format_exc(chain=False), file=stderr)
exit(1)
sys_exit(1)
except KeyboardInterrupt:
exit(2)
sys_exit(2)


if __name__ == '__main__':
try:
main()
except Exception as exc:
print(str(exc), file=stderr)
except Exception as _exc:
print(str(_exc), file=stderr)
37 changes: 18 additions & 19 deletions pyftdi/bin/pyterm.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
from logging import Formatter, StreamHandler, DEBUG, ERROR
from os import environ, linesep, stat
from re import search
from sys import exit as sysexit, modules, platform, stderr, stdout
from sys import exit as sys_exit, modules, platform, stderr, stdout
from time import sleep
from threading import Event, Thread
from traceback import format_exc
Expand Down Expand Up @@ -57,7 +57,7 @@ def run(self, fullmode=False, loopback=False, silent=False,
"""Switch to a pure serial terminal application"""

self._terminal.init(fullmode)
print('Entering minicom mode @ %d bps' % self._port.baudrate)
print(f'Entering minicom mode @ { self._port.baudrate} bps')
stdout.flush()
self._resume = True
# start the reader (target to host direction) within a dedicated thread
Expand Down Expand Up @@ -132,7 +132,7 @@ def _reader(self, loopback, getfunc):
except KeyboardInterrupt:
return
except Exception as exc:
print("Exception: %s" % exc)
print(f'Exception: {exc}')
if self._debug:
print(format_exc(chain=False), file=stderr)
interrupt_main()
Expand Down Expand Up @@ -182,7 +182,7 @@ def _writer(self, fullmode, silent, localecho, crlf=0):
def _cleanup(self, *args):
"""Cleanup resource before exiting"""
if args and args[0]:
print('%sAborting...' % linesep)
print(f'{linesep}Aborting...')
try:
self._resume = False
if self._port:
Expand Down Expand Up @@ -222,7 +222,7 @@ def _open_port(device, baudrate, parity, rtscts, debug=False):
if not vmo:
# unable to parse version
raise ValueError()
if tuple([int(x) for x in vmo.groups()]) < (3, 0):
if tuple(int(x) for x in vmo.groups()) < (3, 0):
# pysrial version is too old
raise ValueError()
except (ValueError, IndexError, ImportError) as exc:
Expand All @@ -243,10 +243,10 @@ def _open_port(device, baudrate, parity, rtscts, debug=False):
if not port.is_open:
port.open()
if not port.is_open:
raise IOError('Cannot open port "%s"' % device)
raise IOError(f"Cannot open port '{device}'")
if debug:
backend = port.BACKEND if hasattr(port, 'BACKEND') else '?'
print("Using serial backend '%s'" % backend)
print(f"Using serial backend '{backend}'")
return port
except SerialException as exc:
raise IOError(str(exc)) from exc
Expand All @@ -272,24 +272,23 @@ def get_default_device() -> str:
return device



def main():
"""Main routine"""
debug = False
try:
default_device = get_default_device()
argparser = ArgumentParser(description=modules[__name__].__doc__)
argparser.add_argument('-f', '--fullmode', dest='fullmode',
action='store_true',
help='use full terminal mode, exit with '
'[Ctrl]+B')
action='store_true',
help='use full terminal mode, exit with '
'[Ctrl]+B')
argparser.add_argument('device', nargs='?', default=default_device,
help='serial port device name (default: %s)' %
default_device)
help=f'serial port device name '
f'(default: {default_device}')
argparser.add_argument('-b', '--baudrate',
help='serial port baudrate (default: %d)' %
MiniTerm.DEFAULT_BAUDRATE,
default='%s' % MiniTerm.DEFAULT_BAUDRATE)
efault=str(MiniTerm.DEFAULT_BAUDRATE),
help=f'serial port baudrate '
f'(default: {MiniTerm.DEFAULT_BAUDRATE})')
argparser.add_argument('-w', '--hwflow',
action='store_true',
help='hardware flow control')
Expand Down Expand Up @@ -355,12 +354,12 @@ def main():
args.crlf)

except (IOError, ValueError) as exc:
print('\nError: %s' % exc, file=stderr)
print(f'\nError: {exc}', file=stderr)
if debug:
print(format_exc(chain=False), file=stderr)
sysexit(1)
sys_exit(1)
except KeyboardInterrupt:
sysexit(2)
sys_exit(2)


if __name__ == '__main__':
Expand Down
15 changes: 8 additions & 7 deletions pyftdi/bits.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ def __init__(self, value: Union['BitSequence', str, int] = None,
elif value is None:
pass
else:
raise BitSequenceError("Cannot initialize from a %s" % type(value))
raise BitSequenceError(f"Cannot initialize from '{type(value)}'")
self._update_length(length, msb)

def sequence(self) -> bytearray:
Expand Down Expand Up @@ -272,7 +272,7 @@ def __str__(self):
else:
j = None
chunks.append(srepr[-i-8:j])
return '%d: %s' % (len(self), ' '.join(reversed(chunks)))
return f'{len(self)}: {" ".join(reversed(chunks))}'

def __int__(self):
value = 0
Expand Down Expand Up @@ -371,14 +371,15 @@ def invert(self):
return self

def tobyte(self, msb=False):
raise BitSequenceError("Type %s cannot be converted to byte" %
type(self))
raise BitSequenceError(f'Type {type(self)} cannot be converted to '
f'byte')

def tobytes(self, msb=False, msby=False):
raise BitSequenceError("Type %s cannot be converted to bytes" %
type(self))
raise BitSequenceError(f'Type {type(self)} cannot be converted to '
f'bytes')

def matches(self, other):
# pylint: disable=missing-function-docstring
if not isinstance(self, BitSequence):
raise BitSequenceError('Not a BitSequence instance')
# the bit sequence should be of the same length
Expand Down Expand Up @@ -494,7 +495,7 @@ def to_seq(self, msb=0, lsb=0):
def __getitem__(self, index):
if isinstance(index, slice):
if index.stop == index.start:
return
return None
if index.stop < index.start:
offset = index.stop
count = index.start-index.stop+1
Expand Down

0 comments on commit 1001c46

Please sign in to comment.