print("\nSYAMIL NAQIB BIN SHAMSUDIN\n")
print("\n18/11/24\n")

# Import Libraries
from machine import Pin, I2C, PWM
from ssd1306 import SSD1306_I2C
from encoder import RotaryEncoder
import dht
import time

# Constants
COST_PER_UNIT = 0.15  # Revenue per kWh generated
EFFICIENCY_FACTOR = 0.8  # Turbine efficiency (80%)
TICKS_TO_RPM = 10  # Conversion factor for encoder ticks to RPM
ENERGY_PER_RPM = 0.001  # Energy generated (kWh) per RPM
UPDATE_INTERVAL = 5  # Time interval for updates (seconds)

# Pin Declaration
encoder = RotaryEncoder(Pin(12), Pin(14))
dht_sensor = dht.DHT22(Pin(27))
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
led = Pin(2, Pin.OUT)  
buzzer = Pin(5, Pin.OUT)  

# Parameter Declaration
oled = SSD1306_I2C(128, 64, i2c)
TEMP_THRESHOLD = 50.0
pwm_buzzer = PWM(buzzer, freq=1000, duty=0) 

# Variables
total_energy = 0
revenue = 0

# Main Program
while True:
    try:
        ticks = encoder.get_ticks()
        rpm = ticks * TICKS_TO_RPM
        wind_speed = rpm / 10  
        power_output = wind_speed * EFFICIENCY_FACTOR  

        energy_generated = rpm * ENERGY_PER_RPM
        total_energy += energy_generated
        revenue = total_energy * COST_PER_UNIT

        dht_sensor.measure()
        temperature = dht_sensor.temperature()
        humidity = dht_sensor.humidity()

        # Update OLED display
        oled.fill(0)
        oled.text("Wind Turbine Tracker", 0, 0)
        oled.text(f"Wind: {wind_speed:.2f} m/s", 0, 10)
        oled.text(f"Power: {power_output:.2f} kW", 0, 20)
        oled.text(f"Energy: {total_energy:.2f} kWh", 0, 30)
        oled.text(f"Revenue: ${revenue:.2f}", 0, 40)
        oled.text(f"Temp: {temperature:.1f}C", 0, 50)
        oled.text(f"Humidity: {humidity:.1f}%", 0, 60)
        oled.show()

        # Continuous LED and Buzzer Blinking inside the loop
        if temperature >= TEMP_THRESHOLD:
            print("\nWARNING!!! Temperature is high!\n")
            led.on()  
            pwm_buzzer.init(freq=1500, duty=50)  
            time.sleep(0.5) 
            led.off()  
            pwm_buzzer.duty(0)  
            time.sleep(0.5)  
        else:
            print("\nTemperature is normal.\n")
            led.off()  
            pwm_buzzer.duty(0)  

        # Send data to server
        print("Sending data to server...")
        print(f"Wind Speed: {wind_speed:.2f} m/s")
        print(f"Power Output: {power_output:.2f} kW")
        print(f"Total Energy: {total_energy:.2f} kWh")
        print(f"Revenue: ${revenue:.2f}")
        print(f"Temperature: {temperature:.2f}°C, Humidity: {humidity:.2f}%")
        print("Data sent successfully!")
        time.sleep(0.5)

        encoder.reset()

        time.sleep(1)

    except Exception as e:
        print(f"Error: {e}")
        time.sleep(1)