Added All relevant code shit

This commit is contained in:
Bart Koolen 2025-02-24 21:46:51 +01:00 committed by GitHub
parent 872ba17e85
commit 309a1cfd58
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 387 additions and 0 deletions

143
src/GlucoseCheck.py Normal file
View file

@ -0,0 +1,143 @@
import requests
import time
import paho.mqtt.client as mqtt
from datetime import datetime
from collections import deque
##### Mqtt vars #####
broker_address = "192.168.1.250"
broker_port = 1883
recieve_topic = "telegrambot/in"
send_topic = "telegrambot/out"
brokercreds = ["hass","Bruk#5"]
##### Variables #####
# API JWT token, Account-Id and Patient_Id
jwt_token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6ImM1ZGVhZGZiLTNlZDYtMTFlYS1hZjZmLTAyNDJhYzExMDAwYSIsImZpcnN0TmFtZSI6IkdlcnRqYW4iLCJsYXN0TmFtZSI6Iktvb2xlbiIsImNvdW50cnkiOiJOTCIsInJlZ2lvbiI6ImV1Iiwicm9sZSI6InBhdGllbnQiLCJ1bml0cyI6MCwicHJhY3RpY2VzIjpbXSwiYyI6MCwicyI6ImxsdS5hbmRyb2lkIiwic2lkIjoiYWYzZTJlYTctMjMxNC00ZDc0LTkzMGItZGU1Mzc1MmI3YzZkIiwiZXhwIjoxNzU1MzQ3Mzk3LCJpYXQiOjE3Mzk3OTUzOTcsImp0aSI6ImQ4MDdiMmExLTkyYjgtNGQ2Mi05ZmViLTU1MTJhNzU0NmU3YiJ9.svZ6cM2mhHsHV5DIYnrDsERrx9EwCO-plADAk7FYR2k"
Account_ID = "dad20d62aeef891d94bda411af269900180cb7b84a0ce51d60b52463339935b1"
Patient_ID = "c5deadfb-3ed6-11ea-af6f-0242ac11000a"
# API endpoint for login
url = f"https://api-eu.libreview.io/llu/connections/{Patient_ID}/graph"
# Headers
headers = {
"content-type": "application/json", # This nececcery
"product": "llu.android", # This nececcery
"version": "4.13.0", # Version older then 4.12.0 gives error.
"Authorization": f"Bearer {jwt_token}", # JWT_token for login
"Account-Id" : Account_ID # Extra login credentials
}
# limits_table[0] is after just compensating (no eating), and [1] is after eating
limits_table = [
[ [20, 99], # hour 0 constants after compensating /c [max_level, max_slope]
[16, 99], # hour 1
[12, 6], # hour 2
[10, 6], # hour 3
[ 8, 6] ], # hour 4
[ [20, 99], # hour 0 constants after eating /e [max_level, max_slope]
[18, 99], # hour 1
[14, 6], # hour 2
[12, 6], # hour 3
[ 8, 6] ] # hour 4
]
limits_max_hours = 4 # nr of hours in the above lists
last_bolus_time = time.time()-7200
last_bolus_type = 0
GLUC_READOUT_PERIOD = 5 # in minutes
GLUC_SLOPE_PERIOD = 30 # in minutes
GLUC_BUFFER_LENGTH = round(GLUC_SLOPE_PERIOD/GLUC_READOUT_PERIOD)
gluc_buffer = deque([6.0] * GLUC_BUFFER_LENGTH, maxlen=GLUC_BUFFER_LENGTH) # The gluc_buffer always contains only the last xx elements. Initialized on 6.0
##### Main #####
def glucose_value(data_glucose): #Inputs json string and unbinds glucose value
# Gets glucose value
glucose_data = data_glucose.get("data", {}).get("connection", {}).get("glucoseMeasurement", {} ).get("Value")
return glucose_data
def graph_value(data_graph): #Inputs json string and unbinds glucose graph and turns into dictionary
# Gets the whole graph
graph_data = data_graph.get("data", {}).get("graphData", [])
# Turns Date into a dict
graph_dict = {entry["Timestamp"]: entry["Value"] for entry in graph_data}
return graph_dict
# Main loop that runs code
def main(url_main, headers_main):
global last_bolus_time
global last_bolus_type
while True:
try:
# Send the Get request
response = requests.get(url_main, headers=headers_main) # json=payload
if response.status_code == 200: # If request has succeeded
data = response.json()
gluc_value = glucose_value(data)
print(f"current level: {gluc_value}")
# let's determine the slope of the last 30 minutes
gluc_buffer.append(gluc_value)
old_value = list(gluc_buffer)[0]
print(f"old level: {old_value}")
gluc_slope = (gluc_value-old_value)* 60 / 30 # slope is gluc_level per hour (normalized)
print(f"slope: {gluc_slope}")
print(f"time.time: {time.time()}")
print(f"last_bolus_time: {last_bolus_time}")
seconds_since_last_bolus = time.time() - last_bolus_time
hours_since_last_bolus = int(min((seconds_since_last_bolus / 3600) , limits_max_hours))
print(f"hrs after last bolus: {hours_since_last_bolus}")
if ((gluc_value > limits_table[last_bolus_type][hours_since_last_bolus][0]) or
(gluc_slope > limits_table[last_bolus_type][hours_since_last_bolus][1])):
print("Hey joh check je glucosepeil !")
Mqtt.publish(send_topic, "Hey joh check je glucosepeil !")
else: # Request has failed
print(f"❌ Error: Could not connect to server: {response.status_code}")
except requests.exceptions.JSONDecodeError:
print("❌ Error: Response is not valid JSON.")
print("📝 Raw response:", response.text)
time.sleep(GLUC_READOUT_PERIOD*60)
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
global last_bolus_time
global last_bolus_type
args = msg.payload.decode()
if not args:
return
elif args[0] == "c":
last_bolus_type = 0
elif args[0] == "e":
last_bolus_type = 1
last_bolus_time = time.time()
print("Bolussen")
print(last_bolus_type)
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
if __name__ == "__main__":
main(url, headers)

