// Functions control the logical power on/off for the chip

#include "CM_LIB.h"
#include "CM_I2C.h"
#include "CM_I2C_L.h"
#include <unistd.h>
#include <stdio.h>
#include "linux/fcntl.h"
#include "driver.h"
#include <string.h>
// Power On Chip  
//
// Returns 0 (SUCCESS) if no error
//
void cm_PowerOn(void)   
{
//    printf("---> cm_PowerOn\n");
	// Reset chip data
	cm_ResetCrypto();
    ucCM_UserZone = ucCM_AntiTearing = 0;
    
    int ret;
    crypto_t crypto_arg;
    crypto_arg.loop = CM_PWRON_CLKS;
    int fd = open("/dev/crypto", O_RDWR);
    if(fd <= 0)
    {
        printf("Open /dev/crypto error!\n");
        return;
    }

    ret = ioctl(fd, CRYPTO_POWER_ON, &crypto_arg);
    if(ret != 0)
    {
        printf("cm_PowerOn failed!\n");
        close(fd);
        return;
    }
    close(fd);


 //    // Sequence for powering on secure memory according to ATMEL spec
 //    CM_DATA_OUT;                              // SDA and SCL start as outputs
	// CM_CLK_OUT;
 //    CM_CLK_LO;                                // Clock should start LOW
 //    CM_DATA_HI;                               // Data high during reset
 //    cm_ClockCycles(CM_PWRON_CLKS);            // Give chip some clocks cycles to get started

    // Chip should now be in sync mode and ready to operate
}

// Shut down secure memory
//
void cm_PowerOff(void)
{
    printf("---> cm_PowerOff\n");
	// cm_Delay(1);
	// CM_CLK_LO;
	// cm_Delay(6);

    int ret;
    crypto_t crypto_arg;
    int fd = open("/dev/crypto", O_RDWR);
    if(fd <= 0)
    {
        printf("Open /dev/crypto error!\n");
        return;
    }

    ret = ioctl(fd, CRYPTO_POWER_OFF, &crypto_arg);
    if(ret != 0)
    {
        printf("cm_PowerOff failed!\n");
        close(fd);
        return;
    }
    close(fd);
}
