Initial code with Python stubs for Lego Spike API, Go Robot Code and an example how to structure our code

This commit is contained in:
Lars Haferkamp 2023-02-14 17:43:41 +01:00
commit a58ba5fd6d
18 changed files with 4561 additions and 0 deletions

50
hub/__init__.py Normal file
View file

@ -0,0 +1,50 @@
from typing import Tuple, overload
from hub import port, battery, bluetooth, button, display, motion, sound, supervision
from hub.display import Image
__version__ = 'v1.0.0.0000-0000000'
config = {}
TOP = 0
FRONT = 1
RIGHT = 2
BOTTOM = 3
BACK = 4
LEFT = 5
def info() -> dict:
pass
def status() -> dict:
pass
def temperature() -> float:
pass
@overload
def power_off(fast=True, restart=False):
pass
@overload
def power_off(timeout=0):
pass
def repl_restart(restart: bool):
pass
@overload
def led(color: int):
pass
@overload
def led(red: int, green: int, blue: int):
pass
@overload
def led(color: Tuple[int, int, int]):
pass
def file_transfer(filename: str, filesize: int, packetsize=1000, timeout=2000, mode=None):
pass

96
hub/battery.py Normal file
View file

@ -0,0 +1,96 @@
from typing import Union
def voltage() -> int:
"""
Gets the battery voltage.
### Returns
- The voltage in mV.
"""
pass
def current() -> int:
"""
Gets current flowing out of the battery.
### Returns
- The current in in mA.
"""
pass
def capacity_left() -> int:
"""
Gets the remaining capacity as a percentage of a fully charged battery.
### Returns
- The remaining battery capacity.
"""
pass
def temperature() -> float:
"""
Gets the temperature of the battery.
### Returns
- The temperature in degrees Celsius.
"""
pass
def charger_detect() -> Union[bool, int]:
"""
Checks what type of charger was detected.
### Returns
- See charging constants for all possible return values. Returns False if it failed to detect a charger.
"""
pass
def info() -> dict:
"""
Gets status information about the battery.
This returns a dictionary of the form:
```
{
# Battery measurements as documented above.
'battery_capacity_left': 100
'temperature': 25.7,
'charge_current': 248,
'charge_voltage': 8294,
# Filtered version of the battery voltage.
'charge_voltage_filtered': 8287,
# A list of active errors. See constants given below.
'error_state': [0],
# Charging state. See constants given below.
'charger_state': 2,
}
```
### Returns
- Battery status information.
"""
pass
# Battery status values
BATTERY_NO_ERROR = 0 #The battery is happy.
BATTERY_HUB_TEMPERATURE_CRITICAL_OUT_OF_RANGE= -1 #The battery temperature is outside of the expected range.
BATTERY_TEMPERATURE_OUT_OF_RANGE= -2 #The battery temperature is outside of the critical range.
BATTERY_TEMPERATURE_SENSOR_FAIL= -3 #The battery temperature sensor is not working.
BATTERY_BAD_BATTERY= -4 #Something is wrong with the battery.
BATTERY_VOLTAGE_TOO_LOW= -5 #The battery voltage is too low.
BATTERY_MISSING= -6 #No battery detected.
#Charger types
USB_CH_PORT_NONE= 0 #No charger detected.
USB_CH_PORT_SDP= 1 #Standard downstream port (typical USB port).
USB_CH_PORT_CDP= 2 #Charging Downstream Port (wall charger).
USB_CH_PORT_DCP= 3 #Dedicated charging port (high current USB port).
#Charging states
CHARGER_STATE_FAIL= -1 #There was a problem charging the battery.
CHARGER_STATE_DISCHARGING= 0 #The battery is discharging.
CHARGER_STATE_CHARGING_ONGOING= 1 #The battery is charging.
CHARGER_STATE_CHARGING_COMPLETED= 2 #The battery is fully charged.

144
hub/bluetooth.py Normal file
View file

