#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <stdbool.h> 

enum SYSTEM_CMD_TYPE {
	CMDQU_SEND = 1,
	CMDQU_SEND_WAIT,
	CMDQU_SEND_WAKEUP,
};

#define T_FILE "/sys/devices/virtual/thermal/thermal_zone0/temp"
#define RTOS_CMDQU_DEV_NAME "/dev/cvi-rtos-cmdqu"
#define RTOS_CMDQU_SEND                         _IOW('r', CMDQU_SEND, unsigned long)
#define RTOS_CMDQU_SEND_WAIT                    _IOW('r', CMDQU_SEND_WAIT, unsigned long)
#define RTOS_CMDQU_SEND_WAKEUP                  _IOW('r', CMDQU_SEND_WAKEUP, unsigned long)

struct valid_t {
	unsigned char linux_valid;
	unsigned char rtos_valid;
} __attribute__((packed));

typedef union resv_t {
	struct valid_t valid;
	unsigned short mstime; // 0 : noblock, -1 : block infinite
} resv_t;

typedef struct cmdqu_t cmdqu_t;
/* cmdqu size should be 8 bytes because of mailbox buffer size */
struct cmdqu_t {
	unsigned char ip_id;
	unsigned char cmd_id : 7;
	unsigned char block : 1;
	union resv_t resv;
	unsigned int  param_ptr;
} __attribute__((packed)) __attribute__((aligned(0x8)));

int main()
{
    int ret = 0, tempr, fd;
    char temp[6];

while( true ) {
	FILE *tf = fopen( T_FILE, "r");
	if( tf <= 0)
    {   printf("open T_FILE failed! tf = %d\n", tf);
        return 0;  
     } 
   fread( temp, 1, 3, tf );		// we will only take the 1st 3 single bytes.
       tempr = atoi( temp );	// convert the 3 digit temperature reading to an ascii string
       printf( "temp = %d\n\r", tempr );  //  print the reading - at this point it is in 1/10s of a degree C
 
 // Here we open the mailbox
    fd = open(RTOS_CMDQU_DEV_NAME, O_RDWR);
    if(fd <= 0)
    {   printf("open CMFQ failed! fd = %d\n", fd);
        return 0;  
     }

    struct cmdqu_t cmd = {0};

    cmd.param_ptr = tempr;		// we will only use the param_ptr element to send the temperature

    ret = ioctl(fd , RTOS_CMDQU_SEND_WAIT, &cmd);	//  here we send the mail
    if(ret < 0)
    {
        printf("ioctl error!\n");
        close(fd);
    }
//    sleep(1);
    printf("Linux core: cmd.param_ptr = 0x%x, (%d)\n", cmd.param_ptr, cmd.param_ptr );

    sleep(3);
    fclose( tf );
}  //  end of endless loop

    close(fd);
    return 0;
}
