visor-kit 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,31 @@
1
+ # Gradle and Android build output
2
+ .gradle/
3
+ build/
4
+ .kotlin/
5
+ local.properties
6
+ *.iml
7
+
8
+ # Signing material and credentials, never commit
9
+ *.jks
10
+ *.keystore
11
+ *.gpg
12
+ *.asc
13
+ secrets/
14
+
15
+ # IDE
16
+ .idea/
17
+ bin/
18
+
19
+ # OS
20
+ .DS_Store
21
+ Thumbs.db
22
+
23
+ # Local agent setup
24
+ .claude/
25
+ .agents/
26
+
27
+ # Client builds
28
+ node_modules/
29
+ dist/
30
+ __pycache__/
31
+ *.egg-info/
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,135 @@
1
+ Metadata-Version: 2.5
2
+ Name: visor-kit
3
+ Version: 0.1.0
4
+ Summary: The Visor Development Kit from Python: Meta's glasses through Visor, over adb or the network.
5
+ Project-URL: Homepage, https://visor.macedonga.com/developers/
6
+ Project-URL: Documentation, https://visor.macedonga.com/developers/docs/
7
+ Project-URL: Source, https://github.com/macedonga/visor-kit
8
+ Project-URL: Issues, https://github.com/macedonga/visor-kit/issues
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: meta,neural-band,ray-ban,smart-glasses,vdk,visor,wearables
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Framework :: AsyncIO
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Topic :: Software Development :: Libraries
17
+ Requires-Python: >=3.9
18
+ Provides-Extra: network
19
+ Requires-Dist: websockets>=13; extra == 'network'
20
+ Description-Content-Type: text/markdown
21
+
22
+ <p align="center">
23
+ <img src="https://raw.githubusercontent.com/macedonga/visor-kit/main/clients/python/banner.png" alt="VDK for Python: scripts and agents, over adb or the network" width="100%">
24
+ </p>
25
+
26
+ <p align="center">
27
+ <b>The Visor Development Kit in Python.</b><br>
28
+ Meta glasses from your scripts and agents, over adb or the network, through <a href="https://visor.macedonga.com">Visor</a>.
29
+ </p>
30
+
31
+ <p align="center">
32
+ <a href="https://pypi.org/project/visor-kit/"><img src="https://img.shields.io/pypi/v/visor-kit?style=for-the-badge&label=PyPI&color=2563EB&labelColor=0B1220" alt="visor-kit on PyPI"></a>
33
+ <a href="https://visor.macedonga.com/developers/docs/"><img src="https://img.shields.io/badge/Docs-read%20the%20guide-2563EB?style=for-the-badge&labelColor=0B1220" alt="Documentation"></a>
34
+ <a href="https://github.com/macedonga/visor-kit/blob/main/LICENSE"><img src="https://img.shields.io/badge/License-Apache--2.0-2563EB?style=for-the-badge&labelColor=0B1220" alt="License: Apache-2.0"></a>
35
+ </p>
36
+
37
+ <p align="center">
38
+ <a href="#install">Install</a> |
39
+ <a href="#connect">Connect</a> |
40
+ <a href="#use-it">Use it</a> |
41
+ <a href="#layouts-and-briefing-cards">Layouts</a> |
42
+ <a href="#test-without-the-glasses">Testing</a>
43
+ </p>
44
+
45
+ ---
46
+
47
+ Call any method of the VDK, follow its topics and read its feeds: the glasses' status, the camera, the Display,
48
+ the Neural Band, voice and the assistant. All of it is `asyncio`.
49
+
50
+ ## Install
51
+
52
+ ```
53
+ pip install visor-kit # over adb
54
+ pip install "visor-kit[network]" # also the network door and visor fake
55
+ ```
56
+
57
+ From a clone of visor-kit: `pip install "./clients/python[network]"`.
58
+
59
+ ## Connect
60
+
61
+ ```python
62
+ import asyncio
63
+ import visor_kit
64
+
65
+ async def main():
66
+ async with await visor_kit.connect_adb() as visor:
67
+ print(await visor.call("glasses.status"))
68
+ async for gesture in visor.subscribe("band.gestures"):
69
+ print(gesture["finger"], gesture["derived"])
70
+
71
+ asyncio.run(main())
72
+ ```
73
+
74
+ | Connect with | What it needs | Scopes |
75
+ |---|---|---|
76
+ | `connect_adb(serial=None)` | adb, and Developer mode on in Visor | Every scope |
77
+ | `connect_network("ws://127.0.0.1:7333/rpc", token)` | A client the person made in Visor's Advanced settings, under Network access, and the network extra | That client's |
78
+ | `connect_fake()` | `visor fake` running on this computer, and the network extra | The ones the fake grants |
79
+
80
+ ## Use it
81
+
82
+ - `call(method, params)` returns the result.
83
+ - `subscribe(topic, params)` yields events, and subscribes when the iteration starts.
84
+ - `open(topic, params)` subscribes first and returns a `Stream` to iterate and `aclose()`, for events that follow
85
+ something you do.
86
+ - `feed(name, params)` yields a feed's records as `(header, payload)`, the payload as bytes.
87
+ - `supports(name)` says whether this Visor answers a method, topic or feed; `welcome` holds its whole hello.
88
+
89
+ All of them raise `VisorError`, whose `code` and `reason` are the VDK's. Every method and topic works this way, by
90
+ its name, with the scopes the connection holds. The [JSON-RPC docs](https://visor.macedonga.com/developers/docs/json-rpc/)
91
+ list them all, and [`openrpc.json`](https://github.com/macedonga/visor-kit/blob/main/protocol/api/openrpc.json)
92
+ describes them for tools.
93
+
94
+ ## Layouts and Briefing cards
95
+
96
+ `visor_kit.layout` builds layouts and Briefing cards for the Display as plain dicts, with the same pieces as the
97
+ Kotlin builder. Fields take snake_case: `max_lines=1` is `maxLines`.
98
+
99
+ ```python
100
+ from visor_kit.layout import card, header, stat, progress, page, chart, field
101
+
102
+ await visor.call("display.cards.set", card(
103
+ "pasta", "Kitchen timer",
104
+ header("Kitchen timer", icon="clock"),
105
+ stat("4:00", "Pasta"),
106
+ progress(0.6),
107
+ icon="clock",
108
+ pages=[page(field("Started", "19:42")), page(chart([20, 60, 95, 100]))],
109
+ ))
110
+ ```
111
+
112
+ It has `column`, `row`, `text`, `image`, `icon`, `button`, `buttons`, `video`, `chart`, `pager` and `page`, and the
113
+ blocks `header`, `stat`, `change`, `field` and `progress`. `image_file(path)` turns a photo into a `data:` URI for
114
+ `image()`; Visor scales it to the Display.
115
+
116
+ ## Test without the glasses
117
+
118
+ `visor fake` runs a fake Visor on your computer, with a Display simulator in the browser that draws your layouts and
119
+ cards. Connect to it with `connect_fake()`. Install the command with one line:
120
+
121
+ ```
122
+ curl -fsSL https://visor.macedonga.com/install.sh | sh # macOS and Linux
123
+ irm https://visor.macedonga.com/install.ps1 | iex # Windows
124
+ ```
125
+
126
+ ## Docs
127
+
128
+ - [The network door](https://visor.macedonga.com/developers/docs/network/): tokens, scopes and MCP
129
+ - [Testing](https://visor.macedonga.com/developers/docs/testing/): the `visor` command and `visor fake`
130
+ - [AI-assisted development](https://visor.macedonga.com/developers/docs/ai-tools/): a prompt that sets up your agent
131
+ - [All the docs](https://visor.macedonga.com/developers/docs/)
132
+
133
+ ## License
134
+
135
+ Apache 2.0.
@@ -0,0 +1,114 @@
1
+ <p align="center">
2
+ <img src="https://raw.githubusercontent.com/macedonga/visor-kit/main/clients/python/banner.png" alt="VDK for Python: scripts and agents, over adb or the network" width="100%">
3
+ </p>
4
+
5
+ <p align="center">
6
+ <b>The Visor Development Kit in Python.</b><br>
7
+ Meta glasses from your scripts and agents, over adb or the network, through <a href="https://visor.macedonga.com">Visor</a>.
8
+ </p>
9
+
10
+ <p align="center">
11
+ <a href="https://pypi.org/project/visor-kit/"><img src="https://img.shields.io/pypi/v/visor-kit?style=for-the-badge&label=PyPI&color=2563EB&labelColor=0B1220" alt="visor-kit on PyPI"></a>
12
+ <a href="https://visor.macedonga.com/developers/docs/"><img src="https://img.shields.io/badge/Docs-read%20the%20guide-2563EB?style=for-the-badge&labelColor=0B1220" alt="Documentation"></a>
13
+ <a href="https://github.com/macedonga/visor-kit/blob/main/LICENSE"><img src="https://img.shields.io/badge/License-Apache--2.0-2563EB?style=for-the-badge&labelColor=0B1220" alt="License: Apache-2.0"></a>
14
+ </p>
15
+
16
+ <p align="center">
17
+ <a href="#install">Install</a> |
18
+ <a href="#connect">Connect</a> |
19
+ <a href="#use-it">Use it</a> |
20
+ <a href="#layouts-and-briefing-cards">Layouts</a> |
21
+ <a href="#test-without-the-glasses">Testing</a>
22
+ </p>
23
+
24
+ ---
25
+
26
+ Call any method of the VDK, follow its topics and read its feeds: the glasses' status, the camera, the Display,
27
+ the Neural Band, voice and the assistant. All of it is `asyncio`.
28
+
29
+ ## Install
30
+
31
+ ```
32
+ pip install visor-kit # over adb
33
+ pip install "visor-kit[network]" # also the network door and visor fake
34
+ ```
35
+
36
+ From a clone of visor-kit: `pip install "./clients/python[network]"`.
37
+
38
+ ## Connect
39
+
40
+ ```python
41
+ import asyncio
42
+ import visor_kit
43
+
44
+ async def main():
45
+ async with await visor_kit.connect_adb() as visor:
46
+ print(await visor.call("glasses.status"))
47
+ async for gesture in visor.subscribe("band.gestures"):
48
+ print(gesture["finger"], gesture["derived"])
49
+
50
+ asyncio.run(main())
51
+ ```
52
+
53
+ | Connect with | What it needs | Scopes |
54
+ |---|---|---|
55
+ | `connect_adb(serial=None)` | adb, and Developer mode on in Visor | Every scope |
56
+ | `connect_network("ws://127.0.0.1:7333/rpc", token)` | A client the person made in Visor's Advanced settings, under Network access, and the network extra | That client's |
57
+ | `connect_fake()` | `visor fake` running on this computer, and the network extra | The ones the fake grants |
58
+
59
+ ## Use it
60
+
61
+ - `call(method, params)` returns the result.
62
+ - `subscribe(topic, params)` yields events, and subscribes when the iteration starts.
63
+ - `open(topic, params)` subscribes first and returns a `Stream` to iterate and `aclose()`, for events that follow
64
+ something you do.
65
+ - `feed(name, params)` yields a feed's records as `(header, payload)`, the payload as bytes.
66
+ - `supports(name)` says whether this Visor answers a method, topic or feed; `welcome` holds its whole hello.
67
+
68
+ All of them raise `VisorError`, whose `code` and `reason` are the VDK's. Every method and topic works this way, by
69
+ its name, with the scopes the connection holds. The [JSON-RPC docs](https://visor.macedonga.com/developers/docs/json-rpc/)
70
+ list them all, and [`openrpc.json`](https://github.com/macedonga/visor-kit/blob/main/protocol/api/openrpc.json)
71
+ describes them for tools.
72
+
73
+ ## Layouts and Briefing cards
74
+
75
+ `visor_kit.layout` builds layouts and Briefing cards for the Display as plain dicts, with the same pieces as the
76
+ Kotlin builder. Fields take snake_case: `max_lines=1` is `maxLines`.
77
+
78
+ ```python
79
+ from visor_kit.layout import card, header, stat, progress, page, chart, field
80
+
81
+ await visor.call("display.cards.set", card(
82
+ "pasta", "Kitchen timer",
83
+ header("Kitchen timer", icon="clock"),
84
+ stat("4:00", "Pasta"),
85
+ progress(0.6),
86
+ icon="clock",
87
+ pages=[page(field("Started", "19:42")), page(chart([20, 60, 95, 100]))],
88
+ ))
89
+ ```
90
+
91
+ It has `column`, `row`, `text`, `image`, `icon`, `button`, `buttons`, `video`, `chart`, `pager` and `page`, and the
92
+ blocks `header`, `stat`, `change`, `field` and `progress`. `image_file(path)` turns a photo into a `data:` URI for
93
+ `image()`; Visor scales it to the Display.
94
+
95
+ ## Test without the glasses
96
+
97
+ `visor fake` runs a fake Visor on your computer, with a Display simulator in the browser that draws your layouts and
98
+ cards. Connect to it with `connect_fake()`. Install the command with one line:
99
+
100
+ ```
101
+ curl -fsSL https://visor.macedonga.com/install.sh | sh # macOS and Linux
102
+ irm https://visor.macedonga.com/install.ps1 | iex # Windows
103
+ ```
104
+
105
+ ## Docs
106
+
107
+ - [The network door](https://visor.macedonga.com/developers/docs/network/): tokens, scopes and MCP
108
+ - [Testing](https://visor.macedonga.com/developers/docs/testing/): the `visor` command and `visor fake`
109
+ - [AI-assisted development](https://visor.macedonga.com/developers/docs/ai-tools/): a prompt that sets up your agent
110
+ - [All the docs](https://visor.macedonga.com/developers/docs/)
111
+
112
+ ## License
113
+
114
+ Apache 2.0.
Binary file
@@ -0,0 +1,29 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "visor-kit"
7
+ version = "0.1.0"
8
+ description = "The Visor Development Kit from Python: Meta's glasses through Visor, over adb or the network."
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ requires-python = ">=3.9"
12
+ dependencies = []
13
+ keywords = ["meta", "ray-ban", "smart-glasses", "neural-band", "wearables", "visor", "vdk"]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Framework :: AsyncIO",
17
+ "Intended Audience :: Developers",
18
+ "Programming Language :: Python :: 3",
19
+ "Topic :: Software Development :: Libraries",
20
+ ]
21
+
22
+ [project.urls]
23
+ Homepage = "https://visor.macedonga.com/developers/"
24
+ Documentation = "https://visor.macedonga.com/developers/docs/"
25
+ Source = "https://github.com/macedonga/visor-kit"
26
+ Issues = "https://github.com/macedonga/visor-kit/issues"
27
+
28
+ [project.optional-dependencies]
29
+ network = ["websockets>=13"]
@@ -0,0 +1,249 @@
1
+ """The Visor Development Kit from Python: Visor's methods and topics over JSON-RPC.
2
+
3
+ Two ways in:
4
+
5
+ - ``connect_adb()`` reaches Visor's adb socket through ``adb forward``. It needs adb and Developer mode on in Visor,
6
+ and holds every scope.
7
+ - ``connect_network(url, token)`` reaches Visor's network door with a client's token. It needs the ``websockets``
8
+ package, and holds the client's scopes.
9
+ - ``connect_fake()`` reaches the FakeVisor that ``visor fake`` runs on this computer, for building without a phone.
10
+
11
+ import asyncio, visor_kit
12
+
13
+ async def main():
14
+ async with await visor_kit.connect_adb() as visor:
15
+ print(await visor.call("glasses.status"))
16
+ async for gesture in visor.subscribe("band.gestures"):
17
+ print(gesture["finger"], gesture["derived"])
18
+
19
+ asyncio.run(main())
20
+ """
21
+
22
+ import asyncio
23
+ import base64
24
+ import itertools
25
+ import json
26
+ import os
27
+ import shutil
28
+ import subprocess
29
+
30
+ __all__ = ["Stream", "Visor", "VisorError", "connect_adb", "connect_fake", "connect_network"]
31
+
32
+ PROTOCOL = 1
33
+ SOCKET = "visor-kit"
34
+
35
+ # A feed's record is one JSON message, and a keyframe in Base64 runs to megabytes.
36
+ MAX_MESSAGE = 64 << 20
37
+
38
+
39
+ class VisorError(Exception):
40
+ """A failed call or stream. ``code`` is the kit's error code, such as ``scope_denied``."""
41
+
42
+ def __init__(self, failure):
43
+ self.code = failure.get("code", "failed")
44
+ self.reason = failure.get("reason")
45
+ self.scope = failure.get("scope")
46
+ super().__init__(f"{self.code}: {failure.get('message', '')}")
47
+
48
+
49
+ class Stream:
50
+ """The events of one subscription, from ``Visor.open``. Iterate it with ``async for``; it ends when Visor ends
51
+ the stream, and raises ``VisorError`` when it fails. ``aclose()`` it when done."""
52
+
53
+ def __init__(self, visor, id, events):
54
+ self._visor, self._id, self._events = visor, id, events
55
+
56
+ def __aiter__(self):
57
+ return self
58
+
59
+ async def __anext__(self):
60
+ if self._events is None:
61
+ raise StopAsyncIteration
62
+ kind, value = await self._events.get()
63
+ if kind == "event":
64
+ return value
65
+ self._events = None
66
+ if value is None:
67
+ raise StopAsyncIteration
68
+ raise VisorError(value)
69
+
70
+ async def aclose(self):
71
+ """Unsubscribes. After the connection closed, the stream went with it and nothing is sent."""
72
+ self._events = None
73
+ if self._visor._streams.pop(self._id, None) is not None and not self._visor._closed:
74
+ try:
75
+ await self._visor.call("kit.unsubscribe", {"subscription": self._id})
76
+ except VisorError:
77
+ pass # Visor is gone, and the stream with it.
78
+
79
+
80
+ class Visor:
81
+ """One connection to Visor. Use ``connect_adb`` or ``connect_network`` to make one."""
82
+
83
+ def __init__(self, send, receive, close):
84
+ self._send, self._receive, self._close = send, receive, close
85
+ self._ids = itertools.count(1)
86
+ self._calls = {}
87
+ self._streams = {}
88
+ self._closed = False
89
+ self._reader = asyncio.ensure_future(self._read())
90
+ self.welcome = None
91
+
92
+ def supports(self, name):
93
+ """True when this Visor answers the method, topic or feed ``name``, as its hello said: check before using
94
+ something newer than the oldest Visor you support."""
95
+ welcome = self.welcome or {}
96
+ return any(name in welcome.get(key, []) for key in ("methods", "topics", "feeds"))
97
+
98
+ async def call(self, method, params=None):
99
+ """Runs ``method`` with ``params`` and returns its result. Raises ``VisorError``."""
100
+ id = next(self._ids)
101
+ answer = asyncio.get_running_loop().create_future()
102
+ self._calls[id] = answer
103
+ try:
104
+ await self._send(json.dumps({"jsonrpc": "2.0", "id": id, "method": method, "params": params or {}}))
105
+ return await answer
106
+ finally:
107
+ self._calls.pop(id, None)
108
+
109
+ async def subscribe(self, topic, params=None):
110
+ """Yields each event of ``topic`` until the stream ends; a failure raises ``VisorError``. It subscribes when
111
+ iteration starts: use ``open`` to be subscribed before doing something whose events you want."""
112
+ stream = await self.open(topic, params)
113
+ try:
114
+ async for event in stream:
115
+ yield event
116
+ finally:
117
+ await stream.aclose()
118
+
119
+ async def open(self, topic, params=None):
120
+ """Subscribes to ``topic`` and returns a ``Stream`` of its events once Visor has the subscription: nothing
121
+ Visor sends after this returns is missed. Raises ``VisorError`` when Visor refuses it."""
122
+ id = next(self._ids)
123
+ events = asyncio.Queue()
124
+ self._streams[id] = events
125
+ answer = asyncio.get_running_loop().create_future()
126
+ self._calls[id] = answer
127
+ try:
128
+ await self._send(json.dumps({"jsonrpc": "2.0", "id": id, "method": "kit.subscribe",
129
+ "params": {"topic": topic, "params": params or {}}}))
130
+ await answer
131
+ except BaseException:
132
+ self._streams.pop(id, None)
133
+ raise
134
+ finally:
135
+ self._calls.pop(id, None)
136
+ return Stream(self, id, events)
137
+
138
+ async def feed(self, name, params=None):
139
+ """Yields ``(header, payload)`` for each record of the feed ``name``, such as ``camera.live``: the header as a
140
+ dict, the payload as bytes. Ends as ``subscribe`` does."""
141
+ records = self.subscribe(name, params)
142
+ try:
143
+ async for record in records:
144
+ yield record["header"], base64.b64decode(record["payload"])
145
+ finally:
146
+ await records.aclose()
147
+
148
+ async def close(self):
149
+ self._closed = True
150
+ self._reader.cancel()
151
+ await self._close()
152
+
153
+ async def __aenter__(self):
154
+ return self
155
+
156
+ async def __aexit__(self, *_):
157
+ await self.close()
158
+
159
+ async def _read(self):
160
+ failure = {"code": "visor_gone", "message": "The connection to Visor broke."}
161
+ try:
162
+ while (message := await self._receive()) is not None:
163
+ self._dispatch(json.loads(message))
164
+ finally:
165
+ for answer in self._calls.values():
166
+ if not answer.done():
167
+ answer.set_exception(VisorError(failure))
168
+ for events in self._streams.values():
169
+ events.put_nowait(("ended", failure))
170
+
171
+ def _dispatch(self, message):
172
+ if "method" not in message:
173
+ answer = self._calls.get(message.get("id"))
174
+ if answer is None or answer.done():
175
+ return
176
+ if "error" in message:
177
+ error = message["error"]
178
+ answer.set_exception(VisorError(error.get("data") or {"code": "failed", "message": error.get("message")}))
179
+ else:
180
+ answer.set_result(message.get("result"))
181
+ return
182
+ params = message.get("params") or {}
183
+ events = self._streams.get(params.get("subscription"))
184
+ if events is None:
185
+ return
186
+ if message["method"] == "kit.event":
187
+ events.put_nowait(("event", params.get("event")))
188
+ elif message["method"] == "kit.ended":
189
+ self._streams.pop(params.get("subscription"), None)
190
+ events.put_nowait(("ended", params.get("failure")))
191
+
192
+
193
+ async def _hello(visor, name):
194
+ visor.welcome = await visor.call("kit.hello", {"protocol": PROTOCOL, "kit": name})
195
+ return visor
196
+
197
+
198
+ def _adb():
199
+ for variable in ("ANDROID_HOME", "ANDROID_SDK_ROOT"):
200
+ home = os.environ.get(variable)
201
+ if home:
202
+ path = os.path.join(home, "platform-tools", "adb.exe" if os.name == "nt" else "adb")
203
+ if os.path.isfile(path):
204
+ return path
205
+ return shutil.which("adb") or "adb"
206
+
207
+
208
+ async def connect_adb(serial=None):
209
+ """Connects to Visor through adb. ``serial`` picks a device, as ``adb -s`` does."""
210
+ adb = [_adb()] + (["-s", serial] if serial else [])
211
+ port = int(subprocess.run(adb + ["forward", "tcp:0", f"localabstract:{SOCKET}"],
212
+ check=True, capture_output=True, text=True).stdout.strip())
213
+ reader, writer = await asyncio.open_connection("127.0.0.1", port, limit=MAX_MESSAGE)
214
+
215
+ async def send(text):
216
+ writer.write(text.encode() + b"\n")
217
+ await writer.drain()
218
+
219
+ async def receive():
220
+ line = await reader.readline()
221
+ return line.decode() if line else None
222
+
223
+ async def close():
224
+ writer.close()
225
+ subprocess.run(adb + ["forward", "--remove", f"tcp:{port}"], capture_output=True)
226
+
227
+ return await _hello(Visor(send, receive, close), "python-adb")
228
+
229
+
230
+ async def connect_network(url, token):
231
+ """Connects to Visor's network door, such as ``ws://127.0.0.1:7333/rpc``, with a client's ``token``."""
232
+ # The asyncio client, from websockets 13 on: the package's top-level connect is the older one there.
233
+ from websockets.asyncio.client import connect
234
+ from websockets.exceptions import ConnectionClosed
235
+
236
+ socket = await connect(url, additional_headers={"Authorization": f"Bearer {token}"}, max_size=MAX_MESSAGE)
237
+
238
+ async def receive():
239
+ try:
240
+ return await socket.recv()
241
+ except ConnectionClosed:
242
+ return None
243
+
244
+ return await _hello(Visor(socket.send, receive, socket.close), "python-network")
245
+
246
+
247
+ async def connect_fake(port=7333):
248
+ """Connects to the FakeVisor that ``visor fake`` runs on this computer. It holds the scopes the fake grants."""
249
+ return await connect_network(f"ws://127.0.0.1:{port}/rpc", "fake")
@@ -0,0 +1,185 @@
1
+ """Layouts and Briefing cards for the Display, as the Kotlin builder makes them: plain dicts, ready for a call.
2
+
3
+ from visor_kit.layout import card, header, stat, change, field, progress, chart, page, icon
4
+
5
+ await visor.call("display.cards.set", card(
6
+ "pasta", "Kitchen timer",
7
+ header("Kitchen timer", icon="clock"),
8
+ stat("4:00", "Pasta"),
9
+ progress(0.6),
10
+ icon="clock",
11
+ pages=[
12
+ page(header("Started"), field("At", "19:42")),
13
+ page(header("Boiling"), chart([20, 60, 95, 100, 100])),
14
+ ],
15
+ ))
16
+
17
+ Fields take the wire's names or their snake_case form: ``max_lines=1`` is ``maxLines``, ``pin_top=0`` is ``pinTop``.
18
+ The elements, their fields and the colours are in the VDK's docs, page display.md.
19
+ """
20
+
21
+ import base64
22
+ import mimetypes
23
+
24
+ __all__ = [
25
+ "BLUE", "GREEN", "PRIMARY", "RED", "SECONDARY", "TRACK",
26
+ "button", "buttons", "card", "change", "chart", "column", "field", "header", "icon", "image", "image_file",
27
+ "layout", "page", "pager", "progress", "rgb", "row", "stat", "text", "video",
28
+ ]
29
+
30
+ PRIMARY = "primary"
31
+ SECONDARY = "secondary"
32
+ GREEN = "#009914"
33
+ RED = "#E5484D"
34
+ BLUE = "#4DA3FF"
35
+ TRACK = "#2A2D33"
36
+
37
+ # A card and its detail take at most this much as JSON, images included: BriefingCard.MAX_BYTES.
38
+ MAX_CARD_BYTES = 262_144
39
+
40
+
41
+ def rgb(value):
42
+ """A colour from ``0xRRGGBB``, as ``"#RRGGBB"``."""
43
+ return "#%06X" % (value & 0xFFFFFF)
44
+
45
+
46
+ def _camel(name):
47
+ head, *rest = name.split("_")
48
+ return head + "".join(part.title() for part in rest)
49
+
50
+
51
+ def _node(kind, fields, children=None):
52
+ node = {"type": kind}
53
+ node.update({_camel(k): v for k, v in fields.items() if v is not None})
54
+ if children:
55
+ node["children"] = list(children)
56
+ return node
57
+
58
+
59
+ def column(*children, **fields):
60
+ """A box that lays its children out top to bottom: ``gap``, ``padding``, ``align``, ``background`` and the rest."""
61
+ return _node("column", fields, children)
62
+
63
+
64
+ def row(*children, **fields):
65
+ """A box that lays its children out side by side."""
66
+ return _node("row", fields, children)
67
+
68
+
69
+ def text(words, **fields):
70
+ """A text: ``style`` (heading, title, body, meta), ``color``, ``max_lines``, ``align``."""
71
+ return _node("text", dict(fields, text=words))
72
+
73
+
74
+ def image(url, **fields):
75
+ """An image from an ``https://`` URL or a ``data:`` URI; ``height``, ``corners``, ``size``."""
76
+ return _node("image", dict(fields, url=url))
77
+
78
+
79
+ def image_file(path):
80
+ """A ``data:`` URI of an image file, for ``image()``. Visor scales one larger than the Display's 600 px."""
81
+ mime = mimetypes.guess_type(path)[0] or "image/jpeg"
82
+ with open(path, "rb") as f:
83
+ return "data:%s;base64,%s" % (mime, base64.b64encode(f.read()).decode("ascii"))
84
+
85
+
86
+ def icon(name, size=None, **fields):
87
+ """One of the Display's icons by name, such as ``"clock"`` or ``"bks_rainy"``; ``size`` in pixels, ``color``."""
88
+ return _node("icon", dict(fields, icon=name, height=size))
89
+
90
+
91
+ def video(url, **fields):
92
+ """A video, MP4 over ``https://``, at most 400 pixels a side; ``controls=True`` shows play and pause. It fills the
93
+ screen alone: a layout with a video holds nothing else."""
94
+ return _node("video", dict(fields, url=url))
95
+
96
+
97
+ def button(id, label, **fields):
98
+ """A button whose clicks come with ``id``: ``style``, ``icon``, ``primary``, and ``toast``, a word the Display
99
+ shows at once when the wearer clicks it in a card's detail."""
100
+ return _node("button", dict(fields, id=id, text=label))
101
+
102
+
103
+ def buttons(*items, **fields):
104
+ """The Display's own bar of buttons."""
105
+ return _node("button_group", fields, items)
106
+
107
+
108
+ def chart(values, **fields):
109
+ """``values`` as a line (the default) or ``style="bars"``; ``color``, ``height``. Visor draws it on the phone."""
110
+ return _node("chart", dict(fields, values=[float(v) for v in values]))
111
+
112
+
113
+ def page(*children, **fields):
114
+ """One page of a pager: a column."""
115
+ return column(*children, **fields)
116
+
117
+
118
+ def pager(*pages, **fields):
119
+ """Pages the wearer swipes through, with dots under them."""
120
+ return _node("pager", fields, pages)
121
+
122
+
123
+ def header(title, icon=None):
124
+ """A card's first line, as Meta's: an icon beside a bold title."""
125
+ if icon is None:
126
+ return text(title, style="title", max_lines=1)
127
+ return row(
128
+ _node("icon", {"icon": icon, "height": 24}),
129
+ text(title, style="title", max_lines=1, shrink=1.0),
130
+ gap=8, cross_align="center",
131
+ )
132
+
133
+
134
+ def stat(value, caption=None):
135
+ """A figure in large type, with a grey caption under it."""
136
+ figure = text(value, style="heading", max_lines=1)
137
+ if caption is None:
138
+ return figure
139
+ return column(figure, text(caption, style="meta", max_lines=1))
140
+
141
+
142
+ def change(words, rising):
143
+ """A green triangle up and green text, or a red triangle down and red text."""
144
+ tone = GREEN if rising else RED
145
+ glyph = "small_triangle_up" if rising else "small_triangle_down"
146
+ return row(
147
+ _node("icon", {"icon": glyph, "height": 20, "color": tone}),
148
+ text(words, color=tone, max_lines=1, shrink=1.0),
149
+ gap=4, cross_align="center",
150
+ )
151
+
152
+
153
+ def field(label, value):
154
+ """A grey label and its value on one line, the value at the end."""
155
+ return row(
156
+ text(label, color=SECONDARY, max_lines=1, shrink=1.0),
157
+ text(value, align="end", max_lines=1),
158
+ align="space_between", cross_align="center", gap=16,
159
+ )
160
+
161
+
162
+ def progress(fraction, color=BLUE):
163
+ """A bar filled ``fraction`` of the way, from 0 to 1."""
164
+ filled = min(1.0, max(0.0, float(fraction)))
165
+ return row(
166
+ row(grow=filled, background=color),
167
+ row(grow=1.0 - filled),
168
+ height=8, background=TRACK, cross_align="stretch",
169
+ )
170
+
171
+
172
+ def layout(*children, **fields):
173
+ """A layout for ``display.layout.show``: its root column."""
174
+ return {"root": column(*children, **fields)}
175
+
176
+
177
+ def card(id, name, *children, icon="bell", detail=None, pages=None, **fields):
178
+ """A card for ``display.cards.set``. ``detail`` is a list of elements a click opens; ``pages`` a list of
179
+ ``page()``s the wearer swipes through instead."""
180
+ built = {"id": id, "name": name, "icon": icon, "layout": layout(*children, **fields)}
181
+ if pages is not None:
182
+ built["detail"] = layout(pager(*pages))
183
+ elif detail is not None:
184
+ built["detail"] = layout(*detail)
185
+ return built