Compare commits

..
Author SHA1 Message Date
David Lechner bfa0b69e93 npm/jedi: fix exports and copy extra files
The export keys were wrong and the README and CHANGELOG files were
missing the the final package.
2022-09-07 20:19:23 -05:00
David Lechner f664757ef3 npm/jedi: new js package
This adds a new javascript package for distributing the pybricks-jedi
Python package and it's dependencies via the npm ecosystem for use in
Pybricks Code.
2022-09-07 20:10:34 -05:00
David Lechner b747520d1c jedi: add LICENSE file
This adds a LICENSE file to the jedi directory specifically for the
pybricks-jedi Python package. Poetry will automatically pick up this
file and include it in the distributed package.
2022-09-07 19:41:23 -05:00
The Vinh Luong (Lương Thế Vinh) dcddf15d15 flake8: Update VSCode settings and suppress some Flake8 linting warnings.
* update VSCode settings to exclude __pycache__

* suppress some Flake8 linting warnings

* minor fix: SPHINX_BUILD env var may not be set

* decorate _PybricksEnumMeta.__dir__() with @classmethod

* flake8-ignore E501
2022-09-05 18:40:39 -05:00
The Vinh Luong (Lương Thế Vinh) c64458d3b9 parameters: Fix wrong typing in pybricks.parameters.Stop. 2022-09-05 18:38:29 -05:00
David Lechner 2a963b2a0b poetry: update dependencies
This fixes:

    Invalid PEP 440 version: '5.1.0.dev20220527.dev-20220527'
2022-09-05 16:58:56 -05:00
Laurens Valk 6df509b66e pybricks.hubs.EssentialHub: Fix duplicate example.
Also delete reference image with the light consistent with other small hubs.
2022-07-04 15:00:41 +02:00
Laurens Valk ac9585b7a5 ubuiltins: Fix broken classmethod decorator.
Since classmethod is being redefined here, it broke Sphinx.

Fixes https://github.com/pybricks/pybricks-api/issues/86
2022-07-04 14:33:17 +02:00
Laurens Valk 0982d5d65b ubuiltins: Document int. 2022-07-04 14:33:17 +02:00
Laurens Valk 8e7f8c619e ubuiltins: Document float. 2022-07-04 14:33:17 +02:00
Laurens Valk a0b3ba1d74 ubuiltins: Document dict.
This just adds a direct reference to the Python docs.
2022-07-04 14:33:17 +02:00
Laurens Valk 3dc28579ef ubuiltins: Document bool, complex. 2022-07-04 14:33:17 +02:00
Laurens Valk 923f9df3da ubuiltins: Document input, print. 2022-07-04 14:33:17 +02:00
Laurens Valk 1665b77847 ubuiltins: Start converting signatures to new standard.
Also clarify description wherever applicable.
2022-07-04 14:33:17 +02:00
Laurens Valk 96e7e5f3d0 umath: Convert signatures to new standard. 2022-07-04 14:33:17 +02:00
Laurens Valk 1b51d71061 examples: Generate hub examples while building.
This way we don't have to commit the generated scripts.

While we do this, rename ExampleHub to ThisHub so that the common scripts can actually run.
2022-07-04 14:29:33 +02:00
Laurens Valk 9d706d719a .gitignore: Ignore .python-version. 2022-07-04 08:40:28 +02:00
David Lechner 7c62a2833a doc/main/images: add temporary essentialhub images
We don't have proper images yet, so we are adding copies of the Prime
hub images for now to not take up space in git history with temporary
images and to at least have something so the docs will build.
2022-06-29 12:08:33 -05:00
David Lechner 03ee7f74e8 doc/pup/essentialhub: fix bit rot
This fixes bitrot for PR #96. Also fixes a few minor issues where
changes were missed.
2022-06-29 12:08:33 -05:00
Pavel Lobodinský 025147680c pybricks.hubs.EssentialHub: Added missing Hub 2022-06-29 12:08:33 -05:00
David Lechner e467bb57c9 pybricks_jedi/v1.1.0 2022-06-26 00:10:04 -05:00
David Lechner 33d0c9fa49 v3.2.0b1-r3 2022-06-26 00:00:11 -05:00
David Lechner e95386e23e jedi: improve signature information
This fixes numerous issues where jedi provided incomplete or poorly
formatted signatures and docstrings.

Issue: https://github.com/pybricks/pybricks-code/issues/932
2022-06-25 23:54:49 -05:00
David Lechner a758eaa1db github/build: don't run build on tags
This is almost always redundant.
2022-06-24 15:37:59 -05:00
David Lechner 470eebd1c5 github/jedi: fix working directory in publish job
This was building the pybricks package instead of the pybricks_jedi
package because it was using the wrong directory.
2022-06-24 15:29:02 -05:00
David Lechner 37cdd2a83b v3.2.0b1-r2 2022-06-24 15:14:42 -05:00
David Lechner a2d9c33eb5 jedi: add new pybricks_jedi package
This package will be used in Pybricks Code to provide some intellesense
operations.
2022-06-24 14:52:45 -05:00
Laurens Valk 6d0de1effa doc/main: Drop beta tag.
Less variants is better. Now we'll just have to add beta support for SPIKE in the next release.

Fixes https://github.com/pybricks/pybricks-api/issues/102
2022-06-10 11:31:08 +02:00
Laurens Valk 8e7fc53974 doc/main: Disable NXT and EV3 pages again.
Now that all typehints have been added, we can
revert commit 4c583a9d4e again.
2022-06-10 11:20:32 +02:00
Laurens Valk e456c8ef91 pybricks: Drop underscores on imports.
Fixes https://github.com/pybricks/pybricks-api/issues/101
2022-06-10 11:10:20 +02:00
Laurens Valk 6500440031 pybricks: Drop most ellipsis and pass instances.
See [1]: "I still prefer ... over pass. This clarifies to the readers that they are reading a stub. But if there's a docstring we need neither."

[1] https://github.com/srittau/type-stub-pep/issues/88#issuecomment-758843441

Fixes https://github.com/pybricks/pybricks-api/issues/101#issuecomment-1148780369
2022-06-10 10:46:44 +02:00
Laurens Valk 8ec1b18629 pybricks.parameters: Add typing, part 2. 2022-06-10 10:33:33 +02:00
Laurens Valk 26908040eb pybricks.common: Add CommonColorSensor class.
Fixes https://github.com/pybricks/pybricks-api/issues/103
2022-06-10 10:05:13 +02:00
Laurens Valk f67c98105a pybricks.parameters: Add typing, part 1. 2022-06-10 10:05:13 +02:00
Laurens Valk 877391dea7 pybricks.parameters: Add typing. 2022-06-10 10:05:13 +02:00
Laurens Valk fb3446ad0d pybricks.robotics: Add typing. 2022-06-10 10:05:12 +02:00
Laurens Valk 31256d70c1 pybricks.tools: Add typing. 2022-06-10 10:05:12 +02:00
Laurens Valk f87e1b48ac pybricks.messaging: Add typing. 2022-06-10 10:05:12 +02:00
Laurens Valk 6bcf6117c3 pybricks.hubs: Add typing. 2022-06-10 10:05:11 +02:00
Laurens Valk c77682f50d pybricks.iodevices: Add typing. 2022-06-10 10:05:11 +02:00
Laurens Valk 4c583a9d4e doc/main: Enable NXT and EV3 pages.
This will help us review the pages as we add typing to the documentation. Then they will be hidden again.

This commit can be cherry-picked later on if we ever enable NXT and EV3 content again.
2022-06-10 10:05:10 +02:00
Laurens Valk 0688b8dded doc/common/conf.py: Add missing units.
These are used for NXT sensors.
2022-06-10 10:05:10 +02:00
Laurens Valk d1a4327751 pybricks.ev3dev.media: Type file classes. 2022-06-10 10:05:10 +02:00
Laurens Valk 4aec24a051 pybricks.ev3dev.media: Type Font class. 2022-06-10 10:05:09 +02:00
Laurens Valk 7bc995d0b6 pybricks.ev3dev.media: Type Image class. 2022-06-10 10:05:09 +02:00
Laurens Valk 725a07e6e1 pybricks.ev3dev._speaker: Add typing. 2022-06-10 10:05:09 +02:00
David Lechner d43bf94720 v3.2.0b1-r1 2022-06-09 19:31:04 -05:00
David Lechner c6163fcc81 pybricks: add __init__.py
This file was missing which breaks some tools that don't know about
namespace packages. Also `from pybricks import version` is a thing.
2022-06-09 19:25:44 -05:00
David Lechner 34992d5b20 vscode: drop deprecated setting
This setting no longer has any effect.
2022-06-09 19:25:21 -05:00
David Lechner c77aedcd8a @pybricks/ide-docs v2.2.0 2022-06-02 10:44:03 -05:00
David Lechner 7b9209681c @pybricks/ide-docs v2.1.0 2022-06-02 10:40:55 -05:00
Laurens Valk 7de33c0ce5 v3.2.0b1 2022-06-02 17:10:46 +02:00
Laurens Valk dbc5d327e3 doc/common/conf: Display s^2 units correctly.
Now that we no longer use these in hyperlinks, we can use the right
unicode to display this unit correctly.
2022-05-30 17:29:30 +02:00
Laurens Valk 2e39740e4b pybricks.nxtdevices: Add typing. 2022-05-30 17:19:38 +02:00
Laurens Valk 45e0744b3f pybricks.ev3devices: Add typing. 2022-05-30 15:34:07 +02:00
Laurens Valk aab6c0d3e0 pybricks.media.ev3dev: Repair build.
Upon temporarily including these to update typing for pybricks.ev3devices, a lot of build errors were encountered.

Even though we won't be re-including these pages any time soon, we'll want to occasionally make sure that they still build with more recent versions of Sphinx.
2022-05-30 14:29:14 +02:00
Laurens Valk 8a4c4a5400 CONTRIBUTING: Add basic docstring guidelines.
Fixes https://github.com/pybricks/pybricks-api/issues/99
2022-05-30 10:57:31 +02:00
Laurens Valk ecfbc6ca75 CONTRIBUTING: Fix formatting and link to setup.
We don't have a wiki.
2022-05-30 10:21:34 +02:00
Laurens Valk c3b6d44c59 pybricks.geometry: Add typing. 2022-05-30 10:17:47 +02:00
Laurens Valk db71a80f36 pybricks.common.IMU: Add typing. 2022-05-30 10:03:44 +02:00
Laurens Valk a80d5cf91e pybricks.common.Accelerometer: Add typing.
Also remove tapped and shaken, which are not implemented.
2022-05-30 09:46:00 +02:00
Laurens Valk 515d261bad pybricks.common.Charger: Add typing. 2022-05-30 09:29:14 +02:00
Laurens Valk dd54d67720 pybricks.common: Use Number as input type where allowed. 2022-05-28 11:33:08 +02:00
Laurens Valk 453332201e pybricks.common.Battery: Add typing. 2022-05-28 11:23:21 +02:00
Laurens Valk 3548ff47ce pybricks.common.Keypad: Add typing. 2022-05-28 11:20:07 +02:00
Laurens Valk a02b283f3f pybricks.common.LightMatrix: Add typing. 2022-05-28 11:15:17 +02:00
Laurens Valk f197531979 pybricks.common.LightArray: Add typing.
Remove blink and animate, which aren't implemented. These weren't displayed in the docs, so this is not a real change; it just makes typing more correct.
2022-05-28 10:55:40 +02:00
Laurens Valk 2167b9d52d pybricks.common.ColorLight: Add typing.
Also remove pybricks.common.Light which isn't used anywhere.

pupdevices.Light is a standalone light that does not support animations or blinks, so don't inherit from this nonexistent class.

Also remove the ColorLight.reset() method which was never implemented.
2022-05-27 20:00:28 +02:00
Laurens Valk 2be15fdf4d pybricks.common.Speaker: Add typing. 2022-05-27 19:14:22 +02:00
Laurens Valk aaf3ad1b9c pybricks.common.Control: Add typing. 2022-05-27 17:15:24 +02:00
Laurens Valk bd7806d2d4 all: Format with black.
Also activate auto formatting. Bump flake8 and mark black
disagreements in setup.cfg.
2022-05-27 16:22:05 +02:00
Laurens Valk 24f7d7c288 pybricks.common.Motor: Add typing. 2022-05-27 16:01:18 +02:00
Laurens Valk 5e0ba1de07 doc/common/conf: Format units in return type.
This formats return types so they don't look like tuples:

int: deg

If we can figure out how these nodes work, we can create proper links
and maybe use italics for the units or a slightly different font color.
2022-05-27 14:59:32 +02:00
Laurens Valk 2f8ba40034 poetry: Patch Sphinx to use docstring signatures when given.
This is the intended behavior everywhere, but it wasn't working for overloaded functions and methods.

See https://github.com/pybricks/sphinx/commit/f57417c042cbf4a72448518b7599517495cc6fde
2022-05-27 12:21:45 +02:00
Laurens Valk c4a09ab62a pybricks.common.DCMotor: Add typing. 2022-05-09 15:05:09 +02:00
Laurens Valk c0c53db5ee pybricks.common.System: Add typing. 2022-05-09 10:41:39 +02:00
Laurens Valk 5e09a6f1bd .vscode/settings: Add rewrap setting.
Now we can press Alt+Q to hard (re)wrap comments and docstrings.
2022-05-09 10:28:39 +02:00
Laurens Valk 5e9a8c5737 doc/main/signaltypes: Change how units are documented.
Previously, arguments had "types" like ":ref:`speed`", which would be rendered by Sphinx as a hyperlink and displayed as "rotational speed: deg/s".

This worked well enough but it had a few shortcomings:
- It looks bad on autocomplete, which doesn't know how to render RST with cross references.
- No real type information: int, float, ... ?
- Some units are very long, making the docs less concise.
- The unified approach doesn't always work. Some method arguments can be either deg/s or mm/s, depending on the application. This gets even lengthier.
- It's hard to maintain if you don't know what to link to.

In the new approach, the unit is just added to the type as plain text. Instead of giving the physical signal name, we give the real data type, which is more standard. The physical signal name is usually apparent from the docstring anyway, and can be inferred from the unit as well. This also solves all of the above problems.

Since most Pybricks methods allow both int and float for numeric inputs, we document these as a Number type, which is the union of int and float. Since the type is no longer directly tied to the type, we can still document the return type correctly, since this is never a union.

Instead of having complicated hacks in Sphinx to make this work (I have tried many), it turns out we can conveniently suppress broken references and still display the units. The only downside is that units will no longer have hyperlinks to the signal pages, at least for the moment. We should be able to make on_missing_reference a bit smarter to format the units as we see fit if needed.

The approach here is exemplified in the Motor.run_until_stalled method. Subsequent commits will apply it everywhere. Also clarify the behavior for duty_limit=None while we are updating this code anyway.
2022-05-09 10:28:31 +02:00
Laurens Valk f934fdd9bd pybricks.common.IMU: Change example to print G force.
Since we changed the acceleration units to mm/s/s, the output values are
fairly large.

The Matrix repr function prints values up to 999, so this avoids
truncating the output.

It is also a good demo of scalar division for a Matrix / Vector.
2022-04-01 16:32:39 +02:00
Laurens Valk 556728937f pybricks.common.Accelerometer: Use mm/s/s units.
Fixes https://github.com/pybricks/pybricks-api/issues/94

For Move Hub, this is a breaking change since Move Hub IMU support
was already released. For the other hubs, the IMU API has not been
released yet, so we can do this silently.
2022-04-01 15:41:15 +02:00
Laurens Valk 813ea61308 doc/main/conf.py: Show beta features on RTD/latest. 2022-04-01 14:51:38 +02:00
Laurens Valk 2e8e43bcdf rtd-requirements: Upgrade to Sphinx 4.4.0. 2022-04-01 14:31:35 +02:00
Laurens Valk e4ddd1ffce pybricks.geometry.Axis: Drop ANY.
This was previously dropped in a2583944d9
but it was added in again in c666009511.

