/* test-spi-rpi-01.c - Programme pour Raspberry Pi */
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include <linux/types.h>
#include <linux/spi/spidev.h>

#include <sys/ioctl.h>

int focus( int fd_spi){
	unsigned char bytes[2]={0x00,0x19};
printf("FOCUS !\n");
	return write(fd_spi,bytes,2);
}

int shot ( int fd_spi ) {

 unsigned char bytes[2]={0x00,0x0A};
	printf("SHOT !\n"); 
       return write(fd_spi,bytes,2);
}

int stdby ( int fd_spi ) {

 unsigned char bytes[2]={0x00,0xD0};
printf("STDBY !\n ");       
 return write(fd_spi,bytes,2);
}


int main(int argc, char *argv[])
{
        int fd_spi;
        char ligne[80];
        int value;
        unsigned char byte;

        unsigned int speed = 250000;

        if (argc != 3) {
                fprintf(stderr, "usage: %s <spi-port> <spi-speed>n", argv[0]);
                exit(EXIT_FAILURE);
        }
        fd_spi = open(argv[1], O_RDWR);
        if (fd_spi < 0) {
                perror(argv[1]);
                exit(EXIT_FAILURE);
        }

        if (sscanf(argv[2], "%d", & speed) != 1) {
                fprintf(stderr, "Wrong value for speed: %sn", argv[2]);
                exit(EXIT_FAILURE);
        }
        if (ioctl(fd_spi, SPI_IOC_WR_MAX_SPEED_HZ, & speed) != 0) {
                perror("ioctl");
                exit(EXIT_FAILURE);
        }

	while ( 1 )
	{
		stdby(fd_spi);
	 	sleep(4);	
		focus(fd_spi);
		usleep(200000);
		shot(fd_spi);
		usleep(100000);
	}



        while (fgets(ligne, 80, stdin) != NULL) {
                if (sscanf(ligne, "%d", & value) != 1){
                        fprintf(stderr, "integer value expectedn");
                        continue;
                }
                byte = (unsigned char) (value & 0xFF);
                if (write(fd_spi, & byte, 1) != 1) {
                        perror("write");
                        exit(EXIT_FAILURE);
                }
        }
        close(fd_spi);
        return EXIT_SUCCESS;
}


