Brick
- class nxt.brick.Brick(sock)
Object connected to a NXT brick.
It provides low level access to brick commands and high level access to internal brick components (file system, modules…). It can be used to create motor or sensor objects.
Create an instance with
nxt.locator.find()
.The
Brick
object implements the context manager interface, so you can use it with thewith
syntax to close the connection when done with it.
Connection Management
- Brick.close()
Disconnect from the NXT brick.
- Return type:
None
You can also use the context manager interface:
with nxt.locator.find() as b:
b.play_tone(440, 1000)
# Here, connection is closed automatically.
Brick Information
- Brick.get_device_info()
Get brick information.
- Returns:
The brick name, Bluetooth address, Bluetooth signal strengths and free user flash.
- Return type:
tuple[str, str, tuple[int, int, int, int], int]
Bluetooth address uses this notation:
00:16:53:xx:xx:xx
, where xx is the brick unique address part (00:16:53 is the LEGO OUI used for the NXT bricks).
- Brick.get_battery_level()
Get brick battery voltage.
- Returns:
Battery voltage in millivolt.
- Return type:
int
- Brick.get_firmware_version()
Get firmware version information.
- Returns:
Protocol and firmware versions, as two tuples with major and minor for each version.
- Return type:
tuple[tuple[int, int], tuple[int, int]]
- Brick.set_brick_name(name)
Set brick name.
- Parameters:
name (str) – New brick name.
- Return type:
None
- Brick.keep_alive()
Reset the brick standby timer.
- Returns:
Sleep timeout in milliseconds.
- Return type:
int
Sound
- Brick.play_tone_and_wait(frequency_hz, duration_ms)
Play a tone and wait until finished.
- Parameters:
frequency_hz (int) – Tone frequency in Hertz.
duration_ms (int) – Tone duration in milliseconds.
- Return type:
None
- Brick.play_sound_file(loop, name)
Play a sound file on the brick.
- Parameters:
loop (bool) – Loop mode, play continuously.
name (str) – Sound file name.
- Return type:
None
- Brick.play_tone(frequency_hz, duration_ms)
Play a tone on the brick, do not wait until finished.
- Parameters:
frequency_hz (int) – Tone frequency in Hertz.
duration_ms (int) – Tone duration in milliseconds.
- Return type:
None
This function do not wait until finished, if you want to play several notes, you may need
play_tone_and_wait()
.
- Brick.stop_sound_playback()
Stop currently running sound file on the brick.
- Return type:
None
Motors and Sensors
- Brick.get_motor(port)
Return a motor object connected to one of the brick output port.
- Brick.get_sensor(port, cls=None, *args, **kwargs)
Return a sensor object connected to one of the brick input port.
- Parameters:
port (Port) – Input port identifier.
cls (Optional[type[nxt.sensor.Sensor]]) – Sensor class, or
None
to autodetect.args (Any) – Additional constructor positional arguments when cls is given.
kwargs (Any) – Additional constructor keyword arguments when cls is given.
- Returns:
A sensor object.
- Raises:
nxt.sensor.digital.SearchError – When sensor can not be identified.
- Return type:
When cls is not given or
None
, try to detect the sensor type and return the correct sensor object. This only works for digital sensors with identification information.For autodetection to work, the module containing the sensor class must be imported at least once. See modules in
nxt.sensor
.
Programs
- Brick.start_program(name)
Start a program on the brick.
- Parameters:
name (str) – Program file name (example:
"myprogram.rxe"
).- Return type:
None
Warning
When starting or stopping a program, the NXT firmware resets every sensors and motors.
- Brick.stop_program()
Stop the running program on the brick.
- Raises:
nxt.error.NoActiveProgramError – When no program is running.
- Return type:
None
Warning
When starting or stopping a program, the NXT firmware resets every sensors and motors.
- Brick.get_current_program_name()
Return name of program currently running on the brick.
- Returns:
Program file name
- Raises:
nxt.error.NoActiveProgramError – When no program is running.
- Return type:
str
File System Access
Brick file system has no directory and file names are not case sensitive.
- Brick.open_file(name, mode='r', size=None, *, buffering=-1, encoding=None, errors=None, newline=None)
Open a file and return a corresponding file-like object.
- Parameters:
name (str) – Name of the file to open.
mode (str) – Specification of open mode.
size (Optional[int]) – For writing, give the final size of the file.
buffering (int) – Buffering control.
encoding (Optional[str]) – Encoding for text mode.
errors (Optional[str]) – Encoding error handling for text mode.
newline (Optional[str]) – Newline handling for text mode.
- Returns:
A file-like object connected to the file on the NXT brick.
- Raises:
nxt.error.FileNotFoundError – When file does not exists.
nxt.error.FileExistsError – When file already exists.
nxt.error.SystemProtocolError – When no space is available.
- Return type:
IOBase
mode is a string which specifies how the file should be open. You can combine several characters to build the specification:
Character
Meaning
‘r’
open for reading (default)
‘w’
open for writing (size must be given)
‘t’
use text mode (default)
‘b’
use binary mode
When writing a file, the NXT brick needs to know the total size when opening the file, so this must be given as parameter.
Other parameters (buffering, encoding, errors and newline) have the same meaning as the standard
open()
function, they must be given as keyword parameters.When encoding is
None
or not given, it defaults toascii
as this is the only encoding understood by the NXT brick.
- Brick.find_files(pattern='*.*')
Find all files matching a pattern.
- Parameters:
pattern (str) – Pattern to match files against.
- Returns:
An iterator on all matching files, returning file name and file size as a tuple.
- Return type:
Iterator[tuple[str, int]]
Accepted patterns are:
*.*
: to match anything (default),<name>.*
: to match files with any extension,*.<extension>
: to match files with given extension,<name>.<extension>
: to match using full name.
- Brick.file_delete(name)
Delete a file on the brick.
- Parameters:
name (str) – File name.
- Returns:
The deleted file name.
- Raises:
nxt.error.FileNotFoundError – When file does not exists.
- Return type:
str
- Brick.delete_user_flash()
Erase the brick user flash.
- Return type:
None
Mailboxes
Mailboxes can be used to exchange messages with the running program.
- Brick.message_write(inbox, message)
Send a message to a brick mailbox.
- Parameters:
inbox (int) – Mailbox number (0 to 19).
message (bytes) – Message to send (58 bytes maximum).
- Return type:
None
- Brick.message_read(remote_inbox, local_inbox, remove)
Read a message from a brick mailbox.
- Parameters:
remote_inbox (int) – Mailbox number (0 to 19).
local_inbox (int) – Local mailbox number, not used by brick.
remove (bool) – Whether to remove the message from the mailbox.
- Returns:
A tuple with the local mailbox number and the read message.
- Raises:
nxt.error.EmptyMailboxError – When mailbox is empty.
nxt.error.NoActiveProgramError – When no program is running.
- Return type:
tuple[int, bytes]
Low Level Modules Access
Low level modules access allows to read and write directly in modules memory. This can be used for example to take a screenshot or to debug the virtual machine. You need to look at the firmware source code for how to use it.
- Brick.find_modules(pattern='*.*')
Find all modules matching a pattern.
- Parameters:
pattern (str) – Pattern to match modules against, use
*.*
(default) to match any module.- Returns:
An iterator on all matching modules, returning module name, identifier, size and IO map size as a tuple.
- Return type:
Iterator[tuple[str, int, int, int]]
- Brick.read_io_map(mod_id, offset, size)
Read module IO map on the brick.
- Parameters:
mod_id (int) – Module identifier.
offset (int) – Offset in IO map.
size (int) – Number of bytes to read.
- Returns:
Module identifier and read data.
- Return type:
tuple[int, bytes]
Module identifier can be found using
find_modules()
. You need to know the structure of the module IO map. You can find it by reading the firmware source code.
- Brick.write_io_map(mod_id, offset, data)
Write module IO map on the brick.
- Parameters:
mod_id (int) – Module identifier.
offset (int) – Offset in IO map.
data (bytes) – Data to write.
- Returns:
Module identifier and written size.
- Return type:
tuple[int, int]
Module identifier can be found using
find_modules()
. You need to know the structure of the module IO map. You can find it by reading the firmware source code.
Low Level Output Ports Methods
These are low level methods, you can use the nxt.motor
module for an
easier interface.
- Brick.set_output_state(port, power, mode, regulation_mode, turn_ratio, run_state, tacho_limit)
Set output port state on the brick.
- Parameters:
port (Port) – Output port identifier.
power (int) – Motor speed or power level (-100 to 100).
mode (Mode) – Motor power mode.
regulation_mode (RegulationMode) – Motor regulation mode.
turn_ratio (int) – Turn ratio (-100 to 100). Negative value shift power to the left motor.
run_state (RunState) – Motor run state.
tacho_limit (int) – Number of degrees the motor should rotate relative to the current position.
- Return type:
None
Warning
This is a low level function, prefer to use
nxt.motor.Motor()
, you can get one fromget_motor()
.
- Brick.get_output_state(port)
Get output port state from the brick.
- Parameters:
port (Port) – Output port identifier.
- Returns:
A tuple with port, power, mode, regulation_mode, turn_ratio, run_state, tacho_limit, tacho_count, block_tacho_count, and rotation_count.
- Return type:
tuple[nxt.motor.Port, int, nxt.motor.Mode, nxt.motor.RegulationMode, int, nxt.motor.RunState, int, int, int, int]
Return value details:
port Output port identifier.
power Motor speed or power level (-100 to 100).
mode Motor power mode.
regulation_mode Motor regulation mode.
turn_ratio Turn ratio (-100 to 100). Negative value shift power to the left motor.
run_state Motor run state.
tacho_limit Number of degrees the motor should rotate.
block_tacho_count Number of degrees the motor rotated relative to the “block” start.
rotation_count Number of degrees the motor rotated relative to the program start.
Warning
This is a low level function, prefer to use
nxt.motor.Motor()
, you can get one fromget_motor()
.
- Brick.reset_motor_position(port, relative)
Reset block or program motor position for a brick output port.
- Parameters:
port (Port) – Output port identifier.
relative (bool) – If
True
, reset block position, ifFalse
, reset program position.
- Return type:
None
Warning
This is a low level function, prefer to use
nxt.motor.Motor()
, you can get one fromget_motor()
.
Low Level Intput Ports Methods
This are low level methods, you can use the nxt.sensor
module for an
easier interface.
- Brick.set_input_mode(port, sensor_type, sensor_mode)
Set input port mode on the brick.
- Parameters:
- Return type:
None
Warning
This is a low level function, prefer to use a
nxt.sensor
class.
- Brick.get_input_values(port)
Get input port values from the brick.
- Parameters:
port (Port) – Input port identifier.
- Returns:
A tuple with port, valid, calibrated, sensor_type, sensor_mode, raw_value, normalized_value, scaled_value, and calibrated_value. rotation_count.
- Return type:
tuple[nxt.sensor.Port, bool, bool, nxt.sensor.Type, nxt.sensor.Mode, int, int, int, int]
Return value details:
port Input port identifier.
valid
True
if the value is valid, elseFalse
.calibrated Always
False
, there is no calibration in NXT firmware.sensor_type Sensor type.
sensor_mode Sensor mode.
raw_value Raw analog to digital converter value.
normalized_value Normalized value.
scaled_value Scaled value.
calibrated_value Always normalized value, there is no calibration in NXT firmware.
Warning
This is a low level function, prefer to use a
nxt.sensor
class.
- Brick.reset_input_scaled_value(port)
Reset scaled value for an input port on the brick.
- Parameters:
port (Port) – Input port identifier.
- Return type:
None
This can be used to reset accumulated value for some sensor modes.
Warning
This is a low level function, prefer to use a
nxt.sensor
class.
- Brick.ls_get_status(port)
Get status of last low-speed transaction to a brick input port.
- Parameters:
port (Port) – Input port identifier.
- Returns:
Number of bytes to read as a result of the transaction.
- Raises:
nxt.error.I2CPendingError – When transaction is still in progress.
nxt.error.DirectProtocolError – When there is an error on the bus.
- Return type:
int
Warning
This is a low level function, prefer to use a
nxt.sensor
class.
- Brick.ls_write(port, tx_data, rx_bytes)
Write data to a brick input port using low speed transaction.
- Parameters:
port (Port) – Input port identifier.
tx_data (bytes) – Data to send.
rx_bytes (int) – Number of bytes to receive.
- Return type:
None
Function returns immediately. Transaction status can be retrieved using
ls_get_status()
and result must be read usingls_read()
.Warning
This is a low level function, prefer to use a
nxt.sensor
class.
- Brick.ls_read(port)
Read result of low speed transaction.
- Parameters:
port (Port) – Input port identifier.
- Returns:
Data received.
- Raises:
nxt.error.I2CPendingError – When transaction is still in progress.
nxt.error.DirectProtocolError – When there is an error on the bus.
- Return type:
bytes
The
ls_write()
function must be called to initiate the transaction.Warning
This is a low level function, prefer to use a
nxt.sensor
class.
Low Level Methods
Do not use these functions unless you know exactly what you are doing.
- Brick.file_open_read(name)
Open file for reading.
- Parameters:
name (str) – File name.
- Returns:
The file handle and the file size.
- Raises:
nxt.error.FileNotFoundError – When file does not exists.
- Return type:
tuple[int, int]
Warning
This is a low level function, prefer to use
open_file()
.
- Brick.file_open_write(name, size)
Open file for writing.
- Parameters:
name (str) – File name.
size (int) – Final file size.
- Returns:
The file handle.
- Raises:
nxt.error.FileExistsError – When file already exists.
nxt.error.SystemProtocolError – When no space is available.
- Return type:
int
Warning
This is a low level function, prefer to use
open_file()
.
- Brick.file_read(handle, size)
Read data from open file.
- Parameters:
handle (int) – Open file handle.
size (int) – Number of bytes to read.
- Returns:
The file handle and the read data.
- Return type:
tuple[int, bytes]
Warning
This is a low level function, prefer to use
open_file()
.
- Brick.file_write(handle, data)
Write data to open file.
- Parameters:
handle (int) – Open file handle.
data (bytes) – Data to write.
- Returns:
The file handle and the number of bytes written.
- Return type:
tuple[int, int]
Warning
This is a low level function, prefer to use
open_file()
.
- Brick.file_close(handle)
Close open file.
- Parameters:
handle (int) – Open file handle.
- Returns:
The closed file handle.
- Return type:
int
Warning
This is a low level function, prefer to use
open_file()
.
- Brick.file_find_first(pattern)
Start finding files matching a pattern.
- Parameters:
pattern (str) – Pattern to match files against.
- Returns:
A handle for the search, first file found name and size.
- Raises:
nxt.error.FileNotFoundError – When no file is found.
- Return type:
tuple[int, str, int]
Warning
This is a low level function, prefer to use
find_files()
.
- Brick.file_find_next(handle)
Continue finding files.
- Parameters:
handle (int) – Handle open with
file_find_first()
.- Returns:
The handle, next file found name and size.
- Raises:
nxt.error.FileNotFoundError – When no more file is found.
- Return type:
tuple[int, str, int]
Warning
This is a low level function, prefer to use
find_files()
.
- Brick.file_open_write_linear(name, size)
Open file for writing, reserve a linear space.
- Parameters:
name (str) – File name.
size (int) – Final file size.
- Returns:
The file handle.
- Raises:
nxt.error.FileExistsError – When file already exists.
nxt.error.SystemProtocolError – When no space is available.
- Return type:
int
Linear space is required for programs, but the brick will automatically use linear mode with
file_open_write()
when extension is.rxe
,.sys
or.rtm
.Warning
This is a low level function, prefer to use
open_file()
.
- Brick.file_open_write_data(name, size)
Open file for writing, using data mode.
- Parameters:
name (str) – File name.
size (int) – Maximum file size.
- Returns:
The file handle.
- Raises:
nxt.error.FileExistsError – When file already exists.
nxt.error.SystemProtocolError – When no space is available.
- Return type:
int
A data file can be written in small chunks, and can grow later. It can be used for data logging.
Warning
This is a low level function, however, there is no support yet for data files in
open_file()
.
- Brick.file_open_append_data(name)
Open file for appending, using data mode.
- Parameters:
name (str) – File name.
- Returns:
The file handle and available size
- Raises:
nxt.error.FileNotFoundError – When file does not exists.
nxt.error.SystemProtocolError – When file is full or file is not a data file.
- Return type:
tuple[int, int]
The file must be a data file. The available size is the size which has not been written to last time the file was open.
Warning
This is a low level function, however, there is no support yet for data files in
open_file()
.
- Brick.module_find_first(pattern)
Start finding modules matching a pattern.
- Parameters:
pattern (str) – Pattern to match modules against.
- Returns:
A handle for the search, first module found name, identifier, size and IO map size.
- Raises:
nxt.error.ModuleNotFoundError – When no module is found.
- Return type:
tuple[int, str, int, int, int]
Warning
This is a low level function, prefer to use
find_modules()
.
- Brick.module_find_next(handle)
Continue finding modules.
- Parameters:
handle (int) – Handle open with
module_find_first()
.- Returns:
The handle, next module found name, identifier, size and IO map size.
- Raises:
nxt.error.ModuleNotFoundError – When no more module is found.
- Return type:
tuple[int, str, int, int, int]
Warning
This is a low level function, prefer to use
find_modules()
.
- Brick.module_close(handle)
Close module search.
- Parameters:
handle (int) – Open module handle.
- Returns:
The closed module handle.
- Return type:
int
Warning
This is a low level function, prefer to use
find_modules()
.
- Brick.poll_command_length(buf_num)
Get number of bytes available in brick poll buffer.
- Parameters:
buf_num (int) – Buffer number, 0 for USB, 1 for high speed.
- Returns:
Buffer number and number of available bytes.
- Return type:
tuple[int, int]
- Brick.poll_command(buf_num, size)
Get bytes from brick poll buffer.
- Parameters:
buf_num (int) – Buffer number, 0 for USB, 1 for high speed.
size (int) – Number of bytes to read.
- Returns:
Buffer number and read bytes.
- Return type:
tuple[int, bytes]
- Brick.boot(*, sure=False)
Erase NXT brick firmware and go to SAM-BA boot mode.
- Parameters:
sure (bool) – Set to
True
if you are really sure. Must be a keyword parameter.- Returns:
Brick response, should be
"Yes\"
.- Return type:
bytes
This only works on USB connection.
Danger
This erases the firmware of the brick, you need to send a new firmware to use it. Sending a firmware is not supported by NXT-Python. You can use the original LEGO software or libnxt for example. Be sure to know what you are doing.
- Brick.bluetooth_factory_reset()
Reset brick Bluetooth to factory settings.
This only works on USB connection.
- Return type:
None