switched from qsettings to json added editng of actors

This commit is contained in:
2019-06-06 21:19:12 +02:00
parent b04fbfb5bc
commit df27b622a0
141 changed files with 4402 additions and 5068 deletions

View File

@ -4,7 +4,9 @@
#
#-------------------------------------------------
QT += core gui widgets network serialport multimedia
QT += core gui widgets network
QT += serialport
TARGET = SHinterface
TEMPLATE = app
@ -15,34 +17,104 @@ TEMPLATE = app
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS
QMAKE_CXXFLAGS += -flto -std=c++17 -O2
SOURCES += \
src/broadcast.cpp \
src/ui/actorwidgets/sensoractorwidget.cpp \
src/ui/actorwidgets/alarmwidget.cpp \
src/ui/actorwidgets/timeractorwidget.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
SOURCES += main.cpp mainwindow.cpp ampmanager.cpp alarmtime.cpp \
microcontroller.cpp \
relaydialog.cpp \
alarmsettingsdialog.cpp \
alarmactions.cpp \
relaywidget.cpp \
actor.cpp \
relay.cpp \
relaymanager.cpp
HEADERS += \
src/broadcast.h \
src/ui/actorwidgets/alarmwidget.h \
src/ui/actorwidgets/sensoractorwidget.h \
src/ui/actorwidgets/timeractorwidget.h \
src/ui/itemwidget.h \
src/ui/itemsettingsdialog.h \
src/ui/itemscrollbox.h \
src/items/poweritem.h \
src/ui/actorwidgets/regulatorwdiget.h
HEADERS += mainwindow.h \
ampmanager.h \
alarmtime.h \
microcontroller.h \
relaydialog.h \
alarmsettingsdialog.h \
alarmactions.h \
relaywidget.h \
actor.h \
relay.h \
relaymanager.h
HEADERS += \
src/ui/actorsettingsdialog.h \
src/ui/mainwindow.h \
src/ui/sensorlistwidget.h
FORMS += mainwindow.ui \
relaydialog.ui \
alarmsettingsdialog.ui \
relaywidget.ui
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/actorsettingsdialog.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

View File

@ -1,6 +0,0 @@
#include "actor.h"
Actor::Actor()
{
}

46
actor.h
View File

@ -1,46 +0,0 @@
#ifndef ACTOR_H
#define ACTOR_H
#include <QObject>
#include <QString>
class Actor : public QObject
{
Q_OBJECT
public:
static const uint8_t ACTION_DEFAULT = 0;
static const uint8_t ACTION_TOGGLE = 1;
static const uint8_t ACTION_ON = 2;
static const uint8_t ACTION_OFF = 3;
static const uint8_t ACTION_TRIGGER_ONLY = 4;
QString name;
protected:
uint8_t action_ = 0;
void performAction();
private:
bool active = false;
signals:
void on();
void off();
void trigger();
void toggle();
public slots:
public:
Actor();
virtual ~Actor();
virtual bool isActive();
virtual bool makeActive();
virtual bool makeInactive();
void setAction(uint8_t action);
};
#endif // ACTOR_H

View File

@ -1,14 +0,0 @@
#include "actorsettingsdialog.h"
#include "ui_actorsettingsdialog.h"
ActorSettingsDialog::ActorSettingsDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::ActorSettingsDialog)
{
ui->setupUi(this);
}
ActorSettingsDialog::~ActorSettingsDialog()
{
delete ui;
}

View File

@ -1,22 +0,0 @@
#ifndef ACTORSETTINGSDIALOG_H
#define ACTORSETTINGSDIALOG_H
#include <QDialog>
namespace Ui {
class ActorSettingsDialog;
}
class ActorSettingsDialog : public QDialog
{
Q_OBJECT
public:
explicit ActorSettingsDialog(QWidget *parent = nullptr);
~ActorSettingsDialog();
private:
Ui::ActorSettingsDialog *ui;
};
#endif // ACTORSETTINGSDIALOG_H

View File

@ -1,71 +0,0 @@
<ui version="4.0">
<author/>
<comment/>
<exportmacro/>
<class>ActorSettingsDialog</class>
<widget class="QDialog" name="ActorSettingsDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>400</width>
<height>300</height>
</rect>
</property>
<property name="windowTitle">
<string>Dialog</string>
</property>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="geometry">
<rect>
<x>30</x>
<y>240</y>
<width>341</width>
<height>32</height>
</rect>
</property>
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
</property>
</widget>
</widget>
<pixmapfunction/>
<resources/>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>ActorSettingsDialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>248</x>
<y>254</y>
</hint>
<hint type="destinationlabel">
<x>157</x>
<y>274</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonBox</sender>
<signal>rejected()</signal>
<receiver>ActorSettingsDialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>316</x>
<y>260</y>
</hint>
<hint type="destinationlabel">
<x>286</x>
<y>274</y>
</hint>
</hints>
</connection>
</connections>
</ui>

View File

@ -1,33 +0,0 @@
#include "alarmactions.h"
#include <QProcess>
#include <QSound>
#include <QProcess>
#include <QTime>
#include <QApplication>
AlarmActions::AlarmActions(QSettings *settings, Microcontroller* micro, QObject *parent) : QObject(parent), _micro(micro), _settings(settings)
{
}
void AlarmActions::syncoff()
{
_settings->sync();
for(unsigned int i = 0; i < _micro->getLastState().size(); i++) _micro->relayOff(i);
QProcess::execute ( "syncoff" );
}
void AlarmActions::Alarm()
{
if(_settings->value("Alarms/alarmSoundFile").toString().size() != 0)_micro->startSunrise();
if(_settings->value("Alarms/alarmSoundFile").toString().size() != 0)
{
_micro->relayOn(0);
QTime dieTime= QTime::currentTime().addSecs(10);
while (QTime::currentTime() < dieTime) QApplication::processEvents(QEventLoop::AllEvents, 100);
QSound::play(_settings->value("Alarms/alarmSoundFile").toString());
}
}

View File

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

View File

@ -1,50 +0,0 @@
#include "alarmsettingsdialog.h"
#include "ui_alarmsettingsdialog.h"
#include <QFileDialog>
AlarmSettingsDialog::AlarmSettingsDialog(AlarmTime* almNight, AlarmTime* almAlarm, QSettings* settings, QWidget *parent): QDialog(parent), ui(new Ui::AlarmSettingsDialog), almNight_(almNight), almAlarm_(almAlarm), settings_(settings)
{
ui->setupUi(this);
//restore settings
ui->checkBox_Alarm->setChecked(settings_->value("Alarms/alarmOn").toBool());
ui->checkBox_Sunrise->setChecked(settings_->value("Alarms/sunrise").toBool());
ui->timeEdit_Shutdown->setTime(settings_->value("Alarms/shutdownTime").toTime());
ui->timeEdit_Alarm->setTime(settings_->value("Alarms/alarmTime").toTime());
ui->lineEdit->setText(settings_->value("Alarms/alarmSoundFile").toString());
connect(ui->pushButton_changeFile, SIGNAL(clicked()), this, SLOT(showFileChooser()));
}
AlarmSettingsDialog::~AlarmSettingsDialog()
{
delete ui;
}
void AlarmSettingsDialog::accept()
{
//store settings
settings_->setValue("Alarms/alarmOn", ui->checkBox_Alarm->checkState());
settings_->setValue("Alarms/sunrise", ui->checkBox_Sunrise->checkState());
settings_->setValue("Alarms/shutdownTime", ui->timeEdit_Shutdown->time());
settings_->setValue("Alarms/alarmTime", ui->timeEdit_Alarm->time());
settings_->setValue("Alarms/alarmSoundFile", ui->lineEdit->text());
//send signals
signalAlarmSoundFile(ui->lineEdit->text());
signalSunrise(ui->checkBox_Sunrise->checkState());
//modify alarm objects
almAlarm_->changeTime(ui->timeEdit_Alarm->time());
almNight_->changeTime(ui->timeEdit_Shutdown->time());
QDialog::accept();
}
void AlarmSettingsDialog::showFileChooser()
{
ui->lineEdit->setText(QFileDialog::getOpenFileName(this));
}

View File

@ -1,43 +0,0 @@
#ifndef ALARMSETTINGSDIALOG_H
#define ALARMSETTINGSDIALOG_H
#include <QDialog>
#include <QTime>
#include <QString>
#include <QSettings>
#include "alarmtime.h"
namespace Ui {
class AlarmSettingsDialog;
}
class AlarmSettingsDialog : public QDialog
{
Q_OBJECT
AlarmTime* almNight_;
AlarmTime* almAlarm_;
QSettings* settings_;
public:
explicit AlarmSettingsDialog(AlarmTime* almNight, AlarmTime* almAlarm, QSettings* settings, QWidget* parent = nullptr);
~AlarmSettingsDialog();
signals:
void signalAlarmSoundFile(QString fileName);
void signalSunrise(bool enabled);
public slots:
void accept();
private slots:
void showFileChooser();
private:
Ui::AlarmSettingsDialog *ui;
};
#endif // ALARMSETTINGSDIALOG_H

View File

@ -1,241 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>AlarmSettingsDialog</class>
<widget class="QDialog" name="AlarmSettingsDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>462</width>
<height>406</height>
</rect>
</property>
<property name="windowTitle">
<string>Dialog</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QGroupBox" name="groupBox">
<property name="title">
<string>Alarm</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<layout class="QHBoxLayout" name="horizontalLayout_alm">
<item>
<widget class="QLabel" name="label_3">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Time</string>
</property>
</widget>
</item>
<item>
<widget class="QTimeEdit" name="timeEdit_Alarm">
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="checkBox_Alarm">
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Enable</string>
</property>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_snd">
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<item>
<widget class="QLabel" name="label">
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Sound File</string>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="lineEdit">
<property name="enabled">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="pushButton_changeFile">
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Change</string>
</property>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_2">
<property name="topMargin">
<number>0</number>
</property>
<item>
<widget class="QLabel" name="label_2">
<property name="text">
<string>Sunrise</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="QCheckBox" name="checkBox_Sunrise">
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Enable</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
</item>
<item>
<widget class="QGroupBox" name="groupBox_2">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="title">
<string>Auto Power off</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout_3">
<item>
<layout class="QHBoxLayout" name="horizontalLayout_4">
<item>
<widget class="QLabel" name="label_4">
<property name="text">
<string>Time</string>
</property>
</widget>
</item>
<item>
<widget class="QTimeEdit" name="timeEdit_Shutdown"/>
</item>
<item>
<widget class="QCheckBox" name="checkBox_Shutdown">
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Enable</string>
</property>
<property name="checked">
<bool>true</bool>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
</item>
<item>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
</property>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>AlarmSettingsDialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>248</x>
<y>254</y>
</hint>
<hint type="destinationlabel">
<x>157</x>
<y>274</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonBox</sender>
<signal>rejected()</signal>
<receiver>AlarmSettingsDialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>316</x>
<y>260</y>
</hint>
<hint type="destinationlabel">
<x>286</x>
<y>274</y>
</hint>
</hints>
</connection>
</connections>
</ui>

View File

@ -1,50 +0,0 @@
#include "alarmtime.h"
AlarmTime::AlarmTime(const QTime time, QObject *parent) : QObject(parent), time_(time)
{
connect(&timer, SIGNAL(timeout()), this, SLOT(doTick()));
timer.setInterval(1000);
}
AlarmTime::~AlarmTime()
{
abort();
}
void AlarmTime::run()
{
abort();
timer.start();
qDebug()<<"Start Alarm Time Manager\n";
}
void AlarmTime::abort()
{
timer.stop();
qDebug()<<"Stop Alarm Time Manager\n";
}
void AlarmTime::doTick()
{
if(time_.hour() == QTime::currentTime().hour() && time_.minute() == QTime::currentTime().minute() && triggerd_==false )
{
qDebug()<<"Trigger\n";
triggerd_=true;
trigger();
}
else if( time_.hour() != QTime::currentTime().hour() ) triggerd_=false;
}
void AlarmTime::changeTime(QTime time)
{
time_=time;
qDebug()<<"Time Changed\n";
}
void AlarmTime::runOrAbort(int state)
{
state ? run() : abort();
}

View File

@ -1,36 +0,0 @@
#ifndef ALARMTIME_H
#define ALARMTIME_H
#include <QTime>
#include <QObject>
#include <QRunnable>
#include <QScopedPointer>
#include <QEventLoop>
#include <QTimer>
#include <QProcess>
#include <QDebug>
class AlarmTime : public QObject, public QRunnable
{
Q_OBJECT
private:
bool triggerd_ = false;
QTime time_;
QTimer timer;
public:
explicit AlarmTime(const QTime time = QTime::currentTime(), QObject *parent = nullptr);
~AlarmTime();
signals:
void trigger();
public slots:
void run();
void abort();
void runOrAbort(int state);
void doTick();
void changeTime(QTime time);
};
#endif // ALARMTIME_H

View File

@ -1,14 +0,0 @@
#include "alarmwidget.h"
#include "ui_alarmwidget.h"
AlarmWidget::AlarmWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::AlarmWidget)
{
ui->setupUi(this);
}
AlarmWidget::~AlarmWidget()
{
delete ui;
}

View File

@ -1,21 +0,0 @@
<ui version="4.0">
<author/>
<comment/>
<exportmacro/>
<class>AlarmWidget</class>
<widget class="QWidget" name="AlarmWidget">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>400</width>
<height>300</height>
</rect>
</property>
<property name="windowTitle">
<string>Form</string>
</property>
</widget>
<pixmapfunction/>
<connections/>
</ui>

View File

@ -1,65 +0,0 @@
#include "ampmanager.h"
AmpManager::AmpManager(Microcontroller *micro, int relayNumber, QObject *parent) : QObject(parent), _micro(micro), _relayNumber(relayNumber)
{
silenceCount = 0;
}
AmpManager::~AmpManager()
{
abort();
}
void AmpManager::run()
{
abort();
arecord.start( "arecord -D front -" );
loop.reset(new QEventLoop);
QTimer timer;
connect(&timer, SIGNAL(timeout()), this, SLOT(doTick()));
timer.setInterval(500);
timer.start();
qDebug()<<"Start Auto Amp Manager\n";
_micro->relayOn(_relayNumber);
relayState = true;
loop->exec();
}
void AmpManager::abort()
{
if (!loop.isNull()){
loop->quit();
}
if(arecord.state() == QProcess::Running)arecord.close();
qDebug()<<"Stop Auto Amp Manager\n";
}
void AmpManager::doTick()
{
if(arecord.state() == QProcess::Running)
{
QByteArray buffer = arecord.readAllStandardOutput();
for(long i = 0; i < buffer.size(); i++)
{
if((uint8_t) buffer.at(i) != 128)
{
silenceCount = 0;
}
}
if(silenceCount > 40 && relayState)
{
std::cout<<"Auto off Amp\n";
_micro->relayOff(_relayNumber);
relayState = false;
}
else if(silenceCount == 0 && !relayState)
{
std::cout<<"Auto on Amp\n";
_micro->relayOn(_relayNumber);
relayState = true;
}
silenceCount ++;
}
}

View File

@ -1,48 +0,0 @@
#ifndef AMPMANAGER_H
#define AMPMANAGER_H
#include <iostream>
#include <QObject>
#include <QRunnable>
#include <QScopedPointer>
#include <QEventLoop>
#include <QTimer>
#include <QProcess>
#include <QByteArray>
#include <QtDebug>
#include "microcontroller.h"
class AmpManager : public QObject
{
Q_OBJECT
public:
explicit AmpManager(Microcontroller *micro, int relayNumber, QObject *parent = nullptr);
~AmpManager();
public slots:
void run();
void abort();
private slots:
void doTick();
private:
QScopedPointer<QEventLoop> loop;
long silenceCount = 0;
Microcontroller *_micro;
int _relayNumber;
QProcess arecord;
bool relayState = false;
};
#endif // AMPMANAGER_H

139
main.cpp
View File

@ -1,139 +0,0 @@
#include <QtWidgets/QApplication>
#include <stdio.h>
#include <QDir>
#include <QDebug>
#include <QString>
#include <QSettings>
#include <QSignalMapper>
#include <QTcpSocket>
#include <QtSerialPort/QtSerialPort>
#include <QtSerialPort/QSerialPortInfo>
#include <QCommandLineParser>
#include "alarmtime.h"
#include "microcontroller.h"
#include "mainwindow.h"
#include "relaydialog.h"
#include "ampmanager.h"
#include "alarmactions.h"
#include "alarmsettingsdialog.h"
#define BAUD QSerialPort::Baud38400
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
//set info
QCoreApplication::setOrganizationName("UVOS");
QCoreApplication::setOrganizationDomain("uvos.xyz");
QCoreApplication::setApplicationName("SHinterface");
QCoreApplication::setApplicationVersion("0.5");
QDir::setCurrent(a.applicationDirPath());
//parse comand line
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 secondaryOption(QStringList() << "e" << "secondary", QCoreApplication::translate("main", "Set if instance is not main instance"));
parser.addOption(secondaryOption);
parser.process(a);
QSettings settings;
//connect to microcontoler
Microcontroller micro;
if(parser.isSet(tcpOption))
{
QTcpSocket* microSocket = new QTcpSocket;
int port = 6856;
if(parser.isSet(portOption)) port = parser.value(portOption).toInt();
QString host("127.0.0.1");
if(parser.isSet(hostOption)) host = parser.value(hostOption);
std::cout<<"connecting to "<<host.toStdString()<<':'<<port<<'\n';
microSocket->connectToHost(host, port, QIODevice::ReadWrite);
if(!microSocket->waitForConnected(1000))
{
std::cout<<"Can not connect to to Server.\n";
return 1;
}
micro.setIODevice(microSocket);
}
else
{
QSerialPort* microPort = new QSerialPort;
if(parser.isSet(portOption)) microPort->setPortName(parser.value(portOption));
else microPort->setPortName("ttyUSB0");
if(parser.isSet(portOption)) microPort->setBaudRate(parser.value(baudOption).toInt());
else microPort->setBaudRate(BAUD);
if(!microPort->open(QIODevice::ReadWrite)) std::cout<<"Can not open serial port "<<microPort->portName().toStdString()<<". Continueing in demo mode"<<'\n';
else micro.setIODevice(microPort);
}
AlarmActions alarmActions(&settings, &micro);
AmpManager amp(&micro, 0);
//Alarms
AlarmTime almNight(settings.value("nightTime").toTime());
AlarmTime almAlarm(settings.value("alarmTime").toTime());
//mainwindow
MainWindow w(&micro, parser.isSet(secondaryOption));
QObject::connect(&micro, SIGNAL(textRecived(QString)), &w, SLOT(changeHeaderLableText(QString)));
QObject::connect(&micro, SIGNAL(relayStateChanged(std::vector<bool>)), &w, SLOT(relayStateChanged(std::vector<bool>)));
QObject::connect(&micro, SIGNAL(auxStateChanged(int)), &w, SLOT(auxStateChanged(int)));
//dialogs
AlarmSettingsDialog alarmDialog(&almNight, &almAlarm, &settings, &w);
RelayDialog relayDialog(&micro, &w);
QObject::connect(&micro, SIGNAL(relayStateChanged(std::vector<bool>)), &relayDialog, SLOT(relayStateChanged(std::vector<bool>)));
if(!parser.isSet(secondaryOption))
{
QObject::connect(&almNight, SIGNAL(trigger()), &alarmActions, SLOT(syncoff()));
QObject::connect(&w, SIGNAL(signalAlmNightChanged(QTime)), &almNight, SLOT(changeTime(QTime)));
QObject::connect(&w, SIGNAL(signalAlmNightStateChanged(int)), &almNight, SLOT(runOrAbort(int)));
almNight.run();
QObject::connect(&almAlarm, &AlarmTime::trigger, &micro, &Microcontroller::startSunrise);
QObject::connect(&w, SIGNAL(signalAlmAlarmChanged(QTime)), &almAlarm, SLOT(changeTime(QTime)));
QObject::connect(&w, SIGNAL(signalAlmAlarmStateChanged(int)), &almAlarm, SLOT(runOrAbort(int)));
almAlarm.run();
//Amplifyer
QObject::connect(&w, SIGNAL(signalAmpOn()), &amp, SLOT(run()));
QObject::connect(&w, SIGNAL(signalAmpOff()), &amp, SLOT(abort()));
QMetaObject::invokeMethod(&amp, "run", Qt::QueuedConnection );
}
//show dialogs
QObject::connect(&w, SIGNAL(showAdvRelayDialog()), &relayDialog, SLOT(show()));
QObject::connect(&w, &MainWindow::showAlmSettingsDialog, &alarmDialog, &AlarmSettingsDialog::show);
QMetaObject::invokeMethod(&micro, "run", Qt::QueuedConnection );
w.show();
return a.exec();
}

