Russian Qt Forum
Март 29, 2024, 16:18 *
Добро пожаловать, Гость. Пожалуйста, войдите или зарегистрируйтесь.
Вам не пришло письмо с кодом активации?

Войти
 
  Начало   Форум  WIKI (Вики)FAQ Помощь Поиск Войти Регистрация  

Страниц: [1] 2 3   Вниз
  Печать  
Автор Тема: Зависает программа через некоторое врямя  (Прочитано 15630 раз)
Ostapich
Гость
« : Декабрь 04, 2017, 13:58 »

Добрый день! ОС Windows XP SP3. при работе программы зависает через некоторое время бездействия. Как я понимаю это связанно со ждущим режимом и т.п.  Возможности нет поменять настройки ждущего режима, админа не поймаешь нашего. Может есть какое то решение. По коду там есть поток принятие данных с Com порта, код выложу вечером. Может будут какие то идеи?
Записан
__Heaven__
Джедай : наставник для всех
*******
Offline Offline

Сообщений: 2130



Просмотр профиля
« Ответ #1 : Декабрь 04, 2017, 14:33 »

https://movemouse.codeplex.com/
Записан
__Heaven__
Джедай : наставник для всех
*******
Offline Offline

Сообщений: 2130



Просмотр профиля
« Ответ #2 : Декабрь 04, 2017, 14:35 »

Это больше в качестве шутки, но ждущий режим эта программа уберёт...
Записан
Ostapich
Гость
« Ответ #3 : Декабрь 04, 2017, 14:39 »

Нууу,... спасибо конечно, но есть какое то программное решение ?:
Записан
Ostapich
Гость
« Ответ #4 : Декабрь 04, 2017, 14:50 »

Тем более не помогает))))
Записан
__Heaven__
Джедай : наставник для всех
*******
Offline Offline

Сообщений: 2130



Просмотр профиля
« Ответ #5 : Декабрь 04, 2017, 14:55 »

Кажется, программно только так: https://msdn.microsoft.com/en-us/library/aa373208(VS.85).aspx
Записан
Ostapich
Гость
« Ответ #6 : Декабрь 04, 2017, 15:34 »

Я правильно поняд, подключить Windows.h, и написать в начале SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED | ES_AWAYMODE_REQUIRED); а в конце SetThreadExecutionState(ES_CONTINUOUS); Непонимающий
Записан
Ostapich
Гость
« Ответ #7 : Декабрь 04, 2017, 22:57 »

Код вот :

mainwindow.cpp
Код:
#include "mainwindow.h"
#include <QMessageBox>
#include <QString>
#include <QDesktopWidget>
#include <QScreen>
#include <QMetaEnum>
//#include <unistd.h>
#include <errno.h>
#include "ui_mainwindow.h"
#include <QPixmap>
#include "dialog_settings.h"
#include "packet.h"
#include <qdebug.h>
#include "QPalette"



MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    QPixmap myPixmap_on( "C:/if_Circle_Green_34211.png" );
    QPixmap myPixmap_of( "C:/if_Circle_Grey_34212.png" );
    QPixmap myPixmap_red( "C:/if_Circle_Red_34214.png" );

    ui->setupUi(this);

    info = new Dialog_Settings(this);//Создаем окно с настройками Com порта,
    info->setVisible(false);//                                              но не отображаем.

    ui->lcdNumber_3->display("00:00");
    ui->lcdNumber_4->display("00:00");

    ui->label_4->setPixmap(myPixmap_red);
    ui->label_3->setPixmap(myPixmap_of);

    ui->spinBox->setMaximum(250);
    ui->spinBox_2->setMaximum(500);

    connect(ui->action_Com,SIGNAL(triggered(bool)),this,SLOT(settings_menu()));
    connect(ui->action_3,SIGNAL(triggered(bool)),this,SLOT(close()));

    connect(ui->pushButton_3,SIGNAL(clicked()),this,SLOT(nasos_on()));
    connect(ui->pushButton_4,SIGNAL(clicked()),this,SLOT(nasos_of()));

    connect(ui->pushButton_5,SIGNAL(clicked(bool)),this,SLOT(on_Button_clicked()));
    connect(this,SIGNAL(on()),this,SLOT(vizvat_taimer()));
    connect(this,SIGNAL(off()),this,SLOT(taimer_stop()));

    connect(ui->pushButton_2,SIGNAL(clicked(bool)),this,SLOT(disp_lcd_time()));
    connect(ui->pushButton,SIGNAL(clicked(bool)),this,SLOT(disp_lcd_temp()));
    connect(info, SIGNAL(duble_send_signal(QByteArray)), this, SLOT(save_str(QByteArray)));
    connect(this,SIGNAL(sendArray(QByteArray)),info,SIGNAL(writeData(QByteArray)));

    connect(this,SIGNAL(pomp_off(packet_big)),this,SLOT(put_in_array(packet_big)));
    connect(this,SIGNAL(pomp_on(packet_big)),this,SLOT(put_in_array(packet_big)));

}

