/*
    zspidev.c - SPI over spidev
    Copyright (C) 2018 Ladislav Vaiz <ok1zia@nagano.cz>

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License
    version 2 as published by the Free Software Foundation.

*/

#include <libziaint.h>

#include <zbus.h>
#include <zdebug.h>
#include <zspidev.h>
#include <zmisc.h>

#include <fcntl.h>
#include <glib.h>
#ifdef Z_HAVE_LINUX_SPI_SPIDEV_H
#include <linux/spi/spidev.h>
#endif
//#include <stdint.h>
//#ifdef Z_HAVE_SYS_IOCTL_H
//#include <sys/ioctl.h>
//#endif
#ifdef Z_HAVE_UNISTD_H
#include <unistd.h>
#endif


#ifdef Z_HAVE_LINUX_SPI_SPIDEV_H


int zspidev_write(struct zbusdev *dev, void *buf, size_t len){
    if (dev->fd < 0) return -1;

    int ret = write(dev->fd, buf, len); 
    if (ret < 0) {
        close(dev->fd);
        dev->fd = -1;
        return -1;
    }
    return ret;
}

int zspidev_read(struct zbusdev *dev, void *buf, size_t len){
    if (dev->fd < 0) return -1;

    int ret = read(dev->fd, buf, len); 
    if (ret < 0) {
        close(dev->fd);
        dev->fd = -1;
        return -1;
    }
    return ret;
}
#endif

int zspidev_free(struct zbusdev *dev){
    if (dev->fd >= 0){
        close(dev->fd);
        dev->fd = -1;
    }
    return 0;
}


struct zbusdev *zspidev_init(int busnr, int cs){
    struct zbusdev *dev = (struct zbusdev *)g_new0(struct zbusdev, 1);
    dev->busnr = busnr;
    dev->cs = cs;
    
    dev->filename = g_strdup_printf("/dev/spidev%d.%d", dev->busnr, dev->cs);

#ifdef Z_HAVE_LINUX_SPI_SPIDEV_H
    dev->free = zspidev_free;
    dev->write = zspidev_write;
    dev->read = zspidev_read;
#endif
    
    dev->fd = open(dev->filename, O_RDWR);
    if (dev->fd < 0) {
        zspidev_free(dev);
        return NULL;
    }
    
    return dev;
}

