From db6b256853346f5abfd5e9df32b6367564db1faa Mon Sep 17 00:00:00 2001
From: parra <victor+git@parravidales.es>
Date: Fri, 7 Oct 2022 18:01:50 +0200
Subject: [PATCH] Added URL ping to notify when scripts finish OK

---
 README.md | 1 +
 env_file  | 5 ++++-
 main.py   | 5 +++++
 3 files changed, 10 insertions(+), 1 deletion(-)

diff --git a/README.md b/README.md
index cdf7380..7a2c1f3 100644
--- a/README.md
+++ b/README.md
@@ -12,6 +12,7 @@ Copy the `env_file` to `.env` and open it. Complete all environment variables:
 - `MQTT_SENSOR_NAME` contains the sensor name, useful to split the telemetry data if you have more than one sensors.
 - `MQTT_PUBLISH_DELAY` specify, in seconds, how many time should wait since the script take the measurements to publish in the broker
 - `MIJIA_BTLE_ADDRESS` constant with the BLE address of your Mijia device.. This can be retrieved activating the pairing mode in the sensor and scanning the BT devices
+- `PING_URL` used to ping a monitoring service if everything was OK (Useful, for example, for monitor the script with Uptime Kuma)
 
 ## Install dependencies
 
diff --git a/env_file b/env_file
index e14fbdd..af7d4b2 100644
--- a/env_file
+++ b/env_file
@@ -19,4 +19,7 @@ MQTT_TOPIC_STATE=${MQTT_TELE_PREFIX}/${MQTT_SENSOR_NAME}/event
 MQTT_PUBLISH_DELAY=5
 
 # Sensor configuration
-MIJIA_BTLE_ADDRESS=
\ No newline at end of file
+MIJIA_BTLE_ADDRESS=
+
+# Ping URL (Uptime Kuma, for example)
+PING_URL=
diff --git a/main.py b/main.py
index c8dc83b..80482ac 100755
--- a/main.py
+++ b/main.py
@@ -5,6 +5,7 @@
 import os
 import re
 import time
+import urllib.request
 
 from dotenv import load_dotenv
 import paho.mqtt.client as mqtt
@@ -12,6 +13,8 @@ from bluepy import btle
 
 load_dotenv() # Cargamos las variables de entorno necesarias
 
+PING_URL = os.getenv('PING_URL')
+
 MQTT_TOPIC_HUMIDITY = os.getenv('MQTT_TOPIC_HUMIDITY')
 MQTT_TOPIC_TEMPERATURE = os.getenv('MQTT_TOPIC_TEMPERATURE')
 MQTT_TOPIC_BATTERY = os.getenv('MQTT_TOPIC_BATTERY')
@@ -96,6 +99,8 @@ def main():
                 publish_sensor_data(mqttc)
                 last_msg_time = time.time()
                 reset_variables()
+                if PING_URL:
+                    urllib.request.urlopen(PING_URL).read()
                 break
 
         except (btle.BTLEDisconnectError, IOError):