moved a bunch of garbage (things that have nothing to do in root) to _trash

This commit is contained in:
mia 2025-06-15 22:42:02 +02:00
parent d094982b2c
commit 3226ed29ec
2610 changed files with 0 additions and 0 deletions

247
_trash/bin/Activate.ps1 Normal file
View file

@ -0,0 +1,247 @@
<#
.Synopsis
Activate a Python virtual environment for the current PowerShell session.
.Description
Pushes the python executable for a virtual environment to the front of the
$Env:PATH environment variable and sets the prompt to signify that you are
in a Python virtual environment. Makes use of the command line switches as
well as the `pyvenv.cfg` file values present in the virtual environment.
.Parameter VenvDir
Path to the directory that contains the virtual environment to activate. The
default value for this is the parent of the directory that the Activate.ps1
script is located within.
.Parameter Prompt
The prompt prefix to display when this virtual environment is activated. By
default, this prompt is the name of the virtual environment folder (VenvDir)
surrounded by parentheses and followed by a single space (ie. '(.venv) ').
.Example
Activate.ps1
Activates the Python virtual environment that contains the Activate.ps1 script.
.Example
Activate.ps1 -Verbose
Activates the Python virtual environment that contains the Activate.ps1 script,
and shows extra information about the activation as it executes.
.Example
Activate.ps1 -VenvDir C:\Users\MyUser\Common\.venv
Activates the Python virtual environment located in the specified location.
.Example
Activate.ps1 -Prompt "MyPython"
Activates the Python virtual environment that contains the Activate.ps1 script,
and prefixes the current prompt with the specified string (surrounded in
parentheses) while the virtual environment is active.
.Notes
On Windows, it may be required to enable this Activate.ps1 script by setting the
execution policy for the user. You can do this by issuing the following PowerShell
command:
PS C:\> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
For more information on Execution Policies:
https://go.microsoft.com/fwlink/?LinkID=135170
#>
Param(
[Parameter(Mandatory = $false)]
[String]
$VenvDir,
[Parameter(Mandatory = $false)]
[String]
$Prompt
)
<# Function declarations --------------------------------------------------- #>
<#
.Synopsis
Remove all shell session elements added by the Activate script, including the
addition of the virtual environment's Python executable from the beginning of
the PATH variable.
.Parameter NonDestructive
If present, do not remove this function from the global namespace for the
session.
#>
function global:deactivate ([switch]$NonDestructive) {
# Revert to original values
# The prior prompt:
if (Test-Path -Path Function:_OLD_VIRTUAL_PROMPT) {
Copy-Item -Path Function:_OLD_VIRTUAL_PROMPT -Destination Function:prompt
Remove-Item -Path Function:_OLD_VIRTUAL_PROMPT
}
# The prior PYTHONHOME:
if (Test-Path -Path Env:_OLD_VIRTUAL_PYTHONHOME) {
Copy-Item -Path Env:_OLD_VIRTUAL_PYTHONHOME -Destination Env:PYTHONHOME
Remove-Item -Path Env:_OLD_VIRTUAL_PYTHONHOME
}
# The prior PATH:
if (Test-Path -Path Env:_OLD_VIRTUAL_PATH) {
Copy-Item -Path Env:_OLD_VIRTUAL_PATH -Destination Env:PATH
Remove-Item -Path Env:_OLD_VIRTUAL_PATH
}
# Just remove the VIRTUAL_ENV altogether:
if (Test-Path -Path Env:VIRTUAL_ENV) {
Remove-Item -Path env:VIRTUAL_ENV
}
# Just remove VIRTUAL_ENV_PROMPT altogether.
if (Test-Path -Path Env:VIRTUAL_ENV_PROMPT) {
Remove-Item -Path env:VIRTUAL_ENV_PROMPT
}
# Just remove the _PYTHON_VENV_PROMPT_PREFIX altogether:
if (Get-Variable -Name "_PYTHON_VENV_PROMPT_PREFIX" -ErrorAction SilentlyContinue) {
Remove-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Scope Global -Force
}
# Leave deactivate function in the global namespace if requested:
if (-not $NonDestructive) {
Remove-Item -Path function:deactivate
}
}
<#
.Description
Get-PyVenvConfig parses the values from the pyvenv.cfg file located in the
given folder, and returns them in a map.
For each line in the pyvenv.cfg file, if that line can be parsed into exactly
two strings separated by `=` (with any amount of whitespace surrounding the =)
then it is considered a `key = value` line. The left hand string is the key,
the right hand is the value.
If the value starts with a `'` or a `"` then the first and last character is
stripped from the value before being captured.
.Parameter ConfigDir
Path to the directory that contains the `pyvenv.cfg` file.
#>
function Get-PyVenvConfig(
[String]
$ConfigDir
) {
Write-Verbose "Given ConfigDir=$ConfigDir, obtain values in pyvenv.cfg"
# Ensure the file exists, and issue a warning if it doesn't (but still allow the function to continue).
$pyvenvConfigPath = Join-Path -Resolve -Path $ConfigDir -ChildPath 'pyvenv.cfg' -ErrorAction Continue
# An empty map will be returned if no config file is found.
$pyvenvConfig = @{ }
if ($pyvenvConfigPath) {
Write-Verbose "File exists, parse `key = value` lines"
$pyvenvConfigContent = Get-Content -Path $pyvenvConfigPath
$pyvenvConfigContent | ForEach-Object {
$keyval = $PSItem -split "\s*=\s*", 2
if ($keyval[0] -and $keyval[1]) {
$val = $keyval[1]
# Remove extraneous quotations around a string value.
if ("'""".Contains($val.Substring(0, 1))) {
$val = $val.Substring(1, $val.Length - 2)
}
$pyvenvConfig[$keyval[0]] = $val
Write-Verbose "Adding Key: '$($keyval[0])'='$val'"
}
}
}
return $pyvenvConfig
}
<# Begin Activate script --------------------------------------------------- #>
# Determine the containing directory of this script
$VenvExecPath = Split-Path -Parent $MyInvocation.MyCommand.Definition
$VenvExecDir = Get-Item -Path $VenvExecPath
Write-Verbose "Activation script is located in path: '$VenvExecPath'"
Write-Verbose "VenvExecDir Fullname: '$($VenvExecDir.FullName)"
Write-Verbose "VenvExecDir Name: '$($VenvExecDir.Name)"
# Set values required in priority: CmdLine, ConfigFile, Default
# First, get the location of the virtual environment, it might not be
# VenvExecDir if specified on the command line.
if ($VenvDir) {
Write-Verbose "VenvDir given as parameter, using '$VenvDir' to determine values"
}
else {
Write-Verbose "VenvDir not given as a parameter, using parent directory name as VenvDir."
$VenvDir = $VenvExecDir.Parent.FullName.TrimEnd("\\/")
Write-Verbose "VenvDir=$VenvDir"
}
# Next, read the `pyvenv.cfg` file to determine any required value such
# as `prompt`.
$pyvenvCfg = Get-PyVenvConfig -ConfigDir $VenvDir
# Next, set the prompt from the command line, or the config file, or
# just use the name of the virtual environment folder.
if ($Prompt) {
Write-Verbose "Prompt specified as argument, using '$Prompt'"
}
else {
Write-Verbose "Prompt not specified as argument to script, checking pyvenv.cfg value"
if ($pyvenvCfg -and $pyvenvCfg['prompt']) {
Write-Verbose " Setting based on value in pyvenv.cfg='$($pyvenvCfg['prompt'])'"
$Prompt = $pyvenvCfg['prompt'];
}
else {
Write-Verbose " Setting prompt based on parent's directory's name. (Is the directory name passed to venv module when creating the virtual environment)"
Write-Verbose " Got leaf-name of $VenvDir='$(Split-Path -Path $venvDir -Leaf)'"
$Prompt = Split-Path -Path $venvDir -Leaf
}
}
Write-Verbose "Prompt = '$Prompt'"
Write-Verbose "VenvDir='$VenvDir'"
# Deactivate any currently active virtual environment, but leave the
# deactivate function in place.
deactivate -nondestructive
# Now set the environment variable VIRTUAL_ENV, used by many tools to determine
# that there is an activated venv.
$env:VIRTUAL_ENV = $VenvDir
if (-not $Env:VIRTUAL_ENV_DISABLE_PROMPT) {
Write-Verbose "Setting prompt to '$Prompt'"
# Set the prompt to include the env name
# Make sure _OLD_VIRTUAL_PROMPT is global
function global:_OLD_VIRTUAL_PROMPT { "" }
Copy-Item -Path function:prompt -Destination function:_OLD_VIRTUAL_PROMPT
New-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Description "Python virtual environment prompt prefix" -Scope Global -Option ReadOnly -Visibility Public -Value $Prompt
function global:prompt {
Write-Host -NoNewline -ForegroundColor Green "($_PYTHON_VENV_PROMPT_PREFIX) "
_OLD_VIRTUAL_PROMPT
}
$env:VIRTUAL_ENV_PROMPT = $Prompt
}
# Clear PYTHONHOME
if (Test-Path -Path Env:PYTHONHOME) {
Copy-Item -Path Env:PYTHONHOME -Destination Env:_OLD_VIRTUAL_PYTHONHOME
Remove-Item -Path Env:PYTHONHOME
}
# Add the venv to the PATH
Copy-Item -Path Env:PATH -Destination Env:_OLD_VIRTUAL_PATH
$Env:PATH = "$VenvExecDir$([System.IO.Path]::PathSeparator)$Env:PATH"

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

