/*
    zbus.c - I2C/SPI abstractions
    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>

#define ZBUSDEBUGx

int zbus_free(struct zbusdev *dev){
    if (!dev) return 0;
    if (!dev->free) return -1;
    return dev->free(dev);
}

int zbus_write(struct zbusdev *dev, void *buf, size_t len){
    if (!dev->write) return -1;
    return dev->write(dev, buf, len);
}

int zbus_read(struct zbusdev *dev, void *buf, size_t len){
    if (!dev->read) return -1;
    return dev->read(dev, buf, len);
}




int zbus_write_reg(struct zbusdev *dev, unsigned char addr, unsigned char value){
    int ret = 0;
    char buf[2];
    buf[0] = addr;
    buf[1] = value;

#ifdef ZBUSDEBUG
    dbg("zbus_write_reg(0x%02x, 0x%02x)\n", addr, value);
#endif
    ZRET(zbus_write(dev, buf, 2));
    return ret;
}


int zbus_read_reg(struct zbusdev *dev, unsigned char addr){
    unsigned char buf[1];
    int ret = 0;

    ZRET(zbus_read_regs(dev, addr, buf, 1));
#ifdef ZBUSDEBUG
    dbg("zbus_read_reg(0x%02x) = 0x%02x\n", addr, buf[0]);
#endif
    return buf[0];
}

int zbus_read_regs(struct zbusdev *dev, unsigned char addr, void *buf, size_t len){
    if (dev->read_regs) return dev->read_regs(dev, addr, buf, len);
                                                          

    // I2C can work this way, SPI not
    int ret = 0;
    ZRET(zbus_write(dev, &addr, 1));
    ZRET(zbus_read(dev, buf, len));

#ifdef ZBUSDEBUG
    if (zdebug_debug_type){
        int i;
        dbg("zbus_read_regs(0x%02x) =", addr);
        for (i = 0; i < len; i++) dbg(" %02x", ((unsigned char *)buf)[i]);
        dbg("\n");
    }
#endif
    return ret;
}




