pax_global_header00006660000000000000000000000064145762633170014530gustar00rootroot0000000000000052 comment=57e6bb35911db26f275c59de0281802e00c5c542 gnumpi-pyEGPS-57e6bb3/000077500000000000000000000000001457626331700145535ustar00rootroot00000000000000gnumpi-pyEGPS-57e6bb3/.flake8000066400000000000000000000005621457626331700157310ustar00rootroot00000000000000[flake8] max-line-length = 120 # for black compatibility # E501: line too long # W503: Line break occurred before a binary operator # E203: Whitespace before ':' # D202 No blank lines allowed after function docstring # D102 Missing docstring in public method # D105 Missing docstring in magic method ignore = E501, W503, E203, D202, D102 D105 gnumpi-pyEGPS-57e6bb3/.gitignore000066400000000000000000000004711457626331700165450ustar00rootroot00000000000000# Temporary and binary files *~ *.py[cod] *.so *.cfg !.isort.cfg !setup.cfg *.orig *.log *.pot __pycache__/* .cache/* .*.swp */.ipynb_checkpoints/* .DS_Store # Per-project virtualenvs .venv*/ # Package files *.egg *.eggs/ .installed.cfg *.egg-info dist/ # Testing and Linting .tox # runtime files _version.py gnumpi-pyEGPS-57e6bb3/.pre-commit-config.yaml000066400000000000000000000015361457626331700210410ustar00rootroot00000000000000repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.5.0 hooks: - id: end-of-file-fixer - id: trailing-whitespace - id: check-shebang-scripts-are-executable - id: check-executables-have-shebangs - repo: https://github.com/Lucas-C/pre-commit-hooks rev: v1.5.4 hooks: - id: remove-tabs args: [--whitespaces-count, '4'] - repo: https://github.com/psf/black rev: 23.11.0 hooks: - id: black files: ^((src|tests)/.+)?[^/]+\.py$ - repo: https://github.com/PyCQA/flake8 rev: 6.1.0 hooks: - id: flake8 additional_dependencies: - flake8-docstrings==1.5.0 - pydocstyle==5.1.1 files: ^(src|tests)/.+\.py$ - repo: https://github.com/asottile/pyupgrade rev: v3.15.0 hooks: - id: pyupgrade args: [--py39-plus] gnumpi-pyEGPS-57e6bb3/LICENSE.md000066400000000000000000000261351457626331700161660ustar00rootroot00000000000000 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 [yyyy] [name of copyright owner] 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. gnumpi-pyEGPS-57e6bb3/README.md000066400000000000000000000016151457626331700160350ustar00rootroot00000000000000# PyEGPS Python library for controlling [Energenie powerstrips](https://energenie.com/item.aspx?id=7415). This library is meant to be used with [Home Assistant](https://www.home-assistant.io/) components. ### Installation: ``` pip install pyegps ``` Make sure the user has the necessary rights to access the device. E.g.: find your device with: ```bash lsusb #e.g.: Bus 001 Device 005: ID 04b4:fd15 Cypress Semiconductor Corp. Energenie EG-PMS2 ``` ```bash sudo echo 'SUBSYSTEM=="usb", ATTR{idVendor}=="04b4", ATTR{idProduct}=="fd15", MODE="0666"' > /lib/udev/rules.d/60-energenie-usb.rules sudo udevadm control --reload-rules sudo udevadm trigger ``` ### Command Line Interace (CLI) For help, see: ``` python3 -m pyegps --help ``` ### Acknowledgment Thanks go to the author of 'pysispm' for figuring out which HID-Reports are used for communicating with the device: https://github.com/xypron/pysispm gnumpi-pyEGPS-57e6bb3/pyproject.toml000066400000000000000000000016011457626331700174650ustar00rootroot00000000000000[project] name = "pyEGPS" dynamic = ["version"] authors = [ {name = "Mischa Siekmann", email = "mischa@gnumpi.com"}, ] description = "Controlling Energenie Power Strips with python." readme = "README.md" requires-python = ">=3.8" keywords = [] license = {text = "Apache-2.0"} classifiers = [ "Programming Language :: Python :: 3", ] dependencies = [ "pyusb", ] [project.urls] # Optional "Homepage" = "https://github.com/gnumpi/pyegps" [build-system] requires = ["setuptools", "setuptools-scm"] build-backend = "setuptools.build_meta" [tool.setuptools.packages.find] where = ["src"] [tool.setuptools_scm] # For smarter version schemes and other configuration options, # check out https://github.com/pypa/setuptools_scm version_scheme = "no-guess-dev" version_file = "src/pyegps/_version.py" [tool.mypy] [[tool.mypy.overrides]] module = 'usb.*' ignore_missing_imports = true gnumpi-pyEGPS-57e6bb3/requirements_dev.txt000066400000000000000000000001541457626331700206750ustar00rootroot00000000000000black==23.11.0 flake8==6.1.0 pyupgrade==v3.15.0 tox pytest==7.4.3 pre-commit==3.5.0 tox==4.11.4 mypy==1.7.1 gnumpi-pyEGPS-57e6bb3/scripts/000077500000000000000000000000001457626331700162425ustar00rootroot00000000000000gnumpi-pyEGPS-57e6bb3/scripts/fake_cli.py000066400000000000000000000007771457626331700203640ustar00rootroot00000000000000"""Allows direct execution of CLI with dummy devices.""" from unittest.mock import patch import sys import os sys.path.append( os.path.join(os.path.dirname(__file__), "..","src") ) import pyegps from pyegps.fakes.powerstrip import FakePowerStrip def take_dummy_devices(): return patch("pyegps.search_for_devices", return_value=FakePowerStrip.search_for_devices() ) if __name__ == "__main__": with take_dummy_devices() as mock: from pyegps import cli sys.exit(cli.cli(sys.argv[1:])) gnumpi-pyEGPS-57e6bb3/src/000077500000000000000000000000001457626331700153425ustar00rootroot00000000000000gnumpi-pyEGPS-57e6bb3/src/pyegps/000077500000000000000000000000001457626331700166515ustar00rootroot00000000000000gnumpi-pyEGPS-57e6bb3/src/pyegps/__init__.py000066400000000000000000000025461457626331700207710ustar00rootroot00000000000000"""Controlling Energenie Power Strips.""" from __future__ import annotations from importlib.metadata import version, PackageNotFoundError try: __version__ = version("pyegps") except PackageNotFoundError: from ._version import __version__ # noqa from .device import Device from .usb.eg_powerstrip import PowerStripUSB from .fakes.powerstrip import FakePowerStrip DEVICE_IMPLEMENTATIONS: list[type[Device]] = [PowerStripUSB] def search_for_devices(device_type: str | None = None) -> list[Device]: """Search and return all supported devices.""" return [ dev for impl in DEVICE_IMPLEMENTATIONS if device_type is None or impl.get_device_type() == device_type for dev in impl.search_for_devices() ] def get_device_types() -> list[str]: """Return all supported device types.""" return [impl.get_device_type() for impl in DEVICE_IMPLEMENTATIONS] def get_device(device_id: str) -> Device | None: """Try to find the device for the given device_id and return it.""" for impl in DEVICE_IMPLEMENTATIONS: dev_or_none = impl.get_device(device_id) if dev_or_none is not None: return dev_or_none return None def use_fake_devices() -> None: """Let dummy devices appear in searches for devices.""" DEVICE_IMPLEMENTATIONS.clear() DEVICE_IMPLEMENTATIONS.append(FakePowerStrip) gnumpi-pyEGPS-57e6bb3/src/pyegps/__main__.py000066400000000000000000000001431457626331700207410ustar00rootroot00000000000000"""Using CLI as main entry point.""" import sys from .cli import cli sys.exit(cli(sys.argv[1:])) gnumpi-pyEGPS-57e6bb3/src/pyegps/cli.py000066400000000000000000000120101457626331700177640ustar00rootroot00000000000000"""Simple command line interface for pyEGPS.""" from __future__ import annotations import argparse from . import search_for_devices, get_device_types, __version__ from .device import Device from .powerstrip import PowerStrip from .exceptions import EgpsException, InvalidSocketNumber def print_status(dev: Device): """Print summary of given device.""" print(dev.summary()) def list_devices(device_type: str = "all") -> int: """Print __repr__() for all devices.""" for dev in search_for_devices(): if device_type == "all" or dev.get_device_type() == device_type: print(dev) return 0 def cli(argList: list[str]) -> int: """Command Line Interface (CLI).""" parser = argparse.ArgumentParser( description="Simple command line interface for controlling EnerGenie Power Strips" ) subparsers = parser.add_subparsers(dest="command") parser.add_argument( "--device", metavar="DEVICE_ID", nargs="?", help="Specify device[s] to use. Can be omitted if only one device is present.", ) parser.add_argument("--debug", action="store_true", help="Print debug information.") parser.add_argument( "--version", action="store_true", help="Print debug information." ) # List devices list_cmd = subparsers.add_parser("list", help="Search for supported devices.") # If several device types are defined, allow filtering by device type device_types = get_device_types() if len(device_types) > 1: list_cmd.add_argument( "--type", type=str, choices=["all"] + device_types, default="all" ) set_cmd = subparsers.add_parser("set", help="Set status of sockets.") set_cmd.add_argument( "--on", type=int, nargs="*", action="append", metavar="SOCKET_NR", default=[], help="Turn SOCKET_NR on.", ) set_cmd.add_argument( "--off", type=int, nargs="*", action="append", metavar="SOCKET_NR", default=[], help="Turn SOCKET_NR off.", ) status_cmd = subparsers.add_parser("status", help="Get current device status.") status_cmd.add_argument( "SOCKET_NR", nargs="*", type=int, help="Status of SOCKET_NR, print summary if no SOCKET_NR is given.", ) args = parser.parse_args(argList) if args.version: print(__version__) return 0 if args.command == "list": dev_type = args.type if len(device_types) > 1 else "all" try: return list_devices(dev_type) except EgpsException as e: print(f"Error: {e}") return 1 try: devices = search_for_devices(device_type="PowerStrip") except EgpsException as e: print(f"Error: {e}") return 1 # filter devices if requested if args.device is not None: devices = [d for d in devices if d.device_id == args.device] if len(devices) == 0: print( "Couldn't find any devices{}.".format( f" with ids in {args.device}" if args.device is not None else "!" ) ) return 1 if args.command == "set": on_sockets = [item for sublist in args.on for item in sublist] off_sockets = [item for sublist in args.off for item in sublist] if len(on_sockets) + len(off_sockets) == 0: print("Please specify at least one --on or --off argument") return 1 for device in devices: assert isinstance(device, PowerStrip) for socket in on_sockets: try: device.switch_on(socket) except InvalidSocketNumber: print( f"Device {device} has no socket {socket}. Known sockets: {list(range(device.numberOfSockets))}." ) return 1 for socket in off_sockets: try: device.switch_off(socket) except InvalidSocketNumber: print( f"Device {device} has no socket {socket}. Known sockets: {list(range(device.numberOfSockets))}." ) return 1 return 0 elif args.command == "status": for device in devices: assert isinstance(device, PowerStrip) if len(args.SOCKET_NR) == 0: print_status(device) else: status = [] for socket in args.SOCKET_NR: try: status.append(device.get_status(socket)) except InvalidSocketNumber: print( f"Device {device} has no socket {socket}. Known sockets: {list(range(device.numberOfSockets))}." ) return 1 print(" ".join(map(lambda s: "on" if s else "off", status))) return 0 else: parser.print_usage() return 1 return 1 gnumpi-pyEGPS-57e6bb3/src/pyegps/device.py000066400000000000000000000040071457626331700204630ustar00rootroot00000000000000"""Definition of the base class for alle devices.""" from __future__ import annotations import abc from typing import TypeVar T = TypeVar("T", bound="Device") class Device(abc.ABC): """Abstract base class for all devices.""" def release(self) -> None: """Free any resources if needed.""" @property def device_id(self) -> str: """Return a unique identifier among all devices of any type.""" return f"{self.get_implementation_id()}:{self.uid}" @classmethod def is_responsible(cls, device_id: str) -> bool: """Check if the given device_id is handled by this device implementation.""" return device_id.split(":")[0] == cls.get_implementation_id() @classmethod def get_device(cls, device_id: str) -> Device | None: """Get the device for the given device_id.""" if not cls.is_responsible(device_id): return None devices = cls.search_for_devices() for d in devices: if d.device_id == device_id: return d return None @property @abc.abstractmethod def uid(self) -> str: """Return an identifier within the implementation context.""" @staticmethod @abc.abstractmethod def get_device_type() -> str: """Return the implemented device type.""" @property @abc.abstractmethod def manufacturer(self) -> str: """Return the device manufacturer.""" @property @abc.abstractmethod def name(self) -> str: """Return the product name.""" @classmethod @abc.abstractmethod def get_implementation_id(cls) -> str: """Return an identifier for this implementation.""" @classmethod @abc.abstractmethod def search_for_devices(cls: type[T]) -> list[T]: """Search for supported devices.""" @abc.abstractmethod def summary(self) -> str: """Return a summary of the device and current status.""" def __repr__(self) -> str: return f"{self.get_device_type()}: {self.device_id}" gnumpi-pyEGPS-57e6bb3/src/pyegps/exceptions.py000066400000000000000000000007761457626331700214160ustar00rootroot00000000000000"""Custom Exceptions of pyEGPS.""" class EgpsException(Exception): """General EGPS exception.""" class MissingLibrary(EgpsException): """System is a missing a library.""" class UsbError(EgpsException): """Can't access the usb device.""" class UnsupportedProducId(UsbError): """Device has an unsupported product id.""" class MaximumConnectionTriesReached(UsbError): """Couldn't connect to device.""" class InvalidSocketNumber(EgpsException): """Device has no such socket.""" gnumpi-pyEGPS-57e6bb3/src/pyegps/fakes/000077500000000000000000000000001457626331700177425ustar00rootroot00000000000000gnumpi-pyEGPS-57e6bb3/src/pyegps/fakes/__init__.py000066400000000000000000000002331457626331700220510ustar00rootroot00000000000000"""Dummy implementations to be used for testings. Dummy devices can be used for running tests against the library when no actual device is connected. """ gnumpi-pyEGPS-57e6bb3/src/pyegps/fakes/powerstrip.py000066400000000000000000000035221457626331700225340ustar00rootroot00000000000000"""Dummy implementation of PowerStrip.""" from __future__ import annotations import random from pyegps.powerstrip import PowerStrip class FakePowerStrip(PowerStrip): """Dummy PowerStrip Device.""" DEVICES: list[FakePowerStrip] = [] def __init__(self, devId: str, number_of_sockets: int): """Initiate new DummyDevice.""" self._devId = devId self._numberOfSockets = number_of_sockets self._status = [random.randint(0, 1) for _ in range(number_of_sockets)] # PowerStrip implementations @property def numberOfSockets(self): return self._numberOfSockets def switch_on(self, socket: int) -> None: super().switch_on(socket) self._status[socket] = 1 def switch_off(self, socket: int) -> None: super().switch_off(socket) self._status[socket] = 0 def get_status(self, socket: int) -> bool: super().get_status(socket) return self._status[socket] == 1 # Device implementations @property def uid(self) -> str: """Return an identifier among DummyPowerStrip devices.""" return self._devId @property def manufacturer(self) -> str: """Return the device manufacturer.""" return "DummyDevices" @property def name(self) -> str: """Return the product name.""" return "DummyPowerStrip" @classmethod def get_implementation_id(cls) -> str: """Return an identifier for this implementation.""" return "DYPS" @classmethod def search_for_devices(cls) -> list[FakePowerStrip]: """Return the dummy devices, create new if necessary.""" if len(cls.DEVICES) == 0: cls.DEVICES += [ cls(devId, sockets) for devId, sockets in [("AA:BB:CC", 4), ("00:11:22", 2)] ] return cls.DEVICES gnumpi-pyEGPS-57e6bb3/src/pyegps/powerstrip.py000066400000000000000000000032311457626331700214400ustar00rootroot00000000000000"""Abstract PowerStrip Class.""" from __future__ import annotations import abc import logging from .device import Device from .exceptions import ( InvalidSocketNumber, ) _logger = logging.getLogger(__name__) class PowerStrip(Device, abc.ABC): """Abstract class of a PowerStrip device.""" @staticmethod def get_device_type() -> str: return "PowerStrip" @property @abc.abstractmethod def numberOfSockets(self) -> int: """Return number of controllable sockets.""" return 0 def get_status(self, socket: int) -> bool | None: """ Get the status of the socket given by 'socket'. @param socket: socket number @return: status """ if socket < 0 or socket > self.numberOfSockets - 1: raise InvalidSocketNumber return None def switch_off(self, socket: int) -> None: """ Switches the socket with the given id off. @param socket: socket number """ if socket < 0 or socket > self.numberOfSockets - 1: raise InvalidSocketNumber _logger.info(f"Socket {socket} switched off.") def switch_on(self, socket: int) -> None: """ Switches the socket with the given id on. @param socket: socket number """ if socket < 0 or socket > self.numberOfSockets - 1: raise InvalidSocketNumber _logger.info(f"Socket {socket} switched on.") def summary(self) -> str: s = self.__repr__() + "\n" for socket in range(self.numberOfSockets): s += f"Socket #{socket}: {'on' if self.get_status(socket) else 'off'}\n" return s gnumpi-pyEGPS-57e6bb3/src/pyegps/usb/000077500000000000000000000000001457626331700174425ustar00rootroot00000000000000gnumpi-pyEGPS-57e6bb3/src/pyegps/usb/__init__.py000066400000000000000000000000461457626331700215530ustar00rootroot00000000000000"""Implementations of USB Devices.""" gnumpi-pyEGPS-57e6bb3/src/pyegps/usb/eg_powerstrip.py000066400000000000000000000173301457626331700227110ustar00rootroot00000000000000"""Implementation of USB PowerStrips by Energenie.""" from __future__ import annotations import logging from array import array import usb.core from usb.core import Device as UsbDevice, NoBackendError from usb.util import ( CTRL_IN, CTRL_OUT, CTRL_TYPE_CLASS, CTRL_RECIPIENT_INTERFACE, dispose_resources, ) from ..device import Device from ..powerstrip import PowerStrip from ..exceptions import ( MissingLibrary, MaximumConnectionTriesReached, UnsupportedProducId, ) _logger = logging.getLogger(__name__) USB_VENDOR_ID = 0x04B4 USB_PRODUCT_IDS = [0xFD10, 0xFD11, 0xFD12, 0xFD13, 0xFD15] PRODUCT_SOCKET_RANGES = [(0, 0), (1, 1), (1, 4), (1, 4), (1, 4)] USB_CTRL_TRANSFER_TRIES = 5 USB_CTRL_TRANSFER_TIMEOUT = 500 USB_HID_GET_REPORT = 0x01 USB_HID_SET_REPORT = 0x09 USB_HID_REPORT_INPUT = 0x01 USB_HID_REPORT_OUTPUT = 0x02 USB_HID_REPORT_FEATURE = 0x03 class PowerStripUSB(PowerStrip): """Represents an Energenie Power-Strip.""" opened_devices: dict[str, Device] = {} port_dev_mapping: dict[str, str] = {} def __init__(self, dev: UsbDevice) -> None: """Initiate PowerStripUSB device. :param dev: usb device instance :type dev: usb.core.Device :raises UNSUPPORTED_PRODUCT_ID: Given usb device has unsupported product id. """ self.productId: int = dev.idProduct if self.productId not in USB_PRODUCT_IDS: raise UnsupportedProducId self._dev: UsbDevice = dev self._uid: str | None = None _logger.debug(f"active kernel driver: {str(dev.is_kernel_driver_active(0))}") _logger.debug(f"address: {dev.address} bus: {dev.bus} ") minAddr, maxAddr = PRODUCT_SOCKET_RANGES[USB_PRODUCT_IDS.index(self.productId)] self._addrMapping: range = range(minAddr, maxAddr + 1) def release(self) -> None: """Release the usb device.""" PowerStripUSB.opened_devices.pop(self.device_id, None) PowerStripUSB.port_dev_mapping.pop(f"{self._dev.bus}_{self._dev.address}", None) try: dispose_resources(self._dev) except Exception: pass @classmethod def get_implementation_id(cls) -> str: """Return an identifier for this implementation.""" return "EGPS-USB" @property def uid(self) -> str: """Return an identifier for PowerStripUSB devices, read from firmware.""" if self._uid is None: self._uid = self._read_device_id() return self._uid @property def manufacturer(self) -> str: """Return the manufacturer as read from the device.""" return self._dev.manufacturer @property def name(self) -> str: """Return the product name as read from the device.""" return self._dev.product @property def numberOfSockets(self) -> int: """Return number of controllable sockets.""" return len(self._addrMapping) def get_status(self, socket: int) -> bool: """ Get the status of the socket given by 'socket'. @param socket: socket number @return: status """ super().get_status(socket) addr = self._addrMapping[socket] buf: bytes = self._get_feature_report(3 * addr) return (1 & buf[1]) == 1 def switch_off(self, socket: int) -> None: """ Switch the socket with the given id off. @param socket: socket number """ super().switch_off(socket) addr = self._addrMapping[socket] buf = bytes([3 * addr, 0x00]) self._set_feature_report(3 * addr, buf) def switch_on(self, socket: int) -> None: """ Switch the socket with the given id on. @param socket: socket number """ super().switch_on(socket) addr = self._addrMapping[socket] buf = bytes([3 * addr, 0x03]) self._set_feature_report(3 * addr, buf) def _read_device_id(self) -> str: report_id: int = 0x01 id = self._get_feature_report(report_id) _logger.debug(f"The device id is: {id!r}") return ":".join([format(x, "02x") for x in id]) def _get_feature_report(self, report_id: int) -> bytes: bmRequestType: int = CTRL_IN | CTRL_TYPE_CLASS | CTRL_RECIPIENT_INTERFACE bRequest: int = USB_HID_GET_REPORT wValue: int = (USB_HID_REPORT_FEATURE << 8) | (report_id & 255) wIndex: int = 0 wLength: int = 5 ret = self._retry_ctrl_transfer( bmRequestType, bRequest, wValue, wIndex, wLength ) assert isinstance(ret, bytes) return ret def _set_feature_report(self, report_id: int, data: bytes) -> int: bmRequestType: int = CTRL_OUT | CTRL_TYPE_CLASS | CTRL_RECIPIENT_INTERFACE bRequest: int = USB_HID_SET_REPORT wValue: int = (USB_HID_REPORT_FEATURE << 8) | (report_id & 255) wIndex: int = 0 ret = self._retry_ctrl_transfer(bmRequestType, bRequest, wValue, wIndex, data) assert isinstance(ret, int) return ret def _retry_ctrl_transfer( self, bmRequestType: int, bRequest: int, wValue: int, wIndex: int, data_or_wLength: bytes | int, ) -> int | bytes: """Perform ctrl transfer and retry if not successful. The parameters bmRequestType, bRequest, wValue and wIndex are the same of the USB Standard Control Request format. Return the number of bytes written (for OUT transfers) or the data read (for IN transfers), as an array.array object. """ _logger.debug( f"ctrl_transfer: {bmRequestType}, {bRequest}, {wValue}, {data_or_wLength!r}" ) req_in: bool = (bmRequestType & CTRL_IN) == CTRL_IN for i in range(USB_CTRL_TRANSFER_TRIES): try: buf_or_len: bytes | int = self._dev.ctrl_transfer( bmRequestType, bRequest, wValue, wIndex, data_or_wLength, USB_CTRL_TRANSFER_TIMEOUT, ) except usb.core.USBError as e: _logger.debug(f"ctrl_transfer: try number {i}, usb error: {e}") continue if req_in: assert isinstance(buf_or_len, array) if len(buf_or_len) == 0: continue return bytes(buf_or_len) return int(buf_or_len) raise MaximumConnectionTriesReached @classmethod def search_for_devices(cls) -> list[PowerStripUSB]: """List the usb devices which have a known EG-PM product_id.""" devices = [] for prodId in USB_PRODUCT_IDS: try: devices += [ cls(dev) for dev in usb.core.find( find_all=True, idVendor=USB_VENDOR_ID, idProduct=prodId ) if f"{dev.bus}_{dev.address}" not in cls.port_dev_mapping ] except NoBackendError: raise MissingLibrary return devices @classmethod def get_device(cls, device_id: str) -> Device | None: """Try to locate a specific EG-PM device. :param deviceId: The device specific firmware id. :type deviceId: str :return: _description_ :rtype: PowerStripUSB | None """ if device_id in cls.opened_devices: return cls.opened_devices[device_id] candidates = cls.search_for_devices() for dev in candidates: if dev.device_id == device_id: cls.opened_devices[device_id] = dev cls.port_dev_mapping[f"{dev._dev.bus}_{dev._dev.address}"] = device_id return dev return None gnumpi-pyEGPS-57e6bb3/tests/000077500000000000000000000000001457626331700157155ustar00rootroot00000000000000gnumpi-pyEGPS-57e6bb3/tests/__init__.py000066400000000000000000000000371457626331700200260ustar00rootroot00000000000000"""Test Package for pyEGPM.""" gnumpi-pyEGPS-57e6bb3/tests/conftest.py000066400000000000000000000020511457626331700201120ustar00rootroot00000000000000"""Fixtures definitions for pyEGPS tests.""" from __future__ import annotations from array import array from unittest.mock import MagicMock import pytest CTRL_IN = 1 << 7 def get_usb_mock(product_id: int) -> MagicMock: """Create a Mock representing a pyusb device.""" mock = MagicMock() mock.idProduct = product_id mock.manufacturer = "AllFake" mock.product = "Fake-Product" def ctrl_transfer( bmRequestType, bRequest, wValue, wIndex, data_or_wLength, USB_CTRL_TRANSFER_TIMEOUT, ) -> bytes | int: req_in: bool = (bmRequestType & CTRL_IN) == CTRL_IN return array("B", []) if req_in else 0 mock.ctrl_transfer = ctrl_transfer return mock @pytest.fixture def fakeUsbDevice() -> MagicMock: """Return a fake USB device with supported product_id.""" return get_usb_mock(product_id=0xFD15) @pytest.fixture def fakeUnknownUsbDevice() -> MagicMock: """Return a fake USB device with unsupported product_id.""" return get_usb_mock(product_id=0xFD20) gnumpi-pyEGPS-57e6bb3/tests/test_cli.py000066400000000000000000000034021457626331700200740ustar00rootroot00000000000000"""Command line interface (cli) tests for pyEGPS.""" import pytest from unittest.mock import patch from pyegps import cli from pyegps.fakes.powerstrip import FakePowerStrip fake_devices = FakePowerStrip.search_for_devices() @pytest.mark.parametrize( ("device_id", "cli_args", "return_code"), [ # Device not found ("XX:XX:XX:XX", ("set", "--on", "0"), 1), # No socket specified ("DYPS:00:11:22", ("set", "--on"), 1), # Device has sockets 0..3, set socket 3 ("DYPS:AA:BB:CC", ("set", "--on", "3"), 0), # Device has sockets 0..1, set socket 3 ("DYPS:00:11:22", ("set", "--on", "3"), 1), # Device has sockets 0..3, receive status 0..3 ("DYPS:AA:BB:CC", ("status", "0", "1", "2", "3"), 0), # Device has sockets 0..1, receive status 0..3 ("DYPS:00:11:22", ("status", "0", "1", "2", "3"), 1), # Device has sockets 0..3, receive status summary ("DYPS:AA:BB:CC", ("status",), 0), ], ) def test_exit_codes(device_id: str, cli_args: tuple["str"], return_code: int) -> None: """Checking error handling via exit codes.""" with patch("pyegps.cli.search_for_devices", return_value=fake_devices): assert cli.cli(("--device", device_id) + cli_args) == return_code def test_outputs(capsys): """Checking consistency of setting and reading socket status.""" with patch("pyegps.cli.search_for_devices", return_value=fake_devices): # set status and read if it the same cli.cli( ["--device", "DYPS:AA:BB:CC", "set", "--on", "0", "2", "--off", "1", "3"] ) cli.cli(["--device", "DYPS:AA:BB:CC", "status", "0", "1", "2", "3"]) captured = capsys.readouterr() assert captured.out.strip() == "on off on off" gnumpi-pyEGPS-57e6bb3/tests/test_main.py000066400000000000000000000005661457626331700202610ustar00rootroot00000000000000"""Test main functionality.""" from pyegps import DEVICE_IMPLEMENTATIONS def test_implementations_have_unique_ids(): """Test that all device implementations have their unique implementation id.""" unique_ids = [] for impl in DEVICE_IMPLEMENTATIONS: assert (impl_id := impl.get_implementation_id()) is not unique_ids unique_ids.append(impl_id) gnumpi-pyEGPS-57e6bb3/tests/test_usb_socket.py000066400000000000000000000025211457626331700214670ustar00rootroot00000000000000"""Main pyEGPS tests.""" from __future__ import annotations from array import array import pytest from unittest.mock import patch import usb.core from pyegps.usb.eg_powerstrip import PowerStripUSB from pyegps.exceptions import MaximumConnectionTriesReached, MissingLibrary def test_main(fakeUsbDevice): """Dummy Test.""" # check that all device impl have a unique id ps = PowerStripUSB(fakeUsbDevice) assert ps.manufacturer == "AllFake" with pytest.raises(MaximumConnectionTriesReached): _ = ps.device_id with patch.object( fakeUsbDevice, "ctrl_transfer", return_value=array("B", [1, 2, 3]) ): assert ps.device_id == ":".join( [ps.get_implementation_id()] + [format(x, "02x") for x in [1, 2, 3]] ) def test_main_error_check(fakeUsbDevice): """Dummy Test.""" # check that all device impl have a unique id ps = PowerStripUSB(fakeUsbDevice) with patch.object( fakeUsbDevice, "ctrl_transfer", return_value=array("B", [1, 2, 3]), side_effect=usb.core.USBError("Error"), ): with pytest.raises(MaximumConnectionTriesReached): _ = ps.device_id with patch("usb.core.find", side_effect=usb.core.NoBackendError("Error")): with pytest.raises(MissingLibrary): PowerStripUSB.search_for_devices() gnumpi-pyEGPS-57e6bb3/tox.ini000066400000000000000000000034241457626331700160710ustar00rootroot00000000000000[tox] env_list = py{39}, type [testenv] description = Invoke pytest to run automated tests deps = pytest commands = python -m pytest {posargs} [testenv:lint] description = check the code style skip_install = true deps = pre-commit commands = pre-commit run --all-files --show-diff-on-failure [testenv:pylint] deps = pylint commands = pylint --rcfile=tox.ini pyegps [testenv:type] description = type check ourselves deps = mypy passenv = TERM MYPY_FORCE_COLOR MYPY_FORCE_TERMINAL_WIDTH commands = python -m mypy src/pyegps [testenv:{build,clean}] description = build: Build the package in isolation according to PEP517, see https://github.com/pypa/build clean: Remove old distribution files and temporary build artifacts (./build and ./dist) # https://setuptools.pypa.io/en/stable/build_meta.html#how-to-use-it skip_install = True changedir = {toxinidir} deps = build: build[virtualenv] passenv = SETUPTOOLS_* commands = clean: python -c 'import shutil; [shutil.rmtree(p, True) for p in ("build", "dist")]' clean: python -c 'import pathlib, shutil; [shutil.rmtree(p, True) for p in pathlib.Path("src").glob("*.egg-info")]' build: python -m build {posargs} [testenv:publish] description = Publish the package you have been developing to a package index server. By default, it uses testpypi. If you really want to publish your package to be publicly accessible in PyPI, use the `-- --repository pypi` option. skip_install = True changedir = {toxinidir} passenv = # See: https://twine.readthedocs.io/en/latest/ TWINE_USERNAME TWINE_PASSWORD TWINE_REPOSITORY TWINE_REPOSITORY_URL deps = twine commands = python -m twine check dist/* python -m twine upload {posargs:--repository {env:TWINE_REPOSITORY:testpypi}} dist/*