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

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

Examples

Write event status to log file

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

Source code    
  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