View File

@ -1,157 +0,0 @@
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(Microcontroller *micro , bool isRemoteMode , QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),
colorChooser(this),
_micro(micro)
{
ui->setupUi(this);
if(!_micro->connected()) ui->label_serialRecive->setText("No IO Port! Debug only.");
//RGB Leds
connect(ui->presettApply, SIGNAL(clicked()), this, SLOT(slotApplyPreset()));
connect(&colorChooser, SIGNAL(colorSelected(const QColor)), this, SLOT(slotChangedRgb(const QColor)));
connect(ui->button_lightsOn, SIGNAL(clicked()), _micro, SLOT(rgbOn()));
connect(ui->button_lightsOff, SIGNAL(clicked()), _micro, SLOT(rgbOff()));
connect(ui->button_quit, SIGNAL(clicked()), this, SLOT(close()));
connect(ui->button_color, SIGNAL(clicked()), &colorChooser, SLOT(show()));
new QListWidgetItem(tr("Pattern 0 Solid"), ui->listWidget_patern);
new QListWidgetItem(tr("Pattern 1"), ui->listWidget_patern);
new QListWidgetItem(tr("Pattern 2 Alarm"), ui->listWidget_patern);
new QListWidgetItem(tr("Pattern 3"), ui->listWidget_patern);
new QListWidgetItem(tr("Pattern 4 Sunrise"), ui->listWidget_patern);
//Desk light
connect(ui->horizontalSlider_deskLight, &QAbstractSlider::valueChanged, _micro, [this](int value){ _micro->setAuxPwm(value); });
//Relays
_relayCheckBoxes.push_back(ui->checkBox_amp);
_relayCheckBoxes.push_back(ui->checkBox_bspeaker);
_relayCheckBoxes.push_back(ui->checkBox_inf);
_relayCheckBoxes.push_back(ui->checkBox_SolderingIorn);
_relayCheckBoxes.push_back(ui->checkBox_testEquitmpent);
for(unsigned int i = 0; i < _relayCheckBoxes.size(); i++) connect(_relayCheckBoxes[i], SIGNAL(stateChanged(int)), this, SLOT(relayCheckBoxToggeled(int)));
//Amp
if(!isRemoteMode)connect(ui->checkBox_ampAuto, SIGNAL(stateChanged(int)), this, SLOT(slotAmpAutoToggle(int)));
//Bedroom Speakers
if(!isRemoteMode)connect(ui->checkBox_bspeakerAuto, SIGNAL(stateChanged(int)), this, SLOT(slotBSpeakerAutoToggle(int)));
//Infinity Mirror
if(!isRemoteMode)connect(ui->checkBox_infAuto, SIGNAL(stateChanged(int)), this, SLOT(slotInfMirrorAutoToggle(int)));
else remoteMode();
//dialogs
connect(ui->button_advRelay, SIGNAL(clicked()), this, SIGNAL(showAdvRelayDialog()));
connect(ui->pushButton_alarms, SIGNAL(clicked()), this, SIGNAL(showAlmSettingsDialog()));
}
void MainWindow::remoteMode()
{
ui->checkBox_ampAuto->setEnabled(false);
ui->checkBox_ampAuto->setChecked(false);
ui->checkBox_bspeakerAuto->setEnabled(false);
ui->checkBox_amp->setEnabled(true);
ui->checkBox_bspeaker->setEnabled(true);
ui->checkBox_inf->setEnabled(true);
ui->checkBox_inf->setChecked(false);
ui->checkBox_infAuto->setEnabled(false);
ui->checkBox_infAuto->setChecked(false);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::slotChangedRgb(const QColor color)
{
_micro->changeRgbColor(color);
if( ui->checkBox_infAuto->isChecked() )
{
if( color.redF() < 0.2 && color.greenF() < 0.2 && color.blueF() > 0.8 )
{
qDebug()<<"Auto turn on inf mirror\n";
_micro->relayOn(2);
}
else _micro->relayOff(2);
}
}
void MainWindow::slotApplyPreset()
{
if(ui->listWidget_patern->selectedItems().count() == 1) _micro->setPattern(ui->listWidget_patern->currentRow());
}
void MainWindow::relayCheckBoxToggeled(int state)
{
for(unsigned int i = 0; i < _relayCheckBoxes.size(); i++)
if(_relayCheckBoxes[i] == sender()) _micro->relayToggle(state, i);
}
void MainWindow::relayStateChanged(std::vector<bool> relayStates)
{
if(relayStates.size() >= 4) for(unsigned int i = 0; i < _relayCheckBoxes.size(); i++)
{
_relayCheckBoxes[i]->blockSignals(true);
_relayCheckBoxes[i]->setChecked(relayStates[i]);
_relayCheckBoxes[i]->blockSignals(false);
}
}
void MainWindow::slotBSpeakerAutoToggle(int state)
{
ui->checkBox_bspeaker->setEnabled(!state);
}
void MainWindow::slotDoorOpenTimeout()
{
//ui->checkBox_doorOpen->setChecked(true);
}
void MainWindow::slotInfMirrorAutoToggle(int state)
{
ui->checkBox_inf->setEnabled(!state);
if(!state)
{
_micro->relayToggle(ui->checkBox_inf->isChecked(), 2);
}
}
void MainWindow::auxStateChanged(int value)
{
ui->horizontalSlider_deskLight->blockSignals(true);
ui->horizontalSlider_deskLight->setValue(value);
ui->horizontalSlider_deskLight->blockSignals(false);
}
void MainWindow::slotAmpAutoToggle(int state)
{
ui->checkBox_amp->setEnabled(!state);
if(state)
{
signalAmpOn();
}
else
{
signalAmpOff();
_micro->relayToggle(ui->checkBox_amp->checkState(), 0);
}
}
void MainWindow::changeHeaderLableText(const QString string)
{
ui->label_serialRecive->setText(string);
}

View File

@ -1,74 +0,0 @@
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QColorDialog>
#include <QListWidgetItem>
#include <QTime>
#include <vector>
#include "alarmtime.h"
#include "microcontroller.h"
namespace Ui
{
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(Microcontroller *micro, bool isRemoteMode = false, QWidget *parent = nullptr);
~MainWindow();
private:
Ui::MainWindow *ui;
QColorDialog colorChooser;
Microcontroller *_micro;
std::vector<QAbstractButton*> _relayCheckBoxes;
void remoteMode();
signals:
void signalAmpOn();
void signalAmpOff();
void showAlmSettingsDialog();
void showAdvRelayDialog();
private slots:
//RGB
void slotChangedRgb(const QColor color);
void slotApplyPreset();
void changeHeaderLableText(const QString string);
//relays
void relayCheckBoxToggeled(int state);
//Automation
void slotAmpAutoToggle(int state);
void slotBSpeakerAutoToggle(int state);
void slotInfMirrorAutoToggle(int state);
//door
void slotDoorOpenTimeout();
public slots:
void relayStateChanged(std::vector<bool> relayStates);
void auxStateChanged(int value);
};
#endif // MAINWINDOW_H

View File

@ -1,539 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>862</width>
<height>570</height>
</rect>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>50</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>600</width>
<height>197</height>
</size>
</property>
<property name="windowTitle">
<string>Smart Home Interface</string>
</property>
<property name="windowIcon">
<iconset resource="resources.qrc">
<normaloff>:/images/UVOSicon.bmp</normaloff>:/images/UVOSicon.bmp</iconset>
</property>
<widget class="QWidget" name="centralWidget">
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="MinimumExpanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="layoutDirection">
<enum>Qt::LeftToRight</enum>
</property>
<property name="autoFillBackground">
<bool>false</bool>
</property>
<layout class="QHBoxLayout" name="horizontalLayout_10">
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<layout class="QHBoxLayout" name="horizontalLayout_9">
<property name="topMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>10</number>
</property>
<item>
<widget class="QLabel" name="label_serialRecive">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="frameShape">
<enum>QFrame::Box</enum>
</property>
<property name="text">
<string>SHinterface</string>
</property>
</widget>
</item>
</layout>
</item>
<item>
<widget class="QGroupBox" name="groupBox">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="title">
<string>Relays</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout_4">
<item>
<layout class="QHBoxLayout" name="horizontalLayout_6">
<item>
<widget class="QLabel" name="label_7">
<property name="text">
<string>Audio Amp</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_4">
<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="QCheckBox" name="checkBox_amp">
<property name="enabled">
<bool>false</bool>
</property>
<property name="text">
<string>On</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="checkBox_ampAuto">
<property name="text">
<string>Auto</string>
</property>
<property name="checked">
<bool>true</bool>
</property>
</widget>
</item>
</layout>
</item>
<item>
<widget class="Line" name="line_3">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_5">
<item>
<widget class="QLabel" name="label_6">
<property name="text">
<string>Bedroom Speakers</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_5">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QCheckBox" name="checkBox_bspeaker">
<property name="enabled">
<bool>true</bool>
</property>
<property name="text">
<string>On</string>
</property>
<property name="checkable">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="checkBox_bspeakerAuto">
<property name="text">
<string>Auto</string>
</property>
<property name="checked">
<bool>false</bool>
</property>
</widget>
</item>
</layout>
</item>
<item>
<widget class="Line" name="line_2">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_4">
<item>
<widget class="QLabel" name="label_2">
<property name="text">
<string>Infinity Mirror</string>
</property>
</widget>
</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>
<item>
<widget class="QCheckBox" name="checkBox_inf">
<property name="enabled">
<bool>false</bool>
</property>
<property name="text">
<string>On</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="checkBox_infAuto">
<property name="text">
<string>Auto</string>
</property>
<property name="checked">
<bool>true</bool>
</property>
</widget>
</item>
</layout>
</item>
<item>
<widget class="Line" name="line">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_3">
<item>
<widget class="QLabel" name="label">
<property name="text">
<string>Soldering iron</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="QCheckBox" name="checkBox_SolderingIorn">
<property name="text">
<string>On</string>
</property>
</widget>
</item>
</layout>
</item>
<item>
<widget class="Line" name="line_4">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_7">
<item>
<widget class="QLabel" name="label_4">
<property name="text">
<string>Test Equitment</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_6">
<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="QCheckBox" name="checkBox_testEquitmpent">
<property name="text">
<string>On</string>
</property>
</widget>
</item>
</layout>
</item>
<item>
<widget class="QPushButton" name="button_advRelay">
<property name="text">
<string>Advanced</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
</layout>
</item>
</layout>
</item>
<item>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QListWidget" name="listWidget_patern">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>0</width>
<height>0</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>120</height>
</size>
</property>
<property name="baseSize">
<size>
<width>0</width>
<height>50</height>
</size>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<spacer name="horizontalSpacer_3">
<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="presettApply">
<property name="minimumSize">
<size>
<width>128</width>
<height>32</height>
</size>
</property>
<property name="text">
<string>Apply</string>
</property>
</widget>
</item>
</layout>
</item>
<item>
<widget class="QPushButton" name="button_color">
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>50</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>0</width>
<height>0</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>80</height>
</size>
</property>
<property name="baseSize">
<size>
<width>0</width>
<height>128</height>
</size>
</property>
<property name="text">
<string>Choose Color</string>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_11">
<property name="topMargin">
<number>10</number>
</property>
<property name="bottomMargin">
<number>10</number>
</property>
<item>
<widget class="QPushButton" name="button_lightsOn">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>50</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>0</width>
<height>48</height>
</size>
</property>
<property name="text">
<string>ON</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="button_lightsOff">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Minimum">
<horstretch>0</horstretch>
<verstretch>50</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>0</width>
<height>48</height>
</size>
</property>
<property name="text">
<string>OFF</string>
</property>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_8">
<item>
<widget class="QLabel" name="label_3">
<property name="text">
<string>Desk Light</string>
</property>
</widget>
</item>
<item>
<widget class="QSlider" name="horizontalSlider_deskLight">
<property name="maximum">
<number>254</number>
</property>
<property name="tracking">
<bool>false</bool>
</property>
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</widget>
</item>
</layout>
</item>
<item>
<spacer name="verticalSpacer_2">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeType">
<enum>QSizePolicy::Preferred</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QPushButton" name="pushButton_alarms">
<property name="text">
<string>Alarms</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="button_quit">
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="layoutDirection">
<enum>Qt::RightToLeft</enum>
</property>
<property name="text">
<string>Quit</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
</widget>
<layoutdefault spacing="6" margin="11"/>
<resources>
<include location="resources.qrc"/>
</resources>
<connections/>
</ui>

View File

@ -1,202 +0,0 @@
#include "microcontroller.h"
//relays
void Microcontroller::relayToggle(int state, int relay)
{
char buffer[8];
int length = sprintf(buffer, "%d \n", relay);
if(_port != nullptr) state ? _port->write("relay on ", sizeof("relay on ")-1) : _port->write("relay off ", sizeof("relay off ")-1);
state ? std::cout<<"relay on " : std::cout<<"relay off ";
std::cout<<buffer;
if(_port != nullptr) _port->write(buffer, length);
}
void Microcontroller::relayOn(int relay)
{
relayToggle(true, relay);
}
void Microcontroller::relayOff(int relay)
{
relayToggle(false, relay);
}
//rgb lights
void Microcontroller::rgbOn()
{
if(_port != nullptr) _port->write("rgb on\n", sizeof("rgb on\n")-1);
}
void Microcontroller::rgbOff()
{
if(_port != nullptr) _port->write( "rgb off\n", sizeof("rgb off\n")-1);
}
void Microcontroller::changeRgbColor(const QColor color)
{
char buffer[64];
int length = sprintf(buffer, "rgb set %03d %03d %03d \n", color.red(), color.green(), color.blue() );
if(_port != nullptr) _port->write(buffer, length);
std::cout<<buffer;
}
void Microcontroller::setAuxPwm(int duty)
{
if(duty != _auxState)
{
if(duty > 1)
{
if(_auxState <= 1 && _port != nullptr) _port->write("aux on\n");
char buffer[64];
int length = sprintf(buffer, "aux set %03d \n", duty );
if(_port != nullptr) _port->write(buffer, length);
}
else if(_port != nullptr)_port->write("aux off\n");
}
_auxState = duty;
}
void Microcontroller::setPattern(int pattern)
{
if(_port != nullptr)
{
char buffer[4];
std::cout<<"pattern apply\n";
_port->write("rgb pattern ", sizeof("rgb pattern ")-1);
int length = sprintf(buffer, "%d \n", pattern);
_port->write(buffer, length);
}
}
void Microcontroller::startSunrise()
{
setPattern(4);
}
bool Microcontroller::connected()
{
if(_port != nullptr) return _port->isOpen();
else return false;
}
void Microcontroller::run()
{
abort();
loop.reset(new QEventLoop);
QTimer timer;
connect(&timer, SIGNAL(timeout()), this, SLOT(doTick()));
timer.setInterval(500);
timer.start();
loop->exec();
}
void Microcontroller::requestState()
{
if(_port != nullptr) _port->write("state\n", sizeof("state\n"));
}
void Microcontroller::requestRelayList()
{
if(_port != nullptr) _port->write("relay list\n", sizeof("relay list\n"));
}
void Microcontroller::abort()
{
if (!loop.isNull())
{
loop->quit();
}
}
std::vector<bool> Microcontroller::getLastState()
{
return _relayStates;
}
//housekeeping
Microcontroller::Microcontroller(QIODevice* port): _port(port)
{
requestState();
}
Microcontroller::Microcontroller()
{
}
Microcontroller::~Microcontroller()
{
if(_port != nullptr) delete _port;
}
void Microcontroller::setIODevice(QIODevice *port)
{
_port = port;
requestState();
}
void Microcontroller::processMicroReturn()
{
QString workbuff = _buffer;
if(_buffer.size() > 2 && _buffer[0] == "S" && _buffer[1] == "T")
{
workbuff.remove(0, 2);
QStringList workbufList = workbuff.split(',');
//aux state
if(workbufList[0].toInt() != _auxState)
{
_auxState = workbufList[0].toInt();
auxStateChanged(_auxState);
}
//relay state
uint_fast8_t numberOfRelays = workbufList[1].toInt();
if(workbufList.size() >= numberOfRelays+2)
{
_relayStates.resize(numberOfRelays, false);
for(uint_fast8_t i = 0; i < numberOfRelays; i++)
{
if(_relayStates[i] != static_cast<bool>(workbufList[i+2].toInt()))
{
_relayStates[i] = static_cast<bool>(workbufList[i+2].toInt());
relayStateChanged(Relay(this, i));
}
}
}
}
else if(workbuff.contains("Door Open Warning"))
{
doorOpenTimeout();
}
else if(workbuff.size() > 2 && workbuff[0]=='D' && workbuff[1]=='2')
{
if(workbuff[3] == 'O') doorOpened(1);
else if(workbuff[3] == 'C') doorClosed(1);
}
}
void Microcontroller::doTick()
{
if(_port != nullptr)
{
char charBuf;
while(_port->getChar(&charBuf))
{
_buffer.push_back(charBuf);
if( _buffer.endsWith('\n') )
{
processMicroReturn();
textRecived(_buffer);
_buffer.clear();
}
}
}
}

View File

@ -1,76 +0,0 @@
#ifndef MICROCONTROLLER_H
#define MICROCONTROLLER_H
#include <iostream>
#include <QObject>
#include <QColor>
#include <QIODevice>
#include <QString>
#include <QRunnable>
#include <QScopedPointer>
#include <QEventLoop>
#include <QTimer>
#include <QAbstractButton>
#include <vector>
#include "relay.h"
class Microcontroller : public QObject
{
Q_OBJECT
public:
static constexpr char AMP_RELAY = 0;
private:
std::vector<bool> _relayStates; //ugh vector of bools
int _auxState = 0;
QIODevice* _port = nullptr;
QScopedPointer<QEventLoop> loop;
QString _buffer;
void processMicroReturn();
void requestState();
public:
Microcontroller(QIODevice* port);
Microcontroller();
~Microcontroller();
bool connected();
void setIODevice(QIODevice* port);
std::vector<bool> getLastState();
public slots:
void rgbOn();
void rgbOff();
void changeRgbColor(const QColor color);
void setPattern(int pattern);
void startSunrise();
void requestRelayList();
void setAuxPwm(int duty);
void relayOn(int relay);
void relayOff(int relay);
void relayToggle(bool state, int id);
void run();
void abort();
void doTick();
signals:
void textRecived(const QString string);
void relayStateChanged(Relay relay);
void auxStateChanged(int value);
void gotRelayList(std::vector<Relay> relays);
void doorOpenTimeout();
void doorOpened(int id);
void doorClosed(int id);
};
#endif // MICROCONTROLLER_H

View File

@ -1,58 +0,0 @@
#include "relay.h"
#include "microcontroller.h"
Relay::Relay(Microcontroller* micro, uint8_t id, QString name, uint16_t address, QObject* parent): QObject(parent), micro_(micro), name_(name), id_(id), address_(address)
{
}
QString Relay::getName()
{
return name_;
}
void Relay::setName(QString name)
{
name_ = name;
}
void Relay::addActor(std::unique_ptr<Actor> actor)
{
actors_.push_back(actor);
connect(actor.get(), &Actor::on, this, &Relay::on);
connect(actor.get(), &Actor::off, this, &Relay::off);
connect(actor.get(), &Actor::toggle, this, &Relay::toggle);
}
std::vector< std::unique_ptr<Actor> >* Relay::getActors()
{
return &actors_;
}
bool Relay::hasActors()
{
return actors_.size() > 0;
}
void Relay::on()
{
micro_->relayOn(id_);
state_ = true;
}
void Relay::off()
{
micro_->relayOn(id_);
state_ = false;
}
void Relay::setState(bool state)
{
state_ = state;
}
void Relay::setActorsActive(bool in)
{
actorsActive_ = true;
for(unsigned i = 0; i < actors_.size(); i++) in ? actors_[i]->makeActive() : actors_[i]->makeInactive();
}

42
relay.h
View File

@ -1,42 +0,0 @@
#ifndef RELAY_H
#define RELAY_H
#include<stdint.h>
#include<QObject>
#include<QString>
#include<vector>
#include<memory>
#include"actor.h"
class Microcontroller;
class Relay : public QObject
{
Q_OBJECT
private:
Microcontroller* micro_;
QString name_;
bool state_ = false;
uint8_t id_;
uint16_t address_;
std::vector< std::unique_ptr<Actor> > actors_;
bool actorsActive_ = true;
public slots:
void on();
void off();
void toggle();
public:
Relay(Microcontroller* micro, uint8_t id, QString name = "", uint16_t address = 0, QObject *parent = nullptr);
void addActor(std::unique_ptr<Actor> actor);
void setState(bool state);
bool hasActors();
void setActorsActive(bool in);
QString getName();
void setName(QString name);
std::vector< std::unique_ptr<Actor> >* getActors();
~Relay();
};
#endif // RELAY_H

View File

@ -1,230 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>RelayDialog</class>
<widget class="QDialog" name="RelayDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>358</width>
<height>320</height>
</rect>
</property>
<property name="windowTitle">
<string>Advanced Relays</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QGroupBox" name="groupBox">
<property name="title">
<string>Advanced</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<layout class="QHBoxLayout" name="horizontalLayout_3">
<item>
<widget class="QLabel" name="label_3">
<property name="text">
<string>3Dator</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_3">
<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="QCheckBox" name="checkBox_R0">
<property name="text">
<string>On</string>
</property>
</widget>
</item>
</layout>
</item>
<item>
<widget class="Line" name="line_4">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_4">
<item>
<widget class="QLabel" name="label_4">
<property name="text">
<string>3040</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_4">
<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="QCheckBox" name="checkBox_R1">
<property name="text">
<string>On</string>
</property>
</widget>
</item>
</layout>
</item>
<item>
<widget class="Line" name="line_5">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<widget class="QLabel" name="label_6">
<property name="text">
<string>Aux</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_6">
<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="QCheckBox" name="checkBox_R2">
<property name="text">
<string>On</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_5">
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<item>
<widget class="QLabel" name="label_5">
<property name="text">
<string>Enterance Watch</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_5">
<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="QCheckBox" name="checkBox">
<property name="text">
<string>Inside</string>
</property>
<property name="checked">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="checkBox_2">
<property name="text">
<string>Watch</string>
</property>
<property name="checked">
<bool>true</bool>
</property>
</widget>
</item>
</layout>
</item>
<item>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Ok</set>
</property>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>RelayDialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>248</x>
<y>254</y>
</hint>
<hint type="destinationlabel">
<x>157</x>
<y>274</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonBox</sender>
<signal>rejected()</signal>
<receiver>RelayDialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>316</x>
<y>260</y>
</hint>
<hint type="destinationlabel">
<x>286</x>
<y>274</y>
</hint>
</hints>
</connection>
</connections>
</ui>

View File

@ -1,14 +0,0 @@
#include "relayscrollbox.h"
#include "ui_relayscrollbox.h"
RelayScrollBox::RelayScrollBox(QWidget *parent) :
QWidget(parent),
ui(new Ui::RelayScrollBox)
{
ui->setupUi(this);
}
RelayScrollBox::~RelayScrollBox()
{
delete ui;
}

View File

@ -1,22 +0,0 @@
#ifndef RELAYSCROLLBOX_H
#define RELAYSCROLLBOX_H
#include <QWidget>
namespace Ui {
class RelayScrollBox;
}
class RelayScrollBox : public QWidget
{
Q_OBJECT
public:
explicit RelayScrollBox(QWidget *parent = nullptr);
~RelayScrollBox();
private:
Ui::RelayScrollBox *ui;
};
#endif // RELAYSCROLLBOX_H

View File

@ -1,21 +0,0 @@
<ui version="4.0">
<author/>
<comment/>
<exportmacro/>
<class>RelayScrollBox</class>
<widget name="RelayScrollBox" class="QWidget">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>400</width>
<height>300</height>
</rect>
</property>
<property name="windowTitle">
<string>Form</string>
</property>
</widget>
<pixmapfunction/>
<connections/>
</ui>

View File

@ -1,14 +0,0 @@
#include "relaysettingsdialog.h"
#include "ui_relaysettingsdialog.h"
RelaySettingsDialog::RelaySettingsDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::RelaySettingsDialog)
{
ui->setupUi(this);
}
RelaySettingsDialog::~RelaySettingsDialog()
{
delete ui;
}

