Compare commits

..

No commits in common. "master" and "954eec754c68e20213480a745ace23f99980e0fa" have entirely different histories.

117 changed files with 3387 additions and 4385 deletions

View file

@ -1,174 +0,0 @@
cmake_minimum_required(VERSION 4.0)
project(SHinterface VERSION 1.0 LANGUAGES CXX)
# Set C++ standard
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# Enable all warnings
add_compile_options(-Wall)
# Find Qt packages
find_package(Qt6 COMPONENTS Core Gui Widgets Network Multimedia SerialPort Mqtt REQUIRED)
# Find dependencies using pkg-config
find_package(PkgConfig REQUIRED)
pkg_check_modules(PIPEWIRE REQUIRED libpipewire-0.3)
pkg_check_modules(LIBNL3 REQUIRED libnl-3.0 libnl-genl-3.0)
# Enable automatic moc and uic processing
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTOUIC ON)
# Add src to include path for relative includes
include_directories(${CMAKE_CURRENT_SOURCE_DIR}/src)
# Create executable
add_executable(SHinterface
src/sensors/mqttsensorsource.h src/sensors/mqttsensorsource.cpp)
# Add sources to executable
target_sources(SHinterface
PRIVATE
src/main.cpp
src/mainobject.h
src/mainobject.cpp
src/apgetconnected.h
src/apgetconnected.cpp
src/microcontroller.h
src/microcontroller.cpp
src/sun.h
src/sun.cpp
src/programmode.h
src/programmode.cpp
src/pipewire.h
src/pipewire.cpp
src/service/service.h
src/service/service.cpp
src/service/tcpclient.h
src/service/tcpclient.cpp
src/service/tcpserver.h
src/service/tcpserver.cpp
src/actors/actor.h
src/actors/actor.cpp
src/actors/factoractor.h
src/actors/factoractor.cpp
src/actors/polynomalactor.h
src/actors/polynomalactor.cpp
src/actors/sensoractor.h
src/actors/sensoractor.cpp
src/actors/alarmtime.h
src/actors/alarmtime.cpp
src/actors/regulator.h
src/actors/regulator.cpp
src/actors/timeractor.h
src/actors/timeractor.cpp
src/sensors/sensor.h
src/sensors/sensor.cpp
src/sensors/sunsensor.h
src/sensors/sunsensor.cpp
src/items/item.h
src/items/item.cpp
src/items/relay.h
src/items/relay.cpp
src/items/poweritem.h
src/items/poweritem.cpp
src/items/messageitem.h
src/items/messageitem.cpp
src/items/systemitem.h
src/items/systemitem.cpp
src/items/auxitem.h
src/items/auxitem.cpp
src/items/rgbitem.h
src/items/rgbitem.cpp
src/items/itemsource.h
src/items/itemsource.cpp
src/items/itemloadersource.h
src/items/itemloadersource.cpp
src/items/fixeditemsource.h
src/items/fixeditemsource.cpp
src/items/itemstore.h
src/items/itemstore.cpp
src/ui/mainwindow.h
src/ui/mainwindow.cpp
src/ui/itemwidget.h
src/ui/itemwidget.cpp
src/ui/itemscrollbox.h
src/ui/itemscrollbox.cpp
src/ui/sensorlistwidget.h
src/ui/sensorlistwidget.cpp
src/ui/itemcreationdialog.h
src/ui/itemcreationdialog.cpp
src/ui/itemsettingsdialog.h
src/ui/itemsettingsdialog.cpp
src/ui/actorsettingsdialog.h
src/ui/actorsettingsdialog.cpp
src/ui/actorwidgets/factoractorwidget.h
src/ui/actorwidgets/factoractorwidget.cpp
src/ui/actorwidgets/polynomalactorwidget.h
src/ui/actorwidgets/polynomalactorwidget.cpp
src/ui/actorwidgets/sensoractorwidget.h
src/ui/actorwidgets/sensoractorwidget.cpp
src/ui/actorwidgets/timeractorwidget.h
src/ui/actorwidgets/timeractorwidget.cpp
src/ui/actorwidgets/alarmwidget.h
src/ui/actorwidgets/alarmwidget.cpp
src/ui/actorwidgets/regulatorwdiget.h
src/ui/actorwidgets/regulatorwdiget.cpp
src/ui/itemsettingswidgets/messageitemsettingswidget.h
src/ui/itemsettingswidgets/messageitemsettingswidget.cpp
src/ui/itemsettingswidgets/relayitemsettingswidget.h
src/ui/itemsettingswidgets/relayitemsettingswidget.cpp
src/ui/itemsettingswidgets/systemitemsettingswidget.h
src/ui/itemsettingswidgets/systemitemsettingswidget.cpp
)
# Add UI files
target_sources(SHinterface
PRIVATE
src/ui/mainwindow.ui
src/ui/itemwidget.ui
src/ui/relayscrollbox.ui
src/ui/itemcreationdialog.ui
src/ui/itemsettingsdialog.ui
src/ui/actorsettingsdialog.ui
src/ui/actorwidgets/factoractorwidget.ui
src/ui/actorwidgets/polynomalactorwidget.ui
src/ui/actorwidgets/sensoractorwidget.ui
src/ui/actorwidgets/timeractorwidget.ui
src/ui/actorwidgets/alarmwidget.ui
src/ui/actorwidgets/regulatorwdiget.ui
src/ui/itemsettingswidgets/messageitemsettingswidget.ui
src/ui/itemsettingswidgets/relayitemsettingswidget.ui
src/ui/itemsettingswidgets/systemitemsettingswidget.ui
)
# Add resource file
target_sources(SHinterface
PRIVATE
resources.qrc
)
# Link libraries
target_link_libraries(SHinterface
Qt6::Core
Qt6::Gui
Qt6::Widgets
Qt6::Network
Qt6::Multimedia
Qt6::SerialPort
Qt6::Mqtt
${PIPEWIRE_LIBRARIES}
${LIBNL3_LIBRARIES}
)
# Add include paths
include_directories(${PIPEWIRE_INCLUDE_DIRS} ${LIBNL3_INCLUDE_DIRS})

156
SHinterface.pro Normal file
View file

@ -0,0 +1,156 @@
#-------------------------------------------------
#
# Project created by QtCreator 2017-06-01T22:31:38
#
#-------------------------------------------------
QT += core gui widgets network multimedia
QT += serialport
TARGET = SHinterface
TEMPLATE = app
INCLUDEPATH += /usr/include/libnl3/
LIBS += -lnl-3 -lnl-genl-3
# The following define makes your compiler emit warnings if you use
# any feature of Qt which as been marked as deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS
QMAKE_CXXFLAGS += -std=c++17 -O2
SOURCES += \
src/actors/factoractor.cpp \
src/actors/polynomalactor.cpp \
src/broadcast.cpp \
src/iomuliplexer.cpp \
src/items/messageitem.cpp \
src/items/systemitem.cpp \
src/ui/actorwidgets/factoractorwidget.cpp \
src/ui/itemcreationdialog.cpp \
src/ui/itemsettingswidgets/messageitemsettingswidget.cpp \
src/mainobject.cpp \
src/apgetconnected.cpp \
src/ui/actorwidgets/polynomalactorwidget.cpp \
src/ui/actorwidgets/sensoractorwidget.cpp \
src/ui/actorwidgets/alarmwidget.cpp \
src/ui/actorwidgets/timeractorwidget.cpp \
src/ui/itemsettingswidgets/relayitemsettingswidget.cpp \
src/ui/itemsettingswidgets/systemitemsettingswidget.cpp \
src/ui/itemwidget.cpp \
src/ui/itemsettingsdialog.cpp \
src/ui/itemscrollbox.cpp \
src/items/poweritem.cpp \
src/ui/actorwidgets/regulatorwdiget.cpp
SOURCES += \
src/ui/actorsettingsdialog.cpp \
src/ui/mainwindow.cpp \
src/ui/sensorlistwidget.cpp
SOURCES += \
src/actors/actor.cpp \
src/actors/sensoractor.cpp \
src/actors/alarmtime.cpp \
src/actors/regulator.cpp \
src/actors/timeractor.cpp
SOURCES += \
src/sensors/sensor.cpp \
src/sensors/speakersensor.cpp \
src/sensors/sunsensor.cpp \
src/sensors/ocupancysensor.cpp
SOURCES += \
src/items/relay.cpp \
src/items/item.cpp \
src/items/itemstore.cpp \
src/items/auxitem.cpp \
src/items/rgbitem.cpp
SOURCES += \
src/alarmactions.cpp \
src/main.cpp \
src/microcontroller.cpp \
src/sun.cpp
HEADERS += \
src/actors/factoractor.h \
src/actors/polynomalactor.h \
src/broadcast.h \
src/iomuliplexer.h \
src/items/messageitem.h \
src/items/systemitem.h \
src/ui/actorwidgets/factoractorwidget.h \
src/ui/itemcreationdialog.h \
src/ui/itemsettingswidgets/messageitemsettingswidget.h \
src/mainobject.h \
src/apgetconnected.h \
src/ui/actorwidgets/alarmwidget.h \
src/ui/actorwidgets/polynomalactorwidget.h \
src/ui/actorwidgets/sensoractorwidget.h \
src/ui/actorwidgets/timeractorwidget.h \
src/ui/itemsettingswidgets/relayitemsettingswidget.h \
src/ui/itemsettingswidgets/systemitemsettingswidget.h \
src/ui/itemwidget.h \
src/ui/itemsettingsdialog.h \
src/ui/itemscrollbox.h \
src/items/poweritem.h \
src/ui/actorwidgets/regulatorwdiget.h
HEADERS += \
src/ui/actorsettingsdialog.h \
src/ui/mainwindow.h \
src/ui/sensorlistwidget.h
HEADERS += \
src/actors/actor.h \
src/actors/alarmtime.h \
src/actors/sensoractor.h \
src/actors/regulator.h \
src/actors/timeractor.h
HEADERS += \
src/sensors/sensor.h \
src/sensors/speakersensor.h \
src/sensors/sunsensor.h \
src/sensors/ocupancysensor.h
HEADERS += \
src/items/relay.h \
src/items/item.h \
src/items/itemstore.h \
src/items/auxitem.h \
src/items/rgbitem.h
HEADERS += \
src/alarmactions.h \
src/microcontroller.h \
src/sun.h
FORMS += \
src/ui/actorwidgets/factoractorwidget.ui \
src/ui/itemcreationdialog.ui \
src/ui/itemsettingswidgets/messageitemsettingswidget.ui \
src/ui/actorsettingsdialog.ui \
src/ui/actorwidgets/polynomalactorwidget.ui \
src/ui/itemsettingswidgets/relayitemsettingswidget.ui \
src/ui/itemsettingswidgets/systemitemsettingswidget.ui \
src/ui/mainwindow.ui \
src/ui/relayscrollbox.ui \
src/ui/actorwidgets/sensoractorwidget.ui \
src/ui/actorwidgets/alarmwidget.ui \
src/ui/actorwidgets/timeractorwidget.ui \
src/ui/itemsettingsdialog.ui \
src/ui/itemwidget.ui \
src/ui/actorwidgets/regulatorwdiget.ui
android:FORMS += src/ui/mainwindow-android.ui
RESOURCES += \
resources.qrc

100
src/actor.cpp.autosave Normal file
View file

@ -0,0 +1,100 @@
#include "actor.h"
#include<QDebug>
Actor::Actor(QObject *parent): QObject(parent)
{
buildName();
}
Actor::~Actor()
{
}
void Actor::performAction()
{
if(active)
{
trigger();
if(action_ == ACTION_OFF) off();
else if(action_ == ACTION_ON) on();
else if(action_ != ACTION_TOGGLE) toggle();
else if(action_ != ACTION_VALUE) sigValue(value_);
}
}
void Actor::makeActive()
{
active = true;
}
void Actor::makeInactive()
{
active = false;
}
void Actor::buildName()
{
name = "Actor";
appendActionToName();
}
void Actor::appendActionToName()
{
if(action_ == ACTION_OFF || action_ == ACTION_DEFAULT ) name.append("off");
else if(action_ == ACTION_ON ) name.append("on");
else if(action_ == ACTION_TOGGLE ) name.append("toggle");
else if(action_ == ACTION_VALUE ) name.append("value to " + QString::number(value_));
}
void Actor::setActive(int state)
{
state ? makeActive() : makeInactive();
buildName();
}
bool Actor::isActive()
{
return active;
}
bool Actor::isExausted()
{
return exausted;
}
void Actor::saveSettings(QString subsecton, QSettings* settings)
{
settings->setValue(subsecton + "Active", active);
settings->setValue(subsecton + "Exausted", exausted);
settings->setValue(subsecton + "Name", name);
settings->setValue(subsecton + "Action", action_);
}
void Actor::loadSettings(QString subsecton, QSettings* settings)
{
active = settings->value(subsecton + "Active").toBool();
exausted = settings->value(subsecton + "Exausted").toBool();
name = settings->value(subsecton + "Name").toString();
action_ = settings->value(subsecton + "Action").toUInt();
}
void Actor::setAction(uint8_t action)
{
action_ = action;
qDebug()<<"setting action to "<<action;
buildName();
}
void Actor::setValue(uint8_t value)
{
value_=value;
buildName();
}
void Actor::onStateChanged(bool state)
{
}

View file

@ -19,102 +19,102 @@ Actor::~Actor()
void Actor::performAction() void Actor::performAction()
{ {
if(active) if(active)
{ {
sigValue(triggerValue); sigValue(triggerValue);
} }
} }
void Actor::makeActive() void Actor::makeActive()
{ {
active = true; active = true;
} }
void Actor::makeInactive() void Actor::makeInactive()
{ {
active = false; active = false;
} }
QString Actor::actionName() QString Actor::actionName()
{ {
QString string; QString string;
if(triggerValue == 0 ) string = "off"; if(triggerValue == 0 ) string = "off";
else if(triggerValue == 1 ) string = "on"; else if(triggerValue == 1 ) string = "on";
else string = "value to " + QString::number(triggerValue); else string = "value to " + QString::number(triggerValue);
return string; return string;
} }
void Actor::setActive(uint8_t state) void Actor::setActive(uint8_t state)
{ {
state ? makeActive() : makeInactive(); state ? makeActive() : makeInactive();
} }
bool Actor::isActive() bool Actor::isActive()
{ {
return active; return active;
} }
bool Actor::isExausted() bool Actor::isExausted()
{ {
return exausted; return exausted;
} }
void Actor::store(QJsonObject& json) void Actor::store(QJsonObject& json)
{ {
Item::store(json); Item::store(json);
json["Active"] = active; json["Active"] = active;
json["Exausted"] = exausted; json["Exausted"] = exausted;
json["TriggerValue"] = triggerValue; json["TriggerValue"] = triggerValue;
} }
void Actor::load(const QJsonObject& json, const bool preserve) void Actor::load(const QJsonObject& json, const bool preserve)
{ {
Item::load(json, preserve); Item::load(json, preserve);
active = json["Active"].toBool(); active = json["Active"].toBool();
exausted = json["Exausted"].toBool(); exausted = json["Exausted"].toBool();
triggerValue = json["TriggerValue"].toInt(); triggerValue = json["TriggerValue"].toInt();
} }
void Actor::setTriggerValue(uint8_t value) void Actor::setTriggerValue(uint8_t value)
{ {
triggerValue=value; triggerValue=value;
} }
uint8_t Actor::getTriggerValue() uint8_t Actor::getTriggerValue()
{ {
return triggerValue; return triggerValue;
} }
void Actor::onValueChanged(uint8_t value) void Actor::onValueChanged(uint8_t value)
{ {
(void)value;
} }
std::shared_ptr<Actor> Actor::createActor(const QString& type) std::shared_ptr<Actor> Actor::createActor(const QString& type)
{ {
std::shared_ptr<Actor> actor; std::shared_ptr<Actor> actor;
if(type == "Alarm") actor = std::shared_ptr<Actor>(new AlarmTime()); if(type == "Alarm") actor = std::shared_ptr<Actor>(new AlarmTime());
else if(type == "Sensor") actor = std::shared_ptr<Actor>(new SensorActor()); else if(type == "Sensor") actor = std::shared_ptr<Actor>(new SensorActor());
else if(type == "Timer") actor = std::shared_ptr<Actor>(new TimerActor()); else if(type == "Timer") actor = std::shared_ptr<Actor>(new TimerActor());
else if(type == "Regulator") actor = std::shared_ptr<Actor>(new Regulator()); else if(type == "Regulator") actor = std::shared_ptr<Actor>(new Regulator());
else if(type == "Polynomal") actor = std::shared_ptr<Actor>(new PolynomalActor()); else if(type == "Polynomal") actor = std::shared_ptr<Actor>(new PolynomalActor());
else if(type == "MultiFactor") actor = std::shared_ptr<Actor>(new MultiFactorActor()); else if(type == "MultiFactor") actor = std::shared_ptr<Actor>(new MultiFactorActor());
else if(type == "Actor") actor = std::shared_ptr<Actor>(new Actor()); else if(type == "Actor") actor = std::shared_ptr<Actor>(new Actor());
return actor; return actor;
} }
std::shared_ptr<Actor> Actor::loadActor(const QJsonObject &json) std::shared_ptr<Actor> Actor::loadActor(const QJsonObject &json)
{ {
QString type = json["Type"].toString("Actor"); QString type = json["Type"].toString("Actor");
std::shared_ptr<Actor> actor = createActor(type); std::shared_ptr<Actor> actor = createActor(type);
if(actor) actor->load(json); if(actor) actor->load(json);
return actor; return actor;
} }
void Actor::setValue(uint8_t value) void Actor::setValue(uint8_t value)
{ {
Item::setValue(value); Item::setValue(value);
setActive(value); setActive(value);
} }

View file

@ -5,50 +5,50 @@
#include <QString> #include <QString>
#include <QJsonObject> #include <QJsonObject>
#include "items/item.h" #include "../items/item.h"
class Actor : public Item class Actor : public Item
{ {
Q_OBJECT Q_OBJECT
public: public:
uint8_t triggerValue = 0; uint8_t triggerValue = 0;
protected: protected:
bool active = true; bool active = true;
bool exausted = false; bool exausted = false;
void performAction(); void performAction();
signals: signals:
void sigValue(uint8_t value); void sigValue(uint8_t value);
public slots: public slots:
virtual void makeActive(); virtual void makeActive();
virtual void makeInactive(); virtual void makeInactive();
virtual void setActive(uint8_t state); virtual void setActive(uint8_t state);
virtual void onValueChanged(uint8_t state); virtual void onValueChanged(uint8_t state);
virtual void setValue(uint8_t value); virtual void setValue(uint8_t value);
public: public:
Actor(QObject* parent = nullptr); Actor(QObject* parent = nullptr);
virtual ~Actor(); virtual ~Actor();
bool isExausted(); bool isExausted();
virtual QString actionName(); virtual QString actionName();
bool isActive(); bool isActive();
void setTriggerValue(uint8_t value); void setTriggerValue(uint8_t value);
uint8_t getTriggerValue(); uint8_t getTriggerValue();
static std::shared_ptr<Actor> createActor(const QString& type); static std::shared_ptr<Actor> createActor(const QString& type);
virtual void store(QJsonObject& json); virtual void store(QJsonObject& json);
virtual void load(const QJsonObject& json, const bool preserve = false); virtual void load(const QJsonObject& json, const bool preserve = false);
static std::shared_ptr<Actor> loadActor(const QJsonObject& json); static std::shared_ptr<Actor> loadActor(const QJsonObject& json);
}; };
#endif // ACTOR_H #endif // ACTOR_H

View file

@ -2,132 +2,132 @@
AlarmTime::AlarmTime(const QDateTime time, QObject *parent) : Actor(parent), time_(time) AlarmTime::AlarmTime(const QDateTime time, QObject *parent) : Actor(parent), time_(time)
{ {
connect(&timer, SIGNAL(timeout()), this, SLOT(doTick())); connect(&timer, SIGNAL(timeout()), this, SLOT(doTick()));
timer.setInterval(1000); timer.setInterval(1000);
AlarmTime::run(); run();
} }
AlarmTime::~AlarmTime() AlarmTime::~AlarmTime()
{ {
AlarmTime::makeInactive(); makeInactive();
} }
void AlarmTime::run() void AlarmTime::run()
{ {
AlarmTime::makeInactive(); makeInactive();
active = true; active = true;
timer.start(); timer.start();
} }
void AlarmTime::makeActive() void AlarmTime::makeActive()
{ {
run(); run();
} }
QString AlarmTime::getName() const QString AlarmTime::getName() const
{ {
if(name_.size() > 0)return name_; if(name_.size() > 0)return name_;
else else
{ {
QString string; QString string;
string = "Alarm: "; string = "Alarm: ";
if(repeat_ == REPEAT_DAILY) if(repeat_ == REPEAT_DAILY)
{ {
string.append("daily "); string.append("daily ");
string.append(time_.toString("HH:mm")); string.append(time_.toString("HH:mm"));
} }
else if(repeat_ == REPEAT_WEEKLY) else if(repeat_ == REPEAT_WEEKLY)
{ {
string.append("weekly "); string.append("weekly ");
string.append(time_.toString("ddd HH:mm")); string.append(time_.toString("ddd HH:mm"));
} }
else if(repeat_ == REPEAT_MONTHLY) else if(repeat_ == REPEAT_MONTHLY)
{ {
string.append("monthly "); string.append("monthly ");
string.append(time_.toString("dd HH:mm")); string.append(time_.toString("dd HH:mm"));
} }
else if(repeat_ == REPEAT_YEARLY) else if(repeat_ == REPEAT_YEARLY)
{ {
string.append("yearly "); string.append("yearly ");
string.append(time_.toString("dd.mm HH:mm")); string.append(time_.toString("dd.mm HH:mm"));
} }
else string.append(time_.toString("dd.mm.yyyy HH:mm")); else string.append(time_.toString("dd.mm.yyyy HH:mm"));
return string; return string;
} }
} }
void AlarmTime::setRepeat(const uint8_t repeat) void AlarmTime::setRepeat(const uint8_t repeat)
{ {
repeat_ = repeat; repeat_=repeat;
exausted = false; exausted = false;
} }
uint8_t AlarmTime::getRepeat() uint8_t AlarmTime::getRepeat()
{ {
return repeat_; return repeat_;
} }
QDateTime AlarmTime::getDateTime() QDateTime AlarmTime::getDateTime()
{ {
return time_; return time_;
} }
void AlarmTime::makeInactive() void AlarmTime::makeInactive()
{ {
timer.stop(); timer.stop();
active = false; active = false;
} }
void AlarmTime::doTick() void AlarmTime::doTick()
{ {
if( if(
( (
(triggerd_ == false) && (triggerd_ == false) &&
(time_.date().year() == QDate::currentDate().year() || repeat_ != REPEAT_NEVER) && (time_.date().year() == QDate::currentDate().year() || repeat_ != REPEAT_NEVER) &&
(time_.date().month() == QDate::currentDate().month() || repeat_ == REPEAT_MONTHLY || repeat_ == REPEAT_DAILY) && (time_.date().month() == QDate::currentDate().month() || repeat_ == REPEAT_MONTHLY || repeat_ == REPEAT_DAILY) &&
(time_.date().day() == QDate::currentDate().day() || repeat_ == REPEAT_DAILY) (time_.date().day() == QDate::currentDate().day() || repeat_ == REPEAT_DAILY)
) )
|| ||
( (
(repeat_ == REPEAT_WEEKLY) && (repeat_ == REPEAT_WEEKLY) &&
(time_.date().dayOfWeek() == QDate::currentDate().dayOfWeek()) (time_.date().dayOfWeek() == QDate::currentDate().dayOfWeek())
) )
) )
{ {
if(time_.time().hour() == QTime::currentTime().hour() && time_.time().minute() == QTime::currentTime().minute()) if(time_.time().hour() == QTime::currentTime().hour() && time_.time().minute() == QTime::currentTime().minute())
{ {
triggerd_=true; triggerd_=true;
performAction(); performAction();
if(repeat_ == REPEAT_NEVER) exausted = true; if(repeat_ == REPEAT_NEVER) exausted = true;
} }
} }
else if( repeat_ != REPEAT_NEVER && time_.time().hour() != QTime::currentTime().hour() ) triggerd_=false; else if( repeat_ != REPEAT_NEVER && time_.time().hour() != QTime::currentTime().hour() ) triggerd_=false;
} }
void AlarmTime::changeTime(const QDateTime& time) void AlarmTime::changeTime(const QDateTime& time)
{ {
time_=time; time_=time;
exausted = false; exausted = false;
qDebug()<<"time: "<<time_; qDebug()<<"time: "<<time_;
} }
void AlarmTime::store(QJsonObject& json) void AlarmTime::store(QJsonObject& json)
{ {
json["Type"] = "Alarm"; json["Type"] = "Alarm";
Actor::store(json); Actor::store(json);
json["Time"] = time_.toString(); json["Time"] = time_.toString();
json["Repeat"] = repeat_; json["Repeat"] = repeat_;
} }
void AlarmTime::load(const QJsonObject& json, const bool preserve) void AlarmTime::load(const QJsonObject& json, const bool preserve)
{ {
bool oldActive = isActive(); bool oldActive = isActive();
Actor::load(json, preserve); Actor::load(json, preserve);
time_ = QDateTime::fromString(json["Time"].toString("")); time_ = QDateTime::fromString(json["Time"].toString(""));
repeat_ = json["Repeat"].toInt(REPEAT_NEVER); repeat_ = json["Repeat"].toInt(REPEAT_NEVER);
if(oldActive != isActive()) setActive(isActive()); if(oldActive != isActive()) setActive(isActive());
} }

View file

@ -14,41 +14,41 @@
class AlarmTime : public Actor, public QRunnable class AlarmTime : public Actor, public QRunnable
{ {
Q_OBJECT Q_OBJECT
public: public:
static const uint8_t REPEAT_NEVER = 0; static const uint8_t REPEAT_NEVER = 0;
static const uint8_t REPEAT_DAILY = 1; static const uint8_t REPEAT_DAILY = 1;
static const uint8_t REPEAT_WEEKLY = 2; static const uint8_t REPEAT_WEEKLY = 2;
static const uint8_t REPEAT_MONTHLY = 3; static const uint8_t REPEAT_MONTHLY = 3;
static const uint8_t REPEAT_YEARLY = 4; static const uint8_t REPEAT_YEARLY = 4;
private: private:
bool triggerd_ = false; bool triggerd_ = false;
QDateTime time_; QDateTime time_;
QTimer timer; QTimer timer;
uint8_t repeat_ = REPEAT_NEVER; uint8_t repeat_ = REPEAT_NEVER;
public: public:
explicit AlarmTime(const QDateTime time = QDateTime::currentDateTime(), QObject *parent = nullptr); explicit AlarmTime(const QDateTime time = QDateTime::currentDateTime(), QObject *parent = nullptr);
~AlarmTime(); ~AlarmTime();
QDateTime getDateTime(); QDateTime getDateTime();
virtual void store(QJsonObject& json); virtual void store(QJsonObject& json);
virtual void load(const QJsonObject& json, const bool preserve = false); virtual void load(const QJsonObject& json, const bool preserve = false);
uint8_t getRepeat(); uint8_t getRepeat();
public slots: public slots:
void run(); void run();
virtual void makeActive(); virtual void makeActive();
virtual void makeInactive(); virtual void makeInactive();
virtual QString getName() const; virtual QString getName() const;
void doTick(); void doTick();
void changeTime(const QDateTime& time); void changeTime(const QDateTime& time);
void setRepeat(const uint8_t repeat); void setRepeat(const uint8_t repeat);
}; };
#endif // ALARMTIME_H #endif // ALARMTIME_H

View file

@ -1,80 +1,79 @@
#include "factoractor.h" #include "factoractor.h"
MultiFactorActor::MultiFactorActor(Actor* factorActor, const uint preCancleMin, QObject *parent): MultiFactorActor::MultiFactorActor(Actor* factorActor, const uint preCancleMin, QObject *parent):
Actor(parent), Actor(parent),
factorActor_(factorActor), factorActor_(factorActor),
preCancleMin_(preCancleMin) preCancleMin_(preCancleMin)
{ {
activationTime.setMSecsSinceEpoch(0); activationTime.setMSecsSinceEpoch(0);
if(factorActor) connect(factorActor, &Actor::sigValue, this, &MultiFactorActor::factorActorSlot); if(factorActor) connect(factorActor, &Actor::sigValue, this, &MultiFactorActor::factorActorSlot);
} }
void MultiFactorActor::factorActorSlot(uint8_t value) void MultiFactorActor::factorActorSlot(uint8_t value)
{ {
if(value == factorDirection) if(value == factorDirection)
{ {
activationTime = QDateTime::currentDateTime(); activationTime = QDateTime::currentDateTime();
} }
} }
void MultiFactorActor::setValue(uint8_t value) void MultiFactorActor::setValue(uint8_t value)
{ {
if(value) if(value)
{ {
QDateTime current = QDateTime::currentDateTime(); QDateTime current = QDateTime::currentDateTime();
if(current.addSecs(-preCancleMin_*60) > activationTime ) if(current.addSecs(-preCancleMin_*60) > activationTime )
{ {
performAction(); performAction();
} }
exausted = true; bool exausted = true;
for(size_t i = 0; i < getActors().size(); ++i) if(!getActors()[i]->isExausted()) for(size_t i = 0; i < getActors().size(); ++i) if(!getActors()[i]->isExausted()) exausted = false;
exausted = false; }
}
} }
QString MultiFactorActor::getName() const QString MultiFactorActor::getName() const
{ {
if(name_.size() > 0) return name_; if(name_.size() > 0) return name_;
else else
{ {
QString string; QString string;
string = "Multi Factor \"" + (factorActor_ ? factorActor_->getName() : "NULL") + "\""; string = "Multi Factor \"" + (factorActor_ ? factorActor_->getName() : "NULL") + "\"";
return string; return string;
} }
} }
void MultiFactorActor::setFactorActor(std::shared_ptr<Actor> factorActor) void MultiFactorActor::setFactorActor(std::shared_ptr<Actor> factorActor)
{ {
factorActor_=factorActor; factorActor_=factorActor;
connect(factorActor_.get(), &Actor::sigValue, this, &MultiFactorActor::factorActorSlot); connect(factorActor_.get(), &Actor::sigValue, this, &MultiFactorActor::factorActorSlot);
} }
void MultiFactorActor::store(QJsonObject &json) void MultiFactorActor::store(QJsonObject &json)
{ {
json["Type"] = "MultiFactor"; json["Type"] = "MultiFactor";
Actor::store(json); Actor::store(json);
json["PreCancleMinutes"] = static_cast<int>(preCancleMin_); json["PreCancleMinutes"] = static_cast<int>(preCancleMin_);
json["FactorDirection"] = factorDirection; json["FactorDirection"] = factorDirection;
QJsonObject factorActorObject; QJsonObject factorActorObject;
if(factorActor_) if(factorActor_)
{ {
factorActor_->store(factorActorObject); factorActor_->store(factorActorObject);
} }
} }
void MultiFactorActor::load(const QJsonObject &json, bool preserve) void MultiFactorActor::load(const QJsonObject &json, bool preserve)
{ {
Actor::load(json, preserve); Actor::load(json, preserve);
preCancleMin_ = static_cast<uint>(json["PreCancleMinutes"].toInt(10)); preCancleMin_ = static_cast<uint>(json["PreCancleMinutes"].toInt(10));
factorDirection = json["FacotorDirection"].toBool(true); factorDirection = json["FacotorDirection"].toBool(true);
if(json["FactorActor"].isObject()) if(json["FactorActor"].isObject())
{ {
factorActor_ = Actor::loadActor(json["FactorActor"].toObject()); factorActor_ = Actor::loadActor(json["FactorActor"].toObject());
} }
if(factorActor_) if(factorActor_)
{ {
connect(factorActor_.get(), &Actor::sigValue, this, &MultiFactorActor::factorActorSlot); connect(factorActor_.get(), &Actor::sigValue, this, &MultiFactorActor::factorActorSlot);
} }
} }

View file

@ -8,52 +8,37 @@ class MultiFactorActor: public Actor
{ {
private: private:
std::shared_ptr<Actor> factorActor_; std::shared_ptr<Actor> factorActor_;
QDateTime activationTime; QDateTime activationTime;
uint preCancleMin_; uint preCancleMin_;
bool factorDirection = true; bool factorDirection = true;
private slots: private slots:
void factorActorSlot(uint8_t value); void factorActorSlot(uint8_t value);
public slots: public slots:
virtual void setValue(uint8_t value); virtual void setValue(uint8_t value);
public: public:
MultiFactorActor(Actor* FactorActor = nullptr, const uint preCancleMin = 10, QObject *parent = nullptr); MultiFactorActor(Actor* FactorActor = nullptr, const uint preCancleMin = 10, QObject *parent = nullptr);
virtual QString getName() const; virtual QString getName() const;
void setFactorActor(std::shared_ptr<Actor> factorActor); void setFactorActor(std::shared_ptr<Actor> factorActor);
std::shared_ptr<Actor> getFactorActor() std::shared_ptr<Actor> getFactorActor(){return factorActor_;}
{ void setFactorDirection(const bool direction){factorDirection = direction;}
return factorActor_; bool getFactorDirection(){return factorDirection;}
} uint getPreCancleTime(){return preCancleMin_;}
void setFactorDirection(const bool direction) void setPreCancleTime(uint minutes){preCancleMin_ = minutes;}
{
factorDirection = direction;
}
bool getFactorDirection()
{
return factorDirection;
}
uint getPreCancleTime()
{
return preCancleMin_;
}
void setPreCancleTime(uint minutes)
{
preCancleMin_ = minutes;
}
virtual ~MultiFactorActor() {} virtual ~MultiFactorActor(){}
virtual void store(QJsonObject& json); virtual void store(QJsonObject& json);
virtual void load(const QJsonObject& json, bool preserve); virtual void load(const QJsonObject& json, bool preserve);
}; };
#endif // REMINDERACTOR_H #endif // REMINDERACTOR_H

View file

