Last modified 4 years ago Last modified on 12/07/09 15:52:57



<!> Totally outdated page <!>



Changes and new features planned for toolbox release version 2.00

New command layer structure



Layer Description Output/Motors Input/Sensors General Communication
4 High Level Regulation MotorRotateAbs

WaitForMotor
    COM_MakeBTConfigFile
3 High Level Functions SendMotorSettings
SetMotor
SetPower
SetAngleLimit
SetRampMode
SpeedRegulation
SyncToMotor

StopMotor

GetMotorSettings
GetMotor

ResetMotorAngle

SetMemoryCount
GetMemoryCount
OpenLight
OpenSound
OpenSwitch
OpenUltrasonic

GetLight
GetSound
GetSwitch
GetUltrasonic

CloseSensor
readFromIniFile COM_OpenNXT
COM_OpenNXTEx

COM_CloseNXT

2 Direct NXT Commands NXT_SetOutputState

NXT_GetOutputState

NXT_ResetMotorPosition
NXT_SetInputMode

NXT_GetInputValues


NXT_ResetInputScaledValue

NXT_LSRead
NXT_LSWrite
NXT_LSGetStatus
NXT_PlayTone

NXT_PlaySoundFile
NXT_StopSoundPlayback

NXT_SendKeepAlive
NXT_GetBatteryLevel

NXT_StartProgram
NXT_StopProgram

NXT_SetBrickName
NXT_Get_Firmware_Version
COM_CreatePacket
COM_SendPacket
COM_CollectPacket

COM_SetDefaultNXT
COM_GetDefaultNXT
1 Low Level Functions:
Helper, Conversion and
Lookup Functions
MOTOR_A
MOTOR_B
MOTOR_C

byte2outputmode
byte2regmode
byte2runstate
outputmode2byte
regmode2byte
runstate2byte


initializeGlobalMotorStateVar
SENSOR_1
SENSOR_2
SENSOR_3
SENSOR_4

byte2sensortype
byte2sensormode
sensortype2byte
sensormode2byte
textOut
DebugMode
isdebug

tictic (o)
toctoc (o)

dec2wordbytes
name2commandbytes
commandbyte2name
wordbytes2dec
checkStatusByte

createHandleStruct
checkHandleStruct

getReplyLengthFromCmdByte

libusb_proto
fantom_proto
getVISAErrorString
getLibusbErrorString
legend: NXT_* = NXT Direct commands without any limitations (mapped to the LEGO direct command documentation)
           BT_* = Functions related to the Bluetooth connection
           bold = Main funcions or main group functions
           italic = private functions
           (o) = obsolete functions (will be removed in a future release)


Communication functions (USB and BT) / handle concept

  • Replace BT_ functions by COM_ functions (maybe call them CON_ (for connection), NET_ (for network), COM_ (for communication), or ???).
  • Replace old handle variable by new handle structure (see below).
  • All functions support both USB and Bluetooth, transparent to the users (i.e. they don't know and don't have to care about implementation, they just pass a handle, be it USB or BT, and it simply works).