@ -0,0 +1,144 @@
from typing import Callable, overload
# The Bluetooth module.
@overload
def discoverable() -> int:
pass
@overload
def discoverable(time: int):
"""
Gets or sets the Bluetooth classic discoverability state.
### Parameters
- `time` - For how many seconds the hub should be discoverable. During this time, you can find the hub when you search for Bluetooth devices using your computer or phone.
### Returns
- If no argument is given, this returns the remaining number of seconds that the hub is discoverable. Once the hub is no longer discoverable, it returns 0.
"""
pass
@overload
def rfcomm_connect() -> str:
pass
@overload
def rfcomm_connect(address: str) -> bool:
"""
Connects to a Bluetooth Classic MAC address.
### Parameters
- `address` - A string of format aa:bb:cc:dd:ee:ff that represents the MAC address of the Bluetooth Classic device to connect with.
### Returns
- If no argument is given, returns the MAC address that the RFCOMM service is conneted to. If there is no active connection the address is 00:00:00:00:00:00.
- True if a valid address was given, or False if the address is not a valid MAC address string.
- The result does not reflect the status of the connection attempt.
"""
pass
def rfcomm_disconnect() -> None:
"""
Disconnects an active RFCOMM channel
The result does not reflect the status of the disconnection attempt.
"""
pass
def info() -> dict:
"""
Gets a dictionary of the form:
```
{
# The Bluetooth device MAC address.
'mac_addr': '38:0B:3C:A2:E1:E4',
# The Bluetooth device UUID.
'device_uuid': '03970000-1800-3500-1551-383235373836'
# The outgoing service UUID.
'service_uuid': '',
# Bluetooth name of the device.
'name': 'LEGO Hub 38:0B:3C:A2:E1:E4',
# iPod Accessory Protocol (iAP) status dictionary.
'iap': {
'device_version': 7,
'authentication_revision': 1,
'device_id': -1,
'certificate_serial_no': '54D2891DEC5E5104F7132BC3059365CB',
'protocol_major_version': 3,
'protocol_minor_version': 0
},
# A list of devices that the hub has been connected to.
'known_devices': ['8C:8D:28:2D:E0:0F', 'E8:6D:CB:77:64:D5'],
}
```
### Returns
- Bluetooth subsystem information dictionary similar to the example above, or None if the Bluetooth subsystem is not running.
- The MAC address in known_devices is reversed for Windows devices.
"""
pass
def forget(address) -> bool:
"""
Removes a device from the list of known Bluetooth devices.
### Parameters
- `address` - Bluetooth address of the form '01:23:45:67:89:AB'.
### Returns
- True if a valid address was given, or False if not.
- Functions for the LEGO Wireless Protocol
"""
pass
@overload
def lwp_advertise() -> int:
pass
@overload
def lwp_advertise(timeout: int):
"""
Gets or sets the Bluetooth Low Energy LEGO Wireless protocol advertising state.
### Parameters
- `time` - For how many seconds the hub should advertise the LEGO Wireless Protocol. During this time, you can find the hub when you search for Bluetooth devices using your computer or phone.
### Returns
- If no argument is given, this returns the remaining number of seconds that the hub will advertise. Once the hub is no longer advertising, it returns 0.
"""
pass
@overload
def lwp_bypass() -> bool:
pass
@overload
def lwp_bypass(bypass: bool):
"""
Controls whether the LEGO Wireless Protocol is bypassed when using Bluetooth Low Energy.
### Parameters
- `bypass` - Choose True to bypass the LEGO Wireless protocol or choose False to enable it.
### Returns
- If no argument is given, this returns the current bypass state.
"""
pass
def lwp_monitor(self, handler: Callable[[int], None]):
"""
Sets the callback function that is called when a connection is made using the LEGO Wireless Protocol.
The function must accept one argument, which provides information about the incoming connection.
### Parameters
- `handler` - Callable function that takes one argument. Choose None to disable the callback.
"""
pass

57
hub/button.py Normal file
View file

@ -0,0 +1,57 @@
from typing import Callable
class Button:
"""
Provides access to button state and callback.
Each of the buttons listed below are instances of this class. You cannot instantiate additional button objects.
"""
def is_pressed(self) -> bool:
"""
Gets the state of the button.
### Returns
- True if it is pressed, False otherwise.
"""
pass
def was_pressed() -> bool:
"""
Checks if this button was pressed since this method was last called.
### Returns
- True if it was pressed at least once since the previous call, False otherwise.
"""
pass
def presses() -> int:
"""
Gets the number of times this button was pressed since this method was last called.
### Returns
- The number of presses since the last call.
"""
pass
def callback(function: Callable[[int], None]) -> None:
"""
Sets the callback function that is called when the button is pressed and when it is released.
The function must accept one argument, whose value indicates why the callback was called:
If the value is 0, the button is now pressed.
Otherwise, the button is now released. The value represents how many milliseconds it was pressed before it was released.
### Parameters
- `function` - Callable function that takes one argument. Choose None to disable the callback.
"""
pass
left: Button # The left button.
right: Button # The right button.
center: Button # The center button.
connect: Button # The button with the Bluetooth symbol.

378
hub/display.py Normal file
View file

