heykube package

Submodules

heykube.heykube module

Defines the HEYKUBE hardware internal structure.

class heykube.heykube.Cube

Bases: object

Define the Cube class.

Hold the model of a 3x3 cube.

apply_moves(moves: Moves) None

Apply a sequence of moves to the current Cube object.

Iterate through the given moves, update the cube’s state based on a predefined rotation table, and maintain a sequence number for tracking the number of moves applied.

Parameters:

moves (Moves) – A sequence of moves to apply to the cube. Each move is representing a rotation or transformation.

Returns:

None

Return type:

NoneType

clear_moves() None

Clear all moves from the device.

Reset the move history of the cube, ensuring that no previous moves are retained in the internal state.

Returns:

None

Return type:

NoneType

decodePerm(lex: int, n: int) List[int]

Decode a cube permutation.

Decode a given permutation value (lex) into a list of indices representing the positions of the pieces in the permutation.

Parameters:
  • lex (int) – The lexicographic index of the permutation to decode.

  • n (int) – The total number of elements in the permutation.

Returns:

A list of integers representing the decoded permutation.

Return type:

List[int]

decode_state(cstate: List[int]) Tuple[bool, List[int], int]

Decode the cube state to reconstruct its configurations.

Take an encoded cube state and reconstruct the cube’s configurations by determining the placement and orientation of edge and corner. Check the validity of the reconstructed state.

Parameters:

cstate (List[int]) – A list of integers representing the encoded cube state.

Returns:

A tuple containing a validity flag, the reconstructed state, and the center orientation.

Return type:

Tuple[bool, List[int], int]

encodePerm(a: List[int]) int

Encode a cube permutation.

Take a list of indices representing a permutation and encode it into a single integer value. The encoding is based on the lexicographic order of the permutations.

Parameters:

a (List[int]) – A list of integers representing the permutation indices.

Returns:

An integer representing the encoded permutation, or -1 if the permutation is invalid.

Return type:

int

encode_state() List[int]

Encode the Cube state to a list of byte.

Encode the current state of the cube into an 11-byte list representation. Calculate the orientation of edges and corners, as well as the permutation of the cube, allowing for a compact representation of the cube’s state.

Returns:

A list of integers representing the encoded cube state.

Return type:

List[int]

get_location_color(cube_index: Facelet | int) Cube_Color

Return the color of the selected cube at the current state.

Retrieve the color corresponding to the specified cube index based on the current state of the cube. The cube index should be an integer representing the position of the facelet or a Facelet object.

Parameters:
  • cube_index – The cube index for which to retrieve the color.

  • cube_index – Facelet or int

Returns:

The color of the specified cube.

Return type:

Cube_Color

get_orientation() Dict

Get the current Cube orientation with UP and FRONT faces.

Retrieve the colors of the UP and FRONT faces of the cube, construct a dictionary to represent the current orientation, and log the orientation.

Returns:

A dictionary containing the colors of the UP and FRONT cube faces, with keys “U” and “F” respectively.

Return type:

Dict

get_piece_color(cube_index: Facelet | int) Cube_Color

Return the color of the selected cube when solved.

Retrieve the color corresponding to the specified cube index based on the solved state of the cube. The cube index should be an integer representing the position of the facelet or a Facelet object.

Parameters:

cube_index – The cube index for which to retrieve the color.

Returns:

The color of the specified cube in the solved position.

Return type:

Cube_Color

get_state() List[int]

Return the current cube state.

Encode the cube’s current configuration into a state representation and return it as a list of integers.

Returns:

A list of integers representing the current state.

Return type:

List[int]

initialize() None

Initialize the state list with default values for a solved cube.

Reset the cube state to the default solved position by setting each element of the state list to its index. Also clear the current move sequence.

Returns:

None

Return type:

NoneType

is_solved() bool

Check if the cube is solved.

Iterate through the cube’s state to verify that each facelet is in its correct position, returning True if all facelets are correctly aligned and False otherwise.

Returns:

True if the cube is solved, False otherwise

Return type:

bool

print_piece_square(val: Facelet | int, label: bool = True) str

Print on console the piece of cube with the color as background.

Generate a string that represents a piece of the cube, with its background color corresponding to the piece’s color in the cube. The piece can also be optionally labeled with its index value.

Parameters:
  • val (Facelet of int) – The index of the cube piece to print.

  • label (bool) – A boolean flag indicating whether to include the piece’s index in the output. Defaults to True.

Returns:

A formatted string with ANSI color codes for console output.

