Repository: bigtreetech/OctoBTT Branch: master Commit: cee483835601 Files: 56 Total size: 436.3 KB Directory structure: gitextract_r06cqxp9/ ├── .gitattributes ├── .gitignore ├── LICENSE ├── OctoBTT.pro ├── OctoBTT.sudoers.d ├── OctoBTT_zh_CN.ts ├── README.md ├── StyleSheet/ │ └── globalStyleSheet.qss ├── accesscontrol.cpp ├── accesscontrol.h ├── assets.qrc ├── cameradialog.cpp ├── cameradialog.h ├── cameradialog.ui ├── config.conf ├── configuration.cpp ├── configuration.h ├── configuration.ui ├── controlpanel.cpp ├── controlpanel.h ├── controlpanel.ui ├── customdialog.cpp ├── customdialog.h ├── filedialog.cpp ├── filedialog.h ├── filedialog.ui ├── gcodedialog.cpp ├── gcodedialog.h ├── gcodedialog.ui ├── inputdialog.cpp ├── inputdialog.h ├── inputdialog.ui ├── install.sh ├── liblog.cpp ├── liblog.h ├── main.cpp ├── mainwindow.cpp ├── mainwindow.h ├── mainwindow.ui ├── materialctrlpanel.cpp ├── materialctrlpanel.h ├── materialctrlpanel.ui ├── mylineedit.cpp ├── mylineedit.h ├── octonetwork.cpp ├── octonetwork.h ├── start.sh ├── startup.sh ├── terminaldialog.cpp ├── terminaldialog.h ├── terminaldialog.ui ├── update.sh ├── upgrade.sh ├── wlanconfig.cpp ├── wlanconfig.h └── wlanconfig.ui ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitattributes ================================================ # Auto detect text files and perform LF normalization * text=auto ================================================ FILE: .gitignore ================================================ # C++ objects and libs *.slo *.lo *.o *.a *.la *.lai *.so *.so.* *.dll *.dylib # Qt-es object_script.*.Release object_script.*.Debug *_plugin_import.cpp /.qmake.cache /.qmake.stash *.pro.user *.pro.user.* *.qbs.user *.qbs.user.* *.moc moc_*.cpp moc_*.h qrc_*.cpp ui_*.h *.qmlc *.jsc Makefile* *build-* *.qm *.prl # Qt unit tests target_wrapper.* # QtCreator *.autosave # QtCreator Qml *.qmlproject.user *.qmlproject.user.* # QtCreator CMake CMakeLists.txt.user* # QtCreator 4.8< compilation database compile_commands.json # QtCreator local machine specific files for imported projects *creator.user* # OS-specific files .DS_Store *.DS_Store # Custom .DS_Store assets/.DS_Store assets/icon/.DS_Store ================================================ FILE: LICENSE ================================================ GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are 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. 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. Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. 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 Affero 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. Remote Network Interaction; Use with the GNU General Public License. Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. 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 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 work with which it is combined will remain governed by version 3 of the GNU General Public License. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU Affero 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 Affero 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 Affero 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 Affero 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. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. 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 AGPL, see . ================================================ FILE: OctoBTT.pro ================================================ QT += core gui svg #QT += multimedia #QT += multimediawidgets QT += network websockets #QT += multimedia #QT += script #QT += webenginewidgets greaterThan(QT_MAJOR_VERSION, 4): QT += widgets CONFIG += c++11 CONFIG += lang-zh_CN CONFIG += console # The following define makes your compiler emit warnings if you use # any Qt feature that has been marked deprecated (the exact warnings # depend on your compiler). Please consult the documentation of the # deprecated API in order to know how to port your code away from it. DEFINES += QT_DEPRECATED_WARNINGS VERSION = 2.0.0 QMAKE_TARGET_COMPANY = BigtreeTech QMAKE_TARGET_PRODUCT = OctoBTT QMAKE_TARGET_COPYRIGHT = Copyright(C) 2020 By BigtreeTech QMAKE_TARGET_DESCRIPTION = First suggested for OctoPi # You can also make your code fail to compile if it uses deprecated APIs. # In order to do so, uncomment the following line. # You can also select to disable deprecated APIs only up to a certain version of Qt. #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 SOURCES += \ accesscontrol.cpp \ cameradialog.cpp \ configuration.cpp \ controlpanel.cpp \ customdialog.cpp \ filedialog.cpp \ gcodedialog.cpp \ inputdialog.cpp \ liblog.cpp \ main.cpp \ mainwindow.cpp \ materialctrlpanel.cpp \ mylineedit.cpp \ octonetwork.cpp \ terminaldialog.cpp \ # webdialog.cpp \ wlanconfig.cpp HEADERS += \ accesscontrol.h \ cameradialog.h \ configuration.h \ controlpanel.h \ customdialog.h \ filedialog.h \ gcodedialog.h \ inputdialog.h \ liblog.h \ mainwindow.h \ materialctrlpanel.h \ mylineedit.h \ octonetwork.h \ terminaldialog.h \ # webdialog.h \ wlanconfig.h FORMS += \ cameradialog.ui \ configuration.ui \ controlpanel.ui \ filedialog.ui \ gcodedialog.ui \ inputdialog.ui \ mainwindow.ui \ materialctrlpanel.ui \ terminaldialog.ui \ # webdialog.ui \ wlanconfig.ui TRANSLATIONS += \ OctoBTT_zh_CN.ts # Default rules for deployment. qnx: target.path = /tmp/$${TARGET}/bin else: unix:!android: target.path = /opt/$${TARGET}/bin !isEmpty(target.path): INSTALLS += target RESOURCES += \ assets.qrc DISTFILES += \ start.sh \ wav/KBClick.wav ================================================ FILE: OctoBTT.sudoers.d ================================================ pi ALL=(ALL) NOPASSWD: /sbin/iwlist, /sbin/wpa_cli, /sbin/iwconfig, /sbins/ifconfig ================================================ FILE: OctoBTT_zh_CN.ts ================================================ ================================================ FILE: README.md ================================================ # OctoBTT ![OctoBTT](assets/icon/BTT_Duck.svg "OctoBTT") ## Introduce * A UI that matches OctoPrint printer ## Software architecture * Client and server architecture solution * OctoPi -> OctoPrint service -> Printer ## Install the tutorial ### One-click installation based on image mode ### [OctoPi-0.17.0 with OctoBTT](https://drive.google.com/file/d/1pR2fpxu22XdM08EMIsEXZj7D5zPRO70z/view?usp=sharing) ### Manual installation based on source code > (The update and upgrade operations are not redundant) ### 1. Install OctoPrint(direct use of OctoPi is recommended , Up to [Octopi 0.17](https://drive.google.com/file/d/1F3xRiC6GXkHNvPAKEho4P9ylevF9G_HR/view?usp=sharing) is supported, and you need to go to OctoprInt's Web page to complete the initialization, need to be disable access control)-- (install under directory) ### [OctoPi-0.17.0](https://drive.google.com/file/d/1F3xRiC6GXkHNvPAKEho4P9ylevF9G_HR/view?usp=sharing) ![Flash](IMG/Ready/Flash.png "Flash") * You can create a WPA profile in the boot directory **boot/wpa_supplicant.txt** to add WiFi connections ![ConfigWPA](IMG/Ready/ConfigWPA.png "ConfigWPA") * If you are a BX machine model user, you will need to add the following fragment lines to the RaspberryPi **boot/config.txt** file to display them correctly on screen: > * max_usb_current=1 > * hdmi_group=2 > * hdmi_mode=87 > * hdmi_cvt 1024 600 60 > * hdmi_drive=1 ![ConfigDisplayMode](IMG/Ready/ConfigDisplayMode.jpg "ConfigDisplayMode") * SSH your PI on your computer for further action > After Pi boot you can get the IP address of Pi from the screen ![RaspiShowIP](IMG/Login/RaspiShowIP.jpeg "RaspiShowIP") > If you connect with console ![ConfigConsole](IMG/Login/ConfigConsole.png "ConfigConsole") ![ConsoleShow](IMG/Login/ConsoleShow.png "ConsoleShow") > If you connect with terminal ![ConfigTermius](IMG/Login/ConfigTermius.jpeg "ConfigTermius") ![TermiusShow](IMG/Login/TermiusShow.jpeg "TermiusShow") ### 2. Install OctoBTT : > Run Command (Installation): * rm -f startup.sh ; wget --no-check-certificate https://raw.githubusercontent.com/bigtreetech/OctoBTT/master/startup.sh && sudo /bin/sh startup.sh ![InstallOctoBTT.png](IMG/2_InstallOctoBTT.png "InstallOctoBTT") ### 3. OctoBTT is entered automatically after you wait for the auto setup to complete and then restart ![Show](IMG/Show.png "Show") ## Instructions for use > 1. Used with OctoPrint ![Show](IMG/All.png "Show") ## Notes > 1. Because the serial port delay is long, the background has blocked the serial port connection, we only use the USB automatic connection > 2. It is recommended to run with Marlin firmware. Currently there may be some unknown problems due to non-marlin firmware > 3. If you want to use octoprint online , you can use the network cable to connect to the router. ## Contribute > 1. Fork the repository > 2. New Feat_ XXX branch > 3. Submit code > 4. New Pull Request ================================================ FILE: StyleSheet/globalStyleSheet.qss ================================================ /*1.0.0*/ /* ================================= 上述为版本号,如您自己更换了新的样式表, 请将版本号首位改为0,例如:0.5.6 ================================= */ /* ============================================ The above is the version number. If you change the new style sheet yourself, change the first part of the version number to 0, for example: 0.5.6 ============================================ */ QWidget { background-color:rgb(25, 25, 25); } /*按钮静止无操作样式*/ QPushButton[whatsThis="BTStyleSheet"] { padding: 10px; border-style: solid; border-width: 5px; border-radius: 20px; border-color: rgb(255, 0, 0); color: rgb(245, 246, 250); } /*鼠标悬停在按钮样式*/ QPushButton:hover[whatsThis="BTStyleSheet"] { padding: 10px; border-style: solid; border-width: 5px; border-radius: 20px; border-color: rgb(0, 255, 0); background-color: rgba(128, 128, 128, 25%); color: rgb(245, 246, 250); } /*鼠标按下按钮样式*/ QPushButton:pressed[whatsThis="BTStyleSheet"] { padding: 10px; border-style: solid; border-width: 5px; border-radius: 20px; border-color: rgb(0, 255, 0); background-color: rgba(128, 128, 128, 25%); color: rgb(245, 246, 250); padding-right:4px; padding-bottom:4px; } /*按钮静止无操作样式*/ QPushButton[whatsThis="BTStyleSheet1"] { padding: 10px; border-style: solid; border-width: 5px; border-radius: 20px; color: rgb(245, 246, 255); } /*鼠标悬停在按钮样式*/ QPushButton:hover[whatsThis="BTStyleSheet1"] { padding: 10px; border-style: solid; border-width: 5px; border-radius: 20px; background-color:rgb(128, 128, 128, 25%); color: rgb(245, 246, 255); } /*鼠标按下按钮样式*/ QPushButton:pressed[whatsThis="BTStyleSheet1"] { padding: 10px; border-style: solid; border-width: 5px; border-radius: 20px; background-color:rgba(128, 128, 128, 25%); color: rgb(245, 246, 255); padding-right:4px; padding-bottom:4px; } /*按钮静止无操作样式*/ QPushButton[whatsThis="BTStyleSheet2"] { border:none; color: rgb(245, 246, 255); } /*鼠标悬停在按钮样式*/ QPushButton:hover[whatsThis="BTStyleSheet2"] { border:none; background-color:rgba(128, 128, 128, 25%); color: rgb(245, 246, 255); } /*鼠标按下按钮样式*/ QPushButton:pressed[whatsThis="BTStyleSheet2"] { border:none; background-color:rgba(128, 128, 128, 25%); padding-left:4px; padding-top:4px; color: rgb(245, 246, 255); } /*按钮静止无操作样式*/ QPushButton[whatsThis="BTStyleSheet3"] { border:none; font: 75 30pt Gill Sans MT; color: rgb(245, 246, 255); } /*鼠标悬停在按钮样式*/ QPushButton:hover[whatsThis="BTStyleSheet3"] { border:none; background-color: rgba(128, 128, 128, 25%); font: 75 30pt Gill Sans MT; color: rgb(245, 246, 255); } /*鼠标按下按钮样式*/ QPushButton:pressed[whatsThis="BTStyleSheet3"] { border:none; background-color: rgba(128, 128, 128, 25%); font: 75 30pt Gill Sans MT; color: rgb(245, 246, 255); padding-left:4px; padding-top:4px; } /*按钮静止无操作样式*/ QPushButton[whatsThis="BTStyleSheet4"] { border:none; } /*鼠标悬停在按钮样式*/ QPushButton:hover[whatsThis="BTStyleSheet4"] { border:none; background-color: rgba(128, 128, 128, 25%); } /*鼠标按下按钮样式*/ QPushButton:pressed[whatsThis="BTStyleSheet4"] { border:none; background-color: rgba(128, 128, 128, 25%); padding-left:4px; padding-top:4px; } /*按钮静止无操作样式*/ QPushButton[whatsThis="BTStyleSheet5"] { color: rgb(245, 246, 255); } /*鼠标悬停在按钮样式*/ QPushButton:hover[whatsThis="BTStyleSheet5"] { background-color:rgba(128, 128, 128, 25%); color: rgb(245, 246, 255); } /*鼠标按下按钮样式*/ QPushButton:pressed[whatsThis="BTStyleSheet5"] { background-color:rgba(128, 128, 128, 25%); padding-left:4px; padding-top:4px; color: rgb(245, 246, 255); } /*按钮静止无操作样式*/ QPushButton[whatsThis="BTStyleSheet6"] { padding: 10px; border-style: solid; border-width: 1px;border-radius: 20px; border-color: rgb(245, 246, 255); color: rgb(245, 246, 255); } /*鼠标悬停在按钮样式*/ QPushButton:hover[whatsThis="BTStyleSheet6"] { padding: 10px; border-style: solid; border-width: 1px; border-radius: 20px;border-color: rgb(245,246,255); background-color:rgba(128, 128, 128, 25%); color: rgb(245, 246, 255); } /*鼠标按下按钮样式*/ QPushButton:pressed[whatsThis="BTStyleSheet6"] { padding: 10px; border-style: solid; border-width: 1px;border-radius: 20px; border-color: rgb(245,246,255); background-color:rgb(128, 128, 128, 25%); color: rgb(245, 246, 255);padding-right:4px; padding-bottom:4px; } /*按钮静止无操作样式*/ QPushButton[whatsThis="BTStyleSheet7"] { background-color: rgb(0, 0, 0); color: rgb(255, 255, 10); } /*鼠标悬停在按钮样式*/ QPushButton:hover[whatsThis="BTStyleSheet7"] { color: rgb(255, 255, 10); background-color: rgba(128, 128, 128, 25%); } /*鼠标按下按钮样式*/ QPushButton:pressed[whatsThis="BTStyleSheet7"] { color: rgb(255, 255, 10); background-color: rgba(128, 128, 128, 25%); padding-left:4px;padding-top:4px; } /*按钮静止无操作样式*/ QToolButton[whatsThis="BTStyleSheet8"] { padding: 10px; border-style: solid; border-width: 2px;border-radius: 20px; border-color: rgb(245, 246, 255); color: rgb(245, 246, 255); } /*鼠标悬停在按钮样式*/ QToolButton:hover[whatsThis="BTStyleSheet8"] { padding: 10px; border-style: solid; border-width: 2px;border-radius: 20px; background-color:rgba(128, 128, 128, 25%); color: rgb(245, 246, 255); } /*鼠标按下按钮样式*/ QToolButton:pressed[whatsThis="BTStyleSheet8"] { padding: 10px; border-style: solid; border-width: 2px; border-radius: 20px; background-color:rgba(128, 128, 128, 25%); color: rgb(245, 246, 255); padding-right:4px; padding-bottom:4px; } /*按钮静止无操作样式*/ QToolButton[whatsThis="BTStyleSheet9"] { border:none; font: 20pt "Gill Sans Ultra Bold Condensed"; color: rgb(245, 246, 250); } /*鼠标悬停在按钮样式*/ QToolButton:hover[whatsThis="BTStyleSheet9"] { border:none; background-color: rgba(128, 128, 128, 25%); font: 20pt "Gill Sans Ultra Bold Condensed"; color: rgb(245, 246, 250); } /*鼠标按下按钮样式*/ QToolButton:pressed[whatsThis="BTStyleSheet9"] { border:none; background-color: rgba(128, 128, 128, 25%); padding-left:4px; padding-top:4px; font: 20pt "Gill Sans Ultra Bold Condensed"; color: rgb(245, 246, 250); } /*按钮静止无操作样式*/ QPushButton[whatsThis="BTStyleSheet10"] { padding: 10px; border-style: solid; border-width: 2px; border-radius: 20px; border: rgba(60, 255, 138, 25%); } /*鼠标悬停在按钮样式*/ QPushButton:hover[whatsThis="BTStyleSheet10"] { padding: 10px; border-style: solid; border-width: 2px; border-radius: 20px; border: rgba(60, 255, 138, 25%); background-color:rgba(128, 128, 128, 25%); } /*鼠标按下按钮样式*/ QPushButton:pressed[whatsThis="BTStyleSheet10"] { padding: 10px; border-style: solid; border-width: 2px; border-radius: 20px; border: rgba(60, 255, 138, 25%); background-color:rgba(128, 128, 128, 25%); padding-right:4px; padding-bottom:4px; } /*滑动条样式表*/ QScrollBar:vertical { width:40px; background:rgba(0,128,255,0%); margin:0px,0px,0px,0px; padding-top:40px; padding-bottom:40px; } QScrollBar::handle:vertical { width:40px; background:rgba(0,128,255,25%); border-radius:10px; min-height:40; } QScrollBar::handle:vertical:hover { width:40px; background:rgba(0,128,255,50%); border-radius:10px; min-height:40; } QScrollBar::add-page:vertical,QScrollBar::sub-page:vertical { background:rgba(0,128,255,10%); border-radius:0px; } QScrollBar:horizontal { height:40px; background:rgba(0,128,255,0%); margin:0px,0px,0px,0px; padding-left:40px; padding-right:40px; } QScrollBar::handle:horizontal { height:40x; background:rgba(0,128,255,25%); border-radius:10px; min-width:40; } QScrollBar::handle:horizontal:hover { height:40px; background:rgba(0,128,255,50%); border-radius:10px; min-width:40; } QScrollBar::add-page:horizontal,QScrollBar::sub-page:horizontal { background:rgba(0,128,255,10%); border-radius:0px; } /* 未下拉时,QComboBox的样式 */ QComboBox { border: none; } QComboBox::showPopup QAbstractItemView { outline: 0px solid gray; /* 选定项的虚框 */ color: rgb(255, 255, 255); /* 整个下拉窗体被选中项的背景色 */ background-color: rgb(128, 128, 128); /* 整个下拉窗体的背景色 */ selection-background-color: rgb(64, 64, 192); /* 整个下拉窗体被选中项的背景色 */ selection-color: rgb(0, 0, 0); /* 整个下拉窗体被选中项的背景色 */ } ================================================ FILE: accesscontrol.cpp ================================================ #include "accesscontrol.h" //#include "octonetwork.h"//Global prama #include #include #include #include //#include //#include AccessControl::AccessControl() { // GetACRequest.setUrl(QUrl(MainUrl));//http://IP/api/login GetACRequest.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/json")); } //login void AccessControl::acLogin() { if(userinfo.uid == NULL || userinfo.uid.trimmed() == "" || userinfo.pwd == NULL) { emit CommunicationStateChange(false); return; } GetACRequest.setUrl(QUrl(MainUrl + "login"));//http://IP/api/login QJsonObject TemperatureJsonObj; // { // "user": "uid", // "pass": "pwd", // "remember": "remember me" // } TemperatureJsonObj.insert("user",userinfo.uid); TemperatureJsonObj.insert("pass",userinfo.pwd); TemperatureJsonObj.insert("remember","remember me"); TemperatureJsonObj.insert("passive",true);//被动模式登录,如果免登录依旧能够获取session///需要允许被动登录才可以获得免登录方式 QJsonDocument _SenderJson; _SenderJson.setObject(TemperatureJsonObj); ACManager->disconnect(SIGNAL(finished(QNetworkReply*))); connect(ACManager,&QNetworkAccessManager::finished,this,&AccessControl::LoginReply); ACManager->post(GetACRequest,_SenderJson.toJson()); } void AccessControl::LoginReply(QNetworkReply *reply) { bool _return=false; // ACManager->disconnect(SIGNAL(finished(QNetworkReply*))); if(reply->error() == QNetworkReply::NoError) { int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); if(statusCode == 200)//Have receive { // userinfo.login = true; //创建接收对象 QByteArray replyArray = reply->readAll(); QJsonDocument loadDoc(QJsonDocument::fromJson(replyArray)); QJsonObject QObj = loadDoc.object(); //获取登录反馈内容 QList result = SearchJsonValue(LoginMsg , QObj);//{{"active"},{"admin"},{"apikey"},{"name"},{"session"}}; userinfo.login = result[0].toBool(); userinfo.admin = result[1].toBool(); userinfo.API_Key = result[2].toString().toUtf8(); userinfo.onlineUid = result[3].toString(); userinfo.session = result[4].toString().toUtf8(); _return = true; } } ACManager->disconnect(SIGNAL(finished(QNetworkReply*))); emit CommunicationStateChange(_return); } //logout void AccessControl::acLogout() { GetACRequest.setUrl(QUrl(MainUrl + "logout"));//http://IP/api/logout ACManager->disconnect(SIGNAL(finished(QNetworkReply*))); connect(ACManager,&QNetworkAccessManager::finished,this,&AccessControl::LogoutReply); } void AccessControl::LogoutReply(QNetworkReply *reply) { bool _return=false; if(reply->error() == QNetworkReply::NoError) { int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); if(statusCode == 200)//Have receive { //重置登录参数 userinfo = UserInfo(userinfo.uid,userinfo.pwd); //创建接收对象 QByteArray replyArray = reply->readAll(); QJsonDocument loadDoc(QJsonDocument::fromJson(replyArray)); QJsonObject QObj = loadDoc.object(); // QList SearchLink ; //获取登录反馈内容 QList result = SearchJsonValue(LoginMsg , QObj);//{{"active"},{"admin"},{"apikey"},{"name"},{"session"}};///被动账户执行退出登录才会返回账户信息 if(!result[3].isNull() && result[3].isString() && result[3].toString() == "_admin") { userinfo.login = result[0].toBool(); userinfo.admin = result[1].toBool(); userinfo.onlineUid = result[3].toString();//判定免登录账户:_admin } _return = true; } } ACManager->disconnect(SIGNAL(finished(QNetworkReply*))); emit CommunicationStateChange(_return); } //Function //Find_List_Name : Retrieved List Sequence --> [Grandma,Mother,Me] //_QObj:Retrieved Retrieved Json Objecet QJsonValue AccessControl::SearchJsonValue(QList Find_List_Name , QJsonObject _QObj) { QJsonValue returnValue; QList SearchLink ; SearchLink << Find_List_Name; if(SearchLink.count() > 1) { QString MotherKey = SearchLink[0]; SearchLink.removeFirst(); if(MotherKey.indexOf("*") >= 0)//wildcard { QJsonArray ArrayValue; for(int i = 0 ; i <= 9 ; i++) { QString TempMotherKey = MotherKey; if(_QObj.find(TempMotherKey.replace("*",QString::number(i))).value().isUndefined())continue; // if(QSysInfo::productType() != "raspbian"){qDebug()<<_QObj.find(TempMotherKey.replace("*",QString::number(i))).value().isUndefined();}; QJsonValue data = SearchJsonValue(SearchLink , _QObj.constFind(TempMotherKey.replace("*",QString::number(i))).value().toObject()); ArrayValue.append(data); } returnValue = ArrayValue; } else returnValue = SearchJsonValue(SearchLink , _QObj.constFind(MotherKey).value().toObject()); } else { if(SearchLink[0].indexOf("*") >= 0)//wildcard { } else returnValue = _QObj.constFind(SearchLink[0]).value(); } return returnValue; } QList AccessControl::SearchJsonValue(QList> Find_List_Names , QJsonObject _QObj) { QList _returnValue ; foreach(QList item , Find_List_Names) { _returnValue.append(SearchJsonValue(item,_QObj)); } return _returnValue; } ================================================ FILE: accesscontrol.h ================================================ #ifndef ACCESSCONTROL_H #define ACCESSCONTROL_H #include #include #include #include struct UserInfo{ QString uid;//用户设置登录账号 QString onlineUid;//当前登录账号 QString pwd;//账户密码 bool admin;//{"admin"}//判断权限是否充足,仅仅高级账户才能运行UI运作 bool login;//{"active"}//登录失败403拒绝访问,布尔值归位默认false QByteArray API_Key;//{"apikey"}//如果没设置就不存在,引用全局Key QByteArray session;//{"session"}//每次登录成功会获得新的对话ID,不区分超级账户和用户账户///为websocket提供接入ID UserInfo(QString _uid = NULL , QString _pwd = NULL) { if(_uid != NULL && _pwd != NULL) { uid = _uid; pwd = _pwd; } admin = false; login = false; API_Key = ""; session = ""; } }; Q_DECLARE_METATYPE(UserInfo); class AccessControl: public QObject { Q_OBJECT public: AccessControl(); QNetworkAccessManager *ACManager = new QNetworkAccessManager(); QNetworkRequest GetACRequest; void acLogin(); void acLogout(); UserInfo userinfo = UserInfo(); // QByteArray user_X_API_Key = ""; signals: void CommunicationStateChange(bool); private: // QWidget *FUI; QString MainIP = "127.0.0.1"; QString MainAddress = "http://"+MainIP+"/"; QString MainUrl = MainAddress + "api/"; QJsonValue SearchJsonValue(QList Find_List_Name , QJsonObject _QObj); QList SearchJsonValue(QList> Find_List_Names , QJsonObject _QObj); const QList> LoginMsg = {{"active"},{"admin"},{"apikey"},{"name"},{"session"}}; private slots: void LoginReply(QNetworkReply *reply); void LogoutReply(QNetworkReply *reply); }; #endif // ACCESSCONTROL_H ================================================ FILE: assets.qrc ================================================  assets/adjust.svg assets/back.svg assets/cancel.svg assets/checkmark.svg assets/confirm.svg assets/control.svg assets/delete.svg assets/error.svg assets/fan.svg assets/filament.svg assets/folder.svg assets/heat-bed.svg assets/help.svg assets/invalid-config.svg assets/next.svg assets/nozzle.svg assets/object.svg assets/pause.svg assets/print.svg assets/resume.svg assets/settings.svg assets/sort.svg assets/thermometer.svg assets/upload.svg assets/sync-alt.svg assets/arrow_down.svg assets/arrow_up.svg assets/camera.svg assets/daochu.svg assets/daoru.svg assets/emoji.svg assets/guanji.svg assets/info.svg assets/more.svg assets/off.svg assets/rizhi.svg assets/setting.svg assets/shanchu.svg assets/shangchuan.svg assets/shezhi.svg assets/shuaxin.svg assets/video.svg assets/xiazai.svg assets/xinzeng.svg assets/yuanchengkongzhi.svg assets/zhongqi.svg assets/chupeng.svg assets/re.svg assets/Wifi.svg assets/penzui.svg assets/heat.svg assets/Network.svg assets/heat-gas.svg assets/nib.svg assets/icon/icon-main-btt.svg assets/icon/icon-main-btt-blue.svg assets/3ddayin.svg assets/Ddayin.svg assets/huidaoyuandian.svg assets/kongzhiqi_fengji.svg assets/sanweidianyunsaomiao.svg assets/sanweizuobiao.svg assets/shanchuwenjian.svg assets/shangchuanwenjian.svg assets/wenjian.svg assets/xiazaiwenjian.svg assets/xitongpeizhi.svg assets/yuandian.svg assets/zhouxiang.svg assets/haocaiguanli.svg assets/jinggao.svg assets/icon/BTT_Duck.svg assets/dangxinjixieshangren.svg assets/jixiezhizao.svg assets/shebeiweilianjie-copy.svg assets/fanhuiyemian.svg assets/hazard.svg assets/huijia.svg assets/icon_liangchi.svg assets/jiareqi.svg assets/shuangdong.svg assets/zhongzhi.svg assets/kongzhimianban.svg assets/kongzhimianban_B.svg assets/kongzhimianban_L.svg assets/kongzhimianban_W.svg assets/xiangxiaji.svg assets/jiare.svg assets/huitui.svg assets/shang.svg assets/shangsheng.svg assets/xia.svg assets/xiajiang.svg assets/you.svg assets/yuandian_W.svg assets/zuo.svg assets/shangxiajuzhong.svg assets/zuoyoujuzhong.svg assets/chuizhijuzhong.svg assets/youshang.svg assets/zuoxia.svg assets/tingzhi.svg assets/hold__easyico.svg assets/jiesuo.svg assets/terminal.svg assets/usb.svg assets/queren.svg assets/wangluo.svg assets/wangluolianjiechaoshi.svg assets/Wifi_Lock.svg assets/Wifi_Unlock.svg assets/WiFi2.svg assets/kongzhimianban2.svg assets/xiangji.svg assets/yuanchengkongzhi2.svg assets/terminal-box-line.svg assets/ceshi.gif assets/start.svg assets/stop.svg assets/flip-2.svg assets/flip.svg assets/webside.svg assets/webside2.svg config.conf StyleSheet/globalStyleSheet.qss assets/kongge.svg assets/deleteBtn.svg assets/icon/BingoTouch_Logo_H.svg ================================================ FILE: cameradialog.cpp ================================================ #include "cameradialog.h" #include "ui_cameradialog.h" #include //#include //#include "QList" //#include "QCamera" //#include "QCameraInfo" CameraDialog::CameraDialog(QWidget *parent) : QDialog(parent), ui(new Ui::CameraDialog) { ui->setupUi(this); FUI = (MainWindow*)parent; // QList list; // list = QCameraInfo::availableCameras(); // ui->Box_CameraId->clear(); // for (int i = 0; i < list.size(); i++) // { // ui->Box_CameraId->addItem(list.at(i).description()); // } this->resize((int)(SizePercent.width()*800),(int)(SizePercent.height()*480)); this->setMaximumSize((int)(SizePercent.width()*800),(int)(SizePercent.height()*480)); this->setFixedSize((int)(SizePercent.width()*800),(int)(SizePercent.height()*480)); QFont _font = ui->Btn_Sensor->font(); _font.setPointSize(this->maximumWidth() > this->maximumHeight() ? (int)this->maximumHeight()/30 : (int)this->maximumWidth()/30); ui->Btn_Sensor->setFont(_font); ui->Btn_FlipH->setFont(_font); ui->Btn_FlipV->setFont(_font); // if(ui->Windows->geometry().width() > ui->Windows->geometry().height()) // ui->Windows->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Expanding); // else // ui->Windows->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Preferred); /* 创建一个用于应用程序发送网络请求和接收网络应答的"管理员" */ manager = new QNetworkAccessManager(this); /* 创建一个要发送的请求实例 */ request = new QNetworkRequest(QUrl(((MainWindow*)FUI)->octonetwork.MainAddress +"/webcam/?action=snapshot")); request->setRawHeader("X_Api_Key",((MainWindow*)FUI)->octonetwork.X_API_Key); ui->Btn_Sensor->setChecked(false); } CameraDialog::~CameraDialog() { delete ui; } void CameraDialog::showEvent(QShowEvent *event) { Q_UNUSED(event); ui->Btn_Sensor->setChecked(true); } void CameraDialog::on_Btn_Back_clicked() { // ui->Btn_Sensor->setText("Start"); // ui->Windows->clear(); // /* 解除关联,这样就不显示了 */ // disconnect(manager, SIGNAL(finished(QNetworkReply*)), this, NULL); ui->Btn_Sensor->setChecked(false); this->close(); } /* 实现槽函数 */ void CameraDialog::mjpeg_streamer_reply(QNetworkReply *reply) { /* 读出全部数据 */ QByteArray byteArr = reply->readAll(); // qDebug() << byteArr; /* 构建pixmap */ // QPixmap pixmap; // pixmap.loadFromData(byteArr); QImage image; image.loadFromData(byteArr); // QPixmap pixmap = QPixmap::fromImage(mirroredImage); /* Label显示图像 */ ui->Windows->clear(); ui->Windows->setPixmap(QPixmap::fromImage(image.mirrored(ui->Btn_FlipH->isChecked(), ui->Btn_FlipV->isChecked()))); // ui->Windows->setScaledContents(true); ui->Windows->show(); delete(reply); /* 继续请求URL */ manager->get(*request); } void CameraDialog::on_Btn_Sensor_toggled(bool checked) { if(checked) { ui->Btn_Sensor->setText("Stop"); ui->Btn_Sensor->setIcon(QIcon(":/assets/stop.svg")); request->setUrl(QUrl(((MainWindow*)FUI)->octonetwork.MainAddress +"/webcam/?action=snapshot")); /* 设置"请求完成"与mjpeg_streamer_reply()这个槽关联 */ connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(mjpeg_streamer_reply(QNetworkReply*))); /* 开始请求URL */ manager->get(*request); } else { ui->Btn_Sensor->setText("Start"); ui->Btn_Sensor->setIcon(QIcon(":/assets/start.svg")); ui->Windows->clear(); /* 解除关联,这样就不显示了 */ disconnect(manager, SIGNAL(finished(QNetworkReply*)), this, NULL); } } ================================================ FILE: cameradialog.h ================================================ #ifndef CAMERADIALOG_H #define CAMERADIALOG_H #include #include #include extern int DebugFlat ; extern QSizeF SizePercent; //#include //#include //#include namespace Ui { class CameraDialog; } //class QCamera; //class QCameraViewfinder; //class QCameraImageCapture; class CameraDialog : public QDialog { Q_OBJECT public: explicit CameraDialog(QWidget *parent = nullptr); ~CameraDialog(); private slots: virtual void on_Btn_Back_clicked(); void mjpeg_streamer_reply(QNetworkReply *reply); void on_Btn_Sensor_toggled(bool checked); private: Ui::CameraDialog *ui; QNetworkAccessManager *manager = new QNetworkAccessManager(); QNetworkRequest *request; QWidget *FUI; protected: void showEvent(QShowEvent *event); }; #endif // CAMERADIALOG_H ================================================ FILE: cameradialog.ui ================================================ CameraDialog 0 0 800 480 0 0 .AppleSystemUIFont Camera :/assets/xiangji.svg:/assets/xiangji.svg 3 5 5 5 5 BTStyleSheet2 :/assets/huitui.svg:/assets/huitui.svg 72 72 Qt::Horizontal 40 20 border:none; font: 75 30pt "Gill Sans MT"; :/assets/camera.svg:/assets/camera.svg 72 72 Qt::Horizontal 40 20 76 72 Qt::Vertical QSizePolicy::Fixed 20 2 5 5 5 5 0 Qt::Horizontal QSizePolicy::Fixed 10 5 Qt::Vertical QSizePolicy::Preferred 20 5 0 0 true Qt::Vertical QSizePolicy::Preferred 20 5 Qt::Horizontal QSizePolicy::Fixed 10 20 7 0 0 SimSun 75 true BTStyleSheet8 Stop :/assets/stop.svg:/assets/stop.svg 140 80 true true Qt::ToolButtonTextUnderIcon 0 0 SimSun 75 true BTStyleSheet8 Flip Horizontal :/assets/flip-2.svg:/assets/flip-2.svg 140 80 true Qt::ToolButtonTextUnderIcon 0 0 SimSun 75 true BTStyleSheet8 Flip Vertical :/assets/flip.svg:/assets/flip.svg 140 80 true Qt::ToolButtonTextUnderIcon Qt::Vertical QSizePolicy::Fixed 20 2 ================================================ FILE: config.conf ================================================ /*1.0.0*/ ================================================ FILE: configuration.cpp ================================================ #include "configuration.h" #include "ui_configuration.h" #include //#include Configuration::Configuration(QWidget *parent) : QDialog(parent), ui(new Ui::Configuration) { ui->setupUi(this); FUI = (MainWindow*)parent;//((MainWindow*)FUI)->octonetwork.SendGCode(_GCode_Setting); //各个窗体名字 QStringList strList; strList.append("Wifi"); // strList.append("GConde"); strList.append("RPI Terminal"); strList.append("Gcode Terminal"); // strList.append("OctoPrint Webside"); foreach(QString item,strList) { QStandardItem *menulist = new QStandardItem(static_cast(item)); menulist->setForeground(QColor(255,255,255)); menulist->setTextAlignment(Qt::AlignCenter); if(item == "Wifi") { menulist->setIcon(QIcon(":/assets/Wifi.svg")); } else if(item == "RPI Terminal") { menulist->setIcon(QIcon(":/assets/terminal.svg")); } else if(item == "Gcode Terminal") { menulist->setIcon(QIcon(":/assets/yuanchengkongzhi.svg")); } // else if(item == "OctoPrint Webside") // { // menulist->setIcon(QIcon(":/assets/webside.svg")); // menulist->setBackground(QBrush(Qt::blue)); // } ItemModel->appendRow(menulist); } ui->Frm_ListView->setModel(ItemModel); ui->Frm_ListView->setIconSize(QSize((int)(SizePercent.width()*72),(int)(SizePercent.height()*72))); QFont font; font.setPointSize((int)(ui->Frm_ListView->font().pointSize()*(SizePercent.width() < SizePercent.height() ? SizePercent.width():SizePercent.height()))); ui->Frm_ListView->setFont(font); this->resize((int)(SizePercent.width()*800),(int)(SizePercent.height()*480)); this->setMaximumSize((int)(SizePercent.width()*800),(int)(SizePercent.height()*480)); this->setFixedSize((int)(SizePercent.width()*800),(int)(SizePercent.height()*480)); } Configuration::~Configuration() { delete ui; } void Configuration::on_Btn_Back_clicked() { this->close(); } void Configuration::showEvent(QShowEvent *event) { Q_UNUSED(event); } void Configuration::on_Frm_ListView_clicked(const QModelIndex &index) { //ui->Btn_Help->setText(index.data().toString()); if(index.data().toString() == "Wifi") ((MainWindow*)FUI)->wlanconfig->show(); if(index.data().toString() == "RPI Terminal") ((MainWindow*)FUI)->terminaldialog->show(); if(index.data().toString() == "Gcode Terminal")//GCode 控制台 ((MainWindow*)FUI)->gcodedialog->show(); // if(index.data().toString() == "OctoPrint Webside") // ((MainWindow*)FUI)->webdialog->show(); } void Configuration::on_Btn_Help_clicked() { ((MainWindow*)FUI)->wlanconfig->GetNetworkInfo(); } ================================================ FILE: configuration.h ================================================ #ifndef CONFIGURATION_H #define CONFIGURATION_H #include #include #include extern int DebugFlat ; extern QSizeF SizePercent; namespace Ui { class Configuration; } class Configuration : public QDialog { Q_OBJECT public: explicit Configuration(QWidget *parent = nullptr); ~Configuration(); private slots: virtual void on_Btn_Back_clicked(); void on_Frm_ListView_clicked(const QModelIndex &index); void on_Btn_Help_clicked(); private: Ui::Configuration *ui; QWidget *FUI; QStandardItemModel *ItemModel = new QStandardItemModel(this); protected: void showEvent(QShowEvent *event); }; #endif // CONFIGURATION_H ================================================ FILE: configuration.ui ================================================ Configuration 0 0 800 480 0 0 Configuration :/assets/xitongpeizhi.svg:/assets/xitongpeizhi.svg 3 5 5 5 5 5 5 5 5 BTStyleSheet2 :/assets/huitui.svg:/assets/huitui.svg 72 72 Qt::Horizontal 40 20 border:none; font: 75 30pt "Gill Sans MT"; :/assets/xitongpeizhi.svg:/assets/xitongpeizhi.svg 72 72 Qt::Horizontal 40 20 BTStyleSheet2 Qt::RightToLeft :/assets/help.svg:/assets/help.svg 72 72 0 0 50 QAbstractItemView::NoEditTriggers QListView::Adjust ================================================ FILE: controlpanel.cpp ================================================ #include "controlpanel.h" #include "ui_controlpanel.h" #include #include #include //#include #include #include #include #include #include ControlPanel::ControlPanel(QWidget *parent) : QDialog(parent), ui(new Ui::ControlPanel) { ui->setupUi(this); FUI = (MainWindow*)parent;//((MainWindow*)FUI)->octonetwork.SendGCode(_GCode_Setting); //使控件适应屏幕的大小 this->resize((int)(SizePercent.width()*800),(int)(SizePercent.height()*480)); //将控件大小固定为800*480 this->setMaximumSize((int)(SizePercent.width()*800),(int)(SizePercent.height()*480)); this->setFixedSize((int)(SizePercent.width()*800),(int)(SizePercent.height()*480)); //设置冷热按键的样式表 ui->Btn_Cool->setStyleSheet("QPushButton {padding: 10px;border-style: solid;border-width: 5px;border-radius: 20px;border-color: rgb(36, 148, 251);color: rgb(245, 246, 250);}"\ "QPushButton:hover {padding: 10px;border-style: solid;border-width: 5px;border-radius: 20px;border-color: rgb(36, 148, 251); background-color: rgb(18, 74, 125);}"\ "QPushButton:pressed{padding: 10px;border-style: solid;border-width: 5px;border-radius: 20px;border-color: rgb(36, 148, 251); background-color: rgb(18, 74, 125); padding-right:4px;padding-bottom:4px;}"); ui->Btn_Heat->setStyleSheet("QPushButton {padding: 10px;border-style: solid;border-width: 5px;border-radius: 20px;border-color: rgb(216, 30, 6);color: rgb(245, 246, 250);}"\ "QPushButton:hover {padding: 10px;border-style: solid;border-width: 5px;border-radius: 20px;border-color: rgb(216, 30, 6); background-color: rgb(108, 15, 3);}"\ "QPushButton:pressed{padding: 10px;border-style: solid;border-width: 5px;border-radius: 20px;border-color: rgb(216, 30, 6); background-color: rgb(108, 15, 3); padding-right:4px;padding-bottom:4px;}"); ui->Btn_Axle_Home->setStyleSheet("border-color: rgb(230, 230, 230);"); ui->Btn_Unlock->setStyleSheet("border-color: rgb(43, 166, 56);"); ui->Btn_Restore->setStyleSheet("border-color: rgb(205, 205, 205);"); ui->Btn_Shutdown->setStyleSheet("border-color: rgb(216, 30, 6);"); ui->Btn_Extruder_E->setStyleSheet("border-color: rgb(245, 246, 255);"); ui->Btn_Extruder_R->setStyleSheet("border-color: rgb(245, 246, 255);"); } ControlPanel::~ControlPanel() { delete ui; } void ControlPanel::on_Btn_Back_clicked() { this->close();//关闭窗口 } void ControlPanel::on_Btn_R_1_clicked() { MoveSpeed = 1; ui->Btn_R_1->setStyleSheet(SelectKey); ui->Btn_R_5->setStyleSheet(UnSelectKey); ui->Btn_R_10->setStyleSheet(UnSelectKey); ui->Btn_R_50->setStyleSheet(UnSelectKey); ui->Btn_R_100->setStyleSheet(UnSelectKey); } void ControlPanel::on_Btn_R_5_clicked() { MoveSpeed = 5; ui->Btn_R_1->setStyleSheet(UnSelectKey); ui->Btn_R_5->setStyleSheet(SelectKey); ui->Btn_R_10->setStyleSheet(UnSelectKey); ui->Btn_R_50->setStyleSheet(UnSelectKey); ui->Btn_R_100->setStyleSheet(UnSelectKey); } void ControlPanel::on_Btn_R_10_clicked() { MoveSpeed = 10; ui->Btn_R_1->setStyleSheet(UnSelectKey); ui->Btn_R_5->setStyleSheet(UnSelectKey); ui->Btn_R_10->setStyleSheet(SelectKey); ui->Btn_R_50->setStyleSheet(UnSelectKey); ui->Btn_R_100->setStyleSheet(UnSelectKey); } void ControlPanel::on_Btn_R_50_clicked() { MoveSpeed = 50; ui->Btn_R_1->setStyleSheet(UnSelectKey); ui->Btn_R_5->setStyleSheet(UnSelectKey); ui->Btn_R_10->setStyleSheet(UnSelectKey); ui->Btn_R_50->setStyleSheet(SelectKey); ui->Btn_R_100->setStyleSheet(UnSelectKey); } void ControlPanel::on_Btn_R_100_clicked() { MoveSpeed = 100; ui->Btn_R_1->setStyleSheet(UnSelectKey); ui->Btn_R_5->setStyleSheet(UnSelectKey); ui->Btn_R_10->setStyleSheet(UnSelectKey); ui->Btn_R_50->setStyleSheet(UnSelectKey); ui->Btn_R_100->setStyleSheet(SelectKey); } void ControlPanel::on_Btn_Heat_toggled(bool checked) { if(checked)//如果升温按钮被点击,关闭降温按钮 { ui->Btn_Cool->setStyleSheet("QPushButton {padding: 10px;border-style: solid;border-width: 5px;border-radius: 20px;border-color: rgb(36, 148, 251);}"\ "QPushButton:hover {padding: 10px;border-style: solid;border-width: 5px;border-radius: 20px;border-color: rgb(36, 148, 251); background-color: rgb(18, 74, 125);}"\ "QPushButton:pressed{padding: 10px;border-style: solid;border-width: 5px;border-radius: 20px;border-color: rgb(36, 148, 251); background-color: rgb(18, 74, 125); padding-right:4px;padding-bottom:4px;}"); ui->Btn_Heat->setStyleSheet("QPushButton {padding: 10px;border-style: solid;border-width: 5px;border-radius: 20px;border-color: rgb(216, 30, 6); background-color: rgb(108, 15, 3); padding-right:4px;padding-bottom:4px;}"\ "QPushButton:hover {padding: 10px;border-style: solid;border-width: 5px;border-radius: 20px;border-color: rgb(216, 30, 6); background-color: rgb(108, 15, 3); padding-right:4px;padding-bottom:4px;}"\ "QPushButton:pressed{padding: 10px;border-style: solid;border-width: 5px;border-radius: 20px;border-color: rgb(216, 30, 6); background-color: rgb(108, 15, 3); padding-right:4px;padding-bottom:4px;}"); if(ui->Btn_Cool->isChecked()) { ui->Btn_Cool->setChecked(false); //发送升温指令 QList _GCode_Setting; _GCode_Setting.append("M140 S60"); _GCode_Setting.append("M104 S200"); ((MainWindow*)FUI)->octonetwork.SendGCode(_GCode_Setting); } } } void ControlPanel::on_Btn_Cool_toggled(bool checked) { if(checked) { ui->Btn_Heat->setStyleSheet("QPushButton {padding: 10px;border-style: solid;border-width: 5px;border-radius: 20px;border-color: rgb(216, 30, 6);}"\ "QPushButton:hover {padding: 10px;border-style: solid;border-width: 5px;border-radius: 20px;border-color: rgb(216, 30, 6); background-color: rgb(108, 15, 3);}"\ "QPushButton:pressed{padding: 10px;border-style: solid;border-width: 5px;border-radius: 20px;border-color: rgb(216, 30, 6); background-color: rgb(108, 15, 3); padding-right:4px;padding-bottom:4px;}"); ui->Btn_Cool->setStyleSheet("QPushButton {padding: 10px;border-style: solid;border-width: 5px;border-radius: 20px;border-color: rgb(36, 148, 251); background-color: rgb(18, 74, 125); padding-right:4px;padding-bottom:4px;}"\ "QPushButton:hover {padding: 10px;border-style: solid;border-width: 5px;border-radius: 20px;border-color: rgb(36, 148, 251); background-color: rgb(18, 74, 125); padding-right:4px;padding-bottom:4px;}"\ "QPushButton:pressed{padding: 10px;border-style: solid;border-width: 5px;border-radius: 20px;border-color: rgb(36, 148, 251); background-color: rgb(18, 74, 125); padding-right:4px;padding-bottom:4px;}"); } // ui->Btn_Cool->setStyleSheet(checked?ui->Btn_Cool->styleSheet()+"background-color:rgb(18, 74, 125);":"padding: 10px;\nborder-style: solid;\nborder-width: 5px;\nborder-radius: 20px;\nborder-color: rgb(36, 148, 251);"); QList _GCode_; if(checked)//如果降下温按钮被点击,关闭升温按钮 { if(ui->Btn_Heat->isChecked()) ui->Btn_Heat->setChecked(false); //发送降温指令 _GCode_.append("M106 S255"); _GCode_.append("M104 S0"); _GCode_.append("M140 S0"); } else { _GCode_.append("M106 S0");//? } ((MainWindow*)FUI)->octonetwork.SendGCode(_GCode_); } //坐标归位按键按下所有坐标归位,按键变色 void ControlPanel::on_Btn_Axle_Home_clicked() { //发送归位指令 QList _GCode_; _GCode_.append("G91"); _GCode_.append("G28"); _GCode_.append("G90"); ((MainWindow*)FUI)->octonetwork.SendGCode(_GCode_); } //Unlock Motors 锁定喷头温度和工床温度 void ControlPanel::on_Btn_Unlock_clicked() { QList _GCode_; _GCode_.append("M18"); ((MainWindow*)FUI)->octonetwork.SendGCode(_GCode_); } //重启 OctoBTT、重启OctoPrint以及取消 void ControlPanel::on_Btn_Restore_clicked() { // StyleSheet_Temp = ui->Btn_Restore->styleSheet();//获取按键的样式表用以恢复颜色 // ui->Btn_Restore->setStyleSheet(StyleSheet_Temp+"\nbackground-color:rgb(128,128,128,128);"); QStringList btnName = {"Restart OctoBTT" , "Restart OctoPrint", "Cancel"} ; CustomDialog *newDialog = new CustomDialog(); QObject::connect(newDialog, &CustomDialog::OutputEvent, newDialog,[=](QString instruct) { if(instruct == "Restart OctoBTT") { //重启OctoBTT qApp->exit(Base_Restart); } else if(instruct == "Restart OctoPrint") { //重启Octoprint QProcess P(0); P.start("sudo service octoprint restart"); P.waitForStarted(); P.waitForFinished(); qApp->exit(Base_Restart); } }); newDialog->showCustomDialog("what do you want ?",":/assets/zhongzhi.svg",btnName,this); } //紧急制停、关机以及取消 void ControlPanel::on_Btn_Shutdown_clicked() { QStringList btnName = {"Emergency Stop" , "Shutdown", "Cancel"} ; CustomDialog *newDialog = new CustomDialog(); QObject::connect(newDialog, &CustomDialog::OutputEvent, newDialog,[=](QString instruct) { if(instruct == "Emergency Stop") { //紧急制停 QList _GCode_; // _GCode_.append("M110 N0"); _GCode_.append("M112"); ((MainWindow*)FUI)->octonetwork.SendGCode(_GCode_); } else if(instruct == "Shutdown") { //关机 QProcess P(0); P.start("xset dpms force off"); P.waitForStarted(); P.waitForFinished(); qApp->exit(Base_Shutdown); } }); newDialog->showCustomDialog("what do you want ?",":/assets/hazard.svg",btnName,this); } void ControlPanel::on_Btn_Axle_X_clicked() { QList _GCode_; _GCode_.append("G91"); _GCode_.append("G28 X"); _GCode_.append("G90"); ((MainWindow*)FUI)->octonetwork.SendGCode(_GCode_); } void ControlPanel::on_Btn_Axle_Y_clicked() { QList _GCode_; _GCode_.append("G91"); _GCode_.append("G28 Y"); _GCode_.append("G90"); ((MainWindow*)FUI)->octonetwork.SendGCode(_GCode_); } void ControlPanel::on_Btn_Axle_Z_clicked() { QList _GCode_; _GCode_.append("G91"); _GCode_.append("G28 Z"); _GCode_.append("G90"); ((MainWindow*)FUI)->octonetwork.SendGCode(_GCode_); } void ControlPanel::on_Btn_XY_Res_clicked() { QList _GCode_; _GCode_.append("G91"); _GCode_.append("G28 X Y"); _GCode_.append("G90"); ((MainWindow*)FUI)->octonetwork.SendGCode(_GCode_); } void ControlPanel::on_Btn_Y_Add_clicked() { QList _GCode_; _GCode_.append("G91"); _GCode_.append("G1 Y"+QString::number(MoveSpeed)+" F6000"); _GCode_.append("G90"); ((MainWindow*)FUI)->octonetwork.SendGCode(_GCode_); } void ControlPanel::on_Btn_Y_Dec_clicked() { QList _GCode_; _GCode_.append("G91"); _GCode_.append("G1 Y-"+QString::number(MoveSpeed)+" F6000"); _GCode_.append("G90"); ((MainWindow*)FUI)->octonetwork.SendGCode(_GCode_); } void ControlPanel::on_Btn_X_Dec_clicked() { QList _GCode_; _GCode_.append("G91"); _GCode_.append("G1 X-"+QString::number(MoveSpeed)+" F6000"); _GCode_.append("G90"); ((MainWindow*)FUI)->octonetwork.SendGCode(_GCode_); } void ControlPanel::on_Btn_X_Add_clicked() { QList _GCode_; _GCode_.append("G91"); _GCode_.append("G1 X"+QString::number(MoveSpeed)+" F6000"); _GCode_.append("G90"); ((MainWindow*)FUI)->octonetwork.SendGCode(_GCode_); } void ControlPanel::on_Btn_Z_Add_clicked() { QList _GCode_; _GCode_.append("G91"); _GCode_.append("G1 Z"+QString::number(MoveSpeed)+" F200"); _GCode_.append("G90"); ((MainWindow*)FUI)->octonetwork.SendGCode(_GCode_); } void ControlPanel::on_Btn_Z_Dec_clicked() { QList _GCode_; _GCode_.append("G91"); _GCode_.append("G1 Z-"+QString::number(MoveSpeed)+" F200"); _GCode_.append("G90"); ((MainWindow*)FUI)->octonetwork.SendGCode(_GCode_); } void ControlPanel::on_Btn_Extruder_R_clicked() { QList _GCode_; _GCode_.append("G91"); _GCode_.append("G1 E-"+QString::number(MoveSpeed)+" F300"); _GCode_.append("G90"); ((MainWindow*)FUI)->octonetwork.SendGCode(_GCode_); } void ControlPanel::on_Btn_Extruder_E_clicked() { QList _GCode_; _GCode_.append("G91"); _GCode_.append("G1 E"+QString::number(MoveSpeed)+" F300"); _GCode_.append("G90"); ((MainWindow*)FUI)->octonetwork.SendGCode(_GCode_); } void ControlPanel::on_Btn_Z_BS_Add_clicked() { QList _GCode_; // _GCode_.append("M110 N0"); _GCode_.append("G91"); _GCode_.append("M290 Z"+QString::number((double)MoveSpeed/100)); _GCode_.append("M500"); _GCode_.append("G90"); ((MainWindow*)FUI)->octonetwork.SendGCode(_GCode_); } void ControlPanel::on_Btn_Z_BS_Dec_clicked() { QList _GCode_; // _GCode_.append("M110 N0"); _GCode_.append("G91"); _GCode_.append("M290 Z-"+QString::number((double)MoveSpeed/100)); _GCode_.append("M500"); _GCode_.append("G90"); ((MainWindow*)FUI)->octonetwork.SendGCode(_GCode_); } //自动调平按键 void ControlPanel::on_Btn_Level_clicked() { //如果点击退出,关闭弹窗 if(((MainWindow*)FUI)->octonetwork.ConnectState == "Operational") { QStringList btnName = {"Yes", "No"} ; CustomDialog *newDialog = new CustomDialog(); QObject::connect(newDialog, &CustomDialog::OutputEvent, newDialog,[=](QString instruct) { if(instruct == "Yes") { QList _GCode_; _GCode_.append("M502"); _GCode_.append("M500"); _GCode_.append("G91"); _GCode_.append("G28"); _GCode_.append("G29"); _GCode_.append("G90"); _GCode_.append("M500"); ((MainWindow*)FUI)->octonetwork.SendGCode(_GCode_); } }); newDialog->showCustomDialog("Self-leveling",":/assets/kongzhimianban_B.svg",btnName,"Whether the automatic leveling sensor has been installed ?",this); } else { CustomDialog *newDialog = new CustomDialog(); newDialog->showCustomDialog("Self-leveling",":/assets/kongzhimianban_B.svg","Current state not supported !",this); } } ================================================ FILE: controlpanel.h ================================================ #ifndef CONTROLPANEL_H #define CONTROLPANEL_H #include #include #include #include "customdialog.h" extern int DebugFlat ; extern QSizeF SizePercent; const static int Base_Restart = 773; const static int Base_Shutdown = 772; const static int Base_OnlyExitApp = 770; namespace Ui { class ControlPanel; } class ControlPanel : public QDialog { Q_OBJECT public: explicit ControlPanel(QWidget *parent = nullptr); ~ControlPanel(); private slots: virtual void on_Btn_Back_clicked(); virtual void on_Btn_R_1_clicked(); virtual void on_Btn_R_5_clicked(); virtual void on_Btn_R_10_clicked(); virtual void on_Btn_R_50_clicked(); virtual void on_Btn_R_100_clicked(); virtual void on_Btn_Heat_toggled(bool checked); virtual void on_Btn_Cool_toggled(bool checked); virtual void on_Btn_Axle_Home_clicked(); virtual void on_Btn_Unlock_clicked(); virtual void on_Btn_Restore_clicked(); virtual void on_Btn_Shutdown_clicked(); virtual void on_Btn_Axle_X_clicked(); virtual void on_Btn_Axle_Y_clicked(); virtual void on_Btn_Axle_Z_clicked(); virtual void on_Btn_XY_Res_clicked(); virtual void on_Btn_Y_Add_clicked(); virtual void on_Btn_Y_Dec_clicked(); virtual void on_Btn_X_Dec_clicked(); virtual void on_Btn_X_Add_clicked(); virtual void on_Btn_Z_Add_clicked(); virtual void on_Btn_Z_Dec_clicked(); virtual void on_Btn_Extruder_R_clicked(); virtual void on_Btn_Extruder_E_clicked(); virtual void on_Btn_Z_BS_Add_clicked(); virtual void on_Btn_Z_BS_Dec_clicked(); virtual void on_Btn_Level_clicked(); private: Ui::ControlPanel *ui; QString UnSelectKey = "QPushButton{color: rgb(245, 246, 250); border-color:rgb(245, 246, 250); border-style: solid; border-width: 5px; border-radius: 20px;}"\ "QPushButton:hover{border:none;background-color:rgb(128,128,128,128); border-color:rgb(245, 246, 250); border-style: solid; border-width: 5px; border-radius: 20px;}"\ "QPushButton:pressed{border:none; padding-right:4px; padding-bottom:4px; border-color:rgb(245, 246, 250); border-style: solid; border-width: 5px; border-radius: 20px;}"; QString SelectKey = "background-color: rgb(128,128,128);\ncolor: rgb(245, 246, 250);\nborder-color:rgb(0, 255, 0)"; QString StyleSheet_Temp; int MoveSpeed = 10; QWidget *FUI; int RestoreFlag = 0; }; #endif // CONTROLPANEL_H ================================================ FILE: controlpanel.ui ================================================ ControlPanel 0 0 800 480 0 0 Control :/assets/Ddayin.svg:/assets/Ddayin.svg 3 5 5 5 5 BTStyleSheet2 :/assets/huitui.svg:/assets/huitui.svg 72 72 Qt::Horizontal 40 20 border:none; font: 75 30pt "Gill Sans MT"; :/assets/jixiezhizao.svg:/assets/jixiezhizao.svg 72 72 Qt::Horizontal 40 20 84 78 2 5 QLayout::SetDefaultConstraint 2 Qt::Horizontal QSizePolicy::Fixed 40 10 0 0 BTStyleSheet2 :/assets/you.svg:/assets/you.svg 64 64 Btn_Axle 0 0 BTStyleSheet2 Qt::LeftToRight :/assets/shangxiajuzhong.svg:/assets/shangxiajuzhong.svg 64 64 Qt::Horizontal QSizePolicy::Fixed 40 10 0 0 BTStyleSheet2 :/assets/youshang.svg:/assets/youshang.svg 64 64 Btn_Axle Qt::Horizontal QSizePolicy::Fixed 40 10 0 0 Gill Sans MT 15 75 true border: none; color: rgb(245, 246, 250); Z BabyStep 0 0 Gill Sans MT 15 75 true border: none; color: rgb(245, 246, 250); Z 0 0 Gill Sans MT 15 75 true border: none; color: rgb(245, 246, 250); X 0 0 Gill Sans MT 15 75 true border: none; color: rgb(245, 246, 250); Restore 0 0 Gill Sans MT 20 75 true BTStyleSheet1 Ext. 64 64 Qt::Horizontal QSizePolicy::Fixed 40 10 0 0 BTStyleSheet2 Qt::LeftToRight :/assets/zuoyoujuzhong.svg:/assets/zuoyoujuzhong.svg 64 64 0 0 Gill Sans MT 15 75 true border: none; color: rgb(245, 246, 250); Level Qt::Horizontal QSizePolicy::Fixed 40 10 0 0 XY Axle Restore BTStyleSheet2 :/assets/yuandian_W.svg:/assets/yuandian_W.svg 64 64 Btn_Axle 0 0 BabyStep : Speed Value Divided By One Hundred BTStyleSheet2 :/assets/shangsheng.svg:/assets/shangsheng.svg 64 64 0 0 BTStyleSheet2 :/assets/shang.svg:/assets/shang.svg 64 64 Btn_Axle 0 0 Gill Sans MT 15 75 true border: none; color: rgb(245, 246, 250); Y 0 0 BTStyleSheet2 :/assets/xia.svg:/assets/xia.svg 64 64 Btn_Axle Qt::Horizontal QSizePolicy::Fixed 40 10 0 0 Gill Sans MT 20 75 true BTStyleSheet1 Ret. 64 64 Qt::Horizontal QSizePolicy::Fixed 40 10 0 0 BTStyleSheet2 :/assets/kongzhimianban.svg:/assets/kongzhimianban.svg 64 64 Btn_Axle Qt::Horizontal QSizePolicy::Fixed 40 10 0 0 BabyStep : Speed Value Divided By One Hundred BTStyleSheet2 :/assets/xiajiang.svg:/assets/xiajiang.svg 64 64 0 0 BTStyleSheet2 :/assets/zuoxia.svg:/assets/zuoxia.svg 64 64 Btn_Axle 0 0 BTStyleSheet2 Qt::LeftToRight :/assets/zuo.svg:/assets/zuo.svg 64 64 Btn_Axle 0 0 BTStyleSheet2 Qt::LeftToRight :/assets/chuizhijuzhong.svg:/assets/chuizhijuzhong.svg 64 64 0 0 Gill Sans MT 15 75 true border: none; color: rgb(245, 246, 250); Speed padding: 10px; border-style: solid; border-width: 5px; border-radius: 20px; Gill Sans MT 20 75 true color: rgb(245, 246, 250); 1 true false Btn_Rate Gill Sans MT 20 75 true color: rgb(245, 246, 250); 5 true false Btn_Rate Gill Sans MT 20 75 true color: rgb(245, 246, 250); border-color:rgb(0, 255, 0); background-color: rgb(128, 128, 128); 10 true true Btn_Rate Gill Sans MT 20 75 true color: rgb(245, 246, 250); 50 true false Btn_Rate Gill Sans MT 20 75 true color: rgb(245, 246, 250); 100 true false Btn_Rate QLayout::SetDefaultConstraint 3 0 0 BTStyleSheet1 :/assets/zhongzhi.svg:/assets/zhongzhi.svg 64 64 0 0 BTStyleSheet1 :/assets/hazard.svg:/assets/hazard.svg 64 64 0 0 :/assets/shuangdong.svg:/assets/shuangdong.svg 64 64 true false 0 0 BTStyleSheet1 :/assets/huijia.svg:/assets/huijia.svg 64 64 0 0 BTStyleSheet1 :/assets/jiesuo.svg:/assets/jiesuo.svg 64 64 0 0 :/assets/jiare.svg:/assets/jiare.svg 64 64 true false ================================================ FILE: customdialog.cpp ================================================ #include "customdialog.h" /// windowName:窗体标题 /// windowIcon:窗体标识图片路径 /// buttonName:按键水平布局---纯按键(垂直布局) /// textContent:文本垂直布局 void CustomDialog::showCustomDialog(QString windowName, QString windowIcon, QStringList buttonName, QString textContent, QWidget *parent) { //传参 _WindowName = windowName; _WindowIcon = windowIcon; _ButtonName = buttonName; _TextContent = textContent; _Parent = parent; //背景颜色 this->setWindowOpacity(0.9); //透明度 this->setStyleSheet("background-color: rgba(128, 128, 128, 25%)"); //背景 //设置窗口的标题和标识 this->setWindowTitle(_WindowName); this->setWindowIcon(QIcon(_WindowIcon)); //适应屏幕大小 this->resize(_Parent->width()*0.9,_Parent->height()*0.9); this->setFixedSize(_Parent->width()*0.9,_Parent->height()*0.9); //使弹窗居中显示 this->move(_Parent->pos().x() + (_Parent->width() - this->width()) / 2,_Parent->pos().y() + (_Parent->height() - this->height()) / 2); //设置文本显示 QTextBrowser textBrowser; textBrowser.setStyleSheet("border: none; color: rgb(245, 246, 255);background-color: rgba(128, 128, 128, 0%);"); textBrowser.setText(_TextContent); textBrowser.setFixedSize(_Parent->width()*0.877,_Parent->height()*0.5); // textBrowser.move(); // textBrowser.setGeometry(50,50,_Parent->width()*800*0.8,_Parent->height()*480*0.5); textBrowser.setAlignment(Qt::AlignCenter); //根据QStringList buttonName创建按键 QList btn; for(int i = 0;i < _ButtonName.count() ;i++) { btn.append(new QPushButton(_ButtonName[i])); btn[i] = new QPushButton(_ButtonName[i]); //指定按键样式 btn[i]->setWhatsThis("BTStyleSheet"); //调整字体大小 QFont _font = btn[i]->font(); _font.setPointSize(_Parent->maximumWidth() > _Parent->maximumHeight() ? (int)_Parent->maximumHeight()/30 : (int)_Parent->maximumWidth()/30); btn[i]->setFont(_font); textBrowser.setFont(_font); } //调整按键和文本的位置 //文本垂直布局 QVBoxLayout VLayout(this); VLayout.addSpacing(150); VLayout.addWidget(&textBrowser); VLayout.addSpacing(300); //按键水平布局 QHBoxLayout RestartBT; foreach(QPushButton *item , btn) { RestartBT.addWidget(item); //按键信号连接槽 QObject::connect(item, &QPushButton::clicked, this,[=]() { QPushButton *optBtn = qobject_cast(sender()); emit OutputEvent(optBtn->text()); this->close(); }); } VLayout.addLayout(&RestartBT); //模态显示 this->exec(); } void CustomDialog::showCustomDialog(QString windowName, QString windowIcon, QStringList buttonName, QWidget *parent) { //传参 _WindowName = windowName; _WindowIcon = windowIcon; _ButtonName = buttonName; _Parent = parent; //背景颜色 this->setWindowOpacity(0.9); //透明度 this->setStyleSheet("background-color: rgba(128, 128, 128, 25%)"); //背景 //设置窗口的标题和标识 this->setWindowTitle(_WindowName); this->setWindowIcon(QIcon(_WindowIcon)); //适应屏幕大小 this->resize(_Parent->width()*0.9,_Parent->height()*0.9); this->setFixedSize(_Parent->width()*0.9,_Parent->height()*0.9); //使弹窗居中显示 this->move(_Parent->pos().x() + (_Parent->width() - this->width()) / 2,_Parent->pos().y() + (_Parent->height() - this->height()) / 2); //根据QStringList buttonName创建按键 QList btn; for(int i = 0;i < _ButtonName.count() ;i++) { btn.append(new QPushButton(_ButtonName[i])); btn[i] = new QPushButton(_ButtonName[i]); //指定按键样式 btn[i]->setWhatsThis("BTStyleSheet"); //调整字体大小 QFont _font = btn[i]->font(); _font.setPointSize(_Parent->maximumWidth() > _Parent->maximumHeight() ? (int)_Parent->maximumHeight()/30 : (int)_Parent->maximumWidth()/30); btn[i]->setFont(_font); } //调整按键的位置 QVBoxLayout VLayout(this); //按键水平布局 foreach(QPushButton *item , btn) { VLayout.addWidget(item); //按键信号连接槽 QObject::connect(item, &QPushButton::clicked, this,[=]() { QPushButton *optBtn = qobject_cast(sender()); emit OutputEvent(optBtn->text()); this->close(); }); } //模态显示 this->exec(); } void CustomDialog::showCustomDialog(QString windowName, QString windowIcon, QString textContent, QWidget *parent) { QStringList btnName = {"Ok"}; showCustomDialog(windowName, windowIcon, btnName, textContent, parent); } ================================================ FILE: customdialog.h ================================================ #ifndef CUSTOMDIALOG_H #define CUSTOMDIALOG_H #include #include #include #include #include class CustomDialog : public QDialog { Q_OBJECT public: //文本加按键(按键属于水平布局,文本和按键属于垂直布局) void showCustomDialog(QString windowName, QString windowIcon, QStringList buttonName, QString textContent, QWidget *parent = nullptr); //纯按键(垂直布局) void showCustomDialog(QString windowName, QString windowIcon, QStringList buttonName, QWidget *parent = nullptr); //纯文本(居中显示,提醒语句) void showCustomDialog(QString windowName, QString windowIcon, QString textContent, QWidget *parent = nullptr); private: QString _WindowName; QString _WindowIcon; QStringList _ButtonName; QString _TextContent; QWidget *_Parent; signals: void OutputEvent(QString); }; #endif // CUSTOMDIALOG_H ================================================ FILE: filedialog.cpp ================================================ #include "filedialog.h" #include "ui_filedialog.h" //MY Dialog #include #include #include #include #include #include #include #include #include #include #include //#include FileDialog::FileDialog(QWidget *parent) : QDialog(parent), ui(new Ui::FileDialog) { ui->setupUi(this); FUI = (MainWindow*)parent; // SelectURL = QUrl(((MainWindow*)FUI)->octonetwork.MainUrl + "files/local/Demo.gcode"); //Init File // QObject::connect(((MainWindow*)FUI)->octonetwork.FSnetworkAccessManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(FSReply(QNetworkReply*)),Qt::UniqueConnection); // ((MainWindow*)FUI)->octonetwork.FSnetworkAccessManager->get(((MainWindow*)FUI)->octonetwork.FileRequest); terminal_timer = new QTimer(this); terminal_timer->setSingleShot(true); this->resize((int)(SizePercent.width()*800),(int)(SizePercent.height()*480)); this->setMaximumSize((int)(SizePercent.width()*800),(int)(SizePercent.height()*480)); this->setFixedSize((int)(SizePercent.width()*800),(int)(SizePercent.height()*480)); QFont _font = ui->Btn_Upload->font(); _font.setPointSize(this->maximumWidth() > this->maximumHeight() ? (int)this->maximumHeight()/30 : (int)this->maximumWidth()/30); ui->Btn_Upload->setFont(_font); ui->Btn_Print->setFont(_font); ui->Btn_Delete->setFont(_font); /* 创建一个用于应用程序发送网络请求和接收网络应答的"管理员" */ manager = new QNetworkAccessManager(this); /* 创建一个要发送的请求实例 */ request = new QNetworkRequest(QUrl(((MainWindow*)FUI)->octonetwork.MainUrl +"/files")); request->setRawHeader("X_Api_Key",((MainWindow*)FUI)->octonetwork.X_API_Key); // InitializeUSBDrive(); } FileDialog::~FileDialog() { delete ui; } void FileDialog::showEvent(QShowEvent *event) { Q_UNUSED(event); RefreshFileList(); // ui->Btn_Upload->setEnabled(true); } void FileDialog::on_Btn_back_clicked() { this->close(); } void FileDialog::on_Btn_Refresh_pressed() { StyleSheet_Temp = ui->Btn_Refresh->styleSheet(); ui->Btn_Refresh->setStyleSheet(StyleSheet_Temp+"\nbackground-color:rgb(128,128,128,128);"); } void FileDialog::on_Btn_Refresh_released() { ui->Btn_Refresh->setStyleSheet(StyleSheet_Temp); } void FileDialog::RefreshFileList() { ReFreshJson(); disconnect(((MainWindow*)FUI)->terminaldialog,&TerminalDialog::CMD_Reply,0,0); // QObject::connect(((MainWindow*)FUI)->terminaldialog,&TerminalDialog::CMD_Reply,this,SLOT(GetDirlist(QStringList))); QObject::connect(((MainWindow*)FUI)->terminaldialog,&TerminalDialog::CMD_Reply,this,[=](QStringList CommandLine) { GetDirlist(CommandLine); }); ((MainWindow*)FUI)->terminaldialog->SendCMD("cd /home/pi/USB && find [s,h]d[a-z]* -maxdepth 0 -type d -regex \"[s,h]d[a-z][0-9]+$\"; cd /home/pi",TeminalState); QObject::connect(terminal_timer,SIGNAL(timeout()),this,SLOT(GetDirlistTimeout())); terminal_timer->start(500); } void FileDialog::ReFreshJson() { //ReFresh Json ((MainWindow*)FUI)->octonetwork.SD_ReLoad(); //Reload FileList // if(((MainWindow*)FUI)->octonetwork.ConnectState == "Operational" || ((MainWindow*)FUI)->octonetwork.ConnectState == "Pausing" || ((MainWindow*)FUI)->octonetwork.ConnectState == "Starting" || ((MainWindow*)FUI)->octonetwork.ConnectState == "Printing" || ((MainWindow*)FUI)->octonetwork.ConnectState == "Cancelling") // {} ((MainWindow*)FUI)->octonetwork.FSnetworkAccessManager->disconnect(SIGNAL(finished(QNetworkReply*)));//disconnect QObject::connect(((MainWindow*)FUI)->octonetwork.FSnetworkAccessManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(FSReply(QNetworkReply*)),Qt::UniqueConnection); ((MainWindow*)FUI)->octonetwork.FSnetworkAccessManager->get(((MainWindow*)FUI)->octonetwork.FileRequest); } void FileDialog::on_Btn_Refresh_clicked() { RefreshFileList(); } void FileDialog::FSReply(QNetworkReply *reply) { int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); if(reply->error() == QNetworkReply::NoError) { QByteArray replyArray = reply->readAll(); QJsonDocument loadDoc(QJsonDocument::fromJson(replyArray)); QJsonObject QObj = loadDoc.object(); //建立列表 ui->treeWidget->clear(); QTreeWidgetItem *RootItem = new QTreeWidgetItem(ui->treeWidget,QStringList(QString("Local"))); RootItem->setIcon(0,QIcon(":/assets/wenjian.svg")); // QTreeWidgetItem *USBItem = new QTreeWidgetItem(ui->treeWidget,QStringList(QString("USB"))); // USBItem->setIcon(0,QIcon(":/assets/usb.svg")); // QList *USBItem; SDcardItem = new QTreeWidgetItem(ui->treeWidget,QStringList(QString("Board"))); SDcardItem->setIcon(0,QIcon(":/assets/wenjian.svg")); FilesPraser(RootItem , QObj.constFind("files").value().toArray()); QCoreApplication::processEvents();//update Dir QList USBDev = LoadUSBPath("/home/pi/USB"); QList AllItems; AllItems.append(RootItem); AllItems.append(USBDev); AllItems.append(SDcardItem); if(SDcardItem->childCount() <= 0) { SDcardItem->setHidden(true); } ui->treeWidget->insertTopLevelItems(0,AllItems); ui->treeWidget->setItemsExpandable(true); ui->treeWidget->expandAll(); if(QSysInfo::productType() != "raspbian"){ LibLog::LogRec(QString("%1___%2___%3").arg(QString(replyArray)).arg(__FILE__).arg(__LINE__), "connect"); } } if(QSysInfo::productType() != "raspbian") { LibLog::LogRec(QString("statusCode : %1___%2___%3").arg(statusCode).arg(__FILE__).arg(__LINE__), "connect"); LibLog::LogRec("***************************************" ,"connect"); } reply->deleteLater(); ui->Btn_Delete->setEnabled(false); ui->Btn_Print->setEnabled(false); ui->Btn_Upload->setEnabled(false); ((MainWindow*)FUI)->octonetwork.FSnetworkAccessManager->disconnect(SIGNAL(finished(QNetworkReply*)));//disconnect } QList FileDialog::LoadUSBPath(QString USBPath) { QList USBDev; QDir RootDir = QDir(USBPath); if(RootDir.exists() && RootDir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot).count() > 0)//文件夹存在,并且包含内容 { QDirIterator dir_iterator(USBPath, QDir::Dirs | QDir::NoDotAndDotDot/*,QDirIterator::Subdirectories*/); while(dir_iterator.hasNext()) { dir_iterator.next(); // dir_iterator.fileInfo().dir().path(); QTreeWidgetItem *USBItem = new QTreeWidgetItem(ui->treeWidget,QStringList(QString(dir_iterator.fileName().toUpper()))); USBItem->setIcon(0,QIcon(":/assets/usb.svg")); // QStringList chilData; // chilData.append(dir_iterator.fileName().toUpper()); // QTreeWidgetItem *chilItem = new QTreeWidgetItem(MotherItem,chilData); // chilItem->setIcon(0,QIcon(":/assets/usb.svg")); LoadFiles(USBItem , dir_iterator.filePath()); USBDev.append(USBItem); // MotherItem->addChild(chilItem); } } return USBDev; } void FileDialog::LoadFiles(QTreeWidgetItem *MotherItem , QString DirPath) { QDirIterator dir_iterator(DirPath,QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot/*,QDirIterator::Subdirectories*/); while(dir_iterator.hasNext()) { dir_iterator.next(); // QFileInfo file_info = dir_iterator.fileInfo(); // QString files = file_info.absoluteFilePath(); if(dir_iterator.fileInfo().isDir()) { if(dir_iterator.fileInfo().fileName() == "System Volume Information") continue; QStringList chilData; chilData.append(dir_iterator.fileName()); QTreeWidgetItem *chilItem = new QTreeWidgetItem(MotherItem,chilData); chilItem->setIcon(0,QIcon(":/assets/wenjian.svg")); LoadFiles(chilItem , dir_iterator.filePath()); MotherItem->addChild(chilItem); } else if(dir_iterator.fileInfo().isFile()) { QStringList chilData; chilData.append(dir_iterator.fileName()); chilData.append(dir_iterator.filePath()); QTreeWidgetItem *chilItem = new QTreeWidgetItem(MotherItem,chilData); QString ext = dir_iterator.fileInfo().suffix().toLower(); if(ext == "gco" || ext == "gcode" || ext == "g")//machinecode { chilItem->setIcon(0,QIcon(":/assets/3ddayin.svg")); } else if(ext == "stl" || ext == "obj" )//model object { chilItem->setIcon(0,QIcon(":/assets/object.svg")); } else { chilItem->setIcon(0,QIcon(":/assets/rizhi.svg")); } MotherItem->addChild(chilItem); } } } void FileDialog::FilesPraser(QTreeWidgetItem *MotherItem , QJsonArray Data) { //QList _return; foreach(QJsonValue item,Data) { if(item.toObject().constFind("origin").value().toString() == "local") { QStringList chilData; chilData.append(Hex2QString(item.toObject().constFind("display").value().toString())); chilData.append(item.toObject().constFind("refs").value().toObject().constFind("resource").value().toString()); QTreeWidgetItem *chilItem = new QTreeWidgetItem(MotherItem,chilData); chilItem->setIcon(0, item.toObject().constFind("type").value().toString() == "machinecode" ? QIcon(":/assets/3ddayin.svg") : item.toObject().constFind("type").value().toString() == "model" ? QIcon(":/assets/object.svg") : QIcon(":/assets/rizhi.svg")); MotherItem->addChild(chilItem); } else if(item.toObject().constFind("origin").value().toString() == "sdcard") { QStringList chilData; chilData.append(Hex2QString(item.toObject().constFind("display").value().toString())); chilData.append(item.toObject().constFind("refs").value().toObject().constFind("resource").value().toString()); QTreeWidgetItem *chilItem = new QTreeWidgetItem(SDcardItem,chilData); chilItem->setIcon(0, item.toObject().constFind("type").value().toString() == "machinecode" ? QIcon(":/assets/3ddayin.svg") : item.toObject().constFind("type").value().toString() == "model" ? QIcon(":/assets/object.svg") : QIcon(":/assets/rizhi.svg")); SDcardItem->addChild(chilItem); } else if(item.toObject().constFind("type").value().toString() == "folder") { QStringList chilData; chilData.append(item.toObject().constFind("display").value().toString()); QTreeWidgetItem *chilItem = new QTreeWidgetItem(MotherItem,chilData); chilItem->setIcon(0,QIcon(":/assets/wenjian.svg")); // if(item.toObject().constFind("display").value().toString().contains(QRegExp("[s,h]d[a-z][0-9]+"))) // chilItem->setIcon(0,QIcon(":/assets/usb.svg")); // else // chilItem->setIcon(0,QIcon(":/assets/wenjian.svg")); FilesPraser(chilItem , item.toObject().constFind("children").value().toArray()); MotherItem->addChild(chilItem); } } } void FileDialog::on_treeWidget_itemClicked(QTreeWidgetItem *item, int column) { if(QSysInfo::productType() != "raspbian") { LibLog::LogRec(QString("%1:%2___%3___%4").arg(column).arg(item->text(column)).arg(__FILE__).arg(__LINE__), "connect"); LibLog::LogRec(QString("%1___%3___%4").arg(item->data(1,0).toString()).arg(__FILE__).arg(__LINE__), "connect"); } if(((MainWindow*)FUI)->octonetwork.ConnectState.contains("Printing") ||((MainWindow*)FUI)->octonetwork.ConnectState == "Starting print from SD" || ((MainWindow*)FUI)->octonetwork.ConnectState == "Starting") return; QString ext = item->data(1,0).toString().split('.').last(); if(ext.toLower() == "gcode" || ext.toLower() == "gco" || ext.toLower() == "g") { SelectURL = QUrl(item->data(1,0).toString()); DisplayName = item->data(0,0).toString(); ui->Btn_Delete->setEnabled(true); ui->Btn_Print->setEnabled(true); if(!SelectURL.url().startsWith("http://")) ui->Btn_Upload->setEnabled(true); else ui->Btn_Upload->setEnabled(false); } else { ui->Btn_Delete->setEnabled(false); ui->Btn_Print->setEnabled(false); ui->Btn_Upload->setEnabled(false); } } //quick print void FileDialog::on_treeWidget_itemDoubleClicked(QTreeWidgetItem *item, int column) { Q_UNUSED(column); QString ext = item->data(1,0).toString().split('.').last(); if(ext.toLower() == "gcode" || ext.toLower() == "gco" || ext.toLower() == "g") { ((MainWindow*)FUI)->octonetwork.JobSwitch(SelectURL); this->close(); } } QUrl FileDialog::GetRealURL(QUrl URL) { QUrl _URL; if(!URL.url().startsWith("http://")) { // QString newFileName = QString2Hex(URL.url() , false); // //构建新文件名称 // if(!QDir("/home/pi").exists("temp")) // QDir("/home/pi").mkdir("temp"); // if(QFile::exists("/home/pi/temp/"+newFileName)) // QFile::remove("/home/pi/temp/"+newFileName); // //检查同名堆积 // QFile::copy(URL.url(),"/home/pi/temp/"+newFileName); // //复制外部路径文件到临时文件夹 // _URL = UploadFile("/home/pi/temp/"+newFileName); // //上传临时文件至Octoprint并索取真实URL // QFile::remove("/home/pi/temp/"+newFileName); // //删除临时文件 _URL = UploadFile(URL.url()); } else { _URL = URL; } return _URL; } void FileDialog::DeleteURL(QUrl URL) { QString FileName = Hex2QString(URL.url(),false); QStringList btnName = {"Yes", "No",} ; CustomDialog *newDialog = new CustomDialog(); QObject::connect(newDialog, &CustomDialog::OutputEvent, newDialog,[=](QString instruct) { if(instruct == "Yes") { if(URL.url().toLower().startsWith("http://")) { request->setUrl(URL); if(manager->deleteResource(*request)->error() == QNetworkReply::NoError) RefreshFileList(); } else { DeleteFile(URL.url()); } SelectURL.setUrl(""); } }); newDialog->showCustomDialog("Delete",":/assets/delete.svg",btnName,"Do you want to Delete "+FileName+" ?",this); } void FileDialog::DeleteFile(QString FilePath) { if(QFile::exists(FilePath)) { QFile::remove(FilePath); RefreshFileList(); } } QUrl FileDialog::UploadFile(QString FilePath) { QUrl _return; //设置发送的数据 QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType); QFile *file = new QFile(FilePath); //由于是异步,所以记得一定要new file->open(QIODevice::ReadOnly); QHttpPart contentPart; contentPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant(QString("form-data; name=\"file\"; filename=\"%1\"").arg(QFileInfo(FilePath).fileName()))); contentPart.setBodyDevice(file); file->setParent(multiPart); multiPart->append(contentPart); request->setUrl(QUrl(((MainWindow*)FUI)->octonetwork.MainUrl +"/files/local")); QNetworkReply *reply = manager->post(*request,multiPart); while(!reply->isFinished()) QCoreApplication::processEvents();//update http post // QMessageBox::information(NULL, "item.dir().path()", "reply statusCode:" + QString::number(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt()), QMessageBox::Ok, QMessageBox::Ok);//Debug file->close(); if(reply->error() == QNetworkReply::NoError) { QByteArray replyArray = reply->readAll(); QJsonDocument loadDoc(QJsonDocument::fromJson(replyArray)); QJsonObject QObj = loadDoc.object(); QList ResourcesLocation = {"files","local","refs","resource"}; _return = QUrl(((MainWindow*)FUI)->octonetwork.SearchJsonValue( ResourcesLocation, QObj).toString()); } reply->deleteLater(); return _return; } QUrl FileDialog::GetRealURL() { return GetRealURL(SelectURL); } void FileDialog::GetDirlist(QStringList CommandLine) { disconnect(terminal_timer,SIGNAL(timeout()),0,0); terminal_timer->stop(); DirList.clear(); foreach(QString Dir , CommandLine) { DirList.append(Dir.split("\t", QString::SkipEmptyParts)); } disconnect(((MainWindow*)FUI)->terminaldialog,&TerminalDialog::CMD_Reply,0,0); // QObject::connect(((MainWindow*)FUI)->terminaldialog,&TerminalDialog::CMD_Reply,this,SLOT(GetDevlist(QStringList))); QObject::connect(((MainWindow*)FUI)->terminaldialog,&TerminalDialog::CMD_Reply,this,[=](QStringList CommandLine) { GetDevlist(CommandLine); }); ((MainWindow*)FUI)->terminaldialog->SendCMD("cd /dev/ && find [s,h]d[a-z]* -maxdepth 0 -type b -regex \"[s,h]d[a-z][0-9]+$\"; cd /home/pi",TeminalState); QObject::connect(terminal_timer,SIGNAL(timeout()),this,SLOT(GetDevlistTimeout())); terminal_timer->start(500); } void FileDialog::GetDirlistTimeout() { DirList.clear(); disconnect(((MainWindow*)FUI)->terminaldialog,&TerminalDialog::CMD_Reply,0,0); // QObject::connect(((MainWindow*)FUI)->terminaldialog,&TerminalDialog::CMD_Reply,this,SLOT(GetDevlist(QStringList))); QObject::connect(((MainWindow*)FUI)->terminaldialog,&TerminalDialog::CMD_Reply,this,[=](QStringList CommandLine) { GetDevlist(CommandLine); }); ((MainWindow*)FUI)->terminaldialog->SendCMD("cd /dev/ && find [s,h]d[a-z]* -maxdepth 0 -type b -regex \"[s,h]d[a-z][0-9]+$\"; cd /home/pi",TeminalState); disconnect(terminal_timer,SIGNAL(timeout()),0,0); QObject::connect(terminal_timer,SIGNAL(timeout()),this,SLOT(GetDevlistTimeout())); terminal_timer->start(500); } void FileDialog::GetDevlist(QStringList CommandLine) { disconnect(terminal_timer,SIGNAL(timeout()),0,0); terminal_timer->stop(); DevList.clear(); foreach(QString Dev , CommandLine) { DevList.append(Dev.split("\t", QString::SkipEmptyParts)); } disconnect(((MainWindow*)FUI)->terminaldialog,&TerminalDialog::CMD_Reply,0,0); RmList.clear(); foreach(QString Dir , DirList) { if(!DevList.contains(Dir)) RmList.append(Dir); } NewList.clear(); foreach(QString Dev , DevList) { if(!DirList.contains(Dev)) NewList.append(Dev); } if(!RmList.isEmpty()) { QString RmCMD = "cd /home/pi/USB ; sudo umount "; // RmCMD = RmCMD + RmList.join(" ") + " ; rm -rf " + RmList.join(" ") + " ; cd /home/pi"; RmCMD = RmCMD + RmList.join(" ") + " ; cd /home/pi"; ((MainWindow*)FUI)->terminaldialog->SendCMD(RmCMD,TeminalState); QCoreApplication::processEvents(); QThread::msleep(500); QCoreApplication::processEvents(); RmCMD = "cd /home/pi/USB ; rm -rf " + RmList.join(" ") + " ; cd /home/pi"; ((MainWindow*)FUI)->terminaldialog->SendCMD(RmCMD,TeminalState); QCoreApplication::processEvents(); QThread::msleep(500); QCoreApplication::processEvents(); if(!SelectURL.url().startsWith("http://")) { SelectURL = QUrl(); } } if(!NewList.isEmpty())//sudo mount -o uid=pi,gid=pi /dev/sda1 /mnt/1GB_USB_flash { QString NewCMD = ""; QDir dir("/home/pi/USB");//Load USB Path if(QSysInfo::productType() == "raspbian" && !dir.exists()) { NewCMD = "mkdir /home/pi/USB ; "; } NewCMD = NewCMD + "cd /home/pi/USB ; mkdir " + NewList.join(" "); foreach(QString Newitem , NewList) { NewCMD = NewCMD + " ; sudo mount -o uid=pi,gid=pi,utf8=true,iocharset=utf8 /dev/" + Newitem + " " + Newitem;//字符集编码异常Debug文件夹被破坏 } NewCMD = NewCMD + " ; cd /home/pi"; ((MainWindow*)FUI)->terminaldialog->SendCMD(NewCMD,TeminalState); QCoreApplication::processEvents(); QThread::msleep(500); QCoreApplication::processEvents(); } if(!RmList.isEmpty() || !NewList.isEmpty()) { QThread::msleep(500); ReFreshJson(); } } void FileDialog::GetDevlistTimeout() { DevList.clear(); disconnect(((MainWindow*)FUI)->terminaldialog,&TerminalDialog::CMD_Reply,0,0); disconnect(terminal_timer,SIGNAL(timeout()),0,0); RmList.clear(); foreach(QString Dir , DirList) { if(!DevList.contains(Dir)) RmList.append(Dir); } NewList.clear(); foreach(QString Dev , DevList) { if(!DirList.contains(Dev)) NewList.append(Dev); } if(!RmList.isEmpty()) { QString RmCMD = "cd /home/pi/USB ; sudo umount "; // RmCMD = RmCMD + RmList.join(" ") + " ; rm -rf " + RmList.join(" ") + " ; cd /home/pi"; RmCMD = RmCMD + RmList.join(" ") + " ; cd /home/pi"; ((MainWindow*)FUI)->terminaldialog->SendCMD(RmCMD,TeminalState); QCoreApplication::processEvents(); QThread::msleep(500); QCoreApplication::processEvents(); RmCMD = "cd /home/pi/USB ; rm -rf " + RmList.join(" ") + " ; cd /home/pi"; ((MainWindow*)FUI)->terminaldialog->SendCMD(RmCMD,TeminalState); QCoreApplication::processEvents(); QThread::msleep(500); QCoreApplication::processEvents(); if(!SelectURL.url().startsWith("http://")) { SelectURL = QUrl(); } } if(!NewList.isEmpty()) { QString NewCMD = ""; QDir dir("/home/pi/USB");//Load USB Path if(QSysInfo::productType() == "raspbian" && !dir.exists()) { NewCMD = "mkdir /home/pi/USB ; "; } NewCMD = NewCMD + "cd /home/pi/.octoprint/uploads ; mkdir " + NewList.join(" "); foreach(QString Newitem , NewList) { NewCMD = NewCMD + " ; sudo mount -o uid=pi,gid=pi,utf8=true,iocharset=utf8 /dev/" + Newitem + " " + Newitem; //字符集编码异常(iocharset=cp936,codepage=cp936) posix=true utf8=true uid=pi,gid=pi nls=utf8 } NewCMD = NewCMD + " ; cd /home/pi"; ((MainWindow*)FUI)->terminaldialog->SendCMD(NewCMD,TeminalState); QCoreApplication::processEvents(); QThread::msleep(500); QCoreApplication::processEvents(); } if(!RmList.isEmpty() || !NewList.isEmpty()) { // QThread::msleep(500); ReFreshJson(); } } void FileDialog::InitializeUSBDrive() { QDir dir("/home/pi/USB");//Load USB Path if(QSysInfo::productType() == "raspbian" && dir.exists()) { QStringList DirList = dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot); QString RmCMD = "cd /home/pi/USB ; "; RmCMD = RmCMD + "sudo umount " + DirList.join(" ") + " ; cd /home/pi"; ((MainWindow*)FUI)->terminaldialog->SendCMD(RmCMD,TeminalState); // QStringList DirList = dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot); // QString RmCMD = "cd /home/pi/USB ; "; // RmCMD = RmCMD + "sudo umount " + DirList.join(" ") + " ; rm -rf " + DirList.join(" ") + " ; cd /home/pi"; // ((MainWindow*)FUI)->terminaldialog->SendCMD(RmCMD,TeminalState); QCoreApplication::processEvents(); QThread::msleep(500); QCoreApplication::processEvents(); RmCMD = "cd /home/pi/USB ; "; RmCMD = RmCMD + " rm -rf " + DirList.join(" ") + " ; cd /home/pi"; ((MainWindow*)FUI)->terminaldialog->SendCMD(RmCMD,TeminalState); QCoreApplication::processEvents(); QThread::msleep(500); QCoreApplication::processEvents(); } RefreshFileList(); } QString FileDialog::QString2Hex(QString str ,bool FullPath) { QString _returnData = "--BTT--"; QStringList strList = str.split('.'); if(str.contains(QRegExp("([a-z]|[A-Z])+:\\\\")))//windows path mode { if(FullPath) _returnData = str.left(str.length() - str.split("\\").last().length()) + _returnData; str = str.split("\\").last(); } else if(str.startsWith("/"))//unix path mode { if(FullPath) _returnData = str.left(str.length() - str.split("/").last().length()) + _returnData; str = str.split("/").last(); } QByteArray hexData = str.left(str.length() - strList.last().length() - 1).toUtf8(); _returnData = _returnData + hexData.toHex('-').toUpper() + (strList.length() >= 2 ? ("." + strList.last()) : ""); return _returnData; } QString FileDialog::Hex2QString(QString hx,bool FullPath) { QString _returnData = ""; if(hx.contains(("--BTT--"))) { QString fileNameWExt = hx.split("--BTT--").last(); QStringList strList = fileNameWExt.split('.'); QByteArray hexData = QByteArray::fromHex(fileNameWExt.left(fileNameWExt.length() - strList.last().length() - 1).replace("-","").toLocal8Bit()); _returnData = FullPath ? hx.left(hx.length()-fileNameWExt.length() - 7) : "" + QString::fromUtf8(hexData.data(),hexData.size()) + (strList.length() >= 2 ? ("." + strList.last()) : ""); } else { if(FullPath) _returnData=hx; else { if(hx.contains(QRegExp("([a-z]|[A-Z])+:\\\\")))//windows path mode { _returnData = hx.split("\\").last(); } else if(hx.startsWith("/"))//unix path mode { _returnData = hx.split("/").last(); } else if(hx.startsWith("http://"))//url mode { _returnData = hx.split("/").last(); } else _returnData=hx; } } return _returnData; } void FileDialog::on_Btn_Upload_clicked() { if(!SelectURL.url().startsWith("http://") && !SelectURL.url().isEmpty()) { SelectURL=UploadFile(SelectURL.url()); RefreshFileList(); } } void FileDialog::on_Btn_Print_clicked() { if(!SelectURL.url().isEmpty()) { ((MainWindow*)FUI)->octonetwork.JobSwitch(SelectURL); this->close(); } } void FileDialog::on_Btn_Delete_clicked() { if(!SelectURL.url().isEmpty()) { DeleteURL(SelectURL); } } ================================================ FILE: filedialog.h ================================================ #ifndef FILEDIALOG_H #define FILEDIALOG_H #include #include //MY Dialog #include #include #include #include #include "liblog.h" #define BTSTYLE6 "QPushButton {padding: 10px;border-style: solid;border-width: 1px;border-radius: 20px;border-color: rgb(245,246,255); color: rgb(245, 246, 255);}"\ "QPushButton:hover {padding: 10px;border-style: solid;border-width: 1px;border-radius: 20px;border-color: rgb(245,246,255); background-color:rgb(128,128,128,128);color: rgb(245, 246, 255);}"\ "QPushButton:pressed{padding: 10px;border-style: solid;border-width: 1px;border-radius: 20px;border-color: rgb(245,246,255); background-color:rgb(128,128,128,128);color: rgb(245, 246, 255);padding-right:4px;padding-bottom:4px;}" extern int DebugFlat ; extern QSizeF SizePercent; namespace Ui { class FileDialog; } class FileDialog : public QDialog { Q_OBJECT public: explicit FileDialog(QWidget *parent = nullptr); ~FileDialog(); private slots: virtual void on_Btn_back_clicked(); virtual void on_Btn_Refresh_pressed(); virtual void on_Btn_Refresh_released(); virtual void on_Btn_Refresh_clicked(); virtual void FSReply(QNetworkReply *reply); virtual void ReFreshJson(); virtual void GetDirlistTimeout(); virtual void GetDevlistTimeout(); virtual void on_treeWidget_itemClicked(QTreeWidgetItem *item, int column); virtual void on_treeWidget_itemDoubleClicked(QTreeWidgetItem *item, int column); void on_Btn_Upload_clicked(); void on_Btn_Print_clicked(); void on_Btn_Delete_clicked(); private: Ui::FileDialog *ui; public: QUrl SelectURL; QString DisplayName; QUrl GetRealURL(QUrl URL); QUrl GetRealURL(); static QString QString2Hex(QString str,bool FullPath = true); static QString Hex2QString(QString hx,bool FullPath = true); void InitializeUSBDrive(); private: virtual void FilesPraser(QTreeWidgetItem *MotherItem , QJsonArray Data); virtual QList LoadUSBPath(QString USBPath); virtual void LoadFiles(QTreeWidgetItem *MotherItem , QString DirPath); virtual void RefreshFileList(); virtual void GetDirlist(QStringList CommandLine); virtual void GetDevlist(QStringList CommandLine); void DeleteURL(QUrl URL); void DeleteFile(QString FilePath); QUrl UploadFile(QString FilePath); private: QNetworkAccessManager *manager = new QNetworkAccessManager(); QNetworkRequest *request; QString StyleSheet_Temp; QWidget *FUI; QTreeWidgetItem *SDcardItem; QStringList DirList; QStringList DevList; QStringList RmList; QStringList NewList; QTimer *terminal_timer; QString TeminalState = "-q-e"; protected: void showEvent(QShowEvent *event); }; #endif // FILEDIALOG_H ================================================ FILE: filedialog.ui ================================================ FileDialog 0 0 800 480 0 0 Files :/assets/wenjian.svg:/assets/wenjian.svg 3 QLayout::SetDefaultConstraint 5 5 5 5 6 QLayout::SetDefaultConstraint 0 0 0 BTStyleSheet2 :/assets/huitui.svg:/assets/huitui.svg 72 72 Qt::Horizontal QSizePolicy::Expanding 40 20 border:none; font: 75 30pt "Gill Sans MT"; :/assets/folder.svg:/assets/folder.svg 72 72 Qt::Horizontal QSizePolicy::Expanding 40 20 0 0 76 72 BTStyleSheet2 Qt::RightToLeft :/assets/sync-alt.svg:/assets/sync-alt.svg 72 72 3 0 0 0 30 color: rgb(255, 255, 255); QAbstractItemView::NoEditTriggers 64 64 true true false 1 Qt::Vertical QSizePolicy::Maximum 20 5 6 Qt::Horizontal QSizePolicy::Fixed 10 20 0 50 BTStyleSheet6 UpLoad to OctoPrint :/assets/upload.svg:/assets/upload.svg 40 40 Qt::Horizontal QSizePolicy::Fixed 10 20 0 50 BTStyleSheet6 Print :/assets/print.svg:/assets/print.svg 40 40 Qt::Horizontal QSizePolicy::Fixed 10 20 0 50 BTStyleSheet6 Delete :/assets/delete.svg:/assets/delete.svg 40 40 Qt::Horizontal QSizePolicy::Fixed 10 20 Qt::Vertical QSizePolicy::Fixed 10 5 ================================================ FILE: gcodedialog.cpp ================================================ #include "gcodedialog.h" #include "ui_gcodedialog.h" #include #include //#include #include #include #include #include #include "inputdialog.h" #include #include #include #include GcodeDialog::GcodeDialog(QWidget *parent) : QDialog(parent), ui(new Ui::GcodeDialog) { ui->setupUi(this); FUI = (MainWindow*)parent;//((MainWindow*)FUI)->octonetwork.SendGCode(_GCode_Setting); ui->Sender->setFocus(); _ptimer = new QTimer(); connect(_pdataRecvWS,SIGNAL(disconnected()),this,SLOT(onWSDisconnected()),Qt::AutoConnection); connect(_pdataRecvWS,SIGNAL(textMessageReceived(QString)),this,SLOT(onWSTextReceived(QString)),Qt::AutoConnection); connect(_pdataRecvWS,SIGNAL(connected()),this,SLOT(onWSConnected()),Qt::AutoConnection); connect(_ptimer,SIGNAL(timeout()),this,SLOT(onWSReconnect()),Qt::AutoConnection); _pdataRecvWS->open(QUrl("ws://"+((MainWindow*)FUI)->octonetwork.MainIP+"/sockjs/websocket")); // _pdataRecvWS->open(QUrl("ws://192.168.100.111/sockjs/websocket")); this->resize((int)(SizePercent.width()*800),(int)(SizePercent.height()*480)); this->setMaximumSize((int)(SizePercent.width()*800),(int)(SizePercent.height()*480)); this->setFixedSize((int)(SizePercent.width()*800),(int)(SizePercent.height()*480)); } GcodeDialog::~GcodeDialog() { delete ui; } void GcodeDialog::showEvent(QShowEvent *event) { Q_UNUSED(event); } void GcodeDialog::on_Btn_Back_clicked() { this->close(); } void GcodeDialog::on_Btn_Send_clicked() { if(ui->Sender->text().isEmpty()) { // ui->Sender->setFocus(); return; } ui->Sender->setText(ui->Sender->text().trimmed()); // SendCMD(ui->Sender->text()); ((MainWindow*)FUI)->octonetwork.SendGCode(ui->Sender->text()); ui->Sender->setFocus(); } void GcodeDialog::on_pushButton_clicked() { ui->Receiver->clear(); } void GcodeDialog::on_Btn_Logo_clicked() { } //断开连接会触发这个槽函数 void GcodeDialog::onWSDisconnected() { _ptimer->start(); } //连接成功会触发这个槽函数 void GcodeDialog::onWSConnected() { _ptimer->stop(); } //收到服务发来的消息会触发这个槽函数 void GcodeDialog::onWSTextReceived(QString msg) { // msg = msg.replace("\\","\""); if(!msg.trimmed().startsWith("{\"current\":") || msg.trimmed().length() == 0) return; QJsonDocument loadDoc(QJsonDocument::fromJson(msg.toUtf8())); QJsonObject QObj = loadDoc.object(); QList SearchLink ; SearchLink << "current" << "logs"; foreach(QJsonValue _value, SearchWSJsonValue(SearchLink , QObj).toArray()) { ui->Receiver->append(_value.toString()); // recveData(_value.toString()); } // recveData(SearchWSJsonValue(SearchLink , QObj)[0].toString()); // recvData(SearchJsonValue(SearchLink , QObj).toString()); } //断开连接会启动定时器,触发这个槽函数重新连接 void GcodeDialog::onWSReconnect() { _pdataRecvWS->abort(); _pdataRecvWS->open(QUrl("ws://"+((MainWindow*)FUI)->octonetwork.MainIP+"/sockjs/websocket")); } //Find_List_Name : Retrieved List Sequence --> [Grandma,Mother,Me] //_QObj:Retrieved Retrieved Json Objecet QJsonValue GcodeDialog::SearchWSJsonValue(QList Find_List_Name , QJsonObject _QObj) { QJsonValue returnValue; QList SearchLink ; SearchLink << Find_List_Name; if(SearchLink.count() > 1) { QString MotherKey = SearchLink[0]; SearchLink.removeFirst(); if(MotherKey.indexOf("*") >= 0)//wildcard { QJsonArray ArrayValue; for(int i = 0 ; i <= 9 ; i++) { QString TempMotherKey = MotherKey; if(_QObj.find(TempMotherKey.replace("*",QString::number(i))).value().isUndefined())continue; // if(QSysInfo::productType() != "raspbian"){qDebug()<<_QObj.find(TempMotherKey.replace("*",QString::number(i))).value().isUndefined();}; QJsonValue data = SearchWSJsonValue(SearchLink , _QObj.constFind(TempMotherKey.replace("*",QString::number(i))).value().toObject()); ArrayValue.append(data); } returnValue = ArrayValue; } else returnValue = SearchWSJsonValue(SearchLink , _QObj.constFind(MotherKey).value().toObject()); } else { if(SearchLink[0].indexOf("*") >= 0)//wildcard { } else returnValue = _QObj.constFind(SearchLink[0]).value(); } return returnValue; } QList GcodeDialog::SearchWSJsonValue(QList> Find_List_Names , QJsonObject _QObj) { QList _returnValue ; foreach(QList item , Find_List_Names) { _returnValue.append(SearchWSJsonValue(item,_QObj)); } return _returnValue; } ================================================ FILE: gcodedialog.h ================================================ #ifndef GCODEDIALOG_H #define GCODEDIALOG_H #include #include #include #include //#include #include #include #include #include extern int DebugFlat ; extern QSizeF SizePercent; namespace Ui { class GcodeDialog; } class GcodeDialog : public QDialog { Q_OBJECT signals: private slots: void onWSDisconnected(); void onWSConnected(); void onWSTextReceived(QString msg); void onWSReconnect(); public: explicit GcodeDialog(QWidget *parent = nullptr); ~GcodeDialog(); private slots: virtual void on_Btn_Back_clicked(); virtual void on_Btn_Send_clicked(); virtual void on_pushButton_clicked(); virtual void on_Btn_Logo_clicked(); private: Ui::GcodeDialog *ui; QWidget *FUI; private: QJsonValue SearchWSJsonValue(QList Find_List_Name , QJsonObject _QObj); QList SearchWSJsonValue(QList> Find_List_Names , QJsonObject _QObj); QTimer* _ptimer; public: QWebSocket* _pdataRecvWS = new QWebSocket(); protected: void showEvent(QShowEvent *event); }; #endif // GCODEDIALOG_H ================================================ FILE: gcodedialog.ui ================================================ GcodeDialog 0 0 800 480 0 0 Gcode :/assets/yuanchengkongzhi2.svg:/assets/yuanchengkongzhi2.svg 5 5 5 5 0 0 150 50 15 75 true BTStyleSheet7 false Send gcode true 0 0 25 Qt::ClickFocus false false background-color: rgb(0, 0, 0); color: rgb(0, 255, 0); 5 5 5 5 BTStyleSheet2 :/assets/huitui.svg:/assets/huitui.svg 72 72 Qt::Horizontal 40 20 border:none; font: 75 30pt "Gill Sans MT"; :/assets/yuanchengkongzhi.svg:/assets/yuanchengkongzhi.svg 72 72 Qt::Horizontal 40 20 84 78 15 true background-color: rgb(0, 0, 0); color: rgb(0, 255, 0); false true 20 BTStyleSheet7 Clean Window MyLineEdit QLineEdit
mylineedit.h
================================================ FILE: inputdialog.cpp ================================================ #include "inputdialog.h" #include "ui_inputdialog.h" #include //#include //#include //#include InputDialog::InputDialog(QWidget *parent) : QDialog(parent), ui(new Ui::InputDialog) { ui->setupUi(this); // FUI = (MainWindow*)parent;//((MainWindow*)FUI)->octonetwork.SendGCode(_GCode_Setting); AllBtns = this->findChildren(); NumBtns = this->findChildren(QRegExp("Num_[0-9]")); CharBtns = this->findChildren(QRegExp("Char_[A-Z]")); SymbBtns = this->findChildren(QRegExp("Symb_[.]*")); foreach(QPushButton *item , CharBtns) { connect(item,SIGNAL(clicked()),this,SLOT(on_CharKey_click())); } foreach(QPushButton *item , NumBtns) { connect(item,SIGNAL(clicked()),this,SLOT(on_NumKey_click())); } foreach(QPushButton *item , SymbBtns) { connect(item,SIGNAL(clicked()),this,SLOT(on_SymbKey_click())); } foreach(QPushButton *item , AllBtns) { if(item->objectName()!=ui->Btn_Undo->objectName()&&item->objectName()!=ui->Btn_Confirm->objectName()) connect(item,SIGNAL(clicked()),this,SLOT(on_Beep_clicked())); connect(item,SIGNAL(released()),this,SLOT(released_clicked())); } QFont font; //font.setPointSize(32*(SizePercent.width() < SizePercent.height() ? SizePercent.width():SizePercent.height())); foreach(QPushButton *item , AllBtns) { // if(item->objectName() == ui->Btn_Back->objectName() // || item->objectName() == ui->Btn_Confirm->objectName()) // item->setIconSize(QSize(72*SizePercent.width(),72*SizePercent.height())); // if(item->objectName() == ui->Space->objectName() // || item->objectName() == ui->Key_Left->objectName() // || item->objectName() == ui->Key_Right->objectName() // || item->objectName() == ui->Symb_Wave->objectName() // || item->objectName() == ui->Symb_Semi->objectName() // || item->objectName() == ui->Symb_Quo->objectName()) item->setIconSize(QSize((int)(item->iconSize().width()*SizePercent.width()),(int)(item->iconSize().height()*SizePercent.height()))); font.setPointSize((int)(item->font().pointSize()*(SizePercent.width() < SizePercent.height() ? SizePercent.width():SizePercent.height()))); item->setFont(font); } font.setPointSize((int)(ui->TextBlock->font().pointSize()*(SizePercent.width() < SizePercent.height() ? SizePercent.width():SizePercent.height()))); ui->TextBlock->setFont(font); //窗体自适应屏幕大小 this->resize((int)(SizePercent.width()*800),(int)(SizePercent.height()*480)); this->setMaximumSize((int)(SizePercent.width()*800),(int)(SizePercent.height()*480)); this->setFixedSize((int)(SizePercent.width()*800),(int)(SizePercent.height()*480)); } InputDialog::~InputDialog() { delete ui; } void InputDialog::setvalue(QString PlaceholdText , QString InputMode , QString DefaultValue) { ui->TextBlock->setPlaceholderText(PlaceholdText); if(!DefaultValue.isNull() && !DefaultValue.trimmed().isEmpty()) ui->TextBlock->setText(DefaultValue); InputMode = InputMode.trimmed(); QRegExp MyRegExp; if(InputMode.toLower().contains("-int"))//Multi Validator { MyRegExp.setPattern((MyRegExp.pattern().count() > 0 ? MyRegExp.pattern() +"|" : "") + "[+,-]?(0|[0-9]+)"); } if(InputMode.toLower().contains("-double"))//Multi Validator { MyRegExp.setPattern((MyRegExp.pattern().count() > 0 ? MyRegExp.pattern() +"|" : "") + "[+,-]?(0|[0-9]+)[.]?[0-9]*"); } if(InputMode.toLower().contains("-lower"))//Multi Validator { MyRegExp.setPattern((MyRegExp.pattern().count() > 0 ? MyRegExp.pattern() +"|" : "") + "[a-z]*"); } if(InputMode.toLower().contains("-upper"))//Multi Validator { MyRegExp.setPattern((MyRegExp.pattern().count() > 0 ? MyRegExp.pattern() +"|" : "") + "[A-Z]*"); } if(InputMode.toLower().contains(" int"))//single Validator { MyRegExp.setPattern("0|[0-9]+"); } if(InputMode.toLower().contains(" double"))//single Validator { MyRegExp.setPattern("(0|[0-9]+)[.]?[0-9]*"); } if(InputMode.toLower().contains("-ip"))//single Validator { MyRegExp.setPattern("((?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d))"); } if(!InputMode.toLower().contains("-all") && InputMode != "")//single Validator { ui->TextBlock->setValidator(new QRegExpValidator(MyRegExp,this)); } this->show(); } void InputDialog::on_Btn_Undo_clicked() { bool SettingMark = false; QString ReturnValue = ui->TextBlock->text(); this->close(); emit closedialog(ReturnValue,SettingMark); } void InputDialog::on_CharKey_click() { //发送信号者的对象 QPushButton *optBtn = qobject_cast(sender()); //发送信号者的对象名 //QString name = sender()->objectName(); QKeySequence Key = QKeySequence(QString(optBtn->text().toUpper()[0])); // Qt::Key key = Qt::Key(); // Qt::KeyboardModifier Key_Modifier = Func_Ang_State ? Qt::ShiftModifier : Qt::NoModifier; // ui->TextBlock->setFocus(); QKeyEvent keyPress(QEvent::KeyPress, Key[0], Key_Modifier, QString(optBtn->text()[0])); // QKeyEvent keyPress(QEvent::KeyPress, Qt::Key_A, Qt::NoModifier, optBtn->text()); QCoreApplication::sendEvent(ui->TextBlock, &keyPress); ui->TextBlock->setFocus(); } void InputDialog::on_NumKey_click() { QPushButton *optBtn = qobject_cast(sender()); QKeySequence Key = QKeySequence(QString(optBtn->text().toUpper()[0])); // Qt::KeyboardModifier Key_Modifier = Func_Ang_State ? Qt::ShiftModifier : Qt::NoModifier; int KeyData; if(Func_UL_State) { KeyData = Qt::Key(); } else { KeyData = Key[0]; } QKeyEvent keyPress(QEvent::KeyPress, KeyData, Key_Modifier, QString(optBtn->text()[0])); QCoreApplication::sendEvent(ui->TextBlock, &keyPress); ui->TextBlock->setFocus(); } void InputDialog::on_SymbKey_click() { QPushButton *optBtn = qobject_cast(sender()); // QKeySequence Key = QKeySequence(QString(optBtn->text()[0])); // Qt::KeyboardModifier Key_Modifier = Func_Ang_State ? Qt::ShiftModifier : Qt::NoModifier; QKeyEvent keyPress(QEvent::KeyPress, Qt::Key(), Key_Modifier, QString(optBtn->text()[0])); QCoreApplication::sendEvent(ui->TextBlock, &keyPress); ui->TextBlock->setFocus(); } void InputDialog::released_clicked() { ui->TextBlock->setFocus(); } void InputDialog::on_Beep_clicked() { //QApplication::beep(); // QSoundEffect effect; // effect.setSource(QUrl::fromLocalFile(QCoreApplication ::applicationDirPath() + "/wav/KBClick.wav"));//获取资源文件中的声音文件 // effect.setLoopCount(1);//设置循环次数 // effect.setVolume(1.0); // effect.play();//播放 // QSound::play(QCoreApplication ::applicationDirPath() + "/wav/KBClick.wav"); // QSound::play(".../wav/KBClick.wav"); // QPoint pos(ui->TextBlock->cursor().pos()); // QMouseEvent cursorrvrnt(QEvent::MouseButtonPress, pos, Qt::LeftButton, Qt::LeftButton, Qt::NoModifier) ; ui->TextBlock->setFocus(); // QApplication::sendEvent(ui->TextBlock, &cursorrvrnt); } void InputDialog::showEvent(QShowEvent *event) { Q_UNUSED(event); ui->TextBlock->setFocus(); // ui->TextBlock->setText(QString::number( NumBtns.count())); } void InputDialog::on_Btn_Confirm_clicked() { bool SettingMark = true; QString ReturnValue = ui->TextBlock->text(); this->close(); emit closedialog(ReturnValue,SettingMark); } void InputDialog::on_Func_UL_clicked(bool checked) { Func_UL_State = checked; if(checked) { ui->Func_UL->setText(ui->Func_UL->text().toUpper()); foreach(QPushButton *item , CharBtns) { item->setText(item->objectName().replace("Char_","").toUpper()); } foreach(QPushButton *item , NumBtns) { switch (item->objectName().replace("Num_","").toInt()) { case 0: item->setText(Func_Ang_State? ")" : ")"); break; case 1: item->setText(Func_Ang_State? "!" : "!"); break; case 2: item->setText(Func_Ang_State? "@" : "@"); break; case 3: item->setText(Func_Ang_State? "#" : "#"); break; case 4: item->setText(Func_Ang_State? "¥" : "$"); break; case 5: item->setText(Func_Ang_State? "%" : "%"); break; case 6: item->setText(Func_Ang_State? "…" : "^"); break; case 7: item->setText(Func_Ang_State? "&&" : "&&"); break; case 8: item->setText(Func_Ang_State? "*" : "*"); break; case 9: item->setText(Func_Ang_State? "(" : "("); break; } } ui->Symb_Dot->setText(Func_Ang_State ? ",":","); ui->Symb_Par_L->setText(Func_Ang_State ? "「":"["); ui->Symb_Par_R->setText(Func_Ang_State ? "」":"]"); ui->Symb_Add->setText(Func_Ang_State ? "+":"+"); ui->Symb_Dec->setText(Func_Ang_State ? "—":"-"); ui->Symb_Bra_L->setText(Func_Ang_State ? "?":"?"); ui->Symb_Bra_R->setText(Func_Ang_State ? "/":"/"); ui->Symb_Ver->setText(Func_Ang_State ? "、":"\\"); ui->Symb_Wave->setText(Func_Ang_State ? "·":"·"); ui->Symb_Semi->setText(Func_Ang_State ? ":":":"); ui->Symb_Quo->setText(Func_Ang_State ? "”":"“"); } else { ui->Func_UL->setText(ui->Func_UL->text().toLower()); foreach(QPushButton *item , CharBtns) { item->setText(item->objectName().replace("Char_","").toLower()); } foreach(QPushButton *item , NumBtns) { item->setText(item->objectName().replace("Num_","")); } ui->Symb_Dot->setText(Func_Ang_State ? "。":"."); ui->Symb_Par_L->setText(Func_Ang_State ? "【":"["); ui->Symb_Par_R->setText(Func_Ang_State ? "】":"]"); ui->Symb_Add->setText(Func_Ang_State ? "=":"+"); ui->Symb_Dec->setText(Func_Ang_State ? "-":"-"); ui->Symb_Bra_L->setText(Func_Ang_State ? "《":"<"); ui->Symb_Bra_R->setText(Func_Ang_State ? "》":">"); ui->Symb_Ver->setText(Func_Ang_State ? "|":"|"); ui->Symb_Wave->setText(Func_Ang_State ? "~":"~"); ui->Symb_Semi->setText(Func_Ang_State ? ";":";"); ui->Symb_Quo->setText(Func_Ang_State ? "'":"\""); } ui->TextBlock->setFocus(); // QKeyEvent keyPress(QEvent::KeyPress, Qt::Key_CapsLock, Qt::NoModifier, QString()); // QCoreApplication::sendEvent(this, &keyPress); } void InputDialog::on_Func_Ang_clicked(bool checked) { Key_Modifier = checked ? Qt::ShiftModifier : Qt::NoModifier; Func_Ang_State = checked; ui->Func_Ang->setText(Func_Ang_State ? "●":"☾"); if(Func_UL_State) { foreach(QPushButton *item , NumBtns) { switch (item->objectName().replace("Num_","").toInt()) { case 0: item->setText(Func_Ang_State? ")" : ")"); break; case 1: item->setText(Func_Ang_State? "!" : "!"); break; case 2: item->setText(Func_Ang_State? "@" : "@"); break; case 3: item->setText(Func_Ang_State? "#" : "#"); break; case 4: item->setText(Func_Ang_State? "¥" : "$"); break; case 5: item->setText(Func_Ang_State? "%" : "%"); break; case 6: item->setText(Func_Ang_State? "…" : "^"); break; case 7: item->setText(Func_Ang_State? "&&" : "&&"); break; case 8: item->setText(Func_Ang_State? "*" : "*"); break; case 9: item->setText(Func_Ang_State? "(" : "("); break; } } ui->Symb_Dot->setText(Func_Ang_State ? ",":","); ui->Symb_Par_L->setText(Func_Ang_State ? "「":"["); ui->Symb_Par_R->setText(Func_Ang_State ? "」":"]"); ui->Symb_Add->setText(Func_Ang_State ? "+":"+"); ui->Symb_Dec->setText(Func_Ang_State ? "—":"-"); ui->Symb_Bra_L->setText(Func_Ang_State ? "?":"?"); ui->Symb_Bra_R->setText(Func_Ang_State ? "/":"/"); ui->Symb_Ver->setText(Func_Ang_State ? "、":"\\"); ui->Symb_Wave->setText(Func_Ang_State ? "·":"·"); ui->Symb_Semi->setText(Func_Ang_State ? ":":":"); ui->Symb_Quo->setText(Func_Ang_State ? "”":"“"); } else { ui->Symb_Dot->setText(Func_Ang_State ? "。":"."); ui->Symb_Par_L->setText(Func_Ang_State ? "【":"["); ui->Symb_Par_R->setText(Func_Ang_State ? "】":"]"); ui->Symb_Add->setText(Func_Ang_State ? "=":"+"); ui->Symb_Dec->setText(Func_Ang_State ? "-":"-"); ui->Symb_Bra_L->setText(Func_Ang_State ? "《":"<"); ui->Symb_Bra_R->setText(Func_Ang_State ? "》":">"); ui->Symb_Ver->setText(Func_Ang_State ? "|":"|"); ui->Symb_Wave->setText(Func_Ang_State ? "~":"~"); ui->Symb_Semi->setText(Func_Ang_State ? ";":";"); ui->Symb_Quo->setText(Func_Ang_State ? "'":"\""); } ui->TextBlock->setFocus(); } void InputDialog::on_Func_BS_pressed() { // QKeyEvent keyPress(QEvent::KeyPress, Qt::Key(), Qt::NoModifier, QString()); // ui->TextBlock->keyPressEvent(key); Flag = true; if(Flag) { QObject::connect(timer, &QTimer::timeout, this, [=](){ QKeyEvent keyPress(QEvent::KeyPress, Qt::Key_Backspace, Key_Modifier, QString()); QCoreApplication::sendEvent(ui->TextBlock, &keyPress); ui->TextBlock->setFocus(); }); } //第一次点击 if(Flag1 == false) { QKeyEvent keyPress(QEvent::KeyPress, Qt::Key_Backspace, Key_Modifier, QString()); QCoreApplication::sendEvent(ui->TextBlock, &keyPress); ui->TextBlock->setFocus(); Flag1 = true; timer->start(100); } } void InputDialog::on_Key_Left_pressed() { Flag = true; if(Flag) { QObject::connect(timer, &QTimer::timeout, this, [=](){ QKeyEvent keyPress(QEvent::KeyPress, Qt::Key_Left, Key_Modifier, QString()); QCoreApplication::sendEvent(ui->TextBlock, &keyPress); ui->TextBlock->setFocus(); }); } //第一次点击 if(Flag1 == false) { QKeyEvent keyPress(QEvent::KeyPress, Qt::Key_Left, Key_Modifier, QString()); QCoreApplication::sendEvent(ui->TextBlock, &keyPress); ui->TextBlock->setFocus(); Flag1 = true; timer->start(100); } } void InputDialog::on_Key_Right_pressed() { Flag = true; if(Flag) { QObject::connect(timer, &QTimer::timeout, this, [=](){ QKeyEvent keyPress(QEvent::KeyPress, Qt::Key_Right, Key_Modifier, QString()); QCoreApplication::sendEvent(ui->TextBlock, &keyPress); ui->TextBlock->setFocus(); }); } //第一次点击 if(Flag1 == false) { QKeyEvent keyPress(QEvent::KeyPress, Qt::Key_Right, Key_Modifier, QString()); QCoreApplication::sendEvent(ui->TextBlock, &keyPress); ui->TextBlock->setFocus(); Flag1 = true; timer->start(100); } } void InputDialog::on_Space_clicked() { QKeyEvent keyPress(QEvent::KeyPress, Qt::Key_Space, Key_Modifier, " "); QCoreApplication::sendEvent(ui->TextBlock, &keyPress); ui->TextBlock->setFocus(); } void InputDialog::on_Func_BS_released() { timer->stop(); timer->disconnect(); Flag = false; Flag1 = false; } void InputDialog::on_Key_Left_released() { timer->stop(); timer->disconnect(); Flag = false; Flag1 = false; } void InputDialog::on_Key_Right_released() { timer->stop(); timer->disconnect(); Flag = false; Flag1 = false; } ================================================ FILE: inputdialog.h ================================================ #ifndef INPUTDIALOG_H #define INPUTDIALOG_H #include #include #include extern int DebugFlat ; extern QSizeF SizePercent; namespace Ui { class InputDialog; } class InputDialog : public QDialog { Q_OBJECT signals: void closedialog(QString &value,bool &SettingMark); public: explicit InputDialog(QWidget *parent = nullptr); ~InputDialog(); public: // QString ReturnValue; // bool SettingMark = false; enum Option { All = 0, AD_int = 1, A_int = 2, AD_double = 3, A_double = 4, C_Lower = 5, C_Upper = 6 , F_ip = 7 }; QStringList Options { "-all", "-int", "int", "-double", "double", "-lower", "-upper", "-ip" }; public: void setvalue(QString PlaceholdText , QString InputMode , QString DefaultValue = QString::Null()); private slots: virtual void on_Btn_Undo_clicked(); virtual void on_Btn_Confirm_clicked(); virtual void on_Func_UL_clicked(bool checked); virtual void on_Func_Ang_clicked(bool checked); virtual void on_Func_BS_pressed(); virtual void on_Key_Left_pressed(); virtual void on_Key_Right_pressed(); virtual void on_CharKey_click(); virtual void on_NumKey_click(); virtual void on_SymbKey_click(); virtual void on_Space_clicked(); virtual void on_Beep_clicked(); virtual void released_clicked(); void on_Func_BS_released(); void on_Key_Left_released(); void on_Key_Right_released(); private: Ui::InputDialog *ui; // QWidget *FUI; QList NumBtns; QList CharBtns; QList SymbBtns; QList AllBtns; bool Func_UL_State = false; bool Func_Ang_State = false; bool Flag = false; bool Flag1 = false; QTimer *timer = new QTimer(); Qt::KeyboardModifier Key_Modifier = Qt::NoModifier; protected: void showEvent(QShowEvent *event); }; #endif // INPUTDIALOG_H ================================================ FILE: inputdialog.ui ================================================ InputDialog 0 0 800 480 0 0 InputPanel :/assets/icon/BingoTouch_Logo_H.svg:/assets/icon/BingoTouch_Logo_H.svg 3 5 5 5 5 3 BTStyleSheet2 :/assets/off.svg:/assets/off.svg 72 72 Qt::Horizontal QSizePolicy::Fixed 10 20 0 0 32 Qt::ClickFocus background-color: rgb(0, 0, 0); color: rgb(245, 246, 255); Please Input true Qt::Horizontal QSizePolicy::Fixed 10 20 BTStyleSheet2 Qt::RightToLeft :/assets/queren.svg:/assets/queren.svg 72 72 3 0 0 32 BTStyleSheet10 color: rgb(255, 255, 255); e 0 0 32 BTStyleSheet10 color: rgb(0, 255, 255); 0 0 0 32 BTStyleSheet10 color: rgb(255, 255, 255); s 0 0 32 BTStyleSheet10 color: rgb(255, 255, 255); o 0 0 32 BTStyleSheet10 color: rgb(255, 255, 255); z 0 0 32 BTStyleSheet10 color: rgb(255, 255, 255); k 0 0 32 BTStyleSheet10 color: rgb(214, 35, 29); > 0 0 32 BTStyleSheet10 color: rgb(214, 35, 29); - 0 0 32 BTStyleSheet10 color: rgb(0, 255, 255); 4 0 0 32 BTStyleSheet10 color: rgb(255, 255, 255); q 0 0 32 BTStyleSheet10 color: rgb(255, 255, 255); b 0 0 32 BTStyleSheet10 color: rgb(214, 35, 29); . 0 0 32 BTStyleSheet10 color: rgb(255, 255, 255); v 0 0 20 BTStyleSheet10 :/assets/kongge.svg:/assets/kongge.svg 300 30 0 0 32 BTStyleSheet10 color: rgb(255, 255, 255); j 0 0 32 BTStyleSheet10 color: rgb(214, 35, 29); ] 0 0 32 BTStyleSheet10 color: rgb(214, 35, 29); :/assets/deleteBtn.svg:/assets/deleteBtn.svg 40 40 0 0 20 BTStyleSheet10 color: rgb(214, 35, 29); ; 0 0 32 BTStyleSheet10 color: rgb(255, 255, 255); n 0 0 32 BTStyleSheet10 color: rgb(255, 255, 255); y 0 0 20 BTStyleSheet10 color: rgb(214, 35, 29); ~ 0 0 32 BTStyleSheet10 color: rgb(255, 255, 255); d 0 0 32 BTStyleSheet10 color: rgb(0, 255, 255); 7 0 0 32 BTStyleSheet10 color: rgb(255, 255, 255); t 0 0 32 BTStyleSheet10 color: rgb(214, 35, 29); [ 0 0 32 BTStyleSheet10 color: rgb(255, 255, 255); m 0 0 32 BTStyleSheet10 color: rgb(214, 35, 29); < 0 0 32 BTStyleSheet10 color: rgb(0, 255, 255); 3 0 0 32 BTStyleSheet10 color: rgb(255, 255, 255); i 0 0 32 BTStyleSheet10 color: rgb(255, 255, 255); p 0 0 32 BTStyleSheet10 color: rgb(255, 255, 255); g 0 0 32 BTStyleSheet10 color: rgb(0, 255, 255); 5 0 0 32 BTStyleSheet10 color: rgb(0, 255, 255); 2 0 0 32 BTStyleSheet10 color: rgb(214, 35, 29); 0 0 32 BTStyleSheet10 color: rgb(0, 255, 255); 1 0 0 32 BTStyleSheet10 color: rgb(0, 255, 255); 9 0 0 20 BTStyleSheet10 color: rgb(255, 249, 79) :/assets/back.svg:/assets/back.svg 0 0 32 BTStyleSheet10 color: rgb(255, 255, 255); l 0 0 32 BTStyleSheet10 color: rgb(255, 255, 255); r 0 0 32 BTStyleSheet10 color: rgb(255, 255, 255); c 0 0 20 BTStyleSheet10 color: rgb(255, 249, 79) :/assets/next.svg:/assets/next.svg 0 0 32 BTStyleSheet10 color: rgb(0, 255, 255); 8 0 0 32 BTStyleSheet10 color: rgb(255, 255, 255); h 0 0 32 BTStyleSheet10 color: rgb(255, 255, 255); a 0 0 32 BTStyleSheet10 color: rgb(255, 255, 255); w 0 0 32 BTStyleSheet10 color: rgb(255, 255, 255); f 0 0 32 BTStyleSheet10 color: rgb(0, 255, 255); 6 0 0 32 BTStyleSheet10 color: rgb(255, 255, 255); u 0 0 32 BTStyleSheet10 color: rgb(255, 255, 255); x 0 0 32 BTStyleSheet10 color: rgb(214, 35, 29); + 0 0 20 BTStyleSheet10 color: rgb(214, 35, 29); " 0 0 32 BTStyleSheet10 color: rgb(214, 35, 29); true 0 0 32 true BTStyleSheet10 color: rgb(0, 255, 255); Cap true ================================================ FILE: install.sh ================================================ echo "Updating system resources ..." sudo apt update -y #sudo apt upgrade -y echo "Done." #install Dependencies and Display Driver echo "Installing Dependencies ..." sudo apt install qt5-default qtcreator python3-pyqt5-dbg libqt5svg5 libqt5svg5-dev python3-pyqt5.qtsvg qtsvg5-doc libqt5websockets5 libqt5websockets5-dev ttf-wqy-zenhei qml-module-qtquick-controls2 libboost1.58-all-dev libudev-dev libinput-dev libts-dev libmtdev-dev libjpeg-dev libfontconfig1-dev libssl-dev libdbus-1-dev libglib2.0-dev libxkbcommon-dev libgbm-dev libgl1-mesa-dri qtdeclarative5-dev libqt5svg5 libqt5websockets5 ttf-wqy-zenhei -y echo "Check GLdriver ..." for package in gldriver-test libgl1-mesa-dri; do if [ "$(dpkg -l "$package" 2> /dev/null | tail -n 1 | cut -d ' ' -f 1)" != "ii" ]; then missing_packages="$package $missing_packages" fi done apt-get install $missing_packages -y echo "Done." echo "Set render ..." sudo gpasswd -a pi render echo "Done." #Change the permissions echo "Setting Permissions ..." #Set the boot options to CLI mode and set the auto-login to user 'pi' sudo systemctl set-default multi-user.target sudo ln -fs /lib/systemd/system/getty@.service /etc/systemd/system/getty.target.wants/getty@tty1.service sudo cat > /etc/systemd/system/getty@tty1.service.d/autologin.conf << EOF [Service] ExecStart= ExecStart=-/sbin/agetty --autologin pi --noclear %I \$TERM EOF sudo cat >> /etc/profile << EOF export QT_QPA_EGLFS_ALWAYS_SET_MODE=1 export QT_QPA_PLATFORM=eglfs EOF echo "Done." #Add sudo access for wireless configurations echo "Setting up Sudo for wifi configuration..." #sudo touch /etc/sudoers.d/OctoBTT #sudo echo "pi ALL=(ALL) NOPASSWD: /sbin/iwlist, /sbin/wpa_cli, /sbin/iwconfig, /sbins/ifconfig" > /etc/sudoers.d/OctoBTT sudo cp OctoBTT/OctoBTT.sudoers.d /etc/sudoers.d/OctoBTT echo "Done." su -l pi << EOF echo "Download OctoBTT ..." cd rm -rf OctoBTT git clone https://github.com/bigtreetech/OctoBTT.git #git clone https://gitee.com/Shine6Z/OctoBTT.git echo "Done." echo "Installing OctoBTT ..." cd ~/OctoBTT #mkdir projectfile #make clean #cp OctoBTT.pro projectfile/OctoBTT.pro qmake OctoBTT.pro #cp projectfile/OctoBTT.pro OctoBTT.pro #rm -r -f projectfile if [ ! -f "$OctoBTT" ]; then rm OctoBTT make clean fi make -j$(cat /proc/cpuinfo | grep processor | wc -l) EOF echo "Setting up Autostart ..." sudo sed -i 's/sudo \/bin\/sh \/home\/pi\/install.sh/su -l pi -c \"cd \/home\/pi\/OctoBTT \&\& .\/OctoBTT -platform eglfs\"/g' /etc/rc.local #sudo sed -i '/\[pi4\]/ i \[pi3\]\ndtoverlay=vc4-fkms-v3d' /boot/config.txt sudo sed '/\[all\]/adtoverlay=vc4-fkms-v3d\ngpu_mem=256' /boot/config.txt echo "Done." sudo reboot ================================================ FILE: liblog.cpp ================================================ #include "liblog.h" #include void LibLog::LogRec(QString message, QString exceptionName) { QTime systemTime = QTime::currentTime(); QDate systemDate = QDate::currentDate(); //文件名 日期+.log QString fileName = QString("%1%2.log").arg(systemDate.toString("yyyy_MM_dd")).arg((exceptionName.isNull()? "":"_" + exceptionName)); QFile file; //文件路径 file.setFileName("Log/" + fileName); //判断文件夹是否存在 if(!QDir("Log").exists()) { QDir().mkdir("Log"); } //以可读可写的形式打开文件,并将信息保存于该文件 file.open(QFile::Append); QFile::setPermissions(file.fileName(), QFileDevice::ReadOwner|QFileDevice::WriteOwner); if(file.isOpen()) { QString saveMessage = systemTime.toString("hh:mm:ss.zzz") + "\t" + message+ "\n"; file.write(saveMessage.toUtf8()); // debugShow(QSysInfo::productType() != "raspbian",systemTime.toString("hh:mm:ss.zzz"),message,exceptionName); } file.close(); } void LibLog::debugShow(bool flag, QString times, QString message, QString exceptionName) { if(flag) { //清除头尾的非必要字符并以\t划分 QStringList messageModule = message.trimmed().split('\t'); QStringList messageModules; foreach(QString inf , messageModule) { //排除空格 if(inf.trimmed().count() == 0) continue; //剩下以\n划分 messageModules.append(inf.trimmed().split('\n')); } //组合 message = messageModules.join(" > "); message = (exceptionName.isNull() ? QString("%1 >>> %2").arg(times).arg(message) : QString("%1 >>> %2 *** %3").arg(times).arg(exceptionName).arg(message)); //输出信息 qDebug() << message; } } ================================================ FILE: liblog.h ================================================ #ifndef LIBLOG_H #define LIBLOG_H #include #include #include #include #include class LibLog { public: static void LogRec(QString Message, QString exceptionName = NULL); private: static void debugShow(bool flag,QString times, QString message,QString exceptionName = NULL); // QTime systemTime = QTime::currentTime(); // QDate systemDate = QDate::currentDate(); }; #endif // LIBLOG_H ================================================ FILE: main.cpp ================================================ #include "mainwindow.h" //#include "controlpanel.h" #include #include #include #include #include #include #include #include #include #include #include QSharedMemory mem("OctoBTT"); QByteArray Global_X_API_Key = "";//Test Key int DebugFlat = 0;//Normal Flat : 0 ;Debug Mode : 1 QSizeF SizePercent = QSizeF(1.0,1.0);//Design Size 800:480 //QSize SizePercent(1,1); //存放配置信息 QString strConfiguration = ""; int main(int argc, char *argv[]) { //Application Encoding QTextCodec *codec = QTextCodec::codecForName("UTF-8"); QTextCodec::setCodecForLocale(codec); //Program Statement Code QApplication a(argc, argv); //设置全局按键默认样式表---12.24 //判断config.conf文件在不在 if(!QFile("config.conf").exists()) { //复制资源文件中的config.conf到用户本地文件夹里 QFile::copy(":/config.conf", "config.conf"); //设置权限 QFile::setPermissions("config.conf", QFileDevice::ReadOwner|QFileDevice::WriteOwner); //设置默认按键的样式表 QFile file("config.conf"); file.open(QFile::ReadOnly); if(file.isOpen()) { strConfiguration = file.readAll(); //全局默认设置 // // qApp->setStyleSheet(strConfiguration); } file.close(); } else { QFile file(":/config.conf"); file.open(QFile::ReadOnly); //获取用户本地的版本号 QString userNumber = file.readLine().trimmed(); QStringList userNumberList = userNumber.replace(QString("/*"),QString("")).replace(QString("*/"),QString("")).split("."); //判断版本号是否更新,如果版本号大于旧的版本号,就更新,否则不变 bool upDateFlag = false; QFile userFile("config.conf"); userFile.open(QFile::ReadOnly); QString strUpDate = userFile.readLine().trimmed(); QStringList strUpDateList = strUpDate.replace(QString("/*"),QString("")).replace(QString("*/"),QString("")).split("."); if(QString(strUpDateList.at(0)).toInt() > QString(userNumberList.at(0)).toInt()) upDateFlag = true; else if(QString(strUpDateList.at(0)).toInt() == QString(userNumberList.at(0)).toInt()) { if(QString(strUpDateList.at(1)).toInt() > QString(userNumberList.at(1)).toInt()) upDateFlag = true; else if(QString(strUpDateList.at(1)).toInt() == QString(userNumberList.at(1)).toInt()) if(QString(strUpDateList.at(2)).toInt() > QString(userNumberList.at(2)).toInt()) upDateFlag = true; } if(upDateFlag) { file.close(); //删除旧版本并复制新版本到用户本地文件中 //配置文件修改函数======================= // QFile::remove("/config.conf"); // QFile::copy(":/config.conf", "/config.conf"); //设置权限 QFile::setPermissions("config.conf", QFileDevice::ReadOwner|QFileDevice::WriteOwner); file.open(QFile::ReadOnly); if(file.isOpen()) { strConfiguration = file.readAll(); // qApp->setStyleSheet(strConfiguration); } } else { if(file.isOpen()) { strConfiguration = file.readAll(); // qApp->setStyleSheet(strConfiguration); } } file.close(); userFile.close(); } //设置全局按键默认样式表---12.22 QString strStyleSheet = ""; //判断StyleSheet目录在不在 if(!QDir("StyleSheet").exists()) { QDir().mkdir("StyleSheet"); //复制资源文件中的globalStyleSheet.qss到用户本地文件夹里 QFile::copy(":/StyleSheet/globalStyleSheet.qss", "StyleSheet/globalStyleSheet.qss"); //设置权限 QFile::setPermissions("StyleSheet/globalStyleSheet.qss", QFileDevice::ReadOwner|QFileDevice::WriteOwner); //设置默认按键的样式表 QFile file("StyleSheet/globalStyleSheet.qss"); file.open(QFile::ReadOnly); if(file.isOpen()) { strStyleSheet = file.readAll(); //全局默认设置 qApp->setStyleSheet(strStyleSheet); } file.close(); } else { QFile file("StyleSheet/globalStyleSheet.qss"); file.open(QFile::ReadOnly); //获取用户本地的版本号 QString userNumber = file.readLine().trimmed(); QStringList userNumberList = userNumber.replace(QString("/*"),QString("")).replace(QString("*/"),QString("")).split("."); //判断用户是否自定义了样式表 if(0 == QString(userNumberList.at(0)).toInt() && DebugFlat == 0) { //使用用户定义的样式表文件qss if(file.isOpen()) { strStyleSheet = file.readAll(); qApp->setStyleSheet(strStyleSheet); } } //如果不是就判断版本号是否更新 else { //如果资源版本号大于旧的版本号,就更新,否则不变 bool upDateFlag = false; QFile userFile(":/StyleSheet/globalStyleSheet.qss"); userFile.open(QFile::ReadOnly); QString strUpDate = userFile.readLine().trimmed(); QStringList strUpDateList = strUpDate.replace(QString("/*"),QString("")).replace(QString("*/"),QString("")).split("."); if(QString(strUpDateList.at(0)).toInt() > QString(userNumberList.at(0)).toInt()) upDateFlag = true; else if(QString(strUpDateList.at(0)).toInt() == QString(userNumberList.at(0)).toInt()) { if(QString(strUpDateList.at(1)).toInt() > QString(userNumberList.at(1)).toInt()) upDateFlag = true; else if(QString(strUpDateList.at(1)).toInt() == QString(userNumberList.at(1)).toInt()) if(QString(strUpDateList.at(2)).toInt() > QString(userNumberList.at(2)).toInt()) upDateFlag = true; } if(upDateFlag || DebugFlat == 1) { file.close(); //删除旧版本并复制新版本到用户本地文件中 QFile::remove("StyleSheet/globalStyleSheet.qss"); QFile::copy(":/StyleSheet/globalStyleSheet.qss", "StyleSheet/globalStyleSheet.qss"); //设置权限 QFile::setPermissions("StyleSheet/globalStyleSheet.qss", QFileDevice::ReadOwner|QFileDevice::WriteOwner); file.open(QFile::ReadOnly); if(file.isOpen()) { strStyleSheet = file.readAll(); qApp->setStyleSheet(strStyleSheet); } } else { if(file.isOpen()) { strStyleSheet = file.readAll(); qApp->setStyleSheet(strStyleSheet); } } file.close(); userFile.close(); } } //Find Api Key if(QSysInfo::productType() == "raspbian") { QFile configfile("/home/pi/.octoprint/config.yaml"); if(configfile.open(QIODevice::ReadOnly)) { QTextStream txtInput(&configfile); QStringList ConfigArgu = txtInput.readAll().split('\n'); configfile.close(); bool has_api = false; foreach(QString Argu,ConfigArgu) { if(Argu.indexOf("api:")>=0) { has_api = true; continue; } else if(has_api && Argu.indexOf("key:")>=0) { Global_X_API_Key = ((Argu.trimmed()).remove(0,(Argu.trimmed()).indexOf("key:")+4)).trimmed().toUtf8(); break; } } } else { DebugFlat = 1; } //Calculate the scale QScreen *screen=QGuiApplication::primaryScreen(); QRect mm=screen->availableGeometry(); SizePercent.setWidth((float)mm.width()/(float)800); SizePercent.setHeight((float)mm.height()/(float)480); // SizePercent = QSize(mm.width()/800,mm.height()/480); } MainWindow w; //Release Code if(QSysInfo::productType() == "raspbian") { //Single Program//Need a life cycle as the program was accidenta if (DebugFlat != 1 && !mem.create(1)) { QApplication::exit(); QApplication::quit(); return 0; } w.setWindowState(Qt::WindowFullScreen); // qDebug()<applicationDirPath()+"/start.sh"); } else { QProcess::startDetached(qApp->applicationFilePath(), QStringList()); } QApplication::exit(); QApplication::quit(); return 0; } else if(MCode == Base_Shutdown) { QProcess P(0); P.start("sudo shutdown now"); P.waitForStarted(); P.waitForFinished(); QApplication::exit(); QApplication::quit(); return 0; } else if(MCode == Base_OnlyExitApp) { if (mem.isAttached()) { mem.unlock(); mem.detach(); } QApplication::exit(); QApplication::quit(); return 0; } return MCode; } ================================================ FILE: mainwindow.cpp ================================================ #include "mainwindow.h" #include "ui_mainwindow.h" #include #include //#include #include #include #include #include //MY Dialog #include "controlpanel.h" #include "filedialog.h" #include "materialctrlpanel.h" #include #include #include #include #include #include #include MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); //network wake up octonetwork.ConnectFlat = true; QObject::connect(octonetwork.networkAccessManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(ConnectReply(QNetworkReply*)),Qt::UniqueConnection); octonetwork.networkAccessManager->get(octonetwork.GetConnectRequest); //SysTimer QTimer *m_timer= new QTimer(this); //启动或重启定时器, 并设置定时器时间:毫秒 //系统状态扫描触发计时器 m_timer->start(1000); //定时器触发信号槽 connect(m_timer, SIGNAL(timeout()), this, SLOT(TimerTimeOut())); this->resize((int)(SizePercent.width()*800),(int)(SizePercent.height()*480)); this->setMaximumSize((int)(SizePercent.width()*800),(int)(SizePercent.height()*480)); this->setFixedSize((int)(SizePercent.width()*800),(int)(SizePercent.height()*480)); // ui->Btn_Camera->setVisible(false); filedialog->InitializeUSBDrive(); //移动光标位置 QPoint pt(0,0); QPoint center = this->mapToGlobal(pt); QCursor::setPos(center); //设置各个按键的样式表 ui->Btn_CP->setStyleSheet("QPushButton{border:none;font: 20pt Gill Sans MT; MT;color: rgb(245, 246, 250);}" "QPushButton:pressed{border:none;background-color: rgb(128, 128, 128, 30%); padding-left:4px; padding-top:4px;}" "QPushButton:hover {border:none;background-color: rgb(128, 128, 128, 30%);}"); } MainWindow::~MainWindow() { if(!(gcodedialog->_pdataRecvWS->state() == QAbstractSocket::UnconnectedState)) gcodedialog->_pdataRecvWS->abort();//Close WS delete ui; } void MainWindow::TimerTimeOut() { if(QSysInfo::productType() != "raspbian") { LibLog::LogRec(QString("%1 : In :___%2___%3").arg(seq).arg(__FILE__).arg(__LINE__), "connect"); } //uodate UI ui->Btn_ConnectState->setText(octonetwork.ConnectState.contains("Printing") ? "Printing : " + filedialog->DisplayName :octonetwork.ConnectState); ui->Btn_CP->setText((materialctrlpanel->Hotend < 0 ? "-" : QString::number(materialctrlpanel->Hotend))+materialctrlpanel->Symb_Temp); ui->Btn_CP_1->setText((materialctrlpanel->Hotend < 0 ? "-" : QString::number(materialctrlpanel->Hotend))+materialctrlpanel->Symb_Temp); ui->Btn_CP_2->setText((materialctrlpanel->Heatbed < 0 ? "-" : QString::number(materialctrlpanel->Heatbed))+materialctrlpanel->Symb_Temp); if(octonetwork.ConnectState != "Printing" && octonetwork.ConnectState != "Printing from SD") { ui->Btn_CP_3->setIcon(QIcon(":/assets/fan.svg")); ui->Btn_CP_3->setText(QString::number(materialctrlpanel->FanSpeed/materialctrlpanel->FanSpeed_Max)+materialctrlpanel->Symb_Per); } //ui->Btn_ConnectState->repaint(); if(QSysInfo::productType() != "raspbian") { LibLog::LogRec(QString("%1 : %2___%3___%4").arg(octonetwork.ConnectState).arg(ui->Btn_ConnectState->text()).arg(__FILE__).arg(__LINE__), "connect"); } if(!octonetwork.ConnectFlat) { if(octonetwork.ConnectState == "Operational" || octonetwork.ConnectState == "Pausing" || octonetwork.ConnectState == "Starting" /*|| octonetwork.ConnectState == "Printing"*/ || octonetwork.ConnectState == "Cancelling" || octonetwork.ConnectState == "Starting print from SD") { octonetwork.ConnectFlat = true; QObject::connect(octonetwork.networkAccessManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(ConnectReply(QNetworkReply*)),Qt::UniqueConnection); octonetwork.networkAccessManager->get(octonetwork.GetConnectRequest); } else if(octonetwork.ConnectState == "Connecting" || octonetwork.ConnectState =="Detecting baudrate"|| octonetwork.ConnectState =="Detecting serial port") { octonetwork.ConnectFlat = true; QObject::connect(octonetwork.networkAccessManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(ConnectReply(QNetworkReply*)),Qt::UniqueConnection); octonetwork.networkAccessManager->get(octonetwork.GetConnectRequest); } else if(!USB_Port.isEmpty() && !octonetwork.ConnectState.contains("Printing"))//Close Offline Error { //Post materialctrlpanel->ReplyFlag = false; octonetwork.ConnectState = "Connecting"; QJsonDocument ConnectJson; QJsonObject _ConnectJson; _ConnectJson.insert("command","connect"); _ConnectJson.insert("port",USB_Port.takeFirst()); _ConnectJson.insert("baudrate",115200); _ConnectJson.insert("printerProfile","_default"); _ConnectJson.insert("save",false); _ConnectJson.insert("autoconnect",false); ConnectJson.setObject(_ConnectJson); if(QSysInfo::productType() != "raspbian") { LibLog::LogRec(QString("Connect : %1 : In :___%2___%3").arg(_ConnectJson.constFind("port").value().toString()).arg(__FILE__).arg(__LINE__), "connect"); } octonetwork.networkAccessManager->post(octonetwork.SetConnectRequest,ConnectJson.toJson()); } else if(!octonetwork.ConnectState.contains("Printing")) { octonetwork.ConnectFlat = true; QObject::connect(octonetwork.networkAccessManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(ConnectReply(QNetworkReply*)),Qt::UniqueConnection); octonetwork.networkAccessManager->get(octonetwork.GetConnectRequest); } //Button State if(octonetwork.ConnectState.contains("Printing")) { octonetwork.ConnectFlat = true; QObject::connect(octonetwork.networkAccessManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(StateReply(QNetworkReply*)),Qt::UniqueConnection); octonetwork.networkAccessManager->get(octonetwork.GetStateRequest); ui->Btn_Filament->setIcon(QIcon(":/assets/cancel.svg")); ui->Btn_Filament->setText(octonetwork.ConnectState); // ui->Btn_Filament->setEnabled(true); } else if(octonetwork.ConnectState == "Connecting" || octonetwork.ConnectState =="Detecting baudrate" || octonetwork.ConnectState =="Detecting serial port") { ui->Btn_Filament->setIcon(QIcon(":/assets/emoji.svg")); ui->Btn_Filament->setText("Connecting"); // ui->Btn_Filament->setEnabled(false); } else if(octonetwork.ConnectState == "Cancelling" || octonetwork.ConnectState =="Error" || octonetwork.ConnectState == "Starting print from SD" || octonetwork.ConnectState == "Starting") { ui->Btn_Filament->setIcon(QIcon(":/assets/emoji.svg")); ui->Btn_Filament->setText("Busy"); // ui->Btn_Filament->setEnabled(false); } else if(octonetwork.ConnectState =="Closed" || octonetwork.ConnectState =="Offline") { ui->Btn_Filament->setIcon(QIcon(":/assets/emoji.svg")); ui->Btn_Filament->setText("Lost connection"); } else { ui->Btn_Filament->setIcon(QIcon(":/assets/haocaiguanli.svg")); ui->Btn_Filament->setText("Print " + (filedialog->SelectURL.url() == "" ? "" : filedialog->DisplayName)); // ui->Btn_Filament->setEnabled(true); } } if(QSysInfo::productType() != "raspbian") { LibLog::LogRec(QString("%1 : Out :___%2___%3").arg(seq++).arg(__FILE__).arg(__LINE__), "connect"); LibLog::LogRec("***************************************", "connect"); } } void MainWindow::ConnectReply(QNetworkReply *reply) { int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); if(reply->error() == QNetworkReply::NoError) { QByteArray replyArray = reply->readAll(); QJsonDocument loadDoc(QJsonDocument::fromJson(replyArray)); QJsonObject QObj = loadDoc.object(); QList ReplyResult = octonetwork.SearchJsonValue(octonetwork.ConnectLink , QObj); octonetwork.ConnectState = ReplyResult[0].toString(); // ReplyResult[0].toArray().isEmpty()//判断是否为空 if(!USB_Port.isEmpty()) USB_Port.clear(); foreach(QJsonValue item , ReplyResult[1].toArray())//遍历可连接非串口设备 { if(octonetwork.ConnectSerialLink.contains(item.toString())) continue;//属于串口 USB_Port.append(item.toString()); } if(QSysInfo::productType() != "raspbian") { LibLog::LogRec(QString("%1___%2___%3").arg(QString(replyArray)).arg(__FILE__).arg(__LINE__), "connect"); } } else { octonetwork.ConnectState = "Error"; } if(QSysInfo::productType() != "raspbian") { LibLog::LogRec(QString("statusCode : %1___%2___%3").arg(statusCode).arg(__FILE__).arg(__LINE__), "connect"); LibLog::LogRec("***************************************", "connect"); } reply->deleteLater(); octonetwork.ConnectFlat = !octonetwork.ConnectFlat; octonetwork.networkAccessManager->disconnect(SIGNAL(finished(QNetworkReply*)));//disconnect } void MainWindow::StateReply(QNetworkReply *reply) { int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); if(reply->error() == QNetworkReply::NoError) { QByteArray replyArray = reply->readAll(); QJsonDocument loadDoc(QJsonDocument::fromJson(replyArray)); QJsonObject QObj = loadDoc.object(); QList ReplyResult = octonetwork.SearchJsonValue(octonetwork.StateLink , QObj); octonetwork.ConnectState = ReplyResult[0].toString(); // ui->Btn_Filament_B->setText(ui->Btn_Filament_B->text() + " " + QString::number((int)ReplyResult[1].Double) + "%"); ui->Btn_CP_3->setIcon(QIcon(":/assets/filament.svg")); ui->Btn_CP_3->setText(QString::number(ReplyResult[1].toDouble(),'f',2) + "%"); if(QSysInfo::productType() != "raspbian") { LibLog::LogRec(QString("%1___%2___%3").arg(QString(replyArray)).arg(__FILE__).arg(__LINE__), "connect"); } } else { octonetwork.ConnectState = "Error"; } if(QSysInfo::productType() != "raspbian") { LibLog::LogRec(QString("statusCode : %1___%2___%3").arg(statusCode).arg(__FILE__).arg(__LINE__), "connect"); LibLog::LogRec("***************************************", "connect"); } reply->deleteLater(); octonetwork.ConnectFlat = !octonetwork.ConnectFlat; octonetwork.networkAccessManager->disconnect(SIGNAL(finished(QNetworkReply*)));//disconnect } //Debug Btn void MainWindow::on_Btn_setting_clicked() { // terminaldialog->resize(this->width(),this->height()); // terminaldialog->setFixedSize(this->width(),this->height()); // terminaldialog->setWindowState(this->windowState()); // terminaldialog->show(); configuration->show(); // if(DebugFlat == 1) // { // connect(terminaldialog,&TerminalDialog::CMD_Reply,this,[=](QStringList CommandLine){ // disconnect(terminaldialog,&TerminalDialog::CMD_Reply,0,0); // }); // } } void MainWindow::on_Btn_Ctrl_clicked() { // controlpanel->resize(this->width(),this->height()); // controlpanel->setFixedSize(this->width(),this->height()); // controlpanel->setWindowState(this->windowState()); controlpanel->show(); } void MainWindow::on_UILogo_clicked() { if(DebugFlat > 0) { QStringList btnName = {"Yes", "No",} ; CustomDialog *newDialog = new CustomDialog(); QObject::connect(newDialog, &CustomDialog::OutputEvent, newDialog,[=](QString instruct) { if(instruct == "Yes") { qApp->exit(Base_OnlyExitApp); } }); newDialog->showCustomDialog("Quit desktop",":/assets/info.svg",btnName,"Do you want to quit desktop ?",this); } } void MainWindow::on_Btn_FS_clicked() { // filedialog->resize(this->width(),this->height()); // filedialog->setFixedSize(this->width(),this->height()); // filedialog->setWindowState(this->windowState()); // filedialog->RefreshFileList(); filedialog->show(); } void MainWindow::on_Btn_CP_clicked() { // materialctrlpanel->resize(this->width(),this->height()); // materialctrlpanel->setFixedSize(this->width(),this->height()); // materialctrlpanel->setWindowState(this->windowState()); materialctrlpanel->show(); } void MainWindow::on_Btn_Camera_clicked() { // cameradialog->resize(this->width(),this->height()); // cameradialog->setWindowState(this->windowState()); // cameradialog->show(); // url_camera->resize(this->width(),this->height()); // url_camera->setFixedSize(this->width(),this->height()); // url_camera->setWindowState(this->windowState()); cameradialog->show(); } //Detail For Print void MainWindow::on_Btn_Filament_clicked() { if(filedialog->SelectURL.url().trimmed() == "") filedialog->show(); else octonetwork.JobSwitch(filedialog->SelectURL); } ================================================ FILE: mainwindow.h ================================================ #ifndef MAINWINDOW_H #define MAINWINDOW_H #include #include //#include //#include #include //MY Dialog #include "cameradialog.h" #include "controlpanel.h" #include "filedialog.h" #include "materialctrlpanel.h" #include "octonetwork.h" #include "terminaldialog.h" #include "configuration.h" #include "wlanconfig.h" #include "gcodedialog.h" //#include "webdialog.h" extern int DebugFlat ; extern QSizeF SizePercent; QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); public: OctoNetwork octonetwork = OctoNetwork(this); // OctoNetwork octonetwork; private slots: virtual void on_Btn_setting_clicked(); virtual void on_Btn_Ctrl_clicked(); virtual void on_UILogo_clicked(); virtual void on_Btn_FS_clicked(); virtual void on_Btn_CP_clicked(); virtual void on_Btn_Camera_clicked(); virtual void TimerTimeOut(); virtual void ConnectReply(QNetworkReply *reply); virtual void StateReply(QNetworkReply *reply); virtual void on_Btn_Filament_clicked(); private: Ui::MainWindow *ui; // QString SearchJsonValue(QList Find_List_Name , QJsonObject _QObj); public://Frm ControlPanel *controlpanel = new ControlPanel(this); FileDialog *filedialog = new FileDialog(this); MaterialCtrlPanel *materialctrlpanel = new MaterialCtrlPanel(this); CameraDialog *cameradialog = new CameraDialog(this); // URL_Camera *url_camera = new URL_Camera(this); TerminalDialog *terminaldialog = new TerminalDialog(this); GcodeDialog *gcodedialog = new GcodeDialog(this); Configuration *configuration = new Configuration(this); Wlanconfig *wlanconfig = new Wlanconfig(this); // WebDialog *webdialog = new WebDialog(this); private: QList USB_Port; // QTimer *m_timer; // void InitTimer(); // QNetworkAccessManager *networkAccessManager = new QNetworkAccessManager(); // QNetworkRequest request; // bool ConnectFlat = false; // QString ConnectState = "Close"; // QByteArray X_API_Key = "C1B64D24AE99475EAA9385B5DBC77820"; // QString MainUrl = "http://192.168.3.111/api/"; int seq = 1; }; #endif // MAINWINDOW_H ================================================ FILE: mainwindow.ui ================================================ MainWindow Qt::WindowModal 0 0 800 480 0 0 OctoBTT :/assets/icon/BTT_Duck.svg:/assets/icon/BTT_Duck.svg 0 0 5 5 5 5 3 QLayout::SetDefaultConstraint 2 QLayout::SetFixedSize Qt::Horizontal QSizePolicy::MinimumExpanding 5 10 0 0 ArrowCursor border:none;font: 40pt "Gill Sans Ultra Bold"; color: rgb(0, 170, 255); OctoBTT :/assets/icon/icon-main-btt-blue.svg:/assets/icon/icon-main-btt-blue.svg 72 72 Qt::Horizontal QSizePolicy::MinimumExpanding 5 10 true 0 0 PointingHandCursor Qt::NoContextMenu BTStyleSheet4 border:none; :/assets/xitongpeizhi.svg:/assets/xitongpeizhi.svg 72 72 3 Qt::Horizontal QSizePolicy::MinimumExpanding 5 10 0 Qt::Vertical QSizePolicy::Preferred 10 60 0 0 96 86 PointingHandCursor Qt::NoContextMenu BTStyleSheet9 Files :/assets/wenjian.svg:/assets/wenjian.svg 96 96 Qt::ToolButtonTextUnderIcon Qt::Vertical QSizePolicy::Preferred 10 60 Qt::Horizontal QSizePolicy::MinimumExpanding 5 10 0 Qt::Vertical QSizePolicy::Preferred 10 60 0 0 0 0 PointingHandCursor Qt::NoContextMenu BTStyleSheet9 Filament :/assets/haocaiguanli.svg:/assets/haocaiguanli.svg 96 96 Qt::ToolButtonTextUnderIcon Qt::Vertical QSizePolicy::Preferred 10 20 Qt::Horizontal QSizePolicy::MinimumExpanding 5 10 0 Qt::Vertical QSizePolicy::Preferred 10 60 0 0 PointingHandCursor Qt::NoContextMenu BTStyleSheet9 Control :/assets/Ddayin.svg:/assets/Ddayin.svg 96 96 Qt::ToolButtonTextUnderIcon Qt::Vertical QSizePolicy::Preferred 10 20 Qt::Horizontal QSizePolicy::MinimumExpanding 5 10 2 QLayout::SetFixedSize Qt::Horizontal QSizePolicy::MinimumExpanding 5 10 Qt::Horizontal QSizePolicy::MinimumExpanding 5 10 0 0 PointingHandCursor BTStyleSheet3 border:none; font: 75 30pt "Gill Sans MT"; color: rgb(194, 54, 22); 23℃ :/assets/penzui.svg:/assets/penzui.svg 64 64 Qt::Horizontal QSizePolicy::MinimumExpanding 5 10 0 0 PointingHandCursor BTStyleSheet3 border:none; font: 75 30pt "Gill Sans MT"; color: rgb(215, 169, 42); 23℃ :/assets/re.svg:/assets/re.svg 64 64 Qt::Horizontal QSizePolicy::MinimumExpanding 5 10 0 0 PointingHandCursor BTStyleSheet3 border:none; color: rgb(0, 151, 230); font: 75 30pt "Gill Sans MT"; 100% :/assets/fan.svg:/assets/fan.svg 64 64 Qt::Horizontal QSizePolicy::MinimumExpanding 5 10 Qt::Horizontal QSizePolicy::MinimumExpanding 5 10 2 QLayout::SetFixedSize 0 0 PointingHandCursor BTStyleSheet3 border:none;; font: 20pt "Gill Sans MT"; color: rgb(245, 246, 250); Camera :/assets/video.svg:/assets/video.svg 32 32 Qt::Horizontal QSizePolicy::MinimumExpanding 5 10 0 0 PointingHandCursor border:none; font: 20pt "Gill Sans MT"; color: rgb(245, 246, 250); 23.4℃ :/assets/thermometer.svg:/assets/thermometer.svg 32 32 Qt::Horizontal QSizePolicy::MinimumExpanding 5 10 0 0 ArrowCursor Qt::RightToLeft border:none; font: 20pt "Gill Sans MT"; color: rgb(245, 246, 250); Close :/assets/icon/BingoTouch_Logo_H.svg:/assets/icon/BingoTouch_Logo_H.svg 32 32 Btn_CP_1 clicked() Btn_CP click() 188 408 377 461 Btn_CP_2 clicked() Btn_CP click() 395 408 377 461 Btn_CP_3 clicked() Btn_CP click() 606 408 377 461 ================================================ FILE: materialctrlpanel.cpp ================================================ #include "materialctrlpanel.h" #include "ui_materialctrlpanel.h" #include #include #include //#include #include #include //#include MaterialCtrlPanel::MaterialCtrlPanel(QWidget *parent) : QDialog(parent), ui(new Ui::MaterialCtrlPanel) { ui->setupUi(this); FUI = (MainWindow*)parent; ReLoopFlag = E_Temperature; QObject::connect(((MainWindow*)FUI)->octonetwork.MCPnetworkAccessManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(Reply(QNetworkReply*)),Qt::UniqueConnection); //SysTimer QTimer *m_timer= new QTimer(this); //启动或重启定时器, 并设置定时器时间:毫秒 m_timer->start(10); //定时器触发信号槽 connect(m_timer, SIGNAL(timeout()), this, SLOT(TimerTimeOut())); //屏幕自适应大小 this->resize((int)(SizePercent.width()*800),(int)(SizePercent.height()*480)); this->setMaximumSize((int)(SizePercent.width()*800),(int)(SizePercent.height()*480)); this->setFixedSize((int)(SizePercent.width()*800),(int)(SizePercent.height()*480)); //设置Save按键的边框样式表 ui->Btn_Save->setStyleSheet("border-color: rgb(85, 255, 0);"); } void MaterialCtrlPanel::TimerTimeOut() { if(!SettingFlag) { Hotend_Target = Hotend; Heatbed_Target = Heatbed; Feedrate_Target = Feedrate; Flowrate_Target = Flowrate; Tool_Target = Tool; FanSpeed_Target = FanSpeed; } //update UI ui->Txt_Hotend->setText((Hotend < 0 ? "-" : QString::number(Hotend_Target))+Symb_Temp); ui->Btn_Hotend_A->setEnabled(Hotend >= 0); ui->Btn_Hotend_D->setEnabled(Hotend >= 0); ui->Txt_Heatbed->setText((Heatbed < 0 ? "-" : QString::number(Heatbed_Target))+Symb_Temp); ui->Btn_Heatbed_A->setEnabled(Heatbed >= 0); ui->Btn_Heatbed_D->setEnabled(Heatbed >= 0); ui->Txt_Feedrate->setText((Feedrate < 0 ? "-" : QString::number(Feedrate_Target))+Symb_Per); ui->Btn_Feedrate_A->setEnabled(Feedrate >= 0); ui->Btn_Feedrate_D->setEnabled(Feedrate >= 0); ui->Txt_Flowrate->setText((Flowrate < 0 ? "-" : QString::number(Flowrate_Target))+Symb_Per); ui->Btn_Flowrate_A->setEnabled(Flowrate >= 0); ui->Btn_Flowrate_D->setEnabled(Flowrate >= 0); //ui->Btn_ConnectState->repaint(); if((((MainWindow*)FUI)->octonetwork.ConnectState == "Operational" || ((MainWindow*)FUI)->octonetwork.ConnectState == "Printing" || ((MainWindow*)FUI)->octonetwork.ConnectState == "Cancelling" || ((MainWindow*)FUI)->octonetwork.ConnectState == "Pausing" || ((MainWindow*)FUI)->octonetwork.ConnectState == "Starting" || ((MainWindow*)FUI)->octonetwork.ConnectState == "Printing from SD" || ((MainWindow*)FUI)->octonetwork.ConnectState == "Starting print from SD") && !ReplyFlag) { // //Post // Fui->octonetwork.ConnectState = "Connecting"; switch(ReLoopFlag) { case E_Temperature : ((MainWindow*)FUI)->octonetwork.MCPnetworkAccessManager->get(((MainWindow*)FUI)->octonetwork.GetTemperatureRequest); break; default: break; } ReplyFlag = true; } else if((((MainWindow*)FUI)->octonetwork.ConnectState == "Closed" || ((MainWindow*)FUI)->octonetwork.ConnectState.contains("Error")) || ((MainWindow*)FUI)->octonetwork.ConnectState == "Connecting" || ((MainWindow*)FUI)->octonetwork.ConnectState =="Detecting baudrate" || ((MainWindow*)FUI)->octonetwork.ConnectState =="Detecting serial port") { Hotend = -15; Heatbed = -15; Feedrate = 0; Flowrate = 0; Tool = -15; FanSpeed = 0; } } void MaterialCtrlPanel::Reply(QNetworkReply *reply) { QList _V_Temperature; int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); if(reply->error() == QNetworkReply::NoError) { QByteArray replyArray = reply->readAll(); QJsonDocument loadDoc(QJsonDocument::fromJson(replyArray)); QJsonObject QObj = loadDoc.object(); double HotendValue = -15; double ToolValue = -15; switch(ReLoopFlag) { case E_Temperature : _V_Temperature << ((MainWindow*)FUI)->octonetwork.SearchJsonValue(((MainWindow*)FUI)->octonetwork.TemperatureLink , QObj); Heatbed = _V_Temperature[0].toDouble(); foreach(QJsonValue item,_V_Temperature[1].toArray()) { if(QSysInfo::productType() != "raspbian"){ LibLog::LogRec(QString("%1___%2___%3").arg(item.toDouble()).arg(__FILE__).arg(__LINE__), "connect"); } if(item.toDouble() > HotendValue) HotendValue = item.toDouble(); else if(item.toDouble() > ToolValue) ToolValue = item.toDouble(); } Hotend = HotendValue; Tool = ToolValue; break; default: break; } if(QSysInfo::productType() != "raspbian") { LibLog::LogRec(QString("%1___%2___%3").arg(QString(replyArray)).arg(__FILE__).arg(__LINE__), "connect"); } } else { ((MainWindow*)FUI)->octonetwork.ConnectState = "Error"; } if(QSysInfo::productType() != "raspbian") { LibLog::LogRec(QString("statusCode : %1___%2___%3").arg(statusCode).arg(__FILE__).arg(__LINE__), "connect"); LibLog::LogRec("***************************************", "connect"); } reply->deleteLater(); ReLoopFlag ++ ; if(ReLoopFlag > E_Temperature) { ReLoopFlag = E_Temperature; } ReplyFlag = false; // ((MainWindow*)FUI)->octonetwork.MCPnetworkAccessManager->disconnect(SIGNAL(finished(QNetworkReply*)));//disconnect } MaterialCtrlPanel::~MaterialCtrlPanel() { delete ui; } void MaterialCtrlPanel::on_Btn_back_clicked() { SettingFlag = false; this->close(); } void MaterialCtrlPanel::on_Btn_Save_pressed() { QList _GCode_Setting; if(Heatbed != Heatbed_Target) { _GCode_Setting.append("M140 S"+QString::number((int)Heatbed_Target)); } if(Hotend != Hotend_Target) { _GCode_Setting.append("M104 S"+QString::number((int)Hotend_Target)); } ((MainWindow*)FUI)->octonetwork.SendGCode(_GCode_Setting); // qDebug()<Btn_Save->setStyleSheet(StyleSheet_Temp); } void MaterialCtrlPanel::on_Btn_Hotend_A_pressed() { SettingFlag = true; StyleSheet_Temp = ui->Btn_Hotend_A->styleSheet(); ui->Btn_Hotend_A->setStyleSheet(StyleSheet_Temp+"\nbackground-color:rgb(128,128,128,128);"); timer = new mTimer(&Hotend_Target,qobject_cast(sender()),1); MaterialCtrlPanel::longPress(&Hotend_Max); } void MaterialCtrlPanel::on_Btn_Hotend_A_released() { timer->stop(); timer->disconnect(); timerStartFlag = false; firstClickedFlag = false; ui->Btn_Hotend_A->setStyleSheet(StyleSheet_Temp); } void MaterialCtrlPanel::on_Btn_Hotend_D_pressed() { SettingFlag = true; StyleSheet_Temp = ui->Btn_Hotend_D->styleSheet(); ui->Btn_Hotend_D->setStyleSheet(StyleSheet_Temp+"\nbackground-color:rgb(128,128,128,128);"); timer = new mTimer(&Hotend_Target,qobject_cast(sender()),-1); MaterialCtrlPanel::longPress(&Hotend_Max); } void MaterialCtrlPanel::on_Btn_Hotend_D_released() { timer->stop(); timer->disconnect(); timerStartFlag = false; firstClickedFlag = false; ui->Btn_Hotend_D->setStyleSheet(StyleSheet_Temp); } void MaterialCtrlPanel::on_Btn_Heatbed_A_pressed() { SettingFlag = true; StyleSheet_Temp = ui->Btn_Heatbed_A->styleSheet(); ui->Btn_Heatbed_A->setStyleSheet(StyleSheet_Temp+"\nbackground-color:rgb(128,128,128,128);"); timer = new mTimer(&Heatbed_Target,qobject_cast(sender()),1); MaterialCtrlPanel::longPress(&Heatbed_Max); } void MaterialCtrlPanel::on_Btn_Heatbed_A_released() { timer->stop(); timer->disconnect(); timerStartFlag = false; firstClickedFlag = false; ui->Btn_Heatbed_A->setStyleSheet(StyleSheet_Temp); } void MaterialCtrlPanel::on_Btn_Heatbed_D_pressed() { SettingFlag = true; StyleSheet_Temp = ui->Btn_Heatbed_D->styleSheet(); ui->Btn_Heatbed_D->setStyleSheet(StyleSheet_Temp+"\nbackground-color:rgb(128,128,128,128);"); timer = new mTimer(&Heatbed_Target,qobject_cast(sender()),-1); MaterialCtrlPanel::longPress(&Heatbed_Max); } void MaterialCtrlPanel::on_Btn_Heatbed_D_released() { timer->stop(); timer->disconnect(); timerStartFlag = false; firstClickedFlag = false; ui->Btn_Heatbed_D->setStyleSheet(StyleSheet_Temp); } void MaterialCtrlPanel::on_Btn_Feedrate_A_pressed() { SettingFlag = true; StyleSheet_Temp = ui->Btn_Feedrate_A->styleSheet(); ui->Btn_Feedrate_A->setStyleSheet(StyleSheet_Temp+"\nbackground-color:rgb(128,128,128,128);"); timer = new mTimer(&Feedrate_Target,qobject_cast(sender()),1); MaterialCtrlPanel::longPress(&Feedrate_Max); } void MaterialCtrlPanel::on_Btn_Feedrate_A_released() { timer->stop(); timer->disconnect(); timerStartFlag = false; firstClickedFlag = false; ui->Btn_Feedrate_A->setStyleSheet(StyleSheet_Temp); } void MaterialCtrlPanel::on_Btn_Feedrate_D_pressed() { SettingFlag = true; StyleSheet_Temp = ui->Btn_Feedrate_D->styleSheet(); ui->Btn_Feedrate_D->setStyleSheet(StyleSheet_Temp+"\nbackground-color:rgb(128,128,128,128);"); timer = new mTimer(&Feedrate_Target,qobject_cast(sender()),-1); MaterialCtrlPanel::longPress(&Feedrate_Max); } void MaterialCtrlPanel::on_Btn_Feedrate_D_released() { timer->stop(); timer->disconnect(); timerStartFlag = false; firstClickedFlag = false; ui->Btn_Feedrate_D->setStyleSheet(StyleSheet_Temp); } void MaterialCtrlPanel::on_Btn_Flowrate_A_pressed() { SettingFlag = true; StyleSheet_Temp = ui->Btn_Flowrate_A->styleSheet(); ui->Btn_Flowrate_A->setStyleSheet(StyleSheet_Temp+"\nbackground-color:rgb(128,128,128,128);"); timer = new mTimer(&Flowrate_Target,qobject_cast(sender()),1); MaterialCtrlPanel::longPress(&Flowrate_Max); } void MaterialCtrlPanel::on_Btn_Flowrate_A_released() { timer->stop(); timer->disconnect(); timerStartFlag = false; firstClickedFlag = false; ui->Btn_Flowrate_A->setStyleSheet(StyleSheet_Temp); } void MaterialCtrlPanel::on_Btn_Flowrate_D_pressed() { SettingFlag = true; StyleSheet_Temp = ui->Btn_Flowrate_D->styleSheet(); ui->Btn_Flowrate_D->setStyleSheet(StyleSheet_Temp+"\nbackground-color:rgb(128,128,128,128);"); timer = new mTimer(&Flowrate_Target,qobject_cast(sender()),-1); MaterialCtrlPanel::longPress(&Flowrate_Max); } void MaterialCtrlPanel::on_Btn_Flowrate_D_released() { timer->stop(); timer->disconnect(); timerStartFlag = false; firstClickedFlag = false; ui->Btn_Flowrate_D->setStyleSheet(StyleSheet_Temp); } void MaterialCtrlPanel::longPress(const double *maximumCount) { //设置长按效果--12.25 timerStartFlag = true; if(timerStartFlag) { connect(timer, &mTimer::mtimeout, this, [=](){ if(timer->addval > 0) { if(*(timer->value) + timer->addval < *maximumCount) *(timer->value) += timer->addval; else *(timer->value) = *maximumCount; } else { if(*(timer->value) + timer->addval > 0) *(timer->value) += timer->addval; else *(timer->value) = 0; } *timer->value = (int)*(timer->value); }); } //第一次点击 if(firstClickedFlag == false) { if(timer->addval > 0) { if(*(timer->value) + timer->addval < *maximumCount) { *(timer->value) += timer->addval; } else *(timer->value) = *maximumCount; } else { if(*(timer->value) + timer->addval > 0) *(timer->value) += timer->addval; else *(timer->value) = 0; } *(timer->value) = (int)*(timer->value); firstClickedFlag = true; timer->start(100); } } ================================================ FILE: materialctrlpanel.h ================================================ #ifndef MATERIALCTRLPANEL_H #define MATERIALCTRLPANEL_H #include #include #include #include extern int DebugFlat ; extern QSizeF SizePercent; namespace Ui { class MaterialCtrlPanel; class mTimer; } class mTimer : public QTimer { Q_OBJECT public: mTimer(double *_value_,QPushButton *_button_,int _addval_) { value=_value_; button=_button_; addval=_addval_; connect(this, &mTimer::timeout, this, [=](){ if(count == 9) { addval *= 10; count++; } else count++; emit mtimeout(); }); } //传入变更值,按键以及阈值 double *value; QPushButton *button; double addval; private: int count = 0; signals: void mtimeout(); }; class MaterialCtrlPanel : public QDialog { Q_OBJECT public: explicit MaterialCtrlPanel(QWidget *parent = nullptr); ~MaterialCtrlPanel(); public: void longPress(const double *maximumCount); double Hotend = 0; double Heatbed = 0; double Tool = 0; double Feedrate = 0; double Flowrate = 0; double FanSpeed = 0; const double Hotend_Max = 260; const double Heatbed_Max = 260; const double Tool_Max = 0; const double Feedrate_Max = 100; const double Flowrate_Max = 100; const double FanSpeed_Max = 255; QString Symb_Temp = "℃"; QString Symb_Per = "%"; bool ReplyFlag = false; private slots: virtual void on_Btn_back_clicked(); virtual void on_Btn_Save_pressed(); virtual void on_Btn_Save_released(); virtual void on_Btn_Hotend_A_pressed(); virtual void on_Btn_Hotend_D_released(); virtual void on_Btn_Hotend_A_released(); virtual void on_Btn_Hotend_D_pressed(); virtual void on_Btn_Heatbed_A_pressed(); virtual void on_Btn_Heatbed_A_released(); virtual void on_Btn_Heatbed_D_pressed(); virtual void on_Btn_Heatbed_D_released(); virtual void on_Btn_Feedrate_A_pressed(); virtual void on_Btn_Feedrate_A_released(); virtual void on_Btn_Feedrate_D_pressed(); virtual void on_Btn_Feedrate_D_released(); virtual void on_Btn_Flowrate_A_pressed(); virtual void on_Btn_Flowrate_A_released(); virtual void on_Btn_Flowrate_D_pressed(); virtual void on_Btn_Flowrate_D_released(); virtual void TimerTimeOut(); virtual void Reply(QNetworkReply *reply); private: double Hotend_Target = 0; double Heatbed_Target = 0; double Tool_Target = 0; double Feedrate_Target = 0; double Flowrate_Target = 0; double FanSpeed_Target = 0; double number = 0; int SettingStep = 1; bool timerStartFlag = false; bool firstClickedFlag = false; mTimer *timer; bool SettingFlag = false; enum ReLoop {E_Temperature}; int ReLoopFlag; Ui::MaterialCtrlPanel *ui; QWidget *FUI; QString StyleSheet_Temp; }; #endif // MATERIALCTRLPANEL_H ================================================ FILE: materialctrlpanel.ui ================================================ MaterialCtrlPanel 0 0 800 480 0 0 Materialctrl :/assets/kongzhimianban2.svg:/assets/kongzhimianban2.svg 3 5 5 5 5 BTStyleSheet2 :/assets/huitui.svg:/assets/huitui.svg 72 72 Qt::Horizontal 40 20 border:none; font: 75 30pt "Gill Sans MT"; :/assets/kongzhimianban_L.svg:/assets/kongzhimianban_L.svg 72 72 Qt::Horizontal 40 20 84 78 QLayout::SetDefaultConstraint 3 Qt::Horizontal QSizePolicy::Preferred 10 10 Gill Sans MT 15 50 false true color: rgb(255, 255, 255); Hotend Qt::AlignCenter 1 3 3 3 3 0 0 Gill Sans MT 25 50 false padding: 10px; border-style: solid; border-width: 5px; border-radius: 20px; + 48 48 false buttonGroup 0 0 Gill Sans MT 30 50 false Border:none; color: rgb(245, 246, 250); 200℃ 64 64 true false 0 0 Gill Sans MT 25 50 false padding: 10px; border-style: solid; border-width: 5px; border-radius: 20px; - 48 48 500 buttonGroup Gill Sans MT 15 50 false true color: rgb(255, 255, 255); Heatbed Qt::AlignCenter 1 3 3 3 3 0 0 Gill Sans MT 25 50 false padding: 10px; border-style: solid; border-width: 5px; border-radius: 20px; + 48 48 buttonGroup 0 0 Gill Sans MT 30 50 false Border:none; color: rgb(245, 246, 250); 60℃ 64 64 true false 0 0 Gill Sans MT 25 50 false padding: 10px; border-style: solid; border-width: 5px; border-radius: 20px; - 48 48 buttonGroup Qt::Horizontal QSizePolicy::Preferred 10 10 Qt::Horizontal QSizePolicy::Preferred 10 10 Qt::Vertical QSizePolicy::Preferred 10 10 Gill Sans MT 15 50 false true color: rgb(255, 255, 255); Flowrate Qt::AlignCenter 1 3 3 3 3 0 0 Gill Sans MT 25 50 false padding: 10px; border-style: solid; border-width: 5px; border-radius: 20px; + 48 48 buttonGroup 0 0 Gill Sans MT 30 50 false Border:none; color: rgb(245, 246, 250); 100% 64 64 true false 0 0 Gill Sans MT 25 50 false padding: 10px; border-style: solid; border-width: 5px; border-radius: 20px; - 48 48 buttonGroup Qt::Horizontal QSizePolicy::Preferred 10 10 0 0 Gill Sans MT 30 50 false BTStyleSheet1 SAVE 64 64 buttonGroup Qt::Vertical QSizePolicy::Preferred 10 10 Qt::Horizontal QSizePolicy::Preferred 10 10 Qt::Vertical QSizePolicy::Preferred 10 10 Gill Sans MT 15 50 false true color: rgb(255, 255, 255); Feedrate Qt::AlignCenter 1 3 3 3 3 0 0 Gill Sans MT 25 50 false padding: 10px; border-style: solid; border-width: 5px; border-radius: 20px; + 48 48 buttonGroup 0 0 Gill Sans MT 30 50 false Border:none; color: rgb(245, 246, 250); 100% 64 64 true false 0 0 Gill Sans MT 25 50 false padding: 10px; border-style: solid; border-width: 5px; border-radius: 20px; - 48 48 buttonGroup ================================================ FILE: mylineedit.cpp ================================================ #include "mylineedit.h" MyLineEdit::MyLineEdit(QWidget *parent):QLineEdit(parent) { FUI = (QWidget*)parent;//((MainWindow*)FUI)->octonetwork.SendGCode(_GCode_Setting); // connect(inputdialog,&InputDialog::closedialog,this,[=](QString value,bool SettingMark){ // FUI->show(); // if(SettingMark) // { // this->setText(value); // } //// inputdialog->close(); //// this->show(); // }); } //MyLineEdit::~MyLineEdit() //{ //// inputdialog->~InputDialog(); //// delete this; // this->close(); //} void MyLineEdit::mousePressEvent(QMouseEvent *event) { Q_UNUSED(event); // inputdialog->setvalue("Please Input Commands","",this->text()); InputDialog *inputdialog = new InputDialog(FUI); connect(inputdialog,&InputDialog::closedialog,this,[=](QString value,bool SettingMark){ if(SettingMark) { this->setText(value); } FUI->show(); delete sender(); }); inputdialog->setvalue("Please Input Commands","",this->text()); } ================================================ FILE: mylineedit.h ================================================ #ifndef MYLINEEDIT_H #define MYLINEEDIT_H #include #include "inputdialog.h" class MyLineEdit : public QLineEdit { public: // MyLineEdit(QWidget *parent=0); explicit MyLineEdit(QWidget *parent = Q_NULLPTR); // explicit MyLineEdit(const QString &, QWidget *parent = Q_NULLPTR); // ~MyLineEdit(); public: private: // InputDialog *inputdialog = new InputDialog(this); QWidget *FUI; protected: void mousePressEvent(QMouseEvent *); }; #endif // MYLINEEDIT_H ================================================ FILE: octonetwork.cpp ================================================ #include "octonetwork.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include "customdialog.h" OctoNetwork::OctoNetwork(QWidget *parent) { FUI = (MainWindow*)parent; GetConnectRequest.setUrl(QUrl(MainUrl + "connection")); GetConnectRequest.setRawHeader("X_Api_Key",X_API_Key); GetConnectRequest.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/json")); GetStateRequest.setUrl(QUrl(MainUrl + "job")); GetStateRequest.setRawHeader("X_Api_Key",X_API_Key); GetStateRequest.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/json")); SetConnectRequest.setUrl(QUrl(MainUrl + "connection")); SetConnectRequest.setRawHeader("X_Api_Key",X_API_Key); SetConnectRequest.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/json")); GetTemperatureRequest.setUrl(QUrl(MainUrl + "printer")); GetTemperatureRequest.setRawHeader("X_Api_Key",X_API_Key); GetTemperatureRequest.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/json")); SetCMDRequest.setUrl(QUrl(MainUrl + "printer/command")); SetCMDRequest.setRawHeader("X_Api_Key",X_API_Key); SetCMDRequest.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/json")); SDRequest.setUrl(QUrl(MainUrl + "printer/sd")); SDRequest.setRawHeader("X_Api_Key",X_API_Key); SDRequest.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/json")); FileRequest.setUrl(QUrl(MainUrl + "files")); FileRequest.setRawHeader("X_Api_Key",X_API_Key); FileRequest.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/json")); // TemperatureJson.object().insert("command","target"); //save code //QMetaObject::Connection connRet = QObject::connect(networkAccessManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(ConnectReplay(QNetworkReply*))); //Q_ASSERT(connRet); } QJsonValue OctoNetwork::SearchJsonValue(QList Find_List_Name ,QNetworkReply *reply) { int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); if(QSysInfo::productType() != "raspbian") { LibLog::LogRec(QString("statusCode : %1___%2___%3").arg(statusCode).arg(__FILE__).arg(__LINE__), "connect"); } if(statusCode != 200) { ConnectState = "Error"; return QJsonValue::Null; } if(reply->error() == QNetworkReply::NoError) { QByteArray replyArray = reply->readAll(); QJsonDocument loadDoc(QJsonDocument::fromJson(replyArray)); QJsonObject QObj = loadDoc.object(); if(QSysInfo::productType() != "raspbian") { LibLog::LogRec(QString("%1___%2___%3").arg(QString(replyArray)).arg(__FILE__).arg(__LINE__), "connect"); LibLog::LogRec("***************************************", "connect"); } QList SearchLink ; SearchLink << Find_List_Name; return SearchJsonValue(SearchLink , QObj); } else { return QJsonValue::Null; } } QList OctoNetwork::SearchJsonValue(QList> Find_List_Names ,QNetworkReply *reply) { int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); if(QSysInfo::productType() != "raspbian"){ LibLog::LogRec(QString("statusCode : %1___%2___%3").arg(statusCode).arg(__FILE__).arg(__LINE__), "connect"); } if(statusCode != 200) { ConnectState = "Error"; return {}; } if(reply->error() == QNetworkReply::NoError) { QByteArray replyArray = reply->readAll(); QJsonDocument loadDoc(QJsonDocument::fromJson(replyArray)); QJsonObject QObj = loadDoc.object(); if(QSysInfo::productType() != "raspbian") { LibLog::LogRec(QString("%1___%2___%3").arg(QString(replyArray)).arg(__FILE__).arg(__LINE__), "connect"); LibLog::LogRec("***************************************", "connect"); } QList> SearchLink ; SearchLink << Find_List_Names; return SearchJsonValue(SearchLink , QObj); } else { return {}; } } //Find_List_Name : Retrieved List Sequence --> [Grandma,Mother,Me] //_QObj:Retrieved Retrieved Json Objecet QJsonValue OctoNetwork::SearchJsonValue(QList Find_List_Name , QJsonObject _QObj) { QJsonValue returnValue; QList SearchLink ; SearchLink << Find_List_Name; if(SearchLink.count() > 1) { QString MotherKey = SearchLink[0]; SearchLink.removeFirst(); if(MotherKey.indexOf("*") >= 0)//wildcard { QJsonArray ArrayValue; for(int i = 0 ; i <= 9 ; i++) { QString TempMotherKey = MotherKey; if(_QObj.find(TempMotherKey.replace("*",QString::number(i))).value().isUndefined())continue; // if(QSysInfo::productType() != "raspbian"){qDebug()<<_QObj.find(TempMotherKey.replace("*",QString::number(i))).value().isUndefined();}; QJsonValue data = SearchJsonValue(SearchLink , _QObj.constFind(TempMotherKey.replace("*",QString::number(i))).value().toObject()); ArrayValue.append(data); } returnValue = ArrayValue; } else returnValue = SearchJsonValue(SearchLink , _QObj.constFind(MotherKey).value().toObject()); } else { if(SearchLink[0].indexOf("*") >= 0)//wildcard { } else returnValue = _QObj.constFind(SearchLink[0]).value(); } return returnValue; } QList OctoNetwork::SearchJsonValue(QList> Find_List_Names , QJsonObject _QObj) { QList _returnValue ; foreach(QList item , Find_List_Names) { _returnValue.append(SearchJsonValue(item,_QObj)); } return _returnValue; } void OctoNetwork::SendGCode(QList _GCode_) { if(_GCode_.count() > 0 && (ConnectState.contains("Printing") || ConnectState == "Operational")) { QJsonObject TemperatureJsonObj; QJsonArray _Commands; foreach(QString item,_GCode_)//遍历_GCode_,把所有指令加入指令合集 { _Commands.append(item); } TemperatureJsonObj.insert("commands",_Commands); QJsonDocument _SenderJson; _SenderJson.setObject(TemperatureJsonObj); //网络访问管理器将Json格式的指令集发送给SetCMDRequest MCPnetworkAccessManager->post(SetCMDRequest,_SenderJson.toJson()); } } void OctoNetwork::SendGCode(QString _GCode_) { if(_GCode_.length() > 0 && (ConnectState == "Operational" || ConnectState.contains("Printing"))) { QJsonObject TemperatureJsonObj; QJsonArray _Commands; _Commands.append(_GCode_); TemperatureJsonObj.insert("commands",_Commands); QJsonDocument _SenderJson; _SenderJson.setObject(TemperatureJsonObj); MCPnetworkAccessManager->post(SetCMDRequest,_SenderJson.toJson()); } } void OctoNetwork::SD_ReLoad() { if(!ConnectState.contains("Printing") && ConnectState != "Pausing") { SD_CMD("release"); SD_CMD("init"); } SD_CMD("refresh"); } void OctoNetwork::SD_CMD(QString CMD) { if(ConnectState == "Operational") { QJsonObject TemperatureJsonObj; TemperatureJsonObj.insert("command",CMD); QJsonDocument _SenderJson; _SenderJson.setObject(TemperatureJsonObj); if(QSysInfo::productType() != "raspbian") { LibLog::LogRec(QString("%1___%2___%3").arg(QString(_SenderJson.toJson())).arg(__FILE__).arg(__LINE__), "connect"); } FSnetworkAccessManager->post(SDRequest,_SenderJson.toJson()); } } //Start Or Stop void OctoNetwork::JobSwitch(QString FilePath) { if(ConnectState == "Operational") { QStringList btnName = {"Yes", "No"} ; CustomDialog *newDialog = new CustomDialog(); QObject::connect(newDialog, &CustomDialog::OutputEvent, newDialog,[=](QString instruct) { if(instruct == "Yes") { JobSwitch(QUrl(MainUrl + "files/" +FilePath)); } }); newDialog->showCustomDialog("Warning",":/assets/info.svg",btnName,"Do you want to Start Print ?",FUI); } else if(ConnectState.contains("Printing") || ConnectState == "Pausing") { JobSwitch();//Stop } } void OctoNetwork::JobSwitch(QUrl FileUrl) { _FileUrl = FileUrl; if(ConnectState == "Operational") { QString FileName = FileDialog::Hex2QString(FileUrl.url(),false); QStringList btnName = {"Yes", "No"} ; CustomDialog *newDialog = new CustomDialog(); QObject::connect(newDialog, &CustomDialog::OutputEvent, newDialog,[=](QString instruct) { if(instruct == "Yes") { _FileUrl = ((MainWindow*)FUI)->filedialog->GetRealURL(FileUrl); //Auto Level // QList _GCode_; // _GCode_.append("G91"); // _GCode_.append("G28"); // _GCode_.append("G29"); // _GCode_.append("G28"); // _GCode_.append("G90"); // SendGCode(_GCode_); QJsonObject TemperatureJsonObj; TemperatureJsonObj.insert("command","select"); TemperatureJsonObj.insert("print",true); QNetworkRequest _Request; _Request.setUrl(FileUrl); _Request.setRawHeader("X_Api_Key",X_API_Key); _Request.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/json")); QJsonDocument _SenderJson; _SenderJson.setObject(TemperatureJsonObj); MCPnetworkAccessManager->post(_Request,_SenderJson.toJson()); } }); newDialog->showCustomDialog("Warning",":/assets/info.svg",btnName,"Do you want to Start Print "+FileName+"?",FUI); } else if(ConnectState.contains("Printing") || ConnectState == "Pausing") { JobSwitch();//Stop } } //Only Stop void OctoNetwork::JobSwitch() { //up z-axis 5cm if(ConnectState.contains("Printing") || ConnectState == "Pausing") { QStringList btnName = {"Yes", "No"} ; CustomDialog *newDialog = new CustomDialog(); QObject::connect(newDialog, &CustomDialog::OutputEvent, newDialog,[=](QString instruct) { if(instruct == "Yes") { QJsonObject TemperatureJsonObj; TemperatureJsonObj.insert("command","cancel"); QNetworkRequest _Request; _Request.setUrl(QUrl(MainUrl + "job")); _Request.setRawHeader("X_Api_Key",X_API_Key); _Request.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/json")); QJsonDocument _SenderJson; _SenderJson.setObject(TemperatureJsonObj); MCPnetworkAccessManager->post(_Request,_SenderJson.toJson()); } }); newDialog->showCustomDialog("Information",":/assets/info.svg",btnName,"Do you want to Stop Print ?",FUI); } } ================================================ FILE: octonetwork.h ================================================ #ifndef OCTONETWORK_H #define OCTONETWORK_H #include #include #include extern QByteArray Global_X_API_Key ;//Test Key extern int DebugFlat ; //extern QSize SizePercent; class OctoNetwork { public: OctoNetwork(QWidget *parent = nullptr); // void Initialize(QByteArray New_X_API_Key = ""); QJsonValue SearchJsonValue(QList Find_List_Name , QJsonObject _QObj); QJsonValue SearchJsonValue(QList Find_List_Name ,QNetworkReply *reply); QList SearchJsonValue(QList> Find_List_Names , QJsonObject _QObj); QList SearchJsonValue(QList> Find_List_Names ,QNetworkReply *reply); void SendGCode(QList _GCode_); void SendGCode(QString _GCode_); void JobSwitch(QString FilePath); void JobSwitch(QUrl FileUrl); void JobSwitch(); void SD_ReLoad(); private: virtual void SD_CMD(QString CMD); QWidget *FUI; QUrl _FileUrl; public: QByteArray X_API_Key = Global_X_API_Key;//Test Key QString MainIP = "127.0.0.1"; // QString MainIP = "192.168.100.94"; QString MainAddress = "http://"+MainIP+"/"; QString MainUrl = MainAddress + "api/"; QString ConnectState = "Close"; bool ConnectFlat = false; QNetworkAccessManager *networkAccessManager = new QNetworkAccessManager(); QNetworkAccessManager *MCPnetworkAccessManager = new QNetworkAccessManager(); QNetworkAccessManager *FSnetworkAccessManager = new QNetworkAccessManager(); QNetworkRequest GetConnectRequest; QNetworkRequest GetStateRequest; QNetworkRequest SetConnectRequest; const QList> ConnectLink = {{"current","state"},{"options","ports"}}; const QList ConnectSerialLink = {"/dev/ttyAMA0","/dev/ttyS0"}; const QList> StateLink = {{"state"},{"progress","completion"}};//using with printer in the Printing state QNetworkRequest SetCMDRequest; QNetworkRequest SDRequest; QNetworkRequest FileRequest; QNetworkRequest GetTemperatureRequest; const QList> TemperatureLink = {{"temperature","bed","actual"},{"temperature","tool*","actual"}}; private: }; #endif // OCTONETWORK_H ================================================ FILE: start.sh ================================================ sleep 2 cd /home/pi/OctoBTT && ./OctoBTT -platform eglfs ================================================ FILE: startup.sh ================================================ su -l pi << EOF cd wget --no-check-certificate https://raw.githubusercontent.com/bigtreetech/OctoBTT/master/install.sh sudo sed -i '/exit 0/ i sudo \/bin\/sh \/home\/pi\/install.sh' /etc/rc.local sudo reboot EOF ================================================ FILE: terminaldialog.cpp ================================================ #include "terminaldialog.h" #include "ui_terminaldialog.h" #include #include #include //#include #include #include #include #include #include #include "inputdialog.h" #include TerminalDialog::TerminalDialog(QWidget *parent) : QDialog(parent), ui(new Ui::TerminalDialog) { ui->setupUi(this); FUI = (MainWindow*)parent;//((MainWindow*)FUI)->octonetwork.SendGCode(_GCode_Setting); cmd = new QProcess(this); /* 将QProcess的输出错误打印到界面 */ connect(cmd,&QProcess::readyReadStandardError,this,[=](){ if(!SendCMD_argu.contains("-e")) ui->Receiver->append("->Receive->->-> Standard Error"); QString outStr = QString::fromLocal8Bit(cmd->readAllStandardError()); if(!SendCMD_argu.contains("-e")) ui->Receiver->append("<Receiver->append(outStr.trimmed()); if(!SendCMD_argu.contains("-e")) ui->Receiver->horizontalScrollBar()->setValue(ui->Receiver->horizontalScrollBar()->maximum()); // QStringList _output; // _output<<"&&StandardError"<Receiver->append("->Receive->->-> Standard Output"); QString outStr = QString::fromLocal8Bit(cmd->readAllStandardOutput()); if(!SendCMD_argu.contains("-q")) ui->Receiver->append("<Receiver->append(outStr.trimmed()); // ui->Receiver->horizontalScrollBar()->setValue(ui->Receiver->horizontalScrollBar()->maximum()); // cmd->disconnect(SIGNAL(readyReadStandardOutput())); QStringList _output; foreach(QString item,outStr.trimmed().split("\n",QString::SkipEmptyParts)) { if(item.trimmed() != "") { QString Data = item.trimmed(); while (Data.indexOf("\\x")>=0)//字符处理 { int index = Data.indexOf("\\x"); QString Block = Data.mid(index,12); Block = Block.replace("\\x", QString()); QString Blocks ; Blocks.append(Block.mid(0,2).toUShort(0,16)); Blocks.append(Block.mid(2,2).toUShort(0,16)); Blocks.append(Block.mid(4,2).toUShort(0,16)); // QTextCodec *codec = QTextCodec::codecForName("UTF-8"); // QString desStr = codec->fromUnicode(Blocks); Data = Data.replace(index, 12, tr(Blocks.toLatin1().data())); // Data = unicodeToUtf8(Data); } // while (Data.indexOf("\\u")>=0) // { // int index = Data.indexOf("\\u"); // QString Block = Data.mid(index,6); // Block = Block.replace("\\u", QString()); // int nHex = Block.toInt(0, 16); // Data.replace(index, 6, QChar(nHex)); // } _output.append(Data);//创建序列 if(!SendCMD_argu.contains("-q")) ui->Receiver->append(Data); if(!SendCMD_argu.contains("-q")) ui->Receiver->horizontalScrollBar()->setValue(ui->Receiver->horizontalScrollBar()->maximum()); } } emit CMD_Reply(_output);//抛出槽触发 // CMD_Reply *CMD_reply = new CMD_Reply(_output); // QCoreApplication::postEvent(this, CMD_reply);//抛出事件 }); /* 将QProcess的 "启动/写入/结束" 打印到界面 */ connect(cmd,&QProcess::started,this,[=](){ ui->Receiver->append("->Started->->->"); ui->Receiver->horizontalScrollBar()->setValue(ui->Receiver->horizontalScrollBar()->maximum()); }); connect(cmd, QOverload::of(&QProcess::finished),[=](int exitCode, QProcess::ExitStatus exitStatus){ Q_UNUSED(exitCode); Q_UNUSED(exitStatus); if(!CloseDialog) { ui->Receiver->append("->Finished->->->"); ui->Receiver->horizontalScrollBar()->setValue(ui->Receiver->horizontalScrollBar()->maximum()); cmd->start("/bin/bash"); } }); // cmd->setReadChannelMode(QProcess::ForwardedChannels); cmd->start("/bin/bash"); ui->Sender->setFocus(); // SendCMD("export DISPLAY=\":0.0\""); this->resize((int)(SizePercent.width()*800),(int)(SizePercent.height()*480)); this->setMaximumSize((int)(SizePercent.width()*800),(int)(SizePercent.height()*480)); this->setFixedSize((int)(SizePercent.width()*800),(int)(SizePercent.height()*480)); } //QString TerminalDialog::unicodeToUtf8(const QString resStr) //{ // QString temp; // for(int i=0;ifromUnicode(temp); // return tr(desStr.toLatin1().data()); //} TerminalDialog::~TerminalDialog() { delete ui; CloseDialog = true; if (cmd->state() == QProcess::Running) { cmd->terminate(); cmd->close(); cmd->waitForFinished(); } } void TerminalDialog::showEvent(QShowEvent *event) { Q_UNUSED(event); if(FirstLoad) { FirstLoad = !FirstLoad; } } void TerminalDialog::on_Btn_Back_clicked() { this->close(); } void TerminalDialog::on_Btn_Send_clicked() { if(ui->Sender->text().isEmpty()) { // ui->Sender->setFocus(); return; } ui->Sender->setText(ui->Sender->text().trimmed()); SendCMD(ui->Sender->text()); // ui->Sender->setFocus(); } void TerminalDialog::on_pushButton_clicked() { ui->Receiver->clear(); } void TerminalDialog::Show_debug(QString msg) { ui->Receiver->append("->System MSG->->->" + msg); } void TerminalDialog::SendCMD(QString CommandLine , QString argu) { SendCMD_argu = argu; command = CommandLine.trimmed(); if(command.isEmpty() || command == "") { return; } if(!cmd->isOpen()) { cmd->open(); } if(command.toLower() == "exit app" || command.toLower() == "exitapp") qApp->exit(Base_OnlyExitApp); // else if(command.toLower().startsWith("qdebug ")) // { // qDebug() << command.remove(0,6); // } else if(cmd->isOpen() && cmd->waitForStarted()) { if(!SendCMD_argu.contains("-q")) ui->Receiver->append(">>Sender:"); if(!SendCMD_argu.contains("-q")) ui->Receiver->append(command); if(command.contains("sudo ")) { int startlocal = command.indexOf("sudo "); command = command.replace(startlocal,5,"echo \"" + CMD_Password + "\" | sudo -S ");//片段阔幅代码未处理 } cmd->write(command.toLocal8Bit()+ "\n"); if(!SendCMD_argu.contains("-q")) ui->Receiver->horizontalScrollBar()->setValue(ui->Receiver->horizontalScrollBar()->maximum()); } else if(!cmd->isOpen()) { ui->Receiver->append("->System Busy->->->"); } } //QEvent::Type CMD_Reply::m_EventType = QEvent::None; //CMD_Reply::CMD_Reply(QStringList _value) : QEvent(eventType()) //{ // m_StringList = _value; //} //CMD_Reply::~CMD_Reply() //{ //} //QEvent::Type CMD_Reply::eventType() //{ // // 创建事件Type // if (m_EventType == QEvent::None) // m_EventType = (QEvent::Type)QEvent::registerEventType(); // return m_EventType; //} //QStringList CMD_Reply::getValue(void) //{ // return m_StringList; //} void TerminalDialog::on_Btn_Logo_clicked() { QStringList btnName = {"Yes", "No"} ; CustomDialog *newDialog = new CustomDialog(); QObject::connect(newDialog, &CustomDialog::OutputEvent, newDialog,[=](QString instruct) { if(instruct == "Yes") { InputDialog *inputdialog = new InputDialog(this); connect(inputdialog,&InputDialog::closedialog,this,[=](QString value,bool SettingMark){ if(SettingMark) { CMD_Password = value; } delete sender(); }); inputdialog->setvalue("Please Input Password","",CMD_Password); } }); newDialog->showCustomDialog("Warning",":/assets/terminal-box-line.svg",btnName,"Do you want to change the incoming password from the console ?",this); } void TerminalDialog::on_Btn_Kill_clicked() { cmd->terminate(); } ================================================ FILE: terminaldialog.h ================================================ #ifndef TERMINALDIALOG_H #define TERMINALDIALOG_H #include #include #include #include //#include extern int DebugFlat ; extern QSizeF SizePercent; namespace Ui { class TerminalDialog; } class TerminalDialog : public QDialog { Q_OBJECT signals: void CMD_Reply(QStringList &value); public: explicit TerminalDialog(QWidget *parent = nullptr); ~TerminalDialog(); void SendCMD(QString CommandLine, QString argu = QString()); void Show_debug(QString msg); private slots: virtual void on_Btn_Back_clicked(); virtual void on_Btn_Send_clicked(); virtual void on_pushButton_clicked(); virtual void on_Btn_Logo_clicked(); void on_Btn_Kill_clicked(); private: Ui::TerminalDialog *ui; QProcess *cmd; // bool CMD_NoPassword = false; QString command; QWidget *FUI; bool FirstLoad = true; QString SendCMD_argu; bool CloseDialog = false; // QString unicodeToUtf8(const QString resStr); public: QString CMD_Password = "raspberry"; protected: void showEvent(QShowEvent *event); }; //class CMD_Reply : public QEvent //{ //public: // CMD_Reply(QStringList _value); // ~CMD_Reply(); // static Type eventType(); // QStringList getValue(void); //private: // static Type m_EventType; // QStringList m_StringList; //}; #endif // TERMINALDIALOG_H ================================================ FILE: terminaldialog.ui ================================================ TerminalDialog 0 0 800 480 0 0 Terminal :/assets/terminal-box-line.svg:/assets/terminal-box-line.svg 5 5 5 5 20 BTStyleSheet7 Clean Window 15 true background-color: rgb(0, 0, 0); color: rgb(0, 255, 0); false true 5 5 5 5 BTStyleSheet2 :/assets/huitui.svg:/assets/huitui.svg 72 72 Qt::Horizontal 40 20 BTStyleSheet2 border:none; font: 75 30pt "Gill Sans MT"; :/assets/terminal.svg:/assets/terminal.svg 72 72 Qt::Horizontal 40 20 84 78 0 0 150 50 15 75 true BTStyleSheet7 false Kill CMD true 0 0 150 50 15 75 true BTStyleSheet7 false Send CMD true 0 0 25 Qt::ClickFocus false false background-color: rgb(0, 0, 0); color: rgb(0, 255, 0); iwlist wlan0 scan | grep -E "ESSID|Quality" MyLineEdit QLineEdit
mylineedit.h
================================================ FILE: update.sh ================================================ sleep 2 su -l pi << EOF echo "Update Dependencies ..." sudo apt install qt5-default qtcreator python3-pyqt5-dbg libqt5svg5 libqt5svg5-dev python3-pyqt5.qtsvg qtsvg5-doc libqt5websockets5 libqt5websockets5-dev ttf-wqy-zenhei qml-module-qtquick-controls2 libboost1.58-all-dev libudev-dev libinput-dev libts-dev libmtdev-dev libjpeg-dev libfontconfig1-dev libssl-dev libdbus-1-dev libglib2.0-dev libxkbcommon-dev libgbm-dev libgl1-mesa-dri qtdeclarative5-dev libqt5svg5 libqt5websockets5 ttf-wqy-zenhei -y echo "Check GLdriver ..." for package in gldriver-test libgl1-mesa-dri; do if [ "$(dpkg -l "$package" 2> /dev/null | tail -n 1 | cut -d ' ' -f 1)" != "ii" ]; then missing_packages="$package $missing_packages" fi done apt-get install $missing_packages -y echo "Done." echo "Set render ..." sudo gpasswd -a pi render echo "Done." cd ~ rm -rf OctoBTTUpdate echo "Update OctoBTT Source ..." git clone https://github.com/bigtreetech/OctoBTT.git OctoBTTUpdate #git clone https://gitee.com/Shine6Z/OctoBTT.git OctoBTTUpdate mv -f OctoBTTUpdate/* OctoBTT #cp -rf OctoBTTUpdate OctoBTT rm -rf OctoBTTUpdate echo "Done." echo "Rebuild OctoBTT Source ..." cd ~/OctoBTT #mkdir projectfile #make clean #cp OctoBTT.pro projectfile/OctoBTT.pro qmake OctoBTT.pro #cp projectfile/OctoBTT.pro OctoBTT.pro #rm -r -f projectfile if [ ! -f "$OctoBTT" ]; then rm -rf OctoBTT make clean fi make -j$(cat /proc/cpuinfo | grep processor | wc -l) make clean echo "Done." EOF echo "Run OctoBTT ..." sleep 2 cd /home/pi/OctoBTT && ./OctoBTT -platform eglfs ================================================ FILE: upgrade.sh ================================================ sleep 2 su -l pi << EOF echo "Update Dependencies ..." sudo apt install qt5-default qtcreator python3-pyqt5-dbg libqt5svg5 libqt5svg5-dev python3-pyqt5.qtsvg qtsvg5-doc libqt5websockets5 libqt5websockets5-dev ttf-wqy-zenhei qml-module-qtquick-controls2 libboost1.58-all-dev libudev-dev libinput-dev libts-dev libmtdev-dev libjpeg-dev libfontconfig1-dev libssl-dev libdbus-1-dev libglib2.0-dev libxkbcommon-dev libgbm-dev libgl1-mesa-dri qtdeclarative5-dev libqt5svg5 libqt5websockets5 ttf-wqy-zenhei -y echo "Check GLdriver ..." for package in gldriver-test libgl1-mesa-dri; do if [ "$(dpkg -l "$package" 2> /dev/null | tail -n 1 | cut -d ' ' -f 1)" != "ii" ]; then missing_packages="$package $missing_packages" fi done apt-get install $missing_packages -y echo "Done." echo "Set render ..." sudo gpasswd -a pi render echo "Done." cd ~ rm -rf OctoBTTUpdate echo "Update OctoBTT Source ..." git clone https://github.com/bigtreetech/OctoBTT.git OctoBTTUpdate #git clone https://gitee.com/Shine6Z/OctoBTT.git OctoBTTUpdate mv -f OctoBTTUpdate/* OctoBTT #cp -rf OctoBTTUpdate OctoBTT rm -rf OctoBTTUpdate echo "Done." echo "Rebuild OctoBTT Source ..." cd ~/OctoBTT #mkdir projectfile #make clean #cp OctoBTT.pro projectfile/OctoBTT.pro qmake OctoBTT.pro #cp projectfile/OctoBTT.pro OctoBTT.pro #rm -r -f projectfile if [ ! -f "$OctoBTT" ]; then rm -rf OctoBTT make clean fi make -j$(cat /proc/cpuinfo | grep processor | wc -l) make clean echo "Done." EOF sudo reboot ================================================ FILE: wlanconfig.cpp ================================================ #include "wlanconfig.h" #include "ui_wlanconfig.h" #include //#include #include #include "inputdialog.h" #include #include #include Wlanconfig::Wlanconfig(QWidget *parent) : QDialog(parent), ui(new Ui::Wlanconfig) { ui->setupUi(this); FUI = (MainWindow*)parent;//((MainWindow*)FUI)->octonetwork.SendGCode(_GCode_Setting); QFont font; font.setPointSize((int)(ui->DevList->font().pointSize()*(SizePercent.width() < SizePercent.height() ? SizePercent.width():SizePercent.height()))); ui->DevList->setFont(font); font.setPointSize((int)(ui->WPA_List->font().pointSize()*(SizePercent.width() < SizePercent.height() ? SizePercent.width():SizePercent.height()))); ui->WPA_List->setFont(font); ui->WPA_List->setIconSize(QSize(SizePercent.width()*64,SizePercent.height()*64)); this->resize((int)(SizePercent.width()*800),(int)(SizePercent.height()*480)); this->setMaximumSize((int)(SizePercent.width()*800),(int)(SizePercent.height()*480)); this->setFixedSize((int)(SizePercent.width()*800),(int)(SizePercent.height()*480)); // WPA_Switch = new QMap; // WPA_SSID = new QMap; // ui->DevList->addItem("baby"); // ui->DevList->addItem("Goodgay"); // ui->DevList->addItem("HappyGirl"); // ui->DevList->addItem("baby1"); // ui->DevList->addItem("Goodgay1"); // ui->DevList->addItem("HappyGirl1"); // ui->DevList->addItem("baby2"); // ui->DevList->addItem("Goodgay2"); // ui->DevList->addItem("HappyGirl2"); // ui->DevList->setCurrentIndex(0); // QStyle *DL = ui->DevList->style(); // ui->Btn_Help->setText(DL->property("on").toString()); // DL->setProperty("on",50); // ui->DevList->setStyle(DL); } Wlanconfig::~Wlanconfig() { delete ui; } void Wlanconfig::on_Btn_Back_clicked() { this->close(); } //Load Scan Funtion //Load List index void Wlanconfig::showEvent(QShowEvent *event) { Q_UNUSED(event); GetDevState(); } void Wlanconfig::on_Btn_DevRefresh_clicked() { GetDevState(); } void Wlanconfig::on_Btn_DevSwitch_clicked() { if(!WPA_Switch.contains(ui->DevList->currentText())) return; ((MainWindow*)FUI)->terminaldialog->SendCMD("ifconfig " + ui->DevList->currentText() + (WPA_Switch[ui->DevList->currentText()] ? " down" : " up"),TeminalState); WPA_Switch[ui->DevList->currentText()] = !WPA_Switch[ui->DevList->currentText()]; ui->Btn_DevSwitch->setIcon(QIcon(WPA_Switch[ui->DevList->currentText()] ? ":/assets/Network.svg":":/assets/shebeiweilianjie-copy.svg")); ui->Btn_Connect->setEnabled(WPA_Switch[ui->DevList->currentText()]); ui->Btn_Scan->setEnabled(WPA_Switch[ui->DevList->currentText()]); ui->WPA_List->setEnabled(WPA_Switch[ui->DevList->currentText()]); } void Wlanconfig::on_Btn_Connect_clicked() { if(ui->WPA_List->model() == NULL || ui->WPA_List->model()->rowCount()==0) return; if(!WPA_Switch.contains(ui->DevList->currentText())) return; if(!WPA_Switch[ui->DevList->currentText()]) return; QString Current_SSID = ui->WPA_List->model()->data(ui->WPA_List->currentIndex()).toString(); if(Current_SSID.trimmed() == "")//未选择SSID return; if(WPA_Scan_SSID_List[Current_SSID].connectflags)//已连接 return; ui->WPA_List->setEnabled(false); if(WPA_Scan_SSID_List[Current_SSID].pwdError)//连接无效,重新输入密码 //pwdError为true本身具有前提是属于已有网络ID的 { SetPassword(); return; } if(WPA_Scan_SSID_List[Current_SSID].id >= 0)//可执行连接 { ConnectNetwork(); return; } CreateNetwork(); } //双击面板输入密码连接或创建连接点 void Wlanconfig::on_WPA_List_doubleClicked(const QModelIndex &index) { if(WPA_Scan_SSID_List[index.data().toString()].id >= 0)//可执行连接 { SetPassword(); return; } CreateNetwork(); } void Wlanconfig::on_Btn_Scan_clicked() { if(!WPA_Switch.contains(ui->DevList->currentText())) return; if(!WPA_Switch[ui->DevList->currentText()]) return; ScanWPAList(); } //点击help查看网络信息 void Wlanconfig::on_Btn_Help_clicked() { GetNetworkInfo(); } void Wlanconfig::GetNetworkInfo() { QString cmd = "ifconfig | grep -E \"flags|inet|ether\""; disconnect(((MainWindow*)FUI)->terminaldialog,&TerminalDialog::CMD_Reply,0,0); QObject::connect(((MainWindow*)FUI)->terminaldialog,&TerminalDialog::CMD_Reply,this,[=](QStringList CommandLine) { disconnect(((MainWindow*)FUI)->terminaldialog,&TerminalDialog::CMD_Reply,0,0); GetNetworkInfo(CommandLine); }); ((MainWindow*)FUI)->terminaldialog->SendCMD(cmd,TeminalState); } void Wlanconfig::GetNetworkInfo(QStringList &Responses) { //=======================================================================12.23 // QStringList data; QStringList sending; foreach(QString item ,Responses) { QString replaceitem = item.replace("\t"," "); // sending.append(replaceitem); QStringList explore = replaceitem.split(" ",QString::SkipEmptyParts); if(explore[0].contains(QRegExp("(eth[0-9]+[0-9]*)|(lo)|(wlan[0-9]+[0-9]*)"))) { sending.append(explore[0]); } else if(explore[0].contains("inet6"))//IPv6 { sending.append(QString("IPv6:%1").arg(explore[1])); } else if(explore[0].contains("inet"))//IP { sending.append(QString("IPv4:%1").arg(explore[1])); sending.append(QString("IPv4 Netmask:%1").arg(explore[3])); } else if(explore[0].contains("ether"))//MAC { sending.append(QString("MAC:%1").arg(explore[1])); } // bool read = false; // data.append(replaceitem).split(" ",QString::SkipEmptyParts)); } //创建QDialog QDialog dialog(this); //设置倒角?和透明度 dialog.setWindowOpacity(0.9); dialog.setStyleSheet("background-color: rgba(128, 128, 128, 25%)"); //设置窗口的标题和标识 dialog.setWindowTitle(tr("Wlan Information")); dialog.setWindowIcon(QIcon(":/assets/WiFi2.svg")); //适应屏幕大小 dialog.resize(SizePercent.width()*800*0.9,SizePercent.height()*480*0.9); dialog.setFixedSize(SizePercent.width()*800*0.9,SizePercent.height()*480*0.8); //使弹窗居中显示 dialog.move(this->pos().x() + (this->width() - dialog.width()) / 2,this->pos().y() + (this->height() - dialog.height()) / 2); //设置文本显示 QTextBrowser textBrowser(&dialog); textBrowser.setStyleSheet("border: none; color: rgb(245, 246, 255);"); textBrowser.setText(sending.join("\n")); textBrowser.setFixedSize(SizePercent.width()*800*0.877,SizePercent.height()*480*0.5); textBrowser.setGeometry(50,50,SizePercent.width()*800*0.8,SizePercent.height()*480*0.5); //设置按键ok QPushButton OKBT("OK",&dialog); OKBT.setWhatsThis("BTStyleSheet"); //按键连接信号 QObject::connect(&OKBT, &QPushButton::clicked, &dialog, &QDialog::reject); //字体适应屏幕大小 QFont _font = OKBT.font(); _font.setPointSize(this->maximumWidth() > this->maximumHeight() ? (int)this->maximumHeight()/30 : (int)this->maximumWidth()/30); OKBT.setFont(_font); textBrowser.setFont(_font); //调整文本和按键的位置 QVBoxLayout VLayout(&dialog); VLayout.addWidget(&textBrowser); VLayout.addWidget(&OKBT); int ret = dialog.exec(); if(ret == QDialog::Rejected) { dialog.close(); } } void Wlanconfig::CreateNetwork() { QString cmd = QString("wpa_cli -i %1 add_network").arg(ui->DevList->currentText()); disconnect(((MainWindow*)FUI)->terminaldialog,&TerminalDialog::CMD_Reply,0,0); QObject::connect(((MainWindow*)FUI)->terminaldialog,&TerminalDialog::CMD_Reply,this,[=](QStringList CommandLine) { disconnect(((MainWindow*)FUI)->terminaldialog,&TerminalDialog::CMD_Reply,0,0); QString Current_SSID = ui->WPA_List->model()->data(ui->WPA_List->currentIndex()).toString(); bool chkID=false; int id = CommandLine[0].toInt(&chkID); if(chkID) { WPA_Scan_SSID_List[Current_SSID].id = id; SetSSID(); } else ui->WPA_List->setEnabled(true); }); ((MainWindow*)FUI)->terminaldialog->SendCMD(cmd,TeminalState); } void Wlanconfig::SetSSID() { QString Current_SSID = ui->WPA_List->model()->data(ui->WPA_List->currentIndex()).toString(); QString cmd = QString("wpa_cli -i %1 set_network %2 ssid '\"%3\"'").arg(ui->DevList->currentText()).arg(QString::number(WPA_Scan_SSID_List[Current_SSID].id)).arg(Current_SSID); disconnect(((MainWindow*)FUI)->terminaldialog,&TerminalDialog::CMD_Reply,0,0); QObject::connect(((MainWindow*)FUI)->terminaldialog,&TerminalDialog::CMD_Reply,this,[=](QStringList CommandLine) { disconnect(((MainWindow*)FUI)->terminaldialog,&TerminalDialog::CMD_Reply,0,0); SetSSID(CommandLine); }); ((MainWindow*)FUI)->terminaldialog->SendCMD(cmd,TeminalState); } void Wlanconfig::SetSSID(QStringList &Responses) { if(Responses[0].toLower().trimmed() == "ok") { //设置密码 SetPassword(); } else { RemoveNetwork(); } } void Wlanconfig::SetPassword() { QString Current_SSID = ui->WPA_List->model()->data(ui->WPA_List->currentIndex()).toString(); QString Dev = ui->DevList->currentText(); InputDialog *inputdialog = new InputDialog(this); connect(inputdialog,&InputDialog::closedialog,this,[=](QString value,bool SettingMark){ if(SettingMark) { // SetPassword(ui->DevList->currentText() , value , WPA_Scan_SSID_List[Current_SSID].id); QString Current_SSID = ui->WPA_List->model()->data(ui->WPA_List->currentIndex()).toString(); QString Dev = ui->DevList->currentText(); QString cmd = QString("wpa_cli -i %1 set_network %3 psk '\"%2\"'").arg(Dev).arg(value).arg(QString::number(WPA_Scan_SSID_List[Current_SSID].id)); disconnect(((MainWindow*)FUI)->terminaldialog,&TerminalDialog::CMD_Reply,0,0); QObject::connect(((MainWindow*)FUI)->terminaldialog,&TerminalDialog::CMD_Reply,this,[=](QStringList CommandLine) { disconnect(((MainWindow*)FUI)->terminaldialog,&TerminalDialog::CMD_Reply,0,0); SetPassword(CommandLine); }); ((MainWindow*)FUI)->terminaldialog->SendCMD(cmd,TeminalState); } else { if(value.trimmed() == "") { QStringList btnName = {"Yes", "No"} ; CustomDialog *newDialog = new CustomDialog(); QObject::connect(newDialog, &CustomDialog::OutputEvent, newDialog,[=](QString instruct) { if(instruct == "Yes") { RemoveNetwork(); } else if(instruct == "No") { ui->WPA_List->setEnabled(true); } }); newDialog->showCustomDialog("Warning",":/assets/info.svg",btnName,QString("Do you want to forget \"%1\" ?").arg(ui->WPA_List->model()->data(ui->WPA_List->currentIndex()).toString()),this); } else ui->WPA_List->setEnabled(true); } delete sender(); }); inputdialog->setvalue("Please Input "+ Current_SSID +" Password",""); } void Wlanconfig::SetPassword(QStringList &Responses) { if(Responses[0].toLower().trimmed() == "ok") { QString Current_SSID = ui->WPA_List->model()->data(ui->WPA_List->currentIndex()).toString(); //设置图标 // if(WPA_Scan_SSID_List[((QStandardItemModel)ui->WPA_List->model()).item(0)->text()].connectflags) // ((QStandardItemModel)ui->WPA_List->model()).item(0)->setIcon(QIcon(":/assets/Wifi_Unlock.svg")); //执行启用并连接 ConnectNetwork(); } else { ui->WPA_List->setEnabled(true); } } void Wlanconfig::RemoveNetwork() { QString Current_SSID = ui->WPA_List->model()->data(ui->WPA_List->currentIndex()).toString(); QString Dev = ui->DevList->currentText(); QString cmd = QString("wpa_cli -i %1 remove_network %2").arg(Dev).arg(QString::number(WPA_Scan_SSID_List[Current_SSID].id)); disconnect(((MainWindow*)FUI)->terminaldialog,&TerminalDialog::CMD_Reply,0,0); QObject::connect(((MainWindow*)FUI)->terminaldialog,&TerminalDialog::CMD_Reply,this,[=](QStringList CommandLine) { disconnect(((MainWindow*)FUI)->terminaldialog,&TerminalDialog::CMD_Reply,0,0); RemoveNetwork(CommandLine); }); ((MainWindow*)FUI)->terminaldialog->SendCMD(cmd,TeminalState); } void Wlanconfig::RemoveNetwork(QStringList &Responses) { QString Current_SSID = ui->WPA_List->model()->data(ui->WPA_List->currentIndex()).toString(); if(Responses[0].toLower().trimmed() == "ok") { WPA_Scan_SSID_List[Current_SSID].id = -1; WPA_Scan_SSID_List[Current_SSID].pwdError = false; WPA_Scan_SSID_List[Current_SSID].connectflags = false; ui->WPA_List->setEnabled(true); } else { CustomDialog *newDialog = new CustomDialog(); newDialog->showCustomDialog("Warning",":/assets/WiFi2.svg",QString("SSID[%1] Delete failed !"),this); ui->WPA_List->setEnabled(true); } } void Wlanconfig::ConnectNetwork() { QString Current_SSID = ui->WPA_List->model()->data(ui->WPA_List->currentIndex()).toString(); QString Dev = ui->DevList->currentText(); QString cmd = QString("wpa_cli -i %1 enable_network %2 && wpa_cli -i %1 select_network %2 && wpa_cli -i %1 save_config").arg(Dev).arg(QString::number(WPA_Scan_SSID_List[Current_SSID].id)); disconnect(((MainWindow*)FUI)->terminaldialog,&TerminalDialog::CMD_Reply,0,0); QObject::connect(((MainWindow*)FUI)->terminaldialog,&TerminalDialog::CMD_Reply,this,[=](QStringList) { disconnect(((MainWindow*)FUI)->terminaldialog,&TerminalDialog::CMD_Reply,0,0); ui->WPA_List->setEnabled(true); }); ((MainWindow*)FUI)->terminaldialog->SendCMD(cmd,TeminalState); } void Wlanconfig::ScanWPAList() { // this->setEnabled(false); if(LastDev != ui->DevList->currentText()) { LastDev = ui->DevList->currentText(); WPAModel->clear(); if(ui->WPA_List->model() != NULL && ui->WPA_List->model()->rowCount()>0) ui->WPA_List->model()->removeRows(0,ui->WPA_List->model()->rowCount()); } disconnect(((MainWindow*)FUI)->terminaldialog,&TerminalDialog::CMD_Reply,0,0); QObject::connect(((MainWindow*)FUI)->terminaldialog,&TerminalDialog::CMD_Reply,this,[=](QStringList CommandLine) { disconnect(((MainWindow*)FUI)->terminaldialog,&TerminalDialog::CMD_Reply,0,0); ScanWPAList(CommandLine); }); ((MainWindow*)FUI)->terminaldialog->SendCMD("wpa_cli -i "+ui->DevList->currentText()+" list_network",TeminalState); } void Wlanconfig::ScanWPAList(QStringList &Responses) { bool ReadData = false; WPA_Scan_SSID_List.clear(); foreach(QString item , Responses) { if(ReadData) { int WPA_ID = item.replace("\t"," ").split(" ",QString::SkipEmptyParts)[0].toInt(); QString LastStr = item.replace("\t"," ").remove(0,QString::number(WPA_ID).length()).trimmed();//remove NID LastStr = ReverseStr(LastStr); bool WPA_Flags = false; bool WPA_PWD_Error = false; if(LastStr.startsWith("]"))//has flags { QString FlagsStr = ((ReverseStr(LastStr.split(" ",QString::SkipEmptyParts)[0]))).toUpper() ; WPA_Flags = (FlagsStr == "[CURRENT]" && WPA_SSID[ui->DevList->currentText()].trimmed() != "");//连接中状态检测[TEMP-DISABLED]//逻辑不够严谨 WPA_PWD_Error = (FlagsStr == "[TEMP-DISABLED]" || (FlagsStr == "[CURRENT]" && WPA_SSID[ui->DevList->currentText()].trimmed() == "")); LastStr = LastStr.remove(0,FlagsStr.count()).trimmed();//remove state } else WPA_Flags = false; QString SSID = ReverseStr(LastStr.remove(0,LastStr.split(" ",QString::SkipEmptyParts)[0].count()).trimmed()); WPA_Scan_SSID_List.insert(SSID,WPAInfo()); WPA_Scan_SSID_List[SSID].id = WPA_ID; // WPA_Scan_SSID_List[SSID].connectflags = SSID == WPA_SSID[ui->DevList->currentText()]; WPA_Scan_SSID_List[SSID].connectflags = WPA_Flags; WPA_Scan_SSID_List[SSID].pwdError = WPA_PWD_Error; } else if(item.toLower().startsWith("network")) { ReadData = true; } } ScanWPA(); } QString Wlanconfig::ReverseStr(QString args) { QString outputdata = ""; foreach(QChar arg , args) { outputdata = arg + outputdata; } return outputdata; } void Wlanconfig::ScanWPA() { disconnect(((MainWindow*)FUI)->terminaldialog,&TerminalDialog::CMD_Reply,0,0); QObject::connect(((MainWindow*)FUI)->terminaldialog,&TerminalDialog::CMD_Reply,this,[=](QStringList CommandLine) { disconnect(((MainWindow*)FUI)->terminaldialog,&TerminalDialog::CMD_Reply,0,0); ScanWPA(CommandLine); }); ((MainWindow*)FUI)->terminaldialog->SendCMD("wpa_cli -i "+ui->DevList->currentText()+" scan",TeminalState); } void Wlanconfig::ScanWPA(QStringList &Responses) { if(Responses[0].toLower().trimmed() == "ok") ScanWPA_Ressult(); else { // this->setEnabled(true); if(WPA_SSID[ui->DevList->currentText()].trimmed() == "") { GetDevState(); } // WPA_Switch[ui->DevList->currentText()] = false; // ui->Btn_DevSwitch->setIcon(QIcon(WPA_Switch[ui->DevList->currentText()] ? ":/assets/Network.svg":":/assets/shebeiweilianjie-copy.svg")); // ui->Btn_Connect->setEnabled(WPA_Switch[ui->DevList->currentText()]); // ui->Btn_Scan->setEnabled(WPA_Switch[ui->DevList->currentText()]); // ui->WPA_List->setEnabled(WPA_Switch[ui->DevList->currentText()]); } } void Wlanconfig::ScanWPA_Ressult() { disconnect(((MainWindow*)FUI)->terminaldialog,&TerminalDialog::CMD_Reply,0,0); QObject::connect(((MainWindow*)FUI)->terminaldialog,&TerminalDialog::CMD_Reply,this,[=](QStringList CommandLine) { disconnect(((MainWindow*)FUI)->terminaldialog,&TerminalDialog::CMD_Reply,0,0); ScanWPA_Ressult(CommandLine); }); ((MainWindow*)FUI)->terminaldialog->SendCMD("wpa_cli -i "+ui->DevList->currentText()+" scan_results",TeminalState); } void Wlanconfig::ScanWPA_Ressult(QStringList &Responses) { bool ReadData = false; QStringList effectiveSSID; foreach(QString item , Responses) { if(ReadData) { QStringList ModuleStr = item.replace("\t"," ").split(" ",QString::SkipEmptyParts); int WPA_Level = ModuleStr[2].toInt(); QString LastStr = item.replace("\t"," ").remove(0,ModuleStr[0].count()).trimmed();//remove bssid LastStr = LastStr.remove(0,ModuleStr[1].count()).trimmed();//remove freq LastStr = LastStr.remove(0,ModuleStr[2].count()).trimmed();//remove level QString SSID = LastStr.remove(0,ModuleStr[3].count()).trimmed();//remove SecurityFlags if(SSID.trimmed() == "") continue; effectiveSSID.append(SSID); if(!WPA_Scan_SSID_List.contains(SSID)) { WPA_Scan_SSID_List.insert(SSID,WPAInfo()); } WPA_Scan_SSID_List[SSID].level = WPA_Level; // WPA_Scan_SSID_List[SSID].Quality_value ;///信号强度排序 if(WPA_Scan_SSID_List[SSID].level <= -100) WPA_Scan_SSID_List[SSID].Quality_value = 0; else if(WPA_Scan_SSID_List[SSID].level >= -50) WPA_Scan_SSID_List[SSID].Quality_value = 100; else WPA_Scan_SSID_List[SSID].Quality_value = 2 * (WPA_Scan_SSID_List[SSID].level + 100); // // dBm to Quality: // if(dBm <= -100) // quality = 0; // else if(dBm >= -50) // quality = 100; // else // quality = 2 * (dBm + 100); // // Quality to dBm: // if(quality <= 0) // dBm = -100; // else if(quality >= 100) // dBm = -50; // else // dBm = (quality / 2) - 100; } else if(item.toLower().startsWith("bssid")) { ReadData = true; } } WPAModel->clear(); if(ui->WPA_List->model() != NULL && ui->WPA_List->model()->rowCount()>0) ui->WPA_List->model()->removeRows(0,ui->WPA_List->model()->rowCount()); if(WPA_Scan_SSID_List.count() > 0) { // if(WPA_Scan_SSID_List.contains(WPA_SSID[ui->DevList->currentText()])) // { // QStandardItem *wpsFirst = new QStandardItem(static_cast(WPA_SSID[ui->DevList->currentText()])); // wpsFirst->setIcon(QIcon(":/assets/Network.svg")); // WPAModel->appendRow(wpsFirst); // } QMapIterator WPAReader(WPA_Scan_SSID_List); while (WPAReader.hasNext()) { WPAReader.next(); if(!effectiveSSID.contains(WPAReader.key())) continue; // if(WPAReader.key() == WPA_SSID[ui->DevList->currentText()]) // continue; QStandardItem *wpsitem = new QStandardItem(static_cast(WPAReader.key())); wpsitem->setForeground(QColor(255,255,255)); if(WPAReader.value().Quality_value < 95) { wpsitem->setIcon(QIcon(":/assets/jinggao.svg")); WPAModel->appendRow(wpsitem); } else if(WPAReader.value().connectflags) { wpsitem->setIcon(QIcon(":/assets/Network.svg")); if(WPAModel->rowCount() > 0) WPAModel->insertRow(0,wpsitem); else WPAModel->appendRow(wpsitem); } else if(WPAReader.value().pwdError) { wpsitem->setIcon(QIcon(":/assets/wangluolianjiechaoshi.svg")); if(WPAModel->rowCount() > 1) { if(WPA_Scan_SSID_List[WPAModel->item(0)->text()].connectflags) WPAModel->insertRow(1,wpsitem); else WPAModel->insertRow(0,wpsitem); } else WPAModel->appendRow(wpsitem); } else if(WPAReader.value().id >= 0) { wpsitem->setIcon(QIcon(":/assets/Wifi_Unlock.svg")); if(WPAModel->rowCount() > 1) { if(WPA_Scan_SSID_List[WPAModel->item(0)->text()].connectflags || WPA_Scan_SSID_List[WPAModel->item(0)->text()].pwdError) WPAModel->insertRow(1,wpsitem); else WPAModel->insertRow(0,wpsitem); } else WPAModel->appendRow(wpsitem); } else { wpsitem->setIcon(QIcon(":/assets/Wifi_Lock.svg")); WPAModel->appendRow(wpsitem); } } } // this->setEnabled(true); // for (int i=0;irowCount();i++) // { // if(i & 1) // WPAModel->item(i)->setBackground(QBrush(Qt::gray)); // else // WPAModel->item(i)->setBackground(QBrush(Qt::darkGray)); // } ui->WPA_List->setModel(WPAModel); if(WPA_SSID[ui->DevList->currentText()].trimmed() == "") { GetDevState(); } } void Wlanconfig::GetDevState() { // this->setEnabled(false); LastDev = ui->DevList->currentText(); disconnect(((MainWindow*)FUI)->terminaldialog,&TerminalDialog::CMD_Reply,0,0); QObject::connect(((MainWindow*)FUI)->terminaldialog,&TerminalDialog::CMD_Reply,this,[=](QStringList CommandLine) { disconnect(((MainWindow*)FUI)->terminaldialog,&TerminalDialog::CMD_Reply,0,0); GetDevState(CommandLine); }); ((MainWindow*)FUI)->terminaldialog->SendCMD("iwconfig | grep -E \"wlan[0-9]|ESSID|Tx-Power=\"",TeminalState); } void Wlanconfig::GetDevState(QStringList &Responses) { ui->Btn_DevSwitch->setIcon(QIcon(":/assets/shebeiweilianjie-copy.svg")); WPA_Switch.clear(); WPA_SSID.clear(); ui->DevList->clear(); QString DevKey = ""; foreach(QString item , Responses) { QStringList Analytical = item.split(" ",QString::SkipEmptyParts); if(Analytical[0].toLower().startsWith("wlan")) { DevKey = Analytical[0]; if(Analytical[3].toLower() == "essid:off/any") { WPA_SSID.insert(DevKey,""); WPA_Switch.insert(DevKey,false); } else { WPA_SSID.insert(DevKey,(item.remove(0,item.indexOf("ESSID:")+6)).replace(QRegExp("\"([^<]*)\""), "\\1")); WPA_Switch.insert(DevKey,true); } } else { //功率数据可在此处提取 Analytical = item.split("Tx-Power=",QString::SkipEmptyParts); WPA_Switch[DevKey] = (Analytical.count() > 1); } } QStringList Dev; foreach(QString item , WPA_Switch.keys()) { Dev.append(item); } ui->DevList->addItems(Dev); //LastDev for (int i = 0;i < ui->DevList->count();i++) { if(ui->DevList->itemText(i) == LastDev) ui->DevList->setCurrentIndex(i); } // this->setEnabled(true); } void Wlanconfig::on_DevList_currentIndexChanged(const QString &arg1) { if(!WPA_Switch.contains(arg1)) { ui->Btn_DevSwitch->setIcon(QIcon(":/assets/shebeiweilianjie-copy.svg")); ui->Btn_Connect->setEnabled(false); ui->Btn_Scan->setEnabled(false); ui->WPA_List->setEnabled(false); return; } ui->Btn_DevSwitch->setIcon(QIcon(WPA_Switch[arg1] ? ":/assets/Network.svg":":/assets/shebeiweilianjie-copy.svg")); ui->Btn_Connect->setEnabled(WPA_Switch[arg1]); ui->Btn_Scan->setEnabled(WPA_Switch[arg1]); ui->WPA_List->setEnabled(WPA_Switch[arg1]); } ================================================ FILE: wlanconfig.h ================================================ #ifndef WLANCONFIG_H #define WLANCONFIG_H #include #include #include #include #include extern int DebugFlat ; extern QSizeF SizePercent; struct WPAInfo{ int id; double level; bool connectflags; bool pwdError; int Quality_value; int Quality_max; WPAInfo() { id = -1; level = -100; Quality_value = 0; Quality_max = 100; connectflags = false; pwdError = false; } }; Q_DECLARE_METATYPE(WPAInfo); namespace Ui { class Wlanconfig; } class Wlanconfig : public QDialog { Q_OBJECT public: explicit Wlanconfig(QWidget *parent = nullptr); ~Wlanconfig(); void GetNetworkInfo(); private slots: virtual void on_Btn_Back_clicked(); void on_Btn_DevRefresh_clicked(); void on_Btn_DevSwitch_clicked(); void on_Btn_Connect_clicked(); void on_Btn_Scan_clicked(); void on_DevList_currentIndexChanged(const QString &arg1); void on_WPA_List_doubleClicked(const QModelIndex &index); void on_Btn_Help_clicked(); private: void GetDevState(); void GetDevState(QStringList &Responses); void ScanWPAList(); void ScanWPAList(QStringList &Responses); void ScanWPA(); void ScanWPA(QStringList &Responses); void ScanWPA_Ressult(); void ScanWPA_Ressult(QStringList &Responses); QString ReverseStr(QString args); void ConnectNetwork(); void SetPassword(QStringList &Responses); void SetPassword(); void SetSSID(); void SetSSID(QStringList &Responses); void CreateNetwork(); // void GetNetworkInfo(); void GetNetworkInfo(QStringList &Responses); void RemoveNetwork(); void RemoveNetwork(QStringList &Responses); private: Ui::Wlanconfig *ui; QWidget *FUI; QString TeminalState = "-q-e"; QMap WPA_Switch ; QMap WPA_SSID ; QMap WPA_Scan_SSID_List ; QStandardItemModel *WPAModel = new QStandardItemModel(this); QString LastDev; protected: void showEvent(QShowEvent *event); }; #endif // WLANCONFIG_H ================================================ FILE: wlanconfig.ui ================================================ Wlanconfig 0 0 800 480 0 0 Wlan :/assets/WiFi2.svg:/assets/WiFi2.svg 3 5 5 5 5 5 5 5 5 BTStyleSheet2 :/assets/huitui.svg:/assets/huitui.svg 72 72 Qt::Horizontal 40 20 border:none; font: 75 30pt "Gill Sans MT"; :/assets/Wifi.svg:/assets/Wifi.svg 72 72 Qt::Horizontal 40 20 BTStyleSheet2 Qt::RightToLeft :/assets/help.svg:/assets/help.svg 72 72 5 30 background-color: rgb(64, 64, 64); QAbstractItemView::NoEditTriggers 0 0 0 BTStyleSheet2 :/assets/shuaxin.svg:/assets/shuaxin.svg 72 72 0 0 21 color: rgb(255, 255, 255); Wlan Device : Qt::AlignCenter 0 0 30 color: rgb(255, 255, 255); 0 0 0 BTStyleSheet2 :/assets/wangluo.svg:/assets/wangluo.svg 72 72 0 0 BTStyleSheet2 :/assets/sanweidianyunsaomiao.svg:/assets/sanweidianyunsaomiao.svg 72 72 0 0 BTStyleSheet2 :/assets/shebeiweilianjie-copy.svg:/assets/shebeiweilianjie-copy.svg 72 72