07.12.2023, 08:52
Create a resident script with non-zero sleep time. Modify username, password and topicname variables as needed. Change group addresses in the ON_MESSAGE callback.
Code:
broker = 'eu1.cloud.thethings.network'
port = 8883
username = 'PUT_USER_HERE@ttn'
password = 'PUT_API_KEY_HERE'
topicname = 'v3/sensor-well-level@ttn/devices/eui-xxxxxxxxxxxxxxxx/up'
require('json')
mqtt = require('mosquitto')
client = mqtt.new()
client.ON_CONNECT = function(status, rc, msg)
if status then
log('mqtt connected')
client:subscribe(topicname)
else
log('mqtt connect failed ' .. tostring(msg))
client:disconnect()
end
end
client.ON_MESSAGE = function(mid, topic, payload)
local data = json.pdecode(payload)
if type(data) ~= 'table' then
return
end
local datetime = data.received_at
local sensor = data.uplink_message.decoded_payload
grp.checkwrite('1/1/1', datetime)
grp.checkwrite('1/1/2', sensor.Bat_V)
grp.checkwrite('1/1/3', sensor.IDC_intput_mA)
grp.checkwrite('1/1/4', sensor.Water_deep_cm)
end
client.ON_ERROR = log
client:login_set(username, password)
client:tls_insecure_set(true)
status, rc, msg = client:connect(broker, port)
if status then
client:loop_forever()
else
log('connect failed: ' .. tostring(msg))
end