LED Device Features, Fixes and Refactoring (Resubmit PR855) (#875)

* Refactor LedDevices - Initial version
* Small renamings
* Add WLED as own device
* Lpd8806 Remove open() method
* remove dependency on Qt 5.10
* Lpd8806 Remove open() method
* Update WS281x
* Update WS2812SPI
* Add writeBlack for WLED powerOff
* WLED remove extra bracket
* Allow different Nanoleaf panel numbering sequence (Feature req.#827)
* build(deps): bump websocket-extensions from 0.1.3 to 0.1.4 in /docs (#826)
* Bumps [websocket-extensions](https://github.com/faye/websocket-extensions-node) from 0.1.3 to 0.1.4.
  - [Release notes](https://github.com/faye/websocket-extensions-node/releases)
  - [Changelog](https://github.com/faye/websocket-extensions-node/blob/master/CHANGELOG.md)
  - [Commits](https://github.com/faye/websocket-extensions-node/compare/0.1.3...0.1.4)
* Fix typos
* Nanoleaf clean-up
* Yeelight support, generalize wizard elements
* Update Yeelight to handle quota in music mode
* Yeelight extend rage for extraTimeDarkness for testing
* Clean-up - Add commentary, Remove development debug statements
* Fix brightnessSwitchOffOnMinimum typo and default value
* Yeelight support restoreOriginalState, additional Fixes
* WLED - Remove UDP-Port, as it is not configurable
* Fix merging issue
* Remove QHostAddress::operator=(const QString&)' is deprecated
* Windows compile errors and (Qt 5.15 deprecation) warnings
* Fix order includes
* LedDeviceFile Support Qt5.7 and greater
* Windows compatibility and other Fixes
* Fix Qt Version compatability
* Rs232 - Resolve portname from unix /dev/ style, fix DMX sub-type support
* Disable WLED Wizard Button (until Wizard is available)
* Yeelight updates
* Add wrong log-type as per #505
* Fixes and Clean-up after clang-tidy report
* Fix udpe131 not enabled for generated CID
* Change timer into dynamic for Qt Thread-Affinity
* Hue clean-up and diyHue workaround
* Updates after review feedback by m-seker
* Add "chrono" includes
This commit is contained in:
LordGrey
2020-07-12 20:27:56 +02:00
committed by GitHub
parent 3b48d8c9d6
commit 7389068a66
125 changed files with 8864 additions and 3217 deletions

View File

@@ -2,13 +2,13 @@
LedDeviceAdalight::LedDeviceAdalight(const QJsonObject &deviceConfig)
: ProviderRs232()
, _headerSize(6)
, _ligthBerryAPA102Mode(false)
, _headerSize(6)
, _ligthBerryAPA102Mode(false)
{
_devConfig = deviceConfig;
_deviceReady = false;
_isDeviceReady = false;
connect(this,SIGNAL(receivedData(QByteArray)),this,SLOT(receivedData(QByteArray)));
_activeDeviceType = deviceConfig["type"].toString("UNSPECIFIED").toLower();
}
LedDevice* LedDeviceAdalight::construct(const QJsonObject &deviceConfig)
@@ -18,43 +18,49 @@ LedDevice* LedDeviceAdalight::construct(const QJsonObject &deviceConfig)
bool LedDeviceAdalight::init(const QJsonObject &deviceConfig)
{
bool isInitOK = ProviderRs232::init(deviceConfig);
bool isInitOK = false;
_ligthBerryAPA102Mode = deviceConfig["lightberry_apa102_mode"].toBool(false);
// create ledBuffer
unsigned int totalLedCount = _ledCount;
if (_ligthBerryAPA102Mode)
// Initialise sub-class
if ( ProviderRs232::init(deviceConfig) )
{
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<= static_cast<int>( _ledCount); iLed++)
_ligthBerryAPA102Mode = deviceConfig["lightberry_apa102_mode"].toBool(false);
// create ledBuffer
unsigned int totalLedCount = _ledCount;
if (_ligthBerryAPA102Mode)
{
_ledBuffer[iLed*4+_headerSize] = 0xFF;
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<= static_cast<int>( _ledCount); iLed++)
{
_ledBuffer[iLed*4+_headerSize] = 0xFF;
}
Debug( _log, "Adalight driver with activated LightBerry APA102 mode");
}
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] );
isInitOK = true;
}
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 isInitOK;
}
@@ -74,11 +80,8 @@ int LedDeviceAdalight::write(const std::vector<ColorRgb> & ledValues)
{
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());
int rc = writeBytes(_ledBuffer.size(), _ledBuffer.data());
return rc;
}

View File

@@ -1,37 +1,47 @@
#pragma once
#ifndef LEDEVICETADALIGHT_H
#define LEDEVICETADALIGHT_H
// hyperion includes
#include "ProviderRs232.h"
///
/// Implementation of the LedDevice interface for writing to an Adalight led device.
/// Implementation of the LedDevice interface for writing to an Adalight LED-device.
///
class LedDeviceAdalight : public ProviderRs232
{
Q_OBJECT
public:
///
/// Constructs specific LedDevice
/// @brief Constructs an Adalight LED-device
///
/// @param deviceConfig json device config
/// @param deviceConfig Device's configuration as JSON-Object
///
explicit LedDeviceAdalight(const QJsonObject &deviceConfig);
/// constructs leddevice
///
/// @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
///
virtual bool init(const QJsonObject &deviceConfig) override;
public slots:
void receivedData(QByteArray data);
private:
///
/// Writes the led color values to the led-device
/// @brief Writes the RGB-Color values to the LEDs.
///
/// @param ledValues The color-value per led
/// @return Zero on succes else negative
/// @param[in] ledValues The RGB-color per LED
/// @return Zero on success, else negative
///
virtual int write(const std::vector<ColorRgb> & ledValues) override;
@@ -39,3 +49,4 @@ private:
bool _ligthBerryAPA102Mode;
};
#endif // LEDEVICETADALIGHT_H

View File

@@ -5,9 +5,12 @@ LedDeviceAtmo::LedDeviceAtmo(const QJsonObject &deviceConfig)
: ProviderRs232()
{
_devConfig = deviceConfig;
_deviceReady = false;
_isDeviceReady = false;
_activeDeviceType = deviceConfig["type"].toString("UNSPECIFIED").toLower();
}
LedDevice* LedDeviceAtmo::construct(const QJsonObject &deviceConfig)
{
return new LedDeviceAtmo(deviceConfig);
@@ -15,13 +18,13 @@ LedDevice* LedDeviceAtmo::construct(const QJsonObject &deviceConfig)
bool LedDeviceAtmo::init(const QJsonObject &deviceConfig)
{
bool isInitOK = ProviderRs232::init(deviceConfig);
bool isInitOK = false;
if ( isInitOK )
// Initialise sub-class
if ( ProviderRs232::init(deviceConfig) )
{
if (_ledCount != 5)
{
//Error( _log, "%d channels configured. This should always be 5!", _ledCount);
QString errortext = QString ("%1 channels configured. This should always be 5!").arg(_ledCount);
this->setInError(errortext);
isInitOK = false;
@@ -33,6 +36,8 @@ bool LedDeviceAtmo::init(const QJsonObject &deviceConfig)
_ledBuffer[1] = 0x00; // StartChannel(Low)
_ledBuffer[2] = 0x00; // StartChannel(High)
_ledBuffer[3] = 0x0F; // Number of Databytes send (always! 15)
isInitOK = true;
}
}
return isInitOK;

View File

@@ -1,4 +1,5 @@
#pragma once
#ifndef LEDEVICEATMO_H
#define LEDEVICEATMO_H
// hyperion includes
#include "ProviderRs232.h"
@@ -9,24 +10,35 @@
class LedDeviceAtmo : public ProviderRs232
{
public:
///
/// Constructs specific LedDevice
/// @brief Constructs an Atmo LED-device
///
/// @param deviceConfig json device config
/// @param deviceConfig Device's configuration as JSON-Object
///
explicit LedDeviceAtmo(const QJsonObject &deviceConfig);
/// constructs leddevice
///
/// @brief Destructor of the LedDevice
///
static LedDevice* construct(const QJsonObject &deviceConfig);
private:
///
/// @brief Initialise the device's configuration
///
/// @param[in] deviceConfig the JSON device configuration
/// @return True, if success
virtual bool init(const QJsonObject &deviceConfig) override;
private:
///
/// Writes the led color values to the led-device
/// @brief Writes the RGB-Color values to the LEDs.
///
/// @param ledValues The color-value per led
/// @return Zero on succes else negative
/// @param[in] ledValues The RGB-color per LED
/// @return Zero on success, else negative
///
virtual int write(const std::vector<ColorRgb> &ledValues) override;
};
#endif // LEDEVICEATMO_H

View File

@@ -1,4 +1,5 @@
#include "LedDeviceDMX.h"
#include <QSerialPort>
#ifndef _WIN32
#include <time.h>
@@ -13,9 +14,12 @@ LedDeviceDMX::LedDeviceDMX(const QJsonObject &deviceConfig)
, _dmxChannelCount(0)
{
_devConfig = deviceConfig;
_deviceReady = false;
_isDeviceReady = false;
_activeDeviceType = deviceConfig["type"].toString("UNSPECIFIED").toLower();
}
LedDevice* LedDeviceDMX::construct(const QJsonObject &deviceConfig)
{
return new LedDeviceDMX(deviceConfig);
@@ -23,18 +27,19 @@ LedDevice* LedDeviceDMX::construct(const QJsonObject &deviceConfig)
bool LedDeviceDMX::init(const QJsonObject &deviceConfig)
{
bool isInitOK = ProviderRs232::init(deviceConfig);
bool isInitOK = false;
if ( isInitOK )
// Initialise sub-class
if ( ProviderRs232::init(deviceConfig) )
{
QString dmxString = deviceConfig["dmxdevice"].toString("invalid");
if (dmxString == "raw")
QString dmxTypeString = deviceConfig["dmxtype"].toString("invalid");
if (dmxTypeString == "raw")
{
_dmxDeviceType = 0;
_dmxStart = 1;
_dmxSlotsPerLed = 3;
}
else if (dmxString == "McCrypt")
else if (dmxTypeString == "McCrypt")
{
_dmxDeviceType = 1;
_dmxStart = 1;
@@ -43,12 +48,12 @@ bool LedDeviceDMX::init(const QJsonObject &deviceConfig)
else
{
//Error(_log, "unknown dmx device type %s", QSTRING_CSTR(dmxString));
QString errortext = QString ("unknown dmx device type: %1").arg(dmxString);
QString errortext = QString ("unknown dmx device type: %1").arg(dmxTypeString);
this->setInError(errortext);
return false;
}
Debug(_log, "_dmxString \"%s\", _dmxDeviceType %d", QSTRING_CSTR(dmxString), _dmxDeviceType );
Debug(_log, "_dmxTypeString \"%s\", _dmxDeviceType %d", QSTRING_CSTR(dmxTypeString), _dmxDeviceType );
_rs232Port.setStopBits(QSerialPort::TwoStop);
_dmxLedCount = qMin(static_cast<int>(_ledCount), 512/_dmxSlotsPerLed);
@@ -59,6 +64,8 @@ bool LedDeviceDMX::init(const QJsonObject &deviceConfig)
_ledBuffer.resize(_dmxChannelCount, 0);
_ledBuffer[0] = 0x00; // NULL START code
isInitOK = true;
}
return isInitOK;
}

View File

@@ -1,37 +1,53 @@
#pragma once
#ifndef LEDEVICEDMX_H
#define LEDEVICEDMX_H
// hyperion includes
#include "ProviderRs232.h"
///
/// Implementation of the LedDevice interface for writing to DMX512 rs232 led device.
/// Implementation of the LedDevice interface for writing to DMX512 rs232 LED-device.
///
class LedDeviceDMX : public ProviderRs232
{
public:
///
/// Constructs specific LedDevice
/// @brief Constructs a DMX LED-device
///
/// @param deviceConfig json device config
/// @param deviceConfig Device's configuration as JSON-Object
///
explicit LedDeviceDMX(const QJsonObject &deviceConfig);
/// constructs leddevice
///
/// @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
///
virtual bool init(const QJsonObject &deviceConfig) override;
private:
///
/// Writes the led color values to the led-device
/// @brief Writes the RGB-Color values to the LEDs.
///
/// @param ledValues The color-value per led
/// @return Zero on succes else negative
/// @param[in] ledValues The RGB-color per LED
/// @return Zero on success, else negative
///
virtual int write(const std::vector<ColorRgb> &ledValues) override;
int _dmxDeviceType = 0;
int _dmxStart = 1;
int _dmxSlotsPerLed = 3;
int _dmxLedCount = 0;
unsigned int _dmxChannelCount = 0;
};
#endif // LEDEVICEDMX_H

View File

@@ -5,9 +5,9 @@ LedDeviceKarate::LedDeviceKarate(const QJsonObject &deviceConfig)
: ProviderRs232()
{
_devConfig = deviceConfig;
_deviceReady = false;
_isDeviceReady = false;
connect(this,SIGNAL(receivedData(QByteArray)),this,SLOT(receivedData(QByteArray)));
_activeDeviceType = deviceConfig["type"].toString("UNSPECIFIED").toLower();
}
LedDevice* LedDeviceKarate::construct(const QJsonObject &deviceConfig)
@@ -17,9 +17,10 @@ LedDevice* LedDeviceKarate::construct(const QJsonObject &deviceConfig)
bool LedDeviceKarate::init(const QJsonObject &deviceConfig)
{
bool isInitOK = ProviderRs232::init(deviceConfig);
bool isInitOK = false;
if ( isInitOK )
// Initialise sub-class
if ( ProviderRs232::init(deviceConfig) )
{
if (_ledCount != 16)
{
@@ -30,15 +31,16 @@ bool LedDeviceKarate::init(const QJsonObject &deviceConfig)
}
else
{
_ledBuffer.resize(4 + _ledCount * 3); // 4-byte header, 3 RGB values
_ledBuffer[0] = 0xAA; // Startbyte
_ledBuffer[1] = 0x12; // Send all Channels in Batch
_ledBuffer[2] = 0x00; // Checksum
_ledBuffer[3] = _ledCount * 3; // Number of Databytes send
_ledBuffer[0] = 0xAA; // Startbyte
_ledBuffer[1] = 0x12; // Send all Channels in Batch
_ledBuffer[2] = 0x00; // Checksum
_ledBuffer[3] = _ledCount * 3; // Number of Databytes send
Debug( _log, "Karatelight header for %d leds: 0x%02x 0x%02x 0x%02x 0x%02x", _ledCount,
_ledBuffer[0], _ledBuffer[1], _ledBuffer[2], _ledBuffer[3] );
isInitOK = true;
}
}
return isInitOK;
@@ -62,8 +64,3 @@ int LedDeviceKarate::write(const std::vector<ColorRgb> &ledValues)
return writeBytes(_ledBuffer.size(), _ledBuffer.data());
}
void LedDeviceKarate::receivedData(QByteArray data)
{
Debug(_log, ">>received %d bytes data %s", data.size(),data.data());
}

View File

@@ -1,36 +1,47 @@
#pragma once
#ifndef LEDEVICEKARATE_H
#define LEDEVICEKARATE_H
// hyperion includes
#include "ProviderRs232.h"
///
/// Implementation of the LedDevice interface for writing to serial device using tpm2 protocol.
/// Implementation of the LedDevice interface for writing to serial device
///
class LedDeviceKarate : public ProviderRs232
{
Q_OBJECT
public:
///
/// Constructs specific LedDevice
/// @brief Constructs a Karate LED-device
///
/// @param deviceConfig json device config
/// @param deviceConfig Device's configuration as JSON-Object
///
explicit LedDeviceKarate(const QJsonObject &deviceConfig);
/// constructs leddevice
///
/// @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
///
virtual bool init(const QJsonObject &deviceConfig) override;
public slots:
void receivedData(QByteArray data);
private:
/// @brief Writes the RGB-Color values to the LEDs.
///
/// Writes the led color values to the led-device
///
/// @param ledValues The color-value per led
/// @return Zero on succes else negative
/// @param[in] ledValues The RGB-color per LED
/// @return Zero on success, else negative
///
virtual int write(const std::vector<ColorRgb> &ledValues) override;
};
#endif // LEDEVICEKARATE_H

View File

@@ -10,7 +10,9 @@ LedDeviceSedu::LedDeviceSedu(const QJsonObject &deviceConfig)
: ProviderRs232()
{
_devConfig = deviceConfig;
_deviceReady = false;
_isDeviceReady = false;
_activeDeviceType = deviceConfig["type"].toString("UNSPECIFIED").toLower();
}
LedDevice* LedDeviceSedu::construct(const QJsonObject &deviceConfig)
@@ -20,31 +22,37 @@ LedDevice* LedDeviceSedu::construct(const QJsonObject &deviceConfig)
bool LedDeviceSedu::init(const QJsonObject &deviceConfig)
{
bool isInitOK = ProviderRs232::init(deviceConfig);
bool isInitOK = false;
std::vector<FrameSpec> frameSpecs{{0xA1, 256}, {0xA2, 512}, {0xB0, 768}, {0xB1, 1536}, {0xB2, 3072} };
for (const FrameSpec& frameSpec : frameSpecs)
// Initialise sub-class
if ( ProviderRs232::init(deviceConfig) )
{
if ((unsigned)_ledRGBCount <= frameSpec.size)
std::vector<FrameSpec> frameSpecs{{0xA1, 256}, {0xA2, 512}, {0xB0, 768}, {0xB1, 1536}, {0xB2, 3072} };
for (const FrameSpec& frameSpec : frameSpecs)
{
_ledBuffer.clear();
_ledBuffer.resize(frameSpec.size + 3, 0);
_ledBuffer[0] = 0x5A;
_ledBuffer[1] = frameSpec.id;
_ledBuffer.back() = 0xA5;
break;
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.empty())
{
//Warning(_log, "More rgb-channels required then available");
QString errortext = "More rgb-channels required then available";
this->setInError(errortext);
}
else
{
isInitOK = true;
}
}
if (_ledBuffer.size() == 0)
{
//Warning(_log, "More rgb-channels required then available");
QString errortext = "More rgb-channels required then available";
this->setInError(errortext);
isInitOK = false;
}
return isInitOK;
}

View File

@@ -1,32 +1,47 @@
#pragma once
#ifndef LEDEVICESEDU_H
#define LEDEVICESEDU_H
// hyperion includes
#include "ProviderRs232.h"
///
/// Implementation of the LedDevice interface for writing to SEDU led device.
/// Implementation of the LedDevice interface for writing to SEDU LED-device.
///
class LedDeviceSedu : public ProviderRs232
{
public:
///
/// Constructs specific LedDevice
/// @brief Constructs a SEDU LED-device
///
/// @param deviceConfig json device config
/// @param deviceConfig Device's configuration as JSON-Object
///
explicit LedDeviceSedu(const QJsonObject &deviceConfig);
/// constructs leddevice
///
/// @brief Constructs the LED-device
///
/// @param[in] deviceConfig Device's configuration as JSON-Object
/// @return LedDevice constructed
static LedDevice* construct(const QJsonObject &deviceConfig);
virtual bool init(const QJsonObject &deviceConfig) override;
private:
///
/// Writes the led color values to the led-device
/// @brief Initialise the device's configuration
///
/// @param ledValues The color-value per led
/// @return Zero on succes else negative
/// @param[in] deviceConfig the JSON device configuration
/// @return True, if success
///
virtual 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
///
virtual int write(const std::vector<ColorRgb> &ledValues) override;
};
#endif // LEDEVICESEDU_H

View File

@@ -5,9 +5,12 @@ LedDeviceTpm2::LedDeviceTpm2(const QJsonObject &deviceConfig)
: ProviderRs232()
{
_devConfig = deviceConfig;
_deviceReady = false;
_isDeviceReady = false;
_activeDeviceType = deviceConfig["type"].toString("UNSPECIFIED").toLower();
}
LedDevice* LedDeviceTpm2::construct(const QJsonObject &deviceConfig)
{
return new LedDeviceTpm2(deviceConfig);
@@ -15,15 +18,21 @@ LedDevice* LedDeviceTpm2::construct(const QJsonObject &deviceConfig)
bool LedDeviceTpm2::init(const QJsonObject &deviceConfig)
{
bool isInitOK = ProviderRs232::init(deviceConfig);
bool isInitOK = false;
_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
// Initialise sub-class
if ( 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
isInitOK = true;
}
return isInitOK;
}

View File

@@ -1,4 +1,5 @@
#pragma once
#ifndef LEDEVICETPM2_H
#define LEDEVICETPM2_H
// hyperion includes
#include "ProviderRs232.h"
@@ -9,24 +10,38 @@
class LedDeviceTpm2 : public ProviderRs232
{
public:
///
/// Constructs specific LedDevice
/// @brief Constructs a TPM 2 LED-device
///
/// @param deviceConfig json device config
/// @param deviceConfig Device's configuration as JSON-Object
///
explicit LedDeviceTpm2(const QJsonObject &deviceConfig);
/// constructs leddevice
///
/// @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
///
virtual bool init(const QJsonObject &deviceConfig) override;
private:
///
/// Writes the led color values to the led-device
/// @brief Writes the RGB-Color values to the LEDs.
///
/// @param ledValues The color-value per led
/// @return Zero on succes else negative
/// @param[in] ledValues The RGB-color per LED
/// @return Zero on success, else negative
///
virtual int write(const std::vector<ColorRgb> &ledValues) override;
};
#endif // LEDEVICETPM2_H

View File

@@ -1,290 +1,297 @@
// STL includes
#include <cstring>
#include <iostream>
// Qt includes
#include <QTimer>
#include <QDateTime>
#include <QFile>
#include <QSerialPortInfo>
// Local Hyperion includes
// LedDevice includes
#include <leddevice/LedDevice.h>
#include "ProviderRs232.h"
// qt includes
#include <QSerialPortInfo>
#include <QEventLoop>
#include <chrono>
// Constants
constexpr std::chrono::milliseconds WRITE_TIMEOUT{1000}; // device write timeout in ms
constexpr std::chrono::milliseconds OPEN_TIMEOUT{5000}; // device open timeout in ms
const int MAX_WRITE_TIMEOUTS = 5; // maximum number of allowed timeouts
const int NUM_POWEROFF_WRITE_BLACK = 2; // Number of write "BLACK" during powering off
ProviderRs232::ProviderRs232()
: _rs232Port(this)
, _writeTimeout(this)
, _blockedForDelay(false)
, _stateChanged(true)
, _bytesToWrite(0)
, _frameDropCounter(0)
, _lastError(QSerialPort::NoError)
, _preOpenDelayTimeOut(0)
, _preOpenDelay(2000)
, _enableAutoDeviceName(false)
,_baudRate_Hz(1000000)
,_isAutoDeviceName(false)
,_delayAfterConnect_ms(0)
,_frameDropCounter(0)
{
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()));
_writeTimeout.setInterval(5000);
_writeTimeout.setSingleShot(true);
connect(&_writeTimeout, SIGNAL(timeout()), this, SLOT(writeTimeout()));
}
bool ProviderRs232::init(const QJsonObject &deviceConfig)
{
closeDevice();
bool isInitOK = false;
bool isInitOK = LedDevice::init(deviceConfig);
// Initialise sub-class
if ( 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);
Debug(_log, "DeviceType : %s", QSTRING_CSTR( this->getActiveDeviceType() ));
Debug(_log, "LedCount : %u", this->getLedCount());
Debug(_log, "ColorOrder : %s", QSTRING_CSTR( this->getColorOrder() ));
Debug(_log, "RefreshTime : %d", _refreshTimerInterval_ms);
Debug(_log, "LatchTime : %d", this->getLatchTime());
_deviceName = deviceConfig["output"].toString("auto");
// If device name was given as unix /dev/ system-location, get port name
if ( _deviceName.startsWith(QLatin1String("/dev/")) )
_deviceName = _deviceName.mid(5);
_isAutoDeviceName = _deviceName.toLower() == "auto";
_baudRate_Hz = deviceConfig["rate"].toInt();
_delayAfterConnect_ms = deviceConfig["delayAfterConnect"].toInt(1500);
Debug(_log, "deviceName : %s", QSTRING_CSTR(_deviceName));
Debug(_log, "AutoDevice : %d", _isAutoDeviceName);
Debug(_log, "baudRate_Hz : %d", _baudRate_Hz);
Debug(_log, "delayAfCon ms: %d", _delayAfterConnect_ms);
isInitOK = true;
}
return isInitOK;
}
void ProviderRs232::close()
{
LedDevice::close();
// LedDevice specific closing activites
closeDevice();
}
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();
}
}
return "";
}
void ProviderRs232::bytesWritten(qint64 bytes)
{
_bytesToWrite -= bytes;
if (_bytesToWrite <= 0)
{
_blockedForDelay = false;
_writeTimeout.stop();
}
}
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();
this->setInError( "Rs232 SerialPortError, see details in previous log lines!" );
closeDevice();
}
}
}
ProviderRs232::~ProviderRs232()
{
disconnect(&_rs232Port, SIGNAL(error(QSerialPort::SerialPortError)), this, SLOT(error(QSerialPort::SerialPortError)));
}
void ProviderRs232::closeDevice()
{
_writeTimeout.stop();
if (_rs232Port.isOpen())
{
_rs232Port.close();
Debug(_log,"Close UART: %s", _deviceName.toLocal8Bit().constData());
}
_stateChanged = true;
_bytesToWrite = 0;
_blockedForDelay = false;
_deviceReady = false;
}
int ProviderRs232::open()
{
int retval = -1;
_deviceReady = false;
_isDeviceReady = false;
_isInSwitchOff = false;
// General initialisation and configuration of LedDevice
if ( init(_devConfig) )
// open device physically
if ( tryOpen(_delayAfterConnect_ms) )
{
if ( tryOpen(_delayAfterConnect_ms) )
{
// Everything is OK -> enable device
_deviceReady = true;
setEnable(true);
retval = 0;
}
else
{
this->setInError( "Error opening device!" );
}
// Everything is OK, device is ready
_isDeviceReady = true;
retval = 0;
}
return retval;
}
int ProviderRs232::close()
{
int retval = 0;
_isDeviceReady = false;
// Test, if device requires closing
if (_rs232Port.isOpen())
{
if ( _rs232Port.flush() )
{
Debug(_log,"Flush was successful");
}
Debug(_log,"Close UART: %s", QSTRING_CSTR(_deviceName) );
_rs232Port.close();
// Everything is OK -> device is closed
}
return retval;
}
bool ProviderRs232::powerOff()
{
// Simulate power-off by writing a final "Black" to have a defined outcome
bool rc = false;
if ( writeBlack( NUM_POWEROFF_WRITE_BLACK ) >= 0 )
{
rc = true;
}
return rc;
}
bool ProviderRs232::tryOpen(const int delayAfterConnect_ms)
{
if (_deviceName.isEmpty() || _rs232Port.portName().isEmpty())
{
if ( _enableAutoDeviceName )
if (!_rs232Port.isOpen())
{
_deviceName = findSerialDevice();
if ( _deviceName.isEmpty() )
if ( _isAutoDeviceName )
{
return false;
_deviceName = discoverFirst();
if (_deviceName.isEmpty())
{
this->setInError( QString("No serial device found automatically!") );
return false;
}
}
}
Info(_log, "Opening UART: %s", _deviceName.toLocal8Bit().constData());
_rs232Port.setPortName(_deviceName);
}
if ( ! _rs232Port.isOpen() )
if (!_rs232Port.isOpen())
{
Info(_log, "Opening UART: %s", QSTRING_CSTR(_deviceName));
_frameDropCounter = 0;
_rs232Port.setBaudRate( _baudRate_Hz );
Debug(_log, "_rs232Port.open(QIODevice::WriteOnly): %s, Baud rate [%d]bps", QSTRING_CSTR(_deviceName), _baudRate_Hz);
QSerialPortInfo serialPortInfo(_deviceName);
if (! serialPortInfo.isNull())
QJsonObject portInfo;
Debug(_log, "portName: %s", QSTRING_CSTR(serialPortInfo.portName()));
Debug(_log, "systemLocation: %s", QSTRING_CSTR(serialPortInfo.systemLocation()));
Debug(_log, "description: %s", QSTRING_CSTR(serialPortInfo.description()));
Debug(_log, "manufacturer: %s", QSTRING_CSTR(serialPortInfo.manufacturer()));
Debug(_log, "productIdentifier: %s", QSTRING_CSTR(QString("0x%1").arg(serialPortInfo.productIdentifier(), 0, 16)));
Debug(_log, "vendorIdentifier: %s", QSTRING_CSTR(QString("0x%1").arg(serialPortInfo.vendorIdentifier(), 0, 16)));
Debug(_log, "serialNumber: %s", QSTRING_CSTR(serialPortInfo.serialNumber()));
if (!serialPortInfo.isNull() )
{
if ( _preOpenDelayTimeOut > QDateTime::currentMSecsSinceEpoch() )
if ( !_rs232Port.open(QIODevice::WriteOnly) )
{
this->setInError(_rs232Port.errorString());
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
{
QString errortext = QString("Invalid serial device name: [%1]!").arg(_deviceName);
this->setInError(errortext);
_preOpenDelayTimeOut = QDateTime::currentMSecsSinceEpoch() + _preOpenDelay;
this->setInError( errortext );
return false;
}
}
if (delayAfterConnect_ms > 0)
{
_blockedForDelay = true;
QTimer::singleShot(delayAfterConnect_ms, this, SLOT(unblockAfterDelay()));
Debug(_log, "Device blocked for %d ms", delayAfterConnect_ms);
Debug(_log, "delayAfterConnect for %d ms - start", delayAfterConnect_ms);
// Wait delayAfterConnect_ms before allowing write
QEventLoop loop;
QTimer::singleShot( delayAfterConnect_ms, &loop, SLOT( quit() ) );
loop.exec();
Debug(_log, "delayAfterConnect for %d ms - finished", delayAfterConnect_ms);
}
return _rs232Port.isOpen();
}
int ProviderRs232::writeBytes(const qint64 size, const uint8_t * data)
void ProviderRs232::setInError(const QString& errorMsg)
{
if (! _blockedForDelay)
{
if (!_rs232Port.isOpen())
{
return tryOpen(5000) ? 0 : -1;
}
_rs232Port.clearError();
this->close();
if (_frameDropCounter > 5)
LedDevice::setInError( errorMsg );
}
int ProviderRs232::writeBytes(const qint64 size, const uint8_t *data)
{
DebugIf(_isInSwitchOff, _log, "_inClosing [%d], enabled [%d], _deviceReady [%d], _frameDropCounter [%d]", _isInSwitchOff, this->isEnabled(), _isDeviceReady, _frameDropCounter);
int rc = 0;
if (!_rs232Port.isOpen())
{
Debug(_log, "!_rs232Port.isOpen()");
if ( !tryOpen(OPEN_TIMEOUT.count()) )
{
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;
}
_writeTimeout.start();
}
DebugIf( _isInSwitchOff, _log, "[%s]", QSTRING_CSTR(uint8_t_to_hex_string(data, size, 32)) );
qint64 bytesWritten = _rs232Port.write(reinterpret_cast<const char*>(data), size);
if (bytesWritten == -1 || bytesWritten != size)
{
this->setInError( QString ("Rs232 SerialPortError: %1").arg(_rs232Port.errorString()) );
rc = -1;
}
else
{
_frameDropCounter++;
if (!_rs232Port.waitForBytesWritten(WRITE_TIMEOUT.count()))
{
if ( _rs232Port.error() == QSerialPort::TimeoutError )
{
Debug(_log, "Timeout after %dms: %d frames already dropped", WRITE_TIMEOUT, _frameDropCounter);
++_frameDropCounter;
// Check,if number of timeouts in a given time frame is greater than defined
// TODO: ProviderRs232::writeBytes - Add time frame to check for timeouts that devices does not close after absolute number of timeouts
if ( _frameDropCounter > MAX_WRITE_TIMEOUTS )
{
this->setInError( QString ("Timeout writing data to %1").arg(_deviceName) );
rc = -1;
}
else
{
//give it another try
_rs232Port.clearError();
}
}
else
{
this->setInError( QString ("Rs232 SerialPortError: %1").arg(_rs232Port.errorString()) );
rc = -1;
}
}
else
{
DebugIf(_isInSwitchOff,_log, "In Closing: bytesWritten [%d], _rs232Port.error() [%d], %s", bytesWritten, _rs232Port.error(), _rs232Port.error() == QSerialPort::NoError ? "No Error" : QSTRING_CSTR(_rs232Port.errorString()) );
}
}
return 0;
DebugIf(_isInSwitchOff, _log, "[%d], _inClosing[%d], enabled [%d], _deviceReady [%d]", rc, _isInSwitchOff, this->isEnabled(), _isDeviceReady);
return rc;
}
void ProviderRs232::writeTimeout()
QString ProviderRs232::discoverFirst()
{
//Error(_log, "Timeout on write data to %s", _deviceName.toLocal8Bit().constData());
QString errortext = QString ("Timeout on write data to %1").arg(_deviceName);
setInError( errortext );
close();
// take first available USB serial port - currently no probing!
for (auto const & port : QSerialPortInfo::availablePorts())
{
if (!port.isNull() && !port.isBusy())
{
Info(_log, "found serial device: %s", QSTRING_CSTR(port.portName()));
return port.portName();
}
}
return "";
}
void ProviderRs232::unblockAfterDelay()
QJsonObject ProviderRs232::discover()
{
_blockedForDelay = false;
QJsonObject devicesDiscovered;
devicesDiscovered.insert("ledDeviceType", _activeDeviceType );
QJsonArray deviceList;
// Discover serial Devices
for (auto &port : QSerialPortInfo::availablePorts() )
{
if ( !port.isNull() )
{
QJsonObject portInfo;
portInfo.insert("description", port.description());
portInfo.insert("manufacturer", port.manufacturer());
portInfo.insert("portName", port.portName());
portInfo.insert("productIdentifier", QString("0x%1").arg(port.productIdentifier(), 0, 16));
portInfo.insert("serialNumber", port.serialNumber());
portInfo.insert("systemLocation", port.systemLocation());
portInfo.insert("vendorIdentifier", QString("0x%1").arg(port.vendorIdentifier(), 0, 16));
deviceList.append(portInfo);
}
}
devicesDiscovered.insert("devices", deviceList);
return devicesDiscovered;
}

View File

@@ -1,13 +1,12 @@
#pragma once
#include <QObject>
#include <QSerialPort>
#include <QTimer>
#include <QString>
#ifndef PROVIDERRS232_H
#define PROVIDERRS232_H
// LedDevice includes
#include <leddevice/LedDevice.h>
// qt includes
#include <QSerialPort>
///
/// The ProviderRs232 implements an abstract base-class for LedDevices using a RS232-device.
///
@@ -16,91 +15,106 @@ class ProviderRs232 : public LedDevice
Q_OBJECT
public:
///
/// Constructs specific LedDevice
/// @brief Constructs a RS232 LED-device
///
ProviderRs232();
///
/// Sets configuration
///
/// @param deviceConfig the json device config
/// @return true if success
virtual bool init(const QJsonObject &deviceConfig) override;
///
/// Destructor of the LedDevice; closes the output device if it is open
/// @brief Destructor of the UDP LED-device
///
virtual ~ProviderRs232() override;
///
/// Opens and configures the output device
///
/// @return Zero on succes else negative
///
int open() override;
public slots:
///
/// Closes the output device.
/// Includes switching-off the device and stopping refreshes
///
virtual void close() override;
private slots:
/// Unblock the device after a connection delay
void writeTimeout();
void unblockAfterDelay();
void error(QSerialPort::SerialPortError setInError);
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
*/
///
/// @brief Initialise the RS232 device's configuration and network address details
///
/// @param[in] deviceConfig the JSON device configuration
/// @return True, if success
///
virtual bool init(const QJsonObject &deviceConfig) override;
///
/// @brief Opens the output device.
///
/// @return Zero on success (i.e. device is ready), else negative
///
virtual int open() override;
///
/// @brief Closes the UDP device.
///
/// @return Zero on success (i.e. device is closed), else negative
///
virtual int close() override;
///
/// @brief Power-/turn off a RS232-device
///
/// The off-state is simulated by writing "Black to LED"
///
/// @return True, if success
///
virtual bool powerOff() override;
///
/// @brief Discover first devices of a serial device available (for configuration)
///
/// @return A string of the device found
///
virtual QString discoverFirst() override;
///
/// @brief Discover RS232 serial devices available (for configuration).
///
/// @return A JSON structure holding a list of devices found
///
virtual QJsonObject discover() override;
///
/// @brief Write the given bytes to the RS232-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);
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
/// The RS232 serial-device
QSerialPort _rs232Port;
/// The used baud-rate of the output device
qint32 _baudRate_Hz;
protected slots:
///
/// @brief Set device in error state
///
/// @param errorMsg The error message to be logged
///
virtual void setInError( const QString& errorMsg) override;
private:
///
/// @brief Try to open device if not opened
///
/// @return True,if on success
///
bool tryOpen(const int delayAfterConnect_ms);
/// Try to auto-discover device name?
bool _isAutoDeviceName;
/// Sleep after the connect before continuing
int _delayAfterConnect_ms;
/// The RS232 serial-device
QSerialPort _rs232Port;
/// A timeout timer for the asynchronous connection
QTimer _writeTimeout;
bool _blockedForDelay;
bool _stateChanged;
qint64 _bytesToWrite;
qint64 _frameDropCounter;
QSerialPort::SerialPortError _lastError;
qint64 _preOpenDelayTimeOut;
int _preOpenDelay;
bool _enableAutoDeviceName;
/// Frames dropped, as write failed
int _frameDropCounter;
};
#endif // PROVIDERRS232_H