Leddevices source tree refactoring (#461)

* rework structure of leddevice source tree

* fix data type vor v4l sig detection value in webui

* automate leddevicefactory.cpp
This commit is contained in:
redPanther
2017-08-07 10:05:46 +02:00
committed by GitHub
parent f3bbe158bf
commit 317a903b14
76 changed files with 98 additions and 222 deletions

View File

@@ -0,0 +1,81 @@
#include "LedDeviceAdalight.h"
LedDeviceAdalight::LedDeviceAdalight(const QJsonObject &deviceConfig)
: ProviderRs232()
, _headerSize(6)
, _ligthBerryAPA102Mode(false)
{
_deviceReady = init(deviceConfig);
connect(this,SIGNAL(receivedData(QByteArray)),this,SLOT(receivedData(QByteArray)));
}
LedDevice* LedDeviceAdalight::construct(const QJsonObject &deviceConfig)
{
return new LedDeviceAdalight(deviceConfig);
}
bool LedDeviceAdalight::init(const QJsonObject &deviceConfig)
{
ProviderRs232::init(deviceConfig);
_ligthBerryAPA102Mode = deviceConfig["lightberry_apa102_mode"].toBool(false);
// create ledBuffer
unsigned int totalLedCount = _ledCount;
if (_ligthBerryAPA102Mode)
{
const unsigned int startFrameSize = 4;
const unsigned int bytesPerRGBLed = 4;
const unsigned int endFrameSize = qMax<unsigned int>(((_ledCount + 15) / 16), bytesPerRGBLed);
_ledBuffer.resize(_headerSize + (_ledCount * bytesPerRGBLed) + startFrameSize + endFrameSize, 0x00);
// init constant data values
for (signed iLed=1; iLed<=_ledCount; iLed++)
{
_ledBuffer[iLed*4+_headerSize] = 0xFF;
}
Debug( _log, "Adalight driver with activated LightBerry APA102 mode");
}
else
{
totalLedCount -= 1;
_ledBuffer.resize(_headerSize + _ledRGBCount, 0x00);
}
_ledBuffer[0] = 'A';
_ledBuffer[1] = 'd';
_ledBuffer[2] = 'a';
_ledBuffer[3] = (totalLedCount >> 8) & 0xFF; // LED count high byte
_ledBuffer[4] = totalLedCount & 0xFF; // LED count low byte
_ledBuffer[5] = _ledBuffer[3] ^ _ledBuffer[4] ^ 0x55; // Checksum
Debug( _log, "Adalight header for %d leds: %c%c%c 0x%02x 0x%02x 0x%02x", _ledCount,
_ledBuffer[0], _ledBuffer[1], _ledBuffer[2], _ledBuffer[3], _ledBuffer[4], _ledBuffer[5] );
return true;
}
int LedDeviceAdalight::write(const std::vector<ColorRgb> & ledValues)
{
if(_ligthBerryAPA102Mode)
{
for (signed iLed=1; iLed<=_ledCount; iLed++)
{
const ColorRgb& rgb = ledValues[iLed-1];
_ledBuffer[iLed*4+7] = rgb.red;
_ledBuffer[iLed*4+8] = rgb.green;
_ledBuffer[iLed*4+9] = rgb.blue;
}
}
else
{
memcpy(_headerSize + _ledBuffer.data(), ledValues.data(), ledValues.size() * 3);
}
return writeBytes(_ledBuffer.size(), _ledBuffer.data());
}
void LedDeviceAdalight::receivedData(QByteArray data)
{
Debug(_log, ">>received %d bytes data", data.size());
}

View File

@@ -0,0 +1,40 @@
#pragma once
#include "ProviderRs232.h"
///
/// Implementation of the LedDevice interface for writing to an Adalight led device.
///
class LedDeviceAdalight : public ProviderRs232
{
Q_OBJECT
public:
///
/// Constructs specific LedDevice
///
/// @param deviceConfig json device config
///
LedDeviceAdalight(const QJsonObject &deviceConfig);
/// constructs leddevice
static LedDevice* construct(const QJsonObject &deviceConfig);
virtual bool init(const QJsonObject &deviceConfig);
public slots:
void receivedData(QByteArray data);
private:
///
/// Writes the led color values to the led-device
///
/// @param ledValues The color-value per led
/// @return Zero on succes else negative
///
virtual int write(const std::vector<ColorRgb> & ledValues);
const short _headerSize;
bool _ligthBerryAPA102Mode;
};

View File

@@ -0,0 +1,38 @@
// hyperion local includes
#include "LedDeviceAtmo.h"
LedDeviceAtmo::LedDeviceAtmo(const QJsonObject &deviceConfig)
: ProviderRs232()
{
_deviceReady = init(deviceConfig);
}
LedDevice* LedDeviceAtmo::construct(const QJsonObject &deviceConfig)
{
return new LedDeviceAtmo(deviceConfig);
}
bool LedDeviceAtmo::init(const QJsonObject &deviceConfig)
{
ProviderRs232::init(deviceConfig);
if (_ledCount != 5)
{
Error( _log, "%d channels configured. This should always be 5!", _ledCount);
return 0;
}
_ledBuffer.resize(4 + 5*3); // 4-byte header, 5 RGB values
_ledBuffer[0] = 0xFF; // Startbyte
_ledBuffer[1] = 0x00; // StartChannel(Low)
_ledBuffer[2] = 0x00; // StartChannel(High)
_ledBuffer[3] = 0x0F; // Number of Databytes send (always! 15)
return true;
}
int LedDeviceAtmo::write(const std::vector<ColorRgb> &ledValues)
{
memcpy(4 + _ledBuffer.data(), ledValues.data(), _ledCount * sizeof(ColorRgb));
return writeBytes(_ledBuffer.size(), _ledBuffer.data());
}

View File

@@ -0,0 +1,32 @@
#pragma once
// hyperion incluse
#include "ProviderRs232.h"
///
/// Implementation of the LedDevice interface for writing to serial device using tpm2 protocol.
///
class LedDeviceAtmo : public ProviderRs232
{
public:
///
/// Constructs specific LedDevice
///
/// @param deviceConfig json device config
///
LedDeviceAtmo(const QJsonObject &deviceConfig);
/// constructs leddevice
static LedDevice* construct(const QJsonObject &deviceConfig);
virtual bool init(const QJsonObject &deviceConfig);
private:
///
/// Writes the led color values to the led-device
///
/// @param ledValues The color-value per led
/// @return Zero on succes else negative
///
virtual int write(const std::vector<ColorRgb> &ledValues);
};

View File

@@ -0,0 +1,95 @@
#include "LedDeviceDMX.h"
#include <QSerialPort>
#include <time.h>
LedDeviceDMX::LedDeviceDMX(const QJsonObject &deviceConfig)
: ProviderRs232()
, _dmxDeviceType(0)
, _dmxStart(1)
, _dmxSlotsPerLed(3)
, _dmxLedCount(0)
, _dmxChannelCount(0)
{
_deviceReady = init(deviceConfig);
}
bool LedDeviceDMX::init(const QJsonObject &deviceConfig)
{
ProviderRs232::init(deviceConfig);
QString dmxString = deviceConfig["dmxdevice"].toString("invalid");
if (dmxString == "raw")
{
_dmxDeviceType = 0;
_dmxStart = 1;
_dmxSlotsPerLed = 3;
}
else if (dmxString == "McCrypt")
{
_dmxDeviceType = 1;
_dmxStart = 1;
_dmxSlotsPerLed = 4;
}
else
{
Error(_log, "unknown dmx device type %s", QSTRING_CSTR(dmxString));
}
Debug(_log, "_dmxString \"%s\", _dmxDeviceType %d", QSTRING_CSTR(dmxString), _dmxDeviceType );
_rs232Port.setStopBits(QSerialPort::TwoStop);
_dmxLedCount = qMin(_ledCount, 512/_dmxSlotsPerLed);
_dmxChannelCount = 1 + _dmxSlotsPerLed * _dmxLedCount;
Debug(_log, "_dmxStart %d, _dmxSlotsPerLed %d", _dmxStart, _dmxSlotsPerLed);
Debug(_log, "_ledCount %d, _dmxLedCount %d, _dmxChannelCount %d", _ledCount, _dmxLedCount, _dmxChannelCount);
_ledBuffer.resize(_dmxChannelCount, 0);
_ledBuffer[0] = 0x00; // NULL START code
return true;
}
LedDevice* LedDeviceDMX::construct(const QJsonObject &deviceConfig)
{
return new LedDeviceDMX(deviceConfig);
}
int LedDeviceDMX::write(const std::vector<ColorRgb> &ledValues)
{
switch (_dmxDeviceType) {
case 0:
memcpy(_ledBuffer.data()+1, ledValues.data(), _dmxChannelCount-1);
break;
case 1:
int l =_dmxStart;
for (int d=0; d<_dmxLedCount; d++)
{
_ledBuffer[l++] = ledValues[d].red;
_ledBuffer[l++] = ledValues[d].green;
_ledBuffer[l++] = ledValues[d].blue;
_ledBuffer[l++] = 255;
}
break;
}
_rs232Port.setBreakEnabled(true);
nanosleep((const struct timespec[]){{0, 176000L}}, NULL); // 176 uSec break time
_rs232Port.setBreakEnabled(false);
nanosleep((const struct timespec[]){{0, 12000L}}, NULL); // 176 uSec make after break time
#undef uberdebug
#ifdef uberdebug
printf ("Writing %d bytes", _dmxChannelCount);
for (unsigned int i=0; i < _dmxChannelCount; i++)
{
if (i%32 == 0) {
printf ("\n%04x: ", i);
}
printf ("%02x ", _ledBuffer[i]);
}
printf ("\n");
#endif
return writeBytes(_dmxChannelCount, _ledBuffer.data());
}

View File

@@ -0,0 +1,37 @@
#pragma once
// hyperion incluse
#include "ProviderRs232.h"
///
/// Implementation of the LedDevice interface for writing to DMX512 rs232 led device.
///
class LedDeviceDMX : public ProviderRs232
{
public:
///
/// Constructs specific LedDevice
///
/// @param deviceConfig json device config
///
LedDeviceDMX(const QJsonObject &deviceConfig);
/// constructs leddevice
static LedDevice* construct(const QJsonObject &deviceConfig);
virtual bool init(const QJsonObject &deviceConfig);
private:
///
/// Writes the led color values to the led-device
///
/// @param ledValues The color-value per led
/// @return Zero on succes else negative
///
virtual int write(const std::vector<ColorRgb> &ledValues);
int _dmxDeviceType = 0;
int _dmxStart = 1;
int _dmxSlotsPerLed = 3;
int _dmxLedCount = 0;
unsigned int _dmxChannelCount = 0;
};

View File

@@ -0,0 +1,52 @@
#include "LedDeviceSedu.h"
struct FrameSpec
{
uint8_t id;
size_t size;
};
LedDeviceSedu::LedDeviceSedu(const QJsonObject &deviceConfig)
: ProviderRs232()
{
_deviceReady = init(deviceConfig);
}
LedDevice* LedDeviceSedu::construct(const QJsonObject &deviceConfig)
{
return new LedDeviceSedu(deviceConfig);
}
bool LedDeviceSedu::init(const QJsonObject &deviceConfig)
{
ProviderRs232::init(deviceConfig);
std::vector<FrameSpec> frameSpecs{{0xA1, 256}, {0xA2, 512}, {0xB0, 768}, {0xB1, 1536}, {0xB2, 3072} };
for (const FrameSpec& frameSpec : frameSpecs)
{
if ((unsigned)_ledRGBCount <= frameSpec.size)
{
_ledBuffer.clear();
_ledBuffer.resize(frameSpec.size + 3, 0);
_ledBuffer[0] = 0x5A;
_ledBuffer[1] = frameSpec.id;
_ledBuffer.back() = 0xA5;
break;
}
}
if (_ledBuffer.size() == 0)
{
Warning(_log, "More rgb-channels required then available");
return false;
}
return true;
}
int LedDeviceSedu::write(const std::vector<ColorRgb> &ledValues)
{
memcpy(_ledBuffer.data()+2, ledValues.data(), ledValues.size() * sizeof(ColorRgb));
return writeBytes(_ledBuffer.size(), _ledBuffer.data());
}

View File

@@ -0,0 +1,32 @@
#pragma once
// hyperion incluse
#include "ProviderRs232.h"
///
/// Implementation of the LedDevice interface for writing to SEDU led device.
///
class LedDeviceSedu : public ProviderRs232
{
public:
///
/// Constructs specific LedDevice
///
/// @param deviceConfig json device config
///
LedDeviceSedu(const QJsonObject &deviceConfig);
/// constructs leddevice
static LedDevice* construct(const QJsonObject &deviceConfig);
virtual bool init(const QJsonObject &deviceConfig);
private:
///
/// Writes the led color values to the led-device
///
/// @param ledValues The color-value per led
/// @return Zero on succes else negative
///
virtual int write(const std::vector<ColorRgb> &ledValues);
};

View File

@@ -0,0 +1,33 @@
#include "LedDeviceTpm2.h"
LedDeviceTpm2::LedDeviceTpm2(const QJsonObject &deviceConfig)
: ProviderRs232()
{
_deviceReady = init(deviceConfig);
}
LedDevice* LedDeviceTpm2::construct(const QJsonObject &deviceConfig)
{
return new LedDeviceTpm2(deviceConfig);
}
bool LedDeviceTpm2::init(const QJsonObject &deviceConfig)
{
ProviderRs232::init(deviceConfig);
_ledBuffer.resize(5 + _ledRGBCount);
_ledBuffer[0] = 0xC9; // block-start byte
_ledBuffer[1] = 0xDA; // DATA frame
_ledBuffer[2] = (_ledRGBCount >> 8) & 0xFF; // frame size high byte
_ledBuffer[3] = _ledRGBCount & 0xFF; // frame size low byte
_ledBuffer.back() = 0x36; // block-end byte
return true;
}
int LedDeviceTpm2::write(const std::vector<ColorRgb> &ledValues)
{
memcpy(4 + _ledBuffer.data(), ledValues.data(), _ledRGBCount);
return writeBytes(_ledBuffer.size(), _ledBuffer.data());
}

View File

@@ -0,0 +1,32 @@
#pragma once
// hyperion incluse
#include "ProviderRs232.h"
///
/// Implementation of the LedDevice interface for writing to serial device using tpm2 protocol.
///
class LedDeviceTpm2 : public ProviderRs232
{
public:
///
/// Constructs specific LedDevice
///
/// @param deviceConfig json device config
///
LedDeviceTpm2(const QJsonObject &deviceConfig);
/// constructs leddevice
static LedDevice* construct(const QJsonObject &deviceConfig);
virtual bool init(const QJsonObject &deviceConfig);
private:
///
/// Writes the led color values to the led-device
///
/// @param ledValues The color-value per led
/// @return Zero on succes else negative
///
virtual int write(const std::vector<ColorRgb> &ledValues);
};

View File

@@ -0,0 +1,247 @@
// STL includes
#include <cstring>
#include <iostream>
// Qt includes
#include <QTimer>
#include <QDateTime>
#include <QFile>
#include <QSerialPortInfo>
// Local Hyperion includes
#include "ProviderRs232.h"
ProviderRs232::ProviderRs232()
: _rs232Port(this)
, _blockedForDelay(false)
, _stateChanged(true)
, _bytesToWrite(0)
, _bytesWritten(0)
, _frameDropCounter(0)
, _lastError(QSerialPort::NoError)
, _preOpenDelayTimeOut(0)
, _preOpenDelay(2000)
, _enableAutoDeviceName(false)
{
connect(&_rs232Port, SIGNAL(error(QSerialPort::SerialPortError)), this, SLOT(error(QSerialPort::SerialPortError)));
connect(&_rs232Port, SIGNAL(bytesWritten(qint64)), this, SLOT(bytesWritten(qint64)));
connect(&_rs232Port, SIGNAL(readyRead()), this, SLOT(readyRead()));
}
bool ProviderRs232::init(const QJsonObject &deviceConfig)
{
closeDevice();
LedDevice::init(deviceConfig);
_deviceName = deviceConfig["output"].toString("auto");
_enableAutoDeviceName = _deviceName == "auto";
_baudRate_Hz = deviceConfig["rate"].toInt();
_delayAfterConnect_ms = deviceConfig["delayAfterConnect"].toInt(1500);
_preOpenDelay = deviceConfig["delayBeforeConnect"].toInt(1500);
return true;
}
QString ProviderRs232::findSerialDevice()
{
// take first available usb serial port - currently no probing!
for( auto port : QSerialPortInfo::availablePorts())
{
if (port.hasProductIdentifier() && port.hasVendorIdentifier() && !port.isBusy())
{
Info(_log, "found serial device: %s", port.systemLocation().toLocal8Bit().constData());
return port.systemLocation();
break;
}
}
return "";
}
void ProviderRs232::bytesWritten(qint64 bytes)
{
_bytesWritten += bytes;
if (_bytesWritten >= _bytesToWrite)
{
_bytesToWrite = 0;
_blockedForDelay = false;
}
}
void ProviderRs232::readyRead()
{
emit receivedData(_rs232Port.readAll());
//Debug(_log, "received data");
}
void ProviderRs232::error(QSerialPort::SerialPortError error)
{
if ( error != QSerialPort::NoError )
{
if (_lastError != error)
{
_lastError = error;
switch (error)
{
case QSerialPort::DeviceNotFoundError:
Error(_log, "An error occurred while attempting to open an non-existing device."); break;
case QSerialPort::PermissionError:
Error(_log, "An error occurred while attempting to open an already opened device by another process or a user not having enough permission and credentials to open. Device disabled.");
_deviceReady = false;
break;
case QSerialPort::OpenError:
Error(_log, "An error occurred while attempting to open an already opened device in this object."); break;
case QSerialPort::NotOpenError:
Error(_log, "This error occurs when an operation is executed that can only be successfully performed if the device is open."); break;
case QSerialPort::ParityError:
Error(_log, "Parity error detected by the hardware while reading data."); break;
case QSerialPort::FramingError:
Error(_log, "Framing error detected by the hardware while reading data."); break;
case QSerialPort::BreakConditionError:
Error(_log, "Break condition detected by the hardware on the input line."); break;
case QSerialPort::WriteError:
Error(_log, "An I/O error occurred while writing the data."); break;
case QSerialPort::ReadError:
Error(_log, "An I/O error occurred while reading the data."); break;
case QSerialPort::ResourceError:
Error(_log, "An I/O error occurred when a resource becomes unavailable, e.g. when the device is unexpectedly removed from the system."); break;
case QSerialPort::UnsupportedOperationError:
Error(_log, "The requested device operation is not supported or prohibited by the running operating system. Device disabled.");
_deviceReady = false;
break;
case QSerialPort::TimeoutError:
Error(_log, "A timeout error occurred."); break;
default:
Error(_log,"An unidentified error occurred. Device disabled. (%d)", error);
_deviceReady = false;
}
_rs232Port.clearError();
closeDevice();
}
}
}
ProviderRs232::~ProviderRs232()
{
disconnect(&_rs232Port, SIGNAL(error(QSerialPort::SerialPortError)), this, SLOT(error(QSerialPort::SerialPortError)));
closeDevice();
}
void ProviderRs232::closeDevice()
{
if (_rs232Port.isOpen())
{
_rs232Port.close();
Debug(_log,"Close UART: %s", _deviceName.toLocal8Bit().constData());
}
}
int ProviderRs232::open()
{
return tryOpen(_delayAfterConnect_ms) ? 0 : -1;
}
bool ProviderRs232::tryOpen(const int delayAfterConnect_ms)
{
if (_deviceName.isEmpty() || _rs232Port.portName().isEmpty())
{
if ( _enableAutoDeviceName )
{
_deviceName = findSerialDevice();
if ( _deviceName.isEmpty() )
{
return false;
}
}
Info(_log, "Opening UART: %s", _deviceName.toLocal8Bit().constData());
_rs232Port.setPortName(_deviceName);
}
if ( ! _rs232Port.isOpen() )
{
_frameDropCounter = 0;
if (QFile::exists(_deviceName))
{
if ( _preOpenDelayTimeOut > QDateTime::currentMSecsSinceEpoch() )
{
return false;
}
if ( ! _rs232Port.open(QIODevice::ReadWrite) )
{
if ( _stateChanged )
{
Error(_log, "Unable to open RS232 device (%s)", _deviceName.toLocal8Bit().constData());
_stateChanged = false;
}
return false;
}
Debug(_log, "Setting baud rate to %d", _baudRate_Hz);
_rs232Port.setBaudRate(_baudRate_Hz);
_stateChanged = true;
_preOpenDelayTimeOut = 0;
}
else
{
_preOpenDelayTimeOut = QDateTime::currentMSecsSinceEpoch() + _preOpenDelay;
return false;
}
}
if (delayAfterConnect_ms > 0)
{
_blockedForDelay = true;
QTimer::singleShot(delayAfterConnect_ms, this, SLOT(unblockAfterDelay()));
Debug(_log, "Device blocked for %d ms", delayAfterConnect_ms);
}
return _rs232Port.isOpen();
}
int ProviderRs232::writeBytes(const qint64 size, const uint8_t * data)
{
if (! _blockedForDelay)
{
if (!_rs232Port.isOpen())
{
return tryOpen(5000) ? 0 : -1;
}
if (_frameDropCounter > 5)
{
Debug(_log, "%d frames dropped", _frameDropCounter);
}
_frameDropCounter = 0;
_blockedForDelay = true;
_bytesToWrite = size;
qint64 bytesWritten = _rs232Port.write(reinterpret_cast<const char*>(data), size);
if (bytesWritten == -1 || bytesWritten != size)
{
Warning(_log,"failed writing data");
QTimer::singleShot(500, this, SLOT(unblockAfterDelay()));
return -1;
}
QTimer::singleShot(5000, this, SLOT(unblockAfterDelay()));
}
else
{
_frameDropCounter++;
}
return 0;
}
void ProviderRs232::unblockAfterDelay()
{
_blockedForDelay = false;
}
int ProviderRs232::rewriteLeds()
{
return writeBytes(_ledBuffer.size(), _ledBuffer.data());
}

View File

@@ -0,0 +1,98 @@
#pragma once
#include <QObject>
#include <QSerialPort>
#include <QTimer>
#include <QString>
// Leddevice includes
#include <leddevice/LedDevice.h>
///
/// The ProviderRs232 implements an abstract base-class for LedDevices using a RS232-device.
///
class ProviderRs232 : public LedDevice
{
Q_OBJECT
public:
///
/// Constructs specific LedDevice
///
ProviderRs232();
///
/// Sets configuration
///
/// @param deviceConfig the json device config
/// @return true if success
virtual bool init(const QJsonObject &deviceConfig);
///
/// Destructor of the LedDevice; closes the output device if it is open
///
virtual ~ProviderRs232();
///
/// Opens and configures the output device
///
/// @return Zero on succes else negative
///
int open();
private slots:
/// Write the last data to the leds again
int rewriteLeds();
/// Unblock the device after a connection delay
void unblockAfterDelay();
void error(QSerialPort::SerialPortError error);
void bytesWritten(qint64 bytes);
void readyRead();
signals:
void receivedData(QByteArray data);
protected:
/**
* Writes the given bytes to the RS232-device and
*
* @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);
void closeDevice();
QString findSerialDevice();
// tries to open device if not opened
bool tryOpen(const int delayAfterConnect_ms);
/// The name of the output device
QString _deviceName;
/// The used baudrate of the output device
qint32 _baudRate_Hz;
/// Sleep after the connect before continuing
int _delayAfterConnect_ms;
/// The RS232 serial-device
QSerialPort _rs232Port;
bool _blockedForDelay;
bool _stateChanged;
qint64 _bytesToWrite;
qint64 _bytesWritten;
qint64 _frameDropCounter;
QSerialPort::SerialPortError _lastError;
qint64 _preOpenDelayTimeOut;
int _preOpenDelay;
bool _enableAutoDeviceName;
};