Logic Machine Forum
MQTT publish json - 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 publish json (/showthread.php?tid=2008)



MQTT publish json - JohnTH - 05.04.2019

Hi,

I am using admin`s mqtt script from this post: https://forum.logicmachine.net/showthread.php?tid=1759

Is there a way to change this:

  object_to_mqtt = {
    ['1/1/1'] = 'out/topic1',
    ['1/1/2'] = 'out/topic2',
  }
 
to send a variable that is a json string with multiple values (something like this):

valueX= grp.getvalue('32/3/1')
valueY= grp.getvalue('32/3/2')
topic1 = '{"site": "building", "equipment":"ventilation3601", "current_mode":"'..valueX..'", "current_status":"'..valueY..'"}'

  object_to_mqtt = {
    [topic1] = 'out/topic1',
    ['1/1/2'] = 'out/topic2',
  }

-John


RE: MQTT publish json - admin - 08.04.2019

Do you only need to publish states or do you need two-way communication?


RE: MQTT publish json - JohnTH - 08.04.2019

(08.04.2019, 09:50)admin Wrote: Do you only need to publish states or do you need two-way communication?

It would be nice to have publish and subscribe in the same scipt, but I already have another working script for subscription so not a must.

John


RE: MQTT publish json - admin - 09.04.2019

You can use event script to publish and disconnect after publish, like in this post: https://forum.logicmachine.net/showthread.php?tid=1793
Use json.encode to create your data string instead of creating JSON string manually.

This code will publish once connected and disconnect once publish is done.
Code:
client.ON_CONNECT = function(stat, code, err)
  if stat then
    client:publish('devices/' .. device_id .. '/messages/events/', data)
  else
    log('mqtt connect error', err, code)
  end
end

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



RE: MQTT publish json - JohnTH - 09.04.2019

(09.04.2019, 07:16)admin Wrote: You can use event script to publish and disconnect after publish, like in this post: https://forum.logicmachine.net/showthread.php?tid=1793
Use json.encode to create your data string instead of creating JSON string manually.

This code will publish once connected and disconnect once publish is done.
Code:
client.ON_CONNECT = function(stat, code, err)
 if stat then
   client:publish('devices/' .. device_id .. '/messages/events/', data)
 else
   log('mqtt connect error', err, code)
 end
end

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

Thanks! I will give it a try.