udpReceive (Functionblock)

Top  Previous  Next

Architecture:

X32 / NX32 / NX32L

Device support:

All

Firmware version:

1.00 / 1.00.00


This receives data as a connectionless UDP packet from the specified connection. This function block will indicate when data is ready and placed into the receive buffer.

 

 

Input:

id : SINT

ID for the connection as returned by udpStartListen().

 

data : PTR

Address of the buffer that contains the received data.

 

maxsize : INT

Maximum number of bytes that can be received (size of "data").

The maximum size of any UDP package is 1540 bytes.

If a data package larger than "maxsize" is received, the data will be truncated but still delivered.

 

Output:

ready : BOOL

True if data has been received.

 

size : INT

Number of bytes received (if "ready" is true).

 

ip : INT

IP address of sender (if "ready" is true).

 

port : DINT

IP port of the sender (if "ready" is true).

 

iface : SINT

The network interface where the data was received (if "ready" is true). 1 = Mobile network, 2 = LAN network, etc. (See Network).

 

 

Declaration:

FUNCTION_BLOCK udpReceive;
VAR_INPUT
  id      : SINT; // ID of the connection.
  data    : PTR; // Address of receive buffer
  maxsize : INT; // Maximum number of bytes we can receive (size of 'data')
END_VAR;
VAR_OUTPUT
  ready   : BOOL; // data is ready
  iface   : SINT; // The network interface the data was received on.
  size    : INT;  // Number of bytes received
  ip      : DINT; // IP-address of sender.
  port    : DINT; // IP-port of the sender
END_VAR;

 

 

Example:

INCLUDE rtcu.inc
 
PROGRAM udp_server;
VAR
  fbReceive : udpReceive;           // Receive data on a UDP socket
  port     : INT := 2500;           // port to receive data on
  udp_id   : SINT;                 // listener ID
  host     : STRING;               // translated IP
  line     : STRING;               // ASCII string to send
  data     : ARRAY[1..255] OF SINT; // received data buffer
  rc       : INT;                   // return code of command
END_VAR;
 
gsmPower(power := ON);
gprsOpen();
 
// Wait for the cellular connection to be established
WHILE NOT gprsConnected() DO
  DebugMsg(message := "Waiting for cellular connection");
  Sleep(delay := 2500);
END_WHILE;
 
// Listen for incoming connection on a UDP port
udp_id := udpStartListen(port := port, rip := 0);
BEGIN
  // update udp received data
  fbReceive(id := udp_id, data := ADDR(data), maxsize := SIZEOF(data));
 
  IF fbReceive.ready THEN
     host := sockIPToName(ip := fbReceive.ip);
     DebugFmt(message := "Received '\1' bytes from '" + host + "'", v1 := fbReceive.size);
    line := strFromMemory(src := ADDR(data), len := fbReceive.size);
    DebugMsg(message := "Message : " + line);
  END_IF;
END;
END_PROGRAM;