├── .editorconfig ├── .gitattributes ├── .github ├── ISSUE_TEMPLATE │ └── problem-report.md └── workflows │ ├── close-stale.yml │ ├── lock-closed.yml │ └── unlock-reopened.yml ├── .gitignore ├── LICENSE ├── MANIFEST.in ├── README.md ├── babel.cfg ├── doc ├── avrdude.md ├── bootcommander.md ├── bossac.md ├── dfu-util.md ├── dfuprog.md ├── esptool.md ├── lpc176x.md ├── marlinbft.md └── stm32flash.md ├── extras └── img │ ├── avrdude-config.png │ ├── avrdude.png │ ├── bootcommander.png │ ├── bossac-config.png │ ├── bossac.png │ ├── dfu-prog.png │ ├── dfu-util.png │ ├── ender3v2.png │ ├── esptool.png │ ├── firmware-updater.png │ ├── lpc176x.png │ ├── marlinbft.png │ ├── plugin-options.png │ ├── post-flash-config.png │ ├── pre-post.png │ └── stm32flash.png ├── octoprint_firmwareupdater ├── __init__.py ├── methods │ ├── __init__.py │ ├── avrdude.py │ ├── bootcmdr.py │ ├── bossac.py │ ├── dfuprog.py │ ├── dfuutil.py │ ├── esptool.py │ ├── lpc1768.py │ ├── marlinbft.py │ └── stm32flash.py ├── static │ ├── css │ │ └── firmwareupdater.css │ └── js │ │ └── firmwareupdater.js └── templates │ ├── firmwareupdater_navbar.jinja2 │ └── firmwareupdater_settings.jinja2 ├── requirements.txt ├── setup.py ├── tests └── test_firmwareupdater.py └── translations └── README.txt /.editorconfig: -------------------------------------------------------------------------------- 1 | # This file is for unifying the coding style for different editors and IDEs 2 | # editorconfig.org 3 | 4 | root = true 5 | 6 | [*] 7 | end_of_line = lf 8 | charset = utf-8 9 | insert_final_newline = true 10 | trim_trailing_whitespace = true 11 | 12 | [**.py] 13 | indent_style = tab 14 | 15 | [**.js] 16 | indent_style = space 17 | indent_size = 4 18 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Use UNIX line endings 2 | text eol=lf 3 | 4 | *.css text 5 | *.jinja2 text 6 | *.js text 7 | *.py text 8 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/problem-report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Problem Report 3 | about: Report a problem with the plugin 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Hardware Setup** 11 | Please board type and printer make and model. 12 | 13 | **Describe the problem** 14 | Please provide a clear and concise description of what the problem is, including details of any error messages you receive (screenshots are helpful). 15 | 16 | **Log Files** 17 | Attach the OctoPrint log and the Firmware Updater log Log files, which can be accessed under **Settings** -> **Logging** in OctoPrint, or in `~/.octoprint/logs/` on the host. Both `octoprint.log` and `~/.octoprint/logs/plugin_firmwareupdater_console.log` should be included. 18 | 19 | **Additional context** 20 | Add any other context about the problem here. 21 | -------------------------------------------------------------------------------- /.github/workflows/close-stale.yml: -------------------------------------------------------------------------------- 1 | # 2 | # close-stale.yml 3 | # Close open issues after a period of inactivity 4 | # 5 | 6 | name: Close Stale Issues 7 | 8 | on: 9 | schedule: 10 | - cron: '0 1 * * *' 11 | 12 | jobs: 13 | stale: 14 | name: Close Stale Issues 15 | if: github.repository == 'OctoPrint/OctoPrint-FirmwareUpdater' 16 | 17 | runs-on: ubuntu-latest 18 | 19 | steps: 20 | - uses: actions/stale@v3 21 | with: 22 | repo-token: ${{ secrets.GITHUB_TOKEN }} 23 | stale-issue-message: > 24 | This issue has been automatically marked as stale because it has not had any 25 | recent activity. Please add a reply if you want to keep this issue active, 26 | otherwise it will be automatically closed in 5 days. 27 | days-before-stale: 14 28 | days-before-close: 5 29 | exempt-issue-labels: 'enhancement,work-in-progress' 30 | -------------------------------------------------------------------------------- /.github/workflows/lock-closed.yml: -------------------------------------------------------------------------------- 1 | # 2 | # lock-closed.yml 3 | # Lock closed issues after a period of inactivity 4 | # 5 | 6 | name: Lock Closed Issues 7 | 8 | on: 9 | schedule: 10 | - cron: '0 2 * * *' 11 | 12 | jobs: 13 | lock: 14 | name: Lock Closed Issues 15 | if: github.repository == 'OctoPrint/OctoPrint-FirmwareUpdater' 16 | 17 | runs-on: ubuntu-latest 18 | 19 | steps: 20 | - uses: dessant/lock-threads@v2 21 | with: 22 | github-token: ${{ github.token }} 23 | process-only: 'issues' 24 | issue-lock-inactive-days: '21' 25 | issue-exclude-created-before: '' 26 | issue-exclude-labels: 'no-locking' 27 | issue-lock-labels: '' 28 | issue-lock-comment: > 29 | This issue has been automatically locked because there was no further activity 30 | after it was closed. Please open a new issue for any related problems. 31 | issue-lock-reason: '' 32 | -------------------------------------------------------------------------------- /.github/workflows/unlock-reopened.yml: -------------------------------------------------------------------------------- 1 | # 2 | # unlock-reopened.yml 3 | # Unlock an issue whenever it is re-opened 4 | # 5 | 6 | name: Unlock Reopened Issue 7 | 8 | on: 9 | issues: 10 | types: [reopened] 11 | 12 | jobs: 13 | unlock: 14 | name: Unlock Reopened Issues 15 | if: github.repository == 'OctoPrint/OctoPrint-FirmwareUpdater' 16 | 17 | runs-on: ubuntu-latest 18 | 19 | steps: 20 | - uses: OSDKDev/unlock-issues@v1.1 21 | with: 22 | repo-token: "${{ secrets.GITHUB_TOKEN }}" 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | *.swp 3 | .idea 4 | *.iml 5 | build 6 | dist 7 | *.egg* 8 | .DS_Store 9 | *.zip 10 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include README.md 2 | recursive-include octoprint_firmwareupdater/templates * 3 | recursive-include octoprint_firmwareupdater/translations * 4 | recursive-include octoprint_firmwareupdater/static * 5 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # OctoPrint Firmware Updater Plugin 2 | The Firmware Updater plugin can be used to flash pre-compiled firmware images to your printer from a local file or URL. 3 | 4 |

5 | Firmware Updater 6 |

7 | 8 | ## Documentation Index 9 | 1. [Supported Boards](#supported-boards) 10 | 1. [Plugin Installation](#plugin-installation) 11 | 1. [Plugin Configuration](#plugin-configuration) 12 | 1. [Flashing Firmware](#flashing-firmware) 13 | 1. [Advanced Options](#advanced-options) 14 | 1. [Customizing the Command Lines](#customizing-the-command-lines) 15 | 1. [Pre and Post Flash Settings](#pre-and-post-flash-settings) 16 | 1. [Plugin Options](#plugin-options) 17 | 1. [Troubleshooting](#troubleshooting) 18 | 1. [Donations](#donations) 19 | 20 | ## Supported Boards 21 | The plugin supports a variety of boards, based on the MCU (processor) they have: 22 | 23 | | Description | Examples | Flash Method | 24 | | --- | --- | --- | 25 | | Atmel ATmega 8-bit MCUs | RAMPS, Sanguinololu, Melzi, Anet, Creality, Ender, Prusa MK3, Prusa MMU, Prusa CW1 many others | [avrdude](doc/avrdude.md) | 26 | | Atmel AT90USB 8-bit MCUs | Printrboard | [dfuprog](doc/dfuprog.md) | 27 | | NXP LPC176x 32-bit MCUs | MKS SBASE, SKR v1.1, v1.3, v1.4, v1.4 Turbo etc. | [lpc176x](doc/lpc176x.md) or [marlinbft](doc/marlinbft.md) | 28 | | Atmel SAM 32-bit MCUs | Arduino DUE, etc. | [bossac](doc/bossac.md) | 29 | | STM32 32-bit MCUs (via SD card) | SKR Pro v1.1, SKR Mini E3 v2, etc. | [lpc176x](doc/lpc176x.md) or [marlinbft](doc/marlinbft.md) | 30 | | STM32 32-bit MCUs (ST Bootloader) | FYSETC Cheetah | [stm32flash](doc/stm32flash.md) | 31 | | STM32 32-bit MCUs (DFU Mode) | MKS Rumba 32 | [dfu-util](doc/dfu-util.md) | 32 | | OpenBLT Bootloader | Any board with the OpenBLT bootloader | [lpc176x](doc/lpc176x.md) or [bootcommander](doc/bootcommander.md) | 33 | 34 | Please open a [Github issue](https://github.com/OctoPrint/OctoPrint-FirmwareUpdater/issues) if you would like a new board or MCU to be supported. If it's a new type of board which requires hardware testing please consider making a [donation](#Donations) to help fund the costs. 35 | 36 | ## Plugin Installation 37 | Install via the bundled [Plugin Manager](https://github.com/foosel/OctoPrint/wiki/Plugin:-Plugin-Manager) 38 | or manually using this URL: 39 | https://github.com/OctoPrint/OctoPrint-FirmwareUpdater/archive/master.zip 40 | 41 | Using OctoPrint's Software Update plugin you can choose one of three Release Channels to follow: 42 | 43 | | Release Channel | Description | 44 | | --- | --- | 45 | | Stable (Recommended) | Updated least frequently, features are stable | 46 | | Release Candidate | Updated when new features are ready for testing | 47 | | Development | Updated frequently, may be unstable, used for beta-testing new features | 48 | 49 | If you report a bug or request a new feature you will probalby be asked to test development or RC builds. 50 | 51 | ## Plugin Configuration 52 | The appropriate flashing tool for the board type needs to be selected. See the table in the [supported boards](#supported-boards) section to choose the appropriate method. 53 | 54 | **Note:** If your board is updated by copying a file named `firmware.bin` to the SD card and resetting the board, you should use the **lpc176x** method. This applies to SKR Pro v1.1 or SKR Mini E3 v2 boards and probably others. 55 | 56 | ### Board-Specific Configuration 57 | Plugin settings vary depending on the flashing tool and are documented on the page for each flash method. Follow the instructions on the appropriate page to install and configure any necessary tools: 58 | * [Atmega (AVR) based boards](doc/avrdude.md) 59 | * [AT90USB based boards](doc/dfuprog.md) 60 | * LPC176x and other boards which are updated from the SD card 61 | * Option 1 - [File copy using SD mount](doc/lpc176x.md) 62 | * Option 2 - [File transfer using serial protocol](doc/marlinbft.md) 63 | * [SAM based boards](doc/bossac.md) 64 | * [STM32 based boards which do not update from the SD card](doc/stm32flash.md) 65 | * [STM32 based board with DFU mode](doc/dfu-util.md) 66 | * [Any board with an OpenBLT bootloader](doc/bootcommander.md) 67 | 68 | ## Flashing Firmware 69 | Once the plugin is configured, flashing firmware is a simple operation: 70 | 1. Select the COM port to communicate with the board 71 | 1. Select a firmware file, either located on the filesystem or via a URL 72 | 1. Click the appropriate **Flash from** button 73 | 1. Wait for the firmware update to complete 74 | 75 | ## Advanced Options 76 | ### Customizing the Command Lines 77 | The command lines for `avrdude`, `bossac`, and `dfu-programmer` can be customized by editing the string in the advanced settings for the flash method. Text in braces (`{}`) will be substituted for preconfigured values if present. 78 | 79 | | String | Description| 80 | | --- | --- | 81 | | `{avrdude}` | Full path to the `avrdude` executable1 | 82 | | `{bossac}` | Full path to the `bossac` executable2 | 83 | | `{dfuprogrammer}` | Full path to the `dfu-programmer` executable3 | 84 | | `{mcu}` | MCU type4 | 85 | | `{programmer}` | Avrdude programmer1 | 86 | | `{port}` | COM port the printer is connected to | 87 | | `{conffile}` | Full path to the avrdude configuration file1 | 88 | | `{baudrate}` | Serial port speed1 | 89 | | `{disableverify}` | Switch to disable write verification | 90 | | `{firmware}` | Path to the uploaded firmware file | 91 | 92 | 1. avrdude flash method only 93 | 2. bossac flash method only 94 | 3. dfu-programmer flash method only 95 | 4. avrdude and dfu-programmer flash methods 96 | 97 | #### Command Line Defaults 98 | Command lines can be returned to the default by clicking the **Reset** button. 99 | 100 | ##### Avrdude 101 | `{avrdude} -v -q -p {mcu} -c {programmer} -P {port} -D -C {conffile} -b {baudrate} {disableverify} -U flash:w:{firmware}:i` 102 | 103 | ##### Bossac 104 | `{bossac} -i -p {port} -U true -e -w {disableverify} -b {firmware} -R` 105 | 106 | ##### Dfu-programmer 107 | Erase: `{bossac} -i -p {port} -U true -e -w {disableverify} -b {firmware} -R` 108 | Flash: 109 | 110 | ### Pre and Post-flash Settings 111 | 112 | The flash sequence is: 113 | 1. Execute the pre-flash system command(s) on the host 114 | 1. Send the pre-flash gcode commands(s) to the printer 115 | 1. Pause for the pre-flash gcode delay 116 | 1. Disconnect the printer 117 | 1. Execute the firmware update 118 | 1. Pause for the post-flash delay 119 | 1. Execute the post-flash system command(s) on the host 120 | 1. Reconnect the printer 121 | 1. Send the post-flash gcode command(s) to the printer 122 | 123 | | Option | Description | 124 | | --- | --- | 125 | | Pre-flash System Command| Specify a system command or script to run on the host prior to flashing. Multiple commands can be separated with a semicolon. | 126 | | Pre-flash Gcode | Specify gcode commands to run on the printer prior to flashing. Multiple commands can be separated with a semicolon. **Commands are only run if the printer is connected when flashing is initiated** | 127 | | Pre-flash Gcode Delay | Delay after sending pre-flash gcode. Allows time for code to complete before initiating flash. | 128 | | Post-flash Delay | This setting can be used to insert a delay of up to 180s after the firmware has been uploaded. This can be useful if the board takes some time to restart. A delay of 20-30s is usually enough. | 129 | | Post-flash System Command | Specify a system command or script to run on the host after flashing. Multiple commands can be separated with a semicolon. | 130 | | Post-flash Gcode | You can use the post-flash gcode settings to run gcode commands after a successful firmware flash. The post-flash code will run more or less immediately if the printer was connected before the flash started (so reconnects automatically when the flash finishes), or whenever the printer is manually reconnected after the firmware is flashed. | 131 | 132 | ### Plugin Options 133 | | Option | Description | 134 | | --- | --- | 135 | | Enable Navbar Icon | Enables an icon in the OctoPrint Navbar which can be used to quickly access the Firmware Updater. | 136 | | Remember URL | The last URL will be remembered when using 'Flash from URL. | 137 | 138 | ## Troubleshooting 139 | Log messages can be found in the OctoPrint log `octoprint.log` and the Firmware Updater's console log `plugin_firmwareupdater_console.log`. 140 | 141 | Both log files can be downloaded from OctoPrint's logging interface, found under 'Logging' in the settings page. 142 | 143 | If you have trouble using the plugin please check these logs for any error messages. If you need help, please include both logs when reporting a problem. 144 | 145 | ## Donations 146 | Donations to help with the cost of test hardware are gratefully received using any of the methods below. 147 | 148 | | Currency | Link | 149 | | --- | --- | 150 | | Bitcoin | [1GjUmcjnAxCr9jFPUtVrr6gPQz8FhYddZz](https://www.blockchain.com/btc/address/1GjUmcjnAxCr9jFPUtVrr6gPQz8FhYddZz) | 151 | | Bitcoin Cash | [bitcoincash:qzqys6mv9rgg7dxx0m4jzgqjezu9sryk2vmdexcr56](https://www.blockchain.com/bch/address/bitcoincash:qzqys6mv9rgg7dxx0m4jzgqjezu9sryk2vmdexcr56) | 152 | | Ethereum | [0xA1788874E851b425F65FF5bcB6180b0d9F50fB6d](https://www.blockchain.com/eth/address/0xA1788874E851b425F65FF5bcB6180b0d9F50fB6d) | 153 | | USD | [https://www.paypal.com/](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=PYRBY6KFWX5TJ¤cy_code=USD&source=url) | 154 | -------------------------------------------------------------------------------- /babel.cfg: -------------------------------------------------------------------------------- 1 | [python: */**.py] 2 | [jinja2: */**.jinja2] 3 | extensions=jinja2.ext.autoescape, jinja2.ext.with_ 4 | 5 | [javascript: */**.js] 6 | extract_messages = gettext, ngettext 7 | -------------------------------------------------------------------------------- /doc/avrdude.md: -------------------------------------------------------------------------------- 1 | # Flashing an Atmega (AVR) Board with Avrdude 2 | 3 | All AVR boards can be flashed using avrdude. Many boards have a bootloader installed which allows flashing via the USB port, but some boards will required hardware such as a USBasp or other In-System-Programmer (ISP). 4 | 5 | You will need to know how to configure avrdude to flash your board before you can flash it with the Firmware Updater plugin. If you do not know what settings you need you maybe able to find out from a user community or forums for your printer/board. 6 | 7 | ## Table of Contents 8 | 1. [Avrdude Installation](#avrdude-installation) 9 | 1. [Raspberry Pi](#raspberry-pi) 10 | 1. [Ubuntu Linux](#ubuntu-linux) 11 | 1. [Avrdude Configuration](#avrdude-configuration) 12 | 1. [Required Settings](#required-settings) 13 | 1. [Optional Settings](#optional-settings) 14 | 1. [Hardware Notes](#hardware-notes) 15 | 1. [Creality Ender](#creality-ender) 16 | 1. [Prusa MMU and CW1](#prusa-mmu-and-cw1) 17 | 18 | ## Avrdude Installation 19 | To flash an ATmega-based board the tool `avrdude` needs to be installed on the OctoPrint host. 20 | 21 | ### Raspberry Pi 22 | 23 | ``` 24 | sudo apt-get update 25 | sudo apt-get install avrdude 26 | ``` 27 | 28 | ### Ubuntu Linux 29 | Information about the package needed can be found here [Ubuntu avrdude package](https://launchpad.net/ubuntu/+source/avrdude) 30 | 31 | ``` 32 | sudo add-apt-repository ppa:pmjdebruijn/avrdude-release 33 | sudo apt-get update 34 | sudo apt-get install avrdude 35 | ``` 36 | 37 | ## Avrdude Configuration 38 |

39 | Firmware Updater 40 |

41 | 42 | ### Required Settings 43 | The minimum settings needed are: 44 | * AVR MCU Type 45 | * Path to avrdude 46 | * AVR Programmer Type 47 | 48 | Typical MCU/programmer combinations are: 49 | 50 | | AVR MCU | Programmer | Example Board | 51 | | --- | --- | --- | 52 | | Atmega1284p | arduino | Anet A series, most Creality boards, Ender, etc. | 53 | | Atmega2560 | wiring | Creality CR-10 Max, RAMPS, Prusa MK3 (RAMbo), etc. | 54 | | Atmega644p | arduino | Sanguinololu, Melzi | 55 | | Atmega32u4 | avr109 | Prusa MMU, Prusa CW1 | 56 | 57 | To locate `avrdude` on most Linux variants (including OctoPi): 58 | * Connect via SSH and run the following: `which avrdude` 59 | * The output should be similar to: 60 | ``` 61 | pi@octopi:~ $ which avrdude 62 | /usr/bin/avrdude 63 | pi@octopi:~ $ 64 | ``` 65 | * Add the full path to avrdude in the plugin settings. 66 | 67 | ### Optional Settings 68 | | Option | Description | 69 | | --- | --- | 70 | | avrdude Baud Rate| Speed for communication with the board. 'Default' is strongly recommended. | 71 | | avrdude config file | Can be used to override the default config file with a custom one. | 72 | | Disable write verification | Speed up flashing by not verifying the write operation. Not recommended! | 73 | | Command line | Customize the avrdude command line, e.g. to specify an MCU or programmer which is not listed. | 74 | | Disabling bootloader warning | Disables a warning which is shown the hex filename has 'bootloader' in it. | 75 | 76 | ## Hardware Notes 77 | ### Creality Ender 78 | The Atmega-based mainboard in the Ender 3 (and probably other devices) is supplied without a bootloader. The first time you want to upgrade its firmware you have to use extra programming hardware (a USBasp) to install a bootloader. Alternately you can use the "USB ISP" programmer which they include with their [BL-Touch Add-on Kit](https://www.creality3dofficial.com/products/creality-bl-touch?_pos=8&_sid=07be62867&_ss=rell), which comes with a pinout card. 79 | 80 | ### Prusa MMU and CW1 81 | Original firmware files for Prusa MMU and CW1 have special in the begining of the file: 82 | 83 | For MMU these are: 84 | 85 | ``` 86 | 1 ;device = mm-control 87 | 2 88 | ``` 89 | 90 | and for CW1: 91 | 92 | ``` 93 | 1 ;device = cw1 94 | 2 95 | ``` 96 | 97 | The Firmware Updater plugin will automatically detect these headers and handle the files accordingly. 98 | 99 | #### Plugin Settings for Prusa MMU 100 | 101 | To flash the MMU you need to create an additional profile with different settings: 102 | 103 | | Setting | Selection | 104 | | --- | --- | 105 | | Flash Method | avrdude | 106 | | AVR MCU | ATmega32u4 | 107 | | AVR Programmer | avr109 | 108 | -------------------------------------------------------------------------------- /doc/bootcommander.md: -------------------------------------------------------------------------------- 1 | # Flashing a board with BootCommander 2 | 3 | Boards running the OpenBLT bootloader can be flashed using BootCommander. 4 | 5 | ## Table of Contents 6 | 1. [BootCommander Installation](#bootcommander-installation) 7 | 1. [BootCommander Configuration](#bootcommander-configuration) 8 | 1. [Required Settings](#required-settings) 9 | 1. [Optional Settings](#optional-settings) 10 | 11 | ## BootCommander Installation 12 | To flash an OpenBLT-based board the tool `BootCommander` needs to be installed on the OctoPrint host. 13 | 14 | BootCommander and its dependency LibOpenBLT must be compiled and installed from source. 15 | 16 | Full instructions are [here](https://www.feaser.com/openblt/doku.php?id=manual:bootcommander). 17 | 18 | ## BootCommander Configuration 19 |

20 | Firmware Updater 21 |

22 | 23 | ### Required Settings 24 | The only required setting is the path to the BootCommander binary. 25 | 26 | ### Optional Settings 27 | | Option | Description | 28 | | --- | --- | 29 | | Reset before flashing | Send an `M997` command to the board to initiate a reset and activate the bootloader prior to running BootCommander. Needed if the firmware is not 'OpenBLT aware'. | 30 | | Command timeout | The length of time that the plugin will wait for the bootloader to be detected. Default is 30s. | 31 | | BootCommander Baud Rate | The baud rate BootCommander will use when communicating with the bootloader. Default is 57600. | 32 | | Command line | The command used to flash the firmware to the board. | 33 | -------------------------------------------------------------------------------- /doc/bossac.md: -------------------------------------------------------------------------------- 1 | # Flashing a SAM board with Bossac 2 | 3 | Arduino DUE and other Atmel SAM based 32-bit boards can be flashed using bossac. 4 | 5 | ## Table of Contents 6 | 1. [Bossac Installation](#bossac-installation) 7 | 1. [Linux (including Raspberry Pi)](#linux-including-raspberry-pi) 8 | 1. [Bossac Configuration](#bossac-configuration) 9 | 1. [Required Settings](#required-settings) 10 | 1. [Optional Settings](#optional-settings) 11 | 12 | ## Bossac Installation 13 | To flash a SAM-based board the tool `bossac` needs to be installed on the OctoPrint host. 14 | 15 | ### Linux (includng Raspberry Pi) 16 | Bossac cannot be installed using a package manager as the packaged version is out of date and will not work. Installation from source is straight-forward. 17 | 18 | ``` 19 | cd ~/ 20 | sudo apt-get install libwxgtk3.0-dev libreadline-dev 21 | wget https://github.com/shumatech/BOSSA/archive/1.7.0.zip 22 | unzip 1.7.0.zip 23 | cd BOSSA-1.7.0 24 | ./arduino/make_package.sh 25 | sudo cp ~/BOSSA-1.7.0/bin/bossac /usr/local/bin/ 26 | ``` 27 | 28 | ## Bossac Configuration 29 |

30 | Firmware Updater 31 |

32 | 33 | ### Required Settings 34 | The only required setting is the path to the bossac binary. 35 | 36 | ### Optional Settings 37 | | Option | Description | 38 | | --- | --- | 39 | | Disable write verification | Speed up flashing by not verifying the write operation. Not recommended. | 40 | | Flash command line | The command used to flash the firmware to the board. | 41 | -------------------------------------------------------------------------------- /doc/dfu-util.md: -------------------------------------------------------------------------------- 1 | # Flashing an STM32 board with dfu-util 2 | 3 | MKS Rumba 32 boards, and other STM32 boards with DFU mode, can be flashed with dfu-util. 4 | 5 | ## Table of Contents 6 | 1. [Dfu-util Installation](#dfu-util-installation) 7 | 1. [Linux (including Raspberry Pi)](#linux-including-raspberry-pi) 8 | 1. [Sudo rights](#sudo-rights) 9 | 1. [Configure Sudo](#configure-sudo) 10 | 1. [Bossac Configuration](#bossac-configuration) 11 | 1. [Required Settings](#required-settings) 12 | 1. [Optional Settings](#optional-settings) 13 | 14 | ## Dfu-util Installation 15 | To flash a STM32-based DFU-mode board the tool `dfu-util` needs to be installed on the OctoPrint host. 16 | 17 | ### Linux (includng Raspberry Pi) 18 | Dfu-util can be installed on most systems using the package manager 19 | 20 | ``` 21 | sudo apt update 22 | sudo apt install dfu-util 23 | ``` 24 | 25 | Locate the dfu-util binary using `which`: 26 | 27 | ``` 28 | pi@octopi:~ $ which dfu-util 29 | /usr/bin/dfu-util 30 | pi@octopi:~ $ 31 | ``` 32 | 33 | ### Sudo rights 34 | The plugin needs to be able to run the `dfu-util` utility with root privileges. You must be able to run `sudo dfu-util` at the command line without being prompted for a password. 35 | 36 | If your system is configured to allow `pi` to run all `sudo` commands without a password (the default) then you do not need to do anything further. 37 | 38 | #### Configure Sudo 39 | If you need to enter a password when running `sudo` commands as `pi` you will need to create a new `sudoers` entry in order for the plugin to work correctly. 40 | 41 | 1. Run this command in an SSH prompt on your OctoPrint host to create a new sudo rule file: 42 | 43 | `sudo nano /etc/sudoers.d/020_firmware_updater` 44 | 45 | 2. Paste this line into the new file: 46 | 47 | `pi ALL=NOPASSWD: /usr/bin/dfu-util` 48 | 49 | 3. Save and close the file 50 | 51 | ## Dfu-util Configuration 52 |

53 | Firmware Updater 54 |

55 | 56 | ### Required Settings 57 | The only required setting is the path to the dfu-util binary. 58 | 59 | ### Optional Settings 60 | | Option | Description | 61 | | --- | --- | 62 | | Flash command line | The command used to flash the firmware to the board. | 63 | -------------------------------------------------------------------------------- /doc/dfuprog.md: -------------------------------------------------------------------------------- 1 | # Flashing an AT90USB Board with DFU Programmer 2 | 3 | Printrboard boards using AT90USB MCUs (and possibly other compatible boards) can be flashed using dfu-programmer. 4 | 5 | ## Table of Contents 6 | 1. [Dfu-programmer Installation](#dfu-programmer-installation) 7 | 1. [Linux (including Raspberry Pi)](#linux-including-raspberry-pi) 8 | 1. [Dfu-programmer Configuration](#dfu-programmer-configuration) 9 | 1. [Required Settings](#required-settings) 10 | 1. [Optional Settings](#optional-settings) 11 | 1. [Hardware Notes](#hardware-notes) 12 | 1. [Printrboard DFU Mode](#printrboard-dfu-mode) 13 | 14 | ## Dfu-programmer Installation 15 | To flash an AT90USB-based board the tool `dfu-programmer` needs to be installed on the OctoPrint host. 16 | 17 | ### Linux (including Raspberry Pi) 18 | A version of `dfu-programmer` can be installed via `apt-get install` but it is outdated. Please build the latest version from [Github](https://github.com/dfu-programmer/dfu-programmer) using these commands: 19 | 20 | ``` 21 | cd ~ 22 | sudo apt-get install autoconf libusb-1.0-0-dev 23 | git clone https://github.com/dfu-programmer/dfu-programmer.git 24 | cd dfu-programmer 25 | ./bootstrap.sh 26 | ./configure 27 | make 28 | sudo make install 29 | ``` 30 | If there were no errors `dfu-programmer` should now be installed at /usr/local/bin/dfu-programmer. 31 | 32 | ## Dfu-programmer Configuration 33 |

34 | Firmware Updater 35 |

36 | 37 | ### Required Settings 38 | The minimum settings are: 39 | * AVR MCU Type 40 | * Path to dfu-programmer 41 | 42 | ### Optional Settings 43 | | Option | Description | 44 | | --- | --- | 45 | | Erase command line | The command used to erase the board prior to flashing. | 46 | | Flash command line | The command used to flash the firmware to the board. | 47 | 48 | ## Hardware Notes 49 | AT90USB boards must be in **Boot** or **DFU** mode before they can be flashed. This is done by placing or removing a jumper then resetting the board. 50 | 51 | ### Printrboard DFU Mode 52 | To put a Printrboard board into DFU mode: 53 | * Remove the BOOT jumper (for Rev D, E & F boards, install the BOOT jumper) 54 | * Press and release the **Reset** button. 55 | * Replace the BOOT jumper onto the board (for Rev D, E & F boards, remove the BOOT jumper) 56 | 57 | The board will now be ready for flashing. Once flashing is complete press the **Reset** button again to return to normal operation. 58 | -------------------------------------------------------------------------------- /doc/esptool.md: -------------------------------------------------------------------------------- 1 | # Flashing an ESP32 Board wth esptool.py 2 | 3 | This method applies to ESP32-based boards which can be updated using esptool.py. 4 | 5 | ## Table of Contents 6 | 1. [Esptool Installation](#esptool-installation) 7 | 1. [Esptool Configuration](#stm32flash-configuration) 8 | 1. [Required Settings](#required-settings) 9 | 1. [Optional Settings](#optional-settings) 10 | 11 | ## Esptool Installation 12 | To flash an ESP32-based board using esptool, the tool needs to be installed on the OctoPrint host. 13 | 14 | Installation instructions can be found in the Espressif documentation: 15 | https://docs.espressif.com/projects/esptool/en/latest/esp32/installation.html 16 | 17 | Esptool can be installed in the OctoPrint virtual environment, if one is being used, or in the host's native Python environment. 18 | 19 | ## Esptool Configuration 20 |

21 | Firmware Updater 22 |

23 | 24 | ### Required Settings 25 | The only required setting is the path to esptool.py. 26 | 27 | ### Optional Settings 28 | | Option | Description | 29 | | --- | --- | 30 | | Chip Type | Can be used to override the ESP chip type. Default is `auto`. | 31 | | Baud Rate | Specify the baud rate for esptool to use when writing to the board. Default is `921600`. | 32 | | Flash Address | The address in hex to write the firmware to. Default is `0x10000`. | 33 | | Command Line | Allows full customization of the `esptool.py` command line. | 34 | -------------------------------------------------------------------------------- /doc/lpc176x.md: -------------------------------------------------------------------------------- 1 | # Flashing a Board from the SD Card 2 | 3 | This method applies to LPC1768 and LPC1769 boards, and other boards which are flashed by copying a file named `firmware.bin` to the SD card and resetting the board. This includes some STM32 boards which have the required bootloader installed (e.g., SKR Pro v1.1, SKR Mini E3 v2). 4 | 5 | Flashing a board from the SD requires that the host can mount the board's on-board SD card to a known mount point in the host filesystem. If your firmware does not expose the SD card to the host, and cannot be configured to do so, *this method will not work*. 6 | 7 | ## Table of Contents 8 | 1. [Marlin Firmware Configuration](#marlin-firmware-configuration) 9 | 1. [PlatformIO Build Environment](#platformio-build-environment) 10 | 1. [Testing Host Storage](#testing-host-storage) 11 | 1. [SD Card Mounting](#sd-card-mounting) 12 | 1. [Usbmount](#usbmount) 13 | 1. [Install Usbmount](#install-usbmount) 14 | 1. [Configure Usbmount](#configure-usbmount) 15 | 1. [Configure systemd-udevd](#configure-systemd-udevd) 16 | 1. [File System Permissions](#file-system-permissions) 17 | 1. [Sudo Rights](#sudo-rights) 18 | 1. [Configure sudo](#configure-sudo) 19 | 1. [lpc176x Configuration](#lpc176x-configuration) 20 | 1. [Hardware Notes](#hardware-notes) 21 | 1. [Creality Ender 3](#creality-ender-3) 22 | 1. [Troubleshooting](#troubleshooting) 23 | 1. [Board Reset Failed](#board-reset-failed) 24 | 1. [SD Card Mounting](#sd-card-mounting) 25 | 26 | ## Marlin Firmware Configuration 27 | The following options should be enabled in the Marlin firmware configuration in order for the board's SD card to be accessible by the OctoPrint host: 28 | 29 | Configuration.h: 30 | ``` 31 | #define SDSUPPORT 32 | ``` 33 | 34 | Configuration_adv.h: 35 | ``` 36 | #define SDCARD_CONNECTION ONBOARD 37 | ``` 38 | 39 | Optionally, if you do not routinely use the SD card in Marlin, you can prevent Marlin mounting the card at startup, which will make firmware flashing faster as the firmware's lock on the card does not have to be released. 40 | 41 | Configuration_adv.h: 42 | ``` 43 | #define SD_IGNORE_AT_STARTUP 44 | ``` 45 | 46 | ### PlatformIO Build Environment 47 | Some boards (e.g., SKR Mini E3 V2) need to have a specfic build environment specified in order to include USB storage support in the firmware. If you are compiling with PlatformIO, you can open your `platformio.ini` file and check the variable `default_envs` - environments with USB host storage will end in `_USB` or `_USB_maple`. 48 | 49 | ### Testing Host Storage 50 | If you plug your board into a PC the computer should see the SD card as a storage device. If this is not the case you need to check and adjust your firmware configuration. 51 | 52 | ## SD Card Mounting 53 | There are several ways to have the SD card mounted by the host. Depending on your level of experience and knowledge with Linux you are free to use whatever method you prefer. 54 | 55 | For new users, using [usbmount](https://github.com/rbrito/usbmount) is recommended and is documented below. When properly installed and configured it will automatically mount the board's SD card to `/media/usb`. 56 | 57 | ### Usbmount 58 | Usbmount needs to be installed and configured to make it work. The instructions below assume that you are running OctoPrint on a Raspberry Pi as the user `pi`. 59 | 60 | #### Install usbmount 61 | Usbmount can be installed using the package manager. Run this command in an SSH prompt on your OctoPrint host: 62 | 63 | `sudo apt-get install usbmount` 64 | 65 | #### Configure usbmount 66 | Usbmount must be configured so that the mounted device has the correct permissions for the 'pi' user to access the SD card. 67 | 68 | 1. Run this command in an SSH prompt on your OctoPrint host: 69 | 70 | `sudo nano /etc/usbmount/usbmount.conf` 71 | 72 | 1. Find the `FS_MOUNTOPTIONS` line and change it to: 73 | 74 | `FS_MOUNTOPTIONS="-fstype=vfat,gid=pi,uid=pi,dmask=0022,fmask=0111"` 75 | 76 | #### Configure systemd-udevd 77 | systemd-udevd must be configured so that the mount is accessible. 78 | 79 | 1. Run this command in an SSH prompt on your OctoPrint host: 80 | 81 | `sudo systemctl edit systemd-udevd` 82 | 83 | 1. Insert these lines then save and close the file: 84 | ``` 85 | [Service] 86 | PrivateMounts=no 87 | MountFlags=shared 88 | ``` 89 | 90 | 1. Run the following commands in an SSH prompt on your OctoPrint host: 91 | ``` 92 | sudo systemctl daemon-reload 93 | sudo service systemd-udevd --full-restart 94 | ``` 95 | 96 | Once usbmount is installed and configured the on-board SD card should be mounted at `/media/usb` the next time it is plugged in or restarted. 97 | 98 | #### File System Permissions 99 | 100 | **Important:** Do not modify the permissions on any of the /media/usb* directories! 101 | 102 | See [here](https://github.com/OctoPrint/OctoPrint-FirmwareUpdater/issues/175#issuecomment-760949800) and [here](https://github.com/OctoPrint/OctoPrint-FirmwareUpdater/issues/175#issuecomment-761111117) for the explanation of why this is important and a very bad idea. 103 | 104 | ### Sudo rights 105 | The plugin needs to be able to unmount the SD card to reduce the risk of file system corruption. The default command the plugin will use is `sudo umount /media/usb`. You must be able to run this command at the command line without being prompted for a password. 106 | 107 | If your system is configured to allow `pi` to run all `sudo` commands without a password (the default) then you do not need to do anything further. 108 | 109 | Alternatively, you can disable the unmount command entirely by clearing the **Unmount command** field in the plugin's advanced settings, however this is not recommended. 110 | 111 | #### Configure Sudo 112 | If you need to enter a password when running `sudo` commands as `pi` you will need to create a new `sudoers` entry in order for the plugin to work correctly. 113 | 114 | 1. Run this command in an SSH prompt on your OctoPrint host to create a new sudo rule file: 115 | 116 | `sudo nano /etc/sudoers.d/020_firmware_updater` 117 | 118 | 2. Paste this line into the new file: 119 | 120 | `pi ALL=NOPASSWD: /bin/umount` 121 | 122 | 3. Save and close the file 123 | 124 | ## LPC176x Configuration 125 |

126 | Firmware Updater 127 |

128 | 129 | ### Required Settings 130 | The only required setting is the path to the firmware update folder. If using usbmount it will be `/media/usb`. 131 | 132 | ### Optional Settings 133 | | Option | Description | 134 | | --- | --- | 135 | | Reset before flashing | Adds an extra board reset prior to flashing - can help ensure that the SD card is mounted correctly. | 136 | | Unmount command | The command used to unmount the SD card prior to resetting the board. Clear the command line to disable it | 137 | 138 | ## Hardware Notes 139 | ### Creality Ender 3 140 | Ender 3 V2 printers with 4.2.x boards do not expose the SD card via the USB port. They cannot be updated using this method. 141 | 142 | ## Troubleshooting 143 | ### Board reset failed 144 | The `M997` command is used to reset the board. If flashing an existing Marlin installation, the existing firmware must be newer than March 2nd, 2019 (i.e [this commit](https://github.com/MarlinFirmware/Marlin/pull/13281)) as that is when the `M997` was added to support resetting the board. 145 | 146 | A board running too-old Marlin firmware will report 'Board reset failed' when attempting to flash from the plugin. 147 | 148 | ### SD Card Mounting 149 | The firmware upload will fail if the SD card is not accessible, either because it is not mounted on the host, or because the printer firmware has control over it. 150 | 151 | The most common causes are: 152 | * Firmware not correctly configured to expose SD card to host via USB - reconfigure the firmware 153 | * Firmware is using the SD card so it is not available to the host - release the firmware's hold on the card with the `M22` command 154 | * usbmount is not configured correctly - follow the instructions to install and configure usbmount 155 | -------------------------------------------------------------------------------- /doc/marlinbft.md: -------------------------------------------------------------------------------- 1 | # Flashing an LPC176x or STM32 board using Binary File Transfer 2 | 3 | Binary File ransfer is an alternative method to transfer the `firmware.bin` file to a printer that can be flashed from the SD card. 4 | 5 | **WARNING:** This feature is based on the experimental Marlin [Binary File Transfer Protocol](https://github.com/MarlinFirmware/Marlin/pull/14817). It works well, but the protocol will undergo changes before it goes final, which **will** break it. When that happens I will update the plugin, but it may not happen immediately. 6 | 7 | ## Table of Contents 8 | 1. [Warnings and Caveats](#warnings-and-caveats) 9 | 1. [Installation](#installation) 10 | 1. [Marlin Binary Protocol Package](#marlin-binary-protocol-package) 11 | 1. [Marlin Configuration](#marlin-configuration) 12 | 1. [Enable Binary File Transfer](#enable-the-binary-file-transfer-protocol) 13 | 1. [Set SDCARD_CONNECTION to ONBOARD](#set-sdcard_connection-to-onboard) 14 | 1. [Plugin Configuration](#plugin-configuration) 15 | 1. [Required Settings](#required-settings) 16 | 1. [Optional Settings](#optional-settings) 17 | 1. [Hardware Notes](#hardware-notes) 18 | 1. [Creality Ender 3 V2](#creality-ender-3-v2) 19 | 20 | ## Warnings and Caveats 21 | 1. **The binary file transfer protocol is still work in progress** 22 | 23 | While the current implementation works, it **will** change, and these changes **will** break the current version. As much as possible, I will try to support the current implementation and the final version, but my ability to do so may be limited due to dependencies on other libraries. 24 | 25 | If it comes to a choice, the final version will be the one which is supported. 26 | 27 | 1. **Your Raspberry Pi may crash, but it's not my fault** 28 | 29 | While developing this I came across what seems to be a [bug in the Raspberry Pi kernel](https://github.com/raspberrypi/linux/issues/4120), where it will sometimes panic (crash) when the printer board resets. To mitigate this, as of Feb 6th 2021, a 2s delay [has been added](https://github.com/MarlinFirmware/Marlin/commit/004bed8a7fc3ff9feb73a0ea9794635b50073c27) to the LPC `M997` reset routine which appears to stop the crash from happening. You will need to be running Marlin from the `bugfix-2.0.x` branch, after https://github.com/MarlinFirmware/Marlin/commit/004bed8a7fc3ff9feb73a0ea9794635b50073c27 to have the fix. 30 | 31 | On my test system, with the old reset code, I would easily crash my Pi anywhere between 1-25 resets. After the change I have flashed the board dozens of times and reset it 500+ times without crashing it. 32 | 33 | That said, the underlying bug still exists, so you may still experience your Pi crashing when the board resets. Caveat emptor. 34 | 35 | ## Installation 36 | ### Marlin Binary Protocol Package 37 | The plugin currently uses the `marlin-binary-protocol` package to implement the transfer protocol. This package has dependencies on `heatshrink`, which is hard to install automatically due to compatibility issues with Python 2 and Python 3. For this reason the marlin-binary-protocol package and the heatshrink dependency need to be installed manually using `pip`. 38 | 39 | NB: If you are running OctoPrint in a VirtualEnv (as recommended) you need to run the appropriate `pip` commands below inside that environment. For **OctoPi** users, this is `~/oprint/bin/pip` anywhere it says `pip` or `pip3`. 40 | 41 | Depending on your system, the command you use to restart OctoPrint may also be different. 42 | 43 | #### Python 2 44 | 1. Install `marlin-binary-protocol` - the dependencies just work 45 | 46 | `pip install marlin-binary-protocol` 47 | 1. Restart OctoPrint 48 | 49 | `sudo service octoprint restart` 50 | 51 | #### Python 3 52 | The version of `marlin-binary-protocol` available on pypi has an unresolved dependency on a deprecated veraion of `heatshrink`. A patched version has been made available instead. See [issue #321](https://github.com/OctoPrint/OctoPrint-FirmwareUpdater/issues/321) for more details. 53 | 54 | 1. Install `marlin-binary-protocol` from patched package 55 | 56 | `pip install https://github.com/The-EG/marlin-binary-protocol/archive/refs/heads/master.zip` 57 | 1. Restart OctoPrint 58 | 59 | `sudo service octoprint restart` 60 | 61 | ## Marlin Configuration 62 | ### Enable the Binary File Transfer protocol 63 | Your printer must have the binary file protocol enabled in order to be able to use the protocol to copy firmware files to your printer. 64 | 65 | In other words, before you can use the Firmware Updater plugin, you must compile firmware with this feature enabled and flash it to your printer using your current update process. You only need to do this once. 66 | 67 | **Note:** The `MEATPACK` and `BINARY_FILE_TRANSFER` features cannot both be enabled. If `MEATPACK` is enabled, it must be disabled prior to enabling `BINARY_FILE_TRANSFER`. 68 | 69 | To compile firmware with the binary file protocol enabled, uncomment this line in `Configuration_adv.h`: 70 | 71 | `#define BINARY_FILE_TRANSFER` 72 | 73 | You can verify that the protocol is enabled using the `M115` command to get a capability report. The report must include this line: 74 | ``` 75 | Recv: Cap:BINARY_FILE_TRANSFER:1 76 | ``` 77 | If the value is `0` then the feature has not been enabled and the plugin will not work. 78 | 79 | ### Set SDCARD_CONNECTION to ONBOARD 80 | The SD card connection must be configured for `ONBOARD`. If it is set to `LCD` the firmware file will be copied to the SD card in the LCD and the board will not update when it is reset. 81 | 82 | To set the SD card to `ONBOARD`, modify the `#define SDCARD_CONNECTION` line in `Configuration_adv.h`: 83 | 84 | `#define SDCARD_CONNECTION ONBOARD` 85 | 86 | ## Prerequisite Check 87 | When both prerequisites are satisfied, the `~/.octoprint/logs/octoprint.log` file will contain lines like these shortly after OctoPrint is started and the printer is connected: 88 | ``` 89 | 2021-03-06 09:24:58,000 - octoprint.plugins.firmwareupdater - INFO - Python binproto2 package installed: True 90 | 2021-03-06 09:45:10,815 - octoprint.plugins.firmwareupdater - INFO - Setting BINARY_FILE_TRANSFER capability to True 91 | ``` 92 | 93 | ## Plugin Configuration 94 |

