Sophie

Sophie

distrib > Mageia > 6 > x86_64 > media > core-updates > by-pkgid > c04d50e59eacd9c02ba2ba4314d42c39 > files > 49

qtserialport5-doc-5.9.4-1.mga6.noarch.rpm

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- blockingslave.qdoc -->
  <title>Blocking Slave Example | Qt Serial Port 5.9</title>
  <link rel="stylesheet" type="text/css" href="style/offline-simple.css" />
  <script type="text/javascript">
    document.getElementsByTagName("link").item(0).setAttribute("href", "style/offline.css");
    // loading style sheet breaks anchors that were jumped to before
    // so force jumping to anchor again
    setTimeout(function() {
        var anchor = location.hash;
        // need to jump to different anchor first (e.g. none)
        location.hash = "#";
        setTimeout(function() {
            location.hash = anchor;
        }, 0);
    }, 0);
  </script>
</head>
<body>
<div class="header" id="qtdocheader">
  <div class="main">
    <div class="main-rounded">
      <div class="navigationbar">
        <table><tr>
<td >Qt 5.9</td><td ><a href="qtserialport-index.html">Qt Serial Port</a></td><td ><a href="qtserialport-examples.html">Qt Serial Port Examples</a></td><td >Blocking Slave Example</td></tr></table><table class="buildversion"><tr>
<td id="buildversion" width="100%" align="right">Qt 5.9.4 Reference Documentation</td>
        </tr></table>
      </div>
    </div>
<div class="content">
<div class="line">
<div class="content mainContent">
<div class="sidebar">
<div class="toc">
<h3><a name="toc">Contents</a></h3>
<ul>
<li class="level1"><a href="#running-the-example">Running the Example</a></li>
</ul>
</div>
<div class="sidebar-content" id="sidebar-content"></div></div>
<h1 class="title">Blocking Slave Example</h1>
<span class="subtitle"></span>
<!-- $$$blockingslave-description -->
<div class="descr"> <a name="details"></a>
<p><i>Blocking Slave</i> shows how to create an application for a serial interface using <a href="qserialport.html">QSerialPort</a>'s synchronous API in a non-GUI thread.</p>
<p class="centerAlign"><img src="images/blockingslave-example.png" alt="" /></p><p><a href="qserialport.html">QSerialPort</a> supports two general programming approaches:</p>
<ul>
<li><i>The asynchronous (non-blocking) approach.</i> Operations are scheduled and performed when the control returns to Qt's event loop. <a href="qserialport.html">QSerialPort</a> emits a signal when the operation is finished. For example, QSerialPort::write() returns immediately. When the data is sent to the serial port, <a href="qserialport.html">QSerialPort</a> emits bytesWritten().</li>
<li><i>The synchronous (blocking) approach.</i> In non-GUI and multithreaded applications, the <code>waitFor..&#x2e;()</code> functions can be called (i.e&#x2e; <a href="qserialport.html#waitForReadyRead">QSerialPort::waitForReadyRead</a>()) to suspend the calling thread until the operation has completed.</li>
</ul>
<p>In this example, the synchronous approach is demonstrated. The <a href="qtserialport-terminal-example.html">Terminal</a> example illustrates the asynchronous approach.</p>
<p>The purpose of this example is to demonstrate a pattern that you can use to simplify your serial programming code, without losing responsiveness in your user interface. Use of Qt's blocking serial programming API often leads to simpler code, but because of its blocking behavior, it should only be used in non-GUI threads to prevent the user interface from freezing. But contrary to what many think, using threads with QThread does not necessarily add unmanageable complexity to your application.</p>
<p>This application is a Slave, that demonstrate the work paired with Master application <a href="qtserialport-blockingmaster-example.html">Blocking Master Example</a>.</p>
<p>The Slave application is receives the request via serial port from the Master application and send a response to it.</p>
<p>We will start with the SlaveThread class, which handles the serial programming code.</p>
<pre class="cpp">

  <span class="keyword">class</span> SlaveThread : <span class="keyword">public</span> <span class="type">QThread</span>
  {
      Q_OBJECT

  <span class="keyword">public</span>:
      <span class="keyword">explicit</span> SlaveThread(<span class="type">QObject</span> <span class="operator">*</span>parent <span class="operator">=</span> nullptr);
      <span class="operator">~</span>SlaveThread();

      <span class="type">void</span> startSlave(<span class="keyword">const</span> <span class="type">QString</span> <span class="operator">&amp;</span>portName<span class="operator">,</span> <span class="type">int</span> waitTimeout<span class="operator">,</span> <span class="keyword">const</span> <span class="type">QString</span> <span class="operator">&amp;</span>response);
      <span class="type">void</span> run() Q_DECL_OVERRIDE;

  <span class="keyword">signals</span>:
      <span class="type">void</span> request(<span class="keyword">const</span> <span class="type">QString</span> <span class="operator">&amp;</span>s);
      <span class="type">void</span> error(<span class="keyword">const</span> <span class="type">QString</span> <span class="operator">&amp;</span>s);
      <span class="type">void</span> timeout(<span class="keyword">const</span> <span class="type">QString</span> <span class="operator">&amp;</span>s);

  <span class="keyword">private</span>:
      <span class="type">QString</span> portName;
      <span class="type">QString</span> response;
      <span class="type">int</span> waitTimeout;
      <span class="type">QMutex</span> mutex;
      bool quit;
  };

