Net (HTTP / TCP / UDP)

The net functions let a Lua plugin talk directly to your own server, without going through obniz Cloud. They send and receive data over the network interface that the device is currently connected through, and cover three protocols: HTTP (net.http), raw TCP (net.tcp), and UDP (net.udp).

Use them when a device needs to reach an existing API, a private endpoint, or a service that obniz Cloud does not handle.


Common Behavior and Constraints

Read this section before using any of the net functions.

  • They follow the active network interface. HTTP and TCP run over whichever interface is currently connected — Wi-Fi, Ethernet, or LTE. UDP runs over Wi-Fi or Ethernet only, and is not available over LTE.
  • They block until they finish. Each call runs synchronously and does not return until the operation completes, fails, or times out. The communication watchdog is fed during the wait, so a long transfer does not reset the device. The handler that called the function, however, stays blocked in the meantime. Avoid long transfers inside on_online_loop() or on_offline_loop(), which are expected to return quickly.
  • Plain HTTP only — TLS is not supported. Connections are unencrypted. Use http:// URLs; https:// does not work. Send sensitive data only over a network you trust.
  • Keep to one socket at a time. Open a single connection, finish with it, and close it before opening the next. Depending on available memory and the active network interface, a second socket may or may not succeed, so do not rely on holding several open at once. Always close a socket you no longer need.
  • Errors are returned, not raised. On failure, a function returns nil followed by a short error string. Check the first return value before using the result.

net.http

net.http.get(url)

Performs an HTTP GET request and waits for the full response.

Argument Type Description
url string The target URL. Begins with http://. https:// is not supported.

Returns three values on success, or nil and an error string on failure.

