Simple IOT dumper for MQTT in Lua

Here is a short module for dumping topics on MQTT in Lua?

2 minute read

I decided to post all the data from my ESP8266 projects using MQTT to my Mosquitto broker. Even if I am not doing something useful with it right now, I want to capture the data at least.

Lua to the rescue!

Here is a small dumper written in Lua that will write one big file with the data of the subscribed topic. Something simple, but it might be helpful if you are looking for this.

You need the following dependencies installed:

#!/usr/bin/lua

local mqttclient = require("luamqttc/client")
local argparse = require "argparse"
local parser = argparse() {
   name = "mqtt_dump",
   description = "A script to save mqtt subscription values.",
}
parser:option "-h" "--host"
   :argname "<server hostname>"
parser:option("-o --output", "<output file>", "mqtt_dump.log")
parser:option("-h --host", "<server hostname>", "localhost")
parser:option("-p --port", "<port number>", "1883")
parser:option("-u --user", "<user>", "")
parser:option("-p --pass", "<password>", "")
parser:option("-t --topic", "<topic>", "#")

local args = parser:parse()
local host = args.host
local port = args.port
local user = args.user
local pass = args.pass
local dump_topic = args.topic
local timeout = 1

file = io.open(args.output, "a")
local aclient = mqttclient.new("mqtt_dump",{username = user, password = pass, keep_alive = 180})

local callback = function(topic, data, packet_id, dup, qos, retained)
    print("DUMP: ", os.time(), topic, data, qos)
    file:write(os.time(),";",topic,";", data,"\n")
end

aclient:connect(host, port, {timeout = timeout})
aclient:subscribe(dump_topic, 2, callback)
aclient:message_loop()
aclient:disconnect()
file:close()
comments powered by Disqus