@ -12,74 +12,72 @@ PolynomalActor::PolynomalActor(QObject* parent): Actor(parent)
void PolynomalActor::setSensor(const Sensor sensor) void PolynomalActor::setSensor(const Sensor sensor)
{ {
sensor_ = sensor; sensor_ = sensor;
} }
void PolynomalActor::setCoeffiancts( const double pow3, const double pow2, const double pow1, const double pow0 ) void PolynomalActor::setCoeffiancts( const double pow3, const double pow2, const double pow1, const double pow0 )
{ {
pow3_=pow3; pow3_=pow3;
pow2_=pow2; pow2_=pow2;
pow1_=pow1; pow1_=pow1;
pow0_=pow0; pow0_=pow0;
} }
void PolynomalActor::getCoeffiancts( double& pow3, double& pow2, double& pow1, double& pow0 ) void PolynomalActor::getCoeffiancts( double& pow3, double& pow2, double& pow1, double& pow0 )
{ {
pow3=pow3_; pow3=pow3_;
pow2=pow2_; pow2=pow2_;
pow1=pow1_; pow1=pow1_;
pow0=pow0_; pow0=pow0_;
} }
void PolynomalActor::sensorEvent(Sensor sensor) void PolynomalActor::sensorEvent(Sensor sensor)
{ {
if(active && sensor == sensor_) if(active && sensor == sensor_)
{ {
double result = pow3_*(sensor.field*sensor.field*sensor.field)+pow2_*(sensor.field*sensor.field)+pow1_*sensor.field double result = pow3_*(sensor.field*sensor.field*sensor.field)+pow2_*(sensor.field*sensor.field)+pow1_*sensor.field+pow0_;
+pow0_; if(result < 0) result = 0;
if(result < 0) result = 0; else if(result > 254) result = 255;
else if(result > 254) result = 255; if(result != prevValue)sigValue(static_cast<uint8_t>(result));
if(result != prevValue)sigValue(static_cast<uint8_t>(result)); prevValue = result;
prevValue = result; }
}
} }
void PolynomalActor::store(QJsonObject& json) void PolynomalActor::store(QJsonObject& json)
{ {
json["Type"] = "Polynomal"; json["Type"] = "Polynomal";
Actor::store(json); Actor::store(json);
json["Pow3"] = pow3_; json["Pow3"] = pow3_;
json["Pow2"] = pow2_; json["Pow2"] = pow2_;
json["Pow1"] = pow1_; json["Pow1"] = pow1_;
json["Pow0"] = pow0_; json["Pow0"] = pow0_;
json["SensorType"] = static_cast<int>(sensor_.type); json["SensorType"] = static_cast<int>(sensor_.type);
json["SensorId"] = static_cast<int>(sensor_.id); json["SensorId"] = static_cast<int>(sensor_.id);
json["SensorField"] = sensor_.field; json["SensorField"] = sensor_.field;
json["SensorName"] = sensor_.name; json["SensorName"] = sensor_.name;
} }
void PolynomalActor::load(const QJsonObject& json, bool preserve) void PolynomalActor::load(const QJsonObject& json, bool preserve)
{ {
Actor::load(json, preserve); Actor::load(json, preserve);
pow3_ = json["Pow3"].toDouble(0); pow3_ = json["Pow3"].toDouble(0);
pow2_ = json["Pow2"].toDouble(0); pow2_ = json["Pow2"].toDouble(0);
pow1_ = json["Pow1"].toDouble(1); pow1_ = json["Pow1"].toDouble(1);
pow0_ = json["Pow0"].toDouble(0); pow0_ = json["Pow0"].toDouble(0);
sensor_.type = json["SensorType"].toInt(0); sensor_.type = json["SensorType"].toInt(0);
sensor_.id = json["SensorId"].toInt(0); sensor_.id = json["SensorId"].toInt(0);
sensor_.field = json["SensorField"].toInt(0); sensor_.field = json["SensorField"].toInt(0);
sensor_.name = json["SensorName"].toString("Sensor"); sensor_.name = json["SensorName"].toString("Sensor");
} }
QString PolynomalActor::getName() const QString PolynomalActor::getName() const
{ {
if(name_.size() > 0) return name_; if(name_.size() > 0) return name_;
else else
{ {
QString string; QString string;
string = QString::number(pow3_) + "x^3 + " + QString::number(pow2_) + "x^2 + " + QString::number( string = QString::number(pow3_) + "x^3 + " + QString::number(pow2_) + "x^2 + " + QString::number(pow1_) + "x + " + QString::number(pow0_) + " (x: " + sensor_.name + ")";
pow1_) + "x + " + QString::number(pow0_) + " (x: " + sensor_.name + ")"; return string;
return string; }
}
} }

View file

@ -1,42 +1,39 @@
#ifndef POLYNOMALACTOR_H #ifndef POLYNOMALACTOR_H
#define POLYNOMALACTOR_H #define POLYNOMALACTOR_H
#include "actor.h" #include "actor.h"
#include "sensors/sensor.h" #include "../sensors/sensor.h"
class PolynomalActor: public Actor class PolynomalActor: public Actor
{ {
Q_OBJECT Q_OBJECT
private: private:
Sensor sensor_; Sensor sensor_;
double pow3_ = 0; double pow3_ = 0;
double pow2_ = 0; double pow2_ = 0;
double pow1_ = 1; double pow1_ = 1;
double pow0_ = 0; double pow0_ = 0;
double prevValue = -1; double prevValue = -1;
public slots: public slots:
void sensorEvent(Sensor sensor); void sensorEvent(Sensor sensor);
public: public:
void setCoeffiancts( const double pow3, const double pow2, const double pow1, const double pow0 ); void setCoeffiancts( const double pow3, const double pow2, const double pow1, const double pow0 );
void getCoeffiancts( double& pow3, double& pow2, double& pow1, double& pow0 ); void getCoeffiancts( double& pow3, double& pow2, double& pow1, double& pow0 );
PolynomalActor(const Sensor sensor, QObject* parent = nullptr); PolynomalActor(const Sensor sensor, QObject* parent = nullptr);
PolynomalActor(QObject* parent = nullptr); PolynomalActor(QObject* parent = nullptr);
void setSensor(const Sensor sensor); void setSensor(const Sensor sensor);
Sensor getSensor() Sensor getSensor(){return sensor_;}
{ virtual QString getName() const;
return sensor_; virtual ~PolynomalActor(){}
}
virtual QString getName() const;
virtual ~PolynomalActor() {}
virtual void store(QJsonObject& json); virtual void store(QJsonObject& json);
virtual void load(const QJsonObject& json, bool preserve); virtual void load(const QJsonObject& json, bool preserve);
}; };
#endif // POLYNOMALACTOR_H #endif // POLYNOMALACTOR_H

View file

@ -4,120 +4,82 @@
Regulator::Regulator(const Sensor sensor, QObject* parent): Actor(parent), sensor_(sensor) Regulator::Regulator(const Sensor sensor, QObject* parent): Actor(parent), sensor_(sensor)
{ {
timer.setSingleShot(true);
timer.start(timeout_*1000);
connect(&timer, &QTimer::timeout, this, &Regulator::timeout);
} }
Regulator::Regulator(QObject* parent): Actor(parent) Regulator::Regulator(QObject* parent): Actor(parent)
{ {
timer.setSingleShot(true);
timer.start(timeout_*1000);
connect(&timer, &QTimer::timeout, this, &Regulator::timeout);
} }
void Regulator::setSensor(const Sensor sensor) void Regulator::setSensor(const Sensor sensor)
{ {
sensor_ = sensor; sensor_ = sensor;
} }
void Regulator::sensorEvent(Sensor sensor) void Regulator::sensorEvent(Sensor sensor)
{ {
if(active && sensor == sensor_) if(active && sensor == sensor_)
{ {
timer.start(timeout_*1000); if( sensor.field < setPoint_-band_ && (sensor.field < sensor_.field || sensor_.field > setPoint_-band_ || first) )
if( sensor.field < setPoint_-band_ && (sensor.field < sensor_.field || sensor_.field > setPoint_-band_ || first) ) {
{ sigValue(triggerValue);
sigValue(triggerValue); }
} else if( sensor.field > setPoint_+band_ && (sensor.field > sensor_.field || sensor_.field < setPoint_+band_ || first) )
else if( sensor.field > setPoint_+band_ && (sensor.field > sensor_.field || sensor_.field < setPoint_+band_ || first) ) {
{ sigValue(!triggerValue);
sigValue(!triggerValue); }
} first = false;
first = false; sensor_ = sensor;
sensor_ = sensor; }
}
}
void Regulator::makeInactive()
{
first = true;
if(active)
sigValue(!triggerValue);
timer.stop();
Actor::makeInactive();
}
void Regulator::timeout()
{
sigValue(safeValue_);
} }
void Regulator::setPoint(float setPoint) void Regulator::setPoint(float setPoint)
{ {
setPoint_ = setPoint; setPoint_ = setPoint;
} }
void Regulator::setBand ( float band ) void Regulator::setBand ( float band )
{ {
band_ = band; band_ = band;
} }
void Regulator::setInvert( bool invert ) void Regulator::setInvert( bool invert )
{ {
invert_ = invert; invert_ = invert;
}
void Regulator::setSafeValue(int value)
{
safeValue_ = value;
}
void Regulator::setTimeout(int value)
{
timeout_ = value;
timer.start(timeout_*1000);
} }
void Regulator::store(QJsonObject& json) void Regulator::store(QJsonObject& json)
{ {
json["Type"] = "Regulator"; json["Type"] = "Regulator";
Actor::store(json); Actor::store(json);
json["Band"] = band_; json["Band"] = band_;
json["SetPoint"] = setPoint_; json["SetPoint"] = setPoint_;
json["SafeValue"] = safeValue_; json["SensorType"] = static_cast<int>(sensor_.type);
json["Timeout"] = timeout_; json["SensorId"] = static_cast<int>(sensor_.id);
json["SensorType"] = static_cast<int>(sensor_.type); json["SensorField"] = sensor_.field;
json["SensorId"] = static_cast<int>(sensor_.id); json["SensorName"] = sensor_.name;
json["SensorField"] = sensor_.field;
json["SensorName"] = sensor_.name;
} }
void Regulator::load(const QJsonObject& json, bool preserve) void Regulator::load(const QJsonObject& json, bool preserve)
{ {
Actor::load(json, preserve); Actor::load(json, preserve);
band_ = json["Band"].toDouble(1); band_ = json["Band"].toDouble(1);
setPoint_ = json["SetPoint"].toDouble(22); setPoint_ = json["SetPoint"].toDouble(22);
safeValue_ = json["SafeValue"].toDouble(0); sensor_.type = json["SensorType"].toInt(0);
timeout_ = json["Timeout"].toDouble(1800); sensor_.id = json["SensorId"].toInt(0);
sensor_.type = json["SensorType"].toInt(0); sensor_.field = json["SensorField"].toInt(0);
sensor_.id = json["SensorId"].toInt(0); sensor_.name = json["SensorName"].toString("Sensor");
sensor_.field = json["SensorField"].toInt(0);
sensor_.name = json["SensorName"].toString("Sensor");
timer.start(timeout_*1000);
} }
QString Regulator::getName() const QString Regulator::getName() const
{ {
if(name_.size() > 0) if(name_.size() > 0) return name_;
{ else
return name_; {
} QString string;
else string = "Regulate \"" + sensor_.name + "\" to ";
{ string.append(QString::number(setPoint_) + " ");
QString string; return string;
string = "Regulate \"" + sensor_.name + "\" to "; }
string.append(QString::number(setPoint_) + " ");
return string;
}
} }

View file

@ -1,68 +1,38 @@
#pragma once #pragma once
#include <QTimer>
#include "actor.h" #include "actor.h"
#include "sensors/sensor.h" #include "../sensors/sensor.h"
class Regulator : public Actor class Regulator : public Actor
{ {
Q_OBJECT Q_OBJECT
private: private:
Sensor sensor_; Sensor sensor_;
float setPoint_ = 0; float setPoint_ = 0;
float band_ = 1; float band_ = 1;
bool invert_ = false; bool invert_ = false;
int timeout_ = 1800;
int safeValue_ = 0;
QTimer timer;
bool first = true; bool first = true;
private slots:
void timeout();
public slots: public slots:
void sensorEvent(Sensor sensor); void sensorEvent(Sensor sensor);
void setSensor(const Sensor sensor); void setSensor(const Sensor sensor);
void setPoint(float setPoint ); void setPoint( float setPoint );
void setBand (float band ); void setBand ( float band );
void setInvert(bool invert ); void setInvert( bool invert );
void setSafeValue(int value);
void setTimeout(int value);
virtual void makeInactive() override;
public: public:
float getBand() float getBand() {return band_;}
{ float getSetPoint() {return setPoint_;}
return band_; Regulator(const Sensor sensor, QObject* parent = nullptr);
} Regulator(QObject* parent = nullptr);
float getSetPoint() Sensor getSensor(){return sensor_;}
{ virtual QString getName() const;
return setPoint_; virtual ~Regulator(){}
}
int getSafeValue() virtual void store(QJsonObject& json);
{ virtual void load(const QJsonObject& json, bool preserve);
return safeValue_;
}
int getTimeout()
{
return timeout_;
}
Regulator(const Sensor sensor, QObject* parent = nullptr);
Regulator(QObject* parent = nullptr);
Sensor getSensor()
{
return sensor_;
}
virtual QString getName() const;
virtual ~Regulator() {}
virtual void store(QJsonObject& json);
virtual void load(const QJsonObject& json, bool preserve);
}; };

View file

@ -14,76 +14,74 @@ SensorActor::SensorActor(QObject* parent): Actor(parent)
void SensorActor::setSensor(const Sensor sensor) void SensorActor::setSensor(const Sensor sensor)
{ {
sensor_ = sensor; sensor_ = sensor;
} }
void SensorActor::sensorEvent(Sensor sensor) void SensorActor::sensorEvent(Sensor sensor)
{ {
if(sensor == sensor_) if(sensor == sensor_)
{ {
if((sloap_ == SLOPE_UP || sloap_ == SLOPE_BOTH) && sensor_.field < threshold_ if((sloap_ == SLOPE_UP || sloap_ == SLOPE_BOTH) && sensor_.field < threshold_ && sensor.field >= threshold_ ) performAction();
&& sensor.field >= threshold_ ) performAction(); else if((sloap_ == SLOPE_DOWN || sloap_ == SLOPE_BOTH) && sensor_.field > threshold_ && sensor.field <= threshold_) performAction();
else if((sloap_ == SLOPE_DOWN || sloap_ == SLOPE_BOTH) && sensor_.field > threshold_ sensor_ = sensor;
&& sensor.field <= threshold_) performAction(); }
sensor_ = sensor;
}
} }
void SensorActor::setSloap(uint8_t sloap) void SensorActor::setSloap(uint8_t sloap)
{ {
sloap_=sloap; sloap_=sloap;
} }
void SensorActor::setThreshold(float threshold) void SensorActor::setThreshold(float threshold)
{ {
threshold_ = threshold; threshold_ = threshold;
} }
float SensorActor::getThreshold() float SensorActor::getThreshold()
{ {
return threshold_; return threshold_;
} }
uint8_t SensorActor::getSloap() uint8_t SensorActor::getSloap()
{ {
return sloap_; return sloap_;
} }
void SensorActor::store(QJsonObject& json) void SensorActor::store(QJsonObject& json)
{ {
json["Type"] = "Sensor"; json["Type"] = "Sensor";
Actor::store(json); Actor::store(json);
json["Sloap"] = sloap_; json["Sloap"] = sloap_;
json["Threshold"] = threshold_; json["Threshold"] = threshold_;
json["SensorType"] = static_cast<int>(sensor_.type); json["SensorType"] = static_cast<int>(sensor_.type);
json["SensorId"] = static_cast<int>(sensor_.id); json["SensorId"] = static_cast<int>(sensor_.id);
json["SensorField"] = sensor_.field; json["SensorField"] = sensor_.field;
json["SensorName"] = sensor_.name; json["SensorName"] = sensor_.name;
} }
void SensorActor::load(const QJsonObject& json, bool preserve) void SensorActor::load(const QJsonObject& json, bool preserve)
{ {
Actor::load(json, preserve); Actor::load(json, preserve);
sloap_ = json["Sloap"].toInt(0); sloap_ = json["Sloap"].toInt(0);
threshold_ = json["Threshold"].toDouble(0); threshold_ = json["Threshold"].toDouble(0);
sensor_.type = json["SensorType"].toInt(0); sensor_.type = json["SensorType"].toInt(0);
sensor_.id = json["SensorId"].toInt(0); sensor_.id = json["SensorId"].toInt(0);
sensor_.field = json["SensorField"].toInt(0); sensor_.field = json["SensorField"].toInt(0);
sensor_.name = json["SensorName"].toString("Sensor"); sensor_.name = json["SensorName"].toString("Sensor");
} }
QString SensorActor::getName() const QString SensorActor::getName() const
{ {
if(name_.size() > 0) return name_; if(name_.size() > 0) return name_;
else else
{ {
QString string; QString string;
string = "Sensor \"" + sensor_.name + "\""; string = "Sensor \"" + sensor_.name + "\"";
if(sloap_ == SLOPE_UP) string.append(" rises to "); if(sloap_ == SLOPE_UP) string.append(" rises to ");
else if (sloap_ == SLOPE_DOWN) string.append(" drops to "); else if (sloap_ == SLOPE_DOWN) string.append(" drops to ");
else if (sloap_ == SLOPE_BOTH) string.append(" passes "); else if (sloap_ == SLOPE_BOTH) string.append(" passes ");
string.append(QString::number(threshold_) + " "); string.append(QString::number(threshold_) + " ");
return string; return string;
} }
} }

View file

@ -1,45 +1,42 @@
#pragma once #pragma once
#include "actor.h" #include "actor.h"
#include "sensors/sensor.h" #include "../sensors/sensor.h"
class SensorActor : public Actor class SensorActor : public Actor
{ {
Q_OBJECT Q_OBJECT
public: public:
static constexpr uint8_t SLOPE_UP = 0; static constexpr uint8_t SLOPE_UP = 0;
static constexpr uint8_t SLOPE_DOWN = 1; static constexpr uint8_t SLOPE_DOWN = 1;
static constexpr uint8_t SLOPE_BOTH = 2; static constexpr uint8_t SLOPE_BOTH = 2;
private: private:
Sensor sensor_; Sensor sensor_;
uint8_t sloap_ = SLOPE_UP; uint8_t sloap_ = SLOPE_UP;
float threshold_ = 0; float threshold_ = 0;
public slots: public slots:
void sensorEvent(Sensor sensor);
void sensorEvent(Sensor sensor); void setSloap(uint8_t sloap);
void setSensor(const Sensor sensor);
void setSloap(uint8_t sloap); void setThreshold( float threshold );
void setSensor(const Sensor sensor);
void setThreshold( float threshold );
public: public:
SensorActor(const Sensor sensor, QObject* parent = nullptr); SensorActor(const Sensor sensor, QObject* parent = nullptr);
SensorActor(QObject* parent = nullptr); SensorActor(QObject* parent = nullptr);
Sensor getSensor() Sensor getSensor(){return sensor_;}
{ virtual QString getName() const;
return sensor_; virtual ~SensorActor(){}
}
virtual QString getName() const;
virtual ~SensorActor() {}
float getThreshold(); float getThreshold();
uint8_t getSloap(); uint8_t getSloap();
virtual void store(QJsonObject& json); virtual void store(QJsonObject& json);
virtual void load(const QJsonObject& json, bool preserve); virtual void load(const QJsonObject& json, bool preserve);
}; };

View file

@ -3,55 +3,55 @@
TimerActor::TimerActor(const int timeoutSec, QObject *parent): Actor(parent), timeoutMsec_(timeoutSec*1000) TimerActor::TimerActor(const int timeoutSec, QObject *parent): Actor(parent), timeoutMsec_(timeoutSec*1000)
{ {
connect(&timer, &QTimer::timeout, this, &TimerActor::timeout); connect(&timer, &QTimer::timeout, this, &TimerActor::timeout);
timer.setSingleShot(true); timer.setSingleShot(true);
} }
void TimerActor::onValueChanged(uint8_t state) void TimerActor::onValueChanged(uint8_t state)
{ {
if((state && !triggerValue) || (!state && triggerValue)) if((state && !triggerValue) || (!state && triggerValue))
{ {
if(timer.isActive()) timer.stop(); if(timer.isActive()) timer.stop();
timer.setInterval(timeoutMsec_); timer.setInterval(timeoutMsec_);
timer.start(); timer.start();
} }
} }
void TimerActor::store(QJsonObject& json) void TimerActor::store(QJsonObject& json)
{ {
json["Type"] = "Timer"; json["Type"] = "Timer";
Actor::store(json); Actor::store(json);
json["Timeout"] = timeoutMsec_; json["Timeout"] = timeoutMsec_;
} }
void TimerActor::load(const QJsonObject& json, bool preserve) void TimerActor::load(const QJsonObject& json, bool preserve)
{ {
Actor::load(json, preserve); Actor::load(json, preserve);
timeoutMsec_ = json["Timeout"].toInt(10000); timeoutMsec_ = json["Timeout"].toInt(10000);
} }
void TimerActor::setTimeout(const int timeoutSec) void TimerActor::setTimeout(const int timeoutSec)
{ {
timeoutMsec_ = timeoutSec*1000; timeoutMsec_ = timeoutSec*1000;
} }
int TimerActor::getTimeout() int TimerActor::getTimeout()
{ {
return timeoutMsec_/1000; return timeoutMsec_/1000;
} }
void TimerActor::timeout() void TimerActor::timeout()
{ {
performAction(); performAction();
} }
QString TimerActor::getName() const QString TimerActor::getName() const
{ {
if(name_.size() > 0) return name_; if(name_.size() > 0) return name_;
else else
{ {
QString string; QString string;
string = "Timeout after " + QString::number(timeoutMsec_/1000) + " seconds. "; string = "Timeout after " + QString::number(timeoutMsec_/1000) + " seconds. ";
return string; return string;
} }
} }

View file

@ -4,27 +4,27 @@
class TimerActor: public Actor class TimerActor: public Actor
{ {
Q_OBJECT Q_OBJECT
private: private:
int timeoutMsec_; int timeoutMsec_;
QTimer timer; QTimer timer;
private slots: private slots:
void timeout(); void timeout();
public slots: public slots:
virtual void onValueChanged(uint8_t state); virtual void onValueChanged(uint8_t state);
void setTimeout(const int timeoutSec); void setTimeout(const int timeoutSec);
public: public:
explicit TimerActor(const int timeoutSec = 60, QObject *parent = nullptr); explicit TimerActor(const int timeoutSec = 60, QObject *parent = nullptr);
virtual QString getName() const; virtual QString getName() const;
int getTimeout(); int getTimeout();
virtual void store(QJsonObject& json); virtual void store(QJsonObject& json);
virtual void load(const QJsonObject& json, bool preserve); virtual void load(const QJsonObject& json, bool preserve);
}; };

14
src/alarmactions.cpp Normal file
View file

@ -0,0 +1,14 @@
#include "alarmactions.h"
#include <QProcess>
AlarmActions::AlarmActions(QApplication* a, Microcontroller* micro, QObject *parent) : QObject(parent), _micro(micro), a_(a)
{
}
void AlarmActions::syncoff()
{
qDebug()<<"syncoff";
QProcess::execute ( "syncoff" );
a_->exit(0);
}

25
src/alarmactions.h Normal file
View file

@ -0,0 +1,25 @@
#ifndef POWER_H
#define POWER_H
#include <QApplication>
#include "microcontroller.h"
class AlarmActions : public QObject
{
private:
Q_OBJECT
Microcontroller* _micro;
QApplication* a_;
public:
explicit AlarmActions(QApplication* a, Microcontroller* micro, QObject *parent = nullptr);
signals:
public slots:
void syncoff();
};
#endif // POWER_H

View file

@ -14,163 +14,159 @@
namespace ap namespace ap
{ {
static int nl80211Init(struct nl_sock* nl_sock, int* nl80211_id) static int nl80211Init(struct nl_sock* nl_sock, int* nl80211_id)
{ {
int err; int err;
if (!nl_sock) if (!nl_sock)
{ {
std::cerr<<"Failed to allocate netlink socket.\n"; std::cerr<<"Failed to allocate netlink socket.\n";
return -ENOMEM; return -ENOMEM;
} }
if (genl_connect(nl_sock)) if (genl_connect(nl_sock))
{ {
std::cerr<<"Failed to connect to generic netlink.\n"; std::cerr<<"Failed to connect to generic netlink.\n";
err = -ENOLINK; err = -ENOLINK;
nl_socket_free(nl_sock); nl_socket_free(nl_sock);
return err; return err;
} }
nl_socket_set_buffer_size(nl_sock, 8192, 8192); nl_socket_set_buffer_size(nl_sock, 8192, 8192);
/* try to set NETLINK_EXT_ACK to 1, ignoring errors */ /* try to set NETLINK_EXT_ACK to 1, ignoring errors */
err = 1; err = 1;
setsockopt(nl_socket_get_fd(nl_sock), SOL_NETLINK, NETLINK_EXT_ACK, &err, sizeof(err)); setsockopt(nl_socket_get_fd(nl_sock), SOL_NETLINK, NETLINK_EXT_ACK, &err, sizeof(err));
*nl80211_id = genl_ctrl_resolve(nl_sock, "nl80211"); *nl80211_id = genl_ctrl_resolve(nl_sock, "nl80211");
if (*nl80211_id < 0) if (*nl80211_id < 0)
{ {
std::cerr<<"nl80211 not found.\n"; std::cerr<<"nl80211 not found.\n";
err = -ENOENT; err = -ENOENT;
nl_socket_free(nl_sock); nl_socket_free(nl_sock);
return err; return err;
} }
return 0; return 0;
} }
static int errorHandler(struct sockaddr_nl *nla, struct nlmsgerr *err, void *arg) static int errorHandler(struct sockaddr_nl *nla, struct nlmsgerr *err, void *arg)
{ {
(void)nla; printf("netlink error\n");
(void)err; *reinterpret_cast<int*>(arg) = 0;
printf("netlink error\n"); return NL_STOP;
*reinterpret_cast<int*>(arg) = 0;
return NL_STOP;
} }
static int finishHandler(struct nl_msg *msg, void *arg) static int finishHandler(struct nl_msg *msg, void *arg)
{ {
(void)msg; *reinterpret_cast<int*>(arg) = 0;
*reinterpret_cast<int*>(arg) = 0; return NL_SKIP;
return NL_SKIP;
} }
static int ackHandler(struct nl_msg *msg, void *arg) static int ackHandler(struct nl_msg *msg, void *arg)
{ {
(void)msg; *reinterpret_cast<int*>(arg) = 0;
*reinterpret_cast<int*>(arg) = 0; return NL_STOP;
return NL_STOP;
} }
static int extractDeviceMac(struct nl_msg *msg, void *arg) static int extractDeviceMac(struct nl_msg *msg, void *arg)
{ {
struct nlattr* tb[NL80211_ATTR_MAX + 1]; struct nlattr* tb[NL80211_ATTR_MAX + 1];
struct genlmsghdr* gnlh = (struct genlmsghdr*)nlmsg_data(nlmsg_hdr(msg)); struct genlmsghdr* gnlh = (struct genlmsghdr*)nlmsg_data(nlmsg_hdr(msg));
std::vector<uint64_t>* deviceMacAddrs = reinterpret_cast<std::vector<uint64_t>*>(arg); std::vector<uint64_t>* deviceMacAddrs = reinterpret_cast<std::vector<uint64_t>*>(arg);
nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0), genlmsg_attrlen(gnlh, 0), NULL); nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0), genlmsg_attrlen(gnlh, 0), NULL);
if (!tb[NL80211_ATTR_STA_INFO]) if (!tb[NL80211_ATTR_STA_INFO])
{ {
std::cerr<<"sta stats missing!\n"; std::cerr<<"sta stats missing!\n";
return -1; return -1;
} }
const unsigned char* macChar = reinterpret_cast<const unsigned char*>(nla_data(tb[NL80211_ATTR_MAC])); const unsigned char* macChar = reinterpret_cast<const unsigned char*>(nla_data(tb[NL80211_ATTR_MAC]));
uint64_t macAddr = 0; uint64_t macAddr = 0;
memcpy(&macAddr, macChar, 6); memcpy(&macAddr, macChar, 6);
deviceMacAddrs->push_back(macAddr); deviceMacAddrs->push_back(macAddr);
return 0; return 0;
} }
std::vector<uint64_t> connectedDevices(const std::string& ifDevice, int& error) std::vector<uint64_t> connectedDevices(const std::string& ifDevice, int& error)
{ {
struct nl_sock* nl_sock = nl_socket_alloc(); struct nl_sock* nl_sock = nl_socket_alloc();
int nl80211_id = 0; int nl80211_id = 0;
error = 0; error = 0;
if(nl80211Init(nl_sock, &nl80211_id)) if(nl80211Init(nl_sock, &nl80211_id))
{ {
std::cerr<<"Can not init nl80211\n"; std::cerr<<"Can not init nl80211\n";
error = ERR_INIT; error = ERR_INIT;
} }
signed long long devidx = if_nametoindex(ifDevice.c_str()); signed long long devidx = if_nametoindex(ifDevice.c_str());
if(!devidx) if(!devidx)
{ {
std::cerr<<ifDevice<<" is not a valid if device\n"; std::cerr<<ifDevice<<" is not a valid if device\n";
error = ERR_NO_DEV; error = ERR_NO_DEV;
} }
struct nl_msg *msg; struct nl_msg *msg;
msg = nlmsg_alloc(); msg = nlmsg_alloc();
if(!msg) error = ERR_ALLOC; if(!msg) error = ERR_ALLOC;
struct nl_cb *cb = nl_cb_alloc(NL_CB_DEFAULT); struct nl_cb *cb = nl_cb_alloc(NL_CB_DEFAULT);
struct nl_cb *s_cb = nl_cb_alloc(NL_CB_DEFAULT); struct nl_cb *s_cb = nl_cb_alloc(NL_CB_DEFAULT);
if (!cb || !s_cb) error = ERR_ALLOC; if (!cb || !s_cb) error = ERR_ALLOC;
std::vector<uint64_t> deviceMacAddrs; std::vector<uint64_t> deviceMacAddrs;
if(error == 0) if(error == 0)
{ {
if(!genlmsg_put(msg, 0, 0, nl80211_id, 0, NLM_F_DUMP, NL80211_CMD_GET_STATION, 0)) if(!genlmsg_put(msg, 0, 0, nl80211_id, 0, NLM_F_DUMP, NL80211_CMD_GET_STATION, 0))
{ {
std::cerr<<"genlmsg_put() failed\n"; std::cerr<<"genlmsg_put() failed\n";
error = ERR_GENERAL; error = ERR_GENERAL;
} }
if(error == 0) if(error == 0)
{ {
NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, devidx); NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, devidx);
nl_socket_set_cb(nl_sock, s_cb); nl_socket_set_cb(nl_sock, s_cb);
nl_send_auto_complete(nl_sock, msg); nl_send_auto_complete(nl_sock, msg);
{ {
int ret = 1; int ret = 1;
nl_cb_err(cb, NL_CB_CUSTOM, errorHandler, &ret); nl_cb_err(cb, NL_CB_CUSTOM, errorHandler, &ret);
nl_cb_set(cb, NL_CB_FINISH, NL_CB_CUSTOM, finishHandler, &ret); nl_cb_set(cb, NL_CB_FINISH, NL_CB_CUSTOM, finishHandler, &ret);
nl_cb_set(cb, NL_CB_ACK, NL_CB_CUSTOM, ackHandler, &ret); nl_cb_set(cb, NL_CB_ACK, NL_CB_CUSTOM, ackHandler, &ret);
nl_cb_set(cb, NL_CB_VALID, NL_CB_CUSTOM, extractDeviceMac, &deviceMacAddrs); nl_cb_set(cb, NL_CB_VALID, NL_CB_CUSTOM, extractDeviceMac, &deviceMacAddrs);
while (ret > 0) nl_recvmsgs(nl_sock, cb); while (ret > 0) nl_recvmsgs(nl_sock, cb);
} }
} }
} }
nla_put_failure: nla_put_failure:
nl_cb_put(cb); nl_cb_put(cb);
nl_cb_put(s_cb); nl_cb_put(s_cb);
nlmsg_free(msg); nlmsg_free(msg);
nl_socket_free(nl_sock); nl_socket_free(nl_sock);
return deviceMacAddrs; return deviceMacAddrs;
} }
std::string macAddrToString(uint64_t macAddr) std::string macAddrToString(uint64_t macAddr)
{ {
unsigned char* macAddrPtr = reinterpret_cast<unsigned char*>(&macAddr); unsigned char* macAddrPtr = reinterpret_cast<unsigned char*>(&macAddr);
std::stringstream ss; std::stringstream ss;
ss<<std::uppercase<<std::setfill('0')<<std::setw(2)<<std::hex; ss<<std::uppercase<<std::setfill('0')<<std::setw(2)<<std::hex;
for(unsigned int i = 0; i < 6; ++i) ss<<+macAddrPtr[i]<<':'; for(unsigned int i = 0; i < 6; ++i) ss<<+macAddrPtr[i]<<':';
std::string macString = ss.str(); std::string macString = ss.str();
macString.pop_back(); macString.pop_back();
return macString; return macString;
} }
} }

View file

@ -6,14 +6,14 @@
namespace ap namespace ap
{ {
enum ERRORS enum ERRORS
{ {
SUCESS, SUCESS,
ERR_INIT, ERR_INIT,
ERR_NO_DEV, ERR_NO_DEV,
ERR_ALLOC, ERR_ALLOC,
ERR_GENERAL ERR_GENERAL
}; };
std::vector<uint64_t> connectedDevices(const std::string& ifDevice, int& error); std::vector<uint64_t> connectedDevices(const std::string& ifDevice, int& error);
std::string macAddrToString(uint64_t macAddr); std::string macAddrToString(uint64_t macAddr);
} }

134
src/broadcast.cpp Normal file
View file

@ -0,0 +1,134 @@
#include "broadcast.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QDebug>
BroadCast::BroadCast(QIODevice* const iodevice, bool master ): master_(master), iodevice_(iodevice)
{
if(iodevice_ != nullptr) connect(iodevice_, &QIODevice::readyRead, this, &BroadCast::readyRead);
}
void BroadCast::write(const char * const buffer, const size_t length)
{
QByteArray mBuffer("bcst: ");
for (size_t i = 0; i < length; ++i)
{
if(buffer[i] != '\n' && buffer[i] != '\0') mBuffer.push_back(buffer[i]);
else
{
mBuffer.push_back('\\');
if(buffer[i] == '\n')mBuffer.push_back('n');
else mBuffer.push_back('0');
}
}
mBuffer.push_back('\n');
if(iodevice_)iodevice_->write(mBuffer);
}
void BroadCast::write(const QByteArray& buffer)
{
write(buffer.data(), buffer.size());
}
void BroadCast::sendJson(const QJsonObject& json)
{
QJsonDocument jsonDocument(json);
QByteArray buffer("JSON: ");
buffer.append(jsonDocument.toJson());
write(buffer);
}
void BroadCast::sendSensors()
{
if(iodevice_)for(auto& sensor: *globalSensors.getSensors())
{
iodevice_->write("bcst: "+sensor.toString().toLatin1()+'\n');
}
}
void BroadCast::requestSensors()
{
if(iodevice_)iodevice_->write("bcst: GETSENSORS\n");
}
void BroadCast::requestJson()
{
if(iodevice_)iodevice_->write("bcst: GETJSN\n");
}
void BroadCast::decodeMaster(const QByteArray& buffer)
{
if(buffer.startsWith("GETJSN"))
{
qDebug()<<"json requested";
jsonRequested();
}
else if(buffer.startsWith("GETSENSORS") )
{
qDebug()<<"sensors requested";
sendSensors();
}
}
void BroadCast::decode(QByteArray buffer)
{
qDebug()<<"decodeing: "<<buffer;
if(buffer.size() >= 6 && buffer[0] == 'J' && buffer[1] == 'S' && buffer[2] == 'O' && buffer[3] == 'N' && buffer[4] == ':')
{
qDebug()<<"got json";
buffer.remove(0,6);
for(int i = 0; i < buffer.size()-1; ++i)
{
if( buffer[i] == '\\' && buffer[i+1] == 'n' )
{
buffer[i] = '\n';
buffer.remove(i+1,1);
}
else if( buffer[i] == '\\' && buffer[i+1] == '0' )
{
buffer[i] = '\0';
buffer.remove(i+1,1);
}
}
QJsonParseError error;
QJsonDocument document = QJsonDocument::fromJson(buffer, &error);
qDebug()<<"JSON:";
qDebug()<<document.toJson().data();
QJsonObject jsonObject = document.object();
if(error.error == QJsonParseError::NoError && !document.isEmpty() && !jsonObject.isEmpty()) gotJson(jsonObject);
else
{
qDebug()<<error.errorString();
}
}
else if(buffer.size() >= 6 && buffer[0] == 'S' && buffer[1] == 'E' && buffer[2] == 'N' && buffer[3] == 'S' && buffer[4] == 'O' && buffer[5] == 'R')
{
Sensor sensor = Sensor::sensorFromString(buffer);
if(sensor.type != Sensor::TYPE_DUMMY) gotSensorState(sensor);
}
}
void BroadCast::sendMessage(const QString &title, const QString &body)
{
write(QByteArray("MESG ") + title.toLatin1() + " BODY " + body.toLatin1());
}
void BroadCast::readyRead()
{
buffer_.append(iodevice_->readAll());
int newlineIndex = buffer_.indexOf('\n');
while( newlineIndex != -1 )
{
if(buffer_.startsWith("bcst: "))
{
QByteArray tmp = buffer_.mid(6,newlineIndex-6);
decode(tmp);
if(master_)decodeMaster(tmp);
}
buffer_.remove(0, newlineIndex+1);
newlineIndex = buffer_.indexOf('\n');
}
}

