arjunitedred
Member
Hi all,
My objective is to send data of type int, bool, string etc from the PLC to PC via TCP sockets. I have used the client/server codes to establish a connection and send the data over sockets but I am not sure how I can extract this data from the PC side so that I can insert into a database. I have a written a Python API to do this but I haven't got much success so far. Below are the codes for server/client on the PLC.
Could you please help me out and point out where exactly I am going wrong?
My objective is to send data of type int, bool, string etc from the PLC to PC via TCP sockets. I have used the client/server codes to establish a connection and send the data over sockets but I am not sure how I can extract this data from the PC side so that I can insert into a database. I have a written a Python API to do this but I haven't got much success so far. Below are the codes for server/client on the PLC.
Could you please help me out and point out where exactly I am going wrong?
Code:
Server:
PROGRAM PLC_PRG
VAR
fbTCPConnectionAsync: IL_TCPConnectionAsync;
fbTCPSendAsync: IL_TCPSendAsync;
udiSocket: UDINT;
strHello: STRING := 'Hello World!$r$n'; (* text to send *)
END_VAR
IF fbTCPConnectionAsync.Done = FALSE THEN
fbTCPConnectionAsync(Enable:=TRUE, Server:=TRUE, Port:=27017, Socket=>udiSocket);
IF fbTCPConnectionAsync.Error = TRUE THEN
fbTCPConnectionAsync(Enable:=FALSE, Socket=>udiSocket);
END_IF
ELSE
fbTCPSendAsync(Enable:=TRUE, Socket:=udiSocket, ValueAdr:=ADR(strHello), NoOfBytes:=LEN(strHello));
IF fbTCPSendAsync.Done=TRUE OR fbTCPSendAsync.Error=TRUE THEN
fbTCPSendAsync(Enable:=FALSE);
fbTCPConnectionAsync(Enable:=FALSE, Socket=>udiSocket);
END_IF
END_IF
Client:
PROGRAM PLC_PRG
VAR
fbConnection: IL_TCPConnectionAsync;
fbSend: IL_TCPSendAsync;
fbRecv: IL_TCPRecvAsync;
udiSocket: UDINT := SOCKET_INVALID;
strSend: STRING := 'Hello';
strRecv: STRING;
iState: INT := 0;
END_VAR
CASE iState OF
0:
fbConnection(Enable:=FALSE);
fbSend(Enable:=FALSE);
fbRecv(Enable:=FALSE);
diSocket := SOCKET_INVALID;
iState := 1;
1:
fbConnection(Enable:=TRUE, Server:=FALSE, Address:='127.0.0.1', Port:=27017);
IF fbConnection.Done=TRUE THEN
(* Connection established *)
udiSocket := fbConnection.Socket;
iState := 2;
END_IF
2:
(* Send some data *)
fbSend(Enable:=TRUE, Socket:=udiSocket, ValueAdr:=ADR(strSend), NoOfBytes:=LEN(strSend));
IF fbSend.Done=TRUE THEN
(* Send done *)
fbSend(Enable:=FALSE);
iState := 3;
END_IF
3:
(* Receive some data *)
fbRecv(Enable:=TRUE, Socket:=udiSocket, ValueAdr:=ADR(strRecv), NoOfBytes:=SIZEOF(strRecv)-1);
IF fbRecv.Done=TRUE THEN
(* Received some data *)
strRecv := LEFT(strRecv, UDINT_TO_INT(fbRecv.NoOfRecBytes)); (* end of string marker *)
fbRecv(Enable:=FALSE);
iState := 4;
END_IF
4:
(* Close the connection *)
fbConnection(Enable:=FALSE);
diSocket := SOCKET_INVALID;
END_CASE
Last edited: