2013-11-01 23:48:39 +01:00
|
|
|
|
|
|
|
// STL includes
|
|
|
|
#include <cstring>
|
|
|
|
#include <cstdio>
|
|
|
|
#include <iostream>
|
2016-06-25 14:44:52 +02:00
|
|
|
#include <cerrno>
|
2013-11-01 23:48:39 +01:00
|
|
|
|
|
|
|
// Linux includes
|
|
|
|
#include <fcntl.h>
|
|
|
|
#include <sys/ioctl.h>
|
|
|
|
|
|
|
|
// Local Hyperion includes
|
|
|
|
#include "LedSpiDevice.h"
|
2016-06-25 14:44:52 +02:00
|
|
|
#include <utils/Logger.h>
|
2013-11-01 23:48:39 +01:00
|
|
|
|
|
|
|
|
2013-11-02 19:30:19 +01:00
|
|
|
LedSpiDevice::LedSpiDevice(const std::string& outputDevice, const unsigned baudrate, const int latchTime_ns) :
|
2013-11-01 23:48:39 +01:00
|
|
|
mDeviceName(outputDevice),
|
|
|
|
mBaudRate_Hz(baudrate),
|
2013-11-02 19:30:19 +01:00
|
|
|
mLatchTime_ns(latchTime_ns),
|
2013-11-01 23:48:39 +01:00
|
|
|
mFid(-1)
|
|
|
|
{
|
|
|
|
memset(&spi, 0, sizeof(spi));
|
|
|
|
}
|
|
|
|
|
|
|
|
LedSpiDevice::~LedSpiDevice()
|
|
|
|
{
|
|
|
|
// close(mFid);
|
|
|
|
}
|
|
|
|
|
|
|
|
int LedSpiDevice::open()
|
|
|
|
{
|
|
|
|
const int bitsPerWord = 8;
|
|
|
|
|
|
|
|
mFid = ::open(mDeviceName.c_str(), O_RDWR);
|
|
|
|
|
|
|
|
if (mFid < 0)
|
|
|
|
{
|
2016-06-25 22:08:17 +02:00
|
|
|
Error( _log, "Failed to open device (%s). Error message: %s", mDeviceName.c_str(), strerror(errno) );
|
2013-11-01 23:48:39 +01:00
|
|
|
return -1;
|
|
|
|
}
|
|
|
|
|
|
|
|
int mode = SPI_MODE_0;
|
|
|
|
if (ioctl(mFid, SPI_IOC_WR_MODE, &mode) == -1 || ioctl(mFid, SPI_IOC_RD_MODE, &mode) == -1)
|
|
|
|
{
|
|
|
|
return -2;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (ioctl(mFid, SPI_IOC_WR_BITS_PER_WORD, &bitsPerWord) == -1 || ioctl(mFid, SPI_IOC_RD_BITS_PER_WORD, &bitsPerWord) == -1)
|
|
|
|
{
|
|
|
|
return -4;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (ioctl(mFid, SPI_IOC_WR_MAX_SPEED_HZ, &mBaudRate_Hz) == -1 || ioctl(mFid, SPI_IOC_RD_MAX_SPEED_HZ, &mBaudRate_Hz) == -1)
|
|
|
|
{
|
|
|
|
return -6;
|
|
|
|
}
|
|
|
|
|
|
|
|
return 0;
|
|
|
|
}
|
2013-11-02 06:51:41 +01:00
|
|
|
|
2013-11-02 19:30:19 +01:00
|
|
|
int LedSpiDevice::writeBytes(const unsigned size, const uint8_t * data)
|
2013-11-02 06:51:41 +01:00
|
|
|
{
|
|
|
|
if (mFid < 0)
|
|
|
|
{
|
|
|
|
return -1;
|
|
|
|
}
|
|
|
|
|
2013-11-02 19:30:19 +01:00
|
|
|
spi.tx_buf = __u64(data);
|
|
|
|
spi.len = __u32(size);
|
2013-11-02 06:51:41 +01:00
|
|
|
|
|
|
|
int retVal = ioctl(mFid, SPI_IOC_MESSAGE(1), &spi);
|
|
|
|
|
2013-11-02 19:30:19 +01:00
|
|
|
if (retVal == 0 && mLatchTime_ns > 0)
|
2013-11-02 06:51:41 +01:00
|
|
|
{
|
|
|
|
// The 'latch' time for latching the shifted-value into the leds
|
|
|
|
timespec latchTime;
|
|
|
|
latchTime.tv_sec = 0;
|
2013-11-02 19:30:19 +01:00
|
|
|
latchTime.tv_nsec = mLatchTime_ns;
|
2013-11-02 06:51:41 +01:00
|
|
|
|
|
|
|
// Sleep to latch the leds (only if write succesfull)
|
|
|
|
nanosleep(&latchTime, NULL);
|
|
|
|
}
|
|
|
|
|
|
|
|
return retVal;
|
|
|
|
}
|