diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..3c7043c --- /dev/null +++ b/.editorconfig @@ -0,0 +1,30 @@ +root = true + +[*] +charset = utf-8 +# end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true +indent_style = tab +indent_size = 2 +tab_width = 2 + + +[*.py] +indent_style = tab +indent_size = 2 + +[*.{yml,yaml}] +indent_style = space +indent_size = 2 + +[*.{json,ini}] +indent_style = tab +indent_size = 2 + +[*.md] +trim_trailing_whitespace = false + +[*.rst] +indent_style = space +indent_size = 3 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..615cdd6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,40 @@ +# Python cache and object files +__pycache__/ +*.py[cod] + +# Coverage.py +.coverage +.cov +coverage.xml +/report/coverage + +# mypy +/report/typing + +# pytest +/report/unit + +# bandit +/report/bandit + +# setuptools +/build/**/*.* +/dist/**/*.* +/*.egg-info + +# Dependencies +!requirements.txt + +# Sphinx +doc/_build/ +doc/pyDeviceAccess/**/*.* +!doc/pyDeviceAccess/index.rst + +# BuildTheDocs +doc/_theme/**/*.* + +# PyCharm project files +/.idea/workspace.xml + +# Git files +!.git* diff --git a/.idea/pyDeviceAccess.iml b/.idea/pyDeviceAccess.iml new file mode 100644 index 0000000..d0876a7 --- /dev/null +++ b/.idea/pyDeviceAccess.iml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..7bafa8e --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,82 @@ +This is a local copy of the Apache License Version 2.0. +The original can be obtained here: [http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0) + +-------------------------------------------------------------------------------- + +# Apache License + +Version 2.0, January 2004 + +## 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: + +- You must give any other recipients of the Work or Derivative Works a copy of this License; and +- You must cause any modified files to carry prominent notices stating that You changed the files; and +- 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 +- 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. + + +## 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. diff --git a/README.md b/README.md index a5c11e6..a506213 100644 --- a/README.md +++ b/README.md @@ -1 +1,44 @@ # pyDeviceAccess + +> [!ATTENTION] +> This is under development. + +## Use Cases + +* Abstract access to devices and registers by Python classes. +* Replace C programs with `mmap` or the usage of `devmem` for testing register accesses. + + +## Examples + +```Python +from pyDeviceAccess import Device, RegisterMode + +with Device(0x8000_0000, size=256) as dev: + ctrl = dev.UInt32(0x00) + status = dev.UInt32(0x04, mode=RegisterMode.READ_ONLY) + fifo = dev.UInt32Array(0x10, count=8, mode=RegisterMode.WRITE_ONLY) + + ctrl.value = 0x0000_0001 + print(hex(status.value)) + + for i, reg in enumerate(fifo): + reg.value = i +``` + + +## Contributors + +* [Patrick Lehmann](https://github.com/Paebbels) (Maintainer) +* [Sven Köhler](https://GitHub.com/skoehler) +* [and more...](https://GitHub.com/pyTooling/pyDeviceAccess/graphs/contributors) + + +## License + +This Python package (source code) is licensed under [Apache License 2.0](LICENSE.md). +The accompanying documentation is licensed under Creative Commons - Attribution-4.0 (CC-BY 4.0). + + +------------------------- +SPDX-License-Identifier: Apache-2.0 diff --git a/dist/requirements.txt b/dist/requirements.txt new file mode 100644 index 0000000..fc810d1 --- /dev/null +++ b/dist/requirements.txt @@ -0,0 +1,2 @@ +wheel ~= 0.46.3 +twine ~= 6.2 diff --git a/pyDeviceAccess/__init__.py b/pyDeviceAccess/__init__.py new file mode 100644 index 0000000..fa88d7c --- /dev/null +++ b/pyDeviceAccess/__init__.py @@ -0,0 +1,508 @@ +# ==================================================================================================================== # +# ____ _ _ # +# _ __ _ _| _ \ _____ _(_) ___ ___ / \ ___ ___ ___ ___ ___ # +# | '_ \| | | | | | |/ _ \ \ / / |/ __/ _ \ / _ \ / __/ __/ _ \/ __/ __| # +# | |_) | |_| | |_| | __/\ V /| | (_| __// ___ \ (_| (_| __/\__ \__ \ # +# | .__/ \__, |____/ \___| \_/ |_|\___\___/_/ \_\___\___\___||___/___/ # +# |_| |___/ # +# ==================================================================================================================== # +# Authors: # +# Patrick Lehmann # +# # +# License: # +# ==================================================================================================================== # +# Copyright 2026-2026 Patrick Lehmann - Bötzingen, Germany # +# # +# 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. # +# # +# SPDX-License-Identifier: Apache-2.0 # +# ==================================================================================================================== # +# +""" +Hardware register abstraction over a physical memory-mapped device. + +Typical usage:: + +.. code-block:: python + + from pyDeviceAccess import Device, RegisterMode + + with Device(0xFF20_0000, size=256) as dev: + ctrl = dev.UInt32(0x00) + status = dev.UInt32(0x04, mode=RegisterMode.READ_ONLY) + fifo = dev.UInt32Array(0x10, count=8, mode=RegisterMode.WRITE_ONLY) + + ctrl.value = 0x0000_0001 + print(hex(status.value)) + for i, reg in enumerate(fifo): + reg.value = i + +.. note:: + + Requires read/write access to the backing device file (default ``/dev/mem``). |br| + On Linux, ``CONFIG_STRICT_DEVMEM`` may restrict which physical addresses are accessible. +""" +# WORKAROUND: Required for Python <=3.13 +from __future__ import annotations + +__author__ = "Patrick Lehmann" +__email__ = "Paebbels@gmail.com" +__copyright__ = "2026-2026, Patrick Lehmann" +__license__ = "Apache License, Version 2.0" +__version__ = "0.1.0" +__keywords__ = ["mmap", "DeviceAccess", "RegisterAccess", "DevMem"] +__issue_tracker__ = "https://GitHub.com/pyTooling/pyDeviceAccess/issues" + +from _ctypes import _SimpleCData +from ctypes import sizeof, pointer, c_uint32, c_uint64, _Pointer +from enum import Enum +from mmap import mmap, ALLOCATIONGRANULARITY, MAP_SHARED, PROT_READ, PROT_WRITE +from os import open as osOpen, close as osClose, O_RDWR, O_SYNC +from typing import TypeAlias, Optional as Nullable, Iterator, TypeVar, Generic, Type + + +class DeviceException(Exception): + """ + Base class for all device-layer exceptions. + + All concrete exceptions in this module derive from this class so callers + can catch the entire hierarchy with a single ``except DeviceException``. + """ + + +class DeviceAccessException(DeviceException): + """ + Raised when a low-level device or memory operation fails. + + The originating OS / ctypes exception is always attached as ``__cause__`` + so the full call chain is available in tracebacks. + """ + + +class AlignmentError(DeviceException): + """Raised when a register offset violates natural-alignment constraints.""" + + +class ReadOnlyException(DeviceException): + """Raised when a write operation is attempted on a :attr:`RegisterMode.READ_ONLY` register.""" + + +class WriteOnlyException(DeviceException): + """Raised when a read operation is attempted on a :attr:`RegisterMode.WRITE_ONLY` register.""" + + +class RegisterMode(Enum): + """ + Permitted access direction for a hardware register. + """ + READ_ONLY = "r" #: Read only; writes raise :exc:`ReadOnlyException`. + WRITE_ONLY = "w" #: Write only; reads raise :exc:`WriteOnlyException`. + READ_WRITE = "rw" #: Both read and write are permitted. + + +# TODO: there is also _CData +CType = TypeVar("CType", bound=_SimpleCData) #: Generic datatype for typehinting registers. + + +# TODO: convert Register to a generic Type and derive specific registers like UInt32Register +class Register(Generic[CType]): + """ + A single, fixed-width hardware register mapped into process address space. + + Instances are normally obtained through :meth:`Device.UInt32`, :meth:`Device.UInt64`, or the corresponding array + factories. Direct construction is possible but discouraged outside of subclasses. + + Natural alignment (offset must be a multiple of the register width in bytes) is enforced at construction time. Access + mode checks are applied on every read and write. + + Example:: + + .. code-block:: python + + ctrl = dev.UInt32(0x00) + ctrl.value = 0xDEAD_BEEF + print(hex(ctrl.value)) + """ + _device: Device + _name: Nullable[str] + _offset: int + _cType: Type[CType] + _ptr: _Pointer[CType] + _mode: RegisterMode + + __slots__ = ('_device', '_name', '_offset', '_ctype', '_ptr', '_mode') + + def __init__( + self, + device: Device, + offset: int, + name: Nullable[str] = None, + cType: Type[CType] = c_uint32, + mode: RegisterMode = RegisterMode.READ_WRITE + ) -> None: + """ + :param device: Parent :class:`Device` that owns this register. + :param offset: Absolute byte offset within *device* |br| + (already includes the intra-page adjustment computed by :class:`Device`). + :param name: Optional, name of the register. + :param cType: :mod:`ctypes` type that defines register width and value representation (``c_uint32`` or + ``c_uint64``). + :param mode: Access constraints; defaults to :attr:`RegisterMode.READ_WRITE`. + :raises AlignmentError: When *offset* is not a multiple of ``sizeof(cType)``. + :raises DeviceAccessException: When ctypes fails to create the in-buffer pointer. + """ + # TODO: type checks on inputs + self._device = device + self._name = name + self._offset = offset + self._ctype = cType + self._mode = mode + + size = sizeof(cType) + if self._offset % size != 0: + raise AlignmentError(f"Unaligned {size * 8}-bit register at offset {hex(offset)}: offset must be a multiple of {size}.") + + try: + self._ptr = pointer(cType.from_buffer(device._mappedMemory, offset)) + except Exception as ex: + raise DeviceAccessException(f"Cannot map {size * 8}-bit register at offset {hex(offset)}.") from ex + + @property + def Device(self) -> Device: + """Parent :class:`Device` that owns this register.""" + return self._device + + @property + def Mode(self) -> RegisterMode: + """Access mode of this register (fixed at construction time).""" + return self._mode + + @property + def Offset(self) -> int: + """Absolute byte offset within the device mapping.""" + return self._offset + + @property + def Size(self) -> int: + """Register width in bytes (4 for ``c_uint32``, 8 for ``c_uint64``).""" + return sizeof(self._cType) + + @property + def Value(self) -> int: + """ + Current hardware register value. + + Reads and writes bypass any software cache and go directly to the + memory-mapped register. + + :raises WriteOnlyException: When :attr:`mode` is :attr:`RegisterMode.WRITE_ONLY`. + :raises DeviceAccessException: When the underlying memory access fails. + """ + if self._mode is RegisterMode.WRITE_ONLY: + raise WriteOnlyException(f"{sizeof(self._cType) * 8}-bit register at offset {hex(self._offset)} is write-only.") + + # TODO: check if device was closed (_ptr gets cleared) + try: + return self._ptr.contents.value # type: ignore[no-any-return] + except Exception as ex: + raise DeviceAccessException(f"Read failed for {sizeof(self._cType) * 8}-bit register at offset {hex(self._offset)}.") from ex + + @Value.setter + def Value(self, value: int) -> None: + """ + :raises ReadOnlyException: When :attr:`mode` is :attr:`RegisterMode.READ_ONLY`. + :raises DeviceAccessException: When the underlying memory access fails. + """ + if self._mode is RegisterMode.READ_ONLY: + raise ReadOnlyException(f"{sizeof(self._cType) * 8}-bit register at offset {hex(self._offset)} is read-only.") + + # TODO: check if device was closed (_ptr gets cleared) + try: + self._ptr.contents.value = value + except Exception as ex: + raise DeviceAccessException(f"Write failed for {sizeof(self._cType) * 8}-bit register at offset {hex(self._offset)}.") from ex + + def __repr__(self) -> str: + return f"" + + # TODO: __str__ ? + + +class RegisterArray(Generic[CType]): + """ + A fixed-length, uniformly typed sequence of contiguous hardware registers. + + All elements share the same :class:`RegisterMode`. The array supports ``len()``, integer indexing (including negative + indices), and iteration. Slicing is intentionally omitted to keep hardware access patterns explicit. + + Instances are normally obtained through :meth:`Device.UInt32Array` or :meth:`Device.UInt64Array`. + + Example:: + + .. code-block:. python + + fifo = dev.UInt32Array(0x10, count=16, mode=RegisterMode.WRITE_ONLY) + for reg in fifo: + reg.value = 0x00 + """ + _device: Device + _name: Nullable[str] + _registers: tuple[Register[CType], ...] + + __slots__ = ('_device', '_name', '_registers') + + def __init__( + self, + device: Device, + offset: int, + count: int, + name: Nullable[str] = None, + cType: Type[CType] = c_uint32, + mode: RegisterMode = RegisterMode.READ_WRITE + ) -> None: + """ + :param device: Parent :class:`Device` instance. + :param offset: Absolute byte offset of the first register within *device*. + :param count: Number of registers; must be ≥ 1. + :param name: Optional, name of the register array. + :param cType: ctypes type for each element. + :param mode: Access mode applied uniformly to every element. + :raises ValueError: When *count* is less than 1. + :raises AlignmentError: When any element offset violates natural alignment. + :raises DeviceAccessException: When any element's pointer cannot be created. + """ + # TODO: type checks on inputs + self._device = device + self._name = name + + if count < 1: + raise ValueError(f"Register array count must be ≥ 1, got {count}.") + + stride = sizeof(cType) + self._registers = tuple(Register(device, offset + i * stride, cType=cType, mode=mode) for i in range(count)) + + def __len__(self) -> int: + return len(self._registers) + + def __getitem__(self, index: int) -> Register[CType]: + """ + Return the register at *index*. + + :param index: Zero-based (or negative) integer index. + :raises TypeError: When *index* is not an ``int``. + :raises IndexError: When *index* is out of range. + """ + if not isinstance(index, int): + raise TypeError(f"Register index must be int, not {type(index).__name__}.") + + try: + return self._registers[index] + except IndexError as ex: + n = len(self._registers) + raise IndexError(f"Register array index {index} out of range [{-n}, {n - 1}].") from ex + + def __iter__(self) -> Iterator[Register[CType]]: + return iter(self._registers) + + def __repr__(self) -> str: + r0 = self._registers[0] + return f"" + + # TODO: __str__ ? + + +class Device: + """ + Memory-mapped hardware device backed by a character device (default: ``/dev/mem``). + + Maps the physical address range ``[baseAddress, baseAddress + size)`` into the process via :class:`mmap`. Because + ``mmap`` requires page-aligned offsets (a multiple of :data:`mmap.ALLOCATIONGRANULARITY`), the mapping may begin at + the page boundary below *baseAddress*; the intra-page delta is tracked internally and added transparently to every + register offset. + + Use as a context manager to guarantee cleanup even if an exception is raised:: + + .. code-block:: python + + with Device(0xFF20_0000, size=256) as dev: + ctrl = dev.UInt32(0x00) + status = dev.UInt32(0x04, mode=RegisterMode.READ_ONLY) + ctrl.value = 0x1 + print(hex(status.value)) + + .. note:: + + ``O_SYNC`` is passed to ``open(2)`` so that writes are not reordered or buffered by the VFS layer — essential for + MMIO semantics. + + ``MAP_SHARED`` is required so that accesses reach the physical device rather than a private copy-on-write mapping. + """ + + _pageAddr: int + _offset: int + _size: int + _fd: int + _mappedMemory: mmap + + __slots__ = ('_pageAddr', '_offset', '_size', '_fd', '_mappedMemory') + + def __init__( + self, + baseAddress: int, + size: int, + devFile: str = "/dev/mem" + ) -> None: + """ + :param baseAddress: Physical base address of the device register block. + :param size: Extent of the register space in bytes; defaults to 4096 (one page on most Linux targets). + :param devFile: Path to the character device; defaults to ``/dev/mem``. + :raises DeviceAccessException: When opening *devFile* fails, or when ``mmap`` cannot establish the physical memory mapping. + """ + # ALLOCATIONGRANULARITY is the correct constant for the mmap offset alignment requirement. On Linux it equals + # PAGESIZE (SC_PAGE_SIZE), but using the semantically correct name guards against platforms where they may differ. + mask = ALLOCATIONGRANULARITY - 1 + self._pageAddr = baseAddress & ~mask + self._offset = baseAddress & mask + # Extend the window so the intra-page tail of the register space is covered. + self._size = size + self._offset + # TODO: original size isn't preserved and accessible via properties. + + try: + self._fd = osOpen(devFile, O_RDWR | O_SYNC) + except OSError as ex: + raise DeviceAccessException(f"Cannot open device file '{devFile}': {ex.strerror}.") from ex + + try: + self._mappedMemory = mmap( + self._fd, + self._size, + MAP_SHARED, + PROT_READ | PROT_WRITE, + offset=self._pageAddr, + ) + except OSError as ex: + osClose(self._fd) # prevent fd leak before re-raising + raise DeviceAccessException(f"Cannot mmap {self._size} bytes at page address {hex(self._pageAddr)}: {ex.strerror}.") from ex + + def UInt32( + self, + offset: int, + name: Nullable[str] = None, + mode: RegisterMode = RegisterMode.READ_WRITE + ) -> Register[c_uint32]: + """ + Create a 32-bit register at *offset* bytes from *baseAddress*. + + :param offset: Byte offset relative to the device base address. + :param mode: Access mode; defaults to :attr:`RegisterMode.READ_WRITE`. + :raises AlignmentError: When *offset* is not 4-byte aligned. + :raises DeviceAccessException: When the ctypes buffer mapping fails. + """ + register = Register(self, self._offset + offset, name, cType=c_uint32, mode=mode) + return register + + def UInt64( + self, + offset: int, + name: Nullable[str] = None, + mode: RegisterMode = RegisterMode.READ_WRITE + ) -> Register[c_uint64]: + """ + Create a 64-bit register at *offset* bytes from *baseAddress*. + + :param offset: Byte offset relative to the device base address. + :param mode: Access mode; defaults to :attr:`RegisterMode.READ_WRITE`. + :raises AlignmentError: When *offset* is not 8-byte aligned. + :raises DeviceAccessException: When the ctypes buffer mapping fails. + """ + return Register(self, self._offset + offset, name, cType=c_uint64, mode=mode) + + def UInt32Array( + self, + offset: int, + count: int, + name: Nullable[str] = None, + mode: RegisterMode = RegisterMode.READ_WRITE + ) -> RegisterArray[c_uint32]: + """ + Create a contiguous array of *count* 32-bit registers from *offset*. + + :param offset: Byte offset of the first register, relative to *baseAddress*. + :param count: Number of registers; must be ≥ 1. + :param mode: Access mode applied uniformly to all elements. + :raises ValueError: When *count* is less than 1. + :raises AlignmentError: When the base offset or any element is not 4-byte aligned. + :raises DeviceAccessException: When any element mapping fails. + """ + return RegisterArray(self, self._offset + offset, count, name, cType=c_uint32, mode=mode) + + def UInt64Array( + self, + offset: int, + count: int, + name: Nullable[str] = None, + mode: RegisterMode = RegisterMode.READ_WRITE + ) -> RegisterArray[c_uint64]: + """ + Create a contiguous array of *count* 64-bit registers from *offset*. + + :param offset: Byte offset of the first register, relative to *baseAddress*. + :param count: Number of registers; must be ≥ 1. + :param mode: Access mode applied uniformly to all elements. + :raises ValueError: When *count* is less than 1. + :raises AlignmentError: When the base offset or any element is not 8-byte aligned. + :raises DeviceAccessException: When any element mapping fails. + """ + return RegisterArray(self, self._offset + offset, count, name, cType=c_uint64, mode=mode) + + def Close(self) -> None: + """ + Unmap the memory region and release the file descriptor. + + Both operations are attempted regardless of individual failures so that a failing :meth:`mmap.close` does not leak + the file descriptor. If either operation raises, a :exc:`DeviceAccessException` is raised after both have been + attempted; the first error is attached as ``__cause__``. + + :raises DeviceAccessException: When ``mmap.close()`` or ``os.close()`` fails. + """ + firstEx = None + # TODO: clear pointers in registers to None; requires a list of derived registers. + + try: + self._mappedMemory.close() + except Exception as ex: + firstEx = ex + finally: + try: + osClose(self._fd) + except OSError as ex: + if firstEx is None: + firstEx = ex + + if firstEx is not None: + raise DeviceAccessException(f"Error(s) while closing device at page address {hex(self._pageAddr)}.") from firstEx + + def __enter__(self) -> Device: + return self + + def __exit__( + self, + excType: type[BaseException] | None, + excVal: BaseException | None, + excTb: object + ) -> None: + self.Close() + + def __repr__(self) -> str: + # TODO: include state + return f"" diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..3c2e17a --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,115 @@ +[build-system] +requires = [ + "setuptools >= 80.0", +] +build-backend = "setuptools.build_meta" + +[tool.pylint.format] +indent-string="\t" +max-line-length = 120 +ignore-long-lines = "^.{0,110}#: .*" + +[tool.pylint.basic] +argument-naming-style = "camelCase" +attr-naming-style = "camelCase" +class-attribute-naming-style = "camelCase" +class-const-naming-style = "UPPER_CASE" +class-naming-style = "PascalCase" +const-naming-style = "UPPER_CASE" +function-naming-style = "camelCase" +inlinevar-naming-style = "camelCase" +method-naming-style = "PascalCase" +module-naming-style = "any" +variable-naming-style = "camelCase" + +[tool.mypy] +packages = ["pyDeviceAccess"] +python_version = "3.14" +strict = true +pretty = true +show_error_context = true +show_error_codes = true +namespace_packages = true +html_report = "report/typing/html" +junit_xml = "report/typing/StaticTypingSummary.xml" +cobertura_xml_report = "report/typing" + +[tool.pytest] +addopts = ["--tb=native"] +# Don't set 'python_classes = *' otherwise, pytest doesn't search for classes +# derived from unittest.Testcase +python_files = ["*"] +python_functions = ["test_*"] +filterwarnings = [ + "error::DeprecationWarning", + "error::PendingDeprecationWarning" +] +junit_xml = "report/unit/UnittestReportSummary.xml" +junit_logging = "all" + +[tool.pyedaa-reports] +junit_xml = "report/unit/unittest.xml" + +#[tool.pylint.main] +#disable = ["protected-access"] +# +#[tool.pylint.basic] +#module-naming-style = "PascalCase" +#const-naming-style = "UPPER_CASE" +#variable-naming-style = "camelCase" +#function-naming-style = "camelCase" +#argument-naming-style = "camelCase" +#class-naming-style = "PascalCase" +#class-const-naming-style = "UPPER_CASE" +#class-attribute-naming-style = "camelCase" +#method-naming-style = "PascalCase" +#inlinevar-naming-style = "any" +#attr-naming-style = "PascalCase" +#good-names = ["_", "i", "ex"] +# +#[tool.pylint.format] +#max-line-length = 120 +#indent-string = "\t" + +[tool.interrogate] +color = true +verbose = 1 # possible values: 0 (minimal output), 1 (-v), 2 (-vv) +fail-under = 59 +exclude = [ + "build", + "dist", + "doc", + "tests", + "setup.py" +] +ignore-setters = true + +[tool.coverage.run] +branch = true +relative_files = true +omit = [ + "*site-packages*", + "setup.py", + "tests/unit/*" +] + +[tool.coverage.report] +skip_covered = false +skip_empty = true +exclude_lines = [ + "pragma: no cover", + "raise NotImplementedError" +] +omit = [ + "tests/*" +] + +[tool.coverage.xml] +output = "report/coverage/coverage.xml" + +[tool.coverage.json] +output = "report/coverage/coverage.json" + +[tool.coverage.html] +directory = "report/coverage/html" +title="Code Coverage of pyDeviceAccess" diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..e69de29 diff --git a/run.ps1 b/run.ps1 new file mode 100644 index 0000000..66418ef --- /dev/null +++ b/run.ps1 @@ -0,0 +1,454 @@ +[CmdletBinding()] +Param( +# Clean up all files and directories + [switch]$clean, + +# Commands + [switch]$all, + [switch]$alldoc, + [switch]$copyall, + + [switch]$doc, + [switch]$livedoc, + [switch]$html, + [switch]$latex, + [switch]$pdf, + [switch]$doccov, + + [switch]$unit, + [switch]$liveunit, + [switch]$copyunit, + + [switch]$cov, + [switch]$livecov, + [switch]$copycov, + + [switch]$type, + [switch]$livetype, + [switch]$copytype, + + [switch]$nooutput, + + [switch]$build, + [switch]$install, + +# Display this help" + [switch]$help +) + +$ProjectName = "pyDeviceAccess" +$PackageName = $ProjectName +$PackageVersion = "0.1.0" +$PythonVersion = "3.14" +$LaTeXDocument = "${ProjectName}.tex" + +# set default values +$EnableDebug = [bool]$PSCmdlet.MyInvocation.BoundParameters["Debug"] +$EnableVerbose = [bool]$PSCmdlet.MyInvocation.BoundParameters["Verbose"] -or $EnableDebug + +# Display help if no command was selected +$help = $help -or ( -not ( + $all -or $alldoc -or $copyall -or + $clean -or + $doc -or $livedoc -or $doccov -or $html -or $latex -or $pdf -or + $unit -or $liveunit -or $copyunit -or + $cov -or $livecov -or $copycov -or + $type -or $livetype -or $copytype -or + $build -or $install + ) +) + +Write-Host "================================================================================" -ForegroundColor Magenta +Write-Host "$ProjectName Documentation Compilation and Assembly Tool" -ForegroundColor Magenta +Write-Host "================================================================================" -ForegroundColor Magenta + +if ($help) { + Get-Help $MYINVOCATION.MyCommand.Path -Detailed + exit 0 +} + +if ($all) { + $doc = $true + $html = $true + $latex = $true + $pdf = $true + $unit = $false + $copyunit = $false + $cov = $true + $copycov = $false + $type = $true + $copytype = $true +} elseif ($alldoc) { + $doc = $true + $html = $true + $latex = $true + $pdf = $true +} + +if ($livecov -or $liveunit) { + $cov = $unit = $false +} +if ($livecov -or $cov) { + $liveunit = $unit = $false +} + +if (($doc -or $alldoc -or $livedoc) -and -not ($html -or $latex -or $pdf)) { + $html = $true +} + +if ($copyall) { + $copyunit = $false + $copycov = $false + $copytype = $true +} + +if ($clean) { + Write-Host -ForegroundColor DarkYellow "[live][DOC] Cleaning documentation directories ..." + Remove-Item -Recurse -Force .\doc\_build\* -ErrorAction SilentlyContinue + Remove-Item -Recurse -Force .\doc\$PackageName\* -ErrorAction SilentlyContinue + + Write-Host -ForegroundColor DarkYellow "[live][BUILD] Cleaning build directories ..." + Remove-Item -Recurse -Force .\build\bdist.win-amd64 -ErrorAction SilentlyContinue + Remove-Item -Recurse -Force .\build\lib -ErrorAction SilentlyContinue +} + +if ($build) { + Write-Host -ForegroundColor Yellow "[live][BUILD] Cleaning build directories ..." + Remove-Item -Recurse -Force .\build\bdist.win-amd64 -ErrorAction SilentlyContinue + Remove-Item -Recurse -Force .\build\lib -ErrorAction SilentlyContinue + + Write-Host -ForegroundColor Yellow "[live][BUILD] Building $PackageName package as wheel ..." + py -$PythonVersion -m build --wheel --no-isolation + + Write-Host -ForegroundColor Yellow "[live][BUILD] Building wheel finished" +} +if ($install) { + if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]"Administrator")) { + Write-Host -ForegroundColor Yellow "[live][INSTALL] Installing $PackageName with administrator rights ..." + $proc = Start-Process pwsh.exe "-NoProfile -ExecutionPolicy Bypass -WorkingDirectory `"$PSScriptRoot`" -File `"$PSCommandPath`" `"-install`"" -Verb RunAs -Wait + + # Write-Host -ForegroundColor Yellow "[live][INSTALL] Wait on administrator console ..." + # Wait-Process -Id $proc.Id + } else { + Write-Host -ForegroundColor Cyan "[ADMIN][UNINSTALL] Uninstalling $PackageName ..." + py -$PythonVersion -m pip uninstall -y $PackageName + Write-Host -ForegroundColor Cyan "[ADMIN][INSTALL] Installing $PackageName from wheel ..." + py -$PythonVersion -m pip install .\dist\$PackageName-$PackageVersion-py3-none-any.whl + + Write-Host -ForegroundColor Cyan "[ADMIN][INSTALL] Closing window in 5 seconds ..." + Start-Sleep -Seconds 5 + } +} + +$runUnitCopyFunc = { + param($live) + + cp -Recurse -Force .\report\unit\html\* .\doc\_build\html\unittests + if ($live) { + Write-Host -ForegroundColor DarkBlue "[live][UNIT] Copyed unit testing report to 'unittests' directory in HTML directory" + } +} +$runUnitFunc = { + param($live, $copy, $runCopyStr) + + $runCopyFunc = [ScriptBlock]::Create($runCopyStr) + + $env:PYTHONPATH="." + $env:ENVIRONMENT_NAME = "Windows (x86-64)" + pytest -raP --color=yes --template=html1/index.html --report=report/unit/html/index.html --split-report tests/unit + + if ($copy) { + & $runCopyFunc $live + } +} + +$runCovCopyFunc = { + param($live) + + cp -Recurse -Force .\report\coverage\html\* .\doc\_build\html\coverage + if ($live) { + Write-Host -ForegroundColor DarkMagenta "[live][COV] Copyed code coverage report to 'coverage' directory in HTML directory" + } +} +$runCovFunc = { + param($live, $copy, $runCopyStr) + + $runCopyFunc = [ScriptBlock]::Create($runCopyStr) + + $env:PYTHONPATH="." + $env:ENVIRONMENT_NAME = "Windows (x86-64)" + coverage run --data-file=.coverage --rcfile=pyproject.toml -m pytest -ra --color=yes tests/unit + + if ($live) { + Write-Host -ForegroundColor DarkMagenta "[live][COV] Convert coverage report to HTML ..." + } + coverage html + + if ($live) { + Write-Host -ForegroundColor DarkMagenta "[live][COV] Convert coverage report to XML (Cobertura) ..." + } + coverage xml + + if ($live) { + Write-Host -ForegroundColor DarkMagenta "[live][COV] Convert coverage report to JSON ..." + } + coverage json + + if ($live) { + Write-Host -ForegroundColor DarkMagenta "[live][COV] Write coverage report to console ..." + } + coverage report + + if ($copy) { + & $runCopyFunc $live + } +} + +$runTypingCopyFunc = { + param($live) + + cp -Recurse -Force .\report\typing\* .\doc\_build\html\typing + if ($live) { + Write-Host -ForegroundColor DarkCyan "[live][TYPE] Copyed typing report to 'typing' directory in HTML directory." + } +} +$runTypingFunc = { + param($PackageName, $live, $copy, $runCopyStr) + + $runCopyFunc = [ScriptBlock]::Create($runCopyStr) + + $env:MYPY_FORCE_COLOR = 1 + mypy.exe --platform linux -p $PackageName + + if ($copy) { + & $runCopyFunc $live + } +} + +$compileHTMLDocFunc = { + param($PyVersion, $live, $copyUnit, $copyCov, $copyType, [scriptblock]$runUnitCopyFunc, [scriptblock]$runCovCopyFunc, [scriptblock]$runTypingCopyFunc) + + Push-Location "doc" + py -$PyVersion -m sphinx.cmd.build --builder html --write-all --doctree-dir _build/doctrees-html --jobs 8 --warning-file _build/sphinx-html-warnings.log --verbose . _build/html + Pop-Location + + if ($copyUnit) { + & $runUnitCopyFunc $live + } + if ($copyCov) { + & $runCovCopyFunc $live + } + if ($copyType) { + & $runTypingCopyFunc $live + } +} +$compileLaTeXDocFunc = { + param($PyVersion, $LaTeXDocument) + + Push-Location "doc" + py -$PyVersion -m sphinx.cmd.build --builder latex --write-all --doctree-dir _build/doctrees-latex --jobs 8 --warning-file _build/sphinx-latex-warnings.log --verbose . _build/latex + + Move-Item -Force "_build/latex/doc-CC--BY_41.0-green" "_build/latex/doc-CC--BY_41_0-green.png" + + $texFile = Get-Content "_build/latex/$LaTeXDocument" + $texFile.Replace('{{doc-CC--BY_41}.0-green}}', '{{doc-CC--BY_41_0-green}.png}}') | Set-Content "_build/latex/$LaTeXDocument" + + Pop-Location +} +$compilePDFDocFunc = { + param($Document) + + if (Test-Path -Path "doc/_build/latex" -PathType Container) { + Push-Location "doc/_build/latex" + latexmk -C + # --latexoption=--cnf-line=max_print_line=1000 + latexmk --lualatex --latexoption=--c-style-errors --interaction=nonstopmode --halt-on-error $Document + Pop-Location + } else { + Write-Host -ForegroundColor Yellow "No LaTeX source directory 'doc/_build/latex' found." + } +} + +# Unit testing (with/without code coverage) +if ($livecov) { + Write-Host -ForegroundColor DarkMagenta "[live][COV] Running Unit Tests using pytest with coverage ..." + & $runCovFunc $true $copycov $runCovCopyFunc + Write-Host -ForegroundColor DarkYellow "[live][COV] Unit Tests finished" +} elseif ($liveunit) { + Write-Host -ForegroundColor DarkYellow "[live][UNIT] Running Unit Tests using pytest ..." + & $runUnitFunc $true $copyunit $runUnitCopyFunc + Write-Host -ForegroundColor DarkYellow "[live][UNIT] Unit Tests finished" +} elseif ($cov) { + Write-Host -ForegroundColor DarkYellow "[Job1][COV] Running Unit Tests using pytest with coverage ..." + Write-Host -ForegroundColor DarkGreen "[SCRIPT] Starting Coverage jobs ..." + $testJob = Start-Job -Name "Coverage" -ScriptBlock $runCovFunc -ArgumentList $false, $copycov, $runCovCopyFunc +} elseif ($unit) { + Write-Host -ForegroundColor DarkYellow "[Job1][UNIT] Running Unit Tests using pytest ..." + Write-Host -ForegroundColor DarkGreen "[SCRIPT] Starting UnitTests jobs ..." + $testJob = Start-Job -Name "UnitTests" -ScriptBlock $runUnitFunc -ArgumentList $false, $copyunit, $runUnitCopyFunc +} + +# Static type checking +if ($livetype) { + Write-Host -ForegroundColor DarkCyan "[live][TYPE] Running static type analysis using mypy ..." + & $runTypingFunc $PackageName $true $copytype $runTypingCopyFunc + Write-Host -ForegroundColor DarkCyan "[live][TYPE] Static type analysis finished" +} elseif ($type) { + Write-Host -ForegroundColor DarkCyan "[Job2][TYPE] Running static type analysis using mypy ..." + Write-Host -ForegroundColor DarkCyan "[SCRIPT] Starting TypeChecking jobs ..." + $typingJob = Start-Job -Name "TypeChecking" -ScriptBlock $runTypingFunc -ArgumentList $PackageName, $false, $copytype, $runTypingCopyFunc +} + +# Documentation generation +if ($livedoc) { + if ($typingJob) { + $null = Wait-Job -Job $typingJob + Write-Host "[live][DOC] Awaited Job2:TypeChecking" + } + if ($testJob) { + $null = Wait-Job -Job $testJob + Write-Host "[live][DOC] Awaited Job1:Test" + } + + Write-Host -ForegroundColor DarkYellow "[live][DOC] Building documentation using Sphinx ..." + if ($html) { + Write-Host -ForegroundColor DarkYellow "[live][HTML] Building HTML documentation using Sphinx ..." + & $compileHTMLDocFunc $PythonVersion $true $copyunit $copycov $copytype $runUnitCopyFunc $runCovCopyFunc $runTypingCopyFunc + } + if ($latex) { + Write-Host -ForegroundColor DarkYellow "[live][LaTeX] Building LaTeX documentation using Sphinx ..." + & $compileLaTeXDocFunc $PythonVersion $LaTeXDocument + } + if ($pdf) { + Write-Host -ForegroundColor DarkYellow "[live][PDF] Building PDF documentation using LuaLaTeX ..." + & $compilePDFDocFunc $LaTeXDocument + } + Write-Host -ForegroundColor DarkYellow "[live][DOC] Documentation finished" +} else { + if ($html -or $latex -or $pdf) { + Write-Host -ForegroundColor DarkGreen "[SCRIPT] Starting Documentation jobs ..." + } + + if ($html) { + Write-Host -ForegroundColor DarkYellow "[Job3][HTML] Building HTML documentation using Sphinx (waiting on Job1:Testing and Job2:Typing) ..." + $docHTMLJob = Start-Job -Name "HTMLDoc" -ScriptBlock { + param($typingJob, $testJob, $compileDocStr, $PyVersion, $copyUnit, $copyCov, $copyType, $runUnitCopyStr, $runCovCopyStr, $runTypingCopyStr) + + $compileDocFunc = [ScriptBlock]::Create($compileDocStr) + $runUnitCopyFunc = [ScriptBlock]::Create($runUnitCopyStr) + $runCovCopyFunc = [ScriptBlock]::Create($runCovCopyStr) + $runTypingCopyFunc = [ScriptBlock]::Create($runTypingCopyStr) + + if ($typingJob) { + $null = Wait-Job -Job $typingJob + Write-Host "[Job3][HTML] Awaited Job2:TypeChecking" + } + if ($testJob) { + $null = Wait-Job -Job $testJob + Write-Host "[Job3][HTML] Awaited Job1:Test" + } + + & $compileDocFunc $PyVersion $false $copyUnit $copyCov $copyType $runUnitCopyFunc $runCovCopyFunc $runTypingCopyFunc + } -ArgumentList $typingJob, $testJob, $compileHTMLDocFunc, $PythonVersion, $copyunit, $copycov, $copytype, $runUnitCopyFunc, $runCovCopyFunc, $runTypingCopyFunc + } + if ($latex) { + Write-Host -ForegroundColor DarkYellow "[Job4][LaTeX] Building LaTeX documentation using Sphinx (waiting on Job1:Testing and Job2:Typing) ..." + $docLaTeXJob = Start-Job -Name "LaTeXDoc" -ScriptBlock { + param($typingJob, $testJob, $compileDocStr, $PyVersion, $LaTeXDocument) + + $compileDocFunc = [ScriptBlock]::Create($compileDocStr) + + if ($typingJob) { + $null = Wait-Job -Job $typingJob + Write-Host "[Job4][LaTeX] Awaited Job2:TypeChecking" + } + if ($testJob) { + $null = Wait-Job -Job $testJob + Write-Host "[Job4][LaTeX] Awaited Job1:Test" + } + + & $compileDocFunc $PyVersion $LaTeXDocument + } -ArgumentList $typingJob, $testJob, $compileLaTeXDocFunc, $PythonVersion, $LaTeXDocument + } + if ($pdf) { + Write-Host -ForegroundColor DarkYellow "[Job5][PDF] Building PDF documentation using LuaLaTex (waiting on Job4:LaTeX) ..." + $docPDFJob = Start-Job -Name "PDFDoc" -ScriptBlock { + param($docLaTeXJob, $compileDocStr, $LaTeXDocument) + + $compileDocFunc = [ScriptBlock]::Create($compileDocStr) + + if ($docLaTeXJob) { + $null = Wait-Job -Job $docLaTeXJob + Write-Host "[Job5][PDF] Awaited Job4:LaTeX" + } + & $compileDocFunc $LaTeXDocument + } -ArgumentList $docLaTeXJob, $compilePDFDocFunc, $LaTeXDocument + } +} + +# Await jobs +if ($typingJob) { + Write-Host -ForegroundColor DarkGreen "[SCRIPT] Waiting on TypeChecking job ..." + $null = Wait-Job -Job $typingJob + Write-Host -ForegroundColor DarkYellow "[Job2][TYPE] Static type checking finished" +} +if ($testJob) { + Write-Host -ForegroundColor DarkGreen "[SCRIPT] Waiting on unit testing job ..." + $null = Wait-Job -Job $testJob + Write-Host -ForegroundColor DarkYellow "[Job1][TEST] Unit testing finished" +} +if ($docHTMLJob) { + Write-Host -ForegroundColor DarkGreen "[SCRIPT] Waiting on HTML Documentation job ..." + $null = Wait-Job -Job $docHTMLJob + Write-Host -ForegroundColor DarkYellow "[Job3][HTML] HTML Documentation finished" +} +if ($docLaTeXJob) { + Write-Host -ForegroundColor DarkGreen "[SCRIPT] Waiting on LaTeX Documentation job ..." + $null = Wait-Job -Job $docLaTeXJob + Write-Host -ForegroundColor DarkYellow "[Job4][LaTeX] LaTeX Documentation finished" +} +if ($docPDFJob) { + Write-Host -ForegroundColor DarkGreen "[SCRIPT] Waiting on PDF Documentation job ..." + $null = Wait-Job -Job $docPDFJob + Write-Host -ForegroundColor DarkYellow "[Job5][PDF] PDF Documentation finished" +} + +# Write collected outputs +if ($typingJob) { + Write-Host -ForegroundColor DarkCyan "================================================================================" + if (-not $nooutput) { + Receive-Job -Job $typingJob + } + Remove-Job -Job $typingJob +} +if ($docHTMLJob) { + Write-Host -ForegroundColor DarkYellow "================================================================================" + if (-not $nooutput) { + Receive-Job -Job $docHTMLJob + } + Remove-Job -Job $docHTMLJob +} +if ($docLaTeXJob) { + Write-Host -ForegroundColor DarkYellow "================================================================================" + if (-not $nooutput) { + Receive-Job -Job $docLaTeXJob + } + Remove-Job -Job $docLaTeXJob +} +if ($docPDFJob) { + Write-Host -ForegroundColor DarkYellow "================================================================================" + if (-not $nooutput) { + Receive-Job -Job $docPDFJob + } + Remove-Job -Job $docPDFJob +} +if ($testJob) { + Write-Host -ForegroundColor DarkBlue "================================================================================" + if (-not $nooutput) { + Receive-Job -Job $testJob + } + Remove-Job -Job $testJob +} + +Write-Host -ForegroundColor DarkGreen "================================================================================" +Write-Host -ForegroundColor DarkGreen "[SCRIPT] Finished" diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..e5c2afe --- /dev/null +++ b/setup.py @@ -0,0 +1,66 @@ +# ==================================================================================================================== # +# ____ _ _ # +# _ __ _ _| _ \ _____ _(_) ___ ___ / \ ___ ___ ___ ___ ___ # +# | '_ \| | | | | | |/ _ \ \ / / |/ __/ _ \ / _ \ / __/ __/ _ \/ __/ __| # +# | |_) | |_| | |_| | __/\ V /| | (_| __// ___ \ (_| (_| __/\__ \__ \ # +# | .__/ \__, |____/ \___| \_/ |_|\___\___/_/ \_\___\___\___||___/___/ # +# |_| |___/ # +# ==================================================================================================================== # +# Authors: # +# Patrick Lehmann # +# # +# License: # +# ==================================================================================================================== # +# Copyright 2026-2026 Patrick Lehmann - Bötzingen, Germany # +# # +# 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. # +# # +# SPDX-License-Identifier: Apache-2.0 # +# ==================================================================================================================== # +# +""" +Package installer for 'pyDeviceAccess a low-level device memory and register abstraction.'. +""" +# Add package itself to PYTHON_PATH, so it can be used to package itself. +from os.path import dirname +from sys import path as sys_path +sys_path.insert(0, dirname(__file__)) + +from setuptools import setup + +from pathlib import Path +from pyTooling.Packaging import DescribePythonPackageHostedOnGitHub + +gitHubNamespace = "pyTooling" +packageName = "pyDeviceAccess" +packageDirectory = packageName +packageInformationFile = Path(f"{packageDirectory}/__init__.py") + +setup( + **DescribePythonPackageHostedOnGitHub( + packageName=packageName, + description="pyDeviceAccess a low-level device memory and register abstraction.", + gitHubNamespace=gitHubNamespace, + unittestRequirementsFile=Path("tests/requirements.txt"), + # additionalRequirements={ + # "terminal": ["colorama ~= 0.4.6"], + # "yaml": ["ruamel.yaml ~= 0.19"], + # }, + sourceFileWithVersion=packageInformationFile, + pythonVersions=("3.11", "3.12", "3.13", "3.14"), + dataFiles={ + packageName: ["py.typed"] + }, + debug=True + ) +) diff --git a/tests/requirements.txt b/tests/requirements.txt new file mode 100644 index 0000000..e9c2fe8 --- /dev/null +++ b/tests/requirements.txt @@ -0,0 +1,2 @@ +-r unit/requirements.txt +-r typing/requirements.txt diff --git a/tests/typing/requirements.txt b/tests/typing/requirements.txt new file mode 100644 index 0000000..95ab13e --- /dev/null +++ b/tests/typing/requirements.txt @@ -0,0 +1,6 @@ +-r ../../requirements.txt + +# Static Type Checking +mypy[reports] ~= 1.19 +typing_extensions ~= 4.15 +lxml >= 5.4, <7.0 diff --git a/tests/unit/__init__.py b/tests/unit/__init__.py new file mode 100644 index 0000000..740e1e0 --- /dev/null +++ b/tests/unit/__init__.py @@ -0,0 +1,30 @@ +# ==================================================================================================================== # +# ____ _ _ # +# _ __ _ _| _ \ _____ _(_) ___ ___ / \ ___ ___ ___ ___ ___ # +# | '_ \| | | | | | |/ _ \ \ / / |/ __/ _ \ / _ \ / __/ __/ _ \/ __/ __| # +# | |_) | |_| | |_| | __/\ V /| | (_| __// ___ \ (_| (_| __/\__ \__ \ # +# | .__/ \__, |____/ \___| \_/ |_|\___\___/_/ \_\___\___\___||___/___/ # +# |_| |___/ # +# ==================================================================================================================== # +# Authors: # +# Patrick Lehmann # +# # +# License: # +# ==================================================================================================================== # +# Copyright 2026-2026 Patrick Lehmann - Bötzingen, Germany # +# # +# 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. # +# # +# SPDX-License-Identifier: Apache-2.0 # +# ==================================================================================================================== # +# diff --git a/tests/unit/requirements.txt b/tests/unit/requirements.txt new file mode 100644 index 0000000..b20db85 --- /dev/null +++ b/tests/unit/requirements.txt @@ -0,0 +1,8 @@ +-r ../../requirements.txt + +# Coverage collection +Coverage ~= 7.13 + +# Test Runner +pytest ~= 9.0 +pytest-cov ~= 7.1