├── .gitignore
├── .gitmodules
├── .travis.yml
├── .vscode
├── .cortex-debug.peripherals.state.json
├── .cortex-debug.registers.state.json
├── c_cpp_properties.json
├── launch.json
├── settings.json
└── tasks.json
├── LICENSE
├── Makefile
├── README.txt
├── can-updater.py
├── firmware_loader.cbp
├── include
└── hwinit.h
├── src
├── hwinit.cpp
└── stm32_canloader.cpp
├── stm32_canloader.ld
└── uart-updater.py
/.gitignore:
--------------------------------------------------------------------------------
1 | *.o
2 | obj
3 | linker.map
4 | *.hex
5 | *.bin
6 | stm32_canloader
7 | .vscode
8 |
--------------------------------------------------------------------------------
/.gitmodules:
--------------------------------------------------------------------------------
1 | [submodule "libopencm3"]
2 | path = libopencm3
3 | url = https://github.com/jsphuebner/libopencm3
4 |
5 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: cpp
2 | install: make get-deps
3 |
4 | script:
5 | - make
6 | - cd bootupdater && make
7 |
8 | addons:
9 | apt:
10 | sources:
11 | - sourceline: 'ppa:team-gcc-arm-embedded/ppa'
12 | packages:
13 | - gcc-arm-embedded
14 |
15 |
--------------------------------------------------------------------------------
/.vscode/.cortex-debug.peripherals.state.json:
--------------------------------------------------------------------------------
1 | [{"node":"SPI2","expanded":false,"format":0,"pinned":true},{"node":"CAN1.CAN_TSR","expanded":true,"format":0},{"node":"DMA1.ISR","expanded":true,"format":0},{"node":"DMA1.CNDTR4","expanded":true,"format":0},{"node":"RCC.CR","expanded":true,"format":0},{"node":"RCC.CFGR","expanded":true,"format":0},{"node":"SPI1.CR1","expanded":true,"format":0}]
--------------------------------------------------------------------------------
/.vscode/.cortex-debug.registers.state.json:
--------------------------------------------------------------------------------
1 | []
--------------------------------------------------------------------------------
/.vscode/c_cpp_properties.json:
--------------------------------------------------------------------------------
1 | {
2 | "configurations": [
3 | {
4 | "name": "Linux", //no big deal but shouldn't this reflect project name? Like "STM32-VCU"
5 | "includePath": [
6 | "${workspaceFolder}/include",
7 | "${workspaceFolder}/libopeninv/include",
8 | "${workspaceFolder}/libopencm3/include"
9 | ],
10 | "defines": [
11 | "STM32F1"
12 | ],
13 | "compilerPath": "${env:ARMGCC_DIR}/arm-none-eabi-gcc.exe", //"/usr/lib64/ccache/arm-none-eabi-gcc" use env variable to specify compiler path, hopefully this will work on Linux as well
14 | "cStandard": "c11",
15 | "intelliSenseMode": "gcc-arm", //"linux-gcc-arm" is not acceptable value on Windows, hopefully this will work on Linux as well
16 | "cppStandard": "c++17",
17 | "configurationProvider": "ms-vscode.cmake-tools"
18 | }
19 | ],
20 | "version": 4
21 | }
--------------------------------------------------------------------------------
/.vscode/launch.json:
--------------------------------------------------------------------------------
1 | {
2 | // Use IntelliSense to learn about possible attributes.
3 | // Hover to view descriptions of existing attributes.
4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
5 | "version": "0.2.0",
6 | "configurations": [
7 | {
8 | "name": "Cortex Debug",
9 | "cwd": "${workspaceRoot}",
10 | "executable": "./stm32_canloader",
11 | "request": "launch",
12 | "type": "cortex-debug",
13 | "servertype": "openocd",
14 | "preLaunchTask": "make_clean",
15 | "device": "STM32F107xC",
16 | "configFiles": [
17 | "interface/stlink.cfg",
18 | "target/stm32f1x.cfg"
19 | ],
20 | "svdFile": "./STM32F107.svd"
21 |
22 | }
23 | ]
24 | }
--------------------------------------------------------------------------------
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "files.associations": {
3 | "array": "cpp",
4 | "string": "cpp",
5 | "string_view": "cpp",
6 | "ranges": "cpp",
7 | "utils.h": "c",
8 | "digio.h": "c",
9 | "digio_prj.h": "c",
10 | "hwdefs.h": "c",
11 | "flash.h": "c",
12 | "common.h": "c",
13 | "stdio.h": "c",
14 | "command.h": "c",
15 | "config.h": "c",
16 | "can_interface.h": "c",
17 | "timeout.h": "c",
18 | "string.h": "c",
19 | "stm32_can.h": "c",
20 | "flash_writer.h": "c",
21 | "my_string.h": "c",
22 | "stm32_loader.h": "c",
23 | "stm32_canloader.h": "c",
24 | "params.h": "c",
25 | "param_prj.h": "c",
26 | "desig.h": "c",
27 | "stm32scheduler.h": "c",
28 | "param_save.h": "c",
29 | "hwinit.h": "c",
30 | "crc.h": "c",
31 | "memorymap.h": "c"
32 | },
33 | "C_Cpp.errorSquiggles": "Enabled"
34 | }
--------------------------------------------------------------------------------
/.vscode/tasks.json:
--------------------------------------------------------------------------------
1 | {
2 | // See https://go.microsoft.com/fwlink/?LinkId=733558
3 | // for the documentation about the tasks.json format
4 | "version": "2.0.0",
5 | "tasks": [
6 | {
7 | "label": "make",
8 | "type": "shell",
9 | "command": "make",
10 | "problemMatcher": [],
11 | "group": {
12 | "kind": "build",
13 | "isDefault": true
14 | }
15 | },
16 | {
17 | "label": "make_clean",
18 | "type": "shell",
19 | "command": "make clean ; make",
20 | },
21 | ]
22 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 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 General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | ##
2 | ## This file is part of the libopenstm32 project.
3 | ##
4 | ## Copyright (C) 2009 Uwe Hermann
5 | ##
6 | ## This program is free software: you can redistribute it and/or modify
7 | ## it under the terms of the GNU General Public License as published by
8 | ## the Free Software Foundation, either version 3 of the License, or
9 | ## (at your option) any later version.
10 | ##
11 | ## This program is distributed in the hope that it will be useful,
12 | ## but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | ## GNU General Public License for more details.
15 | ##
16 | ## You should have received a copy of the GNU General Public License
17 | ## along with this program. If not, see .
18 | ##
19 | BINARY = stm32_canloader
20 | OUT_DIR = obj
21 | PREFIX ?= arm-none-eabi
22 | #PREFIX ?= arm-elf
23 | SIZE = $(PREFIX)-size
24 | CC = $(PREFIX)-gcc
25 | CPP = $(PREFIX)-g++
26 | LD = $(PREFIX)-gcc
27 | OBJCOPY = $(PREFIX)-objcopy
28 | OBJDUMP = $(PREFIX)-objdump
29 | MKDIR_P = mkdir -p
30 | TERMINAL_DEBUG ?= 0
31 | CFLAGS = -Os -Wall -Wextra -Ilibopeninv/include -Iinclude/ -Ilibopencm3/include \
32 | -fno-common -fno-builtin -pedantic -DSTM32F1 -DT_DEBUG=$(TERMINAL_DEBUG) \
33 | -mcpu=cortex-m3 -mthumb -std=gnu99 -ffunction-sections -fdata-sections -g
34 | CPPFLAGS = -Os -Wall -Wextra -Ilibopeninv/include -Iinclude/ -Ilibopencm3/include \
35 | -fno-common -std=c++11 -pedantic -DSTM32F1 -DT_DEBUG=$(TERMINAL_DEBUG) \
36 | -ffunction-sections -fdata-sections -fno-builtin -fno-rtti -fno-exceptions -fno-unwind-tables -mcpu=cortex-m3 -mthumb -g
37 | LDSCRIPT = $(BINARY).ld
38 | LDFLAGS = -Llibopencm3/lib -T$(LDSCRIPT) -nostartfiles -Wl,--gc-sections,-Map,linker.map
39 | OBJSL = $(BINARY).o hwinit.o
40 | OBJS = $(patsubst %.o,$(OUT_DIR)/%.o, $(OBJSL))
41 | vpath %.c src/ libopeninv/src/
42 | vpath %.cpp src/ libopeninv/src/
43 |
44 | OPENOCD_BASE = /usr
45 | OPENOCD = $(OPENOCD_BASE)/bin/openocd
46 | OPENOCD_SCRIPTS = $(OPENOCD_BASE)/share/openocd/scripts
47 | OPENOCD_FLASHER = $(OPENOCD_SCRIPTS)/interface/parport.cfg
48 | OPENOCD_BOARD = $(OPENOCD_SCRIPTS)/board/olimex_stm32_h103.cfg
49 |
50 | # Be silent per default, but 'make V=1' will show all compiler calls.
51 | ifneq ($(V),1)
52 | Q := @
53 | NULL := 2>/dev/null
54 | endif
55 |
56 | all: directories images
57 | Debug:images
58 | Release: images
59 | cleanDebug:clean
60 | images: get-deps $(BINARY)
61 | @printf " OBJCOPY $(BINARY).bin\n"
62 | $(Q)$(OBJCOPY) -Obinary $(BINARY) $(BINARY).bin
63 | @printf " OBJCOPY $(BINARY).hex\n"
64 | $(Q)$(OBJCOPY) -Oihex $(BINARY) $(BINARY).hex
65 | $(Q)$(SIZE) $(BINARY)
66 |
67 | directories: ${OUT_DIR}
68 |
69 | ${OUT_DIR}:
70 | $(Q)${MKDIR_P} ${OUT_DIR}
71 |
72 | $(BINARY): $(OBJS) $(LDSCRIPT)
73 | @printf " LD $(subst $(shell pwd)/,,$(@))\n"
74 | $(Q)$(LD) $(LDFLAGS) -o $(BINARY) $(OBJS) -lopencm3_stm32f1
75 |
76 | $(OUT_DIR)/%.o: %.c Makefile
77 | @printf " CC $(subst $(shell pwd)/,,$(@))\n"
78 | $(Q)$(CC) $(CFLAGS) -o $@ -c $<
79 |
80 | $(OUT_DIR)/%.o: %.cpp Makefile
81 | @printf " CPP $(subst $(shell pwd)/,,$(@))\n"
82 | $(Q)$(CPP) $(CPPFLAGS) -o $@ -c $<
83 |
84 | clean:
85 | @printf " CLEAN ${OUT_DIR}\n"
86 | $(Q)rm -rf ${OUT_DIR}
87 | @printf " CLEAN $(BINARY)\n"
88 | $(Q)rm -f $(BINARY)
89 | @printf " CLEAN $(BINARY).bin\n"
90 | $(Q)rm -f $(BINARY).bin
91 | @printf " CLEAN $(BINARY).hex\n"
92 | $(Q)rm -f $(BINARY).hex
93 | @printf " CLEAN $(BINARY).srec\n"
94 | $(Q)rm -f $(BINARY).srec
95 | @printf " CLEAN $(BINARY).list\n"
96 | $(Q)rm -f $(BINARY).list
97 |
98 | flash: images
99 | @printf " FLASH $(BINARY).bin\n"
100 | @# IMPORTANT: Don't use "resume", only "reset" will work correctly!
101 | $(Q)$(OPENOCD) -s $(OPENOCD_SCRIPTS) \
102 | -f $(OPENOCD_FLASHER) \
103 | -f $(OPENOCD_BOARD) \
104 | -c "init" -c "reset halt" \
105 | -c "flash write_image erase $(BINARY).hex" \
106 | -c "reset" \
107 | -c "shutdown" $(NULL)
108 |
109 | .PHONY: directories get-deps images clean
110 |
111 | get-deps:
112 | ifneq ($(shell test -s libopencm3/lib/libopencm3_stm32f1.a && echo -n yes),yes)
113 | @printf " GIT SUBMODULE\n"
114 | $(Q)git submodule update --init
115 | @printf " MAKE libopencm3\n"
116 | $(Q)${MAKE} -C libopencm3 TARGETS=stm32/f1
117 | endif
118 |
119 | Test:
120 | cd test && $(MAKE)
121 | cleanTest:
122 | cd test && $(MAKE) clean
123 |
--------------------------------------------------------------------------------
/README.txt:
--------------------------------------------------------------------------------
1 | --------------------------------------------
2 | -- STM32 Bootloader by CANBus
3 | --
4 | -- Johannes Hübner
5 | -- EV_BUILDER transformed to CAN BOOTLOADER;
6 | --------------------------------------------
7 |
8 |
9 | This boot loader does not interact with the built-in STM32 boot loader. It
10 | uses an interface of your choice, in this version its CANBUS CAN1 and
11 | USART3.
12 | The interface flexibility and the independence from the BOOT pins are the
13 | main reasons for implementing this boot loader.
14 |
15 | New update protocol
16 | - 500KBaud Canbus on CAN1
17 |
18 |
19 | 1 Send '2' indicating version 2 bootloader, wait about 500ms for magic byte 0xAA*
20 | 2 If no reply start firmware
21 | 3 Send an 'S' indicating that it is awaiting an update size in pages
22 | 4 If no reply within about 500ms go to step 7
23 | 4.1 otherwise send a 'P' indicating that it is awaiting the actual page
24 | first 8 bytes, this goes on (bit banging) until complete page is received.
25 | 4.2 When page not received within about 1s, print 'T' and keep waiting
26 | 5 When page received send a 'C' indicating that it is awaiting the pages
27 | checksum
28 | 6 When checksum is correct and more pages need to be received, go to
29 | step 4.1
30 | 6.1 if all pages have been received go to step 5
31 | 6.2 When checksum isn't correct print an 'E' then go to step 4.1
32 | 7 When done print a 'D' and start main firmware
33 |
34 | * When updating via CAN you may specify the 3rd word (DESIG_UNIQUE_ID2)
35 | in bytes 4-7 in order to only have the matching node enter update mode
36 |
37 | Notes:
38 | - By checksum I mean the one calculated by the STMs integrated CRC32 unit.
39 | - The actual firmware has a reset command the cycle through the bootloader
40 | - The main firmware must be linked to start at address 0x08001000
41 | - The bootloader starts at address 0x08000000 and can be 4k in size
42 | (right now its 3.9k)
43 |
44 | --------------------------------------------
45 | -- STM32 CAN Bootloader Updater
46 | --
47 | -- EV_BUILDER OPENINVERTER.ORG
48 | --------------------------------------------
49 |
50 | For both interfaces a python script is included. uart-update.py updates via
51 | serial port, can-update.py updates via CAN (SocketCAN in linux)
52 |
53 | python3 can-updater.py -d can2 -f stm32_sine.bin -i 87215032
54 | The -i argument is optional and specifies the processor id to be updated
55 | python3 uart-updater.py -d /dev/ttyUSB0 -f stm32_sine.bin
56 |
57 | updates via UART
58 |
59 | --------------------------------------------
60 | -- Compiling
61 | --------------------------------------------
62 | You will need the arm-none-eabi toolchain: https://developer.arm.com/open-source/gnu-toolchain/gnu-rm/downloads
63 | The only external depedency is libopencm3 which I forked. You can download and build this dependency by typing
64 |
65 | make get-deps
66 |
67 | Now you can compile stm32-canloader
68 |
69 | make
70 |
71 | And upload it to your board using a JTAG/SWD adapter.
72 |
73 |
--------------------------------------------------------------------------------
/can-updater.py:
--------------------------------------------------------------------------------
1 | import can
2 | from optparse import OptionParser
3 | from time import sleep
4 |
5 | def waitForChar(bus, c):
6 | recv_char = 0
7 | while recv_char not in c:
8 | message = bus.recv(0)
9 | if message and message.arbitration_id == 0x7de:
10 | recv_char = message.data[0]
11 | return chr(recv_char)
12 |
13 | def waitForId(bus, idBytes):
14 | while True:
15 | message = bus.recv()
16 | if message and message.dlc == 8 and message.arbitration_id == 0x7de and message.data[0] == 0x33:
17 | if not idBytes:
18 | return list(message.data[4:8])
19 | if list(message.data[4:8]) == idBytes:
20 | return list(message.data[4:8])
21 |
22 | def calcStmCrc(data, idx, len):
23 | cnt = 0
24 | crc = 0xffffffff
25 |
26 | while cnt < len:
27 | word = data[idx] | (data[idx+1] << 8) | (data[idx+2] << 16) | (data[idx+3] << 24)
28 | cnt = cnt + 4
29 | idx = idx + 4
30 |
31 | crc = crc ^ word
32 |
33 | for i in range(0, 32):
34 | if crc & 0x80000000:
35 | # Polynomial used in STM32
36 | crc = ((crc << 1) ^ 0x04C11DB7) & 0xffffffff
37 | else:
38 | crc = (crc << 1) & 0xffffffff
39 | return crc
40 |
41 | PAGE_SIZE_BYTES = 1024
42 |
43 |
44 | parser = OptionParser()
45 | parser.add_option("-f", "--file", dest="filename",
46 | help="update file")
47 | parser.add_option("-d", "--device", dest="device",
48 | help="serial interface")
49 | parser.add_option("-i", "--id", dest="id",
50 | help="flash only if id=x, x is the 3rd word of processor UID in hex")
51 | parser.add_option("-n", "--nodeid", dest="nodeid", default=1,
52 | help="CANopen node id to send reset command to")
53 |
54 | (options, args) = parser.parse_args()
55 |
56 | if not options.filename: # if filename is not given
57 | parser.error('Filename not given')
58 | exit()
59 | if not options.device: # if device is not given
60 | parser.error('Device not given')
61 | exit()
62 |
63 | bus=can.interface.Bus(bustype='socketcan', channel=options.device, bitrate=500000)
64 |
65 | updateFile = open(options.filename, "rb")
66 | data = bytearray(updateFile.read())
67 | updateFile.close()
68 |
69 | numBytes = len(data)
70 | numPages = (numBytes + PAGE_SIZE_BYTES - 1) // PAGE_SIZE_BYTES
71 |
72 | while (len(data) % PAGE_SIZE_BYTES) > 0:
73 | data.append(0)
74 |
75 | print("File length is %d bytes/%d pages" % (numBytes, numPages))
76 | print("Resetting device...")
77 |
78 | #This sends an SDO request to index 0x5002, subindex 2 which triggers a reset
79 | msg = can.Message(arbitration_id=0x600 + int(options.nodeid), is_extended_id=False, data = [ 0x23, 0x02, 0x50, 0x02, 0, 0, 0, 0 ])
80 | bus.send(msg)
81 |
82 | if options.id:
83 | id = int(options.id, 16)
84 | bytes = [id & 0xFF, (id >> 8) & 0xff, (id >> 16) & 0xff, (id >> 24) & 0xff]
85 | waitForId(bus, bytes)
86 | print("id specified, sending magic and id")
87 | msg = can.Message(arbitration_id=0x7DD, is_extended_id=False, data = bytes)
88 | else:
89 | id = waitForId(bus, False)
90 | print("No id specified, reflecting id", id)
91 | msg = can.Message(arbitration_id=0x7DD, is_extended_id=False, data=id)
92 | bus.send(msg)
93 |
94 | waitForChar(bus, b'S')
95 |
96 | print("Sending number of pages...")
97 |
98 | msg = can.Message(arbitration_id=0x7DD, is_extended_id=False, data=[numPages])
99 | bus.send(msg)
100 |
101 | waitForChar(bus, b'P')
102 |
103 | done = False
104 | page = 0
105 | idx = 0
106 | crc = calcStmCrc(data, idx, PAGE_SIZE_BYTES)
107 |
108 | print("Sending page 0...", end=' ')
109 |
110 | while not done:
111 | msg = can.Message(arbitration_id=0x7DD, is_extended_id=False, data=data[idx:idx+8])
112 | bus.send(msg)
113 | idx = idx + 8
114 |
115 | c = waitForChar(bus, b'CDEPT')
116 |
117 | if 'C' == c:
118 | msg = can.Message(arbitration_id=0x7DD, is_extended_id=False, data=[crc & 0xFF, (crc >> 8) & 0xFF, (crc >> 16) & 0xFF, (crc >> 24) & 0xFF])
119 | bus.send(msg)
120 | c = waitForChar(bus, b'PED')
121 | if 'D' == c:
122 | print("CRC correct!")
123 | print("Update done!")
124 | done = True
125 | elif 'E' == c:
126 | print("CRC error!")
127 | idx = page * PAGE_SIZE_BYTES
128 | print("Sending page %d..." % (page), end=' ')
129 | elif 'P' == c:
130 | print("CRC correct!")
131 | page = page + 1
132 | idx = page * PAGE_SIZE_BYTES
133 | crc = calcStmCrc(data, idx, PAGE_SIZE_BYTES)
134 | print("Sending page %d..." % (page), end=' ')
135 |
136 |
--------------------------------------------------------------------------------
/firmware_loader.cbp:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
--------------------------------------------------------------------------------
/include/hwinit.h:
--------------------------------------------------------------------------------
1 | /*
2 | * This file is part of the CANBootloader project.
3 | *
4 | * Copyright (C) 2022 WDR Automatisering https://wdrautomatisering.nl/
5 | * Copyright (C) 2023 Johannes Huebner https://openinverter.org
6 | *
7 | * This program is free software: you can redistribute it and/or modify
8 | * it under the terms of the GNU General Public License as published by
9 | * the Free Software Foundation, either version 3 of the License, or
10 | * (at your option) any later version.
11 | *
12 | * This program is distributed in the hope that it will be useful,
13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | * GNU General Public License for more details.
16 | *
17 | * You should have received a copy of the GNU General Public License
18 | * along with this program. If not, see .
19 | */
20 | #ifndef HWINIT_H_INCLUDED
21 | #define HWINIT_H_INCLUDED
22 |
23 |
24 | #ifdef __cplusplus
25 | extern "C"
26 | {
27 | #endif
28 |
29 | #define PINDEF_BLKNUM 3 //3rd to last flash page
30 | #define PINDEF_BLKSIZE 1024
31 | #define NUM_PIN_COMMANDS 10
32 | #define PIN_IN 0
33 | #define PIN_OUT 1
34 |
35 | struct pindef
36 | {
37 | uint32_t port;
38 | uint16_t pin;
39 | uint8_t inout;
40 | uint8_t level;
41 | };
42 |
43 | struct pincommands
44 | {
45 | struct pindef pindef[NUM_PIN_COMMANDS];
46 | uint32_t crc;
47 | };
48 |
49 | #define PINDEF_NUMWORDS (sizeof(struct pindef) * NUM_PIN_COMMANDS / 4)
50 |
51 | void clock_setup();
52 | void clock_teardown();
53 | void can_setup(int masterCANID);
54 | void can_teardown();
55 | void usart_setup();
56 | void usart_teardown();
57 | void initialize_pins();
58 |
59 | #ifdef __cplusplus
60 | }
61 | #endif
62 |
63 | #endif // HWINIT_H_INCLUDED
64 |
--------------------------------------------------------------------------------
/src/hwinit.cpp:
--------------------------------------------------------------------------------
1 | /*
2 | * This file is part of the CANBootloader project.
3 | *
4 | * Copyright (C) 2022 WDR Automatisering https://wdrautomatisering.nl/
5 | * Copyright (C) 2023 Johannes Huebner https://openinverter.org
6 | *
7 | * This program is free software: you can redistribute it and/or modify
8 | * it under the terms of the GNU General Public License as published by
9 | * the Free Software Foundation, either version 3 of the License, or
10 | * (at your option) any later version.
11 | *
12 | * This program is distributed in the hope that it will be useful,
13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | * GNU General Public License for more details.
16 | *
17 | * You should have received a copy of the GNU General Public License
18 | * along with this program. If not, see .
19 | */
20 |
21 | #include
22 | #include
23 | #include
24 | #include
25 | #include
26 | #include
27 | #include
28 | #include
29 | #include "hwinit.h"
30 |
31 | //#define CAN1_REMAP
32 |
33 | /**
34 | * Start clocks of all needed peripherals
35 | */
36 | void clock_setup()
37 | {
38 | rcc_set_pll_multiplication_factor(RCC_CFGR_PLLMUL_PLL_CLK_MUL6);
39 | rcc_set_pll_source(RCC_CFGR_PLLSRC_HSI_CLK_DIV2);
40 | rcc_osc_on(RCC_PLL);
41 | rcc_wait_for_osc_ready(RCC_PLL);
42 | rcc_set_sysclk_source(RCC_CFGR_SW_SYSCLKSEL_PLLCLK);
43 | rcc_osc_on(RCC_LSI);
44 |
45 | rcc_apb1_frequency = 24000000;
46 | rcc_apb2_frequency = 24000000;
47 |
48 | rcc_periph_clock_enable(RCC_GPIOA);
49 | rcc_periph_clock_enable(RCC_GPIOB);
50 | rcc_periph_clock_enable(RCC_GPIOC);
51 | rcc_periph_clock_enable(RCC_CRC);
52 | rcc_periph_clock_enable(RCC_CAN1);
53 | rcc_periph_clock_enable(RCC_USART3);
54 | rcc_periph_clock_enable(RCC_AFIO);
55 |
56 | rcc_wait_for_osc_ready(RCC_LSI);
57 | iwdg_set_period_ms(2000);
58 | iwdg_start();
59 | }
60 |
61 | void clock_teardown()
62 | {
63 | rcc_set_sysclk_source(RCC_CFGR_SW_SYSCLKSEL_HSICLK);
64 | rcc_osc_off(RCC_PLL);
65 | }
66 |
67 | void can_setup(int masterId)
68 | {
69 | #ifdef CAN1_REMAP
70 | gpio_primary_remap(AFIO_MAPR_SWJ_CFG_JTAG_OFF_SW_ON, AFIO_MAPR_CAN1_REMAP_PORTB);
71 | gpio_set_mode(GPIO_BANK_CAN1_PB_RX, GPIO_MODE_INPUT, GPIO_CNF_INPUT_PULL_UPDOWN, GPIO_CAN1_PB_RX);
72 | gpio_set(GPIO_BANK_CAN1_PB_RX, GPIO_CAN1_PB_RX);
73 | // Configure CAN pin: TX
74 | gpio_set_mode(GPIO_BANK_CAN1_PB_TX, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_ALTFN_PUSHPULL, GPIO_CAN1_PB_TX);
75 | #else
76 | gpio_set_mode(GPIO_BANK_CAN1_RX, GPIO_MODE_INPUT, GPIO_CNF_INPUT_PULL_UPDOWN, GPIO_CAN1_RX);
77 | gpio_set(GPIO_BANK_CAN1_RX, GPIO_CAN1_RX);
78 | // Configure CAN pin: TX
79 | gpio_set_mode(GPIO_BANK_CAN1_TX, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_ALTFN_PUSHPULL, GPIO_CAN1_TX);
80 | #endif // CAN1_REMAP
81 |
82 | // CAN cell init.
83 | // Setting the bitrate to 500KBit. APB1 = 24MHz,
84 | // prescaler = 6 -> 4MHz time quanta frequency.
85 | // 1tq sync + 6tq bit segment1 (TS1) + 1tq bit segment2 (TS2) =
86 | // 8time quanto per bit period, therefor 4MHz/16 = 500kHz
87 | //
88 | can_init(CAN1,
89 | false, // TTCM: Time triggered comm mode?
90 | true, // ABOM: Automatic bus-off management?
91 | false, // AWUM: Automatic wakeup mode?
92 | false, // NART: No automatic retransmission?
93 | false, // RFLM: Receive FIFO locked mode?
94 | false, // TXFP: Transmit FIFO priority?
95 | CAN_BTR_SJW_1TQ,
96 | CAN_BTR_TS1_6TQ,
97 | CAN_BTR_TS2_1TQ,
98 | 6, // BRP: Baud rate prescaler
99 | false,
100 | false);
101 |
102 | //register master ID
103 | can_filter_id_list_16bit_init(0, masterId << 5, 0, 0, 0, 0, true);
104 | nvic_enable_irq(NVIC_USB_LP_CAN_RX0_IRQ);
105 | can_enable_irq(CAN1, CAN_IER_FMPIE0);
106 | }
107 |
108 | void can_teardown()
109 | {
110 | can_reset(CAN1);
111 | nvic_disable_irq(NVIC_USB_LP_CAN_RX0_IRQ);
112 | }
113 |
114 | void usart_setup()
115 | {
116 | gpio_set_mode(GPIOB, GPIO_MODE_OUTPUT_50_MHZ,
117 | GPIO_CNF_OUTPUT_ALTFN_PUSHPULL, GPIO_USART3_TX);
118 |
119 | /* Setup UART parameters. */
120 | usart_set_baudrate(USART3, 115200);
121 | usart_set_databits(USART3, 8);
122 | usart_set_mode(USART3, USART_MODE_TX_RX);
123 | usart_enable_rx_interrupt(USART3);
124 |
125 | /* Finally enable the USART. */
126 | usart_enable(USART3);
127 | nvic_enable_irq(NVIC_USART3_IRQ);
128 | }
129 |
130 | void usart_teardown()
131 | {
132 | nvic_disable_irq(NVIC_USART3_IRQ);
133 | rcc_periph_reset_pulse(RST_USART3);
134 | }
135 |
136 | //Left over for future usage in an inverter style device..
137 | // Todo: read an application configuration based on fingerprint?
138 | //
139 | void initialize_pins()
140 | {
141 | uint32_t flashSize = desig_get_flash_size();
142 | uint32_t pindefAddr = FLASH_BASE + flashSize * 1024 - PINDEF_BLKNUM * PINDEF_BLKSIZE;
143 | const struct pincommands* pincommands = (struct pincommands*)pindefAddr;
144 |
145 | uint32_t crc = crc_calculate_block(((uint32_t*)pincommands), PINDEF_NUMWORDS);
146 |
147 | gpio_primary_remap(AFIO_MAPR_SWJ_CFG_JTAG_OFF_SW_ON, 0);
148 |
149 | if (crc == pincommands->crc)
150 | {
151 | for (int idx = 0; idx < NUM_PIN_COMMANDS && pincommands->pindef[idx].port > 0; idx++)
152 | {
153 | uint8_t cnf = pincommands->pindef[idx].inout ? GPIO_CNF_OUTPUT_PUSHPULL : GPIO_CNF_INPUT_PULL_UPDOWN;
154 | uint8_t mode = pincommands->pindef[idx].inout ? GPIO_MODE_OUTPUT_50_MHZ : GPIO_MODE_INPUT;
155 | gpio_set_mode(pincommands->pindef[idx].port, mode, cnf, pincommands->pindef[idx].pin);
156 |
157 | if (pincommands->pindef[idx].level)
158 | {
159 | gpio_set(pincommands->pindef[idx].port, pincommands->pindef[idx].pin);
160 | }
161 | else
162 | {
163 | gpio_clear(pincommands->pindef[idx].port, pincommands->pindef[idx].pin);
164 | }
165 | }
166 | }
167 | }
168 |
--------------------------------------------------------------------------------
/src/stm32_canloader.cpp:
--------------------------------------------------------------------------------
1 | /*
2 | * This file is part of the CANBootloader project.
3 | *
4 | * Copyright (C) 2022 WDR Automatisering https://wdrautomatisering.nl/
5 | * Copyright (C) 2023 Johannes Huebner https://openinverter.org
6 | *
7 | * This program is free software: you can redistribute it and/or modify
8 | * it under the terms of the GNU General Public License as published by
9 | * the Free Software Foundation, either version 3 of the License, or
10 | * (at your option) any later version.
11 | *
12 | * This program is distributed in the hope that it will be useful,
13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | * GNU General Public License for more details.
16 | *
17 | * You should have received a copy of the GNU General Public License
18 | * along with this program. If not, see .
19 | */
20 | #include
21 | #include
22 | #include
23 | #include
24 | #include
25 | #include
26 | #include
27 | #include
28 | #include
29 | #include
30 | #include
31 | #include
32 | #include
33 | #include "hwinit.h"
34 |
35 | #define FLASH_START 0x08000000
36 | #define SMALLEST_PAGE_WORDS 256
37 | #define PROGRAM_WORDS 256
38 | #define APP_FLASH_START 0x08001000
39 | #define BOOTLOADER_MAGIC 0xAA
40 | #define DELAY_100 (1 << 17)
41 | #define NODECANID 0x7DE
42 | #define MASTERCANID 0x7DD
43 |
44 | enum states
45 | {
46 | MAGIC, PAGECOUNT, PAGE, CRC, PROGRAM, DONE
47 | };
48 |
49 | static volatile states state = MAGIC;
50 | static uint32_t page_buffer[PROGRAM_WORDS];
51 | static bool usartUpdate = false;
52 |
53 | //Check 1k of flash whether it contains only 0xFF = erased
54 | static bool check_erased(uint32_t* baseAddress)
55 | {
56 | uint32_t check = 0xFFFFFFFF;
57 |
58 | for (int i = 0; i < SMALLEST_PAGE_WORDS; i++, baseAddress++)
59 | check &= *baseAddress;
60 |
61 | return check == 0xFFFFFFFF;
62 | }
63 |
64 | //If the device has 2k pages we must only call flash_erase_page()
65 | //on every other call of write_flash().
66 | //Therefor we check if the the flash region we attempt to write
67 | //is already erased (in case of 2k pages) or not (1k pages)
68 | static void write_flash(uint32_t addr, uint32_t *pageBuffer)
69 | {
70 | if (!check_erased((uint32_t*)addr))
71 | flash_erase_page(addr);
72 |
73 | for (uint32_t idx = 0; idx < PROGRAM_WORDS; idx++)
74 | {
75 | flash_program_word(addr + idx * 4, pageBuffer[idx]);
76 | }
77 | }
78 |
79 | static void send_byte(uint8_t b)
80 | {
81 | can_transmit(CAN1, NODECANID, false, false, 1, &b);
82 | if (usartUpdate) usart_send_blocking(USART3, b);
83 | }
84 |
85 | static void send_can_hello()
86 | {
87 | uint32_t data[] = { '3' | ('1' << 8), DESIG_UNIQUE_ID2 };
88 | can_transmit(CAN1, NODECANID, false, false, 8, (uint8_t*)data);
89 | }
90 |
91 | static bool can_recv(uint8_t* data, uint8_t& len)
92 | {
93 | uint32_t id;
94 | bool ext, rtr;
95 | uint8_t fmi;
96 |
97 | return can_receive(CAN1, 0, true, &id, &ext, &rtr, &fmi, &len, data, 0) > 0;
98 | }
99 |
100 | static void wait()
101 | {
102 | for (volatile uint32_t i = DELAY_100; i > 0; i--);
103 | }
104 |
105 |
106 | extern "C" int main(void)
107 | {
108 | uint32_t addr = APP_FLASH_START;
109 |
110 | clock_setup();
111 | initialize_pins();
112 | can_setup(MASTERCANID);
113 | usart_setup();
114 |
115 | send_can_hello();
116 | usart_send(USART3, '2'); //advertise version 2 as the protocol is unchanged
117 |
118 | wait();
119 |
120 | if (state == PAGECOUNT || state == PAGE || state == PROGRAM)
121 | {
122 | flash_unlock();
123 |
124 | while (state != DONE)
125 | {
126 | if (state == PROGRAM)
127 | {
128 | write_flash(addr, page_buffer);
129 | addr += sizeof(page_buffer);
130 | state = PAGE;
131 | send_byte('P');
132 | }
133 | iwdg_reset();
134 | }
135 |
136 | //Program the final page
137 | write_flash(addr, page_buffer);
138 | flash_lock();
139 | }
140 |
141 | //We are done lets tell the world this!!
142 | if (state == DONE)
143 | send_byte('D');
144 |
145 | wait();
146 |
147 | can_teardown();
148 | usart_teardown();
149 | clock_teardown();
150 |
151 | void (*app_main)(void) = (void (*)(void)) *(volatile uint32_t*)(APP_FLASH_START + 4);
152 | SCB_VTOR = APP_FLASH_START;
153 | app_main();
154 |
155 | return 0;
156 | }
157 |
158 | static void handle_data(uint8_t* data, uint8_t)
159 | {
160 | uint32_t* words = (uint32_t*)data;
161 | static uint8_t numPages = 0;
162 | static uint32_t currentWord = 0;
163 | static uint32_t crc;
164 |
165 | switch (state)
166 | {
167 | case MAGIC:
168 | if ((usartUpdate && data[0] == BOOTLOADER_MAGIC) || words[0] == DESIG_UNIQUE_ID2)
169 | {
170 | send_byte('S');
171 | state = PAGECOUNT;
172 | }
173 | break;
174 | case PAGECOUNT:
175 | numPages = data[0];
176 | state = PAGE;
177 | currentWord = 0;
178 | send_byte('P');
179 | crc_reset();
180 | break;
181 | case PAGE:
182 | page_buffer[currentWord++] = words[0];
183 | page_buffer[currentWord++] = words[1];
184 | crc_calculate(words[0]);
185 | crc = crc_calculate(words[1]);
186 |
187 | if (currentWord == PROGRAM_WORDS)
188 | {
189 | state = CRC;
190 | send_byte('C');
191 | }
192 | else if (!usartUpdate)
193 | {
194 | send_byte('P');
195 | }
196 | break;
197 | case CRC:
198 | currentWord = 0;
199 | crc_reset();
200 | if (words[0] == crc)
201 | {
202 | numPages--;
203 | if (numPages == 0)
204 | {
205 | state = DONE;
206 | }
207 | else
208 | {
209 | state = PROGRAM;
210 | }
211 | }
212 | else
213 | {
214 | send_byte('E');
215 | state = PAGE;
216 | }
217 | break;
218 | case PROGRAM:
219 | //Flash programming done in main()
220 | break;
221 | case DONE:
222 | //Nothing to do!
223 | break;
224 | }
225 |
226 | }
227 |
228 | /* Interrupt service routines */
229 | extern "C" void usb_lp_can_rx0_isr()
230 | {
231 | uint8_t canData[8], len;
232 |
233 | can_recv(canData, len);
234 | handle_data(canData, len);
235 | }
236 |
237 | extern "C" void usart3_isr()
238 | {
239 | static uint8_t buffer[8], currentByte = 0;
240 |
241 | uint8_t data = usart_recv(USART3);
242 |
243 | usartUpdate = true;
244 |
245 | switch (state)
246 | {
247 | case MAGIC:
248 | case PAGECOUNT:
249 | handle_data(&data, 1);
250 | break;
251 | case PAGE:
252 | buffer[currentByte++] = data;
253 | if (currentByte == 8)
254 | {
255 | currentByte = 0;
256 | handle_data(buffer, 8);
257 | }
258 | break;
259 | case CRC:
260 | buffer[currentByte++] = data;
261 | if (currentByte == 4)
262 | {
263 | currentByte = 0;
264 | handle_data(buffer, 4);
265 | }
266 | break;
267 | default:
268 | //Should never get here
269 | break;
270 | }
271 | }
272 |
--------------------------------------------------------------------------------
/stm32_canloader.ld:
--------------------------------------------------------------------------------
1 | /*
2 | * This file is part of the libopenstm32 project.
3 | *
4 | * Copyright (C) 2009 Uwe Hermann
5 | *
6 | * This program is free software: you can redistribute it and/or modify
7 | * it under the terms of the GNU General Public License as published by
8 | * the Free Software Foundation, either version 3 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * This program is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU General Public License
17 | * along with this program. If not, see .
18 | */
19 |
20 | /* Linker script for Olimex STM32-H103 (STM32F103RBT6, 128K flash, 20K RAM). */
21 |
22 | /* Define memory regions. */
23 | MEMORY
24 | {
25 | rom (rx) : ORIGIN = 0x08000000, LENGTH = 8K
26 | ram (rwx) : ORIGIN = 0x20000000, LENGTH = 20K
27 | }
28 |
29 |
30 | /* Include the common ld script from libopenstm32. */
31 | INCLUDE cortex-m-generic.ld
32 |
33 |
--------------------------------------------------------------------------------
/uart-updater.py:
--------------------------------------------------------------------------------
1 | import serial
2 | from optparse import OptionParser
3 | from time import sleep
4 |
5 |
6 | def waitForChar(ser, c):
7 | recv_char = ser.read()
8 | while recv_char not in c:
9 | recv_char = ser.read()
10 | return recv_char
11 |
12 |
13 | def calcStmCrc(data, idx, len):
14 | cnt = 0
15 | crc = 0xffffffff
16 |
17 | while cnt < len:
18 | word = data[idx] | (data[idx+1] << 8) | (data[idx+2]
19 | << 16) | (data[idx+3] << 24)
20 | cnt = cnt + 4
21 | idx = idx + 4
22 |
23 | crc = crc ^ word
24 |
25 | for i in range(0, 32):
26 | if crc & 0x80000000:
27 | # Polynomial used in STM32
28 | crc = ((crc << 1) ^ 0x04C11DB7) & 0xffffffff
29 | else:
30 | crc = (crc << 1) & 0xffffffff
31 | return crc
32 |
33 |
34 | PAGE_SIZE_BYTES = 1024
35 |
36 |
37 | parser = OptionParser()
38 | parser.add_option("-f", "--file", dest="filename",
39 | help="update file")
40 | parser.add_option("-d", "--device", dest="device",
41 | help="serial interface")
42 |
43 | (options, args) = parser.parse_args()
44 |
45 | if not options.filename: # if filename is not given
46 | parser.error('Filename not given')
47 | exit()
48 | if not options.device: # if device is not given
49 | parser.error('Device not given')
50 | exit()
51 | ser = serial.Serial(options.device, 115200, timeout=2, stopbits=2)
52 |
53 | updateFile = open(options.filename, "rb")
54 | data = bytearray(updateFile.read())
55 | updateFile.close()
56 |
57 | numBytes = len(data)
58 | numPages = (numBytes + PAGE_SIZE_BYTES - 1) // PAGE_SIZE_BYTES
59 |
60 | while (len(data) % PAGE_SIZE_BYTES) > 0:
61 | data.append(0)
62 |
63 | print("File length is %d bytes/%d pages" % (numBytes, numPages))
64 | print("Resetting device...")
65 |
66 | ser.write(b'reset\r')
67 | version = waitForChar(ser, b'S2')
68 |
69 | if version == b'2':
70 | print("Version 2 bootloader, sending magic")
71 | ser.write(b'\xAA')
72 | waitForChar(ser, b'S')
73 |
74 | print("Sending number of pages...")
75 |
76 | ser.write([numPages])
77 |
78 | waitForChar(ser, b'P')
79 |
80 | done = False
81 | page = 0
82 | idx = 0
83 |
84 | while not done:
85 | crc = calcStmCrc(data, idx, PAGE_SIZE_BYTES)
86 | c = 0
87 |
88 | while c != b'P' and not done:
89 | print("Sending page %d..." % (page), end=' ')
90 | idx = page * PAGE_SIZE_BYTES
91 | cnt = 0
92 |
93 | while cnt < PAGE_SIZE_BYTES:
94 | ser.write([data[idx]])
95 | idx = idx + 1
96 | cnt = cnt + 1
97 |
98 | c = ser.read()
99 |
100 | if b'C' == c:
101 | ser.write([crc & 0xFF])
102 | ser.write([(crc >> 8) & 0xFF])
103 | ser.write([(crc >> 16) & 0xFF])
104 | ser.write([(crc >> 24) & 0xFF])
105 |
106 | c = ser.read()
107 |
108 | if b'D' == c:
109 | print("CRC correct!")
110 | print("Update done!")
111 | done = True
112 | elif b'E' == c:
113 | print("CRC error!")
114 | waitForChar(ser, b'T')
115 | elif b'P' == c:
116 | print("CRC correct!")
117 | page = page + 1
118 | elif b'T' == c:
119 | print("Sync Error!")
120 | else:
121 | print(c)
122 |
--------------------------------------------------------------------------------