I managed to indirectly find a very simple solution from some OPC tutorial. I used an Interpreted Matlab Fcn block and inside the block I wrote a function which creates a connection and sends data to PLC over TCP/IP. In order to reuse the old connection instead of making a new one every time I defined my TCPIP object as a consistent variable (details here). This way the variable is stored in Matlab memory when the block is not executing.
function [x] = dataWriteandReadTCPIP(b)
persistent init_Server;
persistent tcpClient;
persistent testVal;
persistent bytesAvailable;
if (isempty(init_Server))
testVal = 0;
%bytesAvailable = 0;
init_Server = 0;
end
if init_Server == 0
init_Server = 1;
tcpClient = tcpip('0.0.0.0', 2000, 'NetworkRole', 'server');
tcpClient.InputBufferSize=4;
fopen(tcpClient);
end
A = single(b);
B = typecast(A,'uint8');
C = fliplr(B);
fwrite(tcpClient, C);
newBytesAvailable = get(tcpClient,'BytesAvailable');
if newBytesAvailable > 0
data_Temp = fread(tcpClient, 4);
data_Temp = flipud(data_Temp);
data_Temp = uint8(data_Temp);
testVal = typecast(data_Temp,'single');
bytesAvailable = newBytesAvailable;
end
x=double(testVal);
end