MainWindow::~MainWindow()
{
    delete ui;
    qDebug("del");
}
void MainWindow::nasos_on()
{
    QPixmap myPixmap_on( "C:/if_Circle_Green_34211.png" );
    QPixmap myPixmap_of( "C:/if_Circle_Grey_34212.png" );
    ui->label_3->setPixmap(myPixmap_on);
    ui->label_4->setPixmap(myPixmap_of);


    packet_one.on_of_pomp=1;
    packet_one.pask();
    emit pomp_on(packet_one);
    qDebug("idx1");
}

void MainWindow::nasos_of()
{
    QPixmap myPixmap_of( "C:/if_Circle_Grey_34212.png" );
    QPixmap myPixmap_red( "C:/if_Circle_Red_34214.png" );
    ui->label_4->setPixmap(myPixmap_red);
    ui->label_3->setPixmap(myPixmap_of);

    packet_one.on_of_pomp=0;
    packet_one.pask();
    emit pomp_off(packet_one);
    qDebug("idx2");
}


void MainWindow::settings_menu()
{
    info->setVisible(true);
}


void MainWindow::disp_lcd_time()
{
    num_time=ui->spinBox_2->value();
    ui->lcdNumber_4->display(QTime::fromMSecsSinceStartOfDay(num_time*60000).toString("hh:mm"));
   packet_one.timer_ex=num_time;
   packet_one.pask();
    emit pomp_off(packet_one);

}

void MainWindow::disp_lcd_temp()
{
    num_temp=ui->spinBox->value();
    ui->lcdNumber->display(num_temp);
    packet_one.current_temp_reactor=num_temp;
   packet_one.pask();
    emit pomp_off(packet_one);

}

void MainWindow::vizvat_taimer()
{
    timer = new QTimer(this);
    updater = new QTimer(this);
    updater->setSingleShot(false);
    connect(updater,SIGNAL(timeout()), this, SLOT(disp_lcd_temp_timer()));
    timer->setSingleShot(true);
   // connect(timer, &QTimer::timeout, timer, &QObject::deleteLater);
    connect(timer, SIGNAL(timeout()), timer, SLOT(stop()));
    connect(timer, SIGNAL(timeout()), this, SLOT(nasos_on()));
    connect(timer, SIGNAL(timeout()), updater, SLOT(stop()));
    connect(timer, SIGNAL(timeout()), this, SLOT(end_timer()));
    //connect(timer, &QTimer::timeout, updater, &QObject::deleteLater);
    updater->start(1000);
    timer->start(num_time*60000);
}

void MainWindow::disp_lcd_temp_timer()
{

    QString text = QTime::fromMSecsSinceStartOfDay(timer->interval() - timer->remainingTime()).toString("hh:mm");

    if (((((timer->interval() - timer->remainingTime())/1000)) % 2) != 0)
        text[2] = ' ';
    ui->lcdNumber_3->display(text);
}


