#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <linux/i2c-dev.h>
#include <sys/ioctl.h>

#define MAX_MEASURES 60  // To store 60 sound level measurements

int main()
{
    int file;
    char data;
    int soundLevels[MAX_MEASURES];
    int index = 0;
    int sum = 0;
    int i;
    FILE *fileOutput;  // File pointer for writing to file


    // Initialize the soundLevels array
    for (i = 0; i < MAX_MEASURES; i++) {
        soundLevels[i] = 0;
    }

    // Open I2C1 for reading the sound meter module registers
    if ((file = open("/dev/i2c-1", O_RDWR)) < 0)
    {
        perror("Failed to open I2C1!");
        exit(1);
    }

    // 0x48 is the decibel meter I2C address
    if (ioctl(file, I2C_SLAVE, 0x48) < 0)
    {
        perror("db Meter module is not connected/recognized at I2C addr = 0x48");
        close(file);
        exit(1);
    }

    while (1)
    {
        // Decibel value is stored in register 0x0A
        data = 0x0A;

        // Write: send 1 byte from data (memory address pointer) to file
        if (write(file, &data, 1) != 1)
        {
            perror("Failed to write register 0x0A");
            close(file);
            exit(1);
        }

        // Read the sound level from register 0x0A
        if (read(file, &data, 1) != 1)
        {
            perror("Failed to read register 0x0A");
            close(file);
            exit(1);
        }

        // Insert the new reading into the array
        sum -= soundLevels[index];  // Subtract the old value to maintain the sum
        soundLevels[index] = data;  // Store the new value
        sum += soundLevels[index];  // Add the new value to the sum

        // Move to the next index, wrap around if needed
        index = (index + 1) % MAX_MEASURES;

        // Calculate the moving average (sum of the last 60 values)
        int movingAverage = sum / MAX_MEASURES;

        

        // Find the max and min values in the soundLevels array
        int max = soundLevels[0];
        int min = soundLevels[0];
        for (i = 1; i < MAX_MEASURES; i++)
        {
            if (soundLevels[i] > max) {
                max = soundLevels[i];
            }
            if (soundLevels[i] < min) {
                min = soundLevels[i];
            }
        }

         // Open the file to write the moving average (overwrite)
        fileOutput = fopen("/var/www/nebuleair_pro_4g/sound_meter/moving_avg_minute.txt", "w");

        if (fileOutput == NULL)
        {
            perror("Failed to open file for writing");
            close(file);
            exit(1);
        }
        // Write the moving average to the file
        fprintf(fileOutput, "%d %d %d\n", movingAverage, max, min);
         // Close the file after writing
        fclose(fileOutput);

        // Display the current sound level and the moving average
        printf("Current Sound level: %d\n", data);
        printf("Current index: %d\n", index);

        printf("Sound levels array: ");
        for (i = 0; i < MAX_MEASURES; i++)
        {
            printf("%d ", soundLevels[i]);
        }
        printf("\nMax Sound level: %d\n", max);
        printf("Min Sound level: %d\n", min);
        printf("Moving Average (Last 60 seconds): %d\n\n", movingAverage);


        // Wait for 1 second before taking the next measurement
        sleep(1);
    }

    close(file);
    return 0;
}
