A1210_Desktop/mainwindow.cpp

574 lines
16 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#include "mainwindow.h"
#include "ui_mainwindow.h"
//подключаем последующие окна
#include "setpribor.h"
#include "enums.h"
#include "QDebug"
#include "comWorks.h"
#include "qvalidator.h"
#include "cstring"
#include "QThread"
#include "QInputDialog"
#include <vector>
#include <QSettings>
#include "secondwindows.h"
const char *STRINGS_OUTUNITS[] = {"0.0001мВ/",
"0.0002мВ/",
"0.0005мВ/",
"0.001мВ/", //3
"0.002мВ/",
"0.005мВ/",
"0.01мВ/",//6
"0.02мВ/",
"0.05мВ/",
"0.1мВ/",//9
"0.2мВ/",
"0.5мВ/",
"В/",//12
"В/",
"В/",
"10мВ/",//15
"20мВ/",
"50мВ/",
"100мВ/",//18
"200мВ/",
"500мВ/",
"1В/",//21
"2В/",
"5В/",
"10В/",//24
"20В/",
"50В/",
"100В/",//27
"200В/",
"500В/",
"1000В/", //30
};
const char *STRINGS_UNITS[]={"м/с2","мм/с","Па","кПа","МПа", "Н","кН","мВ"}; // массив с единицами измерений
MainWindow::MainWindow(QWidget *parent): QMainWindow(parent), ui(new Ui::MainWindow)
{
conf = new QSettings();
ui->setupUi(this);
//Перенос хэндлера в друглй поток- перечтают работать сигналы
// modeBusThread = new QThread(this);
modebus = new ModBusHandler();
// modebus ->moveToThread(modeBusThread);
// modeBusThread->start();
connect(modebus, SIGNAL(dataRecivedNotify(DataStruct)),this, SLOT(dataSetter(DataStruct)));
//по получению данных проверяем адрес раскидываем их по переменным
//и обновляем экран
QWidget::setWindowTitle("А1210");
QWidget::setFixedSize( 314, 372 );
OffsetKuDisplay=0;
isConnected = false;
//формирую комбобокс для установки скорости
extern const uint32_t BAUDRATE[];
for(uint i = 0; i<10; i++){ui->comboBoxSpeed->addItem(QString::number(BAUDRATE[i]));
}
//формирую данные для комбобокса бита четности
ui->comboBoxBit->addItem("Нет"); // Добавляем в список доступных
ui->comboBoxBit->addItem("Четности"); // Добавляем в список доступных
ui->comboBoxBit->addItem("Нечетности"); // Добавляем в список доступных
// Перечислим порты в консоль
foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts()){ //для каждого доступного порта
QSerialPort port; //
port.setPort(info); //
if(port.open(QIODevice::ReadWrite)){// если порт доступен
ui->comboBoxPort->addItem(info.portName()); // Добавляем в список доступных
comList.push_back(info.portName());
}
}//конец foreach
// значения для полей из сохраненных значений
ui->comboBoxPort->setCurrentIndex(conf->value("section1/keyCurrentPort").toInt());
ui->comboBoxSpeed->setCurrentIndex(conf->value("section1/keyCurrentSpeed").toInt());
ui->comboBoxBit->setCurrentIndex(conf->value("section1/keyCurrentBit").toInt());
ui->lineEditAddr->setText(conf->value("section1/keyAdress").toString());
//передаем текущие значения полей в глобальные переменные
adrValue=ui->lineEditAddr->text();
bitComboboxIndex=ui->comboBoxBit->currentIndex();
portComboboxIndex=ui->comboBoxPort->currentIndex();
speedComboboxIndex=ui->comboBoxSpeed->currentIndex();
//заполняю статические комбобоксы
ui->comboBoxPlavGround->addItem("ОЗ");
ui->comboBoxPlavGround->addItem("ПЗ");
ui->comboBoxNch->addItem("0.1");
ui->comboBoxNch->addItem("0.3");
ui->comboBoxNch->addItem("1");
ui->comboBoxNch->addItem("3");
ui->comboBoxNch->addItem("10");
ui->comboBoxNch->addItem("30");
ui->comboBoxNch->addItem("100");
ui->comboBoxVch->addItem("0.2");
ui->comboBoxVch->addItem("1");
ui->comboBoxVch->addItem("2");
ui->comboBoxVch->addItem("10");
ui->comboBoxUnitSens->addItem("пКл/м/с2");
ui->comboBoxUnitSens->addItem("пКл/мм/с");
ui->comboBoxUnitSens->addItem("пКл/Па");
ui->comboBoxUnitSens->addItem("пКл/кПа");
ui->comboBoxUnitSens->addItem("пКл/МПа");
ui->comboBoxUnitSens->addItem("пКл/Н");
ui->comboBoxUnitSens->addItem("пКл/кН");
ui->comboBoxUnitSens->addItem("пКл/мВ");
//"м/с2","мм/с","Па","кПа","МПа", "Н","кН","кВ"
hideInteface();
}//конец конструктора главного окна
MainWindow::~MainWindow()
{
qDebug()<<ui->comboBoxPort->currentIndex();
//сохранение значения полей
conf->setValue("section1/keyCurrentPort", ui->comboBoxPort->currentIndex());
conf->setValue("section1/keyCurrentSpeed", ui->comboBoxSpeed->currentIndex());
conf->setValue("section1/keyCurrentBit", ui->comboBoxBit->currentIndex());
conf->setValue("section1/keyAdress", ui->lineEditAddr->text());
// modeBusThread->quit();
// modeBusThread->wait(1000);
delete ui;
}
void MainWindow::dataSetter(DataStruct data)
{
if(adrPri==data.adress){
state=data;
refreshDisplay();
}
}
void MainWindow::hideInteface()
{
ui->label_4->hide();
ui->label_8->hide();
ui->label_11->hide();
ui->label_13->hide();
ui->label_14->hide();
ui->label_16->hide();
ui->labelSens->hide();
ui->labelOverload->hide();
ui->comboBoxKu->hide();
ui->comboBoxNch->hide();
ui->comboBoxVch->hide();
ui->comboBoxUnitSens->hide();
ui->comboBoxPlavGround->hide();
}
void MainWindow::showInteface()
{
ui->label_4->show();
ui->label_8->show();
ui->label_11->show();
ui->label_13->show();
ui->label_14->show();
ui->label_16->show();
ui->labelSens->show();
ui->labelOverload->show();
ui->comboBoxKu->show();
ui->comboBoxVch->show();
ui->comboBoxNch->show();
ui->comboBoxUnitSens->show();
ui->comboBoxPlavGround->show();
}
//todo: заблокировать элементы управления без подключения
void MainWindow::on_pushButtonConnect_clicked()
{
adrPri=ui->lineEditAddr->text().toInt(); //todo:добавить валидатор для адреса
if(isConnected==false){
PrborConnectonAtr thisPribor;
thisPribor.port=ui->comboBoxPort->currentText();
thisPribor.adress=ui->lineEditAddr->text().toInt();
thisPribor.speed=(ui->comboBoxSpeed->currentText().toInt());
thisPribor.parity=(Parity)ui->comboBoxBit->currentIndex();
modebus->addToReqList(thisPribor); //добавляем прибор в список опрашиваемых
ui->pushButtonConnect->setText("Отключение");
//блокируем элементы
ui->lineEditAddr->setDisabled(true);
ui->pushButtonSetPri->setDisabled(true);
ui->comboBoxPort->setDisabled(true);
ui->comboBoxBit->setDisabled(true);
ui->comboBoxSpeed->setDisabled(true);
isConnected=true;
}
else if(isConnected==true){
modebus->removeFromReqList(adrPri);
//удаляем прибор с данным адресом из списка
//разблокируем элементы
ui->lineEditAddr->setDisabled(false);
ui->comboBoxPort->setDisabled(false);
ui->pushButtonSetPri->setDisabled(false);
ui->comboBoxBit->setDisabled(false);
ui->comboBoxSpeed->setDisabled(false);
ui->pushButtonConnect->setText("Подключение");
hideInteface();
isConnected=false;
}
}
void MainWindow::on_pushButtonAddPri_clicked()
{
SecondWindows *w2 = new SecondWindows(this);
w2->show();
}
void MainWindow::on_pushButtonSetPri_clicked()
{
SetPribor *w2 = new SetPribor(this); //передаем в новый обьект указатель на существующий для доступа к нему
w2->exec();
/*
SetPribor setpribor;
setpribor.setModal(true);
setpribor.exec();
*/
}
void MainWindow::getSens(){
// sens=readSens(serial, adrPri);
};
void MainWindow::getState(){
// state = readSet(serial, adrPri);
};
void MainWindow::setState(){
}
void MainWindow::refreshDisplay(){
//делаем дополнение до 6 знаков
if(state.sens==1000) { ui->labelSens->setText(QString::number(state.sens,'f', 1));}
else if(state.sens<1000&&state.sens>=100) {ui->labelSens->setText(QString::number(state.sens,'f', 2));}
else if(state.sens<100&&state.sens>=10){ui->labelSens->setText(QString::number(state.sens,'f', 3));}
else {ui->labelSens->setText(QString::number(state.sens,'f', 4));}
//с автоподгонкой всё начинает прыгать. Я думаю всё прокатит если её применять тоьлко по изменеию содержимого
//ui->labelSens->adjustSize(); //подгоняем размер по содержимому
switch (state.fn) {
case Lp100:
ui->comboBoxNch->setCurrentIndex(0);
break;
case Lp300:
ui->comboBoxNch->setCurrentIndex(1);
break;
case Lp1000:
ui->comboBoxNch->setCurrentIndex(2);
break;
case Lp3000:
ui->comboBoxNch->setCurrentIndex(3);
break;
case Lp10000:
ui->comboBoxNch->setCurrentIndex(4);
break;
case Lp30000:
ui->comboBoxNch->setCurrentIndex(5);
break;
case Lp100000:
ui->comboBoxNch->setCurrentIndex(6);
break;
default:
// ui->labelNch->setText("#####");
break;
}
switch (state.fv) {
case Hp0_2 :
ui->comboBoxVch->setCurrentIndex(0);
break;
case Hp1:
ui->comboBoxVch->setCurrentIndex(1);
break;
case Hp2:
ui->comboBoxVch->setCurrentIndex(2);
break;
case Hp10:
ui->comboBoxVch->setCurrentIndex(3);
break;
default:
break;
}
////////////////////////////////////
///// вывод юнитов и нормирование///
////////////////////////////////////
////Аналогично прибору считаем смещение по массиву значений
///
if (state.sens>=0.0001&&state.sens<0.001) {OffsetKuDisplay=0;} // такие значения не допустимы
else if (state.sens>=0.001&&state.sens<0.01){OffsetKuDisplay=0;}
else if (state.sens>=0.01&&state.sens<0.1){OffsetKuDisplay=3; }
else if (state.sens>=0.1&&state.sens<1){OffsetKuDisplay=6;}
else if (state.sens>=1&&state.sens<10){OffsetKuDisplay=9;}
else if (state.sens>=10&&state.sens<100){OffsetKuDisplay=12;}
else if (state.sens>=100&&state.sens<1000){OffsetKuDisplay=15;}
else if (state.sens<=1000){OffsetKuDisplay=18;}
char * result = (char *)malloc(strlen(STRINGS_OUTUNITS[state.ku+OffsetKuDisplay]) + strlen(STRINGS_UNITS[state.unit]) + 1); // +1 for the null-terminator
strcpy(result, STRINGS_OUTUNITS[state.ku+OffsetKuDisplay]);
strcat(result, STRINGS_UNITS[state.unit]);
free(result); /// освободил память
//шляпа для комбобокса
ui->comboBoxKu->clear();
for(int i=0; i<=12; i++){
QString StringForComboBox;
StringForComboBox.append(STRINGS_OUTUNITS[i+OffsetKuDisplay]);
StringForComboBox.append(STRINGS_UNITS[state.unit]);
ui->comboBoxKu->addItem(StringForComboBox);
};
ui->comboBoxKu->setCurrentIndex(state.ku);
switch (state.pz) { //todo тут нужно нормирование
case 0 :
ui->comboBoxPlavGround->setCurrentIndex(0);
break;
case 1:
ui->comboBoxPlavGround->setCurrentIndex(1);
break;
default:
ui->comboBoxPlavGround->hide();
break;
}
switch (state.unit) { //todo тут нужно нормирование
case Accel:
ui->comboBoxUnitSens->setCurrentIndex(0);
// ui->labelUnitKu->setText("xВ/Н"); // Заменил на нормирование с прибора
break;
case Velocity:
ui->comboBoxUnitSens->setCurrentIndex(1);
// ui->labelUnitKu->setText("xВ/Па");
break;
case Pascal:
ui->comboBoxUnitSens->setCurrentIndex(2);
break;
// ui->labelUnitKu->setText("xВс2");
case k_Pascal:
ui->comboBoxUnitSens->setCurrentIndex(3);
break;
case M_Pascal:
ui->comboBoxUnitSens->setCurrentIndex(4);
break;
case Nython:
ui->comboBoxUnitSens->setCurrentIndex(5);
break;
case k_Nuthon:
ui->comboBoxUnitSens->setCurrentIndex(6);
break;
case mV:
ui->comboBoxUnitSens->setCurrentIndex(7);
break;
default:
break;
}
//ui->labelUnitSens->adjustSize();
switch (state.overload) {
case Norm :
ui->labelOverload->setText("");
break;
case Overload:
ui->labelOverload->setText("ПЕРЕГРУЗКА");
break;
default:
ui->labelOverload->setText("#####");
break;
}
showInteface();
};
void MainWindow::on_labelSens_clicked()
{
bool ok;
state.sens = QInputDialog::getDouble(this, tr("Введите значение"),
tr("Введите значение чувствительности датчика"), state.sens, 0.001, 1000, 4, &ok,
Qt::WindowFlags(), 1);
if (ok){modebus->writeDataToPribor(state, SENS_REQ_TYPE);}
}
void MainWindow::on_comboBoxPort_currentIndexChanged(int )
{
portComboboxIndex=ui->comboBoxPort->currentIndex();
}
void MainWindow::on_comboBoxSpeed_currentIndexChanged(int )
{
speedComboboxIndex=ui->comboBoxSpeed->currentIndex();
}
void MainWindow::on_comboBoxBit_currentIndexChanged(int )
{
bitComboboxIndex=ui->comboBoxBit->currentIndex();
}
void MainWindow::on_lineEditAddr_textEdited(const QString &)
{
adrValue=ui->lineEditAddr->text();
}
void MainWindow::on_comboBoxUnitSens_activated(int index)
{
if(index==0)state.unit=Accel;
if(index==1)state.unit=Velocity; //тут были непонятки, скорее всего сработает без этого
if(index==2)state.unit=Pascal;
if(index==3)state.unit=k_Pascal;
if(index==4)state.unit=M_Pascal; //тут были непонятки, скорее всего сработает без этого
if(index==5)state.unit=Nython;
if(index==6)state.unit=k_Nuthon;
if(index==7)state.unit=mV;
modebus->writeDataToPribor(state, STATE_REQ_TYPE);
}
void MainWindow::on_comboBoxKu_activated(int index)
{
state.ku=typeIKU(index);
modebus->writeDataToPribor(state, STATE_REQ_TYPE);
}
void MainWindow::on_comboBoxVch_activated(int index)
{
state.fv=typeIFV(index);
modebus->writeDataToPribor(state, STATE_REQ_TYPE);
}
void MainWindow::on_comboBoxNch_activated(int index)
{
state.fn=typeIFN(index);
modebus->writeDataToPribor(state, STATE_REQ_TYPE);
}
void MainWindow::on_comboBoxPlavGround_activated(int index)
{
state.pz=typePlavGround(index);
modebus->writeDataToPribor(state, STATE_REQ_TYPE);
}