import time
import urequests

# ThingSpeak parameters
channel_api_key = "5R46WGKPGTJMA1OH"
channel_id = 2402727

# Define custom threshold values
insulin_threshold = 5.0
ketone_threshold = 1.0
glucose_threshold = 100.0

# Initialize ThingSpeak channel
def initialize_thingspeak():
    url = f"https://api.thingspeak.com/update?api_key={channel_api_key}&field7=0"
    urequests.get(url)

# Send data to ThingSpeak
def send_to_thingspeak(data):
    url = f"https://api.thingspeak.com/update?api_key={channel_api_key}&field1={data['insulin']}&field2={data['ketone']}&field3={data['glucose']}&field4={data['insulin_fuzzy']}&field5={data['ketone_fuzzy']}&field6={data['glucose_fuzzy']}&field7={data['overall_status']}"
    urequests.get(url)

# Read sensor data (replace with actual sensor readings)
def read_insulin_sensor():
    return 6.0  # Replace with actual value

def read_ketone_sensor():
    return 0.8  # Replace with actual value

def read_glucose_sensor():
    return 90.0  # Replace with actual value

# Fuzzy logic evaluation
def fuzzy_evaluate(sensor_value, threshold):
    fuzzy_low = 0.2
    fuzzy_medium = 0.5
    fuzzy_high = 0.8

    low = fuzzy_trapezoidal(sensor_value, threshold - 5, threshold - 2, threshold)
    medium = fuzzy_triangular(sensor_value, threshold - 2, threshold, threshold + 2)
    high = fuzzy_trapezoidal(sensor_value, threshold, threshold + 2, threshold + 5)

    # Combine fuzzy sets based on the sensor value
    return (low * fuzzy_low + medium * fuzzy_medium + high * fuzzy_high) / (low + medium + high)

# Fuzzy triangular membership function
def fuzzy_triangular(x, a, b, c):
    return max(0, min((x - a) / (b - a), (c - x) / (c - b)))

# Fuzzy trapezoidal membership function
def fuzzy_trapezoidal(x, a, b, c):
    return max(0, min(min((x - a) / (b - a), 1), (c - x) / (c - b)))

# Main loop
def main():
    initialize_thingspeak()

    while True:
        # Read sensor data
        insulin_value = read_insulin_sensor()
        ketone_value = read_ketone_sensor()
        glucose_value = read_glucose_sensor()

        # Fuzzy logic evaluation
        insulin_fuzzy = fuzzy_evaluate(insulin_value, insulin_threshold)
        ketone_fuzzy = fuzzy_evaluate(ketone_value, ketone_threshold)
        glucose_fuzzy = fuzzy_evaluate(glucose_value, glucose_threshold)

        # Calculate weighted average for overall status
        overall_status = (insulin_fuzzy + ketone_fuzzy + glucose_fuzzy) / 3.0

        # Send data to ThingSpeak
        data_to_send = {
            'insulin': insulin_value,
            'ketone': ketone_value,
            'glucose': glucose_value,
            'insulin_fuzzy': insulin_fuzzy,
            'ketone_fuzzy': ketone_fuzzy,
            'glucose_fuzzy': glucose_fuzzy,
            'overall_status': overall_status
        }

        send_to_thingspeak(data_to_send)

        # Pause for 15 seconds before sending the next set of data
        time.sleep(15)

if __name__ == "__main__":
    main()