UDP Helpers
UDP helper functions provide convenient Lua APIs for sending UDP datagrams from scripts. These functions handle destination addressing, metadata creation, and message scheduling.
API Reference
udp_send(destination_address, destination_port, payload, delay, connection_id) → boolean
Send a UDP datagram to a specified destination address and port.
Parameters:
destination_address(string) - Target IP address or hostname (required, cannot be nil or empty)destination_port(number) - Target UDP port number (required, must be 1-65535)payload(string) - Datagram payload as binary string (can be empty)delay(number) - Delay in milliseconds before sendingconnection_id(number, optional) - Target connection ID (default: 0)
Returns:
true- Datagram scheduled successfullyfalse- Failed to schedule (channel closed or error)- Error - If destination_address is nil/empty or destination_port is invalid
Important Notes:
- Destination Required: UDP transport requires explicit destination for each message. Unlike connection-oriented protocols, there is no default destination.
- Binary Data: Payload is treated as raw binary data, supporting any byte values including null bytes.
- Port Validation: Port 0 is invalid and will raise an error.
Example:
-- Send simple text message to UDP server
udp_send("192.168.1.100", 8888, "Hello UDP", 0)
-- Send to specific connection after 200ms delay
udp_send("localhost", 9000, "Delayed message", 200, 1)
-- Send binary data
local binary_payload = string.char(0xFF, 0x00, 0xAB, 0xCD)
udp_send("10.0.0.50", 5000, binary_payload, 0)
-- Send empty datagram (keepalive)
udp_send("192.168.1.1", 12345, "", 0)
-- Send to hostname
udp_send("iot.example.com", 8080, "sensor_data", 0)
Use Cases
Periodic Sensor Broadcasting:
function on_timer(elapsed_ms)
if elapsed_ms % 5000 == 0 then -- Every 5 seconds
local sensor_data = string.format("temp:%.1f,humidity:%.1f", 23.5, 65.2)
udp_send("192.168.1.100", 9000, sensor_data, 0)
end
end
Protocol Gateway:
function on_receive()
-- Forward serial data to UDP server
local payload = message.payload
udp_send("10.0.0.10", 5555, payload, 0)
return false
end
Multi-Target Broadcasting:
function on_send()
-- Broadcast to multiple UDP destinations
local servers = {
{addr = "192.168.1.10", port = 8000},
{addr = "192.168.1.20", port = 8000},
{addr = "192.168.1.30", port = 8000}
}
for _, server in ipairs(servers) do
udp_send(server.addr, server.port, message.payload, 0)
end
return false
end
See Also
- Lua Script Overview - Core Lua scripting concepts and hooks
- Message API - Message object methods and binary reading functions
- Modbus Helpers - Modbus protocol helpers
- MQTT Helpers - MQTT publish helper