void MainWindow::on_Button_clicked()
{
    if(flag_but_on==0)
    {
        flag_but_on=1;
        qDebug("flag_but_on_1");
        ui->pushButton_5->setText("СТОП");
        emit on();
    }
    else if(flag_but_on==1)
    {
        flag_but_on=0;
        qDebug("flag_but_off_2");
        ui->pushButton_5->setText("ПУСК");
        ui->lcdNumber_3->display("00:00");
        QPalette Pal = ui->lcdNumber_3->palette();
        Pal.setColor(QPalette::Normal, QPalette::WindowText, Qt::black);
        Pal.setColor(QPalette::Normal, QPalette::Window, Qt::black);
        ui->lcdNumber_3->setPalette(Pal);
        emit off();
    }
}

void MainWindow::taimer_stop()
{

    qDebug("stop");
    //updater->stop();
   // timer->stop();
    updater->deleteLater();
    timer->deleteLater();

}


void MainWindow::save_str(QByteArray data)
{
    packet_big tmp;
    unsigned char* masstmp = (unsigned char* )&tmp;
    for(unsigned int i=0; i<sizeof(tmp); i++)
    {
        masstmp[i]=(unsigned char)data[i];
    }
    if(!tmp.test_pask())
    {
        packet_one=tmp;
        qDebug()<<" ONE byte:     "<<packet_one.start_byte_one<<"\n"<<"TWO byte:     " << packet_one.start_byte_two <<"\n"<<"TEMP byte:     "
               << packet_one.temp_pomp<<"\n"<<"ON-OF byte:     "<<packet_one.on_of_pomp<<"\n"<<"CRC8 byte:     "<<packet_one.CRC8<<"\n"<<"Temp_curent:     "<<packet_one.current_temp_reactor
               <<"\n"<<"Timer:     "<<packet_one.timer_ex;
    }
    ui->lcdNumber_5->display(packet_one.temp_pomp);
    ui->lcdNumber_2->display(packet_one.ex_temp_reactor);
    if(packet_one.on_of_pomp==0)
    {
        QPixmap myPixmap_on( "C:/if_Circle_Green_34211.png" );
        QPixmap myPixmap_of( "C:/if_Circle_Grey_34212.png" );
        QPixmap myPixmap_red( "C:/if_Circle_Red_34214.png" );
        ui->label_4->setPixmap(myPixmap_red);
        ui->label_3->setPixmap(myPixmap_of);

    }
    else if(packet_one.on_of_pomp==1)
    {
        QPixmap myPixmap_on( "C:/if_Circle_Green_34211.png" );
        QPixmap myPixmap_of( "C:/if_Circle_Grey_34212.png" );
        ui->label_3->setPixmap(myPixmap_on);
        ui->label_4->setPixmap(myPixmap_of);

    }

}


void  MainWindow::put_in_array(packet_big data)
{

    QByteArray tmp;
    unsigned char* masstmp = (unsigned char* )&data;
    qDebug()<<" QQQQQQQQQQQQQQQQQQQQQ 333    "<<packet_one.on_of_pomp;
    for(unsigned int i=0; i<sizeof(data); i++)
    {
        tmp[i]=masstmp[i];
    }
    emit sendArray(tmp);
}


void MainWindow::end_timer(){
    ui->lcdNumber_3->display(QTime::fromMSecsSinceStartOfDay(num_time*60000).toString("hh:mm"));
    QPalette Pal = ui->lcdNumber_3->palette();
    Pal.setColor(QPalette::Normal, QPalette::WindowText, Qt::red);
    Pal.setColor(QPalette::Normal, QPalette::Window, Qt::black);
    ui->lcdNumber_3->setPalette(Pal);


}



dialog_settings.cpp

Код:
#include "dialog_settings.h"
#include "ui_dialog_settings.h"
#include <QThread>
#include <QString>
#include <qdebug.h>



