我正在记录能源系统中的某些对象。因此,我在本地创建CSV文档。问题是,脚本运行时每隔15分钟就会覆盖前15分钟的数据。我希望它每天创建一个CSV文件(WORKS)将当天的所有数据写入其中(仅最后15分钟)
--require('socket.ftp')
-- ftp file
--ftpfile = string.format('ftp://ftplogin:[email protected]/%s.csv', os.date('%Y-%m-%d_%H-%M'))
--local ftp gebruiken
ftpfile = string.format('/home/ftp/%s.csv', os.date('%Y-%m-%d'))
-- get past quarter data (3600 seconds)
logtime = os.time() - 15 * 60
-- list of objects by id
objects = {}
-- objects with logging enabled
query = 'SELECT address, datatype, name FROM objects WHERE disablelog=0'
for _, object in ipairs(db:getall(query)) do
objects[ tonumber(object.address) ] = {
datatype = tonumber(object.datatype),
name = tostring(object.name or ''),
}
end
-- csv buffer
buffer = { '"date","address","name","value"' }
-- get object logs
query = 'SELECT src, address, datahex, logtime, eventtype FROM objectlog WHERE logtime >= ? ORDER BY id DESC'
for _, row in ipairs(db:getall(query, logtime)) do
object = objects[ tonumber(row.address) ]
-- found matching object and event type is group write
if object and row.eventtype == 'write' then
datatype = object.datatype
-- check that object datatype is set
if datatype then
-- decode data
data = knxdatatype.decode(row.datahex, datatype)
-- remove null chars from char/string datatype
if datatype == dt.char or datatype == dt.string then
data = data:gsub('%z+', '')
-- date to DD.MM.YYYY
elseif datatype == dt.date then
data = string.format('%.2d.%.2d.%.2d', data.day, data.month, data.year)
-- time to HH:MM:SS
elseif datatype == dt.time then
data = string.format('%.2d:%.2d:%.2d', data.hour, data.minute, data.second)
end
else
data = ''
end
-- format csv row
logdate = os.date('%Y.%m.%d %H:%M:%S', row.logtime)
csv = string.format('%q,%q,%q,%q', logdate, knxlib.decodega(row.address), object.name, tostring(data))
-- add to buffer
table.insert(buffer, csv)
end
end
-- upload to ftp only when there's data in buffer
--if #buffer > 1 then
-- result, err = socket.ftp.put(ftpfile, table.concat(buffer, '\r\n'))
--end
-- error while uploading
--if err then
-- alert('FTP upload error: %s', tostring(err))
if #buffer > 1 then
data = table.concat(buffer, '\r\n')
io.writefile(ftpfile, data)
end
我发现了问题:现在可以了感谢帮助的人! :D
if #buffer > 1 then
--We maken de data compatibel om als string te writen in ons doc.
data = table.concat(buffer, '\r\n')
--Connectie leggen met het document , de "ab" wil zeggen dat er append zal worden gebruikt en geen overschrijving
local file = io.open(ftpfile, "ab")
--Schrijf de data naar het opgegeven pad
io.writefile(ftpfile, data)
--connectie stilleggen.
io.close(file)
file = nil
end
if #buffer > 1 then
data = table.concat(buffer, '\r\n')
local file = io.open(ftpfile, "ab")
file:write(data)
io.close(file)
file = nil
end
writefile
没有附加选项,因此您需要以附加模式打开文件的连接,对其进行写入,然后如上所示关闭该连接。