knx-monitor/knx_monitor.py

82 lines
2.2 KiB
Python
Raw Normal View History

2022-12-19 12:24:47 +01:00
"""Example for the telegram monitor callback."""
import asyncio
import getopt
import sys
from xknx import XKNX
from xknx.io import ConnectionConfig, ConnectionType
from xknx.telegram import AddressFilter
from structure import parse_message, load_structure, init_value_mapping
import json
from dotenv import load_dotenv
dotenv_path = join(dirname(__file__), '.env')
load_dotenv(dotenv_path)
from db import publish_measurement
config = {}
mapping = {}
async def telegram_received_cb(telegram):
"""Do something with the received telegram."""
val = parse_message(config, mapping, telegram)
publish_measurement(val)
def show_help():
"""Print Help."""
print("Telegram filter.")
print("")
print("Usage:")
print("")
print(__file__, " Listen to all telegrams")
print(
__file__, "-f --filter 1/2/*,1/4/[5-6] Filter for specific group addresses"
)
print(__file__, "-h --help Print help")
print("")
async def monitor(address_filters):
"""Set telegram_received_cb within XKNX and connect to KNX/IP device in daemon mode."""
connection_config = ConnectionConfig(
connection_type=ConnectionType.TUNNELING,
gateway_ip=os.environ.get('KNX_GATEWAY_IP')
)
xknx = XKNX(connection_config=connection_config, daemon_mode=True)
xknx.telegram_queue.register_telegram_received_cb(
telegram_received_cb, address_filters
)
await xknx.start()
await xknx.stop()
async def main(argv):
"""Parse command line arguments and start monitor."""
try:
opts, _ = getopt.getopt(argv, "hf:", ["help", "filter="])
except getopt.GetoptError:
show_help()
sys.exit(2)
global config
config = load_structure(os.environ.get('KNX_TOPOLOGY'))
global mapping
mapping = init_value_mapping()
address_filters = None
for opt, arg in opts:
if opt in ["-h", "--help"]:
show_help()
sys.exit()
if opt in ["-f", "--filter"]:
address_filters = list(map(AddressFilter, arg.split(",")))
await monitor(address_filters)
if __name__ == "__main__":
asyncio.run(main(sys.argv[1:]))