Leddevices source tree refactoring (#461)

* rework structure of leddevice source tree

* fix data type vor v4l sig detection value in webui

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

View File

@@ -0,0 +1,218 @@
// stl includes
#include <exception>
#include <cstring>
// Local Hyperion includes
#include "LedDeviceHyperionUsbasp.h"
// Static constants which define the Hyperion Usbasp device
uint16_t LedDeviceHyperionUsbasp::_usbVendorId = 0x16c0;
uint16_t LedDeviceHyperionUsbasp::_usbProductId = 0x05dc;
QString LedDeviceHyperionUsbasp::_usbProductDescription = "Hyperion led controller";
LedDeviceHyperionUsbasp::LedDeviceHyperionUsbasp(const QJsonObject &deviceConfig)
: LedDevice()
, _libusbContext(nullptr)
, _deviceHandle(nullptr)
{
init(deviceConfig);
}
LedDeviceHyperionUsbasp::~LedDeviceHyperionUsbasp()
{
if (_deviceHandle != nullptr)
{
libusb_release_interface(_deviceHandle, 0);
libusb_attach_kernel_driver(_deviceHandle, 0);
libusb_close(_deviceHandle);
_deviceHandle = nullptr;
}
if (_libusbContext != nullptr)
{
libusb_exit(_libusbContext);
_libusbContext = nullptr;
}
}
bool LedDeviceHyperionUsbasp::init(const QJsonObject &deviceConfig)
{
LedDevice::init(deviceConfig);
QString ledType = deviceConfig["ledType"].toString("ws2801");
if (ledType != "ws2801" && ledType != "ws2812")
{
throw std::runtime_error("HyperionUsbasp: invalid ledType; must be 'ws2801' or 'ws2812'.");
}
_writeLedsCommand = (ledType == "ws2801") ? CMD_WRITE_WS2801 : CMD_WRITE_WS2812;
return true;
}
LedDevice* LedDeviceHyperionUsbasp::construct(const QJsonObject &deviceConfig)
{
return new LedDeviceHyperionUsbasp(deviceConfig);
}
int LedDeviceHyperionUsbasp::open()
{
int error;
// initialize the usb context
if ((error = libusb_init(&_libusbContext)) != LIBUSB_SUCCESS)
{
Error(_log, "Error while initializing USB context(%d):%s", error, libusb_error_name(error));
_libusbContext = nullptr;
return -1;
}
//libusb_set_debug(_libusbContext, 3);
Debug(_log, "USB context initialized");
// retrieve the list of usb devices
libusb_device ** deviceList;
ssize_t deviceCount = libusb_get_device_list(_libusbContext, &deviceList);
// iterate the list of devices
for (ssize_t i = 0 ; i < deviceCount; ++i)
{
// try to open and initialize the device
error = testAndOpen(deviceList[i]);
if (error == 0)
{
// a device was sucessfully opened. break from list
break;
}
}
// free the device list
libusb_free_device_list(deviceList, 1);
if (_deviceHandle == nullptr)
{
Error(_log, "No %s has been found", QSTRING_CSTR(_usbProductDescription));
}
return _deviceHandle == nullptr ? -1 : 0;
}
int LedDeviceHyperionUsbasp::testAndOpen(libusb_device * device)
{
libusb_device_descriptor deviceDescriptor;
int error = libusb_get_device_descriptor(device, &deviceDescriptor);
if (error != LIBUSB_SUCCESS)
{
Error(_log, "Error while retrieving device descriptor(%d): %s", error, libusb_error_name(error));
return -1;
}
if (deviceDescriptor.idVendor == _usbVendorId &&
deviceDescriptor.idProduct == _usbProductId &&
deviceDescriptor.iProduct != 0 &&
getString(device, deviceDescriptor.iProduct) == _usbProductDescription)
{
// get the hardware address
int busNumber = libusb_get_bus_number(device);
int addressNumber = libusb_get_device_address(device);
Info(_log, "%s found: bus=%d address=%d", QSTRING_CSTR(_usbProductDescription), busNumber, addressNumber);
try
{
_deviceHandle = openDevice(device);
Info(_log, "%s successfully opened", QSTRING_CSTR(_usbProductDescription) );
return 0;
}
catch(int e)
{
_deviceHandle = nullptr;
Error(_log, "Unable to open %s. Searching for other device(%d): %s", QSTRING_CSTR(_usbProductDescription), e, libusb_error_name(e));
}
}
return -1;
}
int LedDeviceHyperionUsbasp::write(const std::vector<ColorRgb> &ledValues)
{
int nbytes = libusb_control_transfer(
_deviceHandle, // device handle
LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE | LIBUSB_ENDPOINT_OUT, // request type
_writeLedsCommand, // request
0, // value
0, // index
(uint8_t *) ledValues.data(), // data
(3*_ledCount) & 0xffff, // length
5000); // timeout
// Disabling interupts for a little while on the device results in a PIPE error. All seems to keep functioning though...
if(nbytes < 0 && nbytes != LIBUSB_ERROR_PIPE)
{
Error(_log, "Error while writing data to %s (%s)", QSTRING_CSTR(_usbProductDescription), libusb_error_name(nbytes));
return -1;
}
return 0;
}
libusb_device_handle * LedDeviceHyperionUsbasp::openDevice(libusb_device *device)
{
Logger * log = Logger::getInstance("LedDevice");
libusb_device_handle * handle = nullptr;
int error = libusb_open(device, &handle);
if (error != LIBUSB_SUCCESS)
{
Error(log, "unable to open device(%d): %s",error,libusb_error_name(error));
throw error;
}
// detach kernel driver if it is active
if (libusb_kernel_driver_active(handle, 0) == 1)
{
error = libusb_detach_kernel_driver(handle, 0);
if (error != LIBUSB_SUCCESS)
{
Error(log, "unable to detach kernel driver(%d): %s",error,libusb_error_name(error));
libusb_close(handle);
throw error;
}
}
error = libusb_claim_interface(handle, 0);
if (error != LIBUSB_SUCCESS)
{
Error(log, "unable to claim interface(%d): %s", error, libusb_error_name(error));
libusb_attach_kernel_driver(handle, 0);
libusb_close(handle);
throw error;
}
return handle;
}
QString LedDeviceHyperionUsbasp::getString(libusb_device * device, int stringDescriptorIndex)
{
libusb_device_handle * handle = nullptr;
int error = libusb_open(device, &handle);
if (error != LIBUSB_SUCCESS)
{
throw error;
}
char buffer[256];
error = libusb_get_string_descriptor_ascii(handle, stringDescriptorIndex, reinterpret_cast<unsigned char *>(buffer), sizeof(buffer));
if (error <= 0)
{
libusb_close(handle);
throw error;
}
libusb_close(handle);
return QString(QByteArray(buffer, error));
}

View File

@@ -0,0 +1,88 @@
#pragma once
// stl includes
#include <vector>
#include <cstdint>
// libusb include
#include <libusb.h>
// Hyperion includes
#include <leddevice/LedDevice.h>
///
/// LedDevice implementation for a USBasp programmer with modified firmware (https://github.com/poljvd/hyperion-usbasp)
///
class LedDeviceHyperionUsbasp : public LedDevice
{
public:
// Commands to the Device
enum Commands {
CMD_WRITE_WS2801 = 10,
CMD_WRITE_WS2812 = 11
};
///
/// Constructs specific LedDevice
///
/// @param deviceConfig json device config
///
LedDeviceHyperionUsbasp(const QJsonObject &deviceConfig);
///
/// Sets configuration
///
/// @param deviceConfig the json device config
/// @return true if success
bool init(const QJsonObject &deviceConfig);
/// constructs leddevice
static LedDevice* construct(const QJsonObject &deviceConfig);
///
/// Destructor of the LedDevice; closes the output device if it is open
///
virtual ~LedDeviceHyperionUsbasp();
///
/// Opens and configures the output device
///
/// @return Zero on succes else negative
///
int open();
protected:
///
/// 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);
///
/// Test if the device is a Hyperion Usbasp device
///
/// @return Zero on succes else negative
///
int testAndOpen(libusb_device * device);
static libusb_device_handle * openDevice(libusb_device * device);
static QString getString(libusb_device * device, int stringDescriptorIndex);
/// command to write the leds
uint8_t _writeLedsCommand;
/// libusb context
libusb_context * _libusbContext;
/// libusb device handle
libusb_device_handle * _deviceHandle;
/// Usb device identifiers
static uint16_t _usbVendorId;
static uint16_t _usbProductId;
static QString _usbProductDescription;
};

View File

@@ -0,0 +1,375 @@
// stl includes
#include <exception>
#include <cstring>
// Local Hyperion includes
#include "LedDeviceLightpack.h"
// from USB_ID.h (http://code.google.com/p/light-pack/source/browse/CommonHeaders/USB_ID.h)
#define USB_OLD_VENDOR_ID 0x03EB
#define USB_OLD_PRODUCT_ID 0x204F
#define USB_VENDOR_ID 0x1D50
#define USB_PRODUCT_ID 0x6022
#define LIGHTPACK_INTERFACE 0
// from commands.h (http://code.google.com/p/light-pack/source/browse/CommonHeaders/commands.h)
// Commands to device, sends it in first byte of data[]
enum COMMANDS{
CMD_UPDATE_LEDS = 1,
CMD_OFF_ALL,
CMD_SET_TIMER_OPTIONS,
CMD_SET_PWM_LEVEL_MAX_VALUE, /* deprecated */
CMD_SET_SMOOTH_SLOWDOWN,
CMD_SET_BRIGHTNESS,
CMD_NOP = 0x0F
};
// from commands.h (http://code.google.com/p/light-pack/source/browse/CommonHeaders/commands.h)
enum DATA_VERSION_INDEXES{
INDEX_FW_VER_MAJOR = 1,
INDEX_FW_VER_MINOR
};
LedDeviceLightpack::LedDeviceLightpack(const QString & serialNumber)
: LedDevice()
, _libusbContext(nullptr)
, _deviceHandle(nullptr)
, _busNumber(-1)
, _addressNumber(-1)
, _serialNumber(serialNumber)
, _firmwareVersion({-1,-1})
, _bitsPerChannel(-1)
, _hwLedCount(-1)
{
}
LedDeviceLightpack::LedDeviceLightpack(const QJsonObject &deviceConfig)
: LedDevice()
{
init(deviceConfig);
}
LedDeviceLightpack::~LedDeviceLightpack()
{
if (_deviceHandle != nullptr)
{
libusb_release_interface(_deviceHandle, LIGHTPACK_INTERFACE);
libusb_attach_kernel_driver(_deviceHandle, LIGHTPACK_INTERFACE);
libusb_close(_deviceHandle);
_deviceHandle = nullptr;
}
if (_libusbContext != nullptr)
{
libusb_exit(_libusbContext);
_libusbContext = nullptr;
}
}
bool LedDeviceLightpack::init(const QJsonObject &deviceConfig)
{
LedDevice::init(deviceConfig);
_serialNumber = deviceConfig["output"].toString("");
return true;
}
LedDevice* LedDeviceLightpack::construct(const QJsonObject &deviceConfig)
{
return new LedDeviceLightpack(deviceConfig);
}
int LedDeviceLightpack::open()
{
int error;
// initialize the usb context
if ((error = libusb_init(&_libusbContext)) != LIBUSB_SUCCESS)
{
Error(_log, "Error while initializing USB context(%d): %s", error, libusb_error_name(error));
_libusbContext = nullptr;
return -1;
}
//libusb_set_debug(_libusbContext, 3);
Debug(_log, "USB context initialized");
// retrieve the list of usb devices
libusb_device ** deviceList;
ssize_t deviceCount = libusb_get_device_list(_libusbContext, &deviceList);
// iterate the list of devices
for (ssize_t i = 0 ; i < deviceCount; ++i)
{
// try to open and initialize the device
error = testAndOpen(deviceList[i], _serialNumber);
if (error == 0)
{
// a device was sucessfully opened. break from list
break;
}
}
// free the device list
libusb_free_device_list(deviceList, 1);
if (_deviceHandle == nullptr)
{
if (_serialNumber.isEmpty())
{
Warning(_log, "No Lightpack device has been found");
}
else
{
Error(_log,"No Lightpack device has been found with serial %s", QSTRING_CSTR(_serialNumber));
}
}
return _deviceHandle == nullptr ? -1 : 0;
}
int LedDeviceLightpack::testAndOpen(libusb_device * device, const QString & requestedSerialNumber)
{
libusb_device_descriptor deviceDescriptor;
int error = libusb_get_device_descriptor(device, &deviceDescriptor);
if (error != LIBUSB_SUCCESS)
{
Error(_log, "Error while retrieving device descriptor(%d): %s", error, libusb_error_name(error));
return -1;
}
if ((deviceDescriptor.idVendor == USB_VENDOR_ID && deviceDescriptor.idProduct == USB_PRODUCT_ID) ||
(deviceDescriptor.idVendor == USB_OLD_VENDOR_ID && deviceDescriptor.idProduct == USB_OLD_PRODUCT_ID))
{
Info(_log, "Found a lightpack device. Retrieving more information...");
// get the hardware address
int busNumber = libusb_get_bus_number(device);
int addressNumber = libusb_get_device_address(device);
// get the serial number
QString serialNumber;
if (deviceDescriptor.iSerialNumber != 0)
{
try
{
serialNumber = LedDeviceLightpack::getString(device, deviceDescriptor.iSerialNumber);
}
catch (int e)
{
Error(_log, "unable to retrieve serial number from Lightpack device(%d): %s", e, libusb_error_name(e));
serialNumber = "";
}
}
Debug(_log,"Lightpack device found: bus=%d address=%d serial=%s", busNumber, addressNumber, QSTRING_CSTR(serialNumber));
// check if this is the device we are looking for
if (requestedSerialNumber.isEmpty() || requestedSerialNumber == serialNumber)
{
// This is it!
try
{
_deviceHandle = openDevice(device);
_serialNumber = serialNumber;
_busNumber = busNumber;
_addressNumber = addressNumber;
Info(_log, "Lightpack device successfully opened");
// get the firmware version
uint8_t buffer[256];
error = libusb_control_transfer(
_deviceHandle,
LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_INTERFACE,
0x01,
0x0100,
0,
buffer, sizeof(buffer), 1000);
if (error < 3)
{
Error(_log, "Unable to retrieve firmware version number from Lightpack device(%d): %s", error, libusb_error_name(error));
}
else
{
_firmwareVersion.majorVersion = buffer[INDEX_FW_VER_MAJOR];
_firmwareVersion.minorVersion = buffer[INDEX_FW_VER_MINOR];
}
// FOR TESTING PURPOSE: FORCE MAJOR VERSION TO 6
_firmwareVersion.majorVersion = 6;
// disable smoothing of the chosen device
disableSmoothing();
// determine the number of leds
if (_firmwareVersion.majorVersion == 4)
{
_hwLedCount = 8;
}
else
{
_hwLedCount = 10;
}
// determine the bits per channel
if (_firmwareVersion.majorVersion == 6)
{
// maybe also or version 7? The firmware suggest this is only for 6... (2013-11-13)
_bitsPerChannel = 12;
}
else
{
_bitsPerChannel = 8;
}
// set the led buffer size (command + 6 bytes per led)
_ledBuffer = std::vector<uint8_t>(1 + _hwLedCount * 6, 0);
_ledBuffer[0] = CMD_UPDATE_LEDS;
// return success
Debug(_log, "Lightpack device opened: bus=%d address=%d serial=%s version=%s.%s.", _busNumber, _addressNumber, QSTRING_CSTR(_serialNumber), _firmwareVersion.majorVersion, _firmwareVersion.minorVersion );
return 0;
}
catch(int e)
{
_deviceHandle = nullptr;
Warning(_log, "Unable to open Lightpack device. Searching for other device(%d): %s", e, libusb_error_name(e));
}
}
}
return -1;
}
int LedDeviceLightpack::write(const std::vector<ColorRgb> &ledValues)
{
return write(ledValues.data(), ledValues.size());
}
int LedDeviceLightpack::write(const ColorRgb * ledValues, int size)
{
int count = qMin(_hwLedCount, _ledCount);
for (int i = 0; i < count ; ++i)
{
const ColorRgb & color = ledValues[i];
// copy the most significant bits of the rgb values to the first three bytes
// offset 1 to accomodate for the command byte
_ledBuffer[6*i+1] = color.red;
_ledBuffer[6*i+2] = color.green;
_ledBuffer[6*i+3] = color.blue;
// leave the next three bytes on zero...
// 12-bit values having zeros in the lowest 4 bits which is almost correct, but it saves extra
// switches to determine what to do and some bit shuffling
}
int error = writeBytes(_ledBuffer.data(), _ledBuffer.size());
return error >= 0 ? 0 : error;
}
int LedDeviceLightpack::switchOff()
{
unsigned char buf[1] = {CMD_OFF_ALL};
return writeBytes(buf, sizeof(buf)) == sizeof(buf);
}
const QString &LedDeviceLightpack::getSerialNumber() const
{
return _serialNumber;
}
int LedDeviceLightpack::getLedCount() const
{
return _ledCount;
}
int LedDeviceLightpack::writeBytes(uint8_t *data, int size)
{
// std::cout << "Writing " << size << " bytes: ";
// for (int i = 0; i < size ; ++i) printf("%02x ", data[i]);
// std::cout << std::endl;
int error = libusb_control_transfer(_deviceHandle,
LIBUSB_ENDPOINT_OUT | LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_INTERFACE,
0x09,
(2 << 8),
0x00,
data, size, 1000);
if (error == size)
{
return 0;
}
Error(_log, "Unable to write %d bytes to Lightpack device(%d): %s", size, error, libusb_error_name(error));
return error;
}
int LedDeviceLightpack::disableSmoothing()
{
unsigned char buf[2] = {CMD_SET_SMOOTH_SLOWDOWN, 0};
return writeBytes(buf, sizeof(buf)) == sizeof(buf);
}
libusb_device_handle * LedDeviceLightpack::openDevice(libusb_device *device)
{
libusb_device_handle * handle = nullptr;
Logger * log = Logger::getInstance("LedDevice");
int error = libusb_open(device, &handle);
if (error != LIBUSB_SUCCESS)
{
Error(log, "unable to open device(%d): %s", error, libusb_error_name(error));
throw error;
}
// detach kernel driver if it is active
if (libusb_kernel_driver_active(handle, LIGHTPACK_INTERFACE) == 1)
{
error = libusb_detach_kernel_driver(handle, LIGHTPACK_INTERFACE);
if (error != LIBUSB_SUCCESS)
{
Error(log, "unable to detach kernel driver(%d): %s", error, libusb_error_name(error));
libusb_close(handle);
throw error;
}
}
error = libusb_claim_interface(handle, LIGHTPACK_INTERFACE);
if (error != LIBUSB_SUCCESS)
{
Error(log, "unable to claim interface(%d): %s", error, libusb_error_name(error));
libusb_attach_kernel_driver(handle, LIGHTPACK_INTERFACE);
libusb_close(handle);
throw error;
}
return handle;
}
QString LedDeviceLightpack::getString(libusb_device * device, int stringDescriptorIndex)
{
libusb_device_handle * handle = nullptr;
int error = libusb_open(device, &handle);
if (error != LIBUSB_SUCCESS)
{
throw error;
}
char buffer[256];
error = libusb_get_string_descriptor_ascii(handle, stringDescriptorIndex, reinterpret_cast<unsigned char *>(buffer), sizeof(buffer));
if (error <= 0)
{
libusb_close(handle);
throw error;
}
libusb_close(handle);
return QString(QByteArray(buffer, error));
}

View File

@@ -0,0 +1,131 @@
#pragma once
// stl includes
#include <cstdint>
// libusb include
#include <libusb.h>
// Hyperion includes
#include <leddevice/LedDevice.h>
///
/// LedDevice implementation for a lightpack device (http://code.google.com/p/light-pack/)
///
class LedDeviceLightpack : public LedDevice
{
public:
///
/// Constructs the LedDeviceLightpack
///
/// @param serialNumber serial output device
///
LedDeviceLightpack(const QString & serialNumber = "");
///
/// Constructs specific LedDevice
///
/// @param deviceConfig json device config
///
LedDeviceLightpack(const QJsonObject &deviceConfig);
///
/// Sets configuration
///
/// @param deviceConfig the json device config
/// @return true if success
bool init(const QJsonObject &deviceConfig);
/// constructs leddevice
static LedDevice* construct(const QJsonObject &deviceConfig);
///
/// Destructor of the LedDevice; closes the output device if it is open
///
virtual ~LedDeviceLightpack();
///
/// Opens and configures the output device
///
/// @return Zero on succes else negative
///
int open();
///
/// Writes the RGB-Color values to the leds.
///
/// @param[in] ledValues Array of RGB values
/// @param[in] size The number of RGB values
///
/// @return Zero on success else negative
///
int write(const ColorRgb * ledValues, int size);
///
/// Switch the leds off
///
/// @return Zero on success else negative
///
virtual int switchOff();
/// Get the serial of the Lightpack
const QString & getSerialNumber() const;
/// Get the number of leds
int getLedCount() const;
private:
///
/// 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);
///
/// Test if the device is a (or the) lightpack we are looking for
///
/// @return Zero on succes else negative
///
int testAndOpen(libusb_device * device, const QString & requestedSerialNumber);
/// write bytes to the device
int writeBytes(uint8_t *data, int size);
/// Disable the internal smoothing on the Lightpack device
int disableSmoothing();
struct Version
{
int majorVersion;
int minorVersion;
};
static libusb_device_handle * openDevice(libusb_device * device);
static QString getString(libusb_device * device, int stringDescriptorIndex);
/// libusb context
libusb_context * _libusbContext;
/// libusb device handle
libusb_device_handle * _deviceHandle;
/// harware bus number
int _busNumber;
/// hardware address number
int _addressNumber;
/// device serial number
QString _serialNumber;
/// firmware version of the device
Version _firmwareVersion;
/// the number of bits per channel
int _bitsPerChannel;
/// count of real hardware leds
int _hwLedCount;
};

View File

@@ -0,0 +1,197 @@
// stl includes
#include <exception>
#include <cstring>
#include <algorithm>
// Local Hyperion includes
#include "LedDeviceMultiLightpack.h"
// from USB_ID.h (http://code.google.com/p/light-pack/source/browse/CommonHeaders/USB_ID.h)
#define USB_OLD_VENDOR_ID 0x03EB
#define USB_OLD_PRODUCT_ID 0x204F
#define USB_VENDOR_ID 0x1D50
#define USB_PRODUCT_ID 0x6022
bool compareLightpacks(LedDeviceLightpack * lhs, LedDeviceLightpack * rhs)
{
return lhs->getSerialNumber() < rhs->getSerialNumber();
}
LedDeviceMultiLightpack::LedDeviceMultiLightpack(const QJsonObject &deviceConfig)
: LedDevice()
, _lightpacks()
{
LedDevice::init(deviceConfig);
}
LedDeviceMultiLightpack::~LedDeviceMultiLightpack()
{
for (LedDeviceLightpack * device : _lightpacks)
{
delete device;
}
}
LedDevice* LedDeviceMultiLightpack::construct(const QJsonObject &deviceConfig)
{
return new LedDeviceMultiLightpack(deviceConfig);
}
int LedDeviceMultiLightpack::open()
{
// retrieve a list with Lightpack serials
QStringList serialList = getLightpackSerials();
// sort the list of Lightpacks based on the serial to get a fixed order
std::sort(_lightpacks.begin(), _lightpacks.end(), compareLightpacks);
// open each lightpack device
foreach (auto serial , serialList)
{
LedDeviceLightpack * device = new LedDeviceLightpack(serial);
int error = device->open();
if (error == 0)
{
_lightpacks.push_back(device);
}
else
{
Error(_log, "Error while creating Lightpack device with serial %s", QSTRING_CSTR(serial));
delete device;
}
}
if (_lightpacks.size() == 0)
{
Warning(_log, "No Lightpack devices were found");
}
else
{
Info(_log, "%d Lightpack devices were found", _lightpacks.size());
}
return _lightpacks.size() > 0 ? 0 : -1;
}
int LedDeviceMultiLightpack::write(const std::vector<ColorRgb> &ledValues)
{
const ColorRgb * data = ledValues.data();
int size = ledValues.size();
for (LedDeviceLightpack * device : _lightpacks)
{
int count = qMin(device->getLedCount(), size);
if (count > 0)
{
device->write(data, count);
data += count;
size -= count;
}
else
{
Warning(_log, "Unable to write data to Lightpack device: no more led data available");
}
}
return 0;
}
int LedDeviceMultiLightpack::switchOff()
{
for (LedDeviceLightpack * device : _lightpacks)
{
device->switchOff();
}
return 0;
}
QStringList LedDeviceMultiLightpack::getLightpackSerials()
{
QStringList serialList;
Logger * log = Logger::getInstance("LedDevice");
Debug(log, "Getting list of Lightpack serials");
// initialize the usb context
libusb_context * libusbContext;
int error = libusb_init(&libusbContext);
if (error != LIBUSB_SUCCESS)
{
Error(log,"Error while initializing USB context(%d): %s", error, libusb_error_name(error));
libusbContext = nullptr;
return serialList;
}
//libusb_set_debug(_libusbContext, 3);
Info(log, "USB context initialized in multi Lightpack device");
// retrieve the list of usb devices
libusb_device ** deviceList;
ssize_t deviceCount = libusb_get_device_list(libusbContext, &deviceList);
// iterate the list of devices
for (ssize_t i = 0 ; i < deviceCount; ++i)
{
libusb_device_descriptor deviceDescriptor;
error = libusb_get_device_descriptor(deviceList[i], &deviceDescriptor);
if (error != LIBUSB_SUCCESS)
{
Error(log, "Error while retrieving device descriptor(%d): %s", error, libusb_error_name(error));
continue;
}
if ((deviceDescriptor.idVendor == USB_VENDOR_ID && deviceDescriptor.idProduct == USB_PRODUCT_ID) ||
(deviceDescriptor.idVendor == USB_OLD_VENDOR_ID && deviceDescriptor.idProduct == USB_OLD_PRODUCT_ID))
{
Info(log, "Found a lightpack device. Retrieving serial...");
// get the serial number
QString serialNumber;
if (deviceDescriptor.iSerialNumber != 0)
{
try
{
serialNumber = LedDeviceMultiLightpack::getString(deviceList[i], deviceDescriptor.iSerialNumber);
}
catch (int e)
{
Error(log,"Unable to retrieve serial number(%d): %s", e, libusb_error_name(e));
continue;
}
}
Error(log, "Lightpack device found with serial %s", QSTRING_CSTR(serialNumber));;
serialList.append(serialNumber);
}
}
// free the device list
libusb_free_device_list(deviceList, 1);
libusb_exit(libusbContext);
return serialList;
}
QString LedDeviceMultiLightpack::getString(libusb_device * device, int stringDescriptorIndex)
{
libusb_device_handle * handle = nullptr;
int error = libusb_open(device, &handle);
if (error != LIBUSB_SUCCESS)
{
throw error;
}
char buffer[256];
error = libusb_get_string_descriptor_ascii(handle, stringDescriptorIndex, reinterpret_cast<unsigned char *>(buffer), sizeof(buffer));
if (error <= 0)
{
libusb_close(handle);
throw error;
}
libusb_close(handle);
return QString(QByteArray(buffer, error));
}

View File

@@ -0,0 +1,64 @@
#pragma once
// stl includes
#include <vector>
#include <cstdint>
#include <QStringList>
#include <QString>
// libusb include
#include <libusb.h>
// Hyperion includes
#include <leddevice/LedDevice.h>
#include "LedDeviceLightpack.h"
///
/// LedDevice implementation for multiple lightpack devices
///
class LedDeviceMultiLightpack : public LedDevice
{
public:
///
/// Constructs specific LedDevice
///
LedDeviceMultiLightpack(const QJsonObject &);
///
/// Destructor of the LedDevice; closes the output device if it is open
///
virtual ~LedDeviceMultiLightpack();
/// constructs leddevice
static LedDevice* construct(const QJsonObject &deviceConfig);
///
/// Opens and configures the output device7
///
/// @return Zero on succes else negative
///
int open();
///
/// Switch the leds off
///
/// @return Zero on success else negative
///
virtual int switchOff();
private:
///
/// 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);
static QStringList getLightpackSerials();
static QString getString(libusb_device * device, int stringDescriptorIndex);
/// buffer for led data
std::vector<LedDeviceLightpack *> _lightpacks;
};

View File

@@ -0,0 +1,34 @@
#include "LedDevicePaintpack.h"
// Use out report HID device
LedDevicePaintpack::LedDevicePaintpack(const QJsonObject &deviceConfig)
: ProviderHID()
{
ProviderHID::init(deviceConfig);
_useFeature = false;
_ledBuffer.resize(_ledRGBCount + 2, uint8_t(0));
_ledBuffer[0] = 3;
_ledBuffer[1] = 0;
}
LedDevice* LedDevicePaintpack::construct(const QJsonObject &deviceConfig)
{
return new LedDevicePaintpack(deviceConfig);
}
int LedDevicePaintpack::write(const std::vector<ColorRgb> & ledValues)
{
auto bufIt = _ledBuffer.begin()+2;
for (const ColorRgb & color : ledValues)
{
*bufIt = color.red;
++bufIt;
*bufIt = color.green;
++bufIt;
*bufIt = color.blue;
++bufIt;
}
return writeBytes(_ledBuffer.size(), _ledBuffer.data());
}

View File

@@ -0,0 +1,31 @@
#pragma once
// Hyperion includes
#include "ProviderHID.h"
///
/// LedDevice implementation for a paintpack device ()
///
class LedDevicePaintpack : public ProviderHID
{
public:
///
/// Constructs specific LedDevice
///
/// @param deviceConfig json device config
///
LedDevicePaintpack(const QJsonObject &deviceConfig);
/// constructs leddevice
static LedDevice* construct(const QJsonObject &deviceConfig);
private:
///
/// 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);
};

View File

@@ -0,0 +1,27 @@
#include "LedDeviceRawHID.h"
// Use feature report HID device
LedDeviceRawHID::LedDeviceRawHID(const QJsonObject &deviceConfig)
: ProviderHID()
{
ProviderHID::init(deviceConfig);
_useFeature = true;
_ledBuffer.resize(_ledRGBCount);
}
LedDevice* LedDeviceRawHID::construct(const QJsonObject &deviceConfig)
{
return new LedDeviceRawHID(deviceConfig);
}
int LedDeviceRawHID::write(const std::vector<ColorRgb> & ledValues)
{
// write data
memcpy(_ledBuffer.data(), ledValues.data(), _ledRGBCount);
return writeBytes(_ledBuffer.size(), _ledBuffer.data());
}
void LedDeviceRawHID::rewriteLeds()
{
writeBytes(_ledBuffer.size(), _ledBuffer.data());
}

View File

@@ -0,0 +1,38 @@
#pragma once
// Qt includes
#include <QTimer>
// hyperion include
#include "ProviderHID.h"
///
/// Implementation of the LedDevice interface for writing to an RawHID led device.
///
class LedDeviceRawHID : public ProviderHID
{
public:
///
/// Constructs specific LedDevice
///
/// @param deviceConfig json device config
///
LedDeviceRawHID(const QJsonObject &deviceConfig);
/// constructs leddevice
static LedDevice* construct(const QJsonObject &deviceConfig);
private slots:
/// Write the last data to the leds again
void rewriteLeds();
private:
///
/// Writes the led color values to the led-device
///
/// @param ledValues The color-value per led
/// @return Zero on succes else negative
///
virtual int write(const std::vector<ColorRgb> & ledValues);
};

View File

@@ -0,0 +1,164 @@
// STL includes
#include <cstring>
#include <iostream>
// Qt includes
#include <QTimer>
// Local Hyperion includes
#include "ProviderHID.h"
ProviderHID::ProviderHID()
: _useFeature(false)
, _deviceHandle(nullptr)
, _blockedForDelay(false)
{
}
ProviderHID::~ProviderHID()
{
if (_deviceHandle != nullptr)
{
hid_close(_deviceHandle);
_deviceHandle = nullptr;
}
hid_exit();
}
bool ProviderHID::init(const QJsonObject &deviceConfig)
{
LedDevice::init(deviceConfig);
_delayAfterConnect_ms = deviceConfig["delayAfterConnect"].toInt(0);
auto VendorIdString = deviceConfig["VID"].toString("0x2341").toStdString();
auto ProductIdString = deviceConfig["PID"].toString("0x8036").toStdString();
// Convert HEX values to integer
_VendorId = std::stoul(VendorIdString, nullptr, 16);
_ProductId = std::stoul(ProductIdString, nullptr, 16);
return true;
}
int ProviderHID::open()
{
// Initialize the usb context
int error = hid_init();
if (error != 0)
{
Error(_log, "Error while initializing the hidapi context");
return -1;
}
Debug(_log,"Hidapi initialized");
// Open the device
Info(_log, "Opening device: VID %04hx PID %04hx\n", _VendorId, _ProductId);
_deviceHandle = hid_open(_VendorId, _ProductId, nullptr);
if (_deviceHandle == nullptr)
{
// Failed to open the device
Error(_log,"Failed to open HID device. Maybe your PID/VID setting is wrong? Make sure to add a udev rule/use sudo.");
// http://www.signal11.us/oss/hidapi/
/*
std::cout << "Showing a list of all available HID devices:" << std::endl;
auto devs = hid_enumerate(0x00, 0x00);
auto cur_dev = devs;
while (cur_dev) {
printf("Device Found\n type: %04hx %04hx\n path: %s\n serial_number: %ls",
cur_dev->vendor_id, cur_dev->product_id, cur_dev->path, cur_dev->serial_number);
printf("\n");
printf(" Manufacturer: %ls\n", cur_dev->manufacturer_string);
printf(" Product: %ls\n", cur_dev->product_string);
printf("\n");
cur_dev = cur_dev->next;
}
hid_free_enumeration(devs);
*/
return -1;
}
else
{
Info(_log,"Opened HID device successful");
}
// Wait after device got opened if enabled
if (_delayAfterConnect_ms > 0)
{
_blockedForDelay = true;
QTimer::singleShot(_delayAfterConnect_ms, this, SLOT(unblockAfterDelay()));
Debug(_log, "Device blocked for %d ms", _delayAfterConnect_ms);
}
return 0;
}
int ProviderHID::writeBytes(const unsigned size, const uint8_t * data)
{
if (_blockedForDelay) {
return 0;
}
if (_deviceHandle == nullptr)
{
// try to reopen
auto status = open();
if(status < 0){
// Try again in 3 seconds
int delay_ms = 3000;
_blockedForDelay = true;
QTimer::singleShot(delay_ms, this, SLOT(unblockAfterDelay()));
Debug(_log,"Device blocked for %d ms", delay_ms);
}
// Return here, to not write led data if the device should be blocked after connect
return status;
}
// Prepend report ID to the buffer
uint8_t ledData[size + 1];
ledData[0] = 0; // Report ID
memcpy(ledData + 1, data, size_t(size));
// Send data via feature or out report
int ret;
if(_useFeature){
ret = hid_send_feature_report(_deviceHandle, ledData, size + 1);
}
else{
ret = hid_write(_deviceHandle, ledData, size + 1);
}
// Handle first error
if(ret < 0){
Error(_log,"Failed to write to HID device.");
// Try again
if(_useFeature){
ret = hid_send_feature_report(_deviceHandle, ledData, size + 1);
}
else{
ret = hid_write(_deviceHandle, ledData, size + 1);
}
// Writing failed again, device might have disconnected
if(ret < 0){
Error(_log,"Failed to write to HID device.");
hid_close(_deviceHandle);
_deviceHandle = nullptr;
}
}
return ret;
}
void ProviderHID::unblockAfterDelay()
{
Debug(_log,"Device unblocked");
_blockedForDelay = false;
}

View File

@@ -0,0 +1,69 @@
#pragma once
#include <QObject>
// libusb include
#include <hidapi/hidapi.h>
// Leddevice includes
#include <leddevice/LedDevice.h>
///
/// The ProviderHID implements an abstract base-class for LedDevices using an HID-device.
///
class ProviderHID : public LedDevice
{
Q_OBJECT
public:
///
/// Constructs specific LedDevice
///
ProviderHID();
///
/// Destructor of the LedDevice; closes the output device if it is open
///
virtual ~ProviderHID();
///
/// Sets configuration
///
/// @param deviceConfig the json device config
/// @return true if success
virtual bool init(const QJsonObject &deviceConfig);
///
/// Opens and configures the output device
///
/// @return Zero on succes else negative
///
int open();
protected:
/**
* Writes the given bytes to the HID-device and
*
* @param[in] size The length of the data
* @param[in] data The data
*
* @return Zero on succes else negative
*/
int writeBytes(const unsigned size, const uint8_t *data);
// HID VID and PID
unsigned short _VendorId;
unsigned short _ProductId;
bool _useFeature;
/// libusb device handle
hid_device * _deviceHandle;
/// Sleep after the connect before continuing
int _delayAfterConnect_ms;
bool _blockedForDelay;
private slots:
/// Unblock the device after a connection delay
void unblockAfterDelay();
};

View File

@@ -0,0 +1,271 @@
// code currently disabled. must be ported to new structure
#if 0
// stl includes
#include <exception>
#include <cstring>
#include <wchar.h>
// Local Hyperion includes
#include "LedDeviceLightpack-hidapi.h"
// from USB_ID.h (http://code.google.com/p/light-pack/source/browse/CommonHeaders/USB_ID.h)
#define USB_OLD_VENDOR_ID 0x03EB
#define USB_OLD_PRODUCT_ID 0x204F
#define USB_VENDOR_ID 0x1D50
#define USB_PRODUCT_ID 0x6022
#define LIGHTPACK_INTERFACE 0
// from commands.h (http://code.google.com/p/light-pack/source/browse/CommonHeaders/commands.h)
// Commands to device, sends it in first byte of data[]
enum COMMANDS {
CMD_UPDATE_LEDS = 1,
CMD_OFF_ALL,
CMD_SET_TIMER_OPTIONS,
CMD_SET_PWM_LEVEL_MAX_VALUE, /* deprecated */
CMD_SET_SMOOTH_SLOWDOWN,
CMD_SET_BRIGHTNESS,
CMD_NOP = 0x0F
};
// from commands.h (http://code.google.com/p/light-pack/source/browse/CommonHeaders/commands.h)
enum DATA_VERSION_INDEXES {
INDEX_FW_VER_MAJOR = 1,
INDEX_FW_VER_MINOR
};
LedDeviceLightpackHidapi::LedDeviceLightpackHidapi()
: LedDevice()
, _deviceHandle(nullptr)
, _serialNumber("")
, _firmwareVersion({-1,-1})
, _bitsPerChannel(-1)
, _hwLedCount(-1)
{
}
LedDeviceLightpackHidapi::~LedDeviceLightpackHidapi()
{
if (_deviceHandle != nullptr)
{
hid_close(_deviceHandle);
_deviceHandle = nullptr;
}
// TODO: Should be called to avoid memory loss, but only at the end of the application
//hid_exit();
}
int LedDeviceLightpackHidapi::open(const std::string & serialNumber)
{
// initialize the usb context
int error = hid_init();
if (error != 0)
{
Error(_log, "Error while initializing the hidapi context");
return -1;
}
Info("Hidapi initialized");
// retrieve the list of usb devices
hid_device_info * deviceList = hid_enumerate(0x0, 0x0);
// iterate the list of devices
for (hid_device_info * deviceInfo = deviceList; deviceInfo != nullptr; deviceInfo = deviceInfo->next)
{
// try to open and initialize the device
error = testAndOpen(deviceInfo, serialNumber);
if (error == 0)
{
// a device was sucessfully opened. break from list
break;
}
}
// free the device list
hid_free_enumeration(deviceList);
if (_deviceHandle == nullptr)
{
if (_serialNumber.empty())
{
Error(_log, "No Lightpack device has been found");
}
else
{
Error(_log, "No Lightpack device has been found with serial %s", _serialNumber);
}
}
return _deviceHandle == nullptr ? -1 : 0;
}
int LedDeviceLightpackHidapi::testAndOpen(hid_device_info *device, const std::string & requestedSerialNumber)
{
if ((device->vendor_id == USB_VENDOR_ID && device->product_id == USB_PRODUCT_ID) ||
(device->vendor_id == USB_OLD_VENDOR_ID && device->product_id == USB_OLD_PRODUCT_ID))
{
Debug(_log, "Found a lightpack device. Retrieving more information...");
// get the serial number
std::string serialNumber = "";
if (device->serial_number != nullptr)
{
// the serial number needs to be converted to a char array instead of wchar
size_t size = wcslen(device->serial_number);
serialNumber.resize(size, '.');
for (size_t i = 0; i < size; ++i)
{
int c = wctob(device->serial_number[i]);
if (c != EOF)
{
serialNumber[i] = c;
}
}
}
else
{
Error(_log, "No serial number for Lightpack device");
}
Debug(_log, "Lightpack device found: path=%s serial=%s", device->path.c_str(), serialNumber.c_str());
// check if this is the device we are looking for
if (requestedSerialNumber.empty() || requestedSerialNumber == serialNumber)
{
// This is it!
_deviceHandle = hid_open_path(device->path);
if (_deviceHandle != nullptr)
{
_serialNumber = serialNumber;
Info(_log, "Lightpack device successfully opened");
// get the firmware version
uint8_t buffer[256];
buffer[0] = 0; // report id
int error = hid_get_feature_report(_deviceHandle, buffer, sizeof(buffer));
if (error < 4)
{
Error(_log, "Unable to retrieve firmware version number from Lightpack device");
}
else
{
_firmwareVersion.majorVersion = buffer[INDEX_FW_VER_MAJOR+1];
_firmwareVersion.minorVersion = buffer[INDEX_FW_VER_MINOR+1];
}
// FOR TESTING PURPOSE: FORCE MAJOR VERSION TO 6
_firmwareVersion.majorVersion = 6;
// disable smoothing of the chosen device
disableSmoothing();
// determine the number of leds
if (_firmwareVersion.majorVersion == 4)
{
_hwLedCount = 8;
}
else
{
_hwLedCount = 10;
}
// determine the bits per channel
if (_firmwareVersion.majorVersion == 6)
{
// maybe also or version 7? The firmware suggest this is only for 6... (2013-11-13)
_bitsPerChannel = 12;
}
else
{
_bitsPerChannel = 8;
}
// set the led buffer size (repport id + command + 6 bytes per led)
_ledBuffer = std::vector<uint8_t>(2 + _hwLedCount * 6, 0);
_ledBuffer[0] = 0x0; // report id
_ledBuffer[1] = CMD_UPDATE_LEDS;
// return success
Debug(_log,"Lightpack device opened: path=%s serial=%s version=%s.%s.%s", device->path.c_str(), _serialNumber.c_str(), _firmwareVersion.majorVersion.c_str(), _firmwareVersion.minorVersion.c_str());
return 0;
}
else
{
Warning(_log, "Unable to open Lightpack device. Searching for other device");
}
}
}
return -1;
}
int LedDeviceLightpack::write(const std::vector<ColorRgb> &ledValues)
{
return write(ledValues.data(), _ledCount);
}
int LedDeviceLightpack::write(const ColorRgb * ledValues, int size)
{
int count = qMin(_hwLedCount,size);
for (int i=0; i<count; i++)
{
const ColorRgb & color = ledValues[i];
// copy the most significant bits of the rgb values to the first three bytes
// offset 1 to accomodate for the report id and command byte
_ledBuffer[6*i+2] = color.red;
_ledBuffer[6*i+3] = color.green;
_ledBuffer[6*i+4] = color.blue;
// leave the next three bytes on zero...
// 12-bit values having zeros in the lowest 4 bits which is almost correct, but it saves extra
// switches to determine what to do and some bit shuffling
}
int error = writeBytes(_ledBuffer.data(), _ledBuffer.size());
return error >= 0 ? 0 : error;
}
int LedDeviceLightpackHidapi::switchOff()
{
unsigned char buf[2] = {0x0, CMD_OFF_ALL};
return writeBytes(buf, sizeof(buf)) == sizeof(buf);
}
const std::string &LedDeviceLightpackHidapi::getSerialNumber() const
{
return _serialNumber;
}
int LedDeviceLightpackHidapi::getLedCount() const
{
return _ledCount;
}
int LedDeviceLightpackHidapi::writeBytes(uint8_t *data, int size)
{
// std::cout << "Writing " << size << " bytes: ";
// for (int i = 0; i < size ; ++i) printf("%02x ", data[i]);
// std::cout << std::endl;
int error = hid_send_feature_report(_deviceHandle, data, size);
if (error == size)
{
return 0;
}
Error(_log, "Unable to write %d bytes to Lightpack device(%d)", size, error);
return error;
}
int LedDeviceLightpackHidapi::disableSmoothing()
{
unsigned char buf[2] = {CMD_SET_SMOOTH_SLOWDOWN, 0};
return writeBytes(buf, sizeof(buf)) == sizeof(buf);
}
#endif

View File

@@ -0,0 +1,107 @@
// code currently disabled. must be ported to new structure
#if 0
#pragma once
// stl includes
#include <vector>
#include <cstdint>
#include <string>
// libusb include
#include <hidapi/hidapi.h>
// Hyperion includes
#include <hyperion/LedDevice.h>
///
/// LedDevice implementation for a lightpack device (http://code.google.com/p/light-pack/)
///
class LedDeviceLightpackHidapi : public LedDevice
{
public:
///
/// Constructs the LedDeviceLightpack
///
LedDeviceLightpackHidapi();
///
/// Destructor of the LedDevice; closes the output device if it is open
///
virtual ~LedDeviceLightpackHidapi();
///
/// Opens and configures the output device
///
/// @return Zero on succes else negative
///
int open(const std::string & serialNumber = "");
///
/// Writes the RGB-Color values to the leds.
///
/// @param[in] ledValues Array of RGB values
/// @param[in] size The number of RGB values
///
/// @return Zero on success else negative
///
int write(const ColorRgb * ledValues, int size);
///
/// Switch the leds off
///
/// @return Zero on success else negative
///
virtual int switchOff();
/// Get the serial of the Lightpack
const std::string & getSerialNumber() const;
/// Get the number of leds
int getLedCount() const;
private:
///
/// 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);
///
/// Test if the device is a (or the) lightpack we are looking for
///
/// @return Zero on succes else negative
///
int testAndOpen(hid_device_info * device, const std::string & requestedSerialNumber);
/// write bytes to the device
int writeBytes(uint8_t *data, int size);
/// Disable the internal smoothing on the Lightpack device
int disableSmoothing();
struct Version
{
int majorVersion;
int minorVersion;
};
/// libusb device handle
hid_device * _deviceHandle;
/// device serial number
std::string _serialNumber;
/// firmware version of the device
Version _firmwareVersion;
/// the number of leds of the device
int _hwLedCount;
/// the number of bits per channel
int _bitsPerChannel;
};
#endif