### Install python-snap7 with CLI support Source: https://python-snap7.readthedocs.io/en/latest/_sources/installation.rst Installs python-snap7 including its command-line interface dependencies, which is necessary for running the emulator. ```shell pip install "python-snap7[cli]" ``` -------------------------------- ### Install python-snap7 from local source Source: https://python-snap7.readthedocs.io/en/latest/_sources/installation.rst Installs the python-snap7 package from the current directory into the active Python virtual environment or system, typically used during manual installation. ```shell pip3 install . ``` -------------------------------- ### Compile Snap7 library from source Source: https://python-snap7.readthedocs.io/en/latest/_sources/installation.rst Provides commands to decompress the Snap7 source archive, navigate to the platform-specific build directory, and compile the library using `make`. ```shell p7zip -d snap7-full-1.0.0.7z cd build/ make -f .mk install ``` -------------------------------- ### Install Snap7 library on Ubuntu Source: https://python-snap7.readthedocs.io/en/latest/_sources/installation.rst Adds the official Snap7 PPA to Ubuntu's package sources, updates the package list, and then installs the core Snap7 library and development files. ```shell sudo add-apt-repository ppa:gijzelaar/snap7 sudo apt-get update sudo apt-get install libsnap7-1 libsnap7-dev ``` -------------------------------- ### Install python-snap7 using pip Source: https://python-snap7.readthedocs.io/en/latest/installation This command installs the python-snap7 library and its optional CLI interface using pip, the Python package installer. It's the recommended method for most users on supported platforms. ```bash pip install python-snap7 pip install "python-snap7[cli]" ``` -------------------------------- ### Install python-snap7 from local source Source: https://python-snap7.readthedocs.io/en/latest/installation This command installs the python-snap7 package from the current directory into the active virtual environment. It's used when installing from a local source clone or tarball. ```bash pip3 install . ``` -------------------------------- ### Install python-snap7 via pip Source: https://python-snap7.readthedocs.io/en/latest/_sources/installation.rst Installs the python-snap7 library using the pip package manager. This is the recommended method for most users. ```shell pip install python-snap7 ``` -------------------------------- ### Install Snap7 library on Ubuntu via PPA Source: https://python-snap7.readthedocs.io/en/latest/installation These commands add the Snap7 PPA (Personal Package Archive) to your system's software sources, update the package list, and then install the Snap7 runtime and development libraries on Ubuntu. ```bash sudo add-apt-repository ppa:gijzelaar/snap7 sudo apt-get update sudo apt-get install libsnap7-1 libsnap7-dev ``` -------------------------------- ### Create and activate Python virtual environment Source: https://python-snap7.readthedocs.io/en/latest/_sources/installation.rst Demonstrates how to create a new isolated Python virtual environment and activate it, which is recommended for managing project dependencies. ```shell python3 -m venv venv source venv/bin/activate ``` -------------------------------- ### Install Snap7 library on macOS with Homebrew Source: https://python-snap7.readthedocs.io/en/latest/_sources/installation.rst Installs the Snap7 library on macOS using the Homebrew package manager, a common method for installing software on macOS. ```shell brew install snap7 ``` -------------------------------- ### Compile Snap7 library from source Source: https://python-snap7.readthedocs.io/en/latest/installation These commands detail the process of compiling the Snap7 library from its source code. It involves extracting the archive, navigating to the platform-specific build directory, and running the make command for your architecture. ```bash p7zip -d snap7-full-1.0.0.7z # requires the p7 program cd build/ make -f .mk install ``` -------------------------------- ### Install Snap7 library on OSX using Homebrew Source: https://python-snap7.readthedocs.io/en/latest/installation This command uses Homebrew, the macOS package manager, to install the Snap7 library on OS X. Homebrew simplifies the installation of command-line tools. ```bash brew install snap7 ``` -------------------------------- ### Create and activate Python virtual environment Source: https://python-snap7.readthedocs.io/en/latest/installation These commands create a new Python virtual environment named 'venv' and then activate it. A virtual environment isolates project dependencies, preventing conflicts with system-wide packages. ```bash python3 -m venv venv source venv/bin/activate ``` -------------------------------- ### Example: Set String in Bytearray Source: https://python-snap7.readthedocs.io/en/latest/API/util Illustrates how to use `set_string` to embed a string 'hello world' into a bytearray, specifying the starting index and maximum size. ```python >>> from snap7.util import set_string >>> data = bytearray(20) >>> set_string(data, 0, "hello world", 254) >>> data bytearray(b'\xff\x0bhello world\x00\x00\x00\x00\x00\x00\x00') ``` -------------------------------- ### Initialize Snap7 Client Source: https://python-snap7.readthedocs.io/en/latest/API/client Examples showing how to create a Snap7 client instance, either relying on the default library path or specifying a custom location. ```python import snap7 client = snap7.client.Client() # If the `snap7.dll` file is in the path location client2 = snap7.client.Client(lib_location="/path/to/snap7.dll") # If the dll is in another location ``` -------------------------------- ### Install Snap7 Server Dependencies Source: https://python-snap7.readthedocs.io/en/latest/API/server Command to install the necessary dependencies for running the Snap7 server, specifically including the command-line interface (CLI) extras. This ensures all required components for server operation are available. ```bash pip install python-snap7[cli] ``` -------------------------------- ### Start Snap7 Server from Command Line Source: https://python-snap7.readthedocs.io/en/latest/API/server Commands to start the Snap7 server using the Python module execution or directly via the `snap7-server` script. The latter option is available if the Python `Scripts/` folder is included in your system's PATH environment variable. ```bash python -m snap7.server # or, if your Python `Scripts/` folder is on PATH: snap7-server ``` -------------------------------- ### Example: Get DATE_AND_TIME from Bytearray Source: https://python-snap7.readthedocs.io/en/latest/API/util Demonstrates how to initialize a bytearray with raw date/time bytes and then parse it into an ISO 8601 string using `snap7.util.get_dt`. ```python data = bytearray(8) data[:] = [32, 7, 18, 23, 50, 2, 133, 65] #'2020-07-12T17:32:02.854000' get_dt(data,0) '2020-07-12T17:32:02.854000' ``` -------------------------------- ### Install Python Snap7 CLI Dependencies Source: https://python-snap7.readthedocs.io/en/latest/_sources/API/server.rst Installs the additional dependencies required for the Snap7 server, specifically the command-line interface components, using pip. ```bash pip install python-snap7[cli] ``` -------------------------------- ### Start Partner Object Communication (Python) Source: https://python-snap7.readthedocs.io/en/latest/_modules/snap7/partner Initializes and starts the Partner object, binding it to a specified IP address and the IsoTCP port. This method establishes the communication link. ```python @error_wrap(context="partner") def start(self) -> int: """ Starts the Partner and binds it to the specified IP address and the IsoTCP port. """ return self._library.Par_Start(self._pointer) ``` -------------------------------- ### Start Snap7 Server Source: https://python-snap7.readthedocs.io/en/latest/_sources/API/server.rst Initiates the default Snap7 server. This can be done either by executing the Python module directly or by using the `snap7-server` command if it's available in your system's PATH. ```bash python -m snap7.server ``` ```bash snap7-server ``` -------------------------------- ### Python Snap7 Server: Start Server Source: https://python-snap7.readthedocs.io/en/latest/_modules/snap7/server Starts the Snap7 server instance. Allows specifying a custom TCP port for the server to listen on. If the port is not 102, it will be set via `set_param`. ```Python @error_wrap(context="server") def start(self, tcp_port: int = 102) -> int: """Starts the server. Args: tcp_port: port that the server will listen. Optional. """ if tcp_port != 102: logger.info(f"setting server TCP port to {tcp_port}") self.set_param(Parameter.LocalPort, tcp_port) logger.info(f"starting server on 0.0.0.0:{tcp_port}") return self._lib.Srv_Start(self._s7_server) ``` -------------------------------- ### Example: Get DINT Value from Bytearray using struct Source: https://python-snap7.readthedocs.io/en/latest/API/util Shows how to create a bytearray representing a DINT value using Python's `struct` module and then retrieve it using `snap7.util.get_dint`. ```python import struct data = bytearray(4) data[:] = struct.pack(">i", 2147483647) get_dint(data, 0) 2147483647 ``` -------------------------------- ### Start Snap7 Server with Custom Port Source: https://python-snap7.readthedocs.io/en/latest/_sources/API/server.rst Starts the Snap7 server and allows the user to specify a custom port for the server to listen on. The `--port` argument is used to define the desired port number. ```bash python -m snap7.server --port 102 ``` -------------------------------- ### snap7 API Methods and Attributes (Underscore Prefix) Source: https://python-snap7.readthedocs.io/en/latest/genindex API documentation for methods starting with an underscore, specifically the `__init__` methods for initializing `snap7.client.Client` and `snap7.server.Server` instances. ```APIDOC snap7.client.Client.__init__() snap7.server.Server.__init__() ``` -------------------------------- ### Start Snap7 Server with Custom Port Source: https://python-snap7.readthedocs.io/en/latest/API/server Command to start the Snap7 server, allowing specification of a custom TCP port for listening. This is useful for environments where the default port might be in use or a specific port is required. ```bash python -m snap7.server --port 102 ``` -------------------------------- ### API Reference: Client.plc_cold_start Source: https://python-snap7.readthedocs.io/en/latest/API/client Puts the CPU in RUN mode performing a COLD START. ```APIDOC Client.plc_cold_start() -> int Returns: Error code from snap7 library. ``` -------------------------------- ### Python Snap7 Server: Start Server on Specific Interface Source: https://python-snap7.readthedocs.io/en/latest/_modules/snap7/server Starts the Snap7 server on a specified IPV4 address and optional TCP port. Validates the provided IP address before attempting to start the server. ```Python @error_wrap(context="server") def start_to(self, ip: str, tcp_port: int = 102) -> int: """Start server on a specific interface. Args: ip: IPV4 address where the server is located. tcp_port: port that the server will listen on. Raises: :obj:`ValueError`: if the `ivp4` is not a valid IPV4 """ if tcp_port != 102: logger.info(f"setting server TCP port to {tcp_port}") self.set_param(Parameter.LocalPort, tcp_port) if not re.match(ipv4, ip): raise ValueError(f"{ip} is invalid ipv4") logger.info(f"starting server to {ip}:102") return self._lib.Srv_StartTo(self._s7_server, ip.encode()) ``` -------------------------------- ### Example: Set Time in Bytearray Source: https://python-snap7.readthedocs.io/en/latest/API/util Shows a sequence of operations to initialize a bytearray, set a time string value using `set_time`, and then inspect the resulting bytearray. ```python >>> data = bytearray(4) ``` ```python >>> set_time(data, 0, '-22:3:57:28.192') ``` ```python >>> data bytearray(b'\x8d\xda\xaf') ``` -------------------------------- ### Start Partner Object Communication with Specific IPs/TSAPs (Python) Source: https://python-snap7.readthedocs.io/en/latest/_modules/snap7/partner Initializes and starts the Partner object, binding it to specified local and remote IP addresses and TSAPs (Transport Service Access Points). This provides fine-grained control over the communication endpoint configuration. It validates IPv4 addresses before proceeding. ```python @error_wrap(context="partner") def start_to(self, local_ip: str, remote_ip: str, local_tsap: int, remote_tsap: int) -> int: """ Starts the Partner and binds it to the specified IP address and the IsoTCP port. :param local_ip: PC host IPV4 Address. "0.0.0.0" is the default adapter :param remote_ip: PLC IPV4 Address :param local_tsap: Local TSAP :param remote_tsap: PLC TSAP """ if not re.match(ipv4, local_ip): raise ValueError(f"{local_ip} is invalid ipv4") if not re.match(ipv4, remote_ip): raise ValueError(f"{remote_ip} is invalid ipv4") logger.info(f"starting partnering from {local_ip} to {remote_ip}") return self._library.Par_StartTo( self._pointer, local_ip.encode(), remote_ip.encode(), word(local_tsap), word(remote_tsap) ) ``` -------------------------------- ### API Reference: Client.plc_hot_start Source: https://python-snap7.readthedocs.io/en/latest/API/client Puts the CPU in RUN mode performing an HOT START. ```APIDOC Client.plc_hot_start() -> int Returns: Error code from snap7 library. ``` -------------------------------- ### Control PLC State (Stop, Cold Start, Hot Start) Source: https://python-snap7.readthedocs.io/en/latest/_modules/snap7/client Provides methods to change the operational state of the connected PLC, allowing it to be stopped, cold started, or hot started. Each method returns an error code from the snap7 library indicating success or failure. ```APIDOC Client.plc_stop(self) -> int Puts the CPU in STOP mode. Returns: Error code from snap7 library. Client.plc_cold_start(self) -> int Puts the CPU in RUN mode performing a COLD START. Returns: Error code from snap7 library. Client.plc_hot_start(self) -> int Puts the CPU in RUN mode performing an HOT START. Returns: Error code from snap7 library. ``` -------------------------------- ### Example: Asynchronously Read Data Block Source: https://python-snap7.readthedocs.io/en/latest/API/client This Python example demonstrates how to use the `as_db_read` method to asynchronously read a specified number of bytes from a Data Block (DB) in a PLC. It uses `ctypes` to prepare a buffer for the incoming data. ```Python import ctypes content = (ctypes.c_uint8 * size)() # In this ctypes array data will be stored. Client().as_db_read(1, 0, size, content) 0 ``` -------------------------------- ### Example: Parse String from Bytearray (snap7.util) Source: https://python-snap7.readthedocs.io/en/latest/API/util Demonstrates how to construct a bytearray with string length and content, then parse it into a Python string using the `get_string` function. ```python >>> data = bytearray([254, len("hello world")] + [ord(l) for letter in "hello world"]) >>> get_string(data, 0) 'hello world' ``` -------------------------------- ### Client.get_cpu_info Source: https://python-snap7.readthedocs.io/en/latest/API/client Retrieves detailed information about the CPU (AG) as an `S7CpuInfo` data structure. Includes examples of how to call the method and print the returned object. ```APIDOC get_cpu_info() -> S7CpuInfo Description: Returns some information about the AG. Returns: data structure with the information. Return type: S7CpuInfo ``` ```python >>> cpu_info = Client().get_cpu_info() >>> print(cpu_info) ``` -------------------------------- ### Example: Read DB from PLC Source: https://python-snap7.readthedocs.io/en/latest/API/client Illustrates how to connect to a PLC and read the contents of Data Block number 1 using `db_get`. The result is a bytearray. ```Python import snap7 client = snap7.client.Client() client.connect("192.168.0.1", 0, 0) buffer = client.db_get(1) # reads the db number 1. buffer bytearray(b"\x00\x00\x00\x00\x00\x00\x00\x00...\x00\x00") ``` -------------------------------- ### Example: Read Unsigned Double Integer (snap7.util) Source: https://python-snap7.readthedocs.io/en/latest/API/util Illustrates how to pack an unsigned integer into a bytearray and then read it back using the `get_udint` function. ```python >>> import struct >>> data = bytearray(4) >>> data[:] = struct.pack(">I", 4294967295) >>> get_udint(data, 0) 4294967295 ``` -------------------------------- ### Initialize Snap7 Client Source: https://python-snap7.readthedocs.io/en/latest/_modules/snap7/client Explains how to create a new `Client` instance, optionally specifying the full path to the `snap7.dll` file. Demonstrates instantiation with and without a custom library path. ```APIDOC Client.__init__(self, lib_location: Optional[str] = None) Creates a new `Client` instance. Args: lib_location: Full path to the snap7.dll file. Optional. ``` ```python import snap7 client = snap7.client.Client() # If the `snap7.dll` file is in the path location client2 = snap7.client.Client(lib_location="/path/to/snap7.dll") # If the dll is in another location # ``` -------------------------------- ### Example: Get Boolean Value from Bytearray Source: https://python-snap7.readthedocs.io/en/latest/API/util Demonstrates how to use `snap7.util.get_bool` to extract a boolean value from a bytearray at a specific byte and bit index. ```python buffer = bytearray([0b00000001]) # Only one byte length get_bool(buffer, 0, 0) # The bit 0 starts at the right. True ``` -------------------------------- ### Snap7 Server CLI main Function API Reference Source: https://python-snap7.readthedocs.io/en/latest/API/server API documentation for the `snap7.server.__main__.main` function, which serves as the command-line entry point for starting a dummy S7 server with default values. This function is also exported as a console entrypoint for direct execution. ```APIDOC function snap7.server.__main__.main(port, dll) Description: Start a S7 dummy server with some default values. ``` -------------------------------- ### Example: Get DWORD Value from Bytearray Source: https://python-snap7.readthedocs.io/en/latest/API/util Illustrates how to create a bytearray with hexadecimal values representing a DWORD and then retrieve its integer value using `snap7.util.get_dword`. ```python data = bytearray(8) data[:] = b"\x12\x34\xAB\xCD" get_dword(data, 0) 4294967295 ``` -------------------------------- ### snap7.client.Client.__init__ Method Source: https://python-snap7.readthedocs.io/en/latest/API/client Initializes a new Client instance, allowing an optional path to the snap7 library. ```APIDOC __init__(lib_location: str | None = None) Creates a new Client instance. Parameters: lib_location: Full path to the snap7.dll file. Optional. ``` -------------------------------- ### Get Wide Character (WCHAR) from Bytearray Source: https://python-snap7.readthedocs.io/en/latest/API/util Extracts a wide character (WCHAR) from a bytearray. WCHARs are 2-byte values in PLCs, expected to be in UTF-16-BE format. The example shows reading from a PLC DB. ```APIDOC snap7.util.get_wchar( bytearray_: bytearray, byte_index: int ) -> str Description: Get wchar value from bytearray. Datatype wchar in the PLC is represented in 2 bytes. It has to be in utf-16-be format. Parameters: bytearray: buffer to read from. byte_index: byte index to start reading from. Returns: Value read. ``` ```python from snap7 import Client data = Client().db_read(db_number=1, start=10, size=2) get_wchar(data, 0) C ``` -------------------------------- ### Initialize Snap7 Server Instance Source: https://python-snap7.readthedocs.io/en/latest/_modules/snap7/server Initializes a new instance of the Snap7 `Server` class, which mimics a Siemens S7 PLC. It sets up the underlying Snap7 library and optionally enables event logging for server activities. ```python class Server: """ A fake S7 server. """ _lib: Snap7CliProtocol _s7_server: S7Object _read_callback = None _callback: Optional[Callable[..., Any]] = None def __init__(self, log: bool = True): """Create a fake S7 server. set log to false if you want to disable event logging to python logging. Args: log: `True` for enabling the event logging. """ self._lib: Snap7CliProtocol = load_library() self.create() if log: self._set_log_callback() ``` -------------------------------- ### Get Block Information from PLC Source: https://python-snap7.readthedocs.io/en/latest/API/client Shows how to retrieve detailed information about a specific block (e.g., a Data Block) from a PLC using the `get_block_info` method. The example prints various attributes of the retrieved block information. ```python block_info = Client().get_block_info("DB", 1) print(block_info) Block type: 10 Block number: 1 Block language: 5 Block flags: 1 MC7Size: 100 Load memory size: 192 Local data: 0 SBB Length: 20 Checksum: 0 Version: 1 Code date: b'1999/11/17' Interface date: b'1999/11/17' Author: b'' Family: b'' Header: b'' ``` -------------------------------- ### API: Get Unsigned Integer (snap7.util.get_uint) Source: https://python-snap7.readthedocs.io/en/latest/API/util Retrieves an unsigned integer (2-byte) value from a bytearray. The possible range for this datatype is 0 to 65535. It takes the bytearray and a starting byte index, returning the integer value. ```APIDOC snap7.util.get_uint(bytearray_: bytearray, byte_index: int) -> int bytearray: buffer to read. byte_index: byte index from where to start reading. Returns: Value read. ``` -------------------------------- ### API: Get Real Value (snap7.util.get_real) Source: https://python-snap7.readthedocs.io/en/latest/API/util Retrieves a real (4-byte float) value from a bytearray. This datatype conforms to IEEE 754 binary32. It takes the bytearray and a starting byte index, returning the float value. ```APIDOC snap7.util.get_real(bytearray_: bytearray, byte_index: int) -> float bytearray: buffer to read from. byte_index: byte index to reading from. Returns: Real value. ``` -------------------------------- ### API: Get Integer Value (snap7.util.get_int) Source: https://python-snap7.readthedocs.io/en/latest/API/util Retrieves an integer value from a bytearray. In PLC, an int is represented in two bytes. This function takes the bytearray and a starting byte index as input, returning the integer value. ```APIDOC get_int(bytearray: bytearray, byte_index: int) -> int bytearray: buffer to read from. byte_index: byte index to start reading from. Returns: Value read. ``` -------------------------------- ### API: Get Unsigned Double Integer (snap7.util.get_udint) Source: https://python-snap7.readthedocs.io/en/latest/API/util Retrieves an unsigned double integer (4-byte) value from a bytearray. The possible range for this datatype is 0 to 4294967295. It takes the bytearray and a starting byte index, returning the integer value. ```APIDOC snap7.util.get_udint(bytearray_: bytearray, byte_index: int) -> int bytearray: buffer to read. byte_index: byte index from where to start reading. Returns: Value read. ``` -------------------------------- ### API: Get Small Integer Value (snap7.util.get_sint) Source: https://python-snap7.readthedocs.io/en/latest/API/util Retrieves a small integer (1-byte signed int) value from a bytearray. The possible range for this datatype is -128 to 127. It takes the bytearray and a starting byte index, returning the integer value. ```APIDOC snap7.util.get_sint(bytearray_: bytearray, byte_index: int) -> int bytearray: buffer to read from. byte_index: byte index from where to start reading. Returns: Value read. ``` -------------------------------- ### API: Get Time Value from Bytearray (snap7.util.get_time) Source: https://python-snap7.readthedocs.io/en/latest/API/util Retrieves a time value (4-byte) from a bytearray. This datatype represents PLC time, with specific maximum and minimum values. It takes the bytearray and a starting byte index, returning the time as a formatted string. ```APIDOC snap7.util.get_time(bytearray_: bytearray, byte_index: int) -> str bytearray: buffer to read. byte_index: byte index from where to start reading. Returns: Value read. ``` -------------------------------- ### Snap7 Server Class API Reference Source: https://python-snap7.readthedocs.io/en/latest/API/server Detailed API documentation for the `snap7.server.Server` class, which provides a fake S7 server implementation. It includes constructor details and methods for server creation, destruction, event handling, parameter retrieval, status checking, and event picking. ```APIDOC class snap7.server.Server(log: bool = True) Description: A fake S7 server. Method: __init__(log: bool = True) Description: Create a fake S7 server. set log to false if you want to disable event logging to python logging. Parameters: log (bool): True for enabling the event logging. Method: create() -> None Description: Create the server. Method: destroy() -> None Description: Destroy the server. Method: event_text(event: SrvEvent) -> str Description: Returns a textual explanation of a given event object Parameters: event (SrvEvent): an PSrvEvent struct object Returns: str: The error string Method: get_mask(kind: int) -> c_uint Description: Reads the specified filter mask. Parameters: kind (int): Returns: c_uint: Mask Method: get_param(number: int) -> int Description: Reads an internal Server object parameter. Parameters: number (int): number of the parameter to be set. Returns: int: Value of the parameter. Method: get_status() -> Tuple[str, str, int] Description: Reads the server status, the Virtual CPU status and the number of the clients connected. Returns: Tuple[str, str, int]: Server status, cpu status, client count Method: pick_event() -> SrvEvent | None Description: Extracts an event (if available) from the Events queue. Returns: SrvEvent | None: Server event. ``` -------------------------------- ### Initialize and Run Fake Snap7 Server Mainloop (Python) Source: https://python-snap7.readthedocs.io/en/latest/_modules/snap7/server Initializes and runs a fake Snap7 server, optionally with standard default values. It registers memory areas for DB, PA, TM, and CT, starts the server, and continuously picks and logs events. ```python server = Server() size = 100 db_data: CDataArrayType = (WordLen.Byte.ctype * size)() pa_data: CDataArrayType = (WordLen.Byte.ctype * size)() tm_data: CDataArrayType = (WordLen.Byte.ctype * size)() ct_data: CDataArrayType = (WordLen.Byte.ctype * size)() server.register_area(SrvArea.DB, 1, db_data) server.register_area(SrvArea.PA, 1, pa_data) server.register_area(SrvArea.TM, 1, tm_data) server.register_area(SrvArea.CT, 1, ct_data) if init_standard_values: logger.info("initialising with standard values") ba = _init_standard_values() userdata = WordLen.Byte.ctype * len(ba) server.register_area(SrvArea.DB, 0, userdata.from_buffer(ba)) server.start(tcp_port=tcp_port) while True: while True: event = server.pick_event() if event: logger.info(server.event_text(event)) else: break time.sleep(1) ``` ```APIDOC mainloop(tcp_port: int = 1102, init_standard_values: bool = False) -> None tcp_port: The TCP port that the server will listen on. Defaults to 1102. init_standard_values: If True, initializes some default values to be read on DB0. ``` -------------------------------- ### API: Get Long Real Value (snap7.util.get_lreal) Source: https://python-snap7.readthedocs.io/en/latest/API/util Retrieves a long real (8-byte float) value from a bytearray. This datatype conforms to IEEE 754 binary64 and covers a wide range of positive and negative values. It takes the bytearray and a starting byte index, returning the float value. ```APIDOC snap7.util.get_lreal(bytearray_: bytearray, byte_index: int) -> float bytearray: buffer to read from. byte_index: byte index from where to start reading. Returns: The real value. ``` -------------------------------- ### Example: Connect Snap7 Client to PLC Source: https://python-snap7.readthedocs.io/en/latest/API/client Demonstrates how to import the snap7 library, create a Client instance, and connect to a PLC at a specified IP address, rack, and slot. The TCP port defaults to 102. ```Python import snap7 client = snap7.client.Client() client.connect("192.168.0.1", 0, 0) # port is implicit = 102. ``` -------------------------------- ### Get Unsigned Integer Value from Bytearray (Python) Source: https://python-snap7.readthedocs.io/en/latest/_modules/snap7/util/getters Obtains a 16-bit unsigned integer from a bytearray, starting at a given index. This function internally leverages `get_word` to retrieve the value. It's specifically for PLC 'uint' data types, supporting values from 0 to 65535. ```python def get_uint(bytearray_: bytearray, byte_index: int) -> int: """Get unsigned int value from bytearray. Notes: Datatype `uint` in the PLC is represented in two bytes Maximum posible value is 65535. Lower posible value is 0. Args: bytearray_: buffer to read from. byte_index: byte index to start reading from. Returns: Value read. Examples: >>> data = bytearray([255, 255]) >>> get_uint(data, 0) 65535 """ return int(get_word(bytearray_, byte_index)) ``` -------------------------------- ### python-snap7 Server API Reference Source: https://python-snap7.readthedocs.io/en/latest/index Documentation for the `Server` class and related functions in the python-snap7 library, enabling the creation of a simulated S7 PLC server. ```APIDOC snap7.server.Server snap7.server.mainloop() snap7.server.__main__.main() ``` -------------------------------- ### Get Real (Float) Value from Bytearray (Python) Source: https://python-snap7.readthedocs.io/en/latest/_modules/snap7/util/getters Parses a 32-bit floating-point number (real) from a bytearray, starting at the specified index. It interprets four consecutive bytes according to the IEEE 754 binary32 standard. This function is crucial for reading PLC 'real' data types. ```python def get_real(bytearray_: bytearray, byte_index: int) -> float: """Get real value. Notes: Datatype `real` is represented in 4 bytes in the PLC. The packed representation uses the `IEEE 754 binary32`. Args: bytearray_: buffer to read from. byte_index: byte index to reading from. Returns: Real value. Examples: >>> data = bytearray(b'B\xf6\xa4Z') >>> get_real(data, 0) 123.32099914550781 """ x = bytearray_[byte_index : byte_index + 4] real: float = struct.unpack(">f", struct.pack("4B", *x))[0] return real ``` -------------------------------- ### Run python-snap7 Test Suite Source: https://python-snap7.readthedocs.io/en/latest/_sources/development.rst This command executes the comprehensive test suite for python-snap7, which includes nearly 100% code coverage. It verifies the functionality of the code and aids in development. Note that some tests may require root privileges due to snap7's need to bind on privileged TCP ports. ```Shell $ make test ``` -------------------------------- ### Get Word Value from Bytearray (Python) Source: https://python-snap7.readthedocs.io/en/latest/_modules/snap7/util/getters Reads a 16-bit unsigned integer (word) from a bytearray, starting at a given byte index. It combines two consecutive bytes from the buffer to form a value between 0 and 65535. This is particularly useful for handling PLC 'WORD' data types. ```python def get_word(bytearray_: bytearray, byte_index: int) -> bytearray: """Get word value from bytearray. Notes: WORD 16bit 2bytes Decimal number unsigned B#(0,0) to B#(255,255) => 0 to 65535 Args: bytearray_: buffer to get the word from. byte_index: byte index from where start reading from. Returns: Word value. Examples: >>> get_word(bytearray([0, 100]), 0) 100 """ data = bytearray_[byte_index : byte_index + 2] data[1] = data[1] & 0xFF data[0] = data[0] & 0xFF packed = struct.pack("2B", *data) value: bytearray = struct.unpack(">H", packed)[0] return value ``` -------------------------------- ### Snap7 Server API Reference Source: https://python-snap7.readthedocs.io/en/latest/_sources/API/server.rst Detailed API documentation for the `snap7.server` and `snap7.server.__main__` modules, including the `main` function and its parameters. ```APIDOC Module: snap7.server Description: The main Snap7 server module. All public members are documented. Module: snap7.server.__main__ Description: The main entry point module for the Snap7 server. Function: main(port, dll) Description: The primary function to start the Snap7 server. Parameters: port: (Type: Not specified, Description: Not provided in source documentation) dll: (Type: Not specified, Description: Not provided in source documentation) Returns: (Type: Not specified) ``` -------------------------------- ### Get Integer Value from Bytearray (Python) Source: https://python-snap7.readthedocs.io/en/latest/_modules/snap7/util/getters Extracts a 16-bit signed integer from a bytearray, starting at a specified byte index. The function interprets two consecutive bytes as a signed value. It's designed to correctly read PLC 'int' data types, which are represented in two bytes. ```python def get_int(bytearray_: bytearray, byte_index: int) -> int: """Get int value from bytearray. Notes: Datatype `int` in the PLC is represented in two bytes Args: bytearray_: buffer to read from. byte_index: byte index to start reading from. Returns: Value read. Examples: >>> get_int(bytearray([0, 255]), 0) 255 """ data = bytearray_[byte_index : byte_index + 2] data[1] = data[1] & 0xFF data[0] = data[0] & 0xFF packed = struct.pack("2B", *data) value: int = struct.unpack(">h", packed)[0] return value ``` -------------------------------- ### Snap7 Client Class Overview and Basic Usage Source: https://python-snap7.readthedocs.io/en/latest/_modules/snap7/client Defines the main `Client` class for interacting with Siemens S7 PLCs, providing methods for connection, data reading/writing, and PLC control. The example demonstrates basic connection, reading a data block, modifying it, and writing it back to the PLC. ```APIDOC class Client: """ A snap7 client """ _lib: Snap7CliProtocol _read_callback = None _callback = None _s7_client: S7Object ``` ```python import snap7 client = snap7.client.Client() client.connect("127.0.0.1", 0, 0, 1102) client.get_connected() # True data = client.db_read(1, 0, 4) data # bytearray(b"\x00\x00\x00\x00") data[3] = 0b00000001 data # bytearray(b'\x00\x00\x00\x01') client.db_write(1, 0, data) ``` -------------------------------- ### Create Snap7 Client Instance (Python Snap7) Source: https://python-snap7.readthedocs.io/en/latest/API/client Initializes and creates a new SNAP7 client instance. This method does not take any parameters and returns None. ```APIDOC create() -> None Returns: None. ``` -------------------------------- ### Snap7 Partner Class API Reference Source: https://python-snap7.readthedocs.io/en/latest/_modules/snap7/partner Comprehensive API documentation for the `Partner` class in Snap7, which enables peer-to-peer communication with Siemens S7 servers. This includes its constructor, destructor, and all public methods for sending/receiving data, checking completion, managing parameters, and retrieving status/statistics. ```APIDOC class Partner:\n """A snap7 partner."""\n _pointer: c_void_p\n\n __init__(self, active: bool = False)\n active: bool = False - If True, the partner is created in an active state.\n Description: Initializes a Partner object, loading the Snap7 library and creating the underlying partner handle.\n\n __del__(self) -> None\n Description: Destroys the Partner object, releasing resources.\n\n as_b_send(self) -> int\n Description: Sends a data packet to the partner asynchronously. Returns immediately, requires completion check.\n Returns: int - Result code from the Snap7 library.\n\n b_recv(self) -> int\n Description: Receives a data packet from the partner synchronously. Blocks until packet received or timeout.\n Returns: int - Result code from the Snap7 library.\n\n b_send(self) -> int\n Description: Sends a data packet to the partner synchronously. Blocks until transfer (send+ack) is complete.\n Returns: int - Result code from the Snap7 library.\n\n check_as_b_recv_completion(self) -> int\n Description: Checks if an asynchronous receive operation has completed.\n Returns: int - Result code indicating completion status.\n\n check_as_b_send_completion(self) -> Tuple[str, c_int32]\n Description: Checks if the current asynchronous send job was completed.\n Returns: Tuple[str, c_int32] - A tuple containing a status string ("job complete", "job in progress", "invalid handled supplied") and the operation result.\n Raises: ValueError - If the client parameter was invalid (result -2).\n\n create(self, active: bool = False) -> None\n active: bool = False - If True, the partner is created in an active state.\n Description: Creates a Partner and returns its handle.\n Returns: None - Sets the internal _pointer to the partner object.\n\n destroy(self) -> Optional[int]\n Description: Destroys a Partner instance, stopping it, disconnecting clients, and releasing shared memory.\n Returns: Optional[int] - Result code from the Snap7 library, or None if library is not loaded.\n\n get_last_error(self) -> c_int32\n Description: Returns the last job result (error code) from the partner.\n Returns: c_int32 - The last error code.\n\n get_param(self, parameter: Parameter) -> int\n parameter: Parameter - The internal parameter to read.\n Description: Reads an internal Partner object parameter.\n Returns: int - The value of the specified parameter.\n\n get_stats(self) -> Tuple[c_uint32, c_uint32, c_uint32, c_uint32]\n Description: Returns communication statistics for the partner.\n Returns: Tuple[c_uint32, c_uint32, c_uint32, c_uint32] - A tuple containing bytes sent, bytes received, send errors, and receive errors.\n\n get_status(self) -> c_int32\n Description: Returns the current status of the Partner.\n Returns: c_int32 - The partner's status code. ``` -------------------------------- ### Example: Set Unsigned Double Integer (udint) in Bytearray Source: https://python-snap7.readthedocs.io/en/latest/API/util Provides an example of using `set_udint` to write the maximum unsigned double integer value (4294967295) into a bytearray. ```python >>> data = bytearray(4) >>> set_udint(data, 0, 4294967295) >>> data bytearray(b'\xff\xff\xff\xff') ``` -------------------------------- ### python-snap7 Client API Reference Source: https://python-snap7.readthedocs.io/en/latest/index Documentation for the `Client` class in the python-snap7 library, used for connecting to and interacting with Siemens S7 PLCs. ```APIDOC snap7.client.Client ```