154
src/ServerCheck.py Normal file
View file

@ -0,0 +1,154 @@
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"
send_topic = "telegrambot/out"
brokercreds = ["hass","Bruk#5"]
#######################
# Setup For Variables #
#######################
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.0.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
print(messageStatus)
Mqtt.publish(send_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
while True:
checkWebServer(webServers) #Update list of websites status
messageStatus = statusCheck(False) #False is only on state change
Mqtt.publish(send_topic, messageStatus)
sleep(30)
if __name__ == '__main__':
main()

90
src/TeleBot.py Normal file
View file

@ -0,0 +1,90 @@
from functools import wraps
from telegram import Update, constants
from telegram.ext import ApplicationBuilder, ContextTypes, CommandHandler, CallbackContext
#import uuid
import requests
import paho.mqtt.client as mqtt
from time import sleep
##### Mqtt vars #####
broker_address = "192.168.1.250"
broker_port = 1883
recieve_topic = "telegrambot/out"
send_topic = "telegrambot/in"
brokercreds = ["hass","Bruk#5"]
x = "AS"
flag = False
##### Bot Variabels #####
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
BotToken = '7690417088:AAGcmBegbLHBDXMBKiE6MEgCp3rnLz5vPCE'
User = {
"7570193598": User(name="Bart", lastName="Koolen", userID="7570193598", mute=0),
"7909366331": User(name="GJ", lastName="Koolen", userID="7909366331", mute=0),}
##### Main #####
async def subscribe(update: Update, context: ContextTypes.DEFAULT_TYPE): #This command can be run to test setting up a database for users
await context.bot.send_message(chat_id=update.effective_chat.id, text=update.message.chat.id)
Mqtt.publish(send_topic,1)
async def gluc_command(update: Update, context: CallbackContext): #This command can be run to test setting up a database for users
args = ' '.join(context.args)
print(args)
#await context.bot.send_message(chat_id=update.effective_chat.id, text=update.message.chat.id)
Mqtt.publish(send_topic, args)
def on_connect(client, userdata, flags, reason_code, properties):
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
global x
global flag
x = msg.payload.decode()
flag = True
async def Cat(context: ContextTypes.DEFAULT_TYPE): #This runs evert second to check for if a mqtt message is recieved
global x
global flag
keys = list(User.keys())
print(flag)
if flag == True:
#await context.bot.send_message(chat_id=keys[0], text=x)
await context.bot.send_message(chat_id=keys[1], text=x)
flag = False
Mqtt = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
Mqtt.on_connect = on_connect
Mqtt.on_message = on_message
Mqtt.username_pw_set(brokercreds[0], password=brokercreds[1])
Mqtt.connect(broker_address, broker_port, 60)
Mqtt.loop_start()
def main():#This is the main loop
application = ApplicationBuilder().token(BotToken).build()
gluc_handler = CommandHandler('g', gluc_command)
subscribe_handler = CommandHandler('subscribe', subscribe)
#mute_handler = CommandHandler('mute', mute)
job_queue = application.job_queue
job_minute = job_queue.run_repeating(Cat , interval=1, first=1)
#job_offline = job_queue.run_repeating(callback_offline , interval=interval_offline_message)
application.add_handler(gluc_handler)
application.add_handler(subscribe_handler)
#application.add_handler(mute_handler)
application.run_polling()
if __name__ == '__main__':
main()