Dialog_Settings::Dialog_Settings(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog_Settings)
{
    ui->setupUi(this);

    connect(ui->BaudRateBox, SIGNAL(currentIndexChanged(int)),this, SLOT(checkCustomBaudRatePolicy(int)));
    ui->BaudRateBox->addItem(QLatin1String("9600"), QSerialPort::Baud9600);
    ui->BaudRateBox->addItem(QLatin1String("19200"), QSerialPort::Baud19200);
    ui->BaudRateBox->addItem(QLatin1String("38400"), QSerialPort::Baud38400);
    ui->BaudRateBox->addItem(QLatin1String("115200"), QSerialPort::Baud115200);
    ui->BaudRateBox->addItem(QLatin1String("Custom"));
    // fill data bits
    ui->DataBitsBox->addItem(QLatin1String("5"), QSerialPort::Data5);
    ui->DataBitsBox->addItem(QLatin1String("6"), QSerialPort::Data6);
    ui->DataBitsBox->addItem(QLatin1String("7"), QSerialPort::Data7);
    ui->DataBitsBox->addItem(QLatin1String("8"), QSerialPort::Data8);
    ui->DataBitsBox->setCurrentIndex(3);
    // fill parity
    ui->ParityBox->addItem(QLatin1String("None"), QSerialPort::NoParity);
    ui->ParityBox->addItem(QLatin1String("Even"), QSerialPort::EvenParity);
    ui->ParityBox->addItem(QLatin1String("Odd"), QSerialPort::OddParity);
    ui->ParityBox->addItem(QLatin1String("Mark"), QSerialPort::MarkParity);
    ui->ParityBox->addItem(QLatin1String("Space"), QSerialPort::SpaceParity);
    // fill stop bits
    ui->StopBitsBox->addItem(QLatin1String("1"), QSerialPort::OneStop);
#ifdef Q_OS_WIN
    ui->StopBitsBox->addItem(QLatin1String("1.5"), QSerialPort::OneAndHalfStop);
#endif
    ui->StopBitsBox->addItem(QLatin1String("2"), QSerialPort::TwoStop);
    // fill flow control
    ui->FlowControlBox->addItem(QLatin1String("None"), QSerialPort::NoFlowControl);
    ui->FlowControlBox->addItem(QLatin1String("RTS/CTS"), QSerialPort::HardwareControl);
    ui->FlowControlBox->addItem(QLatin1String("XON/XOFF"), QSerialPort::SoftwareControl);
    connect(ui->cBtnSend,SIGNAL(clicked()),this, SLOT(on_cEnterText_returnPressed()) );

    QThread *thread_New = new QThread;//Создаем поток для порта платы
    Port *PortNew = new Port();//Создаем обьект по классу
    PortNew->moveToThread(thread_New);//помешаем класс  в поток
    PortNew->thisPort.moveToThread(thread_New);//Помещаем сам порт в поток
    connect(thread_New, SIGNAL(started()), PortNew, SLOT(process_Port()));//Переназначения метода run
    connect(PortNew, SIGNAL(finished_Port()), thread_New, SLOT(quit()));//Переназначение метода выход
    connect(thread_New, SIGNAL(finished()), PortNew, SLOT(deleteLater()));//Удалить к чертям поток
    connect(PortNew, SIGNAL(finished_Port()), thread_New, SLOT(deleteLater()));//Удалить к чертям поток
    connect(this,SIGNAL(savesettings(QString,int,int,int,int,int)),PortNew,SLOT(Write_Settings_Port(QString,int,int,int,int,int)));//Слот - ввод настроек!
    connect(ui->BtnSave, SIGNAL(clicked()),PortNew,SLOT(ConnectPort()));
    connect(PortNew, SIGNAL(Send_Data(QByteArray)), this, SLOT(Print(QByteArray)));//Лог ошибок
    connect(this,SIGNAL(writeData(QByteArray)),PortNew,SLOT(WriteToPort(QByteArray)));//слот на отправку в порт из главного окна
    connect(PortNew, SIGNAL(Send_Data(QByteArray)), this, SIGNAL(duble_send_signal(QByteArray)));//перенаправляем сигнал
    ui->comboBox->clear();
    foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
    {
        ui->comboBox->addItem(info.portName());
    }
    thread_New->start();
}


Dialog_Settings::~Dialog_Settings()
{
    delete ui;
    qDebug("dellit setting");
}

void Dialog_Settings ::on_BtnSave_clicked()
{
    savesettings(ui->comboBox->currentText(), ui->BaudRateBox->currentText().toInt(),ui->DataBitsBox->currentText().toInt(),
                 ui->ParityBox->currentText().toInt(), ui->StopBitsBox->currentText().toInt(), ui->FlowControlBox->currentText().toInt());

    qDebug("save setting");

}


void Dialog_Settings::checkCustomBaudRatePolicy(int idx)
{
    bool isCustomBaudRate = !ui->BaudRateBox->itemData(idx).isValid();
    ui->BaudRateBox->setEditable(isCustomBaudRate);
    if (isCustomBaudRate)
    {
        ui->BaudRateBox->clearEditText();
    }
}


//+++++++++++++[Процедура ввода данных из строки]++++++++++++++++++++++++++++++++++++++++
void Dialog_Settings::on_cEnterText_returnPressed()
{
    QByteArray data; // Текстовая переменная
    data = ui->cEnterText->text().toLocal8Bit(); // Присвоение "data" значения из EnterText
    //data = ui->cEnterText->text().toLocal8Bit().toHex() + '\r';
    writeData(data); // Отправка данных в порт
    Print(data); // Вывод данных в консоль
}
//+++++++++++++[Процедура вывода данных в консоль]++++++++++++++++++++++++++++++++++++++++
void Dialog_Settings::Print(QByteArray data)
{

    ui->consol->textCursor().insertText(data+'\r'); // Вывод текста в консоль

    ui->consol->moveCursor(QTextCursor::End);//Scroll
}




mainwindow.h

Код:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H


#include <QMainWindow>
#include <QTimer>
#include <QTime>
#include "dialog_settings.h"


namespace Ui
{
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    packet_big packet_one= {254, 232, 0, 0, 0, 0, 0, 0, 0};
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
signals:

    void on_off(int baudrate);
    void off();//включение таймера и всего по нажатию пуск
    void on();//отключение таймера и всего по нажатию пуск
    void sendArray(QByteArray data);
    void pomp_on(packet_big packet_one);
    void pomp_off(packet_big packet_one);



public slots:
    void nasos_on();//включить насос
    void nasos_of();//выключить насос
    void settings_menu();//окно настроек Com порта
    void disp_lcd_time();//выставление таймера
    void disp_lcd_temp();
    void vizvat_taimer();
    void disp_lcd_temp_timer();
    void save_str(QByteArray data);
    void put_in_array(packet_big data);
    void end_timer();


private slots:
    void on_Button_clicked();
    void taimer_stop();

private:
    Ui::MainWindow *ui;
    QTimer * timer; //Адресная переменная таймера
    QTimer * updater;
    Dialog_Settings *info;
    int num_time=0;
    int num_temp=0;
    bool flag_but_on=0;
};

#endif // MAINWINDOW_H


dialog_settings.h

Код:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H


#include <QMainWindow>
#include <QTimer>
#include <QTime>
#include "dialog_settings.h"


namespace Ui
{
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    packet_big packet_one= {254, 232, 0, 0, 0, 0, 0, 0, 0};
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
signals:

    void on_off(int baudrate);
    void off();//включение таймера и всего по нажатию пуск
    void on();//отключение таймера и всего по нажатию пуск
    void sendArray(QByteArray data);
    void pomp_on(packet_big packet_one);
    void pomp_off(packet_big packet_one);



public slots:
    void nasos_on();//включить насос
    void nasos_of();//выключить насос
    void settings_menu();//окно настроек Com порта
    void disp_lcd_time();//выставление таймера
    void disp_lcd_temp();
    void vizvat_taimer();
    void disp_lcd_temp_timer();
    void save_str(QByteArray data);
    void put_in_array(packet_big data);
    void end_timer();


private slots:
    void on_Button_clicked();
    void taimer_stop();

private:
    Ui::MainWindow *ui;
    QTimer * timer; //Адресная переменная таймера
    QTimer * updater;
    Dialog_Settings *info;
    int num_time=0;
    int num_temp=0;
    bool flag_but_on=0;
};

#endif // MAINWINDOW_H

