gijzelaerr / python-snap7

A Python wrapper for the snap7 PLC communication library
http://python-snap7.readthedocs.org/
MIT License
632 stars 246 forks source link

as_db_read() doesnt work #481

Closed Grefee closed 6 months ago

Grefee commented 6 months ago

Hello if im not mistaken I suppose that as_db_read should be asynchronsou version of db_read function with the better thing that it returns the response code if we are actually able to connect to plc .. bcs as it is written on documentation teh function get_connected() sometimes returns true eventhough we lost connection to the plc.. so I would like to use as_db_read and if having returned code of 1 then try to reconnect .. so we actually try to access the datablock and check the connection by that ... yet the as_db_read is returing nothing for me or rather just zeros.. I created two same while loops one using as_db_read and second db_read and db read returns actual data I have in plc and as_db_read returns only 0

may I ask if im implementing the function not correctly or if its problem of the snap7? or any other solution how to check for established connection? im trying to build app which would run infinitelly .. but with the ability to reconnect automatically

client = snap7.client.Client()
client.connect("192.168.0.5", 0, 1)

while True:
    byte_length = 2
    datablock = 2001
    start_index_byte = 4

    data_buffer = client.db_read(datablock, start_index_byte, byte_length)

    data_exist = snap7.util.get_int(data_buffer, 0)

    print(f"response buffer ... {data_buffer}")
    print(f"data_exist: .. {data_exist}")

    time.sleep(1)

this returns :

data_exist: .. 98
response buffer ... bytearray(b'\x00b')
data_exist: .. 98
response buffer ... bytearray(b'\x00b')
data_exist: .. 98
response buffer ... bytearray(b'\x00b')
data_exist: .. 98
response buffer ... bytearray(b'\x00b')
data_exist: .. 98

and async function

client = snap7.client.Client()
client.connect("192.168.0.5", 0, 1)

while True:
    byte_length = 2
    datablock = 2001
    start_index_byte = 4

    data_buffer = (ctypes.c_uint8 * byte_length)()
    response_code = client.as_db_read(datablock, start_index_byte, byte_length, data_buffer)
    print(f"response_code {response_code}")
    if response_code != 0:
        print(f"not able to read DB to plc data .. prolly failed tcp")

    int_list = list(data_buffer)   
    int_list = [int(element) for element in int_list]
    print(int_list)

    time.sleep(1)

reutrns :

response_code 0
[0, 0]
response_code 0
[0, 0]
response_code 0
[0, 0]
response_code 0
[0, 0]

Thanks in advance and have a nice day:)