This forum uses cookies
This forum makes use of cookies to store your login information if you are registered, and your last visit if you are not. Cookies are small text documents stored on your computer; the cookies set by this forum can only be used on this website and pose no security risk. Cookies on this forum also track the specific topics you have read and when you last read them. Please confirm that you accept these cookies being set.

Smappee inifinity Energy Monitoring to KNX
#4
Resident script (sleep time = 0), log(msg) will output the received real-time data decoded from JSON.
Code:
if not broker then
  require('json')
  require('socket')

  broker, port = '127.0.0.1', 1883
  mclient = require('mosquitto').new()

  mclient.ON_CONNECT = function(res, rc, msg)
    log('mqtt connect status', res, rc, msg)

    if res then
      mclient:subscribe('servicelocation/+/realtime')
    else
      mclient:disconnect()
    end
  end

  mclient.ON_MESSAGE = function(mid, topic, payload)
    local msg = json.pdecode(payload)
    if type(msg) == 'table' then
      log(msg)
    end
  end

  mclient.ON_DISCONNECT = function(...)
    log('mqtt disconnect', ...)
    mclientfd = nil
  end

  mclient.ON_ERROR = function(...)
    log('callback error', ...)
  end

  function mconnect()
    local fd

    mclient:connect(broker, port)
    fd = mclient:socket()

    -- fd ref is valid
    if fd then
      mclientfd = fd
    end
  end

  mconnect()

  -- run timer every 5 seconds
  timer = require('timerfd').new(5)
  timerfd = socket.fdmaskset(timer:getfd(), 'r')
end

-- mqtt connected
if mclientfd then
  mclientfdset = socket.fdmaskset(mclientfd, mclient:want_write() and 'rw' or 'r')
  res, timerstat, mclientstat = socket.selectfds(10, timerfd, mclientfdset)
-- mqtt not connected
else
  res, timerstat = socket.selectfds(10, timerfd)
end

if res then
  if mclientfd and mclientstat then
    if socket.fdmaskread(mclientstat) then
      mclient:loop_read()
    end

    if socket.fdmaskwrite(mclientstat) then
      mclient:loop_write()
    end
  end

  if timerstat then
    -- clear armed timer
    timer:read()

    if mclientfd then
      mclient:loop_misc()
    else
      mconnect()
    end
  end
end
Reply


Messages In This Thread
RE: Smappee inifinity Energy Monitoring to KNX - by admin - 20.01.2021, 09:19

Forum Jump: