HomeAssistant notification

This commit is contained in:
Ádám Kovács
2024-01-23 20:06:53 +01:00
parent 61d2848045
commit 6aad7b4ad2

36
main.py
View File

@@ -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()