Interfacing a KNX bus with Python

If you are looking for frameworks that allow you to interface a KNX bus using an IP interface, you will find a lot of tools. Many people still use eibd. However, looking at the eibd page you will see that eibd is no longer maintained.

If you read the KNX specification, you will notice that KNX packets are quite small with a simple structure. No XML stuff with namespaces as often used in modern APIs. So why not implementing the communication in a small script? Unfortunately it is a bit more complicated than just sending a packet to the KNX/IP interface an wait for the answer.

While KNX itself is connectionless, the KNX/IP interface isn’t. This means you first have to initialise¬†a control connection to the KNX/IP interface and use this for data transmissions. Also you have to acknowledge every packet, otherwise the KNX/IP interface will drop the connection. Does this seem complicated? It isn’t.

A simple version of a KNX/IP communications stack (with very limited functionality) can be implemented in less than 400 lines of code. This even implements caching. This means the daemon actively listens to the KNX bus and stored the state of every object internally. Just reading the value of an object than does not need any KNX communication when the value has been seen on the bus already.

Using this simple interface, it is very easy to exchange messages with KNX group addresses:

from knx.ip import KNXIPTunnel
import time
import logging

def main():
    logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)

    tunnel = KNXIPTunnel("192.168.1.128",3671)
    tunnel.connect()
    
    while (True):
        # Toggle the value of group address 0/0/1
        tunnel.group_toggle(1)
        
        # display the values of group addresses 0/0/1 to 0/0/5
        for i in range(1,6):
            v=tunnel.group_read(i)
            print("{} = {}".format(i,v))

        # delay
        time.sleep(12)
        
if __name__ == '__main__':
    main()

References: