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)