Logic Machine Forum
Mqtt broker app communication with local client event based script - Printable Version

+- Logic Machine Forum (https://forum.logicmachine.net)
+-- Forum: LogicMachine eco-system (https://forum.logicmachine.net/forumdisplay.php?fid=1)
+--- Forum: Scripting (https://forum.logicmachine.net/forumdisplay.php?fid=8)
+--- Thread: Mqtt broker app communication with local client event based script (/showthread.php?tid=4579)



Mqtt broker app communication with local client event based script - Rajesh - 13.02.2023

broker = "localhost"
port = 1883
username = "admin"
password = "password"
topic = "casambi/1/set/target_level"

value = event.getvalue()

if value == 1
  then
  topic = "casambi/1/set/target_level"
payload = tostring"("level":255,"duration":1,"targetid":177,"targettype":1,)"
else
  payload = tostring"("level":0,"duration":1,"targetid":177,"targettype":1,)"
  end
 
mqtt = require("mosquitto")
client = mqtt.new()

client.ON_CONNECT = function(status, rc, msg)
  if status then
    log("mqtt connected")
    client:publish(topic, tostring(payload))
  else
    log("mqtt connect failed " .. tostring(msg))
    client:disconnect()
  end
end

client.ON_PUBLISH = function()
  client:disconnect()
end

client:login_set(username, password)
status, rc, msg = client:connect(broker, port)

if status then
  client:loop_forever()
else
  log("connect failed: " .. tostring(msg))
end

Error log shows:
attempt to call global 'level' (a nil value)
stack traceback:


RE: Mqtt broker app communication with local client event based script - admin - 13.02.2023

Your tostring() call is incorrect. If this is an event script then value is true / false not 1 / 0. Are you sure about the payload format? Is it JSON?


RE: Mqtt broker app communication with local client event based script - Rajesh - 13.02.2023

(13.02.2023, 12:31)admin Wrote: Your tostring() call is incorrect. If this is an event script then value is true / false not 1 / 0. Are you sure about the payload format? Is it JSON?

Yes the paylod format is in JSON format


RE: Mqtt broker app communication with local client event based script - admin - 13.02.2023

Code:
value = event.getvalue()

level = value and 255 or 0

payload = require('json').encode({
  level = level,
  duration = 1,
  targetid = 177,
  targettype = 1,
})

mqtt = require("mosquitto")



RE: Mqtt broker app communication with local client event based script - Rajesh - 14.02.2023

Thank you admin it's working. but for to get the data from mqtt server in json and load the particular data in group address on event based script.


RE: Mqtt broker app communication with local client event based script - admin - 14.02.2023

See this example: https://forum.logicmachine.net/showthread.php?tid=1759&pid=10926#pid10926