Qt Forum

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    • Unsolved

    Update: Forum Guidelines & Code of Conduct


    Qt World Summit: Early-Bird Tickets

    Solved Problem in call class in mainwindoe.cpp

    Mobile and Embedded
    2
    8
    1392
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • MhM93
      MhM93 last edited by MhM93

      Hi.
      I create a program for embedded ARM system. It reads data from serial port and save it in database.
      I create 2 classes ( one for data base and the other for serial port).
      The database classes is created database and tables if not exist and then will insert update data.
      Serial port classes is open port and config port and read data from port and close the port.
      When I make the classes they do not work.
      the database error show this message :

      [root@FriendlyARM /fgit]# ./TimeAttandent2 -qws -font 12
      QSqlQuery::exec: database not open
      QSqlQuery::exec: database not open

      and the readcard function does not work. (But when I put this code in mainwindow.cpp it worked )
      this is my database class : (create connection and create tables)

      #ifndef DB_H
      #define DB_H
      #include "QtSql/qsql.h"
      #include "QtSql/qsqldatabase.h"
      #include "QtSql/qsqlquery.h"
      #include "QtSql/qsqltablemodel.h"
      #include <QtCore/QDateTime>
      #include <QVariant>   //=>query.value()
      #include <QSqlRecord>
      #include <QSqlError>
      #include <csignal>
      #include <QDateTime>
      class DB
      {
      public:
          QSqlDatabase daba;
          QString msg;
          QSqlQuery q;
          bool success;
          //----------------
      public:
          DB();
          ~DB();
      };
      #endif // DB_H
      

      And this is DB.cpp:

      #include "db.h"
      DB::DB()
      {
          daba = QSqlDatabase::addDatabase("QSQLITE");//not dbConnection
          QString path = "DataBase";
          daba.setDatabaseName(path);
          if(!daba.open())
          {
              msg=("Error to open database");
          }
          else
          {
              msg="The Database is open sucessfully";
              //create the tables if not created.
              q.exec("create table IF NOT EXISTS Person("
                     "name varchar(20),"
                     "pid  varchar(20),"
                     "pic varchar(100),"
                     "password varchar(20),"
                     "boss varchar(10));");
      
              //boos if the user is manager
              q.exec("create table IF NOT EXISTS IO(record int primary key,"
                     "cf varchar(20) ,"
                     "pid varchar(20), "
                     "DateTime varchar(50));");
          }
      }
      DB::~DB()
      {
          daba.close();
      }
      
      

      I read data from serial port and save them in data base.And this is my serial port class :

      #ifndef PORTSERIAL_H
      #define PORTSERIAL_H
      
      #include <stdio.h>   /* Standard input/output definitions */
      #include <unistd.h>  /* UNIX standard function definitions */
      #include <fcntl.h>   /* File control definitions */
      #include "errno.h"   /* Error number definitions */
      #include "termio.h" /* POSIX terminal control definitions */
      #include <QString>
      #include <QDateTime>
      #define MAXDATASIZE 100
      
      class PortSerial
      {
      public :
          int fd;
          int status;
          char buf2[MAXDATASIZE];
          QString output;
      public:
          PortSerial();
          ~PortSerial();
          int openport();
          int configport();
          void closeport();
          void readcard(QString &output);
      };
      
      #endif // PORTSERIAL_H
      

      this is serial port cpp:

      #include "portserial.h"
      #include <QString>
      
      PortSerial::PortSerial()
      {
          fd=0;
          //*************************************************
          //inja hatman bayad khoroji ra check konin
          status=openport();
          if(status==1)
              status=configport();
          //if(status!=1)
          //*************************************************
      
      }
      
      PortSerial::~PortSerial()
      {
          closeport();
      }
      
      //____________________________________________________
      int PortSerial::openport()
      {
         QString portname="/dev/ttySAC3";
         fd=open(portname.toStdString().c_str(),O_RDWR|O_NOCTTY|O_NDELAY);
      
         if (fd==-1)
             return -1;//return open port error
         else
         {
             fcntl(fd,F_SETFL,O_NDELAY);
             return 1;
         }
      }
      //-------------------------------------
      void PortSerial::closeport()
      {
         close(fd);
      }
      //-------------------------------------
      int PortSerial::configport(void)
      {
          struct termios tty;
          struct termios tty_old;
          memset (&tty, 0, sizeof tty);
      
          /* Error Handling */
          if ( tcgetattr ( fd, &tty ) != 0 ) {
             //qDebug() << "Error " << errno << " from tcgetattr: " << strerror(errno) << std::endl;
              return -2;
      
          }
      
          /* Save old tty parameters */
          tty_old = tty;
      
          /* Set Baud Rate */
          cfsetospeed (&tty, (speed_t)B9600);
          cfsetispeed (&tty, (speed_t)B9600);
      
          /* Setting other Port Stuff */
          tty.c_cflag     &=  ~PARENB;            // Make 8n1
          tty.c_cflag     &=  ~CSTOPB;
          tty.c_cflag     &=  ~CSIZE;
          tty.c_cflag     |=  CS8;
      
          tty.c_cflag     &=  ~CRTSCTS;           // no flow control
          tty.c_cc[VMIN]   =  1;                  // read doesn't block
          tty.c_cc[VTIME]  =  5;                  // 0.5 seconds read timeout
          tty.c_cflag     |=  CREAD | CLOCAL;     // turn on READ & ignore ctrl lines
      
          /* Make raw */
          cfmakeraw(&tty);
      
          /* Flush Port, then applies attributes */
          tcflush( fd, TCIFLUSH );
          if ( tcsetattr ( fd, TCSANOW, &tty ) != 0) {
             //qDebug() << "Error " << errno << " from tcsetattr" << std::endl;
              return -3;
          }
          return 1;
      
      }
      //-------------------------------------
      void PortSerial::readcard(QString &output)
      {
          //QString output;//chon ham sat ham shomare kart hast ba * az ham joda mishan
      
          int numbytes;
          numbytes=0;
          //card*sat time
          if(fd==-1)
          {
              if ((numbytes = read(fd,buf2, MAXDATASIZE)) != -1)
              {
                  buf2[numbytes] = '\0';
                  usleep(10000);
                  QString s1(buf2);
                  memset(buf2,'\0',MAXDATASIZE);
                  read(fd,buf2, MAXDATASIZE-1) ;
                  QString s2(buf2);
                  memset(buf2,'\0',MAXDATASIZE);
                  QString card=(s1+s2);
                  QString dt=QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss");
                  output=card+"*"+dt;
              }
      
          }
      
      }
      
      

      and this is my mainwindow.h code:

      #ifndef MAINWINDOW_H
      #define MAINWINDOW_H
      
      #include <QMainWindow>
      #include <QSocketNotifier>
      //#include "menu.h"
      #include "db.h"
      #include "portserial.h"
      
      namespace Ui {
      class MainWindow;
      }
      
      class MainWindow : public QMainWindow
      {
          Q_OBJECT
      
      public:
          explicit MainWindow(QWidget *parent = 0);
          ~MainWindow();
          //=================================
          DB *database;
          PortSerial *serialport;
      //    QSocketNotifier *notifier ;
      
      private slots:
          void on_pushButton_clicked();
          void ReadAndProcessData();
      
      private:
          Ui::MainWindow *ui;
      };
      
      #endif // MAINWINDOW_H
      
      

      and .cpp:

      #include "mainwindow.h"
      #include "ui_mainwindow.h"
      #include "menu.h"
      
      
      //DB *database=new DB("IODataBase");
      //PortSerial *serialport=new PortSerial();
      QSocketNotifier *notifier ;
      //===============================================
      MainWindow::MainWindow(QWidget *parent) :
          QMainWindow(parent),
          ui(new Ui::MainWindow)
      {
          ui->setupUi(this);
          //======================================
          serialport=new PortSerial();
          database=new DB();
          //======================================
          ui->statusBar->addWidget(ui->label,0);
          ui->label->setText("the status of device");
          //ui->label->setText(QString::number(serialport->fd));
      
      
          notifier=new QSocketNotifier(serialport->fd, QSocketNotifier::Read,this);
          notifier->setEnabled(true);
          connect(notifier,SIGNAL(activated(int)),this,SLOT(ReadAndProcessData()));
          int a=serialport->status;
              //serialport->readcard(output);
              ui->lbl_welcome->setText(QString::number(a));
      }
      
      MainWindow::~MainWindow()
      {
          delete ui;
      }
      void MainWindow::on_pushButton_clicked()
      {
          Menu *mf=new Menu();
          mf->showNormal();
      }
      void MainWindow::ReadAndProcessData()
      {
          //ui->lbl_welcome->setText(serialport->readcard());//
          QString st="welcome";
          QString output;
      int a=serialport->status;
          //serialport->readcard(output);
          ui->lbl_welcome->setText(QString::number(a));
          //notifier->setEnabled(false);
          //database.InsertIO("card",)
      }
      
      
      

      H.Ghassami

      1 Reply Last reply Reply Quote 0
      • SGaist
        SGaist Lifetime Qt Champion last edited by

        Hi,

        There's no code related to writing anything in the database so there's no real way to tell why the connection is closed.

        By the way, why not use QSerialPort ?

        Interested in AI ? www.idiap.ch
        Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

        MhM93 1 Reply Last reply Reply Quote 0
        • MhM93
          MhM93 @SGaist last edited by

          @SGaist : Thanks for reply.

          There's no code related to writing anything in the database so there's no real way to tell why the connection is closed.


          In DB.cpp in constructor class ( DB() ) , I open the database and create table. (after tested the project I saw the error that say can not open the database. I decide solve the problem at first then will write other code to update and inset)

          By the way, why not use QSerialPort ?

          For Qserial port in documentation wrote Since: Qt 5.1. I have qt-4.8. That was not worked.

          My problem is : I call my functions but they do not worked.

          H.Ghassami

          1 Reply Last reply Reply Quote 0
          • SGaist
            SGaist Lifetime Qt Champion last edited by

            Why did you erase your original post ?

            The qtserialport module can be build with Qt 4.8, there's a branch for it.

            Without seeing your code there's no way to tell why it doesn't work. Also "doesn't work" doesn't tell much about what is happening (or not happening for that matter). You should explain what you expect to have and what you get.

            For your database problem, at some point it's either never opened or closed before you try to write something in it. Again without seeing the related code, there's no way to help you.

            Interested in AI ? www.idiap.ch
            Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

            MhM93 1 Reply Last reply Reply Quote 0
            • MhM93
              MhM93 @SGaist last edited by MhM93

              @SGaist :

              Why did you erase your original post ?
              The qtserialport module can be build with Qt 4.8, there's a branch for it.

              Yes, you say right. I am finding this resource to use qserialport. :[https://wiki.qt.io/Qt_Serial_Port]
              In this resource says :
              To use the library, add serialport to the *.pro file of your project:
              Qt4

              CONFIG += serialport
              

              Qt5

              
              QT += serialport
              

              but when I added CONFIG += serialport to my .pro file , these codes has error again :

              …
              #include <QSerialPort>
              #include <QSerialPortInfo>
              …
              

              My problem solved and it has a silly mistake on serialport class.
              The database class is worked but that error occurred because I should define query in each function after opening database. [http://www.qtcentre.org/archive/index.php/t-25184.html] This post solved my problem.

              H.Ghassami

              1 Reply Last reply Reply Quote 0
              • SGaist
                SGaist Lifetime Qt Champion last edited by

                You're using Qt 4.8.7 so you have to compile/install it before you can use it. It's described in the Getting the source code part.

                Interested in AI ? www.idiap.ch
                Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

                1 Reply Last reply Reply Quote 1
                • SGaist
                  SGaist Lifetime Qt Champion last edited by

                  As for the database part, re-opening the database each time is not necessarily the cleaner option since you are using a SQLite database. Unless you're in an environment that's highly hostile to your database connection, you should set it up when starting the application and only close it at the end. Thus you'll be using the default connection without the need to re-open the database each time you want to do a query.

                  Interested in AI ? www.idiap.ch
                  Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

                  1 Reply Last reply Reply Quote 0
                  • MhM93
                    MhM93 last edited by

                    Really thanks my friend. For qserial port and advice for opening database.
                    Thanks.thanks.

                    H.Ghassami

                    1 Reply Last reply Reply Quote 0
                    • First post
                      Last post