/*
  v 1.0 By Winson 2018.11.8
  Create first version
  This demo for LX-2031 PAC only.
*/

#include <stdint.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/types.h>
#include <linux/spi/spidev.h>
#include "lx_2031.h"

static const char *device = "/dev/spidev1.0";

#define SIZE 1024

int main(int argc, char *argv[])
{
        uint8_t mode = 0;
        uint8_t bits = 8;
        uint32_t speed = 4000000;
        uint16_t delay = 0;
        char txBuf[131072];
        char rxBuf[131072];
        char status=0;
        int fd;
        int ret = 0, offset;

        fd = open(device, O_RDWR);
        if (fd < 0)
                pabort("can't open device");

        ret = spinor_init(fd, mode, bits, speed, delay);
        printf("\n");
        printf("spi mode: %d\n", mode);
        printf("bits per word: %d\n", bits);
        printf("max speed: %d Hz (%d KHz)\n", speed, speed/1000);

	memset(rxBuf, 0, sizeof(rxBuf));

	offset = 0;	//start address

	for (ret=0; ret < SIZE; ret++) {
		txBuf[ret] = ((ret) & 0xff);
		//printf("%d. %.2X ",ret, txBuf[ret] & 0xff);
	}

	ret = spinor_write(fd, offset, txBuf, SIZE);	//write to mram

	ret = spinor_read(fd, offset, rxBuf, SIZE);	//read from mram

	for (ret = 0; ret < SIZE; ret++) 
	{
		if(ret % 16 == 0)
		{
			printf("\n0x%05x.   ", offset);
			offset += 16;
		}
		else if(ret % 8 == 0)
			printf(" ");
		printf("%.2X ", rxBuf[ret] & 0xff);

	}
	puts("");

        close(fd);
        return ret;
}
