import RPi.GPIO as GPIO
import time
import subprocess
import as7265x
import smbus
import numpy as np
import os
from datetime import datetime

# Konfigurasi sensor
i2c = smbus.SMBus(1)
sensor = as7265x.AS7265X(i2c)
sensor.begin()
sensor.setIntegrationCycles(1)

# Konfigurasi tombol
BUTTON_PIN = 22  # Gunakan GPIO 22
GPIO.setmode(GPIO.BCM)
GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

# Meminta input nama folder
folder = input("Masukkan nama folder untuk menyimpan hasil: ")
if not os.path.exists(folder):
    os.makedirs(folder)

# Fungsi untuk melakukan scanning
def scan_and_save():
    print("Scanning...")
    sensor.enableBulb(as7265x.LED_WHITE)
    sensor.enableBulb(as7265x.LED_IR)
    sensor.enableBulb(as7265x.LED_UV)
    
    sensor.takeMeasurements()
    data = [
        sensor.getCalibratedA(), sensor.getCalibratedB(), sensor.getCalibratedC(),
        sensor.getCalibratedD(), sensor.getCalibratedE(), sensor.getCalibratedF(),
        sensor.getCalibratedG(), sensor.getCalibratedH(), sensor.getCalibratedR(),
        sensor.getCalibratedI(), sensor.getCalibratedS(), sensor.getCalibratedJ(),
        sensor.getCalibratedT(), sensor.getCalibratedU(), sensor.getCalibratedV(),
        sensor.getCalibratedW(), sensor.getCalibratedK(), sensor.getCalibratedL()
    ]
    
    sensor.disableBulb(as7265x.LED_WHITE)
    sensor.disableBulb(as7265x.LED_IR)
    sensor.disableBulb(as7265x.LED_UV)
    
    # Simpan hasil ke dalam file
    filename = datetime.now().strftime("%Y-%m-%d-%H-%M-%S") + ".txt"
    file_path = os.path.join(folder, filename)
    with open(file_path, "w") as file:
        file.write(";".join(map(str, data)))
    
    print(f"Data telah disimpan di {file_path}")

try:
    print("Tekan tombol untuk memulai scanning...")
    while True:
        if GPIO.input(BUTTON_PIN) == GPIO.HIGH:
            scan_and_save()
            time.sleep(1)  # Hindari pemicuan berulang cepat
except KeyboardInterrupt:
    print("Keluar...")
    GPIO.cleanup()
