from machine import Pin, PWM, I2C
import utime
import urequests
from hcsr04 import HCSRF04
import oled_ssd1306
import network

# Thông tin kết nối WiFi và Blynk
BLYNK_TEMPLATE_ID = "TMPL6bh-i6CpX"
BLYNK_TEMPLATE_NAME = "Giám sát lưu lượng của một bồn chứa xăng"
BLYNK_AUTH_TOKEN = "-oJ1oRsnvsGxbSs-IVp0UpTGIEDi3kXc"
BLYNK_URL = f"http://blynk.cloud/external/api/update?token={BLYNK_AUTH_TOKEN}&pin=V0&value="

# Kết nối WiFi
ssid = "Wokwi-GUEST"
password = ""
station = network.WLAN(network.STA_IF)
station.active(True)
station.connect(ssid, password)

while station.isconnected() == False:
    pass

print("Connected to WiFi")

# Khai báo các chân GPIO
trig_pin = Pin(13, Pin.OUT)
echo_pin = Pin(12, Pin.IN)
led_green = Pin(19, Pin.OUT)
led_red = Pin(18, Pin.OUT)

# Khai báo chân cho buzzer, sử dụng PWM để phát âm thanh
buzzer_pwm = PWM(Pin(23))
buzzer_pwm.duty(0)  # Bắt đầu với âm lượng = 0

# Khởi tạo cảm biến siêu âm
sensor = HCSRF04(trigger_pin=trig_pin, echo_pin=echo_pin)

# Khởi tạo oled
i2c = I2C(0,scl = Pin(22), sda = Pin(21))
oled_width = 128
oled_height = 64
oled = oled_ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)

# Chiều cao của bồn nhiên liệu (cm)
tank_height = 300

# Hàm điều khiển buzzer phát âm thanh
def buzzer_on(frequency=1000):
    buzzer_pwm.freq(frequency)  # Thiết lập tần số âm thanh
    buzzer_pwm.duty(512)        # Điều chỉnh độ rộng xung (âm lượng 50%)

def buzzer_off():
    buzzer_pwm.duty(0)  # Tắt âm thanh

def measure_fuel_level():
    distance = sensor.distance_cm()  # Đo khoảng cách bằng HCSR04
    fuel_level = tank_height - distance  # Tính mức nhiên liệu
    fuel_level = max(0, min(fuel_level, tank_height))  # Giới hạn mức nhiên liệu trong khoảng [0, tank_height]

    # Hiển thị trên OLED
    oled.fill(0)
    oled.text("Fuel Monitoring", 0, 0)
    oled.text("Fuel Level: {} cm".format(fuel_level), 0, 10)

    # Cảnh báo dựa trên mức nhiên liệu
    if fuel_level <= 10:
        oled.text("Status: Empty ", 0, 20)
        led_red.on()
        led_green.off()
        buzzer_on(1000)  # Buzzer kêu với tần số 1000Hz khi nhiên liệu dưới 10 cm
    elif fuel_level >= tank_height - 10:
        oled.text("Status: Full ", 0, 20)
        led_green.on()
        led_red.off()
        buzzer_off()  # Tắt buzzer khi đầy nhiên liệu 
    else:
        oled.text("Status: OK ", 0, 20)
        led_green.off()
        led_red.off()
        buzzer_off()  # Tắt buzzer khi nhiên liệu ở mức an toàn

    oled.show()

   # Gửi dữ liệu lên Blynk qua HTTP API
    response = urequests.get(BLYNK_URL + str(fuel_level))
    print(f"Sent to Blynk: {fuel_level} cm, Response: {response.text}")
    response.close()

   # Vòng lặp chính
while True:
    measure_fuel_level()
    utime.sleep(5)  # Đo lường 5 giây