### Configure, Build, and Install PyTango with CMake Presets Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/BUILD.md Build the `_pytango.so` library using CMake presets. This example configures the build in 'Debug' mode, specifies an installation directory, and optionally installs the library. Requires `CMakeUserPresets.json`. ```shell mkdir install # optional: if you want to test installed lib locally cmake --preset=dev -DCMAKE_INSTALL_PREFIX=$(pwd)/install # configuring - the install prefix is optional cmake --build --preset=dev # building cmake --build --preset=dev --target install # optionally install the library ls install/pytango/ _pytango.9.4.0.so _pytango.9.so _pytango.so ``` -------------------------------- ### Start PyTango Server Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/doc/tutorial/servers.md Execute this command to start a PyTango server. The server name and tango class should match. ```console $ python Clock.py test Ready to accept request ``` -------------------------------- ### Start Docker Services Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/examples/training/README.md Starts the PyTango training environment services using Docker Compose. Press CTRL+C to stop. ```bash docker-compose up ``` -------------------------------- ### Start Power Supply Simulator Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/examples/training/README.md Starts the power supply simulator script, which listens on port 45000 for incoming connections. ```bash docker-compose exec cli /training/server/ps-simulator.py ``` -------------------------------- ### Install PyTango using pip Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/README.rst Install PyTango from PyPI using pip. This is the recommended method for most users. ```bash $ python -m pip install pytango ``` -------------------------------- ### Setup Python Virtual Environment for Build Tools Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/BUILD.md Create and activate a Python virtual environment to install necessary developer tools like clang-tidy, clang-format, numpy, and cmake. Ensure cmake is only installed via pip if not already available to avoid conflicts. ```shell cd pytango/ # if you're not already here... user@computer pytango $ python3.11 -m venv venv user@computer pytango $ source venv/bin/activate pip install clang-tidy clang-format numpy pip list Package Version ------------ -------- clang-format 15.0.7 clang-tidy 15.0.2.1 ninja 1.11.1 numpy 1.24.1 pip 22.3.1 setuptools 65.6.3 pip install cmake # ONLY IF CMAKE IS NOT ALREADY AVAILABLE ``` -------------------------------- ### Get Property Example in PyTango Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/doc/api/data_types.md Demonstrates how to retrieve properties using the PyTango database object. The result is always a list. ```python import tango db = tango.Database() s = db.get_property(["TangoSynchrotrons"]) print type(s) ``` -------------------------------- ### Build PyTango with CI Presets Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/BUILD.md Build the `_pytango.so` library in 'Release' mode using CI presets when `CMakeUserPresets.json` is not available. This example uses a 'ci-macOS' preset and requires specifying the Tango installation root. ```shell cmake --preset=ci-macOS -DTango_ROOT=/path/to/installed/tango.9.4 cmake --build --preset=dev ``` -------------------------------- ### Build and Install Pytango with Pixi Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/BUILD.md This sequence of commands clones the pytango repository, changes the directory, and then uses pixi to run the install command. This automatically creates the default environment with necessary requirements and installs pytango in editable mode with debug symbols. ```shell git clone --recurse-submodules https://gitlab.com/tango-controls/pytango.git cd pytango pixi run install ``` -------------------------------- ### Start and Configure Tracing at Runtime Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/doc/how-to/telemetry.md Use DeviceProxy convenience methods to start telemetry, enable tracing, set topics, and configure tracing endpoints dynamically at runtime. This allows for live adjustments without restarting the device server. ```python import tango from tango.telemetry import TelemetryEndpoint, TelemetryExporter proxy = tango.DeviceProxy("sys/tg_test/1") proxy.start_telemetry() proxy.set_telemetry_tracing(True) proxy.set_telemetry_topics(["user"]) proxy.set_telemetry_tracing_endpoints( [ TelemetryEndpoint( TelemetryExporter.HTTP, "https://traces.example.org:4319/v1/traces", ) ] ) ``` -------------------------------- ### PyTango PowerSupply Device Server Example Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/doc/tutorial/servers.md This example demonstrates a comprehensive PyTango device server for a PowerSupply. It includes device properties, class properties, initialization, and various attribute types (read/write, read-only, scalar, image) with different configurations. It also shows how to define commands and use pythonic-style decorators for attribute definition. ```python from time import time from numpy.random import random_sample from tango import AttrQuality, AttrWriteType, DevState, DispLevel, AttReqType from tango.server import Device, attribute, command from tango.server import class_property, device_property class PowerSupply(Device): _my_current = 2.3456 _my_range = 0.0 _my_compliance = 0.0 _output_on = False host = device_property(dtype=str) port = class_property(dtype=int, default_value=9788) def init_device(self): super().init_device() self.info_stream(f"Power supply connection details: {self.host}:{self.port}") self.set_state(DevState.ON) self.set_status("Power supply is ON") current = attribute( label="Current", dtype=float, display_level=DispLevel.EXPERT, access=AttrWriteType.READ_WRITE, unit="A", format="8.4f", min_value=0.0, max_value=8.5, min_alarm=0.1, max_alarm=8.4, min_warning=0.5, max_warning=8.0, fget="get_current", fset="set_current", doc="the power supply current", ) noise = attribute( label="Noise", dtype=((float,),), max_dim_x=1024, max_dim_y=1024, fget="get_noise", ) @attribute def voltage(self): return 10.0 def get_current(self): return self._my_current def set_current(self, current): print("Current set to %f" % current) self._my_current = current def get_noise(self): return random_sample((1024, 1024)) range = attribute(label="Range", dtype=float) @range.setter def range(self, new_range): self._my_range = new_range @range.getter def current_range(self): return self._my_range, time(), AttrQuality.ATTR_WARNING @range.is_allowed def can_range_be_changed(self, req_type): if req_type == AttReqType.WRITE_REQ: return not self._output_on return True compliance = attribute(label="Compliance", dtype=float) @compliance.read def compliance(self): return self._my_compliance @compliance.write def new_compliance(self, new_compliance): self._my_compliance = new_compliance @command(dtype_in=bool, dtype_out=bool) def output_on_off(self, on_off): self._output_on = on_off return self._output_on if __name__ == "__main__": PowerSupply.run_server() ``` -------------------------------- ### Check PyTango Installation and Info Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/README.rst Import the tango module and print tango.utils.info() to verify the installation and display PyTango version and build information. ```python >>> import tango >>> print(tango.utils.info()) ``` -------------------------------- ### Get and Set TANGO Device Properties Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/doc/tutorial/database.md This example shows how to retrieve and modify properties of a TANGO device. It connects to a device, fetches a list of properties, prints their values, and then updates specific properties. ```python from tango import DeviceProxy # connecting to the motor axis device axis1 = DeviceProxy("microxas/motorisation/galilbox") # Getting Device Properties property_names = ["AxisBoxAttachement", "AxisEncoderType", "AxisNumber", "CurrentAcceleration", "CurrentAccuracy", "CurrentBacklash", "CurrentDeceleration", "CurrentDirection", "CurrentMotionAccuracy", "CurrentOvershoot", "CurrentRetry", "CurrentScale", "CurrentVelocity", "EncoderMotorRatio", "logging_level", "logging_target", "UserEncoderRatio", "UserOffset"] axis_properties = axis1.get_property(property_names) for prop in axis_properties.keys(): print("%s: %s" % (prop, axis_properties[prop][0])) # Changing Properties axis_properties["AxisBoxAttachement"] = ["microxas/motorisation/galilbox"] axis_properties["AxisEncoderType"] = ["1"] axis_properties["AxisNumber"] = ["6"] axis1.put_property(axis_properties) ``` -------------------------------- ### Custom CMakeUserPresets.json Example Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/BUILD.md An example of a CMakeUserPresets.json file for local development. It defines presets for common development configurations, including build type and cache variables. Remember to replace the Tango_ROOT path with your local installation. ```json { "version": 2, "cmakeMinimumRequired": { "major": 3, "minor": 18, "patch": 0 }, "configurePresets": [ { "name": "dev-common", "hidden": true, "inherits": ["dev-mode", "clang-tidy", "cppcheck"] }, { "name": "dev-unix", "binaryDir": "${sourceDir}/cmakebuild/dev-unix", "inherits": ["dev-common", "ci-unix"], "cacheVariables": { "CMAKE_BUILD_TYPE": "Debug", "CMAKE_EXPORT_COMPILE_COMMANDS": "ON" } }, { "name": "dev", "binaryDir": "${sourceDir}/cmakebuild/dev", "inherits": "dev-unix", "cacheVariables": { "Tango_ROOT": "/path/to/installed/tango.9.4" # Replace this path for your local installation } } ], "buildPresets": [ { "name": "dev", "configurePreset": "dev", "configuration": "Debug", "jobs": 8 } ] } ``` -------------------------------- ### Build and Install PyTango from Source Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/BUILD.md Activates the Conda environment, clones the PyTango repository, and installs it using pip. ```shell conda activate pytango git clone --recurse-submodules https://gitlab.com/tango-controls/pytango.git cd pytango pip install . ``` -------------------------------- ### Define a Simple Clock Device Server Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/doc/tutorial/servers.md Example of a basic Tango device server for a Clock device. It defines a 'model' property, a 'time' attribute, and a 'strftime' command. Use this as a starting point for creating your own device servers. ```python import time from tango.server import Device, device_property, attribute, command class Clock(Device): model = device_property(dtype=str) @attribute def time(self): return time.time() @command(dtype_in=str, dtype_out=str) def strftime(self, format): return time.strftime(format) if __name__ == "__main__": Clock.run_server() ``` -------------------------------- ### Complete PowerSupply Device Server Example Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/doc/api/server_api/server.md A comprehensive example of a 'PowerSupply' device server using the high-level API. It showcases device description, state, various attribute types (scalar, expert, image), a command, and device/class properties. ```python from time import time from numpy.random import random_sample from tango import AttrQuality, AttrWriteType, DevState, DispLevel from tango.server import Device, attribute, command from tango.server import class_property, device_property class PowerSupply(Device): """PyTango example of PowerSuppy device.""" # alternative way to add device description (see note below) DEVICE_CLASS_DESCRIPTION = "PyTango example of PowerSuppy device." DEVICE_CLASS_INITIAL_STATUS = "Device is in current supply mode" DEVICE_CLASS_INITIAL_STATE = DevState.ON voltage = attribute() current = attribute(label="Current", dtype=float, display_level=DispLevel.EXPERT, access=AttrWriteType.READ_WRITE, unit="A", format="8.4f", min_value=0.0, max_value=8.5, min_alarm=0.1, max_alarm=8.4, min_warning=0.5, max_warning=8.0, fget="get_current", fset="set_current", doc="the power supply current") noise = attribute(label="Noise", dtype=((float,),), max_dim_x=1024, max_dim_y=1024, fget="get_noise") host = device_property(dtype=str) port = class_property(dtype=int, default_value=9788) def read_voltage(self): self.info_stream(f"Get voltage({self.host}, {self.port})") return 10.0 def get_current(self): return 2.3456, time(), AttrQuality.ATTR_CHANGING def set_current(self, current): self.info_stream(f"Current set to {current}") def get_noise(self): return random_sample((1024, 1024)) @command(dtype_in=float) def ramp(self, value): self.info_stream(f"Ramp up requested: {value} seconds") if __name__ == "__main__": PowerSupply.run_server() ``` -------------------------------- ### Asyncio simple example Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/doc/tutorial/green_modes/green_modes_client.md A basic example demonstrating the usage of PyTango in asyncio mode. This snippet requires the asyncio library. ```python import asyncio from tango.asyncio import DeviceProxy async def main(): dev = DeviceProxy("sys/tg_test/1") print(await dev.state()) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Install and Test PyTango Wheel Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/BUILD.md Install the repaired PyTango wheel and run a simple test to verify the installation. Tests should be run from a temporary directory to avoid module name conflicts. ```shell # install the wheel with batteries python -m pip install --prefer-binary wheelhouse/pytango*.whl # Tests need to run somewhere not in the root of the pytango repo since the source code is located in a folder named `tango` and conflicts with the module name. mkdir tmp && cd tmp/ python -c "import tango; print(tango.utils.info())" ``` -------------------------------- ### Start Power Supply Device Server Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/examples/training/README.md Starts the power supply device server script named 'ps1.py' with the argument 'test'. ```bash docker-compose exec cli /training/server/ps1.py test ``` -------------------------------- ### Start Device Server with Verbose Option Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/doc/tutorial/logging.md Start your device server with the verbose option to activate console logging and filter messages by importance level. ```bash python PyDsExp.py PyDs1 -v4 ``` -------------------------------- ### Device Class Constructor Example Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/doc/how-to/server_old_api.md Example of a device class constructor to initialize specific data members and set the device type. It must call the parent class constructor. ```python def __init__(self, name): tango.DeviceClass.__init__(self, name) self.set_type("TestDevice") ``` -------------------------------- ### Check PyTango Installation with Pixi Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/doc/how-to/how-to-contribute.md Verifies the PyTango installation by printing version information. This is a shortcut for importing tango and printing its info. ```console pixi run python -c 'import tango; print(tango.utils.info())' ``` -------------------------------- ### Asyncio Green Mode Example for PyTango Device Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/doc/tutorial/green_modes/green_modes_server.md This example demonstrates how to implement an asynchronous Tango device using the Asyncio green mode. All user methods should be defined with the `async` keyword. ```python from tango import Device, GreenMode from tango.server import run class AsyncioDevice(Device): green_mode = GreenMode.Asyncio async def init_device(self): await super().init_device() self.set_state(tango.DevState.ON) async def read_attribute(self, name): # Example of an asynchronous operation await asyncio.sleep(0.1) return await super().read_attribute(name) if __name__ == '__main__': run([AsyncioDevice]) ``` -------------------------------- ### Install Cpptango from Specific Environment Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/BUILD.md This command installs cpptango using the environment defined in `pixi.toml`. ```shell pixi run -e cpptango install ``` -------------------------------- ### Start ipython Session Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/examples/training/README.md Starts an ipython session within the CLI container of the PyTango training environment. This allows interactive Python scripting with PyTango. ```bash docker-compose exec cli ipython3 ``` -------------------------------- ### Check PyTango installation Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/doc/installation.md Verify the PyTango installation by importing the 'tango' module and printing its version. Ensure you are in a directory that does not contain the source code if you built it from source. ```python import tango print(tango.Release.version) ``` -------------------------------- ### Asyncio TCP server example Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/doc/tutorial/green_modes/green_modes_client.md An example of an asynchronous TCP server using PyTango's asyncio mode. It listens for device attribute names, fetches values, and replies to clients. ```python import asyncio from tango.asyncio import DeviceProxy async def handle_client(reader, writer): data = await reader.read(100) message = data.decode() addr = writer.get_extra_info('peername') print(f"Received {message!r} from {addr!r}") dev = DeviceProxy("sys/tg_test/1") try: value = await dev.read_attribute(message) print(f"Reply {value!r}") writer.write(f"{value!r}\n".encode()) except Exception as e: print(f"Error: {e}") writer.write(f"Error: {e}\n".encode()) print("Close the connection") writer.close() async def main(): server = await asyncio.start_server( handle_client, '127.0.0.1', 8888) addr = server.sockets[0].getsockname() async with server: await server.serve_forever() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Example Branch Name for Release Preparation Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/doc/how-to/how-to-contribute.md When preparing a release, create a new branch from 'develop' with a descriptive name indicating the target version. ```bash prepare-v9.4.4 ``` -------------------------------- ### Example Version Bumping for Development Branch Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/doc/how-to/how-to-contribute.md Illustrates how to update version information for the development branch after a release, appending '-dev' to the version string. ```text version_info = (9, 4, 5, "dev", 0) version = "9.4.5.dev0" VERSION 9.4.5 ``` -------------------------------- ### Install PyTango using pip Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/doc/installation.md Install the latest version of PyTango from PyPI. This method is suitable for Linux, Windows, and MacOS and typically does not require compilation. ```bash $ python -m pip install pytango ``` -------------------------------- ### Build PyTango Wheel Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/BUILD.md Clone the repository, set up a virtual environment, install build tools, and build the basic PyTango wheel. The Tango_ROOT variable is only needed for non-standard cppTango installations. ```shell git clone --recurse-submodules git@gitlab.com:tango-controls/pytango.git cd pytango python3 -m venv venv source venv/bin/activate pip install --upgrade pip build # Setting the Tango_ROOT variable is only required for a non-standard system install of cppTango Tango_ROOT=/path/to/installed/tango.9.4 python3 -m build # Check what has been built: ls dist/ # Further check what is in the wheel if you're really curious: unzip dist/*.whl ``` -------------------------------- ### Start itango Session Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/examples/training/README.md Starts an itango session, an interactive Tango client, within the CLI container. It provides an enhanced interactive Python experience for Tango operations. ```bash docker-compose exec cli itango3 ``` -------------------------------- ### Install Cpptango and Tangotest with Specific Branch Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/BUILD.md This command builds cpptango from a specific branch and installs it along with TangoTest. The `CPPTANGO_BRANCH` environment variable specifies the branch to clone from the `.tmp` directory. If not specified, 'main' is used. ```shell CPPTANGO_BRANCH= pixi run install-cpptango-and-tangotest ``` -------------------------------- ### Install gevent Package Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/examples/training/README.md Installs the 'gevent' package within the CLI container using pip. This is a prerequisite for running certain PyTango server examples. ```bash docker-compose exec cli pip install gevent ``` -------------------------------- ### Build and Serve Documentation Locally Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/doc/how-to/how-to-contribute.md Run this command to build the documentation locally. Use `doc_no_cache` to force a full rebuild if changes are not detected. ```console cd /path/to/pytango pixi run doc ``` -------------------------------- ### Get PyTango Version Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/doc/tutorial.md Retrieve the installed PyTango version using the __version__ attribute. This is useful for compatibility checks and ensuring you have the necessary features. ```python import tango tango.__version__ ``` -------------------------------- ### Register and Run Custom Device Server Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/examples/training/README.md Registers a new device server named 'PowerSupply/test' and starts its execution. This involves using `tango_admin` and then running the server script. ```bash docker-compose exec cli bash tango@c5f6dc31dc6b:/training$ cd server/ tango@c5f6dc31dc6b:/training/server$ ./ps0a.py test tango@c5f6dc31dc6b:/training/server$ tango_admin --add-server PowerSupply/test PowerSupply train/ps/1 tango@c5f6dc31dc6b:/training/server$ ./ps0a.py test ``` -------------------------------- ### Define DevEnum Attributes in PyTango Server Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/doc/api/data_types.md Use Python's `enum.IntEnum` to define DevEnum attributes on the server side. Ensure enums start at 0 and increment by 1. This example shows defining `Noon` and `DisplayType` enums and integrating them into a `Clock` device. ```python import time from enum import IntEnum from tango.server import Device, attribute, command class Noon(IntEnum): AM = 0 # DevEnum's must start at 0 PM = 1 # and increment by 1 class DisplayType(IntEnum): ANALOG = 0 # DevEnum's must start at 0 DIGITAL = 1 # and increment by 1 class Clock(Device): display_type = DisplayType.ANALOG @attribute def time(self) -> float: return time.time() @attribute(max_dim_x=9) def gmtime(self) -> tuple[int]: return time.gmtime() @attribute def noon(self) -> Noon: time_struct = time.gmtime(time.time()) return Noon.AM if time_struct.tm_hour < 12 else Noon.PM @attribute def display(self) -> DisplayType: return self.display_type @display.setter def display(self, display_type: int): # note that we receive an integer, not an enum instance, # so we have to convert that to an instance of our enum. self.display_type = DisplayType(display_type) @command(dtype_in=float, dtype_out=str) def ctime(self, seconds): """ Convert a time in seconds since the Epoch to a string in local time. This is equivalent to asctime(localtime(seconds)). When the time tuple is not present, current time as returned by localtime() is used. """ return time.ctime(seconds) @command def mktime(self, tupl: tuple[int]) -> float: return time.mktime(tuple(tupl)) if __name__ == "__main__": Clock.run_server() ``` -------------------------------- ### Device Server High-Level API Example Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/doc/tep/tep-0001.md Illustrates the simplified structure of a device server using the proposed high-level API, including attributes and commands. ```python class Motor(Device): __metaclass__ = DeviceMeta position = attribute() def read_position(self): return 2.3 @command() def move(self, position): pass if __name__ == "__main__": server_run((Motor,)) ``` -------------------------------- ### Simple Clock Device Server Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/doc/api/server_api/server.md A basic example demonstrating how to create a 'Clock' device server using the high-level API. It includes a time attribute and a strftime command. ```python import time from tango.server import run from tango.server import Device from tango.server import attribute, command class Clock(Device): time = attribute() def read_time(self): return time.time() @command(dtype_in=str, dtype_out=str) def strftime(self, format): return time.strftime(format) if __name__ == "__main__": run((Clock,)) ``` -------------------------------- ### Install PyTango using Conda Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/README.rst Install PyTango from Conda Forge. This is an alternative installation method. ```bash $ conda install -c conda-forge pytango ``` -------------------------------- ### PyTango Device Server with Type Hints Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/doc/tutorial/servers.md Example of a PyTango device server implementing properties, attributes, and commands using Python type hints for data type declaration. ```python from time import time from numpy.random import random_sample from tango import AttrQuality, AttrWriteType, DevState, DispLevel, AttReqType from tango.server import Device, attribute, command from tango.server import class_property, device_property class PowerSupply(Device): _my_current = 2.3456 _my_range = 0 _my_compliance = 0.0 _output_on = False host: str = device_property() port: int = class_property(default_value=9788) def init_device(self): super().init_device() self.info_stream(f"Power supply connection details: {self.host}:{self.port}") self.set_state(DevState.ON) self.set_status("Power supply is ON") current: float = attribute( label="Current", display_level=DispLevel.EXPERT, access=AttrWriteType.READ_WRITE, unit="A", format="8.4f", min_value=0.0, max_value=8.5, min_alarm=0.1, max_alarm=8.4, min_warning=0.5, max_warning=8.0, fget="get_current", fset="set_current", doc="the power supply current", ) noise: list[list[float]] = attribute( label="Noise", max_dim_x=1024, max_dim_y=1024, fget="get_noise" ) @attribute def voltage(self) -> float: return 10.0 def get_current(self): return self._my_current def set_current(self, current): print("Current set to %f" % current) self._my_current = current def get_noise(self): return random_sample((1024, 1024)) range = attribute(label="Range") @range.getter def current_range(self) -> tuple[float, float, AttrQuality]: return self._my_range, time(), AttrQuality.ATTR_WARNING @range.setter def range(self, new_range: float): self._my_range = new_range @range.is_allowed def can_range_be_changed(self, req_type): if req_type == AttReqType.WRITE_REQ: return not self._output_on return True compliance = attribute(label="Compliance") @compliance.read def compliance(self) -> float: return self._my_compliance @compliance.write def new_compliance(self, new_compliance: float): self._my_compliance = new_compliance @command def output_on_off(self, on_off: bool) -> bool: self._output_on = on_off return self._output_on if __name__ == "__main__": PowerSupply.run_server() ``` -------------------------------- ### Install PyTango with Gevent support using pip Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/doc/installation.md Install PyTango with gevent green mode support. This requires a recent version of gevent, which can be forced during installation. ```bash $ python -m pip install pytango[gevent] ``` -------------------------------- ### Example Version Bumping for Release Candidate Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/doc/how-to/how-to-contribute.md Shows how to update version information for a release candidate. This includes specifying the release candidate number in the version tuple and string. ```text version_info = (9, 4, 4, "rc", 1) version = "9.4.4.rc1" VERSION 9.4.4 ``` -------------------------------- ### Install Pytango with Specific Python Version Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/BUILD.md To install pytango using a specific Python version (e.g., 3.11), use the `-e` flag with `pixi run install` to specify the environment. ```shell pixi run -e py311 install ``` -------------------------------- ### Build and Install TangoTest Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/BUILD.md Build and install TangoTest from source to run PyTango unit tests. This requires a previously compiled and installed cppTango library. Ensure you are in a conda environment with pytango-dev-src activated. ```shell # (in pytango-dev-src env) cd /path/to/your/src git clone --recurse-submodules https://gitlab.com/tango-controls/TangoTest.git cd TangoTest mkdir build cd build cmake --install-prefix="$CONDA_PREFIX" .. make -j$CPU_COUNT make install ``` -------------------------------- ### Editable Install with Custom Build Directory Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/BUILD.md Installs PyTango in editable mode with build isolation disabled and a specified build directory for faster recompilation. Requires manual installation of build dependencies. ```shell conda activate pytango conda install scikit-build-core numpy pybind11-stubgen ruff git clone --recurse-submodules https://gitlab.com/tango-controls/pytango.git cd pytango pip install --no-build-isolation --config-settings=build-dir="build/{wheel_tag}" -e ".[tests]" ``` -------------------------------- ### Example Version Bumping for Final Release Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/doc/how-to/how-to-contribute.md Illustrates how to update version information in different files for a final release. This includes tuple-based versioning, string versioning in pyproject.toml, and CMakeLists.txt. ```text version_info = (9, 4, 4) version = "9.4.4" VERSION 9.4.4 ``` -------------------------------- ### Initialize gevent DeviceProxy and get green mode Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/doc/tutorial/green_modes/green_modes_client.md Demonstrates initializing a DeviceProxy in gevent mode and checking its green mode. Requires the gevent library. ```python >>> from tango.gevent import DeviceProxy >>> dev = DeviceProxy("sys/tg_test/1") >>> dev.get_green_mode() tango.GreenMode.Gevent >>> print(dev.state()) RUNNING ``` -------------------------------- ### Build and Install omniORB from Source Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/BUILD.md Instructions for building and installing omniORB from source code, specifically for macOS Apple Silicon where Conda packages are unavailable. This involves downloading, configuring, compiling, and installing omniORB within the Conda environment. ```shell # (in pytango-dev-src env) cd /path/to/your/src mkdir omniORB cd omniORB download omniORB-4.3.1.tar.bz2 from https://sourceforge.net/projects/omniorb/files/omniORB/omniORB-4.3.1/ tar jxvf omniORB-4.3.1.tar.bz2 cd omniORB-4.3.1 cp $CONDA_PREFIX/share/gnuconfig/config.* ./bin/scripts mkdir build cd build # on Apple Silicon, disable long double ../configure --prefix="$CONDA_PREFIX" --disable-longdouble make -j$CPU_COUNT make install ``` -------------------------------- ### Build PyTango Docs Locally Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/doc/README.md Run this command in the PyTango project directory to build the documentation. ```console cd /path/to/pytango pixi run doc ``` -------------------------------- ### Configure Logging at Runtime Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/doc/how-to/telemetry.md Use DeviceProxy convenience methods to enable logging and configure logging endpoints dynamically at runtime. This follows the same pattern as configuring tracing endpoints. ```python proxy.set_telemetry_logging(True) proxy.set_telemetry_logging_endpoints( [ TelemetryEndpoint( TelemetryExporter.GRPC, "grpc://collector.example.org:4317", ) ] ) ``` -------------------------------- ### Install PyTango with Tests Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/BUILD.md Install PyTango in editable mode with test dependencies. This command assumes you are in the pytango source directory and have the pytango-dev-src environment activated. ```shell # (in pytango-dev-src env) cd pytango pip install --no-build-isolation --config-settings=build-dir="build/{wheel_tag}" -e ".[tests]" -v ``` -------------------------------- ### Basic Thread Creation and Management in PyTango Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/doc/how-to/multiprocessing.md This snippet demonstrates basic thread creation, starting, and joining using Python's `Thread` class. It also shows how to use `tango.utils.EventCallback` and `tango.DeviceProxy` for event handling and device interaction. ```python cb = tango.utils.EventCallback() # print events to stdout dp = tango.DeviceProxy("sys/tg_test/1") dp.poll_attribute("double_scalar", 1000) thread = Thread(target=thread_task) running = True thread.start() sleep(5) running = False thread.join() ``` -------------------------------- ### Install and Test PyTango in a Specific Environment with Pixi Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/doc/how-to/how-to-contribute.md Installs and tests PyTango within a specified Conda environment (e.g., 'py311') using pixi. ```console pixi run -e py311 install ``` ```console pixi run -e py311 pytest ``` -------------------------------- ### Dynamically Create Device using Util.create_device Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/doc/how-to/starting_device.md Implements a Tango command to dynamically create a new device at runtime. It requires the class name and device name as input. Note that the Tango class must be registered before the server starts. ```python from tango import Util from tango.server import Device, command class MyDevice(Device): @command(dtype_in=[str]) def CreateDevice(self, pars): klass_name, dev_name = pars util = Util.instance() util.create_device(klass_name, dev_name, alias=None, cb=None) @command(dtype_in=[str]) def DeleteDevice(self, pars): klass_name, dev_name = pars util = Util.instance() util.delete_device(klass_name, dev_name) ``` -------------------------------- ### Main Part of a Python Device Server Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/doc/how-to/server_old_api.md This code initializes the Tango device server, adds device classes, and starts the server loop. Ensure `sys` is imported. ```python if __name__ == '__main__': util = tango.Util(sys.argv) util.add_class(PyDsExpClass, PyDsExp) U = tango.Util.instance() U.server_init() U.server_run() ``` -------------------------------- ### Install Telemetry Reconfiguration Callback Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/internal-docs/telemetry-walkthrough.md Installs the Python _telemetry_reconfigured method onto the DeviceImpl class. This method is called when telemetry configuration changes originate from cppTango. ```python DeviceImpl._telemetry_reconfigured = __DeviceImpl___telemetry_reconfigured ``` -------------------------------- ### Import MultiDeviceTestContext Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/doc/how-to/testing/testing_approaches.md Import the MultiDeviceTestContext class for simplified multi-device testing. This is used when multiple devices need to be launched in a single device server. ```python from tango.test_context import MultiDeviceTestContext ``` -------------------------------- ### Install PyTango in Editable Mode with Pixi Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/doc/how-to/how-to-contribute.md Compiles and installs PyTango in editable mode using pixi, automatically creating a Conda environment with necessary dependencies. ```console pixi run install ``` -------------------------------- ### Server Main Function: Low-level vs High-level Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/doc/tep/tep-0001.md Compares the traditional low-level main function requiring manual initialization and registration of Tango utilities with the simplified high-level approach using a single server_run function call. ```python def main(): try: py = PyTango.Util(sys.argv) py.add_class(MotorClass,Motor,'Motor') U = PyTango.Util.instance() U.server_init() U.server_run() except PyTango.DevFailed,e: print '-------> Received a DevFailed exception:',e except Exception,e: print '-------> An unforeseen exception occured....',e ``` ```python def main(): classes = Motor, PyTango.server_run(classes) ``` -------------------------------- ### Build and Install cppTango Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/BUILD.md Use this command to build and install cppTango from source. For a debug build, set CMAKE_BUILD_TYPE to Debug. Ensure you are in a conda environment with pytango-dev-src activated. ```shell # (in pytango-dev-src env) cd /path/to/your/src git clone --recurse-submodules git@gitlab.com:tango-controls/cppTango.git cd cpptango mkdir build cd build cmake ${CMAKE_ARGS} \ -DCMAKE_BUILD_TYPE=Debug \ -DCMAKE_VERBOSE_MAKEFILE=ON \ -DCMAKE_INSTALL_PREFIX="$CONDA_PREFIX" \ -DCMAKE_PREFIX_PATH="$CONDA_PREFIX" \ -DBUILD_TESTING=OFF \ -DCMAKE_CXX_STANDARD=17 \ -DTANGO_USE_TELEMETRY=ON \ .. make -j$CPU_COUNT make install ``` -------------------------------- ### Install PyTango Dependencies with Homebrew (macOS) Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/BUILD.md Installs PyTango's library dependencies, including pybind11, cppzmq, jpeg-turbo, omniorb, and zeromq, using Homebrew on macOS. ```shell brew install pybind11>=3.0.1 cppzmq jpeg-turbo omniorb zeromq ``` -------------------------------- ### Install PyTango on Debian/Ubuntu Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/doc/installation.md Install the PyTango package for Python 3 using the apt-get package manager on Debian or Ubuntu systems. Note that this may not be the latest release. ```bash $ sudo apt-get install python3-tango ``` -------------------------------- ### Run Server with Multiple Python Device Classes Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/doc/how-to/starting_device.md Combines multiple Python Tango device classes (PLC and IRMirror) into a single device server named PLCMirror. ```python # PLCMirror.py from tango.server import run from PLC import PLC from IRMirror import IRMirror run([PLC, IRMirror]) ``` -------------------------------- ### Create Annotated Git Tag Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/doc/how-to/how-to-contribute.md Demonstrates how to create an annotated Git tag from the command line for a specific version. This is a required step for releases. ```bash git checkout develop git pull git tag -a -m "tag v9.4.4" v9.4.4 git push -v origin refs/tags/v9.4.4 ``` -------------------------------- ### Install Development Tools with Homebrew (macOS) Source: https://gitlab.com/tango-controls/pytango/-/blob/develop/BUILD.md Installs essential development tools like coreutils, cppcheck, git, lcov, pkg-config, and Python 3.11 using Homebrew on macOS. ```shell brew install coreutils cppcheck git lcov pkg-config python@3.11 ```