Safe Haskell | None |
---|---|
Language | Haskell2010 |
This module defines an interface over Bluetooth to a NXT brick as defined in Lego Mindstorms NXT Bluetooth Developer Kit, Appendix 1 - Communication protocol and Appendix 2 - Direct commands. It also defines some additional functions not available directly otherwise.
- withNXT :: FilePath -> NXT a -> IO a
- defaultDevice :: FilePath
- setOutputState :: OutputPort -> OutputPower -> [OutputMode] -> RegulationMode -> TurnRatio -> RunState -> TachoLimit -> NXT ()
- setOutputStateConfirm :: OutputPort -> OutputPower -> [OutputMode] -> RegulationMode -> TurnRatio -> RunState -> TachoLimit -> NXT ()
- getOutputState :: OutputPort -> NXT OutputState
- resetMotorPosition :: OutputPort -> MotorReset -> NXT ()
- setInputMode :: InputPort -> SensorType -> SensorMode -> NXT ()
- setInputModeConfirm :: InputPort -> SensorType -> SensorMode -> NXT ()
- getInputValues :: InputPort -> NXT InputValue
- resetInputScaledValue :: InputPort -> NXT ()
- getVersion :: NXT Version
- getDeviceInfo :: NXT DeviceInfo
- getBatteryLevel :: NXT Voltage
- isBatteryRechargeable :: NXT Bool
- keepAlive :: NXT ()
- keepAliveConfirm :: NXT ()
- getSleepTimeout :: NXT Duration
- getLastKeepAliveTime :: NXT (Maybe POSIXTime)
- stopEverything :: NXT ()
- shutdown :: NXT ()
- startProgram :: FileName -> NXT ()
- startProgramConfirm :: FileName -> NXT ()
- stopProgram :: NXT ()
- stopProgramConfirm :: NXT ()
- stopProgramExisting :: NXT ()
- ensureStartProgram :: FileName -> NXT ()
- getCurrentProgramName :: NXT (Maybe String)
- messageWrite :: Inbox -> String -> NXT ()
- messageWriteConfirm :: Inbox -> String -> NXT ()
- messageRead :: RemoteInbox -> RemoveMessage -> NXT String
- maybeMessageRead :: RemoteInbox -> RemoveMessage -> NXT (Maybe String)
- ensureMessageRead :: RemoteInbox -> RemoveMessage -> NXT String
- playSoundFile :: LoopPlayback -> FileName -> NXT ()
- playSoundFileConfirm :: LoopPlayback -> FileName -> NXT ()
- playTone :: Frequency -> Duration -> NXT ()
- stopSoundPlayback :: NXT ()
- stopSoundPlaybackConfirm :: NXT ()
- lowspeedGetStatus :: InputPort -> NXT Int
- lowspeedWrite :: InputPort -> RxDataLength -> TxData -> NXT ()
- lowspeedWriteConfirm :: InputPort -> RxDataLength -> TxData -> NXT ()
- lowspeedRead :: InputPort -> NXT RxData
- openWrite :: FileName -> FileSize -> NXT FileHandle
- openWriteLinear :: FileName -> FileSize -> NXT FileHandle
- write :: FileHandle -> FileData -> NXT ()
- writeConfirm :: FileHandle -> FileData -> NXT ()
- close :: FileHandle -> NXT ()
- closeConfirm :: FileHandle -> NXT ()
- delete :: FileName -> NXT ()
- deleteConfirm :: FileName -> NXT ()
- deleteExisting :: FileName -> NXT ()
- getModuleID :: ModuleName -> NXT (Maybe ModuleID)
- listModules :: ModuleName -> NXT [ModuleInfo]
- requestFirstModule :: ModuleName -> NXT (ModuleHandle, Maybe ModuleInfo)
- requestNextModule :: ModuleHandle -> NXT (ModuleHandle, Maybe ModuleInfo)
- closeModuleHandle :: ModuleHandle -> NXT ()
- closeModuleHandleConfirm :: ModuleHandle -> NXT ()
- readIOMap :: ModuleID -> IOMapOffset -> IOMapLength -> NXT IOMapData
- writeIOMap :: ModuleID -> IOMapOffset -> IOMapData -> NXT ()
- writeIOMapConfirm :: ModuleID -> IOMapOffset -> IOMapData -> NXT ()
- initialize :: FilePath -> IO NXTInternals
- terminate :: NXTInternals -> IO ()
- runNXT :: NXT a -> NXTInternals -> IO (a, NXTInternals)
- execNXT :: NXT a -> NXTInternals -> IO NXTInternals
- bluetoothRSSI :: NXT Int
- bluetoothLinkQuality :: NXT Int
- data NXT a
- data Version = Version FirmwareVersion ProtocolVersion
- data FirmwareVersion = FirmwareVersion Major Minor
- data ProtocolVersion = ProtocolVersion Major Minor
- type Major = Int
- type Minor = Int
- data DeviceInfo = DeviceInfo Name BTAddress BTStrength FlashFree
- type Name = String
- type BTAddress = String
- type BTStrength = Int64
- type FlashFree = Int64
- data OutputState = OutputState OutputPort OutputPower [OutputMode] RegulationMode TurnRatio RunState TachoLimit TachoCount BlockTachoCount RotationCount
- data OutputPort
- type OutputPower = Int
- data OutputMode
- data RegulationMode
- type TurnRatio = Int
- data RunState
- type TachoLimit = Int64
- type TachoCount = Int64
- type BlockTachoCount = Int64
- type RotationCount = Int64
- data MotorReset
- data InputPort
- data InputValue = InputValue InputPort Valid Calibrated SensorType SensorMode RawADValue NormalizedADValue ScaledValue CalibratedValue
- type Valid = Bool
- type Calibrated = Bool
- data SensorType
- data SensorMode
- type RawADValue = Int
- type NormalizedADValue = Int
- type ScaledValue = Int
- type CalibratedValue = Int
- type Voltage = Ratio Int
- type Duration = NominalDiffTime
- data Inbox
- data RemoteInbox
- type RemoveMessage = Bool
- type LoopPlayback = Bool
- type Frequency = Int
- type RxDataLength = Int
- type TxData = [Word8]
- type RxData = [Word8]
- type DeviceAddress = Word8
- type Command = Word8
- type Measurement = Int
- type FileName = String
- type FileSize = Int
- type FileHandle = Int
- type FileData = [Word8]
- data ModuleInfo = ModuleInfo ModuleName ModuleID ModuleSize ModuleIOMapSize
- type ModuleName = String
- type ModuleID = Int64
- type ModuleSize = Int64
- type ModuleIOMapSize = Int
- type ModuleHandle = Int
- type IOMapOffset = Int
- type IOMapLength = Int
- type IOMapData = [Word8]
- data TimeoutException = TimoutException
- data NXTInternals
- data NXTException = NXTException String
Initialization
withNXT :: FilePath -> NXT a -> IO a Source
Function which initializes and terminates Bluetooth connection to the NXT brick (using initialize
and terminate
) and in-between
runs given computation. It terminates Bluetooth connection on an exception, too, rethrowing it afterwards.
defaultDevice :: FilePath Source
Default Bluetooth serial device filename for current operating system. Currently always /dev/rfcomm0
.
Motors
setOutputState :: OutputPort -> OutputPower -> [OutputMode] -> RegulationMode -> TurnRatio -> RunState -> TachoLimit -> NXT () Source
Sets output port (motor) state. This is the main function for controlling a motor.
setOutputStateConfirm :: OutputPort -> OutputPower -> [OutputMode] -> RegulationMode -> TurnRatio -> RunState -> TachoLimit -> NXT () Source
Same as setOutputState
but also request a confirmation. Useful to assure the command was really accepted. In a case of an error
it throws a NXTException
.
Confirmation requires a change of the direction of NXT Bluetooth communication which takes around 30 ms.
getOutputState :: OutputPort -> NXT OutputState Source
Gets output port (motor) current state. In additional to values used with setOutputState
also TachoCount
, BlockTachoCount
and RotationCount
values are available which tell you current position of a motor.
resetMotorPosition :: OutputPort -> MotorReset -> NXT () Source
Resets one of three position counters for a given output port.
Sensors
setInputMode :: InputPort -> SensorType -> SensorMode -> NXT () Source
Sets input port (sensor) type and mode.
setInputModeConfirm :: InputPort -> SensorType -> SensorMode -> NXT () Source
Same as setInputMode
but also request a confirmation. Useful to assure the command was really accepted. In a case of an error it throws a NXTException
.
Confirmation requires a change of the direction of NXT Bluetooth communication which takes around 30 ms.
getInputValues :: InputPort -> NXT InputValue Source
Gets input port (sensor) values. This is the main function for reading a sensor.
resetInputScaledValue :: InputPort -> NXT () Source
Resets input port (sensor) scaled value.
Miscellaneous
getVersion :: NXT Version Source
Gets firmware and protocol versions of the NXT brick.
getDeviceInfo :: NXT DeviceInfo Source
Gets device (the NXT brick) information: name, Bluetooth 48 bit address in the string format, strength of Bluetooth signal (not implemented in
current NXT firmware versions, use bluetoothRSSI
or bluetoothLinkQuality
as an alternative), free space on flash.
getBatteryLevel :: NXT Voltage Source
Gets current battery level (in volts).
isBatteryRechargeable :: NXT Bool Source
Is battery used in the NXT brick rechargeable?
Sends a keep alive (turned on) packet. It prevents the NXT brick from automatically powering off. Other commands do not prevent that from hapenning so it is useful to send this packet from time to time if you want to prevent powering off.
keepAliveConfirm :: NXT () Source
Same as keepAlive
but also request a confirmation. Useful to assure the command was really accepted. In a case of an error it
throws a NXTException
.
Confirmation requires a change of the direction of NXT Bluetooth communication which takes around 30 ms.
getSleepTimeout :: NXT Duration Source
Gets current sleep timeout setting (in seconds) after which the NXT brick automatically powers off if
not prevented with a keep alive packet (use keepAlive
to send one). This setting is cached.
getLastKeepAliveTime :: NXT (Maybe POSIXTime) Source
When was a last keep alive packet send?
stopEverything :: NXT () Source
Helper function which stops all NXT brick activities: stops motors and disables sensors.
Shutdowns (powers off) the NXT brick. You have to manually turn it on again.
Remote Programs
It is possible to remotely run and control (with messages) programs on the NXT brick. Those here are low-level functions but check also high-level Robotics.NXT.Remote and Robotics.NXT.MotorControl modules.
startProgram :: FileName -> NXT () Source
Starts a given program on the NXT brick.
startProgramConfirm :: FileName -> NXT () Source
Same as startProgram
but also request a confirmation. Useful to assure the command was really accepted, but this does not assure
that the program has really started successfully (especially not that it is already running when the confirmation is received).
Use ensureStartProgram
for that. In a case of an error it throws a NXTException
.
Confirmation requires a change of the direction of NXT Bluetooth communication which takes around 30 ms.
stopProgram :: NXT () Source
Stops a currently running program.
stopProgramConfirm :: NXT () Source
Same as stopProgram
but also request a confirmation. Useful to assure the command was really accepted. In a case of an error it
throws a NXTException
.
Confirmation requires a change of the direction of NXT Bluetooth communication which takes around 30 ms.
stopProgramExisting :: NXT () Source
Same as stopProgramConfirm
but it also requires that the program was really running. It throws a NXTException
otherwise.
ensureStartProgram :: FileName -> NXT () Source
Helper function which first ensures that no other program is running and then ensures that a given program is really running before it returns.
getCurrentProgramName :: NXT (Maybe String) Source
Gets the name of the currently running program, if any.
Messages
It is possible to control programs on the NXT brick with messages. Those here are low-level functions but check also high-level Robotics.NXT.Remote and Robotics.NXT.MotorControl modules.
messageWrite :: Inbox -> String -> NXT () Source
Writes a message to the given inbox queue of the running remote program. A message length is limited to 58 characters/bytes. A queue is limited to 5 messages.
messageWriteConfirm :: Inbox -> String -> NXT () Source
Same as messageWrite
but also request a confirmation. Useful to assure the command was really accepted. In a case of an error it
throws a NXTException
.
Confirmation requires a change of the direction of NXT Bluetooth communication which takes around 30 ms.
messageRead :: RemoteInbox -> RemoveMessage -> NXT String Source
Reads a message from the currently running program from a given remote inbox queue. A queue is limited to 5 messages.
It throws a NXTException
if there is no message in a remote inbox queue.
maybeMessageRead :: RemoteInbox -> RemoveMessage -> NXT (Maybe String) Source
Same as messageWrite
but returns Nothing
if there is no message in a given remote inbox queue.
ensureMessageRead :: RemoteInbox -> RemoveMessage -> NXT String Source
Same as messageWrite
but if there is no message in a given remote inbox queue it retries until there is.
Sounds
playSoundFile :: LoopPlayback -> FileName -> NXT () Source
Plays a given sound file.
playSoundFileConfirm :: LoopPlayback -> FileName -> NXT () Source
Same as playSoundFile
but also request a confirmation. Useful to assure the command was really accepted. In a case of an error it
throws a NXTException
.
Confirmation requires a change of the direction of NXT Bluetooth communication which takes around 30 ms.
playTone :: Frequency -> Duration -> NXT () Source
Plays a tone with a given frequency (in hertz) for a given duration (in seconds).
stopSoundPlayback :: NXT () Source
Stops current sound file playback.
stopSoundPlaybackConfirm :: NXT () Source
Same as stopSoundPlayback
but also request a confirmation. Useful to assure the command was really accepted. In a case of an
error it throws a NXTException
.
Confirmation requires a change of the direction of NXT Bluetooth communication which takes around 30 ms.
Low Speed (I2C)
With those low-level functions it is possible to communicate with digital sensors attached to the NXT brick. But check also high-level Robotics.NXT.Sensor.Ultrasonic and Robotics.NXT.Sensor.Compass modules.
lowspeedGetStatus :: InputPort -> NXT Int Source
Gets number of bytes available to read.
lowspeedWrite :: InputPort -> RxDataLength -> TxData -> NXT () Source
Writes data. At most 16 bytes can be written at a time.
Reply data length must be specified in the write command since reading from the device is done on a master-slave basis.
lowspeedWriteConfirm :: InputPort -> RxDataLength -> TxData -> NXT () Source
Same as lowspeedWrite
but also request a confirmation. Useful to assure the command was really accepted. In a case of an
error it throws a NXTException
.
Confirmation requires a change of the direction of NXT Bluetooth communication which takes around 30 ms.
lowspeedRead :: InputPort -> NXT RxData Source
Reads data. The protocol does not support variable-length return packages so the response always contains 16 data bytes with invalid data padded with zeros.
Filesystem
openWrite :: FileName -> FileSize -> NXT FileHandle Source
Opens a given file for writing as a linked list of flash sectors.
openWriteLinear :: FileName -> FileSize -> NXT FileHandle Source
Opens a given file for writing as a linear contiguous block of flash memory (required for user programs and certain data files).
write :: FileHandle -> FileData -> NXT () Source
Writes data to a file. At most 61 bytes can be written at a time.
writeConfirm :: FileHandle -> FileData -> NXT () Source
Same as write
but also request a confirmation. Useful to assure the command was really accepted. In a case of an error it
throws a NXTException
.
Confirmation requires a change of the direction of NXT Bluetooth communication which takes around 30 ms.
close :: FileHandle -> NXT () Source
Closes a file.
closeConfirm :: FileHandle -> NXT () Source
Same as close
but also request a confirmation. Useful to assure the command was really accepted. In a case of an error it
throws a NXTException
.
Confirmation requires a change of the direction of NXT Bluetooth communication which takes around 30 ms.
deleteConfirm :: FileName -> NXT () Source
Same as delete
but also request a confirmation. Useful to assure the command was really accepted. In a case of an error it throws
a NXTException
.
Confirmation requires a change of the direction of NXT Bluetooth communication which takes around 30 ms.
deleteExisting :: FileName -> NXT () Source
Same as deleteConfirm
but it also requires that the file exists before deletion. It throws a NXTException
otherwise.
IO Map
Interface to NXT firmware is based on internal IO map interface. All commands are in fact just pretty wrappers to this interface, but it is possible to use it directly and thus gain some additional possibilities which are not available otherwise (some of those are already wrapped in this interface's additional functions and feel free to suggest more if you need them).
getModuleID :: ModuleName -> NXT (Maybe ModuleID) Source
Helper function to get an ID of a module matching a given module name. Each module encompass some firmware functionality. Function caches IDs so it hopefully retrieves it from a cache of previous requests.
listModules :: ModuleName -> NXT [ModuleInfo] Source
Helper function to get information about all modules matching a given module name (which can be a wild card).
requestFirstModule :: ModuleName -> NXT (ModuleHandle, Maybe ModuleInfo) Source
Requests information about the first module matching a given module name (which can be a wild card). Returned module handle can be used for followup requests and has to be closed when not needed anymore.
requestNextModule :: ModuleHandle -> NXT (ModuleHandle, Maybe ModuleInfo) Source
Requests information about the next module matching previously requested module name (which can be a wild card). Returned module handle can be used for followup requests and has to be closed when not needed anymore.
closeModuleHandle :: ModuleHandle -> NXT () Source
Closes module handle of previously requested module information.
closeModuleHandleConfirm :: ModuleHandle -> NXT () Source
Same as closeModuleHandle
but also request a confirmation. Useful to assure the command was really accepted. In a case of an
error it throws a NXTException
.
Confirmation requires a change of the direction of NXT Bluetooth communication which takes around 30 ms.
readIOMap :: ModuleID -> IOMapOffset -> IOMapLength -> NXT IOMapData Source
Reads data from an IO map of a given module. At most 119 bytes can be read at a time.
You probably have to know what different values at different positions mean and control. The best way is to check NXT firmware source code.
writeIOMap :: ModuleID -> IOMapOffset -> IOMapData -> NXT () Source
Writes data to an IO map of a given module. At most 54 bytes can be written at a time.
You probably have to know what different values at different positions mean and control. The best way is to check NXT firmware source code.
writeIOMapConfirm :: ModuleID -> IOMapOffset -> IOMapData -> NXT () Source
Same as writeIOMap
but also request a confirmation. Useful to assure the command was really accepted. In a case of an error
it throws a NXTException
.
Confirmation requires a change of the direction of NXT Bluetooth communication which takes around 30 ms.
Internals
Be careful when using those functions as you have to assure your program is well-behaved: you should see NXTInternals
as a
token you have to pass around in order, not reusing or copying values. (The only exception is that you can reuse the token
initally returned by initialize
in terminate
call, even if you have used it in-between.) They are exposed so that you can
decouple initalization, execution and termination phase. If you do not need that use withNXT
.
initialize :: FilePath -> IO NXTInternals Source
Opens and intializes a Bluetooth serial device communication.
terminate :: NXTInternals -> IO () Source
Stops all NXT activities (by calling stopEverything
) and closes the Bluetooth serial device communication. NXTInternals
token must not
be used after that anymore.
runNXT :: NXT a -> NXTInternals -> IO (a, NXTInternals) Source
Runs a computation in a context of a given NXTInternals
token, returning a value and a new token.
execNXT :: NXT a -> NXTInternals -> IO NXTInternals Source
Runs a computation in a context of a given NXTInternals
token, returning just a new token.
Bluetooth utils
getDeviceInfo
returns zero for Bluetooth signal strength as this is not implemented in current NXT firmware versions.
Here are functions which retrieve that from a host (computer) Bluetooth stack.
bluetoothRSSI :: NXT Int Source
Gets received signal strength indicator (RSSI) of the Bluetooth connection to the NXT brick.
Currently supported only on Linux. It throws a NXTException
otherwise.
bluetoothLinkQuality :: NXT Int Source
Gets link quality of the Bluetooth connection to the NXT brick.
Currently supported only on Linux. It throws a NXTException
otherwise.
Types
Monad which encompasses interface to the NXT brick.
The format of version is "major.minor". To format it use
.printf
"%d.%02d" major minor
data FirmwareVersion Source
data ProtocolVersion Source
data DeviceInfo Source
type BTStrength = Int64 Source
Strength of the Bluetooth signal. Not implemented in current NXT firmware versions. Use bluetoothRSSI
or bluetoothLinkQuality
as an alternative.
data OutputState Source
data OutputPort Source
type OutputPower = Int Source
Power and direction. In [-100, 100] range.
data OutputMode Source
data RegulationMode Source
RegulationModeIdle | Disables regulation. |
RegulationModeMotorSpeed | Auto adjust PWM duty cycle if motor is affected by physical load. Really works only if there is room for that (not that motor is already running at the maximum power). |
RegulationModeMotorSync | Attempts to keep rotation in sync with another motor that has this set. Also involves turn ratio. |
In regulated synced mode the difference between two motors. In [-100, 100] range.
MotorRunStateIdle | Disables power to motor. |
MotorRunStateRampUp | Ramping to a new speed set-point that is greater than the current speed set-point. |
MotorRunStateRunning | Enables power to motor. |
MotorRunStateRampDown | Ramping to a new speed set-point that is less than the current speed set-point. |
MotorRunStateHold | Hold at the current position. |
type TachoLimit = Int64 Source
Target tacho limit for a motor movement. 0 means no limit. It is an unsigned value (you select direction of motor movement with
sign of OutputPower
value).
type TachoCount = Int64 Source
Internal (absolute) tacho counter. Number since the last reset of the motor tacho counter.
type BlockTachoCount = Int64 Source
Block-relative position counter. Current position relative to the last programmed movement.
type RotationCount = Int64 Source
Program-relative position counter. Current position relative to the last reset of the rotation sensor for this motor.
data MotorReset Source
AbsolutePosition | Resets program-relative position counter ( |
RelativePosition | Resets block-relative position counter ( |
InternalPosition | Resets internal movement counters (also |
data InputValue Source
type Calibrated = Bool Source
True
if calibration file found and used for CalibratedValue
.
data SensorType Source
data SensorMode Source
RawMode | Reports scaled value equal to the raw value. |
BooleanMode | Reports scaled value as 1 true or 0 false, false if raw value > 55% of total range, true if < 45%. |
TransitionCntMode | Reports scaled value as number of transitions between true and false. |
PeriodCounterMode | Reports scaled value as number of transitions from false to true, then back to false. |
PctFullScaleMode | Reports scaled value as % of full scale reading for a configured sensor type. |
CelsiusMode | For reporting temperature in celsius. |
FahrenheitMode | For reporting temperature in fahrenheit. |
AngleStepsMode | Reports scaled value as count of ticks on RCX-style rotation sensor. |
type RawADValue = Int Source
Raw A/D value. Device dependent.
type NormalizedADValue = Int Source
Normalized A/D value. Type dependent. In [0, 1023] range.
type ScaledValue = Int Source
Scaled value. Mode dependent. In percent.
type CalibratedValue = Int Source
Value scaled according to calibration. Unused in current NXT firmware versions.
type Duration = NominalDiffTime Source
Time duration (in seconds).
Inbox on the NXT brick into which the host (computer) queues messages for the program running there.
data RemoteInbox Source
Outbox on the NXT brick where the program running there queues messages for the host (computer).
There is a convention that only RemoteInbox10
- RemoteInbox19
outboxes are used for this purpose so that lower ones can
be used for inter-brick communication. But this convention is not really obeyed in practice.
type RemoveMessage = Bool Source
Should the message be remove from the queue once received?
type LoopPlayback = Bool Source
Loop playback of the sound file?
type RxDataLength = Int Source
At most 16 data bytes can be read at a time.
type DeviceAddress = Word8 Source
Address of the device (sensor) on the I2C bus.
type Measurement = Int Source
I2C device measurement value.
type FileHandle = Int Source
Handle of the opened file on the NXT brick filesystem.
data ModuleInfo Source
Type of the IO map module information.
type ModuleName = String Source
Module name extension is .mod
. For some functions this can be also a wild card.
type ModuleSize = Int64 Source
type ModuleIOMapSize = Int Source
type ModuleHandle = Int Source
Handle for traversing of modules. Only one module handle can be opened at a time so be careful to close them when not needed anymore.
type IOMapOffset = Int Source
type IOMapLength = Int Source
data TimeoutException Source
Timeout exception for NXT IO operations.
Errors
Possible error codes and their descriptions are described in Lego Mindstorms NXT Bluetooth Developer Kit, Appendix 1 - Communication protocol and Appendix 2 - Direct commands.
data NXTException Source
Exception for NXT interface errors. Currently only one exception is defined which takes textual description as an argument.