leddevice refactoring. code style and extension of baseclass to avoid dups (#174)

This commit is contained in:
redPanther 2016-08-14 10:46:44 +02:00 committed by GitHub
parent bc0c9c469f
commit 97181fa83c
63 changed files with 483 additions and 533 deletions

View File

@ -3,6 +3,8 @@
// STL incldues
#include <vector>
#include <QObject>
// Utility includes
#include <utils/ColorRgb.h>
#include <utils/ColorRgbw.h>
@ -12,8 +14,10 @@
///
/// Interface (pure virtual base class) for LedDevices.
///
class LedDevice
class LedDevice : public QObject
{
Q_OBJECT
public:
LedDevice();
///
@ -41,5 +45,12 @@ public:
virtual int open();
protected:
/// The common Logger instance for all LedDevices
Logger * _log;
int _ledCount;
/// The buffer containing the packed RGB values
std::vector<uint8_t> _ledBuffer;
};

View File

@ -6,8 +6,7 @@
using namespace hyperion;
LinearColorSmoothing::LinearColorSmoothing( LedDevice * ledDevice, double ledUpdateFrequency_hz, int settlingTime_ms, unsigned updateDelay, bool continuousOutput)
: QObject()
, LedDevice()
: LedDevice()
, _ledDevice(ledDevice)
, _updateInterval(1000 / ledUpdateFrequency_hz)
, _settlingTime(settlingTime_ms)

View File

@ -15,7 +15,7 @@
///
/// This class processes the requested led values and forwards them to the device after applying
/// a linear smoothing effect. This class can be handled as a generic LedDevice.
class LinearColorSmoothing : public QObject, public LedDevice
class LinearColorSmoothing : public LedDevice
{
Q_OBJECT

View File

@ -14,6 +14,7 @@ include_directories(
# Group the headers that go through the MOC compiler
SET(Leddevice_QT_HEADERS
${CURRENT_HEADER_DIR}/LedDevice.h
${CURRENT_SOURCE_DIR}/LedRs232Device.h
${CURRENT_SOURCE_DIR}/LedDeviceAdalight.h
${CURRENT_SOURCE_DIR}/LedDeviceAdalightApa102.h
@ -25,7 +26,6 @@ SET(Leddevice_QT_HEADERS
)
SET(Leddevice_HEADERS
${CURRENT_HEADER_DIR}/LedDevice.h
${CURRENT_HEADER_DIR}/LedDeviceFactory.h
${CURRENT_SOURCE_DIR}/LedDeviceLightpack.h

View File

@ -1,7 +1,11 @@
#include <leddevice/LedDevice.h>
LedDevice::LedDevice()
: _log(Logger::getInstance("LedDevice"))
: QObject()
, _log(Logger::getInstance("LedDevice"))
, _ledCount(0)
, _ledBuffer(0)
{
}

View File

@ -14,16 +14,15 @@
LedDeviceAPA102::LedDeviceAPA102(const std::string& outputDevice, const unsigned baudrate)
: LedSpiDevice(outputDevice, baudrate, 500000)
, _ledBuffer(0)
{
}
int LedDeviceAPA102::write(const std::vector<ColorRgb> &ledValues)
{
_mLedCount = ledValues.size();
_ledCount = ledValues.size();
const unsigned int startFrameSize = 4;
const unsigned int endFrameSize = std::max<unsigned int>(((_mLedCount + 15) / 16), 4);
const unsigned int APAbufferSize = (_mLedCount * 4) + startFrameSize + endFrameSize;
const unsigned int endFrameSize = std::max<unsigned int>(((_ledCount + 15) / 16), 4);
const unsigned int APAbufferSize = (_ledCount * 4) + startFrameSize + endFrameSize;
if(_ledBuffer.size() != APAbufferSize){
_ledBuffer.resize(APAbufferSize, 0xFF);
@ -33,7 +32,7 @@ int LedDeviceAPA102::write(const std::vector<ColorRgb> &ledValues)
_ledBuffer[3] = 0x00;
}
for (unsigned iLed=0; iLed < _mLedCount; ++iLed) {
for (signed iLed=0; iLed < _ledCount; ++iLed) {
const ColorRgb& rgb = ledValues[iLed];
_ledBuffer[4+iLed*4] = 0xFF;
_ledBuffer[4+iLed*4+1] = rgb.red;
@ -46,5 +45,5 @@ int LedDeviceAPA102::write(const std::vector<ColorRgb> &ledValues)
int LedDeviceAPA102::switchOff()
{
return write(std::vector<ColorRgb>(_mLedCount, ColorRgb{0,0,0}));
return write(std::vector<ColorRgb>(_ledCount, ColorRgb{0,0,0}));
}

View File

@ -33,11 +33,4 @@ public:
/// Switch the leds off
virtual int switchOff();
private:
/// The buffer containing the packed RGB values
std::vector<uint8_t> _ledBuffer;
unsigned int _mLedCount;
};

View File

@ -11,10 +11,9 @@
// hyperion local includes
#include "LedDeviceAdalight.h"
LedDeviceAdalight::LedDeviceAdalight(const std::string& outputDevice, const unsigned baudrate, int delayAfterConnect_ms) :
LedRs232Device(outputDevice, baudrate, delayAfterConnect_ms),
_ledBuffer(0),
_timer()
LedDeviceAdalight::LedDeviceAdalight(const std::string& outputDevice, const unsigned baudrate, int delayAfterConnect_ms)
: LedRs232Device(outputDevice, baudrate, delayAfterConnect_ms)
, _timer()
{
// setup the timer
_timer.setSingleShot(false);

View File

@ -41,9 +41,6 @@ private slots:
void rewriteLeds();
protected:
/// The buffer containing the packed RGB values
std::vector<uint8_t> _ledBuffer;
/// Timer object which makes sure that led data is written at a minimum rate
/// The Adalight device will switch off when it does not receive data at least
/// every 15 seconds

View File

@ -11,28 +11,20 @@
// hyperion local includes
#include "LedDeviceAdalightApa102.h"
LedDeviceAdalightApa102::LedDeviceAdalightApa102(const std::string& outputDevice, const unsigned baudrate, int delayAfterConnect_ms) :
LedRs232Device(outputDevice, baudrate, delayAfterConnect_ms),
_ledBuffer(0),
_timer()
LedDeviceAdalightApa102::LedDeviceAdalightApa102(const std::string& outputDevice, const unsigned baudrate, int delayAfterConnect_ms)
: LedDeviceAdalight(outputDevice, baudrate, delayAfterConnect_ms)
{
// setup the timer
_timer.setSingleShot(false);
_timer.setInterval(5000);
connect(&_timer, SIGNAL(timeout()), this, SLOT(rewriteLeds()));
// start the timer
_timer.start();
}
//comparing to ws2801 adalight, the following changes were needed:
// 1- differnt data frame (4 bytes instead of 3)
// 2 - in order to accomodate point 1 above, number of leds sent to adalight is increased by 1/3rd
int LedDeviceAdalightApa102::write(const std::vector<ColorRgb> & ledValues)
{
ledCount = ledValues.size();
_ledCount = ledValues.size();
const unsigned int startFrameSize = 4;
const unsigned int endFrameSize = std::max<unsigned int>(((ledCount + 15) / 16), 4);
const unsigned int mLedCount = (ledCount * 4) + startFrameSize + endFrameSize;
const unsigned int endFrameSize = std::max<unsigned int>(((_ledCount + 15) / 16), 4);
const unsigned int mLedCount = (_ledCount * 4) + startFrameSize + endFrameSize;
if(_ledBuffer.size() != mLedCount+6){
_ledBuffer.resize(mLedCount+6, 0x00);
_ledBuffer[0] = 'A';
@ -43,7 +35,7 @@ int LedDeviceAdalightApa102::write(const std::vector<ColorRgb> & ledValues)
_ledBuffer[5] = _ledBuffer[3] ^ _ledBuffer[4] ^ 0x55; // Checksum
}
for (unsigned iLed=1; iLed<=ledCount; iLed++) {
for (signed iLed=1; iLed<=_ledCount; iLed++) {
const ColorRgb& rgb = ledValues[iLed-1];
_ledBuffer[iLed*4+6] = 0xFF;
_ledBuffer[iLed*4+1+6] = rgb.red;
@ -60,7 +52,7 @@ int LedDeviceAdalightApa102::write(const std::vector<ColorRgb> & ledValues)
int LedDeviceAdalightApa102::switchOff()
{
for (unsigned iLed=1; iLed<=ledCount; iLed++) {
for (signed iLed=1; iLed<=_ledCount; iLed++) {
_ledBuffer[iLed*4+6] = 0xFF;
_ledBuffer[iLed*4+1+6] = 0x00;
_ledBuffer[iLed*4+2+6] = 0x00;
@ -74,9 +66,3 @@ int LedDeviceAdalightApa102::switchOff()
return writeBytes(_ledBuffer.size(), _ledBuffer.data());
}
void LedDeviceAdalightApa102::rewriteLeds()
{
writeBytes(_ledBuffer.size(), _ledBuffer.data());
}

View File

@ -3,16 +3,13 @@
// STL includes
#include <string>
// Qt includes
#include <QTimer>
// hyperion incluse
#include "LedRs232Device.h"
// hyperion include
#include "LedDeviceAdalight.h"
///
/// Implementation of the LedDevice interface for writing to an Adalight led device for APA102.
///
class LedDeviceAdalightApa102 : public LedRs232Device
class LedDeviceAdalightApa102 : public LedDeviceAdalight
{
Q_OBJECT
@ -32,19 +29,7 @@ public:
/// @return Zero on succes else negative
///
virtual int write(const std::vector<ColorRgb> & ledValues);
/// Switch the leds off
virtual int switchOff();
private slots:
/// Write the last data to the leds again
void rewriteLeds();
private:
/// The buffer containing the packed RGB values
std::vector<uint8_t> _ledBuffer;
unsigned int ledCount;
/// Timer object which makes sure that led data is written at a minimum rate
/// The Adalight device will switch off when it does not receive data at least
/// every 15 seconds
QTimer _timer;
};

View File

@ -1,15 +1,10 @@
// STL includes
#include <cstring>
#include <iostream>
// hyperion local includes
#include "LedDeviceAtmo.h"
LedDeviceAtmo::LedDeviceAtmo(const std::string& outputDevice, const unsigned baudrate) :
LedRs232Device(outputDevice, baudrate),
_ledBuffer(4 + 5*3) // 4-byte header, 5 RGB values
LedDeviceAtmo::LedDeviceAtmo(const std::string& outputDevice, const unsigned baudrate)
: LedRs232Device(outputDevice, baudrate)
{
_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)

View File

@ -31,8 +31,4 @@ public:
/// Switch the leds off
virtual int switchOff();
private:
/// The buffer containing the packed RGB values
std::vector<uint8_t> _ledBuffer;
};

View File

@ -22,22 +22,30 @@ LedDeviceAtmoOrb::LedDeviceAtmoOrb(
int skipSmoothingDiff,
int port,
int numLeds,
std::vector<unsigned int> orbIds) :
multicastGroup(output.c_str()), useOrbSmoothing(useOrbSmoothing), transitiontime(transitiontime), skipSmoothingDiff(skipSmoothingDiff),
multiCastGroupPort(port), numLeds(numLeds), orbIds(orbIds)
std::vector<unsigned int> orbIds)
: LedDevice()
, _multicastGroup(output.c_str())
, _useOrbSmoothing(useOrbSmoothing)
, _transitiontime(transitiontime)
, _skipSmoothingDiff(skipSmoothingDiff)
, _multiCastGroupPort(port)
, _numLeds(numLeds)
, _orbIds(orbIds)
{
manager = new QNetworkAccessManager();
groupAddress = QHostAddress(multicastGroup);
_manager = new QNetworkAccessManager();
_groupAddress = QHostAddress(_multicastGroup);
udpSocket = new QUdpSocket(this);
udpSocket->bind(QHostAddress::Any, multiCastGroupPort, QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint);
_udpSocket = new QUdpSocket(this);
_udpSocket->bind(QHostAddress::Any, _multiCastGroupPort, QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint);
joinedMulticastgroup = udpSocket->joinMulticastGroup(groupAddress);
joinedMulticastgroup = _udpSocket->joinMulticastGroup(_groupAddress);
}
int LedDeviceAtmoOrb::write(const std::vector <ColorRgb> &ledValues) {
int LedDeviceAtmoOrb::write(const std::vector <ColorRgb> &ledValues)
{
// If not in multicast group return
if (!joinedMulticastgroup) {
if (!joinedMulticastgroup)
{
return 0;
}
@ -47,9 +55,9 @@ int LedDeviceAtmoOrb::write(const std::vector <ColorRgb> &ledValues) {
// 2 = use lamp smoothing and validate by Orb ID
// 4 = validate by Orb ID
// When setting useOrbSmoothing = true it's recommended to disable Hyperion's own smoothing as it will conflict (double smoothing)
// When setting _useOrbSmoothing = true it's recommended to disable Hyperion's own smoothing as it will conflict (double smoothing)
int commandType = 4;
if(useOrbSmoothing)
if(_useOrbSmoothing)
{
commandType = 2;
}
@ -58,27 +66,33 @@ int LedDeviceAtmoOrb::write(const std::vector <ColorRgb> &ledValues) {
// Start off with idx 1 as 0 is reserved for controlling all orbs at once
unsigned int idx = 1;
for (const ColorRgb &color : ledValues) {
for (const ColorRgb &color : ledValues)
{
// Retrieve last send colors
int lastRed = lastColorRedMap[idx];
int lastGreen = lastColorGreenMap[idx];
int lastBlue = lastColorBlueMap[idx];
// If color difference is higher than skipSmoothingDiff than we skip Orb smoothing (if enabled) and send it right away
if ((skipSmoothingDiff != 0 && useOrbSmoothing) && (abs(color.red - lastRed) >= skipSmoothingDiff || abs(color.blue - lastBlue) >= skipSmoothingDiff ||
abs(color.green - lastGreen) >= skipSmoothingDiff))
// If color difference is higher than _skipSmoothingDiff than we skip Orb smoothing (if enabled) and send it right away
if ((_skipSmoothingDiff != 0 && _useOrbSmoothing) && (abs(color.red - lastRed) >= _skipSmoothingDiff || abs(color.blue - lastBlue) >= _skipSmoothingDiff ||
abs(color.green - lastGreen) >= _skipSmoothingDiff))
{
// Skip Orb smoothing when using (command type 4)
for (unsigned int i = 0; i < orbIds.size(); i++) {
if (orbIds[i] == idx) {
for (unsigned int i = 0; i < _orbIds.size(); i++)
{
if (_orbIds[i] == idx)
{
setColor(idx, color, 4);
}
}
}
else {
else
{
// Send color
for (unsigned int i = 0; i < orbIds.size(); i++) {
if (orbIds[i] == idx) {
for (unsigned int i = 0; i < _orbIds.size(); i++)
{
if (_orbIds[i] == idx)
{
setColor(idx, color, commandType);
}
}
@ -96,9 +110,10 @@ int LedDeviceAtmoOrb::write(const std::vector <ColorRgb> &ledValues) {
return 0;
}
void LedDeviceAtmoOrb::setColor(unsigned int orbId, const ColorRgb &color, int commandType) {
void LedDeviceAtmoOrb::setColor(unsigned int orbId, const ColorRgb &color, int commandType)
{
QByteArray bytes;
bytes.resize(5 + numLeds * 3);
bytes.resize(5 + _numLeds * 3);
bytes.fill('\0');
// Command identifier: C0FFEE
@ -120,16 +135,17 @@ void LedDeviceAtmoOrb::setColor(unsigned int orbId, const ColorRgb &color, int c
sendCommand(bytes);
}
void LedDeviceAtmoOrb::sendCommand(const QByteArray &bytes) {
void LedDeviceAtmoOrb::sendCommand(const QByteArray &bytes)
{
QByteArray datagram = bytes;
udpSocket->writeDatagram(datagram.data(), datagram.size(),
groupAddress, multiCastGroupPort);
_udpSocket->writeDatagram(datagram.data(), datagram.size(), _groupAddress, _multiCastGroupPort);
}
int LedDeviceAtmoOrb::switchOff() {
for (unsigned int i = 0; i < orbIds.size(); i++) {
for (unsigned int i = 0; i < _orbIds.size(); i++)
{
QByteArray bytes;
bytes.resize(5 + numLeds * 3);
bytes.resize(5 + _numLeds * 3);
bytes.fill('\0');
// Command identifier: C0FFEE
@ -141,7 +157,7 @@ int LedDeviceAtmoOrb::switchOff() {
bytes[3] = 1;
// Orb ID
bytes[4] = orbIds[i];
bytes[4] = _orbIds[i];
// RED / GREEN / BLUE
bytes[5] = 0;
@ -153,6 +169,7 @@ int LedDeviceAtmoOrb::switchOff() {
return 0;
}
LedDeviceAtmoOrb::~LedDeviceAtmoOrb() {
delete manager;
LedDeviceAtmoOrb::~LedDeviceAtmoOrb()
{
delete _manager;
}

View File

@ -32,7 +32,8 @@ public:
*
* @author RickDB (github)
*/
class LedDeviceAtmoOrb : public QObject, public LedDevice {
class LedDeviceAtmoOrb : public LedDevice
{
Q_OBJECT
public:
// Last send color map
@ -47,17 +48,11 @@ public:
/// Constructs the device.
///
/// @param output is the multicast address of Orbs
///
/// @param transitiontime is optional and not used at the moment
///
/// @param useOrbSmoothing use Orbs own (external) smoothing algorithm (default: false)
///
/// @param skipSmoothingDiff minimal color (0-255) difference to override smoothing so that if current and previously received colors are higher than set dif we override smoothing
///
/// @param port is the multicast port.
///
/// @param numLeds is the total amount of leds per Orb
///
/// @param array containing orb ids
///
LedDeviceAtmoOrb(const std::string &output, bool useOrbSmoothing =
@ -73,7 +68,6 @@ public:
/// Sends the given led-color values to the Orbs
///
/// @param ledValues The color-value per led
///
/// @return Zero on success else negative
///
virtual int write(const std::vector <ColorRgb> &ledValues);
@ -82,43 +76,40 @@ public:
private:
/// QNetworkAccessManager object for sending requests.
QNetworkAccessManager *manager;
QNetworkAccessManager *_manager;
/// String containing multicast group IP address
QString multicastGroup;
QString _multicastGroup;
/// use Orbs own (external) smoothing algorithm
bool useOrbSmoothing;
bool _useOrbSmoothing;
/// Transition time between colors (not implemented)
int transitiontime;
int _transitiontime;
// Maximum allowed color difference, will skip Orb (external) smoothing once reached
int skipSmoothingDiff;
int _skipSmoothingDiff;
/// Multicast port to send data to
int multiCastGroupPort;
int _multiCastGroupPort;
/// Number of leds in Orb, used to determine buffer size
int numLeds;
int _numLeds;
/// QHostAddress object of multicast group IP address
QHostAddress groupAddress;
QHostAddress _groupAddress;
/// QUdpSocket object used to send data over
QUdpSocket *udpSocket;
QUdpSocket * _udpSocket;
/// Array of the orb ids.
std::vector<unsigned int> orbIds;
std::vector<unsigned int> _orbIds;
///
/// Set Orbcolor
///
/// @param orbId the orb id
///
/// @param color which color to set
///
///
/// @param commandType which type of command to send (off / smoothing / etc..)
///
void setColor(unsigned int orbId, const ColorRgb &color, int commandType);

View File

@ -7,6 +7,7 @@ static const unsigned OPC_HEADER_SIZE = 4; // OPC header size
LedDeviceFadeCandy::LedDeviceFadeCandy(const Json::Value &deviceConfig)
: LedDevice()
{
setConfig(deviceConfig);
_opc_data.resize( OPC_HEADER_SIZE );

View File

@ -13,7 +13,7 @@
/// Implementation of the LedDevice interface for sending to
/// fadecandy/opc-server via network by using the 'open pixel control' protocol.
///
class LedDeviceFadeCandy : public QObject, public LedDevice
class LedDeviceFadeCandy : public LedDevice
{
Q_OBJECT

View File

@ -2,8 +2,9 @@
// Local-Hyperion includes
#include "LedDeviceFile.h"
LedDeviceFile::LedDeviceFile(const std::string& output) :
_ofs(output.empty()?"/dev/null":output.c_str())
LedDeviceFile::LedDeviceFile(const std::string& output)
: LedDevice()
, _ofs( output.empty() ? "/dev/null" : output.c_str())
{
// empty
}

View File

@ -11,12 +11,11 @@ uint16_t LedDeviceHyperionUsbasp::_usbProductId = 0x05dc;
std::string LedDeviceHyperionUsbasp::_usbProductDescription = "Hyperion led controller";
LedDeviceHyperionUsbasp::LedDeviceHyperionUsbasp(uint8_t writeLedsCommand) :
LedDevice(),
_writeLedsCommand(writeLedsCommand),
_libusbContext(nullptr),
_deviceHandle(nullptr),
_ledCount(256)
LedDeviceHyperionUsbasp::LedDeviceHyperionUsbasp(uint8_t writeLedsCommand)
: LedDevice()
, _writeLedsCommand(writeLedsCommand)
, _libusbContext(nullptr)
, _deviceHandle(nullptr)
{
}

View File

@ -78,9 +78,6 @@ private:
/// libusb device handle
libusb_device_handle * _deviceHandle;
/// Number of leds
int _ledCount;
/// Usb device identifiers
static uint16_t _usbVendorId;
static uint16_t _usbProductId;

View File

@ -33,15 +33,14 @@ enum DATA_VERSION_INDEXES{
INDEX_FW_VER_MINOR
};
LedDeviceLightpackHidapi::LedDeviceLightpackHidapi() :
LedDevice(),
_deviceHandle(nullptr),
_serialNumber(""),
_firmwareVersion({-1,-1}),
_ledCount(-1),
_bitsPerChannel(-1),
_ledBuffer()
LedDeviceLightpackHidapi::LedDeviceLightpackHidapi()
: LedDevice()
, _deviceHandle(nullptr)
, _serialNumber("")
, _firmwareVersion({-1,-1})
, _bitsPerChannel(-1)
{
_ledCount = -1;
}
LedDeviceLightpackHidapi::~LedDeviceLightpackHidapi()

View File

@ -40,10 +40,9 @@ LedDeviceLightpack::LedDeviceLightpack(const std::string & serialNumber)
, _addressNumber(-1)
, _serialNumber(serialNumber)
, _firmwareVersion({-1,-1})
, _ledCount(-1)
, _bitsPerChannel(-1)
, _ledBuffer()
{
_ledCount = -1;
}
LedDeviceLightpack::~LedDeviceLightpack()

View File

@ -110,12 +110,6 @@ private:
/// firmware version of the device
Version _firmwareVersion;
/// the number of leds of the device
int _ledCount;
/// the number of bits per channel
int _bitsPerChannel;
/// buffer for led data
std::vector<uint8_t> _ledBuffer;
};

View File

@ -10,11 +10,9 @@
// hyperion local includes
#include "LedDeviceLpd6803.h"
LedDeviceLpd6803::LedDeviceLpd6803(const std::string& outputDevice, const unsigned baudrate) :
LedSpiDevice(outputDevice, baudrate),
_ledBuffer(0)
LedDeviceLpd6803::LedDeviceLpd6803(const std::string& outputDevice, const unsigned baudrate)
: LedSpiDevice(outputDevice, baudrate)
{
// empty
}
int LedDeviceLpd6803::write(const std::vector<ColorRgb> &ledValues)

View File

@ -35,8 +35,4 @@ public:
/// Switch the leds off
virtual int switchOff();
private:
/// The buffer containing the packed RGB values
std::vector<uint8_t> _ledBuffer;
};

View File

@ -10,9 +10,8 @@
// hyperion local includes
#include "LedDeviceLpd8806.h"
LedDeviceLpd8806::LedDeviceLpd8806(const std::string& outputDevice, const unsigned baudrate) :
LedSpiDevice(outputDevice, baudrate),
_ledBuffer(0)
LedDeviceLpd8806::LedDeviceLpd8806(const std::string& outputDevice, const unsigned baudrate)
: LedSpiDevice(outputDevice, baudrate)
{
// empty
}

View File

@ -96,8 +96,4 @@ public:
/// Switch the leds off
virtual int switchOff();
private:
/// The buffer containing the packed RGB values
std::vector<uint8_t> _ledBuffer;
};

View File

@ -17,9 +17,9 @@ bool compareLightpacks(LedDeviceLightpack * lhs, LedDeviceLightpack * rhs)
return lhs->getSerialNumber() < rhs->getSerialNumber();
}
LedDeviceMultiLightpack::LedDeviceMultiLightpack() :
LedDevice(),
_lightpacks()
LedDeviceMultiLightpack::LedDeviceMultiLightpack()
: LedDevice()
, _lightpacks()
{
}

View File

@ -11,22 +11,21 @@
// hyperion local includes
#include "LedDeviceP9813.h"
LedDeviceP9813::LedDeviceP9813(const std::string& outputDevice, const unsigned baudrate) :
LedSpiDevice(outputDevice, baudrate, 0),
_ledCount(0)
LedDeviceP9813::LedDeviceP9813(const std::string& outputDevice, const unsigned baudrate)
: LedSpiDevice(outputDevice, baudrate, 0)
{
// empty
}
int LedDeviceP9813::write(const std::vector<ColorRgb> &ledValues)
{
if (_ledCount != ledValues.size())
if (_ledCount != (signed)ledValues.size())
{
_ledBuf.resize(ledValues.size() * 4 + 8, 0x00);
_ledBuffer.resize(ledValues.size() * 4 + 8, 0x00);
_ledCount = ledValues.size();
}
uint8_t * dataPtr = _ledBuf.data();
uint8_t * dataPtr = _ledBuffer.data();
for (const ColorRgb & color : ledValues)
{
*dataPtr++ = calculateChecksum(color);
@ -35,7 +34,7 @@ int LedDeviceP9813::write(const std::vector<ColorRgb> &ledValues)
*dataPtr++ = color.red;
}
return writeBytes(_ledBuf.size(), _ledBuf.data());
return writeBytes(_ledBuffer.size(), _ledBuffer.data());
}
int LedDeviceP9813::switchOff()

View File

@ -18,8 +18,7 @@ public:
/// @param outputDevice The name of the output device (eg '/etc/SpiDev.0.0')
/// @param baudrate The used baudrate for writing to the output device
///
LedDeviceP9813(const std::string& outputDevice,
const unsigned baudrate);
LedDeviceP9813(const std::string& outputDevice, const unsigned baudrate);
///
/// Writes the led color values to the led-device
@ -33,13 +32,6 @@ public:
virtual int switchOff();
private:
/// the number of leds
size_t _ledCount;
/// Buffer for writing/written led data
std::vector<uint8_t> _ledBuf;
///
/// Calculates the required checksum for one led
///

View File

@ -3,9 +3,8 @@
#include "LedDevicePaintpack.h"
// Use out report HID device
LedDevicePaintpack::LedDevicePaintpack(const unsigned short VendorId, const unsigned short ProductId, int delayAfterConnect_ms) :
LedHIDDevice(VendorId, ProductId, delayAfterConnect_ms, false),
_ledBuffer(0)
LedDevicePaintpack::LedDevicePaintpack(const unsigned short VendorId, const unsigned short ProductId, int delayAfterConnect_ms)
: LedHIDDevice(VendorId, ProductId, delayAfterConnect_ms, false)
{
// empty
}

View File

@ -32,8 +32,4 @@ public:
/// @return Zero on success else negative
///
virtual int switchOff();
private:
/// buffer for led data
std::vector<uint8_t> _ledBuffer;
};

View File

@ -21,8 +21,10 @@ bool operator !=(CiColor p1, CiColor p2) {
return !(p1 == p2);
}
PhilipsHueLight::PhilipsHueLight(unsigned int id, QString originalState, QString modelId) :
id(id), originalState(originalState) {
PhilipsHueLight::PhilipsHueLight(unsigned int id, QString originalState, QString modelId)
: id(id)
, originalState(originalState)
{
// Hue system model ids (http://www.developers.meethue.com/documentation/supported-lights).
// Light strips, color iris, ...
const std::set<QString> GAMUT_A_MODEL_IDS = { "LLC001", "LLC005", "LLC006", "LLC007", "LLC010", "LLC011", "LLC012",
@ -32,19 +34,26 @@ PhilipsHueLight::PhilipsHueLight(unsigned int id, QString originalState, QString
// Hue Lightstrip plus, go ...
const std::set<QString> GAMUT_C_MODEL_IDS = { "LLC020", "LST002" };
// Find id in the sets and set the appropiate color space.
if (GAMUT_A_MODEL_IDS.find(modelId) != GAMUT_A_MODEL_IDS.end()) {
if (GAMUT_A_MODEL_IDS.find(modelId) != GAMUT_A_MODEL_IDS.end())
{
colorSpace.red = {0.703f, 0.296f};
colorSpace.green = {0.2151f, 0.7106f};
colorSpace.blue = {0.138f, 0.08f};
} else if (GAMUT_B_MODEL_IDS.find(modelId) != GAMUT_B_MODEL_IDS.end()) {
}
else if (GAMUT_B_MODEL_IDS.find(modelId) != GAMUT_B_MODEL_IDS.end())
{
colorSpace.red = {0.675f, 0.322f};
colorSpace.green = {0.4091f, 0.518f};
colorSpace.blue = {0.167f, 0.04f};
} else if (GAMUT_C_MODEL_IDS.find(modelId) != GAMUT_B_MODEL_IDS.end()) {
}
else if (GAMUT_C_MODEL_IDS.find(modelId) != GAMUT_B_MODEL_IDS.end())
{
colorSpace.red = {0.675f, 0.322f};
colorSpace.green = {0.2151f, 0.7106f};
colorSpace.blue = {0.167f, 0.04f};
} else {
}
else
{
colorSpace.red = {1.0f, 0.0f};
colorSpace.green = {0.0f, 1.0f};
colorSpace.blue = {0.0f, 0.0f};
@ -55,37 +64,45 @@ PhilipsHueLight::PhilipsHueLight(unsigned int id, QString originalState, QString
color = {black.x, black.y, black.bri};
}
float PhilipsHueLight::crossProduct(CiColor p1, CiColor p2) {
float PhilipsHueLight::crossProduct(CiColor p1, CiColor p2)
{
return p1.x * p2.y - p1.y * p2.x;
}
bool PhilipsHueLight::isPointInLampsReach(CiColor p) {
bool PhilipsHueLight::isPointInLampsReach(CiColor p)
{
CiColor v1 = { colorSpace.green.x - colorSpace.red.x, colorSpace.green.y - colorSpace.red.y };
CiColor v2 = { colorSpace.blue.x - colorSpace.red.x, colorSpace.blue.y - colorSpace.red.y };
CiColor q = { p.x - colorSpace.red.x, p.y - colorSpace.red.y };
float s = crossProduct(q, v2) / crossProduct(v1, v2);
float t = crossProduct(v1, q) / crossProduct(v1, v2);
if ((s >= 0.0f) && (t >= 0.0f) && (s + t <= 1.0f)) {
if ((s >= 0.0f) && (t >= 0.0f) && (s + t <= 1.0f))
{
return true;
}
return false;
}
CiColor PhilipsHueLight::getClosestPointToPoint(CiColor a, CiColor b, CiColor p) {
CiColor PhilipsHueLight::getClosestPointToPoint(CiColor a, CiColor b, CiColor p)
{
CiColor AP = { p.x - a.x, p.y - a.y };
CiColor AB = { b.x - a.x, b.y - a.y };
float ab2 = AB.x * AB.x + AB.y * AB.y;
float ap_ab = AP.x * AB.x + AP.y * AB.y;
float t = ap_ab / ab2;
if (t < 0.0f) {
if (t < 0.0f)
{
t = 0.0f;
} else if (t > 1.0f) {
}
else if (t > 1.0f)
{
t = 1.0f;
}
return {a.x + AB.x * t, a.y + AB.y * t};
}
float PhilipsHueLight::getDistanceBetweenTwoPoints(CiColor p1, CiColor p2) {
float PhilipsHueLight::getDistanceBetweenTwoPoints(CiColor p1, CiColor p2)
{
// Horizontal difference.
float dx = p1.x - p2.x;
// Vertical difference.
@ -94,7 +111,8 @@ float PhilipsHueLight::getDistanceBetweenTwoPoints(CiColor p1, CiColor p2) {
return sqrt(dx * dx + dy * dy);
}
CiColor PhilipsHueLight::rgbToCiColor(float red, float green, float blue) {
CiColor PhilipsHueLight::rgbToCiColor(float red, float green, float blue)
{
// Apply gamma correction.
float r = (red > 0.04045f) ? powf((red + 0.055f) / (1.0f + 0.055f), 2.4f) : (red / 12.92f);
float g = (green > 0.04045f) ? powf((green + 0.055f) / (1.0f + 0.055f), 2.4f) : (green / 12.92f);
@ -106,16 +124,19 @@ CiColor PhilipsHueLight::rgbToCiColor(float red, float green, float blue) {
// Convert to x,y space.
float cx = X / (X + Y + Z);
float cy = Y / (X + Y + Z);
if (std::isnan(cx)) {
if (std::isnan(cx))
{
cx = 0.0f;
}
if (std::isnan(cy)) {
if (std::isnan(cy))
{
cy = 0.0f;
}
// Brightness is simply Y in the XYZ space.
CiColor xy = { cx, cy, Y };
// Check if the given XY value is within the color reach of our lamps.
if (!isPointInLampsReach(xy)) {
if (!isPointInLampsReach(xy))
{
// It seems the color is out of reach let's find the closes color we can produce with our lamp and send this XY value out.
CiColor pAB = getClosestPointToPoint(colorSpace.red, colorSpace.green, xy);
CiColor pAC = getClosestPointToPoint(colorSpace.blue, colorSpace.red, xy);
@ -126,11 +147,13 @@ CiColor PhilipsHueLight::rgbToCiColor(float red, float green, float blue) {
float dBC = getDistanceBetweenTwoPoints(xy, pBC);
float lowest = dAB;
CiColor closestPoint = pAB;
if (dAC < lowest) {
if (dAC < lowest)
{
lowest = dAC;
closestPoint = pAC;
}
if (dBC < lowest) {
if (dBC < lowest)
{
lowest = dBC;
closestPoint = pBC;
}
@ -141,46 +164,58 @@ CiColor PhilipsHueLight::rgbToCiColor(float red, float green, float blue) {
return xy;
}
LedDevicePhilipsHue::LedDevicePhilipsHue(const std::string& output, const std::string& username, bool switchOffOnBlack,
int transitiontime, std::vector<unsigned int> lightIds) :
host(output.c_str()), username(username.c_str()), switchOffOnBlack(switchOffOnBlack), transitiontime(
transitiontime), lightIds(lightIds) {
LedDevicePhilipsHue::LedDevicePhilipsHue(const std::string& output, const std::string& username, bool switchOffOnBlack, int transitiontime, std::vector<unsigned int> lightIds)
: LedDevice()
, host(output.c_str())
, username(username.c_str())
, switchOffOnBlack(switchOffOnBlack)
, transitiontime(transitiontime)
, lightIds(lightIds)
{
manager = new QNetworkAccessManager();
timer.setInterval(3000);
timer.setSingleShot(true);
connect(&timer, SIGNAL(timeout()), this, SLOT(restoreStates()));
}
LedDevicePhilipsHue::~LedDevicePhilipsHue() {
LedDevicePhilipsHue::~LedDevicePhilipsHue()
{
delete manager;
}
int LedDevicePhilipsHue::write(const std::vector<ColorRgb> & ledValues) {
int LedDevicePhilipsHue::write(const std::vector<ColorRgb> & ledValues)
{
// Save light states if not done before.
if (!areStatesSaved()) {
if (!areStatesSaved())
{
saveStates((unsigned int) ledValues.size());
switchOn((unsigned int) ledValues.size());
}
// If there are less states saved than colors given, then maybe something went wrong before.
if (lights.size() != ledValues.size()) {
if (lights.size() != ledValues.size())
{
restoreStates();
return 0;
}
// Iterate through colors and set light states.
unsigned int idx = 0;
for (const ColorRgb& color : ledValues) {
for (const ColorRgb& color : ledValues)
{
// Get lamp.
PhilipsHueLight& lamp = lights.at(idx);
// Scale colors from [0, 255] to [0, 1] and convert to xy space.
CiColor xy = lamp.rgbToCiColor(color.red / 255.0f, color.green / 255.0f, color.blue / 255.0f);
// Write color if color has been changed.
if (xy != lamp.color) {
if (xy != lamp.color)
{
// From a color to black.
if (switchOffOnBlack && lamp.color != lamp.black && xy == lamp.black) {
if (switchOffOnBlack && lamp.color != lamp.black && xy == lamp.black)
{
put(getStateRoute(lamp.id), QString("{\"on\": false}"));
}
// From black to a color
else if (switchOffOnBlack && lamp.color == lamp.black && xy != lamp.black) {
else if (switchOffOnBlack && lamp.color == lamp.black && xy != lamp.black)
{
// Send adjust color and brightness command in JSON format.
// We have to set the transition time each time.
// Send also command to switch the lamp on.
@ -189,7 +224,8 @@ int LedDevicePhilipsHue::write(const std::vector<ColorRgb> & ledValues) {
xy.y).arg(qRound(xy.bri * 255.0f)).arg(transitiontime));
}
// Normal color change.
else {
else
{
// Send adjust color and brightness command in JSON format.
// We have to set the transition time each time.
put(getStateRoute(lamp.id),
@ -206,17 +242,20 @@ int LedDevicePhilipsHue::write(const std::vector<ColorRgb> & ledValues) {
return 0;
}
int LedDevicePhilipsHue::switchOff() {
int LedDevicePhilipsHue::switchOff()
{
timer.stop();
// If light states have been saved before, ...
if (areStatesSaved()) {
if (areStatesSaved())
{
// ... restore them.
restoreStates();
}
return 0;
}
void LedDevicePhilipsHue::put(QString route, QString content) {
void LedDevicePhilipsHue::put(QString route, QString content)
{
QString url = getUrl(route);
// Perfrom request
QNetworkRequest request(url);
@ -230,7 +269,8 @@ void LedDevicePhilipsHue::put(QString route, QString content) {
reply->deleteLater();
}
QByteArray LedDevicePhilipsHue::get(QString route) {
QByteArray LedDevicePhilipsHue::get(QString route)
{
QString url = getUrl(route);
// Perfrom request
QNetworkRequest request(url);
@ -248,67 +288,80 @@ QByteArray LedDevicePhilipsHue::get(QString route) {
return response;
}
QString LedDevicePhilipsHue::getStateRoute(unsigned int lightId) {
QString LedDevicePhilipsHue::getStateRoute(unsigned int lightId)
{
return QString("lights/%1/state").arg(lightId);
}
QString LedDevicePhilipsHue::getRoute(unsigned int lightId) {
QString LedDevicePhilipsHue::getRoute(unsigned int lightId)
{
return QString("lights/%1").arg(lightId);
}
QString LedDevicePhilipsHue::getUrl(QString route) {
QString LedDevicePhilipsHue::getUrl(QString route)
{
return QString("http://%1/api/%2/%3").arg(host).arg(username).arg(route);
}
void LedDevicePhilipsHue::saveStates(unsigned int nLights) {
void LedDevicePhilipsHue::saveStates(unsigned int nLights)
{
// Clear saved lamps.
lights.clear();
// Use json parser to parse reponse.
Json::Reader reader;
Json::FastWriter writer;
// Read light ids if none have been supplied by the user.
if (lightIds.size() != nLights) {
if (lightIds.size() != nLights)
{
lightIds.clear();
//
QByteArray response = get("lights");
Json::Value json;
if (!reader.parse(QString(response).toStdString(), json)) {
if (!reader.parse(QString(response).toStdString(), json))
{
throw std::runtime_error(("No lights found at " + getUrl("lights")).toStdString());
}
// Loop over all children.
for (Json::ValueIterator it = json.begin(); it != json.end() && lightIds.size() < nLights; it++) {
for (Json::ValueIterator it = json.begin(); it != json.end() && lightIds.size() < nLights; it++)
{
int lightId = atoi(it.key().asCString());
lightIds.push_back(lightId);
Debug(_log, "nLights=%d: found light with id %d.", nLights, lightId);
}
// Check if we found enough lights.
if (lightIds.size() != nLights) {
if (lightIds.size() != nLights)
{
throw std::runtime_error(("Not enough lights found at " + getUrl("lights")).toStdString());
}
}
// Iterate lights.
for (unsigned int i = 0; i < nLights; i++) {
for (unsigned int i = 0; i < nLights; i++)
{
// Read the response.
QByteArray response = get(getRoute(lightIds.at(i)));
// Parse JSON.
Json::Value json;
if (!reader.parse(QString(response).toStdString(), json)) {
if (!reader.parse(QString(response).toStdString(), json))
{
// Error occured, break loop.
Error(_log, "saveStates(nLights=%d): got invalid response from light %s.", nLights, getUrl(getRoute(lightIds.at(i))).toStdString().c_str());
break;
}
// Get state object values which are subject to change.
Json::Value state(Json::objectValue);
if (!json.isMember("state")) {
if (!json.isMember("state"))
{
Error(_log, "saveStates(nLights=%d): got no state for light from %s", nLights, getUrl(getRoute(lightIds.at(i))).toStdString().c_str());
break;
}
if (!json["state"].isMember("on")) {
if (!json["state"].isMember("on"))
{
Error(_log, "saveStates(nLights=%d,): got no valid state from light %s", nLights, getUrl(getRoute(lightIds.at(i))).toStdString().c_str());
break;
}
state["on"] = json["state"]["on"];
if (json["state"]["on"] == true) {
if (json["state"]["on"] == true)
{
state["xy"] = json["state"]["xy"];
state["bri"] = json["state"]["bri"];
}
@ -320,20 +373,25 @@ void LedDevicePhilipsHue::saveStates(unsigned int nLights) {
}
}
void LedDevicePhilipsHue::switchOn(unsigned int nLights) {
for (PhilipsHueLight light : lights) {
void LedDevicePhilipsHue::switchOn(unsigned int nLights)
{
for (PhilipsHueLight light : lights)
{
put(getStateRoute(light.id), "{\"on\": true}");
}
}
void LedDevicePhilipsHue::restoreStates() {
for (PhilipsHueLight light : lights) {
void LedDevicePhilipsHue::restoreStates()
{
for (PhilipsHueLight light : lights)
{
put(getStateRoute(light.id), light.originalState);
}
// Clear saved light states.
lights.clear();
}
bool LedDevicePhilipsHue::areStatesSaved() {
bool LedDevicePhilipsHue::areStatesSaved()
{
return !lights.empty();
}

View File

@ -60,9 +60,7 @@ public:
/// https://github.com/PhilipsHue/PhilipsHueSDK-iOS-OSX/blob/master/ApplicationDesignNotes/RGB%20to%20xy%20Color%20conversion.md
///
/// @param red the red component in [0, 1]
///
/// @param green the green component in [0, 1]
///
/// @param blue the blue component in [0, 1]
///
/// @return color point
@ -71,14 +69,12 @@ public:
///
/// @param p the color point to check
///
/// @return true if the color point is covered by the lamp color space
///
bool isPointInLampsReach(CiColor p);
///
/// @param p1 point one
///
/// @param p2 point tow
///
/// @return the cross product between p1 and p2
@ -87,9 +83,7 @@ public:
///
/// @param a reference point one
///
/// @param b reference point two
///
/// @param p the point to which the closest point is to be found
///
/// @return the closest color point of p to a and b
@ -98,7 +92,6 @@ public:
///
/// @param p1 point one
///
/// @param p2 point tow
///
/// @return the distance between the two points
@ -116,20 +109,18 @@ public:
*
* @author ntim (github), bimsarck (github)
*/
class LedDevicePhilipsHue: public QObject, public LedDevice {
class LedDevicePhilipsHue: public LedDevice {
Q_OBJECT
public:
///
/// Constructs the device.
///
/// @param output the ip address of the bridge
///
/// @param username username of the hue bridge (default: newdeveloper)
///
/// @param switchOffOnBlack kill lights for black (default: false)
///
/// @param transitiontime the time duration a light change takes in multiples of 100 ms (default: 400 ms).
///
/// @param lightIds light ids of the lights to control if not starting at one in ascending order.
///
LedDevicePhilipsHue(const std::string& output, const std::string& username = "newdeveloper", bool switchOffOnBlack =

View File

@ -12,10 +12,9 @@
#include "LedDeviceRawHID.h"
// Use feature report HID device
LedDeviceRawHID::LedDeviceRawHID(const unsigned short VendorId, const unsigned short ProductId, int delayAfterConnect_ms) :
LedHIDDevice(VendorId, ProductId, delayAfterConnect_ms, true),
_ledBuffer(0),
_timer()
LedDeviceRawHID::LedDeviceRawHID(const unsigned short VendorId, const unsigned short ProductId, int delayAfterConnect_ms)
: LedHIDDevice(VendorId, ProductId, delayAfterConnect_ms, true)
, _timer()
{
// setup the timer
_timer.setSingleShot(false);

View File

@ -38,9 +38,6 @@ private slots:
void rewriteLeds();
private:
/// The buffer containing the packed RGB values
std::vector<uint8_t> _ledBuffer;
/// Timer object which makes sure that led data is written at a minimum rate
/// The RawHID device will switch off when it does not receive data at least
/// every 15 seconds

View File

@ -17,9 +17,8 @@ struct FrameSpec
size_t size;
};
LedDeviceSedu::LedDeviceSedu(const std::string& outputDevice, const unsigned baudrate) :
LedRs232Device(outputDevice, baudrate),
_ledBuffer(0)
LedDeviceSedu::LedDeviceSedu(const std::string& outputDevice, const unsigned baudrate)
: LedRs232Device(outputDevice, baudrate)
{
// empty
}

View File

@ -30,8 +30,4 @@ public:
/// Switch the leds off
virtual int switchOff();
private:
/// The buffer containing the packed RGB values
std::vector<uint8_t> _ledBuffer;
};

View File

@ -14,7 +14,6 @@
LedDeviceSk6812SPI::LedDeviceSk6812SPI(const std::string& outputDevice, const unsigned baudrate, const std::string& whiteAlgorithm,
const int spiMode, const bool spiDataInvert)
: LedSpiDevice(outputDevice, baudrate, 0, spiMode, spiDataInvert)
, mLedCount(0)
, _whiteAlgorithm(whiteAlgorithm)
, bitpair_to_byte {
0b10001000,
@ -29,16 +28,16 @@ LedDeviceSk6812SPI::LedDeviceSk6812SPI(const std::string& outputDevice, const un
int LedDeviceSk6812SPI::write(const std::vector<ColorRgb> &ledValues)
{
mLedCount = ledValues.size();
_ledCount = ledValues.size();
// 4 colours, 4 spi bytes per colour + 3 frame end latch bytes
#define COLOURS_PER_LED 4
#define SPI_BYTES_PER_COLOUR 4
#define SPI_BYTES_PER_LED COLOURS_PER_LED * SPI_BYTES_PER_COLOUR
unsigned spi_size = mLedCount * SPI_BYTES_PER_LED + 3;
if(_spiBuffer.size() != spi_size){
_spiBuffer.resize(spi_size, 0x00);
unsigned spi_size = _ledCount * SPI_BYTES_PER_LED + 3;
if(_ledBuffer.size() != spi_size){
_ledBuffer.resize(spi_size, 0x00);
}
unsigned spi_ptr = 0;
@ -52,19 +51,19 @@ int LedDeviceSk6812SPI::write(const std::vector<ColorRgb> &ledValues)
_temp_rgbw.white;
for (int j=SPI_BYTES_PER_LED - 1; j>=0; j--) {
_spiBuffer[spi_ptr+j] = bitpair_to_byte[ colorBits & 0x3 ];
_ledBuffer[spi_ptr+j] = bitpair_to_byte[ colorBits & 0x3 ];
colorBits >>= 2;
}
spi_ptr += SPI_BYTES_PER_LED;
}
_spiBuffer[spi_ptr++] = 0;
_spiBuffer[spi_ptr++] = 0;
_spiBuffer[spi_ptr++] = 0;
_ledBuffer[spi_ptr++] = 0;
_ledBuffer[spi_ptr++] = 0;
_ledBuffer[spi_ptr++] = 0;
return writeBytes(spi_size, _spiBuffer.data());
return writeBytes(spi_size, _ledBuffer.data());
}
int LedDeviceSk6812SPI::switchOff()
{
return write(std::vector<ColorRgb>(mLedCount, ColorRgb{0,0,0}));
return write(std::vector<ColorRgb>(_ledCount, ColorRgb{0,0,0}));
}

View File

@ -20,8 +20,7 @@ public:
///
LedDeviceSk6812SPI(const std::string& outputDevice, const unsigned baudrate,
const std::string& whiteAlgorithm,
const int spiMode, const bool spiDataInvert);
const std::string& whiteAlgorithm, const int spiMode, const bool spiDataInvert);
///
/// Writes the led color values to the led-device
@ -35,12 +34,9 @@ public:
virtual int switchOff();
private:
/// the number of leds (needed when switching off)
size_t mLedCount;
std::vector<uint8_t> _spiBuffer;
std::string _whiteAlgorithm;
uint8_t bitpair_to_byte[4];
ColorRgbw _temp_rgbw;
};

View File

@ -9,15 +9,15 @@
static const unsigned MAX_NUM_LEDS = 320;
static const unsigned MAX_NUM_LEDS_SETTABLE = 16;
LedDeviceTinkerforge::LedDeviceTinkerforge(const std::string & host, uint16_t port, const std::string & uid, const unsigned interval) :
LedDevice(),
_host(host),
_port(port),
_uid(uid),
_interval(interval),
_ipConnection(nullptr),
_ledStrip(nullptr),
_colorChannelSize(0)
LedDeviceTinkerforge::LedDeviceTinkerforge(const std::string & host, uint16_t port, const std::string & uid, const unsigned interval)
: LedDevice()
, _host(host)
, _port(port)
, _uid(uid)
, _interval(interval)
, _ipConnection(nullptr)
, _ledStrip(nullptr)
, _colorChannelSize(0)
{
// empty
}

View File

@ -7,9 +7,8 @@
// hyperion local includes
#include "LedDeviceTpm2.h"
LedDeviceTpm2::LedDeviceTpm2(const std::string& outputDevice, const unsigned baudrate) :
LedRs232Device(outputDevice, baudrate),
_ledBuffer(0)
LedDeviceTpm2::LedDeviceTpm2(const std::string& outputDevice, const unsigned baudrate)
: LedRs232Device(outputDevice, baudrate)
{
// empty
}

View File

@ -31,8 +31,4 @@ public:
/// Switch the leds off
virtual int switchOff();
private:
/// The buffer containing the packed RGB values
std::vector<uint8_t> _ledBuffer;
};

View File

@ -1,6 +1,8 @@
// Local-Hyperion includes
#include "LedDeviceUdp.h"
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
@ -22,6 +24,7 @@ int update_number;
int fragment_number;
LedDeviceUdp::LedDeviceUdp(const std::string& output, const unsigned protocol, const unsigned maxPacket)
: LedDevice()
{
std::string hostname;
std::string port;
@ -79,6 +82,7 @@ LedDeviceUdp::~LedDeviceUdp()
int LedDeviceUdp::write(const std::vector<ColorRgb> & ledValues)
{
_ledCount = ledValues.size();
char udpbuffer[4096];
int udpPtr=0;
@ -86,11 +90,13 @@ int LedDeviceUdp::write(const std::vector<ColorRgb> & ledValues)
update_number++;
update_number &= 0xf;
if (ledprotocol == 0) {
if (ledprotocol == 0)
{
int i=0;
for (const ColorRgb& color : ledValues)
{
if (i<4090) {
if (i<4090)
{
udpbuffer[i++] = color.red;
udpbuffer[i++] = color.green;
udpbuffer[i++] = color.blue;
@ -98,30 +104,35 @@ int LedDeviceUdp::write(const std::vector<ColorRgb> & ledValues)
}
sendto(sockfd, udpbuffer, i, 0, p->ai_addr, p->ai_addrlen);
}
if (ledprotocol == 1) {
if (ledprotocol == 1)
{
#define MAXLEDperFRAG 450
int mLedCount = ledValues.size();
for (int frag=0; frag<4; frag++) {
for (int frag=0; frag<4; frag++)
{
udpPtr=0;
udpbuffer[udpPtr++] = 0;
udpbuffer[udpPtr++] = 0;
udpbuffer[udpPtr++] = (frag*MAXLEDperFRAG)/256; // high byte
udpbuffer[udpPtr++] = (frag*MAXLEDperFRAG)%256; // low byte
int ct=0;
for (int this_led = frag*300; ((this_led<mLedCount) && (ct++<MAXLEDperFRAG)); this_led++) {
for (int this_led = frag*300; ((this_led<_ledCount) && (ct++<MAXLEDperFRAG)); this_led++)
{
const ColorRgb& color = ledValues[this_led];
if (udpPtr<4090) {
if (udpPtr<4090)
{
udpbuffer[udpPtr++] = color.red;
udpbuffer[udpPtr++] = color.green;
udpbuffer[udpPtr++] = color.blue;
}
}
if (udpPtr > 7)
{
sendto(sockfd, udpbuffer, udpPtr, 0, p->ai_addr, p->ai_addrlen);
}
}
if (ledprotocol == 2) {
}
if (ledprotocol == 2)
{
udpPtr = 0;
unsigned int ledCtr = 0;
fragment_number = 0;
@ -150,7 +161,8 @@ int LedDeviceUdp::write(const std::vector<ColorRgb> & ledValues)
}
}
if (ledprotocol == 3) {
if (ledprotocol == 3)
{
udpPtr = 0;
unsigned int ledCtr = 0;
unsigned int fragments = 1;
@ -168,13 +180,15 @@ int LedDeviceUdp::write(const std::vector<ColorRgb> & ledValues)
for (const ColorRgb& color : ledValues)
{
if (udpPtr<4090) {
if (udpPtr<4090)
{
udpbuffer[udpPtr++] = color.red;
udpbuffer[udpPtr++] = color.green;
udpbuffer[udpPtr++] = color.blue;
}
ledCtr++;
if ( (ledCtr % leds_per_pkt == 0) || (ledCtr == ledValues.size()) ) {
if ( (ledCtr % leds_per_pkt == 0) || (ledCtr == ledValues.size()) )
{
udpbuffer[udpPtr++] = 0x36;
sendto(sockfd, udpbuffer, udpPtr, 0, p->ai_addr, p->ai_addrlen);
memset(udpbuffer, 0, sizeof udpbuffer);
@ -194,6 +208,6 @@ int LedDeviceUdp::write(const std::vector<ColorRgb> & ledValues)
int LedDeviceUdp::switchOff()
{
// return write(std::vector<ColorRgb>(mLedCount, ColorRgb{0,0,0}));
// return write(std::vector<ColorRgb>(_ledCount, ColorRgb{0,0,0}));
return 0;
}

View File

@ -1,8 +1,5 @@
#pragma once
// STL includes0
#include <fstream>
// Leddevice includes
#include <leddevice/LedDevice.h>
@ -35,7 +32,4 @@ public:
/// Switch the leds off
virtual int switchOff();
private:
/// the number of leds (needed when switching off)
size_t mLedCount;
};

View File

@ -11,18 +11,17 @@
// hyperion local includes
#include "LedDeviceUdpRaw.h"
LedDeviceUdpRaw::LedDeviceUdpRaw(const std::string& outputDevice, const unsigned latchTime) :
LedUdpDevice(outputDevice, latchTime),
mLedCount(0)
LedDeviceUdpRaw::LedDeviceUdpRaw(const std::string& outputDevice, const unsigned latchTime)
: LedUdpDevice(outputDevice, latchTime)
{
// empty
}
int LedDeviceUdpRaw::write(const std::vector<ColorRgb> &ledValues)
{
mLedCount = ledValues.size();
_ledCount = ledValues.size();
const unsigned dataLen = ledValues.size() * sizeof(ColorRgb);
const unsigned dataLen = _ledCount * sizeof(ColorRgb);
const uint8_t * dataPtr = reinterpret_cast<const uint8_t *>(ledValues.data());
return writeBytes(dataLen, dataPtr);
@ -30,5 +29,5 @@ int LedDeviceUdpRaw::write(const std::vector<ColorRgb> &ledValues)
int LedDeviceUdpRaw::switchOff()
{
return write(std::vector<ColorRgb>(mLedCount, ColorRgb{0,0,0}));
return write(std::vector<ColorRgb>(_ledCount, ColorRgb{0,0,0}));
}

View File

@ -31,9 +31,4 @@ public:
/// Switch the leds off
virtual int switchOff();
private:
/// the number of leds (needed when switching off)
size_t mLedCount;
};

View File

@ -232,17 +232,13 @@
LedDeviceWS2812b::LedDeviceWS2812b() :
LedDevice(),
mLedCount(0)
LedDeviceWS2812b::LedDeviceWS2812b()
: LedDevice()
#ifdef BENCHMARK
,
runCount(0),
combinedNseconds(0),
shortestNseconds(2147483647)
, runCount(0)
, combinedNseconds(0)
, shortestNseconds(2147483647)
#endif
{
//shortestNseconds = 2147483647;
// Init PWM generator and clear LED buffer
@ -306,7 +302,7 @@ int LedDeviceWS2812b::write(const std::vector<ColorRgb> &ledValues)
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &timeStart);
#endif
mLedCount = ledValues.size();
_ledCount = ledValues.size();
// Read data from LEDBuffer[], translate it into wire format, and write to PWMWaveform
unsigned int colorBits = 0; // Holds the GRB color before conversion to wire bit pattern
@ -319,11 +315,11 @@ int LedDeviceWS2812b::write(const std::vector<ColorRgb> &ledValues)
// 72 bits per pixel / 32 bits per word = 2.25 words per pixel
// Add 1 to make sure the PWM FIFO gets the message: "we're sending zeroes"
// Times 4 because DMA works in bytes, not words
cbp->length = ((mLedCount * 2.25) + 1) * 4;
cbp->length = ((_ledCount * 2.25) + 1) * 4;
if(cbp->length > NUM_DATA_WORDS * 4)
{
cbp->length = NUM_DATA_WORDS * 4;
mLedCount = (NUM_DATA_WORDS - 1) / 2.25;
_ledCount = (NUM_DATA_WORDS - 1) / 2.25;
}
#ifdef WS2812_ASM_OPTI
@ -331,7 +327,7 @@ int LedDeviceWS2812b::write(const std::vector<ColorRgb> &ledValues)
#endif
for(size_t i=0; i<mLedCount; i++)
for(size_t i=0; i<_ledCount; i++)
{
// Create bits necessary to represent one color triplet (in GRB, not RGB, order)
colorBits = ((unsigned int)ledValues[i].red << 8) | ((unsigned int)ledValues[i].green << 16) | ledValues[i].blue;
@ -375,7 +371,7 @@ int LedDeviceWS2812b::write(const std::vector<ColorRgb> &ledValues)
#ifdef WS2812_ASM_OPTI
// calculate the bits manually since it is not needed with asm
//wireBit += mLedCount * 24 *3;
//wireBit += _ledCount * 24 *3;
#endif
//remove one to undo optimization
wireBit --;
@ -455,7 +451,7 @@ int LedDeviceWS2812b::write(const std::vector<ColorRgb> &ledValues)
int LedDeviceWS2812b::switchOff()
{
return write(std::vector<ColorRgb>(mLedCount, ColorRgb{0,0,0}));
return write(std::vector<ColorRgb>(_ledCount, ColorRgb{0,0,0}));
}
LedDeviceWS2812b::~LedDeviceWS2812b()
@ -746,7 +742,7 @@ void LedDeviceWS2812b::initHardware()
// 72 bits per pixel / 32 bits per word = 2.25 words per pixel
// Add 1 to make sure the PWM FIFO gets the message: "we're sending zeroes"
// Times 4 because DMA works in bytes, not words
cbp->length = ((mLedCount * 2.25) + 1) * 4;
cbp->length = ((_ledCount * 2.25) + 1) * 4;
if(cbp->length > NUM_DATA_WORDS * 4)
{
cbp->length = NUM_DATA_WORDS * 4;

View File

@ -149,10 +149,6 @@ public:
virtual int switchOff();
private:
/// the number of leds (needed when switching off)
size_t mLedCount;
page_map_t *page_map; // This will hold the page map, which we'll allocate
uint8_t *virtbase; // Pointer to some virtual memory that will be allocated

View File

@ -1,75 +1,75 @@
#include <iostream>
#include <exception>
#include "LedDeviceWS281x.h"
// Constructor
LedDeviceWS281x::LedDeviceWS281x(const int gpio, const int leds, const uint32_t freq, const int dmanum, const int pwmchannel, const int invert, const int rgbw, const std::string& whiteAlgorithm)
: LedDevice()
, _channel(pwmchannel)
, _initialized(false)
, _whiteAlgorithm(whiteAlgorithm)
{
_whiteAlgorithm = whiteAlgorithm;
Debug( _log, "whiteAlgorithm : %s", whiteAlgorithm.c_str());
initialized = false;
led_string.freq = freq;
led_string.dmanum = dmanum;
if (pwmchannel != 0 && pwmchannel != 1) {
Error( _log, "WS281x: invalid PWM channel; must be 0 or 1.");
throw -1;
}
chan = pwmchannel;
led_string.channel[chan].gpionum = gpio;
led_string.channel[chan].invert = invert;
led_string.channel[chan].count = leds;
led_string.channel[chan].brightness = 255;
if (rgbw == 1) {
led_string.channel[chan].strip_type = SK6812_STRIP_GRBW;
} else {
led_string.channel[chan].strip_type = WS2811_STRIP_RGB;
_led_string.freq = freq;
_led_string.dmanum = dmanum;
if (pwmchannel != 0 && pwmchannel != 1)
{
throw std::runtime_error("WS281x: invalid PWM channel; must be 0 or 1.");
}
_led_string.channel[_channel].gpionum = gpio;
_led_string.channel[_channel].invert = invert;
_led_string.channel[_channel].count = leds;
_led_string.channel[_channel].brightness = 255;
_led_string.channel[_channel].strip_type = ((rgbw == 1) ? SK6812_STRIP_GRBW : WS2811_STRIP_RGB);
led_string.channel[!chan].gpionum = 0;
led_string.channel[!chan].invert = invert;
led_string.channel[!chan].count = 0;
led_string.channel[!chan].brightness = 0;
led_string.channel[!chan].strip_type = WS2811_STRIP_RGB;
if (ws2811_init(&led_string) < 0) {
Error( _log, "Unable to initialize ws281x library.");
throw -1;
_led_string.channel[!_channel].gpionum = 0;
_led_string.channel[!_channel].invert = invert;
_led_string.channel[!_channel].count = 0;
_led_string.channel[!_channel].brightness = 0;
_led_string.channel[!_channel].strip_type = WS2811_STRIP_RGB;
if (ws2811_init(&_led_string) < 0)
{
throw std::runtime_error("Unable to initialize ws281x library.");
}
initialized = true;
_initialized = true;
}
// Send new values down the LED chain
int LedDeviceWS281x::write(const std::vector<ColorRgb> &ledValues)
{
if (!initialized)
if (!_initialized)
return -1;
int idx = 0;
for (const ColorRgb& color : ledValues)
{
if (idx >= led_string.channel[chan].count)
if (idx >= _led_string.channel[_channel].count)
{
break;
}
_temp_rgbw.red = color.red;
_temp_rgbw.green = color.green;
_temp_rgbw.blue = color.blue;
_temp_rgbw.white = 0;
if (led_string.channel[chan].strip_type == SK6812_STRIP_GRBW) {
if (_led_string.channel[_channel].strip_type == SK6812_STRIP_GRBW)
{
Rgb_to_Rgbw(color, &_temp_rgbw, _whiteAlgorithm);
}
led_string.channel[chan].leds[idx++] =
_led_string.channel[_channel].leds[idx++] =
((uint32_t)_temp_rgbw.white << 24) + ((uint32_t)_temp_rgbw.red << 16) + ((uint32_t)_temp_rgbw.green << 8) + _temp_rgbw.blue;
}
while (idx < led_string.channel[chan].count)
led_string.channel[chan].leds[idx++] = 0;
while (idx < _led_string.channel[_channel].count)
{
_led_string.channel[_channel].leds[idx++] = 0;
}
if (ws2811_render(&led_string))
return -1;
return 0;
return ws2811_render(&_led_string) ? -1 : 0;
}
// Turn off the LEDs by sending 000000's
@ -77,25 +77,24 @@ int LedDeviceWS281x::write(const std::vector<ColorRgb> &ledValues)
// make it more likely we don't accidentally drive data into an off strip
int LedDeviceWS281x::switchOff()
{
if (!initialized)
if (!_initialized)
{
return -1;
}
int idx = 0;
while (idx < led_string.channel[chan].count)
led_string.channel[chan].leds[idx++] = 0;
while (idx < _led_string.channel[_channel].count)
_led_string.channel[_channel].leds[idx++] = 0;
if (ws2811_render(&led_string))
return -1;
return 0;
return ws2811_render(&_led_string) ? -1 : 0;
}
// Destructor
LedDeviceWS281x::~LedDeviceWS281x()
{
if (initialized)
if (_initialized)
{
ws2811_fini(&led_string);
ws2811_fini(&_led_string);
}
initialized = false;
_initialized = false;
}

View File

@ -1,6 +1,3 @@
#ifndef LEDDEVICEWS281X_H_
#define LEDDEVICEWS281X_H_
#pragma once
#include <leddevice/LedDevice.h>
@ -41,11 +38,9 @@ public:
virtual int switchOff();
private:
ws2811_t led_string;
int chan;
bool initialized;
ws2811_t _led_string;
int _channel;
bool _initialized;
std::string _whiteAlgorithm;
ColorRgbw _temp_rgbw;
};
#endif /* LEDDEVICEWS281X_H_ */

View File

@ -14,14 +14,13 @@
LedDeviceWs2801::LedDeviceWs2801(const std::string& outputDevice, const unsigned baudrate, const unsigned latchTime,
const int spiMode, const bool spiDataInvert)
: LedSpiDevice(outputDevice, baudrate, latchTime, spiMode, spiDataInvert)
, mLedCount(0)
{
// empty
}
int LedDeviceWs2801::write(const std::vector<ColorRgb> &ledValues)
{
mLedCount = ledValues.size();
_ledCount = ledValues.size();
const unsigned dataLen = ledValues.size() * sizeof(ColorRgb);
const uint8_t * dataPtr = reinterpret_cast<const uint8_t *>(ledValues.data());
@ -31,5 +30,5 @@ int LedDeviceWs2801::write(const std::vector<ColorRgb> &ledValues)
int LedDeviceWs2801::switchOff()
{
return write(std::vector<ColorRgb>(mLedCount, ColorRgb{0,0,0}));
return write(std::vector<ColorRgb>(_ledCount, ColorRgb{0,0,0}));
}

View File

@ -35,9 +35,4 @@ public:
/// Switch the leds off
virtual int switchOff();
private:
/// the number of leds (needed when switching off)
size_t mLedCount;
};

View File

@ -11,55 +11,53 @@
// hyperion local includes
#include "LedDeviceWs2812SPI.h"
LedDeviceWs2812SPI::LedDeviceWs2812SPI(const std::string& outputDevice, const unsigned baudrate,
const int spiMode, const bool spiDataInvert)
LedDeviceWs2812SPI::LedDeviceWs2812SPI(const std::string& outputDevice, const unsigned baudrate, const int spiMode, const bool spiDataInvert)
: LedSpiDevice(outputDevice, baudrate, 0, spiMode, spiDataInvert)
, mLedCount(0)
, bitpair_to_byte {
0b10001000,
0b10001100,
0b11001000,
0b11001100,
}
{
// empty
}
int LedDeviceWs2812SPI::write(const std::vector<ColorRgb> &ledValues)
{
mLedCount = ledValues.size();
_ledCount = ledValues.size();
// 3 colours, 4 spi bytes per colour + 3 frame end latch bytes
#define COLOURS_PER_LED 3
#define SPI_BYTES_PER_COLOUR 4
#define SPI_BYTES_PER_LED COLOURS_PER_LED * SPI_BYTES_PER_COLOUR
const int SPI_BYTES_PER_LED = 3 * 4;
unsigned spi_size = _ledCount * SPI_BYTES_PER_LED + 3;
unsigned spi_size = mLedCount * SPI_BYTES_PER_LED + 3;
if(_spiBuffer.size() != spi_size){
_spiBuffer.resize(spi_size, 0x00);
if(_ledBuffer.size() != spi_size)
{
_ledBuffer.resize(spi_size, 0x00);
}
unsigned spi_ptr = 0;
for (unsigned i=0; i< mLedCount; ++i) {
for (unsigned i=0; i< (unsigned)_ledCount; ++i)
{
uint32_t colorBits = ((unsigned int)ledValues[i].red << 16)
| ((unsigned int)ledValues[i].green << 8)
| ledValues[i].blue;
for (int j=SPI_BYTES_PER_LED - 1; j>=0; j--) {
_spiBuffer[spi_ptr+j] = bitpair_to_byte[ colorBits & 0x3 ];
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;
}
_spiBuffer[spi_ptr++] = 0;
_spiBuffer[spi_ptr++] = 0;
_spiBuffer[spi_ptr++] = 0;
_ledBuffer[spi_ptr++] = 0;
_ledBuffer[spi_ptr++] = 0;
_ledBuffer[spi_ptr++] = 0;
return writeBytes(spi_size, _spiBuffer.data());
return writeBytes(spi_size, _ledBuffer.data());
}
int LedDeviceWs2812SPI::switchOff()
{
return write(std::vector<ColorRgb>(mLedCount, ColorRgb{0,0,0}));
return write(std::vector<ColorRgb>(_ledCount, ColorRgb{0,0,0}));
}

View File

@ -33,10 +33,5 @@ public:
virtual int switchOff();
private:
/// the number of leds (needed when switching off)
size_t mLedCount;
std::vector<uint8_t> _spiBuffer;
uint8_t bitpair_to_byte[4];
};

View File

@ -9,13 +9,13 @@
// Local Hyperion includes
#include "LedHIDDevice.h"
LedHIDDevice::LedHIDDevice(const unsigned short VendorId, const unsigned short ProductId, int delayAfterConnect_ms, const bool useFeature) :
_VendorId(VendorId),
_ProductId(ProductId),
_useFeature(useFeature),
_deviceHandle(nullptr),
_delayAfterConnect_ms(delayAfterConnect_ms),
_blockedForDelay(false)
LedHIDDevice::LedHIDDevice(const unsigned short VendorId, const unsigned short ProductId, int delayAfterConnect_ms, const bool useFeature)
: _VendorId(VendorId)
, _ProductId(ProductId)
, _useFeature(useFeature)
, _deviceHandle(nullptr)
, _delayAfterConnect_ms(delayAfterConnect_ms)
, _blockedForDelay(false)
{
// empty
}

View File

@ -11,7 +11,7 @@
///
/// The LedHIDDevice implements an abstract base-class for LedDevices using an HID-device.
///
class LedHIDDevice : public QObject, public LedDevice
class LedHIDDevice : public LedDevice
{
Q_OBJECT

View File

@ -18,8 +18,6 @@ LedRs232Device::LedRs232Device(const std::string& outputDevice, const unsigned b
, _stateChanged(true)
{
connect(&_rs232Port, SIGNAL(error(QSerialPort::SerialPortError)), this, SLOT(error(QSerialPort::SerialPortError)));
}
void LedRs232Device::error(QSerialPort::SerialPortError error)
@ -109,7 +107,9 @@ bool LedRs232Device::tryOpen()
int LedRs232Device::writeBytes(const unsigned size, const uint8_t * data)
{
if (_blockedForDelay)
{
return 0;
}
if (!_rs232Port.isOpen())
{

View File

@ -9,7 +9,7 @@
///
/// The LedRs232Device implements an abstract base-class for LedDevices using a RS232-device.
///
class LedRs232Device : public QObject, public LedDevice
class LedRs232Device : public LedDevice
{
Q_OBJECT
@ -49,6 +49,7 @@ private slots:
/// Unblock the device after a connection delay
void unblockAfterDelay();
void error(QSerialPort::SerialPortError error);
private:
// tries to open device if not opened
bool tryOpen();

View File

@ -14,47 +14,46 @@
#include <utils/Logger.h>
LedSpiDevice::LedSpiDevice(const std::string& outputDevice, const unsigned baudrate, const int latchTime_ns,
const int spiMode, const bool spiDataInvert)
: mDeviceName(outputDevice)
, mBaudRate_Hz(baudrate)
, mLatchTime_ns(latchTime_ns)
, mFid(-1)
, mSpiMode(spiMode)
, mSpiDataInvert(spiDataInvert)
LedSpiDevice::LedSpiDevice(const std::string& outputDevice, const unsigned baudrate, const int latchTime_ns, const int spiMode, const bool spiDataInvert)
: _deviceName(outputDevice)
, _baudRate_Hz(baudrate)
, _latchTime_ns(latchTime_ns)
, _fid(-1)
, _spiMode(spiMode)
, _spiDataInvert(spiDataInvert)
{
memset(&spi, 0, sizeof(spi));
memset(&_spi, 0, sizeof(_spi));
Debug(_log, "_spiDataInvert %d, _spiMode %d", _spiDataInvert, _spiMode);
}
LedSpiDevice::~LedSpiDevice()
{
// close(mFid);
// close(_fid);
}
int LedSpiDevice::open()
{
//printf ("mSpiDataInvert %d mSpiMode %d\n",mSpiDataInvert, mSpiMode);
const int bitsPerWord = 8;
mFid = ::open(mDeviceName.c_str(), O_RDWR);
_fid = ::open(_deviceName.c_str(), O_RDWR);
if (mFid < 0)
if (_fid < 0)
{
Error( _log, "Failed to open device (%s). Error message: %s", mDeviceName.c_str(), strerror(errno) );
Error( _log, "Failed to open device (%s). Error message: %s", _deviceName.c_str(), strerror(errno) );
return -1;
}
if (ioctl(mFid, SPI_IOC_WR_MODE, &mSpiMode) == -1 || ioctl(mFid, SPI_IOC_RD_MODE, &mSpiMode) == -1)
if (ioctl(_fid, SPI_IOC_WR_MODE, &_spiMode) == -1 || ioctl(_fid, SPI_IOC_RD_MODE, &_spiMode) == -1)
{
return -2;
}
if (ioctl(mFid, SPI_IOC_WR_BITS_PER_WORD, &bitsPerWord) == -1 || ioctl(mFid, SPI_IOC_RD_BITS_PER_WORD, &bitsPerWord) == -1)
if (ioctl(_fid, SPI_IOC_WR_BITS_PER_WORD, &bitsPerWord) == -1 || ioctl(_fid, 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)
if (ioctl(_fid, SPI_IOC_WR_MAX_SPEED_HZ, &_baudRate_Hz) == -1 || ioctl(_fid, SPI_IOC_RD_MAX_SPEED_HZ, &_baudRate_Hz) == -1)
{
return -6;
}
@ -64,30 +63,31 @@ int LedSpiDevice::open()
int LedSpiDevice::writeBytes(const unsigned size, const uint8_t * data)
{
if (mFid < 0)
if (_fid < 0)
{
return -1;
}
spi.tx_buf = __u64(data);
spi.len = __u32(size);
_spi.tx_buf = __u64(data);
_spi.len = __u32(size);
if (mSpiDataInvert) {
if (_spiDataInvert)
{
uint8_t * newdata = (uint8_t *)malloc(size);
for (unsigned i = 0; i<size; i++) {
newdata[i] = data[i] ^ 0xff;
}
spi.tx_buf = __u64(newdata);
_spi.tx_buf = __u64(newdata);
}
int retVal = ioctl(mFid, SPI_IOC_MESSAGE(1), &spi);
int retVal = ioctl(_fid, SPI_IOC_MESSAGE(1), &_spi);
if (retVal == 0 && mLatchTime_ns > 0)
if (retVal == 0 && _latchTime_ns > 0)
{
// The 'latch' time for latching the shifted-value into the leds
timespec latchTime;
latchTime.tv_sec = 0;
latchTime.tv_nsec = mLatchTime_ns;
latchTime.tv_nsec = _latchTime_ns;
// Sleep to latch the leds (only if write succesfull)
nanosleep(&latchTime, NULL);

View File

@ -50,21 +50,23 @@ protected:
private:
/// The name of the output device
const std::string mDeviceName;
const std::string _deviceName;
/// The used baudrate of the output device
const int mBaudRate_Hz;
const int _baudRate_Hz;
/// The time which the device should be untouched after a write
const int mLatchTime_ns;
const int _latchTime_ns;
/// The File Identifier of the opened output device (or -1 if not opened)
int mFid;
int _fid;
/// which spi clock mode do we use? (0..3)
int mSpiMode;
int _spiMode;
/// 1=>invert the data pattern
bool mSpiDataInvert;
bool _spiDataInvert;
/// The transfer structure for writing to the spi-device
spi_ioc_transfer spi;
spi_ioc_transfer _spi;
};

View File

@ -15,35 +15,37 @@
// Local Hyperion includes
#include "LedUdpDevice.h"
LedUdpDevice::LedUdpDevice(const std::string& output, const int latchTime_ns) :
_target(output),
_LatchTime_ns(latchTime_ns)
LedUdpDevice::LedUdpDevice(const std::string& output, const int latchTime_ns)
: _target(output)
, _LatchTime_ns(latchTime_ns)
{
udpSocket = new QUdpSocket();
_udpSocket = new QUdpSocket();
QString str = QString::fromStdString(_target);
QStringList _list = str.split(":");
if (_list.size() != 2) {
QStringList str_splitted = str.split(":");
if (str_splitted.size() != 2)
{
throw("Error parsing hostname:port");
}
QHostInfo info = QHostInfo::fromName(_list.at(0));
if (!info.addresses().isEmpty()) {
_address = info.addresses().first();
QHostInfo info = QHostInfo::fromName(str_splitted.at(0));
if (!info.addresses().isEmpty())
{
// use the first IP address
_address = info.addresses().first();
}
_port = _list.at(1).toInt();
_port = str_splitted.at(1).toInt();
}
LedUdpDevice::~LedUdpDevice()
{
udpSocket->close();
_udpSocket->close();
}
int LedUdpDevice::open()
{
QHostAddress _localAddress = QHostAddress::Any;
quint16 _localPort = 0;
QHostAddress localAddress = QHostAddress::Any;
quint16 localPort = 0;
WarningIf( !udpSocket->bind(_localAddress, _localPort), _log, "Couldnt bind local address: %s", strerror(errno));
WarningIf( !_udpSocket->bind(localAddress, localPort), _log, "Couldnt bind local address: %s", strerror(errno));
return 0;
}
@ -51,7 +53,7 @@ int LedUdpDevice::open()
int LedUdpDevice::writeBytes(const unsigned size, const uint8_t * data)
{
qint64 retVal = udpSocket->writeDatagram((const char *)data,size,_address,_port);
qint64 retVal = _udpSocket->writeDatagram((const char *)data,size,_address,_port);
if (retVal >= 0 && _LatchTime_ns > 0)
{
@ -62,7 +64,9 @@ int LedUdpDevice::writeBytes(const unsigned size, const uint8_t * data)
// Sleep to latch the leds (only if write succesfull)
nanosleep(&latchTime, NULL);
} else {
}
else
{
Warning( _log, "Error sending: %s", strerror(errno));
}

View File

@ -38,7 +38,7 @@ protected:
/// Writes the given bytes/bits to the SPI-device and sleeps the latch time to ensure that the
/// values are latched.
///
/// @param[in[ size The length of the data
/// @param[in] size The length of the data
/// @param[in] data The data
///
/// @return Zero on succes else negative
@ -48,11 +48,12 @@ protected:
private:
/// The UDP destination as "host:port"
const std::string _target;
/// The time which the device should be untouched after a write
const int _LatchTime_ns;
///
QUdpSocket *udpSocket;
QUdpSocket * _udpSocket;
QHostAddress _address;
quint16 _port;
};