Compare commits

...

14 Commits
v0.8.0 ... main

Author SHA1 Message Date
Brian S. Stephan 98a13cca90
put ancillary docs under the main license
Signed-off-by: Brian S. Stephan <bss@incorporeal.org>
2024-04-21 18:55:39 -05:00
Brian S. Stephan 99504bfde6
support loading JSON files as configs to edit
Signed-off-by: Brian S. Stephan <bss@incorporeal.org>
2024-04-20 21:31:14 -05:00
Brian S. Stephan 56eb65dd55
tweak the version flag output to show more package/system info
Signed-off-by: Brian S. Stephan <bss@incorporeal.org>
2024-04-19 08:11:20 -05:00
Brian S. Stephan 2adb1540a1
include .json in the TUI Save As... prompt
Signed-off-by: Brian S. Stephan <bss@incorporeal.org>
2024-04-15 23:22:18 -05:00
Brian S. Stephan b4ba27dda0
add customary EOF \n to written JSON
Signed-off-by: Brian S. Stephan <bss@incorporeal.org>
2024-04-15 20:18:12 -05:00
Brian S. Stephan 58f2f38546
preliminary support for writing configs direct to JSON
I'm hoping this will allow for editing the JSON configs directly with
edit-config

Signed-off-by: Brian S. Stephan <bss@incorporeal.org>
2024-04-15 20:14:08 -05:00
Brian S. Stephan 8ad9b10018
CHANGELOG updates for v0.8.3
Signed-off-by: Brian S. Stephan <bss@incorporeal.org>
2024-04-15 10:18:51 -05:00
Brian S. Stephan 2648aebd4f
add --backup flag to concatenate
makes it so that we retain the old file, e.g. GP2040CE.uf2.old if we're
about to write GP2040CE.uf2

Signed-off-by: Brian S. Stephan <bss@incorporeal.org>
2024-04-15 10:13:28 -05:00
Brian S. Stephan 6a802bb232
support reading segmented UF2 files
now that we create segmented UF2 files properly in concatenate, we need
the ability to read them, which we'd previously saved for later; that
time is now. the reader now supports jumps forward (but not backwards,
and I don't know how likely it is we'll ever see this)

Signed-off-by: Brian S. Stephan <bss@incorporeal.org>
2024-04-15 09:25:26 -05:00
Brian S. Stephan 7d34a441f8
use the proper block count when publishing multipart UF2s
Signed-off-by: Brian S. Stephan <bss@incorporeal.org>
2024-04-15 00:05:54 -05:00
Brian S. Stephan 3524e5aa54
changelog for v0.8.1
Signed-off-by: Brian S. Stephan <bss@incorporeal.org>
2024-04-14 23:35:48 -05:00
Brian S. Stephan e133abc922
concatenate smaller UF2s by using indexed offsets
previous commit added the ability to pass a list of location+binary
combinations to create UF2s, meaning we no longer need to pad the
concatenated UF2 the same way we pad the raw binary output. this makes
for a more sanely-sized UF2 and faster write

Signed-off-by: Brian S. Stephan <bss@incorporeal.org>
2024-04-14 23:26:50 -05:00
Brian S. Stephan 2bb049c442
take multiple binary arguments to convert_binary_to_uf2
this is in preparation for making smaller .uf2 files buy not needing
padding, instead passing multiple location+binary combos to the
converter

Signed-off-by: Brian S. Stephan <bss@incorporeal.org>
2024-04-14 22:54:05 -05:00
Brian S. Stephan ea4d4be709
fix bad loading of .uf2 files in summarize-gp2040ce
the UF2 file wasn't converted to binary format before searching for the
board/user config sections, so it was reading the middle of the UF2 file
instead of the end of the binary file and returning that there were no
configs

Signed-off-by: Brian S. Stephan <bss@incorporeal.org>
2024-04-14 11:21:55 -05:00
10 changed files with 226 additions and 253 deletions

View File

