Created
July 19, 2020 02:23
-
-
Save vishalroygeek/5a6206e1f89455402f90e1afdeca8895 to your computer and use it in GitHub Desktop.
A python script that notifies you whenever there is a power cut ⚡
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from win10toast import ToastNotifier | |
from ping3 import ping | |
import time | |
import os | |
#Defining variables | |
device_ip_address = "192.168.0.101" #IP address of the device to be pinged | |
notification_delay = 120.0 #Frequency of the offline notification in seconds | |
loop_delay = 1.0 #Frequency of device status chekcing in seconds | |
was_offline = False | |
last_notified_time = 0.0 | |
notification_title_online = "Power Restored" | |
notification_title_offline = "Power Down" | |
notification_description_online = "Your device is now running on the mains power supply" | |
notification_description_offline = "Your device is now running on the backup power supply" | |
notification_icon_online = "path\to\power_restored.ico" | |
notification_icon_offline = "path\to\power_down.ico" | |
notification_duration_seconds = 10 | |
#Initializing objects | |
toaster = ToastNotifier() | |
#Function to check if device is online | |
def deviceOnline(): | |
return not (ping(device_ip_address) == None) | |
#Function to get current time in seconds | |
def currentTimeInSeconds(): | |
return time.time()*1.0 | |
while True: | |
if deviceOnline(): | |
print(notification_description_online) | |
#Resetting last played time to get alert ASAP | |
last_notified_time = 0.0 | |
#Marking status as online and sending online alert if the device was previously offline | |
if was_offline: | |
was_offline = False | |
toaster.show_toast(notification_title_online, notification_description_online, notification_icon_online, notification_duration_seconds) | |
#Repeating the loop after the time defined in loop_delay | |
time.sleep(loop_delay) | |
else: | |
print(notification_description_offline) | |
#Marking status as offline and sending offline alert | |
was_offline = True | |
#Resending notification only after the time defined in notification_delay | |
if((currentTimeInSeconds() - last_notified_time) >= notification_delay): | |
last_notified_time = currentTimeInSeconds() | |
toaster.show_toast(notification_title_offline, notification_description_offline, notification_icon_offline, notification_duration_seconds) | |
#Repeating the loop after the time defined in loop_delay | |
time.sleep(loop_delay) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment