Introduction
When the Lua script becomes huge and complex it's time to split it into several Lua modules to simplify reading and support.
In this tutorial we will use ucm.lua
script which was introduced in the blueprint tutorial and do the following:
- Extract commands into separate module.
- Add a dependency to use existing Lua module.
Show ucm.lua
-- Obtain device properties and send it to Enapter Cloud
function send_properties()
enapter.send_properties({
-- We could have called Modbus API here, but use
-- constant value for the example simplicity
serial_number = "AC001215"
})
end
-- Store active alerts as a global array
-- Empty array means there are no alerts by default
active_alerts = {}
-- Obtain device telemetry attributes and send it to Enapter Cloud
function send_telemetry()
enapter.send_telemetry({
-- Again, we use constant value for simplicity
h2_concentration = 0.01,
-- Pass active_alerts into telemetry
alerts = active_alerts
})
end
-- "beep" command implementation
function beep_command(ctx, args)
-- Add h2_high to active alerts array
active_alerts = {"h2_high"}
-- Send some reply back to the user as a text message
return "Sound alarm started"
end
-- "silence" command implementation
function silence_command(ctx, args)
-- Clean active alerts array
active_alerts = {}
return "Sound alarm stopped"
end
-- Register periodic function, will send properties every 30 seconds
scheduler.add(30000, send_properties)
-- Register periodic function, will send telemetry every 1 second
scheduler.add(1000, send_telemetry)
-- Register "beep" and "silence" commands, the function passed as a second argument
-- will be executed every time user starts the command from UI
enapter.register_command_handler("beep", beep_command)
enapter.register_command_handler("silence", silence_command)