I'm new to pymodbus. I am trying to create a custom request to be sent to a TCP client, this specific request needs to have 3 exclamation marks at the beginning of the message. an example message request would be 21 21 21 01 7F 07 40 01 00 88 00 00 in hex, I've tried to follow the custom message example from the pymodbus documentation examples and change the encode function in the request class but I'm not getting any response back. is there any way I can send this specific message and then read the response from the modbus device? this specific function should return the date and time in the device. Thanks!
class CustomBSCRACRequest(ModbusRequest):
"""Custom modbus request."""
function_code = 127
_rtu_frame_size = 8
command = 136
flags = 64
dest_task = 0
def __init__(self, address=None, **kwargs):
"""Initialize."""
ModbusRequest.__init__(self, **kwargs)
self.address = address
self.count = 7
def encode(self):
"""Encode."""
return struct.pack(">HHHHHHHHH", 33, 33, 33, self.address, self.count, self.flags, self.address, self.dest_task, self.command)
To solve this problem I used created a new framer that edits the header of the message that is sent to the device. Pymodbus uses framers that are responsible to create the bytes message, in this case, I've created a framer that inherits from ModbusRtuFramer and overwritten the buildPacket method by adding the needed header. I also needed to overwrite the argument _hsize to the right size of my new header (everything before the function code) in my case this was 4. Lastly, because this is a special request message, it doesn't have the unit ID in the same position as normal RTU responses, thus, the populateHeader method was modified as well to point to the right byte for the unit ID. This is a very particular case but in general, what someone with a similar problem needs to do is create a new framer class and modify the buildPacket method initially and then all the other header-dependent methods. After creating the framer, it is easier to follow the custom message example. I included the buildPacket method for my particular case