95 | Firmware Updater 96 |

97 | 98 | ### Required Settings 99 | There are no required settings. 100 | 101 | ### Optional Settings 102 | | Option | Description | 103 | | --- | --- | 104 | | Wait after connect | Some boards reset after getting the command to start binary transfer mode. A value of 3 seconds is normal for when this wait is required. Default is 0. | 105 | | Communication timeout | Protocol communication timeout. Default is 1000ms. | 106 | | Use alternative reset | Plugin will reconnect OctoPrint to the printer, send the `M997` reset command, and then wait for a `start` message to indicate the reset has occured. Used on boards which do not reset the COM port on restart, such as Ender 3V2 and BTT GTR v1. | 107 | | Use timestamp filesnames | Instead of `firmware.bin`, the uploaded firmware will be named `fwHHMMSS.bin` (where HHMMSS is the current time). Used on boards which expect unique firmware filenames for sequential uploads, such as Ender 3 V2.| 108 | | Customize firmware filename | Instead of `firmware.bin`, the uploaded firmware will be named whatever is set here. | 109 | | Don't wait for reset | The plugin won't wait for the board to initiate the reset and will return 'success' as soon as the `M997` command is sent. | 110 | | Reset timeout | How long to wait for the board to reset after sending `M997`. Default is 10s.| 111 | | Don't wait for restart | Plugin won't wait for the board to restart after the reset has begun. | 112 | | Restart timeout | How long to wait for the board to restart. Default is 20s. | 113 | | Verbose progress logging | Log verbose transfer progress to the OctoPrint log file | 114 | 115 | ## Hardware Notes 116 | ### Creality Ender 3 V2 117 | Two advanced settings must be enabled for Ender 3 V2 boards: 118 | * Use alternative reset 119 | * Use timestamp filenames 120 | 121 |

122 | Ender 3 V2 Settings 123 |

124 | 125 | **NB:** Before attempting to flash the board from the plugin for the first time, put the SD card in a computer and remove any `.bin` files which are on it. 126 | 127 | If flashing from the plugin fails and the plugin displays an error stating that the board reset too quickly check the SD card for `.bin` files and remove any which are present. 128 | -------------------------------------------------------------------------------- /doc/stm32flash.md: -------------------------------------------------------------------------------- 1 | # Flashing an STM32 Board wth STM32Flash 2 | 3 | This method applies to the FYSETC Cheetah and other STM32-based boards which are updated using stm32flash. 4 | 5 | **Note:** STM32-based boards which can be updated from the SD card (e.g., SKR Pro v1.1, SKR Mini E3 v2) should use the [lpc176x flash method](lpc176x.md). This method described on this page is only for boards which are updated using stm32flash. 6 | 7 | ## Table of Contents 8 | 1. [STM32Flash Installation](#stm32flash-installation) 9 | 1. [Linux (Including Raspberry Pi)](#linux-including-raspberry-pi) 10 | 1. [macOS](#macos) 11 | 1. [Windows](#windows) 12 | 1. [Stm32flash Configuration](#stm32flash-configuration) 13 | 1. [Required Settings](#required-settings) 14 | 1. [Optional Settings](#optional-settings) 15 | 16 | ## STM32Flash Installation 17 | To flash an STM32-based board using stm32flash, the tool needs to be installed on the OctoPrint host. 18 | 19 | ### Linux (Including Raspberry Pi) 20 | 21 | ``` 22 | sudo apt-get update 23 | sudo apt-get install stm32flash 24 | ``` 25 | 26 | ### macOS 27 | [Brew](https://brew.sh/) is used to install stm32flash on macOS. 28 | 29 | ``` 30 | brew install stm32flash 31 | ``` 32 | 33 | ### Check the installation 34 | 35 | Use the command `which stm32flash` to check the installation and find the full path to the executable 36 | ``` 37 | pi@octopi:~ $ which stm32flash 38 | /usr/bin/stm32flash 39 | ``` 40 | 41 | ### Windows 42 | You can install a Windows binary from https://sourceforge.net/projects/stm32flash/ however the plugin hasn't been tested on that platform. 43 | 44 | ## STM32Flash Configuration 45 |

46 | Firmware Updater 47 |