Записан
Ostapich
Гость
« Ответ #8 : Декабрь 05, 2017, 00:13 »

port.h

Код:

#ifndef PORT_H
#define PORT_H

#include <QObject>
#include <QtSerialPort/QSerialPort>
#include <QtSerialPort/QSerialPortInfo>

struct Settings
{
    QString name;
    qint32 baudRate;
    QSerialPort::DataBits dataBits;
    QSerialPort::Parity parity;
    QSerialPort::StopBits stopBits;
    QSerialPort::FlowControl flowControl;
};

class Port : public QObject
{
    Q_OBJECT

public:

    explicit Port(QObject *parent = 0);

    ~Port();

    QSerialPort thisPort;

    Settings SettingsPort;
    QByteArray in_data;

signals:

    void finished_Port(); //

    void error_(QString err);

    void outPort(QString data);
    void Send_Data(QByteArray data);

public slots:

    void  DisconnectPort();

    void ConnectPort(void);

    void Write_Settings_Port(QString name, int baudrate, int DataBits, int Parity, int StopBits, int FlowControl);

    void process_Port();

    void WriteToPort(QByteArray data);

    void ReadInPort();

private slots:

    void handleError(QSerialPort::SerialPortError error);//

public:

};

#endif // PORT_H


port.cpp

Код:

#include "port.h"
#include <qdebug.h>
#include "dialog_settings.h"

Port::Port(QObject *parent) :
    QObject(parent)
{
}

Port::~Port()
{
    qDebug("By in Thread!");
    emit finished_Port();
}

void Port :: process_Port(){
    qDebug("Hello World in Thread!222");
    connect(&thisPort,SIGNAL(error(QSerialPort::SerialPortError)), this, SLOT(handleError(QSerialPort::SerialPortError)));
    connect(&thisPort, SIGNAL(readyRead()),this,SLOT(ReadInPort()));
}

void Port :: Write_Settings_Port(QString name, int baudrate,int DataBits,
                         int Parity,int StopBits, int FlowControl){
    SettingsPort.name = name;
    SettingsPort.baudRate = (QSerialPort::BaudRate) baudrate;
    SettingsPort.dataBits = (QSerialPort::DataBits) DataBits;
    SettingsPort.parity = (QSerialPort::Parity) Parity;
    SettingsPort.stopBits = (QSerialPort::StopBits) StopBits;
    SettingsPort.flowControl = (QSerialPort::FlowControl) FlowControl;
}

void Port :: ConnectPort(void){//
    thisPort.setPortName(SettingsPort.name);
    if (thisPort.open(QIODevice::ReadWrite)) {
        if (thisPort.setBaudRate(SettingsPort.baudRate)
                && thisPort.setDataBits(SettingsPort.dataBits)//DataBits
                && thisPort.setParity(SettingsPort.parity)
                && thisPort.setStopBits(SettingsPort.stopBits)
                && thisPort.setFlowControl(SettingsPort.flowControl))
        {
            if (thisPort.isOpen()){
                error_((SettingsPort.name+ " >> Открыт!\r").toLocal8Bit());
            }
        } else {
            thisPort.close();
            error_(thisPort.errorString().toLocal8Bit());
          }
    } else {
        thisPort.close();
        error_(thisPort.errorString().toLocal8Bit());
    }
}

void Port::handleError(QSerialPort::SerialPortError error)//
{
    if ( (thisPort.isOpen()) && (error == QSerialPort::ResourceError)) {
        error_(thisPort.errorString().toLocal8Bit());
        DisconnectPort();
    }
}//


void  Port::DisconnectPort(){
    if(thisPort.isOpen()){
        thisPort.close();
        error_(SettingsPort.name.toLocal8Bit() + " >> Закрыт!\r");
    }
}
//ot tuta kovuratji!!!
void Port :: WriteToPort(QByteArray data){
    if(thisPort.isOpen()){
        thisPort.write(data);
    }
}
//
void Port :: ReadInPort(){
    if(thisPort.bytesAvailable()>0){
        QByteArray tmp;
        in_data.append(thisPort.readAll());
        if(in_data.size()>=sizeof(packet_big)){
            for(size_t i=0;i<in_data.size();i++){
                if(in_data[i]==(char)254){
                    if(in_data[i+1]==(char)232){
                        if(in_data.size()>=sizeof(packet_big)){
                           tmp=in_data.mid(i,sizeof(packet_big));
                           in_data.remove(0,i+(sizeof(packet_big)));
                           i=0;
                           emit Send_Data(tmp);
                        }
                        else{
                            in_data.remove(0,i-1);
                            break;
                        }
                    }
                }
            }
        }
    }
}







