MQTT client app

MQTT client - LM application #

MQTT payload to object value #

MQTT payload is decoded using JSON. Writing to object is done using the following rules for the decoded value:

  • JSON null - no write is performed
  • Invalid JSON (Lua nil) - the original payload string is written
  • Valid JSON - the decoded JSON value is written

Object value to MQTT payload #

Object value is converted to MQTT payload using the following rules:

  • boolean is converted to '1' or '0'
  • table is encoded using JSON
  • number is converted to a string via tostring
  • string is sent as is

Scripts - In (From MQTT) #

Script provides two global variables:

  • topic (string) - topic name
  • payload (string) - payload data

Script must end with a return statement unless the mapped object is not set.


Scripts - Out (To MQTT) #

Script provides one global variable:

  • value (boolean, number, string or table depending on the data type) - object value

Script must end with a return statement.

The returned script value is converted to MQTT payload using the same rules as for topics without scripts except for invalid types (including nil). Invalid values are not published.


Examples #

String to boolean conversion #

MQTT device uses 'on' or 'off' (string) for status and control.

In (From MQTT) script - converts payload string to boolean #
return payload == 'on'
Out (To MQTT) script - converts boolean to payload string #
return value and 'on' or 'off'

JSON payload (single value) #

MQTT payload is the following JSON:

{ "id": "0", "battery": { "V": 2.99, "percent": 98 } }

In (From MQTT) script - gets the battery percent from the JSON object #
local data = json.pdecode(payload)
if type(data) == 'table' then
  return data.battery.percent
end

JSON payload (multiple values) #

MQTT payload is the following JSON:

{ "temperature": 24.5, "humidity": 45 }

In this case no object is mapped to the MQTT topic. Script handles writing multiple values to objects.

In (From MQTT) script - multiple values to objects #
local data = json.pdecode(payload)
if type(data) == 'table' then
  grp.checkwrite('1/1/1', data.temperature)
  grp.checkwrite('1/1/2', data.humidity)
end