Return type:

str

recover_cstate_data(cstate: List[int]) Tuple[bool, List[int], int, List[int], int, int]

Recover the permutation and orientation from the given cstate.

Decode the cube’s state information, including edge and corner permutations and orientations, from the provided cstate list. Check the validity of the state and returns the relevant data for further processing.

Parameters:

cstate (List[int]) – A list of integers representing the encoded cube state.

Returns:

A tuple containing a validity flag, edge permutation, edge orientation, corner permutation, corner orientation, and center orientation.

Return type:

Tuple[bool, List[int], int, List[int], int, int]

reset_orientation() None

Reset the cube orientation to default reference position.

Reorient the cube based on the color of the facelets, specifically ensuring the white face is oriented correctly and then adjusting the position of the green face as needed.

Returns:

None

Return type:

NoneType

set_state(cstate: List[int]) None

Update the internal Cube state.

Set the cube’s state based on the provided state list, which must contain at least 20 integers. Updates the cube’s internal state, moves, and sequence number if the provided state is valid.

Parameters:

cstate (List[int]) – A list of integers representing the cube’s state.

Returns:

None

Return type:

NoneType

test_match(match: Match) bool

Check if the match corresponds to the current cube’s state.

Compare the current state of the cube with a given match object, checking each facelet color against the expected color in the match. If all matched colors correspond or are set to ‘DontCare’, return True; otherwise, return False.

Parameters:

match (Match) – The match object containing the expected cube state.

Returns:

True if the current state matches match, False otherwise.

Return type:

bool

class heykube.heykube.Cube_Color(value)

Bases: Enum

Enum representing the colors used to define cube faces and a neutral one.

Each color is associated with a unique integer value, which can be used for indexing or other purposes in the cube representation.

Attributes:

White (int): Represents the color white on the cube. Orange (int): Represents the color orange on the cube. Green (int): Represents the color green on the cube. Red (int): Represents the color red on the cube. Blue (int): Represents the color blue on the cube. Yellow (int): Represents the color yellow on the cube. DontCare (int): Represents a neutral color for facelets.

Blue = 4
DontCare = 6
Green = 2
Orange = 1
Red = 3
White = 0
Yellow = 5
class heykube.heykube.Facelet(facelet_name: int | str | None = None)

Bases: object

Define Facelet class.

A HEYKUBE facelet represents an individual colored square on a HEYKUBE face. It serves as a basic unit for cube representation and manipulation.

color() Cube_Color

Return the current Facelet color.

The color is determined by dividing the facelet index by 9, mapping it to the corresponding Cube_Color enumeration.

Returns:

The color of the Facelet as a Cube_Color enum value.

Return type:

Cube_Color

cubie() List[Facelet]

Construct a cubie, an individual small cube piece from the cube.

Generate a list of Facelet objects that make up a cubie based on the current Facelet. A cubie can consist of one, two, or three Facelets, depending on its configuration in the cube.

Returns:

A list of Facelet objects representing the cubie.

Return type:

List[Facelet]

class heykube.heykube.Match(init_set: Cube | str | None = None)

Bases: object

Define the Match class.

Enable HEYKUBE to match with patterns, and provide a notification.

add_cross(face_name: int | str) None

Set the match for the cross on the specified face.

Set the match state to reflect a cross on the face indicated by face_name.Apply first the cross color using add_cross_color, then update the match_state for the specified face’s edge pieces to correspond with the correct color. If invalid face name is provided, log an error message.

Parameters:

face_name (str or int) – The face name to set the cross on.

Returns:

None

Return type:

NoneType

add_cross_color(face_name: int | str) None

Set the match for a cross - but just colors on that face.

Update the match_state to reflect the colors of the cross on the specified face. Identify the color corresponding to the face and apply it to the edge pieces that form the cross. If an invalid face name is provided, log an error message.

Parameters:

face_name (str or int) – The face name to set the cross color on.

Returns:

None

Return type:

NoneType

add_cubie(facelet_name: int | str) None

Add a cubie to the current match state.

Add a cubie (a set of connected facelets) to the current match_state. Based on the provided facelet_name, determine the cubie to which the facelet belongs and update the match state for all the facelets of that cubie with their corresponding colors.

Parameters:

facelet_name (int or str) – The Facelets name in the cubie to add.

Returns:

None

Return type:

NoneType

add_face(face_name: int | str) None

Set the match for the colors on the specified face.

