Merge remote-tracking branch 'tvdzwan/master'

Former-commit-id: c100898708
This commit is contained in:
redpanther 2016-01-21 23:30:10 +01:00
commit 3327251ba7
13 changed files with 259 additions and 141 deletions

View File

@ -0,0 +1,12 @@
{
"name" : "Police Lights Single",
"script" : "police.py",
"args" :
{
"rotation-time" : 1.5,
"color_one" : [ 255, 0, 0 ],
"color_two" : [ 0, 0, 255 ],
"colors_count" : 10,
"reverse" : false
}
}

View File

@ -0,0 +1,11 @@
{
"name" : "Police Lights Solid",
"script" : "police.py",
"args" :
{
"rotation-time" : 1.0,
"color_one" : [ 255, 0, 0 ],
"color_two" : [ 0, 0, 255 ],
"reverse" : false
}
}

46
effects/police.py Normal file
View File

@ -0,0 +1,46 @@
import hyperion
import time
import colorsys
# Get the parameters
rotationTime = float(hyperion.args.get('rotation-time', 2.0))
colorOne = hyperion.args.get('color_one', (255,0,0))
colorTwo = hyperion.args.get('color_two', (0,0,255))
colorsCount = hyperion.args.get('colors_count', hyperion.ledCount/2)
reverse = bool(hyperion.args.get('reverse', False))
# Check parameters
rotationTime = max(0.1, rotationTime)
colorsCount = min(hyperion.ledCount/2, colorsCount)
# Initialize the led data
hsv1 = colorsys.rgb_to_hsv(colorOne[0]/255.0, colorOne[1]/255.0, colorOne[2]/255.0)
hsv2 = colorsys.rgb_to_hsv(colorTwo[0]/255.0, colorTwo[1]/255.0, colorTwo[2]/255.0)
colorBlack = (0,0,0)
ledData = bytearray()
for i in range(hyperion.ledCount):
if i <= colorsCount:
rgb = colorsys.hsv_to_rgb(hsv1[0], hsv1[1], hsv1[2])
elif (i >= hyperion.ledCount/2-1) & (i < (hyperion.ledCount/2) + colorsCount):
rgb = colorsys.hsv_to_rgb(hsv2[0], hsv2[1], hsv2[2])
else:
rgb = colorBlack
ledData += bytearray((int(255*rgb[0]), int(255*rgb[1]), int(255*rgb[2])))
# Calculate the sleep time and rotation increment
increment = 3
sleepTime = rotationTime / hyperion.ledCount
while sleepTime < 0.05:
increment *= 2
sleepTime *= 2
increment %= hyperion.ledCount
# Switch direction if needed
if reverse:
increment = -increment
# Start the write data loop
while not hyperion.abort():
hyperion.setColor(ledData)
ledData = ledData[-increment:] + ledData[:-increment]
time.sleep(sleepTime)

View File

