#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import numpy as np
from adafruit_as7341 import AS7341
import RPi.GPIO as GPIO
import board
from time import sleep
from scipy.signal import find_peaks, filtfilt, butter

GPIO.setmode(GPIO.BCM)
sensor = AS7341(board.I2C())


def main():
    try:
        dt = 2 # Number of seconds we give the heart pulse rythm.
        n_sample = 60 # Number of samples we get in dt time.
        peak_threshold = 5 # Minimum difference between the peaks.
        peak_distance = n_sample / (dt * 5) # Minimum distance between each peak.
        while True:
            data = [] # Amount of data we collect at each iteration.
            for _ in range(n_sample):
                data.append(int(sensor.channel_clear))
                sleep(dt / n_sample)
            data = np.array(data)
            a, b = butter(2, [0.25, 10], btype="bandpass", fs=n_sample/dt)
            filtered_data = filtfilt(a, b, data)
            n_peak = find_peaks(filtered_data, threshold=peak_threshold) # We get the peaks' values.
            ppm = len(n_peak[0]) * 60/dt # Pulse per minute.
            print(f"Pulse per Minutes: {ppm}\n{data}\n--------------------------------")
    except:
        GPIO.cleanup()


if __name__ == "__main__":
    main()
    GPIO.cleanup()