Сам пакет

Код:
#ifndef PACKET_H
#define PACKET_H
struct packet_big //пакет PC
{
    unsigned char start_byte_one;//в длинном пакете равен 254
    unsigned char start_byte_two;//в длинном пакете равен 232
    unsigned char temp_pomp;//температура охлаждения
    unsigned char on_of_pomp;//on-off насоса (1 или 0)
    unsigned char ex_temp_reactor;//текущая температура в реакторе
    unsigned char current_temp_reactor;//выставленная температура в реакторе
    unsigned char timer_ex;//таймер
    unsigned char tmp;//пока не трогаем
    unsigned char CRC8;//пока не трогаем
    void pask()
    {
        CRC8 = (start_byte_one + start_byte_two + temp_pomp + on_of_pomp + ex_temp_reactor + current_temp_reactor + timer_ex + tmp) / 10;
    }
    /*проверка упаковки*/
    bool test_pask()
    {
        if (CRC8 == ((start_byte_one + start_byte_two + temp_pomp + on_of_pomp + ex_temp_reactor + current_temp_reactor + timer_ex + tmp)) / 10) return 0; //ОК
        return 1; // ошибка
    }

};
#endif // PACKET_H


Коротко: порт слушает com порт , передает в  mainwindow , там отображает в самой программе. Так же и наоброт: mainwindow передает данные на порт, который отправляется в Com. Настройки порта вынесены отдельным классом dialog_settings, структура пакета описана. Порт в отдельном потоке. В mainwindow по команде можно включить таймер.Понимаю что код очень нагроможденный , писал как мог, не судите строго))
Записан
qate
Супер
******
Offline Offline

Сообщений: 1175


Просмотр профиля
« Ответ #9 : Декабрь 05, 2017, 08:28 »

а что значит "зависает" ?
кнопки не нажимаются или данные не приходят из ком-порта ?
Записан
Ostapich
Гость
« Ответ #10 : Декабрь 05, 2017, 08:56 »

зависает только GUI , в консоле при зависании данные приходят и отправляются. Даже таймер срабатывает, просто зависает картинка и весь интерфейс становится неактивный.
Записан
qate
Супер
******
Offline Offline

Сообщений: 1175


Просмотр профиля
« Ответ #11 : Декабрь 05, 2017, 11:31 »

код не проверяет выходы за размеры массивов (прогони код анализатором, pvs-studio например)
ставь логгирование в каждом входе и выходе обработчиков сигналов, выводи размеры
запусти под отладчиком, как зависнет - жми паузу
смотри монитор потребления памяти
Записан
Ostapich
Гость
« Ответ #12 : Декабрь 05, 2017, 11:40 »

Ни когда не пользовался я такими приблудами))) Да массив там формальность, да и причем тут массив, с принятием данных все ок, виснет само окно, причем после бездействия на компе, если сидеть работь за компом, прога нормально работает.
Записан
qate
Супер
******
Offline Offline

Сообщений: 1175


Просмотр профиля
« Ответ #13 : Декабрь 05, 2017, 13:01 »

если код с ошибками, то как он будет работать никому и неизвестно
например в MainWindow::save_str делается какойто трэш - сишный код вперемежку с классами
Записан
Ostapich
Гость
« Ответ #14 : Декабрь 05, 2017, 13:16 »

Ну как мог, так и заполнил структуру массивом ) А почему бы и нет?)))
Записан
Страниц: [1] 2 3   Вверх
  Печать  
 
Перейти в:  


Страница сгенерирована за 0.057 секунд. Запросов: 23.