Return Type Description
status number The HTTP status code, such as 200.
body string The response body.
headers string The raw response headers.
local status, body, headers = net.http.get("http://example.com/")
if status then
  os.log("status: " .. status .. ", length: " .. #body)
else
  os.log("error: " .. tostring(body)) -- on failure, the second value is the error string
end

net.http.post(url, body, contentType)

Performs an HTTP POST request with the given body.

Argument Type Description
url string The target URL.
body string The request body to send.
contentType string Optional. The Content-Type header. Defaults to application/octet-stream.

The return values are the same as net.http.get().

local voltage = ad.get(1) -- voltage of io1
local body = string.format('{"io":1,"voltage":%.3f}', voltage)

local status, resp = net.http.post("http://192.168.0.10:9002/ad", body, "application/json")
if status then
  os.log("POST -> " .. status .. " " .. resp)
else
  os.log("POST error: " .. tostring(resp))
end

net.http.request(options)

Performs a request with full control over the method, headers, body, and timeout. options is a table.

Field Type Description
url string Required. The target URL.
method string Optional. The HTTP method. Defaults to GET.
headers table Optional. Request headers, as { ["Key"] = "Value" } or { "Key: Value" }.
body string Optional. The request body.
timeout number Optional. The time to wait, in milliseconds. Defaults to 30000.

The return values are the same as net.http.get().

local status, body = net.http.request({
  url = "http://192.168.0.10:9002/config",
  method = "PUT",
  headers = {
    ["Content-Type"] = "application/json",
    ["X-Api-Key"] = "your-key",
  },
  body = '{"interval":60}',
  timeout = 10000, -- 10 seconds
})
if not status then
  os.log("request error: " .. tostring(body))
end

HTTP constraints

The HTTP client is intentionally small, so be aware of the following limits.

  • It sends Connection: close and reads until the server closes the connection. Keep-alive is not used.
  • It does not follow redirects. A 3xx response is returned as is.
  • It does not decode chunked transfer encoding or decompress gzip. The body is returned exactly as received, so request an uncompressed, unchunked response when you can.
  • The host name must be shorter than 128 characters.

net.tcp

net.tcp.connect(host, port)

Opens a plain TCP connection and returns a socket id. TLS is not supported.

Argument Type Description
host string The host name or IP address.
port number The port number.

Returns the socket id on success, or nil and an error string on failure. Pass the id to the other net.tcp functions.

local id, err = net.tcp.connect("192.168.0.10", 9001)
if not id then
  os.log("connect error: " .. tostring(err))
end

net.tcp.write(id, data)

Sends data over the connection. The call returns once all of the data has been sent, and times out after 30 seconds.

Argument Type Description
id number The socket id from net.tcp.connect().
data string The data to send.

Returns the number of bytes written, or nil and an error string on failure.

local written, err = net.tcp.write(id, "ping\n")
if not written then
  os.log("write error: " .. tostring(err))
end

net.tcp.read(id, maxlen)

Reads data that has already arrived. This call does not wait for new data.

Argument Type Description
id number The socket id.
maxlen number Optional. The maximum number of bytes to read. Defaults to 1024, with an upper limit below 4096.
Return Type Description
data string | nil The received data. An empty string ("") means no data has arrived yet. nil means the connection has closed or an error occurred.

Because read returns immediately, poll it across loop iterations rather than expecting a full message in a single call.

local data = net.tcp.read(id)
if data == nil then
  -- the connection was closed by the server (or an error occurred)
  net.tcp.close(id)
elseif #data > 0 then
  os.log("recv: " .. data)
end

net.tcp.close(id)

Closes the connection and releases the socket.

Example: Exchanging data over a persistent connection

The following plugin connects once, sends ping every 3 seconds, and logs what the server sends back. Because net.tcp.read() returns immediately, it is polled in every on_online_loop() call. Based on the net_tcp example.

local HOST = "192.168.0.10"
local PORT = 9001

local sock = nil
local tick = 0
local seq = 0

function on_online_loop()
  -- Connect once and keep the connection open
  if sock == nil then
    local id, err = net.tcp.connect(HOST, PORT)
    if not id then
      os.log("connect error: " .. tostring(err))
      sock = -1 -- do not retry in every loop
      return
    end
    sock = id
  end
  if sock == -1 then return end

  -- Send a message every 3 seconds
  if os.getTick() - tick > 3000 then
    tick = os.getTick()
    seq = seq + 1
    net.tcp.write(sock, "ping " .. seq .. "\n")
  end

  -- Poll for incoming data (does not wait)
  local data = net.tcp.read(sock)
  if data == nil then
    os.log("closed by server")
    net.tcp.close(sock)
    sock = -1
  elseif #data > 0 then
    os.log("recv: " .. data)
  end
end

For a larger example, the net_mqtt example implements a small MQTT client on top of net.tcp.


net.udp

UDP runs over Wi-Fi or Ethernet only. It is not available over LTE: on a cellular connection, net.udp.open() fails with udp not supported on cellular.

net.udp.open(localPort)

Opens a UDP socket and returns its id.

Argument Type Description
localPort number Optional. The local port to bind to. When omitted, the system assigns one.

Returns the socket id on success, or nil and an error string on failure.

local id, err = net.udp.open() -- the system assigns the local port
if not id then
  os.log("open error: " .. tostring(err)) -- for example, "udp not supported on cellular"
end

net.udp.sendTo(id, host, port, data)

Sends a datagram to the given destination.

Argument Type Description
id number The socket id.
host string The destination host name or IP address.
port number The destination port.
data string The datagram payload.

Returns the number of bytes sent, or nil and an error string on failure.

local sent, err = net.udp.sendTo(id, "192.168.0.10", 9003, "ping")
if not sent then
  os.log("send error: " .. tostring(err))
end

net.udp.receive(id, maxlen)

Receives one datagram. This call does not wait; it returns nil when no datagram is waiting.

Argument Type Description
id number The socket id.
maxlen number Optional. The maximum number of bytes to read. Defaults to 1024, with an upper limit below 4096.
Return Type Description
data string | nil The received payload, or nil when nothing is waiting.
ip string The sender's IP address.
port number The sender's port.
local data, ip, port = net.udp.receive(id)
if data then
  os.log("recv from " .. ip .. ":" .. port .. " -> " .. data)
end

net.udp.close(id)

Closes the socket.

Example: Sending and receiving datagrams

The following plugin sends ping to a UDP server every 3 seconds and logs every datagram it receives. Based on the net_udp example.

local HOST = "192.168.0.10"
local PORT = 9003

local sock = nil
local tick = 0
local seq = 0

function on_online_loop()
  if sock == nil then
    local id, err = net.udp.open()
    if not id then
      os.log("open error: " .. tostring(err))
      sock = -1 -- do not retry in every loop
      return
    end
    sock = id
  end
  if sock == -1 then return end

  -- Send a datagram every 3 seconds
  if os.getTick() - tick > 3000 then
    tick = os.getTick()
    seq = seq + 1
    net.udp.sendTo(sock, HOST, PORT, "ping " .. seq)
  end

  -- Poll for incoming datagrams (does not wait)
  local data, ip, port = net.udp.receive(sock)
  if data then
    os.log("recv from " .. ip .. ":" .. port .. " -> " .. data)
  end
end

Limits

Item Limit
TCP sockets open at the same time 8
UDP sockets open at the same time 4
Host name in a URL Shorter than 128 characters
Data returned by one net.tcp.read() / net.udp.receive() 1024 bytes by default, up to 4095 bytes
HTTP timeout 30000 ms by default. Only net.http.request() can change it.

These are upper limits. Whether a socket can actually be opened also depends on free memory and the active network interface.

The HTTP functions keep the whole response (headers and body) in memory. A large response uses as much memory as its size and can run the device out of memory. If the timeout elapses while the response is being received, the data received so far is returned. See Memory for how to keep memory use low.


Error Messages

On failure, the functions return nil and one of the following error strings.

Error string Meaning
connect failed: <code> The connection could not be established (for example, DNS resolution failed or the server did not accept the connection).
too many sockets 8 TCP sockets are already open. Close one with net.tcp.close().
too many udp sockets 4 UDP sockets are already open. Close one with net.udp.close().
invalid socket The socket id is invalid or already closed.
invalid url The URL could not be parsed. Use http://host[:port]/path.
url required url is missing in the options of net.http.request().
https not supported from net; use http:// An https:// URL was given. TLS is not supported.
tls (secure) not supported from net; use plain tcp A secure connection was requested with net.tcp.connect(). TLS is not supported.
write error / write timeout Sending over TCP failed, or did not finish within 30 seconds.
request send failed / body send failed Sending the HTTP request failed.
no response The HTTP server closed the connection or timed out without sending any data.
oom Not enough memory to hold the request or the response.
udp not supported on cellular UDP was used while connected over LTE.
socket failed / bind failed The UDP socket could not be created, or the local port could not be bound.
dns error The destination host name of net.udp.sendTo() could not be resolved.
send error Sending the UDP datagram failed.

Example: Posting an Analog Reading Every Minute

The following plugin reads the voltage on IO0 once a minute and sends it directly to your own server as JSON over plain HTTP. It runs entirely on the device and does not go through obniz Cloud.

last = 0;

function on_online_loop()
  -- Run once every 60 seconds
  if os.getTick() - last < 60 * 1000 then
    return;
  end
  last = os.getTick();

  -- Read the analog voltage on IO0
  local voltage = ad.get(0);
  local body = '{"voltage":' .. tostring(voltage) .. '}';

  -- POST it to your own server
  local status, resp = net.http.post("http://example.com/api/measurements", body, "application/json");

  if status == nil then
    -- On failure, the second value holds the error string
    os.log("post failed: " .. tostring(resp));
    return;
  end

  os.log("posted, status: " .. tostring(status));
end