23.12.2022, 13:00
Create a scheduled script that runs every hour. Modify ids table as needed: key is id in the CSV, value is the trend log name. Also fill in correct mail settings and to variable.
Code:
ids = {
['707057500075005871'] = 'Temperature',
['213123123123123123'] = 'Humidity',
}
require('trends')
dates = {}
dates['start'] = os.date('*t')
dates['start'].day = dates['start'].day - 1
dates['end'] = os.date('*t')
buf = {}
now = os.time()
for id, tname in pairs(ids) do
values = trends.fetch(tname, dates)
count = #values
step = 86400 / count
for i, value in ipairs(values) do
buf[ #buf + 1 ] = {
now - (count - i) * step,
id,
value
}
end
end
table.sort(buf, function(a, b)
return a[ 1 ] > b[ 1 ]
end)
for i, row in ipairs(buf) do
row[ 1 ] = os.date('%Y-%m-%d %H:%M', row[ 1 ])
buf[ i ] = table.concat(row, ',')
end
csv = table.concat(buf, '\n')
to = 'to@example.com'
settings = {
-- "from" field, only e-mail must be specified here
from = 'sender@example.com',
-- smtp username
user = 'sender@example.com',
-- smtp password
password = '12345678',
-- smtp server
server = 'smtp.gmail.com',
-- smtp server port
port = 465,
-- enable ssl, required for gmail smtp
secure = 'tlsv1_2',
}
subject = 'CSV'
smtp = require('socket.smtp')
mime = require('mime')
ltn12 = require('ltn12')
function escape(v)
return '<' .. tostring(v) .. '>'
end
to = escape(to)
msgt = {
headers = {
to = to,
['content-type'] = 'text/csv',
['content-disposition'] = 'attachment; filename="logs.csv"',
['content-transfer-encoding'] = 'BASE64',
subject = subject,
},
body = ltn12.source.chain(
ltn12.source.string(csv),
ltn12.filter.chain(mime.encode('base64'), mime.wrap('base64'))
)
}
settings.source = smtp.message(msgt)
settings.from = escape(settings.from)
settings.rcpt = { to }
res, err = smtp.send(settings)
log(res, err)