MainWindow
::MainWindow(QWidget *parent
) : ui(new Ui::MainWindow)
{
ui->setupUi(this);
ComPort::get().open();
connect(this,
SIGNAL(destroyed
(QObject*)), thread,
SLOT(quit
()));
valve = new Valve(7);
connect(valve, SIGNAL(remoteStatus(bool)), this, SLOT(remoteStatus(bool)));
valve->moveToThread(thread);
connect(valvesReadTimer, SIGNAL(timeout()), valve, SLOT(getAllStates()));
valvesReadTimer->start(1000);
connect(passform, SIGNAL(manualModeEmit(bool)),
this, SLOT(manualMode(bool)));
emergency = new EmergencyResetOfPressure();
connect(emergency, SIGNAL(openValveSignal(int)), this, SLOT(openValve(int)));
connect(emergency, SIGNAL(closeValveSignal(int)), this, SLOT(closeValve(int)));
//emergency->start();
emergency->moveToThread(emergency);
emergency->start();
thread->start();
initActionConnection();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::valveSwitch(int id) //переключатель клапанов
{
if (valve->getState(id))
closeValve(id);
else
openValve(id);
}
void MainWindow::openValve(int id)
{
valveButton[id]->setEnabled(false);
if (valve->open(id)) {
if (manualModeState)
valveButton[id]->setEnabled(true);
//valveButton[id]->setPalette(QPalette(Qt::green));
//valveButton[id]->setStyleSheet(VALVE_OPEN_COLOR);
valveButton[id]->setStyleSheet(style);
ui->mainLabel->setText(str + " открыл! :)");
}
else {
if (manualModeState)
valveButton[id]->setEnabled(true);
ui->mainLabel->setText("Ðе могу открыть " + str);
remoteStatus(0);
}
}
void MainWindow::closeValve(int id)
{
valveButton[id]->setEnabled(false);
if (valve->close(id)) {
if (manualModeState)
valveButton[id]->setEnabled(true);
//valveButton[id]->setPalette(style()->standardPalette());
valveButton[id]->setStyleSheet("");
ui->mainLabel->setText(str + " закрыл! :)");
}
else {
if (manualModeState)
valveButton[id]->setEnabled(true);
ui->mainLabel->setText("Ðе могу закрыть " + str);
remoteStatus(0);
}
}
void MainWindow::pressureDrop() //ИÑпытание по методу "Спад давлениÑ"
{
emergency->begin();
ui->mainLabel->setText("ИÑпытание по методу \n Спад давлениÑ");
}
void MainWindow::initActionConnection()
{
//обработка нажатий на кнопки клапанов
QSignalMapper* signalMapper
= new QSignalMapper (this);
//чтобы можно было обработать Ñ„-ÑŽ Ñ Ð°Ñ€Ð³ÑƒÐ¼ÐµÐ½Ñ‚Ð¾Ð¼ в Слоте for(int i = 0; i < 7; i++)
signalMapper->setMapping(valveButton[i], i);
for(int i = 0; i < 7; i++)
connect(valveButton[i], SIGNAL(clicked()), signalMapper, SLOT(map()));
connect(signalMapper, SIGNAL(mapped(int)), this, SLOT(valveSwitch(int)));
connect(ui->pressureTestButton, SIGNAL(clicked(bool)), this, SLOT(pressureDrop())); //опреÑÑовка и иÑпытание на прочноÑть
}
EmergencyResetOfPressure
::EmergencyResetOfPressure(QObject *parent
) : QThread(parent
){
}
EmergencyResetOfPressure::~EmergencyResetOfPressure()
{
}
void EmergencyResetOfPressure::begin()
{
for (int i = 0; i<7; i++)
{
//sleep(1);
emit openValveSignal(i);
}
for (int i = 0; i<7; i++)
{
//sleep(1);
emit closeValveSignal(i);
}
}
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
ComPort::get().open();
thread = new QThread(this);
connect(this, SIGNAL(destroyed(QObject*)), thread, SLOT(quit()));
valve = new Valve(7);
connect(valve, SIGNAL(remoteStatus(bool)), this, SLOT(remoteStatus(bool)));
valve->moveToThread(thread);
QTimer *valvesReadTimer = new QTimer(this);
connect(valvesReadTimer, SIGNAL(timeout()), valve, SLOT(getAllStates()));
valvesReadTimer->start(1000);
connect(passform, SIGNAL(manualModeEmit(bool)),
this, SLOT(manualMode(bool)));
emergency = new EmergencyResetOfPressure();
connect(emergency, SIGNAL(openValveSignal(int)), this, SLOT(openValve(int)));
connect(emergency, SIGNAL(closeValveSignal(int)), this, SLOT(closeValve(int)));
//emergency->start();
emergency->moveToThread(emergency);
emergency->start();
thread->start();
initActionConnection();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::valveSwitch(int id) //переключатель клапанов
{
if (valve->getState(id))
closeValve(id);
else
openValve(id);
}
void MainWindow::openValve(int id)
{
QString str = "Клапан №" + QString::number(id+1);
valveButton[id]->setEnabled(false);
if (valve->open(id)) {
if (manualModeState)
valveButton[id]->setEnabled(true);
//valveButton[id]->setPalette(QPalette(Qt::green));
//valveButton[id]->setStyleSheet(VALVE_OPEN_COLOR);
QString style = QString(DEFAULT_STYLE_BUTTON) + QString(DEFAULT_BACKGROUND_BUTTON);
valveButton[id]->setStyleSheet(style);
ui->mainLabel->setText(str + " открыл! :)");
}
else {
if (manualModeState)
valveButton[id]->setEnabled(true);
ui->mainLabel->setText("Ðе могу открыть " + str);
remoteStatus(0);
}
}
void MainWindow::closeValve(int id)
{
QString str = "Клапан №" + QString::number(id+1);
valveButton[id]->setEnabled(false);
if (valve->close(id)) {
if (manualModeState)
valveButton[id]->setEnabled(true);
//valveButton[id]->setPalette(style()->standardPalette());
valveButton[id]->setStyleSheet("");
ui->mainLabel->setText(str + " закрыл! :)");
}
else {
if (manualModeState)
valveButton[id]->setEnabled(true);
ui->mainLabel->setText("Ðе могу закрыть " + str);
remoteStatus(0);
}
}
void MainWindow::pressureDrop() //ИÑпытание по методу "Спад давлениÑ"
{
emergency->begin();
ui->mainLabel->setText("ИÑпытание по методу \n Спад давлениÑ");
}
void MainWindow::initActionConnection()
{
//обработка нажатий на кнопки клапанов
QSignalMapper* signalMapper = new QSignalMapper (this); //чтобы можно было обработать Ñ„-ÑŽ Ñ Ð°Ñ€Ð³ÑƒÐ¼ÐµÐ½Ñ‚Ð¾Ð¼ в Слоте
for(int i = 0; i < 7; i++)
signalMapper->setMapping(valveButton[i], i);
for(int i = 0; i < 7; i++)
connect(valveButton[i], SIGNAL(clicked()), signalMapper, SLOT(map()));
connect(signalMapper, SIGNAL(mapped(int)), this, SLOT(valveSwitch(int)));
connect(ui->pressureTestButton, SIGNAL(clicked(bool)), this, SLOT(pressureDrop())); //опреÑÑовка и иÑпытание на прочноÑть
}
EmergencyResetOfPressure::EmergencyResetOfPressure(QObject *parent) : QThread(parent)
{
}
EmergencyResetOfPressure::~EmergencyResetOfPressure()
{
}
void EmergencyResetOfPressure::begin()
{
for (int i = 0; i<7; i++)
{
//sleep(1);
emit openValveSignal(i);
}
for (int i = 0; i<7; i++)
{
//sleep(1);
emit closeValveSignal(i);
}
}
To copy to clipboard, switch view to plain text mode
class ComPort
: public QObject { //клаÑÑ Ñинглтон Q_OBJECT
private:
QSerialPort *serial;
explicit ComPort
(QObject *parent
= 0);
~ComPort();
//защита от копированиÑ
ComPort(ComPort const&) = delete;
ComPort& operator= (ComPort const&) = delete;
int timeoutCount = 0;
int responseCount = 0;
public:
static ComPort& get()
{
static ComPort instance;
return instance;
}
void open();
void close();
private slots:
void readData();
void handleError(QSerialPort::SerialPortError error);
};
class ComPort : public QObject { //клаÑÑ Ñинглтон
Q_OBJECT
private:
QString portName;
QSerialPort *serial;
explicit ComPort(QObject *parent = 0);
~ComPort();
//защита от копированиÑ
ComPort(ComPort const&) = delete;
ComPort& operator= (ComPort const&) = delete;
int timeoutCount = 0;
int responseCount = 0;
public:
QByteArray buffer;
static ComPort& get()
{
static ComPort instance;
return instance;
}
void open();
void close();
QByteArray requestResponse(const QByteArray &data);
void write(const QByteArray &data);
bool crcCheck(const QByteArray &data);
private slots:
void readData();
void handleError(QSerialPort::SerialPortError error);
};
To copy to clipboard, switch view to plain text mode
Valve
::Valve(int size,
QObject *parent
) : QObject(parent
) //конÑтруктор{
valveState.resize(size);
for(int i = 0; i < size; i++)
{
valveState[i] = false;
}
}
Valve::~Valve() //деÑтруктор
{
}
bool Valve::open(int id)
{
arr.resize(7);
arr[0] = 0xAB;
arr[1] = 0x01;
arr[2] = 0x02;
arr[3] = 0x02;
arr[4] = id+1;
arr[5] = 0xFF;
arr[6] = 0x00 - arr[1] - arr[2] - arr[3] - arr[4] - arr[5];
QByteArray response
= ComPort
::get().
requestResponse(arr
);
if(response[0] == arr[0])
{
qDebug() << "клапан №: " << id+1 << " открыт!";
valveState[id] = true;
emit remoteStatus(1);
return 1;
}
emit remoteStatus(0);
return 0;
}
bool Valve::close(int id)
{
arr.resize(7);
arr[0] = 0xAB;
arr[1] = 0x01;
arr[2] = 0x02;
arr[3] = 0x02;
arr[4] = id+1;
arr[5] = 0x00;
arr[6] = 0x00 - arr[1] - arr[2] - arr[3] - arr[4] - arr[5];
QByteArray response
= ComPort
::get().
requestResponse(arr
);
if(response[0] == arr[0])
{
qDebug() << "клапан №: " << id+1 << " закрыт!";
valveState[id] = false;
emit remoteStatus(1);
return 1;
}
emit remoteStatus(0);
return 0;
}
/*****************************************
* КлаÑÑ Ð´Ð»Ñ Ñ€Ð°Ð±Ð¾Ñ‚Ñ‹ Ñ COM портом
* **************************************/
{
buffer = "";
serial = new QSerialPort();
connect(serial, SIGNAL(error(QSerialPort::SerialPortError)), this, SLOT(handleError(QSerialPort::SerialPortError)));
}
ComPort::~ComPort()
{
}
void ComPort::open()
{
if(serial->isOpen())
close();
if(portName != Config::get().getValue("COM/name").toString())
{
qDebug() << "Порт " << portName << "ÑменилÑÑ Ð½Ð° " << Config::get().getValue("COM/name").toString();
portName = Config::get().getValue("COM/name").toString();
}
serial->setPortName(portName);
if (serial->setBaudRate(QSerialPort::Baud115200)
&& serial->setFlowControl(QSerialPort::NoFlowControl)) {
qDebug() << "Порт открыт";
} else {
//QMessageBox::critical(this, "Error", serial->errorString());
qDebug
() <<
QString(serial
->errorString
());
serial->close();
}
} else {
//QMessageBox::critical(this, QObject::tr("Error"), serial->errorString());
}
}
{
qDebug() << "-------------------------";
int attempts = 1;
while (attempts <= REQATTEMPTS) { //3 попытки
if (serial->isWritable())
{
serial->write(data);
qDebug() << "Попытка № " << attempts;
qDebug() << "ЗапроÑ: " << data.toHex();
while (serial->waitForReadyRead(WAITFORREADY)) {
readBuf += serial->readAll();
if (crcCheck(readBuf) && data[2] == readBuf[2] ){ //еÑли CRC и команда ÑошлиÑÑŒ -- уÑпех!
qDebug() << "Ответ: " << readBuf.toHex();
responseCount++;
qDebug() << "Кол-во запроÑов: " << responseCount;
qDebug() << "Кол-во таймаутов: " << timeoutCount;
float percent = timeoutCount * 100;
percent = percent / responseCount;
qDebug
() <<
"Процент коÑÑков: " <<
QString::number(percent,
'f',
3) <<
"%";
close();
open();
return readBuf;
}
}
readBuf.clear();
qDebug() << "Таймаут...";
timeoutCount++;
close();
open();
attempts++;
}
else
{
qDebug() << "Порт " << portName << " не пишетÑÑ!";
return 0;
}
}
// close();
// open();
return 0;
}
void ComPort::close()
{
serial->close();
qDebug() << "Порт закрыт";
}
{
serial->write(data);
qDebug() << "ЗапроÑ: " << data.toHex();
}
void ComPort::readData()
{
buffer = serial->readAll();
if (ComPort::get().crcCheck(buffer))
{
qDebug() << "Ответ: " << buffer.toHex();
qDebug() << "---------------------------";
}
}
void ComPort::handleError(QSerialPort::SerialPortError error)
{
if (error == QSerialPort::ResourceError) {
ComPort::get().close();
qDebug() << "что-то не так!";
}
}
Valve::Valve(int size, QObject *parent) : QObject(parent) //конÑтруктор
{
valveState.resize(size);
for(int i = 0; i < size; i++)
{
valveState[i] = false;
}
}
Valve::~Valve() //деÑтруктор
{
}
bool Valve::open(int id)
{
QByteArray arr;
arr.resize(7);
arr[0] = 0xAB;
arr[1] = 0x01;
arr[2] = 0x02;
arr[3] = 0x02;
arr[4] = id+1;
arr[5] = 0xFF;
arr[6] = 0x00 - arr[1] - arr[2] - arr[3] - arr[4] - arr[5];
QByteArray response = ComPort::get().requestResponse(arr);
if(response[0] == arr[0])
{
qDebug() << "клапан №: " << id+1 << " открыт!";
valveState[id] = true;
emit remoteStatus(1);
return 1;
}
emit remoteStatus(0);
return 0;
}
bool Valve::close(int id)
{
QByteArray arr;
arr.resize(7);
arr[0] = 0xAB;
arr[1] = 0x01;
arr[2] = 0x02;
arr[3] = 0x02;
arr[4] = id+1;
arr[5] = 0x00;
arr[6] = 0x00 - arr[1] - arr[2] - arr[3] - arr[4] - arr[5];
QByteArray response = ComPort::get().requestResponse(arr);
if(response[0] == arr[0])
{
qDebug() << "клапан №: " << id+1 << " закрыт!";
valveState[id] = false;
emit remoteStatus(1);
return 1;
}
emit remoteStatus(0);
return 0;
}
/*****************************************
* КлаÑÑ Ð´Ð»Ñ Ñ€Ð°Ð±Ð¾Ñ‚Ñ‹ Ñ COM портом
* **************************************/
ComPort::ComPort(QObject *parent) : QObject(parent)
{
buffer = "";
serial = new QSerialPort();
connect(serial, SIGNAL(error(QSerialPort::SerialPortError)), this, SLOT(handleError(QSerialPort::SerialPortError)));
}
ComPort::~ComPort()
{
}
void ComPort::open()
{
if(serial->isOpen())
close();
if(portName != Config::get().getValue("COM/name").toString())
{
qDebug() << "Порт " << portName << "ÑменилÑÑ Ð½Ð° " << Config::get().getValue("COM/name").toString();
portName = Config::get().getValue("COM/name").toString();
}
serial->setPortName(portName);
if (serial->open(QIODevice::ReadWrite)) {
if (serial->setBaudRate(QSerialPort::Baud115200)
&& serial->setFlowControl(QSerialPort::NoFlowControl)) {
qDebug() << "Порт открыт";
} else {
//QMessageBox::critical(this, "Error", serial->errorString());
qDebug() << QString(serial->errorString());
serial->close();
}
} else {
//QMessageBox::critical(this, QObject::tr("Error"), serial->errorString());
}
}
QByteArray ComPort::requestResponse(const QByteArray &data)
{
QByteArray readBuf;
qDebug() << "-------------------------";
int attempts = 1;
while (attempts <= REQATTEMPTS) { //3 попытки
if (serial->isWritable())
{
serial->write(data);
qDebug() << "Попытка № " << attempts;
qDebug() << "ЗапроÑ: " << data.toHex();
while (serial->waitForReadyRead(WAITFORREADY)) {
readBuf += serial->readAll();
if (crcCheck(readBuf) && data[2] == readBuf[2] ){ //еÑли CRC и команда ÑошлиÑÑŒ -- уÑпех!
qDebug() << "Ответ: " << readBuf.toHex();
responseCount++;
qDebug() << "Кол-во запроÑов: " << responseCount;
qDebug() << "Кол-во таймаутов: " << timeoutCount;
float percent = timeoutCount * 100;
percent = percent / responseCount;
qDebug() << "Процент коÑÑков: " << QString::number(percent, 'f', 3) << "%";
close();
open();
return readBuf;
}
}
readBuf.clear();
qDebug() << "Таймаут...";
timeoutCount++;
close();
open();
attempts++;
}
else
{
qDebug() << "Порт " << portName << " не пишетÑÑ!";
return 0;
}
}
// close();
// open();
return 0;
}
void ComPort::close()
{
serial->close();
qDebug() << "Порт закрыт";
}
void ComPort::write(const QByteArray &data)
{
serial->write(data);
qDebug() << "ЗапроÑ: " << data.toHex();
}
void ComPort::readData()
{
buffer = serial->readAll();
if (ComPort::get().crcCheck(buffer))
{
qDebug() << "Ответ: " << buffer.toHex();
qDebug() << "---------------------------";
}
}
void ComPort::handleError(QSerialPort::SerialPortError error)
{
if (error == QSerialPort::ResourceError) {
ComPort::get().close();
qDebug() << "что-то не так!";
}
}
To copy to clipboard, switch view to plain text mode
Bookmarks