48 | 49 | ### Required Settings 50 | The only required setting is the path to the stm32flash binary. 51 | 52 | ### Optional Settings 53 | | Option | Description | 54 | | --- | --- | 55 | | Verify while writing | By default write verification is done during the write process; uncheck this box to disable it. It is strongly recommended to keep it enabled. | 56 | | BOOT0 and Reset pins | When using ST serial bootloader the boards needs to enter bootloader mode by setting the MCU `BOOT0 ` to HIGH and then setting MCU `RESET` to LOW. Such MCU inputs are generally connected to RTS/DTR signals of the USB-UART transceiver. For example, FYSETC Cheetah uses RTS to set BOOT0, and DTR to reset. Please set STM32Flash BOOT0/Reset according to your board.| 57 | | Start Execution Address | Unlike other MCUs, STM32s will remain in bootloader mode after resetting DTR line and realeasing UART. The bootloader needs an explicit command to jump at a given flash address. Set the Execution address according to your board. | 58 | | Reset after flashing | When setting Execution address the reset option is ignored by stm32flash. Setting Reset instead of Execution address will actually send an `Execute @ 0x00000000`, which is where the bootloader is located. You will then need to power cycle your board to execute firmware. **Enabling this option is not recommended.** | 59 | -------------------------------------------------------------------------------- /extras/img/avrdude-config.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OctoPrint/OctoPrint-FirmwareUpdater/fb999d7076d4f608dd7aba73152fc1f1875ab8fd/extras/img/avrdude-config.png -------------------------------------------------------------------------------- /extras/img/avrdude.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OctoPrint/OctoPrint-FirmwareUpdater/fb999d7076d4f608dd7aba73152fc1f1875ab8fd/extras/img/avrdude.png -------------------------------------------------------------------------------- /extras/img/bootcommander.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OctoPrint/OctoPrint-FirmwareUpdater/fb999d7076d4f608dd7aba73152fc1f1875ab8fd/extras/img/bootcommander.png -------------------------------------------------------------------------------- /extras/img/bossac-config.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OctoPrint/OctoPrint-FirmwareUpdater/fb999d7076d4f608dd7aba73152fc1f1875ab8fd/extras/img/bossac-config.png -------------------------------------------------------------------------------- /extras/img/bossac.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OctoPrint/OctoPrint-FirmwareUpdater/fb999d7076d4f608dd7aba73152fc1f1875ab8fd/extras/img/bossac.png -------------------------------------------------------------------------------- /extras/img/dfu-prog.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OctoPrint/OctoPrint-FirmwareUpdater/fb999d7076d4f608dd7aba73152fc1f1875ab8fd/extras/img/dfu-prog.png -------------------------------------------------------------------------------- /extras/img/dfu-util.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OctoPrint/OctoPrint-FirmwareUpdater/fb999d7076d4f608dd7aba73152fc1f1875ab8fd/extras/img/dfu-util.png -------------------------------------------------------------------------------- /extras/img/ender3v2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OctoPrint/OctoPrint-FirmwareUpdater/fb999d7076d4f608dd7aba73152fc1f1875ab8fd/extras/img/ender3v2.png -------------------------------------------------------------------------------- /extras/img/esptool.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OctoPrint/OctoPrint-FirmwareUpdater/fb999d7076d4f608dd7aba73152fc1f1875ab8fd/extras/img/esptool.png -------------------------------------------------------------------------------- /extras/img/firmware-updater.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OctoPrint/OctoPrint-FirmwareUpdater/fb999d7076d4f608dd7aba73152fc1f1875ab8fd/extras/img/firmware-updater.png -------------------------------------------------------------------------------- /extras/img/lpc176x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OctoPrint/OctoPrint-FirmwareUpdater/fb999d7076d4f608dd7aba73152fc1f1875ab8fd/extras/img/lpc176x.png -------------------------------------------------------------------------------- /extras/img/marlinbft.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OctoPrint/OctoPrint-FirmwareUpdater/fb999d7076d4f608dd7aba73152fc1f1875ab8fd/extras/img/marlinbft.png -------------------------------------------------------------------------------- /extras/img/plugin-options.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OctoPrint/OctoPrint-FirmwareUpdater/fb999d7076d4f608dd7aba73152fc1f1875ab8fd/extras/img/plugin-options.png -------------------------------------------------------------------------------- /extras/img/post-flash-config.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OctoPrint/OctoPrint-FirmwareUpdater/fb999d7076d4f608dd7aba73152fc1f1875ab8fd/extras/img/post-flash-config.png -------------------------------------------------------------------------------- /extras/img/pre-post.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OctoPrint/OctoPrint-FirmwareUpdater/fb999d7076d4f608dd7aba73152fc1f1875ab8fd/extras/img/pre-post.png -------------------------------------------------------------------------------- /extras/img/stm32flash.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OctoPrint/OctoPrint-FirmwareUpdater/fb999d7076d4f608dd7aba73152fc1f1875ab8fd/extras/img/stm32flash.png -------------------------------------------------------------------------------- /octoprint_firmwareupdater/__init__.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from __future__ import absolute_import 3 | 4 | import flask 5 | import logging 6 | import logging.handlers 7 | import os 8 | import requests 9 | import tempfile 10 | import threading 11 | import shutil 12 | import time 13 | import octoprint.plugin 14 | 15 | import octoprint.server.util.flask 16 | from octoprint.server import admin_permission, NO_CONTENT 17 | from octoprint.events import Events 18 | from octoprint.util import CaseInsensitiveSet, dict_merge 19 | 20 | from past.builtins import basestring 21 | 22 | # import the flash methods 23 | from octoprint_firmwareupdater.methods import avrdude 24 | from octoprint_firmwareupdater.methods import bootcmdr 25 | from octoprint_firmwareupdater.methods import bossac 26 | from octoprint_firmwareupdater.methods import dfuprog 27 | from octoprint_firmwareupdater.methods import dfuutil 28 | from octoprint_firmwareupdater.methods import esptool 29 | from octoprint_firmwareupdater.methods import lpc1768 30 | from octoprint_firmwareupdater.methods import stm32flash 31 | from octoprint_firmwareupdater.methods import marlinbft 32 | 33 | valid_boolean_trues = CaseInsensitiveSet(True, "true", "yes", "y", "1", 1) 34 | 35 | class FirmwareupdaterPlugin(octoprint.plugin.BlueprintPlugin, 36 | octoprint.plugin.TemplatePlugin, 37 | octoprint.plugin.AssetPlugin, 38 | octoprint.plugin.SettingsPlugin, 39 | octoprint.plugin.EventHandlerPlugin): 40 | 41 | def __init__(self): 42 | self._flash_thread = None 43 | 44 | self._flash_prechecks = dict() 45 | self._flash_methods = dict() 46 | 47 | self._console_logger = None 48 | 49 | def initialize(self): 50 | # TODO: make method configurable via new plugin hook "octoprint.plugin.firmwareupdater.flash_methods", 51 | # also include prechecks 52 | self._flash_prechecks = dict( 53 | avrdude=avrdude._check_avrdude, 54 | bootcmdr=bootcmdr._check_bootcmdr, 55 | bossac=bossac._check_bossac, 56 | dfuprogrammer=dfuprog._check_dfuprog, 57 | dfuutil=dfuutil._check_dfuutil, 58 | esptool=esptool._check_esptool, 59 | lpc1768=lpc1768._check_lpc1768, 60 | stm32flash=stm32flash._check_stm32flash, 61 | marlinbft=marlinbft._check_marlinbft 62 | ) 63 | self._flash_methods = dict( 64 | avrdude=avrdude._flash_avrdude, 65 | bootcmdr=bootcmdr._flash_bootcmdr, 66 | bossac=bossac._flash_bossac, 67 | dfuprogrammer=dfuprog._flash_dfuprog, 68 | dfuutil=dfuutil._flash_dfuutil, 69 | esptool=esptool._flash_esptool, 70 | lpc1768=lpc1768._flash_lpc1768, 71 | stm32flash=stm32flash._flash_stm32flash, 72 | marlinbft=marlinbft._flash_marlinbft 73 | ) 74 | 75 | console_logging_handler = logging.handlers.RotatingFileHandler(self._settings.get_plugin_logfile_path(postfix="console"), maxBytes=2*1024*1024) 76 | console_logging_handler.setFormatter(logging.Formatter("%(asctime)s %(message)s")) 77 | console_logging_handler.setLevel(logging.DEBUG) 78 | 79 | self._console_logger = logging.getLogger("octoprint.plugins." + __name__ + ".console") 80 | self._console_logger.addHandler(console_logging_handler) 81 | self._console_logger.setLevel(logging.DEBUG) 82 | self._console_logger.propagate = False 83 | 84 | self._logger.info("Python binproto2 package installed: {}".format(marlinbft._check_binproto2(self))) 85 | 86 | #~~ BluePrint API 87 | 88 | # Log all unhandled exceptions. 89 | @octoprint.plugin.BlueprintPlugin.errorhandler(Exception) 90 | def errorhandler(self, error): 91 | self._logger.exception(error) 92 | return error 93 | 94 | @octoprint.plugin.BlueprintPlugin.route("/status", methods=["GET"]) 95 | @octoprint.server.util.flask.restricted_access 96 | def status(self): 97 | return flask.jsonify(flashing=self._flash_thread is not None) 98 | 99 | @octoprint.plugin.BlueprintPlugin.route("/flash", methods=["POST"]) 100 | @octoprint.server.util.flask.restricted_access 101 | @octoprint.server.admin_permission.require(403) 102 | def flash_firmware(self): 103 | if self._printer.is_printing(): 104 | error_message = "Cannot flash firmware, printer is busy" 105 | self._send_status("flasherror", subtype="busy", message=error_message) 106 | return flask.make_response(error_message, 409) 107 | 108 | value_source = flask.request.json if flask.request.is_json else flask.request.values 109 | 110 | if not "port" in value_source: 111 | error_message = "Cannot flash firmware, printer port was not specified" 112 | self._send_status("flasherror", subtype="port", message=error_message) 113 | return flask.make_response(error_message, 400) 114 | 115 | printer_port = value_source["port"] 116 | 117 | if not "profile" in value_source: 118 | error_message = "Cannot flash firmware, profile index was not specified" 119 | self._send_status("flasherror", subtype="profile", message=error_message) 120 | return flask.make_response(error_message, 400) 121 | 122 | profile_index = value_source["profile"] 123 | 124 | # Save the selected profile 125 | self._logger.info("Firmware update profile index: {}".format(profile_index)) 126 | self._settings.set_int(['_selected_profile'], profile_index) 127 | self._logger.info("Firmware update profile name: {}".format(self.get_profile_setting("_name"))) 128 | 129 | # Save the printer port 130 | self._logger.info("Printer port: {}".format(printer_port)) 131 | if printer_port != "undefined": 132 | self.set_profile_setting("serial_port", printer_port) 133 | 134 | method = self.get_profile_setting("flash_method") 135 | self._logger.info("Flash method: {}".format(method)) 136 | 137 | self._settings.save() 138 | 139 | if method in self._flash_prechecks: 140 | if not self._flash_prechecks[method](self): 141 | if method == "marlinbft": 142 | error_message = "Marlin BINARY_FILE_TRANSFER capability is not supported" 143 | else: 144 | error_message = "Cannot flash firmware, flash method {} is not fully configured".format(method) 145 | self._send_status("flasherror", subtype="method", message=error_message) 146 | return flask.make_response(error_message, 400) 147 | 148 | file_to_flash = None 149 | 150 | input_name = "file" 151 | input_upload_path = input_name + "." + self._settings.global_get(["server", "uploads", "pathSuffix"]) 152 | 153 | if input_upload_path in flask.request.values: 154 | # flash from uploaded file 155 | uploaded_hex_path = flask.request.values[input_upload_path] 156 | 157 | try: 158 | file_to_flash = tempfile.NamedTemporaryFile(mode='r+b', delete=False) 159 | file_to_flash.close() 160 | shutil.move(os.path.abspath(uploaded_hex_path), file_to_flash.name) 161 | except: 162 | if file_to_flash: 163 | try: 164 | os.remove(file_to_flash.name) 165 | except: 166 | self._logger.exception("Error while trying to delete the temporary hex file") 167 | 168 | error_message = "Error while copying the uploaded hex file" 169 | self._send_status("flasherror", subtype="hexfile", message=error_message) 170 | self._logger.exception(error_message) 171 | return flask.make_response(error_message, 500) 172 | 173 | elif "url" in value_source: 174 | # flash from provided URL 175 | url = value_source["url"] 176 | 177 | try: 178 | file_to_flash = tempfile.NamedTemporaryFile(mode='r+b', delete=False) 179 | file_to_flash.close() 180 | 181 | r = requests.get(url, stream=True, timeout=30) 182 | r.raise_for_status() 183 | with open(file_to_flash.name, "wb") as f: 184 | for chunk in r.iter_content(chunk_size=1024): 185 | if chunk: 186 | f.write(chunk) 187 | f.flush() 188 | 189 | except: 190 | if file_to_flash: 191 | try: 192 | os.remove(file_to_flash.name) 193 | except: 194 | self._logger.exception("Error while trying to delete the temporary hex file") 195 | 196 | error_message = "Error while retrieving the hex file from {}".format(url) 197 | self._send_status("flasherror", subtype="hexfile", message=error_message) 198 | self._logger.exception(error_message) 199 | return flask.make_response(error_message, 500) 200 | 201 | else: 202 | return flask.make_response("Neither file nor URL to flash from provided, cannot flash", 400) 203 | 204 | if self._start_flash_process(method, file_to_flash.name, printer_port): 205 | return flask.make_response(NO_CONTENT) 206 | else: 207 | error_message = "Cannot flash firmware, already flashing" 208 | self._send_status("flasherror", subtype="already_flashing") 209 | self._logger.debug(error_message) 210 | return flask.make_response(error_message, 409) 211 | 212 | def _start_flash_process(self, method, hex_file, printer_port): 213 | if self._flash_thread is not None: 214 | return False 215 | 216 | self._flash_thread = threading.Thread(target=self._flash_worker, args=(method, hex_file, printer_port)) 217 | self._flash_thread.daemon = True 218 | self._flash_thread.start() 219 | 220 | return True 221 | 222 | def _flash_worker(self, method, firmware, printer_port): 223 | try: 224 | # Run pre-flash system command 225 | preflash_command = self.get_profile_setting("preflash_commandline") 226 | if preflash_command is not None and self.get_profile_setting_boolean("enable_preflash_commandline"): 227 | self._logger.info("Executing pre-flash commandline '{}'".format(preflash_command)) 228 | try: 229 | r = os.system(preflash_command) 230 | except: 231 | e = sys.exc_info()[0] 232 | self._logger.error("Error executing pre-flash commandline '{}'".format(preflash_command)) 233 | 234 | self._logger.info("Pre-flash command '{}' returned: {}".format(preflash_command, r)) 235 | 236 | # Run pre-flash gcode 237 | preflash_gcode = self.get_profile_setting("preflash_gcode") 238 | if preflash_gcode is not None and self.get_profile_setting_boolean("enable_preflash_gcode"): 239 | if self._printer.is_operational(): 240 | self._logger.info("Sending pre-flash gcode commands: {}".format(preflash_gcode)) 241 | self._printer.commands(preflash_gcode.split(";")) 242 | 243 | preflash_delay = self.get_profile_setting_int("preflash_delay") or 3 244 | if float(preflash_delay) > 0 and self.get_profile_setting_boolean("enable_preflash_delay"): 245 | self._logger.info("Pre-flash delay: {}s".format(preflash_delay)) 246 | time.sleep(float(preflash_delay)) 247 | 248 | else: 249 | self._logger.info("Printer not connected, not sending pre-flash gcode commands") 250 | 251 | try: 252 | self._logger.info("Firmware update started") 253 | 254 | if not method in self._flash_methods: 255 | error_message = "Unsupported flashing method: {}".format(method) 256 | self._logger.error(error_message) 257 | self._send_status("flasherror", message=error_message) 258 | return 259 | 260 | flash_callable = self._flash_methods[method] 261 | if not callable(flash_callable): 262 | error_message = "Don't have a callable for flashing method {}: {!r}".format(method, flash_callable) 263 | self._logger.error(error_message) 264 | self._send_status("flasherror", message=error_message) 265 | return 266 | 267 | reconnect = None 268 | if self._printer.is_operational(): 269 | _, current_port, current_baudrate, current_profile = self._printer.get_current_connection() 270 | reconnect = (current_port, current_baudrate, current_profile) 271 | self._logger.info("Disconnecting from printer") 272 | self._send_status("progress", subtype="disconnecting") 273 | self._printer.disconnect() 274 | 275 | self._send_status("progress", subtype="startingflash") 276 | 277 | try: 278 | if flash_callable(self, firmware=firmware, printer_port=printer_port): 279 | postflash_delay = self.get_profile_setting_int("postflash_delay") or 0 280 | if float(postflash_delay) > 0 and self.get_profile_setting_boolean("enable_postflash_delay"): 281 | self._logger.info("Post-flash delay: {}s".format(postflash_delay)) 282 | self._send_status("progress", subtype="postflashdelay") 283 | time.sleep(float(postflash_delay)) 284 | 285 | message = u"Flashing successful." 286 | self._logger.info(message) 287 | self._console_logger.info(message) 288 | self._send_status("success") 289 | 290 | # Run post-flash commandline 291 | postflash_command = self.get_profile_setting("postflash_commandline") 292 | if postflash_command is not None and self.get_profile_setting_boolean("enable_postflash_commandline"): 293 | self._logger.info("Executing post-flash commandline '{}'".format(postflash_command)) 294 | try: 295 | r = os.system(postflash_command) 296 | except: 297 | e = sys.exc_info()[0] 298 | self._logger.error("Error executing post-flash commandline '{}'".format(postflash_command)) 299 | 300 | self._logger.info("Post-flash command '{}' returned: {}".format(postflash_command, r)) 301 | 302 | # Set run post-flash gcode flag 303 | postflash_gcode = self.get_profile_setting("postflash_gcode") 304 | if postflash_gcode is not None and self.get_profile_setting_boolean("enable_postflash_gcode"): 305 | self._logger.info(u"Setting run_postflash_gcode flag to true") 306 | self.set_profile_setting_boolean("run_postflash_gcode", True) 307 | 308 | else: 309 | self._logger.info(u"No postflash gcode or postflash is disabled, setting run_postflash_gcode to false") 310 | self.set_profile_setting_boolean("run_postflash_gcode", False) 311 | 312 | self._settings.save() 313 | 314 | except: 315 | self._logger.exception(u"Error while attempting to flash") 316 | self._send_status("flasherror") 317 | finally: 318 | try: 319 | os.remove(firmware) 320 | except: 321 | self._logger.exception(u"Could not delete temporary hex file at {}".format(firmware)) 322 | 323 | finally: 324 | self._flash_thread = None 325 | 326 | if self.get_profile_setting_boolean("no_reconnect_after_flash"): 327 | self._logger.info("Automatic reconnection is disabled") 328 | else: 329 | if reconnect is not None: 330 | port, baudrate, profile = reconnect 331 | self._logger.info("Reconnecting to printer: port={}, baudrate={}, profile={}".format(port, baudrate, profile)) 332 | self._send_status("progress", subtype="reconnecting") 333 | self._printer.connect(port=port, baudrate=baudrate, profile=profile) 334 | 335 | except Exception as e: 336 | # Catch and log anything that might happen as we are in separate thread 337 | # and octoprint won't log our failures 338 | self._logger.exception(e) 339 | 340 | # Checks for a valid profile in the plugin's settings 341 | # Returns True if the settings contain one or more profiles, otherwise false 342 | def check_for_profile(self): 343 | # Get all the profiles from the settings 344 | profiles = self._settings.get(["profiles"]) 345 | 346 | # If the profiles aren't an array, make them one 347 | # Catches case when there are no profiles and the defaults are returned 348 | if not isinstance(profiles, list): 349 | profiles = [profiles] 350 | 351 | # If there is only one profile and the name is None there were no real profiles and we have the defaults 352 | if len(profiles) == 1 and profiles[0]["_name"] == None: 353 | return False 354 | else: 355 | return True 356 | 357 | # Gets the settings for the currently-selected profile 358 | # Returns the configured profile settings if one is found at the index, otherwise None 359 | def get_selected_profile(self, **kwargs): 360 | # Get the currently-selected profile index 361 | index = kwargs.pop("index", self._settings.get_int(["_selected_profile"])) 362 | 363 | # Check that the index is valid 364 | if not isinstance(index, int) or index < 0: 365 | self._logger.warn("Invalid profile index '{}' specified".format(index)) 366 | return None 367 | 368 | # Check that there is a valid profile in the settings 369 | if not self.check_for_profile(): 370 | self._logger.warn("No profiles configured") 371 | return None 372 | 373 | # Get all the profiles from the settings 374 | profiles = self._settings.get(["profiles"]) 375 | 376 | # If the profiles aren't an array, make them one 377 | if not isinstance(profiles, list): 378 | profiles = [profiles] 379 | 380 | # Check if the index is within the set of profiles; return the profile if it is, otherwise return None 381 | if len(profiles) >= index: 382 | return profiles[index] 383 | else: 384 | self._logger.warn("Profile with index {} not found. {} profiles are configured.".format(index, len(profiles))) 385 | return None 386 | 387 | # Gets all the settings for a profile - specified values and default values 388 | # Merges the profile settings with the default settings and returns the complete set 389 | def get_profile_settings(self): 390 | # Get the selected profile's configured settings 391 | profile_settings = self.get_selected_profile() 392 | 393 | # Check if the profile is valid 394 | if profile_settings != None: 395 | # Get the profile defaults 396 | profile_defaults = self.get_settings_defaults()["_profiles"] 397 | 398 | # Merge the profile settings with the defaults 399 | profile = dict_merge(profile_defaults, profile_settings) 400 | 401 | # Return the superset of settings 402 | return profile 403 | else: 404 | return None 405 | 406 | # Gets the value of a specified setting from the profile 407 | # Returns the value or None if the given key was not found in the profile 408 | def get_profile_setting(self, key): 409 | # Check if the key is valid 410 | if key != None: 411 | # Get the superset of profile settings 412 | profile = self.get_profile_settings() 413 | 414 | # Check if the profile is valid 415 | if profile == None: 416 | return None 417 | 418 | # Check if the key is present in the profile 419 | if key in profile.keys(): 420 | # Return the value 421 | return profile[key] 422 | else: 423 | return None 424 | else: 425 | return None 426 | 427 | # Gets the integer value of a specified setting from the profile 428 | # Returns the value or None if the given key was not found in the profile or is not an integer 429 | def get_profile_setting_int(self, key, **kwargs): 430 | minimum = kwargs.pop("min", None) 431 | maximum = kwargs.pop("max", None) 432 | 433 | value = self.get_profile_setting(key) 434 | if value is None: 435 | return None 436 | 437 | try: 438 | intValue = int(value) 439 | 440 | if minimum is not None and intValue < minimum: 441 | return minimum 442 | elif maximum is not None and intValue > maximum: 443 | return maximum 444 | else: 445 | return intValue 446 | except ValueError: 447 | self._logger.warning( 448 | "Could not convert %r to a valid integer when getting option %r" 449 | % (value, key) 450 | ) 451 | return None 452 | 453 | # Gets the boolean value of a specified setting from the profile 454 | # Returns the value or None if the given key was not found in the profile or is cannot be parsed as a boolean 455 | def get_profile_setting_boolean(self, key): 456 | value = self.get_profile_setting(key) 457 | if value is None: 458 | return None 459 | if isinstance(value, bool): 460 | return value 461 | if isinstance(value, (int, float)): 462 | return value != 0 463 | if isinstance(value, basestring): 464 | return value.lower() in valid_boolean_trues 465 | return value is not None 466 | 467 | 468 | # Sets the specified value in the profile 469 | def set_profile_setting(self, key, value): 470 | # Get the current value 471 | current_value = self.get_profile_setting(key) 472 | 473 | # Check if the new value matches the current value 474 | if current_value == value: 475 | # Don't need to modify a setting which isn't changing 476 | return 477 | 478 | # Get the default value 479 | default_value = self.get_settings_defaults()["_profiles"][key] 480 | 481 | # Get all the profile settings 482 | profiles = self._settings.get(["profiles"]) 483 | 484 | # Check if the new value matches the default 485 | if default_value == value: 486 | # Don't need to store default values so remove the setting from the profile 487 | del profiles[self._settings.get_int(["_selected_profile"])][key] 488 | else: 489 | # Update this setting in the profile 490 | profiles[self._settings.get_int(["_selected_profile"])][key] = value 491 | 492 | # Save the settings 493 | profiles = self._settings.set(["profiles"], profiles) 494 | 495 | # Sets the specified int value in the profile 496 | def set_profile_setting_int(self, key, value, **kwargs): 497 | if value is None: 498 | self.set_profile_setting(key, None) 499 | return 500 | 501 | minimum = kwargs.pop("min", None) 502 | maximum = kwargs.pop("max", None) 503 | 504 | try: 505 | intValue = int(value) 506 | 507 | if minimum is not None and intValue < minimum: 508 | intValue = minimum 509 | if maximum is not None and intValue > maximum: 510 | intValue = maximum 511 | except ValueError: 512 | self._logger.warning( 513 | "Could not convert %r to a valid integer when setting option %r" 514 | % (value, key) 515 | ) 516 | return 517 | 518 | self.set_profile_setting(key, intValue) 519 | 520 | # Sets the specified boolean value in the profile 521 | def set_profile_setting_boolean(self, key, value): 522 | if value is None or isinstance(value, bool): 523 | self.set_profile_setting(key, value) 524 | elif isinstance(value, basestring) and value.lower() in valid_boolean_trues: 525 | self.set_profile_setting(key, True) 526 | else: 527 | self.set_profile_setting(key, False) 528 | 529 | # Gets the last BFT filename for the current profile 530 | def get_lastbft_filename(self): 531 | profile_id = self.get_profile_setting_int("_id") 532 | if profile_id != None: 533 | filenames = self._settings.get(["last_bft_filenames"]) 534 | if filenames == None: 535 | return None 536 | if profile_id in filenames.keys(): 537 | return filenames[profile_id] 538 | elif str(profile_id) in filenames.keys(): 539 | return filenames[str(profile_id)] 540 | else: 541 | return None 542 | else: 543 | return None 544 | 545 | # Sets the last BFT filename for the current profile 546 | def set_lastbft_filename(self, value): 547 | profile_id = self.get_profile_setting_int("_id") 548 | last_bft_filenames = self._settings.get(["last_bft_filenames"]) 549 | last_bft_filenames[profile_id] = value 550 | self._settings.set(["last_bft_filenames"], last_bft_filenames) 551 | 552 | # Send capability information to the UI 553 | def _send_capability(self, capability, enabled): 554 | self._plugin_manager.send_plugin_message(self._identifier, dict(type="capability", capability=capability, enabled=enabled)) 555 | 556 | # Send status messages to the UI 557 | def _send_status(self, status, subtype=None, message=None): 558 | self._plugin_manager.send_plugin_message(self._identifier, dict(type="status", status=status, subtype=subtype, message=message)) 559 | 560 | #~~ SettingsPlugin API 561 | def get_settings_defaults(self): 562 | return { 563 | "_selected_profile": None, 564 | "_plugin_version": self._plugin_version, 565 | "enable_navbar": False, 566 | "enable_profiles": False, 567 | "save_url": False, 568 | "has_bftcapability": False, 569 | "has_binproto2package": False, 570 | "disable_filefilter": False, 571 | "prevent_connection_when_flashing": True, 572 | "maximum_fw_size_kb": 5120, 573 | "last_bft_filenames": {}, 574 | "profiles": {}, 575 | "_profiles": { 576 | "_id": None, 577 | "_name": None, 578 | "flash_method": None, 579 | "disable_bootloadercheck": False, 580 | "last_url": None, 581 | "avrdude_path": None, 582 | "avrdude_conf": None, 583 | "avrdude_avrmcu": None, 584 | "avrdude_programmer": None, 585 | "avrdude_baudrate": None, 586 | "avrdude_disableverify": False, 587 | "avrdude_commandline": "{avrdude} -v -q -p {mcu} -c {programmer} -P {port} -D -C {conffile} -b {baudrate} {disableverify} -U flash:w:{firmware}:i", 588 | "bootcmdr_path": None, 589 | "bootcmdr_preflashreset": True, 590 | "bootcmdr_commandline": "{bootcommander} -d={port} -b={baudrate} {firmware}", 591 | "bootcmdr_baudrate": 115200, 592 | "bootcmdr_command_timeout": 30, 593 | "bossac_path": None, 594 | "bossac_commandline": "{bossac} -i -p {port} -U true -e -w {disableverify} -b {firmware} -R", 595 | "bossac_disableverify": False, 596 | "dfuprog_path": None, 597 | "dfuprog_avrmcu": None, 598 | "dfuprog_commandline": "sudo {dfuprogrammer} {mcu} flash {firmware} --debug-level 10", 599 | "dfuprog_erasecommandline": "sudo {dfuprogrammer} {mcu} erase --debug-level 10 --force", 600 | "dfuutil_path": None, 601 | "dfuutil_commandline": "sudo {dfuutil} -a 0 -s 0x8000000:leave -D {firmware}", 602 | "esptool_path": None, 603 | "esptool_chip": "auto", 604 | "esptool_address": "0x10000", 605 | "esptool_baudrate": 921600, 606 | "esptool_commandline": "{esptool} -p {port} -c {chip} -b {baud} --before default_reset --after hard_reset write_flash -z -fm dio {address} {firmware}", 607 | "stm32flash_path": None, 608 | "stm32flash_verify": True, 609 | "stm32flash_boot0pin": "rts", 610 | "stm32flash_boot0low": False, 611 | "stm32flash_resetpin": "dtr", 612 | "stm32flash_resetlow": True, 613 | "stm32flash_execute": True, 614 | "stm32flash_executeaddress": "0x8000000", 615 | "stm32flash_reset": False, 616 | "lpc1768_path": None, 617 | "lpc1768_unmount_command": "sudo umount {mountpoint}", 618 | "lpc1768_preflashreset": True, 619 | "lpc1768_no_m997_reset_wait": False, 620 | "lpc1768_no_m997_restart_wait": False, 621 | "lpc1768_use_custom_filename": False, 622 | "lpc1768_custom_filename": "firmware.bin", 623 | "lpc1768_timestamp_filenames": False, 624 | "lpc1768_last_filename": None, 625 | "marlinbft_waitafterconnect": 0, 626 | "marlinbft_timeout": 1000, 627 | "marlinbft_progresslogging": False, 628 | "marlinbft_alt_reset": False, 629 | "marlinbft_m997_reset_wait": 10, 630 | "marlinbft_m997_restart_wait": 20, 631 | "marlinbft_no_m997_reset_wait": False, 632 | "marlinbft_no_m997_restart_wait": False, 633 | "marlinbft_use_custom_filename": False, 634 | "marlinbft_custom_filename": "firmware.bin", 635 | "marlinbft_timestamp_filenames": False, 636 | "marlinbft_last_filename": None, 637 | "marlinbft_got_start": False, 638 | "postflash_delay": 0, 639 | "preflash_delay": 3, 640 | "postflash_gcode": None, 641 | "preflash_gcode": None, 642 | "run_postflash_gcode": False, 643 | "preflash_commandline": None, 644 | "postflash_commandline": None, 645 | "enable_preflash_commandline": False, 646 | "enable_postflash_commandline": False, 647 | "enable_postflash_delay": False, 648 | "enable_preflash_delay": False, 649 | "enable_postflash_gcode": False, 650 | "enable_preflash_gcode": False, 651 | "disable_bootloadercheck": False, 652 | "no_reconnect_after_flash": False, 653 | "serial_port": None, 654 | }, 655 | } 656 | 657 | def get_settings_version(self): 658 | return 3 659 | 660 | def on_settings_migrate(self, target, current=None): 661 | if current is None or current < 2: 662 | # Migrate single printer settings to a profile 663 | self._logger.info("Migrating plugin settings to a profile") 664 | 665 | # Create a new empty array of printer profiles 666 | profiles_new = [] 667 | 668 | # Get a dictionary of the default printer profile settings 669 | settings_dict = self.get_settings_defaults()["_profiles"] 670 | 671 | # Get the names of all the printer profile settings 672 | keys = self.get_settings_defaults()["_profiles"].keys() 673 | 674 | # Iterate over each setting in the defaults 675 | for key in keys: 676 | # Get the current value 677 | value = self._settings.get([key]) 678 | 679 | # Get the default value 680 | default_value = settings_dict[key] 681 | 682 | # If the current value is an empty string, and the default is 'None' set the value to 'None' 683 | if (value == "" and settings_dict[key] == None): 684 | value = None 685 | 686 | # If the current value is None, and the default is a string set the value to the default 687 | if (value == None and settings_dict[key] != None): 688 | value = settings_dict[key] 689 | 690 | # If the current value is a number stored it as a string, convert it to a number 691 | try: 692 | # Python 3 compatible 693 | if isinstance(value, str) and value.isnumeric(): 694 | value = int(value) 695 | except: 696 | try: 697 | # Python 2 compatible 698 | uvalue = unicode(value) 699 | if isinstance(uvalue, unicode) and uvalue.isnumeric(): 700 | value = int(uvalue) 701 | except: 702 | self._logger.warn(u"{}: unable to convert '{}' to a numeric value. Will be reset to default.".format(key, value)) 703 | 704 | 705 | # If the the default value is a number but the current value is not, reset the value to the default 706 | if isinstance(default_value, int) and not isinstance(value, int): 707 | self._logger.warn(u"{}: current value '{}' should be a number but isn't, resetting to default value of '{}'".format(key, value, default_value)) 708 | value = default_value 709 | 710 | # If the current value isn't the same as the default value, set the value otherwise delete it (so we don't set things to their default unnecessarily) 711 | if (value != settings_dict[key]): 712 | self._logger.info(u"{}: {} (default is '{}')".format(key, value, default_value)) 713 | settings_dict[key] = value 714 | else: 715 | del settings_dict[key] 716 | 717 | self._settings.set([key], None) 718 | 719 | # Give the new profile a default ID and name 720 | settings_dict["_id"] = 0 721 | settings_dict["_name"] = "Default" 722 | 723 | # Append the new profile and save the settings 724 | profiles_new.append(settings_dict) 725 | self._settings.set(['profiles'], profiles_new) 726 | 727 | # Set the profile to the new one 728 | self._settings.set_int(['_selected_profile'], 0) 729 | 730 | elif current == 2: 731 | profiles_new = [] 732 | last_bft_filenames_new = {} 733 | # Loop through the profiles 734 | for index, profile in enumerate(self._settings.get(['profiles'])): 735 | self._logger.info("Migrating settings for profile {}: {}".format(index, profile["_name"])) 736 | # Set the id to the index 737 | profile["_id"] = index 738 | 739 | # Migrate the last BFT filesnames 740 | if "marlinbft_last_filename" in profile and profile["marlinbft_last_filename"] is not None: 741 | last_bft_filenames_new.update({index: profile["marlinbft_last_filename"]}) 742 | del profile["marlinbft_last_filename"] 743 | 744 | profiles_new.append(profile) 745 | 746 | self._settings.set(['last_bft_filenames'],last_bft_filenames_new) 747 | self._settings.set(['profiles'],profiles_new) 748 | 749 | #~~ EventHandlerPlugin API 750 | def on_event(self, event, payload): 751 | # Only handle the CONNECTED event 752 | if event == Events.CONNECTED: 753 | self._logger.info("Got CONNECTED event") 754 | 755 | # Check if the current profile has the postflash gcode flag set 756 | if self.get_profile_setting_boolean("run_postflash_gcode"): 757 | self._logger.info("Run postflash gcode flag is set") 758 | 759 | # Get the postflash gcode from the profile 760 | postflash_gcode = self.get_profile_setting("postflash_gcode") 761 | 762 | # If there is something to send, send it 763 | if postflash_gcode is not None: 764 | self._logger.info("Sending post-flash commands: {}".format(postflash_gcode)) 765 | self._printer.commands(postflash_gcode.split(";")) 766 | 767 | # Clear the postflash gcode flag 768 | self._logger.info("Clearing postflash gcode flag") 769 | self.set_profile_setting_boolean("run_postflash_gcode", False) 770 | self._settings.save() 771 | 772 | else: 773 | self._logger.info("Run postflash flag is not set") 774 | 775 | #~~ AssetPlugin API 776 | def get_assets(self): 777 | return dict( 778 | js=["js/firmwareupdater.js"], 779 | css=["css/firmwareupdater.css"] 780 | ) 781 | 782 | #~~ Hook handlers 783 | ##~~ Capabilites hook 784 | def firmware_capability_hook(self, comm_instance, capability, enabled, already_defined): 785 | del comm_instance, already_defined 786 | if capability.lower() == "BINARY_FILE_TRANSFER".lower(): 787 | self._logger.info("Setting BINARY_FILE_TRANSFER capability to %s" % (enabled)) 788 | self._settings.set_boolean(["has_bftcapability"], enabled) 789 | self._settings.save() 790 | self._send_capability("BINARY_FILE_TRANSFER", enabled) 791 | 792 | ##~~ Bodysize hook 793 | def bodysize_hook(self, current_max_body_sizes, *args, **kwargs): 794 | # Max size is (maximum_fw_size_kb * 1024) + 1024B to allow for API overhead 795 | max_size = (self._settings.get(["maximum_fw_size_kb"]) * 1024) + 1024 796 | self._logger.info("Setting maximum upload size for /flash to %s" % (max_size)) 797 | return [("POST", r"/flash", max_size)] 798 | 799 | ##~~ Connect hook 800 | def handle_connect_hook(self, *args, **kwargs): 801 | if self._settings.get_boolean(["prevent_connection_when_flashing"]) and self._flash_thread: 802 | self._logger.info("Flash in progress, preventing connection to printer") 803 | return True 804 | else: 805 | return False 806 | 807 | ##~~ Comm Hook 808 | def check_for_start(self, comm, line, *args, **kwargs): 809 | if line.strip().strip("\0") == "start" and self._flash_thread: 810 | self._logger.info("Got start event while flashing in progress") 811 | self.set_profile_setting_boolean("marlinbft_got_start", True) 812 | else: 813 | return line 814 | 815 | ##~~ Update hook 816 | def update_hook(self): 817 | return dict( 818 | firmwareupdater=dict( 819 | displayName="Firmware Updater", 820 | displayVersion=self._plugin_version, 821 | 822 | # version check: github repository 823 | type="github_release", 824 | user="OctoPrint", 825 | repo="OctoPrint-FirmwareUpdater", 826 | current=self._plugin_version, 827 | 828 | # stable releases 829 | stable_branch=dict( 830 | name="Stable", 831 | branch="master", 832 | comittish=["master"] 833 | ), 834 | 835 | # release candidates 836 | prerelease_branches=[ 837 | dict( 838 | name="Release Candidate", 839 | branch="rc", 840 | comittish=["rc", "master"], 841 | ), 842 | dict( 843 | name="Development", 844 | branch="devel", 845 | comittish=["devel", "rc", "master"], 846 | ) 847 | ], 848 | 849 | # update method: pip 850 | pip="https://github.com/OctoPrint/OctoPrint-FirmwareUpdater/archive/{target_version}.zip" 851 | ) 852 | ) 853 | 854 | def is_blueprint_csrf_protected(self): 855 | return True 856 | 857 | class FlashException(Exception): 858 | def __init__(self, reason, *args, **kwargs): 859 | Exception.__init__(self, *args, **kwargs) 860 | self.reason = reason 861 | 862 | __plugin_name__ = "Firmware Updater" 863 | __plugin_pythoncompat__ = ">=2.7,<4" 864 | 865 | def __plugin_load__(): 866 | global __plugin_implementation__ 867 | global __plugin_hooks__ 868 | 869 | __plugin_implementation__ = FirmwareupdaterPlugin() 870 | 871 | __plugin_hooks__ = { 872 | "octoprint.server.http.bodysize": __plugin_implementation__.bodysize_hook, 873 | "octoprint.plugin.softwareupdate.check_config": __plugin_implementation__.update_hook, 874 | "octoprint.comm.protocol.firmware.capabilities": __plugin_implementation__.firmware_capability_hook, 875 | "octoprint.printer.handle_connect": __plugin_implementation__.handle_connect_hook, 876 | "octoprint.comm.protocol.gcode.received": __plugin_implementation__.check_for_start, 877 | } 878 | -------------------------------------------------------------------------------- /octoprint_firmwareupdater/methods/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /octoprint_firmwareupdater/methods/avrdude.py: -------------------------------------------------------------------------------- 1 | import re 2 | import os 3 | import sarge 4 | import serial 5 | import time 6 | 7 | try: 8 | import serial.tools.list_ports 9 | from serial.tools import list_ports 10 | except ImportError: 11 | exit("This requires serial module\nInstall with: sudo pip install pyserial") 12 | 13 | AVRDUDE_WRITING = "writing flash" 14 | AVRDUDE_VERIFYING = "reading on-chip flash data" 15 | AVRDUDE_TIMEOUT = "timeout communicating with programmer" 16 | AVRDUDE_ERROR = "ERROR:" 17 | AVRDUDE_ERROR_SYNC = "not in sync" 18 | AVRDUDE_ERROR_VERIFICATION = "verification error" 19 | AVRDUDE_ERROR_DEVICE = "can't open device" 20 | 21 | WINDOWS_PATTERN = "^[A-z]\:\\\\.+.exe$" 22 | POSIX_PATTERN = "^(\/[^\0/]+)+$" 23 | 24 | USB_VID_PID_MK2 = "2c99:0001" 25 | USB_VID_PID_MK3 = "2c99:0002" 26 | USB_VID_PID_MMU_BOOT = "2c99:0003" 27 | USB_VID_PID_MMU_APP = "2c99:0004" 28 | USB_VID_PID_CW1_BOOT = "2c99:0007" 29 | USB_VID_PID_CW1_APP = "2c99:0008" 30 | 31 | TARGET_NO_PRUSA = 0 32 | TARGET_MMU = 1 33 | TARGET_CW1 = 2 34 | 35 | ser = serial 36 | 37 | def _check_avrdude(self): 38 | avrdude_path = self.get_profile_setting("avrdude_path") 39 | avrdude_avrmcu = self.get_profile_setting("avrdude_avrmcu") 40 | avrdude_programmer = self.get_profile_setting("avrdude_programmer") 41 | 42 | if os.name == 'nt': 43 | pattern = re.compile(WINDOWS_PATTERN) 44 | else: 45 | pattern = re.compile(POSIX_PATTERN) 46 | 47 | if not pattern.match(avrdude_path): 48 | self._logger.error(u"Path to avrdude is not valid: {path}".format(path=avrdude_path)) 49 | return False 50 | elif not os.path.exists(avrdude_path): 51 | self._logger.error(u"Path to avrdude does not exist: {path}".format(path=avrdude_path)) 52 | return False 53 | elif not os.path.isfile(avrdude_path): 54 | self._logger.error(u"Path to avrdude is not a file: {path}".format(path=avrdude_path)) 55 | return False 56 | elif not os.access(avrdude_path, os.X_OK): 57 | self._logger.error(u"Path to avrdude is not executable: {path}".format(path=avrdude_path)) 58 | return False 59 | elif not avrdude_avrmcu: 60 | self._logger.error(u"AVR MCU type has not been selected.") 61 | return False 62 | elif not avrdude_programmer: 63 | self._logger.error(u"AVR programmer has not been selected.") 64 | return False 65 | else: 66 | return True 67 | 68 | def _flash_avrdude(self, firmware=None, printer_port=None, **kwargs): 69 | assert(firmware is not None) 70 | assert(printer_port is not None) 71 | 72 | avrdude_path = self.get_profile_setting("avrdude_path") 73 | avrdude_conf = self.get_profile_setting("avrdude_conf") 74 | avrdude_avrmcu = self.get_profile_setting("avrdude_avrmcu") 75 | avrdude_programmer = self.get_profile_setting("avrdude_programmer") 76 | avrdude_baudrate = self.get_profile_setting("avrdude_baudrate") 77 | avrdude_disableverify = self.get_profile_setting_boolean("avrdude_disableverify") 78 | 79 | working_dir = os.path.dirname(avrdude_path) 80 | 81 | avrdude_command = self.get_profile_setting("avrdude_commandline") 82 | avrdude_command = avrdude_command.replace("{avrdude}", avrdude_path) 83 | avrdude_command = avrdude_command.replace("{mcu}", avrdude_avrmcu) 84 | avrdude_command = avrdude_command.replace("{programmer}", avrdude_programmer) 85 | 86 | if avrdude_conf is not None and avrdude_conf != "": 87 | avrdude_command = avrdude_command.replace("{conffile}", avrdude_conf) 88 | else: 89 | avrdude_command = avrdude_command.replace(" -C {conffile} ", " ") 90 | 91 | if avrdude_baudrate is not None and avrdude_baudrate != "": 92 | avrdude_command = avrdude_command.replace("{baudrate}", str(avrdude_baudrate)) 93 | else: 94 | avrdude_command = avrdude_command.replace(" -b {baudrate} ", " ") 95 | 96 | if avrdude_disableverify: 97 | avrdude_command = avrdude_command.replace("{disableverify}", "-V") 98 | else: 99 | avrdude_command = avrdude_command.replace(" {disableverify} ", " ") 100 | 101 | if avrdude_programmer is not None and avrdude_programmer == "avr109": 102 | self._logger.info(u"Avrdude_programmer is avr109, check if Prusa MMU or CW1 to be flashed") 103 | 104 | target = TARGET_NO_PRUSA 105 | 106 | list_ports.comports() 107 | 108 | try: 109 | app_port_name = list(list_ports.grep(USB_VID_PID_MMU_APP))[0][0] 110 | self._logger.info(u"MMU found {portname}".format(portname=app_port_name)) 111 | target = TARGET_MMU 112 | self._logger.info(u"Patch MMU2 firmware file if necessary") 113 | try: 114 | with open(firmware,"r+") as f: 115 | lines = f.readlines() 116 | f.seek(0) 117 | for i in lines: 118 | if i.strip("\n") != "; device = mm-control" and i != '\n': 119 | f.write(i) 120 | f.truncate() 121 | f.close() 122 | except: 123 | self._logger.info(u"Opening MMU2 firmware file failed") 124 | raise FlashException("Patching MMU firmware file failed") 125 | except: 126 | self._logger.info(u"Target ist not MMU") 127 | 128 | try: 129 | app_port_name = list(list_ports.grep(USB_VID_PID_CW1_APP))[0][0] 130 | self._logger.info(u"CW1 found {portname}".format(portname=app_port_name)) 131 | target = TARGET_CW1 132 | self._logger.info(u"Patch CW1 firmware file if necessary") 133 | try: 134 | with open(firmware,"r+") as f: 135 | lines = f.readlines() 136 | f.seek(0) 137 | for i in lines: 138 | if i.strip("\n") != "; device = cw1" and i != '\n': 139 | f.write(i) 140 | f.truncate() 141 | f.close() 142 | except: 143 | self._logger.info(u"Opening CW1 firmware file failed") 144 | raise FlashException("Patching CW1 firmware file failed") 145 | except: 146 | self._logger.info(u"Target ist not CW1") 147 | 148 | if target != TARGET_NO_PRUSA: 149 | try: 150 | ser = serial.Serial(printer_port, 1200, timeout = 1) 151 | self._logger.info(u"Reset target") 152 | time.sleep(0.05) 153 | ser.close() 154 | except serial.SerialException: 155 | self._logger.info(u"Serial port could not been serviced") 156 | raise FlashException("Error resetting target") 157 | 158 | time.sleep(3) 159 | 160 | list_ports.comports() 161 | 162 | if target == TARGET_MMU: 163 | try: 164 | boot_port_name = list(list_ports.grep(USB_VID_PID_MMU_BOOT))[0][0] 165 | self._logger.info(u"MMU in bootloader") 166 | printer_port = boot_port_name 167 | except: 168 | self._logger.info(u"MMU not in bootloader") 169 | raise FlashException("Reboot MMU to bootloader failed") 170 | elif target == TARGET_CW1: 171 | try: 172 | boot_port_name = list(list_ports.grep(USB_VID_PID_CW1_BOOT))[0][0] 173 | self._logger.info(u"CW1 in bootloader") 174 | printer_port = boot_port_name 175 | except: 176 | self._logger.info(u"CW1 not in bootloader") 177 | raise FlashException("Reboot CW1 to bootloader failed") 178 | 179 | avrdude_command = avrdude_command.replace("{port}", printer_port) 180 | avrdude_command = avrdude_command.replace("{firmware}", firmware) 181 | 182 | self._logger.info(u"Running '{}' in {}".format(avrdude_command, working_dir)) 183 | self._console_logger.info(u"") 184 | self._console_logger.info(avrdude_command) 185 | 186 | try: 187 | p = sarge.run(avrdude_command, cwd=working_dir, async_=True, stdout=sarge.Capture(), stderr=sarge.Capture()) 188 | p.wait_events() 189 | 190 | while p.returncode is None: 191 | output = p.stderr.read(timeout=0.5).decode('utf-8') 192 | if not output: 193 | p.commands[0].poll() 194 | continue 195 | 196 | for line in output.split("\n"): 197 | if line.endswith("\r"): 198 | line = line[:-1] 199 | self._console_logger.info(u"> {}".format(line)) 200 | 201 | if AVRDUDE_WRITING in output: 202 | self._logger.info(u"Writing memory...") 203 | self._send_status("progress", subtype="writing") 204 | elif AVRDUDE_VERIFYING in output: 205 | self._logger.info(u"Verifying memory...") 206 | self._send_status("progress", subtype="verifying") 207 | elif AVRDUDE_TIMEOUT in output: 208 | p.commands[0].kill() 209 | p.close() 210 | raise FlashException("Timeout communicating with programmer") 211 | elif AVRDUDE_ERROR_DEVICE in output: 212 | p.commands[0].kill() 213 | p.close() 214 | raise FlashException("Error opening serial device") 215 | elif AVRDUDE_ERROR_VERIFICATION in output: 216 | p.commands[0].kill() 217 | p.close() 218 | raise FlashException("Error verifying flash") 219 | elif AVRDUDE_ERROR_SYNC in output: 220 | p.commands[0].kill() 221 | p.close() 222 | raise FlashException("Avrdude says: 'not in sync" + output[output.find(AVRDUDE_ERROR_SYNC) + len(AVRDUDE_ERROR_SYNC):].strip() + "'") 223 | elif AVRDUDE_ERROR in output: 224 | raise FlashException("Avrdude error: " + output[output.find(AVRDUDE_ERROR) + len(AVRDUDE_ERROR):].strip()) 225 | 226 | if p.returncode == 0: 227 | return True 228 | else: 229 | raise FlashException("Avrdude returned code {returncode}".format(returncode=p.returncode)) 230 | 231 | except FlashException as ex: 232 | self._logger.error(u"Flashing failed. {error}.".format(error=ex.reason)) 233 | self._send_status("flasherror", message=ex.reason) 234 | return False 235 | except: 236 | self._logger.exception(u"Flashing failed. Unexpected error.") 237 | self._send_status("flasherror") 238 | return False 239 | 240 | class FlashException(Exception): 241 | def __init__(self, reason, *args, **kwargs): 242 | Exception.__init__(self, *args, **kwargs) 243 | self.reason = reason 244 | -------------------------------------------------------------------------------- /octoprint_firmwareupdater/methods/bootcmdr.py: -------------------------------------------------------------------------------- 1 | import re 2 | import os 3 | import sarge 4 | import serial 5 | import time 6 | 7 | CONNECTING = "Connecting to target bootloader" 8 | ERASING = "Erasing" 9 | WRITING = "Programming" 10 | FINISHING = "Finishing" 11 | LOADING = "Loading firmware data from file" 12 | BACKDOOR = "Attempting backdoor entry" 13 | 14 | current_baudrate = None 15 | 16 | def _check_bootcmdr(self): 17 | bootcmdr_path = self.get_profile_setting("bootcmdr_path") 18 | pattern = re.compile("^(\/[^\0/]+)+$") 19 | 20 | if not pattern.match(bootcmdr_path): 21 | self._logger.error(u"Path to BootCommander is not valid: {path}".format(path=bootcmdr_path)) 22 | return False 23 | elif bootcmdr_path is None: 24 | self._logger.error(u"Path to BootCommander is not set.") 25 | return False 26 | if not os.path.exists(bootcmdr_path): 27 | self._logger.error(u"Path to BootCommander does not exist: {path}".format(path=bootcmdr_path)) 28 | return False 29 | elif not os.path.isfile(bootcmdr_path): 30 | self._logger.error(u"Path to BootCommander is not a file: {path}".format(path=bootcmdr_path)) 31 | return False 32 | elif not os.access(bootcmdr_path, os.X_OK): 33 | self._logger.error(u"Path to BootCommander is not executable: {path}".format(path=bootcmdr_path)) 34 | return False 35 | elif not self._printer.is_operational(): 36 | self._logger.error("Printer is not connected") 37 | self._send_status("flasherror", subtype="notconnected") 38 | return False 39 | else: 40 | global current_baudrate 41 | _, current_port, current_baudrate, current_profile = self._printer.get_current_connection() 42 | return True 43 | 44 | def _flash_bootcmdr(self, firmware=None, printer_port=None, **kwargs): 45 | assert(firmware is not None) 46 | assert(printer_port is not None) 47 | assert(current_baudrate is not None) 48 | 49 | bootcmdr_path = self.get_profile_setting("bootcmdr_path") 50 | bootcmdr_baudrate = self.get_profile_setting("bootcmdr_baudrate") 51 | bootcmdr_command_timeout = self.get_profile_setting("bootcmdr_command_timeout") 52 | if not bootcmdr_command_timeout or bootcmdr_command_timeout < 10 or bootcmdr_command_timeout > 180: 53 | self._logger.warn(u"BootCommander command timeout '{}' is invalid. Defaulting to 30s.".format(bootcmdr_command_timeout)) 54 | self.set_profile_setting_int("bootcmdr_command_timeout", 30) 55 | self._settings.save() 56 | bootcmdr_command_timeout = 30 57 | 58 | working_dir = os.path.dirname(bootcmdr_path) 59 | 60 | bootcmdr_command = self.get_profile_setting("bootcmdr_commandline") 61 | bootcmdr_command = bootcmdr_command.replace("{bootcommander}", bootcmdr_path) 62 | bootcmdr_command = bootcmdr_command.replace("{port}", printer_port) 63 | bootcmdr_command = bootcmdr_command.replace("{baudrate}", str(bootcmdr_baudrate)) 64 | bootcmdr_command = bootcmdr_command.replace("{firmware}", firmware) 65 | 66 | self._logger.info(u"Running '{}' in {}".format(bootcmdr_command, working_dir)) 67 | self._console_logger.info(bootcmdr_command) 68 | 69 | try: 70 | starttime = time.time() 71 | connecting = False 72 | reset = False 73 | p = sarge.run(bootcmdr_command, cwd=working_dir, async_=True, stdout=sarge.Capture(buffer_size=1), stderr=sarge.Capture(buffer_size=1)) 74 | p.wait_events() 75 | 76 | while p.returncode is None: 77 | output = p.stdout.read(timeout=0.02).decode('utf-8') 78 | if not output: 79 | p.commands[0].poll() 80 | if (connecting and time.time() > (starttime + bootcmdr_command_timeout)): 81 | self._logger.error(u"Timeout waiting for command to complete") 82 | p.commands[0].kill() 83 | if connecting: 84 | raise FlashException("Connection timeout") 85 | continue 86 | 87 | for line in output.split("\n"): 88 | if line.endswith("\r"): 89 | line = line[:-1] 90 | self._console_logger.info(u"> {}".format(line)) 91 | 92 | if WRITING in line: 93 | connecting = False 94 | reset = False 95 | self._logger.info(u"Writing memory...") 96 | self._send_status("progress", subtype="writing") 97 | if CONNECTING in line: 98 | connecting = True 99 | reset = False 100 | self._logger.info(u"Connecting to bootloader...") 101 | self._send_status("progress", subtype="connecting") 102 | if BACKDOOR in line: 103 | connecting = True 104 | reset = True 105 | self._logger.info(u"Connecting to backdoor...") 106 | self._send_status("progress", subtype="backdoor") 107 | if ERASING in line: 108 | connecting = False 109 | reset = False 110 | self._logger.info(u"Erasing memory...") 111 | self._send_status("progress", subtype="erasing") 112 | if FINISHING in line: 113 | connecting = False 114 | reset = False 115 | self._logger.info(u"Finishing programming...") 116 | self._send_status("progress", subtype="finishing") 117 | 118 | if connecting and reset and self.get_profile_setting_boolean("bootcmdr_preflashreset"): 119 | reset = False 120 | self._logger.info(u"Attempting to reset the board") 121 | self._send_status("progress", subtype="boardreset") 122 | if not _reset_board(self, printer_port, current_baudrate): 123 | raise FlashException("Reset failed") 124 | time.sleep(2) 125 | 126 | if p.returncode == 0: 127 | time.sleep(2) 128 | return True 129 | else: 130 | raise FlashException("BootCommander returned code {returncode}".format(returncode=p.returncode)) 131 | 132 | except FlashException as ex: 133 | self._logger.error(u"Flashing failed. {error}.".format(error=ex.reason)) 134 | self._send_status("flasherror", message=ex.reason) 135 | return False 136 | except: 137 | self._logger.exception(u"Flashing failed. Unexpected error.") 138 | self._send_status("flasherror") 139 | return False 140 | 141 | def _reset_board(self, printer_port=None, baudrate=None): 142 | assert(printer_port is not None) 143 | assert(baudrate is not None) 144 | 145 | self._logger.info(u"Resetting printer at '{port}'".format(port=printer_port)) 146 | 147 | try: 148 | ser = serial.Serial(printer_port, baudrate, timeout=1) 149 | ser.write(b'reset\r\n') 150 | ser.write(b'M997\r\n') 151 | ser.flush() 152 | ser.close() 153 | except serial.SerialException: 154 | self._logger.error(u"Board reset failed") 155 | return False 156 | 157 | return True 158 | 159 | class FlashException(Exception): 160 | def __init__(self, reason, *args, **kwargs): 161 | Exception.__init__(self, *args, **kwargs) 162 | self.reason = reason 163 | -------------------------------------------------------------------------------- /octoprint_firmwareupdater/methods/bossac.py: -------------------------------------------------------------------------------- 1 | import re 2 | import os 3 | import sarge 4 | import time 5 | import serial 6 | from serial import SerialException 7 | 8 | BOSSAC_ERASING = "Erase flash" 9 | BOSSAC_WRITING = "bytes to flash" 10 | BOSSAC_VERIFYING = "bytes of flash" 11 | BOSSAC_NODEVICE = "No device found on" 12 | BOSSAC_ERROR_VERIFICATION = "verification error" 13 | 14 | def _check_bossac(self): 15 | bossac_path = self.get_profile_setting("bossac_path") 16 | pattern = re.compile("^(\/[^\0/]+)+$") 17 | 18 | if not pattern.match(bossac_path): 19 | self._logger.error(u"Path to bossac is not valid: {path}".format(path=bossac_path)) 20 | return False 21 | elif bossac_path is None: 22 | self._logger.error(u"Path to bossac is not set.") 23 | return False 24 | if not os.path.exists(bossac_path): 25 | self._logger.error(u"Path to bossac does not exist: {path}".format(path=bossac_path)) 26 | return False 27 | elif not os.path.isfile(bossac_path): 28 | self._logger.error(u"Path to bossac is not a file: {path}".format(path=bossac_path)) 29 | return False 30 | elif not os.access(bossac_path, os.X_OK): 31 | self._logger.error(u"Path to bossac is not executable: {path}".format(path=bossac_path)) 32 | return False 33 | else: 34 | return True 35 | 36 | def _flash_bossac(self, firmware=None, printer_port=None, **kwargs): 37 | assert(firmware is not None) 38 | assert(printer_port is not None) 39 | 40 | bossac_path = self.get_profile_setting("bossac_path") 41 | bossac_disableverify = self.get_profile_setting_boolean("bossac_disableverify") 42 | 43 | working_dir = os.path.dirname(bossac_path) 44 | 45 | bossac_command = self.get_profile_setting("bossac_commandline") 46 | bossac_command = bossac_command.replace("{bossac}", bossac_path) 47 | bossac_command = bossac_command.replace("{port}", printer_port) 48 | bossac_command = bossac_command.replace("{firmware}", firmware) 49 | 50 | if bossac_disableverify: 51 | bossac_command = bossac_command.replace("{disableverify}", "") 52 | else: 53 | bossac_command = bossac_command.replace("{disableverify}", "-v") 54 | 55 | self._logger.info(u"Attempting to reset the board to SAM-BA") 56 | self._send_status("progress", subtype="samreset") 57 | if not _reset_1200(self, printer_port): 58 | self._logger.error(u"Reset failed") 59 | return False 60 | 61 | self._logger.info(u"Running '{}' in {}".format(bossac_command, working_dir)) 62 | self._console_logger.info(u"") 63 | self._console_logger.info(bossac_command) 64 | try: 65 | p = sarge.run(bossac_command, cwd=working_dir, async_=True, stdout=sarge.Capture(buffer_size=1), stderr=sarge.Capture(buffer_size=1)) 66 | p.wait_events() 67 | 68 | while p.returncode is None: 69 | output = p.stdout.read(timeout=0.1).decode('utf-8') 70 | if not output: 71 | p.commands[0].poll() 72 | continue 73 | 74 | for line in output.split("\n"): 75 | if line.endswith("\r"): 76 | line = line[:-1] 77 | self._console_logger.info(u"> {}".format(line)) 78 | 79 | if BOSSAC_ERASING in line: 80 | self._logger.info(u"Erasing memory...") 81 | self._send_status("progress", subtype="erasing") 82 | elif BOSSAC_WRITING in line: 83 | self._logger.info(u"Writing memory...") 84 | self._send_status("progress", subtype="writing") 85 | elif BOSSAC_VERIFYING in line: 86 | self._logger.info(u"Verifying memory...") 87 | self._send_status("progress", subtype="verifying") 88 | elif BOSSAC_ERROR_VERIFICATION in line: 89 | raise FlashException("Error verifying flash") 90 | 91 | if p.returncode == 0: 92 | time.sleep(1) 93 | return True 94 | else: 95 | output = p.stderr.read(timeout=0.5).decode('utf-8') 96 | for line in output.split("\n"): 97 | if line.endswith("\r"): 98 | line = line[:-1] 99 | self._console_logger.info(u"> {}".format(line)) 100 | 101 | if BOSSAC_NODEVICE in line: 102 | raise FlashException(line) 103 | 104 | raise FlashException("bossac returned code {returncode}".format(returncode=p.returncode)) 105 | 106 | except FlashException as ex: 107 | self._logger.error(u"Flashing failed. {error}.".format(error=ex.reason)) 108 | self._send_status("flasherror", message=ex.reason) 109 | return False 110 | except: 111 | self._logger.exception(u"Flashing failed. Unexpected error.") 112 | self._send_status("flasherror") 113 | return False 114 | 115 | def _reset_1200(self, printer_port=None): 116 | assert(printer_port is not None) 117 | self._logger.info(u"Toggling '{port}' at 1200bps".format(port=printer_port)) 118 | try: 119 | ser = serial.Serial(port=printer_port, \ 120 | baudrate=1200, \ 121 | parity=serial.PARITY_NONE, \ 122 | stopbits=serial.STOPBITS_ONE , \ 123 | bytesize=serial.EIGHTBITS, \ 124 | timeout=2000) 125 | time.sleep(1) 126 | ser.close() 127 | time.sleep(3) 128 | except SerialException as ex: 129 | self._logger.exception(u"Board reset failed: {error}".format(error=str(ex))) 130 | self._send_status("flasherror", message="Board reset failed") 131 | return False 132 | 133 | return True 134 | 135 | class FlashException(Exception): 136 | def __init__(self, reason, *args, **kwargs): 137 | Exception.__init__(self, *args, **kwargs) 138 | self.reason = reason 139 | -------------------------------------------------------------------------------- /octoprint_firmwareupdater/methods/dfuprog.py: -------------------------------------------------------------------------------- 1 | import re 2 | import os 3 | import sarge 4 | 5 | DFUPROG_ERASING = "Erasing flash" 6 | DFUPROG_WRITING = "Programming" 7 | DFUPROG_VERIFYING = "Reading" 8 | DFUPROG_VALIDATING = "Validating" 9 | DFUPROG_NODEVICE = "no device present" 10 | 11 | def _check_dfuprog(self): 12 | dfuprog_path = self.get_profile_setting("dfuprog_path") 13 | pattern = re.compile("^(\/[^\0/]+)+$") 14 | 15 | if not pattern.match(dfuprog_path): 16 | self._logger.error(u"Path to dfu-programmer is not valid: {path}".format(path=dfuprog_path)) 17 | return False 18 | elif dfuprog_path is None: 19 | self._logger.error(u"Path to dfu-programmer is not set.") 20 | return False 21 | if not os.path.exists(dfuprog_path): 22 | self._logger.error(u"Path to dfu-programmer does not exist: {path}".format(path=dfuprog_path)) 23 | return False 24 | elif not os.path.isfile(dfuprog_path): 25 | self._logger.error(u"Path to dfu-programmer is not a file: {path}".format(path=dfuprog_path)) 26 | return False 27 | elif not os.access(dfuprog_path, os.X_OK): 28 | self._logger.error(u"Path to dfu-programmer is not executable: {path}".format(path=dfuprog_path)) 29 | return False 30 | else: 31 | return True 32 | 33 | def _flash_dfuprog(self, firmware=None, printer_port=None, **kwargs): 34 | assert(firmware is not None) 35 | 36 | if not _erase_dfuprog(self): 37 | return False 38 | 39 | dfuprog_path = self.get_profile_setting("dfuprog_path") 40 | dfuprog_avrmcu = self.get_profile_setting("dfuprog_avrmcu") 41 | working_dir = os.path.dirname(dfuprog_path) 42 | 43 | dfuprog_command = self.get_profile_setting("dfuprog_commandline") 44 | dfuprog_command = dfuprog_command.replace("{dfuprogrammer}", dfuprog_path) 45 | dfuprog_command = dfuprog_command.replace("{mcu}", dfuprog_avrmcu) 46 | dfuprog_command = dfuprog_command.replace("{firmware}", firmware) 47 | 48 | import sarge 49 | self._logger.info(u"Running '{}' in {}".format(dfuprog_command, working_dir)) 50 | self._send_status("progress", subtype="writing") 51 | self._console_logger.info(dfuprog_command) 52 | try: 53 | p = sarge.run(dfuprog_command, cwd=working_dir, async_=True, stdout=sarge.Capture(buffer_size=1), stderr=sarge.Capture(buffer_size=1)) 54 | p.wait_events() 55 | 56 | while p.returncode is None: 57 | output = p.stderr.read(timeout=0.5).decode('utf-8') 58 | if not output: 59 | p.commands[0].poll() 60 | continue 61 | 62 | for line in output.split("\n"): 63 | if line.endswith("\r"): 64 | line = line[:-1] 65 | self._console_logger.info(u"> {}".format(line)) 66 | 67 | if DFUPROG_WRITING in line: 68 | self._logger.info(u"Writing memory...") 69 | self._send_status("progress", subtype="writing") 70 | if DFUPROG_VERIFYING in line: 71 | self._logger.info(u"Verifying memory...") 72 | self._send_status("progress", subtype="verifying") 73 | elif DFUPROG_NODEVICE in line: 74 | raise FlashException("No device found") 75 | 76 | if p.returncode == 0: 77 | return True 78 | else: 79 | raise FlashException("dfu-programmer returned code {returncode}".format(returncode=p.returncode)) 80 | 81 | except FlashException as ex: 82 | self._logger.error(u"Flashing failed. {error}.".format(error=ex.reason)) 83 | self._send_status("flasherror", message=ex.reason) 84 | return False 85 | except: 86 | self._logger.exception(u"Flashing failed. Unexpected error.") 87 | self._send_status("flasherror") 88 | return False 89 | 90 | def _erase_dfuprog(self): 91 | dfuprog_path = self.get_profile_setting("dfuprog_path") 92 | dfuprog_avrmcu = self.get_profile_setting("dfuprog_avrmcu") 93 | 94 | working_dir = os.path.dirname(dfuprog_path) 95 | 96 | dfuprog_erasecommand = self.get_profile_setting("dfuprog_erasecommandline") 97 | dfuprog_erasecommand = dfuprog_erasecommand.replace("{dfuprogrammer}", dfuprog_path) 98 | dfuprog_erasecommand = dfuprog_erasecommand.replace("{mcu}", dfuprog_avrmcu) 99 | 100 | import sarge 101 | self._logger.info(u"Running '{}' in {}".format(dfuprog_erasecommand, working_dir)) 102 | self._console_logger.info(dfuprog_erasecommand) 103 | try: 104 | p = sarge.run(dfuprog_erasecommand, cwd=working_dir, async_=True, stdout=sarge.Capture(buffer_size=1), stderr=sarge.Capture(buffer_size=1)) 105 | p.wait_events() 106 | 107 | while p.returncode is None: 108 | output = p.stderr.read(timeout=0.5).decode('utf-8') 109 | if not output: 110 | p.commands[0].poll() 111 | continue 112 | 113 | for line in output.split("\n"): 114 | if line.endswith("\r"): 115 | line = line[:-1] 116 | self._console_logger.info(u"> {}".format(line)) 117 | 118 | if DFUPROG_ERASING in line: 119 | self._logger.info(u"Erasing memory...") 120 | self._send_status("progress", subtype="erasing") 121 | elif DFUPROG_NODEVICE in line: 122 | raise FlashException("No device found") 123 | 124 | if p.returncode == 0: 125 | return True 126 | else: 127 | raise FlashException("dfu-programmer returned code {returncode}".format(returncode=p.returncode)) 128 | 129 | except FlashException as ex: 130 | self._logger.error(u"Erasing failed. {error}.".format(error=ex.reason)) 131 | self._send_status("flasherror", message=ex.reason) 132 | return False 133 | except: 134 | self._logger.exception(u"Erasing failed. Unexpected error.") 135 | self._send_status("flasherror") 136 | return False 137 | 138 | class FlashException(Exception): 139 | def __init__(self, reason, *args, **kwargs): 140 | Exception.__init__(self, *args, **kwargs) 141 | self.reason = reason 142 | -------------------------------------------------------------------------------- /octoprint_firmwareupdater/methods/dfuutil.py: -------------------------------------------------------------------------------- 1 | import re 2 | import os 3 | import sarge 4 | 5 | DFUUTIL_ERASING = "Erase" 6 | DFUUTIL_WRITING = "Downloading" 7 | DFUUTIL_NOACCESS = "Cannot open DFU device" 8 | DFUUTIL_NODEVICE = "No DFU capable USB device available" 9 | 10 | def _check_dfuutil(self): 11 | dfuutil_path = self.get_profile_setting("dfuutil_path") 12 | pattern = re.compile("^(\/[^\0/]+)+$") 13 | 14 | if not pattern.match(dfuutil_path): 15 | self._logger.error(u"Path to dfu-util is not valid: {path}".format(path=dfuutil_path)) 16 | return False 17 | elif dfuutil_path is None: 18 | self._logger.error(u"Path to dfu-util is not set.") 19 | return False 20 | if not os.path.exists(dfuutil_path): 21 | self._logger.error(u"Path to dfu-util does not exist: {path}".format(path=dfuutil_path)) 22 | return False 23 | elif not os.path.isfile(dfuutil_path): 24 | self._logger.error(u"Path to dfu-util is not a file: {path}".format(path=dfuutil_path)) 25 | return False 26 | elif not os.access(dfuutil_path, os.X_OK): 27 | self._logger.error(u"Path to dfu-util is not executable: {path}".format(path=dfuutil_path)) 28 | return False 29 | else: 30 | return True 31 | 32 | def _flash_dfuutil(self, firmware=None, printer_port=None, **kwargs): 33 | assert(firmware is not None) 34 | 35 | dfuutil_path = self.get_profile_setting("dfuutil_path") 36 | working_dir = os.path.dirname(dfuutil_path) 37 | 38 | dfuutil_command = self.get_profile_setting("dfuutil_commandline") 39 | dfuutil_command = dfuutil_command.replace("{dfuutil}", dfuutil_path) 40 | dfuutil_command = dfuutil_command.replace("{firmware}", firmware) 41 | 42 | import sarge 43 | self._logger.info(u"Running '{}' in {}".format(dfuutil_command, working_dir)) 44 | self._console_logger.info(dfuutil_command) 45 | try: 46 | p = sarge.run(dfuutil_command, cwd=working_dir, async_=True, stdout=sarge.Capture(buffer_size=1), stderr=sarge.Capture(buffer_size=1)) 47 | p.wait_events() 48 | 49 | while p.returncode is None: 50 | output = p.stdout.read(timeout=0.2).decode('utf-8') 51 | error = p.stderr.read(timeout=0.2).decode('utf-8') 52 | 53 | if not output and not error: 54 | p.commands[0].poll() 55 | continue 56 | 57 | for line in output.split("\n"): 58 | if line.endswith("\r"): 59 | line = line[:-1] 60 | self._console_logger.info(u"> {}".format(line)) 61 | 62 | if DFUUTIL_ERASING in line: 63 | self._logger.info(u"Erasing memory...") 64 | self._send_status("progress", subtype="erasing") 65 | elif DFUUTIL_WRITING in line: 66 | self._logger.info(u"Writing memory...") 67 | self._send_status("progress", subtype="writing") 68 | 69 | for line in error.split("\n"): 70 | if line.endswith("\r"): 71 | line = line[:-1] 72 | self._console_logger.info(u"> {}".format(line)) 73 | 74 | if DFUUTIL_NOACCESS in line: 75 | raise FlashException("Cannot access DFU device") 76 | elif DFUUTIL_NODEVICE in line: 77 | raise FlashException("No DFU device found") 78 | 79 | if p.returncode == 0: 80 | return True 81 | else: 82 | raise FlashException("dfu-util returned code {returncode}".format(returncode=p.returncode)) 83 | 84 | except FlashException as ex: 85 | self._logger.error(u"Flashing failed. {error}.".format(error=ex.reason)) 86 | self._send_status("flasherror", message=ex.reason) 87 | return False 88 | except: 89 | self._logger.exception(u"Flashing failed. Unexpected error.") 90 | self._send_status("flasherror") 91 | return False 92 | 93 | class FlashException(Exception): 94 | def __init__(self, reason, *args, **kwargs): 95 | Exception.__init__(self, *args, **kwargs) 96 | self.reason = reason 97 | -------------------------------------------------------------------------------- /octoprint_firmwareupdater/methods/esptool.py: -------------------------------------------------------------------------------- 1 | import re 2 | import os 3 | import sarge 4 | import time 5 | import serial 6 | from serial import SerialException 7 | 8 | ESPTOOL_CONNECTING = "Connecting" 9 | ESPTOOL_WRITING = "Writing at" 10 | ESPTOOL_RESETTING = "resetting" 11 | ESPTOOL_NODATA = "No serial data received" 12 | ESPTOOL_NOBOARD = "Could not open" 13 | ESPTOOL_WRONGCHIP = "Wrong --chip argument?" 14 | ESPTOOL_WRONGMODE = "Wrong boot mode detected" 15 | ESPTOOL_ERROR = "esptool: error:" 16 | ESPTOOL_BADARG = "argument" 17 | 18 | def _check_esptool(self): 19 | esptool_path = self.get_profile_setting("esptool_path") 20 | pattern = re.compile("^(\/[^\0/]+)+$") 21 | 22 | if not pattern.match(esptool_path): 23 | self._logger.error(u"Path to esptool is not valid: {path}".format(path=esptool_path)) 24 | return False 25 | elif esptool_path is None: 26 | self._logger.error(u"Path to esptool is not set.") 27 | return False 28 | if not os.path.exists(esptool_path): 29 | self._logger.error(u"Path to esptool does not exist: {path}".format(path=esptool_path)) 30 | return False 31 | elif not os.path.isfile(esptool_path): 32 | self._logger.error(u"Path to esptool is not a file: {path}".format(path=esptool_path)) 33 | return False 34 | elif not os.access(esptool_path, os.X_OK): 35 | self._logger.error(u"Path to esptool is not executable: {path}".format(path=esptool_path)) 36 | return False 37 | else: 38 | return True 39 | 40 | def _flash_esptool(self, firmware=None, printer_port=None, **kwargs): 41 | assert(firmware is not None) 42 | assert(printer_port is not None) 43 | 44 | esptool_path = self.get_profile_setting("esptool_path") 45 | esptool_chip = self.get_profile_setting("esptool_chip") 46 | esptool_address = self.get_profile_setting("esptool_address") 47 | esptool_baudrate = self.get_profile_setting("esptool_baudrate") 48 | 49 | working_dir = os.path.dirname(esptool_path) 50 | 51 | esptool_command = self.get_profile_setting("esptool_commandline") 52 | esptool_command = esptool_command.replace("{esptool}", esptool_path) 53 | esptool_command = esptool_command.replace("{port}", printer_port) 54 | esptool_command = esptool_command.replace("{chip}", esptool_chip.lower()) 55 | esptool_command = esptool_command.replace("{address}", esptool_address) 56 | esptool_command = esptool_command.replace("{baud}", str(esptool_baudrate)) 57 | esptool_command = esptool_command.replace("{firmware}", firmware) 58 | 59 | self._logger.info(u"Running '{}' in {}".format(esptool_command, working_dir)) 60 | self._console_logger.info(u"") 61 | self._console_logger.info(esptool_command) 62 | try: 63 | p = sarge.run(esptool_command, cwd=working_dir, async_=True, stdout=sarge.Capture(buffer_size=1), stderr=sarge.Capture(buffer_size=1)) 64 | p.wait_events() 65 | 66 | while p.returncode is None: 67 | output = p.stdout.read(timeout=0.1).decode('utf-8') 68 | if not output: 69 | p.commands[0].poll() 70 | continue 71 | 72 | for line in output.split("\n"): 73 | if line.endswith("\r"): 74 | line = line[:-1] 75 | self._console_logger.info(u"> {}".format(line)) 76 | 77 | if ESPTOOL_CONNECTING in line: 78 | self._logger.info(u"Connecting...") 79 | self._send_status("progress", subtype="connecting") 80 | elif ESPTOOL_WRITING in line: 81 | self._logger.info(u"Writing memory...") 82 | self._send_status("progress", subtype="writing") 83 | elif ESPTOOL_RESETTING in line: 84 | self._logger.info(u"Resetting...") 85 | self._send_status("progress", subtype="boardreset") 86 | elif ESPTOOL_NODATA in line: 87 | raise FlashException("No serial data received.") 88 | elif ESPTOOL_NOBOARD in line: 89 | raise FlashException("Could not open the port.") 90 | elif ESPTOOL_WRONGCHIP in line: 91 | message = "Incompatible ESP chip specified." 92 | try: 93 | message = message + u" {}.".format(re.split(r"[\:\.]", line)[1].strip()) 94 | except: 95 | self._logger.info(u"Could not parse chip error") 96 | raise FlashException(message) 97 | elif ESPTOOL_WRONGMODE in line: 98 | raise FlashException("Wrong boot mode detected. The chip needs to be in download mode.") 99 | 100 | if p.returncode == 0: 101 | time.sleep(1) 102 | return True 103 | else: 104 | output = p.stderr.read(timeout=0.1).decode('utf-8') 105 | for line in output.split("\n"): 106 | if line.endswith("\r"): 107 | line = line[:-1] 108 | self._console_logger.info(u"> {}".format(line)) 109 | 110 | if ESPTOOL_ERROR in line and ESPTOOL_BADARG in line: 111 | raise FlashException(u"Unrecognized or invalid Esptool argument(s).\n\n{}".format(line)) 112 | elif ESPTOOL_ERROR in line: 113 | errline = line 114 | 115 | if errline: 116 | raise FlashException("Esptool returned code {returncode}.\n{error}".format(returncode=p.returncode, error=errline)) 117 | else: 118 | raise FlashException("Esptool returned code {returncode}.".format(returncode=p.returncode)) 119 | 120 | except FlashException as ex: 121 | self._logger.error(u"Flashing failed. {error}.".format(error=ex.reason)) 122 | self._send_status("flasherror", message=ex.reason) 123 | return False 124 | except: 125 | self._logger.exception(u"Flashing failed. Unexpected error.") 126 | self._send_status("flasherror") 127 | return False 128 | 129 | class FlashException(Exception): 130 | def __init__(self, reason, *args, **kwargs): 131 | Exception.__init__(self, *args, **kwargs) 132 | self.reason = reason 133 | -------------------------------------------------------------------------------- /octoprint_firmwareupdater/methods/lpc1768.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | import re 3 | import os 4 | import time 5 | import shutil 6 | import subprocess 7 | import sys 8 | 9 | def _check_lpc1768(self): 10 | lpc1768_path = self.get_profile_setting("lpc1768_path") 11 | pattern = re.compile("^(\/[^\0/]+)+$") 12 | 13 | if not pattern.match(lpc1768_path): 14 | self._logger.error(u"Firmware folder path is not valid: {path}".format(path=lpc1768_path)) 15 | return False 16 | elif lpc1768_path is None: 17 | self._logger.error(u"Firmware folder path is not set.") 18 | return False 19 | if not os.path.exists(lpc1768_path): 20 | self._logger.error(u"Firmware folder path does not exist: {path}".format(path=lpc1768_path)) 21 | return False 22 | elif not os.path.isdir(lpc1768_path): 23 | self._logger.error(u"Firmware folder path is not a folder: {path}".format(path=lpc1768_path)) 24 | return False 25 | else: 26 | return True 27 | 28 | def _flash_lpc1768(self, firmware=None, printer_port=None, **kwargs): 29 | assert(firmware is not None) 30 | assert(printer_port is not None) 31 | 32 | no_m997_reset_wait = self.get_profile_setting_boolean("lpc1768_no_m997_reset_wait") 33 | lpc1768_path = self.get_profile_setting("lpc1768_path") 34 | timestamp_filenames = self.get_profile_setting_boolean("lpc1768_timestamp_filenames") 35 | use_custom_filename = self.get_profile_setting_boolean("lpc1768_use_custom_filename") 36 | custom_filename = self.get_profile_setting("lpc1768_custom_filename").strip() 37 | 38 | if self.get_profile_setting_boolean("lpc1768_preflashreset"): 39 | self._send_status("progress", subtype="boardreset") 40 | 41 | # Sync the filesystem to flush writes 42 | self._logger.info(u"Synchronizing cached writes to SD card") 43 | try: 44 | r = os.system('sync') 45 | except: 46 | e = sys.exc_info()[0] 47 | self._logger.error("Error executing 'sync' command") 48 | return False 49 | time.sleep(1) 50 | 51 | if os.access(lpc1768_path, os.W_OK): 52 | unmount_command = self.get_profile_setting("lpc1768_unmount_command") 53 | if unmount_command: 54 | unmount_command = unmount_command.replace("{mountpoint}", lpc1768_path) 55 | 56 | self._logger.info(u"Unmounting SD card: '{}'".format(unmount_command)) 57 | try: 58 | p = subprocess.Popen(unmount_command.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) 59 | out, err = p.communicate() 60 | r = p.returncode 61 | 62 | except: 63 | e = sys.exc_info()[0] 64 | self._logger.error("Error executing unmount command '{}'".format(unmount_command)) 65 | self._logger.error("{}".format(str(e))) 66 | self._send_status("flasherror", message="Unable to unmount SD card") 67 | return False 68 | 69 | if r != 0: 70 | if err.strip().endswith("not mounted."): 71 | self._logger.info("{}".format(err.strip())) 72 | else: 73 | self._logger.error("Error executing unmount command '{}'".format(unmount_command)) 74 | self._logger.error("{}".format(err.strip())) 75 | self._send_status("flasherror", message="Unable to unmount SD card") 76 | return False 77 | else: 78 | self._logger.info(u"SD card not mounted, skipping unmount") 79 | 80 | self._logger.info(u"Pre-flash reset: attempting to reset the board") 81 | if not _reset_lpc1768(self, printer_port): 82 | self._logger.error(u"Reset failed") 83 | return False 84 | 85 | # Release the SD card 86 | if not _unmount_sd(self, printer_port): 87 | self._send_status("flasherror", message="Unable to unmount SD card") 88 | return False 89 | 90 | # loop until the mount is available; timeout after 60s 91 | count = 1 92 | timeout = 60 93 | interval = 1 94 | sdstarttime = time.time() 95 | self._logger.info(u"Waiting for SD card to be available at '{}'".format(lpc1768_path)) 96 | self._send_status("progress", subtype="waitforsd") 97 | while (time.time() < (sdstarttime + timeout) and not os.access(lpc1768_path, os.W_OK)): 98 | self._logger.debug(u"Waiting for firmware folder path to become available [{}/{}]".format(count, int(timeout / interval))) 99 | count = count + 1 100 | time.sleep(interval) 101 | 102 | if not os.access(lpc1768_path, os.W_OK): 103 | self._send_status("flasherror", message="Unable to access firmware folder") 104 | self._logger.error(u"Firmware folder path is not writeable: {path}".format(path=lpc1768_path)) 105 | return False 106 | 107 | self._logger.info(u"Firmware update folder '{}' available for writing after {} seconds".format(lpc1768_path, round((time.time() - sdstarttime),0))) 108 | 109 | # Try to delete the last-flashed file 110 | last_filename = self.get_profile_setting("lpc1768_last_filename") 111 | if timestamp_filenames and last_filename is not None: 112 | last_path = lpc1768_path + '/' + last_filename 113 | self._logger.info(u"Attempting to delete previous firmware file {}".format(last_path)) 114 | if os.path.isfile(last_path): 115 | try: 116 | os.remove(last_path) 117 | except: 118 | self._logger.warn(u"Unable to delete {}".format(last_path)) 119 | else: 120 | self._logger.info(u"{} does not exist".format(last_path)) 121 | 122 | # Copy the new firmware file 123 | if timestamp_filenames: 124 | target = datetime.datetime.now().strftime("fw%H%M%S.bin") 125 | elif use_custom_filename and custom_filename is not None: 126 | target = custom_filename 127 | else: 128 | target = "firmware.bin" 129 | 130 | target_path = lpc1768_path + '/' + target 131 | self._logger.info(u"Copying firmware to update folder '{}' -> '{}'".format(firmware, target_path)) 132 | self._send_status("progress", subtype="copying") 133 | 134 | try: 135 | shutil.copyfile(firmware, target_path) 136 | except: 137 | self._logger.exception(u"Flashing failed. Unable to copy file.") 138 | self._send_status("flasherror", message="Unable to copy firmware file to firmware folder") 139 | return False 140 | 141 | # Save the filename 142 | if timestamp_filenames: 143 | self.set_profile_setting("lpc1768_last_filename", target) 144 | 145 | self._send_status("progress", subtype="unmounting") 146 | 147 | # Sync the filesystem to flush writes 148 | self._logger.info(u"Synchronizing cached writes to SD card") 149 | try: 150 | r = os.system('sync') 151 | except: 152 | e = sys.exc_info()[0] 153 | self._logger.error("Error executing 'sync' command") 154 | return False 155 | time.sleep(1) 156 | 157 | unmount_command = self.get_profile_setting("lpc1768_unmount_command") 158 | if unmount_command: 159 | unmount_command = unmount_command.replace("{mountpoint}", lpc1768_path) 160 | 161 | self._logger.info(u"Unmounting SD card: '{}'".format(unmount_command)) 162 | try: 163 | p = subprocess.Popen(unmount_command.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) 164 | out, err = p.communicate() 165 | r = p.returncode 166 | 167 | except: 168 | e = sys.exc_info()[0] 169 | self._logger.error("Error executing unmount command '{}'".format(unmount_command)) 170 | self._logger.error("{}".format(str(e))) 171 | self._send_status("flasherror", message="Unable to unmount SD card") 172 | return False 173 | 174 | if r != 0: 175 | if err.strip().endswith("not mounted."): 176 | self._logger.info("{}".format(err.strip())) 177 | else: 178 | self._logger.error("Error executing unmount command '{}'".format(unmount_command)) 179 | self._logger.error("{}".format(err.strip())) 180 | self._send_status("flasherror", message="Unable to unmount SD card") 181 | return False 182 | 183 | self._send_status("progress", subtype="boardreset") 184 | self._logger.info(u"Firmware update reset: attempting to reset the board") 185 | if not _reset_lpc1768(self, printer_port, no_m997_reset_wait): 186 | self._logger.error(u"Reset failed") 187 | return False 188 | 189 | return True 190 | 191 | def _reset_lpc1768(self, printer_port=None, no_reset_wait=False): 192 | assert(printer_port is not None) 193 | no_m997_restart_wait = self.get_profile_setting_boolean("lpc1768_no_m997_restart_wait") 194 | self._logger.info(u"Resetting LPC1768 at '{port}'".format(port=printer_port)) 195 | 196 | # Configure the port 197 | try: 198 | os.system('stty -F ' + printer_port + ' speed 115200 -echo > /dev/null') 199 | except: 200 | self._logger.exception(u"Error configuring serial port.") 201 | self._send_status("flasherror", message="Board reset failed") 202 | return False 203 | 204 | # Smoothie reset command 205 | try: 206 | os.system('echo reset >> ' + printer_port) 207 | except: 208 | self._logger.exception(u"Error sending Smoothie 'reset' command.") 209 | self._send_status("flasherror", message="Board reset failed") 210 | return False 211 | 212 | # Marlin reset command 213 | try: 214 | os.system('echo M997 >> ' + printer_port) 215 | except: 216 | self._logger.exception(u"Error sending Marlin 'M997' command.") 217 | self._send_status("flasherror", message="Board reset failed") 218 | return False 219 | 220 | if no_reset_wait: 221 | # Give the board time to reset so that OctoPrint does not try to reconnect before the reset 222 | time.sleep(1) 223 | self._logger.info(u"Not waiting for reset") 224 | return True 225 | else: 226 | if _wait_for_lpc1768(self, printer_port, no_m997_restart_wait): 227 | return True 228 | else: 229 | self._logger.error(u"Board reset failed") 230 | self._send_status("flasherror", message="Board reset failed") 231 | return False 232 | 233 | def _wait_for_lpc1768(self, printer_port=None, no_restart_wait=False): 234 | assert(printer_port is not None) 235 | self._logger.info(u"Waiting for LPC1768 at '{port}' to reset".format(port=printer_port)) 236 | 237 | check_command = 'ls ' + printer_port + ' > /dev/null 2>&1' 238 | start = time.time() 239 | timeout = 10 240 | interval = 0.2 241 | count = 1 242 | connected = True 243 | 244 | loopstarttime = time.time() 245 | 246 | while (time.time() < (loopstarttime + timeout) and connected): 247 | self._logger.debug(u"Waiting for reset to init [{}/{}]".format(count, int(timeout / interval))) 248 | count = count + 1 249 | 250 | if not os.system(check_command): 251 | connected = True 252 | time.sleep(interval) 253 | 254 | else: 255 | time.sleep(interval) 256 | connected = False 257 | 258 | if connected: 259 | self._logger.error(u"Timeout waiting for board reset to init") 260 | return False 261 | 262 | self._logger.info(u"LPC1768 at '{port}' is resetting".format(port=printer_port)) 263 | 264 | if no_restart_wait: 265 | self._logger.info(u"Not waiting for restart to complete") 266 | return True 267 | else: 268 | time.sleep(3) 269 | 270 | timeout = 20 271 | interval = 0.2 272 | count = 1 273 | connected = False 274 | loopstarttime = time.time() 275 | 276 | while (time.time() < (loopstarttime + timeout) and not connected): 277 | self._logger.debug(u"Waiting for reset to complete [{}/{}]".format(count, int(timeout / interval))) 278 | count = count + 1 279 | 280 | if not os.system(check_command): 281 | connected = True 282 | time.sleep(interval) 283 | 284 | else: 285 | time.sleep(interval) 286 | connected = False 287 | 288 | if not connected: 289 | self._logger.error(u"Timeout waiting for board reset to complete") 290 | return False 291 | 292 | end = time.time() 293 | self._logger.info(u"LPC1768 at '{port}' reset in {duration} seconds".format(port=printer_port, duration=(round((end - start),2)))) 294 | return True 295 | 296 | def _unmount_sd(self, printer_port=None): 297 | assert(printer_port is not None) 298 | self._logger.info(u"Release the firmware lock on the SD Card by sending 'M22' to '{port}'".format(port=printer_port)) 299 | 300 | try: 301 | os.system('stty -F ' + printer_port + ' speed 115200 -echo > /dev/null') 302 | except: 303 | self._logger.exception(u"Error configuring serial port.") 304 | self._send_status("flasherror", message="Card unmount failed") 305 | return False 306 | 307 | try: 308 | os.system('echo M22 >> ' + printer_port) 309 | except: 310 | self._logger.exception(u"Error sending 'M22' command.") 311 | self._send_status("flasherror", message="Card unmount failed") 312 | return False 313 | 314 | time.sleep(2) 315 | return True 316 | -------------------------------------------------------------------------------- /octoprint_firmwareupdater/methods/marlinbft.py: -------------------------------------------------------------------------------- 1 | import os 2 | import time 3 | import datetime 4 | 5 | binproto2_installed = True 6 | try: 7 | import binproto2 as mbp 8 | except: 9 | binproto2_installed = False 10 | 11 | current_port = None 12 | current_baudrate = None 13 | current_profile = None 14 | 15 | def _check_binproto2(self): 16 | global binproto2_installed 17 | self._settings.set_boolean(["has_binproto2package"], binproto2_installed) 18 | self._settings.save() 19 | return binproto2_installed 20 | 21 | def _check_marlinbft(self): 22 | self._logger.info("Python package 'marlin-binary-protocol' is installed: %s" % (_check_binproto2(self))) 23 | self._logger.info("Marlin BINARY_FILE_TRANSFER capability is enabled: %s" % (self._settings.get_boolean(["has_bftcapability"]))) 24 | 25 | if not _check_binproto2(self): 26 | self._logger.error("Python package 'marlin-binary-protocol' is not installed") 27 | self._send_status("flasherror", subtype="nobinproto2") 28 | elif not self._settings.get_boolean(["has_bftcapability"]): 29 | self._logger.error("Marlin BINARY_FILE_TRANSFER capability is not supported") 30 | self._send_status("flasherror", subtype="nobftcap") 31 | return False 32 | elif not self._printer.is_operational(): 33 | self._logger.error("Printer is not connected") 34 | self._send_status("flasherror", subtype="notconnected") 35 | return False 36 | else: 37 | global current_baudrate 38 | global current_port 39 | global current_profile 40 | _, current_port, current_baudrate, current_profile = self._printer.get_current_connection() 41 | return True 42 | 43 | def _flash_marlinbft(self, firmware=None, printer_port=None, **kwargs): 44 | assert(firmware is not None) 45 | assert(printer_port is not None) 46 | assert(current_baudrate is not None) 47 | 48 | # Get the settings 49 | selected_profile = self._settings.get_int(["_selected_profile"]) 50 | bft_waitafterconnect = self.get_profile_setting_int("marlinbft_waitafterconnect") 51 | bft_timeout = self.get_profile_setting_int("marlinbft_timeout") 52 | bft_verbose = self.get_profile_setting_boolean("marlinbft_progresslogging") 53 | no_m997_reset_wait = self.get_profile_setting_boolean("marlinbft_no_m997_reset_wait") 54 | timestamp_filenames = self.get_profile_setting_boolean("marlinbft_timestamp_filenames") 55 | use_custom_filename = self.get_profile_setting_boolean("marlinbft_use_custom_filename") 56 | custom_filename = self.get_profile_setting("marlinbft_custom_filename").strip() 57 | 58 | self.set_profile_setting_boolean("marlinbft_got_start", False) 59 | 60 | # Logging 61 | if bft_verbose: 62 | transfer_logger = self._logger 63 | else: 64 | transfer_logger = None 65 | 66 | try: 67 | # Open the binary protocol connection 68 | self._logger.info("Current Baud: %s" % current_baudrate) 69 | 70 | self._logger.info(u"Initializing Marlin BFT protocol") 71 | self._send_status("progress", subtype="bftinit") 72 | protocol = mbp.Protocol(printer_port, current_baudrate, 512, bft_timeout, self._logger) 73 | 74 | # Wait after connect protocol 75 | if bft_waitafterconnect > 0: 76 | self._logger.info("waiting %ss after protocol connect" % bft_waitafterconnect) 77 | time.sleep(bft_waitafterconnect) 78 | 79 | # Try to delete the last-flashed file 80 | last_filename = self.get_lastbft_filename() 81 | if timestamp_filenames and last_filename is not None: 82 | self._logger.info(u"Attempting to delete previous firmware file /{}".format(last_filename)) 83 | protocol.send_ascii("M21") 84 | protocol.send_ascii("M30 {}".format(last_filename)) 85 | 86 | # Make sure temperature auto-reporting is disabled 87 | protocol.send_ascii("M155 S0") 88 | 89 | # Connect 90 | self._logger.info(u"Connecting to printer at '{}' using Marlin BFT protocol".format(printer_port)) 91 | self._send_status("progress", subtype="bftconnect") 92 | protocol.connect() 93 | 94 | # Copy the file 95 | if timestamp_filenames: 96 | target = datetime.datetime.now().strftime("fw%H%M%S.bin") 97 | elif use_custom_filename and custom_filename is not None: 98 | target = custom_filename 99 | else: 100 | target = "firmware.bin" 101 | 102 | self._logger.info(u"Transfering file to printer using Marlin BFT '{}' -> /{}".format(firmware, target)) 103 | self._send_status("progress", subtype="sending") 104 | filetransfer = mbp.FileTransferProtocol(protocol, logger=transfer_logger) 105 | filetransfer.copy(firmware, target, True, False) 106 | self._logger.info(u"Binary file transfer complete") 107 | 108 | # Save the filename 109 | if timestamp_filenames: 110 | self._logger.info(u"Setting '{}' as last firmware filename".format(target)) 111 | self.set_lastbft_filename(target) 112 | 113 | # Disconnect 114 | protocol.disconnect() 115 | 116 | # Display a message on the LCD 117 | protocol.send_ascii("M117 Resetting...") 118 | 119 | except mbp.exceptions.ConnectionLost: 120 | self._logger.exception(u"Flashing failed. Unable to connect to printer.") 121 | self._send_status("flasherror", message="Unable to open binary file transfer connection") 122 | return False 123 | 124 | except mbp.exceptions.FatalError: 125 | self._logger.exception(u"Flashing failed. Too many retries.") 126 | self._send_status("flasherror", message="Unable to transfer firmware file to printer - too many retries") 127 | return False 128 | 129 | except: 130 | self._logger.exception(u"Flashing failed. Unable to transfer file.") 131 | self._send_status("flasherror", message="Unable to transfer firmware file to printer") 132 | return False 133 | 134 | finally: 135 | if (protocol): 136 | protocol.shutdown() 137 | 138 | self._send_status("progress", subtype="boardreset") 139 | self._logger.info(u"Firmware update reset: attempting to reset the board") 140 | if not _reset_board(self, printer_port, current_baudrate, no_m997_reset_wait): 141 | self._logger.error(u"Reset failed") 142 | return False 143 | 144 | return True 145 | 146 | def _reset_board(self, printer_port=None, current_baudrate=None, no_reset_wait=False): 147 | assert(printer_port is not None) 148 | assert(current_baudrate is not None) 149 | 150 | no_m997_restart_wait = self.get_profile_setting_boolean("marlinbft_no_m997_restart_wait") 151 | alt_reset_method = self.get_profile_setting_boolean("marlinbft_alt_reset") 152 | self._logger.info(u"Resetting printer at '{port}'".format(port=printer_port)) 153 | 154 | # Configure the port 155 | try: 156 | os.system('stty -F ' + printer_port + ' speed ' + str(current_baudrate) + ' -echo > /dev/null') 157 | except: 158 | self._logger.exception(u"Error configuring serial port.") 159 | self._send_status("flasherror", message="Board reset failed") 160 | return False 161 | 162 | # Smoothie reset command 163 | try: 164 | os.system('echo reset >> ' + printer_port) 165 | except: 166 | self._logger.exception(u"Error sending Smoothie 'reset' command.") 167 | self._send_status("flasherror", message="Board reset failed") 168 | return False 169 | 170 | # Marlin reset command 171 | if alt_reset_method: 172 | temp_prevent_connect = self._settings.get_boolean(["prevent_connection_when_flashing"]) 173 | self._settings.set_boolean(["prevent_connection_when_flashing"], False) 174 | try: 175 | global current_port 176 | global current_profile 177 | self._logger.info(u"Reconnecting to printer at port '{port}' to initiate reset".format(port=current_port)) 178 | self._printer.connect(port=current_port, baudrate=current_baudrate, profile=current_profile) 179 | time.sleep(2) 180 | self._logger.info(u"Sending M997 reset command to printer") 181 | self._printer.commands("M997") 182 | except: 183 | self._logger.exception(u"Error sending Marlin 'M997' command.") 184 | self._send_status("flasherror", message="Board reset failed") 185 | return False 186 | finally: 187 | self._settings.set_boolean(["prevent_connection_when_flashing"], temp_prevent_connect) 188 | 189 | if no_m997_restart_wait: 190 | # Give the board time to reset so that OctoPrint does not try to reconnect before the reset 191 | self._logger.info(u"Not waiting for reset") 192 | return True 193 | else: 194 | if _wait_for_start(self, current_port): 195 | self._logger.info(u"Disconnecting printer") 196 | self._printer.disconnect() 197 | return True 198 | else: 199 | self._send_status("flasherror", message="Firmware update failed") 200 | return False 201 | else: 202 | try: 203 | self._logger.info(u"Sending out-of-band reset command to '{port}'".format(port=printer_port)) 204 | os.system('echo M997 >> ' + printer_port) 205 | except: 206 | self._logger.exception(u"Error sending Marlin 'M997' command.") 207 | self._send_status("flasherror", message="Board reset failed") 208 | return False 209 | 210 | if no_reset_wait: 211 | # Give the board time to reset so that OctoPrint does not try to reconnect before the reset 212 | time.sleep(1) 213 | self._logger.info(u"Not waiting for reset") 214 | return True 215 | else: 216 | if _wait_for_board(self, printer_port, no_m997_restart_wait): 217 | return True 218 | else: 219 | self._logger.error(u"Board reset failed") 220 | self._send_status("flasherror", message="Board reset failed") 221 | return False 222 | 223 | def _wait_for_start(self, printer_port=None): 224 | assert(printer_port is not None) 225 | m997_restart_wait = self.get_profile_setting("marlinbft_m997_restart_wait") 226 | self._logger.info(u"Waiting {seconds}s for printer at '{port}' to reset".format(seconds=m997_restart_wait, port=printer_port)) 227 | 228 | start = time.time() 229 | timeout = m997_restart_wait 230 | interval = 0.2 231 | count = 1 232 | restarted = False 233 | loopstarttime = time.time() 234 | 235 | while (time.time() < (loopstarttime + timeout) and not restarted): 236 | self._logger.debug(u"Waiting for reset [{}/{}]".format(count, int(timeout / interval))) 237 | count = count + 1 238 | if not self.get_profile_setting_boolean("marlinbft_got_start"): 239 | restarted = False 240 | time.sleep(interval) 241 | else: 242 | time.sleep(interval) 243 | restarted = True 244 | 245 | if not restarted: 246 | self._logger.error(u"Timeout waiting for board to reset") 247 | return False 248 | 249 | end = time.time() 250 | duration = round((end - start),2) 251 | 252 | self._logger.info(u"Printer at '{port}' reset in {duration} seconds".format(port=printer_port, duration=(round((end - start),2)))) 253 | 254 | if duration < 1: 255 | self._logger.error(u"Board reset too quickly - firmware could not have updated") 256 | self.set_profile_setting_boolean("marlinbft_got_start", False) 257 | return False 258 | else: 259 | self.set_profile_setting_boolean("marlinbft_got_start", False) 260 | return True 261 | 262 | def _wait_for_board(self, printer_port=None, no_restart_wait=False): 263 | assert(printer_port is not None) 264 | 265 | m997_reset_wait = self.get_profile_setting("marlinbft_m997_reset_wait") 266 | if m997_reset_wait is None: 267 | m997_reset_wait = 10 268 | 269 | self._logger.info(u"Waiting {seconds}s for printer at '{port}' to reset".format(seconds=m997_reset_wait, port=printer_port)) 270 | 271 | check_command = 'ls ' + printer_port + ' > /dev/null 2>&1' 272 | start = time.time() 273 | timeout = m997_reset_wait 274 | interval = 0.2 275 | count = 1 276 | connected = True 277 | 278 | loopstarttime = time.time() 279 | 280 | while (time.time() < (loopstarttime + timeout) and connected): 281 | self._logger.debug(u"Waiting for reset to init [{}/{}]".format(count, int(timeout / interval))) 282 | count = count + 1 283 | 284 | if not os.system(check_command): 285 | connected = True 286 | time.sleep(interval) 287 | 288 | else: 289 | time.sleep(interval) 290 | connected = False 291 | 292 | if connected: 293 | self._logger.error(u"Timeout waiting for board reset to init") 294 | return False 295 | 296 | self._logger.info(u"Printer at '{port}' is resetting".format(port=printer_port)) 297 | 298 | if no_restart_wait: 299 | self._logger.info(u"Not waiting for restart to complete") 300 | return True 301 | else: 302 | time.sleep(3) 303 | m997_restart_wait = self.get_profile_setting("marlinbft_m997_restart_wait") 304 | if m997_restart_wait is None: 305 | m997_restart_wait = 20 306 | 307 | self._logger.info(u"Waiting {seconds}s for printer at '{port}' to restart".format(seconds=m997_restart_wait, port=printer_port)) 308 | 309 | timeout = m997_restart_wait 310 | interval = 0.2 311 | count = 1 312 | connected = False 313 | loopstarttime = time.time() 314 | 315 | while (time.time() < (loopstarttime + timeout) and not connected): 316 | self._logger.debug(u"Waiting for reset to complete [{}/{}]".format(count, int(timeout / interval))) 317 | count = count + 1 318 | 319 | if not os.system(check_command): 320 | connected = True 321 | time.sleep(interval) 322 | 323 | else: 324 | time.sleep(interval) 325 | connected = False 326 | 327 | if not connected: 328 | self._logger.error(u"Timeout waiting for board reset to complete") 329 | return False 330 | 331 | end = time.time() 332 | self._logger.info(u"Printer at '{port}' reset in {duration} seconds".format(port=printer_port, duration=(round((end - start),2)))) 333 | return True 334 | -------------------------------------------------------------------------------- /octoprint_firmwareupdater/methods/stm32flash.py: -------------------------------------------------------------------------------- 1 | import re 2 | import os 3 | import sarge 4 | 5 | def getGPIO(pin, low): 6 | return ('-' if low else '') + pin 7 | 8 | def _check_stm32flash(self): 9 | stm32flash_path = self.get_profile_setting("stm32flash_path") 10 | 11 | pattern = re.compile("^(\/[^\0/]+)+$") 12 | 13 | if not pattern.match(stm32flash_path): 14 | self._logger.error(u"Path to stm32flash is not valid: {path}".format(path=avrdude_path)) 15 | return False 16 | elif not os.path.exists(stm32flash_path): 17 | self._logger.error(u"Path to stm32flash does not exist: {path}".format(path=avrdude_path)) 18 | return False 19 | elif not os.path.isfile(stm32flash_path): 20 | self._logger.error(u"Path to stm32flash is not a file: {path}".format(path=avrdude_path)) 21 | return False 22 | elif not os.access(stm32flash_path, os.X_OK): 23 | self._logger.error(u"Path to stm32flash is not executable: {path}".format(path=avrdude_path)) 24 | return False 25 | else: 26 | return True 27 | 28 | def _flash_stm32flash(self, firmware=None, printer_port=None, **kwargs): 29 | assert(firmware is not None) 30 | assert(printer_port is not None) 31 | 32 | stm32flash_path = self.get_profile_setting("stm32flash_path") 33 | stm32flash_verify = self.get_profile_setting_boolean("stm32flash_verify") 34 | stm32flash_boot0pin = self.get_profile_setting("stm32flash_boot0pin") 35 | stm32flash_boot0low = self.get_profile_setting_boolean("stm32flash_boot0low") 36 | stm32flash_resetpin = self.get_profile_setting("stm32flash_resetpin") 37 | stm32flash_resetlow = self.get_profile_setting_boolean("stm32flash_resetlow") 38 | stm32flash_execute = self.get_profile_setting("stm32flash_execute") 39 | stm32flash_executeaddress = self.get_profile_setting("stm32flash_executeaddress") 40 | stm32flash_reset = self.get_profile_setting_boolean("stm32flash_reset") 41 | 42 | working_dir = os.path.dirname(stm32flash_path) 43 | 44 | stm32flash_args = [ 45 | stm32flash_path 46 | ] 47 | if (stm32flash_verify): 48 | stm32flash_args.append('-v') 49 | 50 | stm32flash_args.append('-i') 51 | stm32flash_args.append(','.join([ 52 | getGPIO(stm32flash_boot0pin, stm32flash_boot0low), 53 | getGPIO(stm32flash_resetpin, stm32flash_resetlow), 54 | getGPIO(stm32flash_resetpin, not stm32flash_resetlow), 55 | getGPIO(stm32flash_boot0pin, not stm32flash_boot0low), 56 | ])) 57 | 58 | if (stm32flash_execute): 59 | stm32flash_args.append('-g') 60 | stm32flash_args.append(stm32flash_executeaddress) 61 | 62 | if (stm32flash_reset and not stm32flash_execute): 63 | stm32flash_args.append('-R') 64 | 65 | stm32flash_args.append('-w') 66 | stm32flash_args.append(firmware) 67 | stm32flash_args.append(printer_port) 68 | 69 | stm32flash_command = ' '.join(stm32flash_args) 70 | 71 | self._logger.info(u"Running '{}' in {}".format(stm32flash_command, working_dir)) 72 | self._console_logger.info(u"") 73 | self._console_logger.info(stm32flash_command) 74 | 75 | try: 76 | p = sarge.run(stm32flash_command, cwd=working_dir, async_=True, stdout=sarge.Capture(), stderr=sarge.Capture()) 77 | p.wait_events() 78 | 79 | while p.returncode is None: 80 | output = p.stdout.read(timeout=0.5).decode('utf-8') 81 | if not output: 82 | p.commands[0].poll() 83 | continue 84 | 85 | for line in output.split("\n"): 86 | if line.endswith("\r"): 87 | line = line[:-1] 88 | self._console_logger.info(u"> {}".format(line)) 89 | 90 | if "Write to memory" in line: 91 | self._logger.info(u"Writing memory...") 92 | self._send_status("progress", subtype="writing") 93 | 94 | if p.returncode == 0: 95 | return True 96 | else: 97 | output = p.stderr.read(timeout=0.5).decode('utf-8') 98 | for line in output.split("\n"): 99 | if line.endswith("\r"): 100 | line = line[:-1] 101 | self._console_logger.info(u"> {}".format(line)) 102 | if "Error" in line: 103 | raise FlashException("stm32flash error " + line[line.find("Error") + len("Error"):].strip() + "'") 104 | elif "Failed to init device" in line: 105 | raise FlashException("Cannot enter bootloader, check your BOOT0/Reset pins settings and try again") 106 | else: 107 | raise FlashException("stm32flash returned code {returncode} : {message}".format(returncode=p.returncode, message=line)) 108 | 109 | except FlashException as ex: 110 | self._logger.error(u"Flashing failed. {error}.".format(error=ex.reason)) 111 | self._send_status("flasherror", message=ex.reason) 112 | return False 113 | except: 114 | self._logger.exception(u"Flashing failed. Unexpected error.") 115 | self._send_status("flasherror") 116 | return False 117 | 118 | class FlashException(Exception): 119 | def __init__(self, reason, *args, **kwargs): 120 | Exception.__init__(self, *args, **kwargs) 121 | self.reason = reason 122 | -------------------------------------------------------------------------------- /octoprint_firmwareupdater/static/css/firmwareupdater.css: -------------------------------------------------------------------------------- 1 | 2 | .big-icon { 3 | font-size: 1.3em; 4 | padding-top: 4px; 5 | padding-bottom: 2px; 6 | } 7 | 8 | .plugin-version { 9 | font-size:12px; 10 | opacity:0.6; 11 | } 12 | 13 | .btn-primary-fix { 14 | border-color: #04c #04c #002a80; 15 | } 16 | 17 | .color-black { 18 | color: #000; 19 | } 20 | 21 | .leftm-5 { 22 | margin-left: 5px; 23 | } 24 | 25 | .refreshdisabled { 26 | color: #808080 27 | } 28 | -------------------------------------------------------------------------------- /octoprint_firmwareupdater/templates/firmwareupdater_navbar.jinja2: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | ### 2 | # This file is only here to make sure that something like 3 | # 4 | # pip install -e . 5 | # 6 | # works as expected. Requirements can be found in setup.py. 7 | ### 8 | 9 | . 10 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | 3 | ######################################################################################################################## 4 | ### Do not forget to adjust the following variables to your own plugin. 5 | 6 | # The plugin's identifier, has to be unique 7 | plugin_identifier = "firmwareupdater" 8 | 9 | # The plugin's python package, should be "octoprint_", has to be unique 10 | plugin_package = "octoprint_firmwareupdater" 11 | 12 | # The plugin's human readable name. Can be overwritten within OctoPrint's internal data via __plugin_name__ in the 13 | # plugin module 14 | plugin_name = "OctoPrint-FirmwareUpdater" 15 | 16 | # The plugin's version. Can be overwritten within OctoPrint's internal data via __plugin_version__ in the plugin module 17 | plugin_version = "1.14.1" 18 | 19 | # The plugin's description. Can be overwritten within OctoPrint's internal data via __plugin_description__ in the plugin 20 | # module 21 | plugin_description = """Printer Firmware Updater""" 22 | 23 | # The plugin's author. Can be overwritten within OctoPrint's internal data via __plugin_author__ in the plugin module 24 | plugin_author = "Ben Lye and Gina Häußge, based on work by Nicanor Romero Venier" 25 | 26 | # The plugin's author's mail address. 27 | plugin_author_email = "ben@lye.co.nz" 28 | 29 | # The plugin's homepage URL. Can be overwritten within OctoPrint's internal data via __plugin_url__ in the plugin module 30 | plugin_url = "https://github.com/OctoPrint/OctoPrint-FirmwareUpdater" 31 | 32 | # The plugin's license. Can be overwritten within OctoPrint's internal data via __plugin_license__ in the plugin module 33 | plugin_license = "AGPLv3" 34 | 35 | # Any additional requirements besides OctoPrint should be listed here 36 | plugin_requires = ["pyserial>=3.4"] 37 | 38 | ### -------------------------------------------------------------------------------------------------------------------- 39 | ### More advanced options that you usually shouldn't have to touch follow after this point 40 | ### -------------------------------------------------------------------------------------------------------------------- 41 | 42 | # Additional package data to install for this plugin. The subfolders "templates", "static" and "translations" will 43 | # already be installed automatically if they exist. 44 | plugin_additional_data = [] 45 | 46 | # Any additional python packages you need to install with your plugin that are not contains in .* 47 | plugin_addtional_packages = [] 48 | 49 | # Any python packages within .* you do NOT want to install with your plugin 50 | plugin_ignored_packages = [] 51 | 52 | # Additional parameters for the call to setuptools.setup. If your plugin wants to register additional entry points, 53 | # define dependency links or other things like that, this is the place to go. Will be merged recursively with the 54 | # default setup parameters as provided by octoprint_setuptools.create_plugin_setup_parameters using 55 | # octoprint.util.dict_merge. 56 | # 57 | # Example: 58 | # plugin_requires = ["someDependency==dev"] 59 | # additional_setup_parameters = {"dependency_links": ["https://github.com/someUser/someRepo/archive/master.zip#egg=someDependency-dev"]} 60 | additional_setup_parameters = {} 61 | 62 | ######################################################################################################################## 63 | 64 | from setuptools import setup 65 | 66 | try: 67 | import octoprint_setuptools 68 | except: 69 | print("Could not import OctoPrint's setuptools, are you sure you are running that under " 70 | "the same python installation that OctoPrint is installed under?") 71 | import sys 72 | sys.exit(-1) 73 | 74 | setup_parameters = octoprint_setuptools.create_plugin_setup_parameters( 75 | identifier=plugin_identifier, 76 | package=plugin_package, 77 | name=plugin_name, 78 | version=plugin_version, 79 | description=plugin_description, 80 | author=plugin_author, 81 | mail=plugin_author_email, 82 | url=plugin_url, 83 | license=plugin_license, 84 | requires=plugin_requires, 85 | additional_packages=plugin_addtional_packages, 86 | ignored_packages=plugin_ignored_packages, 87 | additional_data=plugin_additional_data 88 | ) 89 | 90 | if len(additional_setup_parameters): 91 | from octoprint.util import dict_merge 92 | setup_parameters = dict_merge(setup_parameters, additional_setup_parameters) 93 | 94 | setup(**setup_parameters) 95 | -------------------------------------------------------------------------------- /translations/README.txt: -------------------------------------------------------------------------------- 1 | Your plugin's translations will reside here. The provided setup.py supports a 2 | couple of additional commands to make managing your translations easier: 3 | 4 | babel_extract 5 | Extracts any translateable messages (marked with Jinja's `_("...")` or 6 | JavaScript's `gettext("...")`) and creates the initial `messages.pot` file. 7 | babel_refresh 8 | Reruns extraction and updates the `messages.pot` file. 9 | babel_new --locale= 10 | Creates a new translation folder for locale ``. 11 | babel_compile 12 | Compiles the translations into `mo` files, ready to be used within 13 | OctoPrint. 14 | babel_pack --locale= [ --author= ] 15 | Packs the translation for locale `` up as an installable 16 | language pack that can be manually installed by your plugin's users. This is 17 | interesting for languages you can not guarantee to keep up to date yourself 18 | with each new release of your plugin and have to depend on contributors for. 19 | 20 | If you want to bundle translations with your plugin, create a new folder 21 | `octoprint_firmwareupdater/translations`. When that folder exists, 22 | an additional command becomes available: 23 | 24 | babel_bundle --locale= 25 | Moves the translation for locale `` to octoprint_firmwareupdater/translations, 26 | effectively bundling it with your plugin. This is interesting for languages 27 | you can guarantee to keep up to date yourself with each new release of your 28 | plugin. 29 | --------------------------------------------------------------------------------