COM_OpenHandle(), simple and flexible method replacing BT_OpenHandle. This is recommended for all purposes, 2 ways to use:

  • COM_OpenHandle()
    Tries to connect to an NXT via USB. Will use the first device that is found. In case multiple NXTs are connected the first device is going to be used, and a warning will be issued (with a hint to use COM_OpenHandleEx if desired).
  • COM_OpenHandle('bluetooth.ini', 'check')
    Well-known syntax. 'check' can be omitted if wanted. This first tries to connect to the NXT via USB, using the first device found (in this case, the bluetooth.ini file will be ignored). Just like COM_OpenHandle(). AFTER that, if no USB device is present (or couldn't be found), bluetooth.ini will be parsed and evaluated, and a BT connection will be established (as known from BT_OpenHandle).
    • Pros: Very easy to use, very flexible: Provide a bluetooth.ini file, it works via BT. Connect the device via USB — hey, it works straight out of the box via USB. Unplug the device again, it works via BT again. Simple and handy.
    • Cons: Function will use USB/Fantom libraries, even if only a BT connection is desired. This will crash on systems, where Fantom or libusb aren't installed (maybe we can work around this: if libusb or Fantom not present, skip USB device detection).

Question (Behrens): Does the USB connection require no further parameter than the Name or MAC-Address? Is it possible that in the future a USB-Inifile will be necessary?


COM_OpenHandleEx(), more advanced function providing full control of USB and BT connections. Probably, COM_OpenHandle will be implemented just as a wrapper around COM_OpenHandleEx. The syntax should be the same all the time:

COM_OpenHandleEx(Mode, NXTNameOrMAC, 'bluetooth.ini', 'check')
All the time, the first 3 parameters have to be specified, i.e. are not optional.

Values for Mode are:

  • 'USB_before_BT' — just as in COM_OpenHandle, the method will try to locate an NXT via USB, and if none is found, the ini file will be used to try Bluetooth.
  • 'USB_only' — no BT, no inifile needed, USB bus will be searched
  • 'BT_only' — no USB, no libusb / fantom library is needed, inifile will be parsed and BT will be used (old-fashioned as BT_OpenHandle did)

Comments (Behrens): I'll prefer the Modes: "USB", "Bluetooth", "Any"

Comments (Behrens): It may be better to combine the parameter NXTNameOrMAC and parameterfile into one parameter. If the given name is not a valid parameter file we interpret it as a name or MAC address with the higher priority as shown in the examples. In the "Any" mode, the name of the NXT and the parameter file has be given. We will loose the difference between the COM_OpenHandleEx('BT_only', 'LfB', 'bluetooth.ini', 'check') and COM_OpenHandleEx('BT_only', ", 'bluetooth.ini', 'check'), but I'm not sure about the advantage to use a NXT name and a parameter file since the BT connection is set manually by the driver.


NXTnameOrMAC can either be the string of the NXT's name, like 'LfB'. Note that this does not have to be unique. It can also be the NXT's serial number / BT MAC which looks like "16:A0:FF:10:….". Note that leaving this string empty will act as a wildcard: The first NXT found will be used. On the other hand, if you specify a name, this will also work on BT: Even if the Bluetooth-Device is connected, it will sill be disconnected if the MAC / Name doesn't match.

'bluetooth.ini', 'check': Those parameters are well known: The inifile and the optional 'check' parameter. 'check' will be pointless on USB connections, as bidirectional functionality is always guarantueed.


Examples:

  • COM_OpenHandleEx('USB_only', 'LfB', ")
    Will only connect to the NXT named LfB if it is connected via USB. Note that inifilename is empty, as it will be ignored. You could also write:
  • COM_OpenHandleEx('USB_only', 'LfB', 'whatever.ini')
    Identical to the one above.
  • COM_OpenHandleEx('USB_only', '16:A0:FF:10:…', 'bluetooth.ini', 'check')
    Will only connect to the NXT with the matching MAC if it is connected via USB
  • COM_OpenHandleEx('BT_only', 'LfB', 'bluetooth.ini', 'check')
    Will only connect to the NXT named LfB, if it is connected via BT. If it is not name LfB, the connection will be dropped
  • COM_OpenHandleEx('BT_only', ", 'bluetooth.ini', 'check')
    Will connect to a device via BT (just as specified inside the inifile), name doesn't matter (i.e. any NXT will be ok)
  • COM_OpenHandleEx('USB_before_BT', ", 'bluetooth.ini', 'check')
    Will first try to find a device via USB and take the first match (if multiples are found), if none are found via USB or USB detection somehow failes, bluetooth.ini will be parsed and used.
  • COM_OpenHandleEx('USB_before_BT', 'LfB', 'bluetooth.ini', 'check')
    Will first try to find a device via USB and take the first one whose name matches LfB, if none are found via USB or USB detection somehow failes, bluetooth.ini will be parsed and used. A valid handle will only be returned, if the device is names LfB.
  • COM_OpenHandleEx('USB_before_BT', '16:A0:FF:10:…', 'bluetooth.ini')
    Same as above, but without the optional 'check' parameter, and specifying MAC instead of NXT name…


Other functions will be: COM_SendPacket() and COM_CollectPacket(). They should both take a full "BT ready" packet, i.e. including the two length bytes at the beginning. If a USB connection is used, the first 2 (on Linux) or first 3 bytes (on Windows with Fantom) will be cutted, but the users don't have to worry about it. COM_CollectPacket will emulate/fake a receiving-queue on Windows with USB, even though the Fantom driver returns the reply straight away. This emulation / temporary storage is needed, so that COM_CollectPacket works the same way on every system. The queue will be added to the NXT handle.


COM_CloseHandle, simple. But do we need COM_CloseAllHandles? It sure is needed for BT, but not for USB… Not sure about it yet…


COM_SetDefaultHandle and COM_GetDefaultHandle will behave the same way they did before.

Alternative naming concept

While the functions names change anyway, I could also imagine to change all the names, losing the word "handle". We could name the functions as follows:

  • COM_OpenNXT, COM_OpenNXTEx
  • COM_CloseNXT, COM_CloseAllNXTs
  • COM_SetActiveNXT, COM_GetActiveNXT (or COM_SetDefaultNXT, COM_GetDefaultNXT)
  • COM_SendPacket, COM_ReceivePacket (no change)

Current draft for handle-structure:

% generic info
  .OSName              % String, 'Windows' or 'Linux'
  .OSValue             % OS encoded as number: 1 = Win, 2 = Linux
  .ConnectionTypeName  % String, 'USB' or 'Bluetooth'
  .ConnectionTypeValue % Type encoded as number: 1 = USB, 2 = BT

% the actual handle
  .Handle              % the actual handle value, datatype depends on OS and connection type

% BT info known from the ini-file...
  .SerialPort          % only valid for *-BT
  .BaudRate            % only valid for Win-BT
  .DataBits            % Win-BT, should we consider hardcoding this?
  .Timeout             % Win-BT

  .SendSendPause       % still needed for *-BT
  .SendReceivePause    % ...

% infos needed for BT, known from global vars inside BT_Send / Collect
  .LastSendTime        % needed for the timers above to work
  .LastReceiveTime     % ...

% description of our NXT
  .NXTName             % from the ini-file, or from the NXT retrieved? should match anyway
  .NXTMAC              % maybe call it NXTID instead? Or Serial? Is it really a MAC?
  .KeepAliveInterval   % could be read out from NXT, so we know when it will turn off

% internal MOTOR state, previously one global var
  .NXTMOTOR_State      % this is another whole struct! name might change

% needed for USB on Windows using Fantom: temporary incoming buffer
  .ReceivedPacketQueue % just a byte array, used as queue

% connections statistics, useful
  .BytesSent           % status infos from here on:
  .BytesReceived       % similar to Matlab's serial object
  .PacketsSent         % just a counter
  .PacketsReceived     % ...
  .TransmissionErrors  % count of invalid packets

% some more additional handle information
  .CreationTime        % just a gimmick? timestamp when connection was established
  .IsDefault           % probably this is not needed

New lowlevel / helper functions

  • isCOMHandleValid
    Integrity check for the new handle structure. Gets called by COM_SendPacket, COM_CollectPacket, COM_SetDefaultHandle, and maybe COM_CloseHandle. This is the lowest level, so we pass on the handle all the time until just before it gets used. Only then it will be checked. We remove all the unneccessary checks inside the NXT_ functions. Note that this function will be called EVERY TIME a packet is sent or received, so it's very critical for performance. We have to make sure the checks are not too expensive…
  • getReplyLengthFromCmdByte.m
    Needed for USB functions, returns payload length of a reply packet to a direct command — this isn't necessary for BT, since length information is encoded into the reply packet, but USB needs this information from somewhere else (i.e. this helper lookup).
  • getVISAErrorString.m
    Returns error description from error number, needed for Fantom (which in turn seems to use VISA, an USB instrument control framework / library)
  • getLibusbErrorString.m
    Returns error description of last error that occured in libusb
  • libusb_proto.m
    Prototype file for libusb, something like a "DLL import header for MATLAB", generated from original C-header-file. Gets called from loadlibrary.
    /!\ With new MATLAB 2008a, we get a "warning: protofile outdated". Are these prototype files MATLAB version dependent? Then we might have to regenerate them (using loadlibrary -mfilename) from the C-header-files. This would be a big disadvantage for m-proto-files, but the advantages on the other hand are: They load faster, are much more reliable, produce less warnings/errors, and are recommended anyway.
  • fantom_proto.m
    see above
  • dec2wordbytes.m / wordbytes2dec.m
    Big performance improvement (factor 10?), important for USB with higher packet rates. Use profiler to improve even more: Instead of typecast we could (or even should?) use typecastc.

New sensor functions

  • Generic OpenSensor and GetSensor functions?
    Pros: Easier to use, more flexible, changing sensors doesn't result in changing so much code (i.e. GetSound?GetLight? now stays GetSensor?GetSensor?), smaller function-count, one powerful function.
    Cons: More changes introduced, losing backwards compatibility (or do we keep the old functions, too?), one huge complex function to maintain, too variable input parameters?, unclear / varying output parameters (no strict expectable type)

Other changes

With the first tests of fast USB connections, sometimes packet errors were reported by checkStatusByte. This means that the NXT apparently "wasn't ready" to reply with a data packet (seems likely), or something went wrong on the USB protocol layer in our request (seems unlikely). This error usually doesn't last long, only a single packet amongst others is invalid. However, payload data is probably unusable in this case.

So, we have to react. The NXT_ functions clearly leave this to the user as they have the status byte as a seperate output for the user to check. But our high level functions (GetLight? etc, GetMotorSettings?) should cope with this invalid status byte situation on their own. I propose a little check, and in case of an error we re-request the sensor reading. This will of course take some additional time, and to prevent endless loops a timeout period is needed. The big advantage is that users now can TRUST the answers they receive from the Get-functions (which they can't with the current implementation). The delay sometimes introduced is necessary and not too bad, since we are working with USB anyway.

The only alternative I see to re-requesting a packet is dropping it or outputting a default value. But this would prevent the Get-functions from returning sensible values at all times, and hence might lead to crashing programs.

Additional Service and Support

  • Provide btconnect script for establishing Bluetooth connection under Linux (based on BlueZ driver)
  • List of recommended Bluetooth adapter as described in BluetoothAdapter