View File

@ -1,22 +0,0 @@
#ifndef RELAYSETTINGSDIALOG_H
#define RELAYSETTINGSDIALOG_H
#include <QDialog>
namespace Ui {
class RelaySettingsDialog;
}
class RelaySettingsDialog : public QDialog
{
Q_OBJECT
public:
explicit RelaySettingsDialog(QWidget *parent = nullptr);
~RelaySettingsDialog();
private:
Ui::RelaySettingsDialog *ui;
};
#endif // RELAYSETTINGSDIALOG_H

View File

@ -1,71 +0,0 @@
<ui version="4.0">
<author/>
<comment/>
<exportmacro/>
<class>RelaySettingsDialog</class>
<widget class="QDialog" name="RelaySettingsDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>400</width>
<height>300</height>
</rect>
</property>
<property name="windowTitle">
<string>Dialog</string>
</property>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="geometry">
<rect>
<x>30</x>
<y>240</y>
<width>341</width>
<height>32</height>
</rect>
</property>
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
</property>
</widget>
</widget>
<pixmapfunction/>
<resources/>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>RelaySettingsDialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>248</x>
<y>254</y>
</hint>
<hint type="destinationlabel">
<x>157</x>
<y>274</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonBox</sender>
<signal>rejected()</signal>
<receiver>RelaySettingsDialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>316</x>
<y>260</y>
</hint>
<hint type="destinationlabel">
<x>286</x>
<y>274</y>
</hint>
</hints>
</connection>
</connections>
</ui>

View File

@ -1,14 +0,0 @@
#include "relaywidget.h"
#include "ui_relaywidget.h"
RelayWidget::RelayWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::RelayWidget)
{
ui->setupUi(this);
}
RelayWidget::~RelayWidget()
{
delete ui;
}

View File

@ -1,22 +0,0 @@
#ifndef RELAYWIDGET_H
#define RELAYWIDGET_H
#include <QWidget>
namespace Ui {
class RelayWidget;
}
class RelayWidget : public QWidget
{
Q_OBJECT
public:
explicit RelayWidget(QWidget *parent = nullptr);
~RelayWidget();
private:
Ui::RelayWidget *ui;
};
#endif // RELAYWIDGET_H

View File

@ -1,62 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>RelayWidget</class>
<widget class="QWidget" name="RelayWidget">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>751</width>
<height>58</height>
</rect>
</property>
<property name="windowTitle">
<string>Form</string>
</property>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QLabel" name="label">
<property name="text">
<string>TextLabel</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="QCheckBox" name="checkBox">
<property name="text">
<string>On</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="checkBox_auto">
<property name="text">
<string>Auto</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="pushButton">
<property name="text">
<string>Settings</string>
</property>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui>

View File

@ -1,67 +0,0 @@
#include "serial_io.h"
struct termios toptions;;
void sWrite(int port, char string[], size_t length)
{
if(port != -1) write(port, string, length);
else std::cout<<string;
}
void sWrite(int port, const char string[], size_t length)
{
if(port != -1) write(port, string, length);
else std::cout<<string;
}
ssize_t sRead(int port, void *buf, size_t count)
{
return (port != -1) ? read(port, buf, count) : 0;
}
int serialport_init()
{
int fd;
system("stty -F /dev/ttyUSB0 38400 sane -echo");
fd = open(DEVICE, O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1)
{
perror("init_serialport: Unable to open port ");
return -1;
}
if (tcgetattr(fd, &toptions) < 0)
{
perror("init_serialport: Couldn't get term attributes");
return -1;
}
speed_t brate = BAUDRATE;
cfsetispeed(&toptions, brate);
cfsetospeed(&toptions, brate);
// 8N1
toptions.c_cflag &= ~PARENB;
toptions.c_cflag &= ~CSTOPB;
toptions.c_cflag &= ~CSIZE;
toptions.c_cflag |= CS8;
// no flow control
toptions.c_cflag &= ~CRTSCTS;
toptions.c_cflag |= CREAD | CLOCAL | IGNPAR; // turn on READ & ignore ctrl lines
toptions.c_iflag &= ~(IXON | IXOFF | IXANY); // turn off s/w flow ctrl
toptions.c_lflag &= ~(ICANON | ISIG | ECHO | ECHOE); // make raw
toptions.c_oflag &= ~OPOST; // make raw
// see: http://unixwiz.net/techtips/termios-vmin-vtime.html
toptions.c_cc[VMIN] = 0;
toptions.c_cc[VTIME] = 20;
fcntl(fd, F_SETFL, FNDELAY);
if( tcsetattr(fd, TCSANOW, &toptions) < 0)
{
perror("init_serialport: Couldn't set term attributes");
return -1;
}
return fd;
}

View File

@ -1,21 +0,0 @@
#ifndef SERIAL_H
#define SERIAL_H
#include <termios.h>
#include <fcntl.h>
#include <unistd.h>
#include <iostream>
#define BAUDRATE B38400
#define DEVICE "/dev/ttyUSB0"
void sWrite(int port, char string[], size_t length);
void sWrite(int port, const char string[], size_t length);
ssize_t sRead(int port, void *buf, size_t count);
int serialport_init();
#endif // SERIAL_H

View File

@ -1,36 +0,0 @@
#include "serialwatcher.h"
void SerialWatcher::run()
{
abort();
loop.reset(new QEventLoop);
QTimer timer;
connect(&timer, SIGNAL(timeout()), this, SLOT(doTick()));
timer.setInterval(500);
timer.start();
loop->exec();
}
void SerialWatcher::abort()
{
if (!loop.isNull()){
loop->quit();
}
}
void SerialWatcher::doTick()
{
char charBuf;
while(sRead(_serial, &charBuf, 1) == 1)
{
_buffer.push_back(charBuf);
if( _buffer.endsWith('\n') )
{
textRecived(_buffer);
_buffer.clear();
}
}
}

View File

@ -1,39 +0,0 @@
#ifndef SERIALWATCHER_H
#define SERIALWATCHER_H
#include "serial_io.h"
#define BUFFER_SIZE 128
#include<QString>
#include<QObject>
#include<QRunnable>
#include<QScopedPointer>
#include<QEventLoop>
#include<QTimer>
class SerialWatcher: public QObject, public QRunnable
{
Q_OBJECT
private:
QScopedPointer<QEventLoop> loop;
int _serial;
QString _buffer;
public:
explicit SerialWatcher(int serial, QObject *parent = 0);
~SerialWatcher();
signals:
void textRecived(const QString string);
public slots:
void run();
void abort();
void doTick();
};
#endif // SERIALWATCHER_H

BIN
src/a.out Executable file

Binary file not shown.

View File

@ -1,41 +0,0 @@
#include "actor.h"
Actor::Actor(QObject *parent): QObject(parent)
{
}
Actor::~Actor()
{
}
void Actor::performAction()
{
trigger();
if(action_ == ACTION_OFF) off();
else if(action_ == ACTION_ON) on();
else if(action_ != ACTION_TRIGGER_ONLY) toggle();
}
void Actor::setActive(int state)
{
state ? makeActive() : makeInactive();
}
bool Actor::isActive()
{
return active;
}
void Actor::setAction(uint8_t action)
{
action_ = action;
}
void Actor::onStateChanged(bool state)
{
}

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

@ -1,45 +0,0 @@
#ifndef ACTOR_H
#define ACTOR_H
#include <QObject>
#include <QString>
class Actor : public QObject
{
Q_OBJECT
public:
static const uint8_t ACTION_DEFAULT = 0;
static const uint8_t ACTION_TOGGLE = 1;
static const uint8_t ACTION_ON = 2;
static const uint8_t ACTION_OFF = 3;
static const uint8_t ACTION_TRIGGER_ONLY = 4;
QString name;
protected:
uint8_t action_ = 0;
bool active = false;
void performAction();
signals:
void on();
void off();
void trigger();
void toggle();
public slots:
virtual void makeActive() = 0;
virtual void makeInactive() = 0;
virtual void setActive(int state);
virtual void onStateChanged(bool state);
public:
Actor(QObject* parent = nullptr);
virtual ~Actor();
bool isActive();
void setAction(uint8_t action);
};
#endif // ACTOR_H

140
src/actors/actor.cpp Normal file
View File

@ -0,0 +1,140 @@
#include "actor.h"
#include<QDebug>
#include "alarmtime.h"
#include "sensoractor.h"
#include "timeractor.h"
#include "regulator.h"
Actor::Actor(QObject *parent): QObject(parent)
{
}
Actor::~Actor()
{
}
void Actor::performAction()
{
if(active)
{
trigger();
sigValue(triggerValue);
}
}
void Actor::makeActive()
{
active = true;
}
void Actor::makeInactive()
{
active = false;
}
QString Actor::actionName()
{
QString string;
if(triggerValue == 0 ) string = "off";
else if(triggerValue == 1 ) string = "on";
else string = "value to " + QString::number(triggerValue);
return string;
}
void Actor::setActive(uint8_t state)
{
state ? makeActive() : makeInactive();
}
bool Actor::isActive()
{
return active;
}
bool Actor::isExausted()
{
return exausted;
}
void Actor::store(QJsonObject& json)
{
json["Active"] = active;
json["Exausted"] = exausted;
if(!name.isEmpty()) json["Name"] = name;
json["TriggerValue"] = triggerValue;
}
void Actor::load(const QJsonObject& json)
{
active = json["Active"].toBool();
exausted = json["Exausted"].toBool();
name = json["Name"].toString("");
triggerValue = json["TriggerValue"].toInt();
}
void Actor::store(QString subsecton, QSettings* settings)
{
settings->setValue(subsecton + "Active", active);
settings->setValue(subsecton + "Exausted", exausted);
if(!name.isEmpty())settings->setValue(subsecton + "Name", name);
settings->setValue(subsecton + "TriggerValue", triggerValue);
}
void Actor::load(QString subsecton, QSettings* settings)
{
active = settings->value(subsecton + "Active").toBool();
exausted = settings->value(subsecton + "Exausted").toBool();
if(settings->contains(subsecton + "Name"))name = settings->value(subsecton + "Name").toString();
triggerValue = settings->value(subsecton + "TriggerValue").toUInt();
}
void Actor::setTriggerValue(uint8_t value)
{
triggerValue=value;
}
uint8_t Actor::getTriggerValue()
{
return triggerValue;
}
QString Actor::getName()
{
if(name.size() > 0) return name;
else return "Actor";
}
void Actor::onValueChanged(uint8_t value)
{
}
Actor* Actor::createActor(const QString& type)
{
Actor* actor = nullptr;
if(type == "Alarm") actor = new AlarmTime();
else if(type == "Sensor") actor = new SensorActor();
else if(type == "Timer") actor = new TimerActor();
else if(type == "Regulator") actor = new Regulator();
else if(type == "Actor") actor = new Actor();
return actor;
}
Actor* Actor::loadActor(const QJsonObject &json)
{
QString type = json["Type"].toString("Actor");
Actor* actor = createActor(type);
if(actor) actor->load(json);
return actor;
}
Actor* Actor::loadActor(QString subsecton, QSettings* settings)
{
QString type = settings->value(subsecton + "Type").toString();
Actor* actor = createActor(type);
if(actor) actor->load(subsecton, settings);
return actor;
}

61
src/actors/actor.h Normal file
View File