@ -16,7 +16,7 @@ License: MIT
# High level repo docs
Files: *.md
Copyright: © 2023 Brian S. Stephan <bss@incorporeal.org>
License: CC-BY-SA-4.0
License: GPL-3.0-or-later
# Test data (GP2040-CE-derived)
Files: tests/test-files/pb2-files/* tests/test-files/proto-files/*

View File

@ -3,6 +3,31 @@
Included is a summary of changes to the project. For full details, especially on behind-the-scenes code changes and
development tools, see the commit history.
## v0.8.3
### Improvements
* `summarize-gp2040ce` can now understand the segmented UF2 files written in v0.8.1.
* `concatenate` has an added `--backup` flag, which will move an existing output file aside before writing the new
output.
## v0.8.2
### Bugfixes
* UF2 files made of parts now have the proper block counts.
## v0.8.1
### Improvements
* `concatenate` no longer writes a padded 2 MB binary (so 4 MB UF2), instead properly indexing the board/user configs
separately from the binary, leading to smaller UF2s.
### Bugfixes
* `summarize-gp2040ce` now properly reads UF2 files.
## v0.8.0
### Features

View File

@ -1,170 +0,0 @@
Creative Commons Attribution-ShareAlike 4.0 International
Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible.
Using Creative Commons Public Licenses
Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses.
Considerations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. More considerations for licensors.
Considerations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensors permission is not necessary for any reasonfor example, because of any applicable exception or limitation to copyrightthen that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described.
Although not required by our licenses, you are encouraged to respect those requests where reasonable. More considerations for the public.
Creative Commons Attribution-ShareAlike 4.0 International Public License
By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-ShareAlike 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions.
Section 1 Definitions.
a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.
b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License.
c. BY-SA Compatible License means a license listed at creativecommons.org/compatiblelicenses, approved by Creative Commons as essentially the equivalent of this Public License.
d. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.
e. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.
f. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.
g. License Elements means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution and ShareAlike.
h. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
i. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.
j. Licensor means the individual(s) or entity(ies) granting rights under this Public License.
k. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.
l. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.
m. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.
Section 2 Scope.
a. License grant.
1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:
A. reproduce and Share the Licensed Material, in whole or in part; and
B. produce, reproduce, and Share Adapted Material.
2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.
3. Term. The term of this Public License is specified in Section 6(a).
4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material.
5. Downstream recipients.
A. Offer from the Licensor Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.
B. Additional offer from the Licensor Adapted Material. Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapters License You apply.
C. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.
6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i).
b. Other rights.
1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise.
2. Patent and trademark rights are not licensed under this Public License.
3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties.
Section 3 License Conditions.
Your exercise of the Licensed Rights is expressly made subject to the following conditions.
a. Attribution.
1. If You Share the Licensed Material (including in modified form), You must:
A. retain the following if it is supplied by the Licensor with the Licensed Material:
i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of warranties;
v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and
C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.
2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information.
3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.
b. ShareAlike.In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply.
1. The Adapters License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-SA Compatible License.
2. You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material.
3. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply.
Section 4 Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database;
b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section 3(b); and
c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database.
For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights.
Section 5 Disclaimer of Warranties and Limitation of Liability.
a. Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.
b. To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.
c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.
Section 6 Term and Termination.
a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically.
b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:
1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or
2. upon express reinstatement by the Licensor.
c. For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License.
d. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License.
e. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.
Section 7 Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.
b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.
Section 8 Interpretation.
a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License.
b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions.
c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor.
d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority.
Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at creativecommons.org/policies, Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses.
Creative Commons may be contacted at creativecommons.org.

View File

@ -33,7 +33,8 @@ logger = logging.getLogger(__name__)
# parse flags that are common to many tools (e.g. adding paths for finding .proto files)
core_parser = argparse.ArgumentParser(add_help=False)
core_parser.add_argument('-v', '--version', action='version', version=f"%(prog)s {__version__}",
core_parser.add_argument('-v', '--version', action='version',
version=f"gp2040ce-binary-tools {__version__} (Python {sys.version})",
help="show version information and exit")
core_parser.add_argument('-d', '--debug', action='store_true', help="enable debug logging")
core_parser.add_argument('-P', '--proto-files-path', type=pathlib.Path, default=list(), action='append',

View File

@ -6,9 +6,11 @@ SPDX-License-Identifier: GPL-3.0-or-later
import argparse
import copy
import logging
import os
import re
from typing import Optional
from google.protobuf.json_format import MessageToJson
from google.protobuf.message import Message
import gp2040ce_bintools.storage as storage
@ -55,13 +57,14 @@ def combine_firmware_and_config(firmware_binary: bytearray, board_config_binary:
return combined
def concatenate_firmware_and_storage_files(firmware_filename: str,
def concatenate_firmware_and_storage_files(firmware_filename: str, # noqa: C901
binary_board_config_filename: Optional[str] = None,
json_board_config_filename: Optional[str] = None,
binary_user_config_filename: Optional[str] = None,
json_user_config_filename: Optional[str] = None,
combined_filename: str = '', usb: bool = False,
replace_extra: bool = False) -> None:
replace_extra: bool = False,
backup: bool = False) -> None:
"""Open the provided binary files and combine them into one combined GP2040-CE with config file.
Args:
@ -72,6 +75,7 @@ def concatenate_firmware_and_storage_files(firmware_filename: str,
json_user_config_filename: filename of the user config section to read, in JSON format
combined_filename: filename of where to write the combine binary
replace_extra: if larger than normal firmware files should have their overage replaced
backup: if the output filename exists, move it to foo.ext.old before writing foo.ext
"""
new_binary = bytearray([])
board_config_binary = bytearray([])
@ -101,27 +105,19 @@ def concatenate_firmware_and_storage_files(firmware_filename: str,
new_binary = combine_firmware_and_config(firmware_binary, board_config_binary, user_config_binary,
replace_extra=replace_extra)
else:
# this was kind of fine, but combining multiple calls of convert_binary_to_uf2 produced
# incorrect total block counts in the file, which picotool handled with some squirrely
# double-output behavior that has me worried it'd cause a real issue, so doing the
# crude padding + write of empty blocks, for now...
#
# new_binary = convert_binary_to_uf2(firmware_binary)
# if board_config_binary:
# new_binary += convert_binary_to_uf2(pad_config_to_storage_size(board_config_binary),
# start=BOARD_CONFIG_BINARY_LOCATION)
# if user_config_binary:
# new_binary += convert_binary_to_uf2(pad_config_to_storage_size(user_config_binary),
# start=USER_CONFIG_BINARY_LOCATION)
#
# the correct way to do the above would be to pass a list of {offset,binary_data} to convert...,
# and have it calculate the total block size before starting to write, and then iterating over
# the three lists. doable, just not on the top of my mind right now
new_binary = storage.convert_binary_to_uf2(combine_firmware_and_config(firmware_binary, board_config_binary,
user_config_binary,
replace_extra=replace_extra))
binary_list = [(0, firmware_binary)]
# we must pad to storage start in order for the UF2 write addresses to make sense
if board_config_binary:
binary_list.append((storage.BOARD_CONFIG_BINARY_LOCATION,
storage.pad_config_to_storage_size(board_config_binary)))
if user_config_binary:
binary_list.append((storage.USER_CONFIG_BINARY_LOCATION,
storage.pad_config_to_storage_size(user_config_binary)))
new_binary = storage.convert_binary_to_uf2(binary_list)
if combined_filename:
if backup and os.path.exists(combined_filename):
os.rename(combined_filename, f'{combined_filename}.old')
with open(combined_filename, 'wb') as combined:
combined.write(new_binary)
@ -253,13 +249,19 @@ def write_new_config_to_filename(config: Message, filename: str, inject: bool =
with open(filename, 'wb') as file:
file.write(binary)
else:
binary = storage.serialize_config_with_footer(config)
with open(filename, 'wb') as file:
if filename[-4:] == '.uf2':
file.write(storage.convert_binary_to_uf2(storage.pad_config_to_storage_size(binary),
start=storage.USER_CONFIG_BINARY_LOCATION))
else:
file.write(binary)
if filename[-5:] == '.json':
with open(filename, 'w') as file:
file.write(f'{MessageToJson(config)}\n')
else:
binary = storage.serialize_config_with_footer(config)
with open(filename, 'wb') as file:
if filename[-4:] == '.uf2':
# we must pad to storage start in order for the UF2 write addresses to make sense
file.write(storage.convert_binary_to_uf2([
(storage.USER_CONFIG_BINARY_LOCATION, storage.pad_config_to_storage_size(binary)),
]))
else:
file.write(binary)
def write_new_config_to_usb(config: Message, endpoint_out: object, endpoint_in: object):
@ -312,6 +314,8 @@ def concatenate():
output_group = parser.add_mutually_exclusive_group(required=True)
output_group.add_argument('--usb', action='store_true', help="write the resulting firmware + storage to USB")
output_group.add_argument('--new-filename', help="output .bin or .uf2 file of the resulting firmware + storage")
parser.add_argument('--backup', action='store_true', default=False,
help="if the output file exists, move it to .old before writing")
args, _ = parser.parse_known_args()
concatenate_firmware_and_storage_files(args.firmware_filename,
@ -320,7 +324,7 @@ def concatenate():
binary_user_config_filename=args.binary_user_config_filename,
json_user_config_filename=args.json_user_config_filename,
combined_filename=args.new_filename, usb=args.usb,
replace_extra=args.replace_extra)
replace_extra=args.replace_extra, backup=args.backup)
def dump_gp2040ce():
@ -352,8 +356,7 @@ def summarize_gp2040ce():
content, endpoint, _ = get_gp2040ce_from_usb()
print(f"USB device {hex(endpoint.device.idVendor)}:{hex(endpoint.device.idProduct)}:\n")
else:
with open(args.filename, 'rb') as file_:
content = file_.read()
content = storage.get_binary_from_file(args.filename)
print(f"File {args.filename}:\n")
gp2040ce_version = find_version_string_in_binary(content)

View File

@ -134,7 +134,8 @@ class SaveAsScreen(ModalScreen):
"""Build the pop-up window prompting for the new filename to save the configuration as."""
self.filename_field = Input(value=None, id='field-input', validators=[Length(minimum=1)])
yield Grid(
Container(Label("Filename (.uf2 or .bin) to write to:", id='field-name'), id='field-name-container'),
Container(Label("Filename (.uf2, .bin, or .json) to write to:", id='field-name'),
id='field-name-container'),
Container(self.filename_field, id='input-field-container'),
Container(Pretty('', id='input-errors', classes='hidden'), id='error-container'),
Horizontal(Container(Button("Cancel", id='cancel-button'), id='cancel-button-container'),

View File

@ -53,36 +53,39 @@ class ConfigMagicError(ConfigReadError):
"""Exception raised when the config section does not have the magic value in its footer."""
def convert_binary_to_uf2(binary: bytearray, start: int = 0) -> bytearray:
def convert_binary_to_uf2(binaries: list[tuple[int, bytearray]]) -> bytearray:
"""Convert a GP2040-CE binary payload to Microsoft's UF2 format.
https://github.com/microsoft/uf2/tree/master#overview
Args:
binary: bytearray content to convert to a UF2 payload
start: position offset to start at rather than flash start (for creating e.g. user config UF2s)
binaries: list of start,binary pairs of binary data to write at the specified memory offset in flash
Returns:
the content in UF2 format
"""
size = len(binary)
blocks = (len(binary) // 256) + 1 if len(binary) % 256 else len(binary) // 256
uf2 = bytearray()
total_blocks = sum([(len(binary) // 256) + 1 if len(binary) % 256 else len(binary) // 256
for offset, binary in binaries])
block_count = 0
index = 0
while index < size:
pad_count = 476 - len(binary[index:index+256])
uf2 += struct.pack('<LLLLLLLL',
UF2_MAGIC_FIRST, # first magic number
UF2_MAGIC_SECOND, # second magic number
0x00002000, # familyID present
0x10000000 + start + index, # address to write to
256, # bytes to write in this block
index // 256, # sequential block number
blocks, # total number of blocks
UF2_FAMILY_ID) # family ID
uf2 += binary[index:index+256] + bytearray(b'\x00' * pad_count) # content
uf2 += struct.pack('<L', UF2_MAGIC_FINAL) # final magic number
index += 256
uf2 = bytearray()
for start, binary in binaries:
size = len(binary)
index = 0
while index < size:
pad_count = 476 - len(binary[index:index+256])
uf2 += struct.pack('<LLLLLLLL',
UF2_MAGIC_FIRST, # first magic number
UF2_MAGIC_SECOND, # second magic number
0x00002000, # familyID present
0x10000000 + start + index, # address to write to
256, # bytes to write in this block
block_count, # sequential block number
total_blocks, # total number of blocks
UF2_FAMILY_ID) # family ID
uf2 += binary[index:index+256] + bytearray(b'\x00' * pad_count) # content
uf2 += struct.pack('<L', UF2_MAGIC_FINAL) # final magic number
index += 256
block_count += 1
return uf2
@ -111,9 +114,13 @@ def convert_uf2_to_binary(uf2: bytearray) -> bytearray:
if block_count != len(uf2) // 512:
raise ValueError(f"inconsistent block count in reading UF2, got {block_count}, expected {len(uf2) // 512}!")
# the UF2 is indexed, which we could convert to binary with padding 0s, but we don't yet
if old_uf2_addr and (uf2_addr != old_uf2_addr + 256):
raise ValueError("segmented UF2 files are not yet supported!")
if old_uf2_addr and (uf2_addr >= old_uf2_addr + bytes_):
# the new binary content is not immediately after what we wrote, it's further ahead, so pad
# the difference
binary += bytearray(b'\x00' * (uf2_addr - (old_uf2_addr + bytes_)))
elif old_uf2_addr and (uf2_addr < old_uf2_addr + bytes_):
# this is seeking backwards which we don't see yet
raise NotImplementedError("going backwards in binary files is not yet supported")
binary += content[0:bytes_]
old_uf2_addr = uf2_addr
@ -202,6 +209,25 @@ def get_config_footer(content: bytes) -> tuple[int, int, str]:
return config_size, config_crc, config_magic
def get_binary_from_file(filename: str) -> bytes:
"""Read the specified file (.bin or .uf2) and get back its raw binary contents.
Args:
filename: the filename of the file to open and read
Returns:
the file's content, in raw binary format
Raises:
FileNotFoundError: if the file was not found
"""
with open(filename, 'rb') as dump:
if filename[-4:] == '.uf2':
content = bytes(convert_uf2_to_binary(bytearray(dump.read())))
else:
content = dump.read()
return content
def get_config_from_file(filename: str, whole_board: bool = False, allow_no_file: bool = False,
board_config: bool = False) -> Message:
"""Read the specified file (memory dump or whole board dump) and get back its config section.
@ -215,25 +241,24 @@ def get_config_from_file(filename: str, whole_board: bool = False, allow_no_file
the parsed configuration
"""
try:
with open(filename, 'rb') as dump:
if filename[-4:] == '.uf2':
content = bytes(convert_uf2_to_binary(bytearray(dump.read())))
if filename[-5:] == '.json':
with open(filename) as file_:
return get_config_from_json(file_.read())
else:
content = get_binary_from_file(filename)
if whole_board:
if board_config:
return get_config(get_board_storage_section(content))
else:
return get_config(get_user_storage_section(content))
else:
content = dump.read()
return get_config(content)
except FileNotFoundError:
if not allow_no_file:
raise
config_pb2 = get_config_pb2()
return config_pb2.Config()
if whole_board:
if board_config:
return get_config(get_board_storage_section(content))
else:
return get_config(get_user_storage_section(content))
else:
return get_config(content)
def get_config_from_usb(address: int) -> tuple[Message, object, object]:
"""Read a config section from a USB device and provide the protobuf Message.
@ -378,8 +403,9 @@ def dump_config():
with open(args.filename, 'wb') as out_file:
if args.filename[-4:] == '.uf2':
# we must pad to storage start in order for the UF2 write addresses to make sense
out_file.write(convert_binary_to_uf2(pad_config_to_storage_size(binary_config),
start=USER_CONFIG_BINARY_LOCATION))
out_file.write(convert_binary_to_uf2([
(USER_CONFIG_BINARY_LOCATION, pad_config_to_storage_size(binary_config)),
]))
else:
out_file.write(binary_config)

View File

@ -3,6 +3,8 @@
SPDX-FileCopyrightText: © 2023 Brian S. Stephan <bss@incorporeal.org>
SPDX-License-Identifier: GPL-3.0-or-later
"""
import logging
import math
import os
import sys
import unittest.mock as mock
@ -13,10 +15,12 @@ from decorator import decorator
import gp2040ce_bintools.builder as builder
from gp2040ce_bintools import get_config_pb2
from gp2040ce_bintools.storage import (STORAGE_SIZE, get_board_storage_section, get_config, get_config_footer,
get_user_storage_section, serialize_config_with_footer)
get_config_from_json, get_user_storage_section, serialize_config_with_footer)
HERE = os.path.dirname(os.path.abspath(__file__))
logger = logging.getLogger(__name__)
@decorator
def with_pb2s(test, *args, **kwargs):
@ -117,8 +121,9 @@ def test_concatenate_to_uf2(tmp_path, firmware_binary, config_binary):
combined_filename=tmp_file)
with open(tmp_file, 'rb') as file:
content = file.read()
# size of the file should be 2x the binary version, and the binary is 2 MB
assert len(content) == 2 * 2 * 1024 * 1024
# size of the file should be 2x the padded firmware + 2x the board config space + 2x the user config space
assert len(content) == (math.ceil(len(firmware_binary)/256) * 512 +
math.ceil(STORAGE_SIZE/256) * 512 * 2)
def test_concatenate_to_uf2_board_only(tmp_path, firmware_binary, config_binary):
@ -130,8 +135,34 @@ def test_concatenate_to_uf2_board_only(tmp_path, firmware_binary, config_binary)
combined_filename=tmp_file)
with open(tmp_file, 'rb') as file:
content = file.read()
# size of the file should be 2x the binary version (minus user config space), and the binary is 2 MB - 16KB
assert len(content) == 2 * (2 * 1024 * 1024 - 16384)
# size of the file should be 2x the padded firmware + 2x the board config space
assert len(content) == (math.ceil(len(firmware_binary)/256) * 512 +
math.ceil(STORAGE_SIZE/256) * 512)
def test_concatenate_with_backup(tmp_path, firmware_binary, config_binary):
"""Test that we write a UF2 file as expected."""
tmp_file = os.path.join(tmp_path, 'concat.uf2')
firmware_file = os.path.join(HERE, 'test-files', 'test-firmware.bin')
config_file = os.path.join(HERE, 'test-files', 'test-config.bin')
# create the file we are going to try to overwrite and want backed up
builder.concatenate_firmware_and_storage_files(firmware_file, binary_board_config_filename=config_file,
combined_filename=tmp_file)
# second file, expecting an overwrite of the target with a backup made
builder.concatenate_firmware_and_storage_files(firmware_file, binary_board_config_filename=config_file,
binary_user_config_filename=config_file,
combined_filename=tmp_file,
backup=True)
# size of the file should be 2x the padded firmware + 2x the board config space + 2x the user config space
with open(tmp_file, 'rb') as file:
content = file.read()
assert len(content) == (math.ceil(len(firmware_binary)/256) * 512 +
math.ceil(STORAGE_SIZE/256) * 512 * 2)
# size of the backup file should be 2x the padded firmware + 2x the board config space
with open(f'{tmp_file}.old', 'rb') as file:
content = file.read()
assert len(content) == (math.ceil(len(firmware_binary)/256) * 512 +
math.ceil(STORAGE_SIZE/256) * 512)
def test_find_version_string(firmware_binary):
@ -323,6 +354,21 @@ def test_write_new_config_to_config_uf2(firmware_binary, tmp_path):
assert len(config_dump) == STORAGE_SIZE * 2
@with_pb2s
def test_write_new_config_to_config_json(config_binary, tmp_path):
"""Test that the config can be written to a file."""
tmp_file = os.path.join(tmp_path, 'config.json')
config = get_config(config_binary)
builder.write_new_config_to_filename(config, tmp_file)
# read new file
with open(tmp_file, 'r') as file:
config_dump = file.read()
logger.debug(config_dump)
config = get_config_from_json(config_dump)
assert config.boardVersion == 'v0.7.5'
@with_pb2s
def test_write_new_config_to_usb(config_binary):
"""Test that the config can be written to USB at the proper alignment."""

View File

@ -30,7 +30,8 @@ def with_pb2s(test, *args, **kwargs):
def test_version_flag():
"""Test that tools report the version."""
result = run(['visualize-config', '-v'], capture_output=True, encoding='utf8')
assert __version__ in result.stdout
assert f'gp2040ce-binary-tools {__version__}' in result.stdout
assert 'Python 3' in result.stdout
def test_help_flag():

View File

@ -12,6 +12,7 @@ import pytest
from decorator import decorator
import gp2040ce_bintools.storage as storage
from gp2040ce_bintools.builder import concatenate_firmware_and_storage_files
HERE = os.path.dirname(os.path.abspath(__file__))
@ -98,6 +99,15 @@ def test_get_board_config_from_file_whole_board_dump():
assert config.addonOptions.bootselButtonOptions.enabled is False
@with_pb2s
def test_get_board_config_from_json_file():
"""Test that we can open a JSON file and parse the config."""
filename = os.path.join(HERE, 'test-files', 'test-config.json')
config = storage.get_config_from_file(filename, whole_board=True, board_config=True)
assert config.boardVersion == 'v0.7.6-15-g71f4512'
assert config.addonOptions.bootselButtonOptions.enabled is False
@with_pb2s
def test_get_config_from_file_file_not_fonud_ok():
"""If we allow opening a file that doesn't exist (e.g. for the editor), check we get an empty config."""
@ -133,7 +143,7 @@ def test_config_from_whole_board_parses(whole_board_dump):
def test_convert_binary_to_uf2(whole_board_with_board_config_dump):
"""Do some sanity checks in the attempt to convert a binary to a UF2."""
uf2 = storage.convert_binary_to_uf2(whole_board_with_board_config_dump)
uf2 = storage.convert_binary_to_uf2([{0, whole_board_with_board_config_dump}])
assert len(uf2) == 4194304 # binary is 8192 256 byte chunks, UF2 is 512 b per chunk
assert uf2[0:4] == b'\x55\x46\x32\x0a' == b'UF2\n' # proper magic
assert uf2[8:12] == bytearray(b'\x00\x20\x00\x00') # family ID set
@ -142,7 +152,7 @@ def test_convert_binary_to_uf2(whole_board_with_board_config_dump):
def test_convert_unaligned_binary_to_uf2(firmware_binary):
"""Do some sanity checks in the attempt to convert a binary to a UF2."""
uf2 = storage.convert_binary_to_uf2(firmware_binary)
uf2 = storage.convert_binary_to_uf2([{0, firmware_binary}])
assert len(uf2) == math.ceil(len(firmware_binary)/256) * 512 # 256 byte complete/partial chunks -> 512 b chunks
assert uf2[0:4] == b'\x55\x46\x32\x0a' == b'UF2\n' # proper magic
assert uf2[8:12] == bytearray(b'\x00\x20\x00\x00') # family ID set
@ -151,7 +161,7 @@ def test_convert_unaligned_binary_to_uf2(firmware_binary):
def test_convert_binary_to_uf2_with_offsets(whole_board_with_board_config_dump):
"""Do some sanity checks in the attempt to convert a binary to a UF2."""
uf2 = storage.convert_binary_to_uf2(whole_board_with_board_config_dump, start=storage.USER_CONFIG_BINARY_LOCATION)
uf2 = storage.convert_binary_to_uf2([{storage.USER_CONFIG_BINARY_LOCATION, whole_board_with_board_config_dump}])
assert len(uf2) == 4194304 # binary is 8192 256 byte chunks, UF2 is 512 b per chunk
assert uf2[0:4] == b'\x55\x46\x32\x0a' == b'UF2\n' # proper magic
assert uf2[8:12] == bytearray(b'\x00\x20\x00\x00') # family ID set
@ -160,7 +170,7 @@ def test_convert_binary_to_uf2_with_offsets(whole_board_with_board_config_dump):
def test_convert_binary_to_uf2_to_binary(whole_board_with_board_config_dump):
"""Do some sanity checks in the attempt to convert a binary to a UF2."""
uf2 = storage.convert_binary_to_uf2(whole_board_with_board_config_dump)
uf2 = storage.convert_binary_to_uf2([{0, whole_board_with_board_config_dump}])
binary = storage.convert_uf2_to_binary(uf2)
assert len(binary) == 2097152
assert whole_board_with_board_config_dump == binary
@ -168,7 +178,7 @@ def test_convert_binary_to_uf2_to_binary(whole_board_with_board_config_dump):
def test_malformed_uf2(whole_board_with_board_config_dump):
"""Check that we expect a properly-formed UF2."""
uf2 = storage.convert_binary_to_uf2(whole_board_with_board_config_dump)
uf2 = storage.convert_binary_to_uf2([{0, whole_board_with_board_config_dump}])
# truncated UF2 --- byte mismatch
with pytest.raises(ValueError):
@ -187,6 +197,36 @@ def test_malformed_uf2(whole_board_with_board_config_dump):
storage.convert_uf2_to_binary(uf2 + uf2)
def test_read_created_uf2(tmp_path, firmware_binary, config_binary):
"""Test that we read a UF2 with disjoint segments."""
tmp_file = os.path.join(tmp_path, 'concat.uf2')
firmware_file = os.path.join(HERE, 'test-files', 'test-firmware.bin')
config_file = os.path.join(HERE, 'test-files', 'test-config.bin')
concatenate_firmware_and_storage_files(firmware_file, binary_board_config_filename=config_file,
binary_user_config_filename=config_file,
combined_filename=tmp_file)
with open(tmp_file, 'rb') as file:
content = file.read()
assert len(content) == (math.ceil(len(firmware_binary)/256) * 512 +
math.ceil(storage.STORAGE_SIZE/256) * 512 * 2)
binary = storage.convert_uf2_to_binary(content)
# the converted binary should be aligned properly and of the right size
assert len(binary) == 2 * 1024 * 1024
assert binary[-16384-4:-16384] == storage.FOOTER_MAGIC
assert binary[-4:] == storage.FOOTER_MAGIC
user_storage = storage.get_user_storage_section(binary)
footer_size, _, _ = storage.get_config_footer(user_storage)
assert footer_size == 3309
def test_cant_read_out_of_order_uf2():
"""Test that we currently raise an exception at out of order UF2s until we fix it."""
uf2 = storage.convert_binary_to_uf2([(0x1000, b'\x11'), (0, b'\x11')])
with pytest.raises(NotImplementedError):
storage.convert_uf2_to_binary(uf2)
@with_pb2s
def test_serialize_config_with_footer(storage_dump, config_binary):
"""Test that reserializing a read in config matches the original.