Set the match state for a particular face of the cube based on the face name provided. Assign colors to the corresponding facelets for the given face (U, L, F, R, B, or D). If an invalid face name is provided, log an error message.

Parameters:

face_name (str) – The name of the face to set (U, L, F, R, B, or D).

Returns:

None

Return type:

NoneType

add_face_color(face_name: int | str) None

Set the colors on the specified Facelet.

Set all 9 facelets of a given face to the same color corresponding to the face_name provided. Calculate the index of the face based on the facelet’s color and updates the match state for each facelet in that face. If an invalid face name is provided, log an error message.

Parameters:

face_name (str) – The name of the face to color (U, L, F, R, B, or D).

Returns:

None

Return type:

NoneType

add_facelet(facelet_name: int | str) None

Add a Facelet to the current match state.

Add a single Facelet to the match_state. Based on the provided facelet_name, determine the corresponding Facelet and update its position in the match_state with its color.

Parameters:

facelet_name (int or str) – The name of the Facelet to add.

Returns:

None

Return type:

NoneType

add_layer(face: str = 'U') None

Set the match for the colors on the specified face.

Set the match state for a particular face of the cube, applying the colors to the corresponding facelets based on the face name provided. Call the add_face method to handle the color assignment. The default face is the upper face (“U”).

Parameters:

face (str) – The name of the face to set (default is “U”).

Returns:

None

Return type:

NoneType

add_two_layer(face: str = 'U') None

Set the match for both the face and its adjacent second layer.

Set the match state for a given face and the adjacent second layer of the cube. Call first add_layer to set the colors for the specified face, and then apply the colors to the adjacent layer based on predefined face color sets. If an invalid face name is provided, an error is logged.

Parameters:

face (str) – The name of the face to set (default is “U”).

Returns:

None

Return type:

NoneType

clear() None

Clear the Match object, setting all Facelets to ‘DontCare’.

Reset all 54 facelets in the match_state to DontCare, effectively clearing the match state. Afterward, restore the center pieces of each face to their original colors using restore_center().

Returns:

None

Return type:

NoneType

decode_state(data: bytearray) None

Decode the current state of the cube.

Process a byte array to update the cube’s state based on the encoded color information. The color values are extracted for each face of the cube using bit manipulation, with special handling for the center pieces of each face (which are fixed and not encoded).

Parameters:

data (bytes) – A byte array representing the encoded cube state.

Returns:

None

Return type:

NoneType

encode_state() List[int]

Encode the current state of the cube.

Encode the state of the cube into a list of integers (bytearray). Processe each non-center piece on each face of the cube, applying bit manipulation to pack the cube colors into the list.

Returns:

A list of integers representing the encoded cube state.

Return type:

List[int]

print_piece_square(color_index: Cube_Color) str

Print the color name with the color as background.

Return a string formatted with ANSI escape codes that represents a colored square corresponding to the specified color. Each color has a specific background and text color, making it visually identifiable when printed in a terminal that supports ANSI color codes. If an unknown color index is provided, return a default gray square.

Parameters:

color_index (Cube_Color) – The color index to be printed.

Returns:

A string containing the formatted color representation.

Return type:

str

restore_center() None

Restore the center pieces of the Match object.

Restore the center pieces of each face in the match_state to their original colors. Each face has a fixed center color corresponding to its face index (0 to 5), which this method reassigns.

Returns:

None

Return type:

NoneType

solved() None

Set the match to a fully solved cube.

Set the match_state to represent fully solved cube configuration. Assign the color corresponding to each face to all 9 facelets of that face, ensuring that each of the six faces has its color correctly represented.

Returns:

None

Return type:

NoneType

to_list() List[int]

Convert the Match object to a list of integers.

Convert the match_state of the current Match object into a list of integers, representing the color value of each non-center piece. Skip the center pieces (positions 4, 13, 22, etc.) as they are fixed and not included in the output list.

Returns:

A list of integers representing the color values of the non-center pieces.

Return type:

List[int]

class heykube.heykube.Moves(move_str: str = '')

Bases: object

Define the moves for HEYKUBE.

Translation between cubing notication U|L|F|R|B|D and the HEYKUBE index.

absolute() Moves

Return the reverse moves sequence to reset cube’s orientation.

Generate the reverse of the current move sequence, which would return the cube back to its original orientation. Additionally, set the orientation of the cube such that the “U” (upper) face is white and the “F” (front) face is green.

Returns:

A Moves object with the reverse moves.

Return type:

Moves

add(x: int | str) None

Add the specified move to the current move list.

Append the given move x to the move_list. The move can be represented either as an integer or a string, which corresponds to a move notation or index.

Parameters:

x (Union[int, str]) – The move to add, either as an integer or a string.

Returns:

None

Return type:

NoneType

add_moves(move_str: str | List[str | int]) None

Add moves to the list.

Processe a string or a list of moves and add them to the move_list. Handle both individual moves and groups of moves, allowing for repeated notations (e.g., “2x” or “3x”). The moves are identified either as face rotations or specific indexed moves.

Parameters:

move_str (Union[str, List[Union[int, str]]]) – The move string or list of moves to process. The input can either be a string of moves (e.g., “U R U’”) or a list of moves represented as integers or strings.

Returns:

None

clear() None

Clear the list of moves.

Reset the move list to an empty list, effectively clearing any previously stored moves.

Returns:

None

Return type:

NoneType

from_string(rot_str: str) None

Populate the Moves object from a string representation of moves.

Parse the provided string (rot_str) containing rotation commands and convert them into the corresponding moves. The format of the string should adhere to the defined rotation notations, such as single letters for face turns and optional modifiers for direction (e.g., ‘2’ for double turns, “’” for counter-clockwise). The moves are added to the move_list attribute of the Moves object.

Parameters:

rot_str (str) – The string representation of moves to parse.

Returns:

None

Return type:

NoneType

hints_on_off() None

Set the Moves object to a specific hints on/off sequence.

Clear the current moves and then add a predefined sequence of moves, “R R D D D’ D’ R’ R’”, which is used to toggle hints on or off.

Returns:

None

Return type:

NoneType

pattern_enable() None

Set the Moves object to a specific pattern enable sequence.

Clear the current moves and then add a predefined sequence of moves, “L’ L’ D’ D’ D D L L”, which is used to enable a specific pattern.

Returns:

None

Return type:

NoneType

randomize(num_rot: int) None

Generate a random scramble of moves for the cube.

Create a randomized list of moves with the specified number of rotations (num_rot). Ensure that no two consecutive moves are the inverse of each other. The generated moves are stored in the move_list attribute. The current implementation is a basic randomization and needs to follow the WCA (World Cube Association) scrambling standards.

Parameters:

num_rot (int) – The number of rotations to include in the scramble.

Returns:

None

Return type:

NoneType

reverse() Moves

Reverse the moves.

Convert clockwise to counter-clockwise moves (and vice versa).

Returns:

A Moves object with reversed move sequence.

Return type:

Moves

scramble(num_rot: int) None

Generate a random scramble of moves.

Generate a random sequence of moves for the cube, based on the number of rotations specified by num_rot. Currently use a simple randomization method.

TODO: Update to generate a WCA (World Cube Association)-type scramble.

Parameters:

num_rot (int) – Number of random rotations for the scramble.

Returns:

None

Return type:

NoneType

class heykube.heykube.heykube

Bases: object

Define the HEYKUBE class.

Include ability to connect/disconnect from HEYKUBEs Program lights and sounds Send custom instructions Query the cube state, register for moves and notifications

append_instructions(instr_moves: Moves) None

Append more instructions to the instructions queue.

Add additional instructions to the existing list of instructions.

Parameters:

instr_moves (Moves) – A Moves object that holds the list of moves to be appended.

Returns:

None

Return type:

NoneType

calc_battery_capacity(batt_voltage: int) int

Compute the battery capacity given the battery voltage.

Returns:

The battery capacity

Return type:

int

clear_instructions() None

Clear the instructions queue, return to the internal solver.

Send a command to the HEYKUBE to clear any queued instructions, effectively resetting the instruction state.

Returns:

None

Return type:

NoneType

clear_notify() None

Clear out old notification messages from the queue.

Remove all notifications currently in the notification queue to ensure that only new messages are processed in subsequent operations.

Returns:

None

Return type:

NoneType

connect(device: BLEDevice) bool

Connect to a specified Bluetooth Low Energy (BLE) device.

Parameters:

device (BLEDevice) – A BLEDevice from the bleak library

Returns:

True if the connection was successful, False otherwise.

Return type:

bool

disable_match() None

Disable the match from firing.

Disable the match feature in the HEYKUBE, preventing it from firing until it is explicitly re-enabled.

Returns:

None

Return type:

NoneType

disable_notifications() None

Disable Bluetooth Low Energy notifications from the HEYKUBE device.

Returns:

None

Return type:

NoneType

disable_sounds() None

Disable the sounds during the BTLE connection session.

Returns:

None

Return type:

NoneType

disconnect() bool

Disconnect from the currently connected HEYKUBE device.

Returns:

True if the disconnection was successful, False otherwise.

Return type:

bool

enable_match() None

Enable the match to fire again since it disable after each match.

Re-enable the match functionality in the HEYKUBE. The match feature is automatically disabled after each match, and this method allows it to be fired again.

Returns:

None

Return type:

NoneType

enable_notifications(notify_list: list[str]) None

Register for notifications from HEYKUBE.

Parameters:

notify_list (list[str]) – A list of notification types to subscribe to.

enable_pattern(pattern: int | str) None

Enable instructions for the pattern if HEYKUBE is solved.

Enable a visual pattern on the HEYKUBE, which can be specified either by its index (integer) or by its name (string). If the HEYKUBE is not in a solved state, the pattern will not be enabled.

Parameters:

pattern (Union[int, str]) – The pattern to enable, either as an integer index or a string name. The index must be within the range of available patterns.

Raises:

ValueError – If the provided pattern index is out of range or the pattern name is not found.

Returns:

None

Return type:

NoneType

enable_sounds(major: bool = True, minor: bool = True) None

Reenable HEYKUBE sounds if they were previous disables.

Parameters:
  • major (bool) – enables major tone in sound

  • minor (bool) – enables minor tone in sound

Returns:

None

Return type:

NoneType

flash_all_lights() None

Flash all the LEDs on the HEYKUBE.

Returns:

None

Return type:

NoneType

get_device() BLEDevice

Scan input args and finds a HEYKUBE for connection.

Defines the HEYKUBE connection options

optional arguments:
-h, --help

show this help message and exit

--verbose

increase output verbosity

-n NAME, --name NAME

Directly defines name of a HEYKUBE for connection

-a ADDRESS, --address ADDRESS

Directly defines an HEYKUBE MAC address for connection

-s, --scan

Scans and reports all the available HEYKUBES

-d, --debug

Turns on debug prints

Returns:

The connected device

Return type:

BLEDevice

get_notify() List[str, Any] | None

Get the first notification from the queue.

Check the notification queue for any incoming messages. If a message is present, process and return the status or cube state.

Returns:

List of the notification type and its associated data if a notification is available, otherwise None.

Return type:

List[str, Any] | NoneType

get_pattern_name(index: int) str

Return a pattern name for a given index.

Parameters:

index (int) – A given patter index

Returns:

A pattern name

Return type:

str

get_pattern_names() List[str]

Return all the pattern names.

Returns:

The list of pattern names.

Return type:

List[str]

get_seq_num() int

Read the current sequence number from the cube.

Returns:

The current sequence number.

Return type:

int

get_timestamp() int

Read the current timestamp from the cube.

Returns:

The current timestamp in milliseconds.

Return type:

int

initialize() None

Reset the internal state back to the solved state.

Initialize the internal cube state to the solved state, send the state to the HEYKUBE, and clear any previous moves. Also read the current cube state to ensure synchronization.

Returns:

None

Return type:

NoneType

is_solved() bool

Check if the HEYKUBE is in the solved state.

Reads the current cube state and checks if the HEYKUBE is solved.

Returns:

True is the cube is solved; False, otherwise.

Return type:

bool

light_led(led_index: int) None

Light one of the LEDs on the cube.

Parameters:

led_index (int) – Picks one of 6 faces to light up

Returns:

None

Return type:

NoneType

parse_status_info(status_bytes: List[int]) Dict[str, bool | int]

Parse HEYKUBE status informations.

Extract relevant status information from the provided list of status bytes and return it as a dictionary.

Parameters:

status_bytes (List[int]) – The received status bytes from the HEYKUBE.

Returns:

A dictionary containing parsed status information, including solution state, sequence number, and timestamp.

Return type:

HKStatus

play_sound(select: int = 0) None

Play a sound on the HEYKUBE device.

Parameters:

select – Selects the sound index between 0-7

Returns:

None

Return type:

NoneType

print_cube() None

Read the current state of HEYKUBE and prints it.

Returns:

None

Return type:

NoneType

read_accel() Tuple[str, List[float]]

Return the cube orientation using the on-board 3D accelerometer.

Retrieve the current orientation of the cube by reading the accelerometer data, along with the 3D acceleration vector.

Returns:

A tuple with the upper face and the acceleration vector.

Return type:

Tuple[str, List[float]]

read_battery() Tuple[float | int]