@ -0,0 +1,61 @@
#ifndef ACTOR_H
#define ACTOR_H
#include <QObject>
#include <QString>
#include <QSettings>
#include <QJsonObject>
class Actor : public QObject
{
Q_OBJECT
public:
uint8_t triggerValue = 0;
protected:
bool active = true;
bool exausted = false;
void performAction();
QString name;
signals:
void sigValue(uint8_t value);
void trigger();
public slots:
virtual void makeActive();
virtual void makeInactive();
virtual void setActive(uint8_t state);
virtual void onValueChanged(uint8_t state);
public:
Actor(QObject* parent = nullptr);
virtual ~Actor();
bool isExausted();
virtual QString actionName();
virtual QString getName();
bool isActive();
void setTriggerValue(uint8_t value);
uint8_t getTriggerValue();
static Actor* createActor(const QString& type);
virtual void store(QJsonObject& json);
virtual void load(const QJsonObject& json);
static Actor* loadActor(const QJsonObject& json);
virtual void store(QString subsecton, QSettings* settings);
virtual void load(QString subsecton, QSettings* settings);
static Actor* loadActor(QString subsecton, QSettings* settings);
};
#endif // ACTOR_H

145
src/actors/alarmtime.cpp Normal file
View File

@ -0,0 +1,145 @@
#include "alarmtime.h"
AlarmTime::AlarmTime(const QDateTime time, QObject *parent) : Actor(parent), time_(time)
{
connect(&timer, SIGNAL(timeout()), this, SLOT(doTick()));
timer.setInterval(1000);
}
AlarmTime::~AlarmTime()
{
makeInactive();
}
void AlarmTime::run()
{
makeInactive();
active = true;
timer.start();
qDebug()<<"Start Alarm Time Manager\n";
}
void AlarmTime::makeActive()
{
run();
}
QString AlarmTime::getName()
{
if(name.size() > 0)return name;
else
{
QString string;
string = "Alarm: ";
if(repeat_ == REPEAT_DAILY)
{
string.append("daily ");
string.append(time_.toString("HH:mm"));
}
else if(repeat_ == REPEAT_WEEKLY)
{
string.append("weekly ");
string.append(time_.toString("ddd HH:mm"));
}
else if(repeat_ == REPEAT_MONTHLY)
{
string.append("monthly ");
string.append(time_.toString("dd HH:mm"));
}
else if(repeat_ == REPEAT_YEARLY)
{
string.append("yearly ");
string.append(time_.toString("dd.mm HH:mm"));
}
else string.append(time_.toString("dd.mm.yyyy HH:mm"));
return string;
}
}
void AlarmTime::setRepeat(const uint8_t repeat)
{
repeat_=repeat;
}
uint8_t AlarmTime::getRepeat()
{
return repeat_;
}
QDateTime AlarmTime::getDateTime()
{
return time_;
}
void AlarmTime::makeInactive()
{
timer.stop();
active = false;
}
void AlarmTime::doTick()
{
if(
(
(triggerd_ == false) &&
(time_.date().year() == QDate::currentDate().year() || repeat_ != REPEAT_NEVER) &&
(time_.date().month() == QDate::currentDate().month() || repeat_ == REPEAT_MONTHLY || repeat_ == REPEAT_DAILY) &&
(time_.date().day() == QDate::currentDate().day() || repeat_ == REPEAT_DAILY)
)
||
(
(repeat_ == REPEAT_WEEKLY) &&
(time_.date().dayOfWeek() == QDate::currentDate().dayOfWeek())
)
)
{
if(time_.time().hour() == QTime::currentTime().hour() && time_.time().minute() == QTime::currentTime().minute())
{
qDebug()<<"Trigger\n";
triggerd_=true;
performAction();
if(repeat_ == REPEAT_NEVER) exausted = true;
}
}
else if( repeat_ != REPEAT_NEVER && time_.time().hour() != QTime::currentTime().hour() ) triggerd_=false;
}
void AlarmTime::changeTime(const QDateTime& time)
{
time_=time;
}
void AlarmTime::store(QJsonObject& json)
{
json["Type"] = "Alarm";
Actor::store(json);
json["Time"] = time_.toString();
json["Repeat"] = repeat_;
}
void AlarmTime::load(const QJsonObject& json)
{
Actor::load(json);
time_ = QDateTime::fromString(json["Time"].toString(""));
repeat_ = json["Repeat"].toInt(REPEAT_NEVER);
}
void AlarmTime::store(QString subsecton, QSettings* settings)
{
settings->setValue(subsecton + "Type", "Alarm");
Actor::store(subsecton, settings);
settings->setValue(subsecton + "Time", time_);
settings->setValue(subsecton + "Repeat", repeat_);
}
void AlarmTime::load(QString subsecton, QSettings* settings)
{
Actor::load(subsecton, settings);
time_ = settings->value(subsecton + "Time").toDateTime();
repeat_ = settings->value(subsecton + "Repeat").toUInt();
}

View File

@ -1,6 +1,6 @@
#ifndef ALARMTIME_H
#define ALARMTIME_H
#include <QTime>
#include <QDateTime>
#include <QObject>
#include <QRunnable>
#include <QScopedPointer>
@ -25,21 +25,33 @@ public:
private:
bool triggerd_ = false;
QTime time_;
QDateTime time_;
QTimer timer;
uint8_t repeat_ = REPEAT_NEVER;
public:
explicit AlarmTime(const QTime time = QTime::currentTime(), QObject *parent = nullptr);
explicit AlarmTime(const QDateTime time = QDateTime::currentDateTime(), QObject *parent = nullptr);
~AlarmTime();
QDateTime getDateTime();
virtual void store(QJsonObject& json);
virtual void load(const QJsonObject& json);
virtual void store(QString subsecton, QSettings* settings);
virtual void load(QString subsecton, QSettings* settings);
uint8_t getRepeat();
public slots:
void run();
virtual void makeActive();
virtual void makeInactive();
virtual QString getName();
void doTick();
void changeTime(QTime time);
void setRepeat(uint8_t repeat);
void changeTime(const QDateTime& time);
void setRepeat(const uint8_t repeat);
};
#endif // ALARMTIME_H

111
src/actors/regulator.cpp Normal file
View File

@ -0,0 +1,111 @@
#include "regulator.h"
#include <QDebug>
Regulator::Regulator(const Sensor sensor, QObject* parent): Actor(parent), sensor_(sensor)
{
}
Regulator::Regulator(QObject* parent): Actor(parent)
{
}
void Regulator::setSensor(const Sensor sensor)
{
sensor_ = sensor;
}
void Regulator::sensorEvent(Sensor sensor)
{
if(active && sensor == sensor_)
{
qDebug()<<"got sensor: "<<sensor.type<<" "<<sensor.id<<" want: "<<sensor_.type<<" "<<sensor_.id;
if( sensor.field < setPoint_-band_ && (sensor.field < sensor_.field || sensor_.field > setPoint_-band_) )
{
trigger();
sigValue(triggerValue);
}
else if( sensor.field > setPoint_+band_ && (sensor.field > sensor_.field || sensor_.field < setPoint_+band_) )
{
trigger();
sigValue(!triggerValue);
}
sensor_ = sensor;
}
}
void Regulator::setPoint(float setPoint)
{
setPoint_ = setPoint;
}
void Regulator::setBand ( float band )
{
band_ = band;
}
void Regulator::setInvert( bool invert )
{
invert_ = invert;
}
void Regulator::store(QJsonObject& json)
{
json["Type"] = "Regulator";
Actor::store(json);
json["Band"] = band_;
json["SetPoint"] = setPoint_;
json["SensorType"] = static_cast<int>(sensor_.type);
json["SensorId"] = static_cast<int>(sensor_.id);
json["SensorField"] = sensor_.field;
json["SensorName"] = sensor_.name;
}
void Regulator::load(const QJsonObject& json)
{
Actor::load(json);
band_ = json["Band"].toInt(1);
setPoint_ = json["SetPoint"].toInt(22);
sensor_.type = json["SensorType"].toInt(0);
sensor_.id = json["SensorId"].toInt(0);
sensor_.field = json["SensorField"].toInt(0);
sensor_.name = json["SensorName"].toString("Sensor");
}
void Regulator::store(QString subsecton, QSettings* settings)
{
settings->setValue(subsecton + "Type", "Regulator");
Actor::store(subsecton, settings);
settings->setValue(subsecton + "Band", band_);
settings->setValue(subsecton + "SetPoint", setPoint_);
settings->setValue(subsecton + "SensorType", static_cast<int>(sensor_.type));
settings->setValue(subsecton + "SensorId", static_cast<int>(sensor_.id));
settings->setValue(subsecton + "SensorField", sensor_.field);
settings->setValue(subsecton + "SensorName", sensor_.name);
}
void Regulator::load(QString subsecton, QSettings* settings)
{
Actor::load(subsecton, settings);
setPoint_ = settings->value(subsecton + "SetPoint").toUInt();
band_ = settings->value(subsecton + "Band").toFloat();
sensor_.type = settings->value(subsecton + "SensorType").toUInt();
sensor_.id = settings->value(subsecton + "SensorId").toUInt();
sensor_.field = settings->value(subsecton + "SensorField").toFloat();
sensor_.name = settings->value(subsecton + "SensorName").toString();
}
QString Regulator::getName()
{
if(name.size() > 0) return name;
else
{
QString string;
string = "Regulate \"" + sensor_.name + "\" to ";
string.append(QString::number(setPoint_) + " ");
return string;
}
}

39
src/actors/regulator.h Normal file
View File

@ -0,0 +1,39 @@
#pragma once
#include "actor.h"
#include "../sensors/sensor.h"
class Regulator : public Actor
{
Q_OBJECT
private:
Sensor sensor_;
float setPoint_ = 0;
float band_ = 1;
bool invert_ = false;
public slots:
void sensorEvent(Sensor sensor);
void setSensor(const Sensor sensor);
void setPoint( float setPoint );
void setBand ( float band );
void setInvert( bool invert );
public:
float getBand() {return band_;}
float getSetPoint() {return setPoint_;}
Regulator(const Sensor sensor, QObject* parent = nullptr);
Regulator(QObject* parent = nullptr);
Sensor getSensor(){return sensor_;}
virtual QString getName();
virtual ~Regulator(){}
virtual void store(QJsonObject& json);
virtual void load(const QJsonObject& json);
virtual void store(QString subsecton, QSettings* settings);
virtual void load(QString subsecton, QSettings* settings);
};

112
src/actors/sensoractor.cpp Normal file
View File

@ -0,0 +1,112 @@
#include "sensoractor.h"
#include <QDebug>
SensorActor::SensorActor(const Sensor sensor, QObject* parent): Actor(parent), sensor_(sensor)
{
}
SensorActor::SensorActor(QObject* parent): Actor(parent)
{
}
void SensorActor::setSensor(const Sensor sensor)
{
sensor_ = sensor;
}
void SensorActor::sensorEvent(Sensor sensor)
{
if(sensor == sensor_)
{
qDebug()<<"got sensor: "<<sensor.type<<" "<<sensor.id<<" want: "<<sensor_.type<<" "<<sensor_.id;
if((sloap_ == SLOPE_UP || sloap_ == SLOPE_BOTH) && sensor_.field < threshold_ && sensor.field >= threshold_ ) performAction();
else if((sloap_ == SLOPE_DOWN || sloap_ == SLOPE_BOTH) && sensor_.field > threshold_ && sensor.field <= threshold_) performAction();
sensor_ = sensor;
}
}
void SensorActor::setSloap(uint8_t sloap)
{
sloap_=sloap;
}
void SensorActor::setThreshold(float threshold)
{
threshold_ = threshold;
}
float SensorActor::getThreshold()
{
return threshold_;
}
uint8_t SensorActor::getSloap()
{
return sloap_;
}
void SensorActor::store(QJsonObject& json)
{
json["Type"] = "Sensor";
Actor::store(json);
json["Sloap"] = sloap_;
json["Threshold"] = threshold_;
json["SensorType"] = static_cast<int>(sensor_.type);
json["SensorId"] = static_cast<int>(sensor_.id);
json["SensorField"] = sensor_.field;
json["SensorName"] = sensor_.name;
}
void SensorActor::load(const QJsonObject& json)
{
Actor::load(json);
sloap_ = json["Sloap"].toInt(0);
threshold_ = json["Threshold"].toDouble(0);
sensor_.type = json["SensorType"].toInt(0);
sensor_.id = json["SensorId"].toInt(0);
sensor_.field = json["SensorField"].toInt(0);
sensor_.name = json["SensorName"].toString("Sensor");
}
void SensorActor::store(QString subsecton, QSettings* settings)
{
settings->setValue(subsecton + "Type", "Sensor");
Actor::store(subsecton, settings);
settings->setValue(subsecton + "Sloap", sloap_);
settings->setValue(subsecton + "Threshold", threshold_);
settings->setValue(subsecton + "SensorType", static_cast<int>(sensor_.type));
settings->setValue(subsecton + "SensorId", static_cast<int>(sensor_.id));
settings->setValue(subsecton + "SensorField", sensor_.field);
settings->setValue(subsecton + "SensorName", sensor_.name);
}
void SensorActor::load(QString subsecton, QSettings* settings)
{
Actor::load(subsecton, settings);
sloap_ = settings->value(subsecton + "Sloap").toUInt();
threshold_ = settings->value(subsecton + "Threshold").toFloat();
sensor_.type = settings->value(subsecton + "SensorType").toUInt();
sensor_.id = settings->value(subsecton + "SensorId").toUInt();
sensor_.field = settings->value(subsecton + "SensorField").toFloat();
sensor_.name = settings->value(subsecton + "SensorName").toString();
}
QString SensorActor::getName()
{
if(name.size() > 0) return name;
else
{
QString string;
string = "Sensor \"" + sensor_.name + "\"";
if(sloap_ == SLOPE_UP) string.append(" rises to ");
else if (sloap_ == SLOPE_DOWN) string.append(" drops to ");
else if (sloap_ == SLOPE_BOTH) string.append(" passes ");
string.append(QString::number(threshold_) + " ");
return string;
}
}

45
src/actors/sensoractor.h Normal file
View File

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

69
src/actors/timeractor.cpp Normal file
View File

@ -0,0 +1,69 @@
#include "timeractor.h"
#include <QDebug>
TimerActor::TimerActor(const int timeoutSec, QObject *parent): Actor(parent), timeoutMsec_(timeoutSec*1000)
{
connect(&timer, &QTimer::timeout, this, &TimerActor::timeout);
timer.setSingleShot(true);
}
void TimerActor::onValueChanged(uint8_t state)
{
if((state && !triggerValue) || (!state && triggerValue))
{
if(timer.isActive()) timer.stop();
timer.setInterval(timeoutMsec_);
timer.start();
}
}
void TimerActor::store(QJsonObject& json)
{
json["Type"] = "Timer";
Actor::store(json);
json["Timeout"] = timeoutMsec_;
}
void TimerActor::load(const QJsonObject& json)
{
Actor::load(json);
timeoutMsec_ = json["Timeout"].toInt(10000);
}
void TimerActor::store(QString subsecton, QSettings* settings)
{
settings->setValue(subsecton + "Type", "Timer");
Actor::store(subsecton, settings);
settings->setValue(subsecton + "Timeout", timeoutMsec_);
}
void TimerActor::load(QString subsecton, QSettings* settings)
{
Actor::load(subsecton, settings);
timeoutMsec_ = settings->value(subsecton + "Timeout").toInt();
}
void TimerActor::setTimeout(const int timeoutSec)
{
timeoutMsec_ = timeoutSec*1000;
}
int TimerActor::getTimeout()
{
return timeoutMsec_*1000;
}
void TimerActor::timeout()
{
performAction();
}
QString TimerActor::getName()
{
if(name.size() > 0) return name;
else
{
QString string;
string = "Timeout after " + QString::number(timeoutMsec_/1000) + " seconds. ";
return string;
}
}

33
src/actors/timeractor.h Normal file
View File

@ -0,0 +1,33 @@
#pragma once
#include <QTimer>
#include "actor.h"
class TimerActor: public Actor
{
Q_OBJECT
private:
int timeoutMsec_;
QTimer timer;
private slots:
void timeout();
public slots:
virtual void onValueChanged(uint8_t state);
void setTimeout(const int timeoutSec);
public:
explicit TimerActor(const int timeoutSec = 60, QObject *parent = nullptr);
virtual QString getName();
int getTimeout();
virtual void store(QJsonObject& json);
virtual void load(const QJsonObject& json);
virtual void store(QString subsecton, QSettings* settings);
virtual void load(QString subsecton, QSettings* settings);
};

View File

@ -1,33 +1,14 @@
#include "alarmactions.h"
#include <QProcess>
#include <QSound>
#include <QProcess>
#include <QTime>
#include <QApplication>
AlarmActions::AlarmActions(QSettings *settings, Microcontroller* micro, QObject *parent) : QObject(parent), _micro(micro), _settings(settings)
AlarmActions::AlarmActions(QApplication* a, Microcontroller* micro, QObject *parent) : QObject(parent), _micro(micro), a_(a)
{
}
void AlarmActions::syncoff()
{
_settings->sync();
for(unsigned int i = 0; i < _micro->getLastState().size(); i++) _micro->relayOff(i);
qDebug()<<"syncoff";
QProcess::execute ( "syncoff" );
}
void AlarmActions::Alarm()
{
if(_settings->value("Alarms/alarmSoundFile").toString().size() != 0)_micro->startSunrise();
if(_settings->value("Alarms/alarmSoundFile").toString().size() != 0)
{
_micro->relayOn(0);
QTime dieTime= QTime::currentTime().addSecs(10);
while (QTime::currentTime() < dieTime) QApplication::processEvents(QEventLoop::AllEvents, 100);
QSound::play(_settings->value("Alarms/alarmSoundFile").toString());
}
a_->exit(0);
}

View File

@ -1,8 +1,7 @@
#ifndef POWER_H
#define POWER_H
#include <QObject>
#include <QSettings>
#include <QApplication>
#include "microcontroller.h"
class AlarmActions : public QObject
@ -10,10 +9,10 @@ class AlarmActions : public QObject
private:
Q_OBJECT
Microcontroller* _micro;
QSettings* _settings;
QApplication* a_;
public:
explicit AlarmActions(QSettings* settings, Microcontroller* micro, QObject *parent = nullptr);
explicit AlarmActions(QApplication* a, Microcontroller* micro, QObject *parent = nullptr);
signals:
@ -21,8 +20,6 @@ public slots:
void syncoff();
void Alarm();
};
#endif // POWER_H

View File

@ -1,51 +0,0 @@
#include "alarmtime.h"
AlarmTime::AlarmTime(const QTime time, QObject *parent) : Actor(parent), time_(time)
{
connect(&timer, SIGNAL(timeout()), this, SLOT(doTick()));
timer.setInterval(1000);
}
AlarmTime::~AlarmTime()
{
makeInactive();
}
void AlarmTime::run()
{
makeInactive();
active = true;
timer.start();
qDebug()<<"Start Alarm Time Manager\n";
}
void AlarmTime::makeActive()
{
run();
}
void AlarmTime::makeInactive()
{
timer.stop();
active = false;
}
void AlarmTime::doTick()
{
if(time_.hour() == QTime::currentTime().hour() && time_.minute() == QTime::currentTime().minute() && triggerd_==false )
{
qDebug()<<"Trigger\n";
triggerd_=true;
performAction();
}
else if( time_.hour() != QTime::currentTime().hour() ) triggerd_=false;
}
void AlarmTime::changeTime(QTime time)
{
time_=time;
qDebug()<<"Time Changed\n";
}