55
src/broadcast.h Normal file
View file

@ -0,0 +1,55 @@
#ifndef BROADCAST_H
#define BROADCAST_H
#include <QIODevice>
#include <QObject>
#include <QString>
#include <QJsonObject>
#include "sensors/sensor.h"
class BroadCast: public QObject
{
Q_OBJECT
private:
bool master_;
static constexpr uint8_t MODE_PREPACKET = 0;
static constexpr uint8_t MODE_PACKET = 1;
QByteArray buffer_;
QIODevice* const iodevice_;
void write(const char * const buffer, const size_t length);
void write(const QByteArray& buffer);
void decode(QByteArray buffer);
void decodeMaster(const QByteArray& buffer);
private slots:
void readyRead();
public slots:
void requestJson();
void requestSensors();
signals:
void jsonRequested();
void gotJson(QJsonObject json);
void gotSensorState(Sensor sensor);
public:
BroadCast(QIODevice* const iodevice = nullptr, bool master = true);
void sendJson(const QJsonObject& json);
void sendSensors();
void sendMessage(const QString& title, const QString& body);
};
#endif // BROADCAST_H

76
src/iomuliplexer.cpp Normal file
View file

@ -0,0 +1,76 @@
#include "iomuliplexer.h"
#include<QDebug>
VirutalIODevice::VirutalIODevice(QObject* parent): QBuffer(parent)
{
}
qint64 VirutalIODevice::writeData(const char *data, qint64 len)
{
blockSignals(true);
qint64 ret = QBuffer::writeData(data, len);
blockSignals(false);
masterReadyRead();
return ret;
}
qint64 VirutalIODevice::masterWrite(const QByteArray &byteArray)
{
return masterWrite(byteArray.data(), byteArray.length());
}
qint64 VirutalIODevice::masterWrite(const char *data, qint64 maxSize)
{
blockSignals(true);
qint64 ret = QBuffer::writeData(data, maxSize);
blockSignals(false);
readyRead();
return ret;
}
IoMuliplexer::IoMuliplexer(QIODevice* mainDevice, QObject* Parent): IoMuliplexer(Parent)
{
setIoDevice(mainDevice);
}
IoMuliplexer::IoMuliplexer(QObject* Parent): QObject(Parent)
{
}
IoMuliplexer::~IoMuliplexer()
{
for(size_t i = 0; i < ioDevices_.size(); ++i) delete ioDevices_[i];
ioDevices_.clear();
}
void IoMuliplexer::setIoDevice(QIODevice* mainDevice)
{
mainDevice_ = mainDevice;
connect(mainDevice_, &QIODevice::readyRead, this, &IoMuliplexer::mainIsReadyRead);
}
QIODevice* IoMuliplexer::getIoDevice()
{
ioDevices_.push_back(new VirutalIODevice);
ioDevices_.back()->open(QIODevice::ReadWrite);
connect(ioDevices_.back(), &VirutalIODevice::masterReadyRead, this, &IoMuliplexer::clientIsReadyRead);
return ioDevices_.back();
}
void IoMuliplexer::clientIsReadyRead()
{
VirutalIODevice* device = dynamic_cast<VirutalIODevice*>(sender());
if(device)
{
QByteArray array = device->readAll();
mainDevice_->write(array);
}
}
void IoMuliplexer::mainIsReadyRead()
{
QByteArray array = mainDevice_->readAll();
for(size_t i = 0; i < ioDevices_.size(); ++i) ioDevices_[i]->masterWrite(array);
}

54
src/iomuliplexer.h Normal file
View file

@ -0,0 +1,54 @@
#ifndef IOMULIPLEXER_H
#define IOMULIPLEXER_H
#include <QObject>
#include <vector>
#include <QIODevice>
#include <QBuffer>
class VirutalIODevice: public QBuffer
{
Q_OBJECT
public:
VirutalIODevice(QObject* parent = nullptr);
virtual ~VirutalIODevice() override {}
virtual qint64 writeData(const char *data, qint64 len) override;
qint64 masterWrite(const QByteArray &byteArray);
qint64 masterWrite(const char *data, qint64 maxSize);
signals:
void masterReadyRead();
};
class IoMuliplexer: public QObject
{
Q_OBJECT
private:
QIODevice* mainDevice_;
std::vector< VirutalIODevice* > ioDevices_;
public:
explicit IoMuliplexer(QIODevice* mainDevice, QObject* Parent = nullptr);
explicit IoMuliplexer(QObject* Parent = nullptr);
~IoMuliplexer();
void setIoDevice(QIODevice* mainDevice);
QIODevice* getIoDevice();
private slots:
void mainIsReadyRead();
void clientIsReadyRead();
};
#endif // IOMULIPLEXER_H

View file

@ -1,19 +1,18 @@
#include "auxitem.h" #include "auxitem.h"
AuxItem::AuxItem(Microcontroller* micro, uint32_t itemIdIn, QString name, uint8_t value, AuxItem::AuxItem(Microcontroller* micro, uint32_t itemIdIn, QString name, uint8_t value, QObject* parent): Item(itemIdIn, name, value, parent), micro_(micro)
QObject* parent): Item(itemIdIn, name, value, parent), micro_(micro)
{ {
type_ = ITEM_VALUE_UINT;
} }
void AuxItem::enactValue(uint8_t value) void AuxItem::setValue(uint8_t value)
{ {
assert(micro_); Item::setValue(value);
micro_->setAuxPwm(value); micro_->setAuxPwm(value);
} }
void AuxItem::store(QJsonObject &json) void AuxItem::store(QJsonObject &json)
{ {
json["Type"] = "Aux"; json["Type"] = "Aux";
Item::store(json); Item::store(json);
} }

View file

@ -1,20 +1,20 @@
#pragma once #pragma once
#include "item.h" #include "item.h"
#include "microcontroller.h" #include "../microcontroller.h"
class AuxItem: public Item class AuxItem: public Item
{ {
Q_OBJECT Q_OBJECT
private: private:
Microcontroller* micro_; Microcontroller* micro_;
protected: public slots:
virtual void enactValue(uint8_t value) override;
virtual void setValue(uint8_t value);
public: public:
AuxItem(Microcontroller* micro = nullptr, uint32_t itemIdIn = QRandomGenerator::global()->generate(), QString name = "", AuxItem(Microcontroller* micro, uint32_t itemIdIn = QRandomGenerator::global()->generate(), QString name = "", uint8_t value = 0, QObject* parent = nullptr);
uint8_t value = 0, QObject* parent = nullptr);
virtual void store(QJsonObject& json) override; virtual void store(QJsonObject& json);
}; };

View file

@ -1,14 +0,0 @@
#include "fixeditemsource.h"
FixedItemSource::FixedItemSource(Microcontroller* micro, QObject *parent):
ItemSource{parent},
powerItem(new PowerItem(5487423)),
rgbItem(new RgbItem(micro, 5487422, "Rgb Lights")),
auxItem(new AuxItem(micro, 5487421, "Desk Light"))
{
}
void FixedItemSource::refresh()
{
gotItems({powerItem, rgbItem, auxItem});
}

View file

@ -1,22 +0,0 @@
#ifndef FIXEDITEMSOURCE_H
#define FIXEDITEMSOURCE_H
#include "itemsource.h"
#include "poweritem.h"
#include "rgbitem.h"
#include "auxitem.h"
#include "microcontroller.h"
class FixedItemSource : public ItemSource
{
Q_OBJECT
std::shared_ptr<PowerItem> powerItem;
std::shared_ptr<RgbItem> rgbItem;
std::shared_ptr<AuxItem> auxItem;
public:
explicit FixedItemSource(Microcontroller* micro, QObject *parent = nullptr);
virtual void refresh() override;
};
#endif // FIXEDITEMSOURCE_H

View file

@ -1,103 +1,44 @@
#include "item.h" #include "item.h"
#include "actors/sensoractor.h"
#include "actors/regulator.h"
#include "actors/polynomalactor.h"
#include "programmode.h"
#include "relay.h" #include "relay.h"
#include "messageitem.h" #include "../microcontroller.h"
#include "systemitem.h" #include "../actors/sensoractor.h"
#include "auxitem.h" #include "../actors/regulator.h"
#include "poweritem.h" #include "../actors/polynomalactor.h"
#include "rgbitem.h"
#include <QJsonArray> #include <QJsonArray>
ItemData::ItemData(uint32_t itemIdIn, QString name, uint8_t value, bool loaded, bool hidden, item_value_type_t type): ItemData::ItemData(uint32_t itemIdIn, QString name, uint8_t value): name_(name), value_(value), itemId_(itemIdIn)
name_(name), value_(value), itemId_(itemIdIn), loaded_(loaded), hidden_(hidden), type_(type)
{ {
} }
QString ItemData::getName() const QString ItemData::getName() const
{ {
return name_; return name_;
} }
void ItemData::setName(QString name) void ItemData::setName(QString name)
{ {
name_ = name; name_ = name;
} }
uint8_t ItemData::getValue() const uint8_t ItemData::getValue() const
{ {
return value_; return value_;
} }
uint32_t ItemData::id() const uint32_t ItemData::id() const
{ {
return itemId_; return itemId_;
} }
void ItemData::store(QJsonObject &json)
{
json["Name"] = name_;
json["ItemId"] = static_cast<double>(itemId_);
json["Value"] = static_cast<double>(value_);
}
void ItemData::load(const QJsonObject &json, const bool preserve)
{
if(!preserve)
{
name_ = json["Name"].toString(name_);
itemId_ = static_cast<uint32_t>(json["ItemId"].toDouble(0));
value_ = json["Value"].toInt();
}
}
bool ItemData::getLoaded() const
{
return loaded_;
}
void ItemData::setLoaded(bool loaded)
{
loaded_ = loaded;
}
bool ItemData::hasChanged(const ItemData& other)
{
if(other != *this)
return false;
if(other.getName() != getName())
return true;
if(other.getValue() != getValue())
return true;
if(other.getLoaded() != getLoaded())
return true;
return false;
}
bool ItemData::isHidden()
{
return hidden_;
}
void ItemData::setHidden(bool hidden)
{
hidden_ = hidden;
}
item_value_type_t ItemData::getValueType()
{
return type_;
}
//item //item
Item::Item(uint32_t itemIdIn, QString name, uint8_t value, QObject *parent): QObject(parent), ItemData (itemIdIn, name, bool Item::secondaryFlag = false;
value)
Item::Item(uint32_t itemIdIn, QString name, uint8_t value, QObject *parent): QObject(parent), ItemData (itemIdIn, name, value)
{ {
} }
@ -113,171 +54,116 @@ Item::~Item()
void Item::store(QJsonObject &json) void Item::store(QJsonObject &json)
{ {
ItemData::store(json); json["Name"] = name_;
json["override"] = override_; json["ItemId"] = static_cast<double>(itemId_);
QJsonArray actorsArray; json["override"] = override_;
for(size_t i = 0; i < actors_.size(); ++i) QJsonArray actorsArray;
{ for(size_t i = 0; i < actors_.size(); ++i)
if(!actors_[i]->isExausted()) {
{ if(!actors_[i]->isExausted())
QJsonObject actorObject; {
actors_[i]->store(actorObject); QJsonObject actorObject;
actorsArray.append(actorObject); actors_[i]->store(actorObject);
} actorsArray.append(actorObject);
} }
json["Actors"] = actorsArray; }
json["Actors"] = actorsArray;
} }
void Item::load(const QJsonObject &json, const bool preserve) void Item::load(const QJsonObject &json, const bool preserve)
{ {
ItemData::load(json, preserve); if(!preserve)
override_ = json["override"].toBool(false); {
const QJsonArray actorsArray(json["Actors"].toArray(QJsonArray())); name_ = json["Name"].toString(name_);
for(int i = 0; i < actorsArray.size(); ++i) itemId_ = static_cast<uint32_t>(json["ItemId"].toDouble(0));
{ }
if(actorsArray[i].isObject()) override_ = json["override"].toBool(false);
{ const QJsonArray actorsArray(json["Actors"].toArray(QJsonArray()));
std::shared_ptr<Actor> actor = Actor::loadActor(actorsArray[i].toObject()); for(int i = 0; i < actorsArray.size(); ++i)
if(actor != nullptr) {
addActor(actor); if(actorsArray[i].isObject())
} {
} std::shared_ptr<Actor> actor = Actor::loadActor(actorsArray[i].toObject());
if(actor != nullptr) addActor(actor);
}
}
} }
void Item::actorSetValue(uint8_t value) void Item::actorSetValue(uint8_t value)
{ {
if(!override_ && (programMode == PROGRAM_MODE_PRIMARY || programMode == PROGRAM_MODE_HEADLESS_PRIMARY)) if(!override_) setValue(value);
setValue(value);
} }
void Item::setValue(uint8_t value) void Item::setValue(uint8_t value)
{ {
qDebug()<<__func__; value_ = value;
informValue(value); valueChanged(value_);
if(programMode == PROGRAM_MODE_PRIMARY || programMode == PROGRAM_MODE_HEADLESS_PRIMARY)
enactValue(value);
} }
void Item::informValue(uint8_t value) void Item::informValue(uint8_t value)
{ {
if(value_ != value) Item::setValue(value);
{
value_ = value;
valueChanged(value_);
updated(*this);
}
}
void Item::enactValue(uint8_t value)
{
(void)value;
} }
void Item::addActor(std::shared_ptr<Actor> actor) void Item::addActor(std::shared_ptr<Actor> actor)
{ {
actor->setParent(this); actor->setParent(this);
actors_.push_back(actor); actors_.push_back(actor);
if(programMode == PROGRAM_MODE_PRIMARY || programMode == PROGRAM_MODE_HEADLESS_PRIMARY) if(!secondaryFlag)
connect(actor.get(), &Actor::sigValue, this, &Item::actorSetValue); {
connect(this, &Item::valueChanged, actor.get(), &Actor::onValueChanged); connect(actor.get(), &Actor::sigValue, this, &Item::actorSetValue);
}
connect(this, &Item::valueChanged, actor.get(), &Actor::onValueChanged);
std::shared_ptr<SensorActor> sensorActor = std::dynamic_pointer_cast<SensorActor>(actor); std::shared_ptr<SensorActor> sensorActor = std::dynamic_pointer_cast<SensorActor>(actor);
if(sensorActor) if(sensorActor)connect(&globalSensors, &SensorStore::sensorChangedState, sensorActor.get(), &SensorActor::sensorEvent);
connect(&globalSensors, &SensorStore::sensorChangedState, sensorActor.get(), &SensorActor::sensorEvent);
std::shared_ptr<Regulator> regulator = std::dynamic_pointer_cast<Regulator>(actor); std::shared_ptr<Regulator> regulator = std::dynamic_pointer_cast<Regulator>(actor);
if(regulator) if(regulator)connect(&globalSensors, &SensorStore::sensorChangedState, regulator.get(), &Regulator::sensorEvent);
connect(&globalSensors, &SensorStore::sensorChangedState, regulator.get(), &Regulator::sensorEvent);
std::shared_ptr<PolynomalActor> polynomalActor = std::dynamic_pointer_cast<PolynomalActor>(actor); std::shared_ptr<PolynomalActor> polynomalActor = std::dynamic_pointer_cast<PolynomalActor>(actor);
if(polynomalActor != nullptr ) if(polynomalActor != nullptr )connect(&globalSensors, &SensorStore::sensorChangedState, polynomalActor.get(), &PolynomalActor::sensorEvent);
connect(&globalSensors, &SensorStore::sensorChangedState, polynomalActor.get(), &PolynomalActor::sensorEvent);
} }
bool Item::removeActor(std::shared_ptr<Actor> actor) bool Item::removeActor(std::shared_ptr<Actor> actor)
{ {
for(unsigned int i = 0; i < actors_.size(); i++) for(unsigned int i = 0; i < actors_.size(); i++)
{ {
if(actors_[i] == actor) if(actors_[i] == actor)
{ {
actors_.erase(actors_.begin()+i); actors_.erase(actors_.begin()+i);
return true; return true;
} }
} }
return false; return false;
} }
void Item::setOverride(const bool in) void Item::setOverride(const bool in)
{ {
override_ = in; override_ = in;
} }
bool Item::getOverride() bool Item::getOverride()
{ {
return override_; return override_;
} }
void Item::removeAllActors() void Item::removeAllActors()
{ {
actors_.clear(); actors_.clear();
} }
std::vector< std::shared_ptr<Actor> >& Item::getActors() std::vector< std::shared_ptr<Actor> >& Item::getActors()
{ {
return actors_; return actors_;
} }
bool Item::hasActors() bool Item::hasActors()
{ {
return actors_.size() > 0; return actors_.size() > 0;
} }
void Item::setActorsActive(bool in) void Item::setActorsActive(bool in)
{ {
for(unsigned i = 0; i < actors_.size(); i++) for(unsigned i = 0; i < actors_.size(); i++) in ? actors_[i]->makeActive() : actors_[i]->makeInactive();
in ? actors_[i]->makeActive() : actors_[i]->makeInactive();
} }
void Item::mergeLoaded(Item& item)
{
name_ = item.name_;
actors_.clear();
for(std::shared_ptr<Actor> actor : item.actors_)
addActor(actor);
}
std::shared_ptr<Item> Item::loadItem(const QJsonObject& json)
{
std::shared_ptr<Item> newItem = nullptr;
if(json["Type"].toString("") == "Relay")
{
newItem = std::shared_ptr<Relay>(new Relay);
}
else if(json["Type"].toString("") == "Message")
{
newItem = std::shared_ptr<MessageItem>(new MessageItem);
}
else if(json["Type"].toString("") == "System")
{
newItem = std::shared_ptr<SystemItem>(new SystemItem);
}
else if(json["Type"].toString("") == "Aux")
{
newItem = std::shared_ptr<AuxItem>(new AuxItem);
}
else if(json["Type"].toString("") == "Power")
{
newItem = std::shared_ptr<PowerItem>(new PowerItem);
}
else if(json["Type"].toString("") == "Rgb")
{
newItem = std::shared_ptr<RgbItem>(new RgbItem);
}
if(newItem)
{
newItem->load(json);
newItem->setLoaded(true);
}
return newItem;
}

View file

@ -8,99 +8,70 @@
class Actor; class Actor;
typedef enum {
ITEM_VALUE_BOOL = 0,
ITEM_VALUE_UINT,
ITEM_VALUE_NO_VALUE
} item_value_type_t;
class ItemData class ItemData
{ {
protected: protected:
QString name_; QString name_;
uint8_t value_; uint8_t value_;
uint32_t itemId_; uint32_t itemId_;
bool loaded_;
bool hidden_;
item_value_type_t type_;
public: public:
ItemData(uint32_t itemIdIn = QRandomGenerator::global()->generate(),
QString name = "Item",
uint8_t value = 0,
bool loaded = false,
bool hidden = false,
item_value_type_t type = ITEM_VALUE_BOOL);
inline bool operator==(const ItemData& in) const ItemData(uint32_t itemIdIn = QRandomGenerator::global()->generate(), QString name = "Item", uint8_t value = 0);
{
return itemId_ == in.itemId_;
}
inline bool operator!=(const ItemData& in) const
{
return itemId_ != in.itemId_;
}
uint32_t id() const; inline bool operator==(const ItemData& in) const{ return itemId_==in.itemId_; }
inline bool operator!=(const ItemData& in) const{ return itemId_!=in.itemId_; }
bool hasChanged(const ItemData& other); uint32_t id() const;
void setName(QString name);
uint8_t getValue() const; void setName(QString name);
bool getLoaded() const; uint8_t getValue() const;
void setLoaded(bool loaded); virtual QString getName() const;
bool isHidden();
void setHidden(bool hidden);
item_value_type_t getValueType();
virtual QString getName() const;
virtual void store(QJsonObject& json);
virtual void load(const QJsonObject& json, const bool preserve = false);
}; };
class Item: public QObject, public ItemData class Item: public QObject, public ItemData
{ {
Q_OBJECT Q_OBJECT
private: private:
std::vector< std::shared_ptr<Actor> > actors_; std::vector< std::shared_ptr<Actor> > actors_;
bool override_ = false; bool override_ = false;
signals:
void valueChanged(uint8_t value);
void updated(ItemData data);
private slots:
virtual void actorSetValue(uint8_t value);
public slots:
void setValue(uint8_t value);
public: public:
Item(uint32_t itemIdIn = QRandomGenerator::global()->generate(), QString name = "Item", uint8_t value = 0, static bool secondaryFlag;
QObject *parent = nullptr);
Item(const ItemData& itemData, QObject *parent = nullptr);
virtual ~Item(); signals:
std::vector< std::shared_ptr<Actor> >& getActors(); void valueChanged(uint8_t value);
bool hasActors();
void addActor(std::shared_ptr<Actor> actor);
bool removeActor(std::shared_ptr<Actor> actor);
void removeAllActors();
void setActorsActive(bool in);
void setOverride(const bool in);
bool getOverride();
void informValue(uint8_t value);
void mergeLoaded(Item& item);
virtual void store(QJsonObject& json); private slots:
virtual void load(const QJsonObject& json, const bool preserve = false); virtual void actorSetValue(uint8_t value);
static std::shared_ptr<Item> loadItem(const QJsonObject& json); public slots:
protected: virtual void setValue(uint8_t value);
virtual void enactValue(uint8_t value);
public:
Item(uint32_t itemIdIn = QRandomGenerator::global()->generate(), QString name = "Item", uint8_t value = 0, QObject *parent = nullptr);
Item(const ItemData& itemData, QObject *parent = nullptr);
virtual ~Item();
std::vector< std::shared_ptr<Actor> >& getActors();
bool hasActors();
void addActor(std::shared_ptr<Actor> actor);
bool removeActor(std::shared_ptr<Actor> actor);
void removeAllActors();
void setActorsActive(bool in);
void setOverride(const bool in);
bool getOverride();
void informValue(uint8_t value);
virtual void store(QJsonObject& json);
virtual void load(const QJsonObject& json, const bool preserve = false);
}; };

View file

@ -1,38 +0,0 @@
#include "itemloadersource.h"
#include <QJsonArray>
ItemLoaderSource::ItemLoaderSource(const QJsonObject& json, QObject *parent):
ItemSource{parent},
json(json)
{
}
void ItemLoaderSource::refresh()
{
std::vector<std::shared_ptr<Item>> items;
const QJsonArray itemsArray(json["Items"].toArray());
for(int i = 0; i < itemsArray.size(); ++i)
{
if(!itemsArray[i].isObject())
continue;
const QJsonObject itemObject = itemsArray[i].toObject();
std::shared_ptr<Item> newItem = Item::loadItem(itemObject);
if(newItem)
{
items.push_back(newItem);
qDebug()<<"Loaded item"<<newItem->getName();
}
}
gotItems(items);
}
void ItemLoaderSource::updateJson(const QJsonObject& json)
{
this->json = json;
}
ItemLoaderSource::~ItemLoaderSource()
{}

View file

@ -1,21 +0,0 @@
#ifndef ITEMLOADERSOURCE_H
#define ITEMLOADERSOURCE_H
#include <QJsonObject>
#include "itemsource.h"
class ItemLoaderSource : public ItemSource
{
Q_OBJECT
QJsonObject json;
public:
explicit ItemLoaderSource(const QJsonObject& json = QJsonObject(), QObject *parent = nullptr);
~ItemLoaderSource();
void updateJson(const QJsonObject& json);
virtual void refresh() override;
};
#endif // ITEMLOADERSOURCE_H

View file

@ -1,5 +0,0 @@
#include "itemsource.h"
ItemSource::ItemSource(QObject *parent)
: QObject{parent}
{}

View file

@ -1,25 +0,0 @@
#ifndef ITEMSOURCE_H
#define ITEMSOURCE_H
#include <QObject>
#include <vector>
#include <memory>
#include "item.h"
class ItemSource : public QObject
{
Q_OBJECT
public:
explicit ItemSource(QObject *parent = nullptr);
public slots:
virtual void refresh() = 0;
signals:
void gotItems(std::vector<std::shared_ptr<Item>> items, bool inform = true);
void requestReplaceItems(std::vector<std::shared_ptr<Item>> items);
void updateItems(std::vector<ItemData> items, bool inform = true);
};
#endif // ITEMSOURCE_H

View file

@ -1,154 +1,130 @@
#include "itemstore.h" #include "itemstore.h"
#include "relay.h"
#include "messageitem.h"
#include "systemitem.h"
#include <QJsonArray> #include <QJsonArray>
#include <typeinfo>
ItemStore::ItemStore(QObject *parent): QObject(parent) ItemStore::ItemStore(QObject *parent): QObject(parent)
{ {
} }
void ItemStore::addItem(std::shared_ptr<Item> item, bool inform) void ItemStore::addItem(std::shared_ptr<Item> item)
{ {
std::shared_ptr<Item> matched = nullptr; bool mached = false;
for(unsigned i = 0; i < items_.size(); i++ ) for(unsigned i = 0; i < items_.size(); i++ ) if(*items_[i] == *item) mached = true;
{ if(!mached)
if(*items_[i] == *item) {
{ items_.push_back(std::shared_ptr<Item>(item));
matched = items_[i]; itemAdded(std::weak_ptr<Item>(items_.back()));
break; }
}
}
if(!matched)
{
items_.push_back(std::shared_ptr<Item>(item));
connect(item.get(), &Item::updated, this, &ItemStore::itemUpdateSlot);
qDebug()<<"Item"<<item->getName()<<"added"<<(item->getLoaded() ? "from loaded" : "");
itemAdded(std::weak_ptr<Item>(items_.back()));
}
else
{
if(item->getLoaded())
matched->mergeLoaded(*item);
else if(item->getValue() != matched->getValue())
updateItem(*item, inform);
}
} }
void ItemStore::addItems(const std::vector<std::shared_ptr<Item>>& itemIn, bool inform) void ItemStore::addItems(const std::vector<std::shared_ptr<Item>>& itemIn)
{ {
for(unsigned j = 0; j < itemIn.size(); j++) for(unsigned i = 0; i < items_.size(); i++ )
addItem(itemIn[j], inform); {
if(Relay* relay = dynamic_cast<Relay*>(items_[i].get()))
{
bool mached = false;
for(unsigned j = 0; j < itemIn.size(); j++) if(*(items_[i]) == *(itemIn[j]))
{
mached = true;
if(itemIn[j]->getValue() != items_[i]->getValue()) items_[i]->informValue(itemIn[j]->getValue());
Relay* relayIn = dynamic_cast<Relay*>(itemIn[j].get());
if(relayIn)
{
if(relay->getId() != relayIn->getId()) relay->setId(relayIn->getId());
}
}
if(!mached)
{
itemDeleted(*items_[i].get());
items_.erase(items_.begin()+i);
}
}
}
for(unsigned j = 0; j < itemIn.size(); j++)addItem(itemIn[j]);
} }
void ItemStore::removeItem(const ItemData& item) void ItemStore::removeItem(const ItemData& item)
{ {
for(unsigned j = 0; j < items_.size(); j++) for(unsigned j = 0; j < items_.size(); j++)
{ {
if(item == *items_[j]) if(item == *items_[j])
{ {
qDebug()<<"Item"<<item.getName()<<"deleted"; items_.erase(items_.begin()+j);
itemDeleted(*items_[j]); --j;
items_.erase(items_.begin()+j); }
--j; }
}
}
} }
void ItemStore::replaceItems(const std::vector<std::shared_ptr<Item>>& items)
{
addItems(items, true);
std::vector<ItemData> deletedItems;
for(std::shared_ptr<Item> item : items_)
{
if(std::find_if(items.begin(), items.end(), [item](const std::shared_ptr<Item> other){return *item == *other;}) == items.end())
deletedItems.push_back(*item);
}
for(const ItemData& item : deletedItems)
removeItem(item);
}
void ItemStore::clear() void ItemStore::clear()
{ {
for(size_t i = 0; i < items_.size(); ++i) itemDeleted(*items_[i]); for(size_t i = 0; i < items_.size(); ++i) itemDeleted(*items_[i]);
items_.clear(); items_.clear();
} }
void ItemStore::updateItems(std::vector<ItemData> items, bool inform) void ItemStore::itemStateChanged(const ItemData& item)
{ {
for(const ItemData& item : items)
updateItem(item, inform);
}
void ItemStore::updateItem(const ItemData& item, bool inform) for(unsigned i = 0; i < items_.size(); i++ )
{ {
for(unsigned i = 0; i < items_.size(); i++ ) if(items_[i]->operator==(item))
{ {
if(items_[i]->operator==(item))
{ if(items_[i]->getValue() != item.getValue())items_[i]->informValue(item.getValue());
if(items_[i]->hasChanged(item)) }
{
if(items_[i]->getValue() != item.getValue()) }
{
items_[i]->setLoaded(false);
if(inform)
items_[i]->informValue(item.getValue());
else
items_[i]->setValue(item.getValue());
}
qDebug()<<"Item"<<items_[i]->getName()<<"updated";
itemUpdated(items_[i]);
}
}
}
} }
void ItemStore::store(QJsonObject& json) void ItemStore::store(QJsonObject& json)
{ {
QJsonArray itemsArray; QJsonArray itemsArray;
for(size_t i = 0; i < items_.size(); ++i) for(size_t i = 0; i < items_.size(); ++i)
{ {
QJsonObject itemObject; QJsonObject itemObject;
items_[i]->store(itemObject); items_[i]->store(itemObject);
itemsArray.append(itemObject); itemsArray.append(itemObject);
} }
json["Items"] = itemsArray; json["Items"] = itemsArray;
} }
void ItemStore::itemUpdateSlot(ItemData data) void ItemStore::load(const QJsonObject& json)
{ {
for(std::shared_ptr<Item>& item: items_) const QJsonArray itemsArray(json["Items"].toArray(QJsonArray()));
{ for(int i = 0; i < itemsArray.size(); ++i)
if(*item == data) {
itemUpdated(std::weak_ptr<Item>(item)); if(itemsArray[i].isObject())
} {
const QJsonObject itemObject = itemsArray[i].toObject();
std::shared_ptr<Item> newItem;
if(itemObject["Type"].toString("") == "Relay")
{
newItem = std::shared_ptr<Relay>(new Relay());
}
else if(itemObject["Type"].toString("") == "Message")
{
newItem = std::shared_ptr<MessageItem>(new MessageItem);
}
else if(itemObject["Type"].toString("") == "System")
{
newItem = std::shared_ptr<SystemItem>(new SystemItem());
}
else if(itemObject["Type"].toString("") == "Aux")
{
}
if(newItem)
{
newItem->load(itemObject);
addItem(newItem);
}
}
}
} }
std::shared_ptr<Item> ItemStore::getItem(uint32_t id)
{
for(std::shared_ptr<Item>& item : items_)
{
if(item->id() == id)
return item;
}
return nullptr;
}
void ItemStore::registerItemSource(ItemSource* source)
{
qDebug()<<__func__<<typeid(*source).name();
connect(source, &ItemSource::gotItems, this, &ItemStore::addItems);
connect(source, &ItemSource::updateItems, this, &ItemStore::updateItems);
connect(source, &ItemSource::requestReplaceItems, this, &ItemStore::replaceItems);
connect(this, &ItemStore::sigRefresh, source, &ItemSource::refresh);
}
void ItemStore::refresh()
{
for(std::shared_ptr<Item>& item : items_)
itemDeleted(*item);
items_.clear();
sigRefresh();
}
ItemStore globalItems;

View file

@ -2,52 +2,37 @@
#include <vector> #include <vector>
#include <memory> #include <memory>
#include "item.h" #include "item.h"
#include "itemsource.h" #include "../sensors/sensor.h"
#include <QJsonObject> #include <QJsonObject>
class ItemStore: public QObject class ItemStore: public QObject
{ {
Q_OBJECT Q_OBJECT
private: private:
std::vector<std::shared_ptr<Item> > items_; std::vector< std::shared_ptr<Item> > items_;
public: public:
ItemStore(QObject *parent = nullptr); ItemStore(QObject *parent = nullptr);
virtual ~ItemStore() {} virtual ~ItemStore(){}
inline std::vector< std::shared_ptr<Item> >* getItems() inline std::vector< std::shared_ptr<Item> >* getItems(){ return &items_; }
{
return &items_;
}
std::shared_ptr<Item> getItem(uint32_t id); void store(QJsonObject &json);
void load(const QJsonObject &json);
void registerItemSource(ItemSource* source); void clear();
void store(QJsonObject &json);
void clear();
signals: signals:
void itemDeleted(ItemData item); void itemDeleted(ItemData item);
void itemAdded(std::weak_ptr<Item> Item); void itemAdded(std::weak_ptr<Item> Item);
void itemUpdated(std::weak_ptr<Item> Item);
void sigRefresh();
public slots: public slots:
void removeItem(const ItemData& item); void removeItem(const ItemData& item);
void addItem(std::shared_ptr<Item> item, bool inform = true); void addItem(std::shared_ptr<Item> item);
void addItems(const std::vector<std::shared_ptr<Item>>& itemsIn, bool inform = true); void addItems(const std::vector<std::shared_ptr<Item>>& itemsIn);
void replaceItems(const std::vector<std::shared_ptr<Item>>& items); void itemStateChanged(const ItemData& item);
void updateItems(std::vector<ItemData> items, bool inform = true);
void updateItem(const ItemData& item, bool inform = true);
void refresh();
private slots:
void itemUpdateSlot(ItemData data);
}; };
extern ItemStore globalItems;

View file

