import cv2
from picamera2 import Picamera2
from pyzbar.pyzbar import decode
import pygame
import time

# Initialize the camera and pygame for playing audio
picam2 = Picamera2()
picam2.start()
pygame.mixer.init()

def play_audio(mp3_file):
    """Plays the specified MP3 file."""
    try:
        pygame.mixer.music.load(mp3_file)
        pygame.mixer.music.play()
        while pygame.mixer.music.get_busy():
            time.sleep(1)
    except Exception as e:
        print(f"Error playing audio: {e}")

def scan_qr_code(image):
    """Scans the QR code from the given image and returns the decoded data."""
    qr_codes = decode(image)
    if qr_codes:
        # Extract the string from the QR code
        qr_data = qr_codes[0].data.decode('utf-8')
        print("QR Code detected:", qr_data)
        return qr_data
    return None

while True:
    # Capture an image from the camera
    image = picam2.capture_array()
    
    # Convert the image to grayscale (QR code scanning works better in grayscale)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    
    # Scan for QR code in the image
    qr_data = scan_qr_code(gray)
    
    if qr_data:
        # If QR code contains "hydrosense", play the corresponding MP3
        if qr_data.lower() == "hydrosense":  # Case insensitive comparison
            print("Playing Hydrosense.mp3")
            play_audio("Hydrosense.mp3")  # Make sure the MP3 file is in the correct path
            
    # Display the image (for debugging purposes)
    cv2.imshow('QR Code Scanner', image)
    
    # Exit the loop if 'q' is pressed
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# Cleanup
picam2.stop()
cv2.destroyAllWindows()
pygame.quit()