83
src/broadcast.cpp Normal file
View File

@ -0,0 +1,83 @@
#include "broadcast.h"
#include <QJsonDocument>
#include <QDebug>
BroadCast::BroadCast(QIODevice* const iodevice): 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');
}
}
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);
write("JSON: ");
write(jsonDocument.toJson());
}
void BroadCast::decode()
{
if(buffer_.size() >= 6 && buffer_[0] == 'J' && buffer_[1] == 'S' && buffer_[2] == 'O' && buffer_[3] == 'N' && buffer_[4] == ':')
{
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);
}
}
QJsonDocument document;
QJsonParseError error;
document.fromJson(buffer_, &error);
if(error.error == QJsonParseError::NoError) gotJson(document.object());
else
{
qDebug()<<error.errorString();
}
}
}
void BroadCast::readyRead()
{
buffer_.append(iodevice_->readAll());
if(buffer_.size() >= 6)
{
if(buffer_[0] == 'B' && buffer_[1] == 'C' && buffer_[2] == 'S' && buffer_[3] == 'T' && buffer_[4] == ':')
{
if(buffer_.contains('\n'))
{
buffer_.remove(0,6);
decode();
buffer_.clear();
}
}
else buffer_.clear();
}
}

42
src/broadcast.h Normal file
View File

@ -0,0 +1,42 @@
#ifndef BROADCAST_H
#define BROADCAST_H
#include <QIODevice>
#include <QObject>
#include <QString>
#include <QJsonObject>
class BroadCast: public QObject
{
Q_OBJECT
private:
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();
private slots:
void readyRead();
signals:
void gotJson(QJsonObject json);
public:
BroadCast(QIODevice* const iodevice = nullptr);
void sendJson(const QJsonObject& json);
};
#endif // BROADCAST_H

24
src/items/auxitem.cpp Normal file
View File

@ -0,0 +1,24 @@
#include "auxitem.h"
AuxItem::AuxItem(SensorStore* sensors, Microcontroller* micro, uint32_t itemIdIn, QString name, uint8_t value, QObject* parent): Item(sensors, itemIdIn, name, value, parent), micro_(micro)
{
}
void AuxItem::setValue(uint8_t value)
{
Item::setValue(value);
micro_->setAuxPwm(value);
}
void AuxItem::store(QJsonObject &json)
{
json["Type"] = "Aux";
Item::store(json);
}
void AuxItem::store(QString subsecton, QSettings* settings)
{
settings->setValue(subsecton + "Type", "Aux");
Item::store(subsecton, settings);
}

21
src/items/auxitem.h Normal file
View File

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

173
src/items/item.cpp Normal file
View File

@ -0,0 +1,173 @@
#include "item.h"
#include "relay.h"
#include "../microcontroller.h"
#include "../actors/sensoractor.h"
#include "../actors/regulator.h"
#include <QJsonArray>
ItemData::ItemData(uint32_t itemIdIn, QString name, uint8_t value): name_(name), value_(value), itemId_(itemIdIn)
{
}
QString ItemData::getName() const
{
return name_;
}
void ItemData::setName(QString name)
{
name_ = name;
}
uint8_t ItemData::getValue() const
{
return value_;
}
uint32_t ItemData::id() const
{
return itemId_;
}
//item
bool Item::secondaryFlag = false;
Item::Item(SensorStore* sensors, uint32_t itemIdIn, QString name, uint8_t value, QObject *parent): QObject(parent), ItemData (itemIdIn, name, value), sensors_(sensors)
{
}
Item::Item(SensorStore* sensors, const ItemData& itemData, QObject *parent): QObject(parent), ItemData(itemData), sensors_(sensors)
{
}
bool Item::actorsActive() const
{
return actorsActive_;
}
void Item::store(QJsonObject &json)
{
json["Name"] = name_;
json["ItemId"] = static_cast<double>(itemId_);
json["ActorsActive"] = actorsActive_;
QJsonArray actorsArray;
for(size_t i = 0; i < actors_.size(); ++i)
{
QJsonObject actorObject;
actors_[i]->store(actorObject);
actorsArray.append(actorObject);
}
json["Actors"] = actorsArray;
}
void Item::load(const QJsonObject &json, const bool preserve)
{
if(!preserve)
{
name_ = json["Name"].toString(name_);
itemId_ = static_cast<uint32_t>(json["ItemId"].toDouble(0));
}
actorsActive_ = json["ActorsActive"].toBool(true);
const QJsonArray actorsArray(json["Actors"].toArray(QJsonArray()));
for(int i = 0; i < actorsArray.size(); ++i)
{
if(actorsArray[i].isObject())
{
Actor* actor = Actor::loadActor(actorsArray[i].toObject());
if(actor != nullptr) addActor(actor);
}
}
}
void Item::store(QString subsecton, QSettings* settings)
{
settings->setValue(subsecton + "Name", name_);
settings->setValue(subsecton + "ItemId", static_cast<unsigned>(itemId_));
settings->setValue(subsecton + "ActorsActive", actorsActive_);
settings->setValue(subsecton + "Actors", static_cast<unsigned>(actors_.size()));
for(size_t i = 0; i < actors_.size(); ++i)
{
actors_[i]->store(subsecton + "/Actor" + QString::number(i), settings);
}
}
void Item::load(QString subsecton, QSettings* settings, bool preserve)
{
if(!preserve)
{
name_ = settings->value(subsecton + "Name").toString();
itemId_ = settings->value(subsecton + "ItemId").toUInt();
}
actorsActive_ = settings->value(subsecton + "ActorsActive").toBool();
unsigned actorsLen = settings->value(subsecton + "Actors").toUInt();
for(unsigned i = 0; i < actorsLen; ++i)
{
Actor* actor = Actor::loadActor(subsecton + "/Actor" + QString::number(i), settings);
if(actor != nullptr) addActor(actor);
}
}
void Item::setValue(uint8_t value)
{
value_ = value;
valueChanged(value_);
}
void Item::informValue(uint8_t value)
{
Item::setValue(value);
}
void Item::addActor(Actor* actor)
{
actor->setParent(this);
actors_.push_back(actor);
if(!secondaryFlag)connect(actor, &Actor::sigValue, this, &Item::setValue);
connect(this, &Item::valueChanged, actor, &Actor::onValueChanged);
SensorActor* sensorActor = dynamic_cast<SensorActor*>(actor);
if(sensorActor != nullptr && sensors_ != nullptr)connect(sensors_, &SensorStore::sensorChangedState, sensorActor, &SensorActor::sensorEvent);
Regulator* regulator = dynamic_cast<Regulator*>(actor);
if(regulator != nullptr && sensors_ != nullptr)connect(sensors_, &SensorStore::sensorChangedState, regulator, &Regulator::sensorEvent);
if(actorsActive_) actor->makeActive();
else actor->makeInactive();
}
bool Item::removeActor(Actor* actor)
{
for(unsigned int i = 0; i < actors_.size(); i++)
{
if(actors_[i] == actor)
{
delete actor;
actors_.erase(actors_.begin()+i);
return true;
}
}
return false;
}
std::vector< Actor* >& Item::getActors()
{
return actors_;
}
bool Item::hasActors()
{
return actors_.size() > 0;
}
void Item::setActorsActive(bool in)
{
actorsActive_ = in;
for(unsigned i = 0; i < actors_.size(); i++) in ? actors_[i]->makeActive() : actors_[i]->makeInactive();
}

75
src/items/item.h Normal file
View File

@ -0,0 +1,75 @@
#pragma once
#include <QObject>
#include <vector>
#include <QRandomGenerator>
#include <QSettings>
#include <QJsonObject>
#include "../actors/actor.h"
#include "../sensors/sensor.h"
class ItemData
{
protected:
QString name_;
uint8_t value_;
uint32_t itemId_;
public:
ItemData(uint32_t itemIdIn = QRandomGenerator::global()->generate(), QString name = "Item", uint8_t value = 0);
inline bool operator==(const ItemData& in) const{ return itemId_==in.itemId_; }
inline bool operator!=(const ItemData& in) const{ return itemId_!=in.itemId_; }
uint32_t id() const;
QString getName() const;
void setName(QString name);
uint8_t getValue() const;
};
class Item: public QObject, public ItemData
{
Q_OBJECT
private:
std::vector< Actor* > actors_;
bool actorsActive_ = true;
public:
static bool secondaryFlag;
SensorStore* sensors_;
signals:
void valueChanged(uint8_t value);
public slots:
virtual void setValue(uint8_t value);
public:
Item(SensorStore* sensors = nullptr, uint32_t itemIdIn = QRandomGenerator::global()->generate(), QString name = "Item", uint8_t value = 0, QObject *parent = nullptr);
Item(SensorStore* sensors, const ItemData& itemData, QObject *parent = nullptr);
std::vector< Actor* >& getActors();
bool hasActors();
void addActor(Actor* actor);
bool removeActor(Actor* actor);
bool actorsActive() const;
void setActorsActive(bool in);
void informValue(uint8_t value);
void setSensorStore(SensorStore* sensors){sensors_ = sensors;}
SensorStore* getSensorStore(){return sensors_;}
virtual void store(QJsonObject& json);
virtual void load(const QJsonObject& json, const bool preserve = false);
virtual void store(QString subsecton, QSettings* settings);
virtual void load(QString subsecton, QSettings* settings, bool preserve = false);
};

132
src/items/itemstore.cpp Normal file
View File

