fg71
Unfortunately the maintainer of python-snap7 have decided to make native implementation of S7 communication and still use the name python-snap7. It could make it very confusing for new users and old who have study the original implementation of the Snap7 C Library when same function use different meaning.
 
So I have decided to use other python library: python-s7comm
 
This code do:
Reading/writing to DB1.DBW2 with the value 1234. The code use start address of 2 with data type WORD of length 1.
 
The module is called: python-s7comm
 
import asyncio
from python_s7comm import AsyncClient

async def main():
    client = AsyncClient()
    await client.connect("IP_PLC", 0, 0)

    if (client.is_connected):
        print("Connected to PLC")

    data = await client.read_area("DB1.2 WORD 1")
    print(f"DB1.DBW2: {int.from_bytes(data, 'big', signed=True)}")

    # write value 1234 to DB1.DBW2
    await client.write_area("DB1.2 WORD 1", int.to_bytes(1234, 2, "big", signed=True))
    await client.disconnect()

if __name__ == "__main__":
    asyncio.run(main())
 
Reply 0 0
fg71
Here is updated version
 

from python_s7comm import Client

from time import sleep

client = Client()
client.connect("IP_PLC", 0, 0)


while True:
    sleep(1)
    # Ensure big-endian for Siemens PLCs

    # We use variable memory V0.1
    client.write_area("DB1.0.1 BOOL 1", bool.to_bytes(True, 1, "big"))
    data = client.read_area("DB1.0.1 BOOL 1")
    print(f"DB1.0.1: {bool.from_bytes(data, 'big', signed=False)}")
    sleep(.3)
    client.write_area("DB1.0.1 BOOL 1", bool.to_bytes(False, 1, "big"))
    data = client.read_area("DB1.0.1 BOOL 1")
    print(f"DB1.0.1: {bool.from_bytes(data, 'big', signed=False)}")
    sleep(1)

    # We use memory marker M2 with start byte 1104 and bit 2 (bit start at 0)
    client.write_area("DB1.1104.1 BOOL 1", bool.to_bytes(True, 1, "big"))
    data = client.read_area("DB1.1104.1 BOOL 1")
    print(f"DB1.1104.1: {bool.from_bytes(data, 'big', signed=False)}")
    sleep(.3)
    client.write_area("DB1.1104.1 BOOL 1", bool.to_bytes(False, 1, "big"))
    data = client.read_area("DB1.1104.1 BOOL 1")
    print(f"DB1.1104.1: {bool.from_bytes(data, 'big', signed=False)}")
    sleep(1)


    # Write analog value AM1 start address 1118 with size word
    client.write_area("DB1.1118 WORD 1", int.to_bytes(1234, 2, "big", signed=False))
    # Read analog value AM1 start address 1118 with size word
    data = client.read_area("DB1.1118 WORD 1")
    print(f"DB1.1118: {int.from_bytes(data, 'big', signed=False)}")
    sleep(1)
    client.write_area("DB1.1118 WORD 1", int.to_bytes(3456, 2, "big", signed=False))
    data = client.read_area("DB1.1118 WORD 1")
    print(f"DB1.1118: {int.from_bytes(data, 'big', signed=False)}")
    sleep(1)
    client.write_area("DB1.1118 WORD 1", int.to_bytes(4321, 2, "big", signed=False))
    data = client.read_area("DB1.1118 WORD 1")
    print(f"DB1.1118: {int.from_bytes(data, 'big', signed=False)}")
 
Reply 0 0
Reply