Logging leds (#50)

* switch to new logger for folowing led devices:
LedDeviceAtmo
LedDeviceFactory
LedDeviceFadeCandy
LedDeviceHyperionUsbasp
LedDeviceLightpack-hidapi
LedDevicePiBlaster
LedDeviceWS281x
LedRs232Device

leddevice base class defines logger already as protected member _log

* migrate to new logger for led devices.
still todo:
LedDeviceWS2812b
LedDeviceWs2812SPI
LedDeviceTinkerforge
LedDeviceLightpack
LedDeviceMultiLightpack
This commit is contained in:
redPanther 2016-06-25 22:08:17 +02:00 committed by brindosch
parent 67afee975f
commit 4033de85ec
20 changed files with 83 additions and 85 deletions

View File

@ -7,6 +7,7 @@
#include <utils/ColorRgb.h>
#include <utils/ColorRgbw.h>
#include <utils/RgbToRgbw.h>
#include <utils/Logger.h>
///
/// Interface (pure virtual base class) for LedDevices.
@ -14,14 +15,11 @@
class LedDevice
{
public:
LedDevice();
///
/// Empty virtual destructor for pure virtual base class
///
virtual ~LedDevice()
{
// empty
}
virtual ~LedDevice() {}
///
/// Writes the RGB-Color values to the leds.
@ -34,4 +32,7 @@ public:
/// Switch the leds off
virtual int switchOff() = 0;
protected:
Logger * _log;
};

View File

@ -44,6 +44,7 @@ SET(Leddevice_HEADERS
)
SET(Leddevice_SOURCES
${CURRENT_SOURCE_DIR}/LedDevice.cpp
${CURRENT_SOURCE_DIR}/LedDeviceFactory.cpp
${CURRENT_SOURCE_DIR}/LedRs232Device.cpp

View File

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

View File

@ -22,8 +22,8 @@ int LedDeviceAtmo::write(const std::vector<ColorRgb> &ledValues)
// (19 bytes) for the hardware to recognize the data
if (ledValues.size() != 5)
{
std::cerr << "AtmoLight: " << ledValues.size() << " channels configured. This should always be 5!" << std::endl;
return 0;
Error( _log, "%d channels configured. This should always be 5!", ledValues.size());
return 0;
}
// write data

View File

@ -8,6 +8,7 @@
// Leddevice includes
#include <leddevice/LedDeviceFactory.h>
#include <utils/Logger.h>
// Local Leddevice includes
#ifdef ENABLE_SPIDEV
@ -51,7 +52,10 @@
LedDevice * LedDeviceFactory::construct(const Json::Value & deviceConfig)
{
std::cout << "LEDDEVICE INFO: configuration: " << deviceConfig << std::endl;
Logger * log = Logger::getInstance("LedDevice");
std::stringstream ss;
ss << deviceConfig;
Info(log, "configuration: %s ", ss.str().c_str());
std::string type = deviceConfig.get("type", "UNSPECIFIED").asString();
std::transform(type.begin(), type.end(), type.begin(), ::tolower);
@ -288,11 +292,6 @@ LedDevice * LedDeviceFactory::construct(const Json::Value & deviceConfig)
device = new LedDeviceAtmoOrb(output, useOrbSmoothing, transitiontime, skipSmoothingDiff, port, numLeds, orbIds);
}
else if (type == "file")
{
const std::string output = deviceConfig.get("output", "/dev/null").asString();
device = new LedDeviceFile(output);
}
else if (type == "fadecandy")
{
const std::string host = deviceConfig.get("output", "127.0.0.1").asString();
@ -362,9 +361,13 @@ LedDevice * LedDeviceFactory::construct(const Json::Value & deviceConfig)
#endif
else
{
std::cout << "LEDDEVICE ERROR: Unknown/Unimplemented device " << type << std::endl;
// Unknown / Unimplemented device
exit(1);
if (type != "file")
{
Error(log, "Dummy device used, because unknown device %s set.", type.c_str());
}
const std::string output = deviceConfig.get("output", "/dev/null").asString();
device = new LedDeviceFile(output);
}
return device;
}

View File

@ -33,7 +33,7 @@ bool LedDeviceFadeCandy::tryConnect()
if ( _client.state() == QAbstractSocket::UnconnectedState ) {
_client.connectToHost( _host.c_str(), _port);
if ( _client.waitForConnected(1000) )
qDebug("fadecandy/opc: connected to %s:%i on channel %i", _host.c_str(), _port, _channel);
Info(_log,"fadecandy/opc: connected to %s:%i on channel %i", _host.c_str(), _port, _channel);
}
return isConnected();
@ -48,7 +48,7 @@ int LedDeviceFadeCandy::write( const std::vector<ColorRgb> & ledValues )
if (nrLedValues > MAX_NUM_LEDS)
{
std::cerr << "fadecandy/opc: Invalid attempt to write led values. Not more than " << MAX_NUM_LEDS << " leds are allowed." << std::endl;
Error(_log, "fadecandy/opc: Invalid attempt to write led values. Not more than %d leds are allowed.", MAX_NUM_LEDS);
return -1;
}

View File

@ -45,12 +45,12 @@ int LedDeviceHyperionUsbasp::open()
// initialize the usb context
if ((error = libusb_init(&_libusbContext)) != LIBUSB_SUCCESS)
{
std::cerr << "Error while initializing USB context(" << error << "): " << libusb_error_name(error) << std::endl;
Error(_log, "Error while initializing USB context(%s):%s", error, libusb_error_name(error));
_libusbContext = nullptr;
return -1;
}
//libusb_set_debug(_libusbContext, 3);
std::cout << "USB context initialized" << std::endl;
Debug(_log, "USB context initialized");
// retrieve the list of usb devices
libusb_device ** deviceList;
@ -74,7 +74,7 @@ int LedDeviceHyperionUsbasp::open()
if (_deviceHandle == nullptr)
{
std::cerr << "No " << _usbProductDescription << " has been found" << std::endl;
Error(_log, "No %s has been found", _usbProductDescription.c_str());
}
return _deviceHandle == nullptr ? -1 : 0;
@ -86,7 +86,7 @@ int LedDeviceHyperionUsbasp::testAndOpen(libusb_device * device)
int error = libusb_get_device_descriptor(device, &deviceDescriptor);
if (error != LIBUSB_SUCCESS)
{
std::cerr << "Error while retrieving device descriptor(" << error << "): " << libusb_error_name(error) << std::endl;
Error(_log, "Error while retrieving device descriptor(%s): %s", error, libusb_error_name(error));
return -1;
}
@ -99,18 +99,18 @@ int LedDeviceHyperionUsbasp::testAndOpen(libusb_device * device)
int busNumber = libusb_get_bus_number(device);
int addressNumber = libusb_get_device_address(device);
std::cout << _usbProductDescription << " found: bus=" << busNumber << " address=" << addressNumber << std::endl;
Info(_log, "%s found: bus=%s address=%s", _usbProductDescription.c_str(), busNumber, addressNumber);
try
{
_deviceHandle = openDevice(device);
std::cout << _usbProductDescription << " successfully opened" << std::endl;
Info(_log, "%s successfully opened", _usbProductDescription.c_str() );
return 0;
}
catch(int e)
{
_deviceHandle = nullptr;
std::cerr << "Unable to open " << _usbProductDescription << ". Searching for other device(" << e << "): " << libusb_error_name(e) << std::endl;
Error(_log, "Unable to open %s. Searching for other device(%s): %s", _usbProductDescription.c_str(), e, libusb_error_name(e));
}
}
@ -134,7 +134,7 @@ int LedDeviceHyperionUsbasp::write(const std::vector<ColorRgb> &ledValues)
// 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)
{
std::cerr << "Error while writing data to " << _usbProductDescription << " (" << libusb_error_name(nbytes) << ")" << std::endl;
Error(_log, "Error while writing data to %s (%s)", _usbProductDescription.c_str(), libusb_error_name(nbytes));
return -1;
}
@ -149,12 +149,13 @@ int LedDeviceHyperionUsbasp::switchOff()
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)
{
std::cerr << "unable to open device(" << error << "): " << libusb_error_name(error) << std::endl;
Error(log, "unable to open device(%s): %s",error,libusb_error_name(error));
throw error;
}
@ -164,7 +165,7 @@ libusb_device_handle * LedDeviceHyperionUsbasp::openDevice(libusb_device *device
error = libusb_detach_kernel_driver(handle, 0);
if (error != LIBUSB_SUCCESS)
{
std::cerr << "unable to detach kernel driver(" << error << "): " << libusb_error_name(error) << std::endl;
Error(log, "unable to detach kernel driver(%s): %s",error,libusb_error_name(error));
libusb_close(handle);
throw error;
}
@ -173,7 +174,7 @@ libusb_device_handle * LedDeviceHyperionUsbasp::openDevice(libusb_device *device
error = libusb_claim_interface(handle, 0);
if (error != LIBUSB_SUCCESS)
{
std::cerr << "unable to claim interface(" << error << "): " << libusb_error_name(error) << std::endl;
Error(log, "unable to claim interface(%s): %s", error, libusb_error_name(error));
libusb_attach_kernel_driver(handle, 0);
libusb_close(handle);
throw error;

View File

@ -62,10 +62,10 @@ int LedDeviceLightpackHidapi::open(const std::string & serialNumber)
int error = hid_init();
if (error != 0)
{
std::cerr << "Error while initializing the hidapi context" << std::endl;
Error(_log, "Error while initializing the hidapi context");
return -1;
}
std::cout << "Hidapi initialized" << std::endl;
Info("Hidapi initialized");
// retrieve the list of usb devices
hid_device_info * deviceList = hid_enumerate(0x0, 0x0);
@ -90,11 +90,11 @@ int LedDeviceLightpackHidapi::open(const std::string & serialNumber)
{
if (_serialNumber.empty())
{
std::cerr << "No Lightpack device has been found" << std::endl;
Error(_log, "No Lightpack device has been found");
}
else
{
std::cerr << "No Lightpack device has been found with serial " << _serialNumber << std::endl;
Error(_log, "No Lightpack device has been found with serial %s", _serialNumber);
}
}
@ -106,7 +106,7 @@ int LedDeviceLightpackHidapi::testAndOpen(hid_device_info *device, const std::st
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))
{
std::cout << "Found a lightpack device. Retrieving more information..." << std::endl;
Debug(_log, "Found a lightpack device. Retrieving more information...");
// get the serial number
std::string serialNumber = "";
@ -126,10 +126,10 @@ int LedDeviceLightpackHidapi::testAndOpen(hid_device_info *device, const std::st
}
else
{
std::cerr << "No serial number for Lightpack device" << std::endl;
Error(_log, "No serial number for Lightpack device");
}
std::cout << "Lightpack device found: path=" << device->path << " serial=" << serialNumber << std::endl;
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)
@ -141,7 +141,7 @@ int LedDeviceLightpackHidapi::testAndOpen(hid_device_info *device, const std::st
{
_serialNumber = serialNumber;
std::cout << "Lightpack device successfully opened" << std::endl;
Info(_log, "Lightpack device successfully opened");
// get the firmware version
uint8_t buffer[256];
@ -149,7 +149,7 @@ int LedDeviceLightpackHidapi::testAndOpen(hid_device_info *device, const std::st
int error = hid_get_feature_report(_deviceHandle, buffer, sizeof(buffer));
if (error < 4)
{
std::cerr << "Unable to retrieve firmware version number from Lightpack device" << std::endl;
Error(_log, "Unable to retrieve firmware version number from Lightpack device");
}
else
{
@ -190,12 +190,12 @@ int LedDeviceLightpackHidapi::testAndOpen(hid_device_info *device, const std::st
_ledBuffer[1] = CMD_UPDATE_LEDS;
// return success
std::cout << "Lightpack device opened: path=" << device->path << " serial=" << _serialNumber << " version=" << _firmwareVersion.majorVersion << "." << _firmwareVersion.minorVersion << std::endl;
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
{
std::cerr << "Unable to open Lightpack device. Searching for other device" << std::endl;
Warning(_log, "Unable to open Lightpack device. Searching for other device");
}
}
}
@ -259,7 +259,7 @@ int LedDeviceLightpackHidapi::writeBytes(uint8_t *data, int size)
return 0;
}
std::cerr << "Unable to write " << size << " bytes to Lightpack device(" << error << ")" << std::endl;
Error(_log, "Unable to write %s bytes to Lightpack device(%s)", size, error);
return error;
}

View File

@ -278,8 +278,7 @@ void LedDevicePhilipsHue::saveStates(unsigned int nLights) {
for (Json::ValueIterator it = json.begin(); it != json.end() && lightIds.size() < nLights; it++) {
int lightId = atoi(it.key().asCString());
lightIds.push_back(lightId);
std::cout << "LedDevicePhilipsHue::saveStates(nLights=" << nLights << "): found light with id " << lightId
<< "." << std::endl;
Debug(_log, "nLights=%d: found light with id %d.", nLights, lightId);
}
// Check if we found enough lights.
if (lightIds.size() != nLights) {
@ -294,20 +293,17 @@ void LedDevicePhilipsHue::saveStates(unsigned int nLights) {
Json::Value json;
if (!reader.parse(QString(response).toStdString(), json)) {
// Error occured, break loop.
std::cerr << "LedDevicePhilipsHue::saveStates(nLights=" << nLights << "): got invalid response from light "
<< getUrl(getRoute(lightIds.at(i))).toStdString() << "." << std::endl;
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")) {
std::cerr << "LedDevicePhilipsHue::saveStates(nLights=" << nLights << "): got no state for light from "
<< getUrl(getRoute(lightIds.at(i))).toStdString() << std::endl;
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")) {
std::cerr << "LedDevicePhilipsHue::saveStates(nLights=" << nLights << "): got no valid state from light "
<< getUrl(getRoute(lightIds.at(i))).toStdString() << std::endl;
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"];

View File

@ -16,8 +16,7 @@
LedDevicePiBlaster::LedDevicePiBlaster(const std::string & deviceName, const Json::Value & gpioMapping) :
_deviceName(deviceName),
_fid(nullptr),
_log(Logger::getInstance("LedDevice"))
_fid(nullptr)
{
signal(SIGPIPE, SIG_IGN);

View File

@ -9,7 +9,6 @@
// Hyperion-Leddevice includes
#include <leddevice/LedDevice.h>
#include <utils/Logger.h>
class LedDevicePiBlaster : public LedDevice
{
@ -60,6 +59,4 @@ private:
/// File-Pointer to the PiBlaster device
FILE * _fid;
/// logger instance
Logger* _log;
};

View File

@ -47,7 +47,7 @@ int LedDeviceSedu::write(const std::vector<ColorRgb> &ledValues)
if (_ledBuffer.size() == 0)
{
std::cout << "More rgb-channels required then available" << std::endl;
Warning(_log, "More rgb-channels required then available");
return -1;
}
}

View File

@ -54,7 +54,7 @@ LedDeviceUdp::LedDeviceUdp(const std::string& output, const unsigned baudrate, c
hints.ai_socktype = SOCK_DGRAM;
if ((rv = getaddrinfo(hostname.c_str() , port.c_str(), &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
Debug(_log, "getaddrinfo: %s", gai_strerror(rv));
assert(rv==0);
}
@ -70,7 +70,7 @@ LedDeviceUdp::LedDeviceUdp(const std::string& output, const unsigned baudrate, c
}
if (p == NULL) {
fprintf(stderr, "talker: failed to create socket\n");
Error(_log,"talker: failed to create socket");
assert(p!=NULL);
}
}

View File

@ -6,13 +6,13 @@
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)
{
_whiteAlgorithm = whiteAlgorithm;
Debug( Logger::getInstance("LedDevice"), "whiteAlgorithm : %s", whiteAlgorithm.c_str());
Debug( _log, "whiteAlgorithm : %s", whiteAlgorithm.c_str());
initialized = false;
led_string.freq = freq;
led_string.dmanum = dmanum;
if (pwmchannel != 0 && pwmchannel != 1) {
Error( Logger::getInstance("LedDevice"), "WS281x: invalid PWM channel; must be 0 or 1.");
Error( _log, "WS281x: invalid PWM channel; must be 0 or 1.");
throw -1;
}
chan = pwmchannel;
@ -32,7 +32,7 @@ LedDeviceWS281x::LedDeviceWS281x(const int gpio, const int leds, const uint32_t
led_string.channel[!chan].brightness = 0;
led_string.channel[!chan].strip_type = WS2811_STRIP_RGB;
if (ws2811_init(&led_string) < 0) {
Error( Logger::getInstance("LedDevice"), "Unable to initialize ws281x library.");
Error( _log, "Unable to initialize ws281x library.");
throw -1;
}
initialized = true;

View File

@ -5,7 +5,6 @@
#include <leddevice/LedDevice.h>
#include <ws2811.h>
#include <utils/Logger.h>
class LedDeviceWS281x : public LedDevice
{

View File

@ -37,19 +37,19 @@ int LedHIDDevice::open()
int error = hid_init();
if (error != 0)
{
std::cerr << "Error while initializing the hidapi context" << std::endl;
Error(_log, "Error while initializing the hidapi context");
return -1;
}
std::cout << "Hidapi initialized" << std::endl;
Debug(_log,"Hidapi initialized");
// Open the device
printf("Opening device: VID %04hx PID %04hx\n", _VendorId, _ProductId);
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
std::cerr << "Failed to open HID device. Maybe your PID/VID setting is wrong? Make sure to add a udev rule/use sudo." << std::endl;
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/
/*
@ -70,8 +70,9 @@ int LedHIDDevice::open()
return -1;
}
else{
std::cout << "Opened HID device successful" << std::endl;
else
{
Info(_log,"Opened HID device successful");
}
// Wait after device got opened if enabled
@ -79,7 +80,7 @@ int LedHIDDevice::open()
{
_blockedForDelay = true;
QTimer::singleShot(_delayAfterConnect_ms, this, SLOT(unblockAfterDelay()));
std::cout << "Device blocked for " << _delayAfterConnect_ms << " ms" << std::endl;
Debug(_log, "Device blocked for %d ms", _delayAfterConnect_ms);
}
return 0;
@ -98,10 +99,10 @@ int LedHIDDevice::writeBytes(const unsigned size, const uint8_t * data)
auto status = open();
if(status < 0){
// Try again in 3 seconds
int seconds = 3000;
int delay_ms = 3000;
_blockedForDelay = true;
QTimer::singleShot(seconds, this, SLOT(unblockAfterDelay()));
std::cout << "Device blocked for " << seconds << " ms" << std::endl;
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;
@ -123,7 +124,7 @@ int LedHIDDevice::writeBytes(const unsigned size, const uint8_t * data)
// Handle first error
if(ret < 0){
std::cerr << "Failed to write to HID device." << std::endl;
Error(_log,"Failed to write to HID device.");
// Try again
if(_useFeature){
@ -135,7 +136,7 @@ int LedHIDDevice::writeBytes(const unsigned size, const uint8_t * data)
// Writing failed again, device might have disconnected
if(ret < 0){
std::cerr << "Failed to write to HID device." << std::endl;
Error(_log,"Failed to write to HID device.");
hid_close(_deviceHandle);
_deviceHandle = nullptr;
@ -147,6 +148,6 @@ int LedHIDDevice::writeBytes(const unsigned size, const uint8_t * data)
void LedHIDDevice::unblockAfterDelay()
{
std::cout << "Device unblocked" << std::endl;
Debug(_log,"Device unblocked");
_blockedForDelay = false;
}

View File

@ -14,8 +14,7 @@ LedRs232Device::LedRs232Device(const std::string& outputDevice, const unsigned b
_baudRate_Hz(baudrate),
_delayAfterConnect_ms(delayAfterConnect_ms),
_rs232Port(this),
_blockedForDelay(false),
_log(Logger::getInstance("LedDevice"))
_blockedForDelay(false)
{
}

View File

@ -6,8 +6,6 @@
// Leddevice includes
#include <leddevice/LedDevice.h>
#include <utils/Logger.h>
///
/// The LedRs232Device implements an abstract base-class for LedDevices using a RS232-device.
///
@ -68,7 +66,4 @@ private:
QSerialPort _rs232Port;
bool _blockedForDelay;
/// logger instance
Logger* _log;
};

View File

@ -36,7 +36,7 @@ int LedSpiDevice::open()
if (mFid < 0)
{
Error( Logger::getInstance("LedDevice"), "Failed to open device (%s). Error message: %s", mDeviceName.c_str(), strerror(errno) );
Error( _log, "Failed to open device (%s). Error message: %s", mDeviceName.c_str(), strerror(errno) );
return -1;
}

View File

@ -24,7 +24,7 @@ LedUdpDevice::LedUdpDevice(const std::string& outputDevice, const unsigned baudr
QString str = QString::fromStdString(mDeviceName);
QStringList _list = str.split(":");
if (_list.size() != 2) {
Error( Logger::getInstance("LedDevice"), "LedUdpDevice: Error parsing hostname:port");
Error( _log, "Error parsing hostname:port");
exit (-1);
}
QHostInfo info = QHostInfo::fromName(_list.at(0));
@ -46,7 +46,7 @@ int LedUdpDevice::open()
quint16 _localPort = 0;
WarningIf( !udpSocket->bind(_localAddress, _localPort),
Logger::getInstance("LedDevice"), "LedUdpDevice: Couldnt bind local address: %s", strerror(errno));
_log, "Couldnt bind local address: %s", strerror(errno));
return 0;
}
@ -66,7 +66,7 @@ int LedUdpDevice::writeBytes(const unsigned size, const uint8_t * data)
// Sleep to latch the leds (only if write succesfull)
nanosleep(&latchTime, NULL);
} else {
Warning( Logger::getInstance("LedDevice"), "LedUdpDevice: Error sending: %s", strerror(errno));
Warning( _log, "Error sending: %s", strerror(errno));
}
return retVal;