@ -0,0 +1,132 @@
#include "itemstore.h"
#include "relay.h"
#include <QJsonArray>
ItemStore::ItemStore(SensorStore* sensors, QObject *parent): QObject(parent), sensors_(sensors)
{
}
void ItemStore::addItem(std::shared_ptr<Item> item)
{
bool mached = false;
for(unsigned i = 0; i < items_.size(); i++ ) if(*items_[i] == *item) mached = true;
if(!mached)
{
items_.push_back(std::shared_ptr<Item>(item));
items_.back()->setSensorStore(sensors_);
itemAdded(std::weak_ptr<Item>(items_.back()));
qDebug()<<"item added";
}
}
void ItemStore::addItems(const std::vector<std::shared_ptr<Item>>& itemIn)
{
for(unsigned i = 0; i < items_.size(); i++ )
{
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::itemStateChanged(const ItemData& item)
{
for(unsigned i = 0; i < items_.size(); i++ )
{
if(items_[i]->operator==(item))
{
qDebug()<<"is item "<<i<<" with ids: "<<item.id()<<" "<<items_[i]->id()<<"\nHas state: "<<items_[i]->getValue()<<" wants state: "<<item.getValue();
if(items_[i]->getValue() != item.getValue())items_[i]->informValue(item.getValue());
}
}
}
void ItemStore::store(QJsonObject& json)
{
QJsonArray itemsArray;
for(size_t i = 0; i < items_.size(); ++i)
{
QJsonObject itemObject;
items_[i]->store(itemObject);
itemsArray.append(itemObject);
}
json["Items"] = itemsArray;
}
void ItemStore::load(const QJsonObject& json, Microcontroller * const micro)
{
const QJsonArray itemsArray(json["Items"].toArray(QJsonArray()));
for(int i = 0; i < itemsArray.size(); ++i)
{
if(itemsArray[i].isObject())
{
const QJsonObject itemObject = itemsArray[i].toObject();
if(!itemObject["Name"].isObject()) qDebug()<<"no name";
std::shared_ptr<Relay> newItem;
if(itemObject["Type"].toString("") == "Relay")
{
newItem = std::shared_ptr<Relay>(new Relay(sensors_, micro));
}
else if(itemObject["Type"].toString("") == "Aux")
{
}
if(newItem)
{
newItem->load(itemObject);
addItem(newItem);
}
}
}
}
void ItemStore::store(QString subsecton, QSettings* settings)
{
settings->setValue(subsecton + "/NumberOfItems", static_cast<unsigned>(items_.size()));
for(size_t i = 0; i < items_.size(); ++i)
{
items_[i]->store(subsecton + "/Item" + QString::number(i), settings);
}
}
void ItemStore::load(QString subsecton, QSettings* settings, Microcontroller* micro)
{
unsigned itemLen = settings->value(subsecton + "/NumberOfItems").toUInt();
for(size_t i = 0; i < itemLen; ++i)
{
std::shared_ptr<Relay> newItem;
if(settings->value(subsecton + "/Item" + QString::number(i)+ "Type").toString() == "Relay")
{
newItem = std::shared_ptr<Relay>(new Relay(sensors_, micro));
}
else if(settings->value(subsecton + "/Item" + QString::number(i)+ "Type").toString() == "Aux")
{
}
if(newItem)
{
newItem->load(subsecton + "/Item" + QString::number(i), settings);
addItem(newItem);
}
}
}

41
src/items/itemstore.h Normal file
View File

@ -0,0 +1,41 @@
#pragma once
#include <vector>
#include <memory>
#include "item.h"
#include "../sensors/sensor.h"
#include "../microcontroller.h"
#include <QJsonObject>
class ItemStore: public QObject
{
Q_OBJECT
private:
std::vector< std::shared_ptr<Item> > items_;
SensorStore* sensors_;
public:
ItemStore(SensorStore* sensors_ = nullptr, QObject *parent = nullptr);
virtual ~ItemStore(){}
inline std::vector< std::shared_ptr<Item> >* getItems(){ return &items_; }
void store(QJsonObject &json);
void load(const QJsonObject &json, Microcontroller * const micro);
void store(QString subsecton, QSettings* settings);
void load(QString subsecton, QSettings* settings, Microcontroller* micro);
signals:
void itemDeleted(ItemData item);
void itemAdded(std::weak_ptr<Item> Item);
public slots:
void addItem(std::shared_ptr<Item> item);
void addItems(const std::vector<std::shared_ptr<Item>>& itemsIn);
void itemStateChanged(const ItemData& item);
};

37
src/items/poweritem.cpp Normal file
View File

@ -0,0 +1,37 @@
#include "poweritem.h"
#include <QProcess>
#include <QApplication>
PowerItem::PowerItem(SensorStore* sensors, QApplication* a, uint32_t itemIdIn, QString name, uint8_t value, QObject* parent): Item(sensors, itemIdIn, name, value, parent), a_(a)
{
stateChanged(Sensor(Sensor::TYPE_SHUTDOWN_IMMINENT, 0, 0));
setValue(true);
}
void PowerItem::setValue(uint8_t value)
{
Item::setValue(value);
if(!value)
{
QTimer::singleShot(5000, this, &PowerItem::timeout);
stateChanged(Sensor(Sensor::TYPE_SHUTDOWN_IMMINENT, 0, 1));
}
}
void PowerItem::timeout()
{
QProcess::startDetached("syncoff");
a_->exit(0);
}
void PowerItem::store(QJsonObject& json)
{
json["Type"] = "Power";
Item::store(json);
}
void PowerItem::store(QString subsecton, QSettings* settings)
{
settings->setValue(subsecton + "Type", "Power");
Item::store(subsecton, settings);
}

32
src/items/poweritem.h Normal file
View File

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

80
src/items/relay.cpp Normal file
View File

@ -0,0 +1,80 @@
#include "relay.h"
#include "../microcontroller.h"
//Relay
Relay::Relay(SensorStore* sensors, Microcontroller* micro, uint8_t id, QString name, uint16_t address, bool state, QObject* parent): Item(sensors, 0, name, state, parent), micro_(micro), id_(id), address_(address)
{
itemId_ = address | ((uint32_t)id << 16);
}
void Relay::setValue(uint8_t value)
{
Item::setValue(value);
if(value)micro_->relayOn(id_);
else micro_->relayOff(id_);
}
void Relay::on()
{
setValue(true);
}
void Relay::off()
{
setValue(false);
}
void Relay::toggle()
{
value_ ? off() : on();
}
void Relay::store(QJsonObject& json)
{
json["Type"] = "Relay";
Item::store(json);
json["Id"] = static_cast<double>(id_);
json["Address"] = address_;
}
void Relay::load(const QJsonObject& json)
{
Item::load(json);
id_ = static_cast<uint8_t>(json["Id"].toInt(0));
address_ = static_cast<uint16_t>(json["Address"].toInt(0));
itemId_ = address_ | (static_cast<uint32_t>(id_) << 16);
}
void Relay::store(QString subsecton, QSettings* settings)
{
settings->setValue(subsecton + "Type", "Relay");
Item::store(subsecton, settings);
settings->setValue(subsecton + "Id", static_cast<unsigned>(id_));
settings->setValue(subsecton + "Address", address_);
}
void Relay::load(QString subsecton, QSettings* settings)
{
Item::load(subsecton, settings);
id_ = settings->value(subsecton + "Id").toUInt();
address_ = settings->value(subsecton + "Address").toUInt();
itemId_ = address_ | ((uint32_t)id_ << 16);
}
uint16_t Relay::getAddress() const
{
return address_;
}
uint8_t Relay::getId() const
{
return id_;
}
void Relay::setId(uint8_t id)
{
id_=id;
itemId_ = address_ | ((uint32_t)id << 16);
}

41
src/items/relay.h Normal file
View File

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

24
src/items/rgbitem.cpp Normal file
View File

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

21
src/items/rgbitem.h Normal file
View File

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

View File

@ -6,21 +6,118 @@
#include <QSettings>
#include <QSignalMapper>
#include <QTcpSocket>
#include <QFileInfo>
#include <QJsonDocument>
#include <QStandardPaths>
#ifndef Q_OS_ANDROID
#include <QtSerialPort/QtSerialPort>
#include <QtSerialPort/QSerialPortInfo>
#include <QCommandLineParser>
#endif
#include "alarmtime.h"
#include "actors/alarmtime.h"
#include "microcontroller.h"
#include "mainwindow.h"
#include "ampmanager.h"
#include "ui/mainwindow.h"
#include "sensors/speakersensor.h"
#include "sensors/sunsensor.h"
#include "sensors/ocupancysensor.h"
#include "alarmactions.h"
#include "alarmsettingsdialog.h"
#include "sensors/sensor.h"
#include "items/itemstore.h"
#include "items/auxitem.h"
#include "items/rgbitem.h"
#include "items/poweritem.h"
#define BAUD QSerialPort::Baud38400
QJsonDocument* createJsonDocument(const bool pathOption, const QString& filePath)
{
QFile file;
#ifndef Q_OS_ANDROID
if(pathOption && 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
{
QJsonDocument* document = new QJsonDocument(QJsonDocument::fromJson(file.readAll()));
file.close();
return document;
}
return new QJsonDocument;
}
void saveJsonDocument(const QJsonDocument * const document, const bool pathOption, const QString& filePath)
{
QFile file;
#ifndef Q_OS_ANDROID
if(pathOption && filePath.size() > 0) file.setFileName(filePath);
else
#endif
{
file.setFileName(QStandardPaths::writableLocation(QStandardPaths::ConfigLocation) + "/shinterface.json");
}
std::cout<<"config file: "<<file.fileName().toLatin1().data()<<std::endl;
file.open(QIODevice::WriteOnly);
if(!file.isOpen()) std::cerr<<"Can not open config file: "<<filePath.toLatin1().data()<<std::endl;
else
{
file.write(document->toJson());
file.close();
}
}
QSettings* createQSettings(const bool pathOption, const QString& filePath )
{
QSettings* settings;
#ifndef Q_OS_ANDROID
if(pathOption && filePath.size() > 0)
{
settings = new QSettings(filePath, QSettings::IniFormat);
std::cout<<"Config file: "<<settings->fileName().toLatin1().data()<<std::endl;
}
else if(pathOption)
{
std::cerr<<"Can not open config file: "<<filePath.toLatin1().data()<<std::endl;
settings = new QSettings;
}
else
#endif
{
settings = new QSettings;
}
return settings;
}
void loadItemState(const QJsonDocument * const jsonDocument, QSettings * const settings, Microcontroller* micro, ItemStore* items, PowerItem* power, RgbItem* rgb, AuxItem* aux )
{
if(jsonDocument)
{
const QJsonObject jsonObject = jsonDocument->object();
items->load(jsonObject, micro);
power->load(jsonObject["Power"].toObject());
if(jsonObject["Items"].toArray().size() >= 2)
{
rgb->load(jsonObject["Items"].toArray()[0].toObject());
aux->load(jsonObject["Items"].toArray()[1].toObject());
}
}
else
{
items->load("Items", settings, micro);
power->load("Power", settings);
}
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
@ -29,11 +126,12 @@ int main(int argc, char *argv[])
QCoreApplication::setOrganizationName("UVOS");
QCoreApplication::setOrganizationDomain("uvos.xyz");
QCoreApplication::setApplicationName("SHinterface");
QCoreApplication::setApplicationVersion("0.5");
QCoreApplication::setApplicationVersion("0.6");
QDir::setCurrent(a.applicationDirPath());
//parse comand line
#ifndef Q_OS_ANDROID
QCommandLineParser parser;
parser.setApplicationDescription("Smart Home Interface");
parser.addHelpOption();
@ -48,14 +146,25 @@ int main(int argc, char *argv[])
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);
QCommandLineOption qsettingsOption(QStringList() << "q" << "qsettigns", QCoreApplication::translate("main", "Set if jsettings file format should be used."));
parser.addOption(secondaryOption);
parser.process(a);
#endif
QSettings* settings = nullptr;
QJsonDocument* jsonDocument = nullptr;
if(parser.isSet(qsettingsOption)) settings = createQSettings(parser.isSet(settingsPathOption), parser.value(settingsPathOption));
else jsonDocument = createJsonDocument(parser.isSet(settingsPathOption), parser.value(settingsPathOption));
QSettings settings;
//connect to microcontoler
Microcontroller micro;
#ifndef Q_OS_ANDROID
if(parser.isSet(tcpOption))
{
QTcpSocket* microSocket = new QTcpSocket;
@ -86,55 +195,95 @@ int main(int argc, char *argv[])
if(!microPort->open(QIODevice::ReadWrite)) std::cout<<"Can not open serial port "<<microPort->portName().toStdString()<<". Continueing in demo mode"<<'\n';
else micro.setIODevice(microPort);
}
#else
QTcpSocket* microSocket = new QTcpSocket;
microSocket->connectToHost("10.0.0.1", 6856, QIODevice::ReadWrite);
if(!microSocket->waitForConnected(1000))
{
std::cout<<"Can not connect to to Server.\n";
return 1;
}
micro.setIODevice(microSocket);
#endif
AlarmActions alarmActions(&settings, &micro);
AmpManager amp(&micro, 0);
AlarmActions alarmActions(&a, &micro);
//Alarms
AlarmTime almNight(settings.value("nightTime").toTime());
AlarmTime almAlarm(settings.value("alarmTime").toTime());
//sensors
SpeakerSensorSource livingroomSpeakerSensorSource("Livingroom Speakers");
SunSensorSource sunSensorSource(49.884450, 8.650536);
OcupancySensorSource ocupancySensor;
SensorStore sensors;
QObject::connect(&micro, &Microcontroller::gotSensorState, &sensors, &SensorStore::sensorGotState);
QObject::connect(&livingroomSpeakerSensorSource, &SpeakerSensorSource::stateChanged, &sensors, &SensorStore::sensorGotState);
QObject::connect(&sunSensorSource, &SunSensorSource::stateChanged, &sensors, &SensorStore::sensorGotState);
QObject::connect(&sensors, &SensorStore::sensorChangedState, &ocupancySensor, &OcupancySensorSource::sensorEvent);
QObject::connect(&ocupancySensor, &OcupancySensorSource::stateChanged, &sensors, &SensorStore::sensorGotState);
QMetaObject::invokeMethod(&livingroomSpeakerSensorSource, "run", Qt::QueuedConnection);
sunSensorSource.run();
//item store
ItemStore items(&sensors);
QObject::connect(&micro, &Microcontroller::gotRelayList, &items, &ItemStore::addItems);
QObject::connect(&micro, &Microcontroller::itemChanged, &items, &ItemStore::itemStateChanged);
//Power Item
PowerItem powerItem(&sensors, &a, 5487423, "Power");
QObject::connect(&powerItem, &PowerItem::stateChanged, &sensors, &SensorStore::sensorGotState);
powerItem.emmitSensor();
//mainwindow
MainWindow w(&micro, parser.isSet(secondaryOption));
MainWindow w(&micro, &powerItem, &items, &sensors);
QObject::connect(&micro, SIGNAL(textRecived(QString)), &w, SLOT(changeHeaderLableText(QString)));
QObject::connect(&micro, SIGNAL(relayStateChanged(std::vector<bool>)), &w, SLOT(relayStateChanged(std::vector<bool>)));
QObject::connect(&micro, SIGNAL(auxStateChanged(int)), &w, SLOT(auxStateChanged(int)));
if(!micro.connected()) w.changeHeaderLableText("No io debug only!");
//dialogs
AlarmSettingsDialog alarmDialog(&almNight, &almAlarm, &settings, &w);
//special items
std::shared_ptr<RgbItem> rgbItem(new RgbItem(&sensors, &micro, 5487422, "Rgb Lights"));
items.addItem(rgbItem);
if(!parser.isSet(secondaryOption))
{
QObject::connect(&almNight, SIGNAL(trigger()), &alarmActions, SLOT(syncoff()));
QObject::connect(&w, SIGNAL(signalAlmNightChanged(QTime)), &almNight, SLOT(changeTime(QTime)));
QObject::connect(&w, SIGNAL(signalAlmNightStateChanged(int)), &almNight, SLOT(runOrAbort(int)));
almNight.run();
QObject::connect(&almAlarm, &AlarmTime::trigger, &micro, &Microcontroller::startSunrise);
QObject::connect(&w, SIGNAL(signalAlmAlarmChanged(QTime)), &almAlarm, SLOT(changeTime(QTime)));
QObject::connect(&w, SIGNAL(signalAlmAlarmStateChanged(int)), &almAlarm, SLOT(runOrAbort(int)));
almAlarm.run();
//Amplifyer
QObject::connect(&w, SIGNAL(signalAmpOn()), &amp, SLOT(run()));
QObject::connect(&w, SIGNAL(signalAmpOff()), &amp, SLOT(abort()));
QMetaObject::invokeMethod(&amp, "run", Qt::QueuedConnection );
}
//show dialogs
QObject::connect(&w, &MainWindow::showAlmSettingsDialog, &alarmDialog, &AlarmSettingsDialog::show);
std::shared_ptr<AuxItem> auxItem(new AuxItem(&sensors, &micro, 5487421, "Desk Light"));
items.addItem(auxItem);
QMetaObject::invokeMethod(&micro, "run", Qt::QueuedConnection );
loadItemState(jsonDocument, settings, &micro, &items, &powerItem, rgbItem.get(), auxItem.get());
#ifndef Q_OS_ANDROID
if(!parser.isSet(secondaryOption))
{
Item::secondaryFlag = false;
}
else
{
Item::secondaryFlag = true;
}
#endif
w.show();
micro.requestRelayList();
micro.requestState();
//micro.requestState();
int retVal = a.exec();
micro.requestRelayList();
micro.requestState();
return a.exec();
if(settings)
{
items.store("Items", settings);
powerItem.store("Power/", settings);
settings->sync();
}
else
{
QJsonObject itemsJsonObject;
items.store(itemsJsonObject);
QJsonObject powerObject;
powerItem.store(powerObject);
itemsJsonObject.insert("Power", powerObject);
jsonDocument->setObject(itemsJsonObject);
saveJsonDocument(jsonDocument, parser.isSet(settingsPathOption), parser.value(settingsPathOption));
}
if(settings) delete settings;
else delete jsonDocument;
return retVal;
}

View File

@ -1,15 +1,16 @@
#include "microcontroller.h"
//relays
#include <chrono>
#include <thread>
static constexpr bool debug = true;
void Microcontroller::relayToggle(int state, int relay)
{
char buffer[8];
int length = sprintf(buffer, "%d \n", relay);
if(_port != nullptr) state ? _port->write("relay on ", sizeof("relay on ")-1) : _port->write("relay off ", sizeof("relay off ")-1);
state ? std::cout<<"relay on " : std::cout<<"relay off ";
std::cout<<buffer;
if(_port != nullptr) _port->write(buffer, length);
state ? write("relay on ") : write("relay off ");
write(buffer, length);
}
void Microcontroller::relayOn(int relay)
@ -26,48 +27,61 @@ void Microcontroller::relayOff(int relay)
void Microcontroller::rgbOn()
{
if(_port != nullptr) _port->write("rgb on\n", sizeof("rgb on\n")-1);
write("rgb on\n");
}
void Microcontroller::rgbOff()
{
if(_port != nullptr) _port->write( "rgb off\n", sizeof("rgb off\n")-1);
write( "rgb off\n");
}
void Microcontroller::changeRgbColor(const QColor color)
{
char buffer[64];
int length = sprintf(buffer, "rgb set %03d %03d %03d \n", color.red(), color.green(), color.blue() );
if(_port != nullptr) _port->write(buffer, length);
std::cout<<buffer;
int length = sprintf(buffer, "rgb set %03d %03d %03d\n", color.red(), color.green(), color.blue());
write(buffer, length);
std::cout<<buffer;
}
void Microcontroller::setAuxPwm(int duty)
{
char buffer[64];
int length = sprintf(buffer, "aux set %03d\n", duty );
write(buffer, length);
}
void Microcontroller::setAuxPwm(int duty)
void Microcontroller::write(const QByteArray& buffer)
{
if(duty != _auxState)
#ifndef Q_OS_ANDROID
if constexpr(debug) std::cerr<<buffer.data();
#endif
if(_port != nullptr)
{
if(duty > 1)
{
if(_auxState <= 1 && _port != nullptr) _port->write("aux on\n");
char buffer[64];
int length = sprintf(buffer, "aux set %03d \n", duty );
if(_port != nullptr) _port->write(buffer, length);
}
else if(_port != nullptr)_port->write("aux off\n");
_port->write(buffer);
_port->waitForBytesWritten(1000);
}
_auxState = duty;
std::this_thread::sleep_for(std::chrono::milliseconds(40));
}
void Microcontroller::write(char* buffer, const size_t length)
{
#ifndef Q_OS_ANDROID
if constexpr(debug) std::cerr<<buffer;
#endif
if(_port != nullptr)
{
_port->write(buffer, length);
_port->waitForBytesWritten(1000);
}
std::this_thread::sleep_for(std::chrono::milliseconds(40));
}
void Microcontroller::setPattern(int pattern)
{
if(_port != nullptr)
{
char buffer[4];
std::cout<<"pattern apply\n";
_port->write("rgb pattern ", sizeof("rgb pattern ")-1);
int length = sprintf(buffer, "%d \n", pattern);
_port->write(buffer, length);
}
write("rgb pattern ");
int length = sprintf(buffer, "%d\n", pattern);
write(buffer, length);
}
void Microcontroller::startSunrise()
@ -96,12 +110,7 @@ void Microcontroller::run()
void Microcontroller::requestState()
{
if(_port != nullptr) _port->write("state\n", sizeof("state\n"));
}
void Microcontroller::requestRelayList()
{
if(_port != nullptr) _port->write("relay list\n", sizeof("relay list\n"));
write("state\n");
}
void Microcontroller::abort()
@ -112,16 +121,12 @@ void Microcontroller::abort()
}
}
std::vector<bool> Microcontroller::getLastState()
{
return _relayStates;
}
//housekeeping
Microcontroller::Microcontroller(QIODevice* port): _port(port)
{
_port->readAll();
_port->write("\n");
}
Microcontroller::Microcontroller()
@ -136,31 +141,60 @@ Microcontroller::~Microcontroller()
void Microcontroller::setIODevice(QIODevice *port)
{
_port = port;
_port->readAll();
_port->write("\n");
}
std::shared_ptr<Relay> Microcontroller::processRelayLine(const QString& buffer)
{
QStringList bufferList = buffer.split(' ');
if(bufferList.size() >= 8 && buffer.startsWith("RELAY NUMBER:"))
{
QString name;
for(int i = 8; i < bufferList.size(); i++) name.append(bufferList[i] + ' ');
if(name.size() > 1)name.remove(name.size()-1, 1);
else name = "Relay " + QString::number(bufferList[1].toInt(nullptr, 2));
qDebug()<<"Relay "<<bufferList[2].toInt()<<"Name "<<name<<" id "<<bufferList[4].toInt(nullptr, 2)<<" state "<<bufferList[6].toInt();
return std::shared_ptr<Relay>( new Relay(nullptr, this, bufferList[2].toInt(), name, bufferList[4].toInt(nullptr, 2), bufferList[6].toInt()));
}
return nullptr;
}
void Microcontroller::processList(const QString& buffer)
{
QStringList bufferList = buffer.split(' ');
if(bufferList.size() >= 8 && buffer.startsWith("RELAY NUMBER:"))
{
relayList.push_back(processRelayLine(buffer));
}
else if(buffer.contains("EOL"))
{
listMode = false;
qDebug()<<"got relay list " << relayList.size();
gotRelayList(relayList);
relayList.clear();
}
else listMode = false;
}
void Microcontroller::processRelayState(const QString& buffer)
{
itemChanged(static_cast<ItemData>(*processRelayLine(buffer)));
}
void Microcontroller::processSensorState(const QString& buffer)
{
QStringList bufferList = buffer.split(' ');
Sensor sensor(bufferList[2].toUInt(), bufferList[4].toUInt(), bufferList[6].toUInt());
if(sensor.type == Sensor::TYPE_HUMIDITY || sensor.type == Sensor::TYPE_TEMPERATURE) sensor.field = sensor.field/10;
if(bufferList.size() >= 7)gotSensorState(sensor);
}
void Microcontroller::processMicroReturn()
{
QString workbuff = _buffer;
if(listMode)
{
QStringList workbufList = workbuff.split(' ');
if(workbufList.size() >= 5 && workbufList[0] == "NUMBER:")
{
QString name;
for(int i = 5; i < workbufList.size(); i++) name.append(workbufList[i] + ' ');
name.remove(name.size()-1, 1);
relayList.push_back(RelayStore(workbufList[1].toInt(), name, workbufList[3].toInt()));
}
else if(_buffer.startsWith("EOL"))
{
listMode = false;
gotRelayList(relayList);
relayList.clear();
}
else listMode = false;
}
qDebug()<<_buffer;
if(listMode) processList(_buffer);
else
{
if(_buffer.startsWith("Relays:"))
@ -168,43 +202,8 @@ void Microcontroller::processMicroReturn()
listMode = true;
relayList.clear();
}
else if(_buffer.startsWith("ST"))
{
workbuff.remove(0, 2);
QStringList workbufList = workbuff.split(',');
//aux state
if(workbufList[0].toInt() != _auxState)
{
_auxState = workbufList[0].toInt();
auxStateChanged(_auxState);
}
//relay state
uint_fast8_t numberOfRelays = workbufList[1].toInt();
if(workbufList.size() >= numberOfRelays+2)
{
_relayStates.resize(numberOfRelays, false);
for(uint_fast8_t i = 0; i < numberOfRelays; i++)
{
if(_relayStates[i] != static_cast<bool>(workbufList[i+2].toInt()))
{
_relayStates[i] = static_cast<bool>(workbufList[i+2].toInt());
relayStateChanged(RelayStore(i, "", 0, _relayStates[i]));
}
}
}
}
else if(workbuff.contains("Door Open Warning"))
{
doorOpenTimeout();
}
else if(workbuff.size() > 2 && workbuff[0]=='D' && workbuff[1]=='2')
{
if(workbuff[3] == 'O') doorOpened(1);
else if(workbuff[3] == 'C') doorClosed(1);
}
else if(_buffer.startsWith("RELAY NUMBER:"))processRelayState(_buffer);
else if(_buffer.startsWith("SENSOR")) processSensorState(_buffer);
}
}

View File

@ -8,12 +8,15 @@
#include <QIODevice>
#include <QString>
#include <QRunnable>
#include <QScopedPointer>
#include <QDebug>
#include <QEventLoop>
#include <QTimer>
#include <QAbstractButton>
#include <vector>
#include "relay.h"
#include <memory>
#include "items/item.h"
#include "items/relay.h"
#include "sensors/sensor.h"
class Microcontroller : public QObject
{
@ -23,20 +26,31 @@ class Microcontroller : public QObject
public:
static constexpr char AMP_RELAY = 0;
static constexpr char SENSOR_TEMPERATURE = 1;
static constexpr char SENSOR_DOOR = 0 ;
private:
bool listMode = false;
std::vector<RelayStore> relayList;
std::vector<bool> _relayStates; //ugh vector of bools
int _auxState = 0;
//uint8_t _auxState = 0;
QIODevice* _port = nullptr;
std::vector< std::shared_ptr<Item> > relayList;
QScopedPointer<QEventLoop> loop;
QString _buffer;
void processMicroReturn();
void processList(const QString& buffer);
void processRelayState(const QString& buffer);
void processSensorState(const QString& buffer);
std::shared_ptr<Relay> processRelayLine(const QString& buffer);
void write(char *buffer, const size_t length);
void write(const QByteArray& buffer);
public:
Microcontroller(QIODevice* port);
@ -44,7 +58,6 @@ public:
~Microcontroller();
bool connected();
void setIODevice(QIODevice* port);
std::vector<bool> getLastState();
public slots:
void rgbOn();
@ -53,8 +66,7 @@ public slots:
void setPattern(int pattern);
void startSunrise();
void requestRelayList();
void requestState();
void requestState();
void setAuxPwm(int duty);
@ -68,12 +80,11 @@ public slots:
signals:
void textRecived(const QString string);
void relayStateChanged(RelayStore relay);
void itemChanged(ItemData relay);
void auxStateChanged(int value);
void gotRelayList(std::vector<RelayStore>& relays);
void doorOpenTimeout();
void doorOpened(int id);
void doorClosed(int id);
void gotRelayList(std::vector< std::shared_ptr<Item> >&);
void gotSensorState(Sensor sensor);
};
#endif // MICROCONTROLLER_H