Since this module was never included in a release (it was hidden),
it is OK to do this.
2022-04-01 14:28:38 +02:00
Laurens Valk 243f2948ef pybricks.hubs.primehub: Show in beta version.
Make it show up in the beta build and hide it in the release build.
2022-04-01 14:28:31 +02:00
Laurens Valk 81a1379781 doc/Makefile: Allow BETA=1 to include beta features.
Prior to every previous release, we we had to delete certain
features that did not make it into the release. This lets us
do that with a tag instead. This way we can keep a clean git
history that is easier to follow.
2022-04-01 13:39:04 +02:00
Laurens Valk 93a9370790 doc/common/extensions: Hide version directives in IDE build.
Version tags can be useful to keep track of new or updated features.

This lets us hide such details in the documentation that ships with the IDE to keep it concise.
2022-04-01 09:38:41 +02:00
Laurens Valk 1989561c90 .github/workflows: Fix typo in build name. 2022-03-22 15:49:23 +01:00
Laurens Valk 4101f9be79 poetry: Update Sphinx and RTD-theme.
We were not using a proper release for sphinx-rtd-theme
in order to work around some bugs. Meanwhile, a proper
release has come out, so let's upgrade to 1.0.0.

Also bump Sphinx to 4.4.

Also update and fix workarounds for cross references.
Fixes https://github.com/pybricks/pybricks-api/issues/98.
2022-03-22 15:38:04 +01:00
Laurens Valk 0a31bc711f pybricks.common.Control: Add deceleration setter.
Fixes https://github.com/pybricks/pybricks-api/issues/97
2022-03-21 11:17:34 +01:00
Pavel Lobodinský d8bd890101 pybricks.common: Charger, IMU and System auto-completion 2022-03-02 10:31:53 -06:00
David Lechner 2ba7edab0c pybricks.ev3/pupdevices: fix Motor code completion
The Microsoft Python extension for VS code doesn't include imports in
type hints, so the Motor type wasn't working properly. We can fix this
by wrapping the import type in a new, empty class definition.

The DCMotor class was also missing from ev3devices and the typing for
the overloaded reset_angle method in pupdevices was missing. These are
fixed as well.
2022-02-21 10:59:00 -06:00
Pavel Lobodinský 616051149b pybricks.common.Speaker: Add volume setter. 2022-01-20 08:56:29 +01:00
Laurens Valk e69c422f83 pybricks.common.Motor: Add absolute value example.
Fixes https://github.com/pybricks/support/issues/611
2022-01-20 08:39:43 +01:00
Laurens Valk 0ceabe8497 pybricks.common.Charger: Document it. 2022-01-14 15:14:28 +01:00
Laurens Valk d3ae4ec9ee pybricks.pupdevices.ColorSensor: Move cleanup example.
The color sensor light is much brighter, so having an example
to turn it off is a bit more useful.

Fixes https://github.com/pybricks/pybricks-api/pull/90
2022-01-07 14:11:03 +01:00
Laurens Valk ffb2f8aa96 pybricks.pupdevices.UltrasonicSensor: Move cleanup example.
Also generalize the example so that it can be used on all hubs.
2022-01-07 13:38:07 +01:00
Pavel Lobodinský 65c81834c9 pybricks.hubs.PrimeHub: Added a cleanup example. 2022-01-07 13:38:07 +01:00
Pavel Lobodinský 97002948d1 pybricks.common: Refactored Speaker API to be hub specific.
The Prime/Inventor Hub Speaker allows only a subset of EV3 Speaker API. Hence, splitting the API up.
2022-01-05 12:10:11 -06:00
Pavel Lobodinský 70aa5ee0e2 pybricks._common: Renamed incorrect argument name, fixed tuple type. 2022-01-03 11:01:33 +01:00
Pavel Lobodinský efc1650e7f pybricks.parameters: Added Icon class, added missing methods and attributes.
Added missing Icon class present in the firmware
2022-01-03 11:01:33 +01:00
Pavel Lobodinský fe60636072 pybricks.geometry: Fixed Matrix incorrect rows type, added missing methods. 2022-01-03 11:01:33 +01:00
Pavel Lobodinský a1342f77c9 pybricks.hubs: Default values for the PrimeHub. 2022-01-03 11:01:33 +01:00
Laurens Valk d806fe9fbe pybricks.common.Control: Fix docstring and type hints for limits().
Fixes https://github.com/pybricks/support/issues/565
2021-12-30 09:12:27 +01:00
David Lechner 1259d5d33a bump version for development 2021-12-16 15:36:52 -06:00
David Lechner 098b8eb9cb v3.1.0 2021-12-16 15:36:14 -06:00
David Lechner c666009511 pybricks.geometry: add Axis.ANY
This exists in the firmware but was missing here.
2021-12-16 15:08:50 -06:00
David Lechner 7f4234fc1e pybricks._common: remove type hint for integral_range()
This was removed in e061617.

Also fix import of Axis while we are touching this file.
2021-12-16 15:07:33 -06:00
David Lechner 482289c384 pybricks.robotics: add type hint for curve()
This method was added in 30803fc.
2021-12-16 15:06:00 -06:00
Laurens Valk 30803fc017 pybricks.robotics.DriveBase: Add curve method.
This generalizes motion to curves (arcs), which is in
between straight lines and in-place turns.
2021-12-01 15:38:27 +01:00
Laurens Valk 749eceefc4 pybricks.robotics.DriveBase: Document then and wait arguments. 2021-12-01 15:35:37 +01:00
Laurens Valk 57f6f0fbef pybricks.pupdevices.DCMotor: Document settings method.
Also update changelog for recent changes.
2021-12-01 14:55:34 +01:00
Laurens Valk e061617c34 pybricks.common.Control: Drop integral_range.
This setting is no longer used. We leave a placeholder setting so we don't break existing programs.

See https://github.com/pybricks/pybricks-micropython/commit/e82dd6a2be4e378ab0b1ee7e3b2643fe654de4a9#diff-e529f43c94cf766ade4b68930f9713a45b62618f4305e4c0c88ba872e9f9cd0e
2021-12-01 14:54:21 +01:00
Laurens Valk eb09ecd7c7 pybricks.common.Control: Drop duty limit.
This is now a per-motor voltage limit.

See https://github.com/pybricks/support/issues/536
2021-12-01 14:41:09 +01:00
Laurens Valk 06a1542613 pybricks.pupdevices.DCMotor: Document settings method.
See https://github.com/pybricks/support/issues/536
2021-12-01 14:40:06 +01:00
Laurens Valk 82a8f2ae89 pybricks.pupdevices.Motor: Add small motor render.
Fixes https://github.com/pybricks/support/issues/441
2021-11-23 08:59:44 +01:00
Laurens Valk 7d0fe9cb85 doc/common/extensions: Fix classlink.
Allow the link to be different from the name.

This lets us fix the link for the Inventor Hub, which was linking to a non-existent page.
2021-11-22 14:49:20 +01:00
Laurens Valk 1af876ac8f pybricks.pupdevices.ColorLightMatrix: Fix render.
- Use isometric projection
- Fix broken plug
- Use correct background color