69
_trash/bin/activate Normal file
View file

@ -0,0 +1,69 @@
# This file must be used with "source bin/activate" *from bash*
# you cannot run it directly
deactivate () {
# reset old environment variables
if [ -n "${_OLD_VIRTUAL_PATH:-}" ] ; then
PATH="${_OLD_VIRTUAL_PATH:-}"
export PATH
unset _OLD_VIRTUAL_PATH
fi
if [ -n "${_OLD_VIRTUAL_PYTHONHOME:-}" ] ; then
PYTHONHOME="${_OLD_VIRTUAL_PYTHONHOME:-}"
export PYTHONHOME
unset _OLD_VIRTUAL_PYTHONHOME
fi
# This should detect bash and zsh, which have a hash command that must
# be called to get it to forget past commands. Without forgetting
# past commands the $PATH changes we made may not be respected
if [ -n "${BASH:-}" -o -n "${ZSH_VERSION:-}" ] ; then
hash -r 2> /dev/null
fi
if [ -n "${_OLD_VIRTUAL_PS1:-}" ] ; then
PS1="${_OLD_VIRTUAL_PS1:-}"
export PS1
unset _OLD_VIRTUAL_PS1
fi
unset VIRTUAL_ENV
unset VIRTUAL_ENV_PROMPT
if [ ! "${1:-}" = "nondestructive" ] ; then
# Self destruct!
unset -f deactivate
fi
}
# unset irrelevant variables
deactivate nondestructive
VIRTUAL_ENV=/home/pi/git/abschlussarbeit
export VIRTUAL_ENV
_OLD_VIRTUAL_PATH="$PATH"
PATH="$VIRTUAL_ENV/"bin":$PATH"
export PATH
# unset PYTHONHOME if set
# this will fail if PYTHONHOME is set to the empty string (which is bad anyway)
# could use `if (set -u; : $PYTHONHOME) ;` in bash
if [ -n "${PYTHONHOME:-}" ] ; then
_OLD_VIRTUAL_PYTHONHOME="${PYTHONHOME:-}"
unset PYTHONHOME
fi
if [ -z "${VIRTUAL_ENV_DISABLE_PROMPT:-}" ] ; then
_OLD_VIRTUAL_PS1="${PS1:-}"
PS1='(abschlussarbeit) '"${PS1:-}"
export PS1
VIRTUAL_ENV_PROMPT='(abschlussarbeit) '
export VIRTUAL_ENV_PROMPT
fi
# This should detect bash and zsh, which have a hash command that must
# be called to get it to forget past commands. Without forgetting
# past commands the $PATH changes we made may not be respected
if [ -n "${BASH:-}" -o -n "${ZSH_VERSION:-}" ] ; then
hash -r 2> /dev/null
fi

26
_trash/bin/activate.csh Normal file
View file

@ -0,0 +1,26 @@
# This file must be used with "source bin/activate.csh" *from csh*.
# You cannot run it directly.
# Created by Davide Di Blasi <davidedb@gmail.com>.
# Ported to Python 3.3 venv by Andrew Svetlov <andrew.svetlov@gmail.com>
alias deactivate 'test $?_OLD_VIRTUAL_PATH != 0 && setenv PATH "$_OLD_VIRTUAL_PATH" && unset _OLD_VIRTUAL_PATH; rehash; test $?_OLD_VIRTUAL_PROMPT != 0 && set prompt="$_OLD_VIRTUAL_PROMPT" && unset _OLD_VIRTUAL_PROMPT; unsetenv VIRTUAL_ENV; unsetenv VIRTUAL_ENV_PROMPT; test "\!:*" != "nondestructive" && unalias deactivate'
# Unset irrelevant variables.
deactivate nondestructive
setenv VIRTUAL_ENV /home/pi/git/abschlussarbeit
set _OLD_VIRTUAL_PATH="$PATH"
setenv PATH "$VIRTUAL_ENV/"bin":$PATH"
set _OLD_VIRTUAL_PROMPT="$prompt"
if (! "$?VIRTUAL_ENV_DISABLE_PROMPT") then
set prompt = '(abschlussarbeit) '"$prompt"
setenv VIRTUAL_ENV_PROMPT '(abschlussarbeit) '
endif
alias pydoc python -m pydoc
rehash

69
_trash/bin/activate.fish Normal file
View file

@ -0,0 +1,69 @@
# This file must be used with "source <venv>/bin/activate.fish" *from fish*
# (https://fishshell.com/); you cannot run it directly.
function deactivate -d "Exit virtual environment and return to normal shell environment"
# reset old environment variables
if test -n "$_OLD_VIRTUAL_PATH"
set -gx PATH $_OLD_VIRTUAL_PATH
set -e _OLD_VIRTUAL_PATH
end
if test -n "$_OLD_VIRTUAL_PYTHONHOME"
set -gx PYTHONHOME $_OLD_VIRTUAL_PYTHONHOME
set -e _OLD_VIRTUAL_PYTHONHOME
end
if test -n "$_OLD_FISH_PROMPT_OVERRIDE"
set -e _OLD_FISH_PROMPT_OVERRIDE
# prevents error when using nested fish instances (Issue #93858)
if functions -q _old_fish_prompt
functions -e fish_prompt
functions -c _old_fish_prompt fish_prompt
functions -e _old_fish_prompt
end
end
set -e VIRTUAL_ENV
set -e VIRTUAL_ENV_PROMPT
if test "$argv[1]" != "nondestructive"
# Self-destruct!
functions -e deactivate
end
end
# Unset irrelevant variables.
deactivate nondestructive
set -gx VIRTUAL_ENV /home/pi/git/abschlussarbeit
set -gx _OLD_VIRTUAL_PATH $PATH
set -gx PATH "$VIRTUAL_ENV/"bin $PATH
# Unset PYTHONHOME if set.
if set -q PYTHONHOME
set -gx _OLD_VIRTUAL_PYTHONHOME $PYTHONHOME
set -e PYTHONHOME
end
if test -z "$VIRTUAL_ENV_DISABLE_PROMPT"
# fish uses a function instead of an env var to generate the prompt.
# Save the current fish_prompt function as the function _old_fish_prompt.
functions -c fish_prompt _old_fish_prompt
# With the original prompt function renamed, we can override with our own.
function fish_prompt
# Save the return status of the last command.
set -l old_status $status
# Output the venv prompt; color taken from the blue of the Python logo.
printf "%s%s%s" (set_color 4B8BBE) '(abschlussarbeit) ' (set_color normal)
# Restore the return status of the previous command.
echo "exit $old_status" | .
# Output the original/"old" prompt.
_old_fish_prompt
end
set -gx _OLD_FISH_PROMPT_OVERRIDE "$VIRTUAL_ENV"
set -gx VIRTUAL_ENV_PROMPT '(abschlussarbeit) '
end