View File

@ -1,116 +0,0 @@
#include "relay.h"
#include "microcontroller.h"
RelayStore::RelayStore(uint8_t id, QString name, uint16_t address, bool state): name_(name), state_(state), id_(id), address_(address)
{
}
QString RelayStore::getName() const
{
return name_;
}
void RelayStore::setName(QString name)
{
name_ = name;
}
bool RelayStore::getState() const
{
return state_;
}
bool RelayStore::actorsActive() const
{
return actorsActive_;
}
uint16_t RelayStore::getAddress() const
{
return address_;
}
uint8_t RelayStore::getId() const
{
return id_;
}
void RelayStore::setId(uint8_t id)
{
id_=id;
}
//Relay
Relay::Relay(Microcontroller* micro, uint8_t id, QString name, uint16_t address, bool state, QObject* parent): QObject(parent), RelayStore(id, name, address, state), micro_(micro)
{
}
Relay::Relay(Microcontroller* micro, const RelayStore& relayStore, QObject *parent): QObject(parent), RelayStore(relayStore), micro_(micro)
{
}
void Relay::setState(bool state)
{
state_ = state;
}
void Relay::addActor(Actor* actor)
{
actor->setParent(this);
actors_.push_back(actor);
connect(actor, &Actor::on, this, &Relay::on);
connect(actor, &Actor::off, this, &Relay::off);
connect(actor, &Actor::toggle, this, &Relay::toggle);
if(actorsActive_) actor->makeActive();
}
std::vector< Actor* > Relay::getActors()
{
return actors_;
}
bool Relay::hasActors()
{
return actors_.size() > 0;
}
Relay* Relay::copy() const
{
Relay* copy = new Relay(micro_, id_, name_, address_, parent());
copy->actors_ = actors_;
return copy;
}
void Relay::on()
{
micro_->relayOn(id_);
state_ = true;
for(unsigned i = 0; i < actors_.size(); i++) actors_[i]->onStateChanged(state_);
}
void Relay::off()
{
micro_->relayOff(id_);
state_ = false;
for(unsigned i = 0; i < actors_.size(); i++) actors_[i]->onStateChanged(state_);
}
void Relay::toggle()
{
state_ ? off() : on();
}
void Relay::moveToState(bool state)
{
state ? on() : off();
}
void Relay::setActorsActive(bool in)
{
actorsActive_ = true;
for(unsigned i = 0; i < actors_.size(); i++) in ? actors_[i]->makeActive() : actors_[i]->makeInactive();
}

View File

@ -1,57 +0,0 @@
#ifndef RELAY_H
#define RELAY_H
#include<stdint.h>
#include<QObject>
#include<QString>
#include<vector>
#include<memory>
#include"actor.h"
class Microcontroller;
class RelayStore
{
protected:
QString name_;
bool state_ = false;
uint8_t id_;
uint16_t address_;
bool actorsActive_ = true;
public:
RelayStore(uint8_t id, QString name = "", uint16_t address = 0, bool state = false);
bool actorsActive() const;
QString getName() const;
void setName(QString name);
uint16_t getAddress() const;
uint8_t getId() const;
void setId(uint8_t id);
bool getState() const;
};
class Relay : public QObject, public RelayStore
{
Q_OBJECT
private:
Microcontroller* micro_;
std::vector< Actor* > actors_;
public slots:
void on();
void off();
void toggle();
void moveToState(bool state);
void setActorsActive(bool in);
public:
Relay(Microcontroller* micro, uint8_t id, QString name = "", uint16_t address = 0, bool state = false, QObject *parent = nullptr);
Relay(Microcontroller* micro, const RelayStore& relayStore, QObject *parent = nullptr);
void addActor(Actor* actor);
bool hasActors();
Relay* copy() const;
void setState(bool state);
std::vector< Actor* > getActors();
};
#endif // RELAY_H

View File

@ -1,66 +0,0 @@
#include "relayscrollbox.h"
#include "ui_relayscrollbox.h"
RelayScrollBox::RelayScrollBox(QWidget *parent) :
QWidget(parent),
ui(new Ui::RelayScrollBox)
{
ui->setupUi(this);
}
RelayScrollBox::~RelayScrollBox()
{
delete ui;
}
void RelayScrollBox::addRelay(const Relay& relay)
{
widgets_.push_back(new RelayWidget(relay.copy(), this));
ui->relayWidgetVbox->addWidget(widgets_.back());
}
void RelayScrollBox::addRelay(const RelayStore& relay)
{
RelayWidget* newWidget = new RelayWidget(new Relay(micro_, relay), this);
widgets_.push_back(newWidget);
ui->relayWidgetVbox->addWidget(widgets_.back());
}
void RelayScrollBox::setMicrocontoller(Microcontroller* micro)
{
micro_ = micro;
}
void RelayScrollBox::gotRelays(const std::vector<RelayStore>& relays)
{
for(unsigned i = 0; i < widgets_.size(); i++ )
{
bool mached = false;
for(unsigned j = 0; j < relays.size(); j++) if(widgets_[i]->getRelay()->getAddress() == relays[j].getAddress())
{
mached = true;
if(widgets_[i]->getRelay()->getId() != relays[j].getId()) widgets_[i]->getRelay()->setId(relays[j].getId());
}
if(!mached)
{
delete widgets_[i];
widgets_.erase(widgets_.begin()+i);
}
}
for(unsigned j = 0; j < relays.size(); j++)
{
bool mached = false;
for(unsigned i = 0; i < widgets_.size(); i++ ) if(widgets_[i]->getRelay()->getAddress() == relays[j].getAddress()) mached = true;
if(!mached)
{
addRelay(relays[j]);
}
}
}
void RelayScrollBox::relaySateChanged(const RelayStore& Realy)
{
}

View File

@ -1,40 +0,0 @@
#ifndef RELAYSCROLLBOX_H
#define RELAYSCROLLBOX_H
#include <QWidget>
#include <vector>
#include <memory>
#include "relaywidget.h"
#include "relay.h"
#include "microcontroller.h"
namespace Ui {
class RelayScrollBox;
}
class RelayScrollBox : public QWidget
{
Q_OBJECT
private:
Microcontroller* micro_ = nullptr;
std::vector< RelayWidget* > widgets_;
public:
explicit RelayScrollBox(QWidget *parent = nullptr);
~RelayScrollBox();
public slots:
void addRelay(const Relay& relay);
void addRelay(const RelayStore& relay);
void setMicrocontoller(Microcontroller* micro);
void gotRelays(const std::vector<RelayStore>& relays);
void relaySateChanged(const RelayStore& Realy);
private:
Ui::RelayScrollBox *ui;
};
#endif // RELAYSCROLLBOX_H

View File

@ -0,0 +1,42 @@
#include "ocupancysensor.h"
#include <QTimer>
#include <QDebug>
OcupancySensorSource::OcupancySensorSource(QObject *parent): QObject (parent)
{
connect(&ping, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(pingExit(int, QProcess::ExitStatus)));
Timeout();
}
void OcupancySensorSource::sensorEvent(Sensor sensor)
{
if(sensor.type == Sensor::TYPE_DOOR && sensor.id == 1 && sensor.field != 0.0f)
{
QTimer::singleShot(240000, this, &OcupancySensorSource::Timeout);
qDebug()<<"starting timer";
}
}
void OcupancySensorSource::Timeout()
{
qDebug()<<"starting ping";
ping.start("ping 192.168.0.104 -c 1 -W 1");
}
void OcupancySensorSource::pingExit(int exitCode, QProcess::ExitStatus exitStatus)
{
qDebug()<<"ping finished";
if(exitStatus == QProcess::ExitStatus::NormalExit)
{
qDebug()<<"Exit Code "<<exitCode;
if(exitCode == 0)
{
stateChanged(Sensor(Sensor::TYPE_OCUPANCY, 0, 1, "Occupancy"));
}
else
{
stateChanged(Sensor(Sensor::TYPE_OCUPANCY, 0, 0, "Occupancy"));
}
}
}

View File

@ -0,0 +1,27 @@
#pragma once
#include <QObject>
#include <QProcess>
#include "sensor.h"
class OcupancySensorSource : public QObject
{
Q_OBJECT
private:
QProcess ping;
public:
explicit OcupancySensorSource(QObject *parent = nullptr);
public slots:
void sensorEvent(Sensor sensor);
private slots:
void Timeout();
void pingExit(int exitCode, QProcess::ExitStatus exitStatus);
signals:
void stateChanged(Sensor sensor);
};

45
src/sensors/sensor.cpp Normal file
View File

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

77
src/sensors/sensor.h Normal file
View File

@ -0,0 +1,77 @@
#pragma once
#include <stdint.h>
#include<QString>
#include<QDateTime>
#include<QObject>
#include<vector>
class Sensor
{
public:
static constexpr uint8_t TYPE_DOOR = 0;
static constexpr uint8_t TYPE_TEMPERATURE = 1;
static constexpr uint8_t TYPE_HUMIDITY = 2;
static constexpr uint8_t TYPE_PRESSURE = 3;
static constexpr uint8_t TYPE_BRIGHTNESS = 4;
static constexpr uint8_t TYPE_LOWBATTERY = 128;
static constexpr uint8_t TYPE_SHUTDOWN_IMMINENT = 251;
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 id;
float field;
QString name;
QDateTime lastSeen;
Sensor(uint8_t typeIn, uint8_t idIn, float fieldIn = 0, QString nameIn = ""): type(typeIn), id(idIn), field(fieldIn), name(nameIn)
{
lastSeen = QDateTime::currentDateTime();
if(nameIn == "") generateName();
}
Sensor(QString nameIn = "dummy"): type(TYPE_DUMMY), id(0), field(0), name(nameIn)
{
lastSeen = QDateTime::currentDateTime();
}
inline bool operator==(const Sensor& in){ return type==in.type && id == in.id; }
inline bool operator!=(const Sensor& in){ return !(*this==in); }
inline void updateSeen(){lastSeen = QDateTime::currentDateTime();}
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_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
{
Q_OBJECT
private:
std::vector<Sensor> sensors_;
public:
SensorStore(QObject *parent = nullptr);
virtual ~SensorStore(){}
inline std::vector<Sensor>* getSensors(){ return &sensors_; }
public slots:
void sensorGotState(const Sensor& sensor);
signals:
void stateChenged(std::vector<Sensor> sensors);
void sensorChangedState(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

@ -10,39 +10,36 @@
#include <QTimer>
#include <QProcess>
#include <QByteArray>
#include <QtDebug>
#include "microcontroller.h"
#include "sensor.h"
class AmpManager : public QObject
class SpeakerSensorSource : public QObject
{
Q_OBJECT
private:
QString name_;
bool state = true;
QTimer timer;
public:
explicit AmpManager(Microcontroller *micro, int relayNumber, QObject *parent = nullptr);
~AmpManager();
explicit SpeakerSensorSource(QString name = "", QObject *parent = nullptr);
~SpeakerSensorSource();
public slots:
void run();
void abort();
signals:
void stateChanged(Sensor sensor);
private slots:
void doTick();
private:
QScopedPointer<QEventLoop> loop;
long silenceCount = 0;
Microcontroller *_micro;
int _relayNumber;
QProcess arecord;
bool relayState = false;
};
#endif // AMPMANAGER_H

25
src/sensors/sunsensor.cpp Normal file
View File

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

29
src/sensors/sunsensor.h Normal file
View File

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

View File

@ -1,67 +0,0 @@
#include "serial_io.h"
struct termios toptions;;
void sWrite(int port, char string[], size_t length)
{
if(port != -1) write(port, string, length);
else std::cout<<string;
}
void sWrite(int port, const char string[], size_t length)
{
if(port != -1) write(port, string, length);
else std::cout<<string;
}
ssize_t sRead(int port, void *buf, size_t count)
{
return (port != -1) ? read(port, buf, count) : 0;
}
int serialport_init()
{
int fd;
system("stty -F /dev/ttyUSB0 38400 sane -echo");
fd = open(DEVICE, O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1)
{
perror("init_serialport: Unable to open port ");
return -1;
}
if (tcgetattr(fd, &toptions) < 0)
{
perror("init_serialport: Couldn't get term attributes");
return -1;
}
speed_t brate = BAUDRATE;
cfsetispeed(&toptions, brate);
cfsetospeed(&toptions, brate);
// 8N1
toptions.c_cflag &= ~PARENB;
toptions.c_cflag &= ~CSTOPB;
toptions.c_cflag &= ~CSIZE;
toptions.c_cflag |= CS8;
// no flow control
toptions.c_cflag &= ~CRTSCTS;
toptions.c_cflag |= CREAD | CLOCAL | IGNPAR; // turn on READ & ignore ctrl lines
toptions.c_iflag &= ~(IXON | IXOFF | IXANY); // turn off s/w flow ctrl
toptions.c_lflag &= ~(ICANON | ISIG | ECHO | ECHOE); // make raw
toptions.c_oflag &= ~OPOST; // make raw
// see: http://unixwiz.net/techtips/termios-vmin-vtime.html
toptions.c_cc[VMIN] = 0;
toptions.c_cc[VTIME] = 20;
fcntl(fd, F_SETFL, FNDELAY);
if( tcsetattr(fd, TCSANOW, &toptions) < 0)
{
perror("init_serialport: Couldn't set term attributes");
return -1;
}
return fd;
}

View File

@ -1,21 +0,0 @@
#ifndef SERIAL_H
#define SERIAL_H
#include <termios.h>
#include <fcntl.h>
#include <unistd.h>
#include <iostream>
#define BAUDRATE B38400
#define DEVICE "/dev/ttyUSB0"
void sWrite(int port, char string[], size_t length);
void sWrite(int port, const char string[], size_t length);
ssize_t sRead(int port, void *buf, size_t count);
int serialport_init();
#endif // SERIAL_H

View File

@ -1,36 +0,0 @@
#include "serialwatcher.h"
void SerialWatcher::run()
{
abort();
loop.reset(new QEventLoop);
QTimer timer;
connect(&timer, SIGNAL(timeout()), this, SLOT(doTick()));
timer.setInterval(500);
timer.start();
loop->exec();
}
void SerialWatcher::abort()
{
if (!loop.isNull()){
loop->quit();
}
}
void SerialWatcher::doTick()
{
char charBuf;
while(sRead(_serial, &charBuf, 1) == 1)
{
_buffer.push_back(charBuf);
if( _buffer.endsWith('\n') )
{
textRecived(_buffer);
_buffer.clear();
}
}
}

View File

@ -1,39 +0,0 @@
#ifndef SERIALWATCHER_H
#define SERIALWATCHER_H
#include "serial_io.h"
#define BUFFER_SIZE 128
#include<QString>
#include<QObject>
#include<QRunnable>
#include<QScopedPointer>
#include<QEventLoop>
#include<QTimer>
class SerialWatcher: public QObject, public QRunnable
{
Q_OBJECT
private:
QScopedPointer<QEventLoop> loop;
int _serial;
QString _buffer;
public:
explicit SerialWatcher(int serial, QObject *parent = 0);
~SerialWatcher();
signals:
void textRecived(const QString string);
public slots:
void run();
void abort();
void doTick();
};
#endif // SERIALWATCHER_H

View File

@ -1,65 +0,0 @@
#include "ampmanager.h"
AmpManager::AmpManager(Microcontroller *micro, int relayNumber, QObject *parent) : QObject(parent), _micro(micro), _relayNumber(relayNumber)
{
silenceCount = 0;
}
AmpManager::~AmpManager()
{
abort();
}
void AmpManager::run()
{
abort();
arecord.start( "arecord -D front -" );
loop.reset(new QEventLoop);
QTimer timer;
connect(&timer, SIGNAL(timeout()), this, SLOT(doTick()));
timer.setInterval(500);
timer.start();
qDebug()<<"Start Auto Amp Manager\n";
_micro->relayOn(_relayNumber);
relayState = true;
loop->exec();
}
void AmpManager::abort()
{
if (!loop.isNull()){
loop->quit();
}
if(arecord.state() == QProcess::Running)arecord.close();
qDebug()<<"Stop Auto Amp Manager\n";
}
void AmpManager::doTick()
{
if(arecord.state() == QProcess::Running)
{
QByteArray buffer = arecord.readAllStandardOutput();
for(long i = 0; i < buffer.size(); i++)
{
if((uint8_t) buffer.at(i) != 128)
{
silenceCount = 0;
}
}
if(silenceCount > 40 && relayState)
{
std::cout<<"Auto off Amp\n";
_micro->relayOff(_relayNumber);
relayState = false;
}
else if(silenceCount == 0 && !relayState)
{
std::cout<<"Auto on Amp\n";
_micro->relayOn(_relayNumber);
relayState = true;
}
silenceCount ++;
}
}

187
src/sun.cpp Normal file
View File

@ -0,0 +1,187 @@
#include "sun.h"
class Sun::JdTime
{
public:
static constexpr double JULIAN_OFFSET = 68.184 / 86400.0;
static constexpr double JULIAN_DATEATY2K = 2451544.500000;
double julianDate;
double daysSinceY2K;
double siderialUtcTime;
double localHour;
double utcHour;
int day;
int year;
JdTime();
void update();
std::time_t toStdTime();
void fromStdTime(std::time_t time);
};
Sun::JdTime::JdTime()
{
update();
}
void Sun::JdTime::update()
{
std::time_t time = std::time(nullptr);
fromStdTime(time);
}
void Sun::JdTime::fromStdTime(std::time_t time)
{
std::tm ltime = *std::localtime( &time );
localHour = ltime.tm_hour + ltime.tm_min/60.0 + ltime.tm_sec/3600.0;
utcHour = localHour - ltime.tm_gmtoff/3600.0;
day = ltime.tm_yday;
year = ltime.tm_year + 1900;
std::tm millennium = {0,0,0,1,0,100};
std::time_t millenniumTime = std::mktime(&millennium) - timezone;
daysSinceY2K = (time - millenniumTime)/(60*60*24.0);
//std::cout<<"days since y2k: "<<daysSinceY2K<<std::endl;
julianDate = daysSinceY2K + JULIAN_DATEATY2K - JULIAN_OFFSET;
//std::cout<<"julianDate: "<<julianDate<<std::endl;
siderialUtcTime = 6.697374558 + 0.06570982441908 * (long)daysSinceY2K + 1.00273790935*utcHour;
while(siderialUtcTime < 0) siderialUtcTime+=24;
siderialUtcTime = fmod(siderialUtcTime, 24);
}
std::time_t Sun::JdTime::toStdTime()
{
std::tm millennium = {0,0,0,0,0,100};
std::time_t millenniumTime = std::mktime(&millennium)- timezone;
millenniumTime = millenniumTime + (julianDate-JULIAN_DATEATY2K+JULIAN_OFFSET)*(24*60*60);
return millenniumTime;
}
Sun::Sun(double latitude, double longitude, double altitude): latitude_(latitude), longetude_(longitude), altitude_(altitude)
{}
double Sun::nextMeanSolarNoonJD(const JdTime& time)
{
return (long)time.daysSinceY2K + 2451545.0 + 0.0009 - (longetude_ / 360);
}
double Sun::meanSolarAnomaly(double meanSolarNoon)
{
return fmod(357.5291 + 0.98560028 * (meanSolarNoon-2451545), 360);
}
double Sun::eqOfCenter(double meanSolarAnomaly)
{
return 1.9148*sin(meanSolarAnomaly*TO_RADS) + 0.0200*sin(2*meanSolarAnomaly*TO_RADS) + 0.0003*sin(3*meanSolarAnomaly*TO_RADS);
}
double Sun::eclipticLongitude(double eqOfCenter, double meanSolarAnomaly)
{
return fmod(meanSolarAnomaly + eqOfCenter + ARGUMENT_OF_PERIHELION + 180, 360); //hmmm
}
double Sun::equationOfTime(double meanSolarAnomaly, double eclipticLongitude) //wrong
{
return (-7.659*sin(meanSolarAnomaly*TO_RADS)+9.863*sin(2*(meanSolarAnomaly+eclipticLongitude)*TO_RADS))/60;
}
double Sun::localSolarTime(const JdTime& time, double equationOfTime)
{
return time.utcHour + equationOfTime + (4/60.0)*longetude_;
}
double Sun::solarDeclination(double eclipticLongitude)
{
return TO_DEGS*asin(sin(eclipticLongitude*TO_RADS)*sin(PLANETARY_AXIAL_TILT*TO_RADS));
}
double Sun::hourAngle(double localSolarTime)
{
return 360/24 * (localSolarTime - 12);
}
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(latitude_*TO_RADS))/(cos(latitude_*TO_RADS)*cos(solarDeclination*TO_RADS)));
}
double Sun::altitude()
{
JdTime time;
double meanSolarNoonValue = nextMeanSolarNoonJD(time);
double meanSolarAnomalyValue = meanSolarAnomaly(meanSolarNoonValue);
double eclipticLongitudeValue = eclipticLongitude(eqOfCenter(meanSolarAnomalyValue), meanSolarAnomalyValue);
double localSolarTimeValue = localSolarTime(time, equationOfTime(meanSolarAnomalyValue, eclipticLongitudeValue));
double declinationValue = solarDeclination(eclipticLongitudeValue);
double cosZenithAngle = sin(latitude_*TO_RADS)*sin(declinationValue*TO_RADS)+cos(latitude_*TO_RADS)*cos(declinationValue*TO_RADS)*cos(hourAngle(localSolarTimeValue)*TO_RADS);
return TO_DEGS*asin(cosZenithAngle);
}
double Sun::maximumAltitude()
{
JdTime time;
double meanSolarNoonValue = nextMeanSolarNoonJD(time);
double meanSolarAnomalyValue = meanSolarAnomaly(meanSolarNoonValue);
double eclipticLongitudeValue = eclipticLongitude(eqOfCenter(meanSolarAnomalyValue), meanSolarAnomalyValue);
double declinationValue = solarDeclination(eclipticLongitudeValue);
double cosZenithAngle = sin(latitude_*TO_RADS)*sin(declinationValue*TO_RADS)+cos(latitude_*TO_RADS)*cos(declinationValue*TO_RADS);
return TO_DEGS*asin(cosZenithAngle);
}
double Sun::azimuth()
{
return 0;
}
std::time_t Sun::riseTime()
{
JdTime time;
double meanSolarNoonValue = nextMeanSolarNoonJD(time);
double meanSolarAnomalyValue = meanSolarAnomaly(meanSolarNoonValue);
double eclipticLongitudeValue = eclipticLongitude(eqOfCenter(meanSolarAnomalyValue), meanSolarAnomalyValue);
double declinationValue = solarDeclination(eclipticLongitudeValue);
double hourAngleValue = hourAngleAtSunset(declinationValue);
time.julianDate = meanSolarNoonValue + equationOfTime(meanSolarAnomalyValue, eclipticLongitudeValue) - hourAngleValue/360.0;
return time.toStdTime();
}
std::time_t Sun::setTime()
{
JdTime time;
double meanSolarNoonValue = nextMeanSolarNoonJD(time);
double meanSolarAnomalyValue = meanSolarAnomaly(meanSolarNoonValue);
double eclipticLongitudeValue = eclipticLongitude(eqOfCenter(meanSolarAnomalyValue), meanSolarAnomalyValue);
double declinationValue = solarDeclination(eclipticLongitudeValue);
double hourAngleValue = hourAngleAtSunset(declinationValue);
time.julianDate = meanSolarNoonValue + equationOfTime(meanSolarAnomalyValue, eclipticLongitudeValue) + hourAngleValue/360.0;
return time.toStdTime();
}
double Sun::declination()
{
JdTime time;
double meanSolarNoonValue = nextMeanSolarNoonJD(time);
double meanSolarAnomalyValue = meanSolarAnomaly(meanSolarNoonValue);
return solarDeclination(eclipticLongitude(eqOfCenter(meanSolarAnomalyValue), meanSolarAnomalyValue));
}
double maximumAltitude()
{
return 0;
}