While we are at it, add colors to show which 9 colors this device supports.
2021-11-22 14:49:20 +01:00
David Lechner 718a28c0da @pybricks/ide-docs v2.0.1 2021-11-19 20:30:11 -06:00
David Lechner a2a375cb5c docs/pupdevices: fix broken link
The link to the color light matrix page was broken due to an invalid
file name.
2021-11-19 20:28:33 -06:00
181 changed files with 7104 additions and 3917 deletions
+14 -2
View File
@@ -3,7 +3,19 @@
name: Build Python package and docs
on: [ push, pull_request ]
on:
push:
tags-ignore:
- "*"
pull_request:
paths:
- doc/**
- src/**
- poetry.lock
- poetry.toml
- pyproject.toml
- setup.cfg
jobs:
build:
@@ -35,7 +47,7 @@ jobs:
run: poetry run doc8
- name: Build html docs for Read the Docs
run: poetry run make -C doc html
- name: Instal IDE docs dependencies
- name: Install IDE docs dependencies
run: |
sudo apt-get update
sudo apt-get install dvisvgm preview-latex-style texlive texlive-fonts-extra texlive-latex-extra
+36
View File
@@ -0,0 +1,36 @@
name: pybricks_jedi
on: [push, pull_request]
jobs:
test:
if: github.ref_type != 'tag'
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v2
- uses: actions/setup-python@v2
with:
python-version: "3.10"
- run: pipx install poetry
- run: poetry install
working-directory: ./jedi
- run: poetry run pytest -vv
working-directory: ./jedi
publish:
if: github.ref_type == 'tag' && startsWith(github.ref_name, 'pybricks_jedi/')
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v2
- uses: actions/setup-python@v2
with:
python-version: "3.10"
- run: pipx install poetry
- run: poetry install
working-directory: ./jedi
- run: poetry build
working-directory: ./jedi
- run: poetry publish
working-directory: ./jedi
env:
POETRY_PYPI_TOKEN_PYPI: ${{ secrets.PYPI_PYBRICKS_JEDI_TOKEN }}
+23
View File
@@ -0,0 +1,23 @@
name: Release @pybricks/jedi
on:
push:
tags:
- '@pybricks/jedi/**'
jobs:
publish_ide_docs:
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v2
# Setup .npmrc file to publish to npm
- uses: actions/setup-node@v3
with:
node-version: '16.x'
registry-url: 'https://registry.npmjs.org'
- run: ./build.py
working-directory: npm/jedi
- run: yarn publish
working-directory: npm/jedi/build
env:
NODE_AUTH_TOKEN: ${{ secrets.NODE_AUTH_TOKEN }}
+3 -1
View File
@@ -26,8 +26,9 @@ build/
build-*/
_build/
# Test failure outputs
# Tests
######################
.pytest_cache/
tests/*.exp
tests/*.out
@@ -57,3 +58,4 @@ genrst/
# Virtual environment
######################
.venv/
.python-version
+24 -3
View File
@@ -1,10 +1,24 @@
{
"python.pythonPath": "${workspaceFolder}/.venv",
"files.exclude": {
"**/__pycache__": true,
},
"python.autoComplete.extraPaths": ["jedi/src"],
"python.formatting.provider": "black",
"python.linting.pycodestyleEnabled": false,
"python.linting.pylintEnabled": false,
"python.linting.flake8Enabled": true,
"python.linting.pycodestyleEnabled": false,
"python.linting.enabled": true,
"[python]": {
"editor.formatOnSave": true,
"editor.defaultFormatter": "ms-python.python"
},
"python.languageServer": "Pylance",
"python.testing.pytestArgs": [
"jedi/tests"
],
"python.testing.unittestEnabled": false,
"python.testing.pytestEnabled": true,
"files.associations": {"*.inc": "restructuredtext"},
"restructuredtext.confPath": "${workspaceFolder}/doc/main",
"spellright.language": [
@@ -34,5 +48,12 @@
"plaintext",
"python",
"restructuredtext",
]
],
"rewrap.wrappingColumn": 78,
"python.analysis.extraPaths": [
"jedi/src"
],
"yaml.schemas": {
"https://json.schemastore.org/github-workflow.json": "file:///home/david/work/pybricks/pybricks-api/.github/workflows/build.yml"
},
}
+1
View File
@@ -78,3 +78,4 @@ thermistor
toctree
TODO
UART
utf-8
+53
View File
@@ -2,6 +2,59 @@
<!-- refer to https://keepachangelog.com/en/1.0.0/ for guidance -->
## Unreleased
### Added
- Code auto-completion for `EssentialHub`.
### Fixed
- Fixed some type hints in `parameters` submodule.
## 3.2.0b1-r3 - 2022-06-26
### Fixed
- Fixed more type hints and improved compatibility with jedi.
## 3.2.0b1-r2 - 2022-06-24
### Changed
- Moved remaining type hints from `.pyi` files to the python stub modules, and
fixed numerous errors in the type hints throughout.
## 3.2.0b1-r1 - 2022-06-09
## Added
- Added `__init__.py` to `pybricks` package.
## 3.2.0b1 - 2022-06-02
### Added
- Code auto-completion for `hub.charger`, `hub.imu` and `hub.system`.
- Moved typing from several `.pyi` files to the actual python modules.
### Fixed
- Fixed code completion for `DCMotor` and `Motor` classes in MS Python VS Code extension.
- Fixed missing `DCMotor` type in `ev3devices`.
- Fixed type hint for `Motor.reset_angle()` in `pupdevices`.
### Changed
- Setter for acceleration can now also be used to set acceleration and
deceleration to different values, using a two-valued tuple.
## 3.1.0 - 2021-12-16
### Added
- Added maximum voltage setter for `DCMotor` and `Motor`.
- Documented `DriveBase.curve()` method.
### Changed
- Removed `duty` setting from `Control.limits` method.
- Removed `integral_range` setting from `Control.pid` method.
### Fixed
- Fixed link to Color Light Matrix page.
- Fixed link to Inventor Hub page.
## 3.1.0rc1 - 2021-11-19
### Added
+82 -5
View File
@@ -32,14 +32,91 @@ will actually be implemented.
- pybricks.tools.wait: Add example of waiting.
- pybricks.pupdevices: Fix all sensor class ports.
- umath.sin: Fix spelling of Hypotenuse.
- If an import path makes no sense, just use the file path without extensions:
- If an import path makes no sense, just use the file path without
extensions:
- .vscode/settings: Fix file associations.
- The subject briefly describes _what_ was changed. Use a short full sentence as in the examples above.
- The subject briefly describes _what_ was changed. Use a short full sentence
as in the examples above.
- The body describes _why_ the change was made, e.g. `The word "sensor" was
spelled incorrectly`.
[commits]: https://github.com/pybricks/pybricks-api/commits/master
**General docstring principles:**
The stubs libraries in this repository have two different purposes:
1. Auto-generating documentation with Sphinx. For this purpose, the
documentation should be concise and clear.
2. Provide autocomplete and intellisense in code editors. For this purpose,
the code needs to be 100% correct. This way, computers can parse your code
correctly and tell you when something is wrong.
Since these objectives don't always align, we address these separately in the
stubs library:
1. The first line(s) of the docstring contain the function or method signature
as it should be displayed in the human-readable documentation.
2. The real function signature can be as complex as it needs to be to make it
correct for intellisense. Overloads can be uses if needed.
In the rare case where the docstring signature is the same as the typed
version, we'll still include it for consistency.
**Docstring details:**
Make sure to look at existing function signatures and docstrings for
inspiration when documenting new functionality. As an example, consider:
```python
def run_until_stalled(
self,
speed: Number,
then: Stop = Stop.COAST,
duty_limit: Optional[Number] = None,
) -> int:
"""
run_until_stalled(speed, then=Stop.COAST, duty_limit=None) -> int: deg
Runs the motor at a constant speed until it stalls.
Arguments:
speed (Number, deg/s): Speed of the motor.
then (Stop): What to do after coming to a standstill.
duty_limit (Number, %): Duty cycle limit during this
command. This is useful to avoid applying the full motor
torque to a geared or lever mechanism. If it is ``None``, the
duty limit won't be changed during this command.
Returns:
Angle at which the motor becomes stalled.
"""
```
The real method signature at the top contains the full detail, including the
type of each argument and return value.
The docstring starts with the signature. Use more than one signature if needed
to represent overloaded methods. The signatures are written in the way they
should be displayed in the docs:
- Argument types are omitted because they are also shown with the argument
description below.
- Default values should be given (``then=Stop.COAST``).
- The return type should be given (``-> int``). When applicable, include
the unit of the return value, so it becomes ``-> int: deg``
Then follows a concise description of what this method, function, or class
does.
Then follows a list of arguments:
- For each argument, include the expected type and unit if applicable, e.g.
``(int)`` or ``(Number, deg/s)``.
- Use ``Number`` when ``int`` and ``float`` are both allowed.
- If the description is long, use the indentation shown above.
- Make it readable. Instead
of ``Union[float, SupportsFloat, complex, SupportsComplex]``,
just say _float or complex_.
Then follows a description of the return value. The type is omitted here since
it is already include in the docstring signature.
**Development environment:**
@@ -49,8 +126,8 @@ Prerequisites:
- [Python 3][python]
- [Poetry][poetry]
Information on installing prerequisites can be found on the [pybricks-micropython
wiki][wiki].
Information on installing prerequisites can be found on the
[pybricks-micropython contributor's guide][contributing].
Initial setup:
@@ -90,4 +167,4 @@ Linting:
[git]: https://git-scm.com/
[python]: https://www.python.org/
[poetry]: https://python-poetry.org/
[wiki]: https://github.com/pybricks-micropython/wiki
[contributing]: https://github.com/pybricks/pybricks-micropython/blob/master/CONTRIBUTING.md
+1 -1
View File
@@ -11,7 +11,7 @@ TAG = main
# Put it first so that "make" without argument is like "make help".
help:
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) -t $(TAG) $(O)
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(TAG) $(O)
.PHONY: help Makefile
+154 -107
View File
@@ -27,21 +27,20 @@ from docutils import nodes
from docutils.parsers.rst.directives import flag
from docutils.parsers.rst import Directive
from sphinx.application import Sphinx
from sphinx.addnodes import pending_xref
from sphinx.environment import BuildEnvironment
from sphinx.util.nodes import make_refnode
import toml
TOP_DIR = os.path.abspath(os.path.join('..', '..'))
sys.path.insert(0, os.path.join(TOP_DIR, 'src'))
sys.path.append(os.path.abspath('../common/extensions'))
from pybricks.hubs import EV3Brick # noqa E402
from pybricks.media.ev3dev import Image # noqa E402
from pybricks._common import Speaker # noqa E402
TOP_DIR = os.path.abspath(os.path.join("..", ".."))
sys.path.insert(0, os.path.join(TOP_DIR, "src"))
sys.path.append(os.path.abspath("../common/extensions"))
# ON_RTD is whether we are on readthedocs.org
# this line of code grabbed from docs.readthedocs.org
ON_RTD = os.environ.get('READTHEDOCS', None) == 'True'
ON_RTD = os.environ.get("READTHEDOCS", None) == "True"
_pyproject = toml.load(os.path.join(TOP_DIR, 'pyproject.toml'))
_pyproject = toml.load(os.path.join(TOP_DIR, "pyproject.toml"))
# -- General configuration ------------------------------------------------
@@ -53,27 +52,29 @@ _pyproject = toml.load(os.path.join(TOP_DIR, 'pyproject.toml'))
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.napoleon',
'sphinx.ext.todo',
'sphinx.ext.mathjax',
'color',
'classlink',
'requirements',
'requirements-static',
"sphinx.ext.autodoc",
"sphinx.ext.napoleon",
"sphinx.ext.todo",
"sphinx.ext.mathjax",
# Custom Pybricks extensions
"color",
"classlink",
"requirements",
"requirements-static",
"versionchanged",
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['../common/_templates']
templates_path = ["../common/_templates"]
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
source_suffix = ".rst"
# The master toctree document.
master_doc = 'index'
master_doc = "index"
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
@@ -82,17 +83,17 @@ master_doc = 'index'
# The full version, including alpha/beta/rc tags.
release = "v" + _pyproject["tool"]["poetry"]["version"]
# The short X.Y version.
version = re.match(r'(v\d+\.\d+)', release)[0]
version = re.match(r"(v\d+\.\d+)", release)[0]
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
language = "en"
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'xcode'
pygments_style = "xcode"
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = True
@@ -100,10 +101,10 @@ todo_include_todos = True
# Figure numbering
numfig = True
numfig_format = {
'figure': 'Figure %s',
'table': 'Table %s',
'code-block': 'Listing %s',
'section': 'Section %s'
"figure": "Figure %s",
"table": "Table %s",
"code-block": "Listing %s",
"section": "Section %s",
}
# Find cross-reference errors
@@ -111,59 +112,49 @@ nitpicky = True
# https://stackoverflow.com/a/30624034/1976323
nitpick_ignore = [
('py:class', 'bool'),
('py:class', 'bytearray'),
('py:class', 'bytes'),
('py:class', 'callable'),
('py:class', 'dict'),
('py:class', 'float'),
('py:class', 'int'),
('py:class', 'iter'),
('py:class', 'list'),
('py:class', 'object'),
('py:class', 'str'),
('py:class', 'tuple'),
('py:exc', 'OSError'),
('py:exc', 'RuntimeError'),
('py:exc', 'TypeError'),
('py:exc', 'ValueError'),
("py:class", "bool"),
("py:class", "bytearray"),
("py:class", "bytes"),
("py:class", "callable"),
("py:class", "dict"),
("py:class", "float"),
("py:class", "int"),
("py:class", "iter"),
("py:class", "list"),
("py:class", "object"),
("py:class", "str"),
("py:class", "tuple"),
("py:exc", "OSError"),
("py:exc", "RuntimeError"),
("py:exc", "TypeError"),
("py:exc", "ValueError"),
]
# not sure why, but this is needed for typing.IO in uselect
nitpick_ignore.append(('py:class', 'IO'))
# Workaround until change below is released.
# https://github.com/sphinx-doc/sphinx/commit/86091934db5ec593b4b0c982b7f08f3231ef995b
nitpick_ignore.extend([
('py:class', '0'),
('py:class', '1'),
('py:class', '2'),
('py:class', '3'),
('py:class', 'big'),
('py:class', 'little'),
])
nitpick_ignore.append(("py:obj", "typing.IO"))
# -- Autodoc options ------------------------------------------------------
autodoc_member_order = 'bysource'
autodoc_member_order = "bysource"
autodoc_default_options = {
'members': True,
'undoc-members': True,
"members": True,
"undoc-members": True,
}
autoclass_content = 'both' # This ensures init arguments are not ignored
autoclass_content = "both" # This ensures init arguments are not ignored
add_module_names = False # Hide module name
# -- Options for HTML output ----------------------------------------------
if ON_RTD:
html_theme = 'default'
html_theme = "default"
else:
import sphinx_rtd_theme
html_theme = 'sphinx_rtd_theme'
html_theme = "sphinx_rtd_theme"
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
html_context = {
'disclaimer': _DISCLAIMER,
"disclaimer": _DISCLAIMER,
}
# The theme to use for HTML and HTML Help pages. See the documentation for
@@ -176,14 +167,14 @@ html_context = {
# documentation.
#
html_theme_options = {
'style_external_links': True,
'logo_only': True,
"style_external_links": True,
"logo_only": True,
}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['../common/_static']
html_static_path = ["../common/_static"]
# Custom sidebar templates, must be a dictionary that maps document names
# to template names.
@@ -191,9 +182,9 @@ html_static_path = ['../common/_static']
# This is required for the alabaster theme
# refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars
html_sidebars = {
'**': [
'relations.html', # needs 'show_related': True theme option to display
'searchbox.html',
"**": [
"relations.html", # needs 'show_related': True theme option to display
"searchbox.html",
]
}
@@ -203,7 +194,7 @@ html_scaled_image_link = False
# -- Options for HTMLHelp output ------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'Pybricksdoc'
htmlhelp_basename = "Pybricksdoc"
# -- Options for LaTeX output ---------------------------------------------
@@ -212,14 +203,12 @@ latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
'preamble': r'''
"preamble": r"""
\usepackage{CJKutf8}
\makeatletter
\fancypagestyle{normal}{
@@ -239,51 +228,46 @@ latex_elements = {
\renewcommand{\footrulewidth}{0.4pt}
}
\makeatother
''' % {
'disclaimer': ' '.join((_DISCLAIMER, '©', copyright)),
"""
% {
"disclaimer": " ".join((_DISCLAIMER, "©", copyright)),
},
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
'extraclassoptions': 'openany,oneside',
'releasename': 'Version',
"extraclassoptions": "openany,oneside",
"releasename": "Version",
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, ''.join([project, '-v', version, '.tex']), _TITLE,
author, 'manual'),
(master_doc, "".join([project, "-v", version, ".tex"]), _TITLE, author, "manual"),
]
# -- Content control -----------------------------------------------------
exclude_patterns = [
'ev3devices.rst',
'hubs/ev3brick.rst',
'iodevices/analogsensor.rst',
'iodevices/dcmotor.rst',
'iodevices/ev3devsensor.rst',
'iodevices/i2cdevice.rst',
'iodevices/lumpdevice.rst',
'iodevices/uartdevice.rst',
'media.rst',
'messaging.rst',
'nxtdevices.rst',
'tools/datalog.rst'
"ev3devices.rst",
"hubs/ev3brick.rst",
"iodevices/analogsensor.rst",
"iodevices/dcmotor.rst",
"iodevices/ev3devsensor.rst",
"iodevices/i2cdevice.rst",
"iodevices/lumpdevice.rst",
"iodevices/uartdevice.rst",
"media.rst",
"messaging.rst",
"nxtdevices.rst",
"tools/datalog.rst",
]
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'pybricks', 'Pybricks Documentation',
[author], 1)
]
man_pages = [(master_doc, "pybricks", "Pybricks Documentation", [author], 1)]
# -- Options for Texinfo output -------------------------------------------
@@ -292,33 +276,96 @@ man_pages = [
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'Pybricks', 'Pybricks Documentation',
author, 'Pybricks', 'One line description of project.',
'Miscellaneous'),
(
master_doc,
"Pybricks",
"Pybricks Documentation",
author,
"Pybricks",
"One line description of project.",
"Miscellaneous",
),
]
# -- .. availability:: directive
class AvailabilityDirective(Directive):
has_content = True
option_spec = {
'movehub': flag,
'cityhub': flag,
'technichub': flag,
'ev3dev-stretch': flag,
"movehub": flag,
"cityhub": flag,
"technichub": flag,
"ev3dev-stretch": flag,
}
def run(self):
if not self.options:
raise self.error('Must specify at least one platform.')
raise self.error("Must specify at least one platform.")
# TODO: make links to platform pages
return [nodes.emphasis(text='Availability: '),
nodes.Text(', '.join(self.options))]
return [
nodes.emphasis(text="Availability: "),
nodes.Text(", ".join(self.options)),
]
def on_missing_reference(
app: Sphinx, env: BuildEnvironment, node: pending_xref, contnode: nodes.Element
) -> nodes.Element:
# The Number type alias is on the Signals and Units page instead of on the
# pybricks.parameters page so normal resolution doesn't work
if node["reftype"] == "class" and node["reftarget"] == "Number":
return make_refnode(
app.builder, node["refdoc"], "signaltypes", "numbers", contnode
)
# References with special characters can't exist, so we have to supress
# warnings when Sphinx tries to cross reference units like deg/s. For
# consistency, we also treat units without special characters this way.
for unit in [
"deg",
"deg/s",
"deg/s²",
"mm",
"mm/s",
"mm/s²",
"%",
"mV",
"mA",
"ms",
"mNm",
"Hz",
"°C",
"J",
"Ω",
"N",
]:
# If they match on raw source, we are dealing with argument types.
if unit == contnode.rawsource:
# Return as-is to suppress missing cross reference warning. We
# could make this more fancy by returning an xref node that links
# to the signals page.
return contnode
# Return types are denoted as "int: deg"
try:
# Try to unpack the node.
ret_type, ret_unit = str(contnode).split(": ")
except ValueError:
# Not a valid format, so skip.
continue
# If it's a match, we could format the node so it looks a bit nicer.
# For now just keep the colon notation as is.
if unit == ret_unit:
return nodes.Text(f"{ret_type}: {ret_unit}")
def setup(app: Sphinx):
app.add_directive('availability', AvailabilityDirective)
app.add_directive("availability", AvailabilityDirective)
app.connect("missing-reference", on_missing_reference)
# -- Python domain hacks ---------------------------------------------------
+16 -12
View File
@@ -5,27 +5,31 @@ from docutils.parsers.rst import Directive
class PybricksClasslinkDirective(Directive):
required_arguments = 1
optional_arguments = 1
def run(self):
# Get link name from sphinx-directive
# Get link and name from sphinx-directive
name = self.arguments[0]
link = name if len(self.arguments) == 1 else self.arguments[1]
html = (
'<a href="{0}.html">'.format(name.lower()) +
'<dl class="py class">' +
'<dt>' +
'<em class="property">class </em>' +
'<code class="sig-name descname">' + name + '</code>' +
'</dt>' +
'<dd></dd>' +
'</dl>' +
'</a>'
'<a href="{0}.html">'.format(link.lower())
+ '<dl class="py class">'
+ "<dt>"
+ '<em class="property">class </em>'
+ '<code class="sig-name descname">'
+ name
+ "</code>"
+ "</dt>"
+ "<dd></dd>"
+ "</dl>"
+ "</a>"
)
# Return the node
node = nodes.raw('', html, format="html")
node = nodes.raw("", html, format="html")
return [node]
def setup(app):
app.add_directive_to_domain('py', 'pybricks-classlink', PybricksClasslinkDirective)
app.add_directive_to_domain("py", "pybricks-classlink", PybricksClasslinkDirective)
+8 -9
View File
@@ -16,28 +16,27 @@ class PybricksColorDirective(Directive):
color = getattr(Color, name)
# Convert HSV to RGB
r, g, b = hsv_to_rgb(color.h/360, color.s/100, color.v/100)
r, g, b = hsv_to_rgb(color.h / 360, color.s / 100, color.v / 100)
# Convert RGB to HEX
rgbhex = '#{0:02x}{1:02x}{2:02x}'.format(
round(r*255),
round(g*255),
round(b*255)
rgbhex = "#{0:02x}{1:02x}{2:02x}".format(
round(r * 255), round(g * 255), round(b * 255)
)
# Render a small block of the given color
css = "background-color: {0}; color: {0}; width: 50px;".format(rgbhex)
if name == "WHITE":
css += "border-style: solid; border-width: 0.5px;" + \
"border-color: #666666;"
css += (
"border-style: solid; border-width: 0.5px;" + "border-color: #666666;"
)
html = '<div id="test" style="{0}">_</div>'.format(css)
# Return the node
node = nodes.raw('', html, format="html")
node = nodes.raw("", html, format="html")
return [node]
def setup(app):
app.add_directive_to_domain('py', 'pybricks-color', PybricksColorDirective)
app.add_directive_to_domain("py", "pybricks-color", PybricksColorDirective)
+27 -25
View File
@@ -10,10 +10,10 @@ FEATURES_SMALL = set()
# Medium feature set.
FEATURES_MEDIUM = FEATURES_SMALL | {
'pybricks-geometry',
'pybricks-iodevices',
'stm32-extra',
'stm32-float',
"pybricks-geometry",
"pybricks-iodevices",
"stm32-extra",
"stm32-float",
}
# Large feature set.
@@ -21,11 +21,12 @@ FEATURES_LARGE = FEATURES_MEDIUM | set()
# Features per hub.
HUB_FEATURES = {
'movehub': {'movehub'} | FEATURES_SMALL,
'cityhub': {'cityhub'} | FEATURES_MEDIUM,
'technichub': {'technichub'} | FEATURES_MEDIUM,
'primehub': {'primehub', 'inventorhub'} | FEATURES_LARGE,
'inventorhub': {'primehub', 'inventorhub'} | FEATURES_LARGE,
"movehub": {"movehub"} | FEATURES_SMALL,
"cityhub": {"cityhub"} | FEATURES_MEDIUM,
"technichub": {"technichub"} | FEATURES_MEDIUM,
"primehub": {"primehub", "inventorhub"} | FEATURES_LARGE,
"inventorhub": {"primehub", "inventorhub"} | FEATURES_LARGE,
"essentialhub": {"essentialhub"} | FEATURES_LARGE,
}
@@ -40,15 +41,15 @@ class PybricksRequirementsStaticDirective(Directive):
# CC BY-SA 4.0 via https://stackoverflow.com/a/63728208
env = self.state.document.settings.env
destdir = path.join(env.app.builder.outdir, '_images')
destdir = path.join(env.app.builder.outdir, "_images")
if not path.exists(destdir):
makedirs(destdir)
for hub in HUB_FEATURES:
for compat in ("true", "false"):
uri = 'compat_{0}_{1}_label.png'.format(hub, compat)
src_uri = path.join(env.app.builder.srcdir, 'images', uri)
build_uri = path.join(env.app.builder.outdir, '_images', uri)
uri = "compat_{0}_{1}_label.png".format(hub, compat)
src_uri = path.join(env.app.builder.srcdir, "images", uri)
build_uri = path.join(env.app.builder.outdir, "_images", uri)
copyfile(src_uri, build_uri)
# Get requirements from sphinx-directive.
@@ -67,13 +68,14 @@ class PybricksRequirementsStaticDirective(Directive):
depth_path = "../" * depth
# Table row with hub images.
compat_row = "".join([
hub_cell.format(
depth_path,
hub,
"true" if requirements <= features else "false")
for hub, features in HUB_FEATURES.items()
])
compat_row = "".join(
[
hub_cell.format(
depth_path, hub, "true" if requirements <= features else "false"
)
for hub, features in HUB_FEATURES.items()
]
)
# Generate full table.
html = """
@@ -86,16 +88,16 @@ class PybricksRequirementsStaticDirective(Directive):
</tbody>
</table>
</div>
""".format(compat_row)
""".format(
compat_row
)
# Return the node.
node = nodes.raw('', html, format="html")
node = nodes.raw("", html, format="html")
return [node]
def setup(app):
app.add_directive_to_domain(
'py',
'pybricks-requirements-static',
PybricksRequirementsStaticDirective
"py", "pybricks-requirements-static", PybricksRequirementsStaticDirective
)
+14 -14
View File
@@ -29,25 +29,25 @@ from sphinx.util.osutil import copyfile
from sphinx.util import logging
CSS_FILE = 'requirements.css'
JS_FILE = 'requirements.js'
CSS_FILE = "requirements.css"
JS_FILE = "requirements.js"
class PybricksRequirementsDirective(Directive):
has_content = True
option_spec = {'header': directives.unchanged}
option_spec = {"header": directives.unchanged}
required_arguments = 0
optional_arguments = 10
def run(self):
node = nodes.container()
node['classes'].append('toggle-content')
node["classes"].append("toggle-content")
par = nodes.container()
par['classes'].append('toggle-header')
par["classes"].append("toggle-header")
content = '.. pybricks-requirements-static:: ' + " ".join(self.arguments)
content = ".. pybricks-requirements-static:: " + " ".join(self.arguments)
self.state.nested_parse(StringList([content]), self.content_offset, node)
@@ -60,20 +60,20 @@ def add_assets(app):
def copy_assets(app, exception):
if app.builder.name not in ['html', 'readthedocs'] or exception:
if app.builder.name not in ["html", "readthedocs"] or exception:
return
logger = logging.getLogger(__name__)
logger.info('Copying requirements stylesheet/javascript... ', nonl=True)
dest = os.path.join(app.builder.outdir, '_static', CSS_FILE)
logger.info("Copying requirements stylesheet/javascript... ", nonl=True)
dest = os.path.join(app.builder.outdir, "_static", CSS_FILE)
source = os.path.join(os.path.abspath(os.path.dirname(__file__)), CSS_FILE)
copyfile(source, dest)
dest = os.path.join(app.builder.outdir, '_static', JS_FILE)
dest = os.path.join(app.builder.outdir, "_static", JS_FILE)
source = os.path.join(os.path.abspath(os.path.dirname(__file__)), JS_FILE)
copyfile(source, dest)
logger.info('done')
logger.info("done")
def setup(app):
app.add_directive('pybricks-requirements', PybricksRequirementsDirective)
app.connect('builder-inited', add_assets)
app.connect('build-finished', copy_assets)
app.add_directive("pybricks-requirements", PybricksRequirementsDirective)
app.connect("builder-inited", add_assets)
app.connect("build-finished", copy_assets)
+31
View File
@@ -0,0 +1,31 @@
"""This directive hides the builtin directives
* versionchanged
* versionadded
* deprecated
when building documentation with the 'ide' tag.
"""
from docutils import nodes
from docutils.parsers.rst import Directive
class PybricksVersionDirective(Directive):
has_content = True
def run(self):
html = ""
node = nodes.raw("", html, format="html")
return [node]
def setup(app):
if "ide" in app.tags.tags:
app.add_directive_to_domain(
"py", "deprecated", PybricksVersionDirective, override=True
)
app.add_directive_to_domain(
"py", "versionadded", PybricksVersionDirective, override=True
)
app.add_directive_to_domain(
"py", "versionchanged", PybricksVersionDirective, override=True
)
+29 -22
View File
@@ -4,47 +4,54 @@
# Pybricks documentation build configuration file
#
import os
import sys
# General information about the project.
project = 'pybricks'
copyright = '2018-2021 The Pybricks Authors'
author = ''
project = "pybricks"
copyright = "2018-2021 The Pybricks Authors"
author = ""
_TITLE = 'Pybricks Modules and Examples'
_DISCLAIMER = 'LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are\
_TITLE = "Pybricks Modules and Examples"
_DISCLAIMER = "LEGO, the LEGO logo, MINDSTORMS and the MINDSTORMS EV3 logo are\
trademarks and/or copyrights of the LEGO Group of companies \
which does not sponsor, authorize or endorse this site.'
which does not sponsor, authorize or endorse this site."
html_favicon = '../common/images/favicon.ico'
html_logo = '../common/images/pybricks-logo-rtd.png'
latex_logo = '../common/images/pybricks-logo-large.png'
html_favicon = "../common/images/favicon.ico"
html_logo = "../common/images/pybricks-logo-rtd.png"
latex_logo = "../common/images/pybricks-logo-large.png"
# Build main docs for RTD by default.
# Since tags cannot be passed via the TAG make variable on read the docs,
# add it manually.
if os.environ.get('READTHEDOCS', None) == 'True':
tags.add('main') # noqa F821
if os.environ.get("READTHEDOCS", None) == "True":
tags.add("main") # noqa F821
# HACK: this allows Number type alias to be imported by Sphinx
os.environ["SPHINX_BUILD"] = "True"
# Addtional configuration of the IDE docs
if 'ide' in tags.tags: # noqa F821
_DISCLAIMER = ''
if "ide" in tags.tags: # noqa F821
_DISCLAIMER = ""
html_show_copyright = False
html_show_sphinx = False
html_css_files = ['css/ide.css']
html_js_files = ['js/ide.js']
html_css_files = ["css/ide.css"]
html_js_files = ["js/ide.js"]
imgmath_image_format = 'svg'
imgmath_image_format = "svg"
imgmath_use_preview = True # requires Sphinx v3
imgmath_latex_preamble = r'''
imgmath_latex_preamble = r"""
\usepackage{newtxsf}
'''
"""
exec(open(os.path.abspath("../common/conf.py")).read())
# Addtional configuration of the IDE docs
if 'ide' in tags.tags: # noqa F821
if "ide" in tags.tags: # noqa F821
extensions.remove('sphinx.ext.mathjax') # noqa F821
extensions.append('sphinx.ext.imgmath') # noqa F821
html_theme_options['prev_next_buttons_location'] = None # noqa F821
extensions.remove("sphinx.ext.mathjax") # noqa F821
extensions.append("sphinx.ext.imgmath") # noqa F821
html_theme_options["prev_next_buttons_location"] = None # noqa F821
# Build hub specific example scripts.
sys.path.append(os.path.abspath("../../examples/pup/hub_common"))
import make_examples # noqa F401, E402
+8 -7
View File
@@ -3,11 +3,12 @@
0 !LICENSE MIT
0 ROTATION CENTER 0 0 0 1 "Custom"
0 ROTATION CONFIG 0 0
1 15 430 -96 190 0 0 1 1 0 0 0 1 0 54675c01.dat
1 15 430 -96 400 0 0 1 1 0 0 0 1 0 54675c01.dat
1 322 430 -72 30 0 0 1 1 0 0 0 1 0 54696c01.dat
1 71 430 -72 -180 0 0 1 1 0 0 0 1 0 54696c01.dat
1 71 190 -144 -180 1 0 0 0 1 0 0 0 1 22169c01.dat
1 71 -20 -216 -140 1 0 0 0 1 0 0 0 1 22172c01.dat
1 15 120 -320 160 1 0 0 0 1 0 0 0 1 26913c01.dat
1 15 450 -76 -20 0 0 1 1 0 0 0 1 0 54675c01.dat
1 15 -30 -76 280 0 0 1 1 0 0 0 1 0 68488c01.dat
1 71 550 -76 200 0 0 1 1 0 0 0 1 0 69730c01.dat
1 15 180 -72 140 0 0 1 1 0 0 0 1 0 54696c01.dat
1 15 260 -72 350 0 0 1 1 0 0 0 1 0 54696p02c01.dat
1 71 430 -84 470 1 0 0 0 1 0 0 0 1 22169c01.dat
1 71 590 -86 360 1 0 0 0 1 0 0 0 1 22172c01.dat
1 15 300 -110 630 1 0 0 0 1 0 0 0 1 26913c01.dat
0
Binary file not shown.

Before

Width:  |  Height:  |  Size: 866 KiB

After

Width:  |  Height:  |  Size: 860 KiB

+41 -17
View File
@@ -11,8 +11,8 @@
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="2000"
height="1118"
viewBox="0 0 529.16666 295.80416"
height="1126"
viewBox="0 0 529.16666 297.92083"
version="1.1"
id="svg8"
inkscape:version="0.92.3 (2405546, 2018-03-11)"
@@ -58,8 +58,8 @@
inkscape:pageopacity="0.0"
inkscape:pageshadow="2"
inkscape:zoom="0.35"
inkscape:cx="619.19211"
inkscape:cy="823.24691"
inkscape:cx="930.75599"
inkscape:cy="703.45816"
inkscape:document-units="mm"
inkscape:current-layer="layer1"
showgrid="false"
@@ -87,18 +87,18 @@
inkscape:label="Layer 1"
inkscape:groupmode="layer"
id="layer1"
transform="translate(0,-1.1958167)">
transform="translate(0,0.92084997)">
<image
sodipodi:absref="pupmotors.png"
xlink:href="pupmotors.png"
width="529.16669"
height="295.80417"
y="-0.92085403"
x="0"
id="image876"
preserveAspectRatio="none"
id="image853"
x="-2.220446e-16"
y="1.1958181" />
height="297.92084"
width="529.16669" />
<g
transform="matrix(1.9732825,0,0,1.9732825,82.068314,-182.19652)"
transform="matrix(1.9732825,0,0,1.9732825,94.897251,-184.86922)"
id="g2717">
<g
transform="matrix(1,-0.27773651,0,1,59.387949,102.27922)"
@@ -123,7 +123,7 @@
</g>
<g
id="g2727"
transform="matrix(1.7059944,0,0,1.7059944,-18.326438,-250.00951)">
transform="matrix(1.7059944,0,0,1.7059944,-93.696445,-190.67567)">
<g
style="fill:#2980b9;fill-opacity:1;stroke:#fffbfb;stroke-width:0.13229167;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="g2721"
@@ -147,7 +147,7 @@
sodipodi:nodetypes="ccccsc" />
</g>
<g
transform="matrix(1.7059944,0,0,1.7059944,40.772154,-187.53273)"
transform="matrix(1.7059944,0,0,1.7059944,105.45138,-208.37975)"
id="g2747">
<g
transform="matrix(1,-0.27773651,0,1,61.231459,102.02783)"
@@ -173,7 +173,7 @@
</g>
<g
id="g2757"
transform="matrix(1.9732825,0,0,1.9732825,-63.81015,-178.54646)">
transform="matrix(1.9732825,0,0,1.9732825,-99.624267,-179.081)">
<g
style="fill:#2980b9;fill-opacity:1;stroke:#fffbfb;stroke-width:0.13229167;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="g2751"
@@ -196,7 +196,7 @@
style="fill:#2980b9;fill-opacity:1;stroke:none;stroke-width:0.26458332px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" />
</g>
<g
transform="matrix(1.9732825,0,0,1.9732825,-192.3424,-182.95247)"
transform="matrix(1.9732825,0,0,1.9732825,-253.27985,-174.39985)"
id="g2767">
<g
transform="matrix(1,-0.27773651,0,1,59.387949,102.27922)"
@@ -221,7 +221,7 @@
</g>
<g
id="g874"
transform="matrix(1.9732825,0,0,1.9732825,-208.72093,-323.71573)">
transform="matrix(1.9732825,0,0,1.9732825,-208.72093,-333.33743)">
<g
style="fill:#2980b9;fill-opacity:1;stroke:#fffbfb;stroke-width:0.13229167;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="g868"
@@ -244,7 +244,7 @@
style="fill:#2980b9;fill-opacity:1;stroke:none;stroke-width:0.26458332px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" />
</g>
<g
transform="matrix(1.9732825,0,0,1.9732825,-134.6376,-374.36454)"
transform="matrix(1.9732825,0,0,1.9732825,-103.63433,-335.34319)"
id="g884">
<g
transform="matrix(1,-0.27773651,0,1,59.387949,102.27922)"
@@ -275,5 +275,29 @@
rx="1.295833"
ry="1.1623898"
transform="matrix(0.89702138,0.44198716,0,1,0,0)" />
<g
id="g899"
transform="matrix(1.9732825,0,0,1.9732825,15.03334,-338.81769)">
<g
style="fill:#2980b9;fill-opacity:1;stroke:#fffbfb;stroke-width:0.13229167;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="g893"
transform="matrix(1,-0.27773651,0,1,59.387949,102.27922)">
<path
id="path891"
style="fill:#2980b9;fill-opacity:1;fill-rule:evenodd;stroke:#fffbfb;stroke-width:0.13229167;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 107.60315,149.3339 -4.4195,12.01847 -4.419489,-12.01847 c 2.609269,1.92005 6.179199,1.90899 8.838989,0 z"
inkscape:connector-curvature="0" />
</g>
<path
inkscape:connector-curvature="0"
id="path895"
d="m 148.90956,215.29575 c -8.02867,2.89572 -14.60635,11.81219 -14.60635,19.93021 l 1.74541,-0.62952 c 0,-7.05178 5.7198,-14.86961 12.86094,-17.44522 7.14113,-2.57561 12.86094,1.11628 12.86094,8.16806 l 1.74541,-0.62952 c 0,-8.11802 -6.57768,-12.28973 -14.60635,-9.39401 z"
style="color:#000000;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:medium;line-height:normal;font-family:sans-serif;font-variant-ligatures:normal;font-variant-position:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-alternates:normal;font-feature-settings:normal;text-indent:0;text-align:start;text-decoration:none;text-decoration-line:none;text-decoration-style:solid;text-decoration-color:#000000;letter-spacing:normal;word-spacing:normal;text-transform:none;writing-mode:lr-tb;direction:ltr;text-orientation:mixed;dominant-baseline:auto;baseline-shift:baseline;text-anchor:start;white-space:normal;shape-padding:0;clip-rule:nonzero;display:inline;overflow:visible;visibility:visible;opacity:1;isolation:auto;mix-blend-mode:normal;color-interpolation:sRGB;color-interpolation-filters:linearRGB;solid-color:#000000;solid-opacity:1;vector-effect:none;fill:#2980b9;fill-opacity:1;fill-rule:nonzero;stroke:#ffffff;stroke-width:0.1;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;color-rendering:auto;image-rendering:auto;shape-rendering:auto;text-rendering:auto;enable-background:accumulate" />
<path
inkscape:connector-curvature="0"
id="path897"
d="m 161.70224,224.65346 1.85836,-0.53454 0.43431,0.40926 -0.98973,1.42822 c 0,0 -2.13398,-0.30486 -2.13398,-0.32574 0,-0.0209 0.83104,-0.9772 0.83104,-0.9772 z"
style="fill:#2980b9;fill-opacity:1;stroke:none;stroke-width:0.26458332px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" />
</g>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 22 KiB

After

Width:  |  Height:  |  Size: 25 KiB

+2 -1
View File
@@ -1,7 +1,8 @@
0 Name: pupmotors
0 Name: pupsensors.ldr
0 Author: Pybricks {laurens@pybricks.com}
0 !LICENSE MIT
0 !LDCAD GROUP_DEF [topLevel=true] [LID=0] [GID=9FDP9pj0O55] [name=Group 1] [center=0 0 0]
1 15 190 -290 750 -1 0 0 0 -1 0 0 0 1 47592c01.dat
1 15 600 -280 180 1 0 0 0 1 0 0 0 1 37316.dat
1 15 60 -272 160 -1 0 0 0 -1 0 0 0 1 37312c01.dat
1 15 -400 -280 240 -1 0 0 0 -1 0 0 0 1 37308c01.dat
@@ -0,0 +1,158 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
version="1.1"
id="svg2"
width="504"
height="322"
viewBox="0 0 504 322"
sodipodi:docname="sensor_colorlightmatrix.svg"
inkscape:version="0.92.3 (2405546, 2018-03-11)">
<metadata
id="metadata8">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title></dc:title>
</cc:Work>
</rdf:RDF>
</metadata>
<defs
id="defs6">
<clipPath
clipPathUnits="userSpaceOnUse"
id="clipPath846">
<path
style="fill:none;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
d="m 384.47481,408.57086 22.58181,23.6974 88.18587,13.9655 -36.98745,-79.56651 -97.14072,-16.49296 z"
id="path848"
inkscape:connector-curvature="0" />
</clipPath>
<clipPath
clipPathUnits="userSpaceOnUse"
id="clipPath874">
<path
style="fill:none;stroke:#000000;stroke-width:0.10000001;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 491.27259,265.371 c 1.71728,2.18035 5.94442,12.92235 5.94442,12.92235 l 40.68619,39.65737 -0.39629,25.87184 -22.19247,7.07325 -62.08608,-14.9528 10.83204,-57.24707 z"
id="path876"
inkscape:connector-curvature="0" />
</clipPath>
</defs>
<sodipodi:namedview
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1"
objecttolerance="10"
gridtolerance="10"
guidetolerance="10"
inkscape:pageopacity="0"
inkscape:pageshadow="2"
inkscape:window-width="1853"
inkscape:window-height="1145"
id="namedview4"
showgrid="false"
inkscape:zoom="0.70710678"
inkscape:cx="-39.716728"
inkscape:cy="-44.222535"
inkscape:window-x="67"
inkscape:window-y="27"
inkscape:window-maximized="1"
inkscape:current-layer="svg2"
inkscape:snap-bbox="true"
inkscape:snap-global="false" />
<image
sodipodi:absref="sensor_colorlightmatrix_main.png"
xlink:href="sensor_colorlightmatrix_main.png"
y="0"
x="0"
id="image10"
preserveAspectRatio="none"
height="322"
width="504" />
<rect
style="fill:#e51a1a;fill-opacity:0.62566845;stroke:none;stroke-width:1.94267738;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;paint-order:normal"
id="rect31"
width="45.163605"
height="44.564522"
x="390.70432"
y="293.66827"
transform="matrix(0.94626691,-0.32338666,0,1,0,0)" />
<rect
transform="matrix(0.94626691,-0.32338666,0,1,0,0)"
y="338.23279"
x="390.70432"
height="43.275879"
width="45.163605"
id="rect838"
style="fill:#e5701a;fill-opacity:0.62566845;stroke:none;stroke-width:1.94267738;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;paint-order:normal" />
<rect
style="fill:#e5bf1a;fill-opacity:0.62566845;stroke:none;stroke-width:1.94267738;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;paint-order:normal"
id="rect840"
width="45.163605"
height="38.992153"
x="390.70432"
y="381.46179"
transform="matrix(0.94626691,-0.32338666,0,1,0,0.05126953)"
clip-path="url(#clipPath846)" />
<rect
transform="matrix(0.94626691,-0.32338666,0,1,0,0)"
y="293.66827"
x="435.86792"
height="44.564514"
width="41.462769"
id="rect856"
style="fill:#00af05;fill-opacity:0.62566847;stroke:none;stroke-width:1.94267738;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;paint-order:normal" />
<rect
style="fill:#0044fb;fill-opacity:0.62566847;stroke:none;stroke-width:1.94267738;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;paint-order:normal"
id="rect858"
width="40.347229"
height="44.564514"
x="477.33069"
y="293.66827"
transform="matrix(0.94626691,-0.32338666,0,1,0,0)"
clip-path="url(#clipPath874)" />
<rect
style="fill:#5dffe2;fill-opacity:1;stroke:none;stroke-width:1.94267738;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;paint-order:normal"
id="rect860"
width="41.462769"
height="43.261936"
x="435.86792"
y="338.24722"
transform="matrix(0.94626691,-0.32338666,0,1,0,0)" />
<rect
transform="matrix(0.94626691,-0.32338666,0,1,0,0)"
y="338.24722"
x="477.33069"
height="43.261951"
width="40.347229"
id="rect862"
style="fill:#941ae5;fill-opacity:0.62566847;stroke:none;stroke-width:1.94267738;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;paint-order:normal" />
<rect
transform="matrix(0.94626691,-0.32338666,0,1,0,0)"
y="381.51306"
x="435.86792"
height="38.88504"
width="41.489174"
id="rect868"
style="fill:#1acee5;fill-opacity:0.62566847;stroke:none;stroke-width:1.94267738;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;paint-order:normal" />
<rect
style="fill:#e51a9a;fill-opacity:0.62566847;stroke:none;stroke-width:1.94267738;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;paint-order:normal"
id="rect870"
width="40.281181"
height="38.928104"
x="477.33069"
y="381.51306"
transform="matrix(0.94626691,-0.32338666,0,1,0,0)" />
</svg>

After

Width:  |  Height:  |  Size: 6.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

+29 -4
View File
@@ -44,17 +44,42 @@ Motors
.. automethod:: pybricks.ev3devices.Motor.run_target
.. automethod:: pybricks.ev3devices.Motor.track_target
.. automethod:: pybricks.ev3devices.Motor.run_until_stalled
.. automethod:: pybricks.ev3devices.Motor.dc
.. rubric:: Advanced motion control
.. rubric:: Motor status
.. automethod:: pybricks.ev3devices.Motor.track_target
.. attribute:: control.scale
.. autoattribute:: pybricks.ev3devices.Motor.control
:annotation:
Number of degrees that the motor turns to complete one degree at the
output of the gear train. This is the gear ratio determined from the
``gears`` argument when initializing the motor.
.. automethod:: pybricks.ev3devices.Motor.control.done
.. automethod:: pybricks.ev3devices.Motor.control.stalled
.. automethod:: pybricks.ev3devices.Motor.control.load
.. rubric:: Motor settings
You can only change these settings while the controller is stopped. For
example, you can change them at the start of your program. Alternatively,
first call :meth:`stop() <pybricks.ev3devices.Motor.stop>`, and then change
the settings.
.. automethod:: pybricks.ev3devices.Motor.settings
.. automethod:: pybricks.ev3devices.Motor.control.limits
.. automethod:: pybricks.ev3devices.Motor.control.pid
.. automethod:: pybricks.ev3devices.Motor.control.target_tolerances
.. automethod:: pybricks.ev3devices.Motor.control.stall_tolerances
Touch Sensor
^^^^^^^^^^^^
+6 -6
View File
@@ -44,25 +44,25 @@ Turning the light on and off
****************************
.. literalinclude::
../../../examples/pup/hub_cityhub/light_off.py
../../../examples/pup/hub_common/build/light_off_cityhub.py
Changing brightness and using custom colors
*******************************************
.. literalinclude::
../../../examples/pup/hub_cityhub/light_hsv.py
../../../examples/pup/hub_common/build/light_hsv_cityhub.py
Making the light blink
**********************
.. literalinclude::
../../../examples/pup/hub_cityhub/light_blink.py
../../../examples/pup/hub_common/build/light_blink_cityhub.py
Creating light animations
*************************
.. literalinclude::
../../../examples/pup/hub_cityhub/light_animate.py
../../../examples/pup/hub_common/build/light_animate_cityhub.py
Button and system examples
----------------------------------
@@ -71,10 +71,10 @@ Using the stop button during your program
*****************************************
.. literalinclude::
../../../examples/pup/hub_cityhub/button_single.py
../../../examples/pup/hub_common/build/button_single_cityhub.py
Turning the hub off
*****************************************
.. literalinclude::
../../../examples/pup/hub_cityhub/system_shutdown.py
../../../examples/pup/hub_common/build/system_shutdown_cityhub.py
+146
View File
@@ -0,0 +1,146 @@
.. pybricks-requirements:: essentialhub
Essential Hub
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. figure:: ../../main/images/essentialhub.png
:height: 15 em
.. note:: Pybricks support for this hub is in beta.
Check the `installation instructions`_ to try it out.
The following functions may change before the final release.
.. _installation instructions: https://pybricks.com/install/
.. autoclass:: pybricks.hubs.EssentialHub
:no-members:
.. rubric:: Using the hub status light
.. automethod:: pybricks.hubs::EssentialHub.light.on
.. automethod:: pybricks.hubs::EssentialHub.light.off
.. automethod:: pybricks.hubs::EssentialHub.light.blink
.. automethod:: pybricks.hubs::EssentialHub.light.animate
.. rubric:: Using the button
.. automethod:: pybricks.hubs::EssentialHub.button.pressed
.. rubric:: Using the IMU
.. automethod:: pybricks.hubs::EssentialHub.imu.up
.. automethod:: pybricks.hubs::EssentialHub.imu.tilt
.. automethod:: pybricks.hubs::EssentialHub.imu.acceleration
.. automethod:: pybricks.hubs::EssentialHub.imu.angular_velocity
.. automethod:: pybricks.hubs::EssentialHub.imu.heading
.. automethod:: pybricks.hubs::EssentialHub.imu.reset_heading
.. rubric:: Using the battery
.. automethod:: pybricks.hubs::EssentialHub.battery.voltage
.. automethod:: pybricks.hubs::EssentialHub.battery.current
.. rubric:: Getting the charger status
.. automethod:: pybricks.hubs::EssentialHub.charger.connected
.. automethod:: pybricks.hubs::EssentialHub.charger.current
.. automethod:: pybricks.hubs::EssentialHub.charger.status
.. rubric:: System control
.. automethod:: pybricks.hubs::EssentialHub.system.set_stop_button
.. automethod:: pybricks.hubs::EssentialHub.system.name
.. automethod:: pybricks.hubs::EssentialHub.system.shutdown
.. automethod:: pybricks.hubs::EssentialHub.system.reset_reason
Status light examples
---------------------
Turning the light on and off
****************************
.. literalinclude::
../../../examples/pup/hub_common/build/light_off_essentialhub.py
Changing brightness and using custom colors
*******************************************
.. literalinclude::
../../../examples/pup/hub_common/build/light_hsv_essentialhub.py
Making the light blink
**********************
.. literalinclude::
../../../examples/pup/hub_common/build/light_blink_essentialhub.py
Creating light animations
*************************
.. literalinclude::
../../../examples/pup/hub_common/build/light_animate_essentialhub.py
IMU examples
---------------
Testing which way is up
********************************
.. literalinclude::
../../../examples/pup/hub_common/build/imu_up_essentialhub.py
Reading the tilt value
********************************
.. literalinclude::
../../../examples/pup/hub_common/build/imu_tilt_essentialhub.py
Using a custom hub orientation
**************************************************
.. literalinclude::
../../../examples/pup/hub_common/build/imu_tilt_blast_essentialhub.py
Reading acceleration and angular velocity vectors
**************************************************
.. literalinclude::
../../../examples/pup/hub_common/build/imu_read_vector_essentialhub.py
Reading acceleration and angular velocity on one axis
*****************************************************
.. literalinclude::
../../../examples/pup/hub_common/build/imu_read_scalar_essentialhub.py
System examples
----------------------------------
Using the stop button during your program
*****************************************
.. literalinclude::
../../../examples/pup/hub_common/build/button_single_essentialhub.py
Turning the hub off
*****************************************
.. literalinclude::
../../../examples/pup/hub_common/build/system_shutdown_essentialhub.py
+4
View File
@@ -38,14 +38,18 @@ MINDSTORMS EV3 Brick
.. automethod:: pybricks.hubs::EV3Brick.screen.clear
.. automethod:: pybricks.hubs::EV3Brick.screen.draw_text
:noindex:
.. automethod:: pybricks.hubs::EV3Brick.screen.print
:noindex:
.. automethod:: pybricks.hubs::EV3Brick.screen.set_font
:noindex:
.. automethod:: pybricks.hubs::EV3Brick.screen.load_image
.. automethod:: pybricks.hubs::EV3Brick.screen.draw_image
:noindex:
.. automethod:: pybricks.hubs::EV3Brick.screen.draw_pixel
+7 -1
View File
@@ -13,6 +13,7 @@
cityhub
technichub
primehub
essentialhub
.. pybricks-classlink:: MoveHub
@@ -38,9 +39,14 @@
:height: 10 em
:target: primehub.html
.. pybricks-classlink:: InventorHub
.. pybricks-classlink:: InventorHub PrimeHub
.. figure:: ../../main/images/inventorhub.png
:height: 10 em
:target: primehub.html
.. pybricks-classlink:: EssentialHub
.. figure:: ../../main/images/essentialhub.png
:height: 10 em
:target: essentialhub.html
+9 -5
View File
@@ -27,6 +27,10 @@ Move Hub
.. automethod:: pybricks.hubs::MoveHub.imu.acceleration
.. versionchanged:: 3.2
Changed acceleration units from m/s² to mm/s².
.. rubric:: Using the battery
.. automethod:: pybricks.hubs::MoveHub.battery.voltage
@@ -52,13 +56,13 @@ Turning the light on and off
******************************
.. literalinclude::
../../../examples/pup/hub_movehub/light_off.py
../../../examples/pup/hub_common/build/light_off_movehub.py
Making the light blink
******************************
.. literalinclude::
../../../examples/pup/hub_movehub/light_blink.py
../../../examples/pup/hub_common/build/light_blink_movehub.py
IMU examples
---------------
@@ -67,7 +71,7 @@ Testing which way is up
********************************
.. literalinclude::
../../../examples/pup/hub_movehub/imu_up.py
../../../examples/pup/hub_common/build/imu_up_movehub.py
Reading acceleration
**************************************************
@@ -82,10 +86,10 @@ Using the stop button during your program
*****************************************
.. literalinclude::
../../../examples/pup/hub_movehub/button_single.py
../../../examples/pup/hub_common/build/button_single_movehub.py
Turning the hub off
*****************************************
.. literalinclude::
../../../examples/pup/hub_movehub/system_shutdown.py
../../../examples/pup/hub_common/build/system_shutdown_movehub.py
+30 -12
View File
@@ -6,6 +6,11 @@ Prime Hub / Inventor Hub
.. figure:: ../../main/images/primeinventorhub.png
:height: 15 em
.. note:: Pybricks support for these hubs is in beta.
Check the `installation instructions`_ to try it out.
The following functions may change before the final release.
.. class:: InventorHub
This class is the same as the ``PrimeHub`` class, shown below. Both classes
@@ -73,6 +78,8 @@ Prime Hub / Inventor Hub
.. rubric:: Using the speaker
.. automethod:: pybricks.hubs::PrimeHub.speaker.volume
.. automethod:: pybricks.hubs::PrimeHub.speaker.beep
.. automethod:: pybricks.hubs::PrimeHub.speaker.play_notes
@@ -83,6 +90,14 @@ Prime Hub / Inventor Hub
.. automethod:: pybricks.hubs::PrimeHub.battery.current
.. rubric:: Getting the charger status
.. automethod:: pybricks.hubs::PrimeHub.charger.connected
.. automethod:: pybricks.hubs::PrimeHub.charger.current
.. automethod:: pybricks.hubs::PrimeHub.charger.status
.. rubric:: System control
.. automethod:: pybricks.hubs::PrimeHub.system.set_stop_button
@@ -94,8 +109,8 @@ Prime Hub / Inventor Hub
.. automethod:: pybricks.hubs::PrimeHub.system.reset_reason
.. note:: The examples below use the ``PrimeHub`` class. The examples work fine
on both hubs because they are the identical. If you prefer, you can
change this to ``InventorHub``.
on both hubs because they are the identical. If you prefer, you can
change this to ``InventorHub``.
Status light examples
---------------------
@@ -104,25 +119,25 @@ Turning the light on and off
****************************
.. literalinclude::
../../../examples/pup/hub_primehub/light_off.py
../../../examples/pup/hub_common/build/light_off_primehub.py
Changing brightness and using custom colors
*******************************************
.. literalinclude::
../../../examples/pup/hub_primehub/light_hsv.py
../../../examples/pup/hub_common/build/light_hsv_primehub.py
Making the light blink
**********************
.. literalinclude::
../../../examples/pup/hub_primehub/light_blink.py
../../../examples/pup/hub_common/build/light_blink_primehub.py
Creating light animations
*************************
.. literalinclude::
../../../examples/pup/hub_primehub/light_animate.py
../../../examples/pup/hub_common/build/light_animate_primehub.py
Matrix display examples
-----------------------
@@ -194,32 +209,32 @@ Testing which way is up
********************************
.. literalinclude::
../../../examples/pup/hub_primehub/imu_up.py
../../../examples/pup/hub_common/build/imu_up_primehub.py
Reading the tilt value
********************************
.. literalinclude::
../../../examples/pup/hub_primehub/imu_tilt.py
../../../examples/pup/hub_common/build/imu_tilt_primehub.py
Using a custom hub orientation
**************************************************
.. literalinclude::
../../../examples/pup/hub_primehub/imu_tilt_blast.py
../../../examples/pup/hub_common/build/imu_tilt_blast_primehub.py
Reading acceleration and angular velocity vectors
**************************************************
.. literalinclude::
../../../examples/pup/hub_primehub/imu_read_vector.py
../../../examples/pup/hub_common/build/imu_read_vector_primehub.py
Reading acceleration and angular velocity on one axis
*****************************************************
.. literalinclude::
../../../examples/pup/hub_primehub/imu_read_scalar.py
../../../examples/pup/hub_common/build/imu_read_scalar_primehub.py
System examples
----------------------------------
@@ -234,4 +249,7 @@ Turning the hub off
*****************************************
.. literalinclude::
../../../examples/pup/hub_primehub/system_shutdown.py
../../../examples/pup/hub_common/build/system_shutdown_primehub.py
.. _installation instructions: https://pybricks.com/install/
+11 -11
View File
@@ -58,25 +58,25 @@ Turning the light on and off
****************************
.. literalinclude::
../../../examples/pup/hub_technichub/light_off.py
../../../examples/pup/hub_common/build/light_off_technichub.py
Changing brightness and using custom colors
*******************************************
.. literalinclude::
../../../examples/pup/hub_technichub/light_hsv.py
../../../examples/pup/hub_common/build/light_hsv_technichub.py
Making the light blink
**********************
.. literalinclude::
../../../examples/pup/hub_technichub/light_blink.py
../../../examples/pup/hub_common/build/light_blink_technichub.py
Creating light animations
*************************
.. literalinclude::
../../../examples/pup/hub_technichub/light_animate.py
../../../examples/pup/hub_common/build/light_animate_technichub.py
IMU examples
---------------
@@ -85,32 +85,32 @@ Testing which way is up
********************************
.. literalinclude::
../../../examples/pup/hub_technichub/imu_up.py
../../../examples/pup/hub_common/build/imu_up_technichub.py
Reading the tilt value
********************************
.. literalinclude::
../../../examples/pup/hub_technichub/imu_tilt.py
../../../examples/pup/hub_common/build/imu_tilt_technichub.py
Using a custom hub orientation
**************************************************
.. literalinclude::
../../../examples/pup/hub_technichub/imu_tilt_blast.py
../../../examples/pup/hub_common/build/imu_tilt_blast_technichub.py
Reading acceleration and angular velocity vectors
**************************************************
.. literalinclude::
../../../examples/pup/hub_technichub/imu_read_vector.py
../../../examples/pup/hub_common/build/imu_read_vector_technichub.py
Reading acceleration and angular velocity on one axis
*****************************************************
.. literalinclude::
../../../examples/pup/hub_technichub/imu_read_scalar.py
../../../examples/pup/hub_common/build/imu_read_scalar_technichub.py
Button and system examples
----------------------------------
@@ -119,10 +119,10 @@ Using the stop button during your program
*****************************************
.. literalinclude::
../../../examples/pup/hub_technichub/button_single.py
../../../examples/pup/hub_common/build/button_single_technichub.py
Turning the hub off
*****************************************
.. literalinclude::
../../../examples/pup/hub_technichub/system_shutdown.py
../../../examples/pup/hub_common/build/system_shutdown_technichub.py
Binary file not shown.

Before

Width:  |  Height:  |  Size: 89 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 142 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1009 KiB

After

Width:  |  Height:  |  Size: 1004 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 67 KiB

+2 -2
View File
@@ -28,8 +28,8 @@ Pybricks Documentation
.. list-table::
* - **Technic Hub, City Hub, BOOST Move Hub**
- **SPIKE Prime Hub / MINDSTORMS Inventor Hub**
* - **Technic, City, and BOOST Move Hubs**
- **SPIKE Essential/Prime, and MINDSTORMS Inventor Hubs**
* - .. figure:: ../main/images/powereduphubs.png
:target: https://pybricks.com/install/technic-boost-city/
+3 -3
View File
@@ -9,12 +9,12 @@ EV3 DC Motor
.. figure:: ../../main/images/rcxmotor.png
:width: 40 %
.. autoclass:: pybricks._common.DCMotor
.. autoclass:: pybricks.iodevices.DCMotor
:noindex:
:no-members:
.. automethod:: pybricks._common.DCMotor.dc
.. automethod:: pybricks.iodevices.DCMotor.dc
:noindex:
.. automethod:: pybricks._common.DCMotor.stop
.. automethod:: pybricks.iodevices.DCMotor.stop
:noindex:
+1 -15
View File
@@ -36,26 +36,12 @@ Basic types
.. pybricks-requirements::
..
_comment: The int class is defined manually because otherwise the classmethod is hidden, see https://github.com/pybricks/pybricks-api/issues/86
.. autoclass:: ubuiltins.int
:no-members:
.. automethod:: ubuiltins.int.to_bytes
.. classmethod:: from_bytes(bytes: Union[bytes, bytearray], byteorder: Literal["little", "big"]) -> int
Returns the integer represented by the given bytes.
:param bytes: The bytes to convert.
:param byteorder: Determines the byte order used to represent the
integer. If byteorder is ``"big"``, the most significant byte is at
the beginning of the byte sequence. If byteorder is ``"little"``,
the most significant byte is at the end of the byte sequence.
:returns: The integer represented by the bytes.
.. automethod:: ubuiltins.int.from_bytes
.. pybricks-requirements::
+6
View File
@@ -45,6 +45,12 @@ NXT Color Sensor
.. automethod:: pybricks.nxtdevices.ColorSensor.rgb
.. rubric:: Advanced color sensing
.. automethod:: pybricks.nxtdevices.ColorSensor.hsv
.. automethod:: pybricks.nxtdevices.ColorSensor.detectable_colors
.. rubric:: Built-in light
This sensor has a built-in light. You can make it red, green, blue, or turn
+5
View File
@@ -41,6 +41,11 @@ Side
.. figure:: ../../main/images/orientation_inventorhub_label.png
:height: 17 em
**Essential Hub**
.. figure:: ../../main/images/orientation_essentialhub_label.png
:height: 17 em
**Move Hub**
.. figure:: ../../main/images/orientation_movehub_label.png
+1 -1
View File
@@ -3,7 +3,7 @@
Color Light Matrix
^^^^^^^^^^^^^^^^^^
.. figure:: ../../main/images/color_light_matrix.png
.. figure:: ../../main/images/sensor_colorlightmatrix_label.png
:width: 35 %
.. autoclass:: pybricks.pupdevices.ColorLightMatrix
+6
View File
@@ -82,3 +82,9 @@ Blinking the built-in lights
.. literalinclude::
../../../examples/pup/sensor_color/lights_blink.py
Turning off the lights when the program ends
**********************************************
.. literalinclude::
../../../examples/pup/sensor_color/cleanup.py
+3
View File
@@ -25,6 +25,9 @@ Motors without rotation sensors
.. automethod:: pybricks.pupdevices.DCMotor.brake
:noindex:
.. automethod:: pybricks.pupdevices.DCMotor.settings
:noindex:
Examples
-------------------
+2 -2
View File
@@ -79,9 +79,9 @@
.. pybricks-classlink:: ColorLightMatrix
.. figure:: ../../main/images/color_light_matrix.png
.. figure:: ../../main/images/sensor_colorlightmatrix_label.png
:width: 35 %
:target: color-light-matrix.html
:target: colorlightmatrix.html
.. pybricks-classlink:: Light
+8
View File
@@ -70,6 +70,8 @@ Motors with rotation sensors
example, you can change them at the start of your program. Alternatively,
first call :meth:`stop() <pybricks.pupdevices.Motor.stop>`, and then change the settings.
.. automethod:: pybricks.pupdevices.Motor.settings
.. automethod:: pybricks.pupdevices.Motor.control.limits
.. automethod:: pybricks.pupdevices.Motor.control.pid
@@ -120,6 +122,12 @@ Resetting the measured angle
.. literalinclude::
../../../examples/pup/motor/motor_reset_angle.py
Getting the absolute angle
*******************************************************
.. literalinclude::
../../../examples/pup/motor/motor_absolute.py
Movement examples
-----------------------
+2
View File
@@ -22,6 +22,8 @@
.. automethod:: pybricks.robotics.DriveBase.turn
.. automethod:: pybricks.robotics.DriveBase.curve
.. automethod:: pybricks.robotics.DriveBase.settings
.. rubric:: Drive forever
+10 -13
View File
@@ -4,6 +4,12 @@ Signals and Units
Many commands allow you to specify arguments in terms of well-known physical
quantities. This page gives an overview of each quantity and its unit.
Numbers
~~~~~~~
.. autodata:: pybricks.parameters.Number
:noindex:
Time
~~~~~~
@@ -56,12 +62,12 @@ use the following table to convert between commonly used units.
.. _acceleration:
rotational acceleration: deg/s/s
rotational acceleration: deg/s²
--------------------------------
Rotational acceleration, or *angular acceleration* describes how fast the
rotational speed changes. This is expressed as the change of the number of
degrees per second, during one second (deg/s/s). This is also commonly written
degrees per second, during one second (deg/s²). This is also commonly written
as :math:`deg/s^2`.
For example, you can adjust the rotational acceleration setting of a ``Motor``
@@ -114,26 +120,17 @@ For example, the speed of a robotic vehicle is expressed in mm/s.
.. _linacceleration:
linear acceleration: mm/s/s
linear acceleration: mm/s²
--------------------------------
Linear acceleration describes how fast the speed changes. This is expressed as
the change of the millimeters per second, during one second (deg/s/s).
the change of the millimeters per second, during one second (mm/s²).
This is also commonly written as :math:`mm/s^2`.
For example, you can adjust the acceleration setting of a
:class:`DriveBase <.robotics.DriveBase>` to change how
smoothly or how quickly it reaches the constant speed set point.
.. _linacceleration_m:
linear acceleration: m/s/s
--------------------------------
As above, but expressed in meters per second squared: :math:`m/s^2`.
This is a more practical unit for large values such as those given by an
accelerometer.
Approximate and relative units
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+5 -5
View File
@@ -9,17 +9,17 @@
from pybricks.messaging import BluetoothMailboxClient, TextMailbox
# This is the name of the remote EV3 or PC we are connecting to.
SERVER = 'ev3dev'
SERVER = "ev3dev"
client = BluetoothMailboxClient()
mbox = TextMailbox('greeting', client)
mbox = TextMailbox("greeting", client)
print('establishing connection...')
print("establishing connection...")
client.connect(SERVER)
print('connected!')
print("connected!")
# In this program, the client sends the first message and then waits for the
# server to reply.
mbox.send('hello!')
mbox.send("hello!")
mbox.wait()
print(mbox.read())
+5 -5
View File
@@ -17,17 +17,17 @@ from pybricks.messaging import BluetoothMailboxClient, TextMailbox
# visible on the EV3. You can skip pairing if you already know the EV3 address.
# This is the address of the server EV3 we are connecting to.
SERVER = 'CC:78:AB:D8:4E:F6'
SERVER = "CC:78:AB:D8:4E:F6"
client = BluetoothMailboxClient()
mbox = TextMailbox('greeting', client)
mbox = TextMailbox("greeting", client)
print('establishing connection...')
print("establishing connection...")
client.connect(SERVER)
print('connected!')
print("connected!")
# In this program, the client sends the first message and then waits for the
# server to reply.
mbox.send('hello!')
mbox.send("hello!")
mbox.wait()
print(mbox.read())
@@ -18,17 +18,17 @@ BDADDR_ANY = ""
def str2ba(string, ba):
"""Convert string to Bluetooth address"""
for i, v in enumerate(string.split(':')):
ba.b[5-i] = int(v, 16)
for i, v in enumerate(string.split(":")):
ba.b[5 - i] = int(v, 16)
def ba2str(ba):
"""Convert Bluetooth address to string"""
string = []
for b in ba.b:
string.append('{:02X}'.format(b))
string.append("{:02X}".format(b))
string.reverse()
return ':'.join(string).upper()
return ":".join(string).upper()
class RFCOMMServer:
@@ -37,6 +37,7 @@ class RFCOMMServer:
This is based on the ``socketserver.SocketServer`` class in the Python
standard library.
"""
request_queue_size = 1
def __init__(self, server_address, RequestHandlerClass):
@@ -88,6 +89,7 @@ class StreamRequestHandler:
This is based on ``socketserver.StreamRequestHandler`` from the Python
standard library.
"""
def __init__(self, request, client_address, server):
self.request = request
self.client_address = client_address
@@ -113,6 +115,7 @@ class ThreadingRFCOMMServer(ThreadingMixIn, RFCOMMServer):
"""Version of :class:`RFCOMMServer` that handles connections in a new
thread.
"""
pass
+33 -19
View File
@@ -5,8 +5,12 @@ from _thread import allocate_lock
from errno import ECONNRESET
from struct import pack, unpack
from .bluetooth import (BDADDR_ANY, ThreadingRFCOMMServer,
ThreadingRFCOMMClient, StreamRequestHandler)
from .bluetooth import (
BDADDR_ANY,
ThreadingRFCOMMServer,
ThreadingRFCOMMClient,
StreamRequestHandler,
)
def resolve(brick):
@@ -99,7 +103,7 @@ class LogicMailbox(Mailbox):
"""
def encode(self, value):
return b'\x01' if value else b'\x00'
return b"\x01" if value else b"\x00"
def decode(self, payload):
return bool(payload[0])
@@ -113,10 +117,10 @@ class NumericMailbox(Mailbox):
"""
def encode(self, value):
return pack('<f', value)
return pack("<f", value)
def decode(self, payload):
return unpack('<f', payload)[0]
return unpack("<f", payload)[0]
class TextMailbox(Mailbox):
@@ -127,10 +131,10 @@ class TextMailbox(Mailbox):
"""
def encode(self, value):
return ('{}\0'.format(value)).encode('utf-8')
return ("{}\0".format(value)).encode("utf-8")
def decode(self, payload):
return payload.decode().strip('\0')
return payload.decode().strip("\0")
# EV3 standard firmware is hard-coded to use channel 1
@@ -155,16 +159,16 @@ class MailboxHandler(StreamRequestHandler):
if ex.args[0] == ECONNRESET:
break
raise
size, = unpack('<H', buf)
(size,) = unpack("<H", buf)
buf = self.rfile.recv(size)
msg_count, cmd_type, cmd, name_size = unpack('<HBBB', buf[0:5])
msg_count, cmd_type, cmd, name_size = unpack("<HBBB", buf[0:5])
if cmd_type != SYSTEM_COMMAND_NO_REPLY:
raise ValueError('Bad message type')
raise ValueError("Bad message type")
if cmd != WRITEMAILBOX:
raise ValueError('Bad command')
mbox = buf[5:5+name_size].decode().strip('\0')
data_size, = unpack('<H', buf[5+name_size:7+name_size])
data = buf[7+name_size:7+name_size+data_size]
raise ValueError("Bad command")
mbox = buf[5 : 5 + name_size].decode().strip("\0")
(data_size,) = unpack("<H", buf[5 + name_size : 7 + name_size])
data = buf[7 + name_size : 7 + name_size + data_size]
with self.server._lock:
self.server._mailboxes[mbox] = data
@@ -216,9 +220,18 @@ class MailboxHandlerMixIn:
mbox_len = len(mbox) + 1
payload_len = len(payload)
send_len = 7 + mbox_len + payload_len
fmt = '<HHBBB{}sH{}s'.format(mbox_len, payload_len)
data = pack(fmt, send_len, 1, SYSTEM_COMMAND_NO_REPLY, WRITEMAILBOX,
mbox_len, mbox.encode('utf-8'), payload_len, payload)
fmt = "<HHBBB{}sH{}s".format(mbox_len, payload_len)
data = pack(
fmt,
send_len,
1,
SYSTEM_COMMAND_NO_REPLY,
WRITEMAILBOX,
mbox_len,
mbox.encode("utf-8"),
payload_len,
payload,
)
with self._lock:
if brick is None:
for client in self._clients.values():
@@ -255,7 +268,8 @@ class BluetoothMailboxServer(MailboxHandlerMixIn, ThreadingRFCOMMServer):
"""
super().__init__()
super(ThreadingRFCOMMServer, self).__init__(
(BDADDR_ANY, EV3_RFCOMM_CHANNEL), MailboxHandler)
(BDADDR_ANY, EV3_RFCOMM_CHANNEL), MailboxHandler
)
def wait_for_connection(self, count=1):
"""Waits for a :class:`BluetoothMailboxClient` on a remote device to
@@ -326,7 +340,7 @@ class BluetoothMailboxClient(MailboxHandlerMixIn):
raise ValueError('no paired devices matching "{}"'.format(brick))
client = MailboxRFCOMMClient(self, addr)
if self._clients.setdefault(addr, client) is not client:
raise ValueError('connection with this address already exists')
raise ValueError("connection with this address already exists")
try:
client.handle_request()
except Exception:
@@ -1,15 +1,9 @@
from uctypes import addressof, sizeof, struct
from usocket import socket, SOCK_STREAM
from _thread import start_new_thread
from pybricks.bluetooth import (
str2ba,
sockaddr_rc,
AF_BLUETOOTH,
BTPROTO_RFCOMM
)
from pybricks.bluetooth import str2ba, sockaddr_rc, AF_BLUETOOTH, BTPROTO_RFCOMM
from pybricks.tools import wait, StopWatch
@@ -25,7 +19,7 @@ def get_bluetooth_rfcomm_socket(address, channel):
return sock
class SpikePrimeStreamReader():
class SpikePrimeStreamReader:
def __init__(self, address):
try:
@@ -56,8 +50,8 @@ class SpikePrimeStreamReader():
break
try:
data = eval(raw)
if data['m'] == 0:
self._values = data['p']
if data["m"] == 0:
self._values = data["p"]
except (SyntaxError, KeyError):
pass
@@ -65,8 +59,8 @@ class SpikePrimeStreamReader():
return self._values
def device(self, port):
if 'A' <= port <= 'F':
return self.values()[ord(port)-ord('A')][1]
if "A" <= port <= "F":
return self.values()[ord(port) - ord("A")][1]
else:
raise ValueError
+1 -1
View File
@@ -9,7 +9,7 @@ ev3 = EV3Brick()
ev3.speaker.beep()
# Create the connection. See README.md to find the address for your SPIKE hub.
spike = SpikePrimeStreamReader('F4:84:4C:AA:C8:A4')
spike = SpikePrimeStreamReader("F4:84:4C:AA:C8:A4")
# Now you can simply read values!
for i in range(100):
+2 -2
View File
@@ -12,7 +12,7 @@ ev3 = EV3Brick()
ev3.speaker.beep()
# Create the connection. See README.md to find the address for your SPIKE hub.
spike = SpikePrimeStreamReader('F4:84:4C:AA:C8:A4')
spike = SpikePrimeStreamReader("F4:84:4C:AA:C8:A4")
# Initialize the motors and drive base
left_motor = Motor(Port.B)
@@ -24,5 +24,5 @@ while True:
yaw, pitch, roll = spike.orientation()
# Set speed and turn rate based on orientation
robot.drive(-pitch*6, roll*2)
robot.drive(-pitch * 6, roll * 2)
wait(20)
+4 -4
View File
@@ -9,15 +9,15 @@
from pybricks.messaging import BluetoothMailboxServer, TextMailbox
server = BluetoothMailboxServer()
mbox = TextMailbox('greeting', server)
mbox = TextMailbox("greeting", server)
# The server must be started before the client!
print('waiting for connection...')
print("waiting for connection...")
server.wait_for_connection()
print('connected!')
print("connected!")
# In this program, the server waits for the client to send the first message
# and then sends a reply.
mbox.wait()
print(mbox.read())
mbox.send('hello to you!')
mbox.send("hello to you!")
+1 -1
View File
@@ -8,7 +8,7 @@ def wait_for_button(ev3):
"""
# Show a picture of the buttons on the screen.
ev3.screen.load_image('buttons.png')
ev3.screen.load_image("buttons.png")
# Tip: add text or icons to the image to help you
# remember what each button will do in your program.
+1 -1
View File
@@ -8,7 +8,7 @@ from pybricks.tools import DataLog, StopWatch, wait
# log_2020_02_13_10_07_44_431260.csv
# * You can optionally specify the titles of your data columns. For example,
# if you want to record the motor angles at a given time, you could do:
data = DataLog('time', 'angle')
data = DataLog("time", "angle")
# Initialize a motor and make it move
wheel = Motor(Port.B)
+4 -4
View File
@@ -3,13 +3,13 @@ from pybricks.parameters import Color
from pybricks.tools import DataLog
# Create a data log file called my_file.txt
data = DataLog('time', 'angle', name='my_file', timestamp=False, extension='txt')
data = DataLog("time", "angle", name="my_file", timestamp=False, extension="txt")
# The log method uses the print() method to add a line of text.
# So, you can do much more than saving numbers. For example:
data.log('Temperature', 25)
data.log('Sunday', 'Monday', 'Tuesday')
data.log({'Kiwi': Color.GREEN}, {'Banana': Color.YELLOW})
data.log("Temperature", 25)
data.log("Sunday", "Monday", "Tuesday")
data.log({"Kiwi": Color.GREEN}, {"Banana": Color.YELLOW})
# You can upload the file to your computer, but you can also print the data:
print(data)
+4 -4
View File
@@ -13,22 +13,22 @@ class MySensor(Ev3devSensor):
super().__init__(port)
# Get the sysfs path.
self.path = '/sys/class/lego-sensor/sensor' + str(self.sensor_index)
self.path = "/sys/class/lego-sensor/sensor" + str(self.sensor_index)
def get_modes(self):
"""Get a list of mode strings so we don't have to look them up."""
# The path of the modes file.
modes_path = self.path + '/modes'
modes_path = self.path + "/modes"
# Open the modes file.
with open(modes_path, 'r') as m:
with open(modes_path, "r") as m:
# Read the contents.
contents = m.read()
# Strip the newline symbol, and split at every space symbol.
return contents.strip().split(' ')
return contents.strip().split(" ")
# Initialize the sensor
+2 -2
View File
@@ -10,10 +10,10 @@ sensor = Ev3devSensor(Port.S3)
while True:
# Read the raw RGB values
r, g, b = sensor.read('RGB-RAW')
r, g, b = sensor.read("RGB-RAW")
# Print results
print('R: {0}\t G: {1}\t B: {2}'.format(r, g, b))
print("R: {0}\t G: {1}\t B: {2}".format(r, g, b))
# Wait
wait(200)
+3 -3
View File
@@ -10,7 +10,7 @@ ev3 = EV3Brick()
device = I2CDevice(Port.S2, 0xD2 >> 1)
# Recommended for reading
result, = device.read(reg=0x0F, length=1)
(result,) = device.read(reg=0x0F, length=1)
# Read 1 byte from no particular register:
device.read(reg=None, length=1)
@@ -23,10 +23,10 @@ device.read(reg=None, length=0)
# can choose to skip the register or data as follows:
# Recommended for writing:
device.write(reg=0x22, data=b'\x08')
device.write(reg=0x22, data=b"\x08")
# Write 1 byte to no particular register:
device.write(reg=None, data=b'\x08')
device.write(reg=None, data=b"\x08")
# Write 0 bytes to a particular register:
device.write(reg=0x08, data=None)
+3 -2
View File
@@ -21,7 +21,7 @@ in_file = open(infile_path, "rb")
# Define the format the event data will be read.
# https://docs.python.org/3/library/struct.html#format-characters
FORMAT = 'llHHi'
FORMAT = "llHHi"
EVENT_SIZE = struct.calcsize(FORMAT)
event = in_file.read(EVENT_SIZE)
@@ -30,10 +30,11 @@ event = in_file.read(EVENT_SIZE)
# numbers (-100 to 100)
def scale(val, src, dst):
result = (float(val - src[0]) / (src[1] - src[0]))
result = float(val - src[0]) / (src[1] - src[0])
result = result * (dst[1] - dst[0]) + dst[0]
return result
# Create a loop to react to events
# This loop reacte to all main PS4 button and stick events. I have left out
# buttons like share and options, but can easily be added in by referring
+1 -1
View File
@@ -7,7 +7,7 @@ from pybricks.tools import wait
class RCXTouchSensor(AnalogSensor):
def pressed(self):
return self.resistance() < 50*1000
return self.resistance() < 50 * 1000
ev3 = EV3Brick()
+41 -13
View File
@@ -15,12 +15,24 @@ ev3 = EV3Brick()
# SPLIT SCREEN ################################################################
# Make a sub-image for the left half of the screen
left = Image(ev3.screen, sub=True, x1=0, y1=0,
x2=ev3.screen.width // 2 - 1, y2=ev3.screen.height - 1)
left = Image(
ev3.screen,
sub=True,
x1=0,
y1=0,
x2=ev3.screen.width // 2 - 1,
y2=ev3.screen.height - 1,
)
# Make a sub-image for the right half of the screen
right = Image(ev3.screen, sub=True, x1=ev3.screen.width // 2, y1=0,
x2=ev3.screen.width - 1, y2=ev3.screen.height - 1)
right = Image(
ev3.screen,
sub=True,
x1=ev3.screen.width // 2,
y1=0,
x2=ev3.screen.width - 1,
y2=ev3.screen.height - 1,
)
# Use a monospaced font so that text is vertically aligned when we print
right.set_font(Font(size=8, monospace=True))
@@ -53,7 +65,7 @@ for t in range(200):
# Print every 10th value on right side
if t % 10 == 0:
right.print('{:10.2f}{:10.2f}'.format(x1, y1))
right.print("{:10.2f}{:10.2f}".format(x1, y1))
wait(100)
@@ -64,8 +76,8 @@ for t in range(200):
buf = Image(ev3.screen)
# Load images from file
bg = Image('background.png')
sprite = Image('sprite.png')
bg = Image("background.png")
sprite = Image("sprite.png")
# Number of cells in each sprite animation
NUM_CELLS = 8
@@ -75,12 +87,28 @@ CELL_WIDTH, CELL_HEIGHT = 75, 100
# Get sub-images for each individual cell
# This is more efficient that loading individual images
walk_right = [Image(sprite, sub=True, x1=x * CELL_WIDTH, y1=0,
x2=(x + 1) * CELL_WIDTH - 1, y2=CELL_HEIGHT - 1)
for x in range(NUM_CELLS)]
walk_left = [Image(sprite, sub=True, x1=x * CELL_WIDTH, y1=CELL_HEIGHT,
x2=(x + 1) * CELL_WIDTH - 1, y2=2 * CELL_HEIGHT - 1)
for x in range(NUM_CELLS)]
walk_right = [
Image(
sprite,
sub=True,
x1=x * CELL_WIDTH,
y1=0,
x2=(x + 1) * CELL_WIDTH - 1,
y2=CELL_HEIGHT - 1,
)
for x in range(NUM_CELLS)
]
walk_left = [
Image(
sprite,
sub=True,
x1=x * CELL_WIDTH,
y1=CELL_HEIGHT,
x2=(x + 1) * CELL_WIDTH - 1,
y2=2 * CELL_HEIGHT - 1,
)
for x in range(NUM_CELLS)
]
# Walk from left to right
+5 -5
View File
@@ -8,7 +8,7 @@ from pybricks.media.ev3dev import Font
# load them once at the beginning of the program like this:
tiny_font = Font(size=6)
big_font = Font(size=24, bold=True)
chinese_font = Font(size=24, lang='zh-cn')
chinese_font = Font(size=24, lang="zh-cn")
# Initialize the EV3
@@ -16,19 +16,19 @@ ev3 = EV3Brick()
# Say hello
ev3.screen.print('Hello!')
ev3.screen.print("Hello!")
# Say tiny hello
ev3.screen.set_font(tiny_font)
ev3.screen.print('hello')
ev3.screen.print("hello")
# Say big hello
ev3.screen.set_font(big_font)
ev3.screen.print('HELLO')
ev3.screen.print("HELLO")
# Say Chinese hello
ev3.screen.set_font(chinese_font)
ev3.screen.print('你好')
ev3.screen.print("你好")
# Wait some time to look at the screen
wait(5000)
+20 -6
View File
@@ -26,9 +26,23 @@ wait(1000)
# PLAY NOTES ##################################################################
# Twinkle, Twinkle Little Star
A = ['C4/4', 'C4/4', 'G4/4', 'G4/4', 'A4/4', 'A4/4', 'G4/2',
'F4/4', 'F4/4', 'E4/4', 'E4/4', 'D4/4', 'D4/4', 'C4/2']
B = ['G4/4', 'G4/4', 'F4/4', 'F4/4', 'E4/4', 'E4/4', 'D4/2'] * 2
A = [
"C4/4",
"C4/4",
"G4/4",
"G4/4",
"A4/4",
"A4/4",
"G4/2",
"F4/4",
"F4/4",
"E4/4",
"E4/4",
"D4/4",
"D4/4",
"C4/2",
]
B = ["G4/4", "G4/4", "F4/4", "F4/4", "E4/4", "E4/4", "D4/2"] * 2
TWINKLE = A + B + A
ev3.speaker.play_notes(TWINKLE)
@@ -46,10 +60,10 @@ wait(1000)
# TEXT TO SPEECH ##############################################################
# Say something in English
ev3.speaker.say('I am am E V 3. Pleased to meet you.')
ev3.speaker.say("I am am E V 3. Pleased to meet you.")
# Say something in Danish + female
ev3.speaker.set_speech_options(voice='da+f5')
ev3.speaker.say('Leg godt!')
ev3.speaker.set_speech_options(voice="da+f5")
ev3.speaker.say("Leg godt!")
wait(1000)
+1 -1
View File
@@ -11,7 +11,7 @@ ev3 = EV3Brick()
ser = UARTDevice(Port.S2, baudrate=115200)
# Write some data
ser.write(b'\r\nHello, world!\r\n')
ser.write(b"\r\nHello, world!\r\n")
# Play a sound while we wait for some data
for i in range(3):
@@ -10,8 +10,8 @@ def convert_raw_to_temperature(voltage):
# Convert the raw voltage to the NTC resistance
# according to the Vernier Adapter EV3 block.
counts = voltage/5000*4096
ntc = 15000*(counts)/(4130-counts)
counts = voltage / 5000 * 4096
ntc = 15000 * (counts) / (4130 - counts)
# Handle log(0) safely: make sure that ntc value is positive.
if ntc <= 0:
@@ -21,7 +21,7 @@ def convert_raw_to_temperature(voltage):
K0 = 1.02119e-3
K1 = 2.22468e-4
K2 = 1.33342e-7
return 1/(K0 + K1*log(ntc) + K2*log(ntc)**3)
return 1 / (K0 + K1 * log(ntc) + K2 * log(ntc) ** 3)
# Initialize the adapter on port 1
-25
View File
@@ -1,25 +0,0 @@
from pybricks.hubs import CityHub
from pybricks.parameters import Color, Button
from pybricks.tools import wait, StopWatch
# Initialize the hub.
hub = CityHub()
# Disable the stop button.
hub.system.set_stop_button(None)
# Check the button for 5 seconds.
watch = StopWatch()
while watch.time() < 5000:
# Set light to green if pressed, else red.
if hub.button.pressed():
hub.light.on(Color.GREEN)
else:
hub.light.on(Color.RED)
# Enable the stop button again.
hub.system.set_stop_button(Button.CENTER)
# Now you can press the stop button as usual.
wait(5000)
-23
View File
@@ -1,23 +0,0 @@
from pybricks.hubs import CityHub
from pybricks.parameters import Color
from pybricks.tools import wait
from umath import sin, pi
# Initialize the hub.
hub = CityHub()
# Make an animation with multiple colors.
hub.light.animate([Color.RED, Color.GREEN, Color.NONE], interval=500)
wait(10000)
# Make the color RED grow faint and bright using a sine pattern.
hub.light.animate(
[Color.RED * (0.5 * sin(i / 15 * pi) + 0.5) for i in range(30)], 40)
wait(10000)
# Cycle through a rainbow of colors.
hub.light.animate([Color(h=i*8) for i in range(45)], interval=40)
wait(10000)
-16
View File
@@ -1,16 +0,0 @@
from pybricks.hubs import CityHub
from pybricks.parameters import Color
from pybricks.tools import wait
# Initialize the hub
hub = CityHub()
# Keep blinking red on and off.
hub.light.blink(Color.RED, [500, 500])
wait(10000)
# Keep blinking green slowly and then quickly.
hub.light.blink(Color.GREEN, [500, 500, 50, 900])
wait(10000)
-15
View File
@@ -1,15 +0,0 @@
from pybricks.hubs import CityHub
from pybricks.parameters import Color
from pybricks.tools import wait
# Initialize the hub.
hub = CityHub()
# Turn the light on and off 5 times.
for i in range(5):
hub.light.on(Color.RED)
wait(1000)
hub.light.off()
wait(500)
@@ -1,12 +0,0 @@
from pybricks.hubs import CityHub
from pybricks.tools import wait
# Initialize the hub.
hub = CityHub()
# Say goodbye and give some time to send it.
print("Goodbye!")
wait(100)
# Shut the hub down.
hub.system.shutdown()
@@ -1,10 +1,10 @@
# ExampleHub = MoveHub CityHub TechnicHub
from pybricks.hubs import ExampleHub
# ThisHub = MoveHub CityHub TechnicHub EssentialHub
from pybricks.hubs import ThisHub
from pybricks.parameters import Color, Button
from pybricks.tools import wait, StopWatch
# Initialize the hub.
hub = ExampleHub()
hub = ThisHub()
# Disable the stop button.
hub.system.set_stop_button(None)
@@ -1,10 +1,10 @@
# ExampleHub = TechnicHub PrimeHub
from pybricks.hubs import ExampleHub
# ThisHub = TechnicHub PrimeHub EssentialHub
from pybricks.hubs import ThisHub
from pybricks.tools import wait
from pybricks.geometry import Axis
# Initialize the hub.
hub = ExampleHub()
hub = ThisHub()
# Get the acceleration or angular_velocity along a single axis.
# If you need only one value, this is more memory efficient.
@@ -1,11 +1,12 @@
from pybricks.hubs import PrimeHub
# ThisHub = TechnicHub PrimeHub EssentialHub
from pybricks.hubs import ThisHub
from pybricks.tools import wait
# Initialize the hub.
hub = PrimeHub()
hub = ThisHub()
# Get the acceleration vector.
print(hub.imu.acceleration())
# Get the acceleration vector in g's.
print(hub.imu.acceleration() / 9810)
# Get the angular velocity vector.
print(hub.imu.angular_velocity())
@@ -1,8 +1,9 @@
from pybricks.hubs import PrimeHub
# ThisHub = TechnicHub PrimeHub EssentialHub
from pybricks.hubs import ThisHub
from pybricks.tools import wait
# Initialize the hub.
hub = PrimeHub()
hub = ThisHub()
while True:
# Read the tilt values.
@@ -1,11 +1,12 @@
from pybricks.hubs import PrimeHub
# ThisHub = TechnicHub PrimeHub EssentialHub
from pybricks.hubs import ThisHub
from pybricks.tools import wait
from pybricks.geometry import Axis
# Initialize the hub. In this case, specify that the hub is mounted with the
# top side facing forward and the front side facing to the right.
# For example, this is how the hub is mounted in BLAST in the 51515 set.
hub = PrimeHub(top_side=Axis.X, front_side=-Axis.Y)
hub = ThisHub(top_side=Axis.X, front_side=-Axis.Y)
while True:
# Read the tilt values. Now, the values are 0 when BLAST stands upright.
@@ -1,9 +1,10 @@
from pybricks.hubs import PrimeHub
# ThisHub = TechnicHub PrimeHub MoveHub EssentialHub
from pybricks.hubs import ThisHub
from pybricks.parameters import Color, Side
from pybricks.tools import wait
# Initialize the hub.
hub = PrimeHub()
hub = ThisHub()
# Define colors for each side in a dictionary.
SIDE_COLORS = {
@@ -1,10 +1,11 @@
from pybricks.hubs import PrimeHub
# ThisHub = CityHub TechnicHub PrimeHub EssentialHub
from pybricks.hubs import ThisHub
from pybricks.parameters import Color
from pybricks.tools import wait
from umath import sin, pi
# Initialize the hub.
hub = PrimeHub()
hub = ThisHub()
# Make an animation with multiple colors.
hub.light.animate([Color.RED, Color.GREEN, Color.NONE], interval=500)
@@ -12,12 +13,11 @@ hub.light.animate([Color.RED, Color.GREEN, Color.NONE], interval=500)
wait(10000)
# Make the color RED grow faint and bright using a sine pattern.
hub.light.animate(
[Color.RED * (0.5 * sin(i / 15 * pi) + 0.5) for i in range(30)], 40)
hub.light.animate([Color.RED * (0.5 * sin(i / 15 * pi) + 0.5) for i in range(30)], 40)
wait(10000)
# Cycle through a rainbow of colors.
hub.light.animate([Color(h=i*8) for i in range(45)], interval=40)
hub.light.animate([Color(h=i * 8) for i in range(45)], interval=40)
wait(10000)
@@ -1,10 +1,10 @@
# ExampleHub = MoveHub CityHub TechnicHub PrimeHub
from pybricks.hubs import ExampleHub
# ThisHub = MoveHub CityHub TechnicHub PrimeHub EssentialHub
from pybricks.hubs import ThisHub
from pybricks.parameters import Color
from pybricks.tools import wait
# Initialize the hub
hub = ExampleHub()
hub = ThisHub()
# Keep blinking red on and off.
hub.light.blink(Color.RED, [500, 500])
@@ -1,9 +1,10 @@
from pybricks.hubs import CityHub
# ThisHub = CityHub TechnicHub PrimeHub EssentialHub
from pybricks.hubs import ThisHub
from pybricks.parameters import Color
from pybricks.tools import wait
# Initialize the hub.
hub = CityHub()
hub = ThisHub()
# Show the color at 30% brightness.
hub.light.on(Color.RED * 0.3)
@@ -1,10 +1,10 @@
# ExampleHub = MoveHub CityHub TechnicHub PrimeHub
from pybricks.hubs import ExampleHub
# ThisHub = MoveHub CityHub TechnicHub PrimeHub EssentialHub
from pybricks.hubs import ThisHub
from pybricks.parameters import Color
from pybricks.tools import wait
# Initialize the hub.
hub = ExampleHub()
hub = ThisHub()
# Turn the light on and off 5 times.
for i in range(5):
+39
View File
@@ -0,0 +1,39 @@
#!/usr/bin/env python3
"""Generates hub-specific examples from common template script."""
import pathlib
# Make build directory.
dir_path = pathlib.Path(__file__).parent
build_path = dir_path / "build"
build_path.mkdir(exist_ok=True)
# Get list of scripts to be parsed.
file_paths = [f for f in dir_path.glob("*.py") if f.stem != "make_examples"]
# Go through all template scripts
for file_path in file_paths:
with open(file_path) as template:
# First line contains hub info
hubs = template.readline().strip().split()[3:]
print("Converting", template.name, "to", hubs)
for hub in hubs:
# Path to hub-specific output script.
gen_path = build_path / (file_path.stem + "_" + hub.lower() + ".py")
# Reset source script and skip over header.
template.seek(0)
template.readline()
# Open destination script:
with open(gen_path, "w") as dest_file:
# Read script line by line.
for line in template.readlines():
# Replace hub name if present.
dest_file.writelines(line.replace("ThisHub", hub))
@@ -1,8 +1,9 @@
from pybricks.hubs import MoveHub
# ThisHub = MoveHub CityHub TechnicHub PrimeHub EssentialHub
from pybricks.hubs import ThisHub
from pybricks.tools import wait
# Initialize the hub.
hub = MoveHub()
hub = ThisHub()
# Say goodbye and give some time to send it.
print("Goodbye!")
-25
View File
@@ -1,25 +0,0 @@
from pybricks.hubs import MoveHub
from pybricks.parameters import Color, Button
from pybricks.tools import wait, StopWatch
# Initialize the hub.
hub = MoveHub()
# Disable the stop button.
hub.system.set_stop_button(None)
# Check the button for 5 seconds.
watch = StopWatch()
while watch.time() < 5000:
# Set light to green if pressed, else red.
if hub.button.pressed():
hub.light.on(Color.GREEN)
else:
hub.light.on(Color.RED)
# Enable the stop button again.
hub.system.set_stop_button(Button.CENTER)
# Now you can press the stop button as usual.
wait(5000)
-29
View File
@@ -1,29 +0,0 @@
from pybricks.hubs import MoveHub
from pybricks.parameters import Color, Side
from pybricks.tools import wait
# Initialize the hub.
hub = MoveHub()
# Define colors for each side in a dictionary.
SIDE_COLORS = {
Side.TOP: Color.RED,
Side.BOTTOM: Color.BLUE,
Side.LEFT: Color.GREEN,
Side.RIGHT: Color.YELLOW,
Side.FRONT: Color.MAGENTA,
Side.BACK: Color.BLACK,
}
# Keep updating the color based on detected up side.
while True:
# Check which side of the hub is up.
up_side = hub.imu.up()
# Change the color based on the side.
hub.light.on(SIDE_COLORS[up_side])
# Also print the result.
print(up_side)
wait(50)
-16
View File
@@ -1,16 +0,0 @@
from pybricks.hubs import MoveHub
from pybricks.parameters import Color
from pybricks.tools import wait
# Initialize the hub
hub = MoveHub()
# Keep blinking red on and off.
hub.light.blink(Color.RED, [500, 500])
wait(10000)
# Keep blinking green slowly and then quickly.
hub.light.blink(Color.GREEN, [500, 500, 50, 900])
wait(10000)
-15
View File
@@ -1,15 +0,0 @@
from pybricks.hubs import MoveHub
from pybricks.parameters import Color
from pybricks.tools import wait
# Initialize the hub.
hub = MoveHub()
# Turn the light on and off 5 times.
for i in range(5):
hub.light.on(Color.RED)
wait(1000)
hub.light.off()
wait(500)
+1 -1
View File
@@ -12,7 +12,7 @@ hub.light.off()
brightness = list(range(0, 100, 4)) + list(range(100, 0, -4))
# Create an animation of the heart icon with changing brightness.
hub.display.animate([Icon.HEART * i/100 for i in brightness], 30)
hub.display.animate([Icon.HEART * i / 100 for i in brightness], 30)
# The animation repeats in the background. Here we just wait.
while True:
@@ -12,15 +12,15 @@ while True:
# Start with random left brow: up or down.
if randint(0, 100) < 70:
brows = Icon.EYE_LEFT_BROW*0.5
brows = Icon.EYE_LEFT_BROW * 0.5
else:
brows = Icon.EYE_LEFT_BROW_UP*0.5
brows = Icon.EYE_LEFT_BROW_UP * 0.5
# Add random right brow: up or down.
if randint(0, 100) < 70:
brows += Icon.EYE_RIGHT_BROW*0.5
brows += Icon.EYE_RIGHT_BROW * 0.5
else:
brows += Icon.EYE_RIGHT_BROW_UP*0.5
brows += Icon.EYE_RIGHT_BROW_UP * 0.5
for i in range(3):
# Display eyes open plus the random brows.
@@ -28,5 +28,7 @@ while True:
wait(2000)
# Display eyes blinked plus the random brows.
hub.display.image(Icon.EYE_LEFT_BLINK*0.7 + Icon.EYE_RIGHT_BLINK*0.7 + brows)
hub.display.image(
Icon.EYE_LEFT_BLINK * 0.7 + Icon.EYE_RIGHT_BLINK * 0.7 + brows
)
wait(200)
+9 -7
View File
@@ -6,13 +6,15 @@ from pybricks.geometry import Matrix
hub = PrimeHub()
# Make a square that is bright on the outside and faint in the middle.
SQUARE = Matrix([
[100, 100, 100, 100, 100],
[100, 50, 50, 50, 100],
[100, 50, 0, 50, 100],
[100, 50, 50, 50, 100],
[100, 100, 100, 100, 100],
])
SQUARE = Matrix(
[
[100, 100, 100, 100, 100],
[100, 50, 50, 50, 100],
[100, 50, 0, 50, 100],
[100, 50, 50, 50, 100],
[100, 100, 100, 100, 100],
]
)
# Display the square.
hub.display.image(SQUARE)
+2 -2
View File
@@ -5,8 +5,8 @@ from pybricks.tools import wait
hub = PrimeHub()
# Display the letter A for two seconds.
hub.display.char('A')
hub.display.char("A")
wait(2000)
# Display text, one letter at a time.
hub.display.text('Hello, world!')
hub.display.text("Hello, world!")
@@ -1,20 +0,0 @@
from pybricks.hubs import PrimeHub
from pybricks.tools import wait
from pybricks.geometry import Axis
# Initialize the hub.
hub = PrimeHub()
# Get the acceleration or angular_velocity along a single axis.
# If you need only one value, this is more memory efficient.
while True:
# Read the forward acceleration.
forward_acceleration = hub.imu.acceleration(Axis.X)
# Read the yaw rate.
yaw_rate = hub.imu.angular_velocity(Axis.Z)
# Print the yaw rate.
print(yaw_rate)
wait(100)
-16
View File
@@ -1,16 +0,0 @@
from pybricks.hubs import PrimeHub
from pybricks.parameters import Color
from pybricks.tools import wait
# Initialize the hub
hub = PrimeHub()
# Keep blinking red on and off.
hub.light.blink(Color.RED, [500, 500])
wait(10000)
# Keep blinking green slowly and then quickly.
hub.light.blink(Color.GREEN, [500, 500, 50, 900])
wait(10000)
-21
View File
@@ -1,21 +0,0 @@
from pybricks.hubs import PrimeHub
from pybricks.parameters import Color
from pybricks.tools import wait
# Initialize the hub.
hub = PrimeHub()
# Show the color at 30% brightness.
hub.light.on(Color.RED * 0.3)
wait(2000)
# Use your own custom color.
hub.light.on(Color(h=30, s=100, v=50))
wait(2000)
# Go through all the colors.
for hue in range(360):
hub.light.on(Color(hue))
wait(10)
-15
View File
@@ -1,15 +0,0 @@
from pybricks.hubs import PrimeHub
from pybricks.parameters import Color
from pybricks.tools import wait
# Initialize the hub.
hub = PrimeHub()
# Turn the light on and off 5 times.
for i in range(5):
hub.light.on(Color.RED)
wait(1000)
hub.light.off()
wait(500)
@@ -1,12 +0,0 @@
from pybricks.hubs import PrimeHub
from pybricks.tools import wait
# Initialize the hub.
hub = PrimeHub()
# Say goodbye and give some time to send it.
print("Goodbye!")
wait(100)
# Shut the hub down.
hub.system.shutdown()

Some files were not shown because too many files have changed in this diff Show More