</pre>
<p>SlaveThread is a QThread subclass that provides an API for receive requests from Master, and it has signals for delivering responses and reporting errors.</p>
<p>You should be call startSlave() to startup Slave application. This method transfers to the SlaveThread desired parameters for configure and startup the serial interface. When SlaveThread received from Master any request then emitted the request() signal. If any error occurs, the error() or timeout() signals is emitted.</p>
<p>It's important to notice that startSlave() is called from the main, GUI thread, but the response data and other parameters will be accessed from SlaveThread's thread. SlaveThread's data members are read and written from different threads concurrently, so it is advisable to use QMutex to synchronize access.</p>
<pre class="cpp">

  <span class="type">void</span> SlaveThread<span class="operator">::</span>startSlave(<span class="keyword">const</span> <span class="type">QString</span> <span class="operator">&amp;</span>portName<span class="operator">,</span> <span class="type">int</span> waitTimeout<span class="operator">,</span> <span class="keyword">const</span> <span class="type">QString</span> <span class="operator">&amp;</span>response)
  {
      <span class="type">QMutexLocker</span> locker(<span class="operator">&amp;</span>mutex);
      <span class="keyword">this</span><span class="operator">-</span><span class="operator">&gt;</span>portName <span class="operator">=</span> portName;
      <span class="keyword">this</span><span class="operator">-</span><span class="operator">&gt;</span>waitTimeout <span class="operator">=</span> waitTimeout;
      <span class="keyword">this</span><span class="operator">-</span><span class="operator">&gt;</span>response <span class="operator">=</span> response;
      <span class="keyword">if</span> (<span class="operator">!</span>isRunning())
          start();
  }