Read the battery status and charging state.

Retrieve the battery voltage and charging status from the HEYKUBE.

Returns:

A tuple containing the battery capacity (float), battery voltage (float), and charging status (int).

Return type:

Tuple[float, float, int]

read_config() List[int]

Read the HEYKUBE configuration.

Retrieve the current configuration settings of the HEYKUBE. The configuration data is returned as a list of integers, each representing a specific configuration parameter.

Returns:

A list of integers representing the HEYKUBE configuration.

Return type:

List[int]

read_cube(field: str) List[int]

Read the value from the specified field and return the response.

Send a read command for the given field and waits for a response from the device. Log the response if received, and time out after 5 seconds then return an empty list in case of a timeout.

Parameters:

field (str) – The field to be read from.

Returns:

The data read from the specified field as a list.

Return type:

List[int]

read_cube_state() Dict[str, int | Moves]

Read the HEYKUBE state.

Retrieve the current state of the HEYKUBE, including the sequence number, moves made, and the timestamp. Update the internal cube state with the information from the cube.

Returns:

A dictionary containing the sequence number, list of moves, and the timestamp.

Return type:

Dict[str, Union[int, Moves]]

read_instructions() Moves

Read out the queued instructions.

Retrieve the list of rotation instructions from the HEYKUBE and process them.

Returns:

Moves containing the list of instructions from queue.

Return type:

Moves

read_last_status() Dict[str, Any] | None

Read the last status from the HEYKUBE.

Retrieve the most recent status event from the HEYKUBE. If no status events are available, return None.

Returns:

dict or None – Returns the most recent status event as a

dictionary, or None if no status events are available.

Return type:

Optional[Dict[str, Any]]

read_moves(prev_seq_num: int | None = None) Dict[str, Moves | float]

Read up to the last 42 moves from the HEYKUBE.

This method retrieves the move data from the HEYKUBE and processes it to form a list of the last moves executed. If a previous sequence number is provided, it will filter the moves to include only those that occurred after that sequence number.

Parameters:

prev_seq_num (Optional[int]) – The previous sequence number to filter moves, if provided.

Returns:

A dictionary containing the sequence number, list of moves, and the timestamp of the last recorded move.

Return type:

Dict[str, Union[Moves, float]]

read_status() List[Dict[str, Any] | None]

Read up to the last 3 status events registered.

Retrieve the last three status events from the HEYKUBE and return them as a list of dictionaries. If there are fewer than three events, only the available events are returned.

Returns:

A list containing up to the last 3 status events, or None if no status events are available.

Return type:

List[Optional[Dict[str, Any]]]

read_version() Dict[str, bool | str]

Read the current software version of the HEYKUBE.

Retrieve the current version information from the HEYKUBE, including version number, battery status, motion status, and other configurations. Log also relevant information about the HEYKUBE’s state.

Returns:

A dictionary containing various HEYKUBE information.

Return type:

Dict[str, Union[bool, str]]

send_hint(index: int) None

Play a hint on the faces.

Parameters:

index (int.) – Picks one of 6 faces to light up

Returns:

None

Return type:

NoneType

send_prompt(index: int) None

Flash the LEDs on the HEYKUBE, typically when the cube is solved.

Parameters:

index (int) – The index to determine the LED flash pattern (0-5).

Returns:

None

Return type:

NoneType

set_match(match: Match, enable: bool = True) None

Set the match configuration from the provided Match object.

Allow the user to define the match settings, specifying whether to enable or disable the match.

Parameters:
  • match (Match) – The Match object containing the match settings.

  • enable (bool) – Flag to enable or disable the match (default is True).

Returns:

None

Return type:

NoneType

software_reset() None

Issue a software reset through BTLE.

Send a predefined action sequence to the HEYKUBE to initiate a software reset.

Returns:

None

Return type:

NoneType

turn_hints_off() None

Turn hints off on HEYKUBE - they will return once solved.

Returns:

None

Return type:

NoneType

turn_hints_on() None

Turn HEYKUBE hints back on.

Returns:

None

Return type:

NoneType

turn_off_led() None

Turn off all the LEDs on the HEYKUBE.

Returns:

None

Return type:

NoneType

wait(timeout: int = 10) None

Wait for specified time.

Parameters:

timeout (int) – Duration to wait in seconds. Default is 10 seconds.

Returns:

None:

Return type:

NoneType

wait_for_cube_state(prev_seq_num: int | None = None, timeout: int = 10) Tuple[int, dict]

