From 6aad7b4ad2c9bb4d6f8c1c6119993622ca18e7ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81d=C3=A1m=20Kov=C3=A1cs?= Date: Tue, 23 Jan 2024 20:06:53 +0100 Subject: [PATCH] HomeAssistant notification --- main.py | 36 ++++++++++++++++++++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/main.py b/main.py index 280b45a..470ec94 100644 --- a/main.py +++ b/main.py @@ -3,6 +3,7 @@ import network import ubinascii import machine import uos +import sys from machine import Pin from time import sleep import urequests as requests @@ -82,7 +83,7 @@ def disconnect_wifi(): wlan.deinit() print('Disconnected') -def send_notification(title, tags): +def send_notification(title, tags, send_ha_notification = False): try: send_notification_to_server('https://ntfy.sh/' + ntfy_topic, title, tags) except: @@ -90,6 +91,16 @@ def send_notification(title, tags): blink_onboard_led(3) send_notification_to_server('https://ntfy.adix.link/' + ntfy_topic, title, tags) + try: + if send_ha_notification: + if homeassistant_url is not None and homeassistant_token is not None: + send_homeassistant_notification(homeassistant_url) + else: + print('HomeAssistant notification is on, but config is missing', homeassistant_url, homeassistant_token) + except Exception as e: + print('Error sending HA notification') + sys.print_exception(e) + def send_notification_to_server(notify_url, title, tags): print('Sending notification to ' + notify_url + '...') # Send notification @@ -101,6 +112,17 @@ def send_notification_to_server(notify_url, title, tags): print(request.content) request.close() +def send_homeassistant_notification(ha_url): + print('Sending notification to HA on ' + ha_url + '...') + # Send notification + request = requests.post(ha_url + '/api/services/input_button/press', data='{"entity_id": "input_button.doorbell"}', headers={ + 'Authorization': 'Bearer ' + (homeassistant_token if homeassistant_token is not None else ""), + 'Content-Type': 'application/json' + }) + print(request.content) + request.close() + + def send_health_update(): try: health_url = healthr_url + '/health/' + healthr_service_name @@ -144,6 +166,16 @@ ntfy_topic = settings['ntfy_topic'] healthr_url = settings['healthr_url'] healthr_service_name = settings['healthr_service_name'] +homeassistant_url = None +homeassistant_token = None +try: + homeassistant_url = settings['homeassistant_url'] + homeassistant_token = settings['homeassistant_token'] +except: + print('HomeAssistant config is missing', homeassistant_url, homeassistant_token) + + + print('Starting up...') wlan = network.WLAN(network.STA_IF) @@ -227,7 +259,7 @@ while True: if connect_wifi(): print('Sending notification...') - send_notification(title = 'Dany Csengo', tags = 'bell') + send_notification(title = 'Dany Csengo', tags = 'bell', send_ha_notification=True) time.sleep(1) check_version_update()