194
_trash/bin/ftconf.py Executable file
View file

@ -0,0 +1,194 @@
#!/home/pi/git/abschlussarbeit/bin/python3
"""Simple FTDI EEPROM configurator.
"""
# 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 exit as sys_exit, modules, stderr, stdout
from textwrap import fill
from traceback import format_exc
from pyftdi import FtdiLogger
from pyftdi.eeprom import FtdiEeprom
from pyftdi.ftdi import Ftdi
from pyftdi.misc import add_custom_devices, hexdump
# pylint: disable=too-many-locals
# pylint: disable=too-many-branches
# pylint: disable=too-many-statements
def main():
"""Main routine"""
debug = False
try:
argparser = ArgumentParser(description=modules[__name__].__doc__)
argparser.add_argument('device', nargs='?', default='ftdi:///?',
help='serial port device name')
files = argparser.add_argument_group(title='Files')
files.add_argument('-i', '--input', type=FileType('rt'),
help='input ini file to load EEPROM content')
files.add_argument('-l', '--load', default='all',
choices=('all', 'raw', 'values'),
help='section(s) to load from input file')
files.add_argument('-o', '--output',
help='output ini file to save EEPROM content')
files.add_argument('-V', '--virtual', type=FileType('r'),
help='use a virtual device, specified as YaML')
device = argparser.add_argument_group(title='Device')
device.add_argument('-P', '--vidpid', action='append',
help='specify a custom VID:PID device ID '
'(search for FTDI devices)')
device.add_argument('-M', '--eeprom',
help='force an EEPROM model')
device.add_argument('-S', '--size', type=int,
choices=FtdiEeprom.eeprom_sizes,
help='force an EEPROM size')
fmt = argparser.add_argument_group(title='Format')
fmt.add_argument('-x', '--hexdump', action='store_true',
help='dump EEPROM content as ASCII')
fmt.add_argument('-X', '--hexblock', type=int,
help='dump EEPROM as indented hexa blocks')
config = argparser.add_argument_group(title='Configuration')
config.add_argument('-s', '--serial-number',
help='set serial number')
config.add_argument('-m', '--manufacturer',
help='set manufacturer name')
config.add_argument('-p', '--product',
help='set product name')
config.add_argument('-c', '--config', action='append',
help='change/configure a property as key=value '
'pair')
config.add_argument('--vid', type=lambda x: int(x, 16),
help='shortcut to configure the USB vendor ID')
config.add_argument('--pid', type=lambda x: int(x, 16),
help='shortcut to configure the USB product ID')
action = argparser.add_argument_group(title='Action')
action.add_argument('-e', '--erase', action='store_true',
help='erase the whole EEPROM content')
action.add_argument('-E', '--full-erase', action='store_true',
default=False,
help='erase the whole EEPROM content, including '
'the CRC')
action.add_argument('-u', '--update', action='store_true',
help='perform actual update, use w/ care')
extra = argparser.add_argument_group(title='Extras')
extra.add_argument('-v', '--verbose', action='count', default=0,
help='increase verbosity')
extra.add_argument('-d', '--debug', action='store_true',
help='enable debug mode')
args = argparser.parse_args()
debug = args.debug
if not args.device:
argparser.error('Serial device not specified')
loglevel = max(DEBUG, ERROR - (10 * args.verbose))
loglevel = min(ERROR, loglevel)
if debug:
formatter = Formatter('%(asctime)s.%(msecs)03d %(name)-20s '
'%(message)s', '%H:%M:%S')
else:
formatter = Formatter('%(message)s')
FtdiLogger.set_formatter(formatter)
FtdiLogger.set_level(loglevel)
FtdiLogger.log.addHandler(StreamHandler(stderr))
if args.virtual:
# pylint: disable=import-outside-toplevel
from pyftdi.usbtools import UsbTools
# Force PyUSB to use PyFtdi test framework for USB backends
UsbTools.BACKENDS = ('pyftdi.tests.backend.usbvirt', )
# Ensure the virtual backend can be found and is loaded
backend = UsbTools.find_backend()
loader = backend.create_loader()()
loader.load(args.virtual)
try:
add_custom_devices(Ftdi, args.vidpid, force_hex=True)
except ValueError as exc:
argparser.error(str(exc))
eeprom = FtdiEeprom()
eeprom.open(args.device, size=args.size, model=args.eeprom)
if args.erase or args.full_erase:
eeprom.erase()
if args.input:
eeprom.load_config(args.input, args.load)
if args.serial_number:
eeprom.set_serial_number(args.serial_number)
if args.manufacturer:
eeprom.set_manufacturer_name(args.manufacturer)
if args.product:
eeprom.set_product_name(args.product)
for conf in args.config or []:
if conf in ('?', 'help'):
helpstr = ', '.join(sorted(eeprom.properties))
print(fill(helpstr, initial_indent=' ',
subsequent_indent=' '))
sys_exit(1)
for sep in ':=':
if sep in conf:
name, value = conf.split(sep, 1)
if not value:
argparser.error(f'Configuration {conf} without value')
if value == 'help':
value = '?'
helpio = StringIO()
eeprom.set_property(name, value, helpio)
helpstr = helpio.getvalue()
if helpstr:
print(fill(helpstr, initial_indent=' ',
subsequent_indent=' '))
sys_exit(1)
break
else:
argparser.error(f'Missing name:value separator in {conf}')
if args.vid:
eeprom.set_property('vendor_id', args.vid)
if args.pid:
eeprom.set_property('product_id', args.pid)
if args.hexdump:
print(hexdump(eeprom.data))
if args.hexblock is not None:
indent = ' ' * args.hexblock
for pos in range(0, len(eeprom.data), 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):
eeprom.reset_device()
if args.verbose > 0:
eeprom.dump_config()
if args.output:
if args.output == '-':
eeprom.save_config(stdout)
else:
with open(args.output, 'wt') as ofp:
eeprom.save_config(ofp)
except (ImportError, IOError, NotImplementedError, ValueError) as exc:
print(f'\nError: {exc}', file=stderr)
if debug:
print(format_exc(chain=False), file=stderr)
sys_exit(1)
except KeyboardInterrupt:
sys_exit(2)
finally:
eeprom.close()
if __name__ == '__main__':
main()

