Example: Event-based program to control Modbus Air-Conditioner from KNX

Task

When KNX group address receives 1, write TRUE in according Modbus register, if 0 – then FALSE.

Event-based program

Source code    
  1. require('luamodbus')
  2. mb = luamodbus.rtu()
  3.  
  4. mb:open('/dev/ttyS2', 9600, 'E', 8, 1, 'H')
  5. mb:connect()
  6.  
  7. mb:setslave(1)
  8.  
  9. -- compare either 1/1/1 received 1 or 0
  10. if event.datahex == '01' then
  11. -- write in specific Modbus register TRUE if 1/1/1 is 1
  12. mb:writeregisters(0x9C40, 0x11)
  13. else
  14. -- write in specific Modbus register FALSE if 1/1/1 is 0
  15. mb:writeregisters(0x9C40, 0)
  16. end

Encoded A/C values

Some Air Conditioners are keeping enocded values in registers, you need to encode them first from HEX to use in the further scripts.
For example, value = 0x0cba after executing the below commands will give 24.2

Source code    
  1. hex = lmcore.inttohex(value, 2)
  2. temp = knxdatatype.decode(hex, dt.float16)

How to encode KNX temperature into 16 Hexadecimal data and write to Modbus registers:

Source code    
  1. function encodetemp(value)
  2. local hex = knxdatatype.encode(value, dt.float16).datahex
  3. return tonumber(hex, 16)
  4. end
  5.  
  6. value = 20.8
  7. mb:writeregisters(30001, encodetemp(value))