@ -0,0 +1,378 @@
from __future__ import annotations
from typing import Callable, Iterable
"""
The Image class lets you create and modify images that you can show on the hub matrix display using the hub.display module.
"""
class Image:
def __init__(self, *args):
"""
Create a new image object for use with the hub.display.show() function.
```
Image(string: str)
Image(width: int, height: int)
Image(width: int, height: int, buffer: bytes)
```
You can use one of the signatures above to initialize an image, depending on what you need.
### Parameters
- `string` - String of the form "00900:09990:99999:09990:09090:", representing the brightness of each pixel (0 to 9). Pixels are listed row by row, separated by a colon (:) or line break (\\n).
- `width` - Number of pixels in one row of the new image.
- `height` - Number of pixels in one column of the new image.
- `buffer` - Bytes representing the brightness values of each pixel in the new image. The buffer size must be equal to width * height. If you give a with and height but no buffer, you will get an image where all pixels are zero.
"""
pass
def width(self) -> int:
"""
Gets the width of the image as a number of pixels.
"""
pass
def height(self) -> int:
"""
Gets the width of the image as a number of pixels.
"""
pass
def shift_left(n: int) -> 'Image':
"""
Shifts the image to the left.
### Parameters
- `n1 - By how many pixels to shift the image.
### Returns
- A new, shifted image.
"""
pass
def shift_right(n: int) -> 'Image':
"""
Shifts the image to the right.
### Parameters
- `n` - By how many pixels to shift the image.
### Returns
- A new, shifted image.
"""
pass
def shift_up(n: int) -> 'Image':
"""
Shifts the image up.
### Parameters
- `n` - By how many pixels to shift the image.
### Returns
- A new, shifted image.
"""
pass
def shift_down(n: int) -> 'Image':
"""
Shifts the image down.
### Parameters
- `n` - By how many pixels to shift the image.
### Returns
- A new, shifted image.
"""
pass
def get_pixel(x: int, y: int, brightness: int) -> int:
"""
Gets the brightness of one pixel in the image.
### Parameters
- `x` - Pixel position counted from the left, starting at zero.
- `y` - Pixel position counted from the top, starting at zero.
### Returns
- Brightness (0-9) of the requested pixel.
"""
pass
def set_pixel(x: int, y: int, brightness: int) -> None:
"""
Sets the brightness of one pixel in the image.
### Parameters
- `x` - Pixel position counted from the left, starting at zero.
- `y` - Pixel position counted from the top, starting at zero.
- `brightness` - Brightness between 0 (fully off) and 9 (fully on).
### Raises
- `ValueError` - If x or y are negative or larger than the image size.
- `TypeError` - If you try to modify a built-in image such as HEART.
"""
pass
ANGRY: Image
ARROW_E: Image
ARROW_N: Image
ARROW_NE: Image
ARROW_NW: Image
ARROW_S: Image
ARROW_SE: Image
ARROW_SW: Image
ARROW_W: Image
ASLEEP: Image
BUTTERFLY: Image
CHESSBOARD: Image
CLOCK1: Image
CLOCK2: Image
CLOCK3: Image
CLOCK4: Image
CLOCK5: Image
CLOCK6: Image
CLOCK7: Image
CLOCK8: Image
CLOCK9: Image
CLOCK10: Image
CLOCK11: Image
CLOCK12: Image
CONFUSED: Image
COW: Image
DIAMOND: Image
DIAMOND_SMALL: Image
DUCK: Image
FABULOUS: Image
GHOST: Image
GIRAFFE: Image
GO_DOWN: Image
GO_LEFT: Image
GO_RIGHT: Image
GO_UP: Image
HAPPY: Image
HEART: Image
HEART_SMALL: Image
HOUSE: Image
MEH: Image
MUSIC_CROTCHET: Image
MUSIC_QUAVER: Image
MUSIC_QUAVERS: Image
NO: Image
PACMAN: Image
PITCHFORK: Image
RABBIT: Image
ROLLERSKATE: Image
SAD: Image
SILLY: Image
SKULL: Image
SMILE: Image
SNAKE: Image
SQUARE: Image
SQUARE_SMALL: Image
STICKFIGURE: Image
SURPRISED: Image
SWORD: Image
TARGET: Image
TORTOISE: Image
TRIANGLE: Image
TRIANGLE_LEFT: Image
TSHIRT: Image
UMBRELLA: Image
XMAS: Image
YES: Image
ALL_CLOCKS: Image
ALL_ARROWS: Image
#Built-in images
Image.ANGRY = Image('90009:09090:00000:99999:90909:')
Image.ARROW_E = Image('00900:00090:99999:00090:00900:')
Image.ARROW_N = Image('00900:09990:90909:00900:00900:')
Image.ARROW_NE = Image('00999:00099:00909:09000:90000:')
Image.ARROW_NW = Image('99900:99000:90900:00090:00009:')
Image.ARROW_S = Image('00900:00900:90909:09990:00900:')
Image.ARROW_SE = Image('90000:09000:00909:00099:00999:')
Image.ARROW_SW = Image('00009:00090:90900:99000:99900:')
Image.ARROW_W = Image('00900:09000:99999:09000:00900:')
Image.ASLEEP = Image('00000:99099:00000:09990:00000:')
Image.BUTTERFLY = Image('99099:99999:00900:99999:99099:')
Image.CHESSBOARD = Image('09090:90909:09090:90909:09090:')
Image.CLOCK1 = Image('00090:00090:00900:00000:00000:')
Image.CLOCK2 = Image('00000:00099:00900:00000:00000:')
Image.CLOCK3 = Image('00000:00000:00999:00000:00000:')
Image.CLOCK4 = Image('00000:00000:00900:00099:00000:')
Image.CLOCK5 = Image('00000:00000:00900:00090:00090:')
Image.CLOCK6 = Image('00000:00000:00900:00900:00900:')
Image.CLOCK7 = Image('00000:00000:00900:09000:09000:')
Image.CLOCK8 = Image('00000:00000:00900:99000:00000:')
Image.CLOCK9 = Image('00000:00000:99900:00000:00000:')
Image.CLOCK10 = Image('00000:99000:00900:00000:00000:')
Image.CLOCK11 = Image('09000:09000:00900:00000:00000:')
Image.CLOCK12 = Image('00900:00900:00900:00000:00000:')
Image.CONFUSED = Image('00000:09090:00000:09090:90909:')
Image.COW = Image('90009:90009:99999:09990:00900:')
Image.DIAMOND = Image('00900:09090:90009:09090:00900:')
Image.DIAMOND_SMALL = Image('00000:00900:09090:00900:00000:')
Image.DUCK = Image('09900:99900:09999:09990:00000:')
Image.FABULOUS = Image('99999:99099:00000:09090:09990:')
Image.GHOST = Image('99999:90909:99999:99999:90909:')
Image.GIRAFFE = Image('99000:09000:09000:09990:09090:')
Image.GO_DOWN = Image('00000:99999:09990:00900:00000:')
Image.GO_LEFT = Image('00090:00990:09990:00990:00090:')
Image.GO_RIGHT = Image('09000:09900:09990:09900:09000:')
Image.GO_UP = Image('00000:00900:09990:99999:00000:')
Image.HAPPY = Image('00000:09090:00000:90009:09990:')
Image.HEART = Image('09090:99999:99999:09990:00900:')
Image.HEART_SMALL = Image('00000:09090:09990:00900:00000:')
Image.HOUSE = Image('00900:09990:99999:09990:09090:')
Image.MEH = Image('09090:00000:00090:00900:09000:')
Image.MUSIC_CROTCHET = Image('00900:00900:00900:99900:99900:')
Image.MUSIC_QUAVER = Image('00900:00990:00909:99900:99900:')
Image.MUSIC_QUAVERS = Image('09999:09009:09009:99099:99099:')
Image.NO = Image('90009:09090:00900:09090:90009:')
Image.PACMAN = Image('09999:99090:99900:99990:09999:')
Image.PITCHFORK = Image('90909:90909:99999:00900:00900:')
Image.RABBIT = Image('90900:90900:99990:99090:99990:')
Image.ROLLERSKATE = Image('00099:00099:99999:99999:09090:')
Image.SAD = Image('00000:09090:00000:09990:90009:')
Image.SILLY = Image('90009:00000:99999:00909:00999:')
Image.SKULL = Image('09990:90909:99999:09990:09990:')
Image.SMILE = Image('00000:00000:00000:90009:09990:')
Image.SNAKE = Image('99000:99099:09090:09990:00000:')
Image.SQUARE = Image('99999:90009:90009:90009:99999:')
Image.SQUARE_SMALL = Image('00000:09990:09090:09990:00000:')
Image.STICKFIGURE = Image('00900:99999:00900:09090:90009:')
Image.SURPRISED = Image('09090:00000:00900:09090:00900:')
Image.SWORD = Image('00900:00900:00900:09990:00900:')
Image.TARGET = Image('00900:09990:99099:09990:00900:')
Image.TORTOISE = Image('00000:09990:99999:09090:00000:')
Image.TRIANGLE = Image('00000:00900:09090:99999:00000:')
Image.TRIANGLE_LEFT = Image('90000:99000:90900:90090:99999:')
Image.TSHIRT = Image('99099:99999:09990:09990:09990:')
Image.UMBRELLA = Image('09990:99999:00900:90900:09900:')
Image.XMAS = Image('00900:09990:00900:09990:99999:')
Image.YES = Image('00000:00009:00090:90900:09000:')
#Built-in tuples of images
Image.ALL_CLOCKS = (Image('00900:00900:00900:00000:00000:'), Image('00090:00090:00900:00000:00000:'), Image('00000:00099:00900:00000:00000:'), Image('00000:00000:00999:00000:00000:'), Image('00000:00000:00900:00099:00000:'), Image('00000:00000:00900:00090:00090:'), Image('00000:00000:00900:00900:00900:'), Image('00000:00000:00900:09000:09000:'), Image('00000:00000:00900:99000:00000:'), Image('00000:00000:99900:00000:00000:'), Image('00000:99000:00900:00000:00000:'), Image('09000:09000:00900:00000:00000:'))
Image.ALL_ARROWS = (Image('00900:09990:90909:00900:00900:'), Image('00999:00099:00909:09000:90000:'), Image('00900:00090:99999:00090:00900:'), Image('90000:09000:00909:00099:00999:'), Image('00900:00900:90909:09990:00900:'), Image('00009:00090:90900:99000:99900:'), Image('00900:09000:99999:09000:00900:'), Image('99900:99000:90900:00090:00009:'))
"""
The display module lets you control the light matrix display on the hub.
"""
def clear():
"""
Turns off all the pixels.
"""
pass
def rotation(rotation: int) -> None:
"""
Rotates the display clockwise relative to its current orientation.
DEPRECATION WARNING - In the next release this is a do-nothing operation. Use the def align() API instead!
Following the next release this call will be removed.
"""
pass
def align() -> int:
pass
def align(face: int) -> int:
"""
Rotates the display by aligning the top with the given face of the hub.
### Parameters
- `face` - Choose hub.FRONT, hub.BACK, hub.LEFT, or hub.RIGHT.
### Returns
- The new or current alignment.
"""
pass
def invert() -> bool:
pass
def invert(invert: bool) -> bool:
"""
Inverts all pixels. This affects what is currently displayed, as well as everything you display afterwards.
In the inverted state, the brightness of each pixel is the opposite of the normal state. If a pixel has brightness b, it will be displayed with brightness 9 - b.
### Parameters
- `invert` - Choose True to activate the inverted state. Choose False to restore the normal state.
### Returns
- The new or current inversion state.
"""
pass
def callback(self, function: Callable[[int], None]) -> None:
"""
Sets the callback function that is called when a display operation is completed or interrupted.
The function must accept one argument, which indicates why the callback was called. It will receive 0 if a display operation completed successfully, or 1 if it was interrupted.
### Parameters
- `function` - Callable function that takes one argument. Choose None to disable the callback.
"""
pass
def pixel(x: int, y: int) -> int:
pass
def pixel(x: int, y: int, brightness: int) -> None:
"""
Gets or sets the brightness of one pixel.
### Parameters
- `x` - Pixel position counted from the left, starting at zero.
- `y` - Pixel position counted from the top, starting at zero.
- `brightness` - Brightness between 0 (fully off) and 9 (fully on).
### Returns
- If no brightness is given, this returns the brightness of the selected pixel. Otherwise it returns None.
"""
pass
def show(image: Image) -> None:
pass
def show(image: Iterable[Image], delay=400, level=9, clear=False, wait=True, loop=False, fade=0) -> None:
"""
Shows an image or a sequence of images.
Except for image, all arguments must be specified as keywords.
### Parameters
- `image` - The image or iterable of images to be displayed.
### Keyword Arguments
- `delay` - Delay between each image in the iterable.
- `level` - Scales the brightness of each pixel in and image or character to a value between 0 (fully off) and 9 (fully on).
- `clear` - Choose `True` to clear the display after showing the last image in the iterable.
- `wait` - Choose `True` to block your program until all images are shown. Choose `False` to show all images in the background while your program continues.
- `loop` - Choose `True` repeat the sequence of images for ever. Choose `False` to show it only once.
- `fade` -
Sets the transitional behavior between images in the sequence:
The image will appear immediately.
The image will appear immediately.
The image fades out while the next image fades in.
Images will scroll to the right.
Images will scroll to the left.
Images will fade in, starting from an empty display.
Images will fade out, starting from the original image.
"""
pass