74
_trash/bin/ftdi_urls.py Executable file
View file

@ -0,0 +1,74 @@
#!/home/pi/git/abschlussarbeit/bin/python3
# Copyright (c) 2019-2024, Emmanuel Blot <emmanuel.blot@free.fr>
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""List valid FTDI device URLs and descriptors."""
from argparse import ArgumentParser, FileType
from logging import Formatter, StreamHandler, DEBUG, ERROR
from sys import exit as sys_exit, modules, stderr
from traceback import format_exc
from pyftdi import FtdiLogger
from pyftdi.ftdi import Ftdi
from pyftdi.misc import add_custom_devices
def main():
"""Entry point."""
debug = False
try:
argparser = ArgumentParser(description=modules[__name__].__doc__)
argparser.add_argument('-P', '--vidpid', action='append',
help='specify a custom VID:PID device ID, '
'may be repeated')
argparser.add_argument('-V', '--virtual', type=FileType('r'),
help='use a virtual device, specified as YaML')
argparser.add_argument('-v', '--verbose', action='count', default=0,
help='increase verbosity')
argparser.add_argument('-d', '--debug', action='store_true',
help='enable debug mode')
args = argparser.parse_args()
debug = args.debug
loglevel = max(DEBUG, ERROR - (10 * args.verbose))
loglevel = min(ERROR, loglevel)
if debug:
formatter = Formatter('%(asctime)s.%(msecs)03d %(name)-20s '
'%(message)s', '%H:%M:%S')
else:
formatter = Formatter('%(message)s')
FtdiLogger.set_formatter(formatter)
FtdiLogger.set_level(loglevel)
FtdiLogger.log.addHandler(StreamHandler(stderr))
if args.virtual:
# pylint: disable=import-outside-toplevel
from pyftdi.usbtools import UsbTools
# Force PyUSB to use PyFtdi test framework for USB backends
UsbTools.BACKENDS = ('pyftdi.tests.backend.usbvirt', )
# Ensure the virtual backend can be found and is loaded
backend = UsbTools.find_backend()
loader = backend.create_loader()()
loader.load(args.virtual)
try:
add_custom_devices(Ftdi, args.vidpid, force_hex=True)
except ValueError as exc:
argparser.error(str(exc))
Ftdi.show_devices()
except (ImportError, IOError, NotImplementedError, ValueError) as exc:
print(f'\nError: {exc}', file=stderr)
if debug:
print(format_exc(chain=False), file=stderr)
sys_exit(1)
except KeyboardInterrupt:
sys_exit(2)
if __name__ == '__main__':
main()

155
_trash/bin/i2cscan.py Executable file
View file

@ -0,0 +1,155 @@
#!/home/pi/git/abschlussarbeit/bin/python3
# -*- coding: utf-8 -*-
# Copyright (c) 2018-2024, Emmanuel Blot <emmanuel.blot@free.fr>
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Tiny I2C bus scanner."""
# pylint: disable=broad-except
from argparse import ArgumentParser, FileType
from logging import Formatter, StreamHandler, getLogger, DEBUG, ERROR
from sys import exit as sys_exit, modules, stderr
from traceback import format_exc
from pyftdi import FtdiLogger
from pyftdi.ftdi import Ftdi
from pyftdi.i2c import I2cController, I2cNackError
from pyftdi.misc import add_custom_devices
class I2cBusScanner:
"""Scan I2C bus to find slave.
Emit the I2C address message, but no data. Detect any ACK on each valid
address.
"""
SMB_READ_RANGE = list(range(0x30, 0x38)) + list(range(0x50, 0x60))
HIGHEST_I2C_SLAVE_ADDRESS = 0x78
@classmethod
def scan(cls, url: str, smb_mode: bool = True, force: bool = False) \
-> None:
"""Scan an I2C bus to detect slave device.
:param url: FTDI URL
:param smb_mode: whether to use SMBbus restrictions or regular I2C
mode.
"""
i2c = I2cController()
slaves = []
getLogger('pyftdi.i2c').setLevel(ERROR)
try:
i2c.set_retry_count(1)
i2c.force_clock_mode(force)
i2c.configure(url)
for addr in range(cls.HIGHEST_I2C_SLAVE_ADDRESS+1):
port = i2c.get_port(addr)
if smb_mode:
try:
if addr in cls.SMB_READ_RANGE:
port.read(0)
slaves.append('R')
else:
port.write([])
slaves.append('W')
except I2cNackError:
slaves.append('.')
else:
try:
port.read(0)
slaves.append('R')
continue
except I2cNackError:
pass
try:
port.write([])
slaves.append('W')
except I2cNackError:
slaves.append('.')
finally:
i2c.terminate()
columns = 16
row = 0
print(' ', ''.join(f' {col:01X} ' for col in range(columns)))
while True:
chunk = slaves[row:row+columns]
if not chunk:
break
print(f' {row//columns:01X}:', ' '.join(chunk))
row += columns
def main():
"""Entry point."""
debug = False
try:
argparser = ArgumentParser(description=modules[__name__].__doc__)
argparser.add_argument('device', nargs='?', default='ftdi:///?',
help='serial port device name')
argparser.add_argument('-S', '--no-smb', action='store_true',
default=False,
help='use regular I2C mode vs. SMBbus scan')
argparser.add_argument('-P', '--vidpid', action='append',
help='specify a custom VID:PID device ID, '
'may be repeated')
argparser.add_argument('-V', '--virtual', type=FileType('r'),
help='use a virtual device, specified as YaML')
argparser.add_argument('-v', '--verbose', action='count', default=0,
help='increase verbosity')
argparser.add_argument('-d', '--debug', action='store_true',
help='enable debug mode')
argparser.add_argument('-F', '--force', action='store_true',
help='force clock mode (for FT2232D)')
args = argparser.parse_args()
debug = args.debug
if not args.device:
argparser.error('Serial device not specified')
loglevel = max(DEBUG, ERROR - (10 * args.verbose))
loglevel = min(ERROR, loglevel)
if debug:
formatter = Formatter('%(asctime)s.%(msecs)03d %(name)-20s '
'%(message)s', '%H:%M:%S')
else:
formatter = Formatter('%(message)s')
FtdiLogger.log.addHandler(StreamHandler(stderr))
FtdiLogger.set_formatter(formatter)
FtdiLogger.set_level(loglevel)
if args.virtual:
# pylint: disable=import-outside-toplevel
from pyftdi.usbtools import UsbTools
# Force PyUSB to use PyFtdi test framework for USB backends
UsbTools.BACKENDS = ('pyftdi.tests.backend.usbvirt', )
# Ensure the virtual backend can be found and is loaded
backend = UsbTools.find_backend()
loader = backend.create_loader()()
loader.load(args.virtual)
try:
add_custom_devices(Ftdi, args.vidpid, force_hex=True)
except ValueError as exc:
argparser.error(str(exc))
I2cBusScanner.scan(args.device, not args.no_smb, args.force)
except (ImportError, IOError, NotImplementedError, ValueError) as exc:
print(f'\nError: {exc}', file=stderr)
if debug:
print(format_exc(chain=False), file=stderr)
sys_exit(1)
except KeyboardInterrupt:
sys_exit(2)
if __name__ == '__main__':
try:
main()
except Exception as _exc:
print(str(_exc), file=stderr)

8
_trash/bin/pip Executable file
View file

@ -0,0 +1,8 @@
#!/home/pi/git/abschlussarbeit/bin/python3
# -*- coding: utf-8 -*-
import re
import sys
from pip._internal.cli.main import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(main())

8
_trash/bin/pip3 Executable file
View file

@ -0,0 +1,8 @@
#!/home/pi/git/abschlussarbeit/bin/python3
# -*- coding: utf-8 -*-
import re
import sys
from pip._internal.cli.main import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(main())

8
_trash/bin/pip3.11 Executable file
View file

@ -0,0 +1,8 @@
#!/home/pi/git/abschlussarbeit/bin/python3
# -*- coding: utf-8 -*-
import re
import sys
from pip._internal.cli.main import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(main())

8
_trash/bin/pyserial-miniterm Executable file
View file

@ -0,0 +1,8 @@
#!/home/pi/git/abschlussarbeit/bin/python3
# -*- coding: utf-8 -*-
import re
import sys
from serial.tools.miniterm import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(main())

8
_trash/bin/pyserial-ports Executable file
View file

@ -0,0 +1,8 @@
#!/home/pi/git/abschlussarbeit/bin/python3
# -*- coding: utf-8 -*-
import re
import sys
from serial.tools.list_ports import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(main())

