├── .gitignore ├── MANIFEST.in ├── .travis.yml ├── setup.py ├── README.md ├── LICENSE └── esptool.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.bin 2 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include README.md 2 | include LICENSE 3 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | sudo: false 3 | 4 | python: 5 | - "2.7" 6 | 7 | install: 8 | - pip install pyflakes 9 | - pip install pep8 10 | 11 | script: 12 | - python setup.py build 13 | - pyflakes *.py 14 | - pep8 --max-line-length=160 --ignore=E231,E221 *.py 15 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | from codecs import open 3 | from os import path 4 | 5 | here = path.abspath(path.dirname(__file__)) 6 | 7 | with open(path.join(here, 'README.md'), encoding='utf-8') as f: 8 | long_description = f.read() 9 | 10 | setup( 11 | name='esptool', 12 | version='0.1.0', 13 | description='A utility to communicate with the ROM bootloader in Espressif ESP8266.', 14 | long_description=long_description, 15 | url='https://github.com/themadinventor/esptool', 16 | author='Fredrik Ahlberg', 17 | author_email='fredrik@z80.se', 18 | license='GPLv2+', 19 | classifiers=[ 20 | 'Development Status :: 4 - Beta', 21 | 'Intended Audience :: Developers', 22 | 'Topic :: Software Development :: Embedded Systems', 23 | 'Environment :: Console', 24 | 'License :: OSI Approved :: GNU General Public License v2 or later (GPLv2+)', 25 | 'Programming Language :: Python :: 2.7', 26 | ], 27 | install_requires=[ 28 | 'pyserial', 29 | ], 30 | scripts=[ 31 | 'esptool.py', 32 | ], 33 | ) 34 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # esptool 2 | 3 | A cute Python utility to communicate with the ROM bootloader in Espressif ESP8266. 4 | It is intended to be a simple, platform independent, open source replacement for XTCOM. 5 | 6 | [![Build Status](https://travis-ci.org/themadinventor/esptool.svg?branch=master)](https://travis-ci.org/themadinventor/esptool) 7 | 8 | ## Installation / dependencies 9 | 10 | esptool depends on [pySerial](http://pyserial.sourceforge.net/) for serial communication 11 | with the target device. 12 | 13 | If you choose to install esptool system-wide by running `python setup.py install`, then 14 | this will be taken care of automatically. 15 | 16 | If not using `setup.py`, then you'll have to install pySerial manually 17 | by running something like `pip install pyserial`, `easy_install pyserial` or `apt-get install python-serial`, 18 | depending on your platform. (The official pySerial installation instructions are 19 | [here](http://pyserial.sourceforge.net/pyserial.html#installation)). 20 | 21 | ## Usage 22 | 23 | This utility actually have a user interface! It uses [Argparse](https://docs.python.org/dev/library/argparse.html) 24 | and is rather self-documenting. Try running `esptool -h`, `esptool write_flash -h`, etc. 25 | Or hack the script to your hearts content. 26 | 27 | ### Ports 28 | 29 | The serial port is selected using the `-p` option, like `-p /dev/ttyUSB0` (on unixen like Linux and OSX) or `-p COM1` 30 | (on Windows). The perhaps not so obvious corner case here is when you run esptool in Cygwin on Windows, where you have to convert the Windows-style name into an Unix-style path (`COM1` -> `/dev/ttyS0`, and so on). 31 | 32 | The baudrate may be set using `-b 921600` (or another baudrate of your choice) to speed up large transfers. 33 | 34 | ### Examples 35 | Typical usage: 36 | 37 | Converting an ELF file to the two binary blobs to be flashed: 38 | ``` 39 | ./esptool.py elf2image my_app.elf 40 | ``` 41 | This creates `my_app.elf-0x00000.bin` and `my_app.elf-0x40000.bin`. 42 | 43 | Writing those binaries to flash: 44 | ``` 45 | ./esptool.py write_flash 0x00000 my_app.elf-0x00000.bin 0x40000 my_app.elf-0x40000.bin 46 | ``` 47 | 48 | You can also create a bootable application image from binary blobs: 49 | ``` 50 | ./esptool.py make_image -f app.text.bin -a 0x40100000 -f app.data.bin -a 0x3ffe8000 -f app.rodata.bin -a 0x3ffe8c00 app.flash.bin 51 | ``` 52 | 53 | Dumping the ROM (64 KiB) from the chip: 54 | ``` 55 | ./esptool.py dump_mem 0x40000000 65536 iram0.bin 56 | ``` 57 | 58 | Reading the MAC Address: 59 | ``` 60 | ./esptool.py read_mac 61 | ``` 62 | 63 | Reading the SPI Flash ID: 64 | ``` 65 | ./esptool.py flash_id 66 | ``` 67 | 68 | Refer to [flashrom source code](http://code.coreboot.org/p/flashrom/source/tree/HEAD/trunk/flashchips.h) for flash chip manufacturer name and part number. 69 | 70 | Note that this document may be out of date. Use the built-in usage (`esptool -h`) when in doubt. 71 | 72 | ## Protocol 73 | 74 | If GPIO0 and GPIO15 is pulled down and GPIO2 is pulled high when the module leaves reset, 75 | then the bootloader will enter the UART download mode. The ROM auto-bauds, that is, it will 76 | automagically detect which baud rate you are using. esptool defaults to 115200. 77 | 78 | esptool uses the RTS and DTR modem status lines to automatically enter the bootloader. 79 | Connect RTS to CH_PD (which is used as active-low reset) and DTR to GPIO0. 80 | 81 | The bootloader protocol uses [SLIP](http://en.wikipedia.org/wiki/SLIP) framing. 82 | Each packet begin and end with `0xC0`, all occurrences of `0xC0` and `0xDB` inside the packet 83 | are replaced with `0xDB 0xDC` and `0xDB 0xDD`, respectively. 84 | 85 | Inside the frame, the packet consists of a header and a variable-length body. 86 | All multi-byte fields are little-endian. 87 | 88 | ### Request 89 | 90 | Byte | Name | Comment 91 | -------|----------------|------------------------------- 92 | 0 | Direction | Always `0x00` for requests 93 | 1 | Command | Requested operation, according to separate table 94 | 2-3 | Size | Size of body 95 | 4-7 | Checksum | XOR checksum of payload, only used in block transfer packets 96 | 8..n | Body | Depends on operation 97 | 98 | ### Response 99 | 100 | Byte | Name | Comment 101 | -------|----------------|------------------------------- 102 | 0 | Direction | Always `0x01` for responses 103 | 1 | Command | Same value as in the request packet that trigged the response 104 | 2-3 | Size | Size of body, normally 2 105 | 4-7 | Value | Response data for some operations 106 | 8..n | Body | Depends on operation 107 | 8 | Status | Status flag, success (`0`) or failure (`1`) 108 | 9 | Error | Last error code, not reset on success 109 | 110 | ### Opcodes 111 | 112 | Byte | Name | Input | Output 113 | -------|------------------------|---------------|------------------------ 114 | `0x02` | Flash Download Start | total size, number of blocks, block size, offset | 115 | `0x03` | Flash Download Data | size, sequence number, data. checksum in value field. | 116 | `0x04` | Flash Download Finish | reboot flag? | 117 | `0x05` | RAM Download Start | total size, packet size, number of packets, memory offset | 118 | `0x06` | RAM Download Finish | execute flag, entry point | 119 | `0x07` | RAM Download Data | size, sequence numer, data. checksum in dedicated field. | 120 | `0x08` | Sync Frame | `0x07 0x07 0x12 0x20`, `0x55` 32 times | 121 | `0x09` | Write register | Four 32-bit words: address, value, mask and delay (in microseconds) | Body is `0x00 0x00` if successful 122 | `0x0a` | Read register | Address as 32-bit word | Read data as 32-bit word in `value` field 123 | `0x0b` | Configure SPI params | 24 bytes of unidentified SPI parameters | 124 | 125 | ### Checksum 126 | Each byte in the payload is XOR'ed together, as well as the magic number `0xEF`. 127 | The result is stored as a zero-padded byte in the 32-bit checksum field in the header. 128 | 129 | ## Firmware image format 130 | The firmware file consists of a header, a variable number of data segments and a footer. 131 | Multi-byte fields are little-endian. 132 | 133 | ### File header 134 | 135 | Byte | Description 136 | --------|----------------------- 137 | 0 | Always `0xE9` 138 | 1 | Number of segments 139 | 2 | SPI Flash Interface (`0` = QIO, `1` = QOUT, `2` = DIO, `0x3` = DOUT) 140 | 3 | High four bits: `0` = 512K, `1` = 256K, `2` = 1M, `3` = 2M, `4` = 4M, Low four bits: `0` = 40MHz, `1`= 26MHz, `2` = 20MHz, `0xf` = 80MHz 141 | 4-7 | Entry point 142 | 8-n | Segments 143 | 144 | esptool overrides the 2nd and 3rd (start from 0) bytes according to the SPI flash info provided through command line option, regardless of corresponding bytes from the input .bin file that will be written to address 0x00000. So you must provide SPI flash info when running `esptool write_flash` command. For example `esptool write_flash -ff 80m -fm qio -fs 8m 0x00000 boot.bin 0x01000 user1.bin` 145 | 146 | ### Segment 147 | 148 | Byte | Description 149 | --------|----------------------- 150 | 0-3 | Memory offset 151 | 4-7 | Segment size 152 | 8...n | Data 153 | 154 | ### Footer 155 | The file is padded with zeros until its size is one byte less than a multiple of 16 bytes. A last byte (thus making the file size a multiple of 16) is the checksum of the data of all segments. The checksum is defined as the xor-sum of all bytes and the byte `0xEF`. 156 | 157 | ## Boot log 158 | The boot rom writes a log to the UART when booting. The timing is a little bit unusual: 74880 baud 159 | 160 | ``` 161 | ets Jan 8 2014,rst cause 1, boot mode:(3,7) 162 | 163 | load 0x40100000, len 24236, room 16 164 | tail 12 165 | chksum 0xb7 166 | ho 0 tail 12 room 4 167 | load 0x3ffe8000, len 3008, room 12 168 | tail 4 169 | chksum 0x2c 170 | load 0x3ffe8bc0, len 4816, room 4 171 | tail 12 172 | chksum 0x46 173 | csum 0x46 174 | ``` 175 | 176 | ## About 177 | 178 | esptool was initially created by Fredrik Ahlberg (themadinventor, kongo), but has since received improvements from several members of the ESP8266 community, including pfalcon, tommie, 0ff and george-hopkins. 179 | 180 | This document and the attached source code is released under GPLv2. 181 | 182 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /esptool.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # 3 | # ESP8266 ROM Bootloader Utility 4 | # https://github.com/themadinventor/esptool 5 | # 6 | # Copyright (C) 2014 Fredrik Ahlberg 7 | # 8 | # This program is free software; you can redistribute it and/or modify it under 9 | # the terms of the GNU General Public License as published by the Free Software 10 | # Foundation; either version 2 of the License, or (at your option) any later version. 11 | # 12 | # This program is distributed in the hope that it will be useful, but WITHOUT 13 | # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 14 | # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU General Public License along with 17 | # this program; if not, write to the Free Software Foundation, Inc., 51 Franklin 18 | # Street, Fifth Floor, Boston, MA 02110-1301 USA. 19 | 20 | import sys 21 | import struct 22 | import serial 23 | import time 24 | import argparse 25 | import os 26 | import subprocess 27 | import tempfile 28 | 29 | 30 | class ESPROM: 31 | # These are the currently known commands supported by the ROM 32 | ESP_FLASH_BEGIN = 0x02 33 | ESP_FLASH_DATA = 0x03 34 | ESP_FLASH_END = 0x04 35 | ESP_MEM_BEGIN = 0x05 36 | ESP_MEM_END = 0x06 37 | ESP_MEM_DATA = 0x07 38 | ESP_SYNC = 0x08 39 | ESP_WRITE_REG = 0x09 40 | ESP_READ_REG = 0x0a 41 | 42 | # Maximum block sized for RAM and Flash writes, respectively. 43 | ESP_RAM_BLOCK = 0x1800 44 | ESP_FLASH_BLOCK = 0x100 45 | 46 | # Default baudrate. The ROM auto-bauds, so we can use more or less whatever we want. 47 | ESP_ROM_BAUD = 115200 48 | 49 | # First byte of the application image 50 | ESP_IMAGE_MAGIC = 0xe9 51 | 52 | # Initial state for the checksum routine 53 | ESP_CHECKSUM_MAGIC = 0xef 54 | 55 | # OTP ROM addresses 56 | ESP_OTP_MAC0 = 0x3ff00050 57 | ESP_OTP_MAC1 = 0x3ff00054 58 | 59 | # Sflash stub: an assembly routine to read from spi flash and send to host 60 | SFLASH_STUB = "\x80\x3c\x00\x40\x1c\x4b\x00\x40\x21\x11\x00\x40\x00\x80" \ 61 | "\xfe\x3f\xc1\xfb\xff\xd1\xf8\xff\x2d\x0d\x31\xfd\xff\x41\xf7\xff\x4a" \ 62 | "\xdd\x51\xf9\xff\xc0\x05\x00\x21\xf9\xff\x31\xf3\xff\x41\xf5\xff\xc0" \ 63 | "\x04\x00\x0b\xcc\x56\xec\xfd\x06\xff\xff\x00\x00" 64 | 65 | def __init__(self, port=0, baud=ESP_ROM_BAUD): 66 | self._port = serial.Serial(port) 67 | # setting baud rate in a separate step is a workaround for 68 | # CH341 driver on some Linux versions (this opens at 9600 then 69 | # sets), shouldn't matter for other platforms/drivers. See 70 | # https://github.com/themadinventor/esptool/issues/44#issuecomment-107094446 71 | self._port.baudrate = baud 72 | 73 | """ Read bytes from the serial port while performing SLIP unescaping """ 74 | def read(self, length=1): 75 | b = '' 76 | while len(b) < length: 77 | c = self._port.read(1) 78 | if c == '\xdb': 79 | c = self._port.read(1) 80 | if c == '\xdc': 81 | b = b + '\xc0' 82 | elif c == '\xdd': 83 | b = b + '\xdb' 84 | else: 85 | raise FatalError('Invalid SLIP escape') 86 | else: 87 | b = b + c 88 | return b 89 | 90 | """ Write bytes to the serial port while performing SLIP escaping """ 91 | def write(self, packet): 92 | buf = '\xc0' \ 93 | + (packet.replace('\xdb','\xdb\xdd').replace('\xc0','\xdb\xdc')) \ 94 | + '\xc0' 95 | self._port.write(buf) 96 | 97 | """ Calculate checksum of a blob, as it is defined by the ROM """ 98 | @staticmethod 99 | def checksum(data, state=ESP_CHECKSUM_MAGIC): 100 | for b in data: 101 | state ^= ord(b) 102 | return state 103 | 104 | """ Send a request and read the response """ 105 | def command(self, op=None, data=None, chk=0): 106 | if op: 107 | pkt = struct.pack(' 0: 116 | (op_ret, val, body) = self.receive_response() 117 | if op is None or op_ret == op: 118 | return val, body # valid response received 119 | retries = retries - 1 120 | 121 | raise FatalError("Response doesn't match request") 122 | 123 | """ Receive a response to a command """ 124 | def receive_response(self): 125 | # Read header of response and parse 126 | if self._port.read(1) != '\xc0': 127 | raise FatalError('Invalid head of packet') 128 | hdr = self.read(8) 129 | (resp, op_ret, len_ret, val) = struct.unpack('> 16) & 0xff) == 0: 247 | oui = (0x18, 0xfe, 0x34) 248 | elif ((mac1 >> 16) & 0xff) == 1: 249 | oui = (0xac, 0xd0, 0x74) 250 | else: 251 | raise FatalError("Unknown OUI") 252 | return oui + ((mac1 >> 8) & 0xff, mac1 & 0xff, (mac0 >> 24) & 0xff) 253 | 254 | """ Read SPI flash manufacturer and device id """ 255 | def flash_id(self): 256 | self.flash_begin(0, 0) 257 | self.write_reg(0x60000240, 0x0, 0xffffffff) 258 | self.write_reg(0x60000200, 0x10000000, 0xffffffff) 259 | flash_id = self.read_reg(0x60000240) 260 | self.flash_finish(False) 261 | return flash_id 262 | 263 | """ Read SPI flash """ 264 | def flash_read(self, offset, size, count=1): 265 | # Create a custom stub 266 | stub = struct.pack(' 16: 327 | raise FatalError('Invalid firmware image') 328 | 329 | for i in xrange(segments): 330 | (offset, size) = struct.unpack(' 0x40200000 or offset < 0x3ffe0000 or size > 65536: 332 | raise FatalError('Suspicious segment 0x%x, length %d' % (offset, size)) 333 | segment_data = f.read(size) 334 | if len(segment_data) < size: 335 | raise FatalError('End of file reading segment 0x%x, length %d (actual length %d)' % (offset, size, len(segment_data))) 336 | self.segments.append((offset, size, segment_data)) 337 | 338 | # Skip the padding. The checksum is stored in the last byte so that the 339 | # file is a multiple of 16 bytes. 340 | align = 15 - (f.tell() % 16) 341 | f.seek(align, 1) 342 | 343 | self.checksum = ord(f.read(1)) 344 | 345 | def add_segment(self, addr, data): 346 | # Data should be aligned on word boundary 347 | l = len(data) 348 | if l % 4: 349 | data += b"\x00" * (4 - l % 4) 350 | if l > 0: 351 | self.segments.append((addr, len(data), data)) 352 | 353 | def save(self, filename): 354 | f = file(filename, 'wb') 355 | f.write(struct.pack(' 0: 579 | esp.mem_block(data[0:esp.ESP_RAM_BLOCK], seq) 580 | data = data[esp.ESP_RAM_BLOCK:] 581 | seq += 1 582 | print 'done!' 583 | 584 | print 'All segments done, executing at %08x' % image.entrypoint 585 | esp.mem_finish(image.entrypoint) 586 | 587 | elif args.operation == 'read_mem': 588 | print '0x%08x = 0x%08x' % (args.address, esp.read_reg(args.address)) 589 | 590 | elif args.operation == 'write_mem': 591 | esp.write_reg(args.address, args.value, args.mask, 0) 592 | print 'Wrote %08x, mask %08x to %08x' % (args.value, args.mask, args.address) 593 | 594 | elif args.operation == 'dump_mem': 595 | f = file(args.filename, 'wb') 596 | for i in xrange(args.size / 4): 597 | d = esp.read_reg(args.address + (i * 4)) 598 | f.write(struct.pack(' 0: 625 | print '\rWriting at 0x%08x... (%d %%)' % (address + seq * esp.ESP_FLASH_BLOCK, 100 * (seq + 1) / blocks), 626 | sys.stdout.flush() 627 | block = image[0:esp.ESP_FLASH_BLOCK] 628 | # Fix sflash config data 629 | if address == 0 and seq == 0 and block[0] == '\xe9': 630 | block = block[0:2] + flash_info + block[4:] 631 | # Pad the last block 632 | block = block + '\xff' * (esp.ESP_FLASH_BLOCK - len(block)) 633 | esp.flash_block(block, seq) 634 | image = image[esp.ESP_FLASH_BLOCK:] 635 | seq += 1 636 | written += len(block) 637 | t = time.time() - t 638 | print '\rWrote %d bytes at 0x%08x in %.1f seconds (%.1f kbit/s)...' % (written, address, t, written / t * 8 / 1000) 639 | print '\nLeaving...' 640 | if args.flash_mode == 'dio': 641 | esp.flash_unlock_dio() 642 | else: 643 | esp.flash_begin(0, 0) 644 | esp.flash_finish(False) 645 | 646 | elif args.operation == 'run': 647 | esp.run() 648 | 649 | elif args.operation == 'image_info': 650 | image = ESPFirmwareImage(args.filename) 651 | print ('Entry point: %08x' % image.entrypoint) if image.entrypoint != 0 else 'Entry point not set' 652 | print '%d segments' % len(image.segments) 653 | print 654 | checksum = ESPROM.ESP_CHECKSUM_MAGIC 655 | for (idx, (offset, size, data)) in enumerate(image.segments): 656 | print 'Segment %d: %5d bytes at %08x' % (idx + 1, size, offset) 657 | checksum = ESPROM.checksum(data, checksum) 658 | print 659 | print 'Checksum: %02x (%s)' % (image.checksum, 'valid' if image.checksum == checksum else 'invalid!') 660 | 661 | elif args.operation == 'make_image': 662 | image = ESPFirmwareImage() 663 | if len(args.segfile) == 0: 664 | raise FatalError('No segments specified') 665 | if len(args.segfile) != len(args.segaddr): 666 | raise FatalError('Number of specified files does not match number of specified addresses') 667 | for (seg, addr) in zip(args.segfile, args.segaddr): 668 | data = file(seg, 'rb').read() 669 | image.add_segment(addr, data) 670 | image.entrypoint = args.entrypoint 671 | image.save(args.output) 672 | 673 | elif args.operation == 'elf2image': 674 | if args.output is None: 675 | args.output = args.input + '-' 676 | e = ELFFile(args.input) 677 | image = ESPFirmwareImage() 678 | image.entrypoint = e.get_entry_point() 679 | for section, start in ((".text", "_text_start"), (".data", "_data_start"), (".rodata", "_rodata_start")): 680 | data = e.load_section(section) 681 | image.add_segment(e.get_symbol_addr(start), data) 682 | 683 | image.flash_mode = {'qio':0, 'qout':1, 'dio':2, 'dout': 3}[args.flash_mode] 684 | image.flash_size_freq = {'4m':0x00, '2m':0x10, '8m':0x20, '16m':0x30, '32m':0x40, '16m-c1': 0x50, '32m-c1':0x60, '32m-c2':0x70}[args.flash_size] 685 | image.flash_size_freq += {'40m':0, '26m':1, '20m':2, '80m': 0xf}[args.flash_freq] 686 | 687 | image.save(args.output + "0x00000.bin") 688 | data = e.load_section(".irom0.text") 689 | off = e.get_symbol_addr("_irom0_text_start") - 0x40200000 690 | assert off >= 0 691 | f = open(args.output + "0x%05x.bin" % off, "wb") 692 | f.write(data) 693 | f.close() 694 | 695 | elif args.operation == 'read_mac': 696 | mac = esp.read_mac() 697 | print 'MAC: %s' % ':'.join(map(lambda x: '%02x' % x, mac)) 698 | 699 | elif args.operation == 'flash_id': 700 | flash_id = esp.flash_id() 701 | print 'Manufacturer: %02x' % (flash_id & 0xff) 702 | print 'Device: %02x%02x' % ((flash_id >> 8) & 0xff, (flash_id >> 16) & 0xff) 703 | 704 | elif args.operation == 'read_flash': 705 | print 'Please wait...' 706 | file(args.filename, 'wb').write(esp.flash_read(args.address, 1024, div_roundup(args.size, 1024))[:args.size]) 707 | 708 | elif args.operation == 'erase_flash': 709 | esp.flash_erase() 710 | 711 | if __name__ == '__main__': 712 | try: 713 | main() 714 | except FatalError as e: 715 | print '\nA fatal error occurred: %s' % e 716 | sys.exit(2) 717 | --------------------------------------------------------------------------------