Skip to main content
. 2025 Jul 30;25(15):4701. doi: 10.3390/s25154701
Listing 4. Share: service temperature_check.
temperature_check = Service.new("2.5.8.4.1", -- declaration service
  function()
    return function(temp, threshold, ip)
      local tcp = socket.tcp() -- Initialize tcp socket
      local host, port = ip, 8888
      tcp:connect(host, port)
      tcp:send(temp .. ’,’ .. threshold)
      local result, status = tcp:receive() -- Get response once
      tcp:close() -- Close connection
      return result
    end
  end,

  function()
    local server = socket.bind("*", 8888)
    while true do
      local client = server:accept()
      local data, err = client:receive()
      if not err then
        local temp, threshold = data:match("([^,]+),([^,]+)")
        temp, threshold = tonumber(temp), tonumber(threshold)
        if temp and threshold and temp >= threshold then
          client:send("ALERT: Temperature exceeded threshold!")
        else
          client:send("Temperature is within normal range.")
        end
      end
      client:close() -- Close client connection
      -- No break here to allow continuous operation
    end
  end,

  function(temp, threshold)
    return temp >= -50 and temp <= 150 and threshold > 0
  end
)

deviceB = Share.new(Myip)
deviceB.attach(temperature_check)