@ -62,13 +62,17 @@ namespace hyperion
BlackBorder process(const Image<Pixel_T> & image)
{
// test center and 1/3, 2/3 of width/heigth
int width = image.width() / 3;
int height = image.height() / 3;
int width2 = width * 2;
int height2 = height * 2;
int xCenter = image.width() / 2;
int yCenter = image.height() / 2;
// test center and 33%, 66% of width/heigth
// 33 and 66 will check left and top
// center ill check right and bottom sids
int width = image.width();
int height = image.height();
int width33percent = width / 3;
int height33percent = height / 3;
int width66percent = width33percent * 2;
int height66percent = height33percent * 2;
int xCenter = width / 2;
int yCenter = height / 2;
int firstNonBlackXPixelIndex = -1;
@ -77,9 +81,9 @@ namespace hyperion
// find first X pixel of the image
for (int x = 0; x < width; ++x)
{
const Pixel_T & color1 = image(x, yCenter);
const Pixel_T & color2 = image(x, height);
const Pixel_T & color3 = image(x, height2);
const Pixel_T & color1 = image( (width - x), yCenter); // right side center line check
const Pixel_T & color2 = image(x, height33percent);
const Pixel_T & color3 = image(x, height66percent);
if (!isBlack(color1) || !isBlack(color2) || !isBlack(color3))
{
firstNonBlackXPixelIndex = x;
@ -90,9 +94,9 @@ namespace hyperion
// find first Y pixel of the image
for (int y = 0; y < height; ++y)
{
const Pixel_T & color1 = image(xCenter, y);
const Pixel_T & color2 = image(width, y);
const Pixel_T & color3 = image(width2, y);
const Pixel_T & color1 = image(xCenter, (height - y)); // bottom center line check
const Pixel_T & color2 = image(width33percent, y );
const Pixel_T & color3 = image(width66percent, y);
if (!isBlack(color1) || !isBlack(color2) || !isBlack(color3))
{
firstNonBlackYPixelIndex = y;

View File

@ -7,6 +7,11 @@
// X11 includes
#include <X11/Xlib.h>
#include <X11/extensions/Xrender.h>
#include <X11/extensions/XShm.h>
#include <sys/ipc.h>
#include <sys/shm.h>
class X11Grabber
{
public:
@ -16,6 +21,8 @@ public:
virtual ~X11Grabber();
int open();
bool Setup();
Image<ColorRgb> & grab();
@ -26,14 +33,24 @@ private:
int _cropRight;
int _cropTop;
int _cropBottom;
XImage* _xImage;
XShmSegmentInfo _shminfo;
/// Reference to the X11 display (nullptr if not opened)
Display * _x11Display;
Display* _x11Display;
Window _window;
XWindowAttributes _windowAttr;
unsigned _screenWidth;
unsigned _screenHeight;
unsigned _croppedWidth;
unsigned _croppedHeight;
Image<ColorRgb> _image;
void freeResources();
void setupResources();
int updateScreenDimensions();
};

View File

@ -1,3 +1,4 @@
//#include <iostream>
// Blackborder includes
#include <blackborder/BlackBorderProcessor.h>
@ -15,7 +16,7 @@ BlackBorderProcessor::BlackBorderProcessor(const unsigned unknownFrameCnt,
_currentBorder({true, -1, -1}),
_previousDetectedBorder({true, -1, -1}),
_consistentCnt(0),
_inconsistentCnt(0)
_inconsistentCnt(10)
{
// empty
}
@ -27,6 +28,19 @@ BlackBorder BlackBorderProcessor::getCurrentBorder() const
bool BlackBorderProcessor::updateBorder(const BlackBorder & newDetectedBorder)
{
// the new changes ignore false small borders (no reset of consistance)
// as long as the previous stable state returns within 10 frames
// and will only switch to a new border if it is realy detected stable >50 frames
// sometimes the grabber delivers "bad" frames with a smaller black border (looks like random number every few frames and even when freezing the image)
// maybe some interferences of the power supply or bad signal causing this effect - not exactly sure what causes it but changing the power supply of the converter significantly increased that "random" effect on my system
// (you can check with the debug output below or if you want i can provide some output logs)
// this "random effect" caused the old algorithm to switch to that smaller border immediatly, resulting in a too small border being detected
// makes it look like the border detectionn is not working - since the new 3 line detection algorithm is more precise this became a problem specialy in dark scenes
// wisc
// std::cout << "cur: " << _currentBorder.verticalSize << " " << _currentBorder.horizontalSize << " new: " << newDetectedBorder.verticalSize << " " << newDetectedBorder.horizontalSize << " c:i " << _consistentCnt << ":" << _inconsistentCnt << std::endl;
// set the consistency counter
if (newDetectedBorder == _previousDetectedBorder)
{
@ -35,15 +49,23 @@ bool BlackBorderProcessor::updateBorder(const BlackBorder & newDetectedBorder)
}
else
{
++_inconsistentCnt;
if (_inconsistentCnt <= 10)// few inconsistent frames
{
//discard the newDetectedBorder -> keep the consistent count for previousDetectedBorder
return false;
}
// the inconsistency threshold is reached
// -> give the newDetectedBorder a chance to proof that its consistent
_previousDetectedBorder = newDetectedBorder;
_consistentCnt = 0;
++_inconsistentCnt;
}
// check if there is a change
if (_currentBorder == newDetectedBorder)
{
// No change required
_inconsistentCnt = 0; // we have found a consistent border -> reset _inconsistentCnt
return false;
}
@ -65,25 +87,6 @@ bool BlackBorderProcessor::updateBorder(const BlackBorder & newDetectedBorder)
_currentBorder = newDetectedBorder;
borderChanged = true;
}
else
{
bool stable = (_consistentCnt >= 10) || (_inconsistentCnt >=30 );
//more then 10 consistent seems like a new size not only a short flicker
//more then 30 inconsistent seems like the image is changing a lot and we need to set smaller border
// apply smaller borders (almost) immediately -> avoid switching for "abnormal" frames
if ( (newDetectedBorder.verticalSize < _currentBorder.verticalSize) && (stable) )
{
_currentBorder.verticalSize = newDetectedBorder.verticalSize;
borderChanged = true;
}
if ( (newDetectedBorder.horizontalSize < _currentBorder.horizontalSize) && (stable) )
{
_currentBorder.horizontalSize = newDetectedBorder.horizontalSize;
borderChanged = true;
}
}
}
return borderChanged;

View File

@ -17,82 +17,116 @@ X11Grabber::X11Grabber(int cropLeft, int cropRight, int cropTop, int cropBottom,
_x11Display(nullptr),
_screenWidth(0),
_screenHeight(0),
_croppedWidth(0),
_croppedHeight(0),
_image(0,0)
{
_imageResampler.setHorizontalPixelDecimation(horizontalPixelDecimation);
_imageResampler.setVerticalPixelDecimation(verticalPixelDecimation);
_imageResampler.setCropping(0, 0, 0, 0); // cropping is performed by XGetImage
_imageResampler.setCropping(0, 0, 0, 0); // cropping is performed by XShmGetImage
}
X11Grabber::~X11Grabber()
{
if (_x11Display != nullptr)
{
freeResources();
XCloseDisplay(_x11Display);
}
}
int X11Grabber::open()
void X11Grabber::freeResources()
{
const char * display_name = nullptr;
_x11Display = XOpenDisplay(display_name);
// Cleanup allocated resources of the X11 grab
XShmDetach(_x11Display, &_shminfo);
XDestroyImage(_xImage);
shmdt(_shminfo.shmaddr);
shmctl(_shminfo.shmid, IPC_RMID, 0);
}
void X11Grabber::setupResources()
{
_xImage = XShmCreateImage(_x11Display, _windowAttr.visual,
_windowAttr.depth, ZPixmap, NULL, &_shminfo,
_croppedWidth, _croppedHeight);
_shminfo.shmid = shmget(IPC_PRIVATE, _xImage->bytes_per_line * _xImage->height, IPC_CREAT|0777);
_shminfo.shmaddr = _xImage->data = (char*)shmat(_shminfo.shmid,0,0);
_shminfo.readOnly = False;
XShmAttach(_x11Display, &_shminfo);
}
bool X11Grabber::Setup()
{
_x11Display = XOpenDisplay(NULL);
if (_x11Display == nullptr)
{
std::cerr << "Failed to open the default X11-display" << std::endl;
return -1;
}
std::cerr << "Unable to open display";
if (getenv("DISPLAY"))
std::cerr << " " << std::string(getenv("DISPLAY")) << std::endl;
else
std::cerr << ". DISPLAY environment variable not set" << std::endl;
return false;
}
_window = DefaultRootWindow(_x11Display);
return 0;
}
return true;
}
Image<ColorRgb> & X11Grabber::grab()
{
if (_x11Display == nullptr)
{
open();
}
updateScreenDimensions();
const unsigned croppedWidth = _screenWidth - _cropLeft - _cropRight;
const unsigned croppedHeight = _screenHeight - _cropTop - _cropBottom;
// Capture the current screen
XImage * xImage = XGetImage(_x11Display, DefaultRootWindow(_x11Display), _cropLeft, _cropTop, croppedWidth, croppedHeight, AllPlanes, ZPixmap);
if (xImage == nullptr)
XShmGetImage(_x11Display, _window, _xImage, _cropLeft, _cropTop, 0x00FFFFFF);
if (_xImage == nullptr)
{
std::cerr << "Grab failed" << std::endl;
return _image;
}
_imageResampler.processImage(reinterpret_cast<const uint8_t *>(xImage->data), xImage->width, xImage->height, xImage->bytes_per_line, PIXELFORMAT_BGR32, _image);
// Cleanup allocated resources of the X11 grab
XDestroyImage(xImage);
_imageResampler.processImage(reinterpret_cast<const uint8_t *>(_xImage->data), _xImage->width, _xImage->height, _xImage->bytes_per_line, PIXELFORMAT_BGR32, _image);
return _image;
}
int X11Grabber::updateScreenDimensions()
{
XWindowAttributes window_attributes_return;
const Status status = XGetWindowAttributes(_x11Display, DefaultRootWindow(_x11Display), &window_attributes_return);
const Status status = XGetWindowAttributes(_x11Display, _window, &_windowAttr);
if (status == 0)
{
std::cerr << "Failed to obtain window attributes" << std::endl;
return -1;
}
if (_screenWidth == unsigned(window_attributes_return.width) && _screenHeight == unsigned(window_attributes_return.height))
if (_screenWidth == unsigned(_windowAttr.width) && _screenHeight == unsigned(_windowAttr.height))
{
// No update required
return 0;
}
std::cout << "Update of screen resolution: [" << _screenWidth << "x" << _screenHeight <<"] => ";
_screenWidth = window_attributes_return.width;
_screenHeight = window_attributes_return.height;
if (_screenWidth || _screenHeight)
freeResources();
_screenWidth = _windowAttr.width;
_screenHeight = _windowAttr.height;
std::cout << "[" << _screenWidth << "x" << _screenHeight <<"]" << std::endl;
if (_screenWidth > unsigned(_cropLeft + _cropRight))
_croppedWidth = _screenWidth - _cropLeft - _cropRight;
else
_croppedWidth = _screenWidth;
if (_screenHeight > unsigned(_cropTop + _cropBottom))
_croppedHeight = _screenHeight - _cropTop - _cropBottom;
else
_croppedHeight = _screenHeight;
setupResources();
return 0;
}

View File

@ -5,15 +5,9 @@
#include <json/json.h>
// qt includes
#include <QtCore/qmath.h>
#include <QUrl>
#ifdef ENABLE_QT5
#else
#include <QHttpRequestHeader>
#endif
#include <QtCore/qmath.h>
#include <QEventLoop>
#include <QNetworkReply>
#include <set>
@ -149,22 +143,14 @@ LedDevicePhilipsHue::LedDevicePhilipsHue(const std::string& output, const std::s
int transitiontime, std::vector<unsigned int> lightIds) :
host(output.c_str()), username(username.c_str()), switchOffOnBlack(switchOffOnBlack), transitiontime(
transitiontime), lightIds(lightIds) {
#ifdef ENABLE_QT5
#else
http = new QHttp(host);
manager = new QNetworkAccessManager();
timer.setInterval(3000);
timer.setSingleShot(true);
connect(&timer, SIGNAL(timeout()), this, SLOT(restoreStates()));
#endif
}
LedDevicePhilipsHue::~LedDevicePhilipsHue() {
#ifdef ENABLE_QT5
#else
delete http;
#endif
delete manager;
}
int LedDevicePhilipsHue::write(const std::vector<ColorRgb> & ledValues) {
@ -214,64 +200,44 @@ int LedDevicePhilipsHue::write(const std::vector<ColorRgb> & ledValues) {
// Next light id.
idx++;
}
#ifdef ENABLE_QT5
#else
timer.start();
#endif
return 0;
}
int LedDevicePhilipsHue::switchOff() {
#ifdef ENABLE_QT5
#else
timer.stop();
// If light states have been saved before, ...
if (areStatesSaved()) {
// ... restore them.
restoreStates();
}
#endif
return 0;
}
void LedDevicePhilipsHue::put(QString route, QString content) {
#ifdef ENABLE_QT5
#else
QString url = QString("/api/%1/%2").arg(username).arg(route);
QHttpRequestHeader header("PUT", url);
header.setValue("Host", host);
header.setValue("Accept-Encoding", "identity");
header.setValue("Connection", "keep-alive");
header.setValue("Content-Length", QString("%1").arg(content.size()));
QEventLoop loop;
// Connect requestFinished signal to quit slot of the loop.
loop.connect(http, SIGNAL(requestFinished(int, bool)), SLOT(quit()));
void LedDevicePhilipsHue::put(QString route, QString content) {
QString url = QString("http://%1/api/%2/%3").arg(host).arg(username).arg(route);
// Perfrom request
http->request(header, content.toAscii());
QNetworkRequest request(url);
QNetworkReply* reply = manager->put(request, content.toAscii());
// Connect finished signal to quit slot of the loop.
QEventLoop loop;
loop.connect(reply, SIGNAL(finished()), SLOT(quit()));
// Go into the loop until the request is finished.
loop.exec();
#endif
}
QByteArray LedDevicePhilipsHue::get(QString route) {
#ifdef ENABLE_QT5
return 0;
#else
QString url = QString("/api/%1/%2").arg(username).arg(route);
// Event loop to block until request finished.
QEventLoop loop;
// Connect requestFinished signal to quit slot of the loop.
loop.connect(http, SIGNAL(requestFinished(int, bool)), SLOT(quit()));
QByteArray LedDevicePhilipsHue::get(QString route) {
QString url = QString("http://%1/api/%2/%3").arg(host).arg(username).arg(route);
// Perfrom request
http->get(url);
QNetworkRequest request(url);
QNetworkReply* reply = manager->get(request);
// Connect requestFinished signal to quit slot of the loop.
QEventLoop loop;
loop.connect(reply, SIGNAL(finished()), SLOT(quit()));
// Go into the loop until the request is finished.
loop.exec();
// Read all data of the response.
return http->readAll();
#endif
// Read all data of the response.
return reply->readAll();
}
QString LedDevicePhilipsHue::getStateRoute(unsigned int lightId) {

View File

@ -4,14 +4,10 @@
#include <string>
// Qt includes
#ifdef ENABLE_QT5
#include <QNetworkAccessManager>
#else
#include <QObject>
#include <QString>
#include <QHttp>
#include <QNetworkAccessManager>
#include <QTimer>
#endif
// Leddevice includes
#include <leddevice/LedDevice.h>
@ -167,15 +163,10 @@ private:
QString host;
/// User name for the API ("newdeveloper")
QString username;
/// Qhttp object for sending requests.
#ifdef ENABLE_QT5
// TODO QNetworkAcessManager stuff
#else
QHttp* http;
/// QNetworkAccessManager object for sending requests.
QNetworkAccessManager* manager;
/// Use timer to reset lights when we got into "GRABBINGMODE_OFF".
QTimer timer;
#endif
///
bool switchOffOnBlack;
/// Transition time in multiples of 100 ms.

View File

@ -29,6 +29,11 @@ void X11Wrapper::stop()
_timer.stop();
}
bool X11Wrapper::displayInit()
{
return _grabber.Setup();
}
void X11Wrapper::capture()
{
const Image<ColorRgb> & screenshot = _grabber.grab();

View File

@ -19,6 +19,8 @@ public:
void start();
void stop();
bool displayInit();
signals:
void sig_screenshot(const Image<ColorRgb> & screenshot);

View File

@ -77,6 +77,9 @@ int main(int argc, char ** argv)
argCropBottom.getValue(),
argSizeDecimation.getValue(), // horizontal decimation
argSizeDecimation.getValue()); // vertical decimation
if (!x11Wrapper.displayInit())
return -1;
if (argScreenshot.isSet())
{

View File

@ -29,7 +29,7 @@ Image<ColorRgb> createImage(unsigned width, unsigned height, unsigned topBorder,
{
for (unsigned y=0; y<image.height(); ++y)
{
if (y < topBorder || x < leftBorder)
if (y < topBorder || y > ( height - topBorder ) || x < leftBorder || x > (width - leftBorder) )
{
image(x,y) = ColorRgb::BLACK;
}
@ -86,7 +86,7 @@ int main()
for (unsigned i=0; i<borderCnt*2; ++i)
{
bool newBorder = processor.process(horzImage);
if (i == borderCnt)
if (i == borderCnt+10)// 10 frames till new border gets a chance to proof consistency
{
if (!newBorder)
{
@ -111,18 +111,42 @@ int main()
exit(EXIT_FAILURE);
}
// Switch back (in one shot) to no border
if (!processor.process(noBorderImage) || (processor.getCurrentBorder().unknown != false || processor.getCurrentBorder().horizontalSize != 0 || processor.getCurrentBorder().verticalSize != 0))
for (unsigned i=0; i<borderCnt*2; ++i)
{
std::cerr << "Failed to switch back to 'no border' with one image" << std::endl;
exit(EXIT_FAILURE);
bool newBorder = processor.process(noBorderImage);
if (i == borderCnt+10)// 10 frames till new border gets a chance to proof consistency
{
if (!newBorder)
{
std::cerr << "Failed to detect 'no border' when required after " << borderCnt << " images" << std::endl;
exit(EXIT_FAILURE);
}
}
else
{
if (newBorder)
{
std::cerr << "Incorrectly detected no border, when there in none" << std::endl;
exit(EXIT_FAILURE);
}
}
}
// Check switch back to no border
if ( (processor.getCurrentBorder().unknown != false || processor.getCurrentBorder().horizontalSize != 0 || processor.getCurrentBorder().verticalSize != 0))
{
std::cerr << "Failed to switch back to 'no border'" << std::endl;
exit(EXIT_FAILURE);
}
Image<ColorRgb> vertImage = createImage(64, 64, 0, borderSize);
for (unsigned i=0; i<borderCnt*2; ++i)
{
bool newBorder = processor.process(vertImage);
if (i == borderCnt)
if (i == borderCnt+10)// 10 frames till new border gets a chance to proof consistency
{
if (!newBorder)
{
@ -147,8 +171,8 @@ int main()
}
// Switch back (in one shot) to no border
assert(processor.process(noBorderImage));
assert(processor.getCurrentBorder().verticalSize == 0 && processor.getCurrentBorder().horizontalSize == 0);
// assert(processor.process(noBorderImage));
// assert(processor.getCurrentBorder().verticalSize == 0 && processor.getCurrentBorder().horizontalSize == 0);
return 0;
}