Glucose-Checker/src/ServerCheck.py
Bart Koolen 608a2c95d2 Added saperate sending and receiving
Je kan nu de server check muten. en ik heb een framework gemaakt voor het versturen naar verschilende personen.
2025-02-28 15:30:21 +01:00

192 lines
No EOL
8.9 KiB
Python

import requests
import paho.mqtt.client as mqtt
#from smbprotocol.connection import Connection
#from smbprotocol.session import Session
#from smbprotocol.tree import TreeConnect
from time import sleep
##### Mqtt vars #####
broker_address = "192.168.1.250"
broker_port = 1883
recieve_topic = "telegrambot/in/server/#"
send_topic = "telegrambot/out/"
brokercreds = ["hass","Bruk#5"]
#######################
# Setup For Variables #
#######################
class User: # Custom classes for my dictionaries
def __init__(self, name, lastName, userID, mute):
self.name = name
self.lastName = lastName
self.userID = userID
self.mute = mute
User = {
"7570193598": User(name="Bart", lastName="Koolen", userID="7570193598", mute=0),
"7909366331": User(name="GJ", lastName="Koolen", userID="7909366331", mute=0),}
mute_time = 86400 #This is in seconds, it defines how long the program /mute command lasts
interval_offline_message = 300
class Site: #Custom classes for my dictionaries
def __init__(self, url, typeVar):
self.url = url
self.typeVar = typeVar
webServers = {"Google" : Site(url="https://google.com", typeVar="URL"), #List with all the servers urls and names and types
"GameServer" : Site(url="http://192.168.1.251", typeVar="URL"),
"SpiritBody" : Site(url="https://spiritbodyhealing.org", typeVar="URL"),
"HeresYourSign": Site(url="https://heresyoursign.nl", typeVar="URL"),
#"SMB_server": Site(url="192.168.1.250", typeVar="SMB"),
}
webServersStatus = {}
mute_time = 86400 #This is in seconds, it defines how long the program /mute command lasts
interval_offline_message = 300 #This is in seconds, it defines how often the the program sents a message of wich sites are offline
green_circle = "🟢"#emoji
red_circle = "🔴"#emji
######################
# Here Begins Script #
######################
def checkWebServer(serverList): #This function checks all servers in list if they changed state
tempVarC = ""
for i in serverList: #Iterates over every server
if serverList[i].typeVar == "SMB": #This is type SMB
try:
guid = uuid.uuid4() # Unique identifier for the connection
connection = Connection(server_name=serverList[i].url, port=445, guid=guid) #Trys to connect to server
connection.connect()
connection.disconnect()
if i in webServersStatus:
if webServersStatus[i] == "Offline": #Checks if status of server has changed
webServersStatus[i] = "Online"
tempVarC = f"{tempVarC}{green_circle} {i} is {webServersStatus[i]}\n"
else:
webServersStatus[i] = "Online" #This runs on boot to get initial server state
tempVarC = f"{tempVarC}{green_circle} {i} is {webServersStatus[i]}\n"
#return True
except Exception as e: # Trows an exeption when the SMb server is unreachble
#print(f"Error accessing SMB share: {e}")
if i in webServersStatus:
if webServersStatus[i] == "Online":
webServersStatus[i] = "Offline"
tempVarC = f"{tempVarC}{red_circle} {i} is {webServersStatus[i]}\n"
else:
webServersStatus[i] = "Offline" #This runs on boot to get initial server state
tempVarC = f"{tempVarC}{red_circle} {i} is {webServersStatus[i]}\n"
#return False
else: #This is type url
try:
r = requests.get(serverList[i].url, timeout=20) #sends request to server
r.raise_for_status()
except (requests.exceptions.ConnectionError, requests.exceptions.Timeout): #this runs if server is down or unreacheble
if i in webServersStatus:
if webServersStatus[i] == "Online": #Checks if status of server has changed
webServersStatus[i] = "Offline"
tempVarC = f"{tempVarC}{red_circle} {i} is {webServersStatus[i]}\n"
#else:
#do nothing
else:
webServersStatus[i] = "Offline" #This runs on boot to get initial server state
tempVarC = f"{tempVarC}{red_circle} {i} is {webServersStatus[i]}\n"
except requests.exceptions.HTTPError:
if i in webServersStatus:
if webServersStatus[i] == "Online": #Checks if status of server has changed
webServersStatus[i] = "Unavailable"
#else:
#do nothing
else:
webServersStatus[i] = "Unavailable" #This runs on boot to get initial server state
tempVarC = f"{tempVarC}{red_circle} {i} is {webServersStatus[i]}\n"
else:
if i in webServersStatus:
if webServersStatus[i] == "Offline": #Checks if status of server has changed
webServersStatus[i] = "Online"
tempVarC = f"{tempVarC}{green_circle} {i} is {webServersStatus[i]}\n"
#else:
#do nothing
else:
webServersStatus[i] = "Online" #This runs on boot to get initial server state
tempVarC = f"{tempVarC}{green_circle} {i} is {webServersStatus[i]}\n"
return tempVarC
def statusCheck(statusReal): #This command can be run by the user to check the state off all servers
tempVarS = ""
for i in webServersStatus: #Adds fancy emoji depending on if server is online or offline
if webServersStatus[i] == "Online":
if statusReal: #This is so depending on what is needed can return every server that is offline and not online
tempVarS = f"{tempVarS}{green_circle} {i} is {webServersStatus[i]}\n"
else:
tempVarS = f"{tempVarS}{red_circle} {i} is {webServersStatus[i]}\n"
return tempVarS
def on_connect(client, userdata, flags, reason_code, properties): #This runs once mqqt starts and try's to connect to mqtt broker
print(f"Connected with result code {reason_code}")
if reason_code == 0:
# success connect
print("Connected to MQTT broker")
Mqtt.subscribe(recieve_topic)
if reason_code > 0:
# error processing
print(f"Failed to connect to MQTT broker. Error code: {rc}")
def on_message(client, userdata, msg): #This runs everytime a mqtt message is recieved
checkWebServer(webServers) #Update list of websites status
messageStatus = statusCheck(True) #True returns every server and state
user_topic = msg.topic.split("/")[-1]
args = msg.payload.decode()
print(user_topic)
keys = list(User.keys())
if not args:
return
elif args[0] == "m":
for i in keys:
if User[i].name.lower() == user_topic:
print(f"right: {user_topic}: {i}")
if User[i].mute > 0:
User[keys[0]].mute = 0
User[keys[1]].mute = 0
else:
User[i].mute = mute_time//interval_offline_message #This is defined in the setup variables
elif args[0] == "s":
print("s")
Mqtt.publish(send_topic + user_topic , messageStatus)
Mqtt = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2) #Creates a mqqt object
Mqtt.on_connect = on_connect #Create callback on connect
Mqtt.on_message = on_message #Create callback on message
Mqtt.username_pw_set(brokercreds[0], password=brokercreds[1]) #Set User and Password
Mqtt.connect(broker_address, broker_port, 60) #Set Connection settings
Mqtt.loop_start() #Start connecting
def main(): #This is the main loop
keys = list(User.keys())
while True:
checkWebServer(webServers) #Update list of websites status
messageStatus = statusCheck(False) #False is only on state change
if User[keys[0]].mute == 0 | User[keys[1]].mute == 0:
Mqtt.publish(send_topic + "broadcast", messageStatus)
sleep(30)
if User[keys[0]].mute > 0:
User[keys[0]].mute = User[keys[0]].mute - 1
if User[keys[1]].mute > 0:
User[keys[1]].mute = User[keys[1]].mute - 1
print(User[keys[0]].mute)
print(User[keys[1]].mute)
if __name__ == '__main__':
main()