diff --git a/.github/workflows/pylint.yml b/.github/workflows/pylint.yml index e029ab0..3a0b733 100644 --- a/.github/workflows/pylint.yml +++ b/.github/workflows/pylint.yml @@ -13,6 +13,10 @@ jobs: uses: actions/setup-python@v2 with: python-version: 3.9 + - name: Install required headers + run: | + sudo apt update + sudo apt install libasound2-dev - name: Install dependencies run: | python -m pip install --upgrade pip @@ -20,4 +24,4 @@ jobs: if [ -f requirements.txt ]; then pip install -r requirements.txt; fi - name: Analysing the code with pylint run: | - pylint --output-format=colorized --disable=C0301,C0103 --fail-under=7.75 python_mcu + pylint python_mcu diff --git a/.github/workflows/python-app.yml b/.github/workflows/python-app.yml index d6bb54c..57ac891 100644 --- a/.github/workflows/python-app.yml +++ b/.github/workflows/python-app.yml @@ -20,6 +20,10 @@ jobs: uses: actions/setup-python@v2 with: python-version: 3.9 + - name: Install required headers + run: | + sudo apt update + sudo apt install libasound2-dev - name: Install dependencies run: | python -m pip install --upgrade pip diff --git a/.gitignore b/.gitignore index 1af8e2a..7db28f8 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,78 @@ +### JetBrains template +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### END JetBrains template + *~ .*~ *.pyc diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/.idea/PythonMcu.iml b/.idea/PythonMcu.iml new file mode 100644 index 0000000..ec63674 --- /dev/null +++ b/.idea/PythonMcu.iml @@ -0,0 +1,7 @@ + + + + + \ No newline at end of file diff --git a/.idea/encodings.xml b/.idea/encodings.xml new file mode 100644 index 0000000..ec8452e --- /dev/null +++ b/.idea/encodings.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/inspectionProfiles/Project_Default.xml b/.idea/inspectionProfiles/Project_Default.xml new file mode 100644 index 0000000..8c21a91 --- /dev/null +++ b/.idea/inspectionProfiles/Project_Default.xml @@ -0,0 +1,28 @@ + + + + \ No newline at end of file diff --git a/.idea/inspectionProfiles/profiles_settings.xml b/.idea/inspectionProfiles/profiles_settings.xml new file mode 100644 index 0000000..105ce2d --- /dev/null +++ b/.idea/inspectionProfiles/profiles_settings.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..27c18e2 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,12 @@ + + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..13d68ab --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/runConfigurations/PythonMcu3.xml b/.idea/runConfigurations/PythonMcu3.xml new file mode 100644 index 0000000..60dad79 --- /dev/null +++ b/.idea/runConfigurations/PythonMcu3.xml @@ -0,0 +1,23 @@ + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..94a25f7 --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.pylintrc b/.pylintrc new file mode 100644 index 0000000..3824fc5 --- /dev/null +++ b/.pylintrc @@ -0,0 +1,628 @@ +[MASTER] + +# A comma-separated list of package or module names from where C extensions may +# be loaded. Extensions are loading into the active Python interpreter and may +# run arbitrary code. +extension-pkg-allow-list=PySide2,rtmidi + +# A comma-separated list of package or module names from where C extensions may +# be loaded. Extensions are loading into the active Python interpreter and may +# run arbitrary code. (This is an alternative name to extension-pkg-allow-list +# for backward compatibility.) +extension-pkg-whitelist= + +# Return non-zero exit code if any of these messages/categories are detected, +# even if score is above --fail-under value. Syntax same as enable. Messages +# specified are enabled, while categories only check already-enabled messages. +fail-on= + +# Specify a score threshold to be exceeded before program exits with error. +fail-under=8 + +# Files or directories to be skipped. They should be base names, not paths. +ignore=.git,.github,docs, + +# Add files or directories matching the regex patterns to the ignore-list. The +# regex matches against paths. +ignore-paths= + +# Files or directories matching the regex patterns are skipped. The regex +# matches against base names, not paths. +ignore-patterns= + +# Python code to execute, usually for sys.path manipulation such as +# pygtk.require(). +#init-hook= + +# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the +# number of processors available to use. +jobs=0 + +# Control the amount of potential inferred values when inferring a single +# object. This can help the performance when dealing with large functions or +# complex, nested conditions. +limit-inference-results=100 + +# List of plugins (as comma separated values of python module names) to load, +# usually to register additional checkers. +load-plugins= + +# Pickle collected data for later comparisons. +persistent=yes + +# When enabled, pylint would attempt to guess common misconfiguration and emit +# user-friendly hints instead of false-positive error messages. +suggestion-mode=yes + +# Allow loading of arbitrary C extensions. Extensions are imported into the +# active Python interpreter and may run arbitrary code. +unsafe-load-any-extension=no + + +[MESSAGES CONTROL] + +# Only show warnings with the listed confidence levels. Leave empty to show +# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED. +confidence= + +# Disable the message, report, category or checker with the given id(s). You +# can either give multiple identifiers separated by comma (,) or put this +# option multiple times (only on the command line, not in the configuration +# file where it should appear only once). You can also use "--disable=all" to +# disable everything first and then reenable specific checks. For example, if +# you want to run only the similarities checker, you can use "--disable=all +# --enable=similarities". If you want to run only the classes checker, but have +# no Warning level messages displayed, use "--disable=all --enable=classes +# --disable=W". +disable=print-statement, + parameter-unpacking, + unpacking-in-except, + old-raise-syntax, + backtick, + long-suffix, + old-ne-operator, + old-octal-literal, + import-star-module-level, + non-ascii-bytes-literal, + raw-checker-failed, + bad-inline-option, + locally-disabled, + file-ignored, + suppressed-message, + useless-suppression, + deprecated-pragma, + use-symbolic-message-instead, + apply-builtin, + basestring-builtin, + buffer-builtin, + cmp-builtin, + coerce-builtin, + execfile-builtin, + file-builtin, + long-builtin, + raw_input-builtin, + reduce-builtin, + standarderror-builtin, + unicode-builtin, + xrange-builtin, + coerce-method, + delslice-method, + getslice-method, + setslice-method, + no-absolute-import, + old-division, + dict-iter-method, + dict-view-method, + next-method-called, + metaclass-assignment, + indexing-exception, + raising-string, + reload-builtin, + oct-method, + hex-method, + nonzero-method, + cmp-method, + input-builtin, + round-builtin, + intern-builtin, + unichr-builtin, + map-builtin-not-iterating, + zip-builtin-not-iterating, + range-builtin-not-iterating, + filter-builtin-not-iterating, + using-cmp-argument, + eq-without-hash, + div-method, + idiv-method, + rdiv-method, + exception-message-attribute, + invalid-str-codec, + sys-max-int, + bad-python3-import, + deprecated-string-function, + deprecated-str-translate-call, + deprecated-itertools-function, + deprecated-types-field, + next-method-defined, + dict-items-not-iterating, + dict-keys-not-iterating, + dict-values-not-iterating, + deprecated-operator-function, + deprecated-urllib-function, + xreadlines-attribute, + deprecated-sys-function, + exception-escape, + comprehension-escape + +# Enable the message, report, category or checker with the given id(s). You can +# either give multiple identifier separated by comma (,) or put this option +# multiple time (only on the command line, not in the configuration file where +# it should appear only once). See also the "--disable" option for examples. +enable=c-extension-no-member + + +[REPORTS] + +# Python expression which should return a score less than or equal to 10. You +# have access to the variables 'error', 'warning', 'refactor', and 'convention' +# which contain the number of messages in each category, as well as 'statement' +# which is the total number of statements analyzed. This score is used by the +# global evaluation report (RP0004). +evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) + +# Template used to display messages. This is a python new-style format string +# used to format the message information. See doc for all details. +#msg-template= + +# Set the output format. Available formats are text, parseable, colorized, json +# and msvs (visual studio). You can also give a reporter class, e.g. +# mypackage.mymodule.MyReporterClass. +output-format=colorized + +# Tells whether to display a full report or only the messages. +reports=yes + +# Activate the evaluation score. +score=yes + + +[REFACTORING] + +# Maximum number of nested blocks for function / method body +max-nested-blocks=5 + +# Complete name of functions that never returns. When checking for +# inconsistent-return-statements if a never returning function is called then +# it will be considered as an explicit return statement and no message will be +# printed. +never-returning-functions=sys.exit,argparse.parse_error + + +[BASIC] + +# Naming style matching correct argument names. +argument-naming-style=snake_case + +# Regular expression matching correct argument names. Overrides argument- +# naming-style. +#argument-rgx= + +# Naming style matching correct attribute names. +attr-naming-style=snake_case + +# Regular expression matching correct attribute names. Overrides attr-naming- +# style. +#attr-rgx= + +# Bad variable names which should always be refused, separated by a comma. +bad-names=foo, + bar, + baz, + toto, + tutu, + tata + +# Bad variable names regexes, separated by a comma. If names match any regex, +# they will always be refused +bad-names-rgxs= + +# Naming style matching correct class attribute names. +class-attribute-naming-style=any + +# Regular expression matching correct class attribute names. Overrides class- +# attribute-naming-style. +#class-attribute-rgx= + +# Naming style matching correct class constant names. +class-const-naming-style=UPPER_CASE + +# Regular expression matching correct class constant names. Overrides class- +# const-naming-style. +#class-const-rgx= + +# Naming style matching correct class names. +class-naming-style=PascalCase + +# Regular expression matching correct class names. Overrides class-naming- +# style. +#class-rgx= + +# Naming style matching correct constant names. +const-naming-style=UPPER_CASE + +# Regular expression matching correct constant names. Overrides const-naming- +# style. +#const-rgx= + +# Minimum line length for functions/classes that require docstrings, shorter +# ones are exempt. +docstring-min-length=-1 + +# Naming style matching correct function names. +function-naming-style=snake_case + +# Regular expression matching correct function names. Overrides function- +# naming-style. +#function-rgx= + +# Good variable names which should always be accepted, separated by a comma. +good-names=i, + j, + k, + ex, + Run, + _ + +# Good variable names regexes, separated by a comma. If names match any regex, +# they will always be accepted +good-names-rgxs= + +# Include a hint for the correct naming format with invalid-name. +include-naming-hint=no + +# Naming style matching correct inline iteration names. +inlinevar-naming-style=any + +# Regular expression matching correct inline iteration names. Overrides +# inlinevar-naming-style. +#inlinevar-rgx= + +# Naming style matching correct method names. +method-naming-style=snake_case + +# Regular expression matching correct method names. Overrides method-naming- +# style. +#method-rgx= + +# Naming style matching correct module names. +#module-naming-style=snake_case # TODO: move to PEP8 module names +module-naming-style=PascalCase + +# Regular expression matching correct module names. Overrides module-naming- +# style. +#module-rgx= + +# Colon-delimited sets of names that determine each other's naming style when +# the name regexes allow several styles. +name-group= + +# Regular expression which should only match function or class names that do +# not require a docstring. +no-docstring-rgx=^_ + +# List of decorators that produce properties, such as abc.abstractproperty. Add +# to this list to register other decorators that produce valid properties. +# These decorators are taken in consideration only for invalid-name. +property-classes=abc.abstractproperty + +# Naming style matching correct variable names. +variable-naming-style=snake_case + +# Regular expression matching correct variable names. Overrides variable- +# naming-style. +#variable-rgx= + + +[FORMAT] + +# Expected format of line ending, e.g. empty (any line ending), LF or CRLF. +expected-line-ending-format= + +# Regexp for a line that is allowed to be longer than the limit. +ignore-long-lines=^\s*(# )??$ + +# Number of spaces of indent required inside a hanging or continued line. +indent-after-paren=4 + +# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 +# tab). +indent-string=' ' + +# Maximum number of characters on a single line. +max-line-length=120 + +# Maximum number of lines in a module. +max-module-lines=1000 + +# Allow the body of a class to be on the same line as the declaration if body +# contains single statement. +single-line-class-stmt=no + +# Allow the body of an if to be on the same line as the test if there is no +# else. +single-line-if-stmt=no + + +[LOGGING] + +# The type of string formatting that logging methods do. `old` means using % +# formatting, `new` is for `{}` formatting. +logging-format-style=old + +# Logging modules to check that the string format arguments are in logging +# function parameter format. +logging-modules=logging + + +[MISCELLANEOUS] + +# List of note tags to take in consideration, separated by a comma. +notes=FIXME, + XXX, + TODO + +# Regular expression of note tags to take in consideration. +#notes-rgx= + + +[SIMILARITIES] + +# Comments are removed from the similarity computation +ignore-comments=yes + +# Docstrings are removed from the similarity computation +ignore-docstrings=yes + +# Imports are removed from the similarity computation +ignore-imports=no + +# Signatures are removed from the similarity computation +ignore-signatures=no + +# Minimum lines number of a similarity. +min-similarity-lines=4 + + +[SPELLING] + +# Limits count of emitted suggestions for spelling mistakes. +max-spelling-suggestions=4 + +# Spelling dictionary name. Available dictionaries: none. To make it work, +# install the 'python-enchant' package. +spelling-dict= + +# List of comma separated words that should be considered directives if they +# appear and the beginning of a comment and should not be checked. +spelling-ignore-comment-directives=fmt: on,fmt: off,noqa:,noqa,nosec,isort:skip,mypy: + +# List of comma separated words that should not be checked. +spelling-ignore-words= + +# A path to a file that contains the private dictionary; one word per line. +spelling-private-dict-file= + +# Tells whether to store unknown words to the private dictionary (see the +# --spelling-private-dict-file option) instead of raising a message. +spelling-store-unknown-words=no + + +[STRING] + +# This flag controls whether inconsistent-quotes generates a warning when the +# character used as a quote delimiter is used inconsistently within a module. +check-quote-consistency=no + +# This flag controls whether the implicit-str-concat should generate a warning +# on implicit string concatenation in sequences defined over several lines. +check-str-concat-over-line-jumps=no + + +[TYPECHECK] + +# List of decorators that produce context managers, such as +# contextlib.contextmanager. Add to this list to register other decorators that +# produce valid context managers. +contextmanager-decorators=contextlib.contextmanager + +# List of members which are set dynamically and missed by pylint inference +# system, and so shouldn't trigger E1101 when accessed. Python regular +# expressions are accepted. +generated-members= + +# Tells whether missing members accessed in mixin class should be ignored. A +# mixin class is detected if its name ends with "mixin" (case insensitive). +ignore-mixin-members=yes + +# Tells whether to warn about missing members when the owner of the attribute +# is inferred to be None. +ignore-none=yes + +# This flag controls whether pylint should warn about no-member and similar +# checks whenever an opaque object is returned when inferring. The inference +# can return multiple potential results while evaluating a Python object, but +# some branches might not be evaluated, which results in partial inference. In +# that case, it might be useful to still emit no-member and other checks for +# the rest of the inferred objects. +ignore-on-opaque-inference=yes + +# List of class names for which member attributes should not be checked (useful +# for classes with dynamically set attributes). This supports the use of +# qualified names. +ignored-classes=optparse.Values,thread._local,_thread._local + +# List of module names for which member attributes should not be checked +# (useful for modules/projects where namespaces are manipulated during runtime +# and thus existing member attributes cannot be deduced by static analysis). It +# supports qualified module names, as well as Unix pattern matching. +ignored-modules= + +# Show a hint with possible names when a member name was not found. The aspect +# of finding the hint is based on edit distance. +missing-member-hint=yes + +# The minimum edit distance a name should have in order to be considered a +# similar match for a missing member name. +missing-member-hint-distance=1 + +# The total number of similar names that should be taken in consideration when +# showing a hint for a missing member. +missing-member-max-choices=1 + +# List of decorators that change the signature of a decorated function. +signature-mutators= + + +[VARIABLES] + +# List of additional names supposed to be defined in builtins. Remember that +# you should avoid defining new builtins when possible. +additional-builtins= + +# Tells whether unused global variables should be treated as a violation. +allow-global-unused-variables=yes + +# List of names allowed to shadow builtins +allowed-redefined-builtins= + +# List of strings which can identify a callback function by name. A callback +# name must start or end with one of those strings. +callbacks=cb_, + _cb + +# A regular expression matching the name of dummy variables (i.e. expected to +# not be used). +dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ + +# Argument names that match this expression will be ignored. Default to name +# with leading underscore. +ignored-argument-names=_.*|^ignored_|^unused_ + +# Tells whether we should check for unused import in __init__ files. +init-import=no + +# List of qualified module names which can have objects that can redefine +# builtins. +redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io + + +[CLASSES] + +# Warn about protected attribute access inside special methods +check-protected-access-in-special-methods=no + +# List of method names used to declare (i.e. assign) instance attributes. +defining-attr-methods=__init__, + __new__, + setUp, + __post_init__ + +# List of member names, which should be excluded from the protected access +# warning. +exclude-protected=_asdict, + _fields, + _replace, + _source, + _make + +# List of valid names for the first argument in a class method. +valid-classmethod-first-arg=cls + +# List of valid names for the first argument in a metaclass class method. +valid-metaclass-classmethod-first-arg=cls + + +[DESIGN] + +# List of qualified class names to ignore when countint class parents (see +# R0901) +ignored-parents= + +# Maximum number of arguments for function / method. +max-args=5 + +# Maximum number of attributes for a class (see R0902). +max-attributes=7 + +# Maximum number of boolean expressions in an if statement (see R0916). +max-bool-expr=5 + +# Maximum number of branch for function / method body. +max-branches=12 + +# Maximum number of locals for function / method body. +max-locals=15 + +# Maximum number of parents for a class (see R0901). +max-parents=7 + +# Maximum number of public methods for a class (see R0904). +max-public-methods=20 + +# Maximum number of return / yield for function / method body. +max-returns=6 + +# Maximum number of statements in function / method body. +max-statements=50 + +# Minimum number of public methods for a class (see R0903). +min-public-methods=2 + + +[IMPORTS] + +# List of modules that can be imported at any level, not just the top level +# one. +allow-any-import-level= + +# Allow wildcard imports from modules that define __all__. +allow-wildcard-with-all=no + +# Analyse import fallback blocks. This can be used to support both Python 2 and +# 3 compatible code, which means that the block might have code that exists +# only in one or another interpreter, leading to false positives when analysed. +analyse-fallback-blocks=no + +# Deprecated modules which should not be used, separated by a comma. +deprecated-modules= + +# Output a graph (.gv or any supported image format) of external dependencies +# to the given file (report RP0402 must not be disabled). +ext-import-graph= + +# Output a graph (.gv or any supported image format) of all (i.e. internal and +# external) dependencies to the given file (report RP0402 must not be +# disabled). +import-graph= + +# Output a graph (.gv or any supported image format) of internal dependencies +# to the given file (report RP0402 must not be disabled). +int-import-graph= + +# Force import order to recognize a module as part of the standard +# compatibility libraries. +known-standard-library= + +# Force import order to recognize a module as part of a third party library. +known-third-party=enchant + +# Couples of modules and preferred modules, separated by a comma. +preferred-modules= + + +[EXCEPTIONS] + +# Exceptions that will emit a warning when being caught. Defaults to +# "BaseException, Exception". +overgeneral-exceptions=BaseException, + Exception diff --git a/TODO.md b/TODO.md index a07886e..731e422 100644 --- a/TODO.md +++ b/TODO.md @@ -5,16 +5,22 @@ - [x] [rdoursenaud] standard Python repository layout - [ ] [rdoursenaud] write pytest unit tests only looking at the protocol docs - [ ] [rdoursenaud] properly handle invalid config file -- [ ] [rdoursenaud] disallow start if MIDI ports are not set in the GUI +- [x] [rdoursenaud] disallow start if MIDI ports are not set in the GUI +- [x] [rdoursenaud] port to PySide6 +- [x] [rdoursenaud] Replace all "old style" string formatting (%) with "new style" (.format and f-strings) - [ ] [rdoursenaud] don't freeze GUI while "Waiting for MIDI input from host..." -- [ ] [rdoursenaud] port from pygame to rtmidi +- [x] [rdoursenaud] port from pygame to rtmidi +- [x] [rdoursenaud] allow manually refreshing available MIDI ports +- [ ] [rdoursenaud] if a MIDI port is removed during operation, don’t crash when trying to close it! Handle gracefully! - [ ] [rdoursenaud] create virtualports using rtmidi for supported platforms (And remove MIDI Yoke references) - [ ] [rdoursenaud] create windows virtualports using pytemidi (Requires Loop Midi to be installed) -- [ ] [rdoursenaud] explore if using mido could be beneficial +- [ ] [rdoursenaud] add option to autostart on launch - [ ] [rdoursenaud] add a nice icon - [ ] [rdoursenaud] reduce and restore from systray using QSystemTrayIcon or pystray - [ ] [rdoursenaud] add setup.py - [ ] [rdoursenaud] create Microsoft Windows binary using pyinstaller? - [x] [rdoursenaud] update documentation - [ ] [rdoursenaud] publish documentation to readthedocs.org -- [ ] [rdoursenaud] release version 2.0 \ No newline at end of file +- [ ] [rdoursenaud] release version 2.0 +- [ ] [rdoursenaud] announce on LAD, libreav and other relevant outlets +- [ ] [rdoursenaud] HUI mode? \ No newline at end of file diff --git a/docs-requirements.txt b/docs-requirements.txt new file mode 100644 index 0000000..70edabc --- /dev/null +++ b/docs-requirements.txt @@ -0,0 +1,2 @@ +-r requirements.txt +Sphinx \ No newline at end of file diff --git a/docs/PythonMcu.Hardware.rst b/docs/PythonMcu.Hardware.rst index 97da21c..2e1f4b8 100644 --- a/docs/PythonMcu.Hardware.rst +++ b/docs/PythonMcu.Hardware.rst @@ -4,10 +4,10 @@ PythonMcu.Hardware package Submodules ---------- -PythonMcu.Hardware.MidiControllerTemplate module +PythonMcu.Hardware._MidiControllerTemplate module ------------------------------------------------ -.. automodule:: PythonMcu.Hardware.MidiControllerTemplate +.. automodule:: PythonMcu.Hardware._MidiControllerTemplate :members: :undoc-members: :show-inheritance: diff --git a/docs/manual.rst b/docs/manual.rst index cf4ef98..4c4ed42 100644 --- a/docs/manual.rst +++ b/docs/manual.rst @@ -198,20 +198,20 @@ Extending Python MCU sequencer using the Mackie Control protocol, translating the raw protocol to something much easier to read and use -- the generalised **MidiControllerTemplate** class and its more +- the generalised **_MidiControllerTemplate** class and its more specific relatives handle all the details of sending data to and receiving data from your hardware controller, again translating raw protocols to something easier to read and use - finally, the **McuInterconnector** class connects the - **MackieHostControl** and **MidiControllerTemplate** classes (and + **MackieHostControl** and **_MidiControllerTemplate** classes (and thus your DAW and hardware controller) with each other This modular design means that the application happily works away with the irrelevant implementation details being effectively hidden from you. As long as you adhere to the internal protocol, you may easily add your own controller to **Python MCU** by deriving a class from -**MidiControllerTemplate**. +**_MidiControllerTemplate**. If all this means nothing to you, go find yourself a Python programmer (or learn Python yourself, it's rather easy and a lot of fun!). As long diff --git a/docs/programmer/SLMKII MIDI Programmers Reference.pdf b/docs/programmer/SLMKII MIDI Programmers Reference.pdf new file mode 100644 index 0000000..f78be8c Binary files /dev/null and b/docs/programmer/SLMKII MIDI Programmers Reference.pdf differ diff --git a/python_mcu/PythonMcu/Hardware/MidiControllerTemplate.py b/python_mcu/PythonMcu/Hardware/MidiControllerTemplate.py deleted file mode 100644 index e814a94..0000000 --- a/python_mcu/PythonMcu/Hardware/MidiControllerTemplate.py +++ /dev/null @@ -1,292 +0,0 @@ -# -*- coding: utf-8 -*- - -""" -PythonMcu -========= -Mackie Host Controller written in Python -Copyright (c) 2011 Martin Zuther (http://www.mzuther.de/) -Copyright (c) 2021 Raphaël Doursenaud - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program. If not, see . - -Thank you for using free software! - -""" - -import sys - -if __name__ == "__main__": - # allow "PythonMcu" package imports when executing this module - sys.path.append('../../../') - -from PythonMcu.Midi.MidiConnection import MidiConnection - - -class MidiControllerTemplate: - MIDI_MANUFACTURER_ID = None - MIDI_DEVICE_ID = None - - VPOT_MODE_SINGLE_DOT = 0x00 - VPOT_MODE_BOOST_CUT = 0x01 - VPOT_MODE_WRAP = 0x02 - VPOT_MODE_SPREAD = 0x03 - - _LED_STATUS = { - 0x00: 'off', - 0x01: 'flashing', - 0x7F: 'on' - } - - def __init__(self, midi_input_name, midi_output_name, callback_log): - self.callback_log = callback_log - - # LCD has 2 rows with 56 characters each, fill with spaces - self._lcd_characters = [' '] * 2 - self._lcd_overlay_characters = [' '] * 2 - - for line in range(2): - # noinspection PyTypeChecker - self._lcd_characters[line] = [' '] * 56 - # noinspection PyTypeChecker - self._lcd_overlay_characters[line] = [' '] * 56 - - self._show_overlay = [False, False] - - self._log('Initialising MIDI ports...', True) - self._midi_input_name = midi_input_name - self._midi_output_name = midi_output_name - self.midi = MidiConnection(self.callback_log, self.receive_midi) - - # Initialized by set_interconnector() - self.interconnector = None - - self.display_lcd_available = True - self.automated_faders_available = True - self.display_7seg_available = True - self.display_timecode_available = True - self.meter_bridge_available = True - - self.display_7seg_characters = [] - for _ in range(4): - self.display_7seg_characters.append(' ') - - self.display_timecode_characters = [] - for _ in range(20): - self.display_timecode_characters.append(' ') - - @staticmethod - def get_usage_hint(): - return '' - - def _log(self, message, repaint=False): - self.callback_log('[Controller Template] ' + message, repaint) - - # --- initialisation --- - def set_interconnector(self, host): - self.interconnector = host - - def unset_interconnector(self): - self.interconnector = None - - def connect(self): - self._log('Opening MIDI ports...', True) - self.midi.connect(self._midi_input_name, self._midi_output_name) - - def disconnect(self): - self._log('Closing MIDI ports...') - self.midi.disconnect() - self._log('Disconnected.', True) - - def go_online(self): - self._log('Mackie Host Control went online...', True) - - def go_offline(self): - self._log('Mackie Host Control went offline...', True) - - # --- abilities of hardware controller --- - def has_display_7seg(self): - return self.display_7seg_available - - def has_display_lcd(self): - return self.display_lcd_available - - def has_display_timecode(self): - return self.display_timecode_available - - def has_automated_faders(self): - return self.automated_faders_available - - def has_meter_bridge(self): - return self.meter_bridge_available - - # --- MIDI processing --- - def process_midi_input(self): - self.midi.process_input_buffer() - - def receive_midi(self, status, message): - message_string = ['status %02X: ' % status] - for byte in message: - message_string.append('%02X' % byte) - self._log(' '.join(message_string)) - - def send_midi_control_change(self, channel, cc_number, cc_value): - self.midi.send_control_change(channel, cc_number, cc_value) - - def send_midi_sysex(self, data): - assert isinstance(data, list) - - header = [] - header.extend(self.MIDI_MANUFACTURER_ID) - header.extend(self.MIDI_DEVICE_ID) - - self.midi.send_sysex(header, data) - - @staticmethod - def get_preferred_midi_input(): - return '' - - @staticmethod - def get_preferred_midi_output(): - return '' - - # --- registration of MIDI controls --- - def register_control(self, mcu_command, midi_switch, midi_led=None): - if midi_led: - self.interconnector.register_control(mcu_command, midi_switch, midi_led) - else: - self.interconnector.register_control(mcu_command, midi_switch, midi_switch) - - def withdraw_control(self, midi_switch): - self.interconnector.withdraw_control(midi_switch) - - def withdraw_all_controls(self): - self.interconnector.withdraw_all_controls() - - # --- handling of Mackie Control commands --- - def set_lcd(self, position, hex_codes, update=True): - for hex_code in hex_codes: - # wrap display and determine position - position %= 112 - (line, pos) = divmod(position, 56) - - # convert illegal characters to asterisk - if (hex_code < 0x20) or (hex_code > 0x7F): - self._lcd_characters[line][pos] = '*' - else: - self._lcd_characters[line][pos] = chr(hex_code) - - position += 1 - - if update: - self.update_lcd() - - def set_led(self, internal_id, led_status): - pass - - def set_display_7seg(self, position, character_code): - character = self._decode_7seg_character(character_code) - position = 23 - (position * 2) - - self.display_7seg_characters[position - 1] = character[0] - self.display_7seg_characters[position] = character[1] - - string_7seg = ''.join(self.display_7seg_characters) - self._log('7 segment display NOT set to "%s".' % string_7seg) - - @staticmethod - def _decode_7seg_character(character_code): - if character_code >= 0x40: - character_code = character_code - 0x40 - dot = '.' - else: - dot = ' ' - - if character_code < 0x20: - return chr(character_code + 0x40), dot - - return chr(character_code), dot - - def set_display_timecode(self, position, character_code): - character = self._decode_7seg_character(character_code) - position = 19 - (position * 2) - - self.display_timecode_characters[position - 1] = character[0] - self.display_timecode_characters[position] = character[1] - - # please note that the logged timecode is not necessarily - # correct: it will only be dumped when the display's last - # character has been updated -- there may be other updates - # still pending! - if position == 19: - string_timecode = ''.join(self.display_timecode_characters) - self._log('timecode display NOT set to "%s".' % string_timecode) - - def set_peak_level(self, meter_id, meter_level): - if meter_level == 0x0F: - self._log('Meter #%d overload NOT cleared.' % meter_id) - elif meter_level == 0x0F: - self._log('Meter #%d NOT set to overload.' % meter_id) - else: - self._log('Meter #%d NOT set to %03d%%.' % (meter_id, meter_level * 10)) - - def fader_moved(self, fader_id, fader_position): - self._log('Hardware fader #%d NOT moved to position %04d.' % (fader_id, fader_position)) - - def set_vpot_led_ring(self, vpot_id, vpot_center_led, vpot_mode, vpot_position): - self._log('V-Pot #%d LED ring NOT set to position %02d (mode %d).' % (vpot_id, vpot_position, vpot_mode)) - - def faders_to_minimum(self): - self._log('Hardware faders NOT set to minimum.') - - def all_leds_off(self): - self._log('Hardware LEDs NOT set to "off".') - - # --- LCD and menu handling - def update_lcd(self): - pass - - def get_lcd_characters(self, line): - line %= 2 - - if self._show_overlay[line]: - return self._lcd_overlay_characters[line] - - return self._lcd_characters[line] - - def show_menu(self, line, menu_strings): - assert len(menu_strings) == 8 - - menu_string_temp = '' - for menu_string in menu_strings: - menu_string_temp += menu_string.center(7)[:7] - - menu_characters = list(menu_string_temp) - self.show_overlay(line, menu_characters) - - def hide_menu(self, line): - self.hide_overlay(line) - - def show_overlay(self, line, overlay_characters): - line %= 2 - assert len(overlay_characters) == 56 - - self._show_overlay[line] = True - self._lcd_overlay_characters[line] = overlay_characters - self.update_lcd() - - def hide_overlay(self, line): - line %= 2 - - self._show_overlay[line] = False - self.update_lcd() diff --git a/python_mcu/PythonMcu/Hardware/NovationZeROSLMkII.py b/python_mcu/PythonMcu/Hardware/NovationZeROSLMkII.py index b1099aa..242d64a 100644 --- a/python_mcu/PythonMcu/Hardware/NovationZeROSLMkII.py +++ b/python_mcu/PythonMcu/Hardware/NovationZeROSLMkII.py @@ -25,17 +25,12 @@ """ import os -import sys -if __name__ == "__main__": - # allow "PythonMcu" package imports when executing this module - sys.path.append('../../../') +from ..Hardware._MidiControllerTemplate import _MidiControllerTemplate +from ..Midi.MidiConnection import MidiConnection -from PythonMcu.Hardware.MidiControllerTemplate import MidiControllerTemplate -from PythonMcu.Midi.MidiConnection import MidiConnection - -class NovationZeROSLMkII(MidiControllerTemplate): +class NovationZeROSLMkII(_MidiControllerTemplate): # Novation Digital Music System MIDI_MANUFACTURER_ID = [0x00, 0x20, 0x29] @@ -93,7 +88,7 @@ class NovationZeROSLMkII(MidiControllerTemplate): _MODE_OTHER_UTILITY = 5 def __init__(self, midi_input, midi_output, callback_log): - MidiControllerTemplate.__init__(self, midi_input, midi_output, callback_log) + super().__init__(midi_input, midi_output, callback_log) self.display_lcd_available = True self.automated_faders_available = False @@ -116,14 +111,14 @@ def __init__(self, midi_input, midi_output, callback_log): @staticmethod def get_usage_hint(): return 'Connect the controller\'s USB port to your computer ' + \ - 'and switch to preset #32 (Ableton Live Automap).' + 'and select the second ZeRO MkII MIDI port.' def _log(self, message, repaint=False): self.callback_log('[Novation ZeRO SL MkII] ' + message, repaint) # --- initialisation --- def connect(self): - MidiControllerTemplate.connect(self) + super().connect() self._is_connected = True self.set_lcd_directly(0, 'Novation ZeRO SL MkII: initialising...') @@ -150,16 +145,16 @@ def disconnect(self): self._leave_ableton_mode() self._is_connected = False - MidiControllerTemplate.disconnect(self) + super().disconnect() def go_online(self): - MidiControllerTemplate.go_online(self) + super().go_online() self.set_lcd_directly(0, 'Novation ZeRO SL MkII: initialised.') self.set_lcd_directly(1, 'Mackie Host Control: online.') def go_offline(self): - MidiControllerTemplate.go_offline(self) + super().go_offline() self.set_lcd_directly(0, 'Novation ZeRO SL MkII: initialised.') self.set_lcd_directly(1, 'Mackie Host Control: offline.') @@ -216,30 +211,34 @@ def receive_midi(self, status, message): return cc_selector = { - self._MIDI_CC_FADERS: 'self.interconnector.move_fader_7bit(0, %d)', - self._MIDI_CC_FADERS + 1: 'self.interconnector.move_fader_7bit(1, %d)', - self._MIDI_CC_FADERS + 2: 'self.interconnector.move_fader_7bit(2, %d)', - self._MIDI_CC_FADERS + 3: 'self.interconnector.move_fader_7bit(3, %d)', - self._MIDI_CC_FADERS + 4: 'self.interconnector.move_fader_7bit(4, %d)', - self._MIDI_CC_FADERS + 5: 'self.interconnector.move_fader_7bit(5, %d)', - self._MIDI_CC_FADERS + 6: 'self.interconnector.move_fader_7bit(6, %d)', - self._MIDI_CC_FADERS + 7: 'self.interconnector.move_fader_7bit(7, %d)', - self._MIDI_CC_ENCODERS: 'self.interconnector.move_vpot_raw(0, %d)', - self._MIDI_CC_ENCODERS + 1: 'self.interconnector.move_vpot_raw(1, %d)', - self._MIDI_CC_ENCODERS + 2: 'self.interconnector.move_vpot_raw(2, %d)', - self._MIDI_CC_ENCODERS + 3: 'self.interconnector.move_vpot_raw(3, %d)', - self._MIDI_CC_ENCODERS + 4: 'self.interconnector.move_vpot_raw(4, %d)', - self._MIDI_CC_ENCODERS + 5: 'self.interconnector.move_vpot_raw(5, %d)', - self._MIDI_CC_ENCODERS + 6: 'self.interconnector.move_vpot_raw(6, %d)', - self._MIDI_CC_ENCODERS + 7: 'self.interconnector.move_vpot_raw(7, %d)', - self._MIDI_CC_CONTROL_PEDAL: 'self.on_control_pedal(%d & 0x01)', - self._MIDI_CC_BUTTON_BANK_UP: 'self._change_mode_edit(%d & 0x01)', - self._MIDI_CC_BUTTON_BANK_DOWN: 'self._change_mode_track(%d & 0x01)', - self._MIDI_CC_BUTTONS_RIGHT_BOTTOM: 'self._change_mode_bank(%d & 0x01)', - self._MIDI_CC_BUTTONS_RIGHT_BOTTOM + 1: 'self._change_mode_automation(%d & 0x01)', - self._MIDI_CC_BUTTONS_RIGHT_BOTTOM + 2: 'self._change_mode_global_view(%d & 0x01)', - self._MIDI_CC_BUTTONS_RIGHT_BOTTOM + 3: 'self._change_mode_utility(%d & 0x01)', - self._MIDI_CC_BUTTON_MODE_TRANSPORT: 'self._change_mode_transport(%d & 0x01)', + self._MIDI_CC_FADERS: {'member': self.interconnector, 'method': 'move_fader_7bit', 'params': [0, '{:d}']}, + self._MIDI_CC_FADERS + 1: {'member': self.interconnector, 'method': 'move_fader_7bit', 'params': [1, '{:d}']}, + self._MIDI_CC_FADERS + 2: {'member': self.interconnector, 'method': 'move_fader_7bit', 'params': [2, '{:d}']}, + self._MIDI_CC_FADERS + 3: {'member': self.interconnector, 'method': 'move_fader_7bit', 'params': [3, '{:d}']}, + self._MIDI_CC_FADERS + 4: {'member': self.interconnector, 'method': 'move_fader_7bit', 'params': [4, '{:d}']}, + self._MIDI_CC_FADERS + 5: {'member': self.interconnector, 'method': 'move_fader_7bit', 'params': [5, '{:d}']}, + self._MIDI_CC_FADERS + 6: {'member': self.interconnector, 'method': 'move_fader_7bit', 'params': [6, '{:d}']}, + self._MIDI_CC_FADERS + 7: {'member': self.interconnector, 'method': 'move_fader_7bit', 'params': [7, '{:d}']}, + self._MIDI_CC_ENCODERS: {'member': self.interconnector, 'method': 'move_vpot_raw', 'params': [0, '{:d}']}, + self._MIDI_CC_ENCODERS + 1: {'member': self.interconnector, 'method': 'move_vpot_raw', 'params': [1, '{:d}']}, + self._MIDI_CC_ENCODERS + 2: {'member': self.interconnector, 'method': 'move_vpot_raw', 'params': [2, '{:d}']}, + self._MIDI_CC_ENCODERS + 3: {'member': self.interconnector, 'method': 'move_vpot_raw', 'params': [3, '{:d}']}, + self._MIDI_CC_ENCODERS + 4: {'member': self.interconnector, 'method': 'move_vpot_raw', 'params': [4, '{:d}']}, + self._MIDI_CC_ENCODERS + 5: {'member': self.interconnector, 'method': 'move_vpot_raw', 'params': [5, '{:d}']}, + self._MIDI_CC_ENCODERS + 6: {'member': self.interconnector, 'method': 'move_vpot_raw', 'params': [6, '{:d}']}, + self._MIDI_CC_ENCODERS + 7: {'member': self.interconnector, 'method': 'move_vpot_raw', 'params': [7, '{:d}']}, + self._MIDI_CC_CONTROL_PEDAL: {'member': self, 'method': 'on_control_pedal', 'params': ['{:d}']}, + self._MIDI_CC_BUTTON_BANK_UP: {'member': self, 'method': '_change_mode_edit', 'params': ['{:d}']}, + self._MIDI_CC_BUTTON_BANK_DOWN: {'member': self, 'method': '_change_mode_track', 'params': ['{:d}']}, + self._MIDI_CC_BUTTONS_RIGHT_BOTTOM: {'member': self, 'method': '_change_mode_bank', 'params': ['{:d}']}, + self._MIDI_CC_BUTTONS_RIGHT_BOTTOM + 1: {'member': self, 'method': '_change_mode_automation', + 'params': ['{:d}']}, + self._MIDI_CC_BUTTONS_RIGHT_BOTTOM + 2: {'member': self, 'method': '_change_mode_global_view', + 'params': ['{:d}']}, + self._MIDI_CC_BUTTONS_RIGHT_BOTTOM + 3: {'member': self, 'method': '_change_mode_utility', + 'params': ['{:d}']}, + self._MIDI_CC_BUTTON_MODE_TRANSPORT: {'member': self, 'method': '_change_mode_transport', + 'params': ['{:d}']}, } # make sure that no submenu disturbs toggling the "Global @@ -252,26 +251,32 @@ def receive_midi(self, status, message): cc_value = message[2] if cc_number in cc_selector: - eval(cc_selector[cc_number] % cc_value) + cc_member = cc_selector[cc_number]['member'] + cc_method = getattr(cc_member, cc_selector[cc_number]['method']) + cc_params = cc_selector[cc_number]['params'] + for index, param in enumerate(cc_params): + if isinstance(param, str): + cc_params[index] = param.format(cc_value) + cc_params[index] = int(cc_params[index]) + cc_method(*cc_params) elif cc_number == 0x6B: # this controller change message is sent on entering # and leaving "Automap" mode and can be probably # ignored pass else: - internal_id = 'cc%d' % cc_number - status = cc_value & 0x01 - key_processed = self.interconnector.keypress(internal_id, status) + internal_id = f'cc{cc_number}' + key_processed = self.interconnector.keypress(internal_id, cc_value) if not key_processed: - message_string = ['status %02X: ' % status] + message_string = [f'status {status:02X}: '] for byte in message: - message_string.append('%02X' % byte) + message_string.append(f'{byte:02X}') self._log(' '.join(message_string)) else: - message_string = ['status %02X: ' % status] + message_string = [f'status {status:02X}: '] for byte in message: - message_string.append('%02X' % byte) + message_string.append(f'{byte:02X}') self._log(' '.join(message_string)) def send_midi_control_change(self, channel=None, cc_number=None, cc_value=None): @@ -281,41 +286,40 @@ def send_midi_control_change(self, channel=None, cc_number=None, cc_value=None): if channel: raise ValueError("The channel is fixed for this device!") - MidiControllerTemplate.send_midi_control_change(self, self._MIDI_DEVICE_CHANNEL, cc_number, cc_value) + super().send_midi_control_change(self._MIDI_DEVICE_CHANNEL, cc_number, cc_value) @staticmethod def get_preferred_midi_input(): if os.name == 'nt': - return 'ZeRO MkII: Port 2' + return 'MIDIIN2 (ZeRO MkII)' # Windows 10 (without Automap drivers) + #return 'ZeRO MkII: Port 2' # Windows 7? return 'ZeRO MkII MIDI 2' @staticmethod def get_preferred_midi_output(): if os.name == 'nt': - return 'ZeRO MkII: Port 2' + return 'MIDIOUT2 (ZeRO MkII)' # Windows 10 (without Automap drivers) + #return 'ZeRO MkII: Port 2' # Windows 7? return 'ZeRO MkII MIDI 2' # --- registration of MIDI controls --- def register_control(self, mcu_command, midi_switch, midi_led=None): - midi_switch_cc = 'cc%d' % midi_switch + midi_switch_cc = f'cc{midi_switch}' if midi_led: - midi_led_cc = 'cc%d' % midi_led + midi_led_cc = f'cc{midi_led}' else: midi_led_cc = midi_switch_cc self.interconnector.register_control(mcu_command, midi_switch_cc, midi_led_cc) def withdraw_control(self, midi_switch): - midi_switch_cc = 'cc%d' % midi_switch + midi_switch_cc = f'cc{midi_switch}' self.interconnector.withdraw_control(midi_switch_cc) - def set_display_7seg(self, position, character_code): - MidiControllerTemplate.set_display_7seg(self, position, character_code) - # --- handling of Mackie Control commands --- def set_lcd_directly(self, line, lcd_string): if len(lcd_string) != 72: @@ -388,15 +392,15 @@ def set_led(self, internal_id, led_status): controller_id = int(internal_id[2:]) if controller_type == 'cc': - MidiControllerTemplate.send_midi_control_change(self, self._MIDI_DEVICE_CHANNEL, controller_id, led_status) + super().send_midi_control_change(self._MIDI_DEVICE_CHANNEL, controller_id, led_status) else: - self._log('controller type "%s" unknown.' % controller_type) + self._log(f'controller type "{controller_type}" unknown.') def _set_led(self, led_id, led_status): if not self._is_connected: return - MidiControllerTemplate.send_midi_control_change(self, self._MIDI_DEVICE_CHANNEL, led_id, led_status) + super().send_midi_control_change(self._MIDI_DEVICE_CHANNEL, led_id, led_status) def set_vpot_led_ring(self, vpot_id, vpot_center_led, vpot_mode, vpot_position): mode = None diff --git a/python_mcu/PythonMcu/Hardware/NovationZeROSLMkIIMIDI.py b/python_mcu/PythonMcu/Hardware/NovationZeROSLMkIIMIDI.py index be37d0d..7c49524 100644 --- a/python_mcu/PythonMcu/Hardware/NovationZeROSLMkIIMIDI.py +++ b/python_mcu/PythonMcu/Hardware/NovationZeROSLMkIIMIDI.py @@ -24,14 +24,8 @@ """ -import sys - -if __name__ == "__main__": - # allow "PythonMcu" package imports when executing this module - sys.path.append('../../../') - -from PythonMcu.Hardware.NovationZeROSLMkII import NovationZeROSLMkII -from PythonMcu.Midi.MidiConnection import MidiConnection +from ..Hardware.NovationZeROSLMkII import NovationZeROSLMkII +from ..Midi.MidiPorts import MidiPorts class NovationZeROSLMkIIMIDI(NovationZeROSLMkII): @@ -40,7 +34,7 @@ def __init__(self, midi_input, midi_output, callback_log): @staticmethod def get_usage_hint(): - return 'Connect the controller\'s "MIDI Port 1" to your computer, ' + \ + return 'Connect the controller\'s "MIDI Port 1" to your MIDI interface, ' + \ 'switch to preset #32 (Ableton Live Automap) ' + \ 'and change the following settings:\n\n' + \ '* Global --> Routing --> MIDI To:\n remove port "M1"\n' + \ @@ -50,8 +44,8 @@ def get_usage_hint(): # --- MIDI processing --- @staticmethod def get_preferred_midi_input(): - return MidiConnection.get_default_midi_input().decode('utf-8') + return MidiPorts.get_default_midi_input() @staticmethod def get_preferred_midi_output(): - return MidiConnection.get_default_midi_output().decode('utf-8') + return MidiPorts.get_default_midi_output() diff --git a/python_mcu/PythonMcu/Hardware/_MidiControllerTemplate.py b/python_mcu/PythonMcu/Hardware/_MidiControllerTemplate.py new file mode 100644 index 0000000..381b300 --- /dev/null +++ b/python_mcu/PythonMcu/Hardware/_MidiControllerTemplate.py @@ -0,0 +1,436 @@ +# -*- coding: utf-8 -*- + +""" +PythonMcu +========= +Mackie Host Controller written in Python +Copyright (c) 2011 Martin Zuther (http://www.mzuther.de/) +Copyright (c) 2021 Raphaël Doursenaud + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . + +Thank you for using free software! + +""" + +from ..Midi.MidiConnection import MidiConnection + + +class _MidiControllerTemplate: + MIDI_MANUFACTURER_ID = None + MIDI_DEVICE_ID = None + + VPOT_MODE_SINGLE_DOT = 0x00 + VPOT_MODE_BOOST_CUT = 0x01 + VPOT_MODE_WRAP = 0x02 + VPOT_MODE_SPREAD = 0x03 + + _LED_STATUS = { + 0x00: 'off', + 0x01: 'flashing', + 0x7F: 'on' + } + + def __init__(self, midi_input_name, midi_output_name, callback_log): + self.callback_log = callback_log + + # LCD has 2 rows with 56 characters each, fill with spaces + self._lcd_characters = [' '] * 2 + self._lcd_overlay_characters = [' '] * 2 + + for line in range(2): + # noinspection PyTypeChecker + self._lcd_characters[line] = [' '] * 56 + # noinspection PyTypeChecker + self._lcd_overlay_characters[line] = [' '] * 56 + + self._show_overlay = [False, False] + + self._log('Initialising MIDI ports...', True) + self._midi_input_name = midi_input_name + self._midi_output_name = midi_output_name + self.midi = MidiConnection(self.callback_log, self.receive_midi) + + # Initialized by set_interconnector() + self.interconnector = None + + self.display_lcd_available = True + self.automated_faders_available = True + self.display_7seg_available = True + self.display_timecode_available = True + self.meter_bridge_available = True + + self.display_7seg_characters = [] + for _ in range(4): + self.display_7seg_characters.append(' ') + + self.display_timecode_characters = [] + for _ in range(20): + self.display_timecode_characters.append(' ') + + @staticmethod + def get_usage_hint(): + return '' + + def _log(self, message, repaint=False): + self.callback_log('[Controller Template] ' + message, repaint) + + # --- initialisation --- + def set_interconnector(self, host): + self.interconnector = host + + def unset_interconnector(self): + self.interconnector = None + + def connect(self): + self._log('Opening MIDI ports...', True) + self.midi.connect(self._midi_input_name, self._midi_output_name) + #self._register_all_controls() + + def _register_all_controls(self): + + # Register all controls (According to Logic Control specs) + ## REC/RDY Ch. 1-8 (Switch + LED) + self.register_control('record_ready_channel_1', 0x00) + self.register_control('record_ready_channel_2', 0x01) + self.register_control('record_ready_channel_3', 0x02) + self.register_control('record_ready_channel_4', 0x03) + self.register_control('record_ready_channel_5', 0x04) + self.register_control('record_ready_channel_6', 0x05) + self.register_control('record_ready_channel_7', 0x06) + self.register_control('record_ready_channel_8', 0x07) + ## SOLO Ch. 1-8 (Switch + LED) + self.register_control('solo_channel_1', 0x08) + self.register_control('solo_channel_2', 0x09) + self.register_control('solo_channel_3', 0x0A) + self.register_control('solo_channel_4', 0x0B) + self.register_control('solo_channel_5', 0x0C) + self.register_control('solo_channel_6', 0x0D) + self.register_control('solo_channel_7', 0x0E) + self.register_control('solo_channel_8', 0x0F) + ## MUTE Ch. 1-8 (Switch + LED) + self.register_control('mute_channel_1', 0x10) + self.register_control('mute_channel_2', 0x11) + self.register_control('mute_channel_3', 0x12) + self.register_control('mute_channel_4', 0x13) + self.register_control('mute_channel_5', 0x14) + self.register_control('mute_channel_6', 0x15) + self.register_control('mute_channel_7', 0x16) + self.register_control('mute_channel_8', 0x17) + ## SELECT Ch. 1-8 (Switch + LED) + self.register_control('select_channel_1', 0x18) + self.register_control('select_channel_2', 0x19) + self.register_control('select_channel_3', 0x1A) + self.register_control('select_channel_4', 0x1B) + self.register_control('select_channel_5', 0x1C) + self.register_control('select_channel_6', 0x1D) + self.register_control('select_channel_7', 0x1E) + self.register_control('select_channel_8', 0x1F) + ## V-Select Ch. 1-8 (Switch only) + self.register_control('vselect_channel_1', 0x20) + self.register_control('vselect_channel_2', 0x21) + self.register_control('vselect_channel_3', 0x22) + self.register_control('vselect_channel_4', 0x23) + self.register_control('vselect_channel_5', 0x24) + self.register_control('vselect_channel_6', 0x25) + self.register_control('vselect_channel_7', 0x26) + self.register_control('vselect_channel_8', 0x27) + ## Assignments (Switch + LED) + self.register_control('assignment_track', 0x28) + self.register_control('assignment_send', 0x29) + self.register_control('assignment_pan_surround', 0x2A) + self.register_control('assignment_plug_in', 0x2B) + self.register_control('assignment_eq', 0x2C) + self.register_control('assignment_instrument', 0x2D) + ## Fader banks (Switc only) + self.register_control('fader_banks_bank_left', 0x2E) + self.register_control('fader_banks_channel_left', 0x2F) + self.register_control('fader_banks_channel_right', 0x30) + self.register_control('fader_banks_bank_right', 0x31) + ## Flip (Switch + LED) + self.register_control('flip', 0x32) + ## Global View (Switch + LED) + self.register_control('global_view', 0x33) + ## Name/Value (Switch only) + self.register_control('name_value', 0x34) + ## SMPTE/BEATS (Switch only) + self.register_control('smpte_beats', 0x35) + ## F1-F8 (Switch only) + self.register_control('function_channel_1', 0x36) + self.register_control('function_channel_2', 0x37) + self.register_control('function_channel_3', 0x38) + self.register_control('function_channel_4', 0x39) + self.register_control('function_channel_5', 0x3A) + self.register_control('function_channel_6', 0x3B) + self.register_control('function_channel_7', 0x3C) + self.register_control('function_channel_8', 0x3D) + ## Global view: functions (Switch only) + self.register_control('global_view_midi_tracks', 0x3E) + self.register_control('global_view_inputs', 0x3F) + self.register_control('global_view_audio_tracks', 0x40) + self.register_control('global_view_audio_instruments', 0x41) + self.register_control('global_view_aux', 0x42) + self.register_control('global_view_busses', 0x43) + self.register_control('global_view_outputs', 0x44) + self.register_control('global_view_user', 0x45) + ## Nav (Switch only) + self.register_control('shift', 0x46) + self.register_control('option', 0x47) + self.register_control('control', 0x48) + self.register_control('command_alt', 0x49) + ## Automation (Switch + LED) + self.register_control('automation_read_off', 0x4A) + self.register_control('automation_write', 0x4B) + self.register_control('automation_trim', 0xC) + self.register_control('automation_touch', 0x4D) + self.register_control('automation_latch', 0x4E) + self.register_control('group', 0x4F) + ## Utilities + self.register_control('utilities_save', 0x50) # Switch + LED + self.register_control('utilities_undo', 0x51) # Switch + LED + self.register_control('utilities_cancel', 0x52) # Switch only + self.register_control('utilities_enter', 0x53) # Switch only + ## Edit (Switch + LED) + self.register_control('marker', 0x54) + self.register_control('nudge', 0x55) + self.register_control('cycle', 0x56) + self.register_control('drop', 0x57) + self.register_control('replace', 0x58) + self.register_control('click', 0x59) + self.register_control('solo', 0x5A) + ## Transport (Switch + LED) + self.register_control('rewind', 0x5A) + self.register_control('fast_forward', 0x5B) + self.register_control('stop', 0x5C) + self.register_control('play', 0x5D) + self.register_control('cycle', 0x5E) + self.register_control('record', 0x5F) + ## Cursor (Switch only) + self.register_control('cursor_left', 0x60) + self.register_control('cursor_right', 0x61) + self.register_control('cursor_down', 0x62) + self.register_control('cursor_up', 0x63) + ## Zoom (Switch + LED) + self.register_control('zoom', 0x64) + ## Scrub (Switch + LED) + self.register_control('scrub', 0x65) + ## User Switches A-B (Switch only) + self.register_control('user_switch_1', 0x66) + self.register_control('user_switch_2', 0x67) + ## Fader Touch Ch. 1-8 (Switch only) + self.register_control('fader_touch_1', 0x68) + self.register_control('fader_touch_2', 0x69) + self.register_control('fader_touch_3', 0x6A) + self.register_control('fader_touch_4', 0x6B) + self.register_control('fader_touch_5', 0x6C) + self.register_control('fader_touch_6', 0x6D) + self.register_control('fader_touch_7', 0x6E) + self.register_control('fader_touch_8', 0x6F) + self.register_control('fader_touch_master', 0x70) + ## Status (LED only) + self.register_control('smpte', 0x71) + self.register_control('beats', 0x72) + self.register_control('rude_solo', 0x73) + self.register_control('relay_click', 0x76) + + def disconnect(self): + self._log('Closing MIDI ports...') + self.midi.disconnect() + self._log('Disconnected.', True) + + def go_online(self): + self._log('Mackie Host Control went online...', True) + + def go_offline(self): + self._log('Mackie Host Control went offline...', True) + + # --- abilities of hardware controller --- + def has_display_7seg(self): + return self.display_7seg_available + + def has_display_lcd(self): + return self.display_lcd_available + + def has_display_timecode(self): + return self.display_timecode_available + + def has_automated_faders(self): + return self.automated_faders_available + + def has_meter_bridge(self): + return self.meter_bridge_available + + # --- MIDI processing --- + def process_midi_input(self): + self.midi.process_input_buffer() + + def receive_midi(self, status, message): + message_string = [f'status {status:02X}: '] + for byte in message: + message_string.append(f'{byte:02X}') + self._log(' '.join(message_string)) + + def send_midi_control_change(self, channel, cc_number, cc_value): + self.midi.send_control_change(channel, cc_number, cc_value) + + def send_midi_sysex(self, data): + assert isinstance(data, list) + + header = [] + header.extend(self.MIDI_MANUFACTURER_ID) + header.extend(self.MIDI_DEVICE_ID) + + self.midi.send_sysex(header, data) + + @staticmethod + def get_preferred_midi_input(): + return '' + + @staticmethod + def get_preferred_midi_output(): + return '' + + # --- registration of MIDI controls --- + def register_control(self, mcu_command, midi_switch, midi_led=None): + if midi_led: + self.interconnector.register_control(mcu_command, midi_switch, midi_led) + else: + self.interconnector.register_control(mcu_command, midi_switch, midi_switch) + + def withdraw_control(self, midi_switch): + self.interconnector.withdraw_control(midi_switch) + + def withdraw_all_controls(self): + self.interconnector.withdraw_all_controls() + + # --- handling of Mackie Control commands --- + def set_lcd(self, position, hex_codes, update=True): + for hex_code in hex_codes: + # wrap display and determine position + position %= 112 + (line, pos) = divmod(position, 56) + + # convert illegal characters to asterisk + if (hex_code < 0x20) or (hex_code > 0x7F): + self._lcd_characters[line][pos] = '*' + else: + self._lcd_characters[line][pos] = chr(hex_code) + + position += 1 + + if update: + self.update_lcd() + + def set_led(self, internal_id, led_status): + self._log(f'LED #{internal_id} NOT set to {self._LED_STATUS[led_status]}.') + + def set_display_7seg(self, position, character_code): + character = self._decode_7seg_character(character_code) + position = 23 - (position * 2) + + self.display_7seg_characters[position - 1] = character[0] + self.display_7seg_characters[position] = character[1] + + string_7seg = ''.join(self.display_7seg_characters) + self._log(f'7 segment display NOT set to "{string_7seg}".') + + @staticmethod + def _decode_7seg_character(character_code): + if character_code >= 0x40: + character_code = character_code - 0x40 + dot = '.' + else: + dot = ' ' + + if character_code < 0x20: + return chr(character_code + 0x40), dot + + return chr(character_code), dot + + def set_display_timecode(self, position, character_code): + character = self._decode_7seg_character(character_code) + position = 19 - (position * 2) + + self.display_timecode_characters[position - 1] = character[0] + self.display_timecode_characters[position] = character[1] + + # please note that the logged timecode is not necessarily + # correct: it will only be dumped when the display's last + # character has been updated -- there may be other updates + # still pending! + if position == 19: + string_timecode = ''.join(self.display_timecode_characters) + self._log(f'timecode display NOT set to "{string_timecode}".') + + def set_peak_level(self, meter_id, meter_level): + if meter_level == 0x0F: + self._log(f'Meter #{meter_id:d} overload NOT cleared.') + elif meter_level == 0x0F: + self._log(f'Meter #{meter_id:d} NOT set to overload.') + else: + self._log(f'Meter #{meter_id:d} NOT set to {meter_level * 10:03d}%.') + + def fader_moved(self, fader_id, fader_position): + self._log(f'Hardware fader #{fader_id:d} NOT moved to position {fader_position:04d}.') + + def set_vpot_led_ring(self, vpot_id, vpot_center_led, vpot_mode, vpot_position): + self._log(f'V-Pot #{vpot_id:d} LED ring NOT set to position {vpot_position:02d} (mode {vpot_mode:d}).') + + def faders_to_minimum(self): + self._log('Hardware faders NOT set to minimum.') + + def all_leds_off(self): + self._log('Hardware LEDs NOT set to "off".') + + # --- LCD and menu handling + def update_lcd(self): + display = ['', ''] + for line in range(2): + display[line].join(self.get_lcd_characters(line)) + self._log(f"Display NOT set to\n'{display[0]}'\n'{display[1]}'") + + def get_lcd_characters(self, line): + line %= 2 + + if self._show_overlay[line]: + return self._lcd_overlay_characters[line] + + return self._lcd_characters[line] + + def show_menu(self, line, menu_strings): + assert len(menu_strings) == 8 + + menu_string_temp = '' + for menu_string in menu_strings: + menu_string_temp += menu_string.center(7)[:7] + + menu_characters = list(menu_string_temp) + self.show_overlay(line, menu_characters) + + def hide_menu(self, line): + self.hide_overlay(line) + + def show_overlay(self, line, overlay_characters): + line %= 2 + assert len(overlay_characters) == 56 + + self._show_overlay[line] = True + self._lcd_overlay_characters[line] = overlay_characters + self.update_lcd() + + def hide_overlay(self, line): + line %= 2 + + self._show_overlay[line] = False + self.update_lcd() diff --git a/python_mcu/PythonMcu/Hardware/__init__.py b/python_mcu/PythonMcu/Hardware/__init__.py index ef58293..943001b 100644 --- a/python_mcu/PythonMcu/Hardware/__init__.py +++ b/python_mcu/PythonMcu/Hardware/__init__.py @@ -23,8 +23,3 @@ Thank you for using free software! """ - -__all__ = [ - 'NovationZeROSLMkII', - 'NovationZeROSLMkIIMIDI' -] diff --git a/python_mcu/PythonMcu/MackieControl/MackieHostControl.py b/python_mcu/PythonMcu/MackieControl/MackieHostControl.py index 7676c00..aa7aa7d 100644 --- a/python_mcu/PythonMcu/MackieControl/MackieHostControl.py +++ b/python_mcu/PythonMcu/MackieControl/MackieHostControl.py @@ -25,14 +25,9 @@ """ import os -import sys import time -if __name__ == "__main__": - # allow "PythonMcu" package imports when executing this module - sys.path.append('../../') - -from PythonMcu.Midi.MidiConnection import MidiConnection +from ..Midi.MidiConnection import MidiConnection class MackieHostControl: @@ -43,6 +38,8 @@ class MackieHostControl: CHALLENGE_RESPONSE = 'Challenge / Response' WAIT_FOR_MIDI_DATA = 'Wait for MIDI data' + MACKIE_SYSEX_ID = [0x00, 0x00, 0x66] + SWITCH_RELEASED = 0 SWITCH_PRESSED = 1 SWITCH_PRESSED_RELEASED = 2 @@ -199,6 +196,9 @@ def connect(self): self._log('Opening MIDI ports...') self._midi.connect(self._midi_input_name, self._midi_output_name) + # let's make sure the MIDI input buffer is empty + self._midi.process_input_buffer(use_callback=False) + if self._mcu_connection == self.CHALLENGE_RESPONSE: self._log('Sending "Host Connection Query"...', True) @@ -209,9 +209,6 @@ def connect(self): return - # let's make sure the MIDI input buffer is empty - self._midi.process_input_buffer(use_callback=False) - if self._mcu_connection == self.WAIT_FOR_MIDI_DATA: self._log('Waiting for MIDI input from host...', True) @@ -318,7 +315,10 @@ def process_midi_input(self): self._midi.process_input_buffer() def receive_midi(self, status, message): - if status == MidiConnection.SYSTEM_MESSAGE and message[0:5] == [0xF0, 0x00, 0x00, 0x66, self._mcu_model_id]: + + # We ignore the byte 4 (mcu_model_id) on purpose since the host can't know it yet + if status == MidiConnection.SYSTEM_MESSAGE and \ + message[0:4] == [MidiConnection.SYSTEM_MESSAGE] + self.MACKIE_SYSEX_ID: if message[5:] == [0x00, 0xF7]: self._log('Received "Device Query".') self._log('Sending "Host Connection Query"...', True) @@ -386,66 +386,66 @@ def receive_midi(self, status, message): # do not make this an "elif" clause, otherwise some MIDI SysEx # messages won't get processed! - if not self.is_offline(): - if status == MidiConnection.SYSTEM_MESSAGE and message[0:5] == [0xF0, 0x00, 0x00, 0x66, self._mcu_model_id]: - if message[5] == 0x12: - if self._display_lcd_available: - position = message[6] - hex_codes = message[7:-1] - - self._hardware_controller.set_lcd(position, hex_codes) - elif status == MidiConnection.PITCH_WHEEL_CHANGE: - if self._automated_faders_available: - fader_id = message[0] & 0x0F - fader_position = (message[1] + (message[2] << 7)) >> 4 - self._hardware_controller.fader_moved(fader_id, fader_position) - elif status == MidiConnection.NOTE_ON_EVENT: - led_id = message[1] - led_status = 0 # off - - if message[2] == 0x7F: - led_status = 1 # on - elif message[2] == 0x01: - led_status = 2 # flashing - - self._set_led(led_id, led_status) - elif (status == MidiConnection.CONTROL_CHANGE) and ((message[1] & 0xF0) == 0x30): - vpot_id = message[1] & 0x0F - vpot_center_led = (message[2] & 0x40) >> 7 - vpot_mode = (message[2] & 0x30) >> 4 - vpot_position = message[2] & 0x0F - self._hardware_controller.set_vpot_led_ring(vpot_id, vpot_center_led, vpot_mode, vpot_position) - elif (status == MidiConnection.CONTROL_CHANGE) and ((message[1] & 0xF0) == 0x40): - position = message[1] & 0x0F - character_code = message[2] - - if position < 10: - if self._display_timecode_available: - self._hardware_controller.set_display_timecode(position, character_code) - elif self._display_7seg_available: - self._hardware_controller.set_display_7seg(position, character_code) - elif status == MidiConnection.CHANNEL_PRESSURE: - if self._meter_bridge_available: - meter_id = (message[1] & 0x70) >> 4 - meter_level = message[1] & 0x0F - self._hardware_controller.set_peak_level(meter_id, meter_level) - else: - output = 'status %02X: ' % status - for byte in message: - output += '%02X ' % byte - - self._log(output.strip()) - else: - output = 'status %02X: ' % status - for byte in message: - output += '%02X ' % byte + if self.is_offline(): + self._log(f"Message received while offline: {message!r}") + return - self._log(output.strip()) + # Once again, we ignore the byte 4 (mcu_model_id) because some DAWs will send whatever (0x20 in Studio One 5) + if status == MidiConnection.SYSTEM_MESSAGE and \ + message[0:4] == [MidiConnection.SYSTEM_MESSAGE] + self.MACKIE_SYSEX_ID: + if message[5] == 0x12: + if self._display_lcd_available: + position = message[6] + hex_codes = message[7:-1] + + self._hardware_controller.set_lcd(position, hex_codes) + elif status == MidiConnection.PITCH_WHEEL_CHANGE: + if self._automated_faders_available: + fader_id = message[0] & 0x0F + fader_position = (message[1] + (message[2] << 7)) >> 4 + self._hardware_controller.fader_moved(fader_id, fader_position) + elif status == MidiConnection.NOTE_ON_EVENT: + led_id = message[1] + + led_status = 0 # off + if message[2] == 0x7F: + led_status = 1 # on + elif message[2] == 0x01: + led_status = 2 # flashing + + self._set_led(led_id, led_status) + elif status == MidiConnection.CONTROL_CHANGE and message[1] & 0xF0 == 0x30: + vpot_id = message[1] & 0x0F + vpot_center_led = (message[2] & 0x40) >> 7 + vpot_mode = (message[2] & 0x30) >> 4 + vpot_position = message[2] & 0x0F + + if vpot_id not in range(0, 8): + self._log(f"Ignoring out of range V-Pot ID received: {vpot_id:d}") + return + + self._hardware_controller.set_vpot_led_ring(vpot_id, vpot_center_led, vpot_mode, vpot_position) + elif (status == MidiConnection.CONTROL_CHANGE) and ((message[1] & 0xF0) == 0x40): + position = message[1] & 0x0F + character_code = message[2] + + if position < 10: + if self._display_timecode_available: + self._hardware_controller.set_display_timecode(position, character_code) + elif self._display_7seg_available: + self._hardware_controller.set_display_7seg(position, character_code) + elif status == MidiConnection.CHANNEL_PRESSURE: + if self._meter_bridge_available: + meter_id = (message[1] & 0x70) >> 4 + meter_level = message[1] & 0x0F + self._hardware_controller.set_peak_level(meter_id, meter_level) + else: + self._log(f"Unsupported message: {message!r}") def send_midi_sysex(self, data): assert isinstance(data, list) - header = [0x00, 0x00, 0x66, self._mcu_model_id] + header = self.MACKIE_SYSEX_ID + [self._mcu_model_id] # leading 0xF0 and trailing 0xF7 are added by "MidiConnection" # class method @@ -492,7 +492,7 @@ def _key_pressed(self, status, switch_id): self._midi.send_note_on(switch_id, 0x7F) self._midi.send_note_on(switch_id, 0x00) else: - self._log('Illegal key press status 0x%02X on switch 0x%02X detected!' % (status, switch_id)) + self._log(f'Illegal key press status 0x{status:02X} on switch 0x{switch_id:02X} detected!') def keypress_record_ready_channel(self, channel, status): # channel: 1 - 8 @@ -874,92 +874,94 @@ def _set_led(self, led_id, status): return selector = { - self._LED_SWITCH_CHANNEL_RECORD_READY: 'self._hardware_controller.set_led_channel_record_ready(0, status)', + self._LED_SWITCH_CHANNEL_RECORD_READY: {'method': 'set_led_channel_record_ready', 'params': f'0, {status}'}, self._LED_SWITCH_CHANNEL_RECORD_READY + 1: - 'self._hardware_controller.set_led_channel_record_ready(1, status)', + {'method': 'set_led_channel_record_ready', 'params': f'1, {status}'}, self._LED_SWITCH_CHANNEL_RECORD_READY + 2: - 'self._hardware_controller.set_led_channel_record_ready(2, status)', + {'method': 'set_led_channel_record_ready', 'params': f'2, {status}'}, self._LED_SWITCH_CHANNEL_RECORD_READY + 3: - 'self._hardware_controller.set_led_channel_record_ready(3, status)', + {'method': 'set_led_channel_record_ready', 'params': f'3, {status}'}, self._LED_SWITCH_CHANNEL_RECORD_READY + 4: - 'self._hardware_controller.set_led_channel_record_ready(4, status)', + {'method': 'set_led_channel_record_ready', 'params': f'4, {status}'}, self._LED_SWITCH_CHANNEL_RECORD_READY + 5: - 'self._hardware_controller.set_led_channel_record_ready(5, status)', + {'method': 'set_led_channel_record_ready', 'params': f'5, {status}'}, self._LED_SWITCH_CHANNEL_RECORD_READY + 6: - 'self._hardware_controller.set_led_channel_record_ready(6, status)', + {'method': 'set_led_channel_record_ready', 'params': f'6, {status}'}, self._LED_SWITCH_CHANNEL_RECORD_READY + 7: - 'self._hardware_controller.set_led_channel_record_ready(7, status)', - self._LED_SWITCH_CHANNEL_SOLO: 'self._hardware_controller.set_led_channel_solo(0, status)', - self._LED_SWITCH_CHANNEL_SOLO + 1: 'self._hardware_controller.set_led_channel_solo(1, status)', - self._LED_SWITCH_CHANNEL_SOLO + 2: 'self._hardware_controller.set_led_channel_solo(2, status)', - self._LED_SWITCH_CHANNEL_SOLO + 3: 'self._hardware_controller.set_led_channel_solo(3, status)', - self._LED_SWITCH_CHANNEL_SOLO + 4: 'self._hardware_controller.set_led_channel_solo(4, status)', - self._LED_SWITCH_CHANNEL_SOLO + 5: 'self._hardware_controller.set_led_channel_solo(5, status)', - self._LED_SWITCH_CHANNEL_SOLO + 6: 'self._hardware_controller.set_led_channel_solo(6, status)', - self._LED_SWITCH_CHANNEL_SOLO + 7: 'self._hardware_controller.set_led_channel_solo(7, status)', - self._LED_SWITCH_CHANNEL_MUTE: 'self._hardware_controller.set_led_channel_mute(0, status)', - self._LED_SWITCH_CHANNEL_MUTE + 1: 'self._hardware_controller.set_led_channel_mute(1, status)', - self._LED_SWITCH_CHANNEL_MUTE + 2: 'self._hardware_controller.set_led_channel_mute(2, status)', - self._LED_SWITCH_CHANNEL_MUTE + 3: 'self._hardware_controller.set_led_channel_mute(3, status)', - self._LED_SWITCH_CHANNEL_MUTE + 4: 'self._hardware_controller.set_led_channel_mute(4, status)', - self._LED_SWITCH_CHANNEL_MUTE + 5: 'self._hardware_controller.set_led_channel_mute(5, status)', - self._LED_SWITCH_CHANNEL_MUTE + 6: 'self._hardware_controller.set_led_channel_mute(6, status)', - self._LED_SWITCH_CHANNEL_MUTE + 7: 'self._hardware_controller.set_led_channel_mute(7, status)', - self._LED_SWITCH_CHANNEL_SELECT: 'self._hardware_controller.set_led_channel_select(0, status)', - self._LED_SWITCH_CHANNEL_SELECT + 1: 'self._hardware_controller.set_led_channel_select(1, status)', - self._LED_SWITCH_CHANNEL_SELECT + 2: 'self._hardware_controller.set_led_channel_select(2, status)', - self._LED_SWITCH_CHANNEL_SELECT + 3: 'self._hardware_controller.set_led_channel_select(3, status)', - self._LED_SWITCH_CHANNEL_SELECT + 4: 'self._hardware_controller.set_led_channel_select(4, status)', - self._LED_SWITCH_CHANNEL_SELECT + 5: 'self._hardware_controller.set_led_channel_select(5, status)', - self._LED_SWITCH_CHANNEL_SELECT + 6: 'self._hardware_controller.set_led_channel_select(6, status)', - self._LED_SWITCH_CHANNEL_SELECT + 7: 'self._hardware_controller.set_led_channel_select(7, status)', - self._LED_SWITCH_CHANNEL_VSELECT: 'self._hardware_controller.set_led_channel_vselect(0, status)', - self._LED_SWITCH_CHANNEL_VSELECT + 1: 'self._hardware_controller.set_led_channel_vselect(1, status)', - self._LED_SWITCH_CHANNEL_VSELECT + 2: 'self._hardware_controller.set_led_channel_vselect(2, status)', - self._LED_SWITCH_CHANNEL_VSELECT + 3: 'self._hardware_controller.set_led_channel_vselect(3, status)', - self._LED_SWITCH_CHANNEL_VSELECT + 4: 'self._hardware_controller.set_led_channel_vselect(4, status)', - self._LED_SWITCH_CHANNEL_VSELECT + 5: 'self._hardware_controller.set_led_channel_vselect(5, status)', - self._LED_SWITCH_CHANNEL_VSELECT + 6: 'self._hardware_controller.set_led_channel_vselect(6, status)', - self._LED_SWITCH_CHANNEL_VSELECT + 7: 'self._hardware_controller.set_led_channel_vselect(7, status)', - self._LED_SWITCH_ASSIGNMENT_TRACK: 'self._hardware_controller.set_led_assignment_track(status)', - self._LED_SWITCH_ASSIGNMENT_SEND: 'self._hardware_controller.set_led_assignment_send(status)', + {'method': 'set_led_channel_record_ready', 'params': f'7, {status}'}, + self._LED_SWITCH_CHANNEL_SOLO: {'method': 'set_led_channel_solo', 'params': f'0, {status}'}, + self._LED_SWITCH_CHANNEL_SOLO + 1: {'method': 'set_led_channel_solo', 'params': f'1, {status}'}, + self._LED_SWITCH_CHANNEL_SOLO + 2: {'method': 'set_led_channel_solo', 'params': f'2, {status}'}, + self._LED_SWITCH_CHANNEL_SOLO + 3: {'method': 'set_led_channel_solo', 'params': f'3, {status}'}, + self._LED_SWITCH_CHANNEL_SOLO + 4: {'method': 'set_led_channel_solo', 'params': f'4, {status}'}, + self._LED_SWITCH_CHANNEL_SOLO + 5: {'method': 'set_led_channel_solo', 'params': f'5, {status}'}, + self._LED_SWITCH_CHANNEL_SOLO + 6: {'method': 'set_led_channel_solo', 'params': f'6, {status}'}, + self._LED_SWITCH_CHANNEL_SOLO + 7: {'method': 'set_led_channel_solo', 'params': f'7, {status}'}, + self._LED_SWITCH_CHANNEL_MUTE: {'method': 'set_led_channel_mute', 'params': f'0, {status}'}, + self._LED_SWITCH_CHANNEL_MUTE + 1: {'method': 'set_led_channel_mute', 'params': f'1, {status}'}, + self._LED_SWITCH_CHANNEL_MUTE + 2: {'method': 'set_led_channel_mute', 'params': f'2, {status}'}, + self._LED_SWITCH_CHANNEL_MUTE + 3: {'method': 'set_led_channel_mute', 'params': f'3, {status}'}, + self._LED_SWITCH_CHANNEL_MUTE + 4: {'method': 'set_led_channel_mute', 'params': f'4, {status}'}, + self._LED_SWITCH_CHANNEL_MUTE + 5: {'method': 'set_led_channel_mute', 'params': f'5, {status}'}, + self._LED_SWITCH_CHANNEL_MUTE + 6: {'method': 'set_led_channel_mute', 'params': f'6, {status}'}, + self._LED_SWITCH_CHANNEL_MUTE + 7: {'method': 'set_led_channel_mute', 'params': f'7, {status}'}, + self._LED_SWITCH_CHANNEL_SELECT: {'method': 'set_led_channel_select', 'params': f'0, {status}'}, + self._LED_SWITCH_CHANNEL_SELECT + 1: {'method': 'set_led_channel_select', 'params': f'1, {status}'}, + self._LED_SWITCH_CHANNEL_SELECT + 2: {'method': 'set_led_channel_select', 'params': f'2, {status}'}, + self._LED_SWITCH_CHANNEL_SELECT + 3: {'method': 'set_led_channel_select', 'params': f'3, {status}'}, + self._LED_SWITCH_CHANNEL_SELECT + 4: {'method': 'set_led_channel_select', 'params': f'4, {status}'}, + self._LED_SWITCH_CHANNEL_SELECT + 5: {'method': 'set_led_channel_select', 'params': f'5, {status}'}, + self._LED_SWITCH_CHANNEL_SELECT + 6: {'method': 'set_led_channel_select', 'params': f'6, {status}'}, + self._LED_SWITCH_CHANNEL_SELECT + 7: {'method': 'set_led_channel_select', 'params': f'7, {status}'}, + self._LED_SWITCH_CHANNEL_VSELECT: {'method': 'set_led_channel_vselect', 'params': f'0, {status}'}, + self._LED_SWITCH_CHANNEL_VSELECT + 1: {'method': 'set_led_channel_vselect', 'params': f'1, {status}'}, + self._LED_SWITCH_CHANNEL_VSELECT + 2: {'method': 'set_led_channel_vselect', 'params': f'2, {status}'}, + self._LED_SWITCH_CHANNEL_VSELECT + 3: {'method': 'set_led_channel_vselect', 'params': f'3, {status}'}, + self._LED_SWITCH_CHANNEL_VSELECT + 4: {'method': 'set_led_channel_vselect', 'params': f'4, {status}'}, + self._LED_SWITCH_CHANNEL_VSELECT + 5: {'method': 'set_led_channel_vselect', 'params': f'5, {status}'}, + self._LED_SWITCH_CHANNEL_VSELECT + 6: {'method': 'set_led_channel_vselect', 'params': f'6, {status}'}, + self._LED_SWITCH_CHANNEL_VSELECT + 7: {'method': 'set_led_channel_vselect', 'params': f'7, {status}'}, + self._LED_SWITCH_ASSIGNMENT_TRACK: {'method': 'set_led_assignment_track', 'params': f'{status}'}, + self._LED_SWITCH_ASSIGNMENT_SEND: {'method': 'set_led_assignment_send', 'params': f'{status}'}, self._LED_SWITCH_ASSIGNMENT_PAN_SURROUND: - 'self._hardware_controller.set_led_assignment_pan_surround(status)', - self._LED_SWITCH_ASSIGNMENT_PLUG_IN: 'self._hardware_controller.set_led_assignment_plug_in(status)', - self._LED_SWITCH_ASSIGNMENT_EQ: 'self._hardware_controller.set_led_assignment_eq(status)', - self._LED_SWITCH_ASSIGNMENT_INSTRUMENT: 'self._hardware_controller.set_led_assignment_instrument(status)', - self._LED_SWITCH_FLIP: 'self._hardware_controller.set_led_flip(status)', - self._LED_SWITCH_GLOBAL_VIEW: 'self._hardware_controller.set_led_global_view(status)', - self._LED_SWITCH_AUTOMATION_READ_OFF: 'self._hardware_controller.set_led_automation_read_off(status)', - self._LED_SWITCH_AUTOMATION_WRITE: 'self._hardware_controller.set_led_automation_write(status)', - self._LED_SWITCH_AUTOMATION_TRIM: 'self._hardware_controller.set_led_automation_trim(status)', - self._LED_SWITCH_AUTOMATION_TOUCH: 'self._hardware_controller.set_led_automation_touch(status)', - self._LED_SWITCH_AUTOMATION_LATCH: 'self._hardware_controller.set_led_automation_latch(status)', - self._LED_SWITCH_GROUP: 'self._hardware_controller.set_led_group(status)', - self._LED_SWITCH_UTILITIES_SAVE: 'self._hardware_controller.set_led_utilities_save(status)', - self._LED_SWITCH_UTILITIES_UNDO: 'self._hardware_controller.set_led_utilities_undo(status)', - self._LED_SWITCH_MARKER: 'self._hardware_controller.set_led_marker(status)', - self._LED_SWITCH_NUDGE: 'self._hardware_controller.set_led_nudge(status)', - self._LED_SWITCH_CYCLE: 'self._hardware_controller.set_led_cycle(status)', - self._LED_SWITCH_DROP: 'self._hardware_controller.set_led_drop(status)', - self._LED_SWITCH_REPLACE: 'self._hardware_controller.set_led_replace(status)', - self._LED_SWITCH_CLICK: 'self._hardware_controller.set_led_click(status)', - self._LED_SWITCH_SOLO: 'self._hardware_controller.set_led_solo(status)', - self._LED_SWITCH_REWIND: 'self._hardware_controller.set_led_rewind(status)', - self._LED_SWITCH_FAST_FORWARD: 'self._hardware_controller.set_led_fast_forward(status)', - self._LED_SWITCH_STOP: 'self._hardware_controller.set_led_stop(status)', - self._LED_SWITCH_PLAY: 'self._hardware_controller.set_led_play(status)', - self._LED_SWITCH_RECORD: 'self._hardware_controller.set_led_record(status)', - self._LED_SWITCH_ZOOM: 'self._hardware_controller.set_led_zoom(status)', - self._LED_SWITCH_SCRUB: 'self._hardware_controller.set_led_scrub(status)', - self._LED_SMPTE: 'self._hardware_controller.set_led_smpte(status)', - self._LED_BEATS: 'self._hardware_controller.set_led_beats(status)', - self._LED_RUDE_SOLO: 'self._hardware_controller.set_led_rude_solo(status)', - self._LED_RELAY_CLICK: 'self._hardware_controller.set_led_relay_click(status)' + {'method': 'set_led_assignment_pan_surround', 'params': f'{status}'}, + self._LED_SWITCH_ASSIGNMENT_PLUG_IN: {'method': 'set_led_assignment_plug_in', 'params': f'{status}'}, + self._LED_SWITCH_ASSIGNMENT_EQ: {'method': 'set_led_assignment_eq', 'params': f'{status}'}, + self._LED_SWITCH_ASSIGNMENT_INSTRUMENT: {'method': 'set_led_assignment_instrument', 'params': f'{status}'}, + self._LED_SWITCH_FLIP: {'method': 'set_led_flip', 'params': f'{status}'}, + self._LED_SWITCH_GLOBAL_VIEW: {'method': 'set_led_global_view', 'params': f'{status}'}, + self._LED_SWITCH_AUTOMATION_READ_OFF: {'method': 'set_led_automation_read_off', 'params': f'{status}'}, + self._LED_SWITCH_AUTOMATION_WRITE: {'method': 'set_led_automation_write', 'params': f'{status}'}, + self._LED_SWITCH_AUTOMATION_TRIM: {'method': 'set_led_automation_trim', 'params': f'{status}'}, + self._LED_SWITCH_AUTOMATION_TOUCH: {'method': 'set_led_automation_touch', 'params': f'{status}'}, + self._LED_SWITCH_AUTOMATION_LATCH: {'method': 'set_led_automation_latch', 'params': f'{status}'}, + self._LED_SWITCH_GROUP: {'method': 'set_led_group', 'params': f'{status}'}, + self._LED_SWITCH_UTILITIES_SAVE: {'method': 'set_led_utilities_save', 'params': f'{status}'}, + self._LED_SWITCH_UTILITIES_UNDO: {'method': 'set_led_utilities_undo', 'params': f'{status}'}, + self._LED_SWITCH_MARKER: {'method': 'set_led_marker', 'params': f'{status}'}, + self._LED_SWITCH_NUDGE: {'method': 'set_led_nudge', 'params': f'{status}'}, + self._LED_SWITCH_CYCLE: {'method': 'set_led_cycle', 'params': f'{status}'}, + self._LED_SWITCH_DROP: {'method': 'set_led_drop', 'params': f'{status}'}, + self._LED_SWITCH_REPLACE: {'method': 'set_led_replace', 'params': f'{status}'}, + self._LED_SWITCH_CLICK: {'method': 'set_led_click', 'params': f'{status}'}, + self._LED_SWITCH_SOLO: {'method': 'set_led_solo', 'params': f'{status}'}, + self._LED_SWITCH_REWIND: {'method': 'set_led_rewind', 'params': f'{status}'}, + self._LED_SWITCH_FAST_FORWARD: {'method': 'set_led_fast_forward', 'params': f'{status}'}, + self._LED_SWITCH_STOP: {'method': 'set_led_stop', 'params': f'{status}'}, + self._LED_SWITCH_PLAY: {'method': 'set_led_play', 'params': f'{status}'}, + self._LED_SWITCH_RECORD: {'method': 'set_led_record', 'params': f'{status}'}, + self._LED_SWITCH_ZOOM: {'method': 'set_led_zoom', 'params': f'{status}'}, + self._LED_SWITCH_SCRUB: {'method': 'set_led_scrub', 'params': f'{status}'}, + self._LED_SMPTE: {'method': 'set_led_smpte', 'params': f'{status}'}, + self._LED_BEATS: {'method': 'set_led_beats', 'params': f'{status}'}, + self._LED_RUDE_SOLO: {'method': 'set_led_rude_solo', 'params': f'{status}'}, + self._LED_RELAY_CLICK: {'method': 'set_led_relay_click', 'params': f'{status}'} } if led_id in selector: - eval(selector[led_id]) + led_method = getattr(self._hardware_controller, selector[led_id]['method']) + led_params = tuple(map(int, selector[led_id]['params'].split(', '))) + led_method(*led_params) else: led_status = 'off' if status == 1: @@ -967,7 +969,7 @@ def _set_led(self, led_id, status): elif status == 2: led_status = 'flashing' - self._log('LED 0x%02X NOT implemented (%s).' % (led_id, led_status)) + self._log(f'LED 0x{led_id:02X} NOT implemented ({led_status}).') def faders_to_minimum(self): if self._hardware_controller: diff --git a/python_mcu/PythonMcu/McuInterconnector/McuInterconnector.py b/python_mcu/PythonMcu/McuInterconnector/McuInterconnector.py index 555c042..194a493 100644 --- a/python_mcu/PythonMcu/McuInterconnector/McuInterconnector.py +++ b/python_mcu/PythonMcu/McuInterconnector/McuInterconnector.py @@ -24,17 +24,10 @@ """ -import sys +import importlib -if __name__ == "__main__": - # allow "PythonMcu" package imports when executing this module - sys.path.append('../../') - -from PythonMcu.MackieControl.MackieHostControl import MackieHostControl -from PythonMcu.Tools.ApplicationConfiguration import ApplicationConfiguration - -# noinspection PyUnresolvedReferences -from PythonMcu.Hardware import * +from ..MackieControl.MackieHostControl import MackieHostControl +from ..Tools.ApplicationConfiguration import ApplicationConfiguration class McuInterconnector: @@ -45,22 +38,6 @@ class McuInterconnector: } _MCU_COMMANDS = [ - 'function_channel_1', - 'function_channel_2', - 'function_channel_3', - 'function_channel_4', - 'function_channel_5', - 'function_channel_6', - 'function_channel_7', - 'function_channel_8', - 'mute_channel_1', - 'mute_channel_2', - 'mute_channel_3', - 'mute_channel_4', - 'mute_channel_5', - 'mute_channel_6', - 'mute_channel_7', - 'mute_channel_8', 'record_ready_channel_1', 'record_ready_channel_2', 'record_ready_channel_3', @@ -69,14 +46,7 @@ class McuInterconnector: 'record_ready_channel_6', 'record_ready_channel_7', 'record_ready_channel_8', - 'select_channel_1', - 'select_channel_2', - 'select_channel_3', - 'select_channel_4', - 'select_channel_5', - 'select_channel_6', - 'select_channel_7', - 'select_channel_8', + 'solo_channel_1', 'solo_channel_2', 'solo_channel_3', @@ -85,6 +55,25 @@ class McuInterconnector: 'solo_channel_6', 'solo_channel_7', 'solo_channel_8', + + 'mute_channel_1', + 'mute_channel_2', + 'mute_channel_3', + 'mute_channel_4', + 'mute_channel_5', + 'mute_channel_6', + 'mute_channel_7', + 'mute_channel_8', + + 'select_channel_1', + 'select_channel_2', + 'select_channel_3', + 'select_channel_4', + 'select_channel_5', + 'select_channel_6', + 'select_channel_7', + 'select_channel_8', + 'vselect_channel_1', 'vselect_channel_2', 'vselect_channel_3', @@ -94,66 +83,99 @@ class McuInterconnector: 'vselect_channel_7', 'vselect_channel_8', - 'assignment_eq', - 'assignment_instrument', + 'assignment_track', + 'assignment_send', 'assignment_pan_surround', 'assignment_plug_in', - 'assignment_send', - 'assignment_track', - 'automation_latch', - 'automation_read_off', - 'automation_touch', - 'automation_trim', - 'automation_write', - 'beats', - 'click', - 'command_alt', - 'control', - 'cursor_down', - 'cursor_left', - 'cursor_right', - 'cursor_up', - 'cycle', - 'drop', + 'assignment_eq', + 'assignment_instrument', + 'fader_banks_bank_left', 'fader_banks_bank_right', 'fader_banks_channel_left', 'fader_banks_channel_right', - 'fast_forward', + 'flip', 'global_view', - 'global_view_audio_instruments', + + 'name_value', + 'smpte_beats', + + 'function_channel_1', + 'function_channel_2', + 'function_channel_3', + 'function_channel_4', + 'function_channel_5', + 'function_channel_6', + 'function_channel_7', + 'function_channel_8', + + 'global_view_midi_tracks', + 'global_view_inputs', 'global_view_audio_tracks', + 'global_view_audio_instruments', 'global_view_aux', 'global_view_busses', - 'global_view_inputs', - 'global_view_midi_tracks', 'global_view_outputs', 'global_view_user', + + 'shift', + 'option', + 'control', + 'command_alt', + + 'automation_read_off', + 'automation_write', + 'automation_trim', + 'automation_touch', + 'automation_latch', + 'group', + + 'utilities_save', + 'utilities_undo', + 'utilities_cancel', + 'utilities_enter', + 'marker', - 'name_value', 'nudge', - 'option', - 'play', - 'record', - 'relay_click', + 'cycle', + 'drop', 'replace', - 'rewind', - 'rude_solo', - 'scrub', - 'shift', - 'smpte', - 'smpte_beats', + 'click', 'solo', + + 'rewind', + 'fast_forward', 'stop', + 'play', + 'record', + + 'cursor_down', + 'cursor_left', + 'cursor_right', + 'cursor_up', + + 'zoom', + 'scrub', + 'user_switch_1', 'user_switch_2', - 'utilities_cancel', - 'utilities_enter', - 'utilities_save', - 'utilities_undo', - 'zoom', + + 'fader_touch_1', + 'fader_touch_2', + 'fader_touch_3', + 'fader_touch_4', + 'fader_touch_5', + 'fader_touch_6', + 'fader_touch_7', + 'fader_touch_8', + 'fader_touch_master', + + 'smpte', + 'beats', + 'rude_solo', + 'relay_click', ] def __init__(self, parent, mcu_model_id, mcu_connection, mcu_midi_input, mcu_midi_output, hardware_controller_class, @@ -162,12 +184,11 @@ def __init__(self, parent, mcu_model_id, mcu_connection, mcu_midi_input, mcu_mid self._callback_log = callback_log self.parent = parent - eval_controller_init = '%(cc)s.%(cc)s("%(midi_in)s", "%(midi_out)s", callback_log)' % { - 'cc': hardware_controller_class, - 'midi_in': controller_midi_input, - 'midi_out': controller_midi_output - } - self._hardware_controller = eval(eval_controller_init) + # FIXME: factorize into factory method + hw_module = importlib.import_module('.' + hardware_controller_class, package='PythonMcu.Hardware') + hw_class = getattr(hw_module, hardware_controller_class) + + self._hardware_controller = hw_class(controller_midi_input, controller_midi_output, callback_log) # get "Python MCU" version number python_mcu_version = ApplicationConfiguration().get_version(False) @@ -259,10 +280,9 @@ def keypress(self, internal_id, status): return False - @staticmethod - def keypress_unregistered(mcu_command, status): - command = 'self._mackie_host_control.keypress_%s(%d)' % (mcu_command, status) - eval(command) + def keypress_unregistered(self, mcu_command, status): + kp_method = getattr(self._mackie_host_control, f'keypress_{mcu_command}') + kp_method(status) def _set_led(self, mcu_command, status): if self._led__mcu_to_hardware[mcu_command]['value'] != status: @@ -328,23 +348,23 @@ def set_lcd(self, position, hex_codes): def set_led_channel_record_ready(self, channel, status): # channel: 0 - 7 - self._set_led('record_ready_channel_%d' % (channel + 1), status) + self._set_led(f'record_ready_channel_{channel + 1}', status) def set_led_channel_solo(self, channel, status): # channel: 0 - 7 - self._set_led('solo_channel_%d' % (channel + 1), status) + self._set_led(f'solo_channel_{channel + 1}', status) def set_led_channel_mute(self, channel, status): # channel: 0 - 7 - self._set_led('mute_channel_%d' % (channel + 1), status) + self._set_led(f'mute_channel_{channel + 1}', status) def set_led_channel_select(self, channel, status): # channel: 0 - 7 - self._set_led('select_channel_%d' % (channel + 1), status) + self._set_led(f'select_channel_{channel + 1}', status) def set_led_channel_vselect(self, channel, status): # channel: 0 - 7 - self._set_led('vselect_channel_%d' % (channel + 1), status) + self._set_led(f'vselect_channel_{channel + 1}', status) def set_led_assignment_track(self, status): self._set_led('assignment_track', status) diff --git a/python_mcu/PythonMcu/Midi/MidiConnection.py b/python_mcu/PythonMcu/Midi/MidiConnection.py index 42e7bf4..2547575 100644 --- a/python_mcu/PythonMcu/Midi/MidiConnection.py +++ b/python_mcu/PythonMcu/Midi/MidiConnection.py @@ -23,24 +23,25 @@ Thank you for using free software! """ +from binascii import hexlify -import pygame.midi - -pygame.midi.init() +import rtmidi +import rtmidi.midiutil +import rtmidi.midiconstants class MidiConnection: __module__ = __name__ __doc__ = 'MIDI connection handler' - NOTE_OFF_EVENT = 0x80 - NOTE_ON_EVENT = 0x90 - POLYPHONIC_KEY_PRESSURE = 0xA0 - CONTROL_CHANGE = 0xB0 - PROGRAM_CHANGE = 0xC0 - CHANNEL_PRESSURE = 0xD0 - PITCH_WHEEL_CHANGE = 0xE0 - SYSTEM_MESSAGE = 0xF0 + NOTE_OFF_EVENT = rtmidi.midiconstants.NOTE_OFF + NOTE_ON_EVENT = rtmidi.midiconstants.NOTE_ON + POLYPHONIC_KEY_PRESSURE = rtmidi.midiconstants.POLYPHONIC_PRESSURE + CONTROL_CHANGE = rtmidi.midiconstants.CONTROL_CHANGE + PROGRAM_CHANGE = rtmidi.midiconstants.PROGRAM_CHANGE + CHANNEL_PRESSURE = rtmidi.midiconstants.CHANNEL_PRESSURE + PITCH_WHEEL_CHANGE = rtmidi.midiconstants.PITCH_BEND + SYSTEM_MESSAGE = rtmidi.midiconstants.SYSTEM_EXCLUSIVE # --- initialisation --- @@ -54,23 +55,40 @@ def __init__(self, callback_log, callback): self._midi_input = None self._midi_output = None - def connect(self, midi_input_name=None, midi_output_name=None): - self._midi_input_name = midi_input_name - if self._midi_input_name: - self._midi_input = self._init_input(self._midi_input_name) + self._input_buffer = [] - self._midi_output_name = midi_output_name - if self._midi_output_name: - self._midi_output = self._init_output(self._midi_output_name) + def connect(self, midi_input_name=None, midi_output_name=None): + if midi_input_name: + midi_input = self._init_input(midi_input_name) + if midi_input: + midi_in_port, in_name = midi_input + self._midi_input = midi_in_port + self._midi_input_name = in_name + self._midi_input.ignore_types(sysex=False) # Make sure rtmidi doesn't filter out SysEx + else: + raise ValueError(f'MIDI input {midi_input_name} not found') + + if midi_output_name: + midi_output = self._init_output(midi_output_name) + if midi_output: + midi_out_port, out_name = midi_output + self._midi_output = midi_out_port + self._midi_output_name = out_name + else: + raise ValueError(f'MIDI output {midi_output_name} not found') def disconnect(self): if self._midi_input: - self._log('Closing MIDI input "%s"...' % self._midi_input_name) - self._midi_input.close() + self._log(f'Closing MIDI input "{self._midi_input_name}"...') + self._midi_input.close_port() + self._midi_input_name = None + self._midi_input = None if self._midi_output: - self._log('Closing MIDI output "%s"...' % self._midi_output_name) - self._midi_output.close() + self._log(f'Closing MIDI output "{self._midi_output_name}"...') + self._midi_output.close_port() + self._midi_output_name = None + self._midi_output = None def _log(self, message): self._callback_log('[MIDI Connection ] ' + message, True) @@ -79,159 +97,128 @@ def _init_input(self, device_name): if device_name is None: return None - for device_id in range(pygame.midi.get_count()): - device = pygame.midi.get_device_info(device_id) - - # noinspection PyUnresolvedReferences - if device[1].decode('utf-8') == device_name and (device[2] == 1): - self._log('Opening MIDI input "%s"...' % device_name) - return pygame.midi.Input(device_id) + self._log(f'Opening MIDI input "{device_name}"...') + try: + midi_input = rtmidi.midiutil.open_midiinput(device_name, interactive=False, client_name="PythonMCU") + except(rtmidi.InvalidPortError, rtmidi.NoDevicesError, rtmidi.SystemError) as e: + self._log(f'MIDI In \'{device_name}\' not found.\nReason: {e}\n') + return None - self._log('MIDI In \'%s\' not found.\n' % device_name) - return None + return midi_input def _init_output(self, device_name): if device_name is None: return None - for device_id in range(pygame.midi.get_count()): - device = pygame.midi.get_device_info(device_id) - - # noinspection PyUnresolvedReferences - if device[1].decode('utf-8') == device_name and (device[3] == 1): - self._log('Opening MIDI output "%s"...' % device_name) - return pygame.midi.Output(device_id, latency=0) - - self._log('MIDI Out \'%s\' not found.\n' % device_name) - return None - - # --- static methods --- - @staticmethod - def get_midi_inputs(): - midi_inputs = [] - - for dev_id in range(pygame.midi.get_count()): - device = pygame.midi.get_device_info(dev_id) - if device[2] == 1: - # noinspection PyUnresolvedReferences - midi_inputs.append(device[1].decode('utf8')) - - return midi_inputs - - @staticmethod - def get_midi_outputs(): - midi_outputs = [] - - for dev_id in range(pygame.midi.get_count()): - device = pygame.midi.get_device_info(dev_id) - if device[3] == 1: - # noinspection PyUnresolvedReferences - midi_outputs.append(device[1].decode('utf8')) - - return midi_outputs - - @staticmethod - def get_default_midi_input(): - device_id = pygame.midi.get_default_input_id() - - if device_id < 0: - return None - - device = pygame.midi.get_device_info(device_id) - return device[1] - - @staticmethod - def get_default_midi_output(): - device_id = pygame.midi.get_default_output_id() - - if device_id < 0: + self._log(f'Opening MIDI output "{device_name}"...') + try: + midi_output = rtmidi.midiutil.open_midioutput(device_name, interactive=False, client_name="PythonMCU") + except(rtmidi.InvalidPortError, rtmidi.NoDevicesError, rtmidi.SystemError) as e: + self._log(f'MIDI Out \'{device_name}\' not found.\nReason: {e}\n') return None - device = pygame.midi.get_device_info(device_id) - return device[1] + return midi_output # --- MIDI processing --- def buffer_is_empty(self): - return not self._midi_input.poll() + if not self._midi_input: + self._log('MIDI input not connected.') + return False + + if msg := self._midi_input.get_message(): + self._input_buffer.append([msg[0]]) # Ignore timestamp + del msg + + return not self._input_buffer def process_input_buffer(self, use_callback=True): - if not self._midi_output: - self._log('MIDI output not connected.') + if not self._midi_input: + self._log('MIDI input not connected.') return - while self._midi_input.poll(): - (status, message) = self._receive_message() + while msg := self._midi_input.get_message(): + self._input_buffer.append([msg[0]]) # Ignore timestamp + del msg - if use_callback: - self._callback(status, message) + if self._input_buffer: + for message in self._input_buffer.pop(0): + (status, message) = self._receive_message(message) - def _receive_message(self): - message = self._midi_input.read(1)[0][0] - status_byte = message[0] & 0xF0 + # FIXME: Factorize and only display in DEBUG mode + output = f'status {status:02X}: ' + for byte in message: + output += f'{byte:02X} ' + self._log('Raw message received: ' + output.strip()) - if message[0] == 0xF0: - while 0xF7 not in message: - message.extend(self._midi_input.read(1)[0][0]) - while message[-1] != 0xF7: - del message[-1] + if use_callback: + self._callback(status, message) - status = None - if status_byte == self.NOTE_OFF_EVENT: + def _receive_message(self, message): + status_byte = message[0] & 0xF0 + + status = 0x00 + if status_byte == rtmidi.midiconstants.NOTE_OFF: status = self.NOTE_OFF_EVENT - del message[3] - elif status_byte == self.NOTE_ON_EVENT: + elif status_byte == rtmidi.midiconstants.NOTE_ON: status = self.NOTE_ON_EVENT - del message[3] - elif status_byte == self.POLYPHONIC_KEY_PRESSURE: + elif status_byte == rtmidi.midiconstants.POLYPHONIC_PRESSURE: status = self.POLYPHONIC_KEY_PRESSURE - del message[3] - elif status_byte == self.CONTROL_CHANGE: + elif status_byte == rtmidi.midiconstants.CONTROL_CHANGE: status = self.CONTROL_CHANGE - del message[3] - elif status_byte == self.PROGRAM_CHANGE: + elif status_byte == rtmidi.midiconstants.PROGRAM_CHANGE: status = self.PROGRAM_CHANGE - del message[2:3] - elif status_byte == self.CHANNEL_PRESSURE: + elif status_byte == rtmidi.midiconstants.CHANNEL_PRESSURE: status = self.CHANNEL_PRESSURE - del message[2:3] - elif status_byte == self.PITCH_WHEEL_CHANGE: + elif status_byte == rtmidi.midiconstants.PITCH_BEND: status = self.PITCH_WHEEL_CHANGE - del message[3] - elif status_byte == self.SYSTEM_MESSAGE: + elif status_byte == rtmidi.midiconstants.SYSTEM_EXCLUSIVE: status = self.SYSTEM_MESSAGE return status, message + def _raw_send(self, message): + + # FIXME: Factorize and only display in DEBUG mode + output = '' + for byte in message: + output += f'{byte:02X} ' + self._log('Raw message sent: ' + output.strip()) + + self._midi_output.send_message(message) + def send(self, status, data_1, data_2): if not self._midi_output: self._log('MIDI output not connected.') return - - self._midi_output.write_short(status, data_1, data_2) + msg = [status, data_1, data_2] + self._raw_send(msg) def send_note_on(self, key, velocity): if not self._midi_output: self._log('MIDI output not connected.') return - # self._log('%02X %02X %02X' % (self.NOTE_ON_EVENT, key, velocity)) - self._midi_output.write_short(self.NOTE_ON_EVENT, key, velocity) +# self._log(f'{self.NOTE_ON_EVENT:02X} {key:02X} {velocity:02X}') + msg = [self.NOTE_ON_EVENT, key, velocity] + self._raw_send(msg) def send_note_off(self, key, velocity): if not self._midi_output: self._log('MIDI output not connected.') return - # self._log('%02X %02X %02X' % (self.NOTE_OFF_EVENT, key, velocity)) - self._midi_output.write_short(self.NOTE_OFF_EVENT, key, velocity) +# self._log(f'{self.NOTE_OFF_EVENT:02X} {key:02X} {velocity:02X}') + msg = [self.NOTE_OFF_EVENT, key, velocity] + self._raw_send(msg) def send_control_change(self, channel, cc_number, cc_value): if not self._midi_output: self._log('MIDI output not connected.') return - # self._log('%02X %02X %02X' % (self.CONTROL_CHANGE + channel, cc_number, cc_value)) - self._midi_output.write_short(self.CONTROL_CHANGE + channel, cc_number, cc_value) +# self._log(f'{self.CONTROL_CHANGE + channel:02X} {cc_number:02X} {cc_value:02X}') + msg = [self.CONTROL_CHANGE + channel, cc_number, cc_value] + self._raw_send(msg) def send_pitch_wheel_change(self, channel, pitch): if not self._midi_output: @@ -240,16 +227,18 @@ def send_pitch_wheel_change(self, channel, pitch): pitch_high = pitch >> 7 pitch_low = pitch & 0x7F - # self._log('%02X %02X %02X' % (self.PITCH_WHEEL_CHANGE + channel, pitch_low, pitch_high)) - self._midi_output.write_short(self.PITCH_WHEEL_CHANGE + channel, pitch_low, pitch_high) +# self._log(f'{self.PITCH_WHEEL_CHANGE + channel:02X} {pitch_low:02X} {pitch_high:02X}') + msg = [self.PITCH_WHEEL_CHANGE + channel, pitch_low, pitch_high] + self._raw_send(msg) def send_pitch_wheel_change_7bit(self, channel, pitch): if not self._midi_output: self._log('MIDI output not connected.') return - # self._log('%02X %02X %02X' % (self.PITCH_WHEEL_CHANGE + channel, pitch, pitch)) - self._midi_output.write_short(self.PITCH_WHEEL_CHANGE + channel, pitch, pitch) +# self._log(f'{self.PITCH_WHEEL_CHANGE + channel:02X} {pitch:02X} {pitch:02X}') + msg = [self.PITCH_WHEEL_CHANGE + channel, pitch, pitch] + self._raw_send(msg) def send_sysex(self, header, data): if not self._midi_output: @@ -259,12 +248,14 @@ def send_sysex(self, header, data): assert isinstance(header, list) assert isinstance(data, list) - sysex = [0xF0] + sysex = [rtmidi.midiconstants.SYSTEM_EXCLUSIVE] sysex.extend(header) sysex.extend(data) - sysex.append(0xF7) + sysex.append(rtmidi.midiconstants.END_OF_EXCLUSIVE) + + assert sysex[0] == rtmidi.midiconstants.SYSTEM_EXCLUSIVE and sysex[-1] == rtmidi.midiconstants.END_OF_EXCLUSIVE - self._midi_output.write_sys_ex(0, sysex) + self._raw_send(sysex) if __name__ == "__main__": @@ -274,10 +265,9 @@ def log_callback(message): print(message) def midi_in_callback(status_byte, message): - print('status %02X: ' % status_byte, ) + print(f'status {status_byte:02X}: ', ) for byte in message: - print('%02X' % byte, ) - print() + print(f'{byte:02X}', ) MIDI_INPUT = 'In From MIDI Yoke: 2' MIDI_OUTPUT = 'Out To MIDI Yoke: 1' diff --git a/python_mcu/PythonMcu/Midi/MidiPorts.py b/python_mcu/PythonMcu/Midi/MidiPorts.py new file mode 100644 index 0000000..fb8d5a6 --- /dev/null +++ b/python_mcu/PythonMcu/Midi/MidiPorts.py @@ -0,0 +1,66 @@ +# -*- coding: utf-8 -*- + +""" +PythonMcu +========= +Mackie Host Controller written in Python +Copyright (c) 2021 Raphaël Doursenaud + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +""" +import string + +import rtmidi + + +def _clean_port_names(ports): + """ + Removes port ID numbers from rtmidi’s names to keep them human friendly. + + Note: this may induce name collisions if multiple interfaces with the same + name are available. + """ + clean_ports = [] + for port in ports: + clean_ports.append(port.rstrip(string.digits).rstrip(string.whitespace)) + return sorted(clean_ports) + + +class MidiPorts: + _inputs = rtmidi.MidiIn() + _outputs = rtmidi.MidiOut() + + input_ports = _clean_port_names(_inputs.get_ports()) + output_ports = _clean_port_names(_outputs.get_ports()) + + @staticmethod + def get_midi_inputs(): + return MidiPorts.input_ports + + @staticmethod + def get_midi_outputs(): + return MidiPorts.output_ports + + @staticmethod + def get_default_midi_input(): + return MidiPorts.input_ports[0] + + @staticmethod + def get_default_midi_output(): + return MidiPorts.output_ports[0] + + @staticmethod + def refresh_ports(): + MidiPorts.input_ports = _clean_port_names(MidiPorts._inputs.get_ports()) + MidiPorts.output_ports = _clean_port_names(MidiPorts._outputs.get_ports()) diff --git a/python_mcu/PythonMcu/Tools/AboutDialog.py b/python_mcu/PythonMcu/Tools/AboutDialog.py index 767ff59..49857f9 100644 --- a/python_mcu/PythonMcu/Tools/AboutDialog.py +++ b/python_mcu/PythonMcu/Tools/AboutDialog.py @@ -26,15 +26,11 @@ import sys -if __name__ == "__main__": - # allow "PythonMcu" package imports when executing this module - sys.path.append('../../') +from PySide6.QtCore import Qt +from PySide6.QtGui import QFont, QTextCharFormat, QFontMetrics +from PySide6.QtWidgets import QDialog, QVBoxLayout, QTextBrowser, QHBoxLayout, QLabel, QPushButton, QApplication -from PythonMcu.Tools.ApplicationConfiguration import ApplicationConfiguration - -from PySide2.QtCore import Qt -from PySide2.QtGui import QFont, QTextCharFormat, QFontMetrics -from PySide2.QtWidgets import QDialog, QVBoxLayout, QTextBrowser, QHBoxLayout, QLabel, QPushButton, QApplication +from .ApplicationConfiguration import ApplicationConfiguration # noinspection PyArgumentList @@ -55,7 +51,8 @@ def __init__(self, parent=None): char_format = QTextCharFormat() char_format.setFontFamily(font.defaultFamily()) - text_width = QFontMetrics(char_format.font()).width('*') * 83 + #text_width = QFontMetrics(char_format.font()).width('*') * 83 + text_width = QFontMetrics(char_format.font()).horizontalAdvance('*' * 83) text_height = QFontMetrics(char_format.font()).height() * 40 self._edit_license = QTextBrowser() diff --git a/python_mcu/PythonMcu/Tools/ApplicationAbout.py b/python_mcu/PythonMcu/Tools/ApplicationAbout.py index 65c00e9..76d9341 100644 --- a/python_mcu/PythonMcu/Tools/ApplicationAbout.py +++ b/python_mcu/PythonMcu/Tools/ApplicationAbout.py @@ -1504,9 +1504,9 @@ def __repr__(self): if setting in ('license_plain', 'license_html'): short_setting = '\n'.join(self._about[setting].split('\n')[:5]) short_setting += '\n[...]' - output += '[%s]\n%s\n\n' % (setting, short_setting) + output += f'[{setting}]\n{short_setting}\n\n' else: - output += '[%s]\n%s\n\n' % (setting, self._about[setting]) + output += f'[{setting}]\n{self._about[setting]}\n\n' output = output.strip('\n') # dump the whole thing @@ -1538,10 +1538,7 @@ def get_copyrights(self): Formatted string containing application copyrights """ - return '(c) %(copyright_years)s %(authors)s' % { - 'copyright_years': self.get('copyright_years'), - 'authors': self.get('authors') - } + return f'(c) {self.get("copyright_years")} {self.get("authors")}' def get_license(self, selection): """Return application license or its terms as string. @@ -1560,7 +1557,7 @@ def get_license(self, selection): """ if selection in ('selected', 'name', 'short', 'plain', 'html'): - return self.get('license_%s' % selection) + return self.get(f'license_{selection}') return None @@ -1577,10 +1574,7 @@ def get_version(self, long): """ if long: - return '%(application)s %(version)s' % { - 'application': self.get('application'), - 'version': self.get('version') - } + return f'{self.get("application")} {self.get("version")}' return self.get('version') @@ -1616,17 +1610,14 @@ def get_full_description(self, text_format='plain'): """ if text_format == 'html': - output = '