</pre>
<p>The startSlave() function stores the serial port name, timeout and response data, and QMutexLocker locks the mutex to protect these data. We then start the thread, unless it is already running. QWaitCondition::wakeOne() will be discussed later.</p>
<pre class="cpp">

  <span class="type">void</span> SlaveThread<span class="operator">::</span>run()
  {
      bool currentPortNameChanged <span class="operator">=</span> <span class="keyword">false</span>;

      mutex<span class="operator">.</span>lock();
      <span class="type">QString</span> currentPortName;
      <span class="keyword">if</span> (currentPortName <span class="operator">!</span><span class="operator">=</span> portName) {
          currentPortName <span class="operator">=</span> portName;
          currentPortNameChanged <span class="operator">=</span> <span class="keyword">true</span>;
      }

      <span class="type">int</span> currentWaitTimeout <span class="operator">=</span> waitTimeout;
      <span class="type">QString</span> currentRespone <span class="operator">=</span> response;
      mutex<span class="operator">.</span>unlock();

</pre>
<p>In the run() function, start by acquiring the mutex lock, fetch the serial port name, timeout and response data from the member data, and then release the lock again. Under no circumstance should the method <code>startSlave()</code> be called simultaneously with a process fetching these data. QString is reentrant but not thread-safe, and it is not recommended to read the serial port name from one startup, call and timeout or response data of another. SlaveThread can only handle one startup at a time.</p>
<p>The <a href="qserialport.html">QSerialPort</a> object we construct on stack into run() function before loop enter:</p>
<pre class="cpp">

      <span class="type"><a href="qserialport.html">QSerialPort</a></span> serial;

      <span class="keyword">while</span> (<span class="operator">!</span>quit) {

</pre>
<p>This allows us once to create an object, while running loop, and also means that all the methods of the object will be executed in the context of the run() thread.</p>
<p>In the loop, check whether the name of the serial port for the current startup has changed or not. If it has, re-open and reconfigure the serial port.</p>
<pre class="cpp">

          <span class="keyword">if</span> (currentPortNameChanged) {
              serial<span class="operator">.</span>close();
              serial<span class="operator">.</span>setPortName(currentPortName);

              <span class="keyword">if</span> (<span class="operator">!</span>serial<span class="operator">.</span>open(<span class="type">QIODevice</span><span class="operator">::</span>ReadWrite)) {
                  <span class="keyword">emit</span> error(tr(<span class="string">&quot;Can't open %1, error code %2&quot;</span>)
                             <span class="operator">.</span>arg(portName)<span class="operator">.</span>arg(serial<span class="operator">.</span>error()));
                  <span class="keyword">return</span>;
              }
          }

          <span class="keyword">if</span> (serial<span class="operator">.</span>waitForReadyRead(currentWaitTimeout)) {

</pre>
<p>The loop will continue waiting for request data:</p>
<pre class="cpp">

              <span class="comment">// read request</span>
              <span class="type">QByteArray</span> requestData <span class="operator">=</span> serial<span class="operator">.</span>readAll();
              <span class="keyword">while</span> (serial<span class="operator">.</span>waitForReadyRead(<span class="number">10</span>))
                  requestData <span class="operator">+</span><span class="operator">=</span> serial<span class="operator">.</span>readAll();

</pre>
<p><b>Warning:</b> The method waitForReadyRead() should be used before each read() call for the blocking approach, because it processes all the I/O routines instead of Qt event-loop.</p>
<p>The timeout() signal is emitted if error occurs when reading data.</p>
<pre class="cpp">

          } <span class="keyword">else</span> {
              <span class="keyword">emit</span> timeout(tr(<span class="string">&quot;Wait read request timeout %1&quot;</span>)
                           <span class="operator">.</span>arg(<span class="type">QTime</span><span class="operator">::</span>currentTime()<span class="operator">.</span>toString()));
          }

</pre>
<p>After a successful read, try to send a response and wait for completion of the transfer:</p>
<pre class="cpp">

              <span class="comment">// write response</span>
              <span class="type">QByteArray</span> responseData <span class="operator">=</span> currentRespone<span class="operator">.</span>toLocal8Bit();
              serial<span class="operator">.</span>write(responseData);
              <span class="keyword">if</span> (serial<span class="operator">.</span>waitForBytesWritten(waitTimeout)) {
                  <span class="type">QString</span> request(requestData);
                  <span class="keyword">emit</span> <span class="keyword">this</span><span class="operator">-</span><span class="operator">&gt;</span>request(request);

</pre>
<p><b>Warning:</b> The method waitForBytesWritten() should be used after each write() call for the blocking approach, because it processes all the I/O routines instead of Qt event-loop.</p>
<p>The timeout() signal is emitted if an error occurs when writing data.</p>
<pre class="cpp">

              } <span class="keyword">else</span> {
                  <span class="keyword">emit</span> timeout(tr(<span class="string">&quot;Wait write response timeout %1&quot;</span>)
                               <span class="operator">.</span>arg(<span class="type">QTime</span><span class="operator">::</span>currentTime()<span class="operator">.</span>toString()));
              }

</pre>
<p>After a successful writing is emitted, request() signal containing the data received from the Master application:</p>
<pre class="cpp">

                  <span class="keyword">emit</span> <span class="keyword">this</span><span class="operator">-</span><span class="operator">&gt;</span>request(request);

</pre>
<p>Next, the thread switches to reading the current parameters for the serial interface, because they can already have been updated, and run the loop from the beginning.</p>
<pre class="cpp">

          mutex<span class="operator">.</span>lock();
          <span class="keyword">if</span> (currentPortName <span class="operator">!</span><span class="operator">=</span> portName) {
              currentPortName <span class="operator">=</span> portName;
              currentPortNameChanged <span class="operator">=</span> <span class="keyword">true</span>;
          } <span class="keyword">else</span> {
              currentPortNameChanged <span class="operator">=</span> <span class="keyword">false</span>;
          }
          currentWaitTimeout <span class="operator">=</span> waitTimeout;
          currentRespone <span class="operator">=</span> response;
          mutex<span class="operator">.</span>unlock();
      }

</pre>
<a name="running-the-example"></a>
<h2 id="running-the-example">Running the Example</h2>
<p>To run the example from Qt Creator, open the <b>Welcome</b> mode and select the example from <b>Examples</b>. For more information, visit Building and Running an Example.</p>
<p>Files:</p>
<ul>
<li><a href="qtserialport-blockingslave-dialog-cpp.html">blockingslave/dialog.cpp</a></li>
<li><a href="qtserialport-blockingslave-dialog-h.html">blockingslave/dialog.h</a></li>
<li><a href="qtserialport-blockingslave-slavethread-cpp.html">blockingslave/slavethread.cpp</a></li>
<li><a href="qtserialport-blockingslave-slavethread-h.html">blockingslave/slavethread.h</a></li>
<li><a href="qtserialport-blockingslave-main-cpp.html">blockingslave/main.cpp</a></li>
<li><a href="qtserialport-blockingslave-blockingslave-pro.html">blockingslave/blockingslave.pro</a></li>
</ul>
</div>
<p><b>See also </b><a href="qtserialport-terminal-example.html">Terminal Example</a> and <a href="qtserialport-blockingmaster-example.html">Blocking Master Example</a>.</p>
<!-- @@@blockingslave -->
        </div>
       </div>
   </div>
   </div>
</div>
<div class="footer">
   <p>
   <acronym title="Copyright">&copy;</acronym> 2017 The Qt Company Ltd.
   Documentation contributions included herein are the copyrights of
   their respective owners.<br>    The documentation provided herein is licensed under the terms of the    <a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation    License version 1.3</a> as published by the Free Software Foundation.<br>    Qt and respective logos are trademarks of The Qt Company Ltd.     in Finland and/or other countries worldwide. All other trademarks are property
   of their respective owners. </p>
</div>
</body>
</html>