@ -1,90 +1,88 @@
#include "messageitem.h" #include "messageitem.h"
#include <QTimer> #include <QTimer>
#include <QSoundEffect> #include <QSound>
BroadCast* MessageItem::broadCast = nullptr;
MessageItem::MessageItem(uint32_t itemIdIn, QString name, uint8_t value, QObject *parent): MessageItem::MessageItem(uint32_t itemIdIn, QString name, uint8_t value, QObject *parent):
Item(itemIdIn, name, value, parent) Item(itemIdIn, name, value, parent)
{ {
alertSound.setVolume(1.0);
type_ = ITEM_VALUE_NO_VALUE;
} }
MessageItem::MessageItem(const ItemData& itemData, QObject *parent): MessageItem::MessageItem(const ItemData& itemData, QObject *parent):
Item(itemData, parent) Item(itemData, parent)
{ {
alertSound.setVolume(1.0);
} }
MessageItem::~MessageItem() MessageItem::~MessageItem()
{ {
closeMessageBox(); closeMessageBox();
} }
void MessageItem::enactValue(uint8_t value) void MessageItem::setValue(uint8_t value)
{ {
if(value && !messageBox_) Item::setValue(value);
{ if(value && !messageBox_)
if(!alertSoundFileName.isEmpty()) {
alertSound.play(); if(broadCast) broadCast->sendMessage(name_, message_);
messageBox_ = new QMessageBox(QMessageBox::NoIcon, name_, message_); if(!alertSoundFileName.isEmpty()) QSound::play(alertSoundFileName);
messageBox_->setModal(false); messageBox_ = new QMessageBox(QMessageBox::NoIcon, name_, message_);
connect(messageBox_, &QMessageBox::finished, this, &MessageItem::closeMessageBox); messageBox_->setModal(false);
messageBox_->show(); connect(messageBox_, &QMessageBox::finished, this, &MessageItem::closeMessageBox);
} messageBox_->show();
else if(!value && messageBox_) }
{ else if(!value && messageBox_)
closeMessageBox(); {
} closeMessageBox();
}
} }
void MessageItem::closeMessageBox() void MessageItem::closeMessageBox()
{ {
if(messageBox_) if(messageBox_)
{ {
value_ = 0; value_ = 0;
messageBox_->hide(); messageBox_->hide();
delete messageBox_; delete messageBox_;
messageBox_ = nullptr; messageBox_ = nullptr;
} }
} }
QString MessageItem::getAlert() QString MessageItem::getAlert()
{ {
return alertSoundFileName; return alertSoundFileName;
} }
void MessageItem::setAlert(const QString &in) void MessageItem::setAlert(const QString &in)
{ {
alertSoundFileName = in; alertSoundFileName = in;
alertSound.setSource(QUrl::fromLocalFile(alertSoundFileName));
} }
void MessageItem::setMessage(const QString& in) void MessageItem::setMessage(const QString& in)
{ {
message_ = in; message_ = in;
} }
QString MessageItem::getMessage() QString MessageItem::getMessage()
{ {
return message_; return message_;
} }
void MessageItem::store(QJsonObject &json) void MessageItem::store(QJsonObject &json)
{ {
json["Type"] = "Message"; json["Type"] = "Message";
Item::store(json); Item::store(json);
json["Message"] = message_; json["Message"] = message_;
if(!alertSoundFileName.isEmpty()) if(!alertSoundFileName.isEmpty()) json["Alert"] = alertSoundFileName;
json["Alert"] = alertSoundFileName;
} }
void MessageItem::load(const QJsonObject &json, const bool preserve) void MessageItem::load(const QJsonObject &json, const bool preserve)
{ {
Item::load(json,preserve); Item::load(json,preserve);
message_ = json["Message"].toString("Invalid Message"); message_ = json["Message"].toString("Invalid Message");
alertSoundFileName = json["Alert"].toString(""); alertSoundFileName = json["Alert"].toString("");
if(!alertSoundFileName.isEmpty())
alertSound.setSource(QUrl::fromLocalFile(alertSoundFileName));
} }

View file

@ -2,40 +2,43 @@
#define MESSAGEITEM_H #define MESSAGEITEM_H
#include <QMessageBox> #include <QMessageBox>
#include <QSoundEffect>
#include "item.h" #include "item.h"
#include "../broadcast.h"
class MessageItem : public Item class MessageItem : public Item
{ {
Q_OBJECT Q_OBJECT
private: private:
QString message_; QString message_;
QMessageBox* messageBox_ = nullptr; QMessageBox* messageBox_ = nullptr;
QString alertSoundFileName = ""; QString alertSoundFileName = "";
QSoundEffect alertSound;
public:
static BroadCast* broadCast;
private slots: private slots:
void closeMessageBox();
protected: void closeMessageBox();
virtual void enactValue(uint8_t value) override;
public: public:
MessageItem(uint32_t itemIdIn = QRandomGenerator::global()->generate(), QString name = "Item", uint8_t value = 0, virtual void setValue(uint8_t value);
QObject *parent = nullptr);
MessageItem(const ItemData& itemData, QObject *parent = nullptr);
~MessageItem();
void setMessage(const QString& in); public:
QString getMessage();
void setAlert(const QString& in);
QString getAlert();
virtual void store(QJsonObject& json) override; MessageItem(uint32_t itemIdIn = QRandomGenerator::global()->generate(), QString name = "Item", uint8_t value = 0, QObject *parent = nullptr);
virtual void load(const QJsonObject& json, const bool preserve = false) override; MessageItem(const ItemData& itemData, QObject *parent = nullptr);
~MessageItem();
void setMessage(const QString& in);
QString getMessage();
void setAlert(const QString& in);
QString getAlert();
virtual void store(QJsonObject& json);
virtual void load(const QJsonObject& json, const bool preserve = false);
}; };
#endif // MESSAGEITEM_H #endif // MESSAGEITEM_H

View file

@ -3,33 +3,31 @@
#include <QApplication> #include <QApplication>
#include <QDebug> #include <QDebug>
PowerItem::PowerItem(uint32_t itemIdIn, QString name, uint8_t value, QObject* parent): PowerItem::PowerItem(uint32_t itemIdIn, QString name, uint8_t value, QObject* parent): Item(itemIdIn, name, value, parent)
Item(itemIdIn, name, value, parent)
{ {
stateChanged(Sensor(Sensor::TYPE_SHUTDOWN_IMMINENT, 0, 0, "Shutdown Imminent", true)); stateChanged(Sensor(Sensor::TYPE_SHUTDOWN_IMMINENT, 0, 0, "Shutdown Imminent", true));
PowerItem::setValue(true); setValue(true);
hidden_ = true;
type_ = ITEM_VALUE_NO_VALUE;
} }
void PowerItem::enactValue(uint8_t value) void PowerItem::setValue(uint8_t value)
{ {
if(!value) qDebug()<<"shutdown";
{ Item::setValue(value);
qDebug()<<"shutdown"; if(!value)
QTimer::singleShot(5000, this, &PowerItem::timeout); {
stateChanged(Sensor(Sensor::TYPE_SHUTDOWN_IMMINENT, 0, 1, "Shutdown Imminent", true)); QTimer::singleShot(5000, this, &PowerItem::timeout);
} stateChanged(Sensor(Sensor::TYPE_SHUTDOWN_IMMINENT, 0, 1, "Shutdown Imminent", true));
}
} }
void PowerItem::timeout() void PowerItem::timeout()
{ {
qDebug()<<"shutdown timeout"; qDebug()<<"shutdown timeout";
QProcess::startDetached("syncoff", QStringList()); QProcess::startDetached("syncoff");
} }
void PowerItem::store(QJsonObject& json) void PowerItem::store(QJsonObject& json)
{ {
json["Type"] = "Power"; json["Type"] = "Power";
Item::store(json); Item::store(json);
} }

View file

@ -1,32 +1,30 @@
#pragma once #pragma once
#include "item.h" #include "item.h"
#include "sensors/sensor.h" #include "../sensors/sensor.h"
#include "microcontroller.h" #include "../microcontroller.h"
#include <QTimer> #include <QTimer>
class PowerItem: public Item class PowerItem: public Item
{ {
Q_OBJECT Q_OBJECT
private: private:
signals: signals:
void stateChanged(Sensor sensor); void stateChanged(Sensor sensor);
private slots: private slots:
void timeout();
protected: void timeout();
virtual void enactValue(uint8_t value) override;
public slots:
virtual void setValue(uint8_t value);
public: public:
PowerItem(uint32_t itemIdIn = QRandomGenerator::global()->generate(), QString name = "Power", uint8_t value = 0, PowerItem(uint32_t itemIdIn = QRandomGenerator::global()->generate(), QString name = "", uint8_t value = 0, QObject* parent = nullptr);
QObject* parent = nullptr); void emmitSensor(){stateChanged(Sensor(Sensor::TYPE_SHUTDOWN_IMMINENT, 0, 0, "Shutdown Imminent", true));}
void emmitSensor() virtual void store(QJsonObject& json);
{
stateChanged(Sensor(Sensor::TYPE_SHUTDOWN_IMMINENT, 0, 0, "Shutdown Imminent", true));
}
virtual void store(QJsonObject& json) override;
}; };

View file

@ -5,68 +5,66 @@
Microcontroller* Relay::micro_ = nullptr; Microcontroller* Relay::micro_ = nullptr;
Relay::Relay(uint8_t id, QString name, uint16_t address, bool state, QObject* parent): Item(0, name, state, parent), Relay::Relay(uint8_t id, QString name, uint16_t address, bool state, QObject* parent): Item(0, name, state, parent), id_(id), address_(address)
id_(id), address_(address)
{ {
itemId_ = address | ((uint32_t)id << 16); itemId_ = address | ((uint32_t)id << 16);
qDebug()<<"Relay "<<id_<<"Name "<<name<<" id "<<itemId_<<" state "<<state<<" addr: "<<address;
} }
void Relay::enactValue(uint8_t value) void Relay::setValue(uint8_t value)
{ {
qDebug()<<"Relay"<<__func__<<micro_; Item::setValue(value);
if(micro_) if(micro_)
{ {
if(value) if(value)micro_->relayOn(id_);
micro_->relayOn(id_); else micro_->relayOff(id_);
else }
micro_->relayOff(id_);
}
} }
void Relay::on() void Relay::on()
{ {
setValue(true); setValue(true);
} }
void Relay::off() void Relay::off()
{ {
setValue(false); setValue(false);
} }
void Relay::toggle() void Relay::toggle()
{ {
value_ ? off() : on(); value_ ? off() : on();
} }
void Relay::store(QJsonObject& json) void Relay::store(QJsonObject& json)
{ {
json["Type"] = "Relay"; json["Type"] = "Relay";
Item::store(json); Item::store(json);
json["Id"] = static_cast<double>(id_); json["Id"] = static_cast<double>(id_);
json["Address"] = address_; json["Address"] = address_;
} }
void Relay::load(const QJsonObject& json, const bool preserve) void Relay::load(const QJsonObject& json, const bool preserve)
{ {
Item::load(json, preserve); Item::load(json, preserve);
id_ = static_cast<uint8_t>(json["Id"].toInt(0)); id_ = static_cast<uint8_t>(json["Id"].toInt(0));
address_ = static_cast<uint16_t>(json["Address"].toInt(0)); address_ = static_cast<uint16_t>(json["Address"].toInt(0));
itemId_ = address_ | (static_cast<uint32_t>(id_) << 16); itemId_ = address_ | (static_cast<uint32_t>(id_) << 16);
} }
uint16_t Relay::getAddress() const uint16_t Relay::getAddress() const
{ {
return address_; return address_;
} }
uint8_t Relay::getId() const uint8_t Relay::getId() const
{ {
return id_; return id_;
} }
void Relay::setId(uint8_t id) void Relay::setId(uint8_t id)
{ {
id_=id; id_=id;
itemId_ = address_ | ((uint32_t)id << 16); itemId_ = address_ | ((uint32_t)id << 16);
} }

View file

@ -4,41 +4,37 @@
#include<stdint.h> #include<stdint.h>
#include<QObject> #include<QObject>
#include "sensors/sensor.h" #include "../sensors/sensor.h"
#include "item.h" #include "item.h"
class Microcontroller; class Microcontroller;
class Relay : public Item class Relay : public Item
{ {
Q_OBJECT Q_OBJECT
private: private:
static Microcontroller* micro_; static Microcontroller* micro_;
uint8_t id_; uint8_t id_;
uint16_t address_; uint16_t address_;
protected:
virtual void enactValue(uint8_t value) override;
public slots: public slots:
void on();
void off(); virtual void setValue(uint8_t value);
void toggle(); void on();
void off();
void toggle();
public: public:
Relay(uint8_t id = 0, QString name = "", uint16_t address = 0, bool state = false, QObject* parent = nullptr); Relay(uint8_t id = 0, QString name = "", uint16_t address = 0, bool state = false, QObject* parent = nullptr);
uint16_t getAddress() const; uint16_t getAddress() const;
uint8_t getId() const; uint8_t getId() const;
void setId(uint8_t id); void setId(uint8_t id);
inline static void setMicrocontroller(Microcontroller* micro) inline static void setMicrocontroller(Microcontroller* micro){ micro_ = micro; }
{
micro_ = micro;
}
virtual void store(QJsonObject& json) override; virtual void store(QJsonObject& json);
virtual void load(const QJsonObject& json, const bool preserve = false) override; virtual void load(const QJsonObject& json, const bool preserve = false);
}; };
#endif // RELAY_H #endif // RELAY_H

View file

@ -1,19 +1,18 @@
#include "rgbitem.h" #include "rgbitem.h"
RgbItem::RgbItem(Microcontroller* micro, uint32_t itemIdIn, QString name, uint8_t value, RgbItem::RgbItem(Microcontroller* micro, uint32_t itemIdIn, QString name, uint8_t value, QObject* parent): Item(itemIdIn, name, value, parent), micro_(micro)
QObject* parent): Item(itemIdIn, name, value, parent), micro_(micro)
{ {
} }
void RgbItem::enactValue(uint8_t value) void RgbItem::setValue(uint8_t value)
{ {
assert(micro_); Item::setValue(value);
value ? micro_->rgbOn() : micro_->rgbOff(); value ? micro_->rgbOn() : micro_->rgbOff();
} }
void RgbItem::store(QJsonObject &json) void RgbItem::store(QJsonObject &json)
{ {
json["Type"] = "Rgb"; json["Type"] = "Rgb";
Item::store(json); Item::store(json);
} }

View file

@ -1,20 +1,20 @@
#pragma once #pragma once
#include "microcontroller.h" #include "../microcontroller.h"
#include "item.h" #include "item.h"
class RgbItem: public Item class RgbItem: public Item
{ {
Q_OBJECT Q_OBJECT
private: private:
Microcontroller* micro_; Microcontroller* micro_;
protected: public slots:
virtual void enactValue(uint8_t value) override;
virtual void setValue(uint8_t value);
public: public:
RgbItem(Microcontroller* micro = nullptr, uint32_t itemIdIn = QRandomGenerator::global()->generate(), QString name = "", RgbItem(Microcontroller* micro, uint32_t itemIdIn = QRandomGenerator::global()->generate(), QString name = "", uint8_t value = 0, QObject* parent = nullptr);
uint8_t value = 0, QObject* parent = nullptr);
virtual void store(QJsonObject& json) override; virtual void store(QJsonObject& json);
}; };

View file

@ -1,43 +1,43 @@
#include "systemitem.h" #include "systemitem.h"
#include <QProcess> #include <QProcess>
void SystemItem::enactValue(uint8_t value) void SystemItem::setValue(uint8_t value)
{ {
QProcess::execute(value ? onCommand_ : offCommand_); QProcess::execute(value ? onCommand_ : offCommand_);
} }
SystemItem::SystemItem(uint32_t itemIdIn, QString name, uint8_t value, QObject *parent): SystemItem::SystemItem(uint32_t itemIdIn, QString name, uint8_t value, QObject *parent):
Item(itemIdIn, name, value, parent) Item(itemIdIn, name, value, parent)
{ {
} }
SystemItem::SystemItem(const ItemData& itemData, QObject *parent): SystemItem::SystemItem(const ItemData& itemData, QObject *parent):
Item(itemData, parent) Item(itemData, parent)
{ {
} }
void SystemItem::setOnCommand(const QString& in) void SystemItem::setOnCommand(const QString& in)
{ {
onCommand_ = in; onCommand_ = in;
} }
void SystemItem::setOffCommand(const QString& in) void SystemItem::setOffCommand(const QString& in)
{ {
offCommand_ = in; offCommand_ = in;
} }
void SystemItem::store(QJsonObject& json) void SystemItem::store(QJsonObject& json)
{ {
json["Type"] = "System"; json["Type"] = "System";
Item::store(json); Item::store(json);
json["OnCommand"] = onCommand_; json["OnCommand"] = onCommand_;
json["OffCommand"] = offCommand_; json["OffCommand"] = offCommand_;
} }
void SystemItem::load(const QJsonObject& json, const bool preserve) void SystemItem::load(const QJsonObject& json, const bool preserve)
{ {
Item::load(json,preserve); Item::load(json,preserve);
onCommand_ = json["OnCommand"].toString(""); onCommand_ = json["OnCommand"].toString("");
offCommand_ = json["OffCommand"].toString(""); offCommand_ = json["OffCommand"].toString("");
} }

View file

@ -1,37 +1,34 @@
#ifndef SYSTEMITEM_H #ifndef SYSTEMITEM_H
#define SYSTEMITEM_H #define SYSTEMITEM_H
#include "item.h" #include "item.h"
class SystemItem : public Item class SystemItem : public Item
{ {
Q_OBJECT Q_OBJECT
private: private:
QString onCommand_;
QString offCommand_;
protected: QString onCommand_;
virtual void enactValue(uint8_t value) override; QString offCommand_;
public: public:
SystemItem(uint32_t itemIdIn = QRandomGenerator::global()->generate(), QString name = "Item", uint8_t value = 0,
QObject *parent = nullptr);
SystemItem(const ItemData& itemData, QObject *parent = nullptr);
~SystemItem() = default;
void setOnCommand(const QString& in); virtual void setValue(uint8_t value);
void setOffCommand(const QString& in);
QString getOnCommand()
{
return onCommand_;
}
QString getOffCommand()
{
return offCommand_;
}
virtual void store(QJsonObject& json) override; public:
virtual void load(const QJsonObject& json, const bool preserve = false) override;
SystemItem(uint32_t itemIdIn = QRandomGenerator::global()->generate(), QString name = "Item", uint8_t value = 0, QObject *parent = nullptr);
SystemItem(const ItemData& itemData, QObject *parent = nullptr);
~SystemItem() = default;
void setOnCommand(const QString& in);
void setOffCommand(const QString& in);
QString getOnCommand(){return onCommand_;}
QString getOffCommand(){return offCommand_;}
virtual void store(QJsonObject& json);
virtual void load(const QJsonObject& json, const bool preserve = false);
}; };
#endif // SYSTEMITEM_H #endif // SYSTEMITEM_H

View file

@ -1,139 +1,133 @@
#include <QtWidgets/QApplication> #include <QtWidgets/QApplication>
#include <stdio.h>
#include <QDebug> #include <QDebug>
#include <QTcpSocket> #include <QTcpSocket>
#include <QMessageBox> #include <QMessageBox>
#include <QSettings>
#ifndef Q_OS_ANDROID
#include <QtSerialPort/QtSerialPort> #include <QtSerialPort/QtSerialPort>
#include <QtSerialPort/QSerialPortInfo> #include <QtSerialPort/QSerialPortInfo>
#include <QCommandLineParser> #include <QCommandLineParser>
#endif
#include "actors/alarmtime.h"
#include "microcontroller.h"
#include "ui/mainwindow.h" #include "ui/mainwindow.h"
#include "sensors/speakersensor.h"
#include "sensors/sunsensor.h"
#include "sensors/ocupancysensor.h"
#include "alarmactions.h"
#include "sensors/sensor.h"
#include "items/itemstore.h" #include "items/itemstore.h"
#include "items/auxitem.h"
#include "items/rgbitem.h"
#include "items/poweritem.h"
#include "mainobject.h" #include "mainobject.h"
#include "programmode.h"
#define BAUD QSerialPort::Baud38400
int main(int argc, char *argv[]) int main(int argc, char *argv[])
{ {
QApplication a(argc, argv); QApplication a(argc, argv);
//pw_init(&argc, &argv); //set info
QCoreApplication::setOrganizationName("UVOS");
QCoreApplication::setOrganizationDomain("uvos.xyz");
QCoreApplication::setApplicationName("SHinterface");
QCoreApplication::setApplicationVersion("0.6");
//set info QDir::setCurrent(a.applicationDirPath());
QCoreApplication::setOrganizationName("UVOS");
QCoreApplication::setOrganizationDomain("uvos.xyz");
QCoreApplication::setApplicationName("SHinterface");
QCoreApplication::setApplicationVersion("0.6");
QDir::setCurrent(a.applicationDirPath()); //parse comand line
#ifndef Q_OS_ANDROID
QCommandLineParser parser;
parser.setApplicationDescription("Smart Home Interface");
parser.addHelpOption();
parser.addVersionOption();
QCommandLineOption tcpOption(QStringList() << "t" << "tcp", QCoreApplication::translate("main", "Use Tcp connection"));
parser.addOption(tcpOption);
QCommandLineOption hostOption(QStringList() << "H" << "host", QCoreApplication::translate("main", "Set server host ip addres"), "adress");
parser.addOption(hostOption);
QCommandLineOption portOption(QStringList() << "p" << "port", QCoreApplication::translate("main", "Set server Port in TCP mode or Serial port in serial mode"), "port");
parser.addOption(portOption);
QCommandLineOption serialOption(QStringList() << "s" << "serial", QCoreApplication::translate("main", "Use serial connection"));
parser.addOption(serialOption);
QCommandLineOption baudOption(QStringList() << "b" << "baud", QCoreApplication::translate("main", "Set Baud Rate"));
parser.addOption(baudOption);
QCommandLineOption settingsPathOption(QStringList() << "c" << "config", QCoreApplication::translate("main", "Set config file"), "configFilePath");
parser.addOption(settingsPathOption);
QCommandLineOption secondaryOption(QStringList() << "e" << "secondary", QCoreApplication::translate("main", "Set if instance is not main instance"));
parser.addOption(secondaryOption);
parser.process(a);
#endif
//parse comand line QIODevice* masterIODevice = nullptr;
QCommandLineParser parser;
parser.setApplicationDescription("Smart Home Interface");
parser.addHelpOption();
parser.addVersionOption();
QCommandLineOption masterOption(QStringList() << "m" << "master", QCoreApplication::translate("main", "Use in master mode"));
parser.addOption(masterOption);
QCommandLineOption hostOption(QStringList() << "H" << "host", QCoreApplication::translate("main", "Set server host ip addres"), "address", "0.0.0.0");
parser.addOption(hostOption);
QCommandLineOption portOption(QStringList() << "p" << "port", QCoreApplication::translate("main", "Set server Port"), "port", "104476");
parser.addOption(portOption);
QCommandLineOption settingsPathOption(QStringList()<<"c"<<"config", QCoreApplication::translate("main", "Set config file"), "configFilePath",
QStandardPaths::writableLocation(QStandardPaths::ConfigLocation) + "/shinterface.json");
parser.addOption(settingsPathOption);
QCommandLineOption headlessOption(QStringList()<<"e"<<"headless", QCoreApplication::translate("main", "Dont start the gui"));
parser.addOption(headlessOption);
parser.process(a);
int retVal; #ifndef Q_OS_ANDROID
if(parser.isSet(tcpOption))
{
QTcpSocket* microSocket = new QTcpSocket;
programMode = PROGRAM_MODE_UI_ONLY; int port = 6856;
if(parser.isSet(masterOption)) if(parser.isSet(portOption)) port = parser.value(portOption).toInt();
{
programMode = PROGRAM_MODE_PRIMARY;
if(parser.isSet(headlessOption))
programMode = PROGRAM_MODE_HEADLESS_PRIMARY;
}
if(programMode == PROGRAM_MODE_PRIMARY || programMode == PROGRAM_MODE_HEADLESS_PRIMARY)
{
QString settingsPath = parser.value(settingsPathOption);
QJsonObject json = MainObject::getJsonObjectFromDisk(settingsPath);
bool tcpMicro = json["MicroTcp"].toBool(true);
json["MicroTcp"] = tcpMicro;
QIODevice* microDevice = nullptr; QString host("127.0.0.1");
if(tcpMicro) if(parser.isSet(hostOption)) host = parser.value(hostOption);
{ std::cout<<"connecting to "<<host.toStdString()<<':'<<port<<'\n';
int port = json["MicroTcpPort"].toInt(6856); microSocket->connectToHost(host, port, QIODevice::ReadWrite);
json["MicroTcpPort"] = port; if(!microSocket->waitForConnected(1000))
QString host = json["MicroTcpHost"].toString("127.0.0.1"); {
json["MicroTcpHost"] = host; std::cout<<"Can not connect to to Server.\n";
QMessageBox::critical(nullptr, "Error", "Can not connect to to Server");
return 1;
}
masterIODevice = microSocket;
}
else
{
QSerialPort* microPort = new QSerialPort;
if(parser.isSet(portOption)) microPort->setPortName(parser.value(portOption));
else microPort->setPortName("ttyUSB0");
QTcpSocket* microSocket = new QTcpSocket; if(parser.isSet(portOption)) microPort->setBaudRate(parser.value(baudOption).toInt());
else microPort->setBaudRate(BAUD);
qInfo()<<"connecting to "<<host<<':'<<port<<" for tcp micro"; if(!microPort->open(QIODevice::ReadWrite)) std::cout<<"Can not open serial port "<<microPort->portName().toStdString()<<". Continueing in demo mode"<<'\n';
microSocket->connectToHost(host, port, QIODevice::ReadWrite); masterIODevice = microPort;
}
if(!microSocket->waitForConnected(1000)) MainObject mainObject(masterIODevice, parser.isSet(settingsPathOption) ? parser.value(settingsPathOption) : "", !parser.isSet(secondaryOption));
{
qCritical()<<"Can not connect to tcp micro";
MainObject::storeJsonObjectToDisk(settingsPath, json);
if(programMode == PROGRAM_MODE_PRIMARY)
QMessageBox::critical(nullptr, "Error", "Can not connect to tcp micro");
return 1;
}
microDevice = microSocket;
}
else
{
QString port = json["MicroSerialPort"].toString("ttyUSB0");
json["MicroSerialPort"] = port;
int baud = json["MicroSerialBaud"].toInt(38400);
json["MicroSerialBaud"] = baud;
QSerialPort *microPort = new QSerialPort; #else
microPort->setPortName(port); QTcpSocket* microSocket = new QTcpSocket;
microPort->setBaudRate(baud); microSocket->connectToHost("10.0.0.1", 6856, QIODevice::ReadWrite);
microPort->open(QIODevice::ReadWrite); if(!microSocket->waitForConnected(1000))
{
std::cout<<"Can not connect to to Server.\n";
return 1;
}
masterIODevice = microSocket;
if(!microPort->isOpen()) MainObject mainObject(masterIODevice, parser.isSet(settingsPathOption) ? parser.value(settingsPathOption) : "", !parser.isSet(secondaryOption));
{ #endif
qCritical()<<"Can not open serial port"<<port;
MainObject::storeJsonObjectToDisk(settingsPath, json);
if(programMode == PROGRAM_MODE_PRIMARY)
QMessageBox::critical(nullptr, "Error", "Can not open serial port " + port);
return 1;
}
microDevice = microPort;
}
PrimaryMainObject mainObject(microDevice, settingsPath, parser.value(hostOption), parser.value(portOption).toInt());
QObject::connect(mainObject.tcpServer, &TcpServer::sigRequestSave, &mainObject, [&mainObject, settingsPath](){mainObject.storeToDisk(settingsPath);});
MainWindow* w = nullptr;
if(programMode != PROGRAM_MODE_HEADLESS_PRIMARY)
{
w = new MainWindow(&mainObject);
QObject::connect(&mainObject.micro, SIGNAL(textRecived(QString)), w, SLOT(changeHeaderLableText(QString)));
QObject::connect(&mainObject.micro, SIGNAL(textRecived(QString)), w, SLOT(changeHeaderLableText(QString)));
QObject::connect(w, &MainWindow::sigSetRgb, &mainObject.micro, &Microcontroller::changeRgbColor);
QObject::connect(w, &MainWindow::sigSave, &mainObject, [&mainObject, settingsPath](){mainObject.storeToDisk(settingsPath);});
QObject::connect(w, &MainWindow::createdItem, &globalItems, [](std::shared_ptr<Item> item){globalItems.addItem(item, false);});
w->show();
}
retVal = a.exec();
delete w;
delete microDevice;
}
else
{
SecondaryMainObject mainObject(parser.value(hostOption), parser.value(portOption).toInt());
MainWindow w(&mainObject);
QObject::connect(&w, &MainWindow::createdItem, &globalItems, [](std::shared_ptr<Item> item){globalItems.addItem(item, false);});
QObject::connect(&w, &MainWindow::sigSave, mainObject.tcpClient, &TcpClient::sendItems);
w.show();
retVal = a.exec(); //mainwindow
} MainWindow w(&mainObject);
QObject::connect(&mainObject.micro, SIGNAL(textRecived(QString)), &w, SLOT(changeHeaderLableText(QString)));
QObject::connect(&w, &MainWindow::sigBrodcast, &mainObject, &MainObject::sendJson);
QObject::connect(&w, &MainWindow::sigSave, &mainObject, &MainObject::storeToDisk);
QObject::connect(&w, &MainWindow::createdItem, &mainObject.items, &ItemStore::addItem);
if(!mainObject.micro.connected()) w.changeHeaderLableText("No io debug only!");
return retVal; w.show();
int retVal = a.exec();
if(masterIODevice)
delete masterIODevice;
return retVal;
} }

View file

@ -1,162 +1,175 @@
#include "mainobject.h" #include "mainobject.h"
#include "items/messageitem.h"
#include<QJsonObject> MainObject::MainObject(QIODevice* ioDevice, const QString& settingsPathIn, const bool masterIn, QObject *parent) :
#include<QJsonArray> QObject(parent),
#include<QMessageBox> master(masterIn),
masterIODevice(ioDevice),
ioMultiplexer(masterIODevice),
micro(ioMultiplexer.getIoDevice()),
broadCast(ioMultiplexer.getIoDevice(), masterIn),
settingsPath(settingsPathIn),
sunSensorSource(49.884450, 8.650536),
powerItem(new PowerItem),
rgbItem(new RgbItem(&micro, 5487422, "Rgb Lights")),
auxItem(new AuxItem(&micro, 5487421, "Desk Light"))
#include "items/itemstore.h"
MainObject::MainObject(QObject *parent) :
QObject(parent)
{ {
qDebug()<<"Is master:"<<master;
//connect sensors subsystem
QObject::connect(&micro, &Microcontroller::gotSensorState, &globalSensors, &SensorStore::sensorGotState);
QObject::connect(&sunSensorSource, &SunSensorSource::stateChanged, &globalSensors, &SensorStore::sensorGotState);
QObject::connect(&globalSensors, &SensorStore::sensorChangedState, &ocupancySensor, &OcupancySensorSource::sensorEvent);
QObject::connect(&ocupancySensor, &OcupancySensorSource::stateChanged, &globalSensors, &SensorStore::sensorGotState);
sunSensorSource.run();
//connect item store
QObject::connect(&micro, &Microcontroller::gotRelayList, &items, &ItemStore::addItems);
QObject::connect(&micro, &Microcontroller::itemChanged, &items, &ItemStore::itemStateChanged);
//special items
QObject::connect(powerItem.get(), &PowerItem::stateChanged, &globalSensors, &SensorStore::sensorGotState);
powerItem->emmitSensor();
items.addItem(rgbItem);
items.addItem(auxItem);
MessageItem::broadCast = &broadCast;
Relay::setMicrocontroller(&micro);
connect(&broadCast, &BroadCast::gotJson, this, &MainObject::recivedJson);
QObject::connect(&broadCast, &BroadCast::gotSensorState, &globalSensors, &SensorStore::sensorGotState);
if(master)connect(&broadCast, &BroadCast::jsonRequested, this, &MainObject::sendJson);
if(master) load(getJsonObjectFromDisk(settingsPath, &noSave));
else
{
broadCast.requestJson();
broadCast.requestSensors();
}
#ifndef Q_OS_ANDROID
Item::secondaryFlag = !master;
#endif
} }
MainObject::~MainObject() MainObject::~MainObject()
{ {
} }
void MainObject::refresh() void MainObject::store(QJsonObject &json)
{ {
globalItems.refresh(); items.store(json);
QJsonObject powerObject;
powerItem->store(powerObject);
json.insert("Power", powerObject);
QJsonDocument pwrDoc(powerObject);
QJsonObject ocupancyObject;
ocupancySensor.store(ocupancyObject);
json.insert("Ocupancy", ocupancyObject);
} }
QJsonObject MainObject::getJsonObjectFromDisk(const QString& filename, bool* error) void MainObject::load(const QJsonObject& json)
{ {
QFile file; items.clear();
file.setFileName(filename); rgbItem->removeAllActors();
auxItem->removeAllActors();
bool ret = file.open(QIODevice::ReadOnly); powerItem->removeAllActors();
if(!file.isOpen() || !ret) items.addItem(rgbItem);
{ items.addItem(auxItem);
std::cerr<<"Can not open config file: "<<filename.toLatin1().data()<<std::endl; items.load(json);
} powerItem->load(json["Power"].toObject());
else ocupancySensor.load(json["Ocupancy"].toObject());
{ qDebug()<<"aray size: "<<json.isEmpty();
QJsonParseError qerror; if(json["Items"].toArray().size() >= 2)
QJsonDocument document(QJsonDocument::fromJson(file.readAll(), &qerror)); {
file.close(); rgbItem->load(json["Items"].toArray()[0].toObject());
if(qerror.error != QJsonParseError::NoError) auxItem->load(json["Items"].toArray()[1].toObject());
{ }
qDebug()<<filename<<" "<<qerror.errorString(); micro.requestState();
if(error)
(*error) = true;
}
return document.object();
}
return QJsonObject();
} }
bool MainObject::storeJsonObjectToDisk(const QString& filename, const QJsonObject& json) void MainObject::storeToDisk()
{ {
QFile file(filename + ".out"); if(master && !noSave)
qDebug()<<"config file: "<<filename;
bool ret = file.open(QIODevice::WriteOnly);
if(!file.isOpen() || !ret)
{ {
std::cerr<<"Can not open config file: "<<filename.toLatin1().data()<<std::endl; QJsonObject json;
return false; store(json);
} storeJsonObjectToDisk(json, settingsPath);
else
{
QJsonDocument document(json);
file.write(document.toJson());
file.close();
QFile::remove(filename);
file.rename(filename);
return true;
} }
} }
PrimaryMainObject::PrimaryMainObject(QIODevice* microDevice, const QString& settingsPath, const QString& host, int port, QObject *parent) : void MainObject::recivedJson(const QJsonObject json)
MainObject(parent),
settingsPath(settingsPath),
micro(microDevice),
tcpServer(new TcpServer),
sunSensorSource(49.824972, 8.702194),
fixedItems(&micro)
{ {
//connect sensors subsystem if(master && !noSave)
connect(&globalSensors, &SensorStore::sensorChangedState, tcpServer, &TcpServer::sensorEvent); storeJsonObjectToDisk(json, settingsPath);
connect(tcpServer, &TcpServer::gotSensor, &globalSensors, &SensorStore::sensorGotState); load(json);
connect(&sunSensorSource, &SunSensorSource::stateChanged, &globalSensors, &SensorStore::sensorGotState);
connect(&micro, &Microcontroller::gotSensorState, &globalSensors, &SensorStore::sensorGotState);
connect(&mqttSensorSource, &MqttSensorSource::stateChanged, &globalSensors, &SensorStore::sensorGotState);
sunSensorSource.run();
globalItems.registerItemSource(&fixedItems);
globalItems.registerItemSource(tcpServer);
globalItems.registerItemSource(&micro);
globalItems.registerItemSource(&itemLoader);
Relay::setMicrocontroller(&micro);
loadFromDisk(settingsPath);
QJsonObject mqttJson = settings["Mqtt"].toObject();
mqttSensorSource.start(mqttJson);
tcpServer->launch(QHostAddress(host), port);
connect(&globalItems, &ItemStore::itemUpdated, tcpServer, &TcpServer::itemUpdated);
} }
PrimaryMainObject::~PrimaryMainObject() void MainObject::sendJson()
{ {
storeToDisk(settingsPath); QJsonObject json;
store(json);
broadCast.sendJson(json);
} }
void PrimaryMainObject::store(QJsonObject &json) QJsonObject MainObject::getJsonObjectFromDisk(const QString& filePath, bool* error)
{ {
globalItems.store(json); QFile file;
QJsonObject mqttJson = json["Mqtt"].toObject();
mqttSensorSource.store(mqttJson); #ifndef Q_OS_ANDROID
json["Mqtt"] = mqttJson; if(filePath.size() > 0) file.setFileName(filePath);
else
#endif
{
file.setFileName(QStandardPaths::writableLocation(QStandardPaths::ConfigLocation) + "/shinterface.json");
}
file.open(QIODevice::ReadOnly);
if(!file.isOpen()) std::cerr<<"Can not open config file: "<<filePath.toLatin1().data()<<std::endl;
else
{
QJsonParseError qerror;
QJsonDocument document(QJsonDocument::fromJson(file.readAll(), &qerror));
file.close();
if(qerror.error != QJsonParseError::NoError)
{
qDebug()<<filePath<<" "<<qerror.errorString();
if(error) (*error) = true;
}
return document.object();
}
return QJsonObject();
} }
void PrimaryMainObject::load(const QJsonObject& json) bool MainObject::storeJsonObjectToDisk(const QJsonObject& json, QString filePath)
{
settings = json;
itemLoader.updateJson(json);
globalItems.clear();
globalItems.refresh();
}
bool PrimaryMainObject::storeToDisk(const QString& filename)
{
store(settings);
itemLoader.updateJson(settings);
return storeJsonObjectToDisk(filename, settings);
}
bool PrimaryMainObject::loadFromDisk(const QString& filename)
{
bool error = false;
QJsonObject json = getJsonObjectFromDisk(filename, &error);
if(!error)
load(json);
return error;
}
SecondaryMainObject::SecondaryMainObject(QString host, int port, QObject *parent) :
MainObject(parent),
tcpClient(new TcpClient)
{
connect(tcpClient, &TcpClient::gotSensor, &globalSensors, &SensorStore::sensorGotState);
globalItems.registerItemSource(tcpClient);
if(!tcpClient->launch(QHostAddress(host), port))
{
QMessageBox::critical(nullptr, "Error", "Could not connect to "+host+":"+QString::number(port));
QMetaObject::invokeMethod(this, [](){exit(1);}, Qt::QueuedConnection);
}
connect(&globalItems, &ItemStore::itemUpdated, tcpClient, &TcpClient::itemUpdated);
globalItems.refresh();
}
SecondaryMainObject::~SecondaryMainObject()
{ {
#ifndef Q_OS_ANDROID
if(filePath.size() == 0)
#endif
{
filePath = QStandardPaths::writableLocation(QStandardPaths::ConfigLocation) + "/shinterface.json";
}
QFile file(filePath + ".out");
qDebug()<<"config file: "<<filePath;
file.open(QIODevice::WriteOnly);
if(!file.isOpen())
{
std::cerr<<"Can not open config file: "<<filePath.toLatin1().data()<<std::endl;
return false;
}
else
{
QJsonDocument document(json);
file.write(document.toJson());
file.close();
QFile::remove(filePath);
file.rename(filePath);
return true;
}
} }