%s

%s
%s

' % ( - self.get_version(True), - self.get_copyrights(), - self.get_description(False) - ) + output = f'

{self.get_version(True)}

' + output += f'

{self.get_copyrights()}
{self.get_description(False)}

' - output += '

License

%s
' % self.get_license('short') + output += f'

License

{self.get_license("short")}
' contributors = self.get('contributors') if contributors: - output += '

Contributors

%s

' % contributors + output += f'

Contributors

{contributors}

' return output diff --git a/python_mcu/PythonMcu/Tools/ApplicationConfiguration.py b/python_mcu/PythonMcu/Tools/ApplicationConfiguration.py index 234d62f..d10fe4c 100644 --- a/python_mcu/PythonMcu/Tools/ApplicationConfiguration.py +++ b/python_mcu/PythonMcu/Tools/ApplicationConfiguration.py @@ -27,7 +27,7 @@ import configparser import os -from PythonMcu.Tools import ApplicationAbout +from .ApplicationAbout import ApplicationAbout class SortedDict(dict): @@ -81,7 +81,7 @@ def __init__(self): """ # initialise application information - self._about = ApplicationAbout.ApplicationAbout() + self._about = ApplicationAbout() # ascertain compatibility with the class "ApplicationAbout" assert self.get_application_information('about_class_incarnation') == 3 @@ -112,10 +112,10 @@ def __repr__(self): output += '\n\n\nConfiguration file\n==================' # append sorted sections for section in self.get_sections(): - output += '\n[%s]\n' % section + output += f'\n{section}\n' # append sorted options for item in self.get_items(section): - output += '%s: %s\n' % (item[0], item[1]) + output += f'{item[0]}: {item[1]}\n' # dump the whole thing return output.strip('\n') diff --git a/python_mcu/__init__.py b/python_mcu/__init__.py new file mode 100644 index 0000000..6e59cc5 --- /dev/null +++ b/python_mcu/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- + +""" +PythonMcu +========= +Mackie Host Controller written in Python +Copyright (c) 2011 Martin Zuther (http://www.mzuther.de/) +Copyright (c) 2021 Raphaël Doursenaud + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +""" diff --git a/python_mcu/python_mcu.py b/python_mcu/python_mcu.py index fc4b567..dee6506 100644 --- a/python_mcu/python_mcu.py +++ b/python_mcu/python_mcu.py @@ -24,27 +24,27 @@ Thank you for using free software! """ - +import importlib import platform import sys -import PySide2 -import pygame.version -from PySide2.QtCore import QTimer, Qt -from PySide2.QtGui import QFont, QFontMetrics, QTextCharFormat, QTextCursor -from PySide2.QtWidgets import QFrame, QApplication, QPlainTextEdit, QStyle, QHBoxLayout, QVBoxLayout, QGridLayout, \ - QLabel, QComboBox, QPushButton +import PySide6 +import rtmidi.version +from PySide6.QtCore import QTimer, Qt +from PySide6.QtGui import QFont, QFontMetrics, QTextCharFormat, QTextCursor +from PySide6.QtWidgets import QFrame, QApplication, QPlainTextEdit, QStyle, QHBoxLayout, QVBoxLayout, QGridLayout, \ + QLabel, QComboBox, QPushButton, QCheckBox -# noinspection PyUnresolvedReferences -from PythonMcu.Hardware import * from PythonMcu.MackieControl.MackieHostControl import MackieHostControl from PythonMcu.McuInterconnector.McuInterconnector import McuInterconnector -from PythonMcu.Midi.MidiConnection import MidiConnection +from PythonMcu.Midi.MidiPorts import MidiPorts from PythonMcu.Tools.AboutDialog import AboutDialog from PythonMcu.Tools.ApplicationConfiguration import ApplicationConfiguration configuration = ApplicationConfiguration() +DEBUG = True + # noinspection PyArgumentList class PythonMcuApp(QFrame): @@ -87,9 +87,10 @@ def __init__(self, parent=None): self.callback_log('') self.callback_log('Version numbers') self.callback_log('===============') - self.callback_log('Python: %s (%s)' % (platform.python_version(), platform.python_implementation())) - self.callback_log('PySide: %s' % PySide2.__version__) - self.callback_log('pygame: %s' % pygame.version.ver) + self.callback_log('') + self.callback_log(f'Python: {platform.python_version()} ({platform.python_implementation()})') + self.callback_log(f'PySide6: {PySide6.__version__}') + self.callback_log(f'rtmidi: {rtmidi.version.version}') self.callback_log('') self.callback_log('') @@ -114,6 +115,8 @@ def __init__(self, parent=None): 'Novation ZeRO SL MkII', 'Novation ZeRO SL MkII (MIDI)' ] + if DEBUG: + hardware_controllers.append('_Midi Controller Template') self.setWindowTitle(configuration.get_version(True)) @@ -153,14 +156,16 @@ def __init__(self, parent=None): 'Connection:', connection_types ) + # TODO: create automatically and only show name self._combo_mcu_midi_input = self._create_combo_box( self.grid_layout_mcu, self._mcu_midi_input, - 'MIDI In:', MidiConnection.get_midi_inputs() + 'MIDI In:', MidiPorts.get_midi_inputs() ) + # TODO: create automatically and only show name self._combo_mcu_midi_output = self._create_combo_box( self.grid_layout_mcu, self._mcu_midi_output, - 'MIDI Out:', MidiConnection.get_midi_outputs() + 'MIDI Out:', MidiPorts.get_midi_outputs() ) self._combo_hardware_controller = self._create_combo_box( @@ -170,14 +175,18 @@ def __init__(self, parent=None): self._combo_controller_midi_input = self._create_combo_box( self.grid_layout_controller, self._controller_midi_input, - 'MIDI In:', MidiConnection.get_midi_inputs() + 'MIDI In:', MidiPorts.get_midi_inputs() ) - self._combo_controller_midi_output = self._create_combo_box( self.grid_layout_controller, self._controller_midi_output, - 'MIDI Out:', MidiConnection.get_midi_outputs() + 'MIDI Out:', MidiPorts.get_midi_outputs() ) + self.button_controller_midi_refresh = QPushButton('Refresh MIDI ports') + row = self.grid_layout_controller.rowCount() + self.grid_layout_controller.addWidget(self.button_controller_midi_refresh, row, 1) + self.button_controller_midi_refresh.clicked.connect(self.midiports_refresh) + self.grid_layout_controller.addWidget( self._edit_usage_hint, self.grid_layout_controller.rowCount(), 0, 1, 2 @@ -194,9 +203,14 @@ def __init__(self, parent=None): self.button_start_stop.setFocus() self.button_start_stop.clicked.connect(self.interconnector_start_stop) + # TODO: add autostart checkbox and configuration + self.checkbox_autostart = QCheckBox('Autostart') + self.bottom_layout.addWidget(self.checkbox_autostart) + self.button_close = QPushButton('&Close') self.bottom_layout.addWidget(self.button_close) self.button_close.clicked.connect(self.close_application) + self.closeEvent = self.close_event # Hide PySide's non pythonic method name self.button_about = QPushButton('A&bout') self.bottom_layout.addWidget(self.button_about) @@ -297,16 +311,15 @@ def _initialise_hardware_controller(self): self._hardware_controller_class = self._hardware_controller_class.replace('[', '').replace(']', '') self._hardware_controller_class = self._hardware_controller_class.replace('{', '').replace('}', '') - # get hardware controller's preferred MIDI ports - eval_controller_midi_input = '{0!s}.{0!s}.get_preferred_midi_input()'.format(self._hardware_controller_class) - eval_controller_midi_output = '{0!s}.{0!s}.get_preferred_midi_output()'.format(self._hardware_controller_class) + # FIXME: factorize into factory method + module = importlib.import_module('.' + self._hardware_controller_class, package='PythonMcu.Hardware') + hw_class = getattr(module, self._hardware_controller_class) - controller_midi_input_default = eval(eval_controller_midi_input) - controller_midi_output_default = eval(eval_controller_midi_output) + controller_midi_input_default = hw_class.get_preferred_midi_input() + controller_midi_output_default = hw_class.get_preferred_midi_output() # show controller's usage hint - usage_hint = '{0!s}.{0!s}.get_usage_hint()'.format(self._hardware_controller_class) - self._edit_usage_hint.setPlainText(eval(usage_hint)) + self._edit_usage_hint.setPlainText(hw_class.get_usage_hint()) return controller_midi_input_default, controller_midi_output_default @@ -317,6 +330,15 @@ def callback_log(self, message, repaint=False): print(message) self._edit_logger.appendPlainText(message) + def midiports_refresh(self): + MidiPorts.refresh_ports() + + self._combo_controller_midi_input.clear() + self._combo_controller_midi_input.addItems(MidiPorts.get_midi_inputs()) + + self._combo_controller_midi_output.clear() + self._combo_controller_midi_output.addItems(MidiPorts.get_midi_outputs()) + def combobox_item_selected(self): widget = self.sender() selected_text = widget.currentText() @@ -381,7 +403,7 @@ def combobox_item_selected(self): self._mcu_connection ) else: - self.callback_log('QComboBox not handled ("%s").' % selected_text) + self.callback_log(f'QComboBox not handled ("{selected_text}").') def process_midi_input(self): self._interconnector.process_midi_input() @@ -391,21 +413,21 @@ def display_about(self): def interconnector_start_stop(self): if not self._interconnector: + self.button_start_stop.setText('&Starting...') self._enable_controls(False) - self.button_start_stop.setText('&Stop') self.callback_log('Settings') self.callback_log('========') - self.callback_log('MCU emulation: %s' % self._mcu_emulated_model) - self.callback_log('Connection: %s' % self._mcu_connection) - self.callback_log('MIDI input: %s' % self._mcu_midi_input) - self.callback_log('MIDI output: %s' % self._mcu_midi_output) + self.callback_log(f'MCU emulation: {self._mcu_emulated_model}') + self.callback_log(f'Connection: {self._mcu_connection}') + self.callback_log(f'MIDI input: {self._mcu_midi_input}') + self.callback_log(f'MIDI output: {self._mcu_midi_output}') self.callback_log('') - self.callback_log('Controller: %s' % self._hardware_controller) - self.callback_log('MIDI input: %s' % self._controller_midi_input) - self.callback_log('MIDI output: %s' % self._controller_midi_output) + self.callback_log(f'Controller: {self._hardware_controller}') + self.callback_log(f'MIDI input: {self._controller_midi_input}') + self.callback_log(f'MIDI output: {self._controller_midi_output}') self.callback_log('') - self.callback_log('MIDI latency: %s ms' % self._midi_latency) + self.callback_log(f'MIDI latency: {self._midi_latency} ms') self.callback_log('') self.callback_log('') @@ -430,13 +452,29 @@ def interconnector_start_stop(self): self._controller_midi_output, self.callback_log ) - self._interconnector.connect() + try: + self._interconnector.connect() + except ValueError as e: + self.callback_log(f'Connecting failed with the following error: {e!r}') + self._interconnector.disconnect() + self. _interconnector = None + self._enable_controls(True) + self.button_start_stop.setText('&Start') + return + + # We set the button after making sure we can connect + self._enable_controls(False) + self.button_start_stop.setText('&Stop') self._timer.start() else: + self.button_start_stop.setText('&Stopping') + + self._interconnector_stop() + + # We set the button after making sure we can properly stop self._enable_controls(True) self.button_start_stop.setText('&Start') - self._interconnector_stop() def _interconnector_stop(self): self._timer.stop() @@ -453,7 +491,7 @@ def _interconnector_stop(self): def close_application(self): self.close() - def closeEvent(self, event): + def close_event(self, _): if self._interconnector: self._interconnector_stop() @@ -470,4 +508,4 @@ def closeEvent(self, event): python_mcu.show() # Run the main Qt loop - sys.exit(app.exec_()) + sys.exit(app.exec()) diff --git a/requirements.txt b/requirements.txt index deffc2b..be03b49 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,2 +1,2 @@ -pygame -pyside2 \ No newline at end of file +python-rtmidi +pyside6 \ No newline at end of file diff --git a/test-requirements.txt b/test-requirements.txt new file mode 100644 index 0000000..18f9fdc --- /dev/null +++ b/test-requirements.txt @@ -0,0 +1,3 @@ +-r requirements.txt +pylint +flake8 \ No newline at end of file