summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLiang Qi <liang.qi@theqtcompany.com>2015-09-25 20:59:24 +0200
committerLiang Qi <liang.qi@theqtcompany.com>2015-09-25 20:59:24 +0200
commit4280d29fff431a87a2771cc37a555fc8cb54be8e (patch)
tree6615fd79d3e7577a190fa484fe8f564ed91a89a7
parent501e14b22a3b0c46bd7b96d3c75973f3b08da650 (diff)
parenta1655d6ccf3f82508286b471819cc5e5cb64ff44 (diff)
downloadqtserialport-4280d29fff431a87a2771cc37a555fc8cb54be8e.tar.gz
Merge remote-tracking branch 'origin/5.6' into dev
Change-Id: Ida48b2300ed5fb4eda3b439a44baf55e42177b00
-rw-r--r--LICENSE.GPLv3686
-rw-r--r--LICENSE.LGPLv32
-rw-r--r--examples/serialport/blockingmaster/dialog.cpp12
-rw-r--r--examples/serialport/blockingslave/dialog.cpp23
-rw-r--r--examples/serialport/creaderasync/serialportreader.cpp7
-rw-r--r--examples/serialport/cwriterasync/serialportwriter.cpp7
-rw-r--r--examples/serialport/master/dialog.cpp9
-rw-r--r--examples/serialport/slave/dialog.cpp22
-rw-r--r--examples/serialport/terminal/mainwindow.cpp22
-rw-r--r--examples/serialport/terminal/settingsdialog.cpp16
-rw-r--r--src/serialport/qserialport.cpp87
-rw-r--r--src/serialport/qserialport.h8
-rw-r--r--src/serialport/qserialport_p.h33
-rw-r--r--src/serialport/qserialport_unix.cpp462
-rw-r--r--src/serialport/qserialport_win.cpp216
-rw-r--r--src/serialport/qserialport_wince.cpp71
-rw-r--r--src/serialport/qserialportinfo.h3
-rw-r--r--src/serialport/qserialportinfo_unix.cpp312
-rw-r--r--tests/auto/qserialport/tst_qserialport.cpp350
19 files changed, 1726 insertions, 622 deletions
diff --git a/LICENSE.GPLv3 b/LICENSE.GPLv3
new file mode 100644
index 0000000..4e49b12
--- /dev/null
+++ b/LICENSE.GPLv3
@@ -0,0 +1,686 @@
+ GNU GENERAL PUBLIC LICENSE
+
+ The Qt Toolkit is Copyright (C) 2015 The Qt Company Ltd.
+ Contact: http://www.qt.io/licensing/
+
+ You may use, distribute and copy the Qt GUI Toolkit under the terms of
+ GNU Lesser General Public License version 3. That license references
+ the General Public License version 3, that is displayed below. Other
+ portions of the Qt Toolkit may be licensed directly under this license.
+
+-------------------------------------------------------------------------
+
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ <program> Copyright (C) <year> <name of author>
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<http://www.gnu.org/licenses/>.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
diff --git a/LICENSE.LGPLv3 b/LICENSE.LGPLv3
index 8fbb743..4d67bac 100644
--- a/LICENSE.LGPLv3
+++ b/LICENSE.LGPLv3
@@ -5,6 +5,8 @@
You may use, distribute and copy the Qt GUI Toolkit under the terms of
GNU Lesser General Public License version 3, which is displayed below.
+ This license makes reference to the version 3 of the GNU General
+ Public License, which you can find in the LICENSE.GPLv3 file.
-------------------------------------------------------------------------
diff --git a/examples/serialport/blockingmaster/dialog.cpp b/examples/serialport/blockingmaster/dialog.cpp
index 6355429..86020a1 100644
--- a/examples/serialport/blockingmaster/dialog.cpp
+++ b/examples/serialport/blockingmaster/dialog.cpp
@@ -78,14 +78,10 @@ Dialog::Dialog(QWidget *parent)
setWindowTitle(tr("Blocking Master"));
serialPortComboBox->setFocus();
- connect(runButton, SIGNAL(clicked()),
- this, SLOT(transaction()));
- connect(&thread, SIGNAL(response(QString)),
- this, SLOT(showResponse(QString)));
- connect(&thread, SIGNAL(error(QString)),
- this, SLOT(processError(QString)));
- connect(&thread, SIGNAL(timeout(QString)),
- this, SLOT(processTimeout(QString)));
+ connect(runButton, &QPushButton::clicked, this, &Dialog::transaction);
+ connect(&thread, &MasterThread::response, this, &Dialog::showResponse);
+ connect(&thread, &MasterThread::error, this, &Dialog::processError);
+ connect(&thread, &MasterThread::timeout, this, &Dialog::processTimeout);
}
void Dialog::transaction()
diff --git a/examples/serialport/blockingslave/dialog.cpp b/examples/serialport/blockingslave/dialog.cpp
index 9933e05..78c2ec0 100644
--- a/examples/serialport/blockingslave/dialog.cpp
+++ b/examples/serialport/blockingslave/dialog.cpp
@@ -78,21 +78,16 @@ Dialog::Dialog(QWidget *parent)
setWindowTitle(tr("Blocking Slave"));
serialPortComboBox->setFocus();
- connect(runButton, SIGNAL(clicked()),
- this, SLOT(startSlave()));
- connect(&thread, SIGNAL(request(QString)),
- this, SLOT(showRequest(QString)));
- connect(&thread, SIGNAL(error(QString)),
- this, SLOT(processError(QString)));
- connect(&thread, SIGNAL(timeout(QString)),
- this, SLOT(processTimeout(QString)));
+ connect(runButton, &QPushButton::clicked, this, &Dialog::startSlave);
+ connect(&thread, &SlaveThread::request, this,&Dialog::showRequest);
+ connect(&thread, &SlaveThread::error, this, &Dialog::processError);
+ connect(&thread, &SlaveThread::timeout, this, &Dialog::processTimeout);
- connect(serialPortComboBox, SIGNAL(currentIndexChanged(QString)),
- this, SLOT(activateRunButton()));
- connect(waitRequestSpinBox, SIGNAL(valueChanged(int)),
- this, SLOT(activateRunButton()));
- connect(responseLineEdit, SIGNAL(textChanged(QString)),
- this, SLOT(activateRunButton()));
+ connect(serialPortComboBox, static_cast<void (QComboBox::*)(const QString &)>(&QComboBox::currentIndexChanged),
+ this, &Dialog::activateRunButton);
+ connect(waitRequestSpinBox, static_cast<void (QSpinBox::*)(const QString &)>(&QSpinBox::valueChanged),
+ this, &Dialog::activateRunButton);
+ connect(responseLineEdit, &QLineEdit::textChanged, this, &Dialog::activateRunButton);
}
void Dialog::startSlave()
diff --git a/examples/serialport/creaderasync/serialportreader.cpp b/examples/serialport/creaderasync/serialportreader.cpp
index 815ff8c..5188c69 100644
--- a/examples/serialport/creaderasync/serialportreader.cpp
+++ b/examples/serialport/creaderasync/serialportreader.cpp
@@ -42,9 +42,10 @@ SerialPortReader::SerialPortReader(QSerialPort *serialPort, QObject *parent)
, m_serialPort(serialPort)
, m_standardOutput(stdout)
{
- connect(m_serialPort, SIGNAL(readyRead()), SLOT(handleReadyRead()));
- connect(m_serialPort, SIGNAL(error(QSerialPort::SerialPortError)), SLOT(handleError(QSerialPort::SerialPortError)));
- connect(&m_timer, SIGNAL(timeout()), SLOT(handleTimeout()));
+ connect(m_serialPort, &QSerialPort::readyRead, this, &SerialPortReader::handleReadyRead);
+ connect(m_serialPort, static_cast<void (QSerialPort::*)(QSerialPort::SerialPortError)>(&QSerialPort::error),
+ this, &SerialPortReader::handleError);
+ connect(&m_timer, &QTimer::timeout, this, &SerialPortReader::handleTimeout);
m_timer.start(5000);
}
diff --git a/examples/serialport/cwriterasync/serialportwriter.cpp b/examples/serialport/cwriterasync/serialportwriter.cpp
index b50b353..4b22259 100644
--- a/examples/serialport/cwriterasync/serialportwriter.cpp
+++ b/examples/serialport/cwriterasync/serialportwriter.cpp
@@ -44,9 +44,10 @@ SerialPortWriter::SerialPortWriter(QSerialPort *serialPort, QObject *parent)
, m_bytesWritten(0)
{
m_timer.setSingleShot(true);
- connect(m_serialPort, SIGNAL(bytesWritten(qint64)), SLOT(handleBytesWritten(qint64)));
- connect(m_serialPort, SIGNAL(error(QSerialPort::SerialPortError)), SLOT(handleError(QSerialPort::SerialPortError)));
- connect(&m_timer, SIGNAL(timeout()), SLOT(handleTimeout()));
+ connect(m_serialPort, &QSerialPort::bytesWritten, this, &SerialPortWriter::handleBytesWritten);
+ connect(m_serialPort, static_cast<void (QSerialPort::*)(QSerialPort::SerialPortError)>(&QSerialPort::error),
+ this, &SerialPortWriter::handleError);
+ connect(&m_timer, &QTimer::timeout, this, &SerialPortWriter::handleTimeout);
}
SerialPortWriter::~SerialPortWriter()
diff --git a/examples/serialport/master/dialog.cpp b/examples/serialport/master/dialog.cpp
index c292b66..847635a 100644
--- a/examples/serialport/master/dialog.cpp
+++ b/examples/serialport/master/dialog.cpp
@@ -80,12 +80,9 @@ Dialog::Dialog(QWidget *parent)
timer.setSingleShot(true);
- connect(runButton, SIGNAL(clicked()),
- this, SLOT(sendRequest()));
- connect(&serial, SIGNAL(readyRead()),
- this, SLOT(readResponse()));
- connect(&timer, SIGNAL(timeout()),
- this, SLOT(processTimeout()));
+ connect(runButton, &QPushButton::clicked, this, &Dialog::sendRequest);
+ connect(&serial, &QSerialPort::readyRead, this, &Dialog::readResponse);
+ connect(&timer, &QTimer::timeout, this, &Dialog::processTimeout);
}
void Dialog::sendRequest()
diff --git a/examples/serialport/slave/dialog.cpp b/examples/serialport/slave/dialog.cpp
index 34118de..2d5d81d 100644
--- a/examples/serialport/slave/dialog.cpp
+++ b/examples/serialport/slave/dialog.cpp
@@ -80,19 +80,15 @@ Dialog::Dialog(QWidget *parent)
timer.setSingleShot(true);
- connect(runButton, SIGNAL(clicked()),
- this, SLOT(startSlave()));
- connect(&serial, SIGNAL(readyRead()),
- this, SLOT(readRequest()));
- connect(&timer, SIGNAL(timeout()),
- this, SLOT(processTimeout()));
-
- connect(serialPortComboBox, SIGNAL(currentIndexChanged(QString)),
- this, SLOT(activateRunButton()));
- connect(waitRequestSpinBox, SIGNAL(valueChanged(int)),
- this, SLOT(activateRunButton()));
- connect(responseLineEdit, SIGNAL(textChanged(QString)),
- this, SLOT(activateRunButton()));
+ connect(runButton, &QPushButton::clicked, this, &Dialog::startSlave);
+ connect(&serial, &QSerialPort::readyRead, this, &Dialog::readRequest);
+ connect(&timer, &QTimer::timeout, this, &Dialog::processTimeout);
+
+ connect(serialPortComboBox, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged),
+ this, &Dialog::activateRunButton);
+ connect(waitRequestSpinBox, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged),
+ this, &Dialog::activateRunButton);
+ connect(responseLineEdit, &QLineEdit::textChanged, this, &Dialog::activateRunButton);
}
void Dialog::startSlave()
diff --git a/examples/serialport/terminal/mainwindow.cpp b/examples/serialport/terminal/mainwindow.cpp
index 3630b1f..b26b884 100644
--- a/examples/serialport/terminal/mainwindow.cpp
+++ b/examples/serialport/terminal/mainwindow.cpp
@@ -66,13 +66,13 @@ MainWindow::MainWindow(QWidget *parent) :
initActionsConnections();
- connect(serial, SIGNAL(error(QSerialPort::SerialPortError)), this,
- SLOT(handleError(QSerialPort::SerialPortError)));
+ connect(serial, static_cast<void (QSerialPort::*)(QSerialPort::SerialPortError)>(&QSerialPort::error),
+ this, &MainWindow::handleError);
//! [2]
- connect(serial, SIGNAL(readyRead()), this, SLOT(readData()));
+ connect(serial, &QSerialPort::readyRead, this, &MainWindow::readData);
//! [2]
- connect(console, SIGNAL(getData(QByteArray)), this, SLOT(writeData(QByteArray)));
+ connect(console, &Console::getData, this, &MainWindow::writeData);
//! [3]
}
//! [3]
@@ -158,13 +158,13 @@ void MainWindow::handleError(QSerialPort::SerialPortError error)
void MainWindow::initActionsConnections()
{
- connect(ui->actionConnect, SIGNAL(triggered()), this, SLOT(openSerialPort()));
- connect(ui->actionDisconnect, SIGNAL(triggered()), this, SLOT(closeSerialPort()));
- connect(ui->actionQuit, SIGNAL(triggered()), this, SLOT(close()));
- connect(ui->actionConfigure, SIGNAL(triggered()), settings, SLOT(show()));
- connect(ui->actionClear, SIGNAL(triggered()), console, SLOT(clear()));
- connect(ui->actionAbout, SIGNAL(triggered()), this, SLOT(about()));
- connect(ui->actionAboutQt, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
+ connect(ui->actionConnect, &QAction::triggered, this, &MainWindow::openSerialPort);
+ connect(ui->actionDisconnect, &QAction::triggered, this, &MainWindow::closeSerialPort);
+ connect(ui->actionQuit, &QAction::triggered, this, &MainWindow::close);
+ connect(ui->actionConfigure, &QAction::triggered, settings, &MainWindow::show);
+ connect(ui->actionClear, &QAction::triggered, console, &Console::clear);
+ connect(ui->actionAbout, &QAction::triggered, this, &MainWindow::about);
+ connect(ui->actionAboutQt, &QAction::triggered, qApp, &QApplication::aboutQt);
}
void MainWindow::showStatusMessage(const QString &message)
diff --git a/examples/serialport/terminal/settingsdialog.cpp b/examples/serialport/terminal/settingsdialog.cpp
index 900d2fe..cd7211d 100644
--- a/examples/serialport/terminal/settingsdialog.cpp
+++ b/examples/serialport/terminal/settingsdialog.cpp
@@ -53,14 +53,14 @@ SettingsDialog::SettingsDialog(QWidget *parent) :
ui->baudRateBox->setInsertPolicy(QComboBox::NoInsert);
- connect(ui->applyButton, SIGNAL(clicked()),
- this, SLOT(apply()));
- connect(ui->serialPortInfoListBox, SIGNAL(currentIndexChanged(int)),
- this, SLOT(showPortInfo(int)));
- connect(ui->baudRateBox, SIGNAL(currentIndexChanged(int)),
- this, SLOT(checkCustomBaudRatePolicy(int)));
- connect(ui->serialPortInfoListBox, SIGNAL(currentIndexChanged(int)),
- this, SLOT(checkCustomDevicePathPolicy(int)));
+ connect(ui->applyButton, &QPushButton::clicked,
+ this, &SettingsDialog::apply);
+ connect(ui->serialPortInfoListBox, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged),
+ this, &SettingsDialog::showPortInfo);
+ connect(ui->baudRateBox, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged),
+ this, &SettingsDialog::checkCustomBaudRatePolicy);
+ connect(ui->serialPortInfoListBox, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged),
+ this, &SettingsDialog::checkCustomDevicePathPolicy);
fillPortsParameters();
fillPortsInfo();
diff --git a/src/serialport/qserialport.cpp b/src/serialport/qserialport.cpp
index 9ed1c5f..690eb65 100644
--- a/src/serialport/qserialport.cpp
+++ b/src/serialport/qserialport.cpp
@@ -44,6 +44,42 @@
QT_BEGIN_NAMESPACE
+QSerialPortErrorInfo::QSerialPortErrorInfo(QSerialPort::SerialPortError newErrorCode,
+ const QString &newErrorString)
+ : errorCode(newErrorCode)
+ , errorString(newErrorString)
+{
+ if (errorString.isNull()) {
+ switch (errorCode) {
+ case QSerialPort::NoError:
+ errorString = QSerialPort::tr("No error");
+ break;
+ case QSerialPort::OpenError:
+ errorString = QSerialPort::tr("Device is already open");
+ break;
+ case QSerialPort::NotOpenError:
+ errorString = QSerialPort::tr("Device is not open");
+ break;
+ case QSerialPort::TimeoutError:
+ errorString = QSerialPort::tr("Operation timed out");
+ break;
+ case QSerialPort::ReadError:
+ errorString = QSerialPort::tr("Error reading from device");
+ break;
+ case QSerialPort::WriteError:
+ errorString = QSerialPort::tr("Error writing to device");
+ break;
+ case QSerialPort::ResourceError:
+ errorString = QSerialPort::tr("Device disappeared from the system");
+ break;
+ default:
+ // an empty string will be interpreted as "Unknown error"
+ // from the QIODevice::errorString()
+ break;
+ }
+ }
+}
+
QSerialPortPrivate::QSerialPortPrivate()
: readBufferMaxSize(0)
, writeBuffer(InitialBufferSize)
@@ -54,19 +90,17 @@ QSerialPortPrivate::QSerialPortPrivate()
, parity(QSerialPort::NoParity)
, stopBits(QSerialPort::OneStop)
, flowControl(QSerialPort::NoFlowControl)
- , policy(QSerialPort::IgnorePolicy)
#if QT_DEPRECATED_SINCE(5,3)
, settingsRestoredOnClose(true)
#endif
, isBreakEnabled(false)
#if defined(Q_OS_WINCE)
, handle(INVALID_HANDLE_VALUE)
- , parityErrorOccurred(false)
, eventNotifier(0)
#elif defined(Q_OS_WIN32)
, handle(INVALID_HANDLE_VALUE)
- , parityErrorOccurred(false)
, readChunkBuffer(ReadChunkSize, 0)
+ , communicationStarted(false)
, writeStarted(false)
, readStarted(false)
, notifier(0)
@@ -176,7 +210,7 @@ void QSerialPortPrivate::setError(const QSerialPortErrorInfo &errorInfo)
used in non-GUI threads, to avoid freezing the user interface.
For more details about these approaches, refer to the
- \l {Examples}{example} applications.
+ \l {Qt Serial Port Examples}{example} applications.
The QSerialPort class can also be used with QTextStream and QDataStream's
stream operators (operator<<() and operator>>()). There is one issue to be
@@ -371,13 +405,16 @@ void QSerialPortPrivate::setError(const QSerialPortErrorInfo &errorInfo)
QtSerialPort 5.2.
\value ParityError Parity error detected by the hardware while
- reading data.
+ reading data. This value is obsolete. We strongly
+ advise against using it in new code.
\value FramingError Framing error detected by the hardware while
- reading data.
+ reading data. This value is obsolete. We strongly
+ advise against using it in new code.
\value BreakConditionError Break condition detected by the hardware on
- the input line.
+ the input line. This value is obsolete. We strongly
+ advise against using it in new code.
\value WriteError An I/O error occurred while writing the data.
@@ -521,7 +558,7 @@ bool QSerialPort::open(OpenMode mode)
Q_D(QSerialPort);
if (isOpen()) {
- d->setError(QSerialPortErrorInfo(QSerialPort::OpenError, tr("Device is already open")));
+ d->setError(QSerialPortErrorInfo(QSerialPort::OpenError));
return false;
}
@@ -561,7 +598,7 @@ void QSerialPort::close()
{
Q_D(QSerialPort);
if (!isOpen()) {
- d->setError(QSerialPortErrorInfo(QSerialPort::NotOpenError, tr("Device is not open")));
+ d->setError(QSerialPortErrorInfo(QSerialPort::NotOpenError));
return;
}
@@ -874,7 +911,7 @@ bool QSerialPort::setDataTerminalReady(bool set)
Q_D(QSerialPort);
if (!isOpen()) {
- d->setError(QSerialPortErrorInfo(QSerialPort::NotOpenError, tr("Device is not open")));
+ d->setError(QSerialPortErrorInfo(QSerialPort::NotOpenError));
qWarning("%s: device not open", Q_FUNC_INFO);
return false;
}
@@ -921,7 +958,7 @@ bool QSerialPort::setRequestToSend(bool set)
Q_D(QSerialPort);
if (!isOpen()) {
- d->setError(QSerialPortErrorInfo(QSerialPort::NotOpenError, tr("Device is not open")));
+ d->setError(QSerialPortErrorInfo(QSerialPort::NotOpenError));
qWarning("%s: device not open", Q_FUNC_INFO);
return false;
}
@@ -971,7 +1008,7 @@ QSerialPort::PinoutSignals QSerialPort::pinoutSignals()
Q_D(QSerialPort);
if (!isOpen()) {
- d->setError(QSerialPortErrorInfo(QSerialPort::NotOpenError, tr("Device is not open")));
+ d->setError(QSerialPortErrorInfo(QSerialPort::NotOpenError));
qWarning("%s: device not open", Q_FUNC_INFO);
return QSerialPort::NoSignal;
}
@@ -1001,7 +1038,7 @@ bool QSerialPort::flush()
Q_D(QSerialPort);
if (!isOpen()) {
- d->setError(QSerialPortErrorInfo(QSerialPort::NotOpenError, tr("Device is not open")));
+ d->setError(QSerialPortErrorInfo(QSerialPort::NotOpenError));
qWarning("%s: device not open", Q_FUNC_INFO);
return false;
}
@@ -1023,7 +1060,7 @@ bool QSerialPort::clear(Directions directions)
Q_D(QSerialPort);
if (!isOpen()) {
- d->setError(QSerialPortErrorInfo(QSerialPort::NotOpenError, tr("Device is not open")));
+ d->setError(QSerialPortErrorInfo(QSerialPort::NotOpenError));
qWarning("%s: device not open", Q_FUNC_INFO);
return false;
}
@@ -1085,24 +1122,23 @@ bool QSerialPort::setDataErrorPolicy(DataErrorPolicy policy)
Q_D(QSerialPort);
if (!isOpen()) {
- d->setError(QSerialPortErrorInfo(QSerialPort::NotOpenError, tr("Device is not open")));
+ d->setError(QSerialPortErrorInfo(QSerialPort::NotOpenError));
qWarning("%s: device not open", Q_FUNC_INFO);
return false;
}
- const bool ret = d->policy == policy || d->setDataErrorPolicy(policy);
- if (ret && (d->policy != policy)) {
- d->policy = policy;
- emit dataErrorPolicyChanged(d->policy);
+ if (policy != QSerialPort::IgnorePolicy) {
+ d->setError(QSerialPortErrorInfo(QSerialPort::UnsupportedOperationError,
+ tr("The device supports only the ignoring policy")));
+ return false;
}
- return ret;
+ return true;
}
QSerialPort::DataErrorPolicy QSerialPort::dataErrorPolicy() const
{
- Q_D(const QSerialPort);
- return d->policy;
+ return QSerialPort::IgnorePolicy;
}
#endif // QT_DEPRECATED_SINCE(5, 2)
@@ -1311,7 +1347,7 @@ bool QSerialPort::sendBreak(int duration)
Q_D(QSerialPort);
if (!isOpen()) {
- d->setError(QSerialPortErrorInfo(QSerialPort::NotOpenError, tr("Device is not open")));
+ d->setError(QSerialPortErrorInfo(QSerialPort::NotOpenError));
qWarning("%s: device not open", Q_FUNC_INFO);
return false;
}
@@ -1341,7 +1377,7 @@ bool QSerialPort::setBreakEnabled(bool set)
Q_D(QSerialPort);
if (!isOpen()) {
- d->setError(QSerialPortErrorInfo(QSerialPort::NotOpenError, tr("Device is not open")));
+ d->setError(QSerialPortErrorInfo(QSerialPort::NotOpenError));
qWarning("%s: device not open", Q_FUNC_INFO);
return false;
}
@@ -1370,8 +1406,6 @@ bool QSerialPort::isBreakEnabled() const
// method will be called.
qint64 QSerialPort::readData(char *data, qint64 maxSize)
{
- Q_D(QSerialPort);
-
Q_UNUSED(data);
Q_UNUSED(maxSize);
@@ -1380,6 +1414,7 @@ qint64 QSerialPort::readData(char *data, qint64 maxSize)
// in case we have a limited read buffer size. Because the read notification can
// be stalled since Windows do not re-triggered an EV_RXCHAR event if a driver's
// buffer has a remainder of data ready to read until a new data will be received.
+ Q_D(QSerialPort);
if (d->readBufferMaxSize || d->flowControl == QSerialPort::HardwareControl)
d->startAsyncRead();
#endif
diff --git a/src/serialport/qserialport.h b/src/serialport/qserialport.h
index 2815ebe..a19e1bf 100644
--- a/src/serialport/qserialport.h
+++ b/src/serialport/qserialport.h
@@ -186,6 +186,14 @@ public:
};
Q_ENUM(SerialPortError)
+#if QT_DEPRECATED_SINCE(5, 6)
+#if defined(_MSC_VER)
+#pragma deprecated(ParityError)
+#pragma deprecated(FramingError)
+#pragma deprecated(BreakConditionError)
+#endif
+#endif
+
explicit QSerialPort(QObject *parent = Q_NULLPTR);
explicit QSerialPort(const QString &name, QObject *parent = Q_NULLPTR);
explicit QSerialPort(const QSerialPortInfo &info, QObject *parent = Q_NULLPTR);
diff --git a/src/serialport/qserialport_p.h b/src/serialport/qserialport_p.h
index 571b0de..d2527e3 100644
--- a/src/serialport/qserialport_p.h
+++ b/src/serialport/qserialport_p.h
@@ -109,12 +109,8 @@ QString serialPortLockFilePath(const QString &portName);
class QSerialPortErrorInfo
{
public:
- explicit QSerialPortErrorInfo(QSerialPort::SerialPortError errorCode = QSerialPort::UnknownError,
- const QString &errorString = QString())
- : errorCode(errorCode)
- , errorString(errorString)
- {
- }
+ explicit QSerialPortErrorInfo(QSerialPort::SerialPortError newErrorCode = QSerialPort::UnknownError,
+ const QString &newErrorString = QString());
QSerialPort::SerialPortError errorCode;
QString errorString;
};
@@ -155,7 +151,6 @@ public:
bool setParity(QSerialPort::Parity parity);
bool setStopBits(QSerialPort::StopBits stopBits);
bool setFlowControl(QSerialPort::FlowControl flowControl);
- bool setDataErrorPolicy(QSerialPort::DataErrorPolicy policy);
QSerialPortErrorInfo getSystemError(int systemErrorCode = -1) const;
@@ -181,7 +176,6 @@ public:
QSerialPort::Parity parity;
QSerialPort::StopBits stopBits;
QSerialPort::FlowControl flowControl;
- QSerialPort::DataErrorPolicy policy;
bool settingsRestoredOnClose;
bool isBreakEnabled;
@@ -194,7 +188,6 @@ public:
bool waitForReadOrWrite(bool *selectForRead, bool *selectForWrite,
bool checkRead, bool checkWrite,
int msecs);
- void processIoErrors(bool error);
bool notifyRead();
bool notifyWrite();
@@ -204,7 +197,6 @@ public:
COMMTIMEOUTS currentCommTimeouts;
COMMTIMEOUTS restoredCommTimeouts;
HANDLE handle;
- bool parityErrorOccurred;
QThread *eventNotifier;
QMutex settingsChangeMutex;
@@ -212,9 +204,9 @@ public:
#elif defined(Q_OS_WIN32)
bool initialize();
- bool updateDcb();
+ bool setDcb(DCB *dcb);
+ bool getDcb(DCB *dcb);
bool updateCommTimeouts();
- void handleLineStatusErrors();
OVERLAPPED *waitForNotified(int msecs);
bool completeAsyncCommunication(qint64 bytesTransferred);
@@ -226,16 +218,14 @@ public:
bool _q_startAsyncWrite();
void _q_notified(DWORD numberOfBytes, DWORD errorCode, OVERLAPPED *overlapped);
- bool emulateErrorPolicy();
void emitReadyRead();
- DCB currentDcb;
DCB restoredDcb;
COMMTIMEOUTS currentCommTimeouts;
COMMTIMEOUTS restoredCommTimeouts;
HANDLE handle;
- bool parityErrorOccurred;
QByteArray readChunkBuffer;
+ bool communicationStarted;
bool writeStarted;
bool readStarted;
QWinOverlappedIoNotifier *notifier;
@@ -250,14 +240,11 @@ public:
#elif defined(Q_OS_UNIX)
bool initialize(QIODevice::OpenMode mode);
- bool updateTermios();
+ bool setTermios(const termios *tio);
+ bool getTermios(termios *tio);
- QSerialPortErrorInfo setBaudRate_helper(qint32 baudRate,
- QSerialPort::Directions directions);
- QSerialPortErrorInfo setCustomBaudRate(qint32 baudRate,
- QSerialPort::Directions directions);
- QSerialPortErrorInfo setStandardBaudRate(qint32 baudRate,
- QSerialPort::Directions directions);
+ bool setCustomBaudRate(qint32 baudRate, QSerialPort::Directions directions);
+ bool setStandardBaudRate(qint32 baudRate, QSerialPort::Directions directions);
bool isReadNotificationEnabled() const;
void setReadNotificationEnabled(bool enable);
@@ -274,13 +261,11 @@ public:
#ifndef CMSPAR
qint64 writePerChar(const char *data, qint64 maxSize);
#endif
- qint64 readPerChar(char *data, qint64 maxSize);
bool readNotification();
bool startAsyncWrite();
bool completeAsyncWrite();
- struct termios currentTermios;
struct termios restoredTermios;
int descriptor;
diff --git a/src/serialport/qserialport_unix.cpp b/src/serialport/qserialport_unix.cpp
index 612d84a..4659a18 100644
--- a/src/serialport/qserialport_unix.cpp
+++ b/src/serialport/qserialport_unix.cpp
@@ -52,6 +52,33 @@
#define CRTSCTS (IHFLOW | OHFLOW)
#endif
+#ifdef Q_OS_LINUX
+
+struct termios2 {
+ tcflag_t c_iflag; /* input mode flags */
+ tcflag_t c_oflag; /* output mode flags */
+ tcflag_t c_cflag; /* control mode flags */
+ tcflag_t c_lflag; /* local mode flags */
+ cc_t c_line; /* line discipline */
+ cc_t c_cc[19]; /* control characters */
+ speed_t c_ispeed; /* input speed */
+ speed_t c_ospeed; /* output speed */
+};
+
+#ifndef TCGETS2
+#define TCGETS2 _IOR('T', 0x2A, struct termios2)
+#endif
+
+#ifndef TCSETS2
+#define TCSETS2 _IOW('T', 0x2B, struct termios2)
+#endif
+
+#ifndef BOTHER
+#define BOTHER 0010000
+#endif
+
+#endif
+
#include <private/qcore_unix_p.h>
#include <QtCore/qelapsedtimer.h>
@@ -409,121 +436,151 @@ bool QSerialPortPrivate::setBaudRate()
&& setBaudRate(outputBaudRate, QSerialPort::Output));
}
-QSerialPortErrorInfo
-QSerialPortPrivate::setBaudRate_helper(qint32 baudRate,
- QSerialPort::Directions directions)
+bool QSerialPortPrivate::setStandardBaudRate(qint32 baudRate, QSerialPort::Directions directions)
{
- if ((directions & QSerialPort::Input) && ::cfsetispeed(&currentTermios, baudRate) < 0)
- return getSystemError();
-
- if ((directions & QSerialPort::Output) && ::cfsetospeed(&currentTermios, baudRate) < 0)
- return getSystemError();
-
- return QSerialPortErrorInfo(QSerialPort::NoError);
-}
+#ifdef Q_OS_LINUX
+ // try to clear custom baud rate, using termios v2
+ struct termios2 tio2;
+ if (::ioctl(descriptor, TCGETS2, &tio2) != -1) {
+ if (tio2.c_cflag & BOTHER) {
+ tio2.c_cflag &= ~BOTHER;
+ tio2.c_cflag |= CBAUD;
+ ::ioctl(descriptor, TCSETS2, &tio2);
+ }
+ }
-#if defined(Q_OS_LINUX)
+ // try to clear custom baud rate, using serial_struct (old way)
+ struct serial_struct serial;
+ ::memset(&serial, 0, sizeof(serial));
+ if (::ioctl(descriptor, TIOCGSERIAL, &serial) != -1) {
+ if (serial.flags & ASYNC_SPD_CUST) {
+ serial.flags &= ~ASYNC_SPD_CUST;
+ serial.custom_divisor = 0;
+ // we don't check on errors because a driver can has not this feature
+ ::ioctl(descriptor, TIOCSSERIAL, &serial);
+ }
+ }
+#endif
-QSerialPortErrorInfo
-QSerialPortPrivate::setStandardBaudRate(qint32 baudRate, QSerialPort::Directions directions)
-{
- struct serial_struct currentSerialInfo;
+ termios tio;
+ if (!getTermios(&tio))
+ return false;
- ::memset(&currentSerialInfo, 0, sizeof(currentSerialInfo));
+ if ((directions & QSerialPort::Input) && ::cfsetispeed(&tio, baudRate) < 0) {
+ setError(getSystemError());
+ return false;
+ }
- if ((::ioctl(descriptor, TIOCGSERIAL, &currentSerialInfo) != -1)
- && (currentSerialInfo.flags & ASYNC_SPD_CUST)) {
- currentSerialInfo.flags &= ~ASYNC_SPD_CUST;
- currentSerialInfo.custom_divisor = 0;
- if (::ioctl(descriptor, TIOCSSERIAL, &currentSerialInfo) == -1)
- return getSystemError();
+ if ((directions & QSerialPort::Output) && ::cfsetospeed(&tio, baudRate) < 0) {
+ setError(getSystemError());
+ return false;
}
- return setBaudRate_helper(baudRate, directions);
+ return setTermios(&tio);
}
-#else
+#if defined(Q_OS_LINUX)
-QSerialPortErrorInfo
-QSerialPortPrivate::setStandardBaudRate(qint32 baudRate, QSerialPort::Directions directions)
+bool QSerialPortPrivate::setCustomBaudRate(qint32 baudRate, QSerialPort::Directions directions)
{
- return setBaudRate_helper(baudRate, directions);
-}
+ if (directions != QSerialPort::AllDirections) {
+ setError(QSerialPortErrorInfo(QSerialPort::UnsupportedOperationError,
+ QSerialPort::tr("Cannot set custom speed for one direction")));
+ return false;
+ }
-#endif
+ struct termios2 tio2;
-#if defined(Q_OS_LINUX)
+ if (::ioctl(descriptor, TCGETS2, &tio2) != -1) {
+ tio2.c_cflag &= ~CBAUD;
+ tio2.c_cflag |= BOTHER;
-QSerialPortErrorInfo
-QSerialPortPrivate::setCustomBaudRate(qint32 baudRate, QSerialPort::Directions directions)
-{
- Q_UNUSED(directions);
+ tio2.c_ispeed = baudRate;
+ tio2.c_ospeed = baudRate;
- struct serial_struct currentSerialInfo;
+ if (::ioctl(descriptor, TCSETS2, &tio2) != -1
+ && ::ioctl(descriptor, TCGETS2, &tio2) != -1) {
+ return true;
+ }
+ }
- ::memset(&currentSerialInfo, 0, sizeof(currentSerialInfo));
+ struct serial_struct serial;
- if (::ioctl(descriptor, TIOCGSERIAL, &currentSerialInfo) == -1)
- return getSystemError();
+ if (::ioctl(descriptor, TIOCGSERIAL, &serial) == -1) {
+ setError(getSystemError());
+ return false;
+ }
- currentSerialInfo.flags &= ~ASYNC_SPD_MASK;
- currentSerialInfo.flags |= (ASYNC_SPD_CUST /* | ASYNC_LOW_LATENCY*/);
- currentSerialInfo.custom_divisor = currentSerialInfo.baud_base / baudRate;
+ serial.flags &= ~ASYNC_SPD_MASK;
+ serial.flags |= (ASYNC_SPD_CUST /* | ASYNC_LOW_LATENCY*/);
+ serial.custom_divisor = serial.baud_base / baudRate;
- if (currentSerialInfo.custom_divisor == 0)
- return QSerialPortErrorInfo(QSerialPort::UnsupportedOperationError, QSerialPort::tr("No suitable custom baud rate divisor"));
+ if (serial.custom_divisor == 0) {
+ setError(QSerialPortErrorInfo(QSerialPort::UnsupportedOperationError,
+ QSerialPort::tr("No suitable custom baud rate divisor")));
+ return false;
+ }
- if (currentSerialInfo.custom_divisor * baudRate != currentSerialInfo.baud_base) {
+ if (serial.custom_divisor * baudRate != serial.baud_base) {
qWarning("Baud rate of serial port %s is set to %d instead of %d: divisor %f unsupported",
qPrintable(systemLocation),
- currentSerialInfo.baud_base / currentSerialInfo.custom_divisor,
- baudRate, (float)currentSerialInfo.baud_base / baudRate);
+ serial.baud_base / serial.custom_divisor,
+ baudRate, (float)serial.baud_base / baudRate);
}
- if (::ioctl(descriptor, TIOCSSERIAL, &currentSerialInfo) == -1)
- return getSystemError();
+ if (::ioctl(descriptor, TIOCSSERIAL, &serial) == -1) {
+ setError(getSystemError());
+ return false;
+ }
- return setBaudRate_helper(B38400, directions);
+ return setStandardBaudRate(B38400, directions);
}
#elif defined(Q_OS_MAC)
-QSerialPortErrorInfo
-QSerialPortPrivate::setCustomBaudRate(qint32 baudRate, QSerialPort::Directions directions)
+bool QSerialPortPrivate::setCustomBaudRate(qint32 baudRate, QSerialPort::Directions directions)
{
- Q_UNUSED(directions);
+ if (directions != QSerialPort::AllDirections) {
+ setError(QSerialPortErrorInfo(QSerialPort::UnsupportedOperationError,
+ QSerialPort::tr("Cannot set custom speed for one direction")));
+ return false;
+ }
#if defined(MAC_OS_X_VERSION_10_4) && (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_4)
- if (::ioctl(descriptor, IOSSIOSPEED, &baudRate) == -1)
- return getSystemError();
+ if (::ioctl(descriptor, IOSSIOSPEED, &baudRate) == -1) {
+ setError(getSystemError());
+ return false;
+ }
- return QSerialPortErrorInfo(QSerialPort::NoError);
+ return true;
+#else
+ setError(QSerialPortErrorInfo(QSerialPort::UnsupportedOperationError,
+ QSerialPort::tr("Custom baud rate is not supported")));
+ return false;
#endif
-
- return QSerialPortErrorInfo(QSerialPort::UnsupportedOperationError, QSerialPort::tr("Custom baud rate is not supported"));
}
#elif defined(Q_OS_QNX)
-QSerialPortErrorInfo
-QSerialPortPrivate::setCustomBaudRate(qint32 baudRate, QSerialPort::Directions directions)
+bool QSerialPortPrivate::setCustomBaudRate(qint32 baudRate, QSerialPort::Directions directions)
{
// On QNX, the values of the 'Bxxxx' constants are set to 'xxxx' (i.e.
// B115200 is defined to '115200'), which means that literal values can be
// passed to cfsetispeed/cfsetospeed, including custom values, provided
// that the underlying hardware supports them.
- return setBaudRate_helper(baudRate, directions);
+ return setStandardBaudRate(baudRate, directions);
}
#else
-QSerialPortErrorInfo
-QSerialPortPrivate::setCustomBaudRate(qint32 baudRate, QSerialPort::Directions directions)
+bool QSerialPortPrivate::setCustomBaudRate(qint32 baudRate, QSerialPort::Directions directions)
{
Q_UNUSED(baudRate);
Q_UNUSED(directions);
- return QSerialPortErrorInfo(QSerialPort::UnsupportedOperationError);
+ setError(QSerialPortErrorInfo(QSerialPort::UnsupportedOperationError,
+ QSerialPort::tr("Custom baud rate is not supported")));
+ return false;
}
#endif
@@ -537,147 +594,124 @@ bool QSerialPortPrivate::setBaudRate(qint32 baudRate, QSerialPort::Directions di
const qint32 unixBaudRate = QSerialPortPrivate::settingFromBaudRate(baudRate);
- const QSerialPortErrorInfo error = (unixBaudRate > 0)
- ? setStandardBaudRate(unixBaudRate, directions)
- : setCustomBaudRate(baudRate, directions);
-
- if (error.errorCode == QSerialPort::NoError)
- return updateTermios();
-
- setError(error);
- return false;
+ return (unixBaudRate > 0)
+ ? setStandardBaudRate(unixBaudRate, directions)
+ : setCustomBaudRate(baudRate, directions);
}
bool QSerialPortPrivate::setDataBits(QSerialPort::DataBits dataBits)
{
- currentTermios.c_cflag &= ~CSIZE;
+ termios tio;
+ if (!getTermios(&tio))
+ return false;
+
+ tio.c_cflag &= ~CSIZE;
switch (dataBits) {
case QSerialPort::Data5:
- currentTermios.c_cflag |= CS5;
+ tio.c_cflag |= CS5;
break;
case QSerialPort::Data6:
- currentTermios.c_cflag |= CS6;
+ tio.c_cflag |= CS6;
break;
case QSerialPort::Data7:
- currentTermios.c_cflag |= CS7;
+ tio.c_cflag |= CS7;
break;
case QSerialPort::Data8:
- currentTermios.c_cflag |= CS8;
+ tio.c_cflag |= CS8;
break;
default:
- currentTermios.c_cflag |= CS8;
+ tio.c_cflag |= CS8;
break;
}
- return updateTermios();
+ return setTermios(&tio);
}
bool QSerialPortPrivate::setParity(QSerialPort::Parity parity)
{
- currentTermios.c_iflag &= ~(PARMRK | INPCK);
- currentTermios.c_iflag |= IGNPAR;
+ termios tio;
+ if (!getTermios(&tio))
+ return false;
+
+ tio.c_iflag &= ~(PARMRK | INPCK);
+ tio.c_iflag |= IGNPAR;
switch (parity) {
#ifdef CMSPAR
// Here Installation parity only for GNU/Linux where the macro CMSPAR.
case QSerialPort::SpaceParity:
- currentTermios.c_cflag &= ~PARODD;
- currentTermios.c_cflag |= PARENB | CMSPAR;
+ tio.c_cflag &= ~PARODD;
+ tio.c_cflag |= PARENB | CMSPAR;
break;
case QSerialPort::MarkParity:
- currentTermios.c_cflag |= PARENB | CMSPAR | PARODD;
+ tio.c_cflag |= PARENB | CMSPAR | PARODD;
break;
#endif
case QSerialPort::NoParity:
- currentTermios.c_cflag &= ~PARENB;
+ tio.c_cflag &= ~PARENB;
break;
case QSerialPort::EvenParity:
- currentTermios.c_cflag &= ~PARODD;
- currentTermios.c_cflag |= PARENB;
+ tio.c_cflag &= ~PARODD;
+ tio.c_cflag |= PARENB;
break;
case QSerialPort::OddParity:
- currentTermios.c_cflag |= PARENB | PARODD;
+ tio.c_cflag |= PARENB | PARODD;
break;
default:
- currentTermios.c_cflag |= PARENB;
- currentTermios.c_iflag |= PARMRK | INPCK;
- currentTermios.c_iflag &= ~IGNPAR;
+ tio.c_cflag |= PARENB;
+ tio.c_iflag |= PARMRK | INPCK;
+ tio.c_iflag &= ~IGNPAR;
break;
}
- return updateTermios();
+ return setTermios(&tio);
}
bool QSerialPortPrivate::setStopBits(QSerialPort::StopBits stopBits)
{
+ termios tio;
+ if (!getTermios(&tio))
+ return false;
+
switch (stopBits) {
case QSerialPort::OneStop:
- currentTermios.c_cflag &= ~CSTOPB;
+ tio.c_cflag &= ~CSTOPB;
break;
case QSerialPort::TwoStop:
- currentTermios.c_cflag |= CSTOPB;
+ tio.c_cflag |= CSTOPB;
break;
default:
- currentTermios.c_cflag &= ~CSTOPB;
+ tio.c_cflag &= ~CSTOPB;
break;
}
- return updateTermios();
+ return setTermios(&tio);
}
bool QSerialPortPrivate::setFlowControl(QSerialPort::FlowControl flowControl)
{
+ termios tio;
+ if (!getTermios(&tio))
+ return false;
+
switch (flowControl) {
case QSerialPort::NoFlowControl:
- currentTermios.c_cflag &= ~CRTSCTS;
- currentTermios.c_iflag &= ~(IXON | IXOFF | IXANY);
+ tio.c_cflag &= ~CRTSCTS;
+ tio.c_iflag &= ~(IXON | IXOFF | IXANY);
break;
case QSerialPort::HardwareControl:
- currentTermios.c_cflag |= CRTSCTS;
- currentTermios.c_iflag &= ~(IXON | IXOFF | IXANY);
+ tio.c_cflag |= CRTSCTS;
+ tio.c_iflag &= ~(IXON | IXOFF | IXANY);
break;
case QSerialPort::SoftwareControl:
- currentTermios.c_cflag &= ~CRTSCTS;
- currentTermios.c_iflag |= IXON | IXOFF | IXANY;
+ tio.c_cflag &= ~CRTSCTS;
+ tio.c_iflag |= IXON | IXOFF | IXANY;
break;
default:
- currentTermios.c_cflag &= ~CRTSCTS;
- currentTermios.c_iflag &= ~(IXON | IXOFF | IXANY);
+ tio.c_cflag &= ~CRTSCTS;
+ tio.c_iflag &= ~(IXON | IXOFF | IXANY);
break;
}
- return updateTermios();
-}
-
-bool QSerialPortPrivate::setDataErrorPolicy(QSerialPort::DataErrorPolicy policy)
-{
- tcflag_t parmrkMask = PARMRK;
-#ifndef CMSPAR
- // in space/mark parity emulation also used PARMRK flag
- if (parity == QSerialPort::SpaceParity
- || parity == QSerialPort::MarkParity) {
- parmrkMask = 0;
- }
-#endif //CMSPAR
- switch (policy) {
- case QSerialPort::SkipPolicy:
- currentTermios.c_iflag &= ~parmrkMask;
- currentTermios.c_iflag |= IGNPAR | INPCK;
- break;
- case QSerialPort::PassZeroPolicy:
- currentTermios.c_iflag &= ~(IGNPAR | parmrkMask);
- currentTermios.c_iflag |= INPCK;
- break;
- case QSerialPort::IgnorePolicy:
- currentTermios.c_iflag &= ~INPCK;
- break;
- case QSerialPort::StopReceivingPolicy:
- currentTermios.c_iflag &= ~IGNPAR;
- currentTermios.c_iflag |= parmrkMask | INPCK;
- break;
- default:
- currentTermios.c_iflag &= ~INPCK;
- break;
- }
- return updateTermios();
+ return setTermios(&tio);
}
bool QSerialPortPrivate::readNotification()
@@ -686,7 +720,7 @@ bool QSerialPortPrivate::readNotification()
// Always buffered, read data from the port into the read buffer
qint64 newBytes = buffer.size();
- qint64 bytesToRead = policy == QSerialPort::IgnorePolicy ? ReadChunkSize : 1;
+ qint64 bytesToRead = ReadChunkSize;
if (readBufferMaxSize && bytesToRead > (readBufferMaxSize - buffer.size())) {
bytesToRead = readBufferMaxSize - buffer.size();
@@ -785,29 +819,28 @@ inline bool QSerialPortPrivate::initialize(QIODevice::OpenMode mode)
setError(getSystemError());
#endif
- if (::tcgetattr(descriptor, &restoredTermios) == -1) {
- setError(getSystemError());
+ termios tio;
+ if (!getTermios(&tio))
return false;
- }
- currentTermios = restoredTermios;
+ restoredTermios = tio;
#ifdef Q_OS_SOLARIS
- currentTermios.c_iflag &= ~(IMAXBEL|IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
- currentTermios.c_oflag &= ~OPOST;
- currentTermios.c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
- currentTermios.c_cflag &= ~(CSIZE|PARENB);
- currentTermios.c_cflag |= CS8;
+ tio.c_iflag &= ~(IMAXBEL|IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
+ tio.c_oflag &= ~OPOST;
+ tio.c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
+ tio.c_cflag &= ~(CSIZE|PARENB);
+ tio.c_cflag |= CS8;
#else
- ::cfmakeraw(&currentTermios);
+ ::cfmakeraw(&tio);
#endif
- currentTermios.c_cflag |= CLOCAL;
- currentTermios.c_cc[VTIME] = 0;
- currentTermios.c_cc[VMIN] = 0;
+ tio.c_cflag |= CLOCAL;
+ tio.c_cc[VTIME] = 0;
+ tio.c_cc[VMIN] = 0;
if (mode & QIODevice::ReadOnly)
- currentTermios.c_cflag |= CREAD;
+ tio.c_cflag |= CREAD;
- if (!updateTermios())
+ if (!setTermios(&tio))
return false;
if (mode & QIODevice::ReadOnly)
@@ -824,9 +857,19 @@ qint64 QSerialPortPrivate::writeData(const char *data, qint64 maxSize)
return maxSize;
}
-bool QSerialPortPrivate::updateTermios()
+bool QSerialPortPrivate::setTermios(const termios *tio)
{
- if (::tcsetattr(descriptor, TCSANOW, &currentTermios) == -1) {
+ if (::tcsetattr(descriptor, TCSANOW, tio) == -1) {
+ setError(getSystemError());
+ return false;
+ }
+ return true;
+}
+
+bool QSerialPortPrivate::getTermios(termios *tio)
+{
+ ::memset(tio, 0, sizeof(termios));
+ if (::tcgetattr(descriptor, tio) == -1) {
setError(getSystemError());
return false;
}
@@ -958,7 +1001,7 @@ bool QSerialPortPrivate::waitForReadOrWrite(bool *selectForRead, bool *selectFor
return false;
}
if (ret == 0) {
- setError(QSerialPortErrorInfo(QSerialPort::TimeoutError, QSerialPort::tr("Operation timed out")));
+ setError(QSerialPortErrorInfo(QSerialPort::TimeoutError));
return false;
}
@@ -969,20 +1012,7 @@ bool QSerialPortPrivate::waitForReadOrWrite(bool *selectForRead, bool *selectFor
qint64 QSerialPortPrivate::readFromPort(char *data, qint64 maxSize)
{
- qint64 bytesRead = 0;
-#if defined(CMSPAR)
- if (parity == QSerialPort::NoParity
- || policy != QSerialPort::StopReceivingPolicy) {
-#else
- if (parity != QSerialPort::MarkParity
- && parity != QSerialPort::SpaceParity) {
-#endif
- bytesRead = qt_safe_read(descriptor, data, maxSize);
- } else {// Perform parity emulation.
- bytesRead = readPerChar(data, maxSize);
- }
-
- return bytesRead;
+ return qt_safe_read(descriptor, data, maxSize);
}
qint64 QSerialPortPrivate::writeToPort(const char *data, qint64 maxSize)
@@ -1002,6 +1032,8 @@ qint64 QSerialPortPrivate::writeToPort(const char *data, qint64 maxSize)
return bytesWritten;
}
+#ifndef CMSPAR
+
static inline bool evenParity(quint8 c)
{
c ^= c >> 4; //(c7 ^ c3)(c6 ^ c2)(c5 ^ c1)(c4 ^ c0)
@@ -1010,10 +1042,12 @@ static inline bool evenParity(quint8 c)
return c & 1; //(c7 ^ c3)(c5 ^ c1)(c6 ^ c2)(c4 ^ c0)
}
-#ifndef CMSPAR
-
qint64 QSerialPortPrivate::writePerChar(const char *data, qint64 maxSize)
{
+ termios tio;
+ if (!getTermios(&tio))
+ return -1;
+
qint64 ret = 0;
quint8 const charMask = (0xFF >> (8 - dataBits));
@@ -1022,11 +1056,11 @@ qint64 QSerialPortPrivate::writePerChar(const char *data, qint64 maxSize)
bool par = evenParity(*data & charMask);
// False if need EVEN, true if need ODD.
par ^= parity == QSerialPort::MarkParity;
- if (par ^ (currentTermios.c_cflag & PARODD)) { // Need switch parity mode?
- currentTermios.c_cflag ^= PARODD;
- flush(); //force sending already buffered data, because updateTermios() cleares buffers
+ if (par ^ (tio.c_cflag & PARODD)) { // Need switch parity mode?
+ tio.c_cflag ^= PARODD;
+ flush(); //force sending already buffered data, because setTermios(&tio); cleares buffers
//todo: add receiving buffered data!!!
- if (!updateTermios())
+ if (!setTermios(&tio))
break;
}
@@ -1043,78 +1077,6 @@ qint64 QSerialPortPrivate::writePerChar(const char *data, qint64 maxSize)
#endif //CMSPAR
-qint64 QSerialPortPrivate::readPerChar(char *data, qint64 maxSize)
-{
- qint64 ret = 0;
- quint8 const charMask = (0xFF >> (8 - dataBits));
-
- // 0 - prefix not started,
- // 1 - received 0xFF,
- // 2 - received 0xFF and 0x00
- int prefix = 0;
- while (ret < maxSize) {
-
- qint64 r = qt_safe_read(descriptor, data, 1);
- if (r < 0) {
- if (errno == EAGAIN) // It is ok for nonblocking mode.
- break;
- return -1;
- }
- if (r == 0)
- break;
-
- bool par = true;
- switch (prefix) {
- case 2: // Previously received both 0377 and 0.
- par = false;
- prefix = 0;
- break;
- case 1: // Previously received 0377.
- if (*data == '\0') {
- ++prefix;
- continue;
- }
- prefix = 0;
- break;
- default:
- if (*data == '\377') {
- prefix = 1;
- continue;
- }
- break;
- }
- // Now: par contains parity ok or error, *data contains received character
- par ^= evenParity(*data & charMask); //par contains parity bit value for EVEN mode
- par ^= (currentTermios.c_cflag & PARODD); //par contains parity bit value for current mode
- if (par ^ (parity == QSerialPort::SpaceParity)) { //if parity error
- switch (policy) {
- case QSerialPort::SkipPolicy:
- continue; //ignore received character
- case QSerialPort::StopReceivingPolicy: {
- if (parity != QSerialPort::NoParity)
- setError(QSerialPortErrorInfo(QSerialPort::ParityError, QSerialPort::tr("Parity error detected while reading")));
- else if (*data == '\0')
- setError(QSerialPortErrorInfo(QSerialPort::BreakConditionError, QSerialPort::tr("Break condition detected while reading")));
- else
- setError(QSerialPortErrorInfo(QSerialPort::FramingError, QSerialPort::tr("Framing error detected while reading")));
- return ++ret; //abort receiving
- }
- break;
- case QSerialPort::UnknownPolicy:
- // Unknown error policy is used! Falling back to PassZeroPolicy
- case QSerialPort::PassZeroPolicy:
- *data = '\0'; //replace received character by zero
- break;
- case QSerialPort::IgnorePolicy:
- break; //ignore error and pass received character
- }
- }
- ++data;
- ++ret;
- }
- return ret;
-}
-
typedef QMap<qint32, qint32> BaudRateMap;
// The OS specific defines can be found in termios.h
diff --git a/src/serialport/qserialport_win.cpp b/src/serialport/qserialport_win.cpp
index a9687a2..39d7e33 100644
--- a/src/serialport/qserialport_win.cpp
+++ b/src/serialport/qserialport_win.cpp
@@ -78,7 +78,7 @@ QT_BEGIN_NAMESPACE
bool QSerialPortPrivate::open(QIODevice::OpenMode mode)
{
DWORD desiredAccess = 0;
- originalEventMask = EV_ERR;
+ originalEventMask = 0;
if (mode & QIODevice::ReadOnly) {
desiredAccess |= GENERIC_READ;
@@ -117,13 +117,12 @@ void QSerialPortPrivate::close()
startAsyncWriteTimer = Q_NULLPTR;
}
+ communicationStarted = false;
readStarted = false;
writeStarted = false;
writeBuffer.clear();
actualBytesToWrite = 0;
- parityErrorOccurred = false;
-
if (settingsRestoredOnClose) {
if (!::SetCommState(handle, &restoredDcb))
setError(getSystemError());
@@ -180,8 +179,12 @@ bool QSerialPortPrivate::setDataTerminalReady(bool set)
return false;
}
- currentDcb.fDtrControl = set ? DTR_CONTROL_ENABLE : DTR_CONTROL_DISABLE;
- return true;
+ DCB dcb;
+ if (!getDcb(&dcb))
+ return false;
+
+ dcb.fDtrControl = set ? DTR_CONTROL_ENABLE : DTR_CONTROL_DISABLE;
+ return setDcb(&dcb);
}
bool QSerialPortPrivate::setRequestToSend(bool set)
@@ -312,98 +315,113 @@ bool QSerialPortPrivate::setBaudRate(qint32 baudRate, QSerialPort::Directions di
setError(QSerialPortErrorInfo(QSerialPort::UnsupportedOperationError, QSerialPort::tr("Custom baud rate direction is unsupported")));
return false;
}
- currentDcb.BaudRate = baudRate;
- return updateDcb();
+
+ DCB dcb;
+ if (!getDcb(&dcb))
+ return false;
+
+ dcb.BaudRate = baudRate;
+ return setDcb(&dcb);
}
bool QSerialPortPrivate::setDataBits(QSerialPort::DataBits dataBits)
{
- currentDcb.ByteSize = dataBits;
- return updateDcb();
+ DCB dcb;
+ if (!getDcb(&dcb))
+ return false;
+
+ dcb.ByteSize = dataBits;
+ return setDcb(&dcb);
}
bool QSerialPortPrivate::setParity(QSerialPort::Parity parity)
{
- currentDcb.fParity = TRUE;
+ DCB dcb;
+ if (!getDcb(&dcb))
+ return false;
+
+ dcb.fParity = TRUE;
switch (parity) {
case QSerialPort::NoParity:
- currentDcb.Parity = NOPARITY;
- currentDcb.fParity = FALSE;
+ dcb.Parity = NOPARITY;
+ dcb.fParity = FALSE;
break;
case QSerialPort::OddParity:
- currentDcb.Parity = ODDPARITY;
+ dcb.Parity = ODDPARITY;
break;
case QSerialPort::EvenParity:
- currentDcb.Parity = EVENPARITY;
+ dcb.Parity = EVENPARITY;
break;
case QSerialPort::MarkParity:
- currentDcb.Parity = MARKPARITY;
+ dcb.Parity = MARKPARITY;
break;
case QSerialPort::SpaceParity:
- currentDcb.Parity = SPACEPARITY;
+ dcb.Parity = SPACEPARITY;
break;
default:
- currentDcb.Parity = NOPARITY;
- currentDcb.fParity = FALSE;
+ dcb.Parity = NOPARITY;
+ dcb.fParity = FALSE;
break;
}
- return updateDcb();
+ return setDcb(&dcb);
}
bool QSerialPortPrivate::setStopBits(QSerialPort::StopBits stopBits)
{
+ DCB dcb;
+ if (!getDcb(&dcb))
+ return false;
+
switch (stopBits) {
case QSerialPort::OneStop:
- currentDcb.StopBits = ONESTOPBIT;
+ dcb.StopBits = ONESTOPBIT;
break;
case QSerialPort::OneAndHalfStop:
- currentDcb.StopBits = ONE5STOPBITS;
+ dcb.StopBits = ONE5STOPBITS;
break;
case QSerialPort::TwoStop:
- currentDcb.StopBits = TWOSTOPBITS;
+ dcb.StopBits = TWOSTOPBITS;
break;
default:
- currentDcb.StopBits = ONESTOPBIT;
+ dcb.StopBits = ONESTOPBIT;
break;
}
- return updateDcb();
+ return setDcb(&dcb);
}
bool QSerialPortPrivate::setFlowControl(QSerialPort::FlowControl flowControl)
{
- currentDcb.fInX = FALSE;
- currentDcb.fOutX = FALSE;
- currentDcb.fOutxCtsFlow = FALSE;
- currentDcb.fRtsControl = RTS_CONTROL_DISABLE;
+ DCB dcb;
+ if (!getDcb(&dcb))
+ return false;
+
+ dcb.fInX = FALSE;
+ dcb.fOutX = FALSE;
+ dcb.fOutxCtsFlow = FALSE;
+ dcb.fRtsControl = RTS_CONTROL_DISABLE;
switch (flowControl) {
case QSerialPort::NoFlowControl:
break;
case QSerialPort::SoftwareControl:
- currentDcb.fInX = TRUE;
- currentDcb.fOutX = TRUE;
+ dcb.fInX = TRUE;
+ dcb.fOutX = TRUE;
break;
case QSerialPort::HardwareControl:
- currentDcb.fOutxCtsFlow = TRUE;
- currentDcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
+ dcb.fOutxCtsFlow = TRUE;
+ dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
break;
default:
break;
}
- return updateDcb();
-}
-
-bool QSerialPortPrivate::setDataErrorPolicy(QSerialPort::DataErrorPolicy policy)
-{
- policy = policy;
- return true;
+ return setDcb(&dcb);
}
bool QSerialPortPrivate::completeAsyncCommunication(qint64 bytesTransferred)
{
+ communicationStarted = false;
+
if (bytesTransferred == qint64(-1))
return false;
- if (EV_ERR & triggeredEventMask)
- handleLineStatusErrors();
return startAsyncRead();
}
@@ -422,12 +440,12 @@ bool QSerialPortPrivate::completeAsyncRead(qint64 bytesTransferred)
readStarted = false;
bool result = true;
- if ((bytesTransferred == ReadChunkSize) && (policy == QSerialPort::IgnorePolicy))
+ if (bytesTransferred == ReadChunkSize)
result = startAsyncRead();
else if (readBufferMaxSize == 0 || readBufferMaxSize > buffer.size())
result = startAsyncCommunication();
- if ((bytesTransferred > 0) && !emulateErrorPolicy())
+ if (bytesTransferred > 0)
emitReadyRead();
return result;
@@ -453,6 +471,9 @@ bool QSerialPortPrivate::completeAsyncWrite(qint64 bytesTransferred)
bool QSerialPortPrivate::startAsyncCommunication()
{
+ if (communicationStarted)
+ return true;
+
::ZeroMemory(&communicationOverlapped, sizeof(communicationOverlapped));
if (!::WaitCommEvent(handle, &triggeredEventMask, &communicationOverlapped)) {
QSerialPortErrorInfo error = getSystemError();
@@ -463,6 +484,7 @@ bool QSerialPortPrivate::startAsyncCommunication()
return false;
}
}
+ communicationStarted = true;
return true;
}
@@ -471,7 +493,7 @@ bool QSerialPortPrivate::startAsyncRead()
if (readStarted)
return true;
- DWORD bytesToRead = policy == QSerialPort::IgnorePolicy ? ReadChunkSize : 1;
+ DWORD bytesToRead = ReadChunkSize;
if (readBufferMaxSize && bytesToRead > (readBufferMaxSize - buffer.size())) {
bytesToRead = readBufferMaxSize - buffer.size();
@@ -544,34 +566,6 @@ void QSerialPortPrivate::_q_notified(DWORD numberOfBytes, DWORD errorCode, OVERL
Q_ASSERT(!"Unknown OVERLAPPED activated");
}
-bool QSerialPortPrivate::emulateErrorPolicy()
-{
- if (!parityErrorOccurred)
- return false;
-
- parityErrorOccurred = false;
-
- switch (policy) {
- case QSerialPort::SkipPolicy:
- buffer.getChar();
- break;
- case QSerialPort::PassZeroPolicy:
- buffer.getChar();
- buffer.ungetChar('\0');
- emitReadyRead();
- break;
- case QSerialPort::IgnorePolicy:
- return false;
- case QSerialPort::StopReceivingPolicy:
- emitReadyRead();
- break;
- default:
- return false;
- }
-
- return true;
-}
-
void QSerialPortPrivate::emitReadyRead()
{
Q_Q(QSerialPort);
@@ -589,7 +583,7 @@ qint64 QSerialPortPrivate::writeData(const char *data, qint64 maxSize)
if (!writeBuffer.isEmpty() && !writeStarted) {
if (!startAsyncWriteTimer) {
startAsyncWriteTimer = new QTimer(q);
- q->connect(startAsyncWriteTimer, SIGNAL(timeout()), q, SLOT(_q_startAsyncWrite()));
+ QObjectPrivate::connect(startAsyncWriteTimer, &QTimer::timeout, this, &QSerialPortPrivate::_q_startAsyncWrite);
startAsyncWriteTimer->setSingleShot(true);
}
startAsyncWriteTimer->start(0);
@@ -597,26 +591,6 @@ qint64 QSerialPortPrivate::writeData(const char *data, qint64 maxSize)
return maxSize;
}
-void QSerialPortPrivate::handleLineStatusErrors()
-{
- DWORD errors = 0;
- if (!::ClearCommError(handle, &errors, Q_NULLPTR)) {
- setError(getSystemError());
- return;
- }
-
- if (errors & CE_FRAME) {
- setError(QSerialPortErrorInfo(QSerialPort::FramingError, QSerialPort::tr("Framing error detected while reading")));
- } else if (errors & CE_RXPARITY) {
- setError(QSerialPortErrorInfo(QSerialPort::FramingError, QSerialPort::tr("ParityError error detected while reading")));
- parityErrorOccurred = true;
- } else if (errors & CE_BREAK) {
- setError(QSerialPortErrorInfo(QSerialPort::BreakConditionError, QSerialPort::tr("Break condition detected while reading")));
- } else {
- setError(QSerialPortErrorInfo(QSerialPort::UnknownError, QSerialPort::tr("Unknown streaming error")));
- }
-}
-
OVERLAPPED *QSerialPortPrivate::waitForNotified(int msecs)
{
OVERLAPPED *overlapped = notifier->waitForAnyNotified(msecs);
@@ -631,28 +605,25 @@ inline bool QSerialPortPrivate::initialize()
{
Q_Q(QSerialPort);
- ::ZeroMemory(&restoredDcb, sizeof(restoredDcb));
- restoredDcb.DCBlength = sizeof(restoredDcb);
-
- if (!::GetCommState(handle, &restoredDcb)) {
- setError(getSystemError());
+ DCB dcb;
+ if (!getDcb(&dcb))
return false;
- }
- currentDcb = restoredDcb;
- currentDcb.fBinary = TRUE;
- currentDcb.fInX = FALSE;
- currentDcb.fOutX = FALSE;
- currentDcb.fAbortOnError = FALSE;
- currentDcb.fNull = FALSE;
- currentDcb.fErrorChar = FALSE;
+ restoredDcb = dcb;
- if (currentDcb.fDtrControl == DTR_CONTROL_HANDSHAKE)
- currentDcb.fDtrControl = DTR_CONTROL_DISABLE;
+ dcb.fBinary = TRUE;
+ dcb.fInX = FALSE;
+ dcb.fOutX = FALSE;
+ dcb.fAbortOnError = FALSE;
+ dcb.fNull = FALSE;
+ dcb.fErrorChar = FALSE;
- currentDcb.BaudRate = inputBaudRate;
+ if (dcb.fDtrControl == DTR_CONTROL_HANDSHAKE)
+ dcb.fDtrControl = DTR_CONTROL_DISABLE;
- if (!updateDcb())
+ dcb.BaudRate = inputBaudRate;
+
+ if (!setDcb(&dcb))
return false;
if (!::GetCommTimeouts(handle, &restoredCommTimeouts)) {
@@ -672,20 +643,32 @@ inline bool QSerialPortPrivate::initialize()
}
notifier = new QWinOverlappedIoNotifier(q);
- q->connect(notifier, SIGNAL(notified(quint32, quint32, OVERLAPPED*)),
- q, SLOT(_q_notified(quint32, quint32, OVERLAPPED*)));
+ QObjectPrivate::connect(notifier, &QWinOverlappedIoNotifier::notified,
+ this, &QSerialPortPrivate::_q_notified);
notifier->setHandle(handle);
notifier->setEnabled(true);
- if (!startAsyncCommunication())
+ if ((originalEventMask & EV_RXCHAR) && !startAsyncCommunication())
return false;
return true;
}
-bool QSerialPortPrivate::updateDcb()
+bool QSerialPortPrivate::setDcb(DCB *dcb)
{
- if (!::SetCommState(handle, &currentDcb)) {
+ if (!::SetCommState(handle, dcb)) {
+ setError(getSystemError());
+ return false;
+ }
+ return true;
+}
+
+bool QSerialPortPrivate::getDcb(DCB *dcb)
+{
+ ::ZeroMemory(dcb, sizeof(DCB));
+ dcb->DCBlength = sizeof(DCB);
+
+ if (!::GetCommState(handle, dcb)) {
setError(getSystemError());
return false;
}
@@ -722,6 +705,9 @@ QSerialPortErrorInfo QSerialPortPrivate::getSystemError(int systemErrorCode) con
case ERROR_FILE_NOT_FOUND:
error.errorCode = QSerialPort::DeviceNotFoundError;
break;
+ case ERROR_PATH_NOT_FOUND:
+ error.errorCode = QSerialPort::DeviceNotFoundError;
+ break;
case ERROR_INVALID_NAME:
error.errorCode = QSerialPort::DeviceNotFoundError;
break;
diff --git a/src/serialport/qserialport_wince.cpp b/src/serialport/qserialport_wince.cpp
index 88872ad..18dd15d 100644
--- a/src/serialport/qserialport_wince.cpp
+++ b/src/serialport/qserialport_wince.cpp
@@ -84,7 +84,7 @@ signals:
public:
CommEventNotifier(DWORD mask, QSerialPortPrivate *d, QObject *parent)
: QThread(parent), dptr(d) {
- connect(this, SIGNAL(eventMask(quint32)), this, SLOT(processNotification(quint32)));
+ connect(this, &CommEventNotifier::eventMask, this, &CommEventNotifier::processNotification);
::SetCommMask(dptr->handle, mask);
}
@@ -119,8 +119,6 @@ private slots:
error = true;
}
- if (error || (EV_ERR & eventMask))
- dptr->processIoErrors(error);
if (EV_RXCHAR & eventMask)
dptr->notifyRead();
if (EV_TXEMPTY & eventMask)
@@ -156,7 +154,7 @@ public:
protected:
void run() {
QTimer timer;
- QObject::connect(&timer, SIGNAL(timeout()), this, SLOT(processTimeout()), Qt::DirectConnection);
+ QObject::connect(&timer, &QTimer::timeout, this, &WaitCommEventBreaker::processTimeout, Qt::DirectConnection);
timer.start(timeout);
exec();
worked = true;
@@ -179,7 +177,7 @@ private:
bool QSerialPortPrivate::open(QIODevice::OpenMode mode)
{
DWORD desiredAccess = 0;
- DWORD eventMask = EV_ERR;
+ DWORD eventMask = 0;
if (mode & QIODevice::ReadOnly) {
desiredAccess |= GENERIC_READ;
@@ -463,17 +461,11 @@ bool QSerialPortPrivate::setFlowControl(QSerialPort::FlowControl flowControl)
return updateDcb();
}
-bool QSerialPortPrivate::setDataErrorPolicy(QSerialPort::DataErrorPolicy policy)
-{
- policy = policy;
- return true;
-}
-
bool QSerialPortPrivate::notifyRead()
{
Q_Q(QSerialPort);
- DWORD bytesToRead = (policy == QSerialPort::IgnorePolicy) ? ReadChunkSize : 1;
+ DWORD bytesToRead = ReadChunkSize;
if (readBufferMaxSize && bytesToRead > (readBufferMaxSize - buffer.size())) {
bytesToRead = readBufferMaxSize - buffer.size();
@@ -491,33 +483,12 @@ bool QSerialPortPrivate::notifyRead()
if (!sucessResult) {
buffer.chop(bytesToRead);
- setError(QSerialPortErrorInfo(QSerialPort::ReadError, QSerialPort::tr("Error reading from device")));
+ setError(QSerialPortErrorInfo(QSerialPort::ReadError));
return false;
}
buffer.chop(bytesToRead - qMax(readBytes, DWORD(0)));
- // Process emulate policy.
- if ((policy != QSerialPort::IgnorePolicy) && parityErrorOccurred) {
-
- parityErrorOccurred = false;
-
- switch (policy) {
- case QSerialPort::SkipPolicy:
- buffer.getChar();
- return true;
- case QSerialPort::PassZeroPolicy:
- buffer.getChar();
- buffer.ungetChar('\0');
- break;
- case QSerialPort::StopReceivingPolicy:
- // FIXME: Maybe need disable read notifier?
- break;
- default:
- break;
- }
- }
-
if (readBytes > 0)
emit q->readyRead();
@@ -534,7 +505,7 @@ bool QSerialPortPrivate::notifyWrite()
DWORD bytesWritten = 0;
if (!::WriteFile(handle, ptr, nextSize, &bytesWritten, Q_NULLPTR)) {
- setError(QSerialPortErrorInfo(QSerialPort::WriteError, QSerialPort::tr("Error writing to device")));
+ setError(QSerialPortErrorInfo(QSerialPort::WriteError));
return false;
}
@@ -554,31 +525,6 @@ qint64 QSerialPortPrivate::writeData(const char *data, qint64 maxSize)
return maxSize;
}
-void QSerialPortPrivate::processIoErrors(bool hasError)
-{
- if (hasError) {
- setError(QSerialPortErrorInfo(QSerialPort::ResourceError, QSerialPort::tr("Device disappeared from the system")));
- return;
- }
-
- DWORD errors = 0;
- if (!::ClearCommError(handle, &errors, Q_NULLPTR)) {
- setError(getSystemError());
- return;
- }
-
- if (errors & CE_FRAME) {
- setError(QSerialPortErrorInfo(QSerialPort::FramingError, QSerialPort::tr("Framing error detected while reading")));
- } else if (errors & CE_RXPARITY) {
- setError(QSerialPortErrorInfo(QSerialPort::FramingError, QSerialPort::tr("ParityError error detected while reading")));
- parityErrorOccurred = true;
- } else if (errors & CE_BREAK) {
- setError(QSerialPortErrorInfo(QSerialPort::BreakConditionError, QSerialPort::tr("Break condition detected while reading")));
- } else {
- setError(QSerialPortErrorInfo(QSerialPort::UnknownError, QSerialPort::tr("Unknown streaming error")));
- }
-}
-
inline bool QSerialPortPrivate::initialize(DWORD eventMask)
{
Q_Q(QSerialPort);
@@ -670,6 +616,9 @@ QSerialPortErrorInfo QSerialPortPrivate::getSystemError(int systemErrorCode) con
case ERROR_FILE_NOT_FOUND:
error.errorCode = QSerialPort::DeviceNotFoundError;
break;
+ case ERROR_PATH_NOT_FOUND:
+ error.errorCode = QSerialPort::DeviceNotFoundError;
+ break;
case ERROR_INVALID_NAME:
error.errorCode = QSerialPort::DeviceNotFoundError;
break;
@@ -708,7 +657,7 @@ bool QSerialPortPrivate::waitForReadOrWrite(bool *selectForRead, bool *selectFor
breaker.stop();
if (breaker.isWorked()) {
- setError(QSerialPortErrorInfo(QSerialPort::TimeoutError, QSerialPort::tr("Operation timed out")));
+ setError(QSerialPortErrorInfo(QSerialPort::TimeoutError));
} else {
if (checkRead) {
Q_ASSERT(selectForRead);
diff --git a/src/serialport/qserialportinfo.h b/src/serialport/qserialportinfo.h
index 9f0352b..2b757f9 100644
--- a/src/serialport/qserialportinfo.h
+++ b/src/serialport/qserialportinfo.h
@@ -84,6 +84,9 @@ private:
QSerialPortInfo(const QSerialPortInfoPrivate &dd);
friend QList<QSerialPortInfo> availablePortsByUdev(bool &ok);
friend QList<QSerialPortInfo> availablePortsBySysfs(bool &ok);
+#ifdef Q_OS_FREEBSD
+ friend QList<QSerialPortInfo> availablePortsBySysctl(bool &ok);
+#endif
friend QList<QSerialPortInfo> availablePortsByFiltersOfDevices(bool &ok);
QScopedPointer<QSerialPortInfoPrivate, QSerialPortInfoPrivateDeleter> d_ptr;
};
diff --git a/src/serialport/qserialportinfo_unix.cpp b/src/serialport/qserialportinfo_unix.cpp
index 0fc5046..f52516f 100644
--- a/src/serialport/qserialportinfo_unix.cpp
+++ b/src/serialport/qserialportinfo_unix.cpp
@@ -42,12 +42,21 @@
#include <QtCore/qdir.h>
#include <QtCore/qscopedpointer.h>
+#ifdef Q_OS_FREEBSD
+#include <QtCore/qdatastream.h>
+#include <QtCore/qvector.h>
+#endif
+
#include <private/qcore_unix_p.h>
#include <errno.h>
#include <sys/types.h> // kill
#include <signal.h> // kill
+#ifdef Q_OS_FREEBSD
+#include <sys/sysctl.h> // sysctl, sysctlnametomib
+#endif
+
#include "qtudev_p.h"
QT_BEGIN_NAMESPACE
@@ -66,7 +75,8 @@ static QStringList filteredDeviceFilePaths()
<< QStringLiteral("ttymxc*") // Motorola IMX serial ports (i.e. Freescale i.MX).
<< QStringLiteral("ttyAMA*") // AMBA serial device for embedded platform on ARM (i.e. Raspberry Pi).
<< QStringLiteral("rfcomm*") // Bluetooth serial device.
- << QStringLiteral("ircomm*"); // IrDA serial device.
+ << QStringLiteral("ircomm*") // IrDA serial device.
+ << QStringLiteral("tnt*"); // Virtual tty0tty serial device.
#elif defined(Q_OS_FREEBSD)
<< QStringLiteral("cu*");
#elif defined(Q_OS_QNX)
@@ -87,8 +97,8 @@ static QStringList filteredDeviceFilePaths()
#ifdef Q_OS_FREEBSD
// it is a quick workaround to skip the non-serial devices
- if (deviceFilePaths.endsWith(QLatin1String(".init"))
- || deviceFilePaths.endsWith(QLatin1String(".lock"))) {
+ if (deviceAbsoluteFilePath.endsWith(QLatin1String(".init"))
+ || deviceAbsoluteFilePath.endsWith(QLatin1String(".lock"))) {
continue;
}
#endif
@@ -141,6 +151,280 @@ static bool isValidSerial8250(const QString &systemLocation)
return false;
}
+#ifdef Q_OS_FREEBSD
+
+static QString deviceProperty(const QString &pnpinfo, const QByteArray &pattern)
+{
+ const int firstbound = pnpinfo.indexOf(QLatin1String(pattern));
+ if (firstbound == -1)
+ return QString();
+ const int lastbound = pnpinfo.indexOf(QLatin1Char(' '), firstbound);
+ return pnpinfo.mid(firstbound + pattern.size(), lastbound - firstbound - pattern.size());
+}
+
+static QString deviceName(const QString &pnpinfo)
+{
+ return deviceProperty(pnpinfo, "ttyname=");
+}
+
+static QString deviceCount(const QString &pnpinfo)
+{
+ return deviceProperty(pnpinfo, "ttyports=");
+}
+
+static quint16 deviceProductIdentifier(const QString &pnpinfo, bool &hasIdentifier)
+{
+ QString result = deviceProperty(pnpinfo, "product=");
+ return result.toInt(&hasIdentifier, 16);
+}
+
+static quint16 deviceVendorIdentifier(const QString &pnpinfo, bool &hasIdentifier)
+{
+ QString result = deviceProperty(pnpinfo, "vendor=");
+ return result.toInt(&hasIdentifier, 16);
+}
+
+static QString deviceSerialNumber(const QString &pnpinfo)
+{
+ QString serialNumber = deviceProperty(pnpinfo, "sernum=");
+ serialNumber.remove(QLatin1Char('"'));
+ return serialNumber;
+}
+
+// A 'desc' string contains the both description and manufacturer
+// properties, which are not possible to extract from the source
+// string. Besides, this string can contains an other information,
+// which should be excluded from the result.
+static QString deviceDescriptionAndManufacturer(const QString &desc)
+{
+ const int classindex = desc.indexOf(QLatin1String(", class "));
+ if (classindex == -1)
+ return desc;
+ return desc.mid(0, classindex);
+}
+
+struct NodeInfo
+{
+ QString name;
+ QString value;
+};
+
+static QVector<int> mibFromName(const QString &name)
+{
+ size_t mibsize = 0;
+ if (::sysctlnametomib(name.toLocal8Bit().constData(), Q_NULLPTR, &mibsize) < 0
+ || mibsize == 0) {
+ return QVector<int>();
+ }
+ QVector<int> mib(mibsize);
+ if (::sysctlnametomib(name.toLocal8Bit().constData(), &mib[0], &mibsize) < 0)
+ return QVector<int>();
+
+ return mib;
+}
+
+static QVector<int> nextOid(const QVector<int> &previousOid)
+{
+ QVector<int> mib;
+ mib.append(0); // Magic undocumented code (CTL_UNSPEC ?)
+ mib.append(2); // Magic undocumented code
+ foreach (int code, previousOid)
+ mib.append(code);
+
+ size_t requiredLength = 0;
+ if (::sysctl(&mib[0], mib.count(), Q_NULLPTR, &requiredLength, Q_NULLPTR, 0) < 0)
+ return QVector<int>();
+ const size_t oidLength = requiredLength / sizeof(int);
+ QVector<int> oid(oidLength, 0);
+ if (::sysctl(&mib[0], mib.count(), &oid[0], &requiredLength, Q_NULLPTR, 0) < 0)
+ return QVector<int>();
+
+ if (previousOid.first() != oid.first())
+ return QVector<int>();
+
+ return oid;
+}
+
+static NodeInfo nodeForOid(const QVector<int> &oid)
+{
+ QVector<int> mib;
+ mib.append(0); // Magic undocumented code (CTL_UNSPEC ?)
+ mib.append(1); // Magic undocumented code
+ foreach (int code, oid)
+ mib.append(code);
+
+ // query node name
+ size_t requiredLength = 0;
+ if (::sysctl(&mib[0], mib.count(), Q_NULLPTR, &requiredLength, Q_NULLPTR, 0) < 0)
+ return NodeInfo();
+ QByteArray name(requiredLength, 0);
+ if (::sysctl(&mib[0], mib.count(), name.data(), &requiredLength, Q_NULLPTR, 0) < 0)
+ return NodeInfo();
+
+ // query node value
+ requiredLength = 0;
+ if (::sysctl(&oid[0], oid.count(), Q_NULLPTR, &requiredLength, Q_NULLPTR, 0) < 0)
+ return NodeInfo();
+ QByteArray value(requiredLength, 0);
+ if (::sysctl(&oid[0], oid.count(), value.data(), &requiredLength, Q_NULLPTR, 0) < 0)
+ return NodeInfo();
+
+ // query value format
+ mib[1] = 4; // Magic undocumented code
+ requiredLength = 0;
+ if (::sysctl(&mib[0], mib.count(), Q_NULLPTR, &requiredLength, Q_NULLPTR, 0) < 0)
+ return NodeInfo();
+ QByteArray buf(requiredLength, 0);
+ if (::sysctl(&mib[0], mib.count(), buf.data(), &requiredLength, Q_NULLPTR, 0) < 0)
+ return NodeInfo();
+
+ QDataStream in(buf);
+ in.setByteOrder(QDataStream::LittleEndian);
+ quint32 kind = 0;
+ qint8 format = 0;
+ in >> kind >> format;
+
+ NodeInfo result;
+
+ // we need only the string-type value
+ if (format == 'A') {
+ result.name = QString::fromLocal8Bit(name.constData());
+ result.value = QString::fromLocal8Bit(value.constData());
+ }
+
+ return result;
+}
+
+static QList<NodeInfo> enumerateDesiredNodes(const QVector<int> &mib)
+{
+ QList<NodeInfo> nodes;
+
+ QVector<int> oid = mib;
+
+ forever {
+ const QVector<int> nextoid = nextOid(oid);
+ if (nextoid.isEmpty())
+ break;
+
+ const NodeInfo node = nodeForOid(nextoid);
+ if (!node.name.isEmpty()) {
+ if (node.name.endsWith("\%desc")
+ || node.name.endsWith("\%pnpinfo")) {
+ nodes.append(node);
+ }
+ }
+
+ oid = nextoid;
+ }
+
+ return nodes;
+}
+
+QList<QSerialPortInfo> availablePortsBySysctl(bool &ok)
+{
+ const QVector<int> mib = mibFromName(QLatin1String("dev"));
+ if (mib.isEmpty()) {
+ ok = false;
+ return QList<QSerialPortInfo>();
+ }
+
+ const QList<NodeInfo> nodes = enumerateDesiredNodes(mib);
+ if (nodes.isEmpty()) {
+ ok = false;
+ return QList<QSerialPortInfo>();
+ }
+
+ QDir deviceDir(QLatin1String("/dev"));
+ if (!(deviceDir.exists() && deviceDir.isReadable())) {
+ ok = false;
+ return QList<QSerialPortInfo>();
+ }
+
+ deviceDir.setNameFilters(QStringList() << QLatin1String("cua*"));
+ deviceDir.setFilter(QDir::Files | QDir::System | QDir::NoSymLinks);
+
+ QList<QSerialPortInfo> serialPortInfoList;
+
+ foreach (const QString &portName, deviceDir.entryList()) {
+ if (portName.endsWith(QLatin1String(".init"))
+ || portName.endsWith(QLatin1String(".lock"))) {
+ continue;
+ }
+
+ QSerialPortInfoPrivate priv;
+ priv.portName = portName;
+ priv.device = QSerialPortInfoPrivate::portNameToSystemLocation(portName);
+
+ foreach (const NodeInfo &node, nodes) {
+ const int pnpinfoindex = node.name.indexOf(QLatin1String("\%pnpinfo"));
+ if (pnpinfoindex == -1)
+ continue;
+
+ if (node.value.isEmpty())
+ continue;
+
+ QString ttyname = deviceName(node.value);
+ if (ttyname.isEmpty())
+ continue;
+
+ const QString ttyportscount = deviceCount(node.value);
+ if (ttyportscount.isEmpty())
+ continue;
+
+ const int count = ttyportscount.toInt();
+ if (count == 0)
+ continue;
+ if (count > 1) {
+ bool matched = false;
+ for (int i = 0; i < count; ++i) {
+ const QString ends = QString(QLatin1String("%1.%2")).arg(ttyname).arg(i);
+ if (portName.endsWith(ends)) {
+ matched = true;
+ break;
+ }
+ }
+
+ if (!matched)
+ continue;
+ } else {
+ if (!portName.endsWith(ttyname))
+ continue;
+ }
+
+ priv.serialNumber = deviceSerialNumber(node.value);
+ priv.vendorIdentifier = deviceVendorIdentifier(node.value, priv.hasVendorIdentifier);
+ priv.productIdentifier = deviceProductIdentifier(node.value, priv.hasProductIdentifier);
+
+ const QString nodebase = node.name.mid(0, pnpinfoindex);
+ const QString descnode = QString(QLatin1String("%1\%desc")).arg(nodebase);
+
+ // search for description and manufacturer properties
+ foreach (const NodeInfo &node, nodes) {
+ if (node.name != descnode)
+ continue;
+
+ if (node.value.isEmpty())
+ continue;
+
+ // We can not separate the description and the manufacturer
+ // properties from the node value, so lets just duplicate it.
+ priv.description = deviceDescriptionAndManufacturer(node.value);
+ priv.manufacturer = priv.description;
+ break;
+ }
+
+ break;
+ }
+
+ serialPortInfoList.append(priv);
+ }
+
+ ok = true;
+ return serialPortInfoList;
+}
+
+#endif // Q_OS_FREEBSD
+
static bool isRfcommDevice(const QString &portName)
{
if (!portName.startsWith(QLatin1String("rfcomm")))
@@ -153,6 +437,15 @@ static bool isRfcommDevice(const QString &portName)
return true;
}
+// provided by the tty0tty driver
+static bool isVirtualNullModemDevice(const QString &portName)
+{
+ if (!portName.startsWith(QLatin1String("tnt")))
+ return false;
+
+ return true;
+}
+
static QString ueventProperty(const QDir &targetDir, const QByteArray &pattern)
{
QFile f(QFileInfo(targetDir, QStringLiteral("uevent")).absoluteFilePath());
@@ -247,8 +540,10 @@ QList<QSerialPortInfo> availablePortsBySysfs(bool &ok)
const QString driverName = deviceDriver(targetDir);
if (driverName.isEmpty()) {
- if (!isRfcommDevice(priv.portName))
+ if (!isRfcommDevice(priv.portName)
+ && !isVirtualNullModemDevice(priv.portName)) {
continue;
+ }
}
priv.device = QSerialPortInfoPrivate::portNameToSystemLocation(priv.portName);
@@ -417,8 +712,10 @@ QList<QSerialPortInfo> availablePortsByUdev(bool &ok)
priv.vendorIdentifier = deviceVendorIdentifier(dev.data(), priv.hasVendorIdentifier);
priv.productIdentifier = deviceProductIdentifier(dev.data(), priv.hasProductIdentifier);
} else {
- if (!isRfcommDevice(priv.portName))
+ if (!isRfcommDevice(priv.portName)
+ && !isVirtualNullModemDevice(priv.portName)) {
continue;
+ }
}
serialPortInfoList.append(priv);
@@ -438,6 +735,11 @@ QList<QSerialPortInfo> QSerialPortInfo::availablePorts()
serialPortInfoList = availablePortsBySysfs(ok);
#endif
+#ifdef Q_OS_FREEBSD
+ if (!ok)
+ serialPortInfoList = availablePortsBySysctl(ok);
+#endif
+
if (!ok)
serialPortInfoList = availablePortsByFiltersOfDevices(ok);
diff --git a/tests/auto/qserialport/tst_qserialport.cpp b/tests/auto/qserialport/tst_qserialport.cpp
index c5c9113..d50afe9 100644
--- a/tests/auto/qserialport/tst_qserialport.cpp
+++ b/tests/auto/qserialport/tst_qserialport.cpp
@@ -38,6 +38,11 @@
#include <QThread>
Q_DECLARE_METATYPE(QSerialPort::SerialPortError);
+Q_DECLARE_METATYPE(QSerialPort::BaudRate);
+Q_DECLARE_METATYPE(QSerialPort::DataBits);
+Q_DECLARE_METATYPE(QSerialPort::Parity);
+Q_DECLARE_METATYPE(QSerialPort::StopBits);
+Q_DECLARE_METATYPE(QSerialPort::FlowControl);
Q_DECLARE_METATYPE(QIODevice::OpenMode);
Q_DECLARE_METATYPE(QIODevice::OpenModeFlag);
Q_DECLARE_METATYPE(Qt::ConnectionType);
@@ -85,6 +90,17 @@ private slots:
void openNotExisting_data();
void openNotExisting();
+ void baudRate_data();
+ void baudRate();
+ void dataBits_data();
+ void dataBits();
+ void parity_data();
+ void parity();
+ void stopBits_data();
+ void stopBits();
+ void flowControl_data();
+ void flowControl();
+
void flush();
void doubleFlush();
@@ -104,21 +120,22 @@ private slots:
void asynchronousWriteByTimer_data();
void asynchronousWriteByTimer();
-#ifdef Q_OS_WIN
void readBufferOverflow();
void readAfterInputClear();
void synchronousReadWriteAfterAsynchronousReadWrite();
-#endif
void controlBreak();
+ void clearAfterOpen();
+
+ void readWriteWithDifferentBaudRate_data();
+ void readWriteWithDifferentBaudRate();
+
protected slots:
void handleBytesWrittenAndExitLoopSlot(qint64 bytesWritten);
void handleBytesWrittenAndExitLoopSlot2(qint64 bytesWritten);
private:
- void clearReceiver(const QString &customReceiverName = QString());
-
QString m_senderPortName;
QString m_receiverPortName;
QStringList m_availablePortNames;
@@ -137,24 +154,6 @@ tst_QSerialPort::tst_QSerialPort()
{
}
-// This method is a workaround for the "com0com" virtual serial port
-// driver or for the SOCAT utility. The problem is that the close/clear
-// methods have no effect on sender serial port. If any data didn't manage
-// to be transferred before closing, then this data will continue to be
-// transferred at next opening of sender port.
-// Thus, this behavior influences other tests and leads to the wrong results
-// (e.g. the receiver port on other test can receive some data which are
-// not expected). It is recommended to use this method for cleaning of
-// read FIFO of receiver for those tests in which reception of data is
-// required.
-void tst_QSerialPort::clearReceiver(const QString &customReceiverName)
-{
- QSerialPort receiver(customReceiverName.isEmpty()
- ? m_receiverPortName : customReceiverName);
- if (receiver.open(QIODevice::ReadOnly))
- enterLoopMsecs(100);
-}
-
void tst_QSerialPort::initTestCase()
{
m_senderPortName = QString::fromLocal8Bit(qgetenv("QTEST_SERIALPORT_SENDER"));
@@ -271,7 +270,7 @@ void tst_QSerialPort::openExisting()
foreach (const QString &serialPortName, m_availablePortNames) {
QSerialPort serialPort(serialPortName);
- QSignalSpy errorSpy(&serialPort, SIGNAL(error(QSerialPort::SerialPortError)));
+ QSignalSpy errorSpy(&serialPort, static_cast<void (QSerialPort::*)(QSerialPort::SerialPortError)>(&QSerialPort::error));
QVERIFY(errorSpy.isValid());
QCOMPARE(serialPort.portName(), serialPortName);
@@ -303,7 +302,7 @@ void tst_QSerialPort::openNotExisting()
QSerialPort serialPort(serialPortName);
- QSignalSpy errorSpy(&serialPort, SIGNAL(error(QSerialPort::SerialPortError)));
+ QSignalSpy errorSpy(&serialPort, static_cast<void (QSerialPort::*)(QSerialPort::SerialPortError)>(&QSerialPort::error));
QVERIFY(errorSpy.isValid());
QCOMPARE(serialPort.portName(), serialPortName);
@@ -315,6 +314,163 @@ void tst_QSerialPort::openNotExisting()
//QCOMPARE(qvariant_cast<QSerialPort::SerialPortError>(errorSpy.at(0).at(0)), errorCode);
}
+void tst_QSerialPort::baudRate_data()
+{
+ QTest::addColumn<qint32>("baudrate");
+ QTest::newRow("Baud1200") << static_cast<qint32>(QSerialPort::Baud1200);
+ QTest::newRow("Baud2400") << static_cast<qint32>(QSerialPort::Baud2400);
+ QTest::newRow("Baud4800") << static_cast<qint32>(QSerialPort::Baud4800);
+ QTest::newRow("Baud9600") << static_cast<qint32>(QSerialPort::Baud9600);
+ QTest::newRow("Baud19200") << static_cast<qint32>(QSerialPort::Baud19200);
+ QTest::newRow("Baud38400") << static_cast<qint32>(QSerialPort::Baud38400);
+ QTest::newRow("Baud57600") << static_cast<qint32>(QSerialPort::Baud57600);
+ QTest::newRow("Baud115200") << static_cast<qint32>(QSerialPort::Baud115200);
+
+ QTest::newRow("31250") << 31250; // custom baudrate (MIDI)
+}
+
+void tst_QSerialPort::baudRate()
+{
+ QFETCH(qint32, baudrate);
+
+ {
+ // setup before opening
+ QSerialPort serialPort(m_senderPortName);
+ QVERIFY(serialPort.setBaudRate(baudrate));
+ QCOMPARE(serialPort.baudRate(), baudrate);
+ QVERIFY(serialPort.open(QIODevice::ReadWrite));
+ }
+
+ {
+ // setup after opening
+ QSerialPort serialPort(m_senderPortName);
+ QVERIFY(serialPort.open(QIODevice::ReadWrite));
+ QVERIFY(serialPort.setBaudRate(baudrate));
+ QCOMPARE(serialPort.baudRate(), baudrate);
+ }
+}
+
+void tst_QSerialPort::dataBits_data()
+{
+ QTest::addColumn<QSerialPort::DataBits>("databits");
+ QTest::newRow("Data5") << QSerialPort::Data5;
+ QTest::newRow("Data6") << QSerialPort::Data6;
+ QTest::newRow("Data7") << QSerialPort::Data7;
+ QTest::newRow("Data8") << QSerialPort::Data8;
+}
+
+void tst_QSerialPort::dataBits()
+{
+ QFETCH(QSerialPort::DataBits, databits);
+
+ {
+ // setup before opening
+ QSerialPort serialPort(m_senderPortName);
+ QVERIFY(serialPort.setDataBits(databits));
+ QCOMPARE(serialPort.dataBits(), databits);
+ QVERIFY(serialPort.open(QIODevice::ReadWrite));
+ }
+
+ {
+ // setup after opening
+ QSerialPort serialPort(m_senderPortName);
+ QVERIFY(serialPort.open(QIODevice::ReadWrite));
+ QVERIFY(serialPort.setDataBits(databits));
+ QCOMPARE(serialPort.dataBits(), databits);
+ }
+}
+
+void tst_QSerialPort::parity_data()
+{
+ QTest::addColumn<QSerialPort::Parity>("parity");
+ QTest::newRow("NoParity") << QSerialPort::NoParity;
+ QTest::newRow("EvenParity") << QSerialPort::EvenParity;
+ QTest::newRow("OddParity") << QSerialPort::OddParity;
+ QTest::newRow("SpaceParity") << QSerialPort::SpaceParity;
+ QTest::newRow("MarkParity") << QSerialPort::MarkParity;
+}
+
+void tst_QSerialPort::parity()
+{
+ QFETCH(QSerialPort::Parity, parity);
+
+ {
+ // setup before opening
+ QSerialPort serialPort(m_senderPortName);
+ QVERIFY(serialPort.setParity(parity));
+ QCOMPARE(serialPort.parity(), parity);
+ QVERIFY(serialPort.open(QIODevice::ReadWrite));
+ }
+
+ {
+ // setup after opening
+ QSerialPort serialPort(m_senderPortName);
+ QVERIFY(serialPort.open(QIODevice::ReadWrite));
+ QVERIFY(serialPort.setParity(parity));
+ QCOMPARE(serialPort.parity(), parity);
+ }
+}
+
+void tst_QSerialPort::stopBits_data()
+{
+ QTest::addColumn<QSerialPort::StopBits>("stopbits");
+ QTest::newRow("OneStop") << QSerialPort::OneStop;
+#ifdef Q_OS_WIN
+ QTest::newRow("OneAndHalfStop") << QSerialPort::OneAndHalfStop;
+#endif
+ QTest::newRow("TwoStop") << QSerialPort::TwoStop;
+}
+
+void tst_QSerialPort::stopBits()
+{
+ QFETCH(QSerialPort::StopBits, stopbits);
+
+ {
+ // setup before opening
+ QSerialPort serialPort(m_senderPortName);
+ QVERIFY(serialPort.setStopBits(stopbits));
+ QCOMPARE(serialPort.stopBits(), stopbits);
+ QVERIFY(serialPort.open(QIODevice::ReadWrite));
+ }
+
+ {
+ // setup after opening
+ QSerialPort serialPort(m_senderPortName);
+ QVERIFY(serialPort.open(QIODevice::ReadWrite));
+ QVERIFY(serialPort.setStopBits(stopbits));
+ QCOMPARE(serialPort.stopBits(), stopbits);
+ }
+}
+
+void tst_QSerialPort::flowControl_data()
+{
+ QTest::addColumn<QSerialPort::FlowControl>("flowcontrol");
+ QTest::newRow("NoFlowControl") << QSerialPort::NoFlowControl;
+ QTest::newRow("HardwareControl") << QSerialPort::HardwareControl;
+ QTest::newRow("SoftwareControl") << QSerialPort::SoftwareControl;
+}
+
+void tst_QSerialPort::flowControl()
+{
+ QFETCH(QSerialPort::FlowControl, flowcontrol);
+
+ {
+ // setup before opening
+ QSerialPort serialPort(m_senderPortName);
+ QVERIFY(serialPort.setFlowControl(flowcontrol));
+ QCOMPARE(serialPort.flowControl(), flowcontrol);
+ QVERIFY(serialPort.open(QIODevice::ReadWrite));
+ }
+
+ {
+ // setup after opening
+ QSerialPort serialPort(m_senderPortName);
+ QVERIFY(serialPort.open(QIODevice::ReadWrite));
+ QVERIFY(serialPort.setFlowControl(flowcontrol));
+ QCOMPARE(serialPort.flowControl(), flowcontrol);
+ }
+}
+
void tst_QSerialPort::handleBytesWrittenAndExitLoopSlot(qint64 bytesWritten)
{
QCOMPARE(bytesWritten, qint64(alphabetArray.size() + newlineArray.size()));
@@ -332,8 +488,8 @@ void tst_QSerialPort::flush()
QVERIFY(dummySerialPort.open(QIODevice::ReadOnly));
QSerialPort serialPort(m_senderPortName);
- connect(&serialPort, SIGNAL(bytesWritten(qint64)), this, SLOT(handleBytesWrittenAndExitLoopSlot(qint64)));
- QSignalSpy bytesWrittenSpy(&serialPort, SIGNAL(bytesWritten(qint64)));
+ connect(&serialPort, &QSerialPort::bytesWritten, this, &tst_QSerialPort::handleBytesWrittenAndExitLoopSlot);
+ QSignalSpy bytesWrittenSpy(&serialPort, &QSerialPort::bytesWritten);
QVERIFY(serialPort.open(QIODevice::WriteOnly));
serialPort.write(alphabetArray + newlineArray);
@@ -367,8 +523,8 @@ void tst_QSerialPort::doubleFlush()
QVERIFY(dummySerialPort.open(QIODevice::ReadOnly));
QSerialPort serialPort(m_senderPortName);
- connect(&serialPort, SIGNAL(bytesWritten(qint64)), this, SLOT(handleBytesWrittenAndExitLoopSlot2(qint64)));
- QSignalSpy bytesWrittenSpy(&serialPort, SIGNAL(bytesWritten(qint64)));
+ connect(&serialPort, &QSerialPort::bytesWritten, this, &tst_QSerialPort::handleBytesWrittenAndExitLoopSlot2);
+ QSignalSpy bytesWrittenSpy(&serialPort, &QSerialPort::bytesWritten);
QVERIFY(serialPort.open(QIODevice::WriteOnly));
serialPort.write(alphabetArray);
@@ -401,12 +557,9 @@ void tst_QSerialPort::waitForBytesWritten()
void tst_QSerialPort::waitForReadyReadWithTimeout()
{
- clearReceiver();
-#ifdef Q_OS_WIN
// the dummy device on other side also has to be open
QSerialPort dummySerialPort(m_senderPortName);
QVERIFY(dummySerialPort.open(QIODevice::WriteOnly));
-#endif
QSerialPort receiverSerialPort(m_receiverPortName);
QVERIFY(receiverSerialPort.open(QIODevice::ReadOnly));
@@ -417,17 +570,13 @@ void tst_QSerialPort::waitForReadyReadWithTimeout()
void tst_QSerialPort::waitForReadyReadWithOneByte()
{
-#ifdef Q_OS_WIN
- clearReceiver();
-#endif
-
const qint64 oneByte = 1;
const int waitMsecs = 50;
QSerialPort senderSerialPort(m_senderPortName);
QVERIFY(senderSerialPort.open(QIODevice::WriteOnly));
QSerialPort receiverSerialPort(m_receiverPortName);
- QSignalSpy readyReadSpy(&receiverSerialPort, SIGNAL(readyRead()));
+ QSignalSpy readyReadSpy(&receiverSerialPort, &QSerialPort::readyRead);
QVERIFY(readyReadSpy.isValid());
QVERIFY(receiverSerialPort.open(QIODevice::ReadOnly));
QCOMPARE(senderSerialPort.write(alphabetArray.constData(), oneByte), oneByte);
@@ -440,16 +589,12 @@ void tst_QSerialPort::waitForReadyReadWithOneByte()
void tst_QSerialPort::waitForReadyReadWithAlphabet()
{
-#ifdef Q_OS_WIN
- clearReceiver();
-#endif
-
const int waitMsecs = 50;
QSerialPort senderSerialPort(m_senderPortName);
QVERIFY(senderSerialPort.open(QIODevice::WriteOnly));
QSerialPort receiverSerialPort(m_receiverPortName);
- QSignalSpy readyReadSpy(&receiverSerialPort, SIGNAL(readyRead()));
+ QSignalSpy readyReadSpy(&receiverSerialPort, &QSerialPort::readyRead);
QVERIFY(readyReadSpy.isValid());
QVERIFY(receiverSerialPort.open(QIODevice::ReadOnly));
QCOMPARE(senderSerialPort.write(alphabetArray), qint64(alphabetArray.size()));
@@ -465,11 +610,6 @@ void tst_QSerialPort::waitForReadyReadWithAlphabet()
void tst_QSerialPort::twoStageSynchronousLoopback()
{
-#ifdef Q_OS_WIN
- clearReceiver();
- clearReceiver(m_senderPortName);
-#endif
-
QSerialPort senderPort(m_senderPortName);
QVERIFY(senderPort.open(QSerialPort::ReadWrite));
@@ -508,10 +648,6 @@ void tst_QSerialPort::twoStageSynchronousLoopback()
void tst_QSerialPort::synchronousReadWrite()
{
-#ifdef Q_OS_WIN
- clearReceiver();
-#endif
-
QSerialPort senderPort(m_senderPortName);
QVERIFY(senderPort.open(QSerialPort::WriteOnly));
@@ -539,7 +675,7 @@ public:
explicit AsyncReader(QSerialPort &port, Qt::ConnectionType connectionType, int expectedBytesCount)
: serialPort(port), expectedBytesCount(expectedBytesCount)
{
- connect(&serialPort, SIGNAL(readyRead()), this, SLOT(receive()), connectionType);
+ connect(&serialPort, &QSerialPort::readyRead, this, &AsyncReader::receive, connectionType);
}
private slots:
@@ -565,7 +701,7 @@ public:
{
writeBuffer.setData(dataToWrite);
writeBuffer.open(QIODevice::ReadOnly);
- connect(&serialPort, SIGNAL(bytesWritten(qint64)), this, SLOT(send()), connectionType);
+ connect(&serialPort, &QSerialPort::bytesWritten, this, &AsyncWriterByBytesWritten::send, connectionType);
send();
}
@@ -595,10 +731,6 @@ void tst_QSerialPort::asynchronousWriteByBytesWritten_data()
void tst_QSerialPort::asynchronousWriteByBytesWritten()
{
-#ifdef Q_OS_WIN
- clearReceiver();
-#endif
-
QFETCH(Qt::ConnectionType, readConnectionType);
QFETCH(Qt::ConnectionType, writeConnectionType);
@@ -626,7 +758,7 @@ public:
{
writeBuffer.setData(dataToWrite);
writeBuffer.open(QIODevice::ReadOnly);
- connect(&timer, SIGNAL(timeout()), this, SLOT(send()), connectionType);
+ connect(&timer, &QTimer::timeout, this, &AsyncWriterByTimer::send, connectionType);
timer.start(0);
}
@@ -659,10 +791,6 @@ void tst_QSerialPort::asynchronousWriteByTimer_data()
void tst_QSerialPort::asynchronousWriteByTimer()
{
-#ifdef Q_OS_WIN
- clearReceiver();
-#endif
-
QFETCH(Qt::ConnectionType, readConnectionType);
QFETCH(Qt::ConnectionType, writeConnectionType);
@@ -680,11 +808,8 @@ void tst_QSerialPort::asynchronousWriteByTimer()
QCOMPARE(receiverPort.readAll(), alphabetArray);
}
-#ifdef Q_OS_WIN
void tst_QSerialPort::readBufferOverflow()
{
- clearReceiver();
-
QSerialPort senderPort(m_senderPortName);
QVERIFY(senderPort.open(QSerialPort::WriteOnly));
@@ -712,8 +837,6 @@ void tst_QSerialPort::readBufferOverflow()
void tst_QSerialPort::readAfterInputClear()
{
- clearReceiver();
-
QSerialPort senderPort(m_senderPortName);
QVERIFY(senderPort.open(QSerialPort::WriteOnly));
@@ -843,7 +966,7 @@ void tst_QSerialPort::synchronousReadWriteAfterAsynchronousReadWrite()
QMetaObject::invokeMethod(slave, "open", Qt::QueuedConnection);
- tst_QSerialPort::enterLoopMsecs(500);
+ tst_QSerialPort::enterLoopMsecs(2000);
thread.quit();
thread.wait();
@@ -851,8 +974,6 @@ void tst_QSerialPort::synchronousReadWriteAfterAsynchronousReadWrite()
QVERIFY2(!timeout(), "Timed out when testing of transactions.");
}
-#endif
-
class BreakReader : public QObject
{
Q_OBJECT
@@ -860,7 +981,7 @@ public:
explicit BreakReader(QSerialPort &port)
: serialPort(port)
{
- connect(&serialPort, SIGNAL(readyRead()), this, SLOT(receive()));
+ connect(&serialPort, &QSerialPort::readyRead, this, &BreakReader::receive);
}
private slots:
@@ -875,15 +996,11 @@ private:
void tst_QSerialPort::controlBreak()
{
-#ifdef Q_OS_WIN
- clearReceiver();
-#endif
-
QSerialPort senderPort(m_senderPortName);
QVERIFY(senderPort.open(QSerialPort::WriteOnly));
QCOMPARE(senderPort.isBreakEnabled(), false);
- QSignalSpy breakSpy(&senderPort, SIGNAL(breakEnabledChanged(bool)));
+ QSignalSpy breakSpy(&senderPort, &QSerialPort::breakEnabledChanged);
QVERIFY(breakSpy.isValid());
QSerialPort receiverPort(m_receiverPortName);
@@ -910,5 +1027,88 @@ void tst_QSerialPort::controlBreak()
QCOMPARE(qvariant_cast<bool>(breakSpy.at(1).at(0)), false);
}
+void tst_QSerialPort::clearAfterOpen()
+{
+ QSerialPort senderPort(m_senderPortName);
+ QVERIFY(senderPort.open(QSerialPort::ReadWrite));
+ QCOMPARE(senderPort.error(), QSerialPort::NoError);
+ QVERIFY(senderPort.clear());
+ QCOMPARE(senderPort.error(), QSerialPort::NoError);
+}
+
+void tst_QSerialPort::readWriteWithDifferentBaudRate_data()
+{
+ QTest::addColumn<int>("senderBaudRate");
+ QTest::addColumn<int>("receiverBaudRate");
+ QTest::addColumn<bool>("expectedResult");
+
+ QTest::newRow("9600, 9600") << 9600 << 9600 << true;
+ QTest::newRow("115200, 115200") << 115200 << 115200 << true;
+ QTest::newRow("9600, 115200") << 9600 << 115200 << false;
+
+ QTest::newRow("31250, 31250") << 31250 << 31250 << true; // custom baudrate (MIDI)
+ QTest::newRow("31250, 115200") << 31250 << 115200 << false;
+
+#ifdef Q_OS_LINUX
+ QTest::newRow("14400, 14400") << 14400 << 14400 << true; // custom baudrate for Linux
+ QTest::newRow("14400, 115200") << 14400 << 115200 << false;
+#endif
+}
+
+void tst_QSerialPort::readWriteWithDifferentBaudRate()
+{
+ QFETCH(int, senderBaudRate);
+ QFETCH(int, receiverBaudRate);
+ QFETCH(bool, expectedResult);
+
+ {
+ // setup before opening
+ QSerialPort senderSerialPort(m_senderPortName);
+ QVERIFY(senderSerialPort.setBaudRate(senderBaudRate));
+ QCOMPARE(senderSerialPort.baudRate(), senderBaudRate);
+ QVERIFY(senderSerialPort.open(QSerialPort::ReadWrite));
+ QSerialPort receiverSerialPort(m_receiverPortName);
+ QVERIFY(receiverSerialPort.setBaudRate(receiverBaudRate));
+ QCOMPARE(receiverSerialPort.baudRate(), receiverBaudRate);
+ QVERIFY(receiverSerialPort.open(QSerialPort::ReadWrite));
+
+ QCOMPARE(senderSerialPort.write(alphabetArray), qint64(alphabetArray.size()));
+ QVERIFY(senderSerialPort.waitForBytesWritten(500));
+
+ do {
+ QVERIFY(receiverSerialPort.waitForReadyRead(500));
+ } while (receiverSerialPort.bytesAvailable() < alphabetArray.size());
+
+ if (expectedResult)
+ QVERIFY(receiverSerialPort.readAll() == alphabetArray);
+ else
+ QVERIFY(receiverSerialPort.readAll() != alphabetArray);
+ }
+
+ {
+ // setup after opening
+ QSerialPort senderSerialPort(m_senderPortName);
+ QVERIFY(senderSerialPort.open(QSerialPort::ReadWrite));
+ QVERIFY(senderSerialPort.setBaudRate(senderBaudRate));
+ QCOMPARE(senderSerialPort.baudRate(), senderBaudRate);
+ QSerialPort receiverSerialPort(m_receiverPortName);
+ QVERIFY(receiverSerialPort.open(QSerialPort::ReadWrite));
+ QVERIFY(receiverSerialPort.setBaudRate(receiverBaudRate));
+ QCOMPARE(receiverSerialPort.baudRate(), receiverBaudRate);
+
+ QCOMPARE(senderSerialPort.write(alphabetArray), qint64(alphabetArray.size()));
+ QVERIFY(senderSerialPort.waitForBytesWritten(500));
+
+ do {
+ QVERIFY(receiverSerialPort.waitForReadyRead(500));
+ } while (receiverSerialPort.bytesAvailable() < alphabetArray.size());
+
+ if (expectedResult)
+ QVERIFY(receiverSerialPort.readAll() == alphabetArray);
+ else
+ QVERIFY(receiverSerialPort.readAll() != alphabetArray);
+ }
+}
+
QTEST_MAIN(tst_QSerialPort)
#include "tst_qserialport.moc"