56
src/sun.h Normal file
View File

@ -0,0 +1,56 @@
// C++ program calculating the solar position for
// the current date and a set location (latitude, longitude)
// Jarmo Lammi 1999
//
// Code refreshed to work in the newer versions of C++
// ComM_PIled and tested with
// Apple LLVM version 6.0 (clang-600.0.56) (based on LLVM 3.5svn)
// Target: x86_64-apple-darwin14.0.0
// Jarmo Lammi 4-Jan-2015
#include <iostream>
#define _USE_MATH_DEFINES
#include <math.h>
#include <ctime>
class Sun
{
private:
static constexpr double TO_DEGS = 180.0/M_PI;
static constexpr double TO_RADS = M_PI/180.0;
static constexpr double SUN_DIA = 0.53; //degrees
static constexpr double AIR_REFRACTION = 34.0/60.0;
static constexpr double ARGUMENT_OF_PERIHELION = 102.9372;
static constexpr double PLANETARY_AXIAL_TILT = 23.44;
class JdTime;
double latitude_;
double longetude_;
double altitude_;
private:
double nextMeanSolarNoonJD(const JdTime& time);
double meanSolarAnomaly(double meanSolarNoon);
double eqOfCenter(double meanSolarAnomaly);
double eclipticLongitude(double eqOfCenter, double meanSolarAnomaly);
double solarTransit(double meanSolarNoon, double meanSolarAnomaly, double eclipticLongitude);
double solarDeclination(double eclipticLongitude);
double hourAngleAtSunset(double solarDeclination);
double hourAngle(double localSolarTime);
double equationOfTime(double meanSolarAnomaly, double eclipticLongitude);
double localSolarTime(const JdTime& time, double equationOfTime);
public:
Sun(double latitude, double longitude, double altitude = 0);
double altitude();
double maximumAltitude();
double azimuth();
double declination();
std::time_t riseTime();
std::time_t setTime();
};

20
src/suntest.cpp Normal file
View File

@ -0,0 +1,20 @@
#include <iostream>
#include "sun.h"
#include <iomanip>
int main()
{
std::cout<<std::setprecision(15);
Sun sun(49.884450, 8.650536);
std::time_t time = sun.setTime();
tm setTime = *localtime(&time);
time = sun.riseTime();
tm riseTime = *localtime(&time);
std::cout<<"sunset: "<<setTime.tm_hour<<':'<<setTime.tm_min<<std::endl;
std::cout<<"riseTime: "<<riseTime.tm_hour<<':'<<riseTime.tm_min<<std::endl;
std::cout<<"current Alt: "<<sun.altitude()<<std::endl;
std::cout<<"maximum Alt: "<<sun.maximumAltitude()<<std::endl;
std::cout<<"declination: "<<sun.declination()<<std::endl;
return 0;
}

View File

@ -1,14 +1,98 @@
#include "actorsettingsdialog.h"
#include "ui_actorsettingsdialog.h"
#include <QDebug>
#include <QSpinBox>
ActorSettingsDialog::ActorSettingsDialog(QWidget *parent) :
ActorSettingsDialog::ActorSettingsDialog(AlarmTime* alarm, QWidget *parent):
QDialog(parent),
actor_(alarm),
ui(new Ui::ActorSettingsDialog)
{
init();
widget = new AlarmWidget(alarm, this);
ui->vertlayout->addWidget(widget);
}
ActorSettingsDialog::ActorSettingsDialog(SensorActor* actor, SensorStore* sensors, QWidget *parent) :
QDialog(parent),
actor_(actor),
ui(new Ui::ActorSettingsDialog)
{
init();
widget = new SensorActorWidget(actor, sensors, this);
ui->vertlayout->addWidget(widget);
}
ActorSettingsDialog::ActorSettingsDialog(Regulator* actor, SensorStore* sensors, QWidget *parent) :
QDialog(parent),
actor_(actor),
ui(new Ui::ActorSettingsDialog)
{
init();
widget = new RegulatorWdiget(actor, sensors, this);
ui->vertlayout->addWidget(widget);
}
ActorSettingsDialog::ActorSettingsDialog(TimerActor* actor, QWidget *parent) :
QDialog(parent),
actor_(actor),
ui(new Ui::ActorSettingsDialog)
{
init();
widget = new TimerActorWidget(actor, this);
ui->vertlayout->addWidget(widget);
}
ActorSettingsDialog::ActorSettingsDialog(Actor* actor, QWidget *parent) :
QDialog(parent),
actor_(actor),
ui(new Ui::ActorSettingsDialog)
{
init();
}
void ActorSettingsDialog::init()
{
ui->setupUi(this);
connect(ui->comboBox_action, SIGNAL(currentIndexChanged(int)), this, SLOT(changeAction(int)));
connect(ui->spinBox, SIGNAL(valueChanged(int)), this, SLOT(valueChanged(int)));
ui->spinBox->hide();
ui->spinBox->setValue(actor_->getTriggerValue());
if(actor_->getTriggerValue() == 0) ui->comboBox_action->setCurrentIndex(0);
else if(actor_->getTriggerValue() == 1) ui->comboBox_action->setCurrentIndex(1);
else ui->comboBox_action->setCurrentIndex(2);
}
ActorSettingsDialog::~ActorSettingsDialog()
{
delete ui;
}
void ActorSettingsDialog::valueChanged(int value)
{
actor_->setTriggerValue(value);
}
void ActorSettingsDialog::hideCancle(const bool hide)
{
}
void ActorSettingsDialog::changeAction(int index)
{
if(index == 0) actor_->setTriggerValue(0);
else if(index == 1) actor_->setTriggerValue(1);
else if(index == 2)
{
ui->spinBox->show();
actor_->setTriggerValue(ui->spinBox->value());
}
if(index != 2)ui->spinBox->hide();
}

View File

@ -2,6 +2,11 @@
#define ACTORSETTINGSDIALOG_H
#include <QDialog>
#include <QWidget>
#include "actorwidgets/alarmwidget.h"
#include "actorwidgets/sensoractorwidget.h"
#include "actorwidgets/timeractorwidget.h"
#include "actorwidgets/regulatorwdiget.h"
namespace Ui {
class ActorSettingsDialog;
@ -11,10 +16,27 @@ class ActorSettingsDialog : public QDialog
{
Q_OBJECT
private:
Actor* actor_;
QWidget* widget;
void init();
public:
explicit ActorSettingsDialog(QWidget *parent = nullptr);
ActorSettingsDialog(AlarmTime* actor, QWidget *parent = nullptr);
ActorSettingsDialog(SensorActor* actor, SensorStore* sensors = nullptr, QWidget *parent = nullptr);
ActorSettingsDialog(Regulator* actor, SensorStore* sensors = nullptr, QWidget *parent = nullptr);
ActorSettingsDialog(TimerActor* actor, QWidget *parent);
ActorSettingsDialog(Actor* actor, QWidget *parent);
~ActorSettingsDialog();
void hideCancle(const bool hide);
private slots:
void changeAction(int index);
void valueChanged(int value);
private:
Ui::ActorSettingsDialog *ui;
};

View File

@ -11,7 +11,11 @@
</rect>
</property>
<property name="windowTitle">
<string>Dialog</string>
<string>Actor Settings</string>
</property>
<property name="windowIcon">
<iconset resource="../../resources.qrc">
<normaloff>:/images/UVOSicon.bmp</normaloff>:/images/UVOSicon.bmp</iconset>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
@ -33,11 +37,6 @@
</item>
<item>
<widget class="QComboBox" name="comboBox_action">
<item>
<property name="text">
<string>On</string>
</property>
</item>
<item>
<property name="text">
<string>Off</string>
@ -45,9 +44,21 @@
</item>
<item>
<property name="text">
<string>Toggle</string>
<string>On</string>
</property>
</item>
<item>
<property name="text">
<string>Value</string>
</property>
</item>
</widget>
</item>
<item>
<widget class="QSpinBox" name="spinBox">
<property name="maximum">
<number>255</number>
</property>
</widget>
</item>
</layout>
@ -66,7 +77,9 @@
</item>
</layout>
</widget>
<resources/>
<resources>
<include location="../../resources.qrc"/>
</resources>
<connections>
<connection>
<sender>buttonBox</sender>

View File

@ -0,0 +1,73 @@
#include "alarmwidget.h"
#include "ui_alarmwidget.h"
AlarmWidget::AlarmWidget(AlarmTime* alarm, QWidget *parent) :
QWidget(parent),
alarm_(alarm),
ui(new Ui::AlarmWidget)
{
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());
if(alarm_->getRepeat() == AlarmTime::REPEAT_NEVER)
{
ui->radioButton->setEnabled(false);
ui->radioButton_2->setEnabled(false);
ui->radioButton_3->setEnabled(false);
ui->radioButton_4->setEnabled(false);
}
else
{
ui->radioButton->setEnabled(true);
ui->radioButton_2->setEnabled(true);
ui->radioButton_3->setEnabled(true);
ui->radioButton_4->setEnabled(true);
}
if(alarm_->getRepeat() == AlarmTime::REPEAT_DAILY) ui->radioButton->setChecked(true);
else if(alarm_->getRepeat() == AlarmTime::REPEAT_WEEKLY) ui->radioButton_2->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->dateTimeEdit, &QDateTimeEdit::dateTimeChanged, alarm, &AlarmTime::changeTime);
}
AlarmWidget::~AlarmWidget()
{
delete ui;
}
void AlarmWidget::setRepeatingType()
{
if(ui->radioButton->isChecked())alarm_->setRepeat(AlarmTime::REPEAT_DAILY);
if(ui->radioButton_2->isChecked())alarm_->setRepeat(AlarmTime::REPEAT_WEEKLY);
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)
{
if(state)
{
ui->radioButton->setEnabled(true);
ui->radioButton_2->setEnabled(true);
ui->radioButton_3->setEnabled(true);
ui->radioButton_4->setEnabled(true);
setRepeatingType();
}
else
{
alarm_->setRepeat(AlarmTime::REPEAT_NEVER);
ui->radioButton->setEnabled(false);
ui->radioButton_2->setEnabled(false);
ui->radioButton_3->setEnabled(false);
ui->radioButton_4->setEnabled(false);
}
}

View File

@ -2,6 +2,7 @@
#define ALARMWIDGET_H
#include <QWidget>
#include "../../actors/alarmtime.h"
namespace Ui {
class AlarmWidget;
@ -11,10 +12,16 @@ class AlarmWidget : public QWidget
{
Q_OBJECT
AlarmTime* alarm_;
public:
explicit AlarmWidget(QWidget *parent = nullptr);
explicit AlarmWidget(AlarmTime* alarm, QWidget *parent = nullptr);
~AlarmWidget();
private slots:
void toggleRepeating(int state);
void setRepeatingType();
private:
Ui::AlarmWidget *ui;
};

View File

@ -7,7 +7,7 @@
<x>0</x>
<y>0</y>
<width>357</width>
<height>166</height>
<height>208</height>
</rect>
</property>
<property name="sizePolicy">
@ -60,7 +60,7 @@
<enum>QDateTimeEdit::DaySection</enum>
</property>
<property name="displayFormat">
<string>dd.mM.yyyy hh:mm</string>
<string>dd.MM.yyyy hh:mm</string>
</property>
<property name="calendarPopup">
<bool>true</bool>
@ -90,7 +90,7 @@
<bool>false</bool>
</property>
<property name="text">
<string>Monthly</string>
<string>&amp;Monthly</string>
</property>
</widget>
</item>

View File

@ -0,0 +1,48 @@
#include "regulatorwdiget.h"
#include "ui_regulatorwdiget.h"
#include <QDebug>
RegulatorWdiget::~RegulatorWdiget()
{
delete ui;
}
RegulatorWdiget::RegulatorWdiget(Regulator* regulator, SensorStore* sensors, QWidget *parent) :
QWidget(parent),
regulator_(regulator),
sensors_(sensors),
ui(new Ui::RegulatorWdiget)
{
ui->setupUi(this);
if(sensors)ui->listView->sensorsChanged(*(sensors->getSensors()));
else
{
ui->listView->hide();
ui->label->hide();
}
ui->doubleSpinBox_setPoint->setValue(regulator->getSetPoint());
ui->doubleSpinBox_band->setValue(regulator->getBand());
connect(ui->listView, &SensorListWidget::clicked, this, &RegulatorWdiget::setSensor);
connect(ui->doubleSpinBox_setPoint, SIGNAL(valueChanged(double)), this, SLOT(setPoint(double)));
connect(ui->doubleSpinBox_band, SIGNAL(valueChanged(double)), this, SLOT(setBand(double)));
}
void RegulatorWdiget::setPoint(double in)
{
regulator_->setPoint(in);
}
void RegulatorWdiget::setBand(double band)
{
regulator_->setBand(band);
}
void RegulatorWdiget::setSensor(const QModelIndex &index)
{
regulator_->setSensor(sensors_->getSensors()->at(index.row()));
setPoint(sensors_->getSensors()->at(index.row()).field);
ui->doubleSpinBox_setPoint->setValue(sensors_->getSensors()->at(index.row()).field);
}

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