Compare commits

...

No commits in common. "develop" and "release" have entirely different histories.

280 changed files with 13 additions and 125675 deletions

29
.gitignore vendored
View File

@ -1,29 +0,0 @@
# Qt-es
*.pro.user
*.pro.user.*
*.qbs.user
*.qbs.user.*
*.qtc*
*build*
# Qt translate file
*.ts
# Qt QMake file
*.stash
*Makefile*
# Qt unit tests
target_wrapper.*
# QtCreator
*.autosave
# QtCreator Qml
*.qmlproject.user.*
# QtCreator CMake
CMakeLists.txt.user*
# QtCreator local machine specific files for imported projects
*creator.user*

Binary file not shown.

BIN
BatteryMonitor.exe Normal file

Binary file not shown.

View File

@ -1,79 +0,0 @@
QT += core gui charts
QT += serialport
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
CONFIG += c++17
# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
SOURCES += \
appproto.cpp \
appproto_english.cpp \
batt.cpp \
chartpaint.cpp \
custom/delegate.cpp \
dialoglogin.cpp \
library/libmodbus/src/modbus-data.c \
library/libmodbus/src/modbus-rtu.c \
library/libmodbus/src/modbus-tcp.c \
library/libmodbus/src/modbus.c \
main.cpp \
mainwindow.cpp \
modbusrtu.cpp \
proto/battery.pb.cc \
appserial.cpp \
proto/battery_english.pb.cc \
upgradeicon.cpp
HEADERS += \
appproto.h \
appproto_english.h \
batt.h \
chartpaint.h \
custom/delegate.h \
dialoglogin.h \
library/libmodbus/include/config.h \
library/libmodbus/include/modbus-private.h \
library/libmodbus/include/modbus-rtu-private.h \
library/libmodbus/include/modbus-rtu.h \
library/libmodbus/include/modbus-tcp-private.h \
library/libmodbus/include/modbus-tcp.h \
library/libmodbus/include/modbus-version.h \
library/libmodbus/include/modbus.h \
mainwindow.h \
modbusrtu.h \
proto/battery.pb.h \
appserial.h \
proto/battery_english.pb.h \
upgradeicon.h
FORMS += \
dialoglogin.ui \
mainwindow.ui
TRANSLATIONS += \
BatteryMonitor_CHN.ts \
BatteryMonitor_ENG.ts
INCLUDEPATH += \
library\libprotobuf\include \
library\libmodbus\include \
custom
LIBS += \
-L$$PWD\library\libprotobuf\lib -lprotobuf \
-lws2_32
# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
DISTFILES +=
RESOURCES += \
image.qrc \
language.qrc

BIN
D3Dcompiler_47.dll Normal file

Binary file not shown.

Binary file not shown.

Before

(image error) Size: 1.1 KiB

Binary file not shown.

Before

(image error) Size: 1.1 KiB

Binary file not shown.

Before

(image error) Size: 1.1 KiB

Binary file not shown.

Before

(image error) Size: 549 B

Binary file not shown.

Before

(image error) Size: 532 B

Binary file not shown.

Before

(image error) Size: 562 B

Binary file not shown.

Before

(image error) Size: 23 KiB

Binary file not shown.

Before

(image error) Size: 3.1 KiB

Binary file not shown.

Before

(image error) Size: 815 B

Binary file not shown.

Before

(image error) Size: 807 B

Binary file not shown.

Before

(image error) Size: 840 B

Binary file not shown.

Before

(image error) Size: 1.5 KiB

Binary file not shown.

Before

(image error) Size: 824 B

Binary file not shown.

Before

(image error) Size: 817 B

Binary file not shown.

Before

(image error) Size: 856 B

Binary file not shown.

Before

(image error) Size: 749 B

Binary file not shown.

Before

(image error) Size: 749 B

Binary file not shown.

Before

(image error) Size: 779 B

Binary file not shown.

Before

(image error) Size: 695 B

Binary file not shown.

Before

(image error) Size: 682 B

Binary file not shown.

Before

(image error) Size: 704 B

Binary file not shown.

Before

(image error) Size: 4.1 KiB

Binary file not shown.

Before

(image error) Size: 755 B

Binary file not shown.

Before

(image error) Size: 746 B

Binary file not shown.

Before

(image error) Size: 785 B

Binary file not shown.

Before

(image error) Size: 662 B

Binary file not shown.

Before

(image error) Size: 660 B

Binary file not shown.

Before

(image error) Size: 667 B

Binary file not shown.

Before

(image error) Size: 859 B

Binary file not shown.

Before

(image error) Size: 850 B

Binary file not shown.

Before

(image error) Size: 921 B

Binary file not shown.

Before

(image error) Size: 846 B

Binary file not shown.

Before

(image error) Size: 1.3 KiB

Binary file not shown.

Before

(image error) Size: 6.7 KiB

Binary file not shown.

Before

(image error) Size: 3.0 KiB

Binary file not shown.

Before

(image error) Size: 1.1 KiB

Binary file not shown.

Before

(image error) Size: 2.0 KiB

304
LICENSE
View File

@ -1,304 +0,0 @@
GNU LESSER 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.
This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License.
"The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version".
The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version:
a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following:
a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license document.
c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.
1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version.
e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions of the GNU Lesser 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 Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library.
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright © 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.
battery_monitor
Copyright (C) 2024 bluesun
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:
battery_monitor Copyright (C) 2024 bluesun
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>.

Binary file not shown.

Binary file not shown.

BIN
Qt5Core.dll Normal file

Binary file not shown.

BIN
Qt5Gui.dll Normal file

Binary file not shown.

BIN
Qt5SerialPort.dll Normal file

Binary file not shown.

BIN
Qt5Sql.dll Normal file

Binary file not shown.

BIN
Qt5Svg.dll Normal file

Binary file not shown.

BIN
Qt5Widgets.dll Normal file

Binary file not shown.

View File

