diff --git a/.flake8 b/.flake8
deleted file mode 100644
index 333c65b..0000000
--- a/.flake8
+++ /dev/null
@@ -1,6 +0,0 @@
-[flake8]
-select = BLK,C,E,F,I,W
-ignore = E203,W503
-max-line-length = 88
-application-import-names = ezcoo_cli
-import-order-style = google
\ No newline at end of file
diff --git a/.github/actions/build/action.yml b/.github/actions/build/action.yml
new file mode 100644
index 0000000..9e57928
--- /dev/null
+++ b/.github/actions/build/action.yml
@@ -0,0 +1,34 @@
+name: Build distribution
+description: Builds the distribution
+
+runs:
+ using: composite
+ steps:
+ - name: Disable initramfs update
+ shell: bash
+ run: sudo sed -i 's/yes/no/g' /etc/initramfs-tools/update-initramfs.conf
+
+ - name: Disable man-db update
+ shell: bash
+ run: sudo rm -f /var/lib/man-db/auto-update
+
+ - name: Set up Python
+ uses: actions/setup-python@v5
+ with:
+ python-version: "3.x"
+
+ - name: Install uv
+ shell: bash
+ run: python3 -m pip install uv
+
+ - name: Build distribution packages
+ shell: bash
+ run: uv build
+ env:
+ UV_PROJECT_ENVIRONMENT: .venv
+
+ - name: Store distribution packages
+ uses: actions/upload-artifact@v4
+ with:
+ name: python-package-distributions
+ path: dist/
\ No newline at end of file
diff --git a/.github/actions/check/action.yml b/.github/actions/check/action.yml
new file mode 100644
index 0000000..c16f22e
--- /dev/null
+++ b/.github/actions/check/action.yml
@@ -0,0 +1,42 @@
+name: Run linter and tests
+description: Runs the format check, linter, type check and tests
+
+runs:
+ using: composite
+ steps:
+ - name: Disable initramfs update
+ shell: bash
+ run: sudo sed -i 's/yes/no/g' /etc/initramfs-tools/update-initramfs.conf
+
+ - name: Disable man-db update
+ shell: bash
+ run: sudo rm -f /var/lib/man-db/auto-update
+
+ - name: Set up Python
+ uses: actions/setup-python@v5
+ with:
+ python-version: "3.x"
+
+ - name: Install uv
+ shell: bash
+ run: python3 -m pip install uv
+
+ - name: Setup project
+ shell: bash
+ run: uv sync --group dev
+ env:
+ UV_PROJECT_ENVIRONMENT: .venv
+
+ - name: Run ruff check
+ uses: astral-sh/ruff-action@v3
+ with:
+ args: "check"
+
+ - name: Run ruff format check
+ uses: astral-sh/ruff-action@v3
+ with:
+ args: "format --check"
+
+ - name: Run tests
+ shell: bash
+ run: uv run pytest tests/ --replay -v
\ No newline at end of file
diff --git a/.github/workflows/check-and-build.yml b/.github/workflows/check-and-build.yml
new file mode 100644
index 0000000..ba30266
--- /dev/null
+++ b/.github/workflows/check-and-build.yml
@@ -0,0 +1,28 @@
+name: Check and Build
+
+on:
+ workflow_call:
+
+jobs:
+ check:
+ name: Check
+ runs-on: ubuntu-latest
+
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+
+ - name: Check
+ uses: ./.github/actions/check
+
+ build:
+ name: Build
+ runs-on: ubuntu-latest
+ needs: [check]
+
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+
+ - name: Build
+ uses: ./.github/actions/build
\ No newline at end of file
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 0000000..26f4c86
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,9 @@
+name: Continuous Integration
+
+on:
+ pull_request:
+ branches: [main]
+
+jobs:
+ check-and-build:
+ uses: ./.github/workflows/check-and-build.yml
\ No newline at end of file
diff --git a/.gitignore b/.gitignore
index b6e4761..2be6a70 100644
--- a/.gitignore
+++ b/.gitignore
@@ -9,6 +9,7 @@ __pycache__/
# Distribution / packaging
.Python
build/
+!.github/actions/build/
develop-eggs/
dist/
downloads/
@@ -127,3 +128,13 @@ dmypy.json
# Pyre type checker
.pyre/
+
+# Devenv
+.devenv*
+devenv.local.nix
+
+# direnv
+.direnv
+
+# pre-commit
+.pre-commit-config.yaml
diff --git a/.vscode/settings.json b/.vscode/settings.json
index fbccdce..045f34a 100644
--- a/.vscode/settings.json
+++ b/.vscode/settings.json
@@ -1,10 +1,8 @@
{
- "python.analysis.typeCheckingMode": "basic",
- "python.linting.flake8Enabled": true,
- "python.linting.mypyEnabled": true,
- "python.linting.mypyCategorySeverity.note": "Warning",
- "[python]": {
- "editor.formatOnSave": true,
- "editor.defaultFormatter": "ms-python.black-formatter"
- },
-}
\ No newline at end of file
+ "python.analysis.typeCheckingMode": "strict",
+ "[python]": {
+ "editor.formatOnSave": true,
+ "editor.defaultFormatter": "charliermarsh.ruff"
+ }
+}
+
diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
index 0000000..b7f41fb
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,136 @@
+# Changelog
+
+All notable changes to this project will be documented in this file.
+
+The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
+and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+
+## [0.2.0] - 2025-10-17
+
+### Added
+
+- **High-level KVM interface**: New `KVM` class in `kvm.py` providing type-safe, structured interface for library usage
+- **Multi-device addressing**: Support for controlling multiple KVM switches on the same serial bus (addresses 0-99)
+- **Device discovery**: New `discover` command to find all devices on the serial bus with their firmware versions
+- **Comprehensive CLI commands** (replacing simple console.py):
+ - `status`: Show system status with firmware version and address
+ - `help`: Display device help information
+ - `input switch`: Switch inputs with output selection
+ - `output routing`: Query current input-to-output routing
+ - `output stream`: Check output stream status
+ - `edid get/set`: Manage EDID data for inputs
+ - `discover`: Find all devices on the serial bus
+ - Multiple output formats: `--format raw|json|pretty`
+- **Comprehensive test suite**: Full test coverage with pytest
+ - Unit tests for `Device`, `KVM`, and CLI commands
+ - Integration tests for end-to-end workflows
+ - Hardware replay tests using pytest-reserial (no hardware needed for CI)
+ - Test coverage reporting with pytest-cov
+- **Test scripts** for different testing scenarios:
+ - `test-record.sh`: Record serial traffic from real hardware
+ - `test-replay.sh`: Run tests using recorded traffic (CI-friendly)
+ - `test-with-hardware.sh`: Run tests with actual hardware
+- **Enhanced documentation**:
+ - Extensive README with installation, usage examples, and library usage guide
+ - Development setup instructions with uv
+ - Testing documentation
+- **Product documentation**: Added official EZCOO KVM switch manual (PDF) in `docs/`
+- **CI/CD workflows**: GitHub Actions for automated testing and building on pull requests
+ - Composite actions for check and build steps
+ - Reusable workflow for check-and-build
+ - CI workflow triggered on PRs to main
+- **Release documentation**: Complete manual release process guide in `RELEASING.md` including:
+ - Version bumping and changelog updates
+ - GitHub release creation
+ - PyPI publishing
+ - AUR package updates
+
+### Changed
+
+- **BREAKING**: License changed from Apache-2.0 to GPL-3.0-or-later
+- **BREAKING**: Migrated from Poetry to uv for dependency management
+ - Removed `poetry.lock` and `poetry.toml`
+ - Added `uv.lock` and updated `pyproject.toml` to use PEP 621 format
+ - Changed build backend from poetry-core to hatchling
+- **BREAKING**: Migrated from flake8 to ruff for linting and formatting
+ - Removed flake8, flake8-black, flake8-import-order
+ - Added ruff with comprehensive rule configuration
+ - Removed `.flake8` configuration file
+- **BREAKING**: Complete CLI rewrite (`cli.py` replaces `console.py`)
+ - New command structure with subcommands and groups
+ - Added `--address` option for multi-device support
+ - Added `--format` option for output formatting (raw/json/pretty)
+ - Default output format changed from raw device response to human-readable pretty format
+ - Removed direct device command exposure
+ - All commands now use high-level KVM interface
+- **BREAKING**: Enhanced `Device` class with improved error handling
+ - Added `DeviceError` and `DeviceConnectionError` exceptions
+ - Added command validation to prevent injection attacks
+ - Better error messages for connection and communication failures
+ - Configurable baudrate and timeout parameters
+ - Type hints updated to use modern Python 3.10+ syntax (`Self`, `type[]`)
+- **BREAKING**: Response parsing now returns structured `KVMResponse[T]` objects
+ - Generic type parameter ensures type safety
+ - Includes raw command, raw response lines, and parsed response
+ - Enables both programmatic access and raw output
+- **Type safety improvements**:
+ - Added `StreamState` enum for on/off states
+ - Generic `KVMResponse[T]` wrapper for all responses
+ - Proper type hints throughout codebase
+ - Dataclasses for all structured data
+- **Dependencies**:
+ - Removed: `attrs`, `mypy`, `flake8` family
+ - Added: `pytest`, `pytest-cov`, `pytest-reserial`, `ruff`
+ - Updated: `click` to 8.1.3+, `pyserial` to 3.5+
+ - Minimum Python version: 3.10
+
+### Removed
+
+- **console.py**: Replaced by comprehensive `cli.py` with structured commands
+- **Poetry configuration**: Migrated to uv
+- **flake8 configuration**: Migrated to ruff
+- **attrs dependency**: Replaced with standard library dataclasses
+
+### Fixed
+
+- Improved error handling in device communication with specific exception types
+- Better validation of command responses with structured parsing
+- More reliable serial port handling with proper connection error handling
+- Command injection prevention through input validation
+
+### Development
+
+- Added `.vscode/settings.json` with Python and testing configurations
+- Updated `.gitignore` with uv-specific patterns and test artifacts
+- Enhanced `pyproject.toml` with:
+ - Ruff configuration (line length, linting rules)
+ - Pytest configuration (test paths, coverage options)
+ - Coverage configuration (source paths, exclusions)
+ - Dependency groups for dev dependencies
+
+## [0.1.1] - 2024-XX-XX
+
+### Changed
+
+- Bump dependencies
+
+## [0.1.0] - 2024-XX-XX
+
+### Fixed
+
+- Fix wrong baudrate
+
+### Changed
+
+- Move things around and refactoring
+
+## [0.0.1] - 2024-XX-XX
+
+### Added
+
+- Initial PoC implementation
+
+[0.2.0]: https://github.com/Luminger/ezcoo-cli/compare/0.1.1...0.2.0
+[0.1.1]: https://github.com/Luminger/ezcoo-cli/compare/0.1.0...0.1.1
+[0.1.0]: https://github.com/Luminger/ezcoo-cli/compare/0.0.1...0.1.0
+[0.0.1]: https://github.com/Luminger/ezcoo-cli/releases/tag/0.0.1
\ No newline at end of file
diff --git a/LICENSE b/LICENSE
index 1ccfa94..f288702 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,201 +1,674 @@
- Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- "License" shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- "Licensor" shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- "Legal Entity" shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- "control" means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- "You" (or "Your") shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- "Source" form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- "Object" form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- "Work" shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- "Derivative Works" shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- "Contribution" shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, "submitted"
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as "Not a Contribution."
-
- "Contributor" shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a "NOTICE" text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
-
- END OF TERMS AND CONDITIONS
-
- APPENDIX: How to apply the Apache License to your work.
-
- To apply the Apache License to your work, attach the following
- boilerplate notice, with the fields enclosed by brackets "[]"
- replaced with your own identifying information. (Don't include
- the brackets!) The text should be enclosed in the appropriate
- comment syntax for the file format. We also recommend that a
- file or class name and description of purpose be included on the
- same "printed page" as the copyright notice for easier
- identification within third-party archives.
-
- Copyright 2023 Simon Brakhane
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ 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 .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ Copyright (C)
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
diff --git a/README.md b/README.md
index 05410c1..c0e500c 100644
--- a/README.md
+++ b/README.md
@@ -1,2 +1,303 @@
# ezcoo-cli
-A tool to control EZCOO KVM switches via the serial interface
+
+A tool to control EZCOO KVM switches via the serial interface.
+
+**Tested Devices:** EZCOO EZ-SW41HA-KVMU3L with firmware version 2.03 (should be equal to EZ-SW41HA-KVMU3P)
+
+## Installation
+
+### From PyPI
+
+Install using uv:
+
+```bash
+uv add ezcoo-cli
+```
+
+### From AUR (Arch Linux)
+
+Install from the Arch User Repository:
+
+```bash
+yay -S ezcoo-cli
+# or
+paru -S ezcoo-cli
+```
+
+AUR package: https://aur.archlinux.org/packages/ezcoo-cli
+
+### From Source
+
+```bash
+git clone https://github.com/Luminger/ezcoo-cli
+cd ezcoo-cli
+uv sync
+```
+
+## CLI Usage
+
+The CLI provides commands to control your EZCOO KVM switch through a serial connection.
+
+### KVM Switching
+
+**Switch between inputs:**
+```bash
+# Switch to input 2
+ezcoo-cli input switch 2
+
+# Switch to input 3 (output 1 is implicit)
+ezcoo-cli input switch 3 --output 1
+```
+
+**Check current status:**
+```bash
+# View system information
+ezcoo-cli status
+
+# Check which input is currently active
+ezcoo-cli output routing
+
+# Check stream status
+ezcoo-cli output stream
+```
+
+**Get device information:**
+```bash
+# View available commands
+ezcoo-cli help
+
+# Get raw device response (useful for debugging)
+ezcoo-cli help --format raw
+ezcoo-cli status --format raw
+```
+
+### Output Formats
+
+Most query commands support multiple output formats to suit different use cases. You can specify the format using the `--format` (or `-f`) flag:
+
+- **`pretty`** - Human-readable formatted output (default)
+- **`json`** - Machine-readable JSON output for scripting and automation
+- **`raw`** - Raw device response as received from the KVM
+
+For example, to get system status as JSON:
+```bash
+ezcoo-cli status --format json
+# or using the short form
+ezcoo-cli status -f json
+```
+
+> [!NOTE]
+> **Breaking Change in v0.2.0:** Version 0.1.0 always printed raw output. Starting from v0.2.0, commands default to pretty-formatted output. Use `--format raw` to get the previous behavior.
+
+### Device Connection and Addressing
+
+By default, the tool connects to `/dev/ttyUSB0` at address 0 (single device mode). You can specify a different device and address:
+
+```bash
+# Use a different serial device
+ezcoo-cli -d /dev/ttyUSB1 input switch 2
+
+# Communicate with device at address 5
+ezcoo-cli --address 5 status
+
+# Short form
+ezcoo-cli -a 5 status
+```
+
+### Multi-Device Setup
+
+EZCOO devices support address-based multi-device setups where multiple KVM switches can share a single serial connection. Each device needs a unique address (0-99), with 0 being the default for single-device setups.
+
+**Discovering devices on the serial port:**
+```bash
+# Scan all addresses (0-99)
+ezcoo-cli system discover
+
+# Scan specific range
+ezcoo-cli system discover --start 0 --end 10
+```
+
+**Changing device addresses:**
+```bash
+# Change device at address 0 to address 5
+ezcoo-cli system set-address 5
+
+# Change device at address 5 to address 10
+ezcoo-cli --address 5 system set-address 10
+```
+
+> [!WARNING]
+> After changing a device's address, you must use the `--address` option to communicate with it at its new address.
+
+## Library Usage
+
+You can use ezcoo-cli as a library in your Python projects. There are two interfaces available:
+
+### High-Level KVM Interface (Recommended)
+
+The high-level interface provides type-safe, structured access to KVM functionality:
+
+```python
+from pathlib import Path
+from ezcoo_cli.kvm import KVM
+
+# Create KVM instance (default address 0)
+kvm = KVM(Path("/dev/ttyUSB0"))
+
+# Get system information
+status = kvm.get_system_status()
+print(f"Firmware: {status.firmware_version}")
+print(f"Address: {status.system_address}")
+
+# Switch inputs
+kvm.switch_input(2) # Switch to input 2
+
+# Get current routing
+routing = kvm.get_output_routing()
+print(f"Output {routing.output} -> Input {routing.input}")
+
+# Get stream status
+stream = kvm.get_stream_status()
+print(f"Stream enabled: {stream.enabled}")
+
+# Get help information
+help_info = kvm.get_help()
+print(f"Available commands: {help_info.total_commands}")
+
+# Working with devices at specific addresses
+kvm_at_5 = KVM(Path("/dev/ttyUSB0"), address=5)
+status = kvm_at_5.get_system_status()
+
+# Change device address
+kvm.set_device_address(5) # Change from 0 to 5
+kvm.address = 5 # Update instance to use new address
+
+# Access raw response for any command
+print(status.raw_response) # Raw device output
+print(status.command) # Command that was sent
+```
+
+### Low-Level Device Interface
+
+For direct command access, use the Device class:
+
+```python
+from pathlib import Path
+from ezcoo_cli.device import Device
+
+# Basic usage
+with Device(Path("/dev/ttyUSB0")) as device:
+ # Switch input 2 to output 1
+ device.write("EZS OUT1 VS IN2")
+
+ # Get help
+ device.write("EZH")
+ for line in device.readlines():
+ print(line, end="")
+```
+
+## Development
+
+This project uses uv for dependency management and ruff for linting.
+
+```bash
+# Install development dependencies
+uv sync --dev
+
+# Run linting
+uv run ruff check
+
+# Run formatting
+uv run ruff format
+```
+
+## Testing
+
+The test suite uses pytest-reserial to record and replay serial device interactions, allowing tests to run without physical hardware.
+
+### Running Tests
+
+**Replay Mode (no hardware needed):**
+```bash
+./scripts/test-replay.sh
+# or: uv run pytest tests/ --replay -v
+```
+
+**Hardware Mode (with real device):**
+```bash
+./scripts/test-with-hardware.sh
+# or: uv run pytest tests/ -v
+```
+
+**Record Mode (capture new traffic):**
+```bash
+./scripts/test-record.sh
+# or: uv run pytest tests/ --record -v
+```
+
+### Recorded Traffic
+
+pytest-reserial automatically records serial traffic in the `tests/` directory, with one recording file per test module.
+
+**Important:** Commit these recording files to version control so others can run tests without hardware.
+
+### Prerequisites for Recording
+
+- EZCOO device connected to `/dev/ttyUSB0`
+- User has permissions to access serial device:
+ ```bash
+ sudo usermod -a -G dialout $USER
+ # Log out and back in for changes to take effect
+ ```
+
+### Command Support Status
+
+Based on testing with EZCOO EZ-SW41HA-KVMU3L devices running firmware 2.03:
+
+#### Working GET Commands
+
+| Command | Description | Response |
+|---------|-------------|----------|
+| `EZSTA` | Get system status | System info with address, firmware, serial config |
+| `EZH` | Get help | Complete command list |
+| `EZG OUTx VS` | Get output routing | Current input routing |
+| `EZG OUT1 STREAM` | Get stream status | Stream on/off status |
+
+#### Working SET Commands
+
+| Command | Description | Response | CLI Command |
+|---------|-------------|----------|-------------|
+| `EZS OUTx VS INy` | Switch input | No response (SET command) | `ezcoo-cli input switch ` |
+| `EZS ADDR xx` | Set system address | No response (SET command) | `ezcoo-cli system set-address ` |
+
+#### Unsupported/Unimplemented Commands
+
+**Query commands that don't return data (Firmware 2.03):**
+
+These commands have been tested and confirmed to return no data on firmware 2.03. They are not exposed by the project as they don't work on this firmware version.
+
+| Command | Description | Test Result |
+|---------|-------------|-------------|
+| `EZG INx SIG STA` | Get input signal status | No response from device |
+| `EZG INx EDID` | Get EDID information | No response from device |
+| `EZG ADDR` | Get system address | No response from device |
+| `EZG AUTO MODE` | Get auto switch mode status | No response from device |
+| `EZG CAS` | Get cascade mode status | No response from device |
+| `EZG STA` | Get system status (alternative) | No response from device (use `EZSTA` instead) |
+
+**SET commands with unknown/unclear effect (not implemented in this tool):**
+
+These SET commands have been tested and the device accepts them without errors (no response, which is normal for SET commands). However, their actual effect is unclear - either no observable changes occurred or the expected behavior was not seen.
+
+| Command | Description | Test Result | Reason Not Implemented |
+|---------|-------------|-------------|------------------------|
+| `EZS CAS EN/DIS` | Set cascade mode enable/disable | Accepted by device, no observable effect | Effect unclear |
+| `EZS OUTx VIDEOy` | Set output video mode (BYPASS/4K->2K) | Accepted by device, no observable effect | Effect unclear |
+| `EZS INx EDID y` | Set input EDID | Accepted by device, no observable effect | Effect unclear |
+| `EZS RST` | Reset to factory defaults | Accepted by device, but address was NOT reset (still at 01 after reset) | Effect unclear - may not work or may only reset some settings |
+
+## License
+
+This project is licensed under the GNU General Public License v3.0 or later (GPL-3.0-or-later).
+
+See the [LICENSE](LICENSE) file for details.
diff --git a/RELEASING.md b/RELEASING.md
new file mode 100644
index 0000000..efb2a60
--- /dev/null
+++ b/RELEASING.md
@@ -0,0 +1,166 @@
+# Release Process
+
+This document describes the manual process for creating a new release of ezcoo-cli.
+
+## Prerequisites
+
+- Ensure you have the `gh` CLI tool installed and authenticated
+- Ensure you have PyPI credentials configured (via `~/.pypirc` or environment variables)
+- Ensure all tests pass locally: `./scripts/test-replay.sh`
+- Ensure the working directory is clean (no uncommitted changes)
+
+## Release Steps
+
+### 1. Update Version
+
+Edit `pyproject.toml` and update the version number:
+
+```toml
+[project]
+version = "X.Y.Z" # Update this line
+```
+
+### 2. Update Changelog
+
+Create or update `CHANGELOG.md` with the changes in this release:
+
+```markdown
+## [X.Y.Z] - YYYY-MM-DD
+
+### Added
+- New features
+
+### Changed
+- Changes to existing functionality
+
+### Fixed
+- Bug fixes
+```
+
+### 3. Commit Version Bump
+
+```bash
+git add pyproject.toml CHANGELOG.md
+git commit -m "chore: bump version to X.Y.Z"
+git push origin main
+```
+
+### 4. Create Git Tag
+
+```bash
+git tag -a vX.Y.Z -m "Release vX.Y.Z"
+git push origin vX.Y.Z
+```
+
+### 5. Build Distribution Packages
+
+```bash
+uv build
+```
+
+This creates distribution files in the `dist/` directory:
+- `ezcoo_cli-X.Y.Z-py3-none-any.whl`
+- `ezcoo_cli-X.Y.Z.tar.gz`
+
+### 6. Create GitHub Release
+
+```bash
+gh release create vX.Y.Z \
+ --title "vX.Y.Z" \
+ --notes-file CHANGELOG.md \
+ dist/*
+```
+
+Or create the release manually via the GitHub web interface:
+1. Go to https://github.com/YOUR_USERNAME/ezcoo-cli/releases/new
+2. Select the tag `vX.Y.Z`
+3. Set the release title to `vX.Y.Z`
+4. Copy the changelog content into the description
+5. Upload the files from `dist/`
+6. Publish the release
+
+### 7. Publish to PyPI
+
+```bash
+uv publish
+```
+
+### 9. Update AUR Package
+
+The AUR package needs to be updated after the PyPI release:
+
+1. Clone the AUR repository (if not already cloned):
+ ```bash
+ git clone ssh://aur@aur.archlinux.org/ezcoo-cli.git aur-ezcoo-cli
+ cd aur-ezcoo-cli
+ ```
+
+2. Update the `PKGBUILD` file:
+ - Update `pkgver` to the new version (without the 'v' prefix)
+ - Update `pkgrel` to `1` (reset for new version)
+ - Update checksums by running:
+ ```bash
+ updpkgsums
+ ```
+
+3. Update `.SRCINFO`:
+ ```bash
+ makepkg --printsrcinfo > .SRCINFO
+ ```
+
+4. Test the package builds correctly:
+ ```bash
+ makepkg -si
+ ```
+
+5. Commit and push to AUR:
+ ```bash
+ git add PKGBUILD .SRCINFO
+ git commit -m "Update to version X.Y.Z"
+ git push
+ ```
+
+
+### 8. Verify Release
+
+- Check the GitHub release: https://github.com/YOUR_USERNAME/ezcoo-cli/releases
+- Check PyPI: https://pypi.org/project/ezcoo-cli/
+- Check AUR: https://aur.archlinux.org/packages/ezcoo-cli
+- Test installation: `pip install ezcoo-cli==X.Y.Z`
+
+## Troubleshooting
+
+### PyPI Upload Fails
+
+If `uv publish` fails, you may need to configure PyPI credentials:
+
+```bash
+# Using environment variables
+export TWINE_USERNAME=__token__
+export TWINE_PASSWORD=pypi-...
+
+# Or create ~/.pypirc
+[pypi]
+username = __token__
+password = pypi-...
+```
+
+### GitHub Release Fails
+
+Ensure you have the `gh` CLI authenticated:
+
+```bash
+gh auth login
+```
+
+### Version Already Exists
+
+If the version already exists on PyPI, you must bump to a new version. PyPI does not allow re-uploading the same version.
+
+## Post-Release
+
+After a successful release:
+
+1. Announce the release (if applicable)
+2. Update any documentation that references version numbers
+3. Close any related GitHub issues/milestones
\ No newline at end of file
diff --git a/docs/A1MFWJFYg8L.pdf b/docs/A1MFWJFYg8L.pdf
new file mode 100644
index 0000000..a4b9b77
Binary files /dev/null and b/docs/A1MFWJFYg8L.pdf differ
diff --git a/poetry.lock b/poetry.lock
deleted file mode 100644
index f6f84a5..0000000
--- a/poetry.lock
+++ /dev/null
@@ -1,327 +0,0 @@
-# This file is automatically @generated by Poetry 1.8.3 and should not be changed by hand.
-
-[[package]]
-name = "attrs"
-version = "23.2.0"
-description = "Classes Without Boilerplate"
-optional = false
-python-versions = ">=3.7"
-files = [
- {file = "attrs-23.2.0-py3-none-any.whl", hash = "sha256:99b87a485a5820b23b879f04c2305b44b951b502fd64be915879d77a7e8fc6f1"},
- {file = "attrs-23.2.0.tar.gz", hash = "sha256:935dc3b529c262f6cf76e50877d35a4bd3c1de194fd41f47a2b7ae8f19971f30"},
-]
-
-[package.extras]
-cov = ["attrs[tests]", "coverage[toml] (>=5.3)"]
-dev = ["attrs[tests]", "pre-commit"]
-docs = ["furo", "myst-parser", "sphinx", "sphinx-notfound-page", "sphinxcontrib-towncrier", "towncrier", "zope-interface"]
-tests = ["attrs[tests-no-zope]", "zope-interface"]
-tests-mypy = ["mypy (>=1.6)", "pytest-mypy-plugins"]
-tests-no-zope = ["attrs[tests-mypy]", "cloudpickle", "hypothesis", "pympler", "pytest (>=4.3.0)", "pytest-xdist[psutil]"]
-
-[[package]]
-name = "black"
-version = "24.4.2"
-description = "The uncompromising code formatter."
-optional = false
-python-versions = ">=3.8"
-files = [
- {file = "black-24.4.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:dd1b5a14e417189db4c7b64a6540f31730713d173f0b63e55fabd52d61d8fdce"},
- {file = "black-24.4.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:8e537d281831ad0e71007dcdcbe50a71470b978c453fa41ce77186bbe0ed6021"},
- {file = "black-24.4.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:eaea3008c281f1038edb473c1aa8ed8143a5535ff18f978a318f10302b254063"},
- {file = "black-24.4.2-cp310-cp310-win_amd64.whl", hash = "sha256:7768a0dbf16a39aa5e9a3ded568bb545c8c2727396d063bbaf847df05b08cd96"},
- {file = "black-24.4.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:257d724c2c9b1660f353b36c802ccece186a30accc7742c176d29c146df6e474"},
- {file = "black-24.4.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:bdde6f877a18f24844e381d45e9947a49e97933573ac9d4345399be37621e26c"},
- {file = "black-24.4.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e151054aa00bad1f4e1f04919542885f89f5f7d086b8a59e5000e6c616896ffb"},
- {file = "black-24.4.2-cp311-cp311-win_amd64.whl", hash = "sha256:7e122b1c4fb252fd85df3ca93578732b4749d9be076593076ef4d07a0233c3e1"},
- {file = "black-24.4.2-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:accf49e151c8ed2c0cdc528691838afd217c50412534e876a19270fea1e28e2d"},
- {file = "black-24.4.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:88c57dc656038f1ab9f92b3eb5335ee9b021412feaa46330d5eba4e51fe49b04"},
- {file = "black-24.4.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:be8bef99eb46d5021bf053114442914baeb3649a89dc5f3a555c88737e5e98fc"},
- {file = "black-24.4.2-cp312-cp312-win_amd64.whl", hash = "sha256:415e686e87dbbe6f4cd5ef0fbf764af7b89f9057b97c908742b6008cc554b9c0"},
- {file = "black-24.4.2-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:bf10f7310db693bb62692609b397e8d67257c55f949abde4c67f9cc574492cc7"},
- {file = "black-24.4.2-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:98e123f1d5cfd42f886624d84464f7756f60ff6eab89ae845210631714f6db94"},
- {file = "black-24.4.2-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:48a85f2cb5e6799a9ef05347b476cce6c182d6c71ee36925a6c194d074336ef8"},
- {file = "black-24.4.2-cp38-cp38-win_amd64.whl", hash = "sha256:b1530ae42e9d6d5b670a34db49a94115a64596bc77710b1d05e9801e62ca0a7c"},
- {file = "black-24.4.2-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:37aae07b029fa0174d39daf02748b379399b909652a806e5708199bd93899da1"},
- {file = "black-24.4.2-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:da33a1a5e49c4122ccdfd56cd021ff1ebc4a1ec4e2d01594fef9b6f267a9e741"},
- {file = "black-24.4.2-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ef703f83fc32e131e9bcc0a5094cfe85599e7109f896fe8bc96cc402f3eb4b6e"},
- {file = "black-24.4.2-cp39-cp39-win_amd64.whl", hash = "sha256:b9176b9832e84308818a99a561e90aa479e73c523b3f77afd07913380ae2eab7"},
- {file = "black-24.4.2-py3-none-any.whl", hash = "sha256:d36ed1124bb81b32f8614555b34cc4259c3fbc7eec17870e8ff8ded335b58d8c"},
- {file = "black-24.4.2.tar.gz", hash = "sha256:c872b53057f000085da66a19c55d68f6f8ddcac2642392ad3a355878406fbd4d"},
-]
-
-[package.dependencies]
-click = ">=8.0.0"
-mypy-extensions = ">=0.4.3"
-packaging = ">=22.0"
-pathspec = ">=0.9.0"
-platformdirs = ">=2"
-tomli = {version = ">=1.1.0", markers = "python_version < \"3.11\""}
-typing-extensions = {version = ">=4.0.1", markers = "python_version < \"3.11\""}
-
-[package.extras]
-colorama = ["colorama (>=0.4.3)"]
-d = ["aiohttp (>=3.7.4)", "aiohttp (>=3.7.4,!=3.9.0)"]
-jupyter = ["ipython (>=7.8.0)", "tokenize-rt (>=3.2.0)"]
-uvloop = ["uvloop (>=0.15.2)"]
-
-[[package]]
-name = "click"
-version = "8.1.7"
-description = "Composable command line interface toolkit"
-optional = false
-python-versions = ">=3.7"
-files = [
- {file = "click-8.1.7-py3-none-any.whl", hash = "sha256:ae74fb96c20a0277a1d615f1e4d73c8414f5a98db8b799a7931d1582f3390c28"},
- {file = "click-8.1.7.tar.gz", hash = "sha256:ca9853ad459e787e2192211578cc907e7594e294c7ccc834310722b41b9ca6de"},
-]
-
-[package.dependencies]
-colorama = {version = "*", markers = "platform_system == \"Windows\""}
-
-[[package]]
-name = "colorama"
-version = "0.4.6"
-description = "Cross-platform colored terminal text."
-optional = false
-python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*,>=2.7"
-files = [
- {file = "colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6"},
- {file = "colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44"},
-]
-
-[[package]]
-name = "flake8"
-version = "6.1.0"
-description = "the modular source code checker: pep8 pyflakes and co"
-optional = false
-python-versions = ">=3.8.1"
-files = [
- {file = "flake8-6.1.0-py2.py3-none-any.whl", hash = "sha256:ffdfce58ea94c6580c77888a86506937f9a1a227dfcd15f245d694ae20a6b6e5"},
- {file = "flake8-6.1.0.tar.gz", hash = "sha256:d5b3857f07c030bdb5bf41c7f53799571d75c4491748a3adcd47de929e34cd23"},
-]
-
-[package.dependencies]
-mccabe = ">=0.7.0,<0.8.0"
-pycodestyle = ">=2.11.0,<2.12.0"
-pyflakes = ">=3.1.0,<3.2.0"
-
-[[package]]
-name = "flake8-black"
-version = "0.3.6"
-description = "flake8 plugin to call black as a code style validator"
-optional = false
-python-versions = ">=3.7"
-files = [
- {file = "flake8-black-0.3.6.tar.gz", hash = "sha256:0dfbca3274777792a5bcb2af887a4cad72c72d0e86c94e08e3a3de151bb41c34"},
- {file = "flake8_black-0.3.6-py3-none-any.whl", hash = "sha256:fe8ea2eca98d8a504f22040d9117347f6b367458366952862ac3586e7d4eeaca"},
-]
-
-[package.dependencies]
-black = ">=22.1.0"
-flake8 = ">=3"
-tomli = {version = "*", markers = "python_version < \"3.11\""}
-
-[package.extras]
-develop = ["build", "twine"]
-
-[[package]]
-name = "flake8-import-order"
-version = "0.18.2"
-description = "Flake8 and pylama plugin that checks the ordering of import statements."
-optional = false
-python-versions = "*"
-files = [
- {file = "flake8-import-order-0.18.2.tar.gz", hash = "sha256:e23941f892da3e0c09d711babbb0c73bc735242e9b216b726616758a920d900e"},
- {file = "flake8_import_order-0.18.2-py2.py3-none-any.whl", hash = "sha256:82ed59f1083b629b030ee9d3928d9e06b6213eb196fe745b3a7d4af2168130df"},
-]
-
-[package.dependencies]
-pycodestyle = "*"
-setuptools = "*"
-
-[[package]]
-name = "mccabe"
-version = "0.7.0"
-description = "McCabe checker, plugin for flake8"
-optional = false
-python-versions = ">=3.6"
-files = [
- {file = "mccabe-0.7.0-py2.py3-none-any.whl", hash = "sha256:6c2d30ab6be0e4a46919781807b4f0d834ebdd6c6e3dca0bda5a15f863427b6e"},
- {file = "mccabe-0.7.0.tar.gz", hash = "sha256:348e0240c33b60bbdf4e523192ef919f28cb2c3d7d5c7794f74009290f236325"},
-]
-
-[[package]]
-name = "mypy"
-version = "1.10.1"
-description = "Optional static typing for Python"
-optional = false
-python-versions = ">=3.8"
-files = [
- {file = "mypy-1.10.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:e36f229acfe250dc660790840916eb49726c928e8ce10fbdf90715090fe4ae02"},
- {file = "mypy-1.10.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:51a46974340baaa4145363b9e051812a2446cf583dfaeba124af966fa44593f7"},
- {file = "mypy-1.10.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:901c89c2d67bba57aaaca91ccdb659aa3a312de67f23b9dfb059727cce2e2e0a"},
- {file = "mypy-1.10.1-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:0cd62192a4a32b77ceb31272d9e74d23cd88c8060c34d1d3622db3267679a5d9"},
- {file = "mypy-1.10.1-cp310-cp310-win_amd64.whl", hash = "sha256:a2cbc68cb9e943ac0814c13e2452d2046c2f2b23ff0278e26599224cf164e78d"},
- {file = "mypy-1.10.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:bd6f629b67bb43dc0d9211ee98b96d8dabc97b1ad38b9b25f5e4c4d7569a0c6a"},
- {file = "mypy-1.10.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:a1bbb3a6f5ff319d2b9d40b4080d46cd639abe3516d5a62c070cf0114a457d84"},
- {file = "mypy-1.10.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b8edd4e9bbbc9d7b79502eb9592cab808585516ae1bcc1446eb9122656c6066f"},
- {file = "mypy-1.10.1-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:6166a88b15f1759f94a46fa474c7b1b05d134b1b61fca627dd7335454cc9aa6b"},
- {file = "mypy-1.10.1-cp311-cp311-win_amd64.whl", hash = "sha256:5bb9cd11c01c8606a9d0b83ffa91d0b236a0e91bc4126d9ba9ce62906ada868e"},
- {file = "mypy-1.10.1-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:d8681909f7b44d0b7b86e653ca152d6dff0eb5eb41694e163c6092124f8246d7"},
- {file = "mypy-1.10.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:378c03f53f10bbdd55ca94e46ec3ba255279706a6aacaecac52ad248f98205d3"},
- {file = "mypy-1.10.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6bacf8f3a3d7d849f40ca6caea5c055122efe70e81480c8328ad29c55c69e93e"},
- {file = "mypy-1.10.1-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:701b5f71413f1e9855566a34d6e9d12624e9e0a8818a5704d74d6b0402e66c04"},
- {file = "mypy-1.10.1-cp312-cp312-win_amd64.whl", hash = "sha256:3c4c2992f6ea46ff7fce0072642cfb62af7a2484efe69017ed8b095f7b39ef31"},
- {file = "mypy-1.10.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:604282c886497645ffb87b8f35a57ec773a4a2721161e709a4422c1636ddde5c"},
- {file = "mypy-1.10.1-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:37fd87cab83f09842653f08de066ee68f1182b9b5282e4634cdb4b407266bade"},
- {file = "mypy-1.10.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8addf6313777dbb92e9564c5d32ec122bf2c6c39d683ea64de6a1fd98b90fe37"},
- {file = "mypy-1.10.1-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:5cc3ca0a244eb9a5249c7c583ad9a7e881aa5d7b73c35652296ddcdb33b2b9c7"},
- {file = "mypy-1.10.1-cp38-cp38-win_amd64.whl", hash = "sha256:1b3a2ffce52cc4dbaeee4df762f20a2905aa171ef157b82192f2e2f368eec05d"},
- {file = "mypy-1.10.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:fe85ed6836165d52ae8b88f99527d3d1b2362e0cb90b005409b8bed90e9059b3"},
- {file = "mypy-1.10.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:c2ae450d60d7d020d67ab440c6e3fae375809988119817214440033f26ddf7bf"},
- {file = "mypy-1.10.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6be84c06e6abd72f960ba9a71561c14137a583093ffcf9bbfaf5e613d63fa531"},
- {file = "mypy-1.10.1-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:2189ff1e39db399f08205e22a797383613ce1cb0cb3b13d8bcf0170e45b96cc3"},
- {file = "mypy-1.10.1-cp39-cp39-win_amd64.whl", hash = "sha256:97a131ee36ac37ce9581f4220311247ab6cba896b4395b9c87af0675a13a755f"},
- {file = "mypy-1.10.1-py3-none-any.whl", hash = "sha256:71d8ac0b906354ebda8ef1673e5fde785936ac1f29ff6987c7483cfbd5a4235a"},
- {file = "mypy-1.10.1.tar.gz", hash = "sha256:1f8f492d7db9e3593ef42d4f115f04e556130f2819ad33ab84551403e97dd4c0"},
-]
-
-[package.dependencies]
-mypy-extensions = ">=1.0.0"
-tomli = {version = ">=1.1.0", markers = "python_version < \"3.11\""}
-typing-extensions = ">=4.1.0"
-
-[package.extras]
-dmypy = ["psutil (>=4.0)"]
-install-types = ["pip"]
-mypyc = ["setuptools (>=50)"]
-reports = ["lxml"]
-
-[[package]]
-name = "mypy-extensions"
-version = "1.0.0"
-description = "Type system extensions for programs checked with the mypy type checker."
-optional = false
-python-versions = ">=3.5"
-files = [
- {file = "mypy_extensions-1.0.0-py3-none-any.whl", hash = "sha256:4392f6c0eb8a5668a69e23d168ffa70f0be9ccfd32b5cc2d26a34ae5b844552d"},
- {file = "mypy_extensions-1.0.0.tar.gz", hash = "sha256:75dbf8955dc00442a438fc4d0666508a9a97b6bd41aa2f0ffe9d2f2725af0782"},
-]
-
-[[package]]
-name = "packaging"
-version = "24.1"
-description = "Core utilities for Python packages"
-optional = false
-python-versions = ">=3.8"
-files = [
- {file = "packaging-24.1-py3-none-any.whl", hash = "sha256:5b8f2217dbdbd2f7f384c41c628544e6d52f2d0f53c6d0c3ea61aa5d1d7ff124"},
- {file = "packaging-24.1.tar.gz", hash = "sha256:026ed72c8ed3fcce5bf8950572258698927fd1dbda10a5e981cdf0ac37f4f002"},
-]
-
-[[package]]
-name = "pathspec"
-version = "0.12.1"
-description = "Utility library for gitignore style pattern matching of file paths."
-optional = false
-python-versions = ">=3.8"
-files = [
- {file = "pathspec-0.12.1-py3-none-any.whl", hash = "sha256:a0d503e138a4c123b27490a4f7beda6a01c6f288df0e4a8b79c7eb0dc7b4cc08"},
- {file = "pathspec-0.12.1.tar.gz", hash = "sha256:a482d51503a1ab33b1c67a6c3813a26953dbdc71c31dacaef9a838c4e29f5712"},
-]
-
-[[package]]
-name = "platformdirs"
-version = "4.2.2"
-description = "A small Python package for determining appropriate platform-specific dirs, e.g. a `user data dir`."
-optional = false
-python-versions = ">=3.8"
-files = [
- {file = "platformdirs-4.2.2-py3-none-any.whl", hash = "sha256:2d7a1657e36a80ea911db832a8a6ece5ee53d8de21edd5cc5879af6530b1bfee"},
- {file = "platformdirs-4.2.2.tar.gz", hash = "sha256:38b7b51f512eed9e84a22788b4bce1de17c0adb134d6becb09836e37d8654cd3"},
-]
-
-[package.extras]
-docs = ["furo (>=2023.9.10)", "proselint (>=0.13)", "sphinx (>=7.2.6)", "sphinx-autodoc-typehints (>=1.25.2)"]
-test = ["appdirs (==1.4.4)", "covdefaults (>=2.3)", "pytest (>=7.4.3)", "pytest-cov (>=4.1)", "pytest-mock (>=3.12)"]
-type = ["mypy (>=1.8)"]
-
-[[package]]
-name = "pycodestyle"
-version = "2.11.1"
-description = "Python style guide checker"
-optional = false
-python-versions = ">=3.8"
-files = [
- {file = "pycodestyle-2.11.1-py2.py3-none-any.whl", hash = "sha256:44fe31000b2d866f2e41841b18528a505fbd7fef9017b04eff4e2648a0fadc67"},
- {file = "pycodestyle-2.11.1.tar.gz", hash = "sha256:41ba0e7afc9752dfb53ced5489e89f8186be00e599e712660695b7a75ff2663f"},
-]
-
-[[package]]
-name = "pyflakes"
-version = "3.1.0"
-description = "passive checker of Python programs"
-optional = false
-python-versions = ">=3.8"
-files = [
- {file = "pyflakes-3.1.0-py2.py3-none-any.whl", hash = "sha256:4132f6d49cb4dae6819e5379898f2b8cce3c5f23994194c24b77d5da2e36f774"},
- {file = "pyflakes-3.1.0.tar.gz", hash = "sha256:a0aae034c444db0071aa077972ba4768d40c830d9539fd45bf4cd3f8f6992efc"},
-]
-
-[[package]]
-name = "pyserial"
-version = "3.5"
-description = "Python Serial Port Extension"
-optional = false
-python-versions = "*"
-files = [
- {file = "pyserial-3.5-py2.py3-none-any.whl", hash = "sha256:c4451db6ba391ca6ca299fb3ec7bae67a5c55dde170964c7a14ceefec02f2cf0"},
- {file = "pyserial-3.5.tar.gz", hash = "sha256:3c77e014170dfffbd816e6ffc205e9842efb10be9f58ec16d3e8675b4925cddb"},
-]
-
-[package.extras]
-cp2110 = ["hidapi"]
-
-[[package]]
-name = "setuptools"
-version = "71.0.3"
-description = "Easily download, build, install, upgrade, and uninstall Python packages"
-optional = false
-python-versions = ">=3.8"
-files = [
- {file = "setuptools-71.0.3-py3-none-any.whl", hash = "sha256:f501b6e6db709818dc76882582d9c516bf3b67b948864c5fa1d1624c09a49207"},
- {file = "setuptools-71.0.3.tar.gz", hash = "sha256:3d8531791a27056f4a38cd3e54084d8b1c4228ff9cf3f2d7dd075ec99f9fd70d"},
-]
-
-[package.extras]
-core = ["importlib-metadata (>=6)", "importlib-resources (>=5.10.2)", "jaraco.text (>=3.7)", "more-itertools (>=8.8)", "ordered-set (>=3.1.1)", "packaging (>=24)", "platformdirs (>=2.6.2)", "tomli (>=2.0.1)", "wheel (>=0.43.0)"]
-doc = ["furo", "jaraco.packaging (>=9.3)", "jaraco.tidelift (>=1.4)", "pygments-github-lexers (==0.0.5)", "pyproject-hooks (!=1.1)", "rst.linker (>=1.9)", "sphinx (<7.4)", "sphinx (>=3.5)", "sphinx-favicon", "sphinx-inline-tabs", "sphinx-lint", "sphinx-notfound-page (>=1,<2)", "sphinx-reredirects", "sphinxcontrib-towncrier"]
-test = ["build[virtualenv] (>=1.0.3)", "filelock (>=3.4.0)", "importlib-metadata", "ini2toml[lite] (>=0.14)", "jaraco.develop (>=7.21)", "jaraco.envs (>=2.2)", "jaraco.path (>=3.2.0)", "jaraco.test", "mypy (==1.10.0)", "packaging (>=23.2)", "pip (>=19.1)", "pyproject-hooks (!=1.1)", "pytest (>=6,!=8.1.*)", "pytest-checkdocs (>=2.4)", "pytest-cov", "pytest-enabler (>=2.2)", "pytest-home (>=0.5)", "pytest-mypy", "pytest-perf", "pytest-ruff (<0.4)", "pytest-ruff (>=0.2.1)", "pytest-ruff (>=0.3.2)", "pytest-subprocess", "pytest-timeout", "pytest-xdist (>=3)", "tomli", "tomli-w (>=1.0.0)", "virtualenv (>=13.0.0)", "wheel"]
-
-[[package]]
-name = "tomli"
-version = "2.0.1"
-description = "A lil' TOML parser"
-optional = false
-python-versions = ">=3.7"
-files = [
- {file = "tomli-2.0.1-py3-none-any.whl", hash = "sha256:939de3e7a6161af0c887ef91b7d41a53e7c5a1ca976325f429cb46ea9bc30ecc"},
- {file = "tomli-2.0.1.tar.gz", hash = "sha256:de526c12914f0c550d15924c62d72abc48d6fe7364aa87328337a31007fe8a4f"},
-]
-
-[[package]]
-name = "typing-extensions"
-version = "4.12.2"
-description = "Backported and Experimental Type Hints for Python 3.8+"
-optional = false
-python-versions = ">=3.8"
-files = [
- {file = "typing_extensions-4.12.2-py3-none-any.whl", hash = "sha256:04e5ca0351e0f3f85c6853954072df659d0d13fac324d0072316b67d7794700d"},
- {file = "typing_extensions-4.12.2.tar.gz", hash = "sha256:1a7ead55c7e559dd4dee8856e3a88b41225abfe1ce8df57b7c13915fe121ffb8"},
-]
-
-[metadata]
-lock-version = "2.0"
-python-versions = "^3.10"
-content-hash = "8364e59737527da3f22d2813f93ca17522f9bf0594e9fa6e506af693ccffcaf4"
diff --git a/poetry.toml b/poetry.toml
deleted file mode 100644
index ab1033b..0000000
--- a/poetry.toml
+++ /dev/null
@@ -1,2 +0,0 @@
-[virtualenvs]
-in-project = true
diff --git a/pyproject.toml b/pyproject.toml
index 20e9f21..3dcd0c5 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,26 +1,55 @@
-[tool.poetry]
+[project]
name = "ezcoo-cli"
-version = "0.1.0"
+version = "0.2.0"
description = "A tool to control EZCOO KVM switches via the serial interface"
-authors = ["Simon Brakhane "]
+authors = [{ name = "Simon Brakhane", email = "simon@brakhane.net" }]
+requires-python = ">=3.10"
readme = "README.md"
-license = "Apache-2.0"
+license = "GPL-3.0-or-later"
+dependencies = ["pyserial>=3.5", "click>=8.1.3"]
-[tool.poetry.scripts]
-ezcoo-cli = "ezcoo_cli.console:main"
+[project.scripts]
+ezcoo-cli = "ezcoo_cli.cli:main"
-[tool.poetry.dependencies]
-python = "^3.10"
-pyserial = "^3.5"
-click = "^8.1.3"
-attrs = "^23.1.0"
+[build-system]
+requires = ["hatchling"]
+build-backend = "hatchling.build"
-[tool.poetry.group.dev.dependencies]
-flake8 = "^6.0.0"
-flake8-black = "^0.3.6"
-flake8-import-order = "^0.18.2"
-mypy = "^1.3.0"
+[tool.ruff]
+line-length = 120
-[build-system]
-requires = ["poetry-core"]
-build-backend = "poetry.core.masonry.api"
+lint.select = [
+ "E", # pycodestyle errors
+ "W", # pycodestyle warnings
+ "F", # pyflakes
+ "I", # isort
+ "C90", # mccabe complexity
+ "B", # flake8-bugbear (equivalent to BLK)
+]
+
+[dependency-groups]
+dev = [
+ "pytest>=8.3.5",
+ "pytest-cov>=6.0.0",
+ "pytest-reserial>=0.4.2",
+ "ruff>=0.13.2",
+]
+
+[tool.pytest.ini_options]
+testpaths = ["tests"]
+addopts = ["--cov=src/ezcoo_cli", "--cov-report=term-missing"]
+
+[tool.coverage.run]
+source = ["src/ezcoo_cli"]
+omit = ["*/tests/*", "*/__pycache__/*"]
+
+[tool.coverage.report]
+exclude_lines = [
+ "pragma: no cover",
+ "def __repr__",
+ "raise AssertionError",
+ "raise NotImplementedError",
+ "if __name__ == .__main__.:",
+ "if TYPE_CHECKING:",
+ "@abstractmethod",
+]
diff --git a/scripts/test-record.sh b/scripts/test-record.sh
new file mode 100755
index 0000000..4471c7e
--- /dev/null
+++ b/scripts/test-record.sh
@@ -0,0 +1,22 @@
+#!/usr/bin/env bash
+# Record serial traffic from real hardware for later replay
+# This creates/updates .jsonl files with recorded device responses
+
+set -e
+
+DEVICE="/dev/ttyUSB0"
+
+# Check if device exists
+if [ ! -e "$DEVICE" ]; then
+ echo "ERROR: Device $DEVICE does not exist"
+ exit 1
+fi
+
+# Check if device is readable and writable
+if [ ! -r "$DEVICE" ] || [ ! -w "$DEVICE" ]; then
+ echo "ERROR: Device $DEVICE is not readable and writable by current user"
+ echo "Try: sudo chmod 666 $DEVICE"
+ exit 1
+fi
+
+uv run pytest tests/ --record -v "$@"
\ No newline at end of file
diff --git a/scripts/test-replay.sh b/scripts/test-replay.sh
new file mode 100755
index 0000000..fae00fb
--- /dev/null
+++ b/scripts/test-replay.sh
@@ -0,0 +1,13 @@
+#!/usr/bin/env bash
+# Run tests using recorded serial traffic (no hardware needed)
+# This uses the .jsonl files created by test-record.sh
+
+set -e
+
+# Check if any .jsonl files exist
+if ! ls tests/*.jsonl 1> /dev/null 2>&1; then
+ echo "ERROR: No recorded traffic files found. Run ./scripts/test-record.sh first."
+ exit 1
+fi
+
+uv run pytest tests/ --replay -v "$@"
\ No newline at end of file
diff --git a/scripts/test-with-hardware.sh b/scripts/test-with-hardware.sh
new file mode 100755
index 0000000..050c83f
--- /dev/null
+++ b/scripts/test-with-hardware.sh
@@ -0,0 +1,22 @@
+#!/usr/bin/env bash
+# Test with real hardware connected
+# This runs tests against the actual EZCOO device without recording or replaying
+
+set -e
+
+DEVICE="/dev/ttyUSB0"
+
+# Check if device exists
+if [ ! -e "$DEVICE" ]; then
+ echo "ERROR: Device $DEVICE does not exist"
+ exit 1
+fi
+
+# Check if device is readable and writable
+if [ ! -r "$DEVICE" ] || [ ! -w "$DEVICE" ]; then
+ echo "ERROR: Device $DEVICE is not readable and writable by current user"
+ echo "Try: sudo chmod 666 $DEVICE"
+ exit 1
+fi
+
+uv run pytest tests/ -v "$@"
\ No newline at end of file
diff --git a/src/ezcoo_cli/__init__.py b/src/ezcoo_cli/__init__.py
index 9c58050..9dd81be 100644
--- a/src/ezcoo_cli/__init__.py
+++ b/src/ezcoo_cli/__init__.py
@@ -1,10 +1,3 @@
-try:
- from importlib.metadata import version, PackageNotFoundError # type: ignore
-except ImportError: # pragma: no cover
- from importlib_metadata import version, PackageNotFoundError # type: ignore
+from importlib.metadata import version
-
-try:
- __version__ = version(__name__)
-except PackageNotFoundError: # pragma: no cover
- __version__ = "unknown"
\ No newline at end of file
+__version__ = version(__name__)
diff --git a/src/ezcoo_cli/cli.py b/src/ezcoo_cli/cli.py
new file mode 100755
index 0000000..784a2f6
--- /dev/null
+++ b/src/ezcoo_cli/cli.py
@@ -0,0 +1,288 @@
+#!/usr/bin/env python
+import json
+from dataclasses import asdict
+from pathlib import Path
+
+import click
+
+from . import __version__
+from .kvm import KVM, KVMError
+from .models import DiscoveredDevice
+
+device_option = click.option(
+ "-d",
+ "--device",
+ type=click.Path(
+ exists=True,
+ dir_okay=False,
+ writable=True,
+ readable=True,
+ path_type=Path,
+ ),
+ required=True,
+ default="/dev/ttyUSB0",
+)
+
+address_option = click.option(
+ "-a",
+ "--address",
+ type=click.IntRange(0, 99),
+ default=0,
+ help="Device address (0-99). Use 0 for single device mode (default).",
+)
+
+format_option = click.option(
+ "-f",
+ "--format",
+ type=click.Choice(["raw", "json", "pretty"], case_sensitive=False),
+ default="pretty",
+ help="Output format (default: pretty)",
+)
+
+
+@click.group()
+def main() -> None:
+ """A tool to control EZCOO KVM switches via the serial interface."""
+ pass
+
+
+@main.command()
+def version() -> None:
+ """Show the version and exit."""
+ click.echo(__version__)
+
+
+@main.command()
+@device_option
+@address_option
+@format_option
+def status(device: Path, address: int, format: str) -> None:
+ """Show global system status."""
+ try:
+ kvm = KVM(device, address=address)
+ status_response = kvm.get_system_status()
+
+ match format:
+ case "json":
+ click.echo(json.dumps(asdict(status_response), indent=2))
+ case "pretty":
+ click.echo(f"System Address: {status_response.response.system_address:02d}")
+ click.echo(f"Firmware Version: {status_response.response.firmware_version}")
+ case _: # raw
+ click.echo("".join(status_response.raw_response), nl=False)
+ except KVMError as e:
+ click.echo(f"Error: {e}", err=True)
+ raise click.Abort() from e
+
+
+@main.command()
+@device_option
+@address_option
+@format_option
+def help(device: Path, address: int, format: str) -> None:
+ """Get help information from the device."""
+ try:
+ kvm = KVM(device, address=address)
+ help_response = kvm.get_help()
+
+ match format:
+ case "json":
+ click.echo(json.dumps(asdict(help_response), indent=2))
+ case "pretty":
+ click.echo("EZCOO Device Help Summary:")
+ click.echo("=" * 40)
+
+ if help_response.response.firmware_version:
+ click.echo(f"Firmware Version: {help_response.response.firmware_version}")
+
+ for cmd in help_response.response.commands:
+ click.echo(f" {cmd.command}: {cmd.description}")
+
+ click.echo(f"\nTotal commands available: {help_response.response.total_commands}")
+ case _: # raw
+ click.echo("".join(help_response.raw_response), nl=False)
+ except KVMError as e:
+ click.echo(f"Error: {e}", err=True)
+ raise click.Abort() from e
+
+
+@main.group()
+def input() -> None:
+ """Commands for managing inputs."""
+ pass
+
+
+@input.command()
+@device_option
+@address_option
+@click.argument("input", type=click.IntRange(1, 4), required=True)
+@click.option(
+ "--output",
+ type=click.IntRange(1, 1),
+ default=1,
+ help="Output to switch (only output 1 supported)",
+)
+def switch(device: Path, address: int, input: int, output: int) -> None:
+ """Switch an input to the specified output.
+
+ INPUT: Input number to switch (1-4)
+ """
+ try:
+ kvm = KVM(device, address=address)
+ kvm.switch_input(input, output_num=output)
+ click.echo(f"Switched input {input} to output {output}")
+ except (KVMError, ValueError) as e:
+ click.echo(f"Error: {e}", err=True)
+ raise click.Abort() from e
+
+
+@main.group()
+def output() -> None:
+ """Commands for managing outputs."""
+ pass
+
+
+@output.command()
+@device_option
+@address_option
+@click.option(
+ "--output",
+ type=click.IntRange(1, 1),
+ default=1,
+ help="Output to query (only output 1 supported)",
+)
+@format_option
+def routing(device: Path, address: int, output: int, format: str) -> None:
+ """Get current output video routing."""
+ try:
+ kvm = KVM(device, address=address)
+ routing_response = kvm.get_output_routing(output)
+
+ match format:
+ case "json":
+ click.echo(json.dumps(asdict(routing_response), indent=2))
+ case "pretty":
+ click.echo(
+ f"Output {routing_response.response.output} is connected to Input {routing_response.response.input}"
+ )
+ case _: # raw
+ click.echo("".join(routing_response.raw_response), nl=False)
+ except (KVMError, ValueError) as e:
+ click.echo(f"Error: {e}", err=True)
+ raise click.Abort() from e
+
+
+@output.command()
+@device_option
+@address_option
+@click.option(
+ "--output",
+ type=click.IntRange(1, 1),
+ default=1,
+ help="Output to query (only output 1 supported)",
+)
+@format_option
+def stream(device: Path, address: int, output: int, format: str) -> None:
+ """Get output stream status."""
+ try:
+ kvm = KVM(device, address=address)
+ stream_response = kvm.get_stream_status(output)
+
+ match format:
+ case "json":
+ click.echo(json.dumps(asdict(stream_response), indent=2))
+ case "pretty":
+ click.echo(f"Output {stream_response.response.output} stream is {stream_response.response.status}")
+ case _: # raw
+ click.echo("".join(stream_response.raw_response), nl=False)
+ except (KVMError, ValueError) as e:
+ click.echo(f"Error: {e}", err=True)
+ raise click.Abort() from e
+
+
+@main.group()
+def system() -> None:
+ """System management commands."""
+ pass
+
+
+@system.command()
+@device_option
+@address_option
+@click.argument("new_address", type=click.IntRange(0, 99), required=True)
+@click.option("--yes", "-y", is_flag=True, help="Skip confirmation prompt")
+def set_address(device: Path, address: int, new_address: int, yes: bool) -> None:
+ """Set the device address.
+
+ NEW_ADDRESS: New address to set (0-99)
+
+ Warning: After changing the address, you must use --address option
+ to communicate with the device at its new address.
+ """
+ try:
+ # Confirm the change unless --yes is used
+ if not yes:
+ click.echo(f"This will change the device address from {address} to {new_address}")
+ click.echo("After this change, you must use --address {new_address} to communicate with the device")
+ if not click.confirm("Do you want to continue?"):
+ click.echo("Address change cancelled")
+ return
+
+ kvm = KVM(device, address=address)
+ kvm.set_device_address(new_address)
+ click.echo(f"Device address changed from {address} to {new_address}")
+ click.echo(f"\nTo communicate with the device now, use: --address {new_address}")
+ except (KVMError, ValueError) as e:
+ click.echo(f"Error: {e}", err=True)
+ raise click.Abort() from e
+
+
+@system.command()
+@device_option
+@click.option("--start", type=click.IntRange(0, 99), default=0, help="Start address (default: 0)")
+@click.option("--end", type=click.IntRange(0, 99), default=99, help="End address (default: 99)")
+@format_option
+def discover(device: Path, start: int, end: int, format: str) -> None:
+ """Discover devices by scanning address range.
+
+ This command scans the specified address range to find all responding devices.
+ """
+ if start > end:
+ click.echo("Error: Start address must be less than or equal to end address", err=True)
+ raise click.Abort()
+
+ try:
+ if format != "json":
+ click.echo(f"Scanning addresses {start} to {end}...", err=True)
+
+ found_devices: list[DiscoveredDevice] = []
+
+ for addr in range(start, end + 1):
+ try:
+ kvm = KVM(device, address=addr)
+ status = kvm.get_system_status()
+ found_devices.append(
+ DiscoveredDevice(
+ address=addr,
+ firmware=status.response.firmware_version,
+ system_address=status.response.system_address,
+ )
+ )
+ if format != "json":
+ click.echo(f"Found device at address {addr} (firmware: {status.response.firmware_version})")
+ except (KVMError, Exception):
+ # No device at this address
+ continue
+
+ match format:
+ case "json":
+ click.echo(json.dumps([asdict(d) for d in found_devices], indent=2))
+ case _:
+ if not found_devices:
+ click.echo("\nNo devices found in the specified range")
+ else:
+ click.echo(f"\nTotal devices found: {len(found_devices)}")
+
+ except Exception as e:
+ click.echo(f"Error during discovery: {e}", err=True)
+ raise click.Abort() from e
diff --git a/src/ezcoo_cli/console.py b/src/ezcoo_cli/console.py
deleted file mode 100755
index 71ce601..0000000
--- a/src/ezcoo_cli/console.py
+++ /dev/null
@@ -1,55 +0,0 @@
-#!/usr/bin/env python
-from pathlib import Path
-
-import click
-
-from . import __version__
-from .device import Device
-
-device_option = click.option(
- "-d",
- "--device",
- type=click.Path(
- exists=True, dir_okay=False, writable=True, readable=True, path_type=Path
- ),
- required=True,
- default="/dev/ttyUSB0",
-)
-
-
-@click.group()
-@click.version_option(version=__version__)
-def main() -> None:
- pass
-
-
-@main.group()
-def input() -> None:
- pass
-
-
-@input.command()
-@device_option
-@click.argument("input", type=click.IntRange(1, 8), required=True)
-@click.option("--output", type=click.IntRange(1, 2), default=1, help="Output to switch")
-def switch(device: Path, input: int, output: int) -> None:
- with Device(device) as client:
- client.write(f"EZS OUT{output} VS IN{input}")
-
-
-@input.command()
-@device_option
-def edid(device: Path) -> None:
- with Device(device) as client:
- client.write("EZG IN0 EDID")
- for line in client.readlines():
- print(line, end="")
-
-
-@main.command()
-@device_option
-def help(device: Path) -> None:
- with Device(device) as client:
- client.write("EZH")
- for line in client.readlines():
- print(line, end="")
diff --git a/src/ezcoo_cli/device.py b/src/ezcoo_cli/device.py
index 3154709..cd1857a 100644
--- a/src/ezcoo_cli/device.py
+++ b/src/ezcoo_cli/device.py
@@ -1,38 +1,124 @@
import contextlib
from pathlib import Path
from types import TracebackType
-from typing import Generator, Type
+from typing import Generator, Self
import serial
-class Device(contextlib.AbstractContextManager):
- def __init__(self, path: Path) -> None:
+class DeviceError(Exception):
+ """Base exception for device-related errors."""
+
+ pass
+
+
+class DeviceConnectionError(DeviceError):
+ """Raised when device connection fails."""
+
+ pass
+
+
+class Device(contextlib.AbstractContextManager["Device"]):
+ """A context manager for communicating with EZCOO KVM switches via serial interface.
+
+ This class can be used both as a CLI tool and as a library component.
+
+ Example:
+ >>> from ezcoo_cli.device import Device
+ >>> from pathlib import Path
+ >>>
+ >>> with Device(Path("/dev/ttyUSB0")) as device:
+ ... device.write("EZS OUT1 VS IN2")
+ """
+
+ def __init__(self, path: Path, baudrate: int = 115200, timeout: float = 1.0) -> None:
+ """Initialize the Device.
+
+ Args:
+ path: Path to the serial device (e.g., /dev/ttyUSB0)
+ baudrate: Serial communication baud rate (default: 115200)
+ timeout: Read timeout in seconds (default: 1)
+ """
+ self._path = path
self._serial = serial.Serial()
self._serial.port = str(path)
- self._serial.baudrate = 115200
- self._serial.timeout = 1
+ self._serial.baudrate = baudrate
+ self._serial.timeout = timeout
- def __enter__(self) -> "Device":
- self._serial.open()
+ def __enter__(self) -> Self:
+ try:
+ self._serial.open()
+ except serial.SerialException as e:
+ raise DeviceConnectionError(f"Failed to open device {self._path}: {e}") from e
return self
def __exit__(
self,
- exc_type: Type[BaseException] | None,
+ exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None:
- self._serial.close()
+ if self._serial.is_open:
+ self._serial.close()
+
+ @staticmethod
+ def validate_command(cmd: str) -> None:
+ """Validate that a command only contains safe characters.
+
+ Args:
+ cmd: Command string to validate
+
+ Raises:
+ DeviceError: If command contains invalid characters
+ """
+ # Only allow ASCII alphanumeric characters and regular spaces (not tabs, newlines, etc.)
+ if not all(c.isalnum() or c == " " for c in cmd):
+ raise DeviceError(
+ f"Command contains invalid characters. Only ASCII alphanumeric and spaces allowed: {cmd!r}"
+ )
def write(self, cmd: str) -> None:
- buffer = (cmd + "\n").encode("ascii")
- self._serial.write(buffer)
+ """Write a command to the device.
+
+ Args:
+ cmd: Command string to send to the device
+
+ Raises:
+ DeviceError: If writing to device fails or command contains invalid characters
+ """
+ if not self._serial.is_open:
+ raise DeviceError("Device is not open")
+
+ # Validate command before sending
+ self.validate_command(cmd)
+
+ try:
+ buffer = (cmd + "\n").encode("ascii")
+ self._serial.write(buffer)
+ except UnicodeEncodeError as e:
+ raise DeviceError(f"Command contains non-ASCII characters: {e}") from e
+ except serial.SerialException as e:
+ raise DeviceError(f"Failed to write to device: {e}") from e
def readlines(self) -> Generator[str, None, None]:
- while True:
- read = self._serial.read_until()
- if not read:
- break
+ """Read lines from the device until no more data is available.
+
+ Yields:
+ str: Each line received from the device
- yield read.decode("ascii")
+ Raises:
+ DeviceError: If reading from device fails
+ """
+ if not self._serial.is_open:
+ raise DeviceError("Device is not open")
+
+ while True:
+ try:
+ read = self._serial.read_until()
+ if not read:
+ break
+ yield read.decode("ascii")
+ except serial.SerialException as e:
+ raise DeviceError(f"Failed to read from device: {e}") from e
+ except UnicodeDecodeError as e:
+ raise DeviceError(f"Failed to decode device response: {e}") from e
diff --git a/src/ezcoo_cli/kvm.py b/src/ezcoo_cli/kvm.py
new file mode 100644
index 0000000..21c1a93
--- /dev/null
+++ b/src/ezcoo_cli/kvm.py
@@ -0,0 +1,364 @@
+"""High-level KVM switch interface."""
+
+import re
+from collections.abc import Callable
+from pathlib import Path
+from typing import TypeVar, overload
+
+from .device import Device
+from .models import Command, HelpInfo, KVMResponse, OutputRouting, StreamState, StreamStatus, SystemStatus
+
+T = TypeVar("T")
+
+
+class KVMError(Exception):
+ """Base exception for KVM-related errors."""
+
+ pass
+
+
+class KVM:
+ """High-level interface for EZCOO KVM switches.
+
+ This class provides a type-safe, structured interface to KVM functionality
+ that can be used both by the CLI and as a library.
+
+ Example:
+ >>> from pathlib import Path
+ >>> from ezcoo_cli.kvm import KVM
+ >>>
+ >>> kvm = KVM(Path("/dev/ttyUSB0"))
+ >>> status = kvm.get_system_status()
+ >>> print(f"Firmware: {status.firmware_version}")
+ >>> kvm.switch_input(2)
+ >>>
+ >>> # For device at address 5
+ >>> kvm = KVM(Path("/dev/ttyUSB0"), address=5)
+ >>> status = kvm.get_system_status() # Sends A05EZSTA
+ """
+
+ def __init__(
+ self,
+ device_path: Path,
+ baudrate: int = 115200,
+ timeout: float = 1.0,
+ address: int = 0,
+ ):
+ """Initialize the KVM interface.
+
+ Args:
+ device_path: Path to the serial device (e.g., /dev/ttyUSB0)
+ baudrate: Serial communication baud rate (default: 115200)
+ timeout: Read timeout in seconds (default: 1.0)
+ address: Device address (0-99). Use 0 for single device (default).
+ For addresses 1-99, commands will be prefixed with Axx.
+ """
+ self.device_path = device_path
+ self.baudrate = baudrate
+ self.timeout = timeout
+ self._address = address
+
+ if not 0 <= address <= 99:
+ raise ValueError("Address must be between 0 and 99")
+
+ @property
+ def address(self) -> int:
+ """Get the current address this KVM instance is configured to use."""
+ return self._address
+
+ @address.setter
+ def address(self, value: int) -> None:
+ """Set the address this KVM instance should use for communication.
+
+ Args:
+ value: Address to use (0-99)
+
+ Raises:
+ ValueError: If address is invalid
+
+ Note:
+ This only changes which address this KVM instance uses for commands.
+ It does NOT change the device's actual address. Use set_device_address()
+ to change the device's address.
+ """
+ if not 0 <= value <= 99:
+ raise ValueError("Address must be between 0 and 99")
+
+ self._address = value
+
+ def _build_command(self, command: str) -> str:
+ """Build a command with address prefix.
+
+ Args:
+ command: The base command (e.g., "EZSTA", "EZH")
+
+ Returns:
+ Command with address prefix if needed
+ """
+ if self._address == 0:
+ return command
+ return f"A{self._address:02d}{command}"
+
+ @overload
+ def _execute_command(
+ self,
+ command: str,
+ parser: Callable[[list[str]], T],
+ ) -> KVMResponse[T]: ...
+
+ @overload
+ def _execute_command(
+ self,
+ command: str,
+ parser: None,
+ ) -> None: ...
+
+ def _execute_command(
+ self,
+ command: str,
+ parser: Callable[[list[str]], T] | None = None,
+ ) -> KVMResponse[T] | None:
+ """Execute a command on the device and optionally parse the response.
+
+ Args:
+ command: The full command to execute (with address prefix already applied)
+ parser: Optional function to parse the response lines into a typed result.
+ If None, no response is expected and None is returned.
+
+ Returns:
+ KVMResponse[T] containing the parsed result if parser is provided, None otherwise
+
+ Raises:
+ KVMError: If parser is provided but no response received, or if parsing fails
+ """
+ with Device(self.device_path, self.baudrate, self.timeout) as device:
+ device.write(command)
+ if parser is None:
+ return None
+ lines = list(device.readlines())
+
+ if not lines:
+ raise KVMError("No response from device")
+
+ parsed_response = parser(lines)
+ return KVMResponse(command=command, raw_response=lines, response=parsed_response)
+
+ def _parse_status_output(self, lines: list[str]) -> SystemStatus:
+ """Parse EZSTA command output into SystemStatus.
+
+ Expected format:
+ - "System Address = XX F/W Version : X.XX"
+ """
+ # Pattern matches: System Address = F/W Version :
+ status_pattern = r"System\s+Address\s*=\s*(?P\d+)\s+F/W\s+Version\s*:\s*(?P[\d.]+)"
+
+ for line in lines:
+ line = line.strip()
+
+ # Try to match system address and firmware version
+ match = re.search(status_pattern, line, re.IGNORECASE)
+ if not match:
+ continue
+
+ system_address = int(match.group("address"))
+ firmware_version = match.group("version")
+
+ return SystemStatus(
+ system_address=system_address,
+ firmware_version=firmware_version,
+ )
+
+ raise KVMError("Failed to parse system status")
+
+ def _parse_help_output(self, lines: list[str]) -> HelpInfo:
+ """Parse EZH command output into HelpInfo.
+
+ Expected format:
+ - "F/W Version : X.XX"
+ - "= COMMAND : Description"
+ """
+ commands: list[Command] = []
+ firmware_version: str | None = None
+
+ # Pattern matches: F/W Version :
+ version_pattern = r"F/W\s+Version\s*:\s*(?P[\d.]+)"
+ # Pattern matches: = COMMAND_NAME : Description
+ # Captures everything from EZ to the colon (trimmed)
+ command_pattern = r"^=\s+(?PEZ[^:]+?)\s*:\s*(?P.+)$"
+
+ for line in lines:
+ line = line.strip()
+
+ # Try to match firmware version
+ version_match = re.search(version_pattern, line, re.IGNORECASE)
+ if version_match:
+ firmware_version = version_match.group("version")
+
+ # Try to match command entries
+ cmd_match = re.match(command_pattern, line)
+ if cmd_match:
+ cmd_name = cmd_match.group("command")
+ cmd_desc = cmd_match.group("description").strip()
+ commands.append(Command(command=cmd_name, description=cmd_desc))
+
+ return HelpInfo(
+ firmware_version=firmware_version,
+ commands=commands,
+ total_commands=len(commands),
+ )
+
+ def _parse_routing_output(self, lines: list[str]) -> OutputRouting:
+ """Parse EZG OUTx VS command output into OutputRouting.
+
+ Expected format: "OUTx VS y" where x is output number and y is input number.
+ """
+ # Pattern matches: OUT VS
+ pattern = r"OUT(?P