/******************************************************************************
*
* Revision: A
* Author: MAW
* Created:  2 Feb 2018 MiniRaman
*
* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*  FILE: Interlocks.c
* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*
* DESCRIPTION: Header file to define callback functions for the Interlocks.
*
* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*   Copyright (c) 2018, Metrohm Raman
* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*/

#include <stdio.h>
#include <string.h>
#include "SRI_Global.h"
#include <ti/drivers/GPIO.h>
#include "Parse.h"
#include "Board.h"
#include "Interlocks.h"
#include "Laser.h"
#include "EEPROM.h"
#include "project_zero.h"


void CC2640R2_MiniRaman_InitInterlocks(void)
 {
    // install callbacks
    GPIO_setCallback(MINI_INTRLCK1, interlockPinIntCb);
    GPIO_setCallback(MINI_INTRLCK2, interlockPinIntCb);
    GPIO_setCallback(MINI_INTRLCK3, interlockPinIntCb);
    // Enable interrupts
    GPIO_enableInt(MINI_INTRLCK1);
    GPIO_enableInt(MINI_INTRLCK2);
    GPIO_enableInt(MINI_INTRLCK3);
 }


// GPIO interrupt callback
void interlockPinIntCb(uint_least8_t index)
{
    /* Yeah, I know you aren't supposed to need to clear
     * the interrupt, but since we don't know which pin it
     * was it is simpler to clear all three.
     */
    GPIO_clearInt(MINI_INTRLCK1);
    GPIO_clearInt(MINI_INTRLCK2);
    GPIO_clearInt(MINI_INTRLCK3);

    if (PIN_getInputValue(MINIRAMAN_INTERLOCK_1) == 0)
    {
        status.Interlock1 = SAFE;
    }
    else
    {
        status.Interlock1 = UNSAFE;
    }
    if (PIN_getInputValue(MINIRAMAN_INTERLOCK_2) == 0)
    {
        status.Interlock2 = SAFE;
    }
    else
    {
        status.Interlock2 = UNSAFE;
    }
    if (PIN_getInputValue(MINIRAMAN_INTERLOCK_3) == 0)
    {
        status.Interlock3 = SAFE;
    }
    else
    {
        status.Interlock3 = UNSAFE;
    }
    if ((status.Interlock1 == SAFE) && (status.Interlock2 == SAFE) && (status.Interlock3 == SAFE))
    {
        status.safe = TRUE;
    }
    else
    {
        if (eeprom_base.eeprom.LaserClass == 1)
        {
            status.safe = FALSE;
            Laser_Control(0);
        }
        else
        {
            status.safe = TRUE;
        }
    }
    // Send message to application that it should update the value of the characteristic from Task context.
    int_enqueueCharDataMsg(APP_MSG_INTERLOCK_INTR, 0xFFFF, USER_INTERRUPT_INTERLOCK_UUID, NULL,
                                    NULL, NULL);
 }




/******************************************************************************
* Done.
*/
