pyhubbledemo 0.0.1__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pyhubbledemo-0.0.1/.gitignore +83 -0
- pyhubbledemo-0.0.1/LICENSE +201 -0
- pyhubbledemo-0.0.1/PKG-INFO +20 -0
- pyhubbledemo-0.0.1/README.md +3 -0
- pyhubbledemo-0.0.1/pyproject.toml +41 -0
- pyhubbledemo-0.0.1/src/hubbledemo/__init__.py +9 -0
- pyhubbledemo-0.0.1/src/hubbledemo/cli.py +115 -0
- pyhubbledemo-0.0.1/src/hubbledemo/elfmgr.py +255 -0
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
# Virtual Environment
|
|
2
|
+
.venv/
|
|
3
|
+
venv/
|
|
4
|
+
env/
|
|
5
|
+
ENV/
|
|
6
|
+
|
|
7
|
+
# Temporary files and directories
|
|
8
|
+
.temp*
|
|
9
|
+
.tmp*
|
|
10
|
+
|
|
11
|
+
# Python
|
|
12
|
+
__pycache__/
|
|
13
|
+
*.py[cod]
|
|
14
|
+
*$py.class
|
|
15
|
+
*.so
|
|
16
|
+
.Python
|
|
17
|
+
build/
|
|
18
|
+
develop-eggs/
|
|
19
|
+
dist/
|
|
20
|
+
downloads/
|
|
21
|
+
eggs/
|
|
22
|
+
.eggs/
|
|
23
|
+
lib/
|
|
24
|
+
lib64/
|
|
25
|
+
parts/
|
|
26
|
+
sdist/
|
|
27
|
+
var/
|
|
28
|
+
wheels/
|
|
29
|
+
*.egg-info/
|
|
30
|
+
.installed.cfg
|
|
31
|
+
*.egg
|
|
32
|
+
MANIFEST
|
|
33
|
+
|
|
34
|
+
# PyInstaller
|
|
35
|
+
*.manifest
|
|
36
|
+
*.spec
|
|
37
|
+
|
|
38
|
+
# Installer logs
|
|
39
|
+
pip-log.txt
|
|
40
|
+
pip-delete-this-directory.txt
|
|
41
|
+
|
|
42
|
+
# Unit test / coverage reports
|
|
43
|
+
htmlcov/
|
|
44
|
+
.tox/
|
|
45
|
+
.coverage
|
|
46
|
+
.coverage.*
|
|
47
|
+
.cache
|
|
48
|
+
nosetests.xml
|
|
49
|
+
coverage.xml
|
|
50
|
+
*.cover
|
|
51
|
+
.hypothesis/
|
|
52
|
+
.pytest_cache/
|
|
53
|
+
|
|
54
|
+
# Jupyter Notebook
|
|
55
|
+
.ipynb_checkpoints
|
|
56
|
+
|
|
57
|
+
# pyenv
|
|
58
|
+
.python-version
|
|
59
|
+
|
|
60
|
+
# Environments
|
|
61
|
+
.env
|
|
62
|
+
.venv
|
|
63
|
+
env/
|
|
64
|
+
venv/
|
|
65
|
+
ENV/
|
|
66
|
+
env.bak/
|
|
67
|
+
venv.bak/
|
|
68
|
+
|
|
69
|
+
# IDE
|
|
70
|
+
.vscode/
|
|
71
|
+
.idea/
|
|
72
|
+
*.swp
|
|
73
|
+
*.swo
|
|
74
|
+
*~
|
|
75
|
+
|
|
76
|
+
# OS
|
|
77
|
+
.DS_Store
|
|
78
|
+
.DS_Store?
|
|
79
|
+
._*
|
|
80
|
+
.Spotlight-V100
|
|
81
|
+
.Trashes
|
|
82
|
+
ehthumbs.db
|
|
83
|
+
Thumbs.db
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pyhubbledemo
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: Hubble demo functionality for flashing and provisioning boards
|
|
5
|
+
Author-email: Paul Buckley <paul@hubble.com>
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Classifier: Operating System :: OS Independent
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Requires-Python: >=3.9
|
|
11
|
+
Requires-Dist: click
|
|
12
|
+
Requires-Dist: petname
|
|
13
|
+
Requires-Dist: pyelftools
|
|
14
|
+
Requires-Dist: pyhubblenetwork
|
|
15
|
+
Requires-Dist: pylink-square
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
|
|
18
|
+
# Hubble Demo Script
|
|
19
|
+
|
|
20
|
+
This will enable you to flash a pre-determined set of boards and provision them with your credentials.
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling >= 1.26"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "pyhubbledemo"
|
|
7
|
+
version = "0.0.1"
|
|
8
|
+
requires-python = ">=3.9"
|
|
9
|
+
authors = [
|
|
10
|
+
{ name="Paul Buckley", email="paul@hubble.com" },
|
|
11
|
+
]
|
|
12
|
+
readme = "README.md"
|
|
13
|
+
description = "Hubble demo functionality for flashing and provisioning boards"
|
|
14
|
+
license = "Apache-2.0"
|
|
15
|
+
license-files = ["LICENSE"]
|
|
16
|
+
classifiers = [
|
|
17
|
+
"Programming Language :: Python :: 3",
|
|
18
|
+
"Operating System :: OS Independent",
|
|
19
|
+
]
|
|
20
|
+
dependencies = [
|
|
21
|
+
"click",
|
|
22
|
+
"petname",
|
|
23
|
+
"pylink-square",
|
|
24
|
+
"pyelftools",
|
|
25
|
+
"pyhubblenetwork",
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
[project.scripts]
|
|
29
|
+
hubbledemo = "hubbledemo.cli:main" # installs a `hubbledemo` console script
|
|
30
|
+
|
|
31
|
+
# ---- Hatchling build config (src layout) ----
|
|
32
|
+
[tool.hatch.build.targets.wheel]
|
|
33
|
+
packages = ["src/hubbledemo"]
|
|
34
|
+
|
|
35
|
+
[tool.hatch.build.targets.sdist]
|
|
36
|
+
include = [
|
|
37
|
+
"src",
|
|
38
|
+
"README.md",
|
|
39
|
+
"LICENSE",
|
|
40
|
+
"pyproject.toml",
|
|
41
|
+
]
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import click
|
|
4
|
+
import os
|
|
5
|
+
import json
|
|
6
|
+
import time
|
|
7
|
+
import base64
|
|
8
|
+
import sys
|
|
9
|
+
import petname
|
|
10
|
+
from datetime import timezone, datetime
|
|
11
|
+
from typing import Optional
|
|
12
|
+
from hubblenetwork import Organization
|
|
13
|
+
from hubbledemo import flash_elf, fetch_elf, patch_elf
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _get_env_or_fail(name: str) -> str:
|
|
17
|
+
val = os.getenv(name)
|
|
18
|
+
if not val:
|
|
19
|
+
raise click.ClickException(f"[ERROR] {name} environment variable not set")
|
|
20
|
+
return val
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _get_org_and_token(org_id, token) -> tuple[str, str]:
|
|
24
|
+
"""
|
|
25
|
+
Helper function that checks if the given token and/or org
|
|
26
|
+
are None and gets the env var if not
|
|
27
|
+
"""
|
|
28
|
+
if not token:
|
|
29
|
+
token = _get_env_or_fail("HUBBLE_API_TOKEN")
|
|
30
|
+
if not org_id:
|
|
31
|
+
org_id = _get_env_or_fail("HUBBLE_ORG_ID")
|
|
32
|
+
return org_id, token
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@click.group(context_settings={"help_option_names": ["-h", "--help"]})
|
|
36
|
+
def cli() -> None:
|
|
37
|
+
"""Hubble SDK CLI."""
|
|
38
|
+
# top-level group; subcommands are added below
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@cli.command("flash")
|
|
42
|
+
@click.argument("board", type=str)
|
|
43
|
+
@click.option(
|
|
44
|
+
"--org-id",
|
|
45
|
+
"-o",
|
|
46
|
+
type=str,
|
|
47
|
+
default=None,
|
|
48
|
+
show_default=False,
|
|
49
|
+
help="Organization ID (if not using HUBBLE_ORG_ID env var)",
|
|
50
|
+
)
|
|
51
|
+
@click.option(
|
|
52
|
+
"--token",
|
|
53
|
+
"-t",
|
|
54
|
+
type=str,
|
|
55
|
+
default=None,
|
|
56
|
+
show_default=False, # show default in --help
|
|
57
|
+
help="Token (if not using HUBBLE_API_TOKEN env var)",
|
|
58
|
+
)
|
|
59
|
+
def flash(board: str, name: str = None, org_id: str = None, token: str = None) -> None:
|
|
60
|
+
org_id, token = _get_org_and_token(org_id, token)
|
|
61
|
+
org = Organization(org_id=org_id, api_token=token)
|
|
62
|
+
|
|
63
|
+
click.secho(f"[INFO] Organization info acquired:")
|
|
64
|
+
click.secho(f"\tID: {org.org_id}")
|
|
65
|
+
click.secho(f"\tName: {org.name}")
|
|
66
|
+
click.secho(f"\tEnvironment: {org.env}")
|
|
67
|
+
|
|
68
|
+
click.secho(f'[INFO] Registering new device"... ', nl=False)
|
|
69
|
+
device = org.register_device()
|
|
70
|
+
click.secho("[SUCCESS]")
|
|
71
|
+
click.secho(f"\tDevice ID: {device.id}")
|
|
72
|
+
click.secho(f"\tDevice Key: {device.key}")
|
|
73
|
+
|
|
74
|
+
if not name:
|
|
75
|
+
name = petname.generate(words=3)
|
|
76
|
+
click.secho(f'[INFO] No name supplied. Naming device "{name}"')
|
|
77
|
+
click.secho(f"[INFO] Setting device name... ", nl=False)
|
|
78
|
+
org.set_device_name(device_id=device.id, name=name)
|
|
79
|
+
click.secho("[SUCCESS]")
|
|
80
|
+
|
|
81
|
+
click.secho(f"[INFO] Retrieving binary for {board}... ", nl=False)
|
|
82
|
+
buf = fetch_elf(board=board)
|
|
83
|
+
click.secho("[SUCCESS]")
|
|
84
|
+
|
|
85
|
+
click.secho("[INFO] Patching key + UTC into binary... ", nl=False)
|
|
86
|
+
patch_elf(buf, device)
|
|
87
|
+
click.secho("[SUCCESS]")
|
|
88
|
+
|
|
89
|
+
click.secho("[INFO] Flashing binary onto device... ", nl=False)
|
|
90
|
+
flash_elf(board=board, buf=buf)
|
|
91
|
+
click.secho("[SUCCESS]")
|
|
92
|
+
|
|
93
|
+
click.secho(f"\n{board} successfully flashed and provisioned!")
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def main(argv: Optional[list[str]] = None) -> int:
|
|
97
|
+
"""
|
|
98
|
+
Entry point used by console_scripts.
|
|
99
|
+
|
|
100
|
+
Returns a process exit code instead of letting Click call sys.exit for easier testing.
|
|
101
|
+
"""
|
|
102
|
+
try:
|
|
103
|
+
# standalone_mode=False prevents Click from calling sys.exit itself.
|
|
104
|
+
cli.main(args=argv, prog_name="hubbledemo", standalone_mode=False)
|
|
105
|
+
except SystemExit as e:
|
|
106
|
+
return int(e.code)
|
|
107
|
+
except Exception as e: # safety net to avoid tracebacks in user CLI
|
|
108
|
+
click.secho(f"Unexpected error: {e}", fg="red", err=True)
|
|
109
|
+
return 2
|
|
110
|
+
return 0
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
if __name__ == "__main__":
|
|
114
|
+
# Forward command-line args (excluding the program name) to main()
|
|
115
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from hubblenetwork import Device
|
|
4
|
+
|
|
5
|
+
import io
|
|
6
|
+
import os
|
|
7
|
+
import base64
|
|
8
|
+
import requests
|
|
9
|
+
import time
|
|
10
|
+
import tempfile
|
|
11
|
+
import pylink
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Dict
|
|
14
|
+
from elftools.elf.elffile import ELFFile
|
|
15
|
+
from elftools.elf.sections import SymbolTableSection
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
_ELF_BASE_URL = (
|
|
19
|
+
"https://raw.githubusercontent.com/HubbleNetwork/hubble-tldm/master/merge"
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
# Map boards to J-Link "device" strings (extend as needed)
|
|
23
|
+
_BOARD_TO_JLINK_DEVICE: Dict[str, str] = {
|
|
24
|
+
"nrf52dk": "nRF52832_xxAA",
|
|
25
|
+
"nrf52840dk": "nRF52840_xxAA",
|
|
26
|
+
"nrf21540dk": "nRF52840_xxAA",
|
|
27
|
+
"xg24_ek2703a": "EFR32MG24BxxxF1536",
|
|
28
|
+
"xg22_ek4108a": "EFR32MG22CxxxF512",
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _compute_file_offset(sym, sec) -> int:
|
|
33
|
+
return sec["sh_offset"] + (sym["st_value"] - sec["sh_addr"])
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _get_endianness_from_elf(buf: io.BytesIO) -> str:
|
|
37
|
+
buf.seek(0)
|
|
38
|
+
elf = ELFFile(buf)
|
|
39
|
+
"""Return 'little' or 'big' by inspecting the ELF header."""
|
|
40
|
+
return "little" if elf.little_endian else "big"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _find_symbol(elf: ELFFile, name: str):
|
|
44
|
+
"""Return (symbol, section) for a named symbol from .symtab or .dynsym."""
|
|
45
|
+
for sec in elf.iter_sections():
|
|
46
|
+
if not isinstance(sec, SymbolTableSection):
|
|
47
|
+
continue
|
|
48
|
+
for sym in sec.iter_symbols():
|
|
49
|
+
if sym.name == name:
|
|
50
|
+
shndx = sym["st_shndx"]
|
|
51
|
+
if shndx == "SHN_UNDEF":
|
|
52
|
+
raise ValueError(f"Symbol '{name}' is undefined (imported).")
|
|
53
|
+
if isinstance(shndx, str):
|
|
54
|
+
raise ValueError(
|
|
55
|
+
f"Symbol '{name}' has special section index {shndx}, cannot patch."
|
|
56
|
+
)
|
|
57
|
+
target_sec = elf.get_section(shndx)
|
|
58
|
+
if target_sec is None:
|
|
59
|
+
raise ValueError(f"Could not find section for symbol '{name}'.")
|
|
60
|
+
if target_sec.name == "bss":
|
|
61
|
+
continue
|
|
62
|
+
return sym, target_sec
|
|
63
|
+
return None, None
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _patch_symbol(buf: io.BytesIO, data: bytes, symbol_name: str):
|
|
67
|
+
buf.seek(0)
|
|
68
|
+
elf = ELFFile(buf)
|
|
69
|
+
|
|
70
|
+
# Resolve symbol
|
|
71
|
+
sym, sec = _find_symbol(elf, symbol_name)
|
|
72
|
+
if sym is None:
|
|
73
|
+
raise ValueError(f"{symbol_name} not found in elf file")
|
|
74
|
+
|
|
75
|
+
file_off = _compute_file_offset(sym, sec)
|
|
76
|
+
sym_size = int(sym["st_size"]) or 0
|
|
77
|
+
|
|
78
|
+
if sym_size not in (0, len(data)):
|
|
79
|
+
raise ValueError(
|
|
80
|
+
f"Symbol size is {sym_size} bytes, but {symbol_name} length is {len(data)}"
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
buf.seek(file_off)
|
|
84
|
+
buf.write(data)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def patch_elf(buf: io.BytesIO, device: Device):
|
|
88
|
+
_patch_symbol(buf, base64.b64decode(device.key), "master_key")
|
|
89
|
+
|
|
90
|
+
endian = _get_endianness_from_elf(buf)
|
|
91
|
+
utc_ms = int(time.time() * 1000)
|
|
92
|
+
_patch_symbol(buf, utc_ms.to_bytes(8, endian, signed=False), "utc_time")
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _addr_for_segment(seg) -> int:
|
|
96
|
+
"""
|
|
97
|
+
Choose a programming address for a PT_LOAD segment.
|
|
98
|
+
Prefer physical address (p_paddr) if present, else virtual (p_vaddr).
|
|
99
|
+
"""
|
|
100
|
+
try:
|
|
101
|
+
paddr = int(seg["p_paddr"])
|
|
102
|
+
except Exception:
|
|
103
|
+
paddr = 0
|
|
104
|
+
vaddr = int(seg["p_vaddr"])
|
|
105
|
+
return paddr if paddr else vaddr
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _always_unsecure(title, msg, flags):
|
|
109
|
+
# proceed with mass erase + unlock
|
|
110
|
+
return pylink.enums.JLinkFlags.DLG_BUTTON_YES
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def flash_elf(buf: io.BytesIO, board: str) -> None:
|
|
114
|
+
"""
|
|
115
|
+
Flash an ELF image (held in a BytesIO) to an nRF52832_xxAA using pylink.
|
|
116
|
+
Creates a temporary .elf on disk (needed by jlink.flash_file) and deletes it afterwards.
|
|
117
|
+
|
|
118
|
+
Args:
|
|
119
|
+
buf: io.BytesIO positioned anywhere (we'll rewind it).
|
|
120
|
+
board: board name
|
|
121
|
+
|
|
122
|
+
Raises:
|
|
123
|
+
ImportError: pylink not installed.
|
|
124
|
+
RuntimeError: on J-Link connection or flashing failure.
|
|
125
|
+
"""
|
|
126
|
+
speed_khz = 4000
|
|
127
|
+
device = _BOARD_TO_JLINK_DEVICE.get(board.strip().lower())
|
|
128
|
+
|
|
129
|
+
# Write the buffer to a real temp file so flash_file can read it (works on all OSes)
|
|
130
|
+
tmp_path = None
|
|
131
|
+
try:
|
|
132
|
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".elf") as tmp:
|
|
133
|
+
tmp_path = tmp.name
|
|
134
|
+
buf.seek(0)
|
|
135
|
+
# Stream copy to avoid duplicating memory with getvalue()
|
|
136
|
+
while True:
|
|
137
|
+
chunk = buf.read(1024 * 1024)
|
|
138
|
+
if not chunk:
|
|
139
|
+
break
|
|
140
|
+
tmp.write(chunk)
|
|
141
|
+
tmp.flush()
|
|
142
|
+
|
|
143
|
+
# jlink will silently fail post-mandated FW update of the jlink
|
|
144
|
+
# for some devices due to a security dialog which pylink ignores.
|
|
145
|
+
# This unsecure_hook just makes it accept the insecurity.
|
|
146
|
+
jlink = pylink.JLink(unsecure_hook=_always_unsecure)
|
|
147
|
+
|
|
148
|
+
try:
|
|
149
|
+
jlink.open()
|
|
150
|
+
jlink.set_tif(pylink.enums.JLinkInterfaces.SWD)
|
|
151
|
+
jlink.connect(device, speed=speed_khz)
|
|
152
|
+
|
|
153
|
+
jlink.halt()
|
|
154
|
+
jlink.flash_file(tmp_path, addr=None) # ELF contains its own load addresses
|
|
155
|
+
jlink.reset()
|
|
156
|
+
except Exception as e:
|
|
157
|
+
raise RuntimeError(f"Flashing failed: {e}") from e
|
|
158
|
+
finally:
|
|
159
|
+
try:
|
|
160
|
+
if jlink.opened():
|
|
161
|
+
jlink.close()
|
|
162
|
+
except Exception:
|
|
163
|
+
pass
|
|
164
|
+
finally:
|
|
165
|
+
if tmp_path:
|
|
166
|
+
try:
|
|
167
|
+
os.unlink(tmp_path)
|
|
168
|
+
except OSError:
|
|
169
|
+
pass
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def fetch_elf(board: str, timeout: float = 20.0) -> io.BytesIO:
|
|
173
|
+
"""
|
|
174
|
+
Download the board-specific ELF from HubbleNetwork/hubble-tldm/merge and
|
|
175
|
+
return it as an io.BytesIO.
|
|
176
|
+
|
|
177
|
+
Parameters
|
|
178
|
+
----------
|
|
179
|
+
board_name : str
|
|
180
|
+
Board identifier (e.g. 'nrf21540dk', 'xg24_ek2703a', 'xg22_ek4108a').
|
|
181
|
+
timeout : float
|
|
182
|
+
Requests timeout in seconds (connect + read).
|
|
183
|
+
|
|
184
|
+
Returns
|
|
185
|
+
-------
|
|
186
|
+
io.BytesIO
|
|
187
|
+
Raw bytes of the .elf file
|
|
188
|
+
|
|
189
|
+
Raises
|
|
190
|
+
------
|
|
191
|
+
ValueError
|
|
192
|
+
If the board is not supported or name is malformed.
|
|
193
|
+
FileNotFoundError
|
|
194
|
+
If the expected ELF file does not exist in the merge directory.
|
|
195
|
+
ConnectionError
|
|
196
|
+
On network, HTTP, or parsing failures.
|
|
197
|
+
"""
|
|
198
|
+
if not isinstance(board, str) or not board.strip():
|
|
199
|
+
raise ValueError("board must be a non-empty string")
|
|
200
|
+
|
|
201
|
+
# If we have a local override, just use that
|
|
202
|
+
local_file = os.getenv("HUBBLE_DEMO_ELF_FILE")
|
|
203
|
+
if local_file:
|
|
204
|
+
return io.BytesIO(Path(local_file).read_bytes())
|
|
205
|
+
|
|
206
|
+
# Give option (for development) to pull binary from elsewhere
|
|
207
|
+
val = os.getenv("HUBBLE_DEMO_ELF_URL_OVERRIDE")
|
|
208
|
+
if val:
|
|
209
|
+
base_url = val
|
|
210
|
+
else:
|
|
211
|
+
base_url = _ELF_BASE_URL
|
|
212
|
+
|
|
213
|
+
url = f"{base_url}/{board}.elf"
|
|
214
|
+
|
|
215
|
+
_RETRY_STATUS = {429, 500, 502, 503, 504}
|
|
216
|
+
retries = 5
|
|
217
|
+
|
|
218
|
+
last_err: Optional[Exception] = None
|
|
219
|
+
for attempt in range(1, max(1, retries) + 1):
|
|
220
|
+
try:
|
|
221
|
+
resp = requests.get(url, timeout=timeout)
|
|
222
|
+
|
|
223
|
+
if resp.status_code == 404:
|
|
224
|
+
# Not found is definitive; don't bother retrying
|
|
225
|
+
raise FileNotFoundError(f"No ELF for board '{board}' at {url}")
|
|
226
|
+
|
|
227
|
+
# Retry transient status codes (unless it's the final attempt)
|
|
228
|
+
if resp.status_code in _RETRY_STATUS and attempt < retries:
|
|
229
|
+
sleep_s = backoff * (2 ** (attempt - 1))
|
|
230
|
+
time.sleep(sleep_s)
|
|
231
|
+
continue
|
|
232
|
+
|
|
233
|
+
# Raise for other non-OK codes
|
|
234
|
+
resp.raise_for_status()
|
|
235
|
+
|
|
236
|
+
# Basic sanity checks: content-type and size
|
|
237
|
+
ctype = (resp.headers.get("Content-Type") or "").lower()
|
|
238
|
+
if "html" in ctype:
|
|
239
|
+
raise ValueError(f"Expected ELF bytes, got {ctype} from {url}")
|
|
240
|
+
|
|
241
|
+
return io.BytesIO(resp.content)
|
|
242
|
+
|
|
243
|
+
except (requests.Timeout, requests.ConnectionError) as e:
|
|
244
|
+
last_err = e
|
|
245
|
+
if attempt < retries:
|
|
246
|
+
sleep_s = backoff * (2 ** (attempt - 1))
|
|
247
|
+
time.sleep(sleep_s)
|
|
248
|
+
continue
|
|
249
|
+
raise ConnectionError(f"Failed to download ELF from {url}: {e}") from e
|
|
250
|
+
|
|
251
|
+
except Exception as e:
|
|
252
|
+
raise
|
|
253
|
+
|
|
254
|
+
# Should not reach here; defensive:
|
|
255
|
+
raise ConnectionError(f"Failed to download ELF from {url}: {last_err}")
|