busytag 0.1.0__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.
@@ -0,0 +1,174 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ #uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ #poetry.lock
109
+
110
+ # pdm
111
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
112
+ #pdm.lock
113
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
114
+ # in version control.
115
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
116
+ .pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
121
+ __pypackages__/
122
+
123
+ # Celery stuff
124
+ celerybeat-schedule
125
+ celerybeat.pid
126
+
127
+ # SageMath parsed files
128
+ *.sage.py
129
+
130
+ # Environments
131
+ .env
132
+ .venv
133
+ env/
134
+ venv/
135
+ ENV/
136
+ env.bak/
137
+ venv.bak/
138
+
139
+ # Spyder project settings
140
+ .spyderproject
141
+ .spyproject
142
+
143
+ # Rope project settings
144
+ .ropeproject
145
+
146
+ # mkdocs documentation
147
+ /site
148
+
149
+ # mypy
150
+ .mypy_cache/
151
+ .dmypy.json
152
+ dmypy.json
153
+
154
+ # Pyre type checker
155
+ .pyre/
156
+
157
+ # pytype static type analyzer
158
+ .pytype/
159
+
160
+ # Cython debug symbols
161
+ cython_debug/
162
+
163
+ # PyCharm
164
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
165
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
166
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
167
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
168
+ #.idea/
169
+
170
+ # Ruff stuff:
171
+ .ruff_cache/
172
+
173
+ # PyPI configuration file
174
+ .pypirc
@@ -0,0 +1,8 @@
1
+ # Default ignored files
2
+ /shelf/
3
+ /workspace.xml
4
+ # Editor-based HTTP Client requests
5
+ /httpRequests/
6
+ # Datasource local storage ignored files
7
+ /dataSources/
8
+ /dataSources.local.xml
@@ -0,0 +1,10 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <module type="PYTHON_MODULE" version="4">
3
+ <component name="NewModuleRootManager">
4
+ <content url="file://$MODULE_DIR$">
5
+ <excludeFolder url="file://$MODULE_DIR$/.venv" />
6
+ </content>
7
+ <orderEntry type="jdk" jdkName="Python 3.11" jdkType="Python SDK" />
8
+ <orderEntry type="sourceFolder" forTests="false" />
9
+ </component>
10
+ </module>
@@ -0,0 +1,6 @@
1
+ <component name="InspectionProjectProfileManager">
2
+ <settings>
3
+ <option name="USE_PROJECT_PROFILE" value="false" />
4
+ <version value="1.0" />
5
+ </settings>
6
+ </component>
@@ -0,0 +1,7 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="Black">
4
+ <option name="sdkName" value="Python 3.11 (busytag_tool)" />
5
+ </component>
6
+ <component name="ProjectRootManager" version="2" project-jdk-name="Python 3.11" project-jdk-type="Python SDK" />
7
+ </project>
@@ -0,0 +1,8 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="ProjectModuleManager">
4
+ <modules>
5
+ <module fileurl="file://$PROJECT_DIR$/.idea/busytag_tool.iml" filepath="$PROJECT_DIR$/.idea/busytag_tool.iml" />
6
+ </modules>
7
+ </component>
8
+ </project>
@@ -0,0 +1,6 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="VcsDirectoryMappings">
4
+ <mapping directory="$PROJECT_DIR$" vcs="Git" />
5
+ </component>
6
+ </project>
@@ -0,0 +1,121 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="AutoImportSettings">
4
+ <option name="autoReloadType" value="SELECTIVE" />
5
+ </component>
6
+ <component name="ChangeListManager">
7
+ <list default="true" id="b00fe0d2-8245-48a8-ad2d-a72d58352d69" name="Changes" comment="- Removed stub for LED colour config from `config.py`. This will have to wait for me to be on the train to be coded.&#10;- Revamped commands, and made it so that only 1 command can be sent at a time, simplifying (error) handling">
8
+ <change afterPath="$PROJECT_DIR$/pyproject.toml" afterDir="false" />
9
+ <change beforePath="$PROJECT_DIR$/README.md" beforeDir="false" afterPath="$PROJECT_DIR$/README.md" afterDir="false" />
10
+ <change beforePath="$PROJECT_DIR$/src/busytag/busytag_tool.py" beforeDir="false" afterPath="$PROJECT_DIR$/src/busytag/tool.py" afterDir="false" />
11
+ </list>
12
+ <option name="SHOW_DIALOG" value="false" />
13
+ <option name="HIGHLIGHT_CONFLICTS" value="true" />
14
+ <option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
15
+ <option name="LAST_RESOLUTION" value="IGNORE" />
16
+ </component>
17
+ <component name="FileTemplateManagerImpl">
18
+ <option name="RECENT_TEMPLATES">
19
+ <list>
20
+ <option value="Python Script" />
21
+ </list>
22
+ </option>
23
+ </component>
24
+ <component name="Git.Settings">
25
+ <option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
26
+ </component>
27
+ <component name="GitHubPullRequestSearchHistory">{
28
+ &quot;lastFilter&quot;: {
29
+ &quot;state&quot;: &quot;OPEN&quot;,
30
+ &quot;assignee&quot;: &quot;acoster&quot;
31
+ }
32
+ }</component>
33
+ <component name="GithubPullRequestsUISettings">{
34
+ &quot;selectedUrlAndAccountId&quot;: {
35
+ &quot;url&quot;: &quot;git@github.com:acoster/busytag_tool.git&quot;,
36
+ &quot;accountId&quot;: &quot;bcded20e-22d0-4617-9b93-716e5c915d77&quot;
37
+ }
38
+ }</component>
39
+ <component name="ProjectColorInfo">{
40
+ &quot;customColor&quot;: &quot;&quot;,
41
+ &quot;associatedIndex&quot;: 2
42
+ }</component>
43
+ <component name="ProjectId" id="2x7WvOCgGlARSsQq7EefNLyM4aW" />
44
+ <component name="ProjectViewState">
45
+ <option name="hideEmptyMiddlePackages" value="true" />
46
+ <option name="showLibraryContents" value="true" />
47
+ </component>
48
+ <component name="PropertiesComponent">{
49
+ &quot;keyToString&quot;: {
50
+ &quot;RunOnceActivity.ShowReadmeOnStart&quot;: &quot;true&quot;,
51
+ &quot;RunOnceActivity.git.unshallow&quot;: &quot;true&quot;,
52
+ &quot;git-widget-placeholder&quot;: &quot;devel&quot;,
53
+ &quot;node.js.detected.package.eslint&quot;: &quot;true&quot;,
54
+ &quot;node.js.detected.package.tslint&quot;: &quot;true&quot;,
55
+ &quot;node.js.selected.package.eslint&quot;: &quot;(autodetect)&quot;,
56
+ &quot;node.js.selected.package.tslint&quot;: &quot;(autodetect)&quot;,
57
+ &quot;nodejs_package_manager_path&quot;: &quot;npm&quot;,
58
+ &quot;settings.editor.selected.configurable&quot;: &quot;com.jetbrains.python.configuration.PyIntegratedToolsModulesConfigurable&quot;,
59
+ &quot;vue.rearranger.settings.migration&quot;: &quot;true&quot;
60
+ }
61
+ }</component>
62
+ <component name="RecentsManager">
63
+ <key name="MoveFile.RECENT_KEYS">
64
+ <recent name="$PROJECT_DIR$/src/busytag" />
65
+ </key>
66
+ </component>
67
+ <component name="SharedIndexes">
68
+ <attachedChunks>
69
+ <set>
70
+ <option value="bundled-js-predefined-d6986cc7102b-1632447f56bf-JavaScript-PY-243.26053.29" />
71
+ <option value="bundled-python-sdk-b1dbf8ef85a6-4df51de95216-com.jetbrains.pycharm.pro.sharedIndexes.bundled-PY-243.26053.29" />
72
+ </set>
73
+ </attachedChunks>
74
+ </component>
75
+ <component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="application-level" UseSingleDictionary="true" transferred="true" />
76
+ <component name="TaskManager">
77
+ <task active="true" id="Default" summary="Default task">
78
+ <changelist id="b00fe0d2-8245-48a8-ad2d-a72d58352d69" name="Changes" comment="" />
79
+ <created>1747289822490</created>
80
+ <option name="number" value="Default" />
81
+ <option name="presentableId" value="Default" />
82
+ <updated>1747289822490</updated>
83
+ <workItem from="1747289824286" duration="872000" />
84
+ <workItem from="1747297510490" duration="857000" />
85
+ <workItem from="1747306945194" duration="1514000" />
86
+ <workItem from="1747320172392" duration="1087000" />
87
+ <workItem from="1747321455924" duration="13000" />
88
+ <workItem from="1747330089513" duration="120000" />
89
+ <workItem from="1747376244597" duration="5032000" />
90
+ <workItem from="1747391190906" duration="1964000" />
91
+ <workItem from="1747395701393" duration="72000" />
92
+ <workItem from="1747402876012" duration="4807000" />
93
+ </task>
94
+ <task id="LOCAL-00001" summary="- Add CLI module with some basic commands for file and display/LED manipulation&#10;- Start using absl logging utility. Mainly because that's what I'm used to">
95
+ <option name="closed" value="true" />
96
+ <created>1747382538655</created>
97
+ <option name="number" value="00001" />
98
+ <option name="presentableId" value="LOCAL-00001" />
99
+ <option name="project" value="LOCAL" />
100
+ <updated>1747382538655</updated>
101
+ </task>
102
+ <task id="LOCAL-00002" summary="- Removed stub for LED colour config from `config.py`. This will have to wait for me to be on the train to be coded.&#10;- Revamped commands, and made it so that only 1 command can be sent at a time, simplifying (error) handling">
103
+ <option name="closed" value="true" />
104
+ <created>1747395762260</created>
105
+ <option name="number" value="00002" />
106
+ <option name="presentableId" value="LOCAL-00002" />
107
+ <option name="project" value="LOCAL" />
108
+ <updated>1747395762260</updated>
109
+ </task>
110
+ <option name="localTasksCounter" value="3" />
111
+ <servers />
112
+ </component>
113
+ <component name="TypeScriptGeneratedFilesManager">
114
+ <option name="version" value="3" />
115
+ </component>
116
+ <component name="VcsManagerConfiguration">
117
+ <MESSAGE value="- Add CLI module with some basic commands for file and display/LED manipulation&#10;- Start using absl logging utility. Mainly because that's what I'm used to" />
118
+ <MESSAGE value="- Removed stub for LED colour config from `config.py`. This will have to wait for me to be on the train to be coded.&#10;- Revamped commands, and made it so that only 1 command can be sent at a time, simplifying (error) handling" />
119
+ <option name="LAST_COMMIT_MESSAGE" value="- Removed stub for LED colour config from `config.py`. This will have to wait for me to be on the train to be coded.&#10;- Revamped commands, and made it so that only 1 command can be sent at a time, simplifying (error) handling" />
120
+ </component>
121
+ </project>
busytag-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Alex Coster
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
busytag-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,61 @@
1
+ Metadata-Version: 2.4
2
+ Name: busytag
3
+ Version: 0.1.0
4
+ Summary: A library and CLI tool to control Busy Tag devices.
5
+ Project-URL: Homepage, https://github.com/acoster/busytag_tool
6
+ Project-URL: Issues, https://github.com/acoster/busytag_tool/issues
7
+ Project-URL: Repository, https://github.com/acoster/busytag_tool.git
8
+ Author-email: Alex Coster <alex@coster.ch>
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Classifier: Development Status :: 2 - Pre-Alpha
12
+ Classifier: Environment :: Console
13
+ Classifier: Operating System :: OS Independent
14
+ Requires-Python: >=3.11
15
+ Requires-Dist: absl-py~=2.1.0
16
+ Requires-Dist: pyserial~=3.5
17
+ Requires-Dist: tomlkit~=0.13.2
18
+ Description-Content-Type: text/markdown
19
+
20
+ # busytag_tool
21
+
22
+ Python library and CLI to interact with [Busy Tag](https://www.busy-tag.com/) devices using
23
+ the [USB CDC interface]( https://luxafor.helpscoutdocs.com/article/47-busy-tag-usb-cdc-command-reference-guide).
24
+
25
+ ## Installation
26
+
27
+ ```shell
28
+ $ pip install busytag
29
+ ```
30
+
31
+ ## CLI usage
32
+
33
+ The first time the tool is used, you should pass the device path through
34
+ the flag `--device=/dev/whatever`. This will be saved in `~/.busytag.toml`
35
+ and will be used in subsequent runs where `--device` is not passed.
36
+
37
+ ```shell
38
+ $ busytag-tool
39
+ Available commands:
40
+ help: Prints this message
41
+ info: Displays device information
42
+ list_pictures: Lists pictures in device
43
+ list_files: Lists files in device
44
+ get_picture: Gets the filename of the picture being shown
45
+ set_picture <filename>: Sets the picture shown in the device
46
+ put <filename>: Uploads <filename>
47
+ get <filename>: Copies <filename> from the device to the working directory
48
+ rm <filename>: Deletes <filename>
49
+ set_led_solid_color <6 hex RGB colour>: Sets the LEDs colour
50
+ get_brightness: Gets current display brightness
51
+ set_brightness <brightness>: Sets current display brightness (int between 1 and 100, inclusive
52
+ ```
53
+
54
+ ## API usage
55
+
56
+ ```python
57
+ from busytag import Device
58
+
59
+ bt = Device('/dev/fooBar')
60
+ bt.set_active_picture('coding.gif')
61
+ ```
@@ -0,0 +1,42 @@
1
+ # busytag_tool
2
+
3
+ Python library and CLI to interact with [Busy Tag](https://www.busy-tag.com/) devices using
4
+ the [USB CDC interface]( https://luxafor.helpscoutdocs.com/article/47-busy-tag-usb-cdc-command-reference-guide).
5
+
6
+ ## Installation
7
+
8
+ ```shell
9
+ $ pip install busytag
10
+ ```
11
+
12
+ ## CLI usage
13
+
14
+ The first time the tool is used, you should pass the device path through
15
+ the flag `--device=/dev/whatever`. This will be saved in `~/.busytag.toml`
16
+ and will be used in subsequent runs where `--device` is not passed.
17
+
18
+ ```shell
19
+ $ busytag-tool
20
+ Available commands:
21
+ help: Prints this message
22
+ info: Displays device information
23
+ list_pictures: Lists pictures in device
24
+ list_files: Lists files in device
25
+ get_picture: Gets the filename of the picture being shown
26
+ set_picture <filename>: Sets the picture shown in the device
27
+ put <filename>: Uploads <filename>
28
+ get <filename>: Copies <filename> from the device to the working directory
29
+ rm <filename>: Deletes <filename>
30
+ set_led_solid_color <6 hex RGB colour>: Sets the LEDs colour
31
+ get_brightness: Gets current display brightness
32
+ set_brightness <brightness>: Sets current display brightness (int between 1 and 100, inclusive
33
+ ```
34
+
35
+ ## API usage
36
+
37
+ ```python
38
+ from busytag import Device
39
+
40
+ bt = Device('/dev/fooBar')
41
+ bt.set_active_picture('coding.gif')
42
+ ```
@@ -0,0 +1,30 @@
1
+ [project]
2
+ name = "busytag"
3
+ version = "0.1.0"
4
+ dynamic = ["dependencies"]
5
+ authors = [{ name = "Alex Coster", email = "alex@coster.ch" }]
6
+ description = "A library and CLI tool to control Busy Tag devices."
7
+ readme = "README.md"
8
+ requires-python = ">=3.11"
9
+ license = "MIT"
10
+ license-files = ["LICENSE"]
11
+ classifiers = [
12
+ "Development Status :: 2 - Pre-Alpha",
13
+ "Environment :: Console",
14
+ "Operating System :: OS Independent"
15
+ ]
16
+
17
+ [project.scripts]
18
+ busytag-tool = "busytag.tool:run_main"
19
+
20
+ [project.urls]
21
+ Homepage = "https://github.com/acoster/busytag_tool"
22
+ Issues = "https://github.com/acoster/busytag_tool/issues"
23
+ Repository = "https://github.com/acoster/busytag_tool.git"
24
+
25
+ [build-system]
26
+ requires = ["hatchling >= 1.26", "hatch-requirements-txt"]
27
+ build-backend = "hatchling.build"
28
+
29
+ [tool.hatch.metadata.hooks.requirements_txt]
30
+ files = ["requirements.txt"]
@@ -0,0 +1,4 @@
1
+ -i https://pypi.org/simple
2
+ absl-py~=2.1.0
3
+ pyserial~=3.5
4
+ tomlkit~=0.13.2
@@ -0,0 +1,4 @@
1
+ # SPDX-License-Identifier: MIT
2
+
3
+ from .device import Device
4
+ from .types import *
@@ -0,0 +1,31 @@
1
+ # SPDX-License-Identifier: MIT
2
+
3
+ import tomlkit
4
+ import os.path
5
+
6
+ from .types import *
7
+
8
+ from typing import Optional, Sequence
9
+
10
+ class ToolConfig(object):
11
+ def __init__(self, path: Optional[str] = None):
12
+ self.device = None
13
+ self.path = path
14
+ if path is not None:
15
+ self.path = os.path.expanduser(path)
16
+ if os.path.exists(self.path):
17
+ self.__load_from_file()
18
+
19
+
20
+ def write_to_file(self):
21
+ assert self.path is not None
22
+ conf = {}
23
+ if self.device is not None:
24
+ conf['device'] = self.device
25
+ with open(self.path, "w") as fp:
26
+ tomlkit.dump(conf, fp)
27
+
28
+ def __load_from_file(self):
29
+ with open(self.path, 'rb') as fp:
30
+ conf = tomlkit.load(fp)
31
+ self.device = conf['device']
@@ -0,0 +1,284 @@
1
+ # SPDX-License-Identifier: MIT
2
+
3
+ from absl import logging
4
+ from typing import Sequence, Optional
5
+
6
+ from .types import *
7
+
8
+ import serial
9
+
10
+ __all__ = ['Device']
11
+
12
+
13
+ class Device(object):
14
+ """Class to interact with Busy-Tag devices through a serial connection.
15
+
16
+ The protocol to communicate with the Busy-Tag device is documented at
17
+ https://luxafor.helpscoutdocs.com/article/47-busy-tag-usb-cdc-command-reference-guide.
18
+ """
19
+
20
+ def __init__(self, port_path: Optional[str] = None,
21
+ connection: Optional[serial.Serial] = None,
22
+ baudrate: int = 115200):
23
+ assert not (port_path is None and connection is None)
24
+ if port_path is not None:
25
+ self._port = port_path
26
+ logging.info(f'Connecting to serial port {port_path}')
27
+ self.conn = serial.Serial(port_path, baudrate)
28
+ else:
29
+ self._port = None
30
+ self.conn = connection
31
+
32
+ self.__capacity = int(self.__get_readonly_attribute('TSS'))
33
+ self.__device_id = self.__get_readonly_attribute('ID')
34
+ self.__firmware_version = self.__get_readonly_attribute('FV')
35
+ self.__hostname = self.__get_readonly_attribute('LHA').removeprefix(
36
+ 'http://')
37
+ self.__manufacturer = self.__get_readonly_attribute('MN')
38
+ self.__name = self.__get_readonly_attribute('DN')
39
+
40
+ def list_pictures(self) -> Sequence[FileEntry]:
41
+ """Lists pictures that can be displayed on the screen."""
42
+ self.__send_command('AT+GPL')
43
+ result = []
44
+ while True:
45
+ l = self.__readline()
46
+ # Unlikely, but event messages might arrive while we're listing
47
+ # files. Silently consume them.
48
+ if l.startswith(b'+evn'):
49
+ continue
50
+
51
+ if l.startswith(b'OK'):
52
+ break
53
+
54
+ filename, size = l.decode().removeprefix('+PL:').split(',')
55
+ result.append(FileEntry(filename, int(size)))
56
+
57
+ return result
58
+
59
+ def list_files(self) -> Sequence[FileEntry]:
60
+ """Lists all files stored on the device."""
61
+ self.__send_command('AT+GFL')
62
+ result = []
63
+ while True:
64
+ l = self.__readline()
65
+ if l.startswith(b'+evn'):
66
+ continue
67
+ if l.startswith(b'OK'):
68
+ break
69
+ filename, entry_type, size = l.decode().removeprefix('+FL:').split(
70
+ ',')
71
+ result.append(
72
+ FileEntry(filename, int(size), FileEntryType(entry_type)))
73
+
74
+ return result
75
+
76
+ def read_file(self, filename: str) -> bytes:
77
+ """Reads a file from the device.
78
+
79
+ :param filename: The filename of the file to read
80
+ :return: a `bytes` object with the file contents
81
+ """
82
+ logging.info(f'Reading file {filename}')
83
+
84
+ self.__send_command('AT+GF=%s' % (filename,))
85
+ # First part of response: +GF:<filename>,<size in bytes>\r\n
86
+ response = self.__read_response('+GF:')
87
+ if b',' not in response:
88
+ raise IOError(
89
+ 'Malformed response to command AT+GF=%s' % (response,))
90
+
91
+ read_size = int(response.split(b',')[1]) + 8
92
+ logging.debug(f'Reading {read_size} bytes from device')
93
+ response = self.conn.read(read_size)
94
+ assert response[-6:] == b'\r\nOK\r\n'
95
+ return response[2:-6]
96
+
97
+ def upload_file(self, filename: str, data: bytes):
98
+ """Uploads a file to the device.
99
+
100
+ :param filename: The filename of the file to upload
101
+ :param data: The contents of the file to upload
102
+ """
103
+ logging.info(f'Uploading file {filename} ({len(data)} bytes)')
104
+
105
+ self.__send_command('AT+UF=%s,%d' % (filename, len(data)))
106
+ self.__readline()
107
+ logging.debug('Writing %d bytes to device', len(data))
108
+ self.conn.write(data)
109
+ terminator = self.conn.read(6)
110
+ assert terminator == b'\r\nOK\r\n'
111
+
112
+ def delete_file(self, filename: str):
113
+ """Deletes a file from the device.'
114
+
115
+ :param filename: The filename of the file to delete
116
+ """
117
+ logging.info(f'Deleting file {filename}')
118
+ self.__send_command('AT+DF=%s' % (filename,))
119
+ self.__read_response('+DF:')
120
+ self.__read_response('OK')
121
+
122
+ def set_active_picture(self, filename: str):
123
+ """Set the picture that will be shown on the display."""
124
+ logging.info(f'Setting active picture {filename}')
125
+ self.__set_attribute('SP', filename)
126
+
127
+ def get_active_picture(self) -> str:
128
+ """Gets the file name of the picture being displayed."""
129
+ return self.__get_attribute('SP')
130
+
131
+ def get_free_storage(self) -> int:
132
+ return int(self.__get_readonly_attribute('FSS'))
133
+
134
+ def get_display_brightness(self) -> int:
135
+ return int(self.__get_attribute('DB'))
136
+
137
+ def set_display_brightness(self, brightness: int):
138
+ if brightness < 1 or brightness > 100:
139
+ raise ValueError('Brightness must be between 1 and 100')
140
+ self.__set_attribute('DB', f'{brightness}')
141
+
142
+ def get_led_solid_color(self) -> LedConfig:
143
+ pins, rgb = self.__get_attribute('SC').split(',')
144
+ return LedConfig(LedPin(int(pins)), rgb)
145
+
146
+ def set_led_solid_color(self, config: LedConfig):
147
+ self.__set_attribute('SC', f'{int(config.pins)},{config.color}')
148
+
149
+ def get_led_pattern(self) -> Sequence[LedPatternEntry]:
150
+ result = []
151
+ self.__send_command('AT+CP?')
152
+ while True:
153
+ entry = self.__readline().strip()
154
+ if entry.startswith(b'ERROR'):
155
+ logging.error('Received error response: %s', entry)
156
+ raise self.build_exception(entry)
157
+ if entry.startswith(b'+CP'):
158
+ pins, rgb, speed, delay = entry.removeprefix(
159
+ b'+CP:').decode().split(',')
160
+ result.append(
161
+ LedPatternEntry(LedPin(int(pins)), rgb, int(speed),
162
+ int(delay)))
163
+ elif entry.startswith(b'OK'):
164
+ break
165
+
166
+ return result
167
+
168
+ def set_led_pattern(self, pattern: Sequence[LedPatternEntry]):
169
+ assert 0 < len(pattern) <= 40
170
+ self.__send_command(f'AT+CP={len(pattern)}')
171
+ self.__read_response('>')
172
+ for entry in pattern:
173
+ self.__send_command(f'+CP:{entry}')
174
+ self.__read_response('OK')
175
+
176
+ def get_wifi_config(self) -> WifiConfig:
177
+ response = self.__get_attribute('WC')
178
+ if ',' not in response:
179
+ raise IOError(f'Malformed response to command AT+WC: {response}')
180
+ ssid, password = response.split(',', 1)
181
+ return WifiConfig(ssid, password)
182
+
183
+ def set_wifi_config(self, wifi_config: WifiConfig):
184
+ logging.info(f'Setting Wifi SSID to {wifi_config.ssid}')
185
+ self.__set_attribute('WC', f'{wifi_config.ssid},{wifi_config.password}')
186
+
187
+ def reset_wifi_config(self):
188
+ logging.info('Resetting wifi configuration')
189
+ self.__send_command('AT+FRWCF')
190
+ self.__read_response('OK')
191
+
192
+ @property
193
+ def capacity(self) -> int:
194
+ return self.__capacity
195
+
196
+ @property
197
+ def device_id(self) -> str:
198
+ return self.__device_id
199
+
200
+ @property
201
+ def hostname(self) -> str:
202
+ return self.__hostname
203
+
204
+ @property
205
+ def firmware_version(self) -> str:
206
+ return self.__firmware_version
207
+
208
+ @property
209
+ def manufacturer(self) -> str:
210
+ return self.__manufacturer
211
+
212
+ @property
213
+ def name(self) -> str:
214
+ return self.__name
215
+
216
+ def __get_readonly_attribute(self, attribute: str) -> str:
217
+ """Retrieves the value of a read-only attribute (e.g. device id)."""
218
+ response_prefix = f'+{attribute}:'
219
+ self.__send_command(f'AT+G{attribute}')
220
+ return self.__read_response(response_prefix).decode().removeprefix(
221
+ response_prefix)
222
+
223
+ def __get_attribute(self, attribute: str) -> str:
224
+ """Retrieves the value of a user-modifiable attribute (e.g. active picture)."""
225
+ response_prefix = f'+{attribute}:'
226
+ self.__send_command(f'AT+{attribute}?')
227
+ return self.__read_response(response_prefix).decode().removeprefix(
228
+ response_prefix)
229
+
230
+ def __set_attribute(self, attribute: str, value: str):
231
+ """Sets the value of a user-modifiable attribute (e.g. active picture)."""
232
+ self.__send_command(f'AT+{attribute}={value}')
233
+ self.__read_response('OK')
234
+
235
+ def __send_command(self, command: str):
236
+ encoded_command = command.encode() + b'\r\n'
237
+ logging.debug('Sending command: %s', encoded_command)
238
+ self.conn.write(encoded_command)
239
+
240
+ def __read_response(self, prefix: str) -> bytes:
241
+ logging.debug(f'Waiting for prefix: {prefix}')
242
+ encoded_prefix = prefix.encode()
243
+ while True:
244
+ response = self.__readline()
245
+ if response.startswith(encoded_prefix):
246
+ return response
247
+
248
+ def __readline(self) -> bytes:
249
+ result = self.conn.readline()
250
+ logging.debug('Read from device: %s', result)
251
+ if result.startswith(b'ERROR'):
252
+ logging.error('Received error response: %s', result)
253
+ raise self.build_exception(result)
254
+ return result.strip()
255
+
256
+ @staticmethod
257
+ def build_exception(error_response: bytes) -> Exception:
258
+ """Converts an error response from Busy Tag to an Exception"""
259
+ if not error_response.startswith(b'ERROR:'):
260
+ return Exception(
261
+ 'Unexpected error response %s' % (error_response.decode(),))
262
+
263
+ parts = error_response.decode().strip().split(':')
264
+ if len(parts) != 2:
265
+ return Exception(
266
+ 'Unexpected error response %s' % (error_response.decode(),))
267
+
268
+ match parts[1]:
269
+ case '-1':
270
+ return Exception(
271
+ 'Unexpected error response %s' % (error_response.decode(),))
272
+ case '0':
273
+ return Exception('Unknown error')
274
+ case '1':
275
+ return ValueError('Invalid command')
276
+ case '2':
277
+ return ValueError('Invalid argument')
278
+ case '3':
279
+ return FileNotFoundError('File not found')
280
+ case '4':
281
+ return ValueError('Invalid size')
282
+ case _:
283
+ return Exception(
284
+ 'Unexpected error response %s' % (error_response.decode(),))
@@ -0,0 +1,127 @@
1
+ #!/usr/bin/env python
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ from absl import app, flags
5
+
6
+ from os.path import basename, expanduser
7
+ from typing import List
8
+
9
+ from .config import ToolConfig
10
+ from .device import Device
11
+ from .types import *
12
+
13
+ FLAGS = flags.FLAGS
14
+ flags.DEFINE_string('config_file', '~/.busytag.toml', 'Config file path')
15
+ flags.DEFINE_string('device', None, 'Busy Tag\'s serial port.')
16
+ flags.DEFINE_integer('baudrate', 115200, 'Connection baudrate.')
17
+
18
+ def format_size(size: int) -> str:
19
+ if size < 1_000:
20
+ return f'{size} B'
21
+ if size < 500_000:
22
+ return f'{size/1_000:.2f} kB'
23
+ return f'{size/1_000_000:.2f} MB'
24
+
25
+
26
+ def main(argv: List[str]) -> None:
27
+ config = ToolConfig(FLAGS.config_file)
28
+ if FLAGS.device is not None:
29
+ config.device = FLAGS.device
30
+ if config.device is None:
31
+ raise Exception('Device must be specified')
32
+
33
+ bt:Device = None
34
+
35
+ # Remove argv[0]
36
+ argv.pop(0)
37
+ command = 'help'
38
+ if len(argv) > 0:
39
+ command = argv.pop(0)
40
+ bt = Device(config.device, baudrate=FLAGS.baudrate)
41
+
42
+
43
+ match command:
44
+ case 'info':
45
+ print(f'Device name: {bt.name}')
46
+ print(f'Device ID: {bt.device_id}')
47
+ print(f'Firmware version: {bt.firmware_version}')
48
+ print(f'Serial port: {config.device}')
49
+ print(f'Storage capacity: {format_size(bt.capacity)}')
50
+ print(f'Free storage: {format_size(bt.get_free_storage())}')
51
+
52
+ case 'list_pictures':
53
+ print('Pictures in device:')
54
+ for picture in bt.list_pictures():
55
+ print(f' {picture.name} ({format_size(picture.size)})')
56
+ print(f'Available space: {format_size(bt.get_free_storage())}')
57
+
58
+ case 'list_files':
59
+ print('Files in device: ')
60
+ for file in bt.list_files():
61
+ print(f' {file.name} ({file.type.value} - {format_size(file.size)})')
62
+ print(f'Available space: {format_size(bt.get_free_storage())}')
63
+
64
+ case 'set_picture':
65
+ assert len(argv) >= 1
66
+ bt.set_active_picture(argv.pop(0))
67
+
68
+ case 'get_picture':
69
+ print(f'Current active picture: {bt.get_active_picture()}')
70
+
71
+ case 'put':
72
+ assert len(argv) >= 1
73
+ filename = expanduser(argv.pop(0))
74
+ with open(filename, 'rb') as fp:
75
+ bt.upload_file(basename(filename), fp.read())
76
+
77
+ case 'get':
78
+ assert len(argv) >= 1
79
+ filename = argv.pop(0)
80
+ data = bt.read_file(filename)
81
+ with open(filename, 'wb') as fp:
82
+ fp.write(data)
83
+
84
+ case 'rm':
85
+ assert len(argv) >= 1
86
+ filename = argv.pop(0)
87
+ bt.delete_file(filename)
88
+
89
+ case 'set_led_solid_color':
90
+ assert len(argv) >= 1
91
+ led_config = LedConfig(LedPin.ALL, argv.pop(0).upper())
92
+ bt.set_led_solid_color(led_config)
93
+
94
+ case 'get_brightness':
95
+ print(f'Brightness: {bt.get_display_brightness()}')
96
+
97
+ case 'set_brightness':
98
+ assert len(argv) >= 1
99
+ brightness = int(argv.pop(0))
100
+ assert 0 < brightness <= 100
101
+ bt.set_display_brightness(brightness)
102
+
103
+ case 'help':
104
+ print('Available commands:')
105
+ print(' help: Prints this message')
106
+ print(' info: Displays device information')
107
+ print(' list_pictures: Lists pictures in device')
108
+ print(' list_files: Lists files in device')
109
+ print(' get_picture: Gets the filename of the picture being shown')
110
+ print(' set_picture <filename>: Sets the picture shown in the device')
111
+ print(' put <filename>: Uploads <filename>')
112
+ print(' get <filename>: Copies <filename> from the device to the working directory')
113
+ print(' rm <filename>: Deletes <filename>')
114
+ print(' set_led_solid_color <6 hex RGB colour>: Sets the LEDs colour')
115
+ print(' get_brightness: Gets current display brightness')
116
+ print(' set_brightness <brightness>: Sets current display brightness (int between 1 and 100, inclusive')
117
+
118
+ case _:
119
+ print(f'Unknown command `{command}`. Please use the `help` to list available commands')
120
+
121
+ config.write_to_file()
122
+
123
+ def run_main():
124
+ app.run(main)
125
+
126
+ if __name__ == '__main__':
127
+ run_main()
@@ -0,0 +1,67 @@
1
+ # SPDX-License-Identifier: MIT
2
+
3
+ import re
4
+ from dataclasses import dataclass
5
+ from enum import Enum, IntFlag, verify, NAMED_FLAGS
6
+
7
+ rgb_re = re.compile(r'^[0-9A-F]{6}$')
8
+
9
+ __all__ = ['LedPin', 'FileEntry', 'FileEntryType', 'WifiConfig', 'LedConfig',
10
+ 'LedPatternEntry' ]
11
+
12
+
13
+ @verify(NAMED_FLAGS)
14
+ class LedPin(IntFlag):
15
+ PIN_0 = 1
16
+ PIN_1 = 2
17
+ PIN_2 = 4
18
+ PIN_3 = 8
19
+ PIN_4 = 16
20
+ PIN_5 = 32
21
+ PIN_6 = 64
22
+ ALL = 127
23
+
24
+
25
+ class FileEntryType(Enum):
26
+ FILE = 'file'
27
+ DIRECTORY = 'dir'
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class FileEntry:
32
+ """File stored in the Busy Tag device."""
33
+ name: str
34
+ size: int
35
+ type: FileEntryType = FileEntryType.FILE
36
+
37
+
38
+ @dataclass(frozen=True)
39
+ class WifiConfig:
40
+ """Wifi configuration."""
41
+ ssid: str
42
+ password: str
43
+
44
+
45
+ @dataclass(frozen=True)
46
+ class LedConfig:
47
+ pins: LedPin
48
+ color: str
49
+
50
+ def __post_init__(self):
51
+ assert rgb_re.match(self.color)
52
+
53
+
54
+ @dataclass(frozen=True)
55
+ class LedPatternEntry:
56
+ pins: LedPin
57
+ color: str
58
+ speed: int
59
+ delay: int
60
+
61
+ def __post_init__(self):
62
+ assert rgb_re.match(self.color)
63
+ assert self.speed >= 0
64
+ assert self.delay >= 0
65
+
66
+ def __str__(self) -> str:
67
+ return f'{int(self.pins)},{self.color},{self.speed},{self.delay}'