/*
 * Copyright (c) 2025, Texas Instruments Incorporated
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * *  Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * *  Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * *  Neither the name of Texas Instruments Incorporated nor the names of
 *    its contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*
 *  ======== smart_detection_pir.c ========
 */

#include <stddef.h>
#include <unistd.h>
#include <stdint.h>
#include <string.h>

/* EdgeAI configuration */
#include "ti_edgeai_config.h"
#include "ti_edgeai_fe_config.h"
#include "ti_drivers_config.h"

/* TVM model */
#include <ai_artifacts/tvmgen_default.h>

/* Device Agent Protocol (DAP) Library */
#include <ti/ai/edge_ai/dap/DAP.h>

/* Sensor Application */
#include <sensor/sensor_app.h>

/* Feature Extraction */
#include <feature_extraction/feature_extract_app.h>

/* Model TVM expected input tensors */
static float pir_input[1][1][1][NUM_WINDOWS][NUM_TOTAL_FEATURES];
static struct tvmgen_default_inputs nn_inputs   = {(void *)&pir_input[0][0][0][0][0]};

/* Model TVM expected output tensors for preduction results */
static float pir_output_class0[1][NUM_CLASSES];
static float pir_output_class1[1][128];
static struct tvmgen_default_outputs nn_outputs = {&pir_output_class0[0], &pir_output_class1[0]};

/* Application buffers */
uint8_t sensor_buffer[QUEUE_BUFFER_SIZE];
static float feature_buffer[NUM_WINDOWS * NUM_TOTAL_FEATURES];

/* Feature Extraction parameters */
static FeatureExtract_Params featureExtractParams;

/* Sensor Inference Result Structure */
static Sensor_InferenceResult pirNetInferenceResult;

/* ======== mainThread ======== */
void *mainThread(void *arg0)
{
    /* Initialize the Sensor task */
    Sensor_init();

    /* Initialize the DAP Task */
    DAP_init();
    DAP_open();

    while (1)
    {
        /* Get the configuration for the application pipeline */
        DAP_PipelineConfiguration DAP_configParams = DAP_getPipelineConfiguration();
        switch (DAP_configParams.mode)
        {
            case DAP_PIPELINE_MODE_UNINITIALIZED:
                /* Loop here if Device is only connected to EdgeAI Studio and no other command has been issued */
                break;

            case DAP_PIPELINE_MODE_DATA_ACQUISITION:
                /* Start fetching data from the sensor */
                if (Sensor_getData(sensor_buffer))
                {
                    /* Transmit sensor data using the DAP */
                    DAP_sendData(DAP_SEND_DATA_TYPE_SENSOR_SIGNAL, sensor_buffer, sizeof(sensor_buffer));
                }

                break;

            case DAP_PIPELINE_MODE_SENSOR_INFERENCING:
                /* Start fetching data from the sensor */
                if (Sensor_getData(sensor_buffer))
                {
                    /* Open Feature Extraction */
                    FeatureExtract_config(&featureExtractParams);

                    samplingfreq     = DAP_getSamplingFrequency();

                    /* Run Feature Extraction */
                    FeatureExtract_run(&featureExtractParams, sensor_buffer, feature_buffer);

                    /* Copy concatenated features into the model's input tensor*/
                    memcpy(pir_input, feature_buffer, sizeof(feature_buffer));

                    /* Run Inference */
                    tvmgen_default_run(&nn_inputs, &nn_outputs);

                    /* Calculate the Label Class based on the inference result
                    */
                    pirNetInferenceResult.inferred_class = FeatureExtract_findClass(pir_output_class0[0], NUM_CLASSES);
                    /* Get probability of each class */
                    pirNetInferenceResult.human_probability = DAP_swapEndianness(pir_output_class0[0][0]);
                    pirNetInferenceResult.dog_probability = DAP_swapEndianness(pir_output_class0[0][1]);
                    pirNetInferenceResult.background_probability = DAP_swapEndianness(pir_output_class0[0][2]);

                    /* Transmit inference results using the DAP */
                    DAP_sendData(DAP_SEND_DATA_TYPE_INFERENCING_VALUE,
                                 &pirNetInferenceResult, sizeof(pirNetInferenceResult));
                }

                break;

            default:

                break;
        }
    }
}