View file

@ -2,6 +2,7 @@
#define MAINOBJECT_H #define MAINOBJECT_H
#include <QObject> #include <QObject>
#include <stdio.h>
#include <QDir> #include <QDir>
#include <QDebug> #include <QDebug>
#include <QString> #include <QString>
@ -11,66 +12,76 @@
#include <QStandardPaths> #include <QStandardPaths>
#include <memory> #include <memory>
#ifndef Q_OS_ANDROID
#include <QtSerialPort/QtSerialPort>
#include <QtSerialPort/QSerialPortInfo>
#include <QCommandLineParser>
#endif
#include "actors/alarmtime.h"
#include "microcontroller.h" #include "microcontroller.h"
#include "ui/mainwindow.h" #include "ui/mainwindow.h"
#include "sensors/speakersensor.h"
#include "sensors/sunsensor.h" #include "sensors/sunsensor.h"
#include "sensors/mqttsensorsource.h" #include "sensors/ocupancysensor.h"
#include "items/fixeditemsource.h" #include "sensors/sensor.h"
#include "items/itemloadersource.h" #include "items/itemstore.h"
#include "service/tcpclient.h" #include "items/auxitem.h"
#include "service/tcpserver.h" #include "items/rgbitem.h"
#include "items/poweritem.h"
#include "iomuliplexer.h"
#include "broadcast.h"
class MainObject : public QObject class MainObject : public QObject
{ {
Q_OBJECT Q_OBJECT
public:
//io
const bool master;
bool noSave = false;
QIODevice * const masterIODevice = nullptr;
IoMuliplexer ioMultiplexer;
Microcontroller micro;
BroadCast broadCast;
const QString settingsPath;
//sensors
SunSensorSource sunSensorSource;
OcupancySensorSource ocupancySensor;
//items
ItemStore items;
std::shared_ptr<PowerItem> powerItem;
std::shared_ptr<RgbItem> rgbItem;
std::shared_ptr<AuxItem> auxItem;
private:
static QJsonObject getJsonObjectFromDisk(const QString& filePath = "", bool* error = nullptr);
static bool storeJsonObjectToDisk(const QJsonObject& json, QString filePath = "");
public: public:
explicit MainObject(QObject *parent = nullptr); explicit MainObject(QIODevice* ioDevice, const QString& settingsPathIn, const bool masterIn, QObject *parent = nullptr);
~MainObject(); ~MainObject();
static QJsonObject getJsonObjectFromDisk(const QString& filename, bool* error = nullptr);
static bool storeJsonObjectToDisk(const QString& filename, const QJsonObject& json); void store(QJsonObject& json);
void load(const QJsonObject& json);
signals:
public slots: public slots:
void refresh();
};
class PrimaryMainObject : public MainObject void storeToDisk();
{ void sendJson();
Q_OBJECT void recivedJson(const QJsonObject json);
public:
QString settingsPath;
QJsonObject settings;
Microcontroller micro;
TcpServer* tcpServer;
//sensors
SunSensorSource sunSensorSource;
MqttSensorSource mqttSensorSource;
//item sources
FixedItemSource fixedItems;
ItemLoaderSource itemLoader;
public:
explicit PrimaryMainObject(QIODevice* microDevice, const QString& settingsPath, const QString& host, int port, QObject *parent = nullptr);
~PrimaryMainObject();
void store(QJsonObject& json);
void load(const QJsonObject& json);
bool storeToDisk(const QString& filename);
bool loadFromDisk(const QString& filename);
};
class SecondaryMainObject : public MainObject
{
Q_OBJECT
public:
TcpClient* tcpClient;
public:
explicit SecondaryMainObject(QString host, int port, QObject *parent = nullptr);
~SecondaryMainObject();
}; };

View file

@ -3,99 +3,108 @@
#include <chrono> #include <chrono>
#include <thread> #include <thread>
static constexpr bool debug = true;
void Microcontroller::relayToggle(int state, int relay) void Microcontroller::relayToggle(int state, int relay)
{ {
char buffer[8]; char buffer[8];
int length = sprintf(buffer, "%d \n", relay); int length = sprintf(buffer, "%d \n", relay);
state ? write("item on ") : write("item off "); state ? write("item on ") : write("item off ");
write(buffer, length); write(buffer, length);
} }
void Microcontroller::relayOn(int relay) void Microcontroller::relayOn(int relay)
{ {
relayToggle(true, relay); relayToggle(true, relay);
} }
void Microcontroller::relayOff(int relay) void Microcontroller::relayOff(int relay)
{ {
relayToggle(false, relay); relayToggle(false, relay);
} }
//rgb lights //rgb lights
void Microcontroller::rgbOn() void Microcontroller::rgbOn()
{ {
write("rgb on\n"); write("rgb on\n");
} }
void Microcontroller::rgbOff() void Microcontroller::rgbOff()
{ {
write( "rgb off\n"); write( "rgb off\n");
} }
void Microcontroller::changeRgbColor(const QColor color) void Microcontroller::changeRgbColor(const QColor color)
{ {
char buffer[64]; char buffer[64];
int length = sprintf(buffer, "rgb set %03d %03d %03d\n", color.red(), color.green(), color.blue()); int length = sprintf(buffer, "rgb set %03d %03d %03d\n", color.red(), color.green(), color.blue());
write(buffer, length); write(buffer, length);
} std::cout<<buffer;
}
void Microcontroller::setAuxPwm(int duty) void Microcontroller::setAuxPwm(int duty)
{ {
char buffer[64]; char buffer[64];
int length = sprintf(buffer, "aux set %03d\n", duty ); int length = sprintf(buffer, "aux set %03d\n", duty );
write(buffer, length); write(buffer, length);
} }
void Microcontroller::write(const QByteArray& buffer) void Microcontroller::write(const QByteArray& buffer)
{ {
if(_port != nullptr) #ifndef Q_OS_ANDROID
{ if constexpr(debug) std::cerr<<buffer.data();
_port->write(buffer); #endif
_port->waitForBytesWritten(1000); if(_port != nullptr)
} {
std::this_thread::sleep_for(std::chrono::milliseconds(40)); _port->write(buffer);
_port->waitForBytesWritten(1000);
}
std::this_thread::sleep_for(std::chrono::milliseconds(40));
} }
void Microcontroller::write(char* buffer, const size_t length) void Microcontroller::write(char* buffer, const size_t length)
{ {
if(_port != nullptr) #ifndef Q_OS_ANDROID
{ if constexpr(debug) std::cerr<<buffer;
_port->write(buffer, length); #endif
_port->waitForBytesWritten(1000); if(_port != nullptr)
} {
std::this_thread::sleep_for(std::chrono::milliseconds(40)); _port->write(buffer, length);
_port->waitForBytesWritten(1000);
}
std::this_thread::sleep_for(std::chrono::milliseconds(40));
} }
void Microcontroller::setPattern(int pattern) void Microcontroller::setPattern(int pattern)
{ {
char buffer[4]; char buffer[4];
write("rgb pattern "); write("rgb pattern ");
int length = sprintf(buffer, "%d\n", pattern); int length = sprintf(buffer, "%d\n", pattern);
write(buffer, length); write(buffer, length);
} }
void Microcontroller::startSunrise() void Microcontroller::startSunrise()
{ {
setPattern(4); setPattern(4);
} }
bool Microcontroller::connected() bool Microcontroller::connected()
{ {
if(_port != nullptr) return _port->isOpen(); if(_port != nullptr) return _port->isOpen();
else return false; else return false;
} }
void Microcontroller::refresh() void Microcontroller::requestState()
{ {
write("state\n"); write("state\n");
} }
//housekeeping //housekeeping
Microcontroller::Microcontroller(QIODevice* port) Microcontroller::Microcontroller(QIODevice* port)
{ {
setIODevice(port); setIODevice(port);
} }
Microcontroller::Microcontroller() Microcontroller::Microcontroller()
@ -108,96 +117,81 @@ Microcontroller::~Microcontroller()
void Microcontroller::setIODevice(QIODevice *port) void Microcontroller::setIODevice(QIODevice *port)
{ {
_port = port; _port = port;
QObject::connect(_port, &QIODevice::readyRead, this, &Microcontroller::isReadyRead); QObject::connect(_port, &QIODevice::readyRead, this, &Microcontroller::isReadyRead);
} }
std::shared_ptr<Relay> Microcontroller::processRelayLine(const QString& buffer) std::shared_ptr<Relay> Microcontroller::processRelayLine(const QString& buffer)
{ {
QStringList bufferList = buffer.split(' '); QStringList bufferList = buffer.split(' ');
if(bufferList.size() >= 9 && buffer.startsWith("ITEM NUMBER:")) if(bufferList.size() >= 9 && buffer.startsWith("ITEM NUMBER:"))
{ {
QString name; QString name;
for(int i = 10; i < bufferList.size(); i++) for(int i = 10; i < bufferList.size(); i++) name.append(bufferList[i] + ' ');
name.append(bufferList[i] + ' '); if(name.size() > 1)name.remove(name.size()-1, 1);
if(name.size() > 1) else name = "Relay " + QString::number(bufferList[1].toInt(nullptr, 2));
name.remove(name.size()-1, 1); return std::shared_ptr<Relay>( new Relay(bufferList[2].toInt(), name, bufferList[4].toInt(nullptr, 2), bufferList[8].toInt()));
else }
name = "Relay " + QString::number(bufferList[1].toInt(nullptr, 2)); return nullptr;
return std::shared_ptr<Relay>(new Relay(bufferList[2].toInt(),
name,
bufferList[6].toInt(nullptr, 2),
bufferList[8].toInt()));
}
return nullptr;
} }
void Microcontroller::processList(const QString& buffer) void Microcontroller::processList(const QString& buffer)
{ {
QStringList bufferList = buffer.split(' '); QStringList bufferList = buffer.split(' ');
if(bufferList.size() >= 8 && buffer.startsWith("ITEM NUMBER:")) if(bufferList.size() >= 8 && buffer.startsWith("ITEM NUMBER:"))
{ {
relayList.push_back(processRelayLine(buffer)); relayList.push_back(processRelayLine(buffer));
} }
else if(buffer.contains("EOL")) else if(buffer.contains("EOL"))
{ {
listMode = false; listMode = false;
gotItems(relayList); qDebug()<<"got relay list " << relayList.size();
relayList.clear(); gotRelayList(relayList);
} relayList.clear();
else listMode = false; }
else listMode = false;
} }
void Microcontroller::processRelayState(const QString& buffer) void Microcontroller::processRelayState(const QString& buffer)
{ {
updateItems({static_cast<ItemData>(*processRelayLine(buffer))}); itemChanged(static_cast<ItemData>(*processRelayLine(buffer)));
} }
void Microcontroller::processSensorState(const QString& buffer) void Microcontroller::processSensorState(const QString& buffer)
{ {
Sensor sensor = Sensor::sensorFromString(buffer); Sensor sensor = Sensor::sensorFromString(buffer);
if(sensor.type != Sensor::TYPE_DUMMY) if(sensor.type != Sensor::TYPE_DUMMY) gotSensorState(sensor);
gotSensorState(sensor);
} }
void Microcontroller::processMicroReturn() void Microcontroller::processMicroReturn()
{ {
if(listMode) if(listMode) processList(_buffer);
{ else
processList(_buffer); {
}
else
{
if(_buffer.startsWith("Items:")) if(_buffer.startsWith("Items:"))
{ {
listMode = true; listMode = true;
relayList.clear(); relayList.clear();
} }
else if(_buffer.startsWith("ITEM NUMBER:")) else if(_buffer.startsWith("ITEM NUMBER:"))processRelayState(_buffer);
{ else if(_buffer.startsWith("SENSOR")) processSensorState(_buffer);
processRelayState(_buffer); }
}
else if(_buffer.startsWith("SENSOR"))
{
processSensorState(_buffer);
}
}
} }
void Microcontroller::isReadyRead() void Microcontroller::isReadyRead()
{ {
char charBuf; char charBuf;
while(_port->getChar(&charBuf)) while(_port->getChar(&charBuf))
{ {
_buffer.push_back(charBuf); _buffer.push_back(charBuf);
if(_buffer.endsWith('\n') ) if( _buffer.endsWith('\n') )
{ {
_buffer.remove('\n'); _buffer.remove('\n');
processMicroReturn(); processMicroReturn();
textRecived(_buffer); textRecived(_buffer);
_buffer.clear(); _buffer.clear();
} }
} }
} }

View file

@ -1,6 +1,8 @@
#ifndef MICROCONTROLLER_H #ifndef MICROCONTROLLER_H
#define MICROCONTROLLER_H #define MICROCONTROLLER_H
#include <iostream>
#include <QObject> #include <QObject>
#include <QColor> #include <QColor>
#include <QIODevice> #include <QIODevice>
@ -15,70 +17,73 @@
#include "items/item.h" #include "items/item.h"
#include "items/relay.h" #include "items/relay.h"
#include "sensors/sensor.h" #include "sensors/sensor.h"
#include "items/itemsource.h"
class Microcontroller : public ItemSource class Microcontroller : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
static constexpr char AMP_RELAY = 0; static constexpr char AMP_RELAY = 0;
static constexpr char SENSOR_TEMPERATURE = 1; static constexpr char SENSOR_TEMPERATURE = 1;
static constexpr char SENSOR_DOOR = 0 ; static constexpr char SENSOR_DOOR = 0 ;
private: private:
bool listMode = false; bool listMode = false;
//uint8_t _auxState = 0; //uint8_t _auxState = 0;
QIODevice* _port = nullptr; QIODevice* _port = nullptr;
std::vector< std::shared_ptr<Item> > relayList; std::vector< std::shared_ptr<Item> > relayList;
QScopedPointer<QEventLoop> loop; QScopedPointer<QEventLoop> loop;
QString _buffer; QString _buffer;
void processMicroReturn(); void processMicroReturn();
void processList(const QString& buffer); void processList(const QString& buffer);
void processRelayState(const QString& buffer); void processRelayState(const QString& buffer);
void processSensorState(const QString& buffer); void processSensorState(const QString& buffer);
std::shared_ptr<Relay> processRelayLine(const QString& buffer); std::shared_ptr<Relay> processRelayLine(const QString& buffer);
void write(char *buffer, const size_t length); void write(char *buffer, const size_t length);
void write(const QByteArray& buffer); void write(const QByteArray& buffer);
public: public:
Microcontroller(QIODevice* port); Microcontroller(QIODevice* port);
Microcontroller(); Microcontroller();
~Microcontroller(); ~Microcontroller();
bool connected(); bool connected();
void setIODevice(QIODevice* port); void setIODevice(QIODevice* port);
public slots: public slots:
void rgbOn(); void rgbOn();
void rgbOff(); void rgbOff();
void changeRgbColor(const QColor color); void changeRgbColor(const QColor color);
void setPattern(int pattern); void setPattern(int pattern);
void startSunrise(); void startSunrise();
void refresh() override; void requestState();
void setAuxPwm(int duty); void setAuxPwm(int duty);
void relayOn(int relay); void relayOn(int relay);
void relayOff(int relay); void relayOff(int relay);
void relayToggle(int state, int id); void relayToggle(int state, int id);
private slots: private slots:
void isReadyRead(); void isReadyRead();
signals: signals:
void textRecived(const QString string); void textRecived(const QString string);
void gotSensorState(Sensor sensor); void itemChanged(ItemData relay);
void auxStateChanged(int value);
void gotRelayList(std::vector< std::shared_ptr<Item> >&);
void gotSensorState(Sensor sensor);
}; };
#endif // MICROCONTROLLER_H #endif // MICROCONTROLLER_H

View file

@ -1,72 +0,0 @@
#include "pipewire.h"
#include <stdexcept>
#include <QDebug>
static const struct pw_registry_events registry_events = {
.version = PW_VERSION_REGISTRY_EVENTS,
.global = &PipeWireHandler::registryEventHandler,
.global_remove = nullptr
};
PipeWireHandler::PipeWireHandler()
{
loop = pw_thread_loop_new("SHinterface", nullptr);
if(!loop)
throw std::runtime_error("Could not create pipewire main loop");
context = pw_context_new(pw_thread_loop_get_loop(loop), nullptr, 0);
if(!context)
throw std::runtime_error("Could not create pipewire context");
core = pw_context_connect(context, NULL, 0);
if(!core)
throw std::runtime_error("Could not connect to pipewire");
registry = pw_core_get_registry(core, PW_VERSION_REGISTRY, 0);
if(!registry)
throw std::runtime_error("Could not get pipewire registry");
spa_zero(registryListener);
pw_registry_add_listener(registry, &registryListener, &registry_events, this);
}
bool PipeWireHandler::startLoop()
{
if(!loop || !context || !core || !registry)
return false;
int ret = pw_thread_loop_start(loop);
return ret == 0;
}
struct pw_registry* PipeWireHandler::getRegistry()
{
return registry;
}
void PipeWireHandler::registryEventHandler(void *data, uint32_t id,
uint32_t permissions, const char *type, uint32_t version,
const struct spa_dict *props)
{
(void)permissions;
(void)version;
PipeWireHandler* handler = static_cast<PipeWireHandler*>(data);
if(std::string(type) == PW_TYPE_INTERFACE_Node)
{
const struct spa_dict_item *item = spa_dict_lookup_item(props, "node.name");
if(item)
{
qDebug()<<"got new pipewire node:"<<id<<"name:"<<item->value;
handler->nodeAdded({id, item->value});
}
}
}
PipeWireHandler::~PipeWireHandler()
{
pw_core_disconnect(core);
pw_context_destroy(context);
pw_thread_loop_stop(loop);
}

View file

@ -1,56 +0,0 @@
#pragma once
#include <pipewire/context.h>
#include <pipewire/core.h>
#include <pipewire/pipewire.h>
#include <QObject>
#include <string>
#include <cstdint>
class PipeWireHandler: public QObject
{
Q_OBJECT
public:
struct PwNode
{
uint32_t id;
std::string name;
};
private:
struct pw_thread_loop* loop;
struct pw_context* context;
struct pw_core* core;
struct pw_registry* registry;
struct spa_hook registryListener;
void write(const char * const buffer, const size_t length);
void write(const QByteArray& buffer);
void decode(QByteArray buffer);
void decodeMaster(const QByteArray& buffer);
public:
static void registryEventHandler(void *data, uint32_t id,
uint32_t permissions, const char *type, uint32_t version,
const struct spa_dict *props);
signals:
void nodeAdded(PwNode node);
void nodeRemoved(PwNode node);
public:
PipeWireHandler();
PipeWireHandler(const PipeWireHandler&) = delete;
PipeWireHandler operator=(const PipeWireHandler&) = delete;
bool startLoop();
struct pw_registry* getRegistry();
~PipeWireHandler();
};

View file

@ -1,3 +0,0 @@
#include "programmode.h"
program_mode_t programMode = PROGRAM_MODE_PRIMARY;

View file

@ -1,13 +0,0 @@
#ifndef PROGRAMMODE_H
#define PROGRAMMODE_H
typedef enum
{
PROGRAM_MODE_PRIMARY = 0,
PROGRAM_MODE_HEADLESS_PRIMARY,
PROGRAM_MODE_UI_ONLY
} program_mode_t;
extern program_mode_t programMode;
#endif // PROGRAMMODE_H

View file

@ -1,187 +0,0 @@
#include "mqttsensorsource.h"
#include<QJsonArray>
MqttSensorSource::MqttSensorSource(QObject *parent)
: QObject{parent}
{
}
void MqttSensorSource::start(const QJsonObject& settings)
{
baseTopicName = settings["BaseTopic"].toString("zigbee2mqtt");
connect(&client, &QMqttClient::stateChanged, this, &MqttSensorSource::onClientStateChanged);
connect(&client, &QMqttClient::errorChanged, this, &MqttSensorSource::onClientError);
client.setHostname(settings["Host"].toString("127.0.0.1"));
client.setPort(settings["Port"].toInt(1883));
if(settings.contains("User"))
client.setUsername(settings["User"].toString());
if(settings.contains("Password"))
client.setPassword(settings["Password"].toString());
client.setProtocolVersion(QMqttClient::MQTT_5_0);
client.connectToHost();
QJsonArray sensorsArray = settings["Sensors"].toArray();
for(QJsonValueRef sensorRef : sensorsArray)
{
QJsonObject sensorObject = sensorRef.toObject();
if(!sensorObject.contains("Topic"))
continue;
SensorSubscription sensor;
sensor.topic = sensorObject["Topic"].toString();
if(!sensorObject.contains("Name"))
sensor.name = sensor.topic;
else
sensor.name = sensorObject["Name"].toString();
sensor.id = qHash(baseTopicName + "/" + sensor.topic);
sensors.push_back(sensor);
}
}
void MqttSensorSource::onClientError(QMqttClient::ClientError error)
{
qWarning()<<"MQTT Client error:"<<error;
}
MqttSensorSource::SensorSubscription& MqttSensorSource::findSubscription(const QString& topic)
{
for(SensorSubscription& sensor : sensors)
{
if(baseTopicName + "/" + sensor.topic == topic)
return sensor;
}
assert(false);
}
void MqttSensorSource::onClientStateChanged(QMqttClient::ClientState state)
{
if(state == QMqttClient::ClientState::Connected)
{
qInfo()<<"Connected to MQTT broker at "<<client.hostname()<<client.port();
for(SensorSubscription& sensor : sensors)
{
qDebug()<<"MQTT subscribeing to"<<baseTopicName + "/" + sensor.topic;
sensor.subscription = client.subscribe(baseTopicName + "/" + sensor.topic);
connect(sensor.subscription, &QMqttSubscription::messageReceived, this, &MqttSensorSource::onMessageReceived);
}
}
else if (state == QMqttClient::ClientState::Disconnected)
{
qWarning()<<"Lost connection to MQTT broker";
for(SensorSubscription& sensor : sensors)
{
if(sensor.subscription)
{
client.unsubscribe(sensor.topic);
sensor.subscription = nullptr;
}
}
}
else if(state == QMqttClient::ClientState::Connecting)
{
qInfo()<<"Connecting to MQTT broker at "<<client.hostname()<<client.port();
}
}
void MqttSensorSource::onMessageReceived(const QMqttMessage& message)
{
Sensor sensor;
SensorSubscription& sensorSub = findSubscription(message.topic().name());
QString baseName = sensorSub.name;
sensor.id = sensorSub.id;
sensor.updateSeen();
QJsonDocument doc = QJsonDocument::fromJson(message.payload());
if(doc.isObject())
{
QJsonObject obj = doc.object();
if(obj.contains("temperature"))
{
sensor.name = baseName + " Temperature";
sensor.type = Sensor::TYPE_TEMPERATURE;
sensor.field = obj["temperature"].toDouble(0);
stateChanged(sensor);
}
if(obj.contains("humidity"))
{
sensor.name = baseName + " Humidity";
sensor.type = Sensor::TYPE_HUMIDITY;
sensor.field = obj["humidity"].toDouble(0);
stateChanged(sensor);
}
if(obj.contains("illuminance"))
{
sensor.name = baseName + " Illuminance";
sensor.type = Sensor::TYPE_BRIGHTNESS;
sensor.field = obj["illuminance"].toDouble(0);
stateChanged(sensor);
}
if(obj.contains("presence"))
{
sensor.name = baseName + " Presence";
sensor.type = Sensor::TYPE_OCUPANCY;
sensor.field = obj["presence"].toBool() ? 1 : 0;
stateChanged(sensor);
}
if(obj.contains("co2"))
{
sensor.name = baseName + " co2";
sensor.type = Sensor::TYPE_CO2;
sensor.field = obj["co2"].toDouble(0);
stateChanged(sensor);
}
if(obj.contains("formaldehyd"))
{
sensor.name = baseName + " Formaldehyd";
sensor.type = Sensor::TYPE_FORMALDEHYD;
sensor.field = obj["formaldehyd"].toDouble(0);
stateChanged(sensor);
}
if(obj.contains("pm25"))
{
sensor.name = baseName + " pm25";
sensor.type = Sensor::TYPE_PM25;
sensor.field = obj["pm25"].toDouble(0);
stateChanged(sensor);
}
if(obj.contains("voc"))
{
sensor.name = baseName + " VOC";
sensor.type = Sensor::TYPE_TOTAL_VOC;
sensor.field = obj["voc"].toDouble(0);
stateChanged(sensor);
}
}
}
void MqttSensorSource::store(QJsonObject& json)
{
json["Host"] = client.hostname();
json["Port"] = client.port();
json["BaseTopic"] = baseTopicName;
if(client.username() != "")
json["User"] = client.username();
if(client.password() != "")
json["Password"] = client.password();
QJsonArray sensorsArray;
for(const SensorSubscription& sensor : sensors)
{
QJsonObject sensorObject;
sensorObject["Name"] = sensor.name;
sensorObject["Topic"] = sensor.topic;
sensorsArray.append(sensorObject);
}
json["Sensors"] = sensorsArray;
}

View file

@ -1,44 +0,0 @@
#ifndef MQTTSENSORSOURCE_H
#define MQTTSENSORSOURCE_H
#include <QObject>
#include <QJsonObject>
#include <QtMqtt/QMqttClient>
#include <vector>
#include "sensor.h"
class MqttSensorSource : public QObject
{
Q_OBJECT
struct SensorSubscription
{
uint64_t id;
QString topic;
QString name;
QMqttSubscription* subscription = nullptr;
};
QString baseTopicName;
std::vector<SensorSubscription> sensors;
QMqttClient client;
private:
SensorSubscription& findSubscription(const QString& topic);
private slots:
void onClientStateChanged(QMqttClient::ClientState state);
void onMessageReceived(const QMqttMessage& message);
void onClientError(QMqttClient::ClientError error);
public:
explicit MqttSensorSource(QObject *parent = nullptr);
void start(const QJsonObject& settings);
void store(QJsonObject& json);
signals:
void stateChanged(Sensor sensor);
};
#endif // MQTTSENSORSOURCE_H

View file

@ -0,0 +1,61 @@
#include "ocupancysensor.h"
#include <QTimer>
#include <QDebug>
#include "../apgetconnected.h"
OcupancySensorSource::OcupancySensorSource(QObject *parent, const QString& device, const QString& deviceMac): QObject (parent), deviceMac_(deviceMac), device_(device)
{
QTimer::singleShot(timeoutMs, this, &OcupancySensorSource::Timeout);
}
void OcupancySensorSource::sensorEvent(Sensor sensor)
{
if(sensor.type == Sensor::TYPE_DOOR && sensor.id == 1 && sensor.field != 0.0f)
{
if(occupied == false) stateChanged(Sensor(Sensor::TYPE_OCUPANCY, 0, 1, "Occupancy"));
QTimer::singleShot(timeoutMs, this, &OcupancySensorSource::Timeout);
}
}
void OcupancySensorSource::Timeout()
{
int error = 0;
qDebug()<<"testing for occupancy";
std::vector<uint64_t> devices = ap::connectedDevices(device_.toLatin1().toStdString(), error);
if(error == 0)
{
bool found = false;
for(size_t i = 0; i < devices.size(); ++i)
{
std::string mac = ap::macAddrToString(devices[i]);
if(mac.find(deviceMac_.toLatin1().toStdString()) != std::string::npos)
{
found = true;
qDebug()<<"occupied";
break;
}
}
stateChanged(Sensor(Sensor::TYPE_OCUPANCY, 0, found, "Occupancy"));
occupied = found;
}
else
{
stateChanged(Sensor(Sensor::TYPE_OCUPANCY, 0, true, "Occupancy"));
qDebug()<<"occupancy sensor error "<<error;
}
}
void OcupancySensorSource::store(QJsonObject &json)
{
json["Device"] = device_;
json["MacAddres"] = deviceMac_;
}
void OcupancySensorSource::load(const QJsonObject &json)
{
device_ = json["Device"].toString("wlan0");
deviceMac_ = json["MacAddres"].toString("60:BE:B5:25:8C:E0");
}

View file

@ -0,0 +1,32 @@
#pragma once
#include <QObject>
#include <QJsonObject>
#include "sensor.h"
class OcupancySensorSource : public QObject
{
Q_OBJECT
private:
QString deviceMac_;
QString device_;
bool occupied = true;
static constexpr unsigned timeoutMs = (15 * 60) * 1000;
public:
explicit OcupancySensorSource(QObject *parent = nullptr, const QString& device = "wlan0", const QString& deviceMac = "60:BE:B5:25:8C:E0");
void store(QJsonObject& json);
void load(const QJsonObject& json);
public slots:
void sensorEvent(Sensor sensor);
private slots:
void Timeout();
signals:
void stateChanged(Sensor sensor);
};

View file

@ -6,44 +6,44 @@ SensorStore globalSensors;
SensorStore::SensorStore(QObject *parent): QObject(parent) SensorStore::SensorStore(QObject *parent): QObject(parent)
{ {
sensors_.push_back(Sensor(0,1,0,"Front door")); sensors_.push_back(Sensor(0,1,0,"Front door"));
sensors_.push_back(Sensor(0,0,0,"Bedroom door")); sensors_.push_back(Sensor(0,0,0,"Bedroom door"));
} }
void SensorStore::sensorGotState(const Sensor& sensor) void SensorStore::sensorGotState(const Sensor& sensor)
{ {
bool exsisting = false; bool exsisting = false;
for(unsigned i = 0; i < sensors_.size(); ++i) for(unsigned i = 0; i < sensors_.size(); ++i)
{ {
if(sensor.type == sensors_[i].type && sensor.id == sensors_[i].id) if(sensor.type == sensors_[i].type && sensor.id == sensors_[i].id)
{ {
sensors_[i].updateSeen(); sensors_[i].updateSeen();
if(sensors_[i].field != sensor.field) if(sensors_[i].field != sensor.field)
{ {
sensors_[i].field = sensor.field; sensors_[i].field = sensor.field;
sensorChangedState(sensor); sensorChangedState(sensor);
stateChenged(sensors_); stateChenged(sensors_);
} }
exsisting = true; exsisting = true;
break; break;
} }
} }
if(!exsisting) if(!exsisting)
{ {
sensors_.push_back(sensor); sensors_.push_back(sensor);
sensorChangedState(sensor); sensorChangedState(sensor);
stateChenged(sensors_); stateChenged(sensors_);
} }
for(unsigned i = 0; i < sensors_.size(); ++i) for(unsigned i = 0; i < sensors_.size(); ++i)
{ {
if(sensors_[i].type > 0 && sensors_[i].type < 128 && QDateTime::currentDateTime() > sensors_[i].lastSeen.addSecs(1800)) if(sensors_[i].type > 0 && sensors_[i].type < 128 && QDateTime::currentDateTime() > sensors_[i].lastSeen.addSecs(1800))
{ {
sensorDeleted(sensors_[i]); sensorDeleted(sensors_[i]);
stateChenged(sensors_); stateChenged(sensors_);
sensors_.erase(sensors_.begin()+i); sensors_.erase(sensors_.begin()+i);
} }
} }
} }

View file