Wait for events from the HEYKUBE.

Listen for notifications regarding the cube’s state and collect move information. If the specified timeout elapses without receiving an event, the method will exit.

Parameters:
  • prev_seq_num (Optional[int]) – The previous sequence number to calculate the number of moves. Defaults to None.

  • timeout (int.) – Specifies the timeout duration in seconds

Returns:

Number of Moves and a dictionary with notifications events.

Return type:

Tuple[int, dict]

wait_for_notify(prev_seq_num: int | None = None, timeout: float = 10) tuple[int, dict]

Wait for events from the HEYKUBE.

Listen for notifications from the HEYKUBE device, including status updates. A timeout mechanism is included to exit the method if no event is received within the specified time.

Parameters:
  • prev_seq_num (Optional[int]) – The previous sequence number to calculate the number of moves (default is None).

  • timeout (float) – Specifies the timeout duration in seconds.

Returns:

Tuple containing the number of new moves and a dict with notification events. Returns (0, {}) if nothing was received.

Return type:

tuple[int, dict]

write_cube(field: str, data: bytes, wait_for_response: bool = True) None

Send a write command to update the specified field with data.

Add a write command to the command queue, sending the specified data to the given field. The optional parameter determines whether to wait for a response after sending the command.

Parameters:
  • field (str) – The field to which the data will be written.

  • data (bytes) – The data to be written to the field.

  • wait_for_response (bool, optional) – Indicates whether to wait for a response.

Returns:

None

Return type:

NoneType

write_cube_state(state: List[int]) None

Override the internal cube state – expert only.

Parameters:

state (List[int]) – The state to set for the cube.

Returns:

None

Return type:

NoneType

write_instructions(instr_moves: Moves, append: bool = False) None

Send a custom list of instructions to the HEYKUBE.

Parameters:
  • instr_moves (Moves) – A Moves object that holds the moves to be sent.

  • append (bool, optional) – If True, append instructions to the existing list; otherwise, overwrite the current instructions.

Raises:

ValueError – If the number of instructions exceeds max limit.

Returns:

None

Return type:

NoneType

heykube.heykube_btle module

Create a HEYKUBE BTLE connectivity class.

Classes:

heykube_btle

class heykube.heykube_btle.heykube_btle

Bases: object

This class manage HEYKUBE BTLE connectivity using Bleak module.

Extend the heykube class.

Variables:
  • logger – object’s prompt logger named heykube_btle

  • client – Bleak Client to manage Bluetooth Low Energy devices

  • connected – Device connection status

  • disconnected – Device disconnection status

  • reconnected – Device reconnection status

  • connected_device – connected Bluetooth Low Energy device

  • cmd_queue – Queue to manage commands

  • read_queue

  • notify_queue

  • device – NOT USED

  • addr – NOT USED

  • heykube_uuid – Device UUID

  • char_uuid – Characterics UUID

  • char_handles – Notifications to handle

  • disconnect_reasons – Reason of device disconnection

  • scan_devices – List of scanned devices

  • loop – event loop to manage Bluetooth and set up the BLEAK client

async cleanup() None

Clean up resources and disconnect the client if connected.

Log a cleanup message and disconnects the client from any active connections if the client is initialized.

Returns:

None

Return type:

NoneType

client: BleakClient = None
async comms_manager() None

Manage communication with HEYKUBE devices.

Checks continuously for commands related to connecting, reading, writing, subscribing, and unsubscribing to characteristics of the HEYKUBE devices. Handle reconnection, logging events, and ensuring communication integrity.

The following commands can be processed: - “disconnect”: Disconnects the client from the device. - “read”: Reads characteristics from the device. - “write”: Writes data to the device. - “subscribe”: Subscribes to notifications from the device. - “unsubscribe”: Unsubscribes from notifications from the device.

Returns:

None

Return type:

NoneType

connect(device: BLEDevice, timeout: int = 10) bool

Connect to a HEYKUBE.

Parameters:
  • device (keykube) – HEYKUBE device

  • timeout – connection time-out in seconds

  • timeout – float

Returns:

The connection status, True if connected, False otherwise.

Return type:

bool

async connection_manager() None

Manage the connection to the HEYKUBE device.

Monitor continuously the connection status. If disconnected, attempt a reconnection to the HEYKUBE device. Keep track of connection retries and log relevant events. Handle the first connection separately from reconnections to ensure appropriate notifications are sent.

Returns:

None

Return type:

NoneType

connection_thread(device: BLEDevice) None

