Example: Read/write file to LM2 connected USB flash

Init script

USB storage will be mounted to /mnt/usb directory.

Note! First found USB storage device will be mounted on system start. Hot plugging is not supported by this script.

 

Usage

  1. -- create usb mount directory
  2. os.execute('mkdir -p /mnt/usb')
  3. -- find first matching usb storage device
  4. dev = io.readproc('ls /dev/sd*1 2>/dev/null'):match('/dev/sd%l1')
  5. -- found it, mount
  6. if dev then
  7. os.execute('mount ' .. dev .. ' /mnt/usb')
  8. alert('[usb-mount] mounted %s', dev)
  9. -- nothing found, local flash will be used
  10. else
  11. alert('[usb-mount] no device found')
  12. end

Read/Write

You can use standard Lua io library functions as well as LM specific helpers for reading/writing whole files at once:

  • Reads whole file at once. Return file contents as a string on success or nil on error.
    1. io.readfile (file)

  • Writes given data to a file. Data can be either a value convertible to string or a table of such values. When data is a table then each table item is terminated by a new line character. Return boolean as write result when file can be open for writing or nil when file cannot be accessed.
    1. io.writefile (file, data)

Examples

Write event status to log file

  1. value = knxdatatype.decode(event.datahex, dt.bool)
  2. data = string.format('%s value is %s', os.date('%c'), tostring(value))
  3. -- write to the end of log file preserving all previous data
  4. file = io.open('/mnt/usb/log.txt', 'a+')
  5. file:write(data .. '\r\n')
  6. file:close()

Produced result:

Mon Jan 3 05:25:13 2011 value is false
Mon Jan 3 05:25:14 2011 value is true
Mon Jan 3 05:25:32 2011 value is false
Mon Jan 3 05:25:33 2011 value is true

 

Read data from file (config in format key=value)

  1. for line in io.lines('/mnt/usb/config.txt') do
  2. -- split line by '=' sing
  3. items = line:split('=')
  4. -- two items, line seems to be valid
  5. if #items == 2 then
  6. key = items[ 1 ]:trim()
  7. value = items[ 2 ]:trim()
  8. alert('[config] %s = %s', key, value)
  9. end
  10. end