@ -4,149 +4,96 @@
#include<QDateTime> #include<QDateTime>
#include<QObject> #include<QObject>
#include<vector> #include<vector>
#include<QJsonObject>
class Sensor class Sensor
{ {
public: public:
static constexpr uint8_t TYPE_DOOR = 0; static constexpr uint8_t TYPE_DOOR = 0;
static constexpr uint8_t TYPE_TEMPERATURE = 1; static constexpr uint8_t TYPE_TEMPERATURE = 1;
static constexpr uint8_t TYPE_HUMIDITY = 2; static constexpr uint8_t TYPE_HUMIDITY = 2;
static constexpr uint8_t TYPE_PRESSURE = 3; static constexpr uint8_t TYPE_PRESSURE = 3;
static constexpr uint8_t TYPE_BRIGHTNESS = 4; static constexpr uint8_t TYPE_BRIGHTNESS = 4;
static constexpr uint8_t TYPE_BUTTON = 5; static constexpr uint8_t TYPE_BUTTON = 5;
static constexpr uint8_t TYPE_ADC = 6; static constexpr uint8_t TYPE_ADC = 6;
static constexpr uint8_t TYPE_CO2 = 7; static constexpr uint8_t TYPE_LOWBATTERY = 128;
static constexpr uint8_t TYPE_FORMALDEHYD= 8; static constexpr uint8_t TYPE_SHUTDOWN_IMMINENT = 251;
static constexpr uint8_t TYPE_PM25 = 9; static constexpr uint8_t TYPE_OCUPANCY = 252;
static constexpr uint8_t TYPE_TOTAL_VOC = 10; static constexpr uint8_t TYPE_SUN_ALTITUDE = 253;
static constexpr uint8_t TYPE_LOWBATTERY = 128; static constexpr uint8_t TYPE_AUDIO_OUTPUT = 254;
static constexpr uint8_t TYPE_SHUTDOWN_IMMINENT = 251; static constexpr uint8_t TYPE_DUMMY = 255;
static constexpr uint8_t TYPE_OCUPANCY = 252;
static constexpr uint8_t TYPE_SUN_ALTITUDE = 253;
static constexpr uint8_t TYPE_AUDIO_OUTPUT = 254;
static constexpr uint8_t TYPE_DUMMY = 255;
uint8_t type; uint8_t type;
uint64_t id; uint8_t id;
float field; float field;
QString name; QString name;
QDateTime lastSeen; QDateTime lastSeen;
bool hidden; bool hidden;
Sensor(uint64_t typeIn, uint8_t idIn, float fieldIn = 0, QString nameIn = "", bool hiddenIn = false): type(typeIn), Sensor(uint8_t typeIn, uint8_t idIn, float fieldIn = 0, QString nameIn = "", bool hiddenIn = false): type(typeIn), id(idIn), field(fieldIn), name(nameIn), hidden(hiddenIn)
id(idIn), field(fieldIn), name(nameIn), hidden(hiddenIn) {
{ lastSeen = QDateTime::currentDateTime();
lastSeen = QDateTime::currentDateTime(); if(nameIn == "") generateName();
if(nameIn == "") }
generateName(); Sensor(QString nameIn = "dummy"): type(TYPE_DUMMY), id(0), field(0), name(nameIn), hidden(false)
} {
Sensor(QString nameIn = "dummy"): type(TYPE_DUMMY), id(0), field(0), name(nameIn), hidden(false) lastSeen = QDateTime::currentDateTime();
{ }
lastSeen = QDateTime::currentDateTime(); inline bool operator==(const Sensor& in) const{ return type==in.type && id == in.id; }
} inline bool operator!=(const Sensor& in) const{ return !(*this==in); }
Sensor(const QJsonObject& json) inline void updateSeen(){lastSeen = QDateTime::currentDateTime();}
{ static Sensor sensorFromString(const QString& str)
type = json["SensorType"].toInt(0); {
id = json["Id"].toInt(0); QStringList bufferList = str.split(' ');
field = json["Field"].toDouble(0); if(bufferList.size() >= 7)
name = json["Name"].toString("Sensor"); {
lastSeen = QDateTime::fromString(json["LastSeen"].toString("")); Sensor sensor(bufferList[2].toUInt(), bufferList[4].toUInt(), bufferList[6].toUInt());
hidden = json["Hidden"].toBool(false); if(sensor.type == Sensor::TYPE_HUMIDITY || sensor.type == Sensor::TYPE_TEMPERATURE) sensor.field = sensor.field/10;
} return sensor;
inline bool operator==(const Sensor& in) const }
{ else return Sensor(TYPE_DUMMY, 0, 0, "", true);
return type==in.type && id == in.id; }
} QString toString()
inline bool operator!=(const Sensor& in) const {
{ return QString("SENSOR TYPE: ")+QString::number(type)+" ID: "+QString::number(id)+" FIELD: "+
return !(*this==in); QString::number((type == Sensor::TYPE_HUMIDITY || type == Sensor::TYPE_TEMPERATURE) ? field*10 : field);
} }
inline void updateSeen() inline void generateName()
{ {
lastSeen = QDateTime::currentDateTime(); if(type == TYPE_TEMPERATURE) name = "Temperature " + QString::number(id);
} else if(type == TYPE_DOOR) name = "Door " + QString::number(id);
static Sensor sensorFromString(const QString& str) else if(type == TYPE_BUTTON) name = "Button " + QString::number(id);
{ else if(type == TYPE_AUDIO_OUTPUT) name = "Speakers " + QString::number(id);
QStringList bufferList = str.split(' '); else if(type == TYPE_HUMIDITY) name = "Humidity " + QString::number(id);
if(bufferList.size() >= 7) else if(type == TYPE_SUN_ALTITUDE) name = "Solar Altitude";
{ else if(type == TYPE_SHUTDOWN_IMMINENT) name = "Shutdown Imminent";
Sensor sensor(bufferList[2].toUInt(), bufferList[4].toUInt(), bufferList[6].toUInt()); else name = "Sensor Type " + QString::number(type) + " Id " + QString::number(id);
if(sensor.type == Sensor::TYPE_HUMIDITY || sensor.type == Sensor::TYPE_TEMPERATURE) }
sensor.field = sensor.field/10;
if(bufferList.size() >= 9)
sensor.lastSeen = QDateTime::fromSecsSinceEpoch(bufferList[8].toLongLong());
return sensor;
}
else
{
return Sensor(TYPE_DUMMY, 0, 0, "", true);
}
}
QString toString()
{
return QString("SENSOR TYPE: ")+QString::number(type)+" ID: "+QString::number(id)+" FIELD: "+
QString::number((type == Sensor::TYPE_HUMIDITY || type == Sensor::TYPE_TEMPERATURE) ? field*10 : field) +
" TIME: " + QString::number(lastSeen.toSecsSinceEpoch());
}
inline void store(QJsonObject& json)
{
json["Type"] = "Sensor";
json["SensorType"] = static_cast<int>(type);
json["Id"] = static_cast<int>(id);
json["Field"] = field;
json["Name"] = name;
json["LastSeen"] = lastSeen.toString();
json["Hidden"] = hidden;
}
inline void generateName()
{
if(type == TYPE_TEMPERATURE)
name = "Temperature " + QString::number(id);
else if(type == TYPE_DOOR)
name = "Door " + QString::number(id);
else if(type == TYPE_BUTTON)
name = "Button " + QString::number(id);
else if(type == TYPE_AUDIO_OUTPUT)
name = "Speakers " + QString::number(id);
else if(type == TYPE_HUMIDITY)
name = "Humidity " + QString::number(id);
else if(type == TYPE_SUN_ALTITUDE)
name = "Solar Altitude";
else if(type == TYPE_SHUTDOWN_IMMINENT)
name = "Shutdown Imminent";
else name = "Sensor Type " + QString::number(type) + " Id " + QString::number(id);
}
}; };
class SensorStore: public QObject class SensorStore: public QObject
{ {
Q_OBJECT Q_OBJECT
private: private:
std::vector<Sensor> sensors_; std::vector<Sensor> sensors_;
public: public:
SensorStore(QObject *parent = nullptr); SensorStore(QObject *parent = nullptr);
virtual ~SensorStore() {} virtual ~SensorStore(){}
inline std::vector<Sensor>* getSensors() inline std::vector<Sensor>* getSensors(){ return &sensors_; }
{
return &sensors_;
}
public slots: public slots:
void sensorGotState(const Sensor& sensor); void sensorGotState(const Sensor& sensor);
signals: signals:
void stateChenged(std::vector<Sensor> sensors); void stateChenged(std::vector<Sensor> sensors);
void sensorChangedState(Sensor sensor); void sensorChangedState(Sensor sensor);
void sensorDeleted(Sensor sensor); void sensorDeleted(Sensor sensor);
}; };

View file

@ -0,0 +1,59 @@
#include "speakersensor.h"
#include <QDebug>
SpeakerSensorSource::SpeakerSensorSource(QString name, QObject *parent) : QObject(parent), name_(name)
{
silenceCount = 0;
}
SpeakerSensorSource::~SpeakerSensorSource()
{
abort();
}
void SpeakerSensorSource::run()
{
abort();
arecord.start( "arecord --disable-softvol -r 8000 -D front -" );
connect(&timer, SIGNAL(timeout()), this, SLOT(doTick()));
timer.setInterval(500);
timer.start();
stateChanged(Sensor(Sensor::TYPE_AUDIO_OUTPUT, 0, 1, name_));
}
void SpeakerSensorSource::abort()
{
if(arecord.state() == QProcess::Running)arecord.close();
if(timer.isActive())timer.stop();
}
void SpeakerSensorSource::doTick()
{
if(arecord.state() == QProcess::Running)
{
QByteArray buffer = arecord.readAllStandardOutput();
//qDebug()<<(int16_t)buffer[0];
for(long i = 0; i < buffer.size(); i++)
{
if((int16_t)buffer.at(i) != -128)
{
silenceCount = 0;
}
}
if(silenceCount > 40 && state)
{
stateChanged(Sensor(Sensor::TYPE_AUDIO_OUTPUT, 0, 0, name_));
state = false;
}
else if(silenceCount == 0 && !state)
{
stateChanged(Sensor(Sensor::TYPE_AUDIO_OUTPUT, 0, 1, name_));
state = true;
}
silenceCount++;
}
}

View file

@ -0,0 +1,45 @@
#ifndef AMPMANAGER_H
#define AMPMANAGER_H
#include <iostream>
#include <QObject>
#include <QRunnable>
#include <QScopedPointer>
#include <QEventLoop>
#include <QTimer>
#include <QProcess>
#include <QByteArray>
#include "sensor.h"
class SpeakerSensorSource : public QObject
{
Q_OBJECT
private:
QString name_;
bool state = true;
QTimer timer;
public:
explicit SpeakerSensorSource(QString name = "", QObject *parent = nullptr);
~SpeakerSensorSource();
public slots:
void run();
void abort();
signals:
void stateChanged(Sensor sensor);
private slots:
void doTick();
private:
long silenceCount = 0;
QProcess arecord;
};
#endif // AMPMANAGER_H

View file

@ -2,24 +2,24 @@
SunSensorSource::SunSensorSource(double lat, double lon, QObject *parent): QObject(parent), sun_(lat, lon) SunSensorSource::SunSensorSource(double lat, double lon, QObject *parent): QObject(parent), sun_(lat, lon)
{ {
connect(&timer, SIGNAL(timeout()), this, SLOT(doTick())); connect(&timer, SIGNAL(timeout()), this, SLOT(doTick()));
} }
void SunSensorSource::run() void SunSensorSource::run()
{ {
connect(&timer, SIGNAL(timeout()), this, SLOT(doTick())); connect(&timer, SIGNAL(timeout()), this, SLOT(doTick()));
timer.setInterval(10000); //10s timer.setInterval(10000); //10s
timer.start(); timer.start();
doTick(); doTick();
} }
void SunSensorSource::abort() void SunSensorSource::abort()
{ {
if(timer.isActive())timer.stop(); if(timer.isActive())timer.stop();
} }
void SunSensorSource::doTick() void SunSensorSource::doTick()
{ {
stateChanged(Sensor(Sensor::TYPE_SUN_ALTITUDE, 0, static_cast<float>(sun_.altitude()))); stateChanged(Sensor(Sensor::TYPE_SUN_ALTITUDE, 0, static_cast<float>(sun_.altitude())));
} }

View file

@ -2,28 +2,28 @@
#include <QTimer> #include <QTimer>
#include "sun.h" #include "../sun.h"
#include "sensor.h" #include "sensor.h"
class SunSensorSource : public QObject class SunSensorSource : public QObject
{ {
Q_OBJECT Q_OBJECT
private: private:
Sun sun_; Sun sun_;
QTimer timer; QTimer timer;
public: public:
explicit SunSensorSource(double lat, double lon, QObject *parent = nullptr); explicit SunSensorSource(double lat, double lon, QObject *parent = nullptr);
public slots: public slots:
void run(); void run();
void abort(); void abort();
signals: signals:
void stateChanged(Sensor sensor); void stateChanged(Sensor sensor);
private slots: private slots:
void doTick(); void doTick();
}; };

View file

@ -1,104 +0,0 @@
#include <QTcpSocket>
#include <QJsonDocument>
#include <QJsonArray>
#include <iostream>
#include "items/item.h"
#include "items/itemstore.h"
#include "service.h"
Service::Service(QObject* parent):
ItemSource(parent)
{}
QJsonObject Service::createMessage(const QString& type, const QJsonArray& data)
{
QJsonObject json;
json["MessageType"] = type;
json["Data"] = data;
return json;
}
void Service::sensorEvent(Sensor sensor)
{
QJsonArray sensors;
QJsonObject sensorjson;
sensor.store(sensorjson);
sensors.append(sensorjson);
QJsonObject json = createMessage("SensorUpdate", sensors);
sendJson(json);
}
void Service::itemUpdated(std::weak_ptr<Item> item)
{
qDebug()<<__func__;
QJsonArray items;
QJsonObject itemjson;
item.lock()->store(itemjson);
items.append(itemjson);
QJsonObject json = createMessage("ItemUpdate", items);
json["FullList"] = false;
sendJson(json);
}
void Service::refresh()
{
sendJson(createMessage("GetSensors", QJsonArray()));
sendJson(createMessage("GetItems", QJsonArray()));
}
void Service::sendSensors()
{
QJsonArray sensors;
for(auto& sensor: *globalSensors.getSensors())
{
QJsonObject sensorjson;
sensor.store(sensorjson);
sensors.append(sensorjson);
}
sendJson(createMessage("SensorUpdate", sensors));
}
void Service::sendItems()
{
QJsonArray items;
for(auto& item: *globalItems.getItems())
{
QJsonObject itemjson;
item->store(itemjson);
items.append(itemjson);
}
QJsonObject json = createMessage("ItemUpdate", items);
json["FullList"] = true;
sendJson(json);
}
void Service::processIncomeingJson(const QByteArray& jsonbytes)
{
QJsonDocument doc = QJsonDocument::fromJson(jsonbytes);
qDebug()<<"Got Json:"<<QString::fromLatin1(doc.toJson(QJsonDocument::JsonFormat::Indented));
QJsonObject json = doc.object();
QString type = json["MessageType"].toString();
if(type == "GetSensors")
{
qDebug()<<"Sending sensors";
sendSensors();
}
else if(type == "GetItems")
{
qDebug()<<"Sending Items";
sendItems();
}
else if(type == "SensorUpdate")
{
QJsonArray data = json["Data"].toArray();
for(QJsonValueRef sensorjson : data)
{
QJsonObject jsonobject = sensorjson.toObject();
Sensor sensor(jsonobject);
gotSensor(sensor);
}
}
}

View file

@ -1,42 +0,0 @@
#ifndef TCPSERVER_BASE_H
#define TCPSERVER_BASE_H
#include <QTcpServer>
#include <vector>
#include "sensors/sensor.h"
#include "items/item.h"
#include "items/itemsource.h"
class Service : public ItemSource
{
Q_OBJECT
protected:
typedef enum
{
STATE_IDLE,
STATE_RECV_JSON,
} client_state_t;
signals:
void gotSensor(Sensor sensor);
public slots:
void sensorEvent(Sensor sensor);
void itemUpdated(std::weak_ptr<Item> item);
virtual void refresh() override;
public:
Service(QObject* parent = nullptr);
void sendSensors();
void sendItems();
virtual void sendJson(const QJsonObject& json) = 0;
virtual bool launch(const QHostAddress &address = QHostAddress::Any, quint16 port = 0) = 0;
protected:
static QJsonObject createMessage(const QString& type, const QJsonArray& data);
virtual void processIncomeingJson(const QByteArray& jsonbytes);
};
#endif // TCPSERVER_BASE_H

View file

@ -1,100 +0,0 @@
#include <QTcpSocket>
#include <QJsonDocument>
#include <QJsonArray>
#include <iostream>
#include "items/item.h"
#include "service.h"
#include "tcpclient.h"
TcpClient::TcpClient(QObject* parent):
Service(parent),
socket(new QTcpSocket(this))
{
connect(socket, &QTcpSocket::readyRead, this, &TcpClient::socketReadyRead);
}
void TcpClient::sendJson(const QJsonObject& json)
{
QByteArray jsonData = QJsonDocument(json).toJson();
socket->write(QString("MSG JSON LEN " + QString::number(jsonData.size()) + "\n").toLatin1() + jsonData);
}
bool TcpClient::launch(const QHostAddress &address, quint16 port)
{
socket->connectToHost(address, port);
return socket->waitForConnected(2000);
}
void TcpClient::processIncomeingJson(const QByteArray& jsonbytes)
{
QJsonDocument doc = QJsonDocument::fromJson(jsonbytes);
QJsonObject json = doc.object();
QString type = json["MessageType"].toString();
if(type == "ItemUpdate")
{
std::cout<<"Got item json:\n"<<QString::fromLatin1(jsonbytes).toStdString();
QJsonArray data = json["Data"].toArray();
std::vector<std::shared_ptr<Item>> items;
for(QJsonValueRef itemjson : data)
{
QJsonObject jsonobject = itemjson.toObject();
std::shared_ptr<Item> item = Item::loadItem(jsonobject);
if(item)
{
item->setLoaded(false);
items.push_back(item);
}
}
if(!items.empty())
gotItems(items, true);
}
else
{
Service::processIncomeingJson(jsonbytes);
}
}
void TcpClient::processComand(const QByteArray& command)
{
if(command.startsWith("MSG JSON LEN "))
{
state = STATE_RECV_JSON;
recievebytes = command.mid(13).toLongLong();
}
}
void TcpClient::socketReadyRead()
{
buffer += socket->readAll();
bool remianing = true;
while(remianing)
{
remianing = false;
while(state == STATE_IDLE && buffer.contains('\n'))
{
size_t newlineIndex = buffer.indexOf('\n');
QByteArray command = buffer.left(newlineIndex);
buffer.remove(0, newlineIndex+1);
processComand(command);
remianing = true;
}
if(state == STATE_RECV_JSON)
{
if(recievebytes <= buffer.size())
{
QByteArray json = buffer.left(recievebytes);
buffer.remove(0, recievebytes);
recievebytes = 0;
state = STATE_IDLE;
processIncomeingJson(json);
remianing = true;
}
}
}
}
TcpClient::~TcpClient()
{
delete socket;
}

View file

@ -1,33 +0,0 @@
#ifndef TCPSERVER_CLIENT_H
#define TCPSERVER_CLIENT_H
#include <QTcpSocket>
#include <QJsonDocument>
#include <QJsonArray>
#include "service.h"
class TcpClient : public Service
{
Q_OBJECT
QTcpSocket* socket;
client_state_t state = STATE_IDLE;
long long recievebytes = 0;
QByteArray buffer;
public:
TcpClient(QObject* parent = nullptr);
~TcpClient();
virtual bool launch(const QHostAddress &address = QHostAddress::Any, quint16 port = 0) override;
virtual void sendJson(const QJsonObject& json) override;
protected:
virtual void processIncomeingJson(const QByteArray& jsonbytes) override;
private slots:
void socketReadyRead();
void processComand(const QByteArray& command);
};
#endif // TCPSERVER_CLIENT_H

View file

@ -1,153 +0,0 @@
#include <QTcpServer>
#include <vector>
#include <QTcpSocket>
#include <QJsonArray>
#include "items/item.h"
#include "service.h"
#include "tcpserver.h"
TcpServer::TcpServer(QObject* parent):
Service(parent),
server(this)
{
connect(&server, &QTcpServer::newConnection, this, &TcpServer::incomingConnection);
}
void TcpServer::sendJson(const QJsonObject& json)
{
for(auto client: clients)
{
QByteArray jsonData = QJsonDocument(json).toJson();
client.socket->write(QString("MSG JSON LEN " + QString::number(jsonData.size()) + "\n").toLatin1() + jsonData);
}
}
void TcpServer::processIncomeingJson(const QByteArray& jsonbytes)
{
QJsonDocument doc = QJsonDocument::fromJson(jsonbytes);
QJsonObject json = doc.object();
QString type = json["MessageType"].toString();
if(type == "ItemUpdate")
{
qDebug()<<"Got Items";
QJsonArray data = json["Data"].toArray();
bool FullList = json["FullList"].toBool(false);
std::vector<std::shared_ptr<Item>> items;
for(QJsonValueRef itemjson : data)
{
QJsonObject jsonobject = itemjson.toObject();
std::shared_ptr<Item> item = Item::loadItem(jsonobject);
item->setLoaded(FullList);
if(item)
items.push_back(item);
}
if(FullList && !items.empty())
{
requestReplaceItems(items);
sigRequestSave();
}
else if(!items.empty())
{
gotItems(items, false);
}
}
else
{
Service::processIncomeingJson(jsonbytes);
}
}
bool TcpServer::launch(const QHostAddress &address, quint16 port)
{
return server.listen(address, port);
}
void TcpServer::incomingConnection()
{
while(server.hasPendingConnections())
{
QTcpSocket* client = server.nextPendingConnection();
qDebug()<<"Got new client from"<<client->peerAddress().toString();
if(client)
{
clients.push_back({client});
connect(client, &QTcpSocket::errorOccurred, this, &TcpServer::socketError);
connect(client, &QTcpSocket::disconnected, this, &TcpServer::socketDisconnect);
connect(client, &QTcpSocket::readyRead, this, &TcpServer::socketReadyRead);
}
}
}
void TcpServer::socketError(QAbstractSocket::SocketError socketError)
{
(void)socketError;
for(size_t i = 0; i < clients.size(); i++)
{
if(clients[i].socket == TcpServer::sender())
{
clients.erase(clients.begin()+i);
--i;
}
}
}
void TcpServer::socketDisconnect()
{
for(size_t i = 0; i < clients.size(); i++)
{
if(clients[i].socket == TcpServer::sender())
{
clients.erase(clients.begin()+i);
--i;
}
}
}
void TcpServer::processComand(const QByteArray& command, Client& client)
{
if(command.startsWith("MSG JSON LEN "))
{
client.state = STATE_RECV_JSON;
client.recievebytes = command.mid(13).toLongLong();
qDebug()<<"Got command:"<<QString::fromLatin1(command);
}
}
void TcpServer::socketReadyRead()
{
for(size_t i = 0; i < clients.size(); i++)
{
if(clients[i].socket == sender())
{
QByteArray newChars = clients[i].socket->readAll();
clients[i].buffer += newChars;
bool remianing = true;
while(remianing)
{
qDebug()<<clients[i].buffer;
remianing = false;
while(clients[i].state == STATE_IDLE && clients[i].buffer.contains('\n'))
{
size_t newlineIndex = clients[i].buffer.indexOf('\n');
QByteArray command = clients[i].buffer.left(newlineIndex);
clients[i].buffer.remove(0, newlineIndex+1);
processComand(command, clients[i]);
remianing = true;
}
if(clients[i].state == STATE_RECV_JSON)
{
if(clients[i].recievebytes <= clients[i].buffer.size())
{
QByteArray json = clients[i].buffer.left(clients[i].recievebytes);
clients[i].buffer.remove(0, clients[i].recievebytes);
clients[i].recievebytes = 0;
clients[i].state = STATE_IDLE;
processIncomeingJson(json);
remianing = true;
}
}
}
}
}
}

View file

@ -1,45 +0,0 @@
#ifndef TCPSERVER_SERVER_H
#define TCPSERVER_SERVER_H
#include <QTcpServer>
#include <vector>
#include "service.h"
class TcpServer : public Service
{
Q_OBJECT
struct Client
{
QTcpSocket* socket;
QByteArray buffer;
client_state_t state = STATE_IDLE;
long long recievebytes = 0;
};
std::vector<Client> clients;
QTcpServer server;
public:
TcpServer(QObject* parent = nullptr);
virtual bool launch(const QHostAddress &address = QHostAddress::Any, quint16 port = 0) override;
virtual void sendJson(const QJsonObject& json) override;
signals:
void sigRequestSave();
private slots:
void incomingConnection();
void socketError(QAbstractSocket::SocketError socketError);
void socketDisconnect();
void socketReadyRead();
protected:
virtual void processIncomeingJson(const QByteArray& jsonbytes) override;
private:
void processComand(const QByteArray& command, Client& client);
};
#endif // TCPSERVER_SERVER_H

View file