125
hub/motion.py Normal file
View file

@ -0,0 +1,125 @@
from typing import Tuple, Callable
from typing import overload
def accelerometer(filtered=False) -> Tuple[int, int, int]:
"""
Gets the acceleration of the hub along the x, y, and z axis.
#### Parameters
- `filtered` - Selecting True gives a more stable value, but it is delayed by 10-100 milliseconds. Selecting False gives the unfiltered value.
#### Returns
- Acceleration of the hub with units of `cm/s^2`. On a perfectly level surface, this gives (0, 0, 981).
"""
pass
def gyroscope(filtered=False) -> Tuple[int, int, int]:
"""
Gets the angular velocity of the hub along the x, y, and z axis.
### Parameters
- `filtered` - Selecting True gives a more stable value, but it is delayed by 10-100 milliseconds. Selecting False gives the unfiltered value.
### Returns
- Angular velocity with units of degrees per second.
"""
pass
@overload
def align_to_model(top: int, front: int) -> None:
pass
@overload
def align_to_model(nsamples: int, callback: Callable[[int], None]) -> None:
pass
@overload
def align_to_model(top: int, front: int, nsamples: int, callback: Callable[[int], None]) -> None:
"""
Sets the default hub orientation and/or calibrates the gyroscope.
The hub must not move while calibrating. It takes about one second by default.
Changing the model alignment affects most other methods in this module. They will now be relative to the hub alignment that you specify.
### Keyword Arguments
- `top` - Which hub side is at the top of your model. See the hub `constants` for all possible values.
- `front` - Which hub side is on the front of your model.
- `nsamples` - Number of samples for calibration between 0 and 10000. It is 100 by default.
- `callback` - Function that will be called when calibration is complete. It must accept one argument. Choose None to disable the callback. This is the default.
"""
pass
@overload
def yaw_pitch_roll() -> Tuple[int, int, int]:
pass
@overload
def yaw_pitch_roll(yaw_preset: int) -> None:
pass
@overload
def yaw_pitch_roll(yaw_correction: float) -> None:
"""
Gets the yaw, pitch, and roll angles of the hub, or resets the yaw.
The yaw_correction is an optional keyword argument to improve the accuracy of the yaw value after one full turn. To use it:
Reset the yaw angle to zero using def yaw_pitch_roll(0).
Rotate the hub smoothly exactly one rotation clockwise.
Call error = def yaw_pitch_roll()[0] to get the yaw error.
The error should be 0. If it is not, you can set the correction using def yaw_pitch_roll(yaw_correction=error).
For even more accuracy, you can turn clockwise 5 times, and use error / 5 as the correction factor.
### Keyword Arguments
- `yaw_preset` - Sets the current yaw to the given value (-180 to 179).
- `yaw_correction` - Adjusts the gain of the yaw axis values. See the yaw adjustment section below.
### Returns
- If no arguments are given, this returns a tuple of yaw, pitch, and roll values in degrees.
"""
pass
@overload
def orientation() -> int:
pass
@overload
def orientation(callback: Callable[[int], None]) -> int:
"""
Gets which hub side of the hub is mostly pointing up.
### Keyword Arguments
- `callback` - Function that will be called when the orientation changes. It must accept one argument, which will tell you which hub side is up. Choose None to disable the callback. This is the default.
### Returns
- Number representing which side is up. See hub constants for all possible values.
"""
pass
@overload
def gesture() -> int:
pass
@overload
def gesture(callback: Callable[[int], None]) -> int:
"""
Gets the most recent gesture that the hub has made since this function was last called.
### Keyword Arguments
- `callback` - Function that will be called when a gesture is detected. It must accept one argument, which will tell you which gesture was detected. Choose None to disable the callback. This is the default.
### Returns
- Number representing the gesture. See motion constants for all possible values. If no gesture was detected since this function was last called, it returns None.
"""
pass
#These values are used by the gesture() function.
TAPPED = 0 #The hub was tapped.
DOUBLETAPPED = 1 #The hub was quickly tapped twice.
SHAKE = 2 #The hub was shaken.
FREEFALL = 3 #The hub fell.

456
hub/port.py Normal file
View file

@ -0,0 +1,456 @@
from __future__ import annotations
from typing import Callable, Union, Optional, Iterable, Tuple, overload
class Pin():
"""
This class can be used to read and control the two logic pins on pins 5 and 6 of each port. You can access two `Pin` objects via each `Port` instance if the port has been set to `MODE_GPIO` mode.
Control a general purpose input/output (GPIO) pin.
"""
def direction(self, direction: Optional[int]) -> int:
"""
Gets and sets the direction of the pin.
### Parameters
- `direction` - Choose 0 to make the pin an input or 1 to make it an output.
### Returns
- The configured direction.
"""
pass
def value(self, value: Optional[int]) -> int:
"""
Gets and sets the logic value of the pin.
### Parameters
- `value` - Choose 1 to make the pin high or 0 to make it low. If the pin is configured as an input, this argument is ignored.
### Returns
- Logic value of the pin.
"""
pass
class Device():
"""
This class is the blueprint for the device attributes of the ports in the `hub.port` module, which in turn are instances of the `Port` class. You cannot import or instantiate this class manually.
Read values from a Powered Up device and configure its modes.
"""
FORMAT_RAW = 0
FORMAT_PCT= 1
FORMAT_SI= 2
def get(self, format: Optional[int]) -> list:
"""
Gets the values that the active device mode provides.
### Parameters
- `format` - Format of the data. Choose `FORMAT_RAW`, `FORMAT_PCT`, or `FORMAT_SI`.
### Returns
- Values or measurements representing the device state.
"""
pass
@overload
def mode(self, mode: int) -> None:
pass
@overload
def mode(self, mode: int, data: bytes) -> None:
pass
@overload
def mode(self, mode: Iterable[Tuple[int, int]]) -> None:
pass
@overload
def mode(self) -> Iterable[Tuple[int, int]]:
pass
def pwm(self, value: int) -> None:
pass
def write_direct(self, data: bytes) -> None:
pass
class Motor(Device):
"""
This class is the blueprint for the motor attributes of the ports in the hub.port module, which in turn are instances of the Port class. You cannot import or instantiate this class manually.
Control a motor.
"""
BUSY_MODE = 0 #The port is busy configuring the device mode."""
BUSY_MOTOR = 1 #The motor is busy executing a command.
STOP_FLOAT = 0 #When stopping, the motor floats. See also float().
STOP_BRAKE = 1 #When stopping, the motor brakes. See also brake().
STOP_HOLD = 2 #When stopping, the motor holds position. See also hold().
EVENT_COMPLETED = 0 #The motor command completed successfully.
EVENT_INTERRUPTED = 1 #The motor command was interrupted.
EVENT_STALLED = 2 #The motor command stopped because the motor was stalled.
def __init__(self):
pass
def float(self) -> None:
"""
Floats (coasts) the motor, as if disconnected from the hub.
"""
pass
def brake(self) -> None:
"""
Passively brakes the motor, as if shorting the motor terminals.
"""
pass
def hold(self) -> None:
"""
Actively hold the motor in its current position.
"""
pass
def busy(self, type:int = BUSY_MODE) -> bool:
"""
Checks whether the motor is busy changing modes, or executing a motor command such as running to a position.
### Parameters
- `type` - Choose `BUSY_MODE` or `BUSY_MOTOR`.
### Returns
- Whether the motor is busy with the specified activity.
"""
pass
@overload
def run_at_speed(self, speed: int) -> None:
pass
@overload
def run_at_speed(self, speed: int, max_power: int, acceleration: int, deceleration: int, stall: bool) -> None:
"""
Starts running a motor at the given speed.
If a keyword argument is not given, its default value will be used.
### Parameters
- `speed` - Sets the speed as a percentage of the rated speed for this motor. Positive means clockwise, negative means counterclockwise.
### Keyword Arguments
- `max_power` - Sets percentage of maximum power used during this command.
- `acceleration` - The time in milliseconds (0-10000) for the motor to reach maximum rated speed from standstill.
- `deceleration` - The time in milliseconds (0-10000) for the motor to stop when starting from the maximum rated speed.
- `stall` - Selects whether the motor should stop when stalled (True) or not (False).
"""
pass
@overload
def run_for_time(self, msec: int) -> None:
pass
@overload
def run_for_time(self, msec: int, speed: int, max_power: int, stop: int, acceleration: int, deceleration: int, stall: bool) -> None:
"""
Runs a motor for a given amount of time.
If a keyword argument is not given, its default value will be used.
### Parameters
- `msec` - How long the motor should run in milliseconds. Negative values will be treated as zero.
### Keyword Arguments
- `speed` - Sets the speed as a percentage of the rated speed for this motor. Positive means clockwise, negative means counterclockwise.
- `max_power` - Sets percentage of maximum power used during this command.
- `stop` - How to stop. Choose type: Choose `STOP_FLOAT`, `STOP_BRAKE`, or `STOP_HOLD`.
- `acceleration` - The time in milliseconds (0-10000) for the motor to reach maximum rated speed from standstill.
- `deceleration` - The time in milliseconds (0-10000) for the motor to stop when starting from the maximum rated speed.
- `stall` - Selects whether the motor should stop trying to reach the endpoint when stalled (True) or not (False).
"""
pass
@overload
def run_for_degrees(self, degrees: int) -> None:
pass
@overload
def run_for_degrees(self, degrees: int, speed: int, max_power: int, stop: int, acceleration: int, deceleration: int, stall: bool) -> None:
"""
Runs a motor for a given number of degrees at a given speed.
If a keyword argument is not given, its default value will be used.
### Parameters
- `degrees` - How many degrees to rotate relative to the starting point.
### Keyword Arguments
- `speed` -
Sets the speed as a percentage of the rated speed for this motor.
If degrees > 0 and speed > 0, the motor turns clockwise.
If degrees > 0 and speed < 0, the motor turns counterclockwise.
If degrees < 0 and speed > 0, the motor turns clockwise.
If degrees < 0 and speed < 0, the motor turns counterclockwise.
- `max_power` - Sets percentage of maximum power used during this command.
- `stop` - How to stop. Choose type: Choose `STOP_FLOAT`, `STOP_BRAKE`, or `STOP_HOLD`.
- `acceleration` - The time in milliseconds (0-10000) for the motor to reach maximum rated speed from standstill.
- `deceleration` - The time in milliseconds (0-10000) for the motor to stop when starting from the maximum rated speed.
- `stall` - Selects whether the motor should stop trying to reach the endpoint when stalled (True) or not (False).
"""
pass
@overload
def run_to_position(self, position: int) -> None:
pass
@overload
def run_to_position(self, position: int, speed: int, max_power: int, stop: int, acceleration: int, deceleration: int, stall: bool) -> None:
"""
Runs a motor to the given position.
The angular position is measured relative to the motor position when the hub was turned on or when the motor was plugged in. You can preset this starting position using preset.
If a keyword argument is not given, its default value will be used.
### Parameters
- `position` - Position to rotate to.
### Keyword Arguments
- `speed` - Sets the speed as a percentage of the rated speed for this motor. The sign of the speed will be ignored.
- `max_power` - Sets percentage of maximum power used during this command.
- `stop` - How to stop. Choose type: Choose STOP_FLOAT, STOP_BRAKE, or STOP_HOLD.
- `acceleration` - The time in milliseconds (0-10000) for the motor to reach maximum rated speed from standstill.
- `deceleration` - The time in milliseconds (0-10000) for the motor to stop when starting from the maximum rated speed.
- `stall` - Selects whether the motor should stop trying to reach the endpoint when stalled (True) or not (False).
"""
pass
def preset(self, position: int) -> None:
"""
Presets the starting position used by run_to_position.
### Parameters
- `position` - The new position preset.
"""
pass
def callback(self, function: Callable[[int], None]) -> None:
"""
Sets the callback function that is called when a command is completed, interrupted, or stalled.
The function must accept one argument, which indicates why the callback was called. It will receive either EVENT_COMPLETED, EVENT_INTERRUPTED, or EVENT_STALLED.
### Parameters
- `function` - Callable function that takes one argument. Choose None to disable the callback.
"""
pass
@overload
def pid(self) -> tuple:
pass
@overload
def pid(self, p: int, i: int, d: int) -> None:
"""
Sets the p, i, and d constants of the motor PID controller.
### Parameters
- `p` - Proportional constant.
- `i` - Integral constant.
- `d` - Derivative constant.
### Returns
- If no arguments are given, this returns the values previously set by the user, if any. The system defaults cannot be read.
"""
pass
@overload
def default(self) -> dict:
pass
@overload
def default(self, speed: int, max_power: int, acceleration: int, deceleration: int, stop: int, pid: tuple, stall: bool, callback: Optional[Callable[[int], None]]):
"""
Gets or sets the motor default settings. These are used by some of the methods listed above, when no explicit argument is given.
### Keyword Arguments
- `speed` - The default speed.
- `max_power` - The default max_power.
- `acceleration` - The default acceleration.
- `deceleration` - The default deceleration.
- `stop` - The default stop argument.
- `pid` - Tuple of p, i, and d. See also pid.
- `stall` - The default stall argument.
### Returns
- If no arguments are given, this returns the current settings.
"""
pass
def pair(self, other_motor: Motor) -> MotorPair:
"""
Pairs this motor to other_motor to create a MotorPair object.
You can only pair two different motors that are not already part of another pair. Both motors must be of the same type.
### Parameters
- `other_motor` - The motor to pair to.
### Returns
- On success, this returns the MotorPair object. It returns False to indicate an incompatible pair or None for other errors.
"""
pass
class MotorPair():
"""
This class can be used to control pairs of motors. You create `MotorPair` objects using the `pair()` method of a `Motor` object.
Control two motors simultaneously in a synchronized way.
"""
def __init__(self):
pass
def id(self) -> int:
pass
def primary(self) -> Motor:
pass
def secondary(self) -> Motor:
pass
def unpair(self) -> bool:
pass
def float(self) -> None:
"""
Floats (coasts) the motor, as if disconnected from the hub.
"""
pass
def brake(self) -> None:
"""
Passively brakes the motor, as if shorting the motor terminals.
"""
pass
def hold(self) -> None:
"""
Actively hold the motor in its current position.
"""
pass
def pwm(self, pwm_0: int, pwm_1: int) -> None:
pass
@overload
def run_at_speed(self, speed_0: int, speed_1: int) -> None:
pass
@overload
def run_at_speed(self, speed_0: int, speed_1: int, max_power: int, acceleration: int, deceleration: int) -> None:
pass
@overload
def run_for_time(self, msec: int) -> None:
pass
@overload
def run_for_time(self, msec: int, speed_0: int, speed_1: int, max_power: int, acceleration: int, deceleration: int, stop: int) -> None:
pass
@overload
def run_for_degrees(self, degrees: int) -> None:
pass
@overload
def run_for_degrees(self, degrees: int, speed_0: int, speed_1: int, max_power: int, acceleration: int, deceleration: int, stop: int) -> None:
pass
@overload
def run_to_position(self, position_0: int, position_1: int) -> None:
pass
@overload
def run_to_position(self, position_0: int, position_1: int, speed: int, max_power: int, acceleration: int, deceleration: int, stop: int) -> None:
pass
def preset(self, position_0: int, position_1: int) -> None:
pass
def callback(self, function: Callable[[int], None]) -> None:
pass
def pid(self, p: int, i: int, d: int) -> None:
pass
class Port():
"""
This class is the blueprint for the port instances in the `hub.port` module. Those instances are automatically instantiated on boot, and further populated when devices are plugged in. You cannot import or instantiate this class manually.
Provides access to port configuration and devices on a port. Some methods and attributes can only be used if the port is in the right mode, as shown below.
Attributes for use with MODE_DEFAULT
- `device`: Powered Up Device on this port. If no device is attached or the port is in a different mode, this attribute is None.
- `motor`: Powered Up Motor on this port. If no motor is attached or the port is in a different mode, this attribute is None.
"""
# motor: Motor
# device: Device
# p5: Pin
# p6: Pin
def __init__(self):
self.motor: Motor
self.device: Device
self.p5: Pin
self.p6: Pin
def info(self) -> dict:
pass
def pwm(self, value: int) -> None:
pass
def callback(self, function: Callable[[int], None]) -> None:
pass
def mode(self, mode: int, baud_rate=2400) -> None:
pass
def baud(self, baud: int) -> None:
pass
def read(self, read: Union[int, any]) -> int:
pass
def write(self, write: bytes) -> int:
pass
A: Port
B: Port
C: Port
D: Port
E: Port
F: Port
# Constants
## Port events
DETACHED = 0
ATTACHED = 1
## Port modes
MODE_DEFAULT = 0
MODE_FULL_DUPLEX = 1
MODE_HALF_DUPLEX = 2
MODE_GPIO = 3

