After more debugging and tinkering with the code, eventually it turned out its not a problem with the software but with the serial port on the computer where my code worked. With the help of someone else I was able to use a logic analyzer and saw that on the /dev/ttyS0
port the request goes successfully to the Modbus RTU device but the response did not arrive properly. It seems like the port is being used for something else too even though I used before that linux commands in the terminal to check if the port is being used and I saw nothing then.
After finding this out, I moved the RS-485 cable to the other serial port present on the computer /dev/ttyS1
and then everything worked fine.
Thank you all for the input. Hopefully this is useful for other people in need too.