@ -13,7 +13,7 @@ public:
double utcHour; double utcHour;
int day; int day;
int year; int year;
JdTime(); JdTime();
void update(); void update();
std::time_t toStdTime(); std::time_t toStdTime();
@ -34,21 +34,21 @@ void Sun::JdTime::update()
void Sun::JdTime::fromStdTime(std::time_t time) void Sun::JdTime::fromStdTime(std::time_t time)
{ {
std::tm ltime = *std::localtime( &time ); std::tm ltime = *std::localtime( &time );
localHour = ltime.tm_hour + ltime.tm_min/60.0 + ltime.tm_sec/3600.0; localHour = ltime.tm_hour + ltime.tm_min/60.0 + ltime.tm_sec/3600.0;
utcHour = localHour - ltime.tm_gmtoff/3600.0; utcHour = localHour - ltime.tm_gmtoff/3600.0;
day = ltime.tm_yday; day = ltime.tm_yday;
year = ltime.tm_year + 1900; year = ltime.tm_year + 1900;
std::tm millennium = {0,0,0,1,0,100}; std::tm millennium = {0,0,0,1,0,100};
std::time_t millenniumTime = std::mktime(&millennium) - timezone; std::time_t millenniumTime = std::mktime(&millennium) - timezone;
daysSinceY2K = (time - millenniumTime)/(60*60*24.0); daysSinceY2K = (time - millenniumTime)/(60*60*24.0);
//std::cout<<"days since y2k: "<<daysSinceY2K<<std::endl; //std::cout<<"days since y2k: "<<daysSinceY2K<<std::endl;
julianDate = daysSinceY2K + JULIAN_DATEATY2K - JULIAN_OFFSET; julianDate = daysSinceY2K + JULIAN_DATEATY2K - JULIAN_OFFSET;
//std::cout<<"julianDate: "<<julianDate<<std::endl; //std::cout<<"julianDate: "<<julianDate<<std::endl;
siderialUtcTime = 6.697374558 + 0.06570982441908 * (long)daysSinceY2K + 1.00273790935*utcHour; siderialUtcTime = 6.697374558 + 0.06570982441908 * (long)daysSinceY2K + 1.00273790935*utcHour;
while(siderialUtcTime < 0) siderialUtcTime+=24; while(siderialUtcTime < 0) siderialUtcTime+=24;
siderialUtcTime = fmod(siderialUtcTime, 24); siderialUtcTime = fmod(siderialUtcTime, 24);
@ -58,13 +58,12 @@ std::time_t Sun::JdTime::toStdTime()
{ {
std::tm millennium = {0,0,0,0,0,100}; std::tm millennium = {0,0,0,0,0,100};
std::time_t millenniumTime = std::mktime(&millennium)- timezone; std::time_t millenniumTime = std::mktime(&millennium)- timezone;
millenniumTime = millenniumTime + (julianDate-JULIAN_DATEATY2K+JULIAN_OFFSET)*(24*60*60); millenniumTime = millenniumTime + (julianDate-JULIAN_DATEATY2K+JULIAN_OFFSET)*(24*60*60);
return millenniumTime; return millenniumTime;
} }
Sun::Sun(double latitude, double longitude, double altitude): latitude_(latitude), longetude_(longitude), Sun::Sun(double latitude, double longitude, double altitude): latitude_(latitude), longetude_(longitude), altitude_(altitude)
altitude_(altitude)
{} {}
double Sun::nextMeanSolarNoonJD(const JdTime& time) double Sun::nextMeanSolarNoonJD(const JdTime& time)
@ -79,8 +78,7 @@ double Sun::meanSolarAnomaly(double meanSolarNoon)
double Sun::eqOfCenter(double meanSolarAnomaly) double Sun::eqOfCenter(double meanSolarAnomaly)
{ {
return 1.9148*sin(meanSolarAnomaly*TO_RADS) + 0.0200*sin(2*meanSolarAnomaly*TO_RADS) + 0.0003*sin( return 1.9148*sin(meanSolarAnomaly*TO_RADS) + 0.0200*sin(2*meanSolarAnomaly*TO_RADS) + 0.0003*sin(3*meanSolarAnomaly*TO_RADS);
3*meanSolarAnomaly*TO_RADS);
} }
double Sun::eclipticLongitude(double eqOfCenter, double meanSolarAnomaly) double Sun::eclipticLongitude(double eqOfCenter, double meanSolarAnomaly)
@ -104,14 +102,13 @@ double Sun::solarDeclination(double eclipticLongitude)
} }
double Sun::hourAngle(double localSolarTime) double Sun::hourAngle(double localSolarTime)
{ {
return 360/24 * (localSolarTime - 12); return 360/24 * (localSolarTime - 12);
} }
double Sun::hourAngleAtSunset(double solarDeclination) double Sun::hourAngleAtSunset(double solarDeclination)
{ {
return TO_DEGS*acos((sin((-0.83-(2.076*sqrt(altitude_)/60.0))*TO_RADS) - sin(solarDeclination*TO_RADS)*sin( return TO_DEGS*acos((sin((-0.83-(2.076*sqrt(altitude_)/60.0))*TO_RADS) - sin(solarDeclination*TO_RADS)*sin(latitude_*TO_RADS))/(cos(latitude_*TO_RADS)*cos(solarDeclination*TO_RADS)));
latitude_*TO_RADS))/(cos(latitude_*TO_RADS)*cos(solarDeclination*TO_RADS)));
} }
double Sun::altitude() double Sun::altitude()
@ -122,10 +119,9 @@ double Sun::altitude()
double eclipticLongitudeValue = eclipticLongitude(eqOfCenter(meanSolarAnomalyValue), meanSolarAnomalyValue); double eclipticLongitudeValue = eclipticLongitude(eqOfCenter(meanSolarAnomalyValue), meanSolarAnomalyValue);
double localSolarTimeValue = localSolarTime(time, equationOfTime(meanSolarAnomalyValue, eclipticLongitudeValue)); double localSolarTimeValue = localSolarTime(time, equationOfTime(meanSolarAnomalyValue, eclipticLongitudeValue));
double declinationValue = solarDeclination(eclipticLongitudeValue); double declinationValue = solarDeclination(eclipticLongitudeValue);
double cosZenithAngle = sin(latitude_*TO_RADS)*sin(declinationValue*TO_RADS)+cos(latitude_*TO_RADS)*cos( double cosZenithAngle = sin(latitude_*TO_RADS)*sin(declinationValue*TO_RADS)+cos(latitude_*TO_RADS)*cos(declinationValue*TO_RADS)*cos(hourAngle(localSolarTimeValue)*TO_RADS);
declinationValue*TO_RADS)*cos(hourAngle(localSolarTimeValue)*TO_RADS);
return TO_DEGS*asin(cosZenithAngle); return TO_DEGS*asin(cosZenithAngle);
} }
@ -136,10 +132,9 @@ double Sun::maximumAltitude()
double meanSolarAnomalyValue = meanSolarAnomaly(meanSolarNoonValue); double meanSolarAnomalyValue = meanSolarAnomaly(meanSolarNoonValue);
double eclipticLongitudeValue = eclipticLongitude(eqOfCenter(meanSolarAnomalyValue), meanSolarAnomalyValue); double eclipticLongitudeValue = eclipticLongitude(eqOfCenter(meanSolarAnomalyValue), meanSolarAnomalyValue);
double declinationValue = solarDeclination(eclipticLongitudeValue); double declinationValue = solarDeclination(eclipticLongitudeValue);
double cosZenithAngle = sin(latitude_*TO_RADS)*sin(declinationValue*TO_RADS)+cos(latitude_*TO_RADS)*cos( double cosZenithAngle = sin(latitude_*TO_RADS)*sin(declinationValue*TO_RADS)+cos(latitude_*TO_RADS)*cos(declinationValue*TO_RADS);
declinationValue*TO_RADS);
return TO_DEGS*asin(cosZenithAngle); return TO_DEGS*asin(cosZenithAngle);
} }
@ -148,6 +143,7 @@ double Sun::azimuth()
return 0; return 0;
} }
std::time_t Sun::riseTime() std::time_t Sun::riseTime()
{ {
JdTime time; JdTime time;
@ -156,13 +152,11 @@ std::time_t Sun::riseTime()
double eclipticLongitudeValue = eclipticLongitude(eqOfCenter(meanSolarAnomalyValue), meanSolarAnomalyValue); double eclipticLongitudeValue = eclipticLongitude(eqOfCenter(meanSolarAnomalyValue), meanSolarAnomalyValue);
double declinationValue = solarDeclination(eclipticLongitudeValue); double declinationValue = solarDeclination(eclipticLongitudeValue);
double hourAngleValue = hourAngleAtSunset(declinationValue); double hourAngleValue = hourAngleAtSunset(declinationValue);
time.julianDate = meanSolarNoonValue + equationOfTime(meanSolarAnomalyValue, time.julianDate = meanSolarNoonValue + equationOfTime(meanSolarAnomalyValue, eclipticLongitudeValue) - hourAngleValue/360.0;
eclipticLongitudeValue) - hourAngleValue/360.0;
return time.toStdTime(); return time.toStdTime();
} }
std::time_t Sun::setTime() std::time_t Sun::setTime()
{ {
JdTime time; JdTime time;
@ -171,13 +165,13 @@ std::time_t Sun::setTime()
double eclipticLongitudeValue = eclipticLongitude(eqOfCenter(meanSolarAnomalyValue), meanSolarAnomalyValue); double eclipticLongitudeValue = eclipticLongitude(eqOfCenter(meanSolarAnomalyValue), meanSolarAnomalyValue);
double declinationValue = solarDeclination(eclipticLongitudeValue); double declinationValue = solarDeclination(eclipticLongitudeValue);
double hourAngleValue = hourAngleAtSunset(declinationValue); double hourAngleValue = hourAngleAtSunset(declinationValue);
time.julianDate = meanSolarNoonValue + equationOfTime(meanSolarAnomalyValue, time.julianDate = meanSolarNoonValue + equationOfTime(meanSolarAnomalyValue, eclipticLongitudeValue) + hourAngleValue/360.0;
eclipticLongitudeValue) + hourAngleValue/360.0;
return time.toStdTime(); return time.toStdTime();
} }
double Sun::declination() double Sun::declination()
{ {
JdTime time; JdTime time;

View file

@ -16,24 +16,24 @@
class Sun class Sun
{ {
private: private:
static constexpr double TO_DEGS = 180.0/M_PI; static constexpr double TO_DEGS = 180.0/M_PI;
static constexpr double TO_RADS = M_PI/180.0; static constexpr double TO_RADS = M_PI/180.0;
static constexpr double SUN_DIA = 0.53; //degrees static constexpr double SUN_DIA = 0.53; //degrees
static constexpr double AIR_REFRACTION = 34.0/60.0; static constexpr double AIR_REFRACTION = 34.0/60.0;
static constexpr double ARGUMENT_OF_PERIHELION = 102.9372; static constexpr double ARGUMENT_OF_PERIHELION = 102.9372;
static constexpr double PLANETARY_AXIAL_TILT = 23.44; static constexpr double PLANETARY_AXIAL_TILT = 23.44;
class JdTime; class JdTime;
double latitude_; double latitude_;
double longetude_; double longetude_;
double altitude_; double altitude_;
private: private:
double nextMeanSolarNoonJD(const JdTime& time); double nextMeanSolarNoonJD(const JdTime& time);
double meanSolarAnomaly(double meanSolarNoon); double meanSolarAnomaly(double meanSolarNoon);
double eqOfCenter(double meanSolarAnomaly); double eqOfCenter(double meanSolarAnomaly);
double eclipticLongitude(double eqOfCenter, double meanSolarAnomaly); double eclipticLongitude(double eqOfCenter, double meanSolarAnomaly);
@ -43,14 +43,14 @@ private:
double hourAngle(double localSolarTime); double hourAngle(double localSolarTime);
double equationOfTime(double meanSolarAnomaly, double eclipticLongitude); double equationOfTime(double meanSolarAnomaly, double eclipticLongitude);
double localSolarTime(const JdTime& time, double equationOfTime); double localSolarTime(const JdTime& time, double equationOfTime);
public: public:
Sun(double latitude, double longitude, double altitude = 0); Sun(double latitude, double longitude, double altitude = 0);
double altitude(); double altitude();
double maximumAltitude(); double maximumAltitude();
double azimuth(); double azimuth();
double declination(); double declination();
std::time_t riseTime(); std::time_t riseTime();
std::time_t setTime(); std::time_t setTime();
}; };

View file

@ -6,7 +6,7 @@
int main() int main()
{ {
std::cout<<std::setprecision(15); std::cout<<std::setprecision(15);
Sun sun(49.884450, 8.650536); Sun sun(49.884450, 8.650536);
std::time_t time = sun.setTime(); std::time_t time = sun.setTime();
tm setTime = *localtime(&time); tm setTime = *localtime(&time);
time = sun.riseTime(); time = sun.riseTime();
@ -16,5 +16,5 @@ int main()
std::cout<<"current Alt: "<<sun.altitude()<<std::endl; std::cout<<"current Alt: "<<sun.altitude()<<std::endl;
std::cout<<"maximum Alt: "<<sun.maximumAltitude()<<std::endl; std::cout<<"maximum Alt: "<<sun.maximumAltitude()<<std::endl;
std::cout<<"declination: "<<sun.declination()<<std::endl; std::cout<<"declination: "<<sun.declination()<<std::endl;
return 0; return 0;
} }

View file

@ -5,121 +5,108 @@
#include <QSpinBox> #include <QSpinBox>
ActorSettingsDialog::ActorSettingsDialog(std::shared_ptr<AlarmTime> alarm, QWidget *parent): ActorSettingsDialog::ActorSettingsDialog(std::shared_ptr<AlarmTime> alarm, QWidget *parent):
QDialog(parent), QDialog(parent),
actor_(alarm), actor_(alarm),
ui(new Ui::ActorSettingsDialog) ui(new Ui::ActorSettingsDialog)
{ {
init(); init();
widget = new AlarmWidget(alarm, this); widget = new AlarmWidget(alarm, this);
ui->vertlayout->addWidget(widget); ui->vertlayout->addWidget(widget);
} }
ActorSettingsDialog::ActorSettingsDialog(std::shared_ptr<SensorActor> actor, QWidget *parent) : ActorSettingsDialog::ActorSettingsDialog(std::shared_ptr<SensorActor> actor, QWidget *parent) :
QDialog(parent), QDialog(parent),
actor_(actor), actor_(actor),
ui(new Ui::ActorSettingsDialog) ui(new Ui::ActorSettingsDialog)
{ {
init(); init();
widget = new SensorActorWidget(actor, &globalSensors, this); widget = new SensorActorWidget(actor, &globalSensors, this);
ui->vertlayout->addWidget(widget); ui->vertlayout->addWidget(widget);
} }
ActorSettingsDialog::ActorSettingsDialog(std::shared_ptr<Regulator> actor, QWidget *parent) : ActorSettingsDialog::ActorSettingsDialog(std::shared_ptr<Regulator> actor, QWidget *parent) :
QDialog(parent), QDialog(parent),
actor_(actor), actor_(actor),
ui(new Ui::ActorSettingsDialog) ui(new Ui::ActorSettingsDialog)
{ {
init(); init();
widget = new RegulatorWdiget(actor, &globalSensors, this); widget = new RegulatorWdiget(actor, &globalSensors, this);
ui->vertlayout->addWidget(widget); ui->vertlayout->addWidget(widget);
} }
ActorSettingsDialog::ActorSettingsDialog(std::shared_ptr<TimerActor> actor, QWidget *parent) : ActorSettingsDialog::ActorSettingsDialog(std::shared_ptr<TimerActor> actor, QWidget *parent) :
QDialog(parent), QDialog(parent),
actor_(actor), actor_(actor),
ui(new Ui::ActorSettingsDialog) ui(new Ui::ActorSettingsDialog)
{ {
init(); init();
widget = new TimerActorWidget(actor, this); widget = new TimerActorWidget(actor, this);
ui->vertlayout->addWidget(widget); ui->vertlayout->addWidget(widget);
} }
ActorSettingsDialog::ActorSettingsDialog(std::shared_ptr<PolynomalActor> actor, QWidget *parent) : ActorSettingsDialog::ActorSettingsDialog(std::shared_ptr<PolynomalActor> actor, QWidget *parent) :
QDialog(parent), QDialog(parent),
actor_(actor), actor_(actor),
ui(new Ui::ActorSettingsDialog) ui(new Ui::ActorSettingsDialog)
{ {
init(); init();
widget = new PolynomalActorWidget(actor, &globalSensors, this); widget = new PolynomalActorWidget(actor, &globalSensors, this);
ui->vertlayout->addWidget(widget); ui->vertlayout->addWidget(widget);
} }
ActorSettingsDialog::ActorSettingsDialog(std::shared_ptr<MultiFactorActor> actor, QWidget *parent) : ActorSettingsDialog::ActorSettingsDialog(std::shared_ptr<MultiFactorActor> actor, QWidget *parent) :
QDialog(parent), QDialog(parent),
actor_(actor), actor_(actor),
ui(new Ui::ActorSettingsDialog) ui(new Ui::ActorSettingsDialog)
{ {
init(); init();
widget = new FactorActorWidget(actor, this); widget = new FactorActorWidget(actor, this);
ui->vertlayout->addWidget(widget); ui->vertlayout->addWidget(widget);
} }
ActorSettingsDialog::ActorSettingsDialog(std::shared_ptr<Actor> actor, QWidget *parent) : ActorSettingsDialog::ActorSettingsDialog(std::shared_ptr<Actor> actor, QWidget *parent) :
QDialog(parent), QDialog(parent),
actor_(actor), actor_(actor),
ui(new Ui::ActorSettingsDialog) ui(new Ui::ActorSettingsDialog)
{ {
init(); init();
} }
void ActorSettingsDialog::init() void ActorSettingsDialog::init()
{ {
ui->setupUi(this); ui->setupUi(this);
connect(ui->comboBox_action, SIGNAL(currentIndexChanged(int)), this, SLOT(changeAction(int))); connect(ui->comboBox_action, SIGNAL(currentIndexChanged(int)), this, SLOT(changeAction(int)));
connect(ui->spinBox, SIGNAL(valueChanged(int)), this, SLOT(valueChanged(int))); connect(ui->spinBox, SIGNAL(valueChanged(int)), this, SLOT(valueChanged(int)));
connect(ui->pushButton_editItem, &QPushButton::clicked, this, &ActorSettingsDialog::editAsItem); connect(ui->pushButton_editItem, &QPushButton::clicked, this, &ActorSettingsDialog::editAsItem);
connect(ui->pushButton_enable, &QPushButton::clicked, this, &ActorSettingsDialog::setEnabled); ui->spinBox->hide();
ui->spinBox->hide();
ui->spinBox->setValue(actor_->getTriggerValue()); ui->spinBox->setValue(actor_->getTriggerValue());
if(actor_->getTriggerValue() == 0) if(actor_->getTriggerValue() == 0) ui->comboBox_action->setCurrentIndex(0);
ui->comboBox_action->setCurrentIndex(0); else if(actor_->getTriggerValue() == 1) ui->comboBox_action->setCurrentIndex(1);
else if(actor_->getTriggerValue() == 1) else ui->comboBox_action->setCurrentIndex(2);
ui->comboBox_action->setCurrentIndex(1);
else
ui->comboBox_action->setCurrentIndex(2);
ui->label_Exausted->setText(actor_->isExausted() ? "True" : "False"); ui->label_Exausted->setText(actor_->isExausted() ? "True" : "False");
ui->label_Enabled->setText(actor_->isActive() ? "True" : "False");
ui->pushButton_enable->setText(actor_->isActive() ? "Disable" : "Enable");
} }
ActorSettingsDialog::~ActorSettingsDialog() ActorSettingsDialog::~ActorSettingsDialog()
{ {
delete ui; delete ui;
} }
void ActorSettingsDialog::editAsItem() void ActorSettingsDialog::editAsItem()
{ {
ItemSettingsDialog itemSettingsDiag(actor_, this); ItemSettingsDialog itemSettingsDiag(actor_, this);
itemSettingsDiag.exec(); itemSettingsDiag.exec();
}
void ActorSettingsDialog::setEnabled()
{
actor_->setActive(!actor_->isActive());
ui->label_Enabled->setText(actor_->isActive() ? "True" : "False");
ui->pushButton_enable->setText(actor_->isActive() ? "Disable" : "Enable");
} }
void ActorSettingsDialog::valueChanged(int value) void ActorSettingsDialog::valueChanged(int value)
{ {
actor_->setTriggerValue(value); actor_->setTriggerValue(value);
} }
void ActorSettingsDialog::hideCancle([[maybe_unused]] const bool hide) void ActorSettingsDialog::hideCancle([[maybe_unused]] const bool hide)
@ -129,13 +116,13 @@ void ActorSettingsDialog::hideCancle([[maybe_unused]] const bool hide)
void ActorSettingsDialog::changeAction(int index) void ActorSettingsDialog::changeAction(int index)
{ {
if(index == 0) actor_->setTriggerValue(0); if(index == 0) actor_->setTriggerValue(0);
else if(index == 1) actor_->setTriggerValue(1); else if(index == 1) actor_->setTriggerValue(1);
else if(index == 2) else if(index == 2)
{ {
ui->spinBox->show(); ui->spinBox->show();
actor_->setTriggerValue(ui->spinBox->value()); actor_->setTriggerValue(ui->spinBox->value());
} }
if(index != 2)ui->spinBox->hide(); if(index != 2)ui->spinBox->hide();
} }

View file

@ -10,42 +10,40 @@
#include "actorwidgets/polynomalactorwidget.h" #include "actorwidgets/polynomalactorwidget.h"
#include "actorwidgets/factoractorwidget.h" #include "actorwidgets/factoractorwidget.h"
namespace Ui namespace Ui {
{
class ActorSettingsDialog; class ActorSettingsDialog;
} }
class ActorSettingsDialog : public QDialog class ActorSettingsDialog : public QDialog
{ {
Q_OBJECT Q_OBJECT
private: private:
std::shared_ptr<Actor> actor_; std::shared_ptr<Actor> actor_;
QWidget* widget; QWidget* widget;
void init(); void init();
public: public:
ActorSettingsDialog(std::shared_ptr<AlarmTime> actor, QWidget *parent = nullptr); ActorSettingsDialog(std::shared_ptr<AlarmTime> actor, QWidget *parent = nullptr);
ActorSettingsDialog(std::shared_ptr<SensorActor> actor, QWidget *parent = nullptr); ActorSettingsDialog(std::shared_ptr<SensorActor> actor, QWidget *parent = nullptr);
ActorSettingsDialog(std::shared_ptr<Regulator> actor, QWidget *parent = nullptr); ActorSettingsDialog(std::shared_ptr<Regulator> actor, QWidget *parent = nullptr);
ActorSettingsDialog(std::shared_ptr<TimerActor> actor, QWidget *parent = nullptr); ActorSettingsDialog(std::shared_ptr<TimerActor> actor, QWidget *parent = nullptr);
ActorSettingsDialog(std::shared_ptr<PolynomalActor> actor, QWidget *parent = nullptr); ActorSettingsDialog(std::shared_ptr<PolynomalActor> actor, QWidget *parent = nullptr);
ActorSettingsDialog(std::shared_ptr<MultiFactorActor> actor, QWidget *parent = nullptr); ActorSettingsDialog(std::shared_ptr<MultiFactorActor> actor, QWidget *parent = nullptr);
ActorSettingsDialog(std::shared_ptr<Actor> actor, QWidget *parent); ActorSettingsDialog(std::shared_ptr<Actor> actor, QWidget *parent);
~ActorSettingsDialog(); ~ActorSettingsDialog();
void hideCancle(const bool hide); void hideCancle(const bool hide);
private slots: private slots:
void changeAction(int index); void changeAction(int index);
void valueChanged(int value); void valueChanged(int value);
void editAsItem(); void editAsItem();
void setEnabled();
private: private:
Ui::ActorSettingsDialog *ui; Ui::ActorSettingsDialog *ui;
}; };
#endif // ACTORSETTINGSDIALOG_H #endif // ACTORSETTINGSDIALOG_H

View file

@ -85,63 +85,6 @@
</property> </property>
</widget> </widget>
</item> </item>
<item>
<spacer name="horizontalSpacer_2">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_3">
<item>
<widget class="QLabel" name="label_3">
<property name="text">
<string>Enabled:</string>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="label_Enabled">
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>True</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QPushButton" name="pushButton_enable">
<property name="text">
<string>Enable</string>
</property>
</widget>
</item>
</layout> </layout>
</item> </item>
<item> <item>

View file

@ -2,81 +2,73 @@
#include "ui_alarmwidget.h" #include "ui_alarmwidget.h"
AlarmWidget::AlarmWidget(std::shared_ptr<AlarmTime> alarm, QWidget *parent) : AlarmWidget::AlarmWidget(std::shared_ptr<AlarmTime> alarm, QWidget *parent) :
QWidget(parent), QWidget(parent),
alarm_(alarm), alarm_(alarm),
ui(new Ui::AlarmWidget) ui(new Ui::AlarmWidget)
{ {
ui->setupUi(this); ui->setupUi(this);
connect(ui->checkBox, &QCheckBox::stateChanged, this, &AlarmWidget::toggleRepeating);
connect(ui->radioButton, &QRadioButton::clicked, this, &AlarmWidget::setRepeatingType);
connect(ui->radioButton_2, &QRadioButton::clicked, this, &AlarmWidget::setRepeatingType);
connect(ui->radioButton_3, &QRadioButton::clicked, this, &AlarmWidget::setRepeatingType);
connect(ui->radioButton_4, &QRadioButton::clicked, this, &AlarmWidget::setRepeatingType);
ui->dateTimeEdit->setDateTime(alarm->getDateTime()); ui->dateTimeEdit->setDateTime(alarm->getDateTime());
if(alarm_->getRepeat() == AlarmTime::REPEAT_NEVER) if(alarm_->getRepeat() == AlarmTime::REPEAT_NEVER)
{ {
ui->radioButton->setEnabled(false); ui->radioButton->setEnabled(false);
ui->radioButton_2->setEnabled(false); ui->radioButton_2->setEnabled(false);
ui->radioButton_3->setEnabled(false); ui->radioButton_3->setEnabled(false);
ui->radioButton_4->setEnabled(false); ui->radioButton_4->setEnabled(false);
} }
else else
{ {
ui->checkBox->setChecked(true); ui->checkBox->setChecked(true);
ui->radioButton->setEnabled(true); ui->radioButton->setEnabled(true);
ui->radioButton_2->setEnabled(true); ui->radioButton_2->setEnabled(true);
ui->radioButton_3->setEnabled(true); ui->radioButton_3->setEnabled(true);
ui->radioButton_4->setEnabled(true); ui->radioButton_4->setEnabled(true);
} }
if(alarm_->getRepeat() == AlarmTime::REPEAT_DAILY) if(alarm_->getRepeat() == AlarmTime::REPEAT_DAILY) ui->radioButton->setChecked(true);
ui->radioButton->setChecked(true); else if(alarm_->getRepeat() == AlarmTime::REPEAT_WEEKLY) ui->radioButton_2->setChecked(true);
else if(alarm_->getRepeat() == AlarmTime::REPEAT_WEEKLY) else if(alarm_->getRepeat() == AlarmTime::REPEAT_MONTHLY)ui->radioButton_3->setChecked(true);
ui->radioButton_2->setChecked(true); else if(alarm_->getRepeat() == AlarmTime::REPEAT_YEARLY) ui->radioButton_4->setChecked(true);
else if(alarm_->getRepeat() == AlarmTime::REPEAT_MONTHLY)
ui->radioButton_3->setChecked(true);
else if(alarm_->getRepeat() == AlarmTime::REPEAT_YEARLY)
ui->radioButton_4->setChecked(true);
connect(ui->checkBox, &QCheckBox::stateChanged, this, &AlarmWidget::toggleRepeating); connect(ui->dateTimeEdit, &QDateTimeEdit::dateTimeChanged, alarm.get(), &AlarmTime::changeTime);
connect(ui->radioButton, &QRadioButton::clicked, this, &AlarmWidget::setRepeatingType);
connect(ui->radioButton_2, &QRadioButton::clicked, this, &AlarmWidget::setRepeatingType);
connect(ui->radioButton_3, &QRadioButton::clicked, this, &AlarmWidget::setRepeatingType);
connect(ui->radioButton_4, &QRadioButton::clicked, this, &AlarmWidget::setRepeatingType);
connect(ui->dateTimeEdit, &QDateTimeEdit::dateTimeChanged, alarm.get(), &AlarmTime::changeTime);
} }
AlarmWidget::~AlarmWidget() AlarmWidget::~AlarmWidget()
{ {
delete ui; delete ui;
} }
void AlarmWidget::setRepeatingType() void AlarmWidget::setRepeatingType()
{ {
if(ui->radioButton->isChecked()) if(ui->radioButton->isChecked())alarm_->setRepeat(AlarmTime::REPEAT_DAILY);
alarm_->setRepeat(AlarmTime::REPEAT_DAILY); if(ui->radioButton_2->isChecked())alarm_->setRepeat(AlarmTime::REPEAT_WEEKLY);
if(ui->radioButton_2->isChecked()) if(ui->radioButton_3->isChecked())alarm_->setRepeat(AlarmTime::REPEAT_MONTHLY);
alarm_->setRepeat(AlarmTime::REPEAT_WEEKLY); if(ui->radioButton_4->isChecked())alarm_->setRepeat(AlarmTime::REPEAT_YEARLY);
if(ui->radioButton_3->isChecked())
alarm_->setRepeat(AlarmTime::REPEAT_MONTHLY);
if(ui->radioButton_4->isChecked())
alarm_->setRepeat(AlarmTime::REPEAT_YEARLY);
} }
void AlarmWidget::toggleRepeating(int state) void AlarmWidget::toggleRepeating(int state)
{ {
if(state) if(state)
{ {
ui->radioButton->setEnabled(true); ui->radioButton->setEnabled(true);
ui->radioButton_2->setEnabled(true); ui->radioButton_2->setEnabled(true);
ui->radioButton_3->setEnabled(true); ui->radioButton_3->setEnabled(true);
ui->radioButton_4->setEnabled(true); ui->radioButton_4->setEnabled(true);
setRepeatingType(); setRepeatingType();
} }
else else
{ {
alarm_->setRepeat(AlarmTime::REPEAT_NEVER); alarm_->setRepeat(AlarmTime::REPEAT_NEVER);
ui->radioButton->setEnabled(false); ui->radioButton->setEnabled(false);
ui->radioButton_2->setEnabled(false); ui->radioButton_2->setEnabled(false);
ui->radioButton_3->setEnabled(false); ui->radioButton_3->setEnabled(false);
ui->radioButton_4->setEnabled(false); ui->radioButton_4->setEnabled(false);
} }
} }

View file

@ -5,27 +5,26 @@
#include <memory> #include <memory>
#include "../../actors/alarmtime.h" #include "../../actors/alarmtime.h"
namespace Ui namespace Ui {
{
class AlarmWidget; class AlarmWidget;
} }
class AlarmWidget : public QWidget class AlarmWidget : public QWidget
{ {
Q_OBJECT Q_OBJECT
std::shared_ptr<AlarmTime> alarm_; std::shared_ptr<AlarmTime> alarm_;
public: public:
explicit AlarmWidget(std::shared_ptr<AlarmTime> alarm, QWidget *parent = nullptr); explicit AlarmWidget(std::shared_ptr<AlarmTime> alarm, QWidget *parent = nullptr);
~AlarmWidget(); ~AlarmWidget();
private slots: private slots:
void toggleRepeating(int state); void toggleRepeating(int state);
void setRepeatingType(); void setRepeatingType();
private: private:
Ui::AlarmWidget *ui; Ui::AlarmWidget *ui;
}; };
#endif // ALARMWIDGET_H #endif // ALARMWIDGET_H

View file

@ -24,16 +24,16 @@
</property> </property>
<layout class="QFormLayout" name="formLayout"> <layout class="QFormLayout" name="formLayout">
<property name="fieldGrowthPolicy"> <property name="fieldGrowthPolicy">
<enum>QFormLayout::FieldGrowthPolicy::AllNonFixedFieldsGrow</enum> <enum>QFormLayout::AllNonFixedFieldsGrow</enum>
</property> </property>
<property name="rowWrapPolicy"> <property name="rowWrapPolicy">
<enum>QFormLayout::RowWrapPolicy::DontWrapRows</enum> <enum>QFormLayout::DontWrapRows</enum>
</property> </property>
<property name="labelAlignment"> <property name="labelAlignment">
<set>Qt::AlignmentFlag::AlignLeading|Qt::AlignmentFlag::AlignLeft|Qt::AlignmentFlag::AlignVCenter</set> <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
</property> </property>
<property name="formAlignment"> <property name="formAlignment">
<set>Qt::AlignmentFlag::AlignLeading|Qt::AlignmentFlag::AlignLeft|Qt::AlignmentFlag::AlignTop</set> <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop</set>
</property> </property>
<property name="horizontalSpacing"> <property name="horizontalSpacing">
<number>50</number> <number>50</number>
@ -57,7 +57,7 @@
<bool>false</bool> <bool>false</bool>
</property> </property>
<property name="currentSection"> <property name="currentSection">
<enum>QDateTimeEdit::Section::DaySection</enum> <enum>QDateTimeEdit::DaySection</enum>
</property> </property>
<property name="displayFormat"> <property name="displayFormat">
<string>dd.MM.yyyy hh:mm</string> <string>dd.MM.yyyy hh:mm</string>

View file

@ -3,82 +3,82 @@
#include "../actorsettingsdialog.h" #include "../actorsettingsdialog.h"
FactorActorWidget::FactorActorWidget(std::shared_ptr<MultiFactorActor> actor, QWidget *parent) : FactorActorWidget::FactorActorWidget(std::shared_ptr<MultiFactorActor> actor, QWidget *parent) :
QWidget(parent), QWidget(parent),
actor_(actor), actor_(actor),
ui(new Ui::FactorActorWidget) ui(new Ui::FactorActorWidget)
{ {
ui->setupUi(this); ui->setupUi(this);
ui->comboBox->setCurrentText(actor_->getFactorDirection() ? "True" : "False"); ui->comboBox->setCurrentText(actor_->getFactorDirection() ? "True" : "False");
ui->spinBox->setValue(actor_->getPreCancleTime()); ui->spinBox->setValue(actor_->getPreCancleTime());
if(actor_->getFactorActor()) ui->label_FactorActor->setText(actor_->getFactorActor()->getName()); if(actor_->getFactorActor()) ui->label_FactorActor->setText(actor_->getFactorActor()->getName());
connect(ui->pushButton, &QPushButton::clicked, this, &FactorActorWidget::createFactorActor); connect(ui->pushButton, &QPushButton::clicked, this, &FactorActorWidget::createFactorActor);
connect(ui->comboBox_Direcion, &QComboBox::currentTextChanged, this, &FactorActorWidget::setDirection); connect(ui->comboBox_Direcion, &QComboBox::currentTextChanged, this, &FactorActorWidget::setDirection);
connect(ui->spinBox, qOverload<int>(&QSpinBox::valueChanged), this, &FactorActorWidget::setPreCancleTime); connect(ui->spinBox, qOverload<int>(&QSpinBox::valueChanged), this, &FactorActorWidget::setPreCancleTime);
} }
FactorActorWidget::~FactorActorWidget() FactorActorWidget::~FactorActorWidget()
{ {
delete ui; delete ui;
} }
void FactorActorWidget::createFactorActor() void FactorActorWidget::createFactorActor()
{ {
ActorSettingsDialog* dialog = nullptr; ActorSettingsDialog* dialog = nullptr;
std::shared_ptr<Actor> actor = nullptr; std::shared_ptr<Actor> actor = nullptr;
if(ui->comboBox->currentText() == "Alarm") if(ui->comboBox->currentText() == "Alarm")
{ {
std::shared_ptr<AlarmTime> alarm = std::shared_ptr<AlarmTime>(new AlarmTime); std::shared_ptr<AlarmTime> alarm = std::shared_ptr<AlarmTime>(new AlarmTime);
actor = alarm; actor = alarm;
dialog = new ActorSettingsDialog(alarm, this); dialog = new ActorSettingsDialog(alarm, this);
} }
else if(ui->comboBox->currentText() == "Sensor") else if(ui->comboBox->currentText() == "Sensor")
{ {
std::shared_ptr<SensorActor> sensorActor = std::shared_ptr<SensorActor>(new SensorActor()); std::shared_ptr<SensorActor> sensorActor = std::shared_ptr<SensorActor>(new SensorActor());
actor = sensorActor; actor = sensorActor;
dialog = new ActorSettingsDialog(sensorActor, this); dialog = new ActorSettingsDialog(sensorActor, this);
} }
else if(ui->comboBox->currentText() == "Timer" ) else if(ui->comboBox->currentText() == "Timer" )
{ {
std::shared_ptr<TimerActor> timerActor = std::shared_ptr<TimerActor>(new TimerActor()); std::shared_ptr<TimerActor> timerActor = std::shared_ptr<TimerActor>(new TimerActor());
actor = timerActor; actor = timerActor;
dialog = new ActorSettingsDialog(timerActor, this); dialog = new ActorSettingsDialog(timerActor, this);
} }
else if(ui->comboBox->currentText() == "Regulator") else if(ui->comboBox->currentText() == "Regulator")
{ {
std::shared_ptr<Regulator> regulator = std::shared_ptr<Regulator>(new Regulator()); std::shared_ptr<Regulator> regulator = std::shared_ptr<Regulator>(new Regulator());
actor = regulator; actor = regulator;
dialog = new ActorSettingsDialog(regulator, this); dialog = new ActorSettingsDialog(regulator, this);
} }
else if(ui->comboBox->currentText() == "Polynomal") else if(ui->comboBox->currentText() == "Polynomal")
{ {
std::shared_ptr<PolynomalActor> polynomalActor = std::shared_ptr<PolynomalActor>(new PolynomalActor()); std::shared_ptr<PolynomalActor> polynomalActor = std::shared_ptr<PolynomalActor>(new PolynomalActor());
actor = polynomalActor; actor = polynomalActor;
dialog = new ActorSettingsDialog(polynomalActor, this); dialog = new ActorSettingsDialog(polynomalActor, this);
} }
if(dialog != nullptr) if(dialog != nullptr)
{ {
dialog->setParent(this); dialog->setParent(this);
dialog->show(); dialog->show();
if(dialog->exec() == QDialog::Accepted) if(dialog->exec() == QDialog::Accepted)
{ {
actor_->setFactorActor(actor); actor_->setFactorActor(actor);
ui->label_FactorActor->setText(actor->getName()); ui->label_FactorActor->setText(actor->getName());
} }
delete dialog; delete dialog;
} }
} }
void FactorActorWidget::setDirection(const QString& type) void FactorActorWidget::setDirection(const QString& type)
{ {
if(type == "True") actor_->setFactorDirection(true); if(type == "True") actor_->setFactorDirection(true);
else actor_->setFactorDirection(false); else actor_->setFactorDirection(false);
} }
void FactorActorWidget::setPreCancleTime(int time) void FactorActorWidget::setPreCancleTime(int time)
{ {
actor_->setPreCancleTime(time); actor_->setPreCancleTime(time);
} }

View file

@ -4,28 +4,27 @@
#include <QWidget> #include <QWidget>
#include "../../actors/factoractor.h" #include "../../actors/factoractor.h"
namespace Ui namespace Ui {
{
class FactorActorWidget; class FactorActorWidget;
} }
class FactorActorWidget : public QWidget class FactorActorWidget : public QWidget
{ {
Q_OBJECT Q_OBJECT
std::shared_ptr<MultiFactorActor> actor_; std::shared_ptr<MultiFactorActor> actor_;
public: public:
explicit FactorActorWidget(std::shared_ptr<MultiFactorActor> actor, QWidget *parent = nullptr); explicit FactorActorWidget(std::shared_ptr<MultiFactorActor> actor, QWidget *parent = nullptr);
~FactorActorWidget(); ~FactorActorWidget();
private slots: private slots:
void createFactorActor(); void createFactorActor();
void setDirection(const QString& direction); void setDirection(const QString& direction);
void setPreCancleTime(int time); void setPreCancleTime(int time);
private: private:
Ui::FactorActorWidget *ui; Ui::FactorActorWidget *ui;
}; };
#endif // FACTORACTORWIDGET_H #endif // FACTORACTORWIDGET_H

View file

@ -1,50 +1,48 @@
#include "polynomalactorwidget.h" #include "polynomalactorwidget.h"
#include "ui_polynomalactorwidget.h" #include "ui_polynomalactorwidget.h"
PolynomalActorWidget::PolynomalActorWidget(std::shared_ptr<PolynomalActor> actor, SensorStore* sensors, PolynomalActorWidget::PolynomalActorWidget(std::shared_ptr<PolynomalActor> actor, SensorStore* sensors, QWidget *parent):
QWidget *parent): QWidget(parent),
QWidget(parent), sensors_(sensors),
sensors_(sensors), actor_(actor),
actor_(actor), ui(new Ui::PolynomalActorWidget)
ui(new Ui::PolynomalActorWidget)
{ {
ui->setupUi(this); ui->setupUi(this);
if(sensors)ui->listView->sensorsChanged(*(sensors->getSensors())); if(sensors)ui->listView->sensorsChanged(*(sensors->getSensors()));
else else
{ {
ui->listView->hide(); ui->listView->hide();
ui->label->hide(); ui->label->hide();
} }
double pow3, pow2, pow1, pow0; double pow3, pow2, pow1, pow0;
actor_->getCoeffiancts(pow3, pow2, pow1, pow0); actor_->getCoeffiancts(pow3, pow2, pow1, pow0);
ui->doubleSpinBox_pow0->setValue(pow0); ui->doubleSpinBox_pow0->setValue(pow0);
ui->doubleSpinBox_pow1->setValue(pow1); ui->doubleSpinBox_pow1->setValue(pow1);
ui->doubleSpinBox_pow2->setValue(pow2); ui->doubleSpinBox_pow2->setValue(pow2);
ui->doubleSpinBox_pow3->setValue(pow3); ui->doubleSpinBox_pow3->setValue(pow3);
connect(ui->doubleSpinBox_pow3, &QDoubleSpinBox::editingFinished, this, &PolynomalActorWidget::setPow); connect(ui->doubleSpinBox_pow3, &QDoubleSpinBox::editingFinished, this, &PolynomalActorWidget::setPow);
connect(ui->doubleSpinBox_pow2, &QDoubleSpinBox::editingFinished, this, &PolynomalActorWidget::setPow); connect(ui->doubleSpinBox_pow2, &QDoubleSpinBox::editingFinished, this, &PolynomalActorWidget::setPow);
connect(ui->doubleSpinBox_pow1, &QDoubleSpinBox::editingFinished, this, &PolynomalActorWidget::setPow); connect(ui->doubleSpinBox_pow1, &QDoubleSpinBox::editingFinished, this, &PolynomalActorWidget::setPow);
connect(ui->doubleSpinBox_pow0, &QDoubleSpinBox::editingFinished, this, &PolynomalActorWidget::setPow); connect(ui->doubleSpinBox_pow0, &QDoubleSpinBox::editingFinished, this, &PolynomalActorWidget::setPow);
connect(ui->listView, &SensorListWidget::clicked, this, &PolynomalActorWidget::setSensor); connect(ui->listView, &SensorListWidget::clicked, this, &PolynomalActorWidget::setSensor);
} }
PolynomalActorWidget::~PolynomalActorWidget() PolynomalActorWidget::~PolynomalActorWidget()
{ {
delete ui; delete ui;
} }
void PolynomalActorWidget::setPow() void PolynomalActorWidget::setPow()
{ {
actor_->setCoeffiancts(ui->doubleSpinBox_pow3->value(), ui->doubleSpinBox_pow2->value(), actor_->setCoeffiancts(ui->doubleSpinBox_pow3->value(), ui->doubleSpinBox_pow2->value(), ui->doubleSpinBox_pow1->value(), ui->doubleSpinBox_pow0->value());
ui->doubleSpinBox_pow1->value(), ui->doubleSpinBox_pow0->value());
} }
void PolynomalActorWidget::setSensor(const QModelIndex &index) void PolynomalActorWidget::setSensor(const QModelIndex &index)
{ {
actor_->setSensor(ui->listView->getSensorForIndex(index)); actor_->setSensor(sensors_->getSensors()->at(index.row()));
} }

View file

@ -4,29 +4,27 @@
#include <QWidget> #include <QWidget>
#include "../../actors/polynomalactor.h" #include "../../actors/polynomalactor.h"
namespace Ui namespace Ui {
{
class PolynomalActorWidget; class PolynomalActorWidget;
} }
class PolynomalActorWidget : public QWidget class PolynomalActorWidget : public QWidget
{ {
Q_OBJECT Q_OBJECT
SensorStore* sensors_; SensorStore* sensors_;
std::shared_ptr<PolynomalActor> actor_; std::shared_ptr<PolynomalActor> actor_;
public: public:
explicit PolynomalActorWidget(std::shared_ptr<PolynomalActor> regulator, SensorStore* sensors = nullptr, explicit PolynomalActorWidget(std::shared_ptr<PolynomalActor> regulator, SensorStore* sensors = nullptr, QWidget *parent = nullptr);
QWidget *parent = nullptr); ~PolynomalActorWidget();
~PolynomalActorWidget();
private slots: private slots:
void setPow(); void setPow();
void setSensor(const QModelIndex &index); void setSensor(const QModelIndex &index);
private: private:
Ui::PolynomalActorWidget *ui; Ui::PolynomalActorWidget *ui;
}; };
#endif // POLYNOMALACTORWIDGET_H #endif // POLYNOMALACTORWIDGET_H

View file

@ -132,7 +132,7 @@
<customwidget> <customwidget>
<class>SensorListWidget</class> <class>SensorListWidget</class>
<extends>QListView</extends> <extends>QListView</extends>
<header location="local">ui/sensorlistwidget.h</header> <header location="global">../src/ui/sensorlistwidget.h</header>
</customwidget> </customwidget>
</customwidgets> </customwidgets>
<resources/> <resources/>

View file

@ -4,50 +4,45 @@
RegulatorWdiget::~RegulatorWdiget() RegulatorWdiget::~RegulatorWdiget()
{ {
delete ui; delete ui;
} }
RegulatorWdiget::RegulatorWdiget(std::shared_ptr<Regulator> regulator, SensorStore* sensors, QWidget *parent) : RegulatorWdiget::RegulatorWdiget(std::shared_ptr<Regulator> regulator, SensorStore* sensors, QWidget *parent) :
QWidget(parent), QWidget(parent),
regulator_(regulator), regulator_(regulator),
sensors_(sensors), sensors_(sensors),
ui(new Ui::RegulatorWdiget) ui(new Ui::RegulatorWdiget)
{ {
ui->setupUi(this); ui->setupUi(this);
if(sensors)ui->listView->sensorsChanged(*(sensors->getSensors())); if(sensors)ui->listView->sensorsChanged(*(sensors->getSensors()));
else else
{ {
ui->listView->hide(); ui->listView->hide();
ui->label->hide(); ui->label->hide();
} }
ui->doubleSpinBox_setPoint->setValue(regulator->getSetPoint()); ui->doubleSpinBox_setPoint->setValue(regulator->getSetPoint());
ui->doubleSpinBox_band->setValue(regulator->getBand()); ui->doubleSpinBox_band->setValue(regulator->getBand());
ui->spinBox_safe->setValue(regulator_->getSafeValue());
ui->spinBox_timeout->setValue(regulator_->getTimeout());
connect(ui->listView, &SensorListWidget::clicked, this, &RegulatorWdiget::setSensor); connect(ui->listView, &SensorListWidget::clicked, this, &RegulatorWdiget::setSensor);
connect(ui->doubleSpinBox_setPoint, SIGNAL(valueChanged(double)), this, SLOT(setPoint(double))); connect(ui->doubleSpinBox_setPoint, SIGNAL(valueChanged(double)), this, SLOT(setPoint(double)));
connect(ui->doubleSpinBox_band, SIGNAL(valueChanged(double)), this, SLOT(setBand(double))); connect(ui->doubleSpinBox_band, SIGNAL(valueChanged(double)), this, SLOT(setBand(double)));
connect(ui->spinBox_safe, SIGNAL(valueChanged(int)), regulator_.get(), SLOT(setSafeValue(int)));
connect(ui->spinBox_timeout, SIGNAL(valueChanged(int)), regulator_.get(), SLOT(setTimeout(int)));
} }
void RegulatorWdiget::setPoint(double in) void RegulatorWdiget::setPoint(double in)
{ {
regulator_->setPoint(in); regulator_->setPoint(in);
} }
void RegulatorWdiget::setBand(double band) void RegulatorWdiget::setBand(double band)
{ {
regulator_->setBand(band); regulator_->setBand(band);
} }
void RegulatorWdiget::setSensor(const QModelIndex &index) void RegulatorWdiget::setSensor(const QModelIndex &index)
{ {
regulator_->setSensor(ui->listView->getSensorForIndex(index)); regulator_->setSensor(sensors_->getSensors()->at(index.row()));
setPoint(ui->listView->getSensorForIndex(index).field); setPoint(sensors_->getSensors()->at(index.row()).field);
ui->doubleSpinBox_setPoint->setValue(ui->listView->getSensorForIndex(index).field); ui->doubleSpinBox_setPoint->setValue(sensors_->getSensors()->at(index.row()).field);
} }

View file

@ -4,31 +4,29 @@
#include <QWidget> #include <QWidget>
#include "../../actors/regulator.h" #include "../../actors/regulator.h"
namespace Ui namespace Ui {
{
class RegulatorWdiget; class RegulatorWdiget;
} }
class RegulatorWdiget : public QWidget class RegulatorWdiget : public QWidget
{ {
Q_OBJECT Q_OBJECT
std::shared_ptr<Regulator> regulator_; std::shared_ptr<Regulator> regulator_;
SensorStore* sensors_; SensorStore* sensors_;
public: public:
explicit RegulatorWdiget(std::shared_ptr<Regulator> regulator, SensorStore* sensors = nullptr, explicit RegulatorWdiget(std::shared_ptr<Regulator> regulator, SensorStore* sensors = nullptr, QWidget *parent = nullptr);
QWidget *parent = nullptr); ~RegulatorWdiget();
~RegulatorWdiget();
private slots: private slots:
void setPoint(double in); void setPoint(double in);
void setBand(double band); void setBand(double band);
void setSensor(const QModelIndex &index); void setSensor(const QModelIndex &index);
private: private:
Ui::RegulatorWdiget *ui; Ui::RegulatorWdiget *ui;
}; };
#endif // REGULATORWDIGET_H #endif // REGULATORWDIGET_H

View file

@ -38,8 +38,15 @@
</widget> </widget>
</item> </item>
<item> <item>
<layout class="QGridLayout" name="gridLayout"> <layout class="QHBoxLayout" name="horizontalLayout">
<item row="0" column="1"> <item>
<widget class="QLabel" name="label_3">
<property name="text">
<string>Set Point</string>
</property>
</widget>
</item>
<item>
<widget class="QDoubleSpinBox" name="doubleSpinBox_setPoint"> <widget class="QDoubleSpinBox" name="doubleSpinBox_setPoint">
<property name="minimum"> <property name="minimum">
<double>-9999.989999999999782</double> <double>-9999.989999999999782</double>
@ -49,7 +56,7 @@
</property> </property>
</widget> </widget>
</item> </item>
<item row="0" column="2"> <item>
<widget class="QLabel" name="label_2"> <widget class="QLabel" name="label_2">
<property name="sizePolicy"> <property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Preferred"> <sizepolicy hsizetype="Fixed" vsizetype="Preferred">
@ -62,46 +69,9 @@
</property> </property>
</widget> </widget>
</item> </item>
<item row="1" column="2"> <item>
<widget class="QLabel" name="label_5">
<property name="text">
<string>Timeout</string>
</property>
</widget>
</item>
<item row="0" column="0">
<widget class="QLabel" name="label_3">
<property name="text">
<string>Set Point</string>
</property>
</widget>
</item>
<item row="0" column="3">
<widget class="QDoubleSpinBox" name="doubleSpinBox_band"/> <widget class="QDoubleSpinBox" name="doubleSpinBox_band"/>
</item> </item>
<item row="1" column="0">
<widget class="QLabel" name="label_4">
<property name="text">
<string>Safety Value</string>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QSpinBox" name="spinBox_safe"/>
</item>
<item row="1" column="3">
<widget class="QSpinBox" name="spinBox_timeout">
<property name="suffix">
<string> s</string>
</property>
<property name="maximum">
<number>999999999</number>
</property>
<property name="value">
<number>1800</number>
</property>
</widget>
</item>
</layout> </layout>
</item> </item>
</layout> </layout>
@ -110,7 +80,7 @@
<customwidget> <customwidget>
<class>SensorListWidget</class> <class>SensorListWidget</class>
<extends>QListView</extends> <extends>QListView</extends>
<header location="local">ui/sensorlistwidget.h</header> <header location="global">../src/ui/sensorlistwidget.h</header>
</customwidget> </customwidget>
</customwidgets> </customwidgets>
<resources/> <resources/>

View file

@ -4,51 +4,49 @@
#include <QDebug> #include <QDebug>
SensorActorWidget::SensorActorWidget(std::shared_ptr<SensorActor> sensorActor, SensorStore* sensors, QWidget *parent) : SensorActorWidget::SensorActorWidget(std::shared_ptr<SensorActor> sensorActor, SensorStore* sensors, QWidget *parent) :
QWidget(parent), QWidget(parent),
sensorActor_(sensorActor), sensorActor_(sensorActor),
sensors_(sensors), sensors_(sensors),
ui(new Ui::SensorActorWidget) ui(new Ui::SensorActorWidget)
{ {
ui->setupUi(this); ui->setupUi(this);
if(sensors)ui->listView->sensorsChanged(*(sensors->getSensors())); if(sensors)ui->listView->sensorsChanged(*(sensors->getSensors()));
else else
{ {
ui->listView->hide(); ui->listView->hide();
ui->label->hide(); ui->label->hide();
} }
if(sensorActor_->getSloap() == SensorActor::SLOPE_UP) if(sensorActor_->getSloap() == SensorActor::SLOPE_UP) ui->comboBox_slope->setCurrentIndex(0);
ui->comboBox_slope->setCurrentIndex(0); else if(sensorActor_->getSloap() == SensorActor::SLOPE_DOWN) ui->comboBox_slope->setCurrentIndex(1);
else if(sensorActor_->getSloap() == SensorActor::SLOPE_DOWN) else if(sensorActor_->getSloap() == SensorActor::SLOPE_BOTH) ui->comboBox_slope->setCurrentIndex(2);
ui->comboBox_slope->setCurrentIndex(1);
else if(sensorActor_->getSloap() == SensorActor::SLOPE_BOTH)
ui->comboBox_slope->setCurrentIndex(2);
ui->doubleSpinBox_threshold->setValue(sensorActor_->getThreshold()); ui->doubleSpinBox_threshold->setValue(sensorActor_->getThreshold());
connect(ui->listView, &SensorListWidget::clicked, this, &SensorActorWidget::setSensor); connect(ui->listView, &SensorListWidget::clicked, this, &SensorActorWidget::setSensor);
connect(ui->doubleSpinBox_threshold, SIGNAL(valueChanged(double)), this, SLOT(setThreshold(double))); connect(ui->doubleSpinBox_threshold, SIGNAL(valueChanged(double)), this, SLOT(setThreshold(double)));
connect(ui->comboBox_slope, SIGNAL(currentIndexChanged(int)), this, SLOT(setSlope(int))); connect(ui->comboBox_slope, SIGNAL(currentIndexChanged(int)), this, SLOT(setSlope(int)));
} }
SensorActorWidget::~SensorActorWidget() SensorActorWidget::~SensorActorWidget()
{ {
delete ui; delete ui;
} }
void SensorActorWidget::setThreshold(double in) void SensorActorWidget::setThreshold(double in)
{ {
sensorActor_->setThreshold(in); sensorActor_->setThreshold(in);
} }
void SensorActorWidget::setSlope(int index) void SensorActorWidget::setSlope(int index)
{ {
if(index == 0) sensorActor_->setSloap(SensorActor::SLOPE_UP); if(index == 0) sensorActor_->setSloap(SensorActor::SLOPE_UP);
else if(index == 1) sensorActor_->setSloap(SensorActor::SLOPE_DOWN); else if(index == 1) sensorActor_->setSloap(SensorActor::SLOPE_DOWN);
else if(index == 2) sensorActor_->setSloap(SensorActor::SLOPE_BOTH); else if(index == 2) sensorActor_->setSloap(SensorActor::SLOPE_BOTH);
} }
void SensorActorWidget::setSensor(const QModelIndex &index) void SensorActorWidget::setSensor(const QModelIndex &index)
{ {
sensorActor_->setSensor(ui->listView->getSensorForIndex(index)); sensorActor_->setSensor(sensors_->getSensors()->at(index.row()));
qDebug()<<"Selected "<<sensors_->getSensors()->at(index.row()).name;
} }

View file

@ -5,31 +5,29 @@
#include <QItemSelection> #include <QItemSelection>
#include "../../actors/sensoractor.h" #include "../../actors/sensoractor.h"
namespace Ui namespace Ui {
{
class SensorActorWidget; class SensorActorWidget;
} }
class SensorActorWidget : public QWidget class SensorActorWidget : public QWidget
{ {
Q_OBJECT Q_OBJECT
std::shared_ptr<SensorActor> sensorActor_; std::shared_ptr<SensorActor> sensorActor_;
SensorStore* sensors_; SensorStore* sensors_;
public: public:
explicit SensorActorWidget(std::shared_ptr<SensorActor> sensorActor, SensorStore* sensors = nullptr, explicit SensorActorWidget(std::shared_ptr<SensorActor> sensorActor, SensorStore* sensors = nullptr, QWidget *parent = nullptr);
QWidget *parent = nullptr); ~SensorActorWidget();
~SensorActorWidget();
private slots: private slots:
void setThreshold(double in); void setThreshold(double in);
void setSlope(int index); void setSlope(int index);
void setSensor(const QModelIndex &index); void setSensor(const QModelIndex &index);
private: private:
Ui::SensorActorWidget *ui; Ui::SensorActorWidget *ui;
}; };
#endif // SENSORACTORWIDGET_H #endif // SENSORACTORWIDGET_H

View file

@ -89,7 +89,7 @@
<customwidget> <customwidget>
<class>SensorListWidget</class> <class>SensorListWidget</class>
<extends>QListView</extends> <extends>QListView</extends>
<header location="local">ui/sensorlistwidget.h</header> <header location="global">../src/ui/sensorlistwidget.h</header>
</customwidget> </customwidget>
</customwidgets> </customwidgets>
<resources/> <resources/>

View file

@ -4,17 +4,17 @@
#include <QSpinBox> #include <QSpinBox>
TimerActorWidget::TimerActorWidget(std::shared_ptr<TimerActor> actor, QWidget *parent) : TimerActorWidget::TimerActorWidget(std::shared_ptr<TimerActor> actor, QWidget *parent) :
QWidget(parent), QWidget(parent),
ui(new Ui::TimerActorWidget) ui(new Ui::TimerActorWidget)
{ {
ui->setupUi(this); ui->setupUi(this);
ui->spinBox->setValue(actor->getTimeout()); ui->spinBox->setValue(actor->getTimeout());
connect(ui->spinBox, SIGNAL(valueChanged(int)), actor.get(), SLOT(setTimeout(int))); connect(ui->spinBox, SIGNAL(valueChanged(int)), actor.get(), SLOT(setTimeout(int)));
} }
TimerActorWidget::~TimerActorWidget() TimerActorWidget::~TimerActorWidget()
{ {
delete ui; delete ui;
} }

View file

@ -4,21 +4,20 @@
#include <QWidget> #include <QWidget>
#include "../../actors/timeractor.h" #include "../../actors/timeractor.h"
namespace Ui namespace Ui {
{
class TimerActorWidget; class TimerActorWidget;
} }
class TimerActorWidget : public QWidget class TimerActorWidget : public QWidget
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit TimerActorWidget(std::shared_ptr<TimerActor> actor, QWidget *parent = nullptr); explicit TimerActorWidget(std::shared_ptr<TimerActor> actor, QWidget *parent = nullptr);
~TimerActorWidget(); ~TimerActorWidget();
private: private:
Ui::TimerActorWidget *ui; Ui::TimerActorWidget *ui;
}; };
#endif // TIMERACTORWIDGET_H #endif // TIMERACTORWIDGET_H