72
hub/sound.py Normal file
View file

@ -0,0 +1,72 @@
from typing import Callable, overload
"""
The sound module lets you control the hub speaker to play sound files and beeps.
"""
@overload
def volume() -> int:
pass
@overload
def volume(volume: int) -> None:
"""
Sets the volume of the speaker.
### Parameters
- volume - Volume between 0 (no sound) and 10 (maximum volume).
### Returns
- If no argument is given, this returns the current volume.
"""
pass
def beep(freq=1000, time=1000, waveform=0) -> None:
"""
Starts beeping with a given frequency, duration, and wave form.
### Keyword Arguments
- `freq` - Frequency of the beep in Hz (100 - 10000).
- `time` - Duration of the beep in milliseconds (0 - 32767).
- `waveform` - Wave form used for the beep. See constants for all possible values.
"""
pass
def play(filename: str, rate=16000) -> None:
"""
Starts playing a sound file.
The sound file must be raw 16 bit data at 16 kHz.
### Parameters
- `filename` - Absolute path to the sound file.
### Keyword Arguments
- `rate` - Playback speed in Hz.
### Raises
- `OSError (ENOENT)` - If the file does not exist.
"""
pass
def callback(self, function: Callable[[int], None]) -> None:
"""
Sets the callback function that is called when a sound finished playing or when it is interrupted.
The function must accept one argument, whose value indicates why the callback was called:
If the value is 0, the sound completed successfully.
If the value is 1, the sound was interrupted.
### Parameters
- `function` - Callable function that takes one argument. Choose None to disable the callback.
"""
pass
#These values are used by the beep() function.
SOUND_SIN = 0 #The beep is a smooth sine wave.
SOUND_SQUARE = 1 #The beep is a loud and raw square wave.
SOUND_TRIANGLE = 2 #The beep has a triangular wave form.
SOUND_SAWTOOTH = 3 #The beep has a sawtooth-shaped wave form.

42
hub/supervision.py Normal file
View file

@ -0,0 +1,42 @@
from typing import Callable
"""
The supervision module lets you monitor critical states of the hub.
"""
def info() -> dict:
"""
Gets status information from the subsystem that supervises the hub.
This returns a dictionary of the form:
```
{
# Checks if the peak current is too high.
'peek_current_too_high': False,
# Checks if the current is too high.
'continous_current_too_high': False,
# The current value in mA.
'continuous_current': 60,
# Checks if the hub temperature is too high.
'temperature_too_high': False
}
```
### Returns
- Supervision status information.
"""
pass
def callback(self, function: Callable[[int], None]) -> None:
"""
Sets the callback function that is called when an over-current event occurs.
The function must accept one argument, which indicates the current in mA that triggered the callback.
### Parameters
- `function` - Callable function that takes one argument. Choose None to disable the callback.
"""
pass