@ -1,36 +0,0 @@
# Battery Monitor
#### Description
{**When you're done, you can delete the content in this README and update the file with details for others getting started with your repository**}
#### Software Architecture
Software architecture description
#### Installation
1. xxxx
2. xxxx
3. xxxx
#### Instructions
1. xxxx
2. xxxx
3. xxxx
#### Contribution
1. Fork the repository
2. Create Feat_xxx branch
3. Commit your code
4. Create Pull Request
#### Gitee Feature
1. You can use Readme\_XXX.md to support different languages, such as Readme\_en.md, Readme\_zh.md
2. Gitee blog [blog.gitee.com](https://blog.gitee.com)
3. Explore open source project [https://gitee.com/explore](https://gitee.com/explore)
4. The most valuable open source project [GVP](https://gitee.com/gvp)
5. The manual of Gitee [https://gitee.com/help](https://gitee.com/help)
6. The most popular members [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/)

View File

@ -1,3 +0,0 @@
# battery_monitor
## Version1.0.0 very smooth!

File diff suppressed because it is too large Load Diff

View File

@ -1,29 +0,0 @@
#ifndef APPPROTO_H
#define APPPROTO_H
#include <QObject>
class AppProto : public QObject
{
Q_OBJECT
public:
AppProto(QObject *parent = nullptr);
~AppProto();
void init();
public:
int itemCount = 0;
int itemCount_balance = 0;
int itemCount_DIDO = 0;
int itemCount_SOX = 0;
int itemCount_other = 0;
int itemCount_alert_value = 0;
int itemCount_alert_delay = 0;
int itemCount_alert_release_value = 0;
int itemCount_alert_release_delay = 0;
int itemCount_alert_dropcurr_rate = 0;
int itemCount_alert_solve_measure = 0;
};
#endif // APPPROTO_H

File diff suppressed because it is too large Load Diff

View File

@ -1,30 +0,0 @@
#ifndef APPPROTO_ENGLISH_H
#define APPPROTO_ENGLISH_H
#include <QObject>
class Appproto_English : public QObject
{
Q_OBJECT
public:
explicit Appproto_English(QObject *parent = nullptr);
~Appproto_English();
void init();
public:
int itemCount = 0;
int itemCount_balance = 0;
int itemCount_DIDO = 0;
int itemCount_SOX = 0;
int itemCount_other = 0;
int itemCount_alert_value = 0;
int itemCount_alert_delay = 0;
int itemCount_alert_release_value = 0;
int itemCount_alert_release_delay = 0;
int itemCount_alert_dropcurr_rate = 0;
int itemCount_alert_solve_measure = 0;
};
#endif // APPPROTO_ENGLISH_H

View File

@ -1,104 +0,0 @@
#include "appserial.h"
#include <QSerialPort>
#include <QSerialPortInfo>
#include <QDebug>
#include <QApplication>
#include <QMutex>
#include <dbt.h>
AppSerial::AppSerial(QObject *parent) : QObject(parent)
{
qApp->installNativeEventFilter(this); // 安装事件过滤器
m_SerialPort = new QSerialPort;
connect(m_SerialPort, &QSerialPort::readyRead, this, &AppSerial::slot_RecvSerialData);
}
AppSerial::~AppSerial()
{
m_SerialPort->close();
delete m_SerialPort;
}
/**
* @brief
* @return
*/
QStringList AppSerial::getAvailablePort()
{
QStringList strName;
foreach(const QSerialPortInfo& info, QSerialPortInfo::availablePorts())
{
QSerialPort port(info);
if(port.open(QIODevice::ReadWrite))
{
strName << info.portName() + "(" + info.manufacturer() + ")";
// qDebug() << strName;
port.close();
}
}
strName.sort();
return strName;
}
/**
* @brief
* @param hwnd
*/
void AppSerial::setHWND(HWND hwnd)
{
this->m_hwnd = hwnd;
}
bool AppSerial::nativeEventFilter(const QByteArray &eventType, void *message, long *result)
{
Q_UNUSED(eventType);
Q_UNUSED(result);
MSG* msg = reinterpret_cast<MSG*>(message);
int msgType = msg->message;
if (msgType == WM_DEVICECHANGE) {
PDEV_BROADCAST_HDR lpdb = (PDEV_BROADCAST_HDR)msg->lParam;
switch (msg->wParam) {
case DBT_DEVICEARRIVAL:
/* 串口插入事件 */
if (lpdb->dbch_devicetype == DBT_DEVTYP_PORT) {
PDEV_BROADCAST_PORT lpdbv = (PDEV_BROADCAST_PORT)lpdb;
QString portName = QString::fromWCharArray(lpdbv->dbcp_name);//插入的串口名
emit comChangeStatus(portName, true);
}
break;
case DBT_DEVICEREMOVECOMPLETE:
/* 串口拔出事件 */
if (lpdb->dbch_devicetype == DBT_DEVTYP_PORT) {
PDEV_BROADCAST_PORT lpdbv = (PDEV_BROADCAST_PORT)lpdb;
QString portName = QString::fromWCharArray(lpdbv->dbcp_name);//拔出的串口名
emit comChangeStatus(portName, false);
}
break;
case DBT_DEVNODES_CHANGED:
break;
default:
break;
}
}
return false;
}
void AppSerial::slot_RecvSerialData()
{
QByteArray recvData = m_SerialPort->readAll();
emit sig_RecvSerialData(recvData, TypeRecvData);
// qDebug() << __FUNCTION__ << "recvData:" << recvData;
}
void AppSerial::slot_SendSerialData(const QByteArray &sendData)
{
emit sig_RecvSerialData(sendData, TypeSendData);
qDebug() << __FUNCTION__ << "recvData:" << sendData;
m_SerialPort->write(sendData);
if (m_SerialPort->waitForBytesWritten(3000)) {
// 数据成功写入
} else {
// 写入失败
}
}

View File

@ -1,52 +0,0 @@
#ifndef APPSERIAL_H
#define APPSERIAL_H
/**/
#include <QObject>
#include <QAbstractNativeEventFilter>
#include <windows.h>
class QSerialPort;
class AppSerial : public QObject, public QAbstractNativeEventFilter
{
Q_OBJECT
public:
explicit AppSerial(QObject *parent = nullptr);
~AppSerial();
public:
QSerialPort *m_SerialPort;
private:
static AppSerial* m_comChange;
HWND m_hwnd;
enum DataType{
TypeRecvData,
TypeSendData
};
public:
// static Serial* getInstance();
static QStringList getAvailablePort();
void setHWND(HWND hwnd);
protected:
bool nativeEventFilter(const QByteArray &eventType, void *message, long *result);
signals:
/**
* @brief
* @param name
* @param flag true false
*/
void comChangeStatus(QString name, bool flag);
void sig_RecvSerialData(QByteArray recvData, int dataType);
public slots:
void slot_RecvSerialData();
void slot_SendSerialData(const QByteArray &sendData);
};
#endif // APPSERIAL_H

163
batt.cpp
View File

@ -1,163 +0,0 @@
#include "batt.h"
batt::batt(QWidget *parent) : QWidget(parent)
{
setContentsMargins(0,0,0,0);
borderWidth = 4;
headWidth = 20;
value = 50;
minValue = 0;
maxValue = 100;
alarmValue = 20;
borderRadio = 10;
drawInRadio = 8;
borderColor = QColor(96, 96, 96);
}
void batt::paintEvent(QPaintEvent *)
{
QPainter painter(this);
painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing);
drawBorder(&painter);
drawRightHead(&painter);
drawBackground(&painter);
drawText(&painter);
}
void batt::resizeEvent(QResizeEvent *)
{
}
// 画边框
void batt::drawBorder(QPainter *painter)
{
painter->save();
painter->setPen(QPen(borderColor,borderWidth));
borderRect = QRect(borderWidth,borderWidth,width()-2*borderWidth-headWidth,height()-2*borderWidth);
painter->drawRoundedRect(borderRect,borderRadio,borderRadio);
painter->restore();
}
// 画右边电池头部
void batt::drawRightHead(QPainter *painter)
{
painter->save();
double headHeight = height()/2;
painter->setPen(Qt::NoPen);
painter->setBrush(QColor(96, 96, 96));
QRectF headRect = QRectF(width()-headWidth-borderWidth/2,height()/2-headHeight/2,headWidth / 1.75,headHeight);
painter->drawRect(headRect);
painter->restore();
}
// 画数值对应颜色
void batt::drawBackground(QPainter *painter)
{
painter->save();
double batteryWidth = width()-headWidth-3*borderWidth; // 电池宽度
double bgWidth= value * batteryWidth / (maxValue-minValue); // 背景绘制宽度
QLinearGradient batteryGradient(QPointF(0, 0), QPointF(borderWidth+bgWidth,height()));
if (value <= alarmValue) {
batteryGradient.setColorAt(0.0, QColor(255, 26, 0));
batteryGradient.setColorAt(1.0, QColor(255, 0, 102));
} else {
batteryGradient.setColorAt(0.0, QColor(0, 255, 26));
batteryGradient.setColorAt(1.0, QColor(102, 255, 0));
}
painter->setBrush(QBrush(batteryGradient));
painter->setPen(Qt::NoPen);
QRectF rectBg = QRectF(borderWidth+borderWidth/2,borderWidth+borderWidth/2,bgWidth,height()-3*borderWidth);
painter->drawRoundedRect(rectBg,drawInRadio,drawInRadio);
painter->restore();
}
// 画百分比数值
void batt::drawText(QPainter *painter)
{
painter->save();
QString value_str = QString("%1%").arg(value);
painter->setPen(QPen(QColor(Qt::black)));
double w = qMin(borderRect.width(),borderRect.height());
// 文字大小自适应 90为控件初始高度30位字体默认大小
int fontSize = 30 * w / 90;
painter->setFont(QFont("Microsoft YaHei UI",fontSize));
painter->drawText(borderRect,value_str,QTextOption(Qt::AlignHCenter | Qt::AlignVCenter));
painter->restore();
}
// 设置当前值
void batt::setValue(int value)
{
this->value = value;
update();
}
void batt::setMinValue(int min)
{
minValue = min;
update();
}
void batt::setMaxValue(int max)
{
maxValue = max;
update();
}
void batt::setRange(int min, int max)
{
minValue = min;
maxValue = max;
update();
}
void batt::setBorderWidth(int width)
{
borderWidth = width;
update();
}
void batt::setBorderRadio(int radio)
{
borderRadio = radio;
update();
}
void batt::setInRadio(int radio)
{
drawInRadio = radio;
update();
}
void batt::setAlarmValue(int alarm)
{
alarmValue = alarm;
update();
}
void batt::setBorderColor(QColor color)
{
borderColor = color;
update();
}
int batt::getValue()
{
return value;
}
int batt::getMinValue()
{
return minValue;
}
int batt::getMaxValue()
{
return maxValue;
}
int batt::getAlarmValue()
{
return alarmValue;
}

60
batt.h
View File

@ -1,60 +0,0 @@
#ifndef BATT_H
#define BATT_H
#include <QWidget>
#include <QPainter>
#include <QtMath>
#include <QDebug>
class batt : public QWidget
{
Q_OBJECT
Q_PROPERTY(int value READ getValue WRITE setValue)
Q_PROPERTY(int minValue READ getMinValue WRITE setMinValue)
Q_PROPERTY(int maxValue READ getMaxValue WRITE setMaxValue)
Q_PROPERTY(int alarmValue READ getAlarmValue WRITE setAlarmValue)
public:
explicit batt(QWidget *parent = nullptr);
protected:
void paintEvent(QPaintEvent *) override;
void resizeEvent(QResizeEvent *) override;
protected:
void drawBorder(QPainter *painter);
void drawRightHead(QPainter *painter);
void drawBackground(QPainter *painter);
void drawText(QPainter *painter);
public slots:
void setValue(int value); // 设置当前值
void setMinValue(int min); // 设置最小值
void setMaxValue(int max); // 设置最大值
void setRange(int min,int max); // 设置数值范围
void setBorderWidth(int width); // 设置边框宽度
void setBorderRadio(int radio); // 设置外边框圆角
void setInRadio(int radio); // 设置内部绘制区域圆角
void setAlarmValue(int alarm); // 设置警告值
void setBorderColor(QColor color); // 设置边框颜色
int getValue(); // 获取当前值
int getMinValue(); // 获取当前最小值
int getMaxValue(); // 获取当前最大值
int getAlarmValue(); // 获取告警值
signals:
private:
int borderWidth; // 边缘线框宽度
int headWidth; // 右侧头部宽度
int value; // 当前值
int minValue; // 最小值
int maxValue; // 最大值
int alarmValue; // 警告值
int borderRadio; // 外部边框圆角
int drawInRadio; // 内部绘制区域圆角
QRectF borderRect; // 电池区域
QColor borderColor;
};
#endif // BATT_H

BIN
battery.data Normal file

Binary file not shown.

BIN
battery_english.data Normal file

Binary file not shown.

View File

@ -1,72 +0,0 @@
#include "chartpaint.h"
#include <QFont>
ChartPaint::ChartPaint(QWidget *parent): QWidget{parent}
{
}
QChartView *ChartPaint::Paint(QString type, int dataArray[])
{
// 创建柱状集合
QBarSet *set0 = new QBarSet("电量"); // 创建第一个柱状集合
QBarSet *set1 = new QBarSet("时间"); // 创建第二个柱状集合
*set0 << dataArray[0] << dataArray[1]; // 电量集合--累计充--累计放--日充--日放
*set1 << dataArray[2] << dataArray[3]; // 时间集合--累计充--累计放--日充--日放
// 创建柱状系列
QBarSeries *series0 = new QBarSeries(); // 创建第一个柱状系列
series0->append(set0); // 将第一个集合添加到第一个系列
series0->setLabelsVisible(true);
series0->setBarWidth(0.3);
// series0->setLabelsPosition(QAbstractBarSeries::LabelsOutsideEnd);
QBarSeries *series1 = new QBarSeries(); // 创建第二个柱状系列
series1->append(set1); // 将第二个集合添加到第二个系列
series1->setLabelsVisible(true);
series1->setBarWidth(0.3);
// series1->setLabelsPosition(QAbstractBarSeries::LabelsOutsideEnd);
// 创建图表
QChart *chart = new QChart(); // 创建图表对象
chart->addSeries(series0); // 将第一个系列添加到图表
chart->addSeries(series1); // 将第二个系列添加到图表
chart->setTitle(type + "充放电电量和时间柱状图"); // 设置图表标题
chart->setTitleFont(QFont("微软雅黑", 10, QFont::Bold));
// chart->setBackgroundBrush(QBrush(Qt::lightGray));
// 创建X轴
QBarCategoryAxis *axisX = new QBarCategoryAxis(); // 创建X轴
axisX->append(QStringList() << type + "" << type + ""); // 设置X轴的类别
chart->addAxis(axisX, Qt::AlignBottom); // 将X轴添加到图表底部
series0->attachAxis(axisX); // 将X轴附加到第一个系列
series1->attachAxis(axisX); // 将X轴附加到第二个系列
axisX->setLabelsFont(QFont("微软雅黑", 10, QFont::Bold));
// 创建第一个Y轴
QValueAxis *axisY1 = new QValueAxis(); // 创建第一个Y轴
axisY1->setRange(0, (std::max(dataArray[0], dataArray[1])) * 1.1); // 设置Y轴的范围
axisY1->setLabelFormat("%i"); // 设置Y轴标签格式
axisY1->setLabelsFont(QFont("微软雅黑", 10, QFont::Bold));
axisY1->setTitleText(type + "充放电量(kWh)"); // 设置Y轴标题
chart->addAxis(axisY1, Qt::AlignLeft); // 将第一个Y轴添加到图表左侧
series0->attachAxis(axisY1); // 将第一个系列附加到第一个Y轴
// 创建第二个Y轴
QValueAxis *axisY2 = new QValueAxis(); // 创建第二个Y轴
axisY2->setRange(0, (std::max(dataArray[2], dataArray[3])) * 1.2); // 设置Y轴的范围
axisY2->setLabelFormat("%i"); // 设置Y轴标签格式
axisY2->setLabelsFont(QFont("微软雅黑", 10, QFont::Bold));
axisY2->setTitleText(type + "充放时间(小时)"); // 设置Y轴标题
chart->addAxis(axisY2, Qt::AlignRight); // 将第二个Y轴添加到图表右侧
series1->attachAxis(axisY2); // 将第二个系列附加到第二个Y轴
// 创建图表视图
QChartView *chartView = new QChartView(chart); // 创建图表视图对象
chartView->setRenderHint(QPainter::Antialiasing); // 设置抗锯齿渲染
return chartView;
}

View File

@ -1,19 +0,0 @@
#ifndef CHARTPAINT_H
#define CHARTPAINT_H
#include <QObject>
#include <QWidget>
#include <QtCharts/QtCharts>
class ChartPaint : public QWidget
{
Q_OBJECT
public:
explicit ChartPaint(QWidget *parent = nullptr);
QChartView* Paint(QString type, int dataArray[]);
signals:
};
#endif // CHARTPAINT_H

13
config.ini Normal file
View File

@ -0,0 +1,13 @@
[System]
Language=0
[Window]
ShowStatusbar=true
[Serial]
BaudRate=7
DataBits=3
StopBits=0
Parity=0
BmuNumber=0
SerialPort=COM9

View File

@ -1,649 +0,0 @@
#include "delegate.h"
#include <QDebug>
#include <QSpinBox>
#include <QDateEdit>
#include <QCheckBox>
#include <QComboBox>
#include <QDateTimeEdit>
#include <QDateEdit>
#include <QPushButton>
#include <QLineEdit>
#include <QCalendarWidget>
#include <QProgressBar>
#include <QApplication>
#include <QPainter>
#include <QMouseEvent>
#include <QLabel>
#include <QTableView>
Delegate::Delegate(QObject *parent): QStyledItemDelegate(parent)
{
this->init();
}
QWidget *Delegate::createEditor(QWidget *parent, const QStyleOptionViewItem &/*option*/, const QModelIndex &/*index*/) const
{
if(delegateType == "QCheckBox")
return 0;
/*创建编辑器*/
QWidget *editor = new QWidget(parent);
/*判断具体的委托,并将编辑器进行响应的设置*/
if(delegateType == "QSpinBox")
{
//必须加上parent负责QSpinBox显示在视图外面
QSpinBox *sbox = new QSpinBox(parent);
sbox->setRange(sboxMinValue,sboxMaxValue);
sbox->setSuffix(sboxSuffixStr);
sbox->setPrefix(sboxPrefixStr);
sbox->setSingleStep(sboxSingleStep);
sbox->setStepType(sboxStepType);
sbox->setValue(sboxInitValue);
editor = sbox;
connect(sbox,SIGNAL(valueChanged(int)),this,SLOT(on_valueChanged(int)));
}
else if(delegateType == "QDoubleSpinBox")
{
QDoubleSpinBox *sdbox = new QDoubleSpinBox(parent);
sdbox->setRange(0,100);
// sdbox->setSuffix(sboxSuffixStr);
// sdbox->setPrefix(sboxPrefixStr);
sdbox->setSingleStep(0.1);
// sdbox->setStepType(sboxStepType);
// sdbox->setValue(sboxInitValue);
editor = sdbox;
connect(sdbox,SIGNAL(valueChanged(double)),this,SLOT(on_valueChanged(double)));
}
else if(delegateType == "QComboBox")
{
QComboBox *cbox = new QComboBox(parent);
cbox->addItems(cboxItems);
cbox->setEditable(cboxEditable);
editor = cbox;
}
else if (delegateType == "QDateTimeEdit") {
QDateTimeEdit *dateTime = new QDateTimeEdit(parent);
dateTime->setCalendarPopup(true);
dateTime->setDisplayFormat("yyyy-MM-dd HH:mm:ss");
dateTime->calendarWidget()->setLocale(QLocale::Chinese);
editor = dateTime;
}
else if (delegateType == "QDateEdit") {
QDateEdit *date = new QDateEdit(parent);
date->setCalendarPopup(true);
date->setDisplayFormat("yyyy-MM-dd");
date->calendarWidget()->setLocale(QLocale::Chinese);
editor = date;
}
else if (delegateType == "QTimeEdit") {
QTimeEdit *time = new QTimeEdit(parent);
time->setDisplayFormat("HH:mm:ss");
editor = time;
}
else if (delegateType == "QLineEdit")
{
QLineEdit *lineEidt = new QLineEdit(parent);
// lineEidt->setReadOnly(true);
editor = lineEidt;
connect(lineEidt, SIGNAL(textChanged(QString)), this, SLOT(on_valueChanged(QString)));
}
else if (delegateType == "QLabel")
{
QLabel *label = new QLabel(parent);
editor = label;
connect(label, SIGNAL(textChanged(QString)), this, SLOT(on_valueChanged(QString)));
}
return editor;
}
void Delegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
auto value = index.model()->data(index, Qt::EditRole);
if(delegateType == "QSpinBox")
{
QSpinBox *spinBox = static_cast<QSpinBox*>(editor);
spinBox->setValue(value.toInt());
}
else if(delegateType == "QDoubleSpinBox")
{
QDoubleSpinBox *dspinBox = static_cast<QDoubleSpinBox*>(editor);
dspinBox->setValue(value.toFloat());
}
else if(delegateType == "QComboBox")
{
QComboBox *cbox = static_cast<QComboBox*>(editor);
cbox->setCurrentText(value.toString());
}
else if (delegateType == "QDateTimeEdit")
{
QDateTimeEdit *dateTime = static_cast<QDateTimeEdit *>(editor);
dateTime->setDateTime(QDateTime::fromString(value.toString(), "yyyy-MM-dd HH:mm:ss"));
}
else if (delegateType == "QDateEdit")
{
QDateEdit *date = static_cast<QDateEdit *>(editor);
date->setDate(QDate::fromString(value.toString(), "yyyy-MM-dd"));
}
else if (delegateType == "QTimeEdit")
{
QTimeEdit *time = static_cast<QTimeEdit *>(editor);
time->setTime(QTime::fromString(value.toString(), "HH:mm:ss"));
}
else if (delegateType == "QLineEdit")
{
QLineEdit *lineEidt = static_cast<QLineEdit *>(editor);
lineEidt->setText(value.toString());
}
else if (delegateType == "QLabel")
{
QLabel *label = static_cast<QLabel *>(editor);
label->setText(value.toString());
}
else
{
QStyledItemDelegate::setEditorData(editor, index);
}
}
void Delegate::setModelData(QWidget *editor, QAbstractItemModel *model,
const QModelIndex &index) const
{
QVariant value = model->data(index);
if(delegateType == "QSpinBox")
{
QSpinBox *spinBox = static_cast<QSpinBox*>(editor);
value = spinBox->value();
}
if(delegateType == "QDoubleSpinBox")
{
QDoubleSpinBox *dspinBox = static_cast<QDoubleSpinBox*>(editor);
value = dspinBox->value();
}
else if(delegateType == "QComboBox")
{
QComboBox *cbox = static_cast<QComboBox*>(editor);
value = cbox->currentText();
}
else if (delegateType == "QDateTimeEdit")
{
QDateTimeEdit *dateTime = static_cast<QDateTimeEdit *>(editor);
value = dateTime->dateTime().toString("yyyy-MM-dd HH:mm:ss");
}
else if (delegateType == "QDateEdit")
{
QDateEdit *date = static_cast<QDateEdit *>(editor);
value = date->date().toString("yyyy-MM-dd");
}
else if (delegateType == "QTimeEdit")
{
QTimeEdit *time = static_cast<QTimeEdit *>(editor);
value = time->time().toString("HH:mm:ss");
}
else if (delegateType == "QLineEdit")
{
QLineEdit *lineEidt = static_cast<QLineEdit *>(editor);
value = lineEidt->text();
}
else if (delegateType == "QLabel")
{
QLabel *label = static_cast<QLabel *>(editor);
value = label->text();
}
model->setData(index, value, Qt::EditRole);
}
void Delegate::updateEditorGeometry(QWidget *editor,
const QStyleOptionViewItem &option,
const QModelIndex &/* index */) const
{
editor->setGeometry(option.rect);
}
void Delegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
if(index.column() == delegateColumnID)
{
if(delegateType == "QProgressBar")
{
drawProgressBar(painter,option,index);
}
else if(delegateType == "QCheckBox")
{
drawCheckBox(painter,option,index);
}
else if(delegateType == "QPushButton")
{
drawPushButton(painter,option,index);
}
else if(delegateType == "QPixmap" && judgmentColumn>=0)
{
drawPixmap(painter,option,index);
}
else if (delegateType == "QLineEdit" && delegatePwd)
{
drawLineEdit(painter, option, index);
}
}//if
else
{
QStyledItemDelegate::paint(painter,option,index);
}
}
bool Delegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index)
{
//Qt6中如果调用了 qApp->setStyleSheet 设置了全局样式的话,鼠标移动也会触发 editorEvent TNND
if (event->type() == QEvent::MouseMove) {
return false;
}
//处理编辑数据
QString data = index.data(Qt::DisplayRole).toString();
if (delegateType == "QCheckBox") {
//鼠标松开不用处理,不然会重复设置
if (event->type() == QEvent::MouseButtonRelease) {
return false;
}
//如果当前的文字和设置的选中文字一致则说明是选中
checkedText = (data == checkBoxChecked ? checkBoxUnchecked : checkBoxChecked);
model->setData(index, checkedText, Qt::EditRole);
emit valueChanged(checkedText);
} else if (delegateType == "QPushButton") {
QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
mousePoint = mouseEvent->pos();
mousePressed = false;
//没有按钮对应的值则不处理
QStringList list = data.split("|");
int count = list.count();
if (data.isEmpty() || count == 0) {
return false;
}
//根据按钮数量自动计算按钮对应的区域
int x = option.rect.x();
int y = option.rect.y();
int width = option.rect.width() / count;
int height = option.rect.height();
QList<QRect> btnRect;
for (int i = 0; i < count; ++i) {
btnRect << QRect(x + i * width, y, width, height);
}
if (event->type() == QEvent::MouseButtonPress) {
//鼠标按下更新对应按钮区域是否按下,并判断按下的区域是哪个按钮,发送对应的按钮索引和index
for (int i = 0; i < count; ++i) {
if (btnRect.at(i).contains(mousePoint)) {
mousePressed = true;
emit buttonClicked(i, index);
break;
}
}
}
//需要返回真表示需要继续绘制
return true;
}
//和事件过滤器类似,也需要继续返回执行
return QStyledItemDelegate::editorEvent(event, model, option, index);
}
void Delegate::init()
{
delegateType = "QSpinBox";
delegateColumnID = -1;
sboxMaxValue = 100;
sboxMinValue = 0;
sboxPrefixStr = "";
sboxSuffixStr = "";
sboxSingleStep = 1;
sboxInitValue = 0;
sboxStepType = QAbstractSpinBox::DefaultStepType;
cboxItems.clear();
cboxEditable = true;
checkBoxChecked = "true";
checkBoxUnchecked = "false";
pgbarMax = 100;
pgbarMin = 0;
pgbarAlignment = Qt::AlignCenter;
isTextVisible = true;
invertedAppearance = false;
imgOk = QPixmap(":/corr.png");
imgNo = QPixmap(":/erro.png");
imgWidth = 20;
imgHeigth = 20;
judgmentColumn = -1;
judgmentValue = "错误";
judgmentCondition = "contains";
}
void Delegate::checkData(const QString &data,bool *selse)const
{
if (judgmentCondition == "==") {
if (data == judgmentValue) {
*selse = true;
}
} else if (judgmentCondition == ">") {
if (data.toDouble() > judgmentValue.toDouble()) {
*selse = true;
}
} else if (judgmentCondition == ">=") {
if (data.toDouble() >= judgmentValue.toDouble()) {
*selse = true;
}
} else if (judgmentCondition == "<") {
if (data.toDouble() < judgmentValue.toDouble()) {
*selse = true;
}
} else if (judgmentCondition == "<=") {
if (data.toDouble() <= judgmentValue.toDouble()) {
*selse = true;
}
} else if (judgmentCondition == "!=") {
if (data != judgmentValue) {
*selse = true;
}
} else if (judgmentCondition == "contains") {
QStringList list = judgmentValue.split("|");
foreach (QString value, list) {
if (data.contains(value)) {
*selse = true;
break;
}
}
}
}
void Delegate::drawProgressBar(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index)const
{
//获得视图中的值
int value = index.model()->data(index,Qt::DisplayRole).toInt();
//创建包含QProgressBar样式信息类
QStyleOptionProgressBar soPgbar;
//使用我们创建的pgBar初始化soPgbar
soPgbar.initFrom(pgBar);
//设置最大值和最小值
soPgbar.maximum = pgbarMax;
soPgbar.minimum = pgbarMin;
//设置进度条值
soPgbar.progress = value;
//设置状态
soPgbar.state |= QStyle::State_Enabled;
soPgbar.state |= QStyle::State_Horizontal;
//设置位置和大小
soPgbar.rect = option.rect;
//设置文本
soPgbar.text = QString("%1%").arg(value);
//设置文本是否可见
soPgbar.textVisible = isTextVisible;
//设置文本居中
soPgbar.textAlignment = pgbarAlignment;
//设置进度条的进度方向
soPgbar.invertedAppearance = invertedAppearance;
//绘制
QApplication::style()->drawControl(QStyle::CE_ProgressBar,&soPgbar,painter,pgBar);
}
void Delegate::drawCheckBox(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
//处理复选框委托,判断是否选中,设置选中状态
QString data = index.data(Qt::EditRole).toString();
bool checked = (data == checkBoxChecked);
QStyleOptionButton styleOption;
styleOption.initFrom(checkBox);
styleOption.state = checked ? QStyle::State_On : QStyle::State_Off;
styleOption.state |= QStyle::State_Enabled;
//设置居中正方形区域
int width = option.rect.width();
int height = option.rect.height();
int size = qMin(width, height);
int x = option.rect.center().x() - (size / 4);
int y = option.rect.y();
styleOption.rect = QRect(x, y, size, size);
QApplication::style()->drawControl(QStyle::CE_CheckBox, &styleOption, painter, checkBox);
}
void Delegate::drawPushButton(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
//没有按钮对应的值则不处理
QString data = index.data(Qt::DisplayRole).toString();
QStringList list = data.split("|");
int count = list.count();
if (data.isEmpty() || count == 0) {
return;
}
//处理按钮集合委托,自动计算分配宽度
int x = option.rect.x();
int y = option.rect.y();
int width = option.rect.width() / count;
int height = option.rect.height();
//分别绘制按钮集合
for (int i = 0; i < count; ++i) {
QStyleOptionButton styleOption;
styleOption.initFrom(button);
styleOption.rect = QRect(x + i * width, y, width, height);
styleOption.text = list.at(i);
styleOption.state |= QStyle::State_Enabled;
//鼠标按下更新对应的样式
if (mousePressed) {
if (styleOption.rect.contains(mousePoint)) {
styleOption.state |= QStyle::State_Sunken;
}
}
//第四个参数也可以为空,为空的话就不能应用样式表
QApplication::style()->drawControl(QStyle::CE_PushButton, &styleOption, painter, button);
}
}
void Delegate::drawPixmap(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QString data = index.model()->index(index.row(),judgmentColumn).data().toString();
bool selse;
checkData(data,&selse);
//图标自动缩放到指定大小
QPixmap pixmap = (selse?imgOk:imgNo);
pixmap = pixmap.scaled(QSize(imgWidth, imgHeigth), Qt::KeepAspectRatio, Qt::SmoothTransformation);
QApplication::style()->drawItemPixmap(painter, option.rect, Qt::AlignCenter, pixmap);
}
void Delegate::drawLineEdit(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
//统计数量,转换成对应数量的密码样式
QString value = index.model()->data(index, Qt::DisplayRole).toString();
int len = value.length();
QString text;
for (int i = 0; i < len; ++i)
{
text += "";
}
QRect rect = option.rect;
rect.setX(rect.x() + 2);
painter->drawText(rect, Qt::AlignCenter, text);
}
void Delegate::on_valueChanged(int value)
{
emit valueChanged(QString("%1").arg(value));
}
void Delegate::on_valueChanged(double value)
{
emit valueChanged(QString("%1").arg(value));
}
void Delegate::on_valueChanged(QString value)
{
emit valueChanged(QString("%1").arg(value));
}
void Delegate::setDelegateType(const QString &delegateType)
{
this->delegateType = delegateType;
/*将需要使用paint绘制的控件在这里new出来。
*paint函数中new呢
* const成员函数paint中分配非静态数据成员
*/
if(delegateType == "QProgressBar")
{
pgBar = new QProgressBar;
}
else if(delegateType == "QPushButton")
{
button = new QPushButton;
}
else if (delegateType == "QCheckBox")
{
checkBox = new QCheckBox;
}
}
void Delegate::setDelegateColumn(const int delegateColumnID)
{
this->delegateColumnID = delegateColumnID;
}
void Delegate::setSboxMaxValue(const int max)
{
sboxMaxValue = max;
}
void Delegate::setSboxMinValue(const int min)
{
sboxMinValue = min;
}
void Delegate::setSboxPrefixStr(const QString &prefix)
{
sboxPrefixStr = prefix;
}
void Delegate::setSboxSuffixStr(const QString &suffix)
{
sboxSuffixStr = suffix;
}
void Delegate::setSboxSingleStep(const int SingleStep)
{
sboxSingleStep = SingleStep;
}
void Delegate::setSboxInitValue(const int initValue)
{
sboxInitValue = initValue;
}
void Delegate::setSboxStepType(QAbstractSpinBox::StepType st)
{
sboxStepType = st;
}
void Delegate::setCboxItems(const QStringList &items)
{
cboxItems = items;
}
void Delegate::setCboxEditable(bool editable)
{
cboxEditable = editable;
}
void Delegate::setPgBarRange(const int min, const int max)
{
pgbarMin = min;
pgbarMax = max;
}
void Delegate::setPgBarTextVisible(bool isTextVisible)
{
this->isTextVisible = isTextVisible;
}
void Delegate::setPgBarAlignment(Qt::Alignment pgbarAlignment)
{
this->pgbarAlignment = pgbarAlignment;
}
void Delegate::setInvertedAppearance(bool invertedAppearance)
{
this->invertedAppearance = invertedAppearance;
}
void Delegate::setCheckBoxText(const QString &checkBoxChecked, const QString &checkBoxUnchecked)
{
this->checkBoxChecked = checkBoxChecked;
this->checkBoxUnchecked = checkBoxUnchecked;
}
void Delegate::setImgOk(const QPixmap &imgOk)
{
this->imgOk = imgOk;
}
void Delegate::setImgNo(const QPixmap &imgNo)
{
this->imgNo = imgNo;
}
void Delegate::setImgSize(int width,int heigth)
{
this->imgWidth = width;
this->imgHeigth = heigth;
}
void Delegate::setJudgmentColumn(int column)
{
this->judgmentColumn = column;
}
void Delegate::setJudgmentValue(const QString &value)
{
this->judgmentValue = value;
}
void Delegate::setJudgmentCondition(const QString &condition)
{
this->judgmentCondition = condition;
}
void Delegate::setDelegatePwd(bool showDelegatePwd)
{
this->delegatePwd = showDelegatePwd;
}
void Delegate::setComboBox(QAbstractItemView *view, QAbstractItemModel *model)
{
for (int row = 0; row < model->rowCount(); ++row) {
QComboBox *comboBox = new QComboBox();
comboBox->addItems(cboxItems);
view->setIndexWidget(model->index(row, delegateColumnID), comboBox);
}
}

View File

@ -1,175 +0,0 @@
#ifndef DELEGATE_H
#define DELEGATE_H
/**
* @projectName Delegate-
* @author m晴朗
* @email mengdadae@qq.com
* 1.
* 2.
* 3.
**/
#include <QStyledItemDelegate>
#include <QAbstractItemModel>
class QComboBox;
class QProgressBar;
class QTableView;
class QPushButton;
class QLineEdit;
class QCheckBox;
class Delegate : public QStyledItemDelegate
{
Q_OBJECT
public:
Delegate(QObject *parent = nullptr);
protected:
QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const override;
void setEditorData(QWidget *editor, const QModelIndex &index) const override;
void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const override;
void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const override;
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override;
bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) override;
public:
/**
*
* @param delegateType
* @return
**/
void setDelegateType(const QString &delegateType);
/**
* paint绘制的委托需要这个参数
* @param delegateColumnID
* @return
**/
void setDelegateColumn(const int delegateColumnID);
/*QSpinBox设置相关参数函数*/
void setSboxMaxValue(const int max);
void setSboxMinValue(const int min);
void setSboxPrefixStr(const QString &prefix);
void setSboxSuffixStr(const QString &suffix);
void setSboxSingleStep(const int SingleStep);
void setSboxInitValue(const int initValue);
void setSboxStepType(QAbstractSpinBox::StepType st);
/*QComboBox相关参数设置*/
void setCboxItems(const QStringList &items);
void setCboxEditable(bool editable);
/*QProgressBar设置相关参数函数*/
void setPgBarRange(const int min,const int max);
void setPgBarTextVisible(bool isTextVisible);
void setPgBarAlignment(Qt::Alignment pgbarAlignment);
void setInvertedAppearance(bool invertedAppearance);
/*QCheckBox*/
void setCheckBoxText(const QString &checkBoxChecked, const QString &checkBoxUnchecked);
/*QPixmap设置相关参数函数*/
void setImgOk(const QPixmap &imgOk);
void setImgNo(const QPixmap &imgNo);
void setImgSize(int width,int heigth);
void setJudgmentColumn(int column);
void setJudgmentValue(const QString &value);
void setJudgmentCondition(const QString &condition);
/*QLineEdit相关参数函数*/
void setDelegatePwd(bool showDelegatePwd);
/*不使用委托实现的控件*/
void setComboBox(QAbstractItemView *view,QAbstractItemModel *model);
private:
/**
*
* @param
* @return
**/
void init();
void checkData(const QString &data,bool *selse)const;
/**
* ,paint函数中调用
* @param paint函数参数保持一致
* @return
**/
void drawProgressBar(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;
void drawCheckBox(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;
void drawPushButton(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;
void drawPixmap(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;
void drawLineEdit(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;
signals:
void valueChanged(QString value);
/**
*
* @param
* @return
**/
void buttonClicked(int btnIndex, const QModelIndex &index);
private slots:
/**
*
* @param
* @return
**/
void on_valueChanged(int value);
void on_valueChanged(double value);
void on_valueChanged(QString value);
private:
QString delegateType;/*委托类型*/
int delegateColumnID;/*需要委托的列*/
QTableView *view;/*在哪个表格*/
QPoint mousePoint;/*鼠标按下处坐标*/
bool mousePressed;/*鼠标是否按下*/
/*QSpinBox相关参数*/
int sboxMaxValue;/*微调框的最大值*/
int sboxMinValue;/*微调框的最小值*/
QString sboxPrefixStr;/*微调框前缀*/
QString sboxSuffixStr;/*微调框后缀*/
int sboxSingleStep;/*微调框步长*/
int sboxInitValue;/*微调框初始值*/
QAbstractSpinBox::StepType sboxStepType;/*微调框步长类型*/
QStringList cboxItems;/*下组合框项目内容*/
bool cboxEditable;/*组合框是否可以编辑*/
/*QProgressBar相关参数*/
int pgbarMax;
int pgbarMin;
Qt::Alignment pgbarAlignment;
bool isTextVisible;
bool invertedAppearance;
/*QCheckBox参数*/
QString checkedText; //存储复选框当前文字
QString checkBoxChecked; //复选框选中对应的文字
QString checkBoxUnchecked; //复选框选中对应的文字
/*QPixmap相关参数*/
QPixmap imgOk;/*表示正确的图标*/
QPixmap imgNo;/*表示错误的图标*/
int imgWidth;/*图片宽度*/
int imgHeigth;/*图片高度*/
int judgmentColumn;/*需要判断的列*/
QString judgmentValue;/*阀值*/
QString judgmentCondition;/*判断条件*/
/*QLineEdit相关参数函数*/
bool delegatePwd; //是否密码显示
/*需要paint重新绘制的委托*/
QProgressBar *pgBar;
QPushButton *button;
QCheckBox *checkBox; //复选框
};
#endif // DELEGATE_H

View File

@ -1,351 +0,0 @@
#include "dialoglogin.h"
#include "ui_dialoglogin.h"
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
#include <QSettings>
#include <QSerialPort>
#include <QSerialPortInfo>
#include <QDebug>
#include "appserial.h"
#include "modbusrtu.h"
#include <windef.h>
#include <QTranslator>
#include <QThread>
#include <QMetaType>
DialogLogin::DialogLogin(QWidget *parent)
: QDialog(parent)
, ui(new Ui::DialogLogin)
{
ui->setupUi(this);
qRegisterMetaType<QList<int>>("QList<int>");
init();
serialInit();
mainwindowInit();
}
DialogLogin::~DialogLogin()
{
delete ui;
free(m_MainWindow);
free(m_Serial);
free(m_ModbusRTU);
}
void DialogLogin::init()
{
/* 设置标题 */
setWindowTitle("Login");
/* 设置Logo */
setWindowIcon(QIcon(":/Image/icon.png"));
/* 隐藏Dialog问号按钮 */
setWindowFlags(Qt::WindowCloseButtonHint);
/* 设置模态化,无法选中其他界面 */
setModal(true);
/* 设置固定大小 */
// setFixedSize(260, 320);
/* 实例化对象 */
m_MainWindow = new MainWindow;
// m_MainWindow->show();
m_Serial = new AppSerial;
m_Serial->setHWND((HWND)this->winId());
m_ModbusRTU = new ModbusRTU;
ini = new QSettings("config.ini", QSettings::IniFormat);
connect(ui->btnConnect, &QPushButton::clicked, this, &DialogLogin::slot_btnConnect_clicked);
ui->groupBox->setStyleSheet("QGroupBox { border: none; }");
ui->label_bluesunLogo->setStyleSheet("QLabel { background-image: url(:/Image/bluesun.png); "
"background-repeat: no-repeat; background-size: cover; background-position: center center;}");
// //将背景设置为白色
// ui->groupBox->setStyleSheet("background-color: #FFFFFF;");
m_MainWindow->setStyleSheet("background-color: #FFFFFF;");
// //传递BCU个数的信号与槽
// BCUNumbers = ui->comboBoxBCUQuantity->currentText().toInt();
// qDebug() << "the number of the BCU: " << BCUNumbers;
// emit sendBCUNumberSignals(BCUNumbers);
// connect(ui->comboBoxBCUQuantity, &QComboBox::currentTextChanged, m_MainWindow, [&]{
// BCUNumbers = ui->comboBoxBCUQuantity->currentText().toInt();
// emit sendBCUNumberSignals(BCUNumbers);
// });
connect(this, &DialogLogin::sendBCUNumberSignals, m_MainWindow, &MainWindow::slot_getBcuNumberFromDialoglogin);
//报文的信号与槽的连接
connect(m_ModbusRTU, &ModbusRTU::sig_showModbusData, m_MainWindow, &MainWindow::slot_pageDebugDisplayMessage);
connect(m_ModbusRTU, &ModbusRTU::sig_showModbusData_sgl_tempt, m_MainWindow, &MainWindow::slot_pageDebugDisplayMessage);
connect(m_ModbusRTU, &ModbusRTU::sig_showModbusData_base_info1_45, m_MainWindow, &MainWindow::slot_pageDebugDisplayMessage);
connect(m_ModbusRTU, &ModbusRTU::sig_showModbusData_base_info57_78, m_MainWindow, &MainWindow::slot_pageDebugDisplayMessage);
connect(m_ModbusRTU, &ModbusRTU::sig_showModbusData_base_info83_106, m_MainWindow, &MainWindow::slot_pageDebugDisplayMessage);
connect(m_ModbusRTU, &ModbusRTU::sig_showModbusData, m_MainWindow, &MainWindow::slot_pageHomeSglDataMessage);
connect(m_ModbusRTU, &ModbusRTU::sig_showModbusData_sgl_tempt, m_MainWindow, &MainWindow::slot_pageHomeSglTempt);
connect(m_ModbusRTU, &ModbusRTU::sig_showModbusData_base_info1_45, m_MainWindow, &MainWindow::slot_pageHomeBaseInfo1_45);
connect(m_ModbusRTU, &ModbusRTU::sig_showModbusData_base_info57_78, m_MainWindow, &MainWindow::slot_pageHomeBaseInfo57_78);
connect(m_ModbusRTU, &ModbusRTU::sig_showModbusData_base_info83_106, m_MainWindow, &MainWindow::slot_pageHomeBaseInfo83_106);
connect(m_ModbusRTU, &ModbusRTU::sig_showModbusData_base_info_list_47_49_51_53_55, m_MainWindow, &MainWindow::slot_pageHomeBaseInfo47_49_51_53_55);
//写寄存器的信号与槽的连接
connect(m_MainWindow, &MainWindow::write_regs_signals, m_ModbusRTU, &ModbusRTU::write_regs_slot);
//读寄存器的信号与槽的连接
connect(m_MainWindow, &MainWindow::read_regs_signals, m_ModbusRTU, &ModbusRTU::read_regs_slot);
connect(m_ModbusRTU, &ModbusRTU::sig_showReadHoldingRegs, m_MainWindow, &MainWindow::slot_pageParaSetShow);
//主窗口关闭时,关闭线程
connect(m_MainWindow, &MainWindow::quitThread, this, [=]{
qDebug() << "关闭线程";
m_ModbusRTU->quit();
});
connect(m_MainWindow, &MainWindow::closeThread, m_ModbusRTU, &ModbusRTU::slot_pauseThread);
connect(m_MainWindow, &MainWindow::openThread, m_ModbusRTU, &ModbusRTU::slot_resumeThread);
// ui->btnConnect->setStyleSheet("QPushButton { background-color: lightgray; color: black; border: none; }");
//主窗口接受语言选择number的信号与槽的连接
connect(this, &DialogLogin::sendLanNumberSignals, m_MainWindow, &MainWindow::getLanNumberSlot);
//故障解析的信号与槽
connect(m_ModbusRTU, &ModbusRTU::sig_showFault, m_MainWindow, &MainWindow::slot_pageHomeFault);
//电池界面中点击bmu发送对应的数据
// connect(m_MainWindow, &MainWindow::read_regs_input_signals_vol, m_ModbusRTU, &ModbusRTU::read_regs_input_slot_vol);
// connect(m_MainWindow, &MainWindow::read_regs_input_signals_temp, m_ModbusRTU, &ModbusRTU::read_regs_input_slot_temp);
//上面的方法太low了直接将row的索引传到modbus的线程中去
connect(m_MainWindow, &MainWindow::row_of_bmus_index, m_ModbusRTU, &ModbusRTU::change_BMUIndex_slot);
// ui->btnConnect->setStyleSheet("QPushButton { background-color: #87CEFA; color: white; }"
// "QPushButton:hover { background-color: #77B5D6; color: white; }");
// QMetaObject::invokeMethod(m_ModbusRTU,"read_regs_slot",Qt::QueuedConnection);
// connect(m_ModbusRTU, &ModbusRTU::sig_readMoveToThread, m_ModbusRTU, &ModbusRTU::read_regs_slot, Qt::QueuedConnection);
// thread = new QThread;
// m_ModbusRTU->moveToThread(thread);
// thread->start();
}
void DialogLogin::serialInit()
{
connect(m_Serial, SIGNAL(comChangeStatus(QString,bool)), this, SLOT(slot_comChangeStatus(QString,bool)));
if(ini->contains("Serial/SerialPort") == false || ini->contains("Serial/BaudRate") == false ||
ini->contains("Serial/DataBits") == false || ini->contains("Serial/StopBits") == false ||
ini->contains("Serial/Parity") == false || ini->contains("Serial/FlowControl") == false) {
ui->comboBoxSerialPort->addItems(m_Serial->getAvailablePort());
ui->comboBoxBaudRate->setCurrentIndex(3);
ui->comboBoxDataBits->setCurrentIndex(3);
ui->comboBoxStopBits->setCurrentIndex(0);
ui->comboBoxParity->setCurrentIndex(0);
ui->comboBoxLanguage->setCurrentIndex(ini->value("System/Language").toUInt());
// qDebug() << "lan currentIndex false:" << ini->value("System/Language").toUInt();
}
else {
ui->comboBoxSerialPort->addItems(m_Serial->getAvailablePort());
ui->comboBoxBaudRate->setCurrentIndex(ini->value("Serial/BaudRate").toUInt());
ui->comboBoxDataBits->setCurrentIndex(ini->value("Serial/DataBits").toUInt());
ui->comboBoxStopBits->setCurrentIndex(ini->value("Serial/StopBits").toUInt());
ui->comboBoxParity->setCurrentIndex(ini->value("Serial/Parity").toUInt());
ui->comboBoxLanguage->setCurrentIndex(ini->value("System/Language").toUInt());
// ui->comboBoxLanguage->setCurrentIndex(ini->value());
// qDebug() << "lan currentIndex " << ini->value("System/Language").toUInt();
}
}
void DialogLogin::modbusRTUInit()
{
}
void DialogLogin::mainwindowInit()
{
connect(m_MainWindow, &MainWindow::showLogin, this, [=]{
this->show();
});
// connect(this, &DialogLogin::finished, m_MainWindow, [=]{
// m_MainWindow->ui->btnSetup->setStyleSheet("#btnSetup{"
// "background-image: url(:/Image/advance-set-line.png);"
// "background-repeat: no-repeat;"
// "background-position: center;"
// "background-color: rgba(255, 255, 255, 0);"
// "}"
// "#btnSetup::hover{"
// "background-image: url(:/Image/advance-set-line1.png);"
// "background-repeat: no-repeat;"
// "background-position: center;"
// "background-color: rgba(255, 255, 255, 0);"
// "}");
// });
// connect(m_MainWindow->ui->btnSetup, &QPushButton::pressed, this, [=]{
// qDebug() << __FUNCTION__ << "disconnected";
// m_ModbusRTU->isConnect = false;
// m_MainWindow->statusBarConnectedIcon->setPixmap(QPixmap(QIcon(":/Image/connected1.png").pixmap(QSize(24, 24))));
// m_Serial->m_SerialPort->close();
// m_ModbusRTU->modbusRTUDisconnect();
// ui->comboBoxSerialPort->clear();
// ui->comboBoxSerialPort->addItems(m_Serial->getAvailablePort());
// });
}
void DialogLogin::slot_comChangeStatus(QString name, bool flag)
{
Q_UNUSED(name);
Q_UNUSED(flag);
ui->comboBoxSerialPort->clear();
ui->comboBoxSerialPort->addItems(m_Serial->getAvailablePort());
}
void DialogLogin::slot_btnConnect_clicked()
{
ini->setValue("Serial/BaudRate", ui->comboBoxBaudRate->currentIndex());
ini->setValue("Serial/DataBits", ui->comboBoxDataBits->currentIndex());
ini->setValue("Serial/StopBits", ui->comboBoxStopBits->currentIndex());
ini->setValue("Serial/Parity", ui->comboBoxParity->currentIndex());
ini->sync();
// BCUNumbers = ui->comboBoxBCUQuantity->currentText().toInt();
QString language = ui->comboBoxLanguage->currentText();
if (language == "English")
{
qDebug() << "ini lanuage index" << ini->value("System/Language");
ini->setValue("System/Language", 1);
ini->sync();
QTranslator trans;
emit sendLanNumberSignals(0);
trans.load(":/Language/BatteryMonitor_ENG.qm");
QApplication::installTranslator(&trans);
m_MainWindow->ui->retranslateUi(m_MainWindow);
}
else if (language == "Chinese")
{
qDebug() << "ini lanuage index" << ini->value("System/Language");
ini->setValue("System/Language", 0);
ini->sync();
emit sendLanNumberSignals(1);
QTranslator trans;
trans.load(":/Language/BatteryMonitor_CHN.qm");
QApplication::installTranslator(&trans);
m_MainWindow->ui->retranslateUi(m_MainWindow);
}
emit sendBCUNumberSignals(BCUNumbers);
connect(this, &DialogLogin::sendBCUNumberSignals, m_MainWindow, &MainWindow::slot_getBcuNumberFromDialoglogin);
if(m_Serial->getAvailablePort().size() == 0) {
if(ini->value("System/Language") == MainWindow::LANGUAGE_ENG) {
QMessageBox::critical(this, "Connect Filed", "No Available Serial");
}
else if(ini->value("System/Language") == MainWindow::LANGUAGE_CHN) {
QMessageBox::critical(this, "连接失败", "没有可用的串口");
}
return;
}
else {
int index = ui->comboBoxSerialPort->currentText().indexOf("(");
QString portName = ui->comboBoxSerialPort->currentText().left(index);
ini->setValue("Serial/SerialPort", portName);
m_ModbusRTU->comPort = portName.toStdString().c_str();
m_Serial->m_SerialPort->setPortName(portName);
if(ui->comboBoxBaudRate->currentText() == "1200") {
m_ModbusRTU->baudRate = 1200;
}
else if(ui->comboBoxBaudRate->currentText() == "2400") {
m_ModbusRTU->baudRate = 2400;
}
else if(ui->comboBoxBaudRate->currentText() == "4800") {
m_ModbusRTU->baudRate = 4800;
}
else if(ui->comboBoxBaudRate->currentText() == "9600") {
m_ModbusRTU->baudRate = 9600;
}
else if(ui->comboBoxBaudRate->currentText() == "19200") {
m_ModbusRTU->baudRate = 19200;
}
else if(ui->comboBoxBaudRate->currentText() == "38400") {
m_ModbusRTU->baudRate = 38400;
}
else if(ui->comboBoxBaudRate->currentText() == "57600") {
m_ModbusRTU->baudRate = 57600;
}
else if(ui->comboBoxBaudRate->currentText() == "115200") {
m_ModbusRTU->baudRate = 115200;
}
if(ui->comboBoxDataBits->currentText() == "5") {
m_ModbusRTU->dataBit = 5;
}
else if(ui->comboBoxDataBits->currentText() == "6") {
m_ModbusRTU->dataBit = 6;
}
else if(ui->comboBoxDataBits->currentText() == "7") {
m_ModbusRTU->dataBit = 7;
}
else if(ui->comboBoxDataBits->currentText() == "8") {
m_ModbusRTU->dataBit = 8;
}
if(ui->comboBoxStopBits->currentText() == "1") {
m_ModbusRTU->stopBit = 1;
}
else if(ui->comboBoxStopBits->currentText() == "2") {
m_ModbusRTU->stopBit = 2;
}
if(ui->comboBoxParity->currentText() == "None") {
m_ModbusRTU->parity = 'N';
}
else if(ui->comboBoxParity->currentText() == "Odd") {
m_ModbusRTU->parity = 'O';
}
else if(ui->comboBoxParity->currentText() == "Even") {
m_ModbusRTU->parity = 'E';
}
bool ret = m_ModbusRTU->modbusRTUConnect(m_ModbusRTU->comPort, m_ModbusRTU->baudRate, m_ModbusRTU->parity, m_ModbusRTU->dataBit, m_ModbusRTU->stopBit);
if(ret == true) {
qDebug() << __FUNCTION__ << "connected";
m_ModbusRTU->isConnect = true;
m_MainWindow->statusBarConnectedIcon->setPixmap(QPixmap(QIcon(":/Image/connected2.png").pixmap(QSize(24, 24))));
m_MainWindow->show();
// m_MainWindow->showMaximized();
// m_ModbusRTU->start();
m_ModbusRTU->start();
m_MainWindow->showMaximized();
}
else {
if(ini->value("System/Language") == MainWindow::LANGUAGE_ENG) {
QMessageBox::critical(this, "Connect Filed", "Serial prot cannot be opened please check and open it again\n"
"1.Check USB-Serial is connected\n"
"2.Check baud rate is set correctly\n"
"3.Check whether the serial port is being used\n"
"4.Check Modbus proto is true");
}
else if(ini->value("System/Language") == MainWindow::LANGUAGE_CHN) {
QMessageBox::critical(this, "连接失败", "当前串口号无法打开,请检查后重新打开\n"
"1.检查USB串口工具是否连接上电脑\n"
"2.检查波特率是否设置正确\n"
"3.检查串口号是否被占用了\n"
"4.检查Modbus通信协议是否有误");
}
}
this->close();
}
}

View File

@ -1,52 +0,0 @@
#ifndef DIALOGLOGIN_H
#define DIALOGLOGIN_H
#include <QDialog>
namespace Ui {
class DialogLogin;
}
class MainWindow;
class QSerialPort;
class QSettings;
class AppSerial;
class ModbusRTU;
class DialogLogin : public QDialog
{
Q_OBJECT
public:
explicit DialogLogin(QWidget *parent = nullptr);
~DialogLogin();
private:
Ui::DialogLogin *ui;
public:
private:
MainWindow *m_MainWindow;
AppSerial *m_Serial;
ModbusRTU *m_ModbusRTU;
QSettings *ini;
// QThread *thread;
int BCUNumbers;
signals:
void sendBCUNumberSignals(int number);
void sendLanNumberSignals(int number);
private slots:
void slot_comChangeStatus(QString name, bool flag);
void slot_btnConnect_clicked();
private:
void init();
void serialInit();
void modbusRTUInit();
void mainwindowInit();
};
#endif // DIALOGLOGIN_H

View File

@ -1,409 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>DialogLogin</class>
<widget class="QDialog" name="DialogLogin">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>362</width>
<height>444</height>
</rect>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="windowTitle">
<string>Dialog</string>
</property>
<layout class="QGridLayout" name="gridLayout">
<item row="2" column="1">
<widget class="QGroupBox" name="groupBox">
<property name="font">
<font>
<family>黑体</family>
<pointsize>11</pointsize>
</font>
</property>
<property name="title">
<string/>
</property>
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<layout class="QVBoxLayout" name="verticalLayout" stretch="4,7,1,3,3">
<item>
<widget class="QLabel" name="label_bluesunLogo">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string/>
</property>
</widget>
</item>
<item>
<layout class="QGridLayout" name="gridLayout_2">
<item row="0" column="0">
<widget class="QLabel" name="labelBCUQuantity_2">
<property name="font">
<font>
<family>华文中宋</family>
<pointsize>10</pointsize>
</font>
</property>
<property name="text">
<string>Language</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QComboBox" name="comboBoxLanguage">
<property name="font">
<font>
<family>华文中宋</family>
<pointsize>10</pointsize>
</font>
</property>
<item>
<property name="text">
<string>Chinese</string>
</property>
</item>
<item>
<property name="text">
<string>English</string>
</property>
</item>
</widget>
</item>
<item row="1" column="0">
<widget class="QLabel" name="labelSerialPort">
<property name="font">
<font>
<family>华文中宋</family>
<pointsize>10</pointsize>
</font>
</property>
<property name="text">
<string>Serial Port</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QComboBox" name="comboBoxSerialPort">
<property name="font">
<font>
<family>华文中宋</family>
<pointsize>10</pointsize>
</font>
</property>
</widget>
</item>
<item row="2" column="0">
<widget class="QLabel" name="labelBaudRate">
<property name="font">
<font>
<family>华文中宋</family>
<pointsize>10</pointsize>
</font>
</property>
<property name="text">
<string>Baud Rate</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item row="2" column="1">
<widget class="QComboBox" name="comboBoxBaudRate">
<property name="font">
<font>
<family>华文中宋</family>
<pointsize>10</pointsize>
</font>
</property>
<item>
<property name="text">
<string>1200</string>
</property>
</item>
<item>
<property name="text">
<string>2400</string>
</property>
</item>
<item>
<property name="text">
<string>4800</string>
</property>
</item>
<item>
<property name="text">
<string>9600</string>
</property>
</item>
<item>
<property name="text">
<string>19200</string>
</property>
</item>
<item>
<property name="text">
<string>38400</string>
</property>
</item>
<item>
<property name="text">
<string>57600</string>
</property>
</item>
<item>
<property name="text">
<string>115200</string>
</property>
</item>
</widget>
</item>
<item row="3" column="0">
<widget class="QLabel" name="labelDataBits">
<property name="font">
<font>
<family>华文中宋</family>
<pointsize>10</pointsize>
</font>
</property>
<property name="text">
<string>Data Bits</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item row="3" column="1">
<widget class="QComboBox" name="comboBoxDataBits">
<property name="font">
<font>
<family>华文中宋</family>
<pointsize>10</pointsize>
</font>
</property>
<item>
<property name="text">
<string>5</string>
</property>
</item>
<item>
<property name="text">
<string>6</string>
</property>
</item>
<item>
<property name="text">
<string>7</string>
</property>
</item>
<item>
<property name="text">
<string>8</string>
</property>
</item>
</widget>
</item>
<item row="4" column="0">
<widget class="QLabel" name="labelStopBits">
<property name="font">
<font>
<family>华文中宋</family>
<pointsize>10</pointsize>
</font>
</property>
<property name="text">
<string>Stop Bits</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item row="4" column="1">
<widget class="QComboBox" name="comboBoxStopBits">
<property name="font">
<font>
<family>华文中宋</family>
<pointsize>10</pointsize>
</font>
</property>
<item>
<property name="text">
<string>1</string>
</property>
</item>
<item>
<property name="text">
<string>2</string>
</property>
</item>
</widget>
</item>
<item row="5" column="0">
<widget class="QLabel" name="labelParity">
<property name="font">
<font>
<family>华文中宋</family>
<pointsize>10</pointsize>
</font>
</property>
<property name="text">
<string>Parity</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item row="5" column="1">
<widget class="QComboBox" name="comboBoxParity">
<property name="font">
<font>
<family>华文中宋</family>
<pointsize>10</pointsize>
</font>
</property>
<item>
<property name="text">
<string>None</string>
</property>
</item>
<item>
<property name="text">
<string>Odd</string>
</property>
</item>
<item>
<property name="text">
<string>Even</string>
</property>
</item>
</widget>
</item>
</layout>
</item>
<item>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout" stretch="1,1,1">
<item>
<spacer name="horizontalSpacer_2">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QPushButton" name="btnConnect">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>40</width>
<height>0</height>
</size>
</property>
<property name="font">
<font>
<family>Microsoft YaHei UI</family>
<pointsize>12</pointsize>
<italic>false</italic>
<bold>true</bold>
</font>
</property>
<property name="styleSheet">
<string notr="true">font: 700 12pt &quot;Microsoft YaHei UI&quot;;</string>
</property>
<property name="text">
<string>Connect</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
<item>
<widget class="QLabel" name="label_Copyright">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="font">
<font>
<family>幼圆</family>
<pointsize>12</pointsize>
</font>
</property>
<property name="text">
<string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p align=&quot;center&quot;&gt;Copyright © 2016 Bluesun Solar Co.Ltd &lt;/p&gt;&lt;p align=&quot;center&quot;&gt;All Rights Reserved.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui>

BIN
iconengines/qsvgicon.dll Normal file

Binary file not shown.

View File

@ -1,41 +0,0 @@
<RCC>
<qresource prefix="/">
<file>Image/icon.png</file>
<file>Image/advance-set-line.png</file>
<file>Image/advance-set-line1.png</file>
<file>Image/advance-set-line2.png</file>
<file>Image/battery.png</file>
<file>Image/battery1.png</file>
<file>Image/battery2.png</file>
<file>Image/connected.png</file>
<file>Image/connected1.png</file>
<file>Image/connected2.png</file>
<file>Image/hardware-line.png</file>
<file>Image/hardware-line1.png</file>
<file>Image/hardware-line2.png</file>
<file>Image/monitor.png</file>
<file>Image/monitor1.png</file>
<file>Image/monitor2.png</file>
<file>Image/home.png</file>
<file>Image/home1.png</file>
<file>Image/home2.png</file>
<file>Image/debug.png</file>
<file>Image/debug1.png</file>
<file>Image/debug2.png</file>
<file>Image/paraSet.png</file>
<file>Image/paraSet1.png</file>
<file>Image/paraSet2.png</file>
<file>Image/curIcon.png</file>
<file>Image/trouble-background-3.png</file>
<file>Image/voltageIcon.png</file>
<file>Image/trouble-background-default.png</file>
<file>Image/trouble-background-normal.png</file>
<file>Image/trouble-background-2.png</file>
<file>Image/trouble-background-1.png</file>
<file>Image/record-out-black.png</file>
<file>Image/record-out-gray.png</file>
<file>Image/record-out-green.png</file>
<file>Image/bluesun.png</file>
<file>Image/bunuo.png</file>
</qresource>
</RCC>

BIN
imageformats/qgif.dll Normal file

Binary file not shown.

BIN
imageformats/qicns.dll Normal file

Binary file not shown.

BIN
imageformats/qico.dll Normal file

Binary file not shown.

BIN
imageformats/qjpeg.dll Normal file

Binary file not shown.

BIN
imageformats/qsvg.dll Normal file

Binary file not shown.

BIN
imageformats/qtga.dll Normal file

Binary file not shown.

BIN
imageformats/qtiff.dll Normal file

Binary file not shown.

BIN
imageformats/qwbmp.dll Normal file

Binary file not shown.

BIN
imageformats/qwebp.dll Normal file

Binary file not shown.

View File

@ -1,6 +0,0 @@
<RCC>
<qresource prefix="/">
<file>Language/BatteryMonitor_CHN.qm</file>
<file>Language/BatteryMonitor_ENG.qm</file>
</qresource>
</RCC>

BIN
libEGL.dll Normal file

Binary file not shown.

BIN
libGLESv2.dll Normal file

Binary file not shown.

BIN
libgcc_s_seh-1.dll Normal file

Binary file not shown.

View File

@ -1,292 +0,0 @@
/* config.h. Generated from config.h.in by configure. */
/* config.h.in. Generated from configure.ac by autoheader. */
/* Define to 1 if you have the `accept4' function. */
/* #undef HAVE_ACCEPT4 */
/* Define to 1 if you have the <arpa/inet.h> header file. */
/* #undef HAVE_ARPA_INET_H */
/* Define to 1 if you have the <byteswap.h> header file. */
/* #undef HAVE_BYTESWAP_H */
/* Define to 1 if you have the declaration of `TIOCM_RTS', and to 0 if you
don't. */
#define HAVE_DECL_TIOCM_RTS 0
/* Define to 1 if you have the declaration of `TIOCSRS485', and to 0 if you
don't. */
#define HAVE_DECL_TIOCSRS485 0
/* Define to 1 if you have the declaration of `__CYGWIN__', and to 0 if you
don't. */
#define HAVE_DECL___CYGWIN__ 0
/* Define to 1 if you have the <dlfcn.h> header file. */
/* #undef HAVE_DLFCN_H */
/* Define to 1 if you have the <errno.h> header file. */
#define HAVE_ERRNO_H 1
/* Define to 1 if you have the <fcntl.h> header file. */
#define HAVE_FCNTL_H 1
/* Define to 1 if you have the `getaddrinfo' function. */
/* #undef HAVE_GETADDRINFO */
/* Define to 1 if you have the `gettimeofday' function. */
#define HAVE_GETTIMEOFDAY 1
/* Define to 1 if you have the `inet_ntop' function. */
/* #undef HAVE_INET_NTOP */
/* Define to 1 if you have the `inet_pton' function. */
/* #undef HAVE_INET_PTON */
/* Define to 1 if you have the <inttypes.h> header file. */
#define HAVE_INTTYPES_H 1
/* Define to 1 if you have the <limits.h> header file. */
#define HAVE_LIMITS_H 1
/* Define to 1 if you have the <linux/serial.h> header file. */
/* #undef HAVE_LINUX_SERIAL_H */
/* Define to 1 if you have the <minix/config.h> header file. */
/* #undef HAVE_MINIX_CONFIG_H */
/* Define to 1 if you have the <netdb.h> header file. */
/* #undef HAVE_NETDB_H */
/* Define to 1 if you have the <netinet/in.h> header file. */
/* #undef HAVE_NETINET_IN_H */
/* Define to 1 if you have the <netinet/tcp.h> header file. */
/* #undef HAVE_NETINET_TCP_H */
/* Define to 1 if you have the `select' function. */
/* #undef HAVE_SELECT */
/* Define to 1 if you have the `socket' function. */
/* #undef HAVE_SOCKET */
/* Define to 1 if you have the <stdint.h> header file. */
#define HAVE_STDINT_H 1
/* Define to 1 if you have the <stdio.h> header file. */
#define HAVE_STDIO_H 1
/* Define to 1 if you have the <stdlib.h> header file. */
#define HAVE_STDLIB_H 1
/* Define to 1 if you have the `strerror' function. */
#define HAVE_STRERROR 1
/* Define to 1 if you have the <strings.h> header file. */
#define HAVE_STRINGS_H 1
/* Define to 1 if you have the <string.h> header file. */
#define HAVE_STRING_H 1
/* Define to 1 if you have the `strlcpy' function. */
/* #undef HAVE_STRLCPY */
/* Define to 1 if you have the <sys/ioctl.h> header file. */
/* #undef HAVE_SYS_IOCTL_H */
/* Define to 1 if you have the <sys/params.h> header file. */
/* #undef HAVE_SYS_PARAMS_H */
/* Define to 1 if you have the <sys/socket.h> header file. */
/* #undef HAVE_SYS_SOCKET_H */
/* Define to 1 if you have the <sys/stat.h> header file. */
#define HAVE_SYS_STAT_H 1
/* Define to 1 if you have the <sys/time.h> header file. */
#define HAVE_SYS_TIME_H 1
/* Define to 1 if you have the <sys/types.h> header file. */
#define HAVE_SYS_TYPES_H 1
/* Define to 1 if you have the <termios.h> header file. */
/* #undef HAVE_TERMIOS_H */
/* Define to 1 if you have the <time.h> header file. */
#define HAVE_TIME_H 1
/* Define to 1 if you have the <unistd.h> header file. */
#define HAVE_UNISTD_H 1
/* Define to 1 if you have the <wchar.h> header file. */
#define HAVE_WCHAR_H 1
/* Define to 1 if you have the <winsock2.h> header file. */
#define HAVE_WINSOCK2_H 1
/* Define to the sub-directory where libtool stores uninstalled libraries. */
#define LT_OBJDIR ".libs/"
/* Name of package */
#define PACKAGE "libmodbus"
/* Define to the address where bug reports for this package should be sent. */
#define PACKAGE_BUGREPORT "https://github.com/stephane/libmodbus/issues"
/* Define to the full name of this package. */
#define PACKAGE_NAME "libmodbus"
/* Define to the full name and version of this package. */
#define PACKAGE_STRING "libmodbus 3.1.10"
/* Define to the one symbol short name of this package. */
#define PACKAGE_TARNAME "libmodbus"
/* Define to the home page for this package. */
#define PACKAGE_URL "http://libmodbus.org/"
/* Define to the version of this package. */
#define PACKAGE_VERSION "3.1.10"
/* Define to 1 if all of the C90 standard headers exist (not just the ones
required in a freestanding environment). This macro is provided for
backward compatibility; new code need not use it. */
#define STDC_HEADERS 1
/* Enable extensions on AIX 3, Interix. */
#ifndef _ALL_SOURCE
# define _ALL_SOURCE 1
#endif
/* Enable general extensions on macOS. */
#ifndef _DARWIN_C_SOURCE
# define _DARWIN_C_SOURCE 1
#endif
/* Enable general extensions on Solaris. */
#ifndef __EXTENSIONS__
# define __EXTENSIONS__ 1
#endif
/* Enable GNU extensions on systems that have them. */
#ifndef _GNU_SOURCE
# define _GNU_SOURCE 1
#endif
/* Enable X/Open compliant socket functions that do not require linking
with -lxnet on HP-UX 11.11. */
#ifndef _HPUX_ALT_XOPEN_SOCKET_API
# define _HPUX_ALT_XOPEN_SOCKET_API 1
#endif
/* Identify the host operating system as Minix.
This macro does not affect the system headers' behavior.
A future release of Autoconf may stop defining this macro. */
#ifndef _MINIX
/* # undef _MINIX */
#endif
/* Enable general extensions on NetBSD.
Enable NetBSD compatibility extensions on Minix. */
#ifndef _NETBSD_SOURCE
# define _NETBSD_SOURCE 1
#endif
/* Enable OpenBSD compatibility extensions on NetBSD.
Oddly enough, this does nothing on OpenBSD. */
#ifndef _OPENBSD_SOURCE
# define _OPENBSD_SOURCE 1
#endif
/* Define to 1 if needed for POSIX-compatible behavior. */
#ifndef _POSIX_SOURCE
/* # undef _POSIX_SOURCE */
#endif
/* Define to 2 if needed for POSIX-compatible behavior. */
#ifndef _POSIX_1_SOURCE
/* # undef _POSIX_1_SOURCE */
#endif
/* Enable POSIX-compatible threading on Solaris. */
#ifndef _POSIX_PTHREAD_SEMANTICS
# define _POSIX_PTHREAD_SEMANTICS 1
#endif
/* Enable extensions specified by ISO/IEC TS 18661-5:2014. */
#ifndef __STDC_WANT_IEC_60559_ATTRIBS_EXT__
# define __STDC_WANT_IEC_60559_ATTRIBS_EXT__ 1
#endif
/* Enable extensions specified by ISO/IEC TS 18661-1:2014. */
#ifndef __STDC_WANT_IEC_60559_BFP_EXT__
# define __STDC_WANT_IEC_60559_BFP_EXT__ 1
#endif
/* Enable extensions specified by ISO/IEC TS 18661-2:2015. */
#ifndef __STDC_WANT_IEC_60559_DFP_EXT__
# define __STDC_WANT_IEC_60559_DFP_EXT__ 1
#endif
/* Enable extensions specified by ISO/IEC TS 18661-4:2015. */
#ifndef __STDC_WANT_IEC_60559_FUNCS_EXT__
# define __STDC_WANT_IEC_60559_FUNCS_EXT__ 1
#endif
/* Enable extensions specified by ISO/IEC TS 18661-3:2015. */
#ifndef __STDC_WANT_IEC_60559_TYPES_EXT__
# define __STDC_WANT_IEC_60559_TYPES_EXT__ 1
#endif
/* Enable extensions specified by ISO/IEC TR 24731-2:2010. */
#ifndef __STDC_WANT_LIB_EXT2__
# define __STDC_WANT_LIB_EXT2__ 1
#endif
/* Enable extensions specified by ISO/IEC 24747:2009. */
#ifndef __STDC_WANT_MATH_SPEC_FUNCS__
# define __STDC_WANT_MATH_SPEC_FUNCS__ 1
#endif
/* Enable extensions on HP NonStop. */
#ifndef _TANDEM_SOURCE
# define _TANDEM_SOURCE 1
#endif
/* Enable X/Open extensions. Define to 500 only if necessary
to make mbstate_t available. */
#ifndef _XOPEN_SOURCE
/* # undef _XOPEN_SOURCE */
#endif
/* Version number of package */
#define VERSION "3.1.10"
/* _ */
#define WINVER 0x0501
/* Number of bits in a file offset, on hosts where this is settable. */
#define _FILE_OFFSET_BITS 64
/* Define for large files, on AIX-style hosts. */
/* #undef _LARGE_FILES */
/* Define for Solaris 2.5.1 so the uint32_t typedef from <sys/synch.h>,
<pthread.h>, or <semaphore.h> is not used. If the typedef were allowed, the
#define below would cause a syntax error. */
/* #undef _UINT32_T */
/* Define for Solaris 2.5.1 so the uint8_t typedef from <sys/synch.h>,
<pthread.h>, or <semaphore.h> is not used. If the typedef were allowed, the
#define below would cause a syntax error. */
/* #undef _UINT8_T */
/* Define to `__inline__' or `__inline' if that's what the C compiler
calls it, or to nothing if 'inline' is not supported under any name. */
#ifndef __cplusplus
/* #undef inline */
#endif
/* Define to the type of a signed integer type of width exactly 64 bits if
such a type exists and the standard includes do not define it. */
/* #undef int64_t */
/* Define to `unsigned int' if <sys/types.h> does not define. */
/* #undef size_t */
/* Define to `int' if <sys/types.h> does not define. */
/* #undef ssize_t */
/* Define to the type of an unsigned integer type of width exactly 16 bits if
such a type exists and the standard includes do not define it. */
/* #undef uint16_t */
/* Define to the type of an unsigned integer type of width exactly 32 bits if
such a type exists and the standard includes do not define it. */
/* #undef uint32_t */
/* Define to the type of an unsigned integer type of width exactly 8 bits if
such a type exists and the standard includes do not define it. */
/* #undef uint8_t */

View File

@ -1,125 +0,0 @@
/*
* Copyright © Stéphane Raimbault <stephane.raimbault@gmail.com>
*
* SPDX-License-Identifier: LGPL-2.1-or-later
*/
#ifndef MODBUS_PRIVATE_H
#define MODBUS_PRIVATE_H
// clang-format off
#ifndef _MSC_VER
# include <stdint.h>
# include <sys/time.h>
#else
# include "stdint.h"
# include <time.h>
typedef int ssize_t;
#endif
// clang-format on
#include <config.h>
#include <sys/types.h>
#include "modbus.h"
MODBUS_BEGIN_DECLS
/* It's not really the minimal length (the real one is report slave ID
* in RTU (4 bytes)) but it's a convenient size to use in RTU or TCP
* communications to read many values or write a single one.
* Maximum between :
* - HEADER_LENGTH_TCP (7) + function (1) + address (2) + number (2)
* - HEADER_LENGTH_RTU (1) + function (1) + address (2) + number (2) + CRC (2)
*/
#define _MIN_REQ_LENGTH 12
#define _REPORT_SLAVE_ID 180
#define _MODBUS_EXCEPTION_RSP_LENGTH 5
/* Timeouts in microsecond (0.5 s) */
#define _RESPONSE_TIMEOUT 500000
#define _BYTE_TIMEOUT 500000
typedef enum {
_MODBUS_BACKEND_TYPE_RTU = 0,
_MODBUS_BACKEND_TYPE_TCP
} modbus_backend_type_t;
/*
* ---------- Request Indication ----------
* | Client | ---------------------->| Server |
* ---------- Confirmation Response ----------
*/
typedef enum {
/* Request message on the server side */
MSG_INDICATION,
/* Request message on the client side */
MSG_CONFIRMATION
} msg_type_t;
/* This structure reduces the number of params in functions and so
* optimizes the speed of execution (~ 37%). */
typedef struct _sft {
int slave;
int function;
int t_id;
} sft_t;
typedef struct _modbus_backend {
unsigned int backend_type;
unsigned int header_length;
unsigned int checksum_length;
unsigned int max_adu_length;
int (*set_slave)(modbus_t *ctx, int slave);
int (*build_request_basis)(
modbus_t *ctx, int function, int addr, int nb, uint8_t *req);
int (*build_response_basis)(sft_t *sft, uint8_t *rsp);
int (*prepare_response_tid)(const uint8_t *req, int *req_length);
int (*send_msg_pre)(uint8_t *req, int req_length);
ssize_t (*send)(modbus_t *ctx, const uint8_t *req, int req_length);
int (*receive)(modbus_t *ctx, uint8_t *req);
ssize_t (*recv)(modbus_t *ctx, uint8_t *rsp, int rsp_length);
int (*check_integrity)(modbus_t *ctx, uint8_t *msg, const int msg_length);
int (*pre_check_confirmation)(modbus_t *ctx,
const uint8_t *req,
const uint8_t *rsp,
int rsp_length);
int (*connect)(modbus_t *ctx);
unsigned int (*is_connected)(modbus_t *ctx);
void (*close)(modbus_t *ctx);
int (*flush)(modbus_t *ctx);
int (*select)(modbus_t *ctx, fd_set *rset, struct timeval *tv, int msg_length);
void (*free)(modbus_t *ctx);
} modbus_backend_t;
struct _modbus {
/* Slave address */
int slave;
/* Socket or file descriptor */
int s;
int debug;
int error_recovery;
int quirks;
struct timeval response_timeout;
struct timeval byte_timeout;
struct timeval indication_timeout;
const modbus_backend_t *backend;
void *backend_data;
uint8_t *sendMsg;
int sendMsgLen;
uint8_t *recvMsg;
int recvMsgLen;
};
void _modbus_init_common(modbus_t *ctx);
void _error_print(modbus_t *ctx, const char *context);
int _modbus_receive_msg(modbus_t *ctx, uint8_t *msg, msg_type_t msg_type);
#ifndef HAVE_STRLCPY
size_t strlcpy(char *dest, const char *src, size_t dest_size);
#endif
MODBUS_END_DECLS
#endif /* MODBUS_PRIVATE_H */

View File

@ -1,77 +0,0 @@
/*
* Copyright © Stéphane Raimbault <stephane.raimbault@gmail.com>
*
* SPDX-License-Identifier: LGPL-2.1-or-later
*/
#ifndef MODBUS_RTU_PRIVATE_H
#define MODBUS_RTU_PRIVATE_H
#ifndef _MSC_VER
#include <stdint.h>
#else
#include "stdint.h"
#endif
#if defined(_WIN32)
#include <windows.h>
#else
#include <termios.h>
#endif
#define _MODBUS_RTU_HEADER_LENGTH 1
#define _MODBUS_RTU_PRESET_REQ_LENGTH 6
#define _MODBUS_RTU_PRESET_RSP_LENGTH 2
#define _MODBUS_RTU_CHECKSUM_LENGTH 2
#if defined(_WIN32)
#if !defined(ENOTSUP)
#define ENOTSUP WSAEOPNOTSUPP
#endif
/* WIN32: struct containing serial handle and a receive buffer */
#define PY_BUF_SIZE 512
struct win32_ser {
/* File handle */
HANDLE fd;
/* Receive buffer */
uint8_t buf[PY_BUF_SIZE];
/* Received chars */
DWORD n_bytes;
};
#endif /* _WIN32 */
typedef struct _modbus_rtu {
/* Device: "/dev/ttyS0", "/dev/ttyUSB0" or "/dev/tty.USA19*" on Mac OS X. */
char *device;
/* Bauds: 9600, 19200, 57600, 115200, etc */
int baud;
/* Data bit */
uint8_t data_bit;
/* Stop bit */
uint8_t stop_bit;
/* Parity: 'N', 'O', 'E' */
char parity;
#if defined(_WIN32)
struct win32_ser w_ser;
DCB old_dcb;
#else
/* Save old termios settings */
struct termios old_tios;
#endif
#if HAVE_DECL_TIOCSRS485
int serial_mode;
#endif
#if HAVE_DECL_TIOCM_RTS
int rts;
int rts_delay;
int onebyte_time;
void (*set_rts)(modbus_t *ctx, int on);
#endif
/* To handle many slaves on the same link */
int confirmation_to_ignore;
} modbus_rtu_t;
#endif /* MODBUS_RTU_PRIVATE_H */

View File

@ -1,43 +0,0 @@
/*
* Copyright © Stéphane Raimbault <stephane.raimbault@gmail.com>
*
* SPDX-License-Identifier: LGPL-2.1-or-later
*/
#ifndef MODBUS_RTU_H
#define MODBUS_RTU_H
#include "modbus.h"
MODBUS_BEGIN_DECLS
/* Modbus_Application_Protocol_V1_1b.pdf Chapter 4 Section 1 Page 5
* RS232 / RS485 ADU = 253 bytes + slave (1 byte) + CRC (2 bytes) = 256 bytes
*/
#define MODBUS_RTU_MAX_ADU_LENGTH 256
MODBUS_API modbus_t *
modbus_new_rtu(const char *device, int baud, char parity, int data_bit, int stop_bit);
#define MODBUS_RTU_RS232 0
#define MODBUS_RTU_RS485 1
MODBUS_API int modbus_rtu_set_serial_mode(modbus_t *ctx, int mode);
MODBUS_API int modbus_rtu_get_serial_mode(modbus_t *ctx);
#define MODBUS_RTU_RTS_NONE 0
#define MODBUS_RTU_RTS_UP 1
#define MODBUS_RTU_RTS_DOWN 2
MODBUS_API int modbus_rtu_set_rts(modbus_t *ctx, int mode);
MODBUS_API int modbus_rtu_get_rts(modbus_t *ctx);
MODBUS_API int modbus_rtu_set_custom_rts(modbus_t *ctx,
void (*set_rts)(modbus_t *ctx, int on));
MODBUS_API int modbus_rtu_set_rts_delay(modbus_t *ctx, int us);
MODBUS_API int modbus_rtu_get_rts_delay(modbus_t *ctx);
MODBUS_END_DECLS
#endif /* MODBUS_RTU_H */

View File

@ -1,41 +0,0 @@
/*
* Copyright © Stéphane Raimbault <stephane.raimbault@gmail.com>
*
* SPDX-License-Identifier: LGPL-2.1-or-later
*/
#ifndef MODBUS_TCP_PRIVATE_H
#define MODBUS_TCP_PRIVATE_H
#define _MODBUS_TCP_HEADER_LENGTH 7
#define _MODBUS_TCP_PRESET_REQ_LENGTH 12
#define _MODBUS_TCP_PRESET_RSP_LENGTH 8
#define _MODBUS_TCP_CHECKSUM_LENGTH 0
/* In both structures, the transaction ID must be placed on first position
to have a quick access not dependent of the TCP backend */
typedef struct _modbus_tcp {
/* Extract from MODBUS Messaging on TCP/IP Implementation Guide V1.0b
(page 23/46):
The transaction identifier is used to associate the future response
with the request. This identifier is unique on each TCP connection. */
uint16_t t_id;
/* TCP port */
int port;
/* IP address */
char ip[16];
} modbus_tcp_t;
typedef struct _modbus_tcp_pi {
/* Transaction ID */
uint16_t t_id;
/* TCP port */
int port;
/* Node */
char *node;
/* Service */
char *service;
} modbus_tcp_pi_t;
#endif /* MODBUS_TCP_PRIVATE_H */

View File

@ -1,52 +0,0 @@
/*
* Copyright © Stéphane Raimbault <stephane.raimbault@gmail.com>
*
* SPDX-License-Identifier: LGPL-2.1-or-later
*/
#ifndef MODBUS_TCP_H
#define MODBUS_TCP_H
#include "modbus.h"
MODBUS_BEGIN_DECLS
#if defined(_WIN32) && !defined(__CYGWIN__)
/* Win32 with MinGW, supplement to <errno.h> */
#include <winsock2.h>
#if !defined(ECONNRESET)
#define ECONNRESET WSAECONNRESET
#endif
#if !defined(ECONNREFUSED)
#define ECONNREFUSED WSAECONNREFUSED
#endif
#if !defined(ETIMEDOUT)
#define ETIMEDOUT WSAETIMEDOUT
#endif
#if !defined(ENOPROTOOPT)
#define ENOPROTOOPT WSAENOPROTOOPT
#endif
#if !defined(EINPROGRESS)
#define EINPROGRESS WSAEINPROGRESS
#endif
#endif
#define MODBUS_TCP_DEFAULT_PORT 502
#define MODBUS_TCP_SLAVE 0xFF
/* Modbus_Application_Protocol_V1_1b.pdf Chapter 4 Section 1 Page 5
* TCP MODBUS ADU = 253 bytes + MBAP (7 bytes) = 260 bytes
*/
#define MODBUS_TCP_MAX_ADU_LENGTH 260
MODBUS_API modbus_t *modbus_new_tcp(const char *ip_address, int port);
MODBUS_API int modbus_tcp_listen(modbus_t *ctx, int nb_connection);
MODBUS_API int modbus_tcp_accept(modbus_t *ctx, int *s);
MODBUS_API modbus_t *modbus_new_tcp_pi(const char *node, const char *service);
MODBUS_API int modbus_tcp_pi_listen(modbus_t *ctx, int nb_connection);
MODBUS_API int modbus_tcp_pi_accept(modbus_t *ctx, int *s);
MODBUS_END_DECLS
#endif /* MODBUS_TCP_H */

View File

@ -1,51 +0,0 @@
/*
* Copyright © Stéphane Raimbault <stephane.raimbault@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef MODBUS_VERSION_H
#define MODBUS_VERSION_H
/* The major version, (1, if %LIBMODBUS_VERSION is 1.2.3) */
#define LIBMODBUS_VERSION_MAJOR (3)
/* The minor version (2, if %LIBMODBUS_VERSION is 1.2.3) */
#define LIBMODBUS_VERSION_MINOR (1)
/* The micro version (3, if %LIBMODBUS_VERSION is 1.2.3) */
#define LIBMODBUS_VERSION_MICRO (10)
/* The full version, like 1.2.3 */
#define LIBMODBUS_VERSION 3.1.10
/* The full version, in string form (suited for string concatenation)
*/
#define LIBMODBUS_VERSION_STRING "3.1.10"
/* Numerically encoded version, eg. v1.2.3 is 0x010203 */
#define LIBMODBUS_VERSION_HEX \
((LIBMODBUS_VERSION_MAJOR << 16) | (LIBMODBUS_VERSION_MINOR << 8) | \
(LIBMODBUS_VERSION_MICRO << 0))
/* Evaluates to True if the version is greater than @major, @minor and @micro
*/
#define LIBMODBUS_VERSION_CHECK(major, minor, micro) \
(LIBMODBUS_VERSION_MAJOR > (major) || \
(LIBMODBUS_VERSION_MAJOR == (major) && LIBMODBUS_VERSION_MINOR > (minor)) || \
(LIBMODBUS_VERSION_MAJOR == (major) && LIBMODBUS_VERSION_MINOR == (minor) && \
LIBMODBUS_VERSION_MICRO >= (micro)))
#endif /* MODBUS_VERSION_H */

View File

@ -1,329 +0,0 @@
/*
* Copyright © Stéphane Raimbault <stephane.raimbault@gmail.com>
*
* SPDX-License-Identifier: LGPL-2.1-or-later
*/
#ifndef MODBUS_H
#define MODBUS_H
// clang-format off
/* Add this for macros that defined unix flavor */
#if (defined(__unix__) || defined(unix)) && !defined(USG)
# include <sys/param.h>
#endif
#ifndef _MSC_VER
# include <stdint.h>
#else
# include "stdint.h"
#endif
#include "modbus-version.h"
#if defined(_MSC_VER)
# if defined(DLLBUILD)
/* define DLLBUILD when building the DLL */
# define MODBUS_API __declspec(dllexport)
# else
# define MODBUS_API __declspec(dllimport)
# endif
#else
# define MODBUS_API
#endif
#ifdef __cplusplus
# define MODBUS_BEGIN_DECLS extern "C" {
# define MODBUS_END_DECLS }
#else
# define MODBUS_BEGIN_DECLS
# define MODBUS_END_DECLS
#endif
// clang-format on
MODBUS_BEGIN_DECLS
#ifndef FALSE
#define FALSE 0
#endif
#ifndef TRUE
#define TRUE 1
#endif
#ifndef OFF
#define OFF 0
#endif
#ifndef ON
#define ON 1
#endif
/* Modbus function codes */
#define MODBUS_FC_READ_COILS 0x01
#define MODBUS_FC_READ_DISCRETE_INPUTS 0x02
#define MODBUS_FC_READ_HOLDING_REGISTERS 0x03
#define MODBUS_FC_READ_INPUT_REGISTERS 0x04
#define MODBUS_FC_WRITE_SINGLE_COIL 0x05
#define MODBUS_FC_WRITE_SINGLE_REGISTER 0x06
#define MODBUS_FC_READ_EXCEPTION_STATUS 0x07
#define MODBUS_FC_WRITE_MULTIPLE_COILS 0x0F
#define MODBUS_FC_WRITE_MULTIPLE_REGISTERS 0x10
#define MODBUS_FC_REPORT_SLAVE_ID 0x11
#define MODBUS_FC_MASK_WRITE_REGISTER 0x16
#define MODBUS_FC_WRITE_AND_READ_REGISTERS 0x17
#define MODBUS_BROADCAST_ADDRESS 0
/* Modbus_Application_Protocol_V1_1b.pdf (chapter 6 section 1 page 12)
* Quantity of Coils to read (2 bytes): 1 to 2000 (0x7D0)
* (chapter 6 section 11 page 29)
* Quantity of Coils to write (2 bytes): 1 to 1968 (0x7B0)
*/
#define MODBUS_MAX_READ_BITS 2000
#define MODBUS_MAX_WRITE_BITS 1968
/* Modbus_Application_Protocol_V1_1b.pdf (chapter 6 section 3 page 15)
* Quantity of Registers to read (2 bytes): 1 to 125 (0x7D)
* (chapter 6 section 12 page 31)
* Quantity of Registers to write (2 bytes) 1 to 123 (0x7B)
* (chapter 6 section 17 page 38)
* Quantity of Registers to write in R/W registers (2 bytes) 1 to 121 (0x79)
*/
#define MODBUS_MAX_READ_REGISTERS 125
#define MODBUS_MAX_WRITE_REGISTERS 123
#define MODBUS_MAX_WR_WRITE_REGISTERS 121
#define MODBUS_MAX_WR_READ_REGISTERS 125
/* The size of the MODBUS PDU is limited by the size constraint inherited from
* the first MODBUS implementation on Serial Line network (max. RS485 ADU = 256
* bytes). Therefore, MODBUS PDU for serial line communication = 256 - Server
* address (1 byte) - CRC (2 bytes) = 253 bytes.
*/
#define MODBUS_MAX_PDU_LENGTH 253
/* Consequently:
* - RTU MODBUS ADU = 253 bytes + Server address (1 byte) + CRC (2 bytes) = 256
* bytes.
* - TCP MODBUS ADU = 253 bytes + MBAP (7 bytes) = 260 bytes.
* so the maximum of both backend in 260 bytes. This size can used to allocate
* an array of bytes to store responses and it will be compatible with the two
* backends.
*/
#define MODBUS_MAX_ADU_LENGTH 260
/* Random number to avoid errno conflicts */
#define MODBUS_ENOBASE 112345678
/* Protocol exceptions */
enum {
MODBUS_EXCEPTION_ILLEGAL_FUNCTION = 0x01,
MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS,
MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE,
MODBUS_EXCEPTION_SLAVE_OR_SERVER_FAILURE,
MODBUS_EXCEPTION_ACKNOWLEDGE,
MODBUS_EXCEPTION_SLAVE_OR_SERVER_BUSY,
MODBUS_EXCEPTION_NEGATIVE_ACKNOWLEDGE,
MODBUS_EXCEPTION_MEMORY_PARITY,
MODBUS_EXCEPTION_NOT_DEFINED,
MODBUS_EXCEPTION_GATEWAY_PATH,
MODBUS_EXCEPTION_GATEWAY_TARGET,
MODBUS_EXCEPTION_MAX
};
#define EMBXILFUN (MODBUS_ENOBASE + MODBUS_EXCEPTION_ILLEGAL_FUNCTION)
#define EMBXILADD (MODBUS_ENOBASE + MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS)
#define EMBXILVAL (MODBUS_ENOBASE + MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE)
#define EMBXSFAIL (MODBUS_ENOBASE + MODBUS_EXCEPTION_SLAVE_OR_SERVER_FAILURE)
#define EMBXACK (MODBUS_ENOBASE + MODBUS_EXCEPTION_ACKNOWLEDGE)
#define EMBXSBUSY (MODBUS_ENOBASE + MODBUS_EXCEPTION_SLAVE_OR_SERVER_BUSY)
#define EMBXNACK (MODBUS_ENOBASE + MODBUS_EXCEPTION_NEGATIVE_ACKNOWLEDGE)
#define EMBXMEMPAR (MODBUS_ENOBASE + MODBUS_EXCEPTION_MEMORY_PARITY)
#define EMBXGPATH (MODBUS_ENOBASE + MODBUS_EXCEPTION_GATEWAY_PATH)
#define EMBXGTAR (MODBUS_ENOBASE + MODBUS_EXCEPTION_GATEWAY_TARGET)
/* Native libmodbus error codes */
#define EMBBADCRC (EMBXGTAR + 1)
#define EMBBADDATA (EMBXGTAR + 2)
#define EMBBADEXC (EMBXGTAR + 3)
#define EMBUNKEXC (EMBXGTAR + 4)
#define EMBMDATA (EMBXGTAR + 5)
#define EMBBADSLAVE (EMBXGTAR + 6)
extern const unsigned int libmodbus_version_major;
extern const unsigned int libmodbus_version_minor;
extern const unsigned int libmodbus_version_micro;
typedef struct _modbus modbus_t;
typedef struct _modbus_mapping_t {
int nb_bits;
int start_bits;
int nb_input_bits;
int start_input_bits;
int nb_input_registers;
int start_input_registers;
int nb_registers;
int start_registers;
uint8_t *tab_bits;
uint8_t *tab_input_bits;
uint16_t *tab_input_registers;
uint16_t *tab_registers;
} modbus_mapping_t;
typedef enum {
MODBUS_ERROR_RECOVERY_NONE = 0,
MODBUS_ERROR_RECOVERY_LINK = (1 << 1),
MODBUS_ERROR_RECOVERY_PROTOCOL = (1 << 2)
} modbus_error_recovery_mode;
typedef enum {
MODBUS_QUIRK_NONE = 0,
MODBUS_QUIRK_MAX_SLAVE = (1 << 1),
MODBUS_QUIRK_REPLY_TO_BROADCAST = (1 << 2),
MODBUS_QUIRK_ALL = 0xFF
} modbus_quirks;
MODBUS_API int modbus_set_slave(modbus_t *ctx, int slave);
MODBUS_API int modbus_get_slave(modbus_t *ctx);
MODBUS_API int modbus_set_error_recovery(modbus_t *ctx,
modbus_error_recovery_mode error_recovery);
MODBUS_API int modbus_set_socket(modbus_t *ctx, int s);
MODBUS_API int modbus_get_socket(modbus_t *ctx);
MODBUS_API int
modbus_get_response_timeout(modbus_t *ctx, uint32_t *to_sec, uint32_t *to_usec);
MODBUS_API int
modbus_set_response_timeout(modbus_t *ctx, uint32_t to_sec, uint32_t to_usec);
MODBUS_API int
modbus_get_byte_timeout(modbus_t *ctx, uint32_t *to_sec, uint32_t *to_usec);
MODBUS_API int modbus_set_byte_timeout(modbus_t *ctx, uint32_t to_sec, uint32_t to_usec);
MODBUS_API int
modbus_get_indication_timeout(modbus_t *ctx, uint32_t *to_sec, uint32_t *to_usec);
MODBUS_API int
modbus_set_indication_timeout(modbus_t *ctx, uint32_t to_sec, uint32_t to_usec);
MODBUS_API int modbus_get_header_length(modbus_t *ctx);
MODBUS_API int modbus_connect(modbus_t *ctx);
MODBUS_API void modbus_close(modbus_t *ctx);
MODBUS_API void modbus_free(modbus_t *ctx);
MODBUS_API int modbus_flush(modbus_t *ctx);
MODBUS_API int modbus_set_debug(modbus_t *ctx, int flag);
MODBUS_API const char *modbus_strerror(int errnum);
MODBUS_API int modbus_read_bits(modbus_t *ctx, int addr, int nb, uint8_t *dest);
MODBUS_API int modbus_read_input_bits(modbus_t *ctx, int addr, int nb, uint8_t *dest);
MODBUS_API int modbus_read_registers(modbus_t *ctx, int addr, int nb, uint16_t *dest);
MODBUS_API int
modbus_read_input_registers(modbus_t *ctx, int addr, int nb, uint16_t *dest);
MODBUS_API int modbus_write_bit(modbus_t *ctx, int coil_addr, int status);
MODBUS_API int modbus_write_register(modbus_t *ctx, int reg_addr, const uint16_t value);
MODBUS_API int modbus_write_bits(modbus_t *ctx, int addr, int nb, const uint8_t *data);
MODBUS_API int
modbus_write_registers(modbus_t *ctx, int addr, int nb, const uint16_t *data);
MODBUS_API int
modbus_mask_write_register(modbus_t *ctx, int addr, uint16_t and_mask, uint16_t or_mask);
MODBUS_API int modbus_write_and_read_registers(modbus_t *ctx,
int write_addr,
int write_nb,
const uint16_t *src,
int read_addr,
int read_nb,
uint16_t *dest);
MODBUS_API int modbus_report_slave_id(modbus_t *ctx, int max_dest, uint8_t *dest);
MODBUS_API modbus_mapping_t *
modbus_mapping_new_start_address(unsigned int start_bits,
unsigned int nb_bits,
unsigned int start_input_bits,
unsigned int nb_input_bits,
unsigned int start_registers,
unsigned int nb_registers,
unsigned int start_input_registers,
unsigned int nb_input_registers);
MODBUS_API modbus_mapping_t *modbus_mapping_new(int nb_bits,
int nb_input_bits,
int nb_registers,
int nb_input_registers);
MODBUS_API void modbus_mapping_free(modbus_mapping_t *mb_mapping);
MODBUS_API int
modbus_send_raw_request(modbus_t *ctx, const uint8_t *raw_req, int raw_req_length);
MODBUS_API int modbus_receive(modbus_t *ctx, uint8_t *req);
MODBUS_API int modbus_receive_confirmation(modbus_t *ctx, uint8_t *rsp);
MODBUS_API int modbus_reply(modbus_t *ctx,
const uint8_t *req,
int req_length,
modbus_mapping_t *mb_mapping);
MODBUS_API int
modbus_reply_exception(modbus_t *ctx, const uint8_t *req, unsigned int exception_code);
MODBUS_API int modbus_enable_quirks(modbus_t *ctx, unsigned int quirks_mask);
MODBUS_API int modbus_disable_quirks(modbus_t *ctx, unsigned int quirks_mask);
/**
* UTILS FUNCTIONS
**/
#define MODBUS_GET_HIGH_BYTE(data) (((data) >> 8) & 0xFF)
#define MODBUS_GET_LOW_BYTE(data) ((data) &0xFF)
#define MODBUS_GET_INT64_FROM_INT16(tab_int16, index) \
(((int64_t) tab_int16[(index)] << 48) | ((int64_t) tab_int16[(index) + 1] << 32) | \
((int64_t) tab_int16[(index) + 2] << 16) | (int64_t) tab_int16[(index) + 3])
#define MODBUS_GET_INT32_FROM_INT16(tab_int16, index) \
(((int32_t) tab_int16[(index)] << 16) | (int32_t) tab_int16[(index) + 1])
#define MODBUS_GET_INT16_FROM_INT8(tab_int8, index) \
(((int16_t) tab_int8[(index)] << 8) | (int16_t) tab_int8[(index) + 1])
#define MODBUS_SET_INT16_TO_INT8(tab_int8, index, value) \
do { \
((int8_t *) (tab_int8))[(index)] = (int8_t) ((value) >> 8); \
((int8_t *) (tab_int8))[(index) + 1] = (int8_t) (value); \
} while (0)
#define MODBUS_SET_INT32_TO_INT16(tab_int16, index, value) \
do { \
((int16_t *) (tab_int16))[(index)] = (int16_t) ((value) >> 16); \
((int16_t *) (tab_int16))[(index) + 1] = (int16_t) (value); \
} while (0)
#define MODBUS_SET_INT64_TO_INT16(tab_int16, index, value) \
do { \
((int16_t *) (tab_int16))[(index)] = (int16_t) ((value) >> 48); \
((int16_t *) (tab_int16))[(index) + 1] = (int16_t) ((value) >> 32); \
((int16_t *) (tab_int16))[(index) + 2] = (int16_t) ((value) >> 16); \
((int16_t *) (tab_int16))[(index) + 3] = (int16_t) (value); \
} while (0)
MODBUS_API void modbus_set_bits_from_byte(uint8_t *dest, int idx, const uint8_t value);
MODBUS_API void modbus_set_bits_from_bytes(uint8_t *dest,
int idx,
unsigned int nb_bits,
const uint8_t *tab_byte);
MODBUS_API uint8_t modbus_get_byte_from_bits(const uint8_t *src,
int idx,
unsigned int nb_bits);
MODBUS_API float modbus_get_float(const uint16_t *src);
MODBUS_API float modbus_get_float_abcd(const uint16_t *src);
MODBUS_API float modbus_get_float_dcba(const uint16_t *src);
MODBUS_API float modbus_get_float_badc(const uint16_t *src);
MODBUS_API float modbus_get_float_cdab(const uint16_t *src);
MODBUS_API void modbus_set_float(float f, uint16_t *dest);
MODBUS_API void modbus_set_float_abcd(float f, uint16_t *dest);
MODBUS_API void modbus_set_float_dcba(float f, uint16_t *dest);
MODBUS_API void modbus_set_float_badc(float f, uint16_t *dest);
MODBUS_API void modbus_set_float_cdab(float f, uint16_t *dest);
#include "modbus-rtu.h"
#include "modbus-tcp.h"
MODBUS_END_DECLS
#endif /* MODBUS_H */

Binary file not shown.

View File

@ -1,292 +0,0 @@
/*
* Copyright © Stéphane Raimbault <stephane.raimbault@gmail.com>
*
* SPDX-License-Identifier: LGPL-2.1-or-later
*/
#include <stdlib.h>
// clang-format off
#ifndef _MSC_VER
# include <stdint.h>
#else
# include "stdint.h"
#endif
#include <string.h>
#include <assert.h>
#if defined(_WIN32)
# include <winsock2.h>
#else
# include <arpa/inet.h>
#endif
#include <config.h>
#include "modbus.h"
#if defined(HAVE_BYTESWAP_H)
# include <byteswap.h>
#endif
#if defined(__APPLE__)
# include <libkern/OSByteOrder.h>
# define bswap_16 OSSwapInt16
# define bswap_32 OSSwapInt32
# define bswap_64 OSSwapInt64
#endif
#if defined(__GNUC__)
# define GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__ * 10)
# if GCC_VERSION >= 430
// Since GCC >= 4.30, GCC provides __builtin_bswapXX() alternatives so we switch to them
# undef bswap_32
# define bswap_32 __builtin_bswap32
# endif
# if GCC_VERSION >= 480
# undef bswap_16
# define bswap_16 __builtin_bswap16
# endif
#endif
#if defined(_MSC_VER) && (_MSC_VER >= 1400)
# define bswap_32 _byteswap_ulong
# define bswap_16 _byteswap_ushort
#endif
#if !defined(bswap_16)
# warning "Fallback on C functions for bswap_16"
static inline uint16_t bswap_16(uint16_t x)
{
return (x >> 8) | (x << 8);
}
#endif
#if !defined(bswap_32)
# warning "Fallback on C functions for bswap_32"
static inline uint32_t bswap_32(uint32_t x)
{
return (bswap_16(x & 0xffff) << 16) | (bswap_16(x >> 16));
}
#endif
// clang-format on
/* Sets many bits from a single byte value (all 8 bits of the byte value are
set) */
void modbus_set_bits_from_byte(uint8_t *dest, int idx, const uint8_t value)
{
int i;
for (i = 0; i < 8; i++) {
dest[idx + i] = (value & (1 << i)) ? 1 : 0;
}
}
/* Sets many bits from a table of bytes (only the bits between idx and
idx + nb_bits are set) */
void modbus_set_bits_from_bytes(uint8_t *dest,
int idx,
unsigned int nb_bits,
const uint8_t *tab_byte)
{
unsigned int i;
int shift = 0;
for (i = idx; i < idx + nb_bits; i++) {
dest[i] = tab_byte[(i - idx) / 8] & (1 << shift) ? 1 : 0;
/* gcc doesn't like: shift = (++shift) % 8; */
shift++;
shift %= 8;
}
}
/* Gets the byte value from many bits.
To obtain a full byte, set nb_bits to 8. */
uint8_t modbus_get_byte_from_bits(const uint8_t *src, int idx, unsigned int nb_bits)
{
unsigned int i;
uint8_t value = 0;
if (nb_bits > 8) {
/* Assert is ignored if NDEBUG is set */
assert(nb_bits < 8);
nb_bits = 8;
}
for (i = 0; i < nb_bits; i++) {
value |= (src[idx + i] << i);
}
return value;
}
/* Get a float from 4 bytes (Modbus) without any conversion (ABCD) */
float modbus_get_float_abcd(const uint16_t *src)
{
float f;
uint32_t i;
uint8_t a, b, c, d;
a = (src[0] >> 8) & 0xFF;
b = (src[0] >> 0) & 0xFF;
c = (src[1] >> 8) & 0xFF;
d = (src[1] >> 0) & 0xFF;
i = (a << 24) | (b << 16) | (c << 8) | (d << 0);
memcpy(&f, &i, 4);
return f;
}
/* Get a float from 4 bytes (Modbus) in inversed format (DCBA) */
float modbus_get_float_dcba(const uint16_t *src)
{
float f;
uint32_t i;
uint8_t a, b, c, d;
a = (src[0] >> 8) & 0xFF;
b = (src[0] >> 0) & 0xFF;
c = (src[1] >> 8) & 0xFF;
d = (src[1] >> 0) & 0xFF;
i = (d << 24) | (c << 16) | (b << 8) | (a << 0);
memcpy(&f, &i, 4);
return f;
}
/* Get a float from 4 bytes (Modbus) with swapped bytes (BADC) */
float modbus_get_float_badc(const uint16_t *src)
{
float f;
uint32_t i;
uint8_t a, b, c, d;
a = (src[0] >> 8) & 0xFF;
b = (src[0] >> 0) & 0xFF;
c = (src[1] >> 8) & 0xFF;
d = (src[1] >> 0) & 0xFF;
i = (b << 24) | (a << 16) | (d << 8) | (c << 0);
memcpy(&f, &i, 4);
return f;
}
/* Get a float from 4 bytes (Modbus) with swapped words (CDAB) */
float modbus_get_float_cdab(const uint16_t *src)
{
float f;
uint32_t i;
uint8_t a, b, c, d;
a = (src[0] >> 8) & 0xFF;
b = (src[0] >> 0) & 0xFF;
c = (src[1] >> 8) & 0xFF;
d = (src[1] >> 0) & 0xFF;
i = (c << 24) | (d << 16) | (a << 8) | (b << 0);
memcpy(&f, &i, 4);
return f;
}
/* DEPRECATED - Get a float from 4 bytes in sort of Modbus format */
float modbus_get_float(const uint16_t *src)
{
float f;
uint32_t i;
i = (((uint32_t) src[1]) << 16) + src[0];
memcpy(&f, &i, sizeof(float));
return f;
}
/* Set a float to 4 bytes for Modbus w/o any conversion (ABCD) */
void modbus_set_float_abcd(float f, uint16_t *dest)
{
uint32_t i;
uint8_t *out = (uint8_t *) dest;
uint8_t a, b, c, d;
memcpy(&i, &f, sizeof(uint32_t));
a = (i >> 24) & 0xFF;
b = (i >> 16) & 0xFF;
c = (i >> 8) & 0xFF;
d = (i >> 0) & 0xFF;
out[0] = a;
out[1] = b;
out[2] = c;
out[3] = d;
}
/* Set a float to 4 bytes for Modbus with byte and word swap conversion (DCBA) */
void modbus_set_float_dcba(float f, uint16_t *dest)
{
uint32_t i;
uint8_t *out = (uint8_t *) dest;
uint8_t a, b, c, d;
memcpy(&i, &f, sizeof(uint32_t));
a = (i >> 24) & 0xFF;
b = (i >> 16) & 0xFF;
c = (i >> 8) & 0xFF;
d = (i >> 0) & 0xFF;
out[0] = d;
out[1] = c;
out[2] = b;
out[3] = a;
}
/* Set a float to 4 bytes for Modbus with byte swap conversion (BADC) */
void modbus_set_float_badc(float f, uint16_t *dest)
{
uint32_t i;
uint8_t *out = (uint8_t *) dest;
uint8_t a, b, c, d;
memcpy(&i, &f, sizeof(uint32_t));
a = (i >> 24) & 0xFF;
b = (i >> 16) & 0xFF;
c = (i >> 8) & 0xFF;
d = (i >> 0) & 0xFF;
out[0] = b;
out[1] = a;
out[2] = d;
out[3] = c;
}
/* Set a float to 4 bytes for Modbus with word swap conversion (CDAB) */
void modbus_set_float_cdab(float f, uint16_t *dest)
{
uint32_t i;
uint8_t *out = (uint8_t *) dest;
uint8_t a, b, c, d;
memcpy(&i, &f, sizeof(uint32_t));
a = (i >> 24) & 0xFF;
b = (i >> 16) & 0xFF;
c = (i >> 8) & 0xFF;
d = (i >> 0) & 0xFF;
out[0] = c;
out[1] = d;
out[2] = a;
out[3] = b;
}
/* DEPRECATED - Set a float to 4 bytes in a sort of Modbus format! */
void modbus_set_float(float f, uint16_t *dest)
{
uint32_t i;
memcpy(&i, &f, sizeof(uint32_t));
dest[0] = (uint16_t) i;
dest[1] = (uint16_t) (i >> 16);
}

File diff suppressed because it is too large Load Diff

View File

@ -1,974 +0,0 @@
/*
* Copyright © Stéphane Raimbault <stephane.raimbault@gmail.com>
*
* SPDX-License-Identifier: LGPL-2.1-or-later
*/
// clang-format off
#if defined(_WIN32)
# define OS_WIN32
/* ws2_32.dll has getaddrinfo and freeaddrinfo on Windows XP and later.
* minwg32 headers check WINVER before allowing the use of these */
# ifndef WINVER
# define WINVER 0x0501
# endif
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#ifndef _MSC_VER
#include <unistd.h>
#endif
#include <signal.h>
#include <sys/types.h>
#if defined(_WIN32)
/* Already set in modbus-tcp.h but it seems order matters in VS2005 */
# include <winsock2.h>
# include <ws2tcpip.h>
# define SHUT_RDWR 2
# define close closesocket
# define strdup _strdup
#else
# include <sys/socket.h>
# include <sys/ioctl.h>
#if defined(__OpenBSD__) || (defined(__FreeBSD__) && __FreeBSD__ < 5)
# define OS_BSD
# include <netinet/in_systm.h>
#endif
# include <netinet/in.h>
# include <netinet/ip.h>
# include <netinet/tcp.h>
# include <arpa/inet.h>
# include <netdb.h>
#endif
#if !defined(MSG_NOSIGNAL)
#define MSG_NOSIGNAL 0
#endif
#if defined(_AIX) && !defined(MSG_DONTWAIT)
#define MSG_DONTWAIT MSG_NONBLOCK
#endif
// clang-format on
#include "modbus-private.h"
#include "modbus-tcp-private.h"
#include "modbus-tcp.h"
#ifdef OS_WIN32
static int _modbus_tcp_init_win32(void)
{
/* Initialise Windows Socket API */
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
fprintf(stderr,
"WSAStartup() returned error code %d\n",
(unsigned int) GetLastError());
errno = EIO;
return -1;
}
return 0;
}
#endif
static int _modbus_set_slave(modbus_t *ctx, int slave)
{
int max_slave = (ctx->quirks & MODBUS_QUIRK_MAX_SLAVE) ? 255 : 247;
/* Broadcast address is 0 (MODBUS_BROADCAST_ADDRESS) */
if (slave >= 0 && slave <= max_slave) {
ctx->slave = slave;
} else if (slave == MODBUS_TCP_SLAVE) {
/* The special value MODBUS_TCP_SLAVE (0xFF) can be used in TCP mode to
* restore the default value. */
ctx->slave = slave;
} else {
errno = EINVAL;
return -1;
}
return 0;
}
/* Builds a TCP request header */
static int _modbus_tcp_build_request_basis(
modbus_t *ctx, int function, int addr, int nb, uint8_t *req)
{
modbus_tcp_t *ctx_tcp = ctx->backend_data;
/* Increase transaction ID */
if (ctx_tcp->t_id < UINT16_MAX)
ctx_tcp->t_id++;
else
ctx_tcp->t_id = 0;
req[0] = ctx_tcp->t_id >> 8;
req[1] = ctx_tcp->t_id & 0x00ff;
/* Protocol Modbus */
req[2] = 0;
req[3] = 0;
/* Length will be defined later by set_req_length_tcp at offsets 4
and 5 */
req[6] = ctx->slave;
req[7] = function;
req[8] = addr >> 8;
req[9] = addr & 0x00ff;
req[10] = nb >> 8;
req[11] = nb & 0x00ff;
return _MODBUS_TCP_PRESET_REQ_LENGTH;
}
/* Builds a TCP response header */
static int _modbus_tcp_build_response_basis(sft_t *sft, uint8_t *rsp)
{
/* Extract from MODBUS Messaging on TCP/IP Implementation
Guide V1.0b (page 23/46):
The transaction identifier is used to associate the future
response with the request. */
rsp[0] = sft->t_id >> 8;
rsp[1] = sft->t_id & 0x00ff;
/* Protocol Modbus */
rsp[2] = 0;
rsp[3] = 0;
/* Length will be set later by send_msg (4 and 5) */
/* The slave ID is copied from the indication */
rsp[6] = sft->slave;
rsp[7] = sft->function;
return _MODBUS_TCP_PRESET_RSP_LENGTH;
}
static int _modbus_tcp_prepare_response_tid(const uint8_t *req, int *req_length)
{
return (req[0] << 8) + req[1];
}
static int _modbus_tcp_send_msg_pre(uint8_t *req, int req_length)
{
/* Subtract the header length to the message length */
int mbap_length = req_length - 6;
req[4] = mbap_length >> 8;
req[5] = mbap_length & 0x00FF;
return req_length;
}
static ssize_t _modbus_tcp_send(modbus_t *ctx, const uint8_t *req, int req_length)
{
/* MSG_NOSIGNAL
Requests not to send SIGPIPE on errors on stream oriented
sockets when the other end breaks the connection. The EPIPE
error is still returned. */
return send(ctx->s, (const char *) req, req_length, MSG_NOSIGNAL);
}
static int _modbus_tcp_receive(modbus_t *ctx, uint8_t *req)
{
return _modbus_receive_msg(ctx, req, MSG_INDICATION);
}
static ssize_t _modbus_tcp_recv(modbus_t *ctx, uint8_t *rsp, int rsp_length)
{
return recv(ctx->s, (char *) rsp, rsp_length, 0);
}
static int _modbus_tcp_check_integrity(modbus_t *ctx, uint8_t *msg, const int msg_length)
{
return msg_length;
}
static int _modbus_tcp_pre_check_confirmation(modbus_t *ctx,
const uint8_t *req,
const uint8_t *rsp,
int rsp_length)
{
unsigned int protocol_id;
/* Check transaction ID */
if (req[0] != rsp[0] || req[1] != rsp[1]) {
if (ctx->debug) {
fprintf(stderr,
"Invalid transaction ID received 0x%X (not 0x%X)\n",
(rsp[0] << 8) + rsp[1],
(req[0] << 8) + req[1]);
}
errno = EMBBADDATA;
return -1;
}
/* Check protocol ID */
protocol_id = (rsp[2] << 8) + rsp[3];
if (protocol_id != 0x0) {
if (ctx->debug) {
fprintf(stderr, "Invalid protocol ID received 0x%X (not 0x0)\n", protocol_id);
}
errno = EMBBADDATA;
return -1;
}
return 0;
}
static int _modbus_tcp_set_ipv4_options(int s)
{
int rc;
int option;
/* Set the TCP no delay flag */
/* SOL_TCP = IPPROTO_TCP */
option = 1;
rc = setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (const void *) &option, sizeof(int));
if (rc == -1) {
return -1;
}
/* If the OS does not offer SOCK_NONBLOCK, fall back to setting FIONBIO to
* make sockets non-blocking */
/* Do not care about the return value, this is optional */
#if !defined(SOCK_NONBLOCK) && defined(FIONBIO)
#ifdef OS_WIN32
{
/* Setting FIONBIO expects an unsigned long according to MSDN */
u_long loption = 1;
ioctlsocket(s, FIONBIO, &loption);
}
#else
option = 1;
ioctl(s, FIONBIO, &option);
#endif
#endif
#ifndef OS_WIN32
/**
* Cygwin defines IPTOS_LOWDELAY but can't handle that flag so it's
* necessary to workaround that problem.
**/
/* Set the IP low delay option */
option = IPTOS_LOWDELAY;
rc = setsockopt(s, IPPROTO_IP, IP_TOS, (const void *) &option, sizeof(int));
if (rc == -1) {
return -1;
}
#endif
return 0;
}
static int _connect(int sockfd,
const struct sockaddr *addr,
socklen_t addrlen,
const struct timeval *ro_tv)
{
int rc = connect(sockfd, addr, addrlen);
#ifdef OS_WIN32
int wsaError = 0;
if (rc == -1) {
wsaError = WSAGetLastError();
}
if (wsaError == WSAEWOULDBLOCK || wsaError == WSAEINPROGRESS) {
#else
if (rc == -1 && errno == EINPROGRESS) {
#endif
fd_set wset;
int optval;
socklen_t optlen = sizeof(optval);
struct timeval tv = *ro_tv;
/* Wait to be available in writing */
FD_ZERO(&wset);
FD_SET(sockfd, &wset);
rc = select(sockfd + 1, NULL, &wset, NULL, &tv);
if (rc <= 0) {
/* Timeout or fail */
return -1;
}
/* The connection is established if SO_ERROR and optval are set to 0 */
rc = getsockopt(sockfd, SOL_SOCKET, SO_ERROR, (void *) &optval, &optlen);
if (rc == 0 && optval == 0) {
return 0;
} else {
errno = ECONNREFUSED;
return -1;
}
}
return rc;
}
/* Establishes a modbus TCP connection with a Modbus server. */
static int _modbus_tcp_connect(modbus_t *ctx)
{
int rc;
/* Specialized version of sockaddr for Internet socket address (same size) */
struct sockaddr_in addr;
modbus_tcp_t *ctx_tcp = ctx->backend_data;
int flags = SOCK_STREAM;
#ifdef OS_WIN32
if (_modbus_tcp_init_win32() == -1) {
return -1;
}
#endif
#ifdef SOCK_CLOEXEC
flags |= SOCK_CLOEXEC;
#endif
#ifdef SOCK_NONBLOCK
flags |= SOCK_NONBLOCK;
#endif
ctx->s = socket(PF_INET, flags, 0);
if (ctx->s < 0) {
return -1;
}
rc = _modbus_tcp_set_ipv4_options(ctx->s);
if (rc == -1) {
close(ctx->s);
ctx->s = -1;
return -1;
}
if (ctx->debug) {
printf("Connecting to %s:%d\n", ctx_tcp->ip, ctx_tcp->port);
}
addr.sin_family = AF_INET;
addr.sin_port = htons(ctx_tcp->port);
rc = inet_pton(addr.sin_family, ctx_tcp->ip, &(addr.sin_addr));
if (rc <= 0) {
if (ctx->debug) {
fprintf(stderr, "Invalid IP address: %s\n", ctx_tcp->ip);
}
close(ctx->s);
ctx->s = -1;
return -1;
}
rc =
_connect(ctx->s, (struct sockaddr *) &addr, sizeof(addr), &ctx->response_timeout);
if (rc == -1) {
close(ctx->s);
ctx->s = -1;
return -1;
}
return 0;
}
/* Establishes a modbus TCP PI connection with a Modbus server. */
static int _modbus_tcp_pi_connect(modbus_t *ctx)
{
int rc;
struct addrinfo *ai_list;
struct addrinfo *ai_ptr;
struct addrinfo ai_hints;
modbus_tcp_pi_t *ctx_tcp_pi = ctx->backend_data;
#ifdef OS_WIN32
if (_modbus_tcp_init_win32() == -1) {
return -1;
}
#endif
memset(&ai_hints, 0, sizeof(ai_hints));
#ifdef AI_ADDRCONFIG
ai_hints.ai_flags |= AI_ADDRCONFIG;
#endif
ai_hints.ai_family = AF_UNSPEC;
ai_hints.ai_socktype = SOCK_STREAM;
ai_hints.ai_addr = NULL;
ai_hints.ai_canonname = NULL;
ai_hints.ai_next = NULL;
ai_list = NULL;
rc = getaddrinfo(ctx_tcp_pi->node, ctx_tcp_pi->service, &ai_hints, &ai_list);
if (rc != 0) {
if (ctx->debug) {
fprintf(stderr, "Error returned by getaddrinfo: %s\n", gai_strerror(rc));
}
errno = ECONNREFUSED;
return -1;
}
for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next) {
int flags = ai_ptr->ai_socktype;
int s;
#ifdef SOCK_CLOEXEC
flags |= SOCK_CLOEXEC;
#endif
#ifdef SOCK_NONBLOCK
flags |= SOCK_NONBLOCK;
#endif
s = socket(ai_ptr->ai_family, flags, ai_ptr->ai_protocol);
if (s < 0)
continue;
if (ai_ptr->ai_family == AF_INET)
_modbus_tcp_set_ipv4_options(s);
if (ctx->debug) {
printf("Connecting to [%s]:%s\n", ctx_tcp_pi->node, ctx_tcp_pi->service);
}
rc = _connect(s, ai_ptr->ai_addr, ai_ptr->ai_addrlen, &ctx->response_timeout);
if (rc == -1) {
close(s);
continue;
}
ctx->s = s;
break;
}
freeaddrinfo(ai_list);
if (ctx->s < 0) {
return -1;
}
return 0;
}
static unsigned int _modbus_tcp_is_connected(modbus_t *ctx)
{
return ctx->s >= 0;
}
/* Closes the network connection and socket in TCP mode */
static void _modbus_tcp_close(modbus_t *ctx)
{
if (ctx->s >= 0) {
shutdown(ctx->s, SHUT_RDWR);
close(ctx->s);
ctx->s = -1;
}
}
static int _modbus_tcp_flush(modbus_t *ctx)
{
int rc;
int rc_sum = 0;
do {
/* Extract the garbage from the socket */
char devnull[MODBUS_TCP_MAX_ADU_LENGTH];
#ifndef OS_WIN32
rc = recv(ctx->s, devnull, MODBUS_TCP_MAX_ADU_LENGTH, MSG_DONTWAIT);
#else
/* On Win32, it's a bit more complicated to not wait */
fd_set rset;
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 0;
FD_ZERO(&rset);
FD_SET(ctx->s, &rset);
rc = select(ctx->s + 1, &rset, NULL, NULL, &tv);
if (rc == -1) {
return -1;
}
if (rc == 1) {
/* There is data to flush */
rc = recv(ctx->s, devnull, MODBUS_TCP_MAX_ADU_LENGTH, 0);
}
#endif
if (rc > 0) {
rc_sum += rc;
}
} while (rc == MODBUS_TCP_MAX_ADU_LENGTH);
return rc_sum;
}
/* Listens for any request from one or many modbus masters in TCP */
int modbus_tcp_listen(modbus_t *ctx, int nb_connection)
{
int new_s;
int enable;
int flags;
struct sockaddr_in addr;
modbus_tcp_t *ctx_tcp;
int rc;
if (ctx == NULL) {
errno = EINVAL;
return -1;
}
ctx_tcp = ctx->backend_data;
#ifdef OS_WIN32
if (_modbus_tcp_init_win32() == -1) {
return -1;
}
#endif
flags = SOCK_STREAM;
#ifdef SOCK_CLOEXEC
flags |= SOCK_CLOEXEC;
#endif
new_s = socket(PF_INET, flags, IPPROTO_TCP);
if (new_s == -1) {
return -1;
}
enable = 1;
if (setsockopt(new_s, SOL_SOCKET, SO_REUSEADDR, (char *) &enable, sizeof(enable)) ==
-1) {
close(new_s);
return -1;
}
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
/* If the modbus port is < to 1024, we need the setuid root. */
addr.sin_port = htons(ctx_tcp->port);
if (ctx_tcp->ip[0] == '0') {
/* Listen any addresses */
addr.sin_addr.s_addr = htonl(INADDR_ANY);
} else {
/* Listen only specified IP address */
rc = inet_pton(addr.sin_family, ctx_tcp->ip, &(addr.sin_addr));
if (rc <= 0) {
if (ctx->debug) {
fprintf(stderr, "Invalid IP address: %s\n", ctx_tcp->ip);
}
close(new_s);
return -1;
}
}
if (bind(new_s, (struct sockaddr *) &addr, sizeof(addr)) == -1) {
close(new_s);
return -1;
}
if (listen(new_s, nb_connection) == -1) {
close(new_s);
return -1;
}
return new_s;
}
int modbus_tcp_pi_listen(modbus_t *ctx, int nb_connection)
{
int rc;
struct addrinfo *ai_list;
struct addrinfo *ai_ptr;
struct addrinfo ai_hints;
const char *node;
const char *service;
int new_s;
modbus_tcp_pi_t *ctx_tcp_pi;
if (ctx == NULL) {
errno = EINVAL;
return -1;
}
ctx_tcp_pi = ctx->backend_data;
#ifdef OS_WIN32
if (_modbus_tcp_init_win32() == -1) {
return -1;
}
#endif
if (ctx_tcp_pi->node[0] == 0) {
node = NULL; /* == any */
} else {
node = ctx_tcp_pi->node;
}
if (ctx_tcp_pi->service[0] == 0) {
service = "502";
} else {
service = ctx_tcp_pi->service;
}
memset(&ai_hints, 0, sizeof(ai_hints));
/* If node is not NULL, than the AI_PASSIVE flag is ignored. */
ai_hints.ai_flags |= AI_PASSIVE;
#ifdef AI_ADDRCONFIG
ai_hints.ai_flags |= AI_ADDRCONFIG;
#endif
ai_hints.ai_family = AF_UNSPEC;
ai_hints.ai_socktype = SOCK_STREAM;
ai_hints.ai_addr = NULL;
ai_hints.ai_canonname = NULL;
ai_hints.ai_next = NULL;
ai_list = NULL;
rc = getaddrinfo(node, service, &ai_hints, &ai_list);
if (rc != 0) {
if (ctx->debug) {
fprintf(stderr, "Error returned by getaddrinfo: %s\n", gai_strerror(rc));
}
errno = ECONNREFUSED;
return -1;
}
new_s = -1;
for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next) {
int flags = ai_ptr->ai_socktype;
int s;
#ifdef SOCK_CLOEXEC
flags |= SOCK_CLOEXEC;
#endif
s = socket(ai_ptr->ai_family, flags, ai_ptr->ai_protocol);
if (s < 0) {
if (ctx->debug) {
perror("socket");
}
continue;
} else {
int enable = 1;
rc =
setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void *) &enable, sizeof(enable));
if (rc != 0) {
close(s);
if (ctx->debug) {
perror("setsockopt");
}
continue;
}
}
rc = bind(s, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
if (rc != 0) {
close(s);
if (ctx->debug) {
perror("bind");
}
continue;
}
rc = listen(s, nb_connection);
if (rc != 0) {
close(s);
if (ctx->debug) {
perror("listen");
}
continue;
}
new_s = s;
break;
}
freeaddrinfo(ai_list);
if (new_s < 0) {
return -1;
}
return new_s;
}
int modbus_tcp_accept(modbus_t *ctx, int *s)
{
struct sockaddr_in addr;
socklen_t addrlen;
if (ctx == NULL) {
errno = EINVAL;
return -1;
}
addrlen = sizeof(addr);
#ifdef HAVE_ACCEPT4
/* Inherit socket flags and use accept4 call */
ctx->s = accept4(*s, (struct sockaddr *) &addr, &addrlen, SOCK_CLOEXEC);
#else
ctx->s = accept(*s, (struct sockaddr *) &addr, &addrlen);
#endif
if (ctx->s < 0) {
return -1;
}
if (ctx->debug) {
char buf[INET_ADDRSTRLEN];
if (inet_ntop(AF_INET, &(addr.sin_addr), buf, INET_ADDRSTRLEN) == NULL) {
fprintf(stderr, "Client connection accepted from unparsable IP.\n");
} else {
printf("Client connection accepted from %s.\n", buf);
}
}
return ctx->s;
}
int modbus_tcp_pi_accept(modbus_t *ctx, int *s)
{
struct sockaddr_in6 addr;
socklen_t addrlen;
if (ctx == NULL) {
errno = EINVAL;
return -1;
}
addrlen = sizeof(addr);
#ifdef HAVE_ACCEPT4
/* Inherit socket flags and use accept4 call */
ctx->s = accept4(*s, (struct sockaddr *) &addr, &addrlen, SOCK_CLOEXEC);
#else
ctx->s = accept(*s, (struct sockaddr *) &addr, &addrlen);
#endif
if (ctx->s < 0) {
return -1;
}
if (ctx->debug) {
char buf[INET6_ADDRSTRLEN];
if (inet_ntop(AF_INET6, &(addr.sin6_addr), buf, INET6_ADDRSTRLEN) == NULL) {
fprintf(stderr, "Client connection accepted from unparsable IP.\n");
} else {
printf("Client connection accepted from %s.\n", buf);
}
}
return ctx->s;
}
static int
_modbus_tcp_select(modbus_t *ctx, fd_set *rset, struct timeval *tv, int length_to_read)
{
int s_rc;
while ((s_rc = select(ctx->s + 1, rset, NULL, NULL, tv)) == -1) {
if (errno == EINTR) {
if (ctx->debug) {
fprintf(stderr, "A non blocked signal was caught\n");
}
/* Necessary after an error */
FD_ZERO(rset);
FD_SET(ctx->s, rset);
} else {
return -1;
}
}
if (s_rc == 0) {
errno = ETIMEDOUT;
return -1;
}
return s_rc;
}
static void _modbus_tcp_free(modbus_t *ctx)
{
if (ctx->backend_data) {
free(ctx->backend_data);
}
free(ctx);
}
static void _modbus_tcp_pi_free(modbus_t *ctx)
{
if (ctx->backend_data) {
modbus_tcp_pi_t *ctx_tcp_pi = ctx->backend_data;
free(ctx_tcp_pi->node);
free(ctx_tcp_pi->service);
free(ctx->backend_data);
}
free(ctx);
}
// clang-format off
const modbus_backend_t _modbus_tcp_backend = {
_MODBUS_BACKEND_TYPE_TCP,
_MODBUS_TCP_HEADER_LENGTH,
_MODBUS_TCP_CHECKSUM_LENGTH,
MODBUS_TCP_MAX_ADU_LENGTH,
_modbus_set_slave,
_modbus_tcp_build_request_basis,
_modbus_tcp_build_response_basis,
_modbus_tcp_prepare_response_tid,
_modbus_tcp_send_msg_pre,
_modbus_tcp_send,
_modbus_tcp_receive,
_modbus_tcp_recv,
_modbus_tcp_check_integrity,
_modbus_tcp_pre_check_confirmation,
_modbus_tcp_connect,
_modbus_tcp_is_connected,
_modbus_tcp_close,
_modbus_tcp_flush,
_modbus_tcp_select,
_modbus_tcp_free
};
const modbus_backend_t _modbus_tcp_pi_backend = {
_MODBUS_BACKEND_TYPE_TCP,
_MODBUS_TCP_HEADER_LENGTH,
_MODBUS_TCP_CHECKSUM_LENGTH,
MODBUS_TCP_MAX_ADU_LENGTH,
_modbus_set_slave,
_modbus_tcp_build_request_basis,
_modbus_tcp_build_response_basis,
_modbus_tcp_prepare_response_tid,
_modbus_tcp_send_msg_pre,
_modbus_tcp_send,
_modbus_tcp_receive,
_modbus_tcp_recv,
_modbus_tcp_check_integrity,
_modbus_tcp_pre_check_confirmation,
_modbus_tcp_pi_connect,
_modbus_tcp_is_connected,
_modbus_tcp_close,
_modbus_tcp_flush,
_modbus_tcp_select,
_modbus_tcp_pi_free
};
// clang-format on
modbus_t *modbus_new_tcp(const char *ip, int port)
{
modbus_t *ctx;
modbus_tcp_t *ctx_tcp;
size_t dest_size;
size_t ret_size;
#if defined(OS_BSD)
/* MSG_NOSIGNAL is unsupported on *BSD so we install an ignore
handler for SIGPIPE. */
struct sigaction sa;
sa.sa_handler = SIG_IGN;
if (sigaction(SIGPIPE, &sa, NULL) < 0) {
/* The debug flag can't be set here... */
fprintf(stderr, "Could not install SIGPIPE handler.\n");
return NULL;
}
#endif
ctx = (modbus_t *) malloc(sizeof(modbus_t));
if (ctx == NULL) {
return NULL;
}
_modbus_init_common(ctx);
/* Could be changed after to reach a remote serial Modbus device */
ctx->slave = MODBUS_TCP_SLAVE;
ctx->backend = &_modbus_tcp_backend;
ctx->backend_data = (modbus_tcp_t *) malloc(sizeof(modbus_tcp_t));
if (ctx->backend_data == NULL) {
modbus_free(ctx);
errno = ENOMEM;
return NULL;
}
ctx_tcp = (modbus_tcp_t *) ctx->backend_data;
if (ip != NULL) {
dest_size = sizeof(char) * 16;
ret_size = strlcpy(ctx_tcp->ip, ip, dest_size);
if (ret_size == 0) {
fprintf(stderr, "The IP string is empty\n");
modbus_free(ctx);
errno = EINVAL;
return NULL;
}
if (ret_size >= dest_size) {
fprintf(stderr, "The IP string has been truncated\n");
modbus_free(ctx);
errno = EINVAL;
return NULL;
}
} else {
ctx_tcp->ip[0] = '0';
}
ctx_tcp->port = port;
ctx_tcp->t_id = 0;
return ctx;
}
modbus_t *modbus_new_tcp_pi(const char *node, const char *service)
{
modbus_t *ctx;
modbus_tcp_pi_t *ctx_tcp_pi;
ctx = (modbus_t *) malloc(sizeof(modbus_t));
if (ctx == NULL) {
return NULL;
}
_modbus_init_common(ctx);
/* Could be changed after to reach a remote serial Modbus device */
ctx->slave = MODBUS_TCP_SLAVE;
ctx->backend = &_modbus_tcp_pi_backend;
ctx->backend_data = (modbus_tcp_pi_t *) malloc(sizeof(modbus_tcp_pi_t));
if (ctx->backend_data == NULL) {
modbus_free(ctx);
errno = ENOMEM;
return NULL;
}
ctx_tcp_pi = (modbus_tcp_pi_t *) ctx->backend_data;
ctx_tcp_pi->node = NULL;
ctx_tcp_pi->service = NULL;
if (node != NULL) {
ctx_tcp_pi->node = strdup(node);
} else {
/* The node argument can be empty to indicate any hosts */
ctx_tcp_pi->node = strdup("");
}
if (ctx_tcp_pi->node == NULL) {
modbus_free(ctx);
errno = ENOMEM;
return NULL;
}
if (service != NULL && service[0] != '\0') {
ctx_tcp_pi->service = strdup(service);
} else {
/* Default Modbus port number */
ctx_tcp_pi->service = strdup("502");
}
if (ctx_tcp_pi->service == NULL) {
modbus_free(ctx);
errno = ENOMEM;
return NULL;
}
ctx_tcp_pi->t_id = 0;
return ctx;
}

File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More