View file

@ -5,49 +5,49 @@
#include "itemsettingswidgets/systemitemsettingswidget.h" #include "itemsettingswidgets/systemitemsettingswidget.h"
ItemCreationDialog::ItemCreationDialog(QWidget *parent) : ItemCreationDialog::ItemCreationDialog(QWidget *parent) :
QDialog(parent), QDialog(parent),
ui(new Ui::ItemCreationDialog) ui(new Ui::ItemCreationDialog)
{ {
ui->setupUi(this); ui->setupUi(this);
std::shared_ptr<MessageItem> messageItem(new MessageItem); std::shared_ptr<MessageItem> messageItem(new MessageItem);
item = messageItem; item = messageItem;
widget = new MessageItemSettingsWidget(messageItem, this); widget = new MessageItemSettingsWidget(messageItem, this);
ui->verticalLayout->addWidget(widget); ui->verticalLayout->addWidget(widget);
connect(ui->comboBox, &QComboBox::currentTextChanged, this, &ItemCreationDialog::itemTypeChanged); connect(ui->comboBox, &QComboBox::currentTextChanged, this, &ItemCreationDialog::itemTypeChanged);
connect(ui->lineEdit, &QLineEdit::textChanged, this, &ItemCreationDialog::itemNameChanged); connect(ui->lineEdit, &QLineEdit::textChanged, this, &ItemCreationDialog::itemNameChanged);
} }
ItemCreationDialog::~ItemCreationDialog() ItemCreationDialog::~ItemCreationDialog()
{ {
delete ui; delete ui;
delete widget; delete widget;
} }
void ItemCreationDialog::itemTypeChanged(const QString& type) void ItemCreationDialog::itemTypeChanged(const QString& type)
{ {
ui->verticalLayout->removeWidget(widget); ui->verticalLayout->removeWidget(widget);
delete widget; delete widget;
if(type == "Message") if(type == "Message")
{ {
std::shared_ptr<MessageItem> messageItem(new MessageItem); std::shared_ptr<MessageItem> messageItem(new MessageItem);
item = messageItem; item = messageItem;
widget = new MessageItemSettingsWidget(messageItem, this); widget = new MessageItemSettingsWidget(messageItem, this);
ui->verticalLayout->addWidget(widget); ui->verticalLayout->addWidget(widget);
} }
if(type == "System") if(type == "System")
{ {
std::shared_ptr<SystemItem> systemItem(new SystemItem); std::shared_ptr<SystemItem> systemItem(new SystemItem);
item = systemItem; item = systemItem;
widget = new SystemItemSettingsWidget(systemItem, this); widget = new SystemItemSettingsWidget(systemItem, this);
ui->verticalLayout->addWidget(widget); ui->verticalLayout->addWidget(widget);
} }
} }
void ItemCreationDialog::itemNameChanged(const QString& name) void ItemCreationDialog::itemNameChanged(const QString& name)
{ {
if(item) if(item)
{ {
item->setName(name); item->setName(name);
} }
} }

View file

@ -5,30 +5,29 @@
#include <memory> #include <memory>
#include "../items/item.h" #include "../items/item.h"
namespace Ui namespace Ui {
{
class ItemCreationDialog; class ItemCreationDialog;
} }
class ItemCreationDialog : public QDialog class ItemCreationDialog : public QDialog
{ {
Q_OBJECT Q_OBJECT
QWidget* widget; QWidget* widget;
public: public:
explicit ItemCreationDialog(QWidget *parent = nullptr); explicit ItemCreationDialog(QWidget *parent = nullptr);
~ItemCreationDialog(); ~ItemCreationDialog();
std::shared_ptr<Item> item; std::shared_ptr<Item> item;
private slots: private slots:
void itemTypeChanged(const QString& type); void itemTypeChanged(const QString& type);
void itemNameChanged(const QString& name); void itemNameChanged(const QString& name);
private: private:
Ui::ItemCreationDialog *ui; Ui::ItemCreationDialog *ui;
}; };
#endif // ITEMCREATIONDIALOG_H #endif // ITEMCREATIONDIALOG_H

View file

@ -4,43 +4,52 @@
#include "../items/messageitem.h" #include "../items/messageitem.h"
ItemScrollBox::ItemScrollBox(QWidget *parent) : ItemScrollBox::ItemScrollBox(QWidget *parent) :
QWidget(parent), QWidget(parent),
ui(new Ui::RelayScrollBox) ui(new Ui::RelayScrollBox)
{ {
ui->setupUi(this); ui->setupUi(this);
QScroller::grabGesture(ui->scrollArea, QScroller::TouchGesture); QScroller::grabGesture(ui->scrollArea, QScroller::TouchGesture);
QScroller::grabGesture(ui->scrollArea, QScroller::LeftMouseButtonGesture); QScroller::grabGesture(ui->scrollArea, QScroller::LeftMouseButtonGesture);
} }
ItemScrollBox::~ItemScrollBox() ItemScrollBox::~ItemScrollBox()
{ {
delete ui; delete ui;
} }
void ItemScrollBox::addItem(std::weak_ptr<Item> item) void ItemScrollBox::addItem(std::weak_ptr<Item> item)
{ {
if(auto workItem = item.lock()) if(auto workItem = item.lock())
{ {
if(workItem->isHidden()) if(dynamic_cast<AuxItem*>(workItem.get()))
return; {
widgets_.push_back(new ItemWidget(item)); widgets_.push_back(new ItemWidget(item, true));
ui->relayWidgetVbox->addWidget(widgets_.back()); }
connect(widgets_.back(), &ItemWidget::deleteRequest, this, &ItemScrollBox::deleteRequest); else if(dynamic_cast<MessageItem*>(workItem.get()))
connect(widgets_.back(), &ItemWidget::deleteRequest, this, &ItemScrollBox::removeItem); {
} widgets_.push_back(new ItemWidget(item, false, true));
}
else
{
widgets_.push_back(new ItemWidget(item));
}
ui->relayWidgetVbox->addWidget(widgets_.back());
connect(widgets_.back(), &ItemWidget::deleteRequest, this, &ItemScrollBox::deleteRequest);
connect(widgets_.back(), &ItemWidget::deleteRequest, this, &ItemScrollBox::removeItem);
}
} }
void ItemScrollBox::removeItem(const ItemData& item) void ItemScrollBox::removeItem(const ItemData& item)
{ {
for(unsigned i = 0; i < widgets_.size(); i++) for(unsigned i = 0; i < widgets_.size(); i++)
{ {
if(widgets_[i]->controles(item)) if(widgets_[i]->controles(item))
{ {
ui->relayWidgetVbox->removeWidget(widgets_[i]); ui->relayWidgetVbox->removeWidget(widgets_[i]);
delete widgets_[i]; delete widgets_[i];
widgets_.erase(widgets_.begin()+i); widgets_.erase(widgets_.begin()+i);
} }
} }
} }

View file

@ -11,34 +11,33 @@
#include "../items/itemstore.h" #include "../items/itemstore.h"
namespace Ui namespace Ui {
{
class RelayScrollBox; class RelayScrollBox;
} }
class ItemScrollBox : public QWidget class ItemScrollBox : public QWidget
{ {
Q_OBJECT Q_OBJECT
private: private:
std::vector< ItemWidget* > widgets_; std::vector< ItemWidget* > widgets_;
signals: signals:
void deleteRequest(const ItemData& item); void deleteRequest(const ItemData& item);
public: public:
explicit ItemScrollBox(QWidget *parent = nullptr); explicit ItemScrollBox(QWidget *parent = nullptr);
~ItemScrollBox(); ~ItemScrollBox();
void setItemStore(ItemStore* itemStore); void setItemStore(ItemStore* itemStore);
public slots: public slots:
void addItem(std::weak_ptr<Item> item); void addItem(std::weak_ptr<Item> item);
void removeItem(const ItemData& item); void removeItem(const ItemData& item);
private: private:
Ui::RelayScrollBox *ui; Ui::RelayScrollBox *ui;
}; };
#endif // RELAYSCROLLBOX_H #endif // RELAYSCROLLBOX_H

View file

@ -1,4 +1,4 @@
#include "itemsettingsdialog.h" #include "itemsettingsdialog.h"
#include "ui_itemsettingsdialog.h" #include "ui_itemsettingsdialog.h"
#include "actorsettingsdialog.h" #include "actorsettingsdialog.h"
#include "../actors/alarmtime.h" #include "../actors/alarmtime.h"
@ -8,180 +8,180 @@
#include "../actors/factoractor.h" #include "../actors/factoractor.h"
#include "../items/messageitem.h" #include "../items/messageitem.h"
#include "../items/systemitem.h" #include "../items/systemitem.h"
#include "itemsettingswidgets/messageitemsettingswidget.h" #include "./itemsettingswidgets/messageitemsettingswidget.h"
#include "itemsettingswidgets/systemitemsettingswidget.h" #include "./itemsettingswidgets/systemitemsettingswidget.h"
#include "itemsettingswidgets/relayitemsettingswidget.h" #include "./itemsettingswidgets/relayitemsettingswidget.h"
#include<memory> #include<memory>
ItemSettingsDialog::ItemSettingsDialog(std::shared_ptr<Item> item, QWidget *parent) : ItemSettingsDialog::ItemSettingsDialog(std::shared_ptr<Item> item, QWidget *parent) :
QDialog(parent), QDialog(parent),
item_(item), item_(item),
ui(new Ui::ItemSettingsDialog) ui(new Ui::ItemSettingsDialog)
{ {
ui->setupUi(this); ui->setupUi(this);
setModal(false); setModal(false);
ui->label_name->setText(item_->getName()); ui->label_name->setText(item_->getName());
ui->checkBox_Override->setChecked(item_->getOverride()); ui->checkBox_Override->setChecked(item_->getOverride());
if(std::shared_ptr<Relay> relay = std::dynamic_pointer_cast<Relay>(item_)) if(std::shared_ptr<Relay> relay = std::dynamic_pointer_cast<Relay>(item_))
{ {
itemSpecificWidget_ = new RelayItemSettingsWidget(relay); itemSpecificWidget_ = new RelayItemSettingsWidget(relay);
} }
else if(std::shared_ptr<MessageItem> msgItem = std::dynamic_pointer_cast<MessageItem>(item_)) else if(std::shared_ptr<MessageItem> msgItem = std::dynamic_pointer_cast<MessageItem>(item_))
{ {
itemSpecificWidget_ = new MessageItemSettingsWidget(msgItem); itemSpecificWidget_ = new MessageItemSettingsWidget(msgItem);
} }
else if(std::shared_ptr<SystemItem> sysItem = std::dynamic_pointer_cast<SystemItem>(item_)) else if(std::shared_ptr<SystemItem> sysItem = std::dynamic_pointer_cast<SystemItem>(item_))
{ {
itemSpecificWidget_ = new SystemItemSettingsWidget(sysItem); itemSpecificWidget_ = new SystemItemSettingsWidget(sysItem);
} }
if(itemSpecificWidget_) if(itemSpecificWidget_)
{ {
ui->verticalLayout_2->addWidget(itemSpecificWidget_); ui->verticalLayout_2->addWidget(itemSpecificWidget_);
} }
connect(ui->pushButton_add, &QPushButton::clicked, this, &ItemSettingsDialog::addActor); connect(ui->pushButton_add, &QPushButton::clicked, this, &ItemSettingsDialog::addActor);
connect(ui->pushButton_remove, &QPushButton::clicked, this, &ItemSettingsDialog::removeActor); connect(ui->pushButton_remove, &QPushButton::clicked, this, &ItemSettingsDialog::removeActor);
connect(ui->pushButton_edit, &QPushButton::clicked, this, &ItemSettingsDialog::editActor); connect(ui->pushButton_edit, &QPushButton::clicked, this, &ItemSettingsDialog::editActor);
connect(ui->checkBox_Override, &QPushButton::clicked, this, &ItemSettingsDialog::changeOverride); connect(ui->checkBox_Override, &QPushButton::clicked, this, &ItemSettingsDialog::changeOverride);
ui->tableWidget->setHorizontalHeaderItem(0, new QTableWidgetItem("Actor")); ui->tableWidget->setHorizontalHeaderItem(0, new QTableWidgetItem("Actor"));
ui->tableWidget->setHorizontalHeaderItem(1, new QTableWidgetItem("Action")); ui->tableWidget->setHorizontalHeaderItem(1, new QTableWidgetItem("Action"));
ui->tableWidget->setHorizontalHeaderItem(2, new QTableWidgetItem("Enabled")); ui->tableWidget->setHorizontalHeaderItem(2, new QTableWidgetItem("Enabled"));
ui->tableWidget->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch); ui->tableWidget->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
ui->tableWidget->horizontalHeader()->resizeSection(1, 60); ui->tableWidget->horizontalHeader()->resizeSection(1, 60);
ui->tableWidget->horizontalHeader()->resizeSection(2, 75); ui->tableWidget->horizontalHeader()->resizeSection(2, 75);
loadActorList(); loadActorList();
} }
ItemSettingsDialog::~ItemSettingsDialog() ItemSettingsDialog::~ItemSettingsDialog()
{ {
if(itemSpecificWidget_) delete itemSpecificWidget_; if(itemSpecificWidget_) delete itemSpecificWidget_;
delete ui; delete ui;
} }
void ItemSettingsDialog::changeOverride() void ItemSettingsDialog::changeOverride()
{ {
item_->setOverride(ui->checkBox_Override->isChecked()); item_->setOverride(ui->checkBox_Override->isChecked());
} }
void ItemSettingsDialog::loadActorList() void ItemSettingsDialog::loadActorList()
{ {
//ui->listWidget->clear(); //ui->listWidget->clear();
ui->tableWidget->setRowCount(item_->getActors().size()); ui->tableWidget->setRowCount(item_->getActors().size());
for(unsigned i = 0; i < item_->getActors().size(); i++) for(unsigned i = 0; i < item_->getActors().size(); i++)
{ {
ui->tableWidget->setItem(i, 0, new QTableWidgetItem(item_->getActors()[i]->getName())); ui->tableWidget->setItem(i, 0, new QTableWidgetItem(item_->getActors()[i]->getName()));
ui->tableWidget->setItem(i, 1, new QTableWidgetItem(item_->getActors()[i]->actionName())); ui->tableWidget->setItem(i, 1, new QTableWidgetItem(item_->getActors()[i]->actionName()));
ui->tableWidget->setItem(i, 2, new QTableWidgetItem(item_->getActors()[i]->isActive() ? "Y" : "N")); ui->tableWidget->setItem(i, 2, new QTableWidgetItem(item_->getActors()[i]->isActive() ? "Y" : "N"));
} }
} }
void ItemSettingsDialog::addActor() void ItemSettingsDialog::addActor()
{ {
ActorSettingsDialog* dialog = nullptr; ActorSettingsDialog* dialog = nullptr;
std::shared_ptr<Actor> actor = nullptr; std::shared_ptr<Actor> actor = nullptr;
if(ui->comboBox->currentText() == "Alarm") if(ui->comboBox->currentText() == "Alarm")
{ {
std::shared_ptr<AlarmTime> alarm = std::shared_ptr<AlarmTime>(new AlarmTime); std::shared_ptr<AlarmTime> alarm = std::shared_ptr<AlarmTime>(new AlarmTime);
actor = alarm; actor = alarm;
dialog = new ActorSettingsDialog(alarm, this); dialog = new ActorSettingsDialog(alarm, this);
} }
else if(ui->comboBox->currentText() == "Sensor") else if(ui->comboBox->currentText() == "Sensor")
{ {
std::shared_ptr<SensorActor> sensorActor = std::shared_ptr<SensorActor>(new SensorActor); std::shared_ptr<SensorActor> sensorActor = std::shared_ptr<SensorActor>(new SensorActor);
actor = sensorActor; actor = sensorActor;
dialog = new ActorSettingsDialog(sensorActor, this); dialog = new ActorSettingsDialog(sensorActor, this);
} }
else if(ui->comboBox->currentText() == "Timer" ) else if(ui->comboBox->currentText() == "Timer" )
{ {
std::shared_ptr<TimerActor> timerActor = std::shared_ptr<TimerActor>(new TimerActor); std::shared_ptr<TimerActor> timerActor = std::shared_ptr<TimerActor>(new TimerActor);
actor = timerActor; actor = timerActor;
dialog = new ActorSettingsDialog(timerActor, this); dialog = new ActorSettingsDialog(timerActor, this);
} }
else if(ui->comboBox->currentText() == "Regulator") else if(ui->comboBox->currentText() == "Regulator")
{ {
std::shared_ptr<Regulator> regulator = std::shared_ptr<Regulator>(new Regulator); std::shared_ptr<Regulator> regulator = std::shared_ptr<Regulator>(new Regulator);
actor = regulator; actor = regulator;
dialog = new ActorSettingsDialog(regulator, this); dialog = new ActorSettingsDialog(regulator, this);
} }
else if(ui->comboBox->currentText() == "Polynomal") else if(ui->comboBox->currentText() == "Polynomal")
{ {
std::shared_ptr<PolynomalActor> polynomalActor = std::shared_ptr<PolynomalActor>(new PolynomalActor); std::shared_ptr<PolynomalActor> polynomalActor = std::shared_ptr<PolynomalActor>(new PolynomalActor);
actor = polynomalActor; actor = polynomalActor;
dialog = new ActorSettingsDialog(polynomalActor, this); dialog = new ActorSettingsDialog(polynomalActor, this);
} }
else if(ui->comboBox->currentText() == "Multi Factor") else if(ui->comboBox->currentText() == "Multi Factor")
{ {
std::shared_ptr<MultiFactorActor> polynomalActor = std::shared_ptr<MultiFactorActor>(new MultiFactorActor); std::shared_ptr<MultiFactorActor> polynomalActor = std::shared_ptr<MultiFactorActor>(new MultiFactorActor);
actor = polynomalActor; actor = polynomalActor;
dialog = new ActorSettingsDialog(polynomalActor, this); dialog = new ActorSettingsDialog(polynomalActor, this);
} }
if(dialog != nullptr) if(dialog != nullptr)
{ {
dialog->setParent(this); dialog->setParent(this);
dialog->show(); dialog->show();
if(dialog->exec() == QDialog::Accepted) if(dialog->exec() == QDialog::Accepted)
{ {
item_->addActor(actor); item_->addActor(actor);
loadActorList(); loadActorList();
} }
delete dialog; delete dialog;
} }
} }
void ItemSettingsDialog::removeActor() void ItemSettingsDialog::removeActor()
{ {
if(item_->getActors().size() > static_cast<size_t>(ui->tableWidget->currentRow())) if(item_->getActors().size() > ui->tableWidget->currentRow())
{ {
item_->removeActor(item_->getActors().at(ui->tableWidget->currentRow())); item_->removeActor(item_->getActors().at(ui->tableWidget->currentRow()));
loadActorList(); loadActorList();
} }
} }
void ItemSettingsDialog::editActor() void ItemSettingsDialog::editActor()
{ {
if(item_->getActors().size() > static_cast<size_t>(ui->tableWidget->currentRow())) if(item_->getActors().size() > ui->tableWidget->currentRow())
{ {
std::shared_ptr<Actor> actor = item_->getActors()[ui->tableWidget->currentRow()]; std::shared_ptr<Actor> actor = item_->getActors()[ui->tableWidget->currentRow()];
std::shared_ptr<AlarmTime> alarmTime = std::dynamic_pointer_cast<AlarmTime>(actor); std::shared_ptr<AlarmTime> alarmTime = std::dynamic_pointer_cast<AlarmTime>(actor);
std::shared_ptr<Regulator> regulator = std::dynamic_pointer_cast<Regulator>(actor); std::shared_ptr<Regulator> regulator = std::dynamic_pointer_cast<Regulator>(actor);
std::shared_ptr<SensorActor> sensorActor = std::dynamic_pointer_cast<SensorActor>(actor); std::shared_ptr<SensorActor> sensorActor = std::dynamic_pointer_cast<SensorActor>(actor);
std::shared_ptr<TimerActor> timerActor = std::dynamic_pointer_cast<TimerActor>(actor); std::shared_ptr<TimerActor> timerActor = std::dynamic_pointer_cast<TimerActor>(actor);
std::shared_ptr<PolynomalActor> polynomalActor = std::dynamic_pointer_cast<PolynomalActor>(actor); std::shared_ptr<PolynomalActor> polynomalActor = std::dynamic_pointer_cast<PolynomalActor>(actor);
std::shared_ptr<MultiFactorActor> factorActor = std::dynamic_pointer_cast<MultiFactorActor>(actor); std::shared_ptr<MultiFactorActor> factorActor = std::dynamic_pointer_cast<MultiFactorActor>(actor);
ActorSettingsDialog* dialog; ActorSettingsDialog* dialog;
if(alarmTime) dialog = new ActorSettingsDialog(alarmTime, this); if(alarmTime) dialog = new ActorSettingsDialog(alarmTime, this);
else if(regulator) dialog = new ActorSettingsDialog(regulator, this); else if(regulator) dialog = new ActorSettingsDialog(regulator, this);
else if(sensorActor) dialog = new ActorSettingsDialog(sensorActor, this); else if(sensorActor) dialog = new ActorSettingsDialog(sensorActor, this);
else if(timerActor) dialog = new ActorSettingsDialog(timerActor, this); else if(timerActor) dialog = new ActorSettingsDialog(timerActor, this);
else if(polynomalActor) dialog = new ActorSettingsDialog(polynomalActor, this); else if(polynomalActor) dialog = new ActorSettingsDialog(polynomalActor, this);
else if(factorActor) dialog = new ActorSettingsDialog(factorActor, this); else if(factorActor) dialog = new ActorSettingsDialog(factorActor, this);
else dialog = new ActorSettingsDialog(actor, this); else dialog = new ActorSettingsDialog(actor, this);
dialog->setParent(this); dialog->setParent(this);
dialog->show(); dialog->show();
dialog->exec(); dialog->exec();
for(int i = 0; i < ui->tableWidget->rowCount() && i < static_cast<int>(item_->getActors().size()); ++i) for(int i = 0; i < ui->tableWidget->rowCount() && i < item_->getActors().size(); ++i)
{ {
ui->tableWidget->item(i, 0)->setText(item_->getActors()[i]->getName()); ui->tableWidget->item(i, 0)->setText(item_->getActors()[i]->getName());
ui->tableWidget->item(i, 1)->setText(item_->getActors()[i]->actionName()); ui->tableWidget->item(i, 1)->setText(item_->getActors()[i]->actionName());
ui->tableWidget->item(i, 2)->setText(item_->getActors()[i]->isActive() ? "Y" : "N"); ui->tableWidget->item(i, 2)->setText(item_->getActors()[i]->isActive() ? "Y" : "N");
} }
} }
} }

View file

@ -6,33 +6,32 @@
#include <memory> #include <memory>
#include "../items/relay.h" #include "../items/relay.h"
namespace Ui namespace Ui {
{
class ItemSettingsDialog; class ItemSettingsDialog;
} }
class ItemSettingsDialog : public QDialog class ItemSettingsDialog : public QDialog
{ {
Q_OBJECT Q_OBJECT
std::shared_ptr<Item> item_; std::shared_ptr<Item> item_;
QWidget* itemSpecificWidget_ = nullptr; QWidget* itemSpecificWidget_ = nullptr;
private: private:
void loadActorList(); void loadActorList();
public: public:
explicit ItemSettingsDialog(std::shared_ptr<Item> item, QWidget *parent = nullptr); explicit ItemSettingsDialog(std::shared_ptr<Item> item, QWidget *parent = nullptr);
~ItemSettingsDialog(); ~ItemSettingsDialog();
private slots: private slots:
void removeActor(); void removeActor();
void addActor(); void addActor();
void editActor(); void editActor();
void changeOverride(); void changeOverride();
private: private:
Ui::ItemSettingsDialog *ui; Ui::ItemSettingsDialog *ui;
}; };
#endif // RELAYSETTINGSDIALOG_H #endif // RELAYSETTINGSDIALOG_H

Some files were not shown because too many files have changed in this diff Show more