I'm using pyads to pull data from a PLC via ADS and process this data in python. Since I have to pull the data quite fast (200 ms cycle) I use a ADS notification to get the values always when they change which is every 200 ms or faster.
In a while Loop I'm waiting for data coming in and putting them together to an array. I have to go that path because the amount of data is high. 1000 values per cycle and I have to put them together so I get an array of 100000 values per signal. There can be 15 signals together. Below you can find the example from the pyads documentation. What I'm looking for is nice Pythonic way to get the values from the callback function inside a while loop and build them together to the 100000 value array. I thought about creating a class which handles what I need but I couldn't find a way to make it work. Only option I can imagine is using a global variable which I don't like to do.
structure_def = (
('nVar', pyads.PLCTYPE_DINT, 1000),
('nVar2', pyads.PLCTYPE_DINT, 1000),
('nVar3', pyads.PLCTYPE_DINT, 1000),
('nVar4', pyads.PLCTYPE_DINT, 1000),
('nVar5', pyads.PLCTYPE_DINT, 1000))
size_of_struct = pyads.size_of_structure(structure_def)
@plc.notification(ctypes.c_ubyte * size_of_struct)
def callback(handle, name, timestamp, value):
values = pyads.dict_from_bytes(value, structure_def)
print(values)
attr = pyads.NotificationAttrib(size_of_struct)
plc.add_device_notification('global.sample_structure', attr, callback)
Use of a global variable will work of course. I tried to pull 100000 values at once but it fails when the amount of signals increases. So I have to pull smaller packets.
You can use a class, you just can't use the decorator inside a class unfortunately.
See this example
An example for detecting the plc status change:
Doing it in a class means you can then have more methods for doing the signal processing etc.
Also depending on what kind of data you are pulling, there can be more efficient ways of converting the byte data back to python types which is useful for data logging applications. Using Read structure by name means pyads does all the conversion for you on a variable by variable basis. You can do a read_by_name with return_ctypes=True and parse the data yourself. This can be orders of magnitude quicker if your data is all the same type as you can do the conversion using numpy for example. see https://github.com/stlehmann/pyads/issues/289 and https://github.com/stlehmann/pyads/issues/63