Implement ftdi led device - 2 (#1746)

This commit is contained in:
LordGrey
2024-05-31 23:08:13 +02:00
committed by GitHub
parent 897e4aac8a
commit 76fff98f5c
24 changed files with 1037 additions and 25 deletions

View File

@@ -0,0 +1,52 @@
#include "LedDeviceAPA102_ftdi.h"
#define LED_HEADER 0b11100000
#define LED_BRIGHTNESS_FULL 31
LedDeviceAPA102_ftdi::LedDeviceAPA102_ftdi(const QJsonObject &deviceConfig) : ProviderFtdi(deviceConfig)
{
}
LedDevice *LedDeviceAPA102_ftdi::construct(const QJsonObject &deviceConfig)
{
return new LedDeviceAPA102_ftdi(deviceConfig);
}
bool LedDeviceAPA102_ftdi::init(const QJsonObject &deviceConfig)
{
bool isInitOK = false;
// Initialise sub-class
if (ProviderFtdi::init(deviceConfig))
{
_brightnessControlMaxLevel = deviceConfig["brightnessControlMaxLevel"].toInt(LED_BRIGHTNESS_FULL);
Info(_log, "[%s] Setting maximum brightness to [%d] = %d%%", QSTRING_CSTR(_activeDeviceType), _brightnessControlMaxLevel, _brightnessControlMaxLevel * 100 / LED_BRIGHTNESS_FULL);
CreateHeader();
isInitOK = true;
}
return isInitOK;
}
void LedDeviceAPA102_ftdi::CreateHeader()
{
const unsigned int startFrameSize = 4;
// Endframe, add additional 4 bytes to cover SK9922 Reset frame (in case SK9922 were sold as AP102) - has no effect on APA102
const unsigned int endFrameSize = (_ledCount / 32) * 4 + 4;
const unsigned int APAbufferSize = (_ledCount * 4) + startFrameSize + endFrameSize;
_ledBuffer.resize(APAbufferSize, 0);
Debug(_log, "APA102 buffer created for %d LEDs", _ledCount);
}
int LedDeviceAPA102_ftdi::write(const std::vector<ColorRgb> &ledValues)
{
for (signed iLed = 0; iLed < static_cast<int>(_ledCount); ++iLed)
{
const ColorRgb &rgb = ledValues[iLed];
_ledBuffer[4 + iLed * 4 + 0] = LED_HEADER | _brightnessControlMaxLevel;
_ledBuffer[4 + iLed * 4 + 1] = rgb.red;
_ledBuffer[4 + iLed * 4 + 2] = rgb.green;
_ledBuffer[4 + iLed * 4 + 3] = rgb.blue;
}
return writeBytes(_ledBuffer.size(), _ledBuffer.data());
}

View File

@@ -0,0 +1,50 @@
#ifndef LEDEVICET_APA102_H
#define LEDEVICET_APA102_H
#include "ProviderFtdi.h"
class LedDeviceAPA102_ftdi : public ProviderFtdi
{
Q_OBJECT
public:
///
/// @brief Constructs an APA102 LED-device
///
/// @param deviceConfig Device's configuration as JSON-Object
///
explicit LedDeviceAPA102_ftdi(const QJsonObject& deviceConfig);
///
/// @brief Constructs the LED-device
///
/// @param[in] deviceConfig Device's configuration as JSON-Object
/// @return LedDevice constructed
static LedDevice* construct(const QJsonObject& deviceConfig);
private:
///
/// @brief Initialise the device's configuration
///
/// @param[in] deviceConfig the JSON device configuration
/// @return True, if success
///
bool init(const QJsonObject& deviceConfig) override;
void CreateHeader();
///
/// @brief Writes the RGB-Color values to the LEDs.
///
/// @param[in] ledValues The RGB-color per LED
/// @return Zero on success, else negative
///
int write(const std::vector<ColorRgb>& ledValues) override;
/// The brighness level. Possibile values 1 .. 31.
int _brightnessControlMaxLevel;
};
#endif // LEDEVICET_APA102_H

View File

@@ -0,0 +1,96 @@
#include "LedDeviceSk6812_ftdi.h"
LedDeviceSk6812_ftdi::LedDeviceSk6812_ftdi(const QJsonObject &deviceConfig)
: ProviderFtdi(deviceConfig),
_whiteAlgorithm(RGBW::WhiteAlgorithm::INVALID),
SPI_BYTES_PER_COLOUR(4),
bitpair_to_byte{
0b10001000,
0b10001100,
0b11001000,
0b11001100}
{
}
LedDevice *LedDeviceSk6812_ftdi::construct(const QJsonObject &deviceConfig)
{
return new LedDeviceSk6812_ftdi(deviceConfig);
}
bool LedDeviceSk6812_ftdi::init(const QJsonObject &deviceConfig)
{
bool isInitOK = false;
// Initialise sub-class
if (ProviderFtdi::init(deviceConfig))
{
_brightnessControlMaxLevel = deviceConfig["brightnessControlMaxLevel"].toInt(255);
Info(_log, "[%s] Setting maximum brightness to [%d]", QSTRING_CSTR(_activeDeviceType), _brightnessControlMaxLevel);
QString whiteAlgorithm = deviceConfig["whiteAlgorithm"].toString("white_off");
_whiteAlgorithm = RGBW::stringToWhiteAlgorithm(whiteAlgorithm);
if (_whiteAlgorithm == RGBW::WhiteAlgorithm::INVALID)
{
QString errortext = QString ("unknown whiteAlgorithm: %1").arg(whiteAlgorithm);
this->setInError(errortext);
isInitOK = false;
}
else
{
Debug(_log, "whiteAlgorithm : %s", QSTRING_CSTR(whiteAlgorithm));
WarningIf((_baudRate_Hz < 2050000 || _baudRate_Hz > 3750000), _log, "Baud rate %d outside recommended range (2050000 -> 3750000)", _baudRate_Hz);
const int SPI_FRAME_END_LATCH_BYTES = 3;
_ledBuffer.resize(_ledRGBWCount * SPI_BYTES_PER_COLOUR + SPI_FRAME_END_LATCH_BYTES, 0x00);
isInitOK = true;
}
}
return isInitOK;
}
inline __attribute__((always_inline)) uint8_t LedDeviceSk6812_ftdi::scale(uint8_t i, uint8_t scale) {
return (((uint16_t)i) * (1+(uint16_t)(scale))) >> 8;
}
int LedDeviceSk6812_ftdi::write(const std::vector<ColorRgb> &ledValues)
{
unsigned spi_ptr = 0;
const int SPI_BYTES_PER_LED = sizeof(ColorRgbw) * SPI_BYTES_PER_COLOUR;
ColorRgbw temp_rgbw;
ColorRgb scaled_color;
for (const ColorRgb &color : ledValues)
{
scaled_color.red = scale(color.red, _brightnessControlMaxLevel);
scaled_color.green = scale(color.green, _brightnessControlMaxLevel);
scaled_color.blue = scale(color.blue, _brightnessControlMaxLevel);
RGBW::Rgb_to_Rgbw(scaled_color, &temp_rgbw, _whiteAlgorithm);
uint32_t colorBits =
((uint32_t)temp_rgbw.red << 24) +
((uint32_t)temp_rgbw.green << 16) +
((uint32_t)temp_rgbw.blue << 8) +
temp_rgbw.white;
for (int j = SPI_BYTES_PER_LED - 1; j >= 0; j--)
{
_ledBuffer[spi_ptr + j] = bitpair_to_byte[colorBits & 0x3];
colorBits >>= 2;
}
spi_ptr += SPI_BYTES_PER_LED;
}
_ledBuffer[spi_ptr++] = 0;
_ledBuffer[spi_ptr++] = 0;
_ledBuffer[spi_ptr++] = 0;
return writeBytes(_ledBuffer.size(), _ledBuffer.data());
}

View File

@@ -0,0 +1,52 @@
#ifndef LEDEVICESK6812ftdi_H
#define LEDEVICESK6812ftdi_H
#include "ProviderFtdi.h"
class LedDeviceSk6812_ftdi : public ProviderFtdi
{
public:
///
/// @brief Constructs a Sk6801 LED-device
///
/// @param deviceConfig Device's configuration as JSON-Object
///
explicit LedDeviceSk6812_ftdi(const QJsonObject& deviceConfig);
///
/// @brief Constructs the LED-device
///
/// @param[in] deviceConfig Device's configuration as JSON-Object
/// @return LedDevice constructed
static LedDevice* construct(const QJsonObject& deviceConfig);
private:
///
/// @brief Initialise the device's configuration
///
/// @param[in] deviceConfig the JSON device configuration
/// @return True, if success
///
bool init(const QJsonObject& deviceConfig) override;
///
/// @brief Writes the RGB-Color values to the LEDs.
///
/// @param[in] ledValues The RGB-color per LED
/// @return Zero on success, else negative
///
int write(const std::vector<ColorRgb>& ledValues) override;
inline __attribute__((always_inline)) uint8_t scale(uint8_t i, uint8_t scale);
RGBW::WhiteAlgorithm _whiteAlgorithm;
const int SPI_BYTES_PER_COLOUR;
uint8_t bitpair_to_byte[4];
int _brightnessControlMaxLevel;
};
#endif // LEDEVICESK6812ftdi_H

View File

@@ -0,0 +1,93 @@
#include "LedDeviceWs2812_ftdi.h"
/*
From the data sheet:
(TH+TL=1.25μs±600ns)
T0H, 0 code, high level time, 0.40µs ±0.150ns
T0L, 0 code, low level time, 0.85µs ±0.150ns
T1H, 1 code, high level time, 0.80µs ±0.150ns
T1L, 1 code, low level time, 0.45µs ±0.150ns
WT, Wait for the processing time, NA
Trst, Reset code,low level time, 50µs (not anymore... need 300uS for latest revision)
To normalise the pulse times so they fit in 4 SPI bits:
On the assumption that the "low" time doesnt matter much
A SPI bit time of 0.40uS = 2.5 Mbit/sec
T0 is sent as 1000
T1 is sent as 1100
With a bit of excel testing, we can work out the maximum and minimum speeds:
2106000 MIN
2590500 AVG
3075000 MAX
Wait time:
Not Applicable for WS2812
Reset time:
using the max of 3075000, the bit time is 0.325
Reset time is 300uS = 923 bits = 116 bytes
*/
LedDeviceWs2812_ftdi::LedDeviceWs2812_ftdi(const QJsonObject &deviceConfig)
: ProviderFtdi(deviceConfig),
SPI_BYTES_PER_COLOUR(4),
SPI_FRAME_END_LATCH_BYTES(116),
bitpair_to_byte{
0b10001000,
0b10001100,
0b11001000,
0b11001100,
}
{
}
LedDevice *LedDeviceWs2812_ftdi::construct(const QJsonObject &deviceConfig)
{
return new LedDeviceWs2812_ftdi(deviceConfig);
}
bool LedDeviceWs2812_ftdi::init(const QJsonObject &deviceConfig)
{
bool isInitOK = false;
// Initialise sub-class
if (ProviderFtdi::init(deviceConfig))
{
WarningIf((_baudRate_Hz < 2106000 || _baudRate_Hz > 3075000), _log, "Baud rate %d outside recommended range (2106000 -> 3075000)", _baudRate_Hz);
_ledBuffer.resize(_ledRGBCount * SPI_BYTES_PER_COLOUR + SPI_FRAME_END_LATCH_BYTES, 0x00);
isInitOK = true;
}
return isInitOK;
}
int LedDeviceWs2812_ftdi::write(const std::vector<ColorRgb> &ledValues)
{
unsigned spi_ptr = 0;
const int SPI_BYTES_PER_LED = sizeof(ColorRgb) * SPI_BYTES_PER_COLOUR;
for (const ColorRgb &color : ledValues)
{
uint32_t colorBits = ((unsigned int)color.red << 16) | ((unsigned int)color.green << 8) | color.blue;
for (int j = SPI_BYTES_PER_LED - 1; j >= 0; j--)
{
_ledBuffer[spi_ptr + j] = bitpair_to_byte[colorBits & 0x3];
colorBits >>= 2;
}
spi_ptr += SPI_BYTES_PER_LED;
}
for (int j = 0; j < SPI_FRAME_END_LATCH_BYTES; j++)
{
_ledBuffer[spi_ptr++] = 0;
}
return writeBytes(_ledBuffer.size(), _ledBuffer.data());
}

View File

@@ -0,0 +1,49 @@
#ifndef LEDEVICEWS2812_ftdi_H
#define LEDEVICEWS2812_ftdi_H
#include "ProviderFtdi.h"
class LedDeviceWs2812_ftdi : public ProviderFtdi
{
public:
///
/// @brief Constructs a Ws2812 LED-device
///
/// @param deviceConfig Device's configuration as JSON-Object
///
explicit LedDeviceWs2812_ftdi(const QJsonObject& deviceConfig);
///
/// @brief Constructs the LED-device
///
/// @param[in] deviceConfig Device's configuration as JSON-Object
/// @return LedDevice constructed
static LedDevice* construct(const QJsonObject& deviceConfig);
private:
///
/// @brief Initialise the device's configuration
///
/// @param[in] deviceConfig the JSON device configuration
/// @return True, if success
///
bool init(const QJsonObject& deviceConfig) override;
///
/// @brief Writes the RGB-Color values to the LEDs.
///
/// @param[in] ledValues The RGB-color per LED
/// @return Zero on success, else negative
///
int write(const std::vector<ColorRgb>& ledValues) override;
const int SPI_BYTES_PER_COLOUR;
const int SPI_FRAME_END_LATCH_BYTES;
uint8_t bitpair_to_byte[4];
};
#endif // LEDEVICEWS2812_ftdi_H

View File

@@ -0,0 +1,208 @@
// LedDevice includes
#include <leddevice/LedDevice.h>
#include "ProviderFtdi.h"
#include <utils/WaitTime.h>
#include <ftdi.h>
#include <libusb.h>
#define ANY_FTDI_VENDOR 0x0
#define ANY_FTDI_PRODUCT 0x0
#define FTDI_CHECK_RESULT(statement) if (statement) {setInError(ftdi_get_error_string(_ftdic)); return rc;}
namespace Pin
{
// enumerate the AD bus for convenience.
enum bus_t
{
SK = 0x01, // ADBUS0, SPI data clock
DO = 0x02, // ADBUS1, SPI data out
CS = 0x08, // ADBUS3, SPI chip select, active low
};
}
const uint8_t pinInitialState = Pin::CS;
// Use these pins as outputs
const uint8_t pinDirection = Pin::SK | Pin::DO | Pin::CS;
const QString ProviderFtdi::AUTO_SETTING = QString("auto");
ProviderFtdi::ProviderFtdi(const QJsonObject &deviceConfig)
: LedDevice(deviceConfig),
_ftdic(nullptr),
_baudRate_Hz(1000000)
{
}
bool ProviderFtdi::init(const QJsonObject &deviceConfig)
{
bool isInitOK = false;
if (LedDevice::init(deviceConfig))
{
_baudRate_Hz = deviceConfig["rate"].toInt(_baudRate_Hz);
_deviceName = deviceConfig["output"].toString(AUTO_SETTING);
Debug(_log, "_baudRate_Hz [%d]", _baudRate_Hz);
Debug(_log, "_deviceName [%s]", QSTRING_CSTR(_deviceName));
isInitOK = true;
}
return isInitOK;
}
int ProviderFtdi::open()
{
int rc = 0;
_ftdic = ftdi_new();
if (ftdi_init(_ftdic) < 0)
{
_ftdic = nullptr;
setInError("Could not initialize the ftdi library");
return -1;
}
Debug(_log, "Opening FTDI device=%s", QSTRING_CSTR(_deviceName));
FTDI_CHECK_RESULT((rc = ftdi_usb_open_string(_ftdic, QSTRING_CSTR(_deviceName))) < 0);
/* doing this disable resets things if they were in a bad state */
FTDI_CHECK_RESULT((rc = ftdi_disable_bitbang(_ftdic)) < 0);
FTDI_CHECK_RESULT((rc = ftdi_setflowctrl(_ftdic, SIO_DISABLE_FLOW_CTRL)) < 0);
FTDI_CHECK_RESULT((rc = ftdi_set_bitmode(_ftdic, 0x00, BITMODE_RESET)) < 0);
FTDI_CHECK_RESULT((rc = ftdi_set_bitmode(_ftdic, 0xff, BITMODE_MPSSE)) < 0);
double reference_clock = 60e6;
int divisor = (reference_clock / 2 / _baudRate_Hz) - 1;
std::vector<uint8_t> buf = {
DIS_DIV_5,
TCK_DIVISOR,
static_cast<unsigned char>(divisor),
static_cast<unsigned char>(divisor >> 8),
SET_BITS_LOW, // opcode: set low bits (ADBUS[0-7]
pinInitialState, // argument: inital pin state
pinDirection
};
FTDI_CHECK_RESULT((rc = ftdi_write_data(_ftdic, buf.data(), buf.size())) != buf.size());
_isDeviceReady = true;
return rc;
}
int ProviderFtdi::close()
{
LedDevice::close();
if (_ftdic != nullptr) {
Debug(_log, "Closing FTDI device");
// Delay to give time to push color black from writeBlack() into the led,
// otherwise frame transmission will be terminated half way through
wait(30);
ftdi_set_bitmode(_ftdic, 0x00, BITMODE_RESET);
ftdi_usb_close(_ftdic);
ftdi_free(_ftdic);
_ftdic = nullptr;
}
return 0;
}
void ProviderFtdi::setInError(const QString &errorMsg, bool isRecoverable)
{
close();
LedDevice::setInError(errorMsg, isRecoverable);
}
int ProviderFtdi::writeBytes(const qint64 size, const uint8_t *data)
{
int rc;
int count_arg = size - 1;
std::vector<uint8_t> buf = {
SET_BITS_LOW,
pinInitialState & ~Pin::CS,
pinDirection,
MPSSE_DO_WRITE | MPSSE_WRITE_NEG,
static_cast<unsigned char>(count_arg),
static_cast<unsigned char>(count_arg >> 8),
SET_BITS_LOW,
pinInitialState | Pin::CS,
pinDirection
};
// insert before last SET_BITS_LOW command
// SET_BITS_LOW takes 2 arguments, so we're inserting data in -3 position from the end
buf.insert(buf.end() - 3, &data[0], &data[size]);
FTDI_CHECK_RESULT((rc = ftdi_write_data(_ftdic, buf.data(), buf.size())) != buf.size());
return rc;
}
QJsonObject ProviderFtdi::discover(const QJsonObject & /*params*/)
{
QJsonObject devicesDiscovered;
QJsonArray deviceList;
struct ftdi_device_list *devlist;
struct ftdi_context *ftdic;
ftdic = ftdi_new();
if (ftdi_usb_find_all(ftdic, &devlist, ANY_FTDI_VENDOR, ANY_FTDI_PRODUCT) > 0)
{
struct ftdi_device_list *curdev = devlist;
QMap<QString, uint8_t> deviceIndexes;
while (curdev)
{
libusb_device_descriptor desc;
int rc = libusb_get_device_descriptor(curdev->dev, &desc);
if (rc == 0)
{
QString vendorIdentifier = QString("0x%1").arg(desc.idVendor, 4, 16, QChar{'0'});
QString productIdentifier = QString("0x%1").arg(desc.idProduct, 4, 16, QChar{'0'});
QString vendorAndProduct = QString("%1:%2")
.arg(vendorIdentifier)
.arg(productIdentifier);
uint8_t deviceIndex = deviceIndexes.value(vendorAndProduct, 0);
char serial_string[128] = {0};
char manufacturer_string[128] = {0};
char description_string[128] = {0};
ftdi_usb_get_strings2(ftdic, curdev->dev, manufacturer_string, 128, description_string, 128, serial_string, 128);
QString serialNumber {serial_string};
QString ftdiOpenString;
if(!serialNumber.isEmpty())
{
ftdiOpenString = QString("s:%1:%2").arg(vendorAndProduct).arg(serialNumber);
}
else
{
ftdiOpenString = QString("i:%1:%2").arg(vendorAndProduct).arg(deviceIndex);
}
deviceList.push_back(QJsonObject{
{"ftdiOpenString", ftdiOpenString},
{"vendorIdentifier", vendorIdentifier},
{"productIdentifier", productIdentifier},
{"deviceIndex", deviceIndex},
{"serialNumber", serialNumber},
{"manufacturer", manufacturer_string},
{"description", description_string}
});
deviceIndexes.insert(vendorAndProduct, deviceIndex + 1);
}
curdev = curdev->next;
}
}
ftdi_list_free(&devlist);
ftdi_free(ftdic);
devicesDiscovered.insert("ledDeviceType", _activeDeviceType);
devicesDiscovered.insert("devices", deviceList);
Debug(_log, "FTDI devices discovered: [%s]", QString(QJsonDocument(devicesDiscovered).toJson(QJsonDocument::Compact)).toUtf8().constData());
return devicesDiscovered;
}

View File

@@ -0,0 +1,76 @@
#ifndef PROVIDERFtdi_H
#define PROVIDERFtdi_H
// LedDevice includes
#include <leddevice/LedDevice.h>
#include <ftdi.h>
///
/// The ProviderFtdi implements an abstract base-class for LedDevices using a Ftdi-device.
///
class ProviderFtdi : public LedDevice
{
Q_OBJECT
public:
///
/// @brief Constructs a Ftdi LED-device
///
ProviderFtdi(const QJsonObject& deviceConfig);
static const QString AUTO_SETTING;
protected:
///
/// @brief Opens the output device.
///
/// @return Zero on success (i.e. device is ready), else negative
///
int open() override;
///
/// Sets configuration
///
/// @param deviceConfig the json device config
/// @return true if success
bool init(const QJsonObject& deviceConfig) override;
///
/// @brief Closes the UDP device.
///
/// @return Zero on success (i.e. device is closed), else negative
///
int close() override;
/// @brief Write the given bytes to the Ftdi-device
///
/// @param[in[ size The length of the data
/// @param[in] data The data
/// @return Zero on success, else negative
///
int writeBytes(const qint64 size, const uint8_t* data);
QJsonObject discover(const QJsonObject& params) override;
/// The Ftdi serial-device
struct ftdi_context *_ftdic;
/// The used baud-rate of the output device
qint32 _baudRate_Hz;
QString _deviceName;
protected slots:
///
/// @brief Set device in error state
///
/// @param errorMsg The error message to be logged
///
void setInError(const QString& errorMsg, bool isRecoverable=true) override;
};
#endif // PROVIDERFtdi_H