Establish a connection to a specified Bluetooth device.

Create a new event loop for managing Bluetooth connections and set up the BLEAK client. Start both the connection manager and communication manager concurrently and run until they complete. After the connection process is finished, log the closure of the connection and clears the command queue.

Parameters:

device (BLEDevice) – The Bluetooth device to connect to.

Returns:

None

Return type:

NoneType

disconnect() None

Disconnect from the BTLE client and terminate the connection thread.

Send a disconnect command to the command queue and waits for the connection thread to finish. It also logs the disconnection status and confirms when the thread has successfully ended.

Returns:

None

Return type:

NoneType

get_device(args) BLEDevice | None

Retrieve the device object based on the input arguments provided.

Scan for available HEYKUBE devices and returns the matching device based on the provided arguments, such as name or address. If no matching device is found, log warnings or prompts user to wake up the devices.

Parameters:

args (argparse.Namespace) – Arguments used to specify the HEYKUBE device.

Returns:

The connected device object or None if not found.

Return type:

BLEDevice or None

is_connected() bool

Return the client’s connection status.

Check if the client is currently connected and returns a boolean indicating the connection status.

Returns:

The connection status of the client.

Return type:

bool

notification_handler(sender: str | int, data: list | bytearray) None

Handle notifications from the Heykube BTLE device.

Invoked when a notification is received from the device. Process the notification by determining the sender and placing the data in a queue for further processing. If the sender is part of the known characteristic handles, associate the data with the corresponding field.

Parameters:
  • sender (str or int) – The notification sender’s identifier, which can be a string or an integer. If a string, it attempts to extract a hexadecimal characteristic ID.

  • data (bytes or list) – Data received in the notification, typically a byte array.

Raises:

Exception – If an error occurs while processing, log the exception and handles the error gracefully.

Returns:

None

Return type:

NoneType

on_disconnect(client: BleakClient)

Handle disconnection from the Bluetooth device.

Invoked when the BLEAK client is disconnected from the HEYKUBE device. Set the connection status to False and print a message indicating the disconnection.

Parameters:

client (BleakClient) – The BLEAK client instance that has disconnected.

Returns:

None

Return type:

NoneType

parse_args() tuple

Parse command line arguments for the HEYKUBE connection interface.

Set up an argument parser for the HEYKUBE connection options, including verbosity, device name, address, scanning, debugging, and devboard mode. Return the parsed arguments and any unknown arguments provided during execution.

Returns:

A tuple containing the known and unknown arguments.

Return type:

tuple

read_cube(field: str) List[int]

Read the value from the specified field and return the response.

Send a read command for the given field and waits for a response from the device. Log the response if received, and time out after 5 seconds then return an empty list in case of a timeout.

Parameters:

field (str) – The field to be read from.

Returns:

The data read from the specified field as a list.

Return type:

List[int]

scan(timeout: float = 5.0) List[str]

Scan for available HEYKUBE devices.

Initiates a scan for HEYKUBE devices and runs the scan for the specified timeout period. Return a list of devices discovered during the scan.

Parameters:

timeout (float) – The duration for which the scan will run, in seconds. Default is 5.0 seconds.

Returns:

A list of discovered HEYKUBE devices.

Return type:

List[str]

async scan_run() None

Perform an asynchronous BTLE scan for available HEYKUBE devices.

Clear any previously scanned devices and discover new devices using the BleakScanner. Log the name, address, and RSSI of HEYKUBE devices found during the scan.

Returns:

None

Return type:

NoneType

subscribe(field: str) None

Subscribe to notifications for a specified field.

Add a subscribe command to the command queue, indicating that notifications should be received for the specified field.

Parameters:

field (str) – The field to which notifications will be subscribed.

Returns:

None

Return type:

NoneType

unsubscribe(field: str) None

Unsubscribe from notifications for a specified field.

Add an unsubscribe command to the command queue, indicating that notifications for the specified field should no longer be received.

Parameters:

field (str) – The field from which notifications will be unsubscribed.

Returns:

None

Return type:

NoneType

write_cube(field: str, data: bytes, wait_for_response: bool = True) None

Send a write command to update the specified field with data.

Add a write command to the command queue, sending the specified data to the given field. The optional parameter determines whether to wait for a response after sending the command.

Parameters:
  • field (str) – The field to which the data will be written.

  • data (bytes) – The data to be written to the field.

  • wait_for_response (bool, optional) – Indicates whether to wait for a response.

Returns:

None

Return type:

NoneType

Module contents