├── .gitignore
├── Cargo.toml
├── LICENSE
├── LICENSE-APACHE
├── LICENSE-MIT
├── README.md
├── docs
└── contributing.md
├── examples
└── read_chip_id.rs
└── src
└── lib.rs
/.gitignore:
--------------------------------------------------------------------------------
1 | target
2 | Cargo.lock
3 |
--------------------------------------------------------------------------------
/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "stm32-bootloader-client"
3 | description = "A library for communicating with the STM32 system bootloader"
4 | repository = "https://github.com/google/stm32-bootloader-client-rs"
5 | version = "0.1.0"
6 | edition = "2021"
7 | license = "BSD-3-Clause"
8 |
9 | [dependencies]
10 | embedded-hal = "0.2.6"
11 | defmt = { version = "0.2.1", optional = true }
12 | log = { version = "0.4.14", optional = true }
13 |
14 | [dev-dependencies]
15 | anyhow = "1.0.38"
16 | embedded-hal-mock = "0.8.0"
17 | mcp2221 = "0.1.0"
18 |
19 | [features]
20 | default = ["std"]
21 | std = []
22 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright [yyyy] [name of copyright owner]
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
203 |
204 | -----
205 |
206 | MIT License
207 |
208 | Copyright (c) 2022 The stm32-bootloader-client-rs authors.
209 |
210 | Permission is hereby granted, free of charge, to any
211 | person obtaining a copy of this software and associated
212 | documentation files (the "Software"), to deal in the
213 | Software without restriction, including without
214 | limitation the rights to use, copy, modify, merge,
215 | publish, distribute, sublicense, and/or sell copies of
216 | the Software, and to permit persons to whom the Software
217 | is furnished to do so, subject to the following
218 | conditions:
219 |
220 | The above copyright notice and this permission notice
221 | shall be included in all copies or substantial portions
222 | of the Software.
223 |
224 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
225 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
226 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
227 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
228 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
229 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
230 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
231 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
232 | DEALINGS IN THE SOFTWARE.
233 |
--------------------------------------------------------------------------------
/LICENSE-APACHE:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright [yyyy] [name of copyright owner]
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
203 |
--------------------------------------------------------------------------------
/LICENSE-MIT:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2022 The stm32-bootloader-client-rs authors.
4 |
5 | Permission is hereby granted, free of charge, to any
6 | person obtaining a copy of this software and associated
7 | documentation files (the "Software"), to deal in the
8 | Software without restriction, including without
9 | limitation the rights to use, copy, modify, merge,
10 | publish, distribute, sublicense, and/or sell copies of
11 | the Software, and to permit persons to whom the Software
12 | is furnished to do so, subject to the following
13 | conditions:
14 |
15 | The above copyright notice and this permission notice
16 | shall be included in all copies or substantial portions
17 | of the Software.
18 |
19 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
20 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
21 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
22 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
23 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
24 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
26 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
27 | DEALINGS IN THE SOFTWARE.
28 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # stm32-bootloader-client
2 |
3 | This is a Rust library for communicating with the STM32 system bootloader. This
4 | can be used, for example, to flash firmware onto an STM32 using an I2C
5 | connection. Support for flashing over UART and SPI is not implemented, but PRs
6 | are welcome.
7 |
8 | ### Example
9 |
10 | See [examples/read_chip_id.rs](examples/read_chip_id.rs).
11 |
12 | ### Contributing
13 |
14 | See [docs/contributing.md](docs/contributing.md).
15 |
16 | ### Disclaimer
17 |
18 | This is not an officially supported Google product.
19 |
20 | ### License
21 |
22 | This project is licensed under either of
23 |
24 | * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or
25 | https://www.apache.org/licenses/LICENSE-2.0)
26 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or
27 | https://opensource.org/licenses/MIT)
28 |
29 | at your option.
30 |
--------------------------------------------------------------------------------
/docs/contributing.md:
--------------------------------------------------------------------------------
1 | # How to Contribute
2 |
3 | We'd love to accept your patches and contributions to this project. There are
4 | just a few small guidelines you need to follow.
5 |
6 | ## Contributor License Agreement
7 |
8 | Contributions to this project must be accompanied by a Contributor License
9 | Agreement. You (or your employer) retain the copyright to your contribution;
10 | this simply gives us permission to use and redistribute your contributions as
11 | part of the project. Head over to to see
12 | your current agreements on file or to sign a new one.
13 |
14 | You generally only need to submit a CLA once, so if you've already submitted one
15 | (even if it was for a different project), you probably don't need to do it
16 | again.
17 |
18 | ## Code Reviews
19 |
20 | All submissions, including submissions by project members, require review. We
21 | use GitHub pull requests for this purpose. Consult
22 | [GitHub Help](https://help.github.com/articles/about-pull-requests/) for more
23 | information on using pull requests.
24 |
25 | ## Community Guidelines
26 |
27 | This project follows [Google's Open Source Community
28 | Guidelines](https://opensource.google/conduct/).
29 |
--------------------------------------------------------------------------------
/examples/read_chip_id.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2022 The stm32-bootloader-client-rs Authors.
2 | // This project is dual-licensed under Apache 2.0 and MIT terms.
3 | // See LICENSE-APACHE and LICENSE-MIT for details.
4 |
5 | use anyhow::Result;
6 | use stm32_bootloader_client::Stm32;
7 |
8 | fn main() {
9 | if let Err(error) = run() {
10 | println!("Error: {}", error);
11 | }
12 | }
13 |
14 | fn run() -> Result<()> {
15 | let mut config = mcp2221::Config::default();
16 | config.i2c_speed_hz = 400_000;
17 | let mut dev = mcp2221::Handle::open_first(&config)?;
18 |
19 | // Set GPIO pin 0 high. This is useful if your I2C bus goes through a level
20 | // shifter and you need to enable that level shifter in order to use the I2C
21 | // bus.
22 | let mut gpio_config = mcp2221::GpioConfig::default();
23 | gpio_config.set_direction(0, mcp2221::Direction::Output);
24 | gpio_config.set_value(0, true);
25 | dev.configure_gpio(&gpio_config)?;
26 |
27 | dev.check_bus()?;
28 |
29 | // This is the address for I2C1 on the STM32G0 series. See AN2606 for
30 | // the list of addresses for other parts.
31 | let config = stm32_bootloader_client::Config::i2c_address(0x51);
32 | let mut stm32 = Stm32::new(dev, config);
33 | let chip_id = stm32.get_chip_id()?;
34 | println!("Found chip ID: 0x{chip_id:x}");
35 |
36 | Ok(())
37 | }
38 |
--------------------------------------------------------------------------------
/src/lib.rs:
--------------------------------------------------------------------------------
1 | // Copyright 2022 The stm32-bootloader-client-rs Authors.
2 | // This project is dual-licensed under Apache 2.0 and MIT terms.
3 | // See LICENSE-APACHE and LICENSE-MIT for details.
4 |
5 | //! Communicates with the STM32 factory bootloader over i2c. See AN4221 for
6 | //! details of how the factory bootloader works.
7 |
8 | #![cfg_attr(not(any(test, feature = "std")), no_std)]
9 |
10 | use core::ops::Deref;
11 | use core::ops::DerefMut;
12 | use embedded_hal::blocking::i2c::Read;
13 | use embedded_hal::blocking::i2c::Write;
14 |
15 | const BOOTLOADER_ACK: u8 = 0x79;
16 | const BOOTLOADER_NACK: u8 = 0x1f;
17 | const BOOTLOADER_BUSY: u8 = 0x76;
18 |
19 | /// Configuration for communication with stm32 system bootloader.
20 | #[derive(Debug, Clone, Copy)]
21 | #[non_exhaustive]
22 | pub struct Config {
23 | /// See AN2606 for the i2c address for the specific chip you're talking to.
24 | /// The i2c address will also depend on which i2c bus on the chip you're
25 | /// connected to.
26 | i2c_address: u8,
27 |
28 | /// The maximum number of milliseconds that a full flash erase can take.
29 | /// Search the datasheet for your specific STM32 for "mass erase time". If
30 | /// in doubt, round up.
31 | pub mass_erase_max_ms: u32,
32 | }
33 |
34 | #[derive(Clone, Copy)]
35 | #[repr(u8)]
36 | enum Command {
37 | GetVersion = 0x01,
38 | GetId = 0x02,
39 | ReadMemory = 0x11,
40 | Go = 0x21,
41 | WriteMemory = 0x31,
42 | Erase = 0x44,
43 | }
44 |
45 | const SPECIAL_ERASE_ALL: [u8; 2] = [0xff, 0xff];
46 |
47 | pub const MAX_READ_WRITE_SIZE: usize = 128;
48 |
49 | type Result = core::result::Result;
50 |
51 | #[derive(Debug, Clone, Copy)]
52 | #[cfg_attr(feature = "defmt", derive(defmt::Format))]
53 | pub enum Error {
54 | TransportError,
55 | Nack,
56 | NackFromCommand(u8),
57 | Busy,
58 | UnexpectedResponse,
59 | InvalidArgument,
60 | VerifyFailedAtAddress(u32),
61 | EraseFailed,
62 | }
63 |
64 | pub struct Stm32<'a, I2c: Write + Read, DelayMs> {
65 | dev: MaybeOwned<'a, I2c>,
66 | delay: MaybeOwned<'a, DelayMs>,
67 | config: Config,
68 | }
69 |
70 | #[derive(Debug, Clone)]
71 | pub struct Progress {
72 | pub bytes_complete: usize,
73 | pub bytes_total: usize,
74 | }
75 |
76 | #[cfg(feature = "std")]
77 | impl Stm32<'static, I2c, StdDelay>
78 | where
79 | E: core::fmt::Debug,
80 | I2c: Write + Read,
81 | {
82 | pub fn new(dev: I2c, config: Config) -> Stm32<'static, I2c, StdDelay> {
83 | Self {
84 | dev: MaybeOwned::Owned(dev),
85 | delay: MaybeOwned::Owned(StdDelay),
86 | config,
87 | }
88 | }
89 | }
90 |
91 | #[cfg(feature = "std")]
92 | impl<'a, E, I2c> Stm32<'a, I2c, StdDelay>
93 | where
94 | E: core::fmt::Debug,
95 | I2c: Write + Read,
96 | {
97 | /// Construct a new instance where we only borrow the I2C implementation.
98 | /// This is useful if you have other things on the I2C bus that want to
99 | /// communicate with so don't want to give up ownership of the I2C bus.
100 | pub fn borrowed(dev: &'a mut I2c, config: Config) -> Stm32<'a, I2c, StdDelay> {
101 | Self {
102 | dev: MaybeOwned::Borrowed(dev),
103 | delay: MaybeOwned::Owned(StdDelay),
104 | config,
105 | }
106 | }
107 | }
108 |
109 | impl Stm32<'static, I2c, Delay>
110 | where
111 | E: core::fmt::Debug,
112 | I2c: Write + Read,
113 | Delay: embedded_hal::blocking::delay::DelayMs,
114 | {
115 | /// Constructs a new instance with a custom delay implementation.
116 | pub fn new_with_delay(dev: I2c, delay: Delay, config: Config) -> Stm32<'static, I2c, Delay> {
117 | Self {
118 | dev: MaybeOwned::Owned(dev),
119 | delay: MaybeOwned::Owned(delay),
120 | config,
121 | }
122 | }
123 | }
124 |
125 | impl<'a, E, I2c, Delay> Stm32<'a, I2c, Delay>
126 | where
127 | E: core::fmt::Debug,
128 | I2c: Write + Read,
129 | Delay: embedded_hal::blocking::delay::DelayMs,
130 | {
131 | /// Borrows both the I2C implementation and a custom delay.
132 | pub fn borrowed_with_delay(
133 | dev: &'a mut I2c,
134 | delay: &'a mut Delay,
135 | config: Config,
136 | ) -> Stm32<'a, I2c, Delay> {
137 | Self {
138 | dev: MaybeOwned::Borrowed(dev),
139 | delay: MaybeOwned::Borrowed(delay),
140 | config,
141 | }
142 | }
143 |
144 | pub fn get_chip_id(&mut self) -> Result {
145 | self.send_command(Command::GetId)?;
146 | // For STM32, the first byte will always be a 1 and the payload will
147 | // always be 3 bytes.
148 | let mut buffer = [0u8; 3];
149 | self.read(&mut buffer)?;
150 | self.get_ack_for_command(Command::GetId)?;
151 | Ok(u16::from_be_bytes([buffer[1], buffer[2]]))
152 | }
153 |
154 | /// Reads memory starting from `address`, putting the result into `out`.
155 | pub fn read_memory(&mut self, address: u32, out: &mut [u8]) -> Result<()> {
156 | if out.len() > MAX_READ_WRITE_SIZE {
157 | return Err(Error::InvalidArgument);
158 | }
159 | self.send_command(Command::ReadMemory)?;
160 | self.send_address(address)?;
161 | let mut buffer = [0u8; 2];
162 | buffer[0] = (out.len() - 1) as u8;
163 | buffer[1] = checksum(&buffer[0..1]);
164 | self.write(&buffer)?;
165 | self.get_ack_for_command(Command::ReadMemory)?;
166 | self.read(out)?;
167 |
168 | Ok(())
169 | }
170 |
171 | /// Writes `data` at `address`. Maximum write size is 256 bytes.
172 | pub fn write_memory(&mut self, address: u32, data: &[u8]) -> Result<()> {
173 | if data.len() > MAX_READ_WRITE_SIZE {
174 | return Err(Error::InvalidArgument);
175 | }
176 | self.send_command(Command::WriteMemory)?;
177 | self.send_address(address)?;
178 |
179 | let mut buffer = [0u8; MAX_READ_WRITE_SIZE + 2];
180 | buffer[0] = (data.len() - 1) as u8;
181 | buffer[1..1 + data.len()].copy_from_slice(data);
182 | buffer[1 + data.len()] = checksum(&buffer[0..1 + data.len()]);
183 | self.write(&buffer[..data.len() + 2])?;
184 |
185 | self.get_ack_for_command(Command::WriteMemory)
186 | }
187 |
188 | /// Writes `bytes` to `address`, calling `progress_cb` after each block.
189 | pub fn write_bulk(
190 | &mut self,
191 | mut address: u32,
192 | bytes: &[u8],
193 | mut progress_cb: impl FnMut(Progress),
194 | ) -> Result<()> {
195 | let mut complete = 0;
196 | for chunk in bytes.chunks(MAX_READ_WRITE_SIZE) {
197 | // Write-memory sometimes gets a NACK, so allow a single retry.
198 | if self.write_memory(address, chunk).is_err() {
199 | self.write_memory(address, chunk)?;
200 | }
201 | complete += chunk.len();
202 | address += chunk.len() as u32;
203 | progress_cb(Progress {
204 | bytes_complete: complete,
205 | bytes_total: bytes.len(),
206 | });
207 | }
208 | Ok(())
209 | }
210 |
211 | /// Verifies that memory at `address` is equal to `bytes`, calling
212 | /// `progress_cb` to report progress.
213 | pub fn verify(
214 | &mut self,
215 | mut address: u32,
216 | bytes: &[u8],
217 | mut progress_cb: impl FnMut(Progress),
218 | ) -> Result<()> {
219 | let mut read_back_buffer = [0; MAX_READ_WRITE_SIZE];
220 | let mut complete = 0;
221 | for chunk in bytes.chunks(MAX_READ_WRITE_SIZE) {
222 | let read_back = &mut read_back_buffer[..chunk.len()];
223 | self.read_memory(address, read_back)?;
224 | for (offset, (expected, actual)) in chunk.iter().zip(read_back.iter()).enumerate() {
225 | if expected != actual {
226 | return Err(Error::VerifyFailedAtAddress(address + offset as u32));
227 | }
228 | }
229 | complete += chunk.len();
230 | address += chunk.len() as u32;
231 | progress_cb(Progress {
232 | bytes_complete: complete,
233 | bytes_total: bytes.len(),
234 | });
235 | }
236 | Ok(())
237 | }
238 |
239 | /// Erase the flash of the STM32.
240 | pub fn erase_flash(&mut self) -> Result<()> {
241 | self.send_command(Command::Erase)?;
242 | let mut buffer = [0u8; 3];
243 | buffer[0..2].copy_from_slice(&SPECIAL_ERASE_ALL);
244 | buffer[2] = checksum(&buffer[..2]);
245 | self.write(&buffer)?;
246 | self.delay.delay_ms(self.config.mass_erase_max_ms);
247 | self.get_ack().map_err(|_| Error::EraseFailed)
248 | }
249 |
250 | /// Returns the version number of the bootloader.
251 | pub fn get_bootloader_version(&mut self) -> Result {
252 | self.send_command(Command::GetVersion)?;
253 | let mut buffer = [0];
254 | self.read(&mut buffer)?;
255 | self.get_ack_for_command(Command::GetVersion)?;
256 | Ok(buffer[0])
257 | }
258 |
259 | /// Exit system bootloader by jumping to the reset vector specified in the
260 | /// vector table at `address`.
261 | pub fn go(&mut self, address: u32) -> Result<()> {
262 | self.send_command(Command::Go)?;
263 | self.send_address(address)
264 | }
265 |
266 | fn write(&mut self, bytes: &[u8]) -> Result<()> {
267 | self.dev
268 | .write(self.config.i2c_address, bytes)
269 | .map_err(|error| {
270 | log_error(&error);
271 | Error::TransportError
272 | })
273 | }
274 |
275 | fn read(&mut self, out: &mut [u8]) -> Result<()> {
276 | self.dev
277 | .read(self.config.i2c_address, out)
278 | .map_err(|error| {
279 | log_error(&error);
280 | Error::TransportError
281 | })
282 | }
283 |
284 | fn read_with_timeout(&mut self, out: &mut [u8]) -> Result<()> {
285 | // TODO: Implement timeout mechanism
286 | const MAX_ATTEMPTS: u32 = 10000;
287 | let mut attempts = 0;
288 | loop {
289 | attempts += 1;
290 | let result = self.read(out);
291 | if result.is_ok() || attempts == MAX_ATTEMPTS {
292 | return result;
293 | }
294 | }
295 | }
296 |
297 | fn send_command(&mut self, command: Command) -> Result<()> {
298 | let command_u8 = command as u8;
299 | self.write(&[command_u8, !command_u8])?;
300 | self.get_ack_for_command(command)
301 | }
302 |
303 | fn get_ack(&mut self) -> Result<()> {
304 | let mut response = [0u8; 1];
305 | self.read_with_timeout(&mut response)?;
306 | match response[0] {
307 | BOOTLOADER_ACK => Ok(()),
308 | BOOTLOADER_NACK => Err(Error::Nack),
309 | BOOTLOADER_BUSY => Err(Error::Busy),
310 | _ => Err(Error::UnexpectedResponse),
311 | }
312 | }
313 |
314 | fn get_ack_for_command(&mut self, command: Command) -> Result<()> {
315 | self.get_ack().map_err(|error| match error {
316 | Error::Nack => Error::NackFromCommand(command as u8),
317 | x => x,
318 | })
319 | }
320 |
321 | fn send_address(&mut self, address: u32) -> Result<()> {
322 | let mut buffer = [0u8; 5];
323 | buffer[0..4].copy_from_slice(&address.to_be_bytes());
324 | buffer[4] = checksum(&buffer[0..4]);
325 | self.write(&buffer)?;
326 | self.get_ack()
327 | }
328 | }
329 |
330 | /// Wraps either an owned value, or a mutable reference. This sounds a little
331 | /// bit like std::borrow::Cow, but is actually quite different in that (a) it
332 | /// doesn't rely on std, (b) it mutates via either variant without having to
333 | /// switch to an owned variant and (c) it works with types that we can't, or
334 | /// don't want to clone.
335 | enum MaybeOwned<'a, T> {
336 | Borrowed(&'a mut T),
337 | Owned(T),
338 | }
339 |
340 | impl<'a, T> Deref for MaybeOwned<'a, T> {
341 | type Target = T;
342 |
343 | fn deref(&self) -> &Self::Target {
344 | match self {
345 | MaybeOwned::Borrowed(x) => *x,
346 | MaybeOwned::Owned(x) => x,
347 | }
348 | }
349 | }
350 |
351 | impl<'a, T> DerefMut for MaybeOwned<'a, T> {
352 | fn deref_mut(&mut self) -> &mut Self::Target {
353 | match self {
354 | MaybeOwned::Borrowed(x) => *x,
355 | MaybeOwned::Owned(x) => x,
356 | }
357 | }
358 | }
359 |
360 | /// An implementation of the embedded-hal DelayMs trait that works when std is
361 | /// available.
362 | #[cfg(feature = "std")]
363 | pub struct StdDelay;
364 |
365 | #[cfg(feature = "std")]
366 | impl embedded_hal::blocking::delay::DelayMs for StdDelay {
367 | fn delay_ms(&mut self, ms: u32) {
368 | std::thread::sleep(std::time::Duration::from_millis(ms.into()));
369 | }
370 | }
371 |
372 | fn checksum(bytes: &[u8]) -> u8 {
373 | let initial = if bytes.len() == 1 { 0xff } else { 0 };
374 | bytes
375 | .iter()
376 | .fold(initial, |checksum, value| checksum ^ value)
377 | }
378 |
379 | impl core::fmt::Display for Error {
380 | fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
381 | match self {
382 | Error::TransportError => write!(f, "Transport error"),
383 | Error::Nack => write!(f, "NACK"),
384 | Error::NackFromCommand(command) => write!(f, "Nack from command {}", command),
385 | Error::Busy => write!(f, "Busy"),
386 | Error::UnexpectedResponse => write!(f, "Unexpected response"),
387 | Error::InvalidArgument => write!(f, "Invalid argument"),
388 | Error::VerifyFailedAtAddress(address) => {
389 | write!(f, "Verify failed at address {:x}", address)
390 | }
391 | Error::EraseFailed => write!(f, "Erase failed"),
392 | }
393 | }
394 | }
395 |
396 | impl Config {
397 | pub const fn i2c_address(i2c_address: u8) -> Self {
398 | Self {
399 | i2c_address,
400 | // A moderately conservative default. stm32g071 has 40.1ms.
401 | // stm32l452 has 24.59ms
402 | mass_erase_max_ms: 200,
403 | }
404 | }
405 | }
406 |
407 | #[cfg(feature = "std")]
408 | impl std::error::Error for Error {}
409 |
410 | fn log_error(_error: &E) {
411 | #[cfg(feature = "defmt")]
412 | {
413 | defmt::error!("I2C error: {:?}", defmt::Debug2Format(_error));
414 | }
415 | #[cfg(feature = "log")]
416 | {
417 | log::error!("I2C error: {:?}", _error);
418 | }
419 | }
420 |
421 | #[cfg(test)]
422 | mod tests {
423 | use super::*;
424 | use embedded_hal_mock::i2c;
425 |
426 | const I2C_ADDRESS: u8 = 0x51;
427 | const CONFIG: Config = Config::i2c_address(I2C_ADDRESS);
428 |
429 | fn mock_write_with_checksum(bytes: &[u8]) -> i2c::Transaction {
430 | let mut with_checksum = Vec::with_capacity(bytes.len() + 1);
431 | with_checksum.extend_from_slice(bytes);
432 | with_checksum.push(checksum(bytes));
433 | i2c::Transaction::write(I2C_ADDRESS, with_checksum)
434 | }
435 |
436 | fn mock_read(bytes: &[u8]) -> i2c::Transaction {
437 | i2c::Transaction::read(I2C_ADDRESS, bytes.to_owned())
438 | }
439 |
440 | struct Delay;
441 |
442 | impl embedded_hal::blocking::delay::DelayMs for Delay {
443 | fn delay_ms(&mut self, _ms: u32) {}
444 | }
445 |
446 | #[test]
447 | fn test_get_chip_id() {
448 | let expectations = [
449 | mock_write_with_checksum(&[Command::GetId as u8]),
450 | mock_read(&[BOOTLOADER_ACK]),
451 | mock_read(&[0, 0xab, 0xcd]),
452 | mock_read(&[BOOTLOADER_ACK]),
453 | ];
454 | let mut i2c = i2c::Mock::new(&expectations);
455 | let mut delay = Delay;
456 | let mut stm32 = Stm32::borrowed_with_delay(&mut i2c, &mut delay, CONFIG);
457 | assert_eq!(stm32.get_chip_id().unwrap(), 0xabcd);
458 | i2c.done();
459 | }
460 |
461 | #[test]
462 | fn test_get_bootloader_version() {
463 | let expectations = [
464 | mock_write_with_checksum(&[Command::GetVersion as u8]),
465 | mock_read(&[BOOTLOADER_ACK]),
466 | mock_read(&[0xef]),
467 | mock_read(&[BOOTLOADER_ACK]),
468 | ];
469 | let mut i2c = i2c::Mock::new(&expectations);
470 | let mut delay = Delay;
471 | let mut stm32 = Stm32::borrowed_with_delay(&mut i2c, &mut delay, CONFIG);
472 | assert_eq!(stm32.get_bootloader_version().unwrap(), 0xef);
473 | i2c.done();
474 | }
475 |
476 | #[test]
477 | fn test_read_memory() {
478 | let expectations = [
479 | mock_write_with_checksum(&[Command::ReadMemory as u8]),
480 | mock_read(&[BOOTLOADER_ACK]),
481 | mock_write_with_checksum(&[0x12, 0x34, 0x56, 0x78]),
482 | mock_read(&[BOOTLOADER_ACK]),
483 | mock_write_with_checksum(&[0x02]),
484 | mock_read(&[BOOTLOADER_ACK]),
485 | mock_read(&[0xab, 0xcd, 0xef]),
486 | ];
487 | let mut i2c = i2c::Mock::new(&expectations);
488 | let mut delay = Delay;
489 | let mut stm32 = Stm32::borrowed_with_delay(&mut i2c, &mut delay, CONFIG);
490 | let mut out = [0u8; 3];
491 | stm32.read_memory(0x12345678, &mut out).unwrap();
492 | assert_eq!(&out, &[0xab, 0xcd, 0xef]);
493 | i2c.done();
494 | }
495 |
496 | #[test]
497 | fn test_write_memory() {
498 | let expectations = [
499 | mock_write_with_checksum(&[Command::WriteMemory as u8]),
500 | mock_read(&[BOOTLOADER_ACK]),
501 | mock_write_with_checksum(&[0x12, 0x34, 0x56, 0x78]),
502 | mock_read(&[BOOTLOADER_ACK]),
503 | mock_write_with_checksum(&[0x03, 0xab, 0xcd, 0xef, 0x12]),
504 | mock_read(&[BOOTLOADER_ACK]),
505 | ];
506 | let mut i2c = i2c::Mock::new(&expectations);
507 | let mut delay = Delay;
508 | let mut stm32 = Stm32::borrowed_with_delay(&mut i2c, &mut delay, CONFIG);
509 | stm32
510 | .write_memory(0x12345678, &[0xab, 0xcd, 0xef, 0x12])
511 | .unwrap();
512 | i2c.done();
513 | }
514 |
515 | #[test]
516 | fn test_go() {
517 | let expectations = [
518 | mock_write_with_checksum(&[Command::Go as u8]),
519 | mock_read(&[BOOTLOADER_ACK]),
520 | mock_write_with_checksum(&[0x12, 0x34, 0x56, 0x78]),
521 | mock_read(&[BOOTLOADER_ACK]),
522 | ];
523 | let mut i2c = i2c::Mock::new(&expectations);
524 | let mut delay = Delay;
525 | let mut stm32 = Stm32::borrowed_with_delay(&mut i2c, &mut delay, CONFIG);
526 | stm32.go(0x12345678).unwrap();
527 | i2c.done();
528 | }
529 |
530 | #[test]
531 | fn test_write_bulk() {
532 | let to_write: Vec = (0..200).collect();
533 | let mut write1 = vec![127u8];
534 | write1.extend_from_slice(&to_write[..128]);
535 | let mut write2 = vec![(to_write.len() - 128 - 1) as u8];
536 | write2.extend_from_slice(&to_write[128..]);
537 | let expectations = [
538 | mock_write_with_checksum(&[Command::WriteMemory as u8]),
539 | mock_read(&[BOOTLOADER_ACK]),
540 | mock_write_with_checksum(&[0x12, 0x34, 0x56, 0x78]),
541 | mock_read(&[BOOTLOADER_ACK]),
542 | mock_write_with_checksum(&write1),
543 | mock_read(&[BOOTLOADER_ACK]),
544 | mock_write_with_checksum(&[Command::WriteMemory as u8]),
545 | mock_read(&[BOOTLOADER_ACK]),
546 | mock_write_with_checksum(&[0x12, 0x34, 0x56, 0xf8]),
547 | mock_read(&[BOOTLOADER_ACK]),
548 | mock_write_with_checksum(&write2),
549 | mock_read(&[BOOTLOADER_ACK]),
550 | ];
551 | let mut i2c = i2c::Mock::new(&expectations);
552 | let mut delay = Delay;
553 | let mut stm32 = Stm32::borrowed_with_delay(&mut i2c, &mut delay, CONFIG);
554 | let mut callback_count = 0;
555 | stm32
556 | .write_bulk(0x12345678, &to_write, |_| {
557 | callback_count += 1;
558 | })
559 | .unwrap();
560 | assert_eq!(callback_count, 2);
561 | i2c.done();
562 | }
563 |
564 | #[test]
565 | fn test_verify() {
566 | let to_verify: Vec = (0..200).collect();
567 | let expectations = [
568 | mock_write_with_checksum(&[Command::ReadMemory as u8]),
569 | mock_read(&[BOOTLOADER_ACK]),
570 | mock_write_with_checksum(&[0x12, 0x34, 0x56, 0x78]),
571 | mock_read(&[BOOTLOADER_ACK]),
572 | mock_write_with_checksum(&[127]),
573 | mock_read(&[BOOTLOADER_ACK]),
574 | mock_read(&to_verify[..128]),
575 | mock_write_with_checksum(&[Command::ReadMemory as u8]),
576 | mock_read(&[BOOTLOADER_ACK]),
577 | mock_write_with_checksum(&[0x12, 0x34, 0x56, 0xf8]),
578 | mock_read(&[BOOTLOADER_ACK]),
579 | mock_write_with_checksum(&[(to_verify.len() - 128 - 1) as u8]),
580 | mock_read(&[BOOTLOADER_ACK]),
581 | mock_read(&to_verify[128..]),
582 | ];
583 | let mut i2c = i2c::Mock::new(&expectations);
584 | let mut delay = Delay;
585 | let mut stm32 = Stm32::borrowed_with_delay(&mut i2c, &mut delay, CONFIG);
586 | let mut callback_count = 0;
587 | stm32
588 | .verify(0x12345678, &to_verify, |_| {
589 | callback_count += 1;
590 | })
591 | .unwrap();
592 | assert_eq!(callback_count, 2);
593 | i2c.done();
594 | }
595 | }
596 |
--------------------------------------------------------------------------------