367
_trash/bin/pyterm.py Executable file
View file

@ -0,0 +1,367 @@
#!/home/pi/git/abschlussarbeit/bin/python3
"""Simple Python serial terminal
"""
# Copyright (c) 2010-2024, Emmanuel Blot <emmanuel.blot@free.fr>
# Copyright (c) 2016, Emmanuel Bouaziz <ebouaziz@free.fr>
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
# pylint: disable=broad-except
# pylint: disable=wrong-import-position
from argparse import ArgumentParser, FileType
from atexit import register
from collections import deque
from logging import Formatter, StreamHandler, DEBUG, ERROR
from os import environ, linesep, stat
from re import search
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
from _thread import interrupt_main
# pylint: disable=import-error
# pylint: disable=import-outside-toplevel
from pyftdi import FtdiLogger
from pyftdi.ftdi import Ftdi
from pyftdi.misc import to_bps, add_custom_devices
from pyftdi.term import Terminal
class MiniTerm:
"""A mini serial terminal to demonstrate pyserial extensions"""
DEFAULT_BAUDRATE = 115200
def __init__(self, device, baudrate=None, parity=None, rtscts=False,
debug=False):
self._terminal = Terminal()
self._device = device
self._baudrate = baudrate or self.DEFAULT_BAUDRATE
self._port = self._open_port(self._device, self._baudrate, parity,
rtscts, debug)
self._resume = False
self._silent = False
self._rxq = deque()
self._rxe = Event()
self._debug = debug
register(self._cleanup)
def run(self, fullmode=False, loopback=False, silent=False,
localecho=False, autocr=False):
"""Switch to a pure serial terminal application"""
self._terminal.init(fullmode)
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
args = [loopback]
if self._device.startswith('ftdi://'):
# with pyftdi/pyusb/libusb stack, there is no kernel buffering
# which means that a UART source with data burst may overflow the
# FTDI HW buffer while the SW stack is dealing with formatting
# and console output. Use an intermediate thread to pop out data
# out from the HW as soon as it is made available, and use a deque
# to serve the actual reader thread
args.append(self._get_from_source)
sourcer = Thread(target=self._sourcer, daemon=True)
sourcer.start()
else:
# regular kernel buffered device
args.append(self._get_from_port)
reader = Thread(target=self._reader, args=tuple(args), daemon=True)
reader.start()
# start the writer (host to target direction)
self._writer(fullmode, silent, localecho, autocr)
def _sourcer(self):
try:
while self._resume:
data = self._port.read(4096)
if not data:
continue
self._rxq.append(data)
self._rxe.set()
except Exception as ex:
self._resume = False
print(str(ex), file=stderr)
interrupt_main()
def _get_from_source(self):
while not self._rxq and self._resume:
if self._rxe.wait(0.1):
self._rxe.clear()
break
if not self._rxq:
return bytearray()
return self._rxq.popleft()
def _get_from_port(self):
try:
return self._port.read(4096)
except OSError as ex:
self._resume = False
print(str(ex), file=stderr)
interrupt_main()
return bytearray()
except Exception as ex:
print(str(ex), file=stderr)
return bytearray()
def _reader(self, loopback, getfunc):
"""Loop forever, processing received serial data in terminal mode"""
try:
# Try to read as many bytes as possible at once, and use a short
# timeout to avoid blocking for more data
self._port.timeout = 0.050
while self._resume:
if self._silent:
sleep(0.25)
continue
data = getfunc()
if data:
stdout.write(data.decode('utf8', errors='replace'))
stdout.flush()
if loopback:
self._port.write(data)
except KeyboardInterrupt:
return
except Exception as exc:
print(f'Exception: {exc}')
if self._debug:
print(format_exc(chain=False), file=stderr)
interrupt_main()
def _writer(self, fullmode, silent, localecho, crlf=0):
"""Loop and copy console->serial until EOF character is found"""
while self._resume:
try:
char = self._terminal.getkey()
if fullmode and ord(char) == 0x2: # Ctrl+B
self._cleanup(True)
return
if self._terminal.IS_MSWIN:
if ord(char) in (0, 224):
char = self._terminal.getkey()
self._port.write(self._terminal.getch_to_escape(char))
continue
if ord(char) == 0x3: # Ctrl+C
raise KeyboardInterrupt('Ctrl-C break')
if silent:
if ord(char) == 0x6: # Ctrl+F
self._silent = True
print('Silent\n')
continue
if ord(char) == 0x7: # Ctrl+G
self._silent = False
print('Reg\n')
continue
if localecho:
stdout.write(char.decode('utf8', errors='replace'))
stdout.flush()
if crlf:
if char == b'\n':
self._port.write(b'\r')
if crlf > 1:
continue
self._port.write(char)
except KeyError:
continue
except KeyboardInterrupt:
if fullmode:
if self._terminal.IS_MSWIN:
self._port.write(b'\x03')
continue
self._cleanup(True)
def _cleanup(self, *args):
"""Cleanup resource before exiting"""
if args and args[0]:
print(f'{linesep}Aborting...')
try:
self._resume = False
if self._port:
# wait till the other thread completes
sleep(0.5)
try:
rem = self._port.inWaiting()
except IOError:
# maybe a bug in underlying wrapper...
rem = 0
# consumes all the received bytes
for _ in range(rem):
self._port.read()
self._port.close()
self._port = None
print('Bye.')
except Exception as ex:
print(str(ex), file=stderr)
finally:
if self._terminal:
self._terminal.reset()
self._terminal = None
@staticmethod
def _open_port(device, baudrate, parity, rtscts, debug=False):
"""Open the serial communication port"""
try:
from serial.serialutil import SerialException
from serial import PARITY_NONE
except ImportError as exc:
raise ImportError("Python serial module not installed") from exc
try:
from serial import serial_for_url, VERSION as serialver
# use a simple regex rather than adding a new dependency on the
# more complete 'packaging' module
vmo = search(r'^(\d+)\.(\d+)', serialver)
if not vmo:
# unable to parse version
raise ValueError()
if tuple(int(x) for x in vmo.groups()) < (3, 0):
# pysrial version is too old
raise ValueError()
except (ValueError, IndexError, ImportError) as exc:
raise ImportError("pyserial 3.0+ is required") from exc
# the following import enables serial protocol extensions
if device.startswith('ftdi:'):
try:
from pyftdi import serialext
serialext.touch()
except ImportError as exc:
raise ImportError("PyFTDI module not installed") from exc
try:
port = serial_for_url(device,
baudrate=baudrate,
parity=parity or PARITY_NONE,
rtscts=rtscts,
timeout=0)
if not port.is_open:
port.open()
if not port.is_open:
raise IOError(f"Cannot open port '{device}'")
if debug:
backend = port.BACKEND if hasattr(port, 'BACKEND') else '?'
print(f"Using serial backend '{backend}'")
return port
except SerialException as exc:
raise IOError(str(exc)) from exc
def get_default_device() -> str:
"""Return the default comm device, depending on the host/OS."""
envdev = environ.get('FTDI_DEVICE', '')
if envdev:
return envdev
if platform == 'win32':
device = 'COM1'
elif platform == 'darwin':
device = '/dev/cu.usbserial'
elif platform == 'linux':
device = '/dev/ttyS0'
else:
device = ''
try:
stat(device)
except OSError:
device = 'ftdi:///1'
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')
argparser.add_argument('device', nargs='?', default=default_device,
help=f'serial port device name '
f'(default: {default_device}')
argparser.add_argument('-b', '--baudrate',
default=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')
argparser.add_argument('-e', '--localecho',
action='store_true',
help='local echo mode (print all typed chars)')
argparser.add_argument('-r', '--crlf',
action='count', default=0,
help='prefix LF with CR char, use twice to '
'replace all LF with CR chars')
argparser.add_argument('-l', '--loopback',
action='store_true',
help='loopback mode (send back all received '
'chars)')
argparser.add_argument('-s', '--silent', action='store_true',
help='silent mode')
argparser.add_argument('-P', '--vidpid', action='append',
help='specify a custom VID:PID device ID, '
'may be repeated')
argparser.add_argument('-V', '--virtual', type=FileType('r'),
help='use a virtual device, specified as YaML')
argparser.add_argument('-v', '--verbose', action='count',
help='increase verbosity')
argparser.add_argument('-d', '--debug', action='store_true',
help='enable debug mode')
args = argparser.parse_args()
debug = args.debug
if not args.device:
argparser.error('Serial device not specified')
loglevel = max(DEBUG, ERROR - (10 * (args.verbose or 0)))
loglevel = min(ERROR, loglevel)
if debug:
formatter = Formatter('%(asctime)s.%(msecs)03d %(name)-20s '
'%(message)s', '%H:%M:%S')
else:
formatter = Formatter('%(message)s')
FtdiLogger.set_formatter(formatter)
FtdiLogger.set_level(loglevel)
FtdiLogger.log.addHandler(StreamHandler(stderr))
if args.virtual:
from pyftdi.usbtools import UsbTools
# Force PyUSB to use PyFtdi test framework for USB backends
UsbTools.BACKENDS = ('pyftdi.tests.backend.usbvirt', )
# Ensure the virtual backend can be found and is loaded
backend = UsbTools.find_backend()
loader = backend.create_loader()()
loader.load(args.virtual)
try:
add_custom_devices(Ftdi, args.vidpid, force_hex=True)
except ValueError as exc:
argparser.error(str(exc))
miniterm = MiniTerm(device=args.device,
baudrate=to_bps(args.baudrate),
parity='N',
rtscts=args.hwflow,
debug=args.debug)
miniterm.run(args.fullmode, args.loopback, args.silent, args.localecho,
args.crlf)
except (IOError, ValueError) as exc:
print(f'\nError: {exc}', file=stderr)
if debug:
print(format_exc(chain=False), file=stderr)
sys_exit(1)
except KeyboardInterrupt:
sys_exit(2)
if __name__ == '__main__':
main()

1
_trash/bin/python Symbolic link
View file

@ -0,0 +1 @@
python3

1
_trash/bin/python3 Symbolic link
View file

@ -0,0 +1 @@
/usr/bin/python3

1
_trash/bin/python3.11 Symbolic link
View file

@ -0,0 +1 @@
python3