Add CodeQL for GitHub code scanning (#1548)

* Create codeql.yml

* Addressing codeql findings
This commit is contained in:
LordGrey 2022-12-27 08:36:10 +01:00 committed by GitHub
parent 1189f86c1a
commit 6fa7bab6f7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
83 changed files with 1984 additions and 2094 deletions

4
.github/config/codeql.yml vendored Normal file
View File

@ -0,0 +1,4 @@
name: "CodeQL config"
paths-ignore:
- 'dependencies/external/'
- 'assets/webconfig/js/lib'

76
.github/workflows/codeql.yml vendored Normal file
View File

@ -0,0 +1,76 @@
name: "CodeQL"
on:
push:
branches: [ "master" ]
pull_request:
branches: [ "master" ]
schedule:
- cron: "36 18 * * 4"
jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
security-events: write
strategy:
fail-fast: false
matrix:
language: [ python, javascript, cpp ]
steps:
- name: Checkout
uses: actions/checkout@v3
with:
submodules: recursive
- name: Install Packages (cpp)
if: ${{ matrix.language == 'cpp' }}
run: |
sudo apt-get update
sudo apt-get install --yes git cmake build-essential qtbase5-dev libqt5serialport5-dev libqt5sql5-sqlite libqt5svg5-dev libqt5x11extras5-dev libusb-1.0-0-dev python3-dev libcec-dev libxcb-image0-dev libxcb-util0-dev libxcb-shm0-dev libxcb-render0-dev libxcb-randr0-dev libxrandr-dev libxrender-dev libavahi-core-dev libavahi-compat-libdnssd-dev libturbojpeg0-dev libjpeg-dev libssl-dev
- name: Initialize CodeQL
uses: github/codeql-action/init@v2
with:
languages: ${{ matrix.language }}
queries: +security-and-quality
config-file: ./.github/config/codeql.yml
- name: Autobuild
uses: github/codeql-action/autobuild@v2
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v2
with:
category: "/language:${{ matrix.language }}"
upload: False
output: sarif-results
- name: Filter SARIF
uses: advanced-security/filter-sarif@v1
with:
patterns: |
-**/dependencies/**
-**/moc_*.cpp
-**/libsrc/flatbufserver/hyperion_request_generated.h
-**/libsrc/protoserver/message.pb.cc
-**/libsrc/protoserver/message.pb.h
input: sarif-results/${{ matrix.language }}.sarif
output: sarif-results/${{ matrix.language }}.sarif
- name: Upload SARIF
uses: github/codeql-action/upload-sarif@v2
with:
sarif_file: sarif-results/${{ matrix.language }}.sarif
- name: Upload loc as a Build Artifact
uses: actions/upload-artifact@v2.2.0
with:
name: sarif-results
path: sarif-results
retention-days: 1

View File

@ -6,7 +6,7 @@
[![Latest-Release](https://img.shields.io/github/v/release/hyperion-project/hyperion.ng?include_prereleases&label=Latest%20Release&logo=github&logoColor=white&color=0f83e7)](https://github.com/hyperion-project/hyperion.ng/releases)
[![GitHub Actions](https://github.com/hyperion-project/hyperion.ng/workflows/Hyperion%20CI%20Build/badge.svg?branch=master)](https://github.com/hyperion-project/hyperion.ng/actions)
[![LGTM](https://img.shields.io/lgtm/grade/cpp/github/hyperion-project/hyperion.ng?label=Code%20Quality&logo=lgtm&logoColor=white&color=4bc51d)](https://lgtm.com/projects/g/hyperion-project/hyperion.ng/context:cpp)
[![CodeQL Analysis](https://github.com/hyperion-project/hyperion.ng/actions/workflows/codeql.yml/badge.svg)](https://github.com/hyperion-project/hyperion.ng/actions/workflows/codeql.yml)
[![Forum](https://img.shields.io/website/https/hyperion-project.org.svg?label=Forum&down_color=red&down_message=offline&up_color=4bc51d&up_message=online&logo=homeadvisor&logoColor=white)](https://www.hyperion-project.org)
[![Documentation](https://img.shields.io/website/https/docs.hyperion-project.org.svg?label=Documentation&down_color=red&down_message=offline&up_color=4bc51d&up_message=online&logo=read-the-docs)](https://docs.hyperion-project.org)
[![Discord](https://img.shields.io/discord/785578322167463937?label=Discord&logo=discord&logoColor=white&color=4bc51d)](https://discord.gg/khkR8Vx3ff)

View File

@ -153,10 +153,9 @@ to this service over the network.
srv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
srv.bind(('0.0.0.0', args.localport)) # lgtm [py/bind-socket-all-network-interfaces]
srv.bind(('0.0.0.0', args.localport))
try:
intentional_exit = False
while True:
try:
while True:
@ -180,7 +179,7 @@ to this service over the network.
# probably got disconnected
break
except KeyboardInterrupt:
intentional_exit = True
# intentional_exit
raise
except socket.error as msg:
if args.develop:
@ -190,6 +189,7 @@ to this service over the network.
ser_to_net.socket = None
sys.stderr.write('Disconnected\n')
except KeyboardInterrupt:
# do not handle exceptions
pass
sys.stderr.write('\n--- exit ---\n')

View File

@ -316,7 +316,7 @@ function showInfoDialog(type, header, message) {
$(document).on('click', '[data-dismiss-modal]', function () {
var target = $(this).attr('data-dismiss-modal');
$(target).modal('hide'); // lgtm [js/xss-through-dom]
$.find(target).modal('hide');
});
}
@ -1314,7 +1314,7 @@ function isValidIPv6(value) {
function isValidHostname(value) {
if (value.match(
'^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9])(.([a-zA-Z0-9]|[_a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9]))*$' //lgtm [js/redos]
'^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9])(.([a-zA-Z0-9]|[_a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9]))*$'
))
return true;
else
@ -1323,7 +1323,7 @@ function isValidHostname(value) {
function isValidServicename(value) {
if (value.match(
'^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9 -]{0,61}[a-zA-Z0-9])(.([a-zA-Z0-9]|[_a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9]))*$' //lgtm [js/redos]
'^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9 -]{0,61}[a-zA-Z0-9])(.([a-zA-Z0-9]|[_a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9]))*$'
))
return true;
else

View File

@ -30,7 +30,7 @@ while not hyperion.abort():
hyperion.setImage(width, 1, imageData)
# Move data into next state
for i in range(increment):
for unused in range(increment):
position += direction
if position == -1:
position = 1

View File

@ -12,7 +12,7 @@ hueIncrement = sleepTime / rotationTime
# Switch direction if needed
if reverse:
increment = -increment
hueIncrement = -hueIncrement
# Start the write data loop
hue = 0.0

View File

@ -14,7 +14,7 @@ if whiteLevel >= lvl:
# Initialize the led data
ledData = bytearray()
for i in range(hyperion.ledCount):
for unused in range(hyperion.ledCount):
ledData += bytearray((0,0,0))
runners = [

View File

@ -61,6 +61,7 @@ def buildGradient(cc, closeCircle = True):
ba += bytearray([0,lC[0],lC[1],lC[2],alpha])
return ba
return bytearray()
def rotateAngle( increment = 1):
global angle

View File

@ -45,7 +45,7 @@ class trail:
tr = []
for i in range(trails):
for unused in range(trails):
r = {'exec': trail()}
if randomise:

View File

@ -7,7 +7,6 @@ rotationTime = float(hyperion.args.get('rotation_time', 90))
colors = hyperion.args.get('colors', ((255,0,0),(255,255,0),(0,255,0),(0,255,255),(0,0,255),(255,0,255)))
reverse = bool(hyperion.args.get('reverse', False))
reverseTime = int(hyperion.args.get('reverse_time', 0))
#rotate = bool(hyperion.args.get('rotate', True))
positions = []
# calc center if random
@ -32,7 +31,7 @@ if centerY < 0.5:
else:
cY = 0.0+centerY
diag = int(round(math.sqrt(((cX*hyperion.imageWidth())**2)+((cY*hyperion.imageHeight())**2))))
diag = int(round(math.hypot(cX*hyperion.imageWidth(),cY*hyperion.imageHeight())))
# some diagonal overhead
diag = int(diag*1.3)
@ -45,9 +44,6 @@ for _ in colors:
# target time
targetTime = time.time()+float(reverseTime)
#hyperion.imageCOffset(int(hyperion.imageWidth()/2), int(hyperion.imageHeight()/2))
while not hyperion.abort():
# verify reverseTime, randomize reverseTime based on reverseTime up to reversedTime*2
if reverseTime >= 1:
@ -55,9 +51,7 @@ while not hyperion.abort():
if now > targetTime:
reverse = not reverse
targetTime = time.time()+random.uniform(float(reverseTime), float(reverseTime*2.0))
# apply rotate
#if rotate:
# hyperion.imageCRotate(1)
# prepare bytearray with colors and positions
gradientBa = bytearray()
it = 0

View File

@ -10,12 +10,12 @@ color2 = hyperion.args.get('color2', (255,0,0))
i = 0
ledDataOdd = bytearray()
while i < hyperion.ledCount:
for l in range(length):
for unused in range(length):
if i<hyperion.ledCount:
ledDataOdd += bytearray((int(color1[0]), int(color1[1]), int(color1[2])))
i += 1
for l in range(length):
for unused in range(length):
if i<hyperion.ledCount:
ledDataOdd += bytearray((int(color2[0]), int(color2[1]), int(color2[2])))
i += 1

View File

@ -157,11 +157,6 @@ protected:
///
bool setHyperionInstance(quint8 inst);
///
/// @brief Get all contrable components and their state
///
std::map<hyperion::Components, bool> getAllComponents();
///
/// @brief Check if Hyperion ist enabled
/// @return True when enabled else false

View File

@ -1,4 +1,3 @@
//#include <iostream>
#pragma once
// Utils includes
@ -219,7 +218,6 @@ namespace hyperion
|| !isBlack(image((width - x), y))
|| !isBlack(image((width - x), (height - y))))
{
// std::cout << "y " << y << " lt " << int(isBlack(color1)) << " lb " << int(isBlack(color2)) << " rt " << int(isBlack(color3)) << " rb " << int(isBlack(color4)) << std::endl;
firstNonBlackYPixelIndex = y;
break;
}

View File

@ -104,24 +104,6 @@ private slots:
private:
// template <typename Func1, typename Func2, typename std::enable_if_t<std::is_member_pointer<Func2>::value, int> = 0>
// static inline QMetaObject::Connection weakConnect(typename QtPrivate::FunctionPointer<Func1>::Object* sender,
// Func1 signal,
// typename QtPrivate::FunctionPointer<Func2>::Object* receiver,
// Func2 slot)
// {
// QMetaObject::Connection conn_normal = QObject::connect(sender, signal, receiver, slot);
// QMetaObject::Connection* conn_delete = new QMetaObject::Connection();
// *conn_delete = QObject::connect(sender, signal, [conn_normal, conn_delete]() {
// QObject::disconnect(conn_normal);
// QObject::disconnect(*conn_delete);
// delete conn_delete;
// });
// return conn_normal;
// }
template <typename Func1, typename Func2, typename std::enable_if_t<!std::is_member_pointer<Func2>::value, int> = 0>
static inline QMetaObject::Connection weakConnect(typename QtPrivate::FunctionPointer<Func1>::Object* sender,
Func1 signal,
@ -139,25 +121,6 @@ private:
return conn_normal;
}
// template <typename Func1, typename Func2, typename std::enable_if_t<!std::is_member_pointer<Func2>::value, int> = 0>
// static inline QMetaObject::Connection weakConnect(typename QtPrivate::FunctionPointer<Func1>::Object* sender,
// Func1 signal,
// typename QtPrivate::FunctionPointer<Func2>::Object* receiver,
// Func2 slot)
// {
// Q_UNUSED(receiver);
// QMetaObject::Connection conn_normal = QObject::connect(sender, signal, slot);
// QMetaObject::Connection* conn_delete = new QMetaObject::Connection();
// *conn_delete = QObject::connect(sender, signal, [conn_normal, conn_delete]() {
// QObject::disconnect(conn_normal);
// QObject::disconnect(*conn_delete);
// delete conn_delete;
// });
// return conn_normal;
// }
/// The logger instance for mDNS-Service
Logger* _log;

View File

@ -122,7 +122,7 @@ namespace NetUtils {
{
if (hostAddress.setAddress(hostname))
{
//Debug(log, "IP-address (%s) not required to be resolved.", QSTRING_CSTR(hostAddress.toString()));
// An IP-address is not required to be resolved
isHostAddressOK = true;
}
else

View File

@ -44,7 +44,7 @@ public:
int getBacklightThreshold() const;
/// @param backlightThreshold New lower brightness
void setBacklightThreshold(int backlightThreshold);
void setBacklightThreshold(double backlightThreshold);
/// @return The current state
bool getBacklightColored() const;

View File

@ -140,13 +140,12 @@ namespace hyperion {
{
// Special case for indices '*' => all leds
adjustment->setAdjustmentForLed(colorAdjustment->_id, 0, ledCnt-1);
//Info(Logger::getInstance("HYPERION"), "ColorAdjustment '%s' => [0-%d]", QSTRING_CSTR(colorAdjustment->_id), ledCnt-1);
continue;
}
if (!overallExp.match(ledIndicesStr).hasMatch())
{
//Error(Logger::getInstance("HYPERION"), "Given led indices %d not correct format: %s", i, QSTRING_CSTR(ledIndicesStr));
// Given LED indices are not correctly formatted
continue;
}
@ -173,7 +172,6 @@ namespace hyperion {
ss << index;
}
}
//Info(Logger::getInstance("HYPERION"), "ColorAdjustment '%s' => [%s]", QSTRING_CSTR(colorAdjustment->_id), ss.str().c_str());
}
return adjustment;

View File

@ -174,9 +174,9 @@ private:
if (!path.isEmpty())
{
QJsonObject obj;
modifyValue(subValue, obj, path, newValue, property);
subValue = obj;
QJsonObject tempObj;
modifyValue(subValue, tempObj, path, newValue, property);
subValue = tempObj;
}
else if (newValue != QJsonValue::Null)
subValue = newValue;

View File

@ -294,13 +294,6 @@ bool API::setHyperionInstance(quint8 inst)
return true;
}
std::map<hyperion::Components, bool> API::getAllComponents()
{
std::map<hyperion::Components, bool> comps;
//QMetaObject::invokeMethod(_hyperion, "getAllComponents", Qt::BlockingQueuedConnection, Q_RETURN_ARG(std::map<hyperion::Components, bool>, comps));
return comps;
}
bool API::isHyperionEnabled()
{
int res;

View File

@ -144,7 +144,6 @@ void JsonAPI::handleMessage(const QString &messageString, const QString &httpAut
{
const QString ident = "JsonRpc@" + _peerAddress;
QJsonObject message;
//std::cout << "JsonAPI::handleMessage | [" << static_cast<int>(_hyperion->getInstanceIndex()) << "] Received: ["<< messageString.toStdString() << "]" << std::endl;
// parse the message
if (!JsonUtils::parse(ident, messageString, message, _log))
@ -553,27 +552,6 @@ void JsonAPI::handleServerInfoCommand(const QJsonObject &message, const QString
info["ledDevices"] = ledDevices;
QJsonObject grabbers;
// *** Deprecated ***
//QJsonArray availableGrabbers;
//if ( GrabberWrapper::getInstance() != nullptr )
//{
// QStringList activeGrabbers = GrabberWrapper::getInstance()->getActive(_hyperion->getInstanceIndex());
// QJsonArray activeGrabberNames;
// for (auto grabberName : activeGrabbers)
// {
// activeGrabberNames.append(grabberName);
// }
// grabbers["active"] = activeGrabberNames;
//}
//for (auto grabber : GrabberWrapper::availableGrabbers(GrabberTypeFilter::ALL))
//{
// availableGrabbers.append(grabber);
//}
//grabbers["available"] = availableGrabbers;
QJsonObject screenGrabbers;
if (GrabberWrapper::getInstance() != nullptr)
{
@ -687,7 +665,6 @@ void JsonAPI::handleServerInfoCommand(const QJsonObject &message, const QString
QJsonObject obj;
obj.insert("friendly_name", entry["friendly_name"].toString());
obj.insert("instance", entry["instance"].toInt());
//obj.insert("last_use", entry["last_use"].toString());
obj.insert("running", entry["running"].toBool());
instanceInfo.append(obj);
}
@ -696,7 +673,7 @@ void JsonAPI::handleServerInfoCommand(const QJsonObject &message, const QString
// add leds configs
info["leds"] = _hyperion->getSetting(settings::LEDS).array();
// BEGIN | The following entries are derecated but used to ensure backward compatibility with hyperion Classic remote control
// BEGIN | The following entries are deprecated but used to ensure backward compatibility with hyperion Classic remote control
// TODO Output the real transformation information instead of default
// HOST NAME
@ -757,7 +734,6 @@ void JsonAPI::handleServerInfoCommand(const QJsonObject &message, const QString
const Hyperion::InputInfo &priorityInfo = _hyperion->getPriorityInfo(_hyperion->getCurrentPriority());
if (priorityInfo.componentId == hyperion::COMP_COLOR && !priorityInfo.ledColors.empty())
{
QJsonObject LEDcolor;
// check if LED Color not Black (0,0,0)
if ((priorityInfo.ledColors.begin()->red +
priorityInfo.ledColors.begin()->green +
@ -1309,8 +1285,8 @@ void JsonAPI::handleAuthorizeCommand(const QJsonObject &message, const QString &
// use comment
// for user authorized sessions
AuthManager::AuthDefinition def;
const QString res = API::createToken(comment, def);
if (res.isEmpty())
const QString createTokenResult = API::createToken(comment, def);
if (createTokenResult.isEmpty())
{
QJsonObject newTok;
newTok["comment"] = def.comment;
@ -1320,7 +1296,7 @@ void JsonAPI::handleAuthorizeCommand(const QJsonObject &message, const QString &
sendSuccessDataReply(QJsonDocument(newTok), command + "-" + subc, tan);
return;
}
sendErrorReply(res, command + "-" + subc, tan);
sendErrorReply(createTokenResult, command + "-" + subc, tan);
return;
}
@ -1328,13 +1304,13 @@ void JsonAPI::handleAuthorizeCommand(const QJsonObject &message, const QString &
if (subc == "renameToken")
{
// use id/comment
const QString res = API::renameToken(id, comment);
if (res.isEmpty())
const QString renameTokenResult = API::renameToken(id, comment);
if (renameTokenResult.isEmpty())
{
sendSuccessReply(command + "-" + subc, tan);
return;
}
sendErrorReply(res, command + "-" + subc, tan);
sendErrorReply(renameTokenResult, command + "-" + subc, tan);
return;
}
@ -1342,13 +1318,13 @@ void JsonAPI::handleAuthorizeCommand(const QJsonObject &message, const QString &
if (subc == "deleteToken")
{
// use id
const QString res = API::deleteToken(id);
if (res.isEmpty())
const QString deleteTokenResult = API::deleteToken(id);
if (deleteTokenResult.isEmpty())
{
sendSuccessReply(command + "-" + subc, tan);
return;
}
sendErrorReply(res, command + "-" + subc, tan);
sendErrorReply(deleteTokenResult, command + "-" + subc, tan);
return;
}
@ -1356,7 +1332,6 @@ void JsonAPI::handleAuthorizeCommand(const QJsonObject &message, const QString &
if (subc == "requestToken")
{
// use id/comment
const QString &comment = message["comment"].toString().trimmed();
const bool &acc = message["accept"].toBool(true);
if (acc)
API::setNewTokenRequest(comment, id, tan);
@ -1373,7 +1348,7 @@ void JsonAPI::handleAuthorizeCommand(const QJsonObject &message, const QString &
if (API::getPendingTokenRequests(vec))
{
QJsonArray arr;
for (const auto &entry : vec)
for (const auto &entry : qAsConst(vec))
{
QJsonObject obj;
obj["comment"] = entry.comment;
@ -1556,12 +1531,8 @@ void JsonAPI::handleLedDeviceCommand(const QJsonObject &message, const QString &
QString full_command = command + "-" + subc;
// TODO: Validate that device type is a valid one
/* if ( ! valid type )
{
sendErrorReply("Unknown device", full_command, tan);
}
else
*/ {
QJsonObject config;
config.insert("type", devType);
LedDevice* ledDevice = nullptr;
@ -1623,12 +1594,7 @@ void JsonAPI::handleInputSourceCommand(const QJsonObject& message, const QString
QString full_command = command + "-" + subc;
// TODO: Validate that source type is a valid one
/* if ( ! valid type )
{
sendErrorReply("Unknown device", full_command, tan);
}
else
*/ {
if (subc == "discover")
{
QJsonObject inputSourcesDiscovered;
@ -2007,6 +1973,11 @@ void JsonAPI::handleInstanceStateChange(InstanceState state, quint8 instance, co
handleInstanceSwitch();
}
break;
case InstanceState::H_STARTED:
case InstanceState::H_STOPPED:
case InstanceState::H_CREATED:
case InstanceState::H_DELETED:
default:
break;
}

View File

@ -148,7 +148,6 @@ void JsonCB::resetSubscriptions()
void JsonCB::setSubscriptionsTo(Hyperion* hyperion)
{
assert(hyperion);
//std::cout << "JsonCB::setSubscriptions for instance [" << static_cast<int>(hyperion->getInstanceIndex()) << "] " << std::endl;
// get current subs
QStringList currSubs(getSubscribedCommands());
@ -179,8 +178,6 @@ void JsonCB::doCallback(const QString& cmd, const QVariant& data)
else
obj["data"] = data.toJsonObject();
//std::cout << "JsonCB::doCallback | [" << static_cast<int>(_hyperion->getInstanceIndex()) << "] Send: [" << QJsonDocument(obj).toJson(QJsonDocument::Compact).toStdString() << "]" << std::endl;
emit newCallback(obj);
}
@ -398,7 +395,6 @@ void JsonCB::handleInstanceChange()
QJsonObject obj;
obj.insert("friendly_name", entry["friendly_name"].toString());
obj.insert("instance", entry["instance"].toInt());
//obj.insert("last_use", entry["last_use"].toString());
obj.insert("running", entry["running"].toBool());
arr.append(obj);
}

View File

@ -23,7 +23,5 @@ uint8_t BlackBorderDetector::calculateThreshold(double threshold) const
uint8_t blackborderThreshold = uint8_t(rgbThreshold);
//Debug(Logger::getInstance("BLACKBORDER"), "threshold set to %f (%d)", threshold , int(blackborderThreshold));
return blackborderThreshold;
}

View File

@ -1,4 +1,5 @@
#include <iostream>
#include <cmath>
#include <hyperion/Hyperion.h>
@ -33,6 +34,8 @@ BlackBorderProcessor::BlackBorderProcessor(Hyperion* hyperion, QObject* parent)
// listen for component state changes
connect(_hyperion, &Hyperion::compStateChangeRequest, this, &BlackBorderProcessor::handleCompStateChangeRequest);
_detector = new BlackBorderDetector(_oldThreshold);
}
BlackBorderProcessor::~BlackBorderProcessor()
@ -60,7 +63,7 @@ void BlackBorderProcessor::handleSettingsUpdate(settings::type type, const QJson
_detectionMode = obj["mode"].toString("default");
const double newThreshold = obj["threshold"].toDouble(5.0) / 100.0;
if (_oldThreshold != newThreshold)
if (fabs(_oldThreshold - newThreshold) > std::numeric_limits<double>::epsilon())
{
_oldThreshold = newThreshold;
@ -140,8 +143,6 @@ bool BlackBorderProcessor::updateBorder(const BlackBorder & newDetectedBorder)
// 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 << "c: " << setw(2) << _currentBorder.verticalSize << " " << setw(2) << _currentBorder.horizontalSize << " p: " << setw(2) << _previousDetectedBorder.verticalSize << " " << setw(2) << _previousDetectedBorder.horizontalSize << " n: " << setw(2) << newDetectedBorder.verticalSize << " " << setw(2) << newDetectedBorder.horizontalSize << " c:i " << setw(2) << _consistentCnt << ":" << setw(2) << _inconsistentCnt << std::endl;
// set the consistency counter
if (newDetectedBorder == _previousDetectedBorder)
{

View File

@ -106,8 +106,6 @@ QString BoblightClientConnection::readMessage(const char* data, const size_t siz
const int len = end - data + 1;
const QString message = QString::fromLatin1(data, len);
//std::cout << bytes << ": \"" << message.toUtf8().constData() << "\"" << std::endl;
return message;
}
@ -124,7 +122,6 @@ void BoblightClientConnection::socketClosed()
void BoblightClientConnection::handleMessage(const QString& message)
{
//std::cout << "boblight message: " << message.toStdString() << std::endl;
QStringList messageParts = QStringUtils::split(message, ' ', QStringUtils::SplitBehavior::SkipEmptyParts);
if (!messageParts.isEmpty())
{
@ -340,7 +337,6 @@ float BoblightClientConnection::parseFloat(const QString& s, bool *ok) const
{
if (ok)
{
//std::cout << "FAIL L " << q << ": " << s.toUtf8().constData() << std::endl;
*ok = false;
}
return 0;
@ -348,7 +344,6 @@ float BoblightClientConnection::parseFloat(const QString& s, bool *ok) const
if (ok)
{
//std::cout << "OK " << d << ": " << s.toUtf8().constData() << std::endl;
*ok = true;
}

View File

@ -12,7 +12,7 @@
#include <QFile>
/* Enable to turn on detailed CEC logs */
// #define VERBOSE_CEC
#define NO_VERBOSE_CEC
CECHandler::CECHandler()
{
@ -138,9 +138,9 @@ bool CECHandler::openAdapter(const CECAdapterDescriptor & descriptor)
if(!_cecAdapter->Open(descriptor.strComName))
{
Error(_logger, QString("Failed to open the CEC adaper on port %1")
.arg(descriptor.strComName)
.toLocal8Bit());
Error(_logger, "%s", QSTRING_CSTR(QString("Failed to open the CEC adaper on port %1")
.arg(descriptor.strComName))
);
return false;
}
@ -149,9 +149,9 @@ bool CECHandler::openAdapter(const CECAdapterDescriptor & descriptor)
void CECHandler::printAdapter(const CECAdapterDescriptor & descriptor) const
{
Info(_logger, QString("CEC Adapter:").toLocal8Bit());
Info(_logger, QString("\tName : %1").arg(descriptor.strComName).toLocal8Bit());
Info(_logger, QString("\tPath : %1").arg(descriptor.strComPath).toLocal8Bit());
Info(_logger, "%s", QSTRING_CSTR(QString("CEC Adapter:")));
Info(_logger, "%s", QSTRING_CSTR(QString("\tName : %1").arg(descriptor.strComName)));
Info(_logger, "%s", QSTRING_CSTR(QString("\tPath : %1").arg(descriptor.strComPath)));
}
QString CECHandler::scan() const
@ -180,12 +180,12 @@ QString CECHandler::scan() const
devices << device;
Info(_logger, QString("\tCECDevice: %1 / %2 / %3 / %4")
.arg(device["name"].toString())
.arg(device["vendor"].toString())
.arg(device["address"].toString())
.arg(device["power"].toString())
.toLocal8Bit());
Info(_logger, "%s", QSTRING_CSTR(QString("\tCECDevice: %1 / %2 / %3 / %4")
.arg(device["name"].toString(),
device["vendor"].toString(),
device["address"].toString(),
device["power"].toString()))
);
}
}
@ -305,16 +305,16 @@ void CECHandler::onCecCommandReceived(void * context, const CECCommand * command
{
if (command->opcode == CEC::CEC_OPCODE_SET_STREAM_PATH)
{
Info(handler->_logger, QString("CEC source activated: %1")
.arg(adapter->ToString(command->initiator))
.toLocal8Bit());
Info(handler->_logger, "%s", QSTRING_CSTR(QString("CEC source activated: %1")
.arg(adapter->ToString(command->initiator)))
);
emit handler->cecEvent(CECEvent::On);
}
if (command->opcode == CEC::CEC_OPCODE_STANDBY)
{
Info(handler->_logger, QString("CEC source deactivated: %1")
.arg(adapter->ToString(command->initiator))
.toLocal8Bit());
Info(handler->_logger, "%s", QSTRING_CSTR(QString("CEC source deactivated: %1")
.arg(adapter->ToString(command->initiator)))
);
emit handler->cecEvent(CECEvent::Off);
}
}

View File

@ -50,7 +50,7 @@ QSqlDatabase DBManager::getDB() const
db.setDatabaseName(_rootPath+"/db/"+_dbn+".db");
if(!db.open())
{
Error(_log, QSTRING_CSTR(db.lastError().text()));
Error(_log, "%s", QSTRING_CSTR(db.lastError().text()));
throw std::runtime_error("Failed to open database connection!");
}
return db;

View File

@ -126,12 +126,10 @@ void EffectEngine::handleUpdatedEffectList()
def.args["smoothing-time_ms"].toInt(),
def.args["smoothing-updateFrequency"].toDouble(),
0 );
//Debug( _log, "Customs Settings: Update effect %s, script %s, file %s, smoothCfg [%u]", QSTRING_CSTR(def.name), QSTRING_CSTR(def.script), QSTRING_CSTR(def.file), def.smoothCfg);
}
else
{
def.smoothCfg = SmoothingConfigID::SYSTEM;
//Debug( _log, "Default Settings: Update effect %s, script %s, file %s, smoothCfg [%u]", QSTRING_CSTR(def.name), QSTRING_CSTR(def.script), QSTRING_CSTR(def.file), def.smoothCfg);
}
_availableEffects.push_back(def);
}

View File

@ -53,9 +53,12 @@ PyObject *EffectModule::json2python(const QJsonValue &jsonData)
Py_RETURN_NOTIMPLEMENTED;
case QJsonValue::Double:
{
if (std::round(jsonData.toDouble()) != jsonData.toDouble())
double doubleIntegratlPart;
double doubleFractionalPart = std::modf(jsonData.toDouble(), &doubleIntegratlPart);
if (doubleFractionalPart > std::numeric_limits<double>::epsilon())
{
return Py_BuildValue("d", jsonData.toDouble());
}
return Py_BuildValue("i", jsonData.toInt());
}
case QJsonValue::Bool:
@ -184,7 +187,8 @@ PyObject* EffectModule::wrapSetColor(PyObject *self, PyObject *args)
PyObject* EffectModule::wrapSetImage(PyObject *self, PyObject *args)
{
// bytearray of values
int width, height;
int width = 0;
int height = 0;
PyObject * bytearray = nullptr;
if (PyArg_ParseTuple(args, "iiO", &width, &height, &bytearray))
{
@ -391,8 +395,10 @@ PyObject* EffectModule::wrapImageLinearGradient(PyObject *self, PyObject *args)
int startRY = 0;
int startX = 0;
int startY = 0;
int endX, width = getEffect()->_imageSize.width();
int endY, height = getEffect()->_imageSize.height();
int width = getEffect()->_imageSize.width();
int endX {width};
int height = getEffect()->_imageSize.height();
int endY {height};
int spread = 0;
bool argsOK = false;
@ -454,7 +460,9 @@ PyObject* EffectModule::wrapImageConicalGradient(PyObject *self, PyObject *args)
{
int argCount = PyTuple_Size(args);
PyObject * bytearray = nullptr;
int centerX, centerY, angle;
int centerX = 0;
int centerY = 0;
int angle = 0;
int startX = 0;
int startY = 0;
int width = getEffect()->_imageSize.width();
@ -520,7 +528,13 @@ PyObject* EffectModule::wrapImageRadialGradient(PyObject *self, PyObject *args)
{
int argCount = PyTuple_Size(args);
PyObject * bytearray = nullptr;
int centerX, centerY, radius, focalX, focalY, focalRadius, spread;
int centerX = 0;
int centerY = 0;
int radius = 0;
int focalX = 0;
int focalY = 0;
int focalRadius =0;
int spread = 0;
int startX = 0;
int startY = 0;
int width = getEffect()->_imageSize.width();
@ -599,7 +613,9 @@ PyObject* EffectModule::wrapImageDrawPolygon(PyObject *self, PyObject *args)
PyObject * bytearray = nullptr;
int argCount = PyTuple_Size(args);
int r, g, b;
int r = 0;
int g = 0;
int b = 0;
int a = 255;
bool argsOK = false;
@ -658,7 +674,9 @@ PyObject* EffectModule::wrapImageDrawPie(PyObject *self, PyObject *args)
QString brush;
int argCount = PyTuple_Size(args);
int radius, centerX, centerY;
int radius = 0;
int centerX = 0;
int centerY = 0;
int startAngle = 0;
int spanAngle = 360;
int r = 0;
@ -749,7 +767,9 @@ PyObject* EffectModule::wrapImageDrawPie(PyObject *self, PyObject *args)
PyObject* EffectModule::wrapImageSolidFill(PyObject *self, PyObject *args)
{
int argCount = PyTuple_Size(args);
int r, g, b;
int r = 0;
int g = 0;
int b = 0;
int a = 255;
int startX = 0;
int startY = 0;
@ -788,7 +808,9 @@ PyObject* EffectModule::wrapImageSolidFill(PyObject *self, PyObject *args)
PyObject* EffectModule::wrapImageDrawLine(PyObject *self, PyObject *args)
{
int argCount = PyTuple_Size(args);
int r, g, b;
int r = 0;
int g = 0;
int b = 0;
int a = 255;
int startX = 0;
int startY = 0;
@ -826,7 +848,11 @@ PyObject* EffectModule::wrapImageDrawLine(PyObject *self, PyObject *args)
PyObject* EffectModule::wrapImageDrawPoint(PyObject *self, PyObject *args)
{
int argCount = PyTuple_Size(args);
int r, g, b, x, y;
int r = 0;
int g = 0;
int b = 0;
int x = 0;
int y = 0;
int a = 255;
int thick = 1;
@ -859,7 +885,9 @@ PyObject* EffectModule::wrapImageDrawPoint(PyObject *self, PyObject *args)
PyObject* EffectModule::wrapImageDrawRect(PyObject *self, PyObject *args)
{
int argCount = PyTuple_Size(args);
int r, g, b;
int r = 0;
int g = 0;
int b = 0;
int a = 255;
int startX = 0;
int startY = 0;
@ -898,7 +926,11 @@ PyObject* EffectModule::wrapImageDrawRect(PyObject *self, PyObject *args)
PyObject* EffectModule::wrapImageSetPixel(PyObject *self, PyObject *args)
{
int argCount = PyTuple_Size(args);
int r, g, b, x, y;
int r = 0;
int g = 0;
int b = 0;
int x = 0;
int y = 0;
if ( argCount == 5 && PyArg_ParseTuple(args, "iiiii", &x, &y, &r, &g, &b ) )
{
@ -913,7 +945,8 @@ PyObject* EffectModule::wrapImageSetPixel(PyObject *self, PyObject *args)
PyObject* EffectModule::wrapImageGetPixel(PyObject *self, PyObject *args)
{
int argCount = PyTuple_Size(args);
int x, y;
int x = 0;
int y = 0;
if ( argCount == 2 && PyArg_ParseTuple(args, "ii", &x, &y) )
{
@ -934,7 +967,8 @@ PyObject* EffectModule::wrapImageSave(PyObject *self, PyObject *args)
PyObject* EffectModule::wrapImageMinSize(PyObject *self, PyObject *args)
{
int argCount = PyTuple_Size(args);
int w, h;
int w = 0;
int h = 0;
int width = getEffect()->_imageSize.width();
int height = getEffect()->_imageSize.height();
@ -994,7 +1028,8 @@ PyObject* EffectModule::wrapImageCOffset(PyObject *self, PyObject *args)
PyObject* EffectModule::wrapImageCShear(PyObject *self, PyObject *args)
{
int sh,sv;
int sh = 0;
int sv = 0;
int argCount = PyTuple_Size(args);
if ( argCount == 2 && PyArg_ParseTuple(args, "ii", &sh, &sv ))

View File

@ -138,7 +138,7 @@ void MessageForwarder::enableTargets(bool enable, const QJsonObject& config)
else
{
_forwarder_enabled = false;
Warning(_log,"No JSON- nor Flatbuffer-Forwarder configured -> Forwarding disabled", _forwarder_enabled);
Warning(_log,"No JSON- nor Flatbuffer-Forwarder configured -> Forwarding disabled");
}
}
_hyperion->setNewComponentState(hyperion::COMP_FORWARDER, _forwarder_enabled);

View File

@ -223,13 +223,11 @@ void EncoderThread::processImageMjpeg()
{
_xform->options = TJXOPT_CROP;
_xform->r = tjregion {_cropLeft,_cropTop,transformedWidth,transformedHeight};
//qDebug() << "processImageMjpeg() | _doTransform - Image cropped: transformedWidth: " << transformedWidth << " transformedHeight: " << transformedHeight;
}
else
{
_xform->options = 0;
_xform->r = tjregion {0,0,_width,_height};
//qDebug() << "processImageMjpeg() | _doTransform - Image not cropped: _width: " << _width << " _height: " << _height;
}
_xform->options |= TJXOPT_TRIM;
@ -344,11 +342,9 @@ bool EncoderThread::onError(const QString context) const
#if LIBJPEG_TURBO_VERSION_NUMBER > 2000000
if (tjGetErrorCode(_tjInstance) == TJERR_FATAL)
{
//qDebug() << context << "Error: " << QString(tjGetErrorStr2(_tjInstance));
treatAsError = true;
}
#else
//qDebug() << context << "Error: " << QString(tjGetErrorStr());
treatAsError = true;
#endif

View File

@ -1209,7 +1209,7 @@ void V4L2Grabber::setCecDetectionEnable(bool enable)
{
_cecDetectionEnabled = enable;
if(_initialized)
Info(_log, QString("CEC detection is now %1").arg(enable ? "enabled" : "disabled").toLocal8Bit());
Info(_log, "%s", QSTRING_CSTR(QString("CEC detection is now %1").arg(enable ? "enabled" : "disabled")));
}
}
@ -1501,19 +1501,19 @@ void V4L2Grabber::enumVideoCaptureDevices()
// Enumerate video control IDs
QList<DeviceControls> deviceControlList;
for (auto it = _controlIDPropertyMap->constBegin(); it != _controlIDPropertyMap->constEnd(); it++)
for (auto itDeviceControls = _controlIDPropertyMap->constBegin(); itDeviceControls != _controlIDPropertyMap->constEnd(); itDeviceControls++)
{
struct v4l2_queryctrl queryctrl;
CLEAR(queryctrl);
queryctrl.id = it.key();
queryctrl.id = itDeviceControls.key();
if (xioctl(fd, VIDIOC_QUERYCTRL, &queryctrl) < 0)
break;
if (queryctrl.flags & V4L2_CTRL_FLAG_DISABLED)
break;
DeviceControls control;
control.property = it.value();
control.property = itDeviceControls.value();
control.minValue = queryctrl.minimum;
control.maxValue = queryctrl.maximum;
control.step = queryctrl.step;
@ -1524,13 +1524,13 @@ void V4L2Grabber::enumVideoCaptureDevices()
CLEAR(ctrl);
CLEAR(ctrls);
ctrl.id = it.key();
ctrl.id = itDeviceControls.key();
ctrls.count = 1;
ctrls.controls = &ctrl;
if (xioctl(fd, VIDIOC_G_EXT_CTRLS, &ctrls) == 0)
{
control.currentValue = ctrl.value;
DebugIf(verbose, _log, "%s: min=%i, max=%i, step=%i, default=%i, current=%i", QSTRING_CSTR(it.value()), control.minValue, control.maxValue, control.step, control.defaultValue, control.currentValue);
DebugIf(verbose, _log, "%s: min=%i, max=%i, step=%i, default=%i, current=%i", QSTRING_CSTR(itDeviceControls.value()), control.minValue, control.maxValue, control.step, control.defaultValue, control.currentValue);
}
else
break;

View File

@ -170,12 +170,12 @@ bool X11Grabber::setupDisplay()
XShmQueryVersion(_x11Display, &dummy, &dummy, &pixmaps_supported);
_XShmPixmapAvailable = pixmaps_supported && XShmPixmapFormat(_x11Display) == ZPixmap;
Info(_log, QString("XRandR=[%1] XRender=[%2] XShm=[%3] XPixmap=[%4]")
.arg(_XRandRAvailable ? "available" : "unavailable")
.arg(_XRenderAvailable ? "available" : "unavailable")
.arg(_XShmAvailable ? "available" : "unavailable")
.arg(_XShmPixmapAvailable ? "available" : "unavailable")
.toStdString().c_str());
Info(_log, "%s", QSTRING_CSTR(QString("XRandR=[%1] XRender=[%2] XShm=[%3] XPixmap=[%4]")
.arg(_XRandRAvailable ? "available" : "unavailable",
_XRenderAvailable ? "available" : "unavailable",
_XShmAvailable ? "available" : "unavailable",
_XShmPixmapAvailable ? "available" : "unavailable"))
);
result = (updateScreenDimensions(true) >=0);
ErrorIf(!result, _log, "X11 Grabber start failed");

View File

@ -242,12 +242,12 @@ bool XcbGrabber::setupDisplay()
setupRender();
setupShm();
Info(_log, QString("XcbRandR=[%1] XcbRender=[%2] XcbShm=[%3] XcbPixmap=[%4]")
.arg(_XcbRandRAvailable ? "available" : "unavailable")
.arg(_XcbRenderAvailable ? "available" : "unavailable")
.arg(_XcbShmAvailable ? "available" : "unavailable")
.arg(_XcbShmPixmapAvailable ? "available" : "unavailable")
.toStdString().c_str());
Info(_log, "%s", QSTRING_CSTR(QString("XcbRandR=[%1] XcbRender=[%2] XcbShm=[%3] XcbPixmap=[%4]")
.arg(_XcbRandRAvailable ? "available" : "unavailable",
_XcbRenderAvailable ? "available" : "unavailable",
_XcbShmAvailable ? "available" : "unavailable",
_XcbShmPixmapAvailable ? "available" : "unavailable"))
);
result = (updateScreenDimensions(true) >= 0);
ErrorIf(!result, _log, "XCB Grabber start failed");

View File

@ -261,26 +261,24 @@ void AuthManager::checkTimeout()
void AuthManager::checkAuthBlockTimeout()
{
// handle user auth block
for (auto it = _userAuthAttempts.begin(); it != _userAuthAttempts.end(); it++)
{
QMutableVectorIterator<uint64_t> itUserAuth(_userAuthAttempts);
while (itUserAuth.hasNext()) {
// after 10 minutes, we remove the entry
if (*it < (uint64_t)QDateTime::currentMSecsSinceEpoch())
{
_userAuthAttempts.erase(it--);
}
if (itUserAuth.next() < static_cast<uint64_t>(QDateTime::currentMSecsSinceEpoch()))
itUserAuth.remove();
}
// handle token auth block
for (auto it = _tokenAuthAttempts.begin(); it != _tokenAuthAttempts.end(); it++)
{
QMutableVectorIterator<uint64_t> itTokenAuth(_tokenAuthAttempts);
while (itTokenAuth.hasNext()) {
// after 10 minutes, we remove the entry
if (*it < (uint64_t)QDateTime::currentMSecsSinceEpoch())
{
_tokenAuthAttempts.erase(it--);
}
if (itTokenAuth.next() < static_cast<uint64_t>(QDateTime::currentMSecsSinceEpoch()))
itTokenAuth.remove();
}
// if the lists are empty we stop
if (_userAuthAttempts.empty() && _tokenAuthAttempts.empty())
{
_authBlockTimer->stop();
}
}

View File

@ -233,9 +233,6 @@ void Hyperion::freeObjects()
void Hyperion::handleSettingsUpdate(settings::type type, const QJsonDocument& config)
{
// std::cout << "Hyperion::handleSettingsUpdate" << std::endl;
// std::cout << config.toJson().toStdString() << std::endl;
if(type == settings::COLOR)
{
const QJsonObject obj = config.object();

View File

@ -406,7 +406,6 @@ void LinearColorSmoothing::performDecay(const int64_t now) {
if(microsTillNextAction > SLEEP_RES_MICROS) {
const int64_t wait = std::min(microsTillNextAction - SLEEP_RES_MICROS, SLEEP_MAX_MICROS);
//usleep(wait);
std::this_thread::sleep_for(std::chrono::microseconds(wait));
}
}
@ -542,7 +541,6 @@ void LinearColorSmoothing::queueColors(const std::vector<ColorRgb> &ledColors)
void LinearColorSmoothing::clearQueuedColors()
{
_timer->stop();
//QMetaObject::invokeMethod(_timer, "stop", Qt::QueuedConnection);
_previousValues.clear();
_targetValues.clear();

View File

@ -42,11 +42,8 @@ void MultiColorAdjustment::setAdjustmentForLed(const QString& id, int startLed,
// Get the identified adjustment (don't care if is nullptr)
ColorAdjustment * adjustment = getAdjustment(id);
//Debug(_log,"ColorAdjustment Profile [%s], startLed[%d], endLed[%d]", QSTRING_CSTR(id), startLed, endLed);
for (int iLed=startLed; iLed<=endLed; ++iLed)
{
//Debug(_log,"_ledAdjustments [%d] -> [%p]", iLed, adjustment);
_ledAdjustments[iLed] = adjustment;
}
}

View File

@ -16,7 +16,7 @@
"title" : "edt_conf_general_port_title",
"minimum" : 80,
"maximum" : 65535,
"default" : 8090,
"default" : 8090.3,
"propertyOrder" : 3
},
"sslPort" :

View File

@ -234,8 +234,6 @@ void LedDevice::startRefreshTimer()
connect(_refreshTimer, &QTimer::timeout, this, &LedDevice::rewriteLEDs);
}
_refreshTimer->setInterval(_refreshTimerInterval_ms);
//Debug(_log, "Start refresh timer with interval = %ims", _refreshTimer->interval());
_refreshTimer->start();
}
else
@ -249,11 +247,9 @@ void LedDevice::stopRefreshTimer()
{
if (_refreshTimer != nullptr)
{
//Debug(_log, "Stopping refresh timer");
_refreshTimer->stop();
delete _refreshTimer;
_refreshTimer = nullptr;
}
}
@ -302,7 +298,7 @@ int LedDevice::updateLeds(std::vector<ColorRgb> ledValues)
int retval = 0;
if (!_isEnabled || !_isOn || !_isDeviceReady || _isDeviceInError)
{
//std::cout << "LedDevice::updateLeds(), LedDevice NOT ready! ";
// LedDevice NOT ready!
retval = -1;
}
else
@ -310,7 +306,6 @@ int LedDevice::updateLeds(std::vector<ColorRgb> ledValues)
qint64 elapsedTimeMs = _lastWriteTime.msecsTo(QDateTime::currentDateTime());
if (_latchTime_ms == 0 || elapsedTimeMs >= _latchTime_ms)
{
//std::cout << "LedDevice::updateLeds(), Elapsed time since last write (" << elapsedTimeMs << ") ms > _latchTime_ms (" << _latchTime_ms << ") ms" << std::endl;
retval = write(ledValues);
_lastWriteTime = QDateTime::currentDateTime();
@ -323,7 +318,7 @@ int LedDevice::updateLeds(std::vector<ColorRgb> ledValues)
}
else
{
//std::cout << "LedDevice::updateLeds(), Skip write. elapsedTime (" << elapsedTimeMs << ") ms < _latchTime_ms (" << _latchTime_ms << ") ms" << std::endl;
// Skip write as elapsedTime < latchTime
if (_isRefreshEnabled)
{
//Stop timer to allow for next non-refresh update
@ -340,14 +335,6 @@ int LedDevice::rewriteLEDs()
if (_isEnabled && _isOn && _isDeviceReady && !_isDeviceInError)
{
// qint64 elapsedTimeMs = _lastWriteTime.msecsTo(QDateTime::currentDateTime());
// std::cout << "LedDevice::rewriteLEDs(): Rewrite LEDs now, elapsedTime [" << elapsedTimeMs << "] ms" << std::endl;
// //:TESTING: Inject "white" output records to differentiate from normal writes
// _lastLedValues.clear();
// _lastLedValues.resize(static_cast<unsigned long>(_ledCount), ColorRgb::WHITE);
// printLedValues(_lastLedValues);
// //:TESTING:
if (!_lastLedValues.empty())
{
retval = write(_lastLedValues);
@ -490,12 +477,15 @@ bool LedDevice::storeState()
{
bool rc{ true };
#if 0
if (_isRestoreOrigState)
{
// Save device's original state
// _originalStateValues = get device's state;
// store original power on/off state, if available
}
#endif
return rc;
}
@ -503,12 +493,14 @@ bool LedDevice::restoreState()
{
bool rc{ true };
#if 0
if (_isRestoreOrigState)
{
// Restore device's original state
// update device using _originalStateValues
// update original power on/off state, if supported
}
#endif
return rc;
}
@ -699,4 +691,3 @@ QString LedDevice::getColorOrder() const
bool LedDevice::componentState() const {
return _isEnabled;
}

View File

@ -69,12 +69,14 @@ int LedDeviceTemplate::close()
int retval = 0;
_isDeviceReady = false;
#if 0
// Test, if device requires closing
if ( true /*If device is still open*/ )
{
// Close device
// Everything is OK -> device is closed
}
#endif
return retval;
}

View File

@ -63,7 +63,9 @@ bool LedDeviceHyperionUsbasp::init(const QJsonObject &deviceConfig)
else
{
Debug(_log, "USB context initialized");
//libusb_set_debug(_libusbContext, 3);
#if 0
libusb_set_debug(_libusbContext, 3);
#endif
// retrieve the list of USB devices
libusb_device ** deviceList;

View File

@ -331,8 +331,6 @@ const QString &LedDeviceLightpack::getSerialNumber() const
int LedDeviceLightpack::writeBytes(uint8_t *data, int size)
{
int rc = 0;
//Debug( _log, "[%s]", QSTRING_CSTR(uint8_t_to_hex_string(data, size, 32)) );
int error = libusb_control_transfer(_deviceHandle,
static_cast<uint8_t>( LIBUSB_ENDPOINT_OUT | LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_INTERFACE ),
0x09,

View File

@ -73,8 +73,8 @@ int ProviderHID::open()
// Failed to open the device
this->setInError( "Failed to open HID device. Maybe your PID/VID setting is wrong? Make sure to add a udev rule/use sudo." );
#if 0
// 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;
@ -88,7 +88,8 @@ int ProviderHID::open()
cur_dev = cur_dev->next;
}
hid_free_enumeration(devs);
*/
#endif
}
else
{

View File

@ -45,7 +45,6 @@ const char PANEL_NUM[] = "numPanels";
const char PANEL_ID[] = "panelId";
const char PANEL_POSITIONDATA[] = "positionData";
const char PANEL_SHAPE_TYPE[] = "shapeType";
//const char PANEL_ORIENTATION[] = "0";
const char PANEL_POS_X[] = "x";
const char PANEL_POS_Y[] = "y";
@ -72,7 +71,6 @@ const quint16 STREAM_CONTROL_DEFAULT_PORT = 60222;
const int API_DEFAULT_PORT = 16021;
const char API_BASE_PATH[] = "/api/v1/%1/";
const char API_ROOT[] = "";
//const char API_EXT_MODE_STRING_V1[] = "{\"write\" : {\"command\" : \"display\", \"animType\" : \"extControl\"}}";
const char API_EXT_MODE_STRING_V2[] = "{\"write\" : {\"command\" : \"display\", \"animType\" : \"extControl\", \"extControlVersion\" : \"v2\"}}";
const char API_STATE[] = "state";
const char API_PANELLAYOUT[] = "panelLayout";
@ -243,7 +241,6 @@ bool LedDeviceNanoleaf::initLedsConfiguration()
int panelX = panelObj[PANEL_POS_X].toInt();
int panelY = panelObj[PANEL_POS_Y].toInt();
int panelshapeType = panelObj[PANEL_SHAPE_TYPE].toInt();
//int panelOrientation = panelObj[PANEL_ORIENTATION].toInt();
DebugIf(verbose,_log, "Panel [%d] (%d,%d) - Type: [%d]", panelId, panelX, panelY, panelshapeType);
@ -613,16 +610,16 @@ bool LedDeviceNanoleaf::storeState()
// effect
_restApi->setPath(API_EFFECT);
httpResponse response = _restApi->get();
if ( response.error() )
httpResponse responseEffects = _restApi->get();
if ( responseEffects.error() )
{
QString errorReason = QString("Storing device state failed with error: '%1'").arg(response.getErrorReason());
QString errorReason = QString("Storing device state failed with error: '%1'").arg(responseEffects.getErrorReason());
setInError(errorReason);
rc = false;
}
else
{
QJsonObject effects = response.getBody().object();
QJsonObject effects = responseEffects.getBody().object();
DebugIf(verbose, _log, "effects: [%s]", QString(QJsonDocument(_originalStateProperties).toJson(QJsonDocument::Compact)).toUtf8().constData() );
_originalEffect = effects[API_EFFECT_SELECT].toString();
_originalIsDynEffect = _originalEffect == "*Dynamic*" || _originalEffect == "*Solid*";
@ -774,7 +771,7 @@ int LedDeviceNanoleaf::write(const std::vector<ColorRgb>& ledValues)
}
else
{
// Set panels not configured to black;
// Set panels not configured to black
color = ColorRgb::BLACK;
DebugIf(verbose3, _log, "[%d] >= panelLedCount [%d] => Set to BLACK", panelCounter, _panelLedCount);
}

View File

@ -38,7 +38,6 @@ const char CONFIG_VERBOSE[] = "verbose";
const char DEV_DATA_BRIDGEID[] = "bridgeid";
const char DEV_DATA_MODEL[] = "modelid";
const char DEV_DATA_NAME[] = "name";
//const char DEV_DATA_MANUFACTURER[] = "manufacturer";
const char DEV_DATA_FIRMWAREVERSION[] = "swversion";
const char DEV_DATA_APIVERSION[] = "apiversion";
@ -65,7 +64,6 @@ const char API_STREAM_RESPONSE_FORMAT[] = "/%1/%2/%3/%4";
// List of resources
const char API_XY_COORDINATES[] = "xy";
const char API_BRIGHTNESS[] = "bri";
//const char API_SATURATION[] = "sat";
const char API_TRANSITIONTIME[] = "transitiontime";
const char API_MODEID[] = "modelid";
@ -188,7 +186,6 @@ CiColor CiColor::rgbToCiColor(double red, double green, double blue, const CiCol
}
if (dBC < lowest)
{
//lowest = dBC;
closestPoint = pBC;
}
// Change the xy value to a value which is within the reach of the lamp.
@ -1089,7 +1086,7 @@ bool LedDevicePhilipsHue::init(const QJsonObject &deviceConfig)
if( _groupId == 0 )
{
Error(_log, "Disabling usage of HueEntertainmentAPI: Group-ID is invalid", "%d", _groupId);
Error(_log, "Disabling usage of HueEntertainmentAPI: Group-ID [%d] is invalid", _groupId);
_useHueEntertainmentAPI = false;
}
}

View File

@ -141,10 +141,6 @@ bool LedDeviceRazer::checkApiError(const httpResponse& response)
else
{
QString errorReason;
QString strJson(response.getBody().toJson(QJsonDocument::Compact));
//DebugIf(verbose, _log, "Reply: [%s]", strJson.toUtf8().constData());
QJsonObject jsonObj = response.getBody().object();
if (!jsonObj[API_RESULT].isNull())

View File

@ -20,15 +20,20 @@ const ushort E131_DEFAULT_PORT = 5568;
/* defined parameters from http://tsp.esta.org/tsp/documents/docs/BSR_E1-31-20xx_CP-2014-1009r2.pdf */
const uint32_t VECTOR_ROOT_E131_DATA = 0x00000004;
//#define VECTOR_ROOT_E131_EXTENDED 0x00000008
const uint8_t VECTOR_DMP_SET_PROPERTY = 0x02;
const uint32_t VECTOR_E131_DATA_PACKET = 0x00000002;
//#define VECTOR_E131_EXTENDED_SYNCHRONIZATION 0x00000001
//#define VECTOR_E131_EXTENDED_DISCOVERY 0x00000002
//#define VECTOR_UNIVERSE_DISCOVERY_UNIVERSE_LIST 0x00000001
//#define E131_E131_UNIVERSE_DISCOVERY_INTERVAL 10 // seconds
//#define E131_NETWORK_DATA_LOSS_TIMEOUT 2500 // milli econds
//#define E131_DISCOVERY_UNIVERSE 64214
#if 0
#define VECTOR_ROOT_E131_EXTENDED 0x00000008
#define VECTOR_E131_EXTENDED_SYNCHRONIZATION 0x00000001
#define VECTOR_E131_EXTENDED_DISCOVERY 0x00000002
#define VECTOR_UNIVERSE_DISCOVERY_UNIVERSE_LIST 0x00000001
#define E131_E131_UNIVERSE_DISCOVERY_INTERVAL 10 // seconds
#define E131_NETWORK_DATA_LOSS_TIMEOUT 2500 // milli econds
#define E131_DISCOVERY_UNIVERSE 64214
#endif
const int DMX_MAX = 512; // 512 usable slots
}

View File

@ -20,28 +20,30 @@
**/
/* E1.31 Packet Offsets */
//#define E131_ROOT_PREAMBLE_SIZE 0
//#define E131_ROOT_POSTAMBLE_SIZE 2
//#define E131_ROOT_ID 4
//#define E131_ROOT_FLENGTH 16
//#define E131_ROOT_VECTOR 18
//#define E131_ROOT_CID 22
#if 0
#define E131_ROOT_PREAMBLE_SIZE 0
#define E131_ROOT_POSTAMBLE_SIZE 2
#define E131_ROOT_ID 4
#define E131_ROOT_FLENGTH 16
#define E131_ROOT_VECTOR 18
#define E131_ROOT_CID 22
//#define E131_FRAME_FLENGTH 38
//#define E131_FRAME_VECTOR 40
//#define E131_FRAME_SOURCE 44
//#define E131_FRAME_PRIORITY 108
//#define E131_FRAME_RESERVED 109
//#define E131_FRAME_SEQ 111
//#define E131_FRAME_OPT 112
//#define E131_FRAME_UNIVERSE 113
#define E131_FRAME_FLENGTH 38
#define E131_FRAME_VECTOR 40
#define E131_FRAME_SOURCE 44
#define E131_FRAME_PRIORITY 108
#define E131_FRAME_RESERVED 109
#define E131_FRAME_SEQ 111
#define E131_FRAME_OPT 112
#define E131_FRAME_UNIVERSE 113
//#define E131_DMP_FLENGTH 115
//#define E131_DMP_VECTOR 117
//#define E131_DMP_TYPE 118
//#define E131_DMP_ADDR_FIRST 119
//#define E131_DMP_ADDR_INC 121
//#define E131_DMP_COUNT 123
#define E131_DMP_FLENGTH 115
#define E131_DMP_VECTOR 117
#define E131_DMP_TYPE 118
#define E131_DMP_ADDR_FIRST 119
#define E131_DMP_ADDR_INC 121
#define E131_DMP_COUNT 123
#endif
const unsigned int E131_DMP_DATA=125;
/* E1.31 Packet Structure */

View File

@ -40,7 +40,6 @@ const char WLED_VERSION_DDP[] = "0.11.0";
const int API_DEFAULT_PORT = -1; //Use default port per communication scheme
const char API_BASE_PATH[] = "/json/";
//const char API_PATH_INFO[] = "info";
const char API_PATH_STATE[] = "state";
// List of State Information
@ -415,7 +414,7 @@ QJsonObject LedDeviceWled::getProperties(const QJsonObject& params)
}
else
{
Info(_log, "DDP streaming is supported by your WLED device version [%s]. No limitation in number of LEDs.", currentVersion.getVersion().c_str(), ddpVersion.getVersion().c_str());
Info(_log, "DDP streaming is supported by your WLED device version [%s]. No limitation in number of LEDs.", currentVersion.getVersion().c_str());
}
}
properties.insert("properties", propertiesDetails);

View File

@ -82,7 +82,6 @@ const char API_PROP_BRIGHT[] = "bright";
// List of Result Information
const char API_RESULT_ID[] = "id";
const char API_RESULT[] = "result";
//const char API_RESULT_OK[] = "OK";
// List of Error Information
const char API_ERROR[] = "error";
@ -383,8 +382,6 @@ bool YeelightLight::streamCommand( const QJsonDocument &command )
{
log ( 2, "Info:", "Skip write. Device is in error");
}
//log (2,"streamCommand() rc","%d, isON[%d], isInMusicMode[%d]", rc, _isOn, _isInMusicMode );
return rc;
}
@ -392,8 +389,6 @@ YeelightResponse YeelightLight::handleResponse(int correlationID, QByteArray con
{
log (3,"handleResponse()","" );
//std::cout << _name.toStdString() <<"| Response: [" << response.toStdString() << "]" << std::endl << std::flush;
YeelightResponse yeeResponse;
QString errorReason;
@ -446,8 +441,6 @@ YeelightResponse YeelightLight::handleResponse(int correlationID, QByteArray con
else
{
int id = jsonObj[API_RESULT_ID].toInt();
//log ( 3, "Correlation ID:", "%d", id );
if ( id != correlationID && TEST_CORRELATION_IDS)
{
errorReason = QString ("%1| API is out of sync, received ID [%2], expected [%3]").
@ -528,9 +521,6 @@ QJsonObject YeelightLight::getProperties()
log (3,"getProperties()","" );
QJsonObject properties;
//Selected properties
//QJsonArray propertyList = { API_PROP_NAME, API_PROP_MODEL, API_PROP_POWER, API_PROP_RGB, API_PROP_BRIGHT, API_PROP_CT, API_PROP_FWVER };
//All properties
QJsonArray propertyList = {"power","bright","ct","rgb","hue","sat","color_mode","flowing","delayoff","music_on","name","bg_power","bg_flowing","bg_ct","bg_bright","bg_hue","bg_sat","bg_rgb","nl_br","active_mode" };
@ -579,9 +569,6 @@ bool YeelightLight::identify()
*/
QJsonArray colorflowParams = { API_PROP_COLORFLOW, 6, 0, "500,1,100,100,500,1,16711696,10"};
//Blink White
//QJsonArray colorflowParams = { API_PROP_COLORFLOW, 6, 0, "500,2,4000,1,500,2,4000,50"};
QJsonDocument command = getCommand( API_METHOD_SETSCENE, colorflowParams );
if ( writeCommand( command ) < 0 )
@ -819,7 +806,6 @@ bool YeelightLight::setColorRGB(const ColorRgb &color)
rc = false;
}
}
//log (2,"setColorRGB() rc","%d, isON[%d], isInMusicMode[%d]", rc, _isOn, _isInMusicMode );
return rc;
}
@ -914,7 +900,7 @@ bool YeelightLight::setColorHSV(const ColorRgb &colorRGB)
}
else
{
//log ( 3, "setColorHSV", "Skip update. Same Color as before");
// Skip update. Same Color as before
}
log( 3,
"setColorHSV() rc",
@ -1471,7 +1457,6 @@ void LedDeviceYeelight::identify(const QJsonObject& params)
int LedDeviceYeelight::write(const std::vector<ColorRgb> & ledValues)
{
//DebugIf(verbose, _log, "enabled [%d], _isDeviceReady [%d]", _isEnabled, _isDeviceReady);
int rc = -1;
//Update on all Yeelights by iterating through lights and set colors.
@ -1545,8 +1530,5 @@ int LedDeviceYeelight::write(const std::vector<ColorRgb> & ledValues)
// Minimum one Yeelight device is working, continue updating devices
rc = 0;
}
//DebugIf(verbose, _log, "rc [%d]", rc );
return rc;
}

View File

@ -24,7 +24,6 @@ const char API_METHOD_MUSIC_MODE[] = "set_music";
const int API_METHOD_MUSIC_MODE_ON = 1;
const int API_METHOD_MUSIC_MODE_OFF = 0;
const char API_METHOD_SETRGB[] = "set_rgb";
const char API_METHOD_SETSCENE[] = "set_scene";
const char API_METHOD_GETPROP[] = "get_prop";

View File

@ -16,10 +16,12 @@ namespace {
const QChar ONE_SLASH = '/';
const int HTTP_STATUS_NO_CONTENT = 204;
const int HTTP_STATUS_BAD_REQUEST = 400;
const int HTTP_STATUS_UNAUTHORIZED = 401;
const int HTTP_STATUS_NOT_FOUND = 404;
enum HttpStatusCode {
NoContent = 204,
BadRequest = 400,
UnAuthorized = 401,
NotFound = 404
};
constexpr std::chrono::milliseconds DEFAULT_REST_TIMEOUT{ 400 };
@ -303,13 +305,13 @@ httpResponse ProviderRestApi::getResponse(QNetworkReply* const& reply)
{
httpResponse response;
int httpStatusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
HttpStatusCode httpStatusCode = static_cast<HttpStatusCode>(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt());
response.setHttpStatusCode(httpStatusCode);
response.setNetworkReplyError(reply->error());
if (reply->error() == QNetworkReply::NoError)
{
if ( httpStatusCode != HTTP_STATUS_NO_CONTENT ){
if ( httpStatusCode != HttpStatusCode::NoContent ){
QByteArray replyData = reply->readAll();
if (!replyData.isEmpty())
@ -320,13 +322,11 @@ httpResponse ProviderRestApi::getResponse(QNetworkReply* const& reply)
if (error.error != QJsonParseError::NoError)
{
//Received not valid JSON response
//std::cout << "Response: [" << replyData.toStdString() << "]" << std::endl;
response.setError(true);
response.setErrorReason(error.errorString());
}
else
{
//std::cout << "Response: [" << QString(jsonDoc.toJson(QJsonDocument::Compact)).toStdString() << "]" << std::endl;
response.setBody(jsonDoc);
}
}
@ -344,13 +344,13 @@ httpResponse ProviderRestApi::getResponse(QNetworkReply* const& reply)
QString httpReason = reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString();
QString advise;
switch ( httpStatusCode ) {
case HTTP_STATUS_BAD_REQUEST:
case HttpStatusCode::BadRequest:
advise = "Check Request Body";
break;
case HTTP_STATUS_UNAUTHORIZED:
case HttpStatusCode::UnAuthorized:
advise = "Check Authentication Token (API Key)";
break;
case HTTP_STATUS_NOT_FOUND:
case HttpStatusCode::NotFound:
advise = "Check Resource given";
break;
default:

View File

@ -92,9 +92,6 @@ int LedDeviceFile::close()
int LedDeviceFile::write(const std::vector<ColorRgb> & ledValues)
{
QTextStream out(_file);
//printLedValues (ledValues);
if ( _printTimeStamp )
{
QDateTime now = QDateTime::currentDateTime();

View File

@ -179,8 +179,6 @@ int LedDevicePiBlaster::write(const std::vector<ColorRgb> & ledValues)
continue;
}
// fprintf(_fid, "%i=%f\n", iPins[iPin], pwmDutyCycle);
if ( (fprintf(_fid, "%i=%f\n", i, pwmDutyCycle) < 0) || (fflush(_fid) < 0))
{
if (_fid != nullptr)

View File

@ -42,7 +42,6 @@ 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(dmxTypeString);
this->setInError(errortext);
return false;

View File

@ -24,7 +24,6 @@ bool LedDeviceKarate::init(const QJsonObject& deviceConfig)
{
if (_ledCount != 8 && _ledCount != 16)
{
//Error( _log, "%d channels configured. This should always be 16!", _ledCount);
QString errortext = QString("%1 channels configured. This should always be 8 or 16!").arg(_ledCount);
this->setInError(errortext);
isInitOK = false;

View File

@ -40,7 +40,6 @@ bool LedDeviceSedu::init(const QJsonObject &deviceConfig)
if (_ledBuffer.empty())
{
//Warning(_log, "More rgb-channels required then available");
QString errortext = "More rgb-channels required then available";
this->setInError(errortext);
}

View File

@ -273,13 +273,6 @@ void ProviderRs232::readFeedback()
{
//Output as received
std::cout << readData.toStdString();
//Output as Hex
//#if (QT_VERSION >= QT_VERSION_CHECK(5, 9, 0))
// std::cout << readData.toHex(':').toStdString();
//#else
// std::cout << readData.toHex().toStdString();
//#endif
}
}

View File

@ -117,10 +117,6 @@ void LedDeviceSK9822::bufferWithAdjustedCurrent(std::vector<uint8_t> &txBuf, con
txBuf[b + 1] = red;
txBuf[b + 2] = green;
txBuf[b + 3] = blue;
//if(iLed == 0) {
// std::cout << std::to_string((int)rgb.red) << "," << std::to_string((int)rgb.green) << "," << std::to_string((int)rgb.blue) << ": " << std::to_string(maxValue) << (maxValue >= threshold ? " >= " : " < ") << std::to_string(threshold) << " -> " << std::to_string((int)(level&SK9822_GBC_MAX_LEVEL))<< "@" << std::to_string((int)red) << "," << std::to_string((int)green) << "," << std::to_string((int)blue) << std::endl;
//}
}
}

View File

@ -67,8 +67,6 @@ bool LedDeviceSk6822SPI::init(const QJsonObject &deviceConfig)
WarningIf(( _baudRate_Hz < 2000000 || _baudRate_Hz > 2460000 ), _log, "SPI rate %d outside recommended range (2000000 -> 2460000)", _baudRate_Hz);
_ledBuffer.resize( (_ledRGBCount * SPI_BYTES_PER_COLOUR) + (_ledCount * SPI_BYTES_WAIT_TIME ) + SPI_FRAME_END_LATCH_BYTES, 0x00);
// Debug(_log, "_ledBuffer.resize(_ledRGBCount:%d * SPI_BYTES_PER_COLOUR:%d) + ( _ledCount:%d * SPI_BYTES_WAIT_TIME:%d ) + SPI_FRAME_END_LATCH_BYTES:%d, 0x00)", _ledRGBCount, SPI_BYTES_PER_COLOUR, _ledCount, SPI_BYTES_WAIT_TIME, SPI_FRAME_END_LATCH_BYTES);
isInitOK = true;
}
@ -95,7 +93,7 @@ int LedDeviceSk6822SPI::write(const std::vector<ColorRgb> &ledValues)
spi_ptr += SPI_BYTES_WAIT_TIME; // the wait between led time is all zeros
}
/*
#if 0
// debug the whole SPI packet
char debug_line[2048];
int ptr=0;
@ -114,7 +112,7 @@ int LedDeviceSk6822SPI::write(const std::vector<ColorRgb> &ledValues)
ptr = 0;
}
}
*/
#endif
return writeBytes(_ledBuffer.size(), _ledBuffer.data());
}

View File

@ -429,7 +429,7 @@ QJsonArray MdnsBrowser::getServicesDiscoveredJson(const QByteArray& serviceType,
void MdnsBrowser::printCache(const QByteArray& name, quint16 type) const
{
DebugIf(verboseBrowser,_log, "for type: ", QSTRING_CSTR(QMdnsEngine::typeName(type)));
DebugIf(verboseBrowser,_log, "for type: %s", QSTRING_CSTR(QMdnsEngine::typeName(type)));
QList<QMdnsEngine::Record> records;
if (_cache.lookupRecords(name, type, records))
{
@ -466,6 +466,6 @@ void MdnsBrowser::printCache(const QByteArray& name, quint16 type) const
}
else
{
DebugIf(verboseBrowser,_log, "Cash is empty for type: ", QSTRING_CSTR(QMdnsEngine::typeName(type)));
DebugIf(verboseBrowser,_log, "Cash is empty for type: %s", QSTRING_CSTR(QMdnsEngine::typeName(type)));
}
}

View File

@ -73,8 +73,6 @@ QString SSDPDiscover::getFirstService(const searchType& type, const QString& st,
QString data(datagram);
//Debug(_log, "_data: [%s]", QSTRING_CSTR(data));
QMap<QString,QString> headers;
QString address;
// parse request
@ -107,7 +105,7 @@ QString SSDPDiscover::getFirstService(const searchType& type, const QString& st,
{
_usnList << headers.value("usn");
QUrl url(headers.value("location"));
//Debug(_log, "Received msearch response from '%s:%d'. Search target: %s",QSTRING_CSTR(sender.toString()), senderPort, QSTRING_CSTR(headers.value("st")));
if(type == searchType::STY_WEBSERVER)
{
Debug(_log, "Found service [%s] at: %s:%d", QSTRING_CSTR(st), QSTRING_CSTR(url.host()), url.port());
@ -191,7 +189,6 @@ void SSDPDiscover::readPendingDatagrams()
if (headers.value("st") == _searchTarget)
{
_usnList << headers.value("usn");
//Debug(_log, "Received msearch response from '%s:%d'. Search target: %s",QSTRING_CSTR(sender.toString()), senderPort, QSTRING_CSTR(headers.value("st")));
QUrl url(headers.value("location"));
emit newService(url.host() + ":" + QString::number(url.port()));
}
@ -226,8 +223,6 @@ int SSDPDiscover::discoverServices(const QString& searchTarget, const QString& k
QString data(datagram);
//Debug(_log, "_data: [%s]", QSTRING_CSTR(data));
QMap<QString,QString> headers;
// parse request
QStringList entries = QStringUtils::split(data,"\n", QStringUtils::SplitBehavior::SkipEmptyParts);
@ -250,7 +245,6 @@ int SSDPDiscover::discoverServices(const QString& searchTarget, const QString& k
if ( match.hasMatch() )
{
Debug(_log,"Found target [%s], plus record [%s] matches [%s:%s]", QSTRING_CSTR(_searchTarget), QSTRING_CSTR(headers[_filterHeader]), QSTRING_CSTR(_filterHeader), QSTRING_CSTR(_filter) );
//Debug(_log, "_data: [%s]", QSTRING_CSTR(data));
QString mapKey = headers[key];
@ -303,8 +297,6 @@ QJsonArray SSDPDiscover::getServicesDiscoveredJson() const
QMultiMap<QString, SSDPService>::const_iterator i;
for (i = _services.begin(); i != _services.end(); ++i)
{
//Debug(_log, "Device discovered at [%s]", QSTRING_CSTR( i.key() ));
QJsonObject obj;
obj.insert("id", i.key());
@ -363,8 +355,6 @@ QJsonArray SSDPDiscover::getServicesDiscoveredJson() const
result << obj;
}
//Debug(_log, "result: [%s]", QString(QJsonDocument(result).toJson(QJsonDocument::Compact)).toUtf8().constData() );
return result;
}
@ -372,7 +362,6 @@ void SSDPDiscover::sendSearch(const QString& st)
{
const QString msg = QString(UPNP_DISCOVER_MESSAGE).arg(_ssdpAddr.toString()).arg(_ssdpPort).arg(_ssdpMaxWaitResponseTime).arg(st);
//Debug(_log,"Search request: [%s]", QSTRING_CSTR(msg));
_udpSocket->writeDatagram(msg.toUtf8(), _ssdpAddr, _ssdpPort);
}

View File

@ -165,7 +165,6 @@ void SSDPServer::readPendingDatagrams()
if (headers.value("man") == "\"ssdp:discover\"")
{
//Debug(_log, "Received msearch from '%s:%d'. Search target: %s",QSTRING_CSTR(sender.toString()), senderPort, QSTRING_CSTR(headers.value("st")));
emit msearchRequestReceived(headers.value("st"), headers.value("mx"), sender.toString(), senderPort);
}
}

View File

@ -94,8 +94,8 @@ void print_trace()
* handler and print_trace functions. */
for (int i = 2; i < size; ++i)
{
std::string line = "\t" + decipher_trace(symbols[i]);
Error(log, line.c_str());
const std::string line = "\t" + decipher_trace(symbols[i]);
Error(log, "%s", line.c_str());
}
free(symbols);
@ -149,8 +149,6 @@ void signal_handler(int signum, siginfo_t * /*info*/, void * /*context*/)
default:
/* If the signal_handler is hit before the event loop is started,
* following call will do nothing. So we queue the call. */
// QCoreApplication::quit();
QMetaObject::invokeMethod(qApp, "quit", Qt::QueuedConnection);
// Reset signal handler to default (in case this handler is not capable of stopping)

View File

@ -59,8 +59,6 @@ namespace JsonUtils {
{
//remove Comments in data
QString cleanData = data;
//cleanData .remove(QRegularExpression("([^:]?\\/\\/.*)"));
QJsonParseError error;
doc = QJsonDocument::fromJson(cleanData.toUtf8(), &error);
@ -145,7 +143,6 @@ namespace JsonUtils {
obj.insert(attribute, resolveRefs(attributeValue.toObject(), obj, log));
else
{
//qDebug() <<"ADD ATTR:VALUE"<<attribute<<attributeValue;
obj.insert(attribute, attributeValue);
}
}

View File

@ -125,9 +125,6 @@ Logger::Logger (const QString & name, const QString & subName, LogLevel minLevel
Logger::~Logger()
{
//Debug(this, "logger '%s' destroyed", QSTRING_CSTR(_name) );
if (LoggerCount.fetchAndSubOrdered(1) == 0)
{
#ifndef _WIN32

View File

@ -17,7 +17,6 @@ RgbChannelAdjustment::RgbChannelAdjustment(uint8_t adjustR, uint8_t adjustG, uin
void RgbChannelAdjustment::resetInitialized()
{
//Debug(_log, "initialize mapping with %d,%d,%d", _adjust[RED], _adjust[GREEN], _adjust[BLUE]);
memset(_initialized, false, sizeof(_initialized));
}

View File

@ -61,7 +61,7 @@ int RgbTransform::getBacklightThreshold() const
return _backlightThreshold;
}
void RgbTransform::setBacklightThreshold(int backlightThreshold)
void RgbTransform::setBacklightThreshold(double backlightThreshold)
{
_backlightThreshold = backlightThreshold;
_sumBrightnessLow = 765.0 * ((qPow(2.0,(_backlightThreshold/100)*2)-1) / 3.0);

View File

@ -1,7 +1,7 @@
// stdlib includes
#include <iterator>
#include <algorithm>
#include <math.h>
#include <cmath>
// Utils-Jsonschema includes
#include <utils/jsonschema/QJsonSchemaChecker.h>
@ -186,7 +186,14 @@ void QJsonSchemaChecker::checkType(const QJsonValue& value, const QJsonValue& sc
else if (type == "integer")
{
if (value.isDouble()) //check if value type not boolean (true = 1 && false = 0)
wrongType = (rint(value.toDouble()) != value.toDouble());
{
double valueIntegratlPart;
double valueFractionalPart = std::modf(value.toDouble(), &valueIntegratlPart);
if (valueFractionalPart > std::numeric_limits<double>::epsilon())
{
wrongType = true;
}
}
else
wrongType = true;
}

View File

@ -77,13 +77,13 @@ void QtHttpClientWrapper::onClientDataReceived (void)
else
{
m_parsingStatus = ParsingError;
//qWarning () << "Error : unhandled HTTP version :" << version;
// Error : unhandled HTTP version
}
}
else
{
m_parsingStatus = ParsingError;
//qWarning () << "Error : incorrect HTTP command line :" << line;
// Error : incorrect HTTP command line
}
break;

View File

@ -1,5 +1,7 @@
#include "StaticFileServing.h"
#include "QtHttpHeader.h"
#include <utils/QStringUtils.h>
#include <QStringBuilder>
@ -9,6 +11,7 @@
#include <QFile>
#include <QFileInfo>
#include <QResource>
#include <exception>
StaticFileServing::StaticFileServing (QObject * parent)

View File

@ -3,10 +3,8 @@
#include <QMimeDatabase>
//#include "QtHttpServer.h"
#include "QtHttpRequest.h"
#include "QtHttpReply.h"
#include "QtHttpHeader.h"
#include "CgiHandler.h"
#include <utils/Logger.h>

View File

@ -58,14 +58,12 @@ void WebSocketClient::handleWebSocketFrame()
if(_socket->bytesAvailable() < (qint64)_wsh.payloadLength)
{
//printf("not enough data %llu %llu\n", _socket->bytesAvailable(), _wsh.payloadLength);
_notEnoughData=true;
return;
}
_notEnoughData = false;
QByteArray buf = _socket->read(_wsh.payloadLength);
//printf("opcode %x payload bytes %llu avail: %llu\n", _wsh.opCode, _wsh.payloadLength, _socket->bytesAvailable());
if (OPCODE::invalid((OPCODE::value)_wsh.opCode))
{
@ -210,10 +208,10 @@ void WebSocketClient::getWsFrameHeader(WebSocketHeader* header)
}
/// See http://tools.ietf.org/html/rfc6455#section-5.2 for more information
void WebSocketClient::sendClose(int status, QString reason)
void WebSocketClient::sendClose(int status, const QString& reason)
{
Debug(_log, "Send close to %s: %d %s", QSTRING_CSTR(_socket->peerAddress().toString()), status, QSTRING_CSTR(reason));
ErrorIf(!reason.isEmpty(), _log, QSTRING_CSTR(reason));
ErrorIf(!reason.isEmpty(), _log, "%s", QSTRING_CSTR(reason));
_receiveBuffer.clear();
QByteArray sendBuffer;
@ -244,8 +242,6 @@ void WebSocketClient::sendClose(int status, QString reason)
void WebSocketClient::handleBinaryMessage(QByteArray &data)
{
//uint8_t priority = data.at(0);
//unsigned duration_s = data.at(1);
unsigned imgSize = data.size() - 4;
unsigned width = ((data.at(2) << 8) & 0xFF00) | (data.at(3) & 0xFF);
unsigned height = imgSize / width;
@ -260,8 +256,6 @@ void WebSocketClient::handleBinaryMessage(QByteArray &data)
image.resize(width, height);
memcpy(image.memptr(), data.data()+4, imgSize);
//_hyperion->registerInput();
//_hyperion->setInputImage(priority, image, duration_s*1000);
}

View File

@ -31,7 +31,7 @@ private:
JsonAPI* _jsonAPI;
void getWsFrameHeader(WebSocketHeader* header);
void sendClose(int status, QString reason = "");
void sendClose(int status, const QString& reason = "");
void handleBinaryMessage(QByteArray &data);
qint64 sendMessage_Raw(const char* data, quint64 size);
qint64 sendMessage_Raw(QByteArray &data);

View File

@ -21,13 +21,6 @@
#include <utils/DefaultSignalHandler.h>
// Constants
namespace {
const char SERVICE_TYPE[] = "flatbuffer";
} //End of constants
using namespace commandline;
// save the image as screenshot

View File

@ -22,13 +22,6 @@
//flatbuf sending
#include <flatbufserver/FlatBufferConnection.h>
// Constants
namespace {
const char SERVICE_TYPE[] = "flatbuffer";
} //End of constants
using namespace commandline;
// save the image as screenshot
@ -49,7 +42,6 @@ int main(int argc, char ** argv)
<< "\tVersion : " << HYPERION_VERSION << " (" << HYPERION_BUILD_ID << ")" << std::endl
<< "\tbuild time: " << __DATE__ << " " << __TIME__ << std::endl;
//QCoreApplication app(argc, argv);
QGuiApplication app(argc, argv);
try

View File

@ -29,14 +29,6 @@
#include <utils/DefaultSignalHandler.h>
// Constants
namespace {
const char SERVICE_TYPE[] = "jsonapi";
} //End of constants
using namespace commandline;
/// Count the number of true values in a list of booleans

View File

@ -1,3 +1,5 @@
#include <cmath>
// Qt includes
#include <QImage>
#include <QCoreApplication>
@ -102,7 +104,6 @@ bool ScreenshotHandler::findNoSignalSettings(const Image<ColorRgb> & image)
auto itG = std::max_element(std::begin(greenCounts), std::end(greenCounts));
auto itB = std::max_element(std::begin(blueCounts), std::end(blueCounts));
//std::cout << *itR << " " << *itG << " " << *itB << std::endl;
double xOffsetSuggested = xOffset;
double yOffsetSuggested = yOffset;
double xMaxSuggested = xMax;
@ -138,7 +139,7 @@ bool ScreenshotHandler::findNoSignalSettings(const Image<ColorRgb> & image)
if (!noSignalBlack)
{
unsigned xMid = (xMaxSuggested + xOffsetSuggested) / 2;
for (unsigned y = yMid; y >= yOffset && yOffsetSuggested != y; --y)
for (unsigned y = yMid; y >= yOffset && (fabs(yOffsetSuggested - y) > std::numeric_limits<double>::epsilon()); --y)
{
ColorRgb rgb = image(xMid, y);
if (rgb <= noSignalThresholdColor)
@ -147,7 +148,7 @@ bool ScreenshotHandler::findNoSignalSettings(const Image<ColorRgb> & image)
}
}
for (unsigned y = yMid; y <= yMax && yMaxSuggested != y; ++y)
for (unsigned y = yMid; y <= yMax && (fabs(yMaxSuggested - y) > std::numeric_limits<double>::epsilon()); ++y)
{
ColorRgb rgb = image(xMid, y);
if (rgb <= noSignalThresholdColor)

View File

@ -33,13 +33,6 @@
#include <utils/DefaultSignalHandler.h>
// Constants
namespace {
const char SERVICE_TYPE[] = "flatbuffer";
} //End of constants
using namespace commandline;
int main(int argc, char** argv)

View File

@ -19,13 +19,6 @@
#endif
#include <utils/NetUtils.h>
// Constants
namespace {
const char SERVICE_TYPE[] = "flatbuffer";
} //End of constants
using namespace commandline;
// save the image as screenshot

View File

@ -19,13 +19,6 @@
#endif
#include <utils/NetUtils.h>
// Constants
namespace {
const char SERVICE_TYPE[] = "flatbuffer";
} //End of constants
using namespace commandline;
// save the image as screenshot

View File

@ -11,7 +11,6 @@ instance under a schema, and will create a validator for you.
from __future__ import division, unicode_literals
import collections
import contextlib
import datetime
import itertools
@ -474,10 +473,10 @@ class _Draft34CommonMixin(object):
yield error
else:
dependencies = _list(dependency)
for dependency in dependencies:
if dependency not in instance:
for depend in dependencies:
if depend not in instance:
yield ValidationError(
"%r is a dependency of %r" % (dependency, property)
"%r is a dependency of %r" % (depend, property)
)
def validate_enum(self, enums, instance, schema):
@ -694,6 +693,7 @@ class Draft4Validator(ValidatorMixin, _Draft34CommonMixin, object):
yield error
def validate_oneOf(self, oneOf, instance, schema):
first_valid = ""
subschemas = enumerate(oneOf)
all_errors = []
for index, subschema in subschemas: