1.18 Use Cases 155
string initializeAndGetVersion( void ) const
{
write( "<01>" ); // must be the first command written
millisleep( 1500 ); // initialization takes time
return getReply();
}
unsigned int replyToInt( const string& reply, int bitNr /
*
< 32, or it won’t fit in an unsigned int
*
/ )
const
{
unsigned int nrOfCharactersNeeded = ( bitNr » 2 ) + 1; // four bits in one character
if( reply.length() < nrOfCharactersNeeded + 4 ) // first four characters contain no status bits
{
throw runtime_error( "Reply string too short" );
}
unsigned int uistatus;
istringstream iss( reply.substr( 4, nrOfCharactersNeeded ) ); // skip the first four characters,
that contain no status bits
iss » hex » uistatus; // string returned is in hex
return uistatus;
}
bool bitIsSet( unsigned int uistatus, int bitNr ) const
{
return ( uistatus & ( 0x1 « bitNr ) ) != 0;
}
bool bitIsNotSet( unsigned int uistatus, int bitNr ) const
{
return ( uistatus & ( 0x1 « bitNr ) ) == 0;
}
bool bitIsSet( const string& reply, int bitNr ) const
{
return bitIsSet( replyToInt( reply, bitNr ), bitNr );
}
bool bitIsNotSet( const string& reply, int bitNr ) const
{
return bitIsNotSet( replyToInt( reply, bitNr ), bitNr );
}
public:
explicit MotorControl( Device
*
device ) : mfc( MotorFocusControl( device ) ), version(
initializeAndGetVersion() )
{
if( bitIsNotSet( getStatus(), 21 ) )
{
writeConfirmed( "<20 1>" ); // only in closed-loop drive mode will command moveToPosition work
}
}
~MotorControl()
{
write( "<03>" ); // halt the motor (do not wait for confirmation, as the dtor will also be called
when the USB plug is pulled, and then one would obviously wait forever)
write( "<02>" ); // release computer control
}
string getVersion( void ) const
{
return version.length() > 8 ? version.substr( 6, version.length() - 7 ) : version;
}
string getReply( void ) const
{
millisleep( 40 );
return mfc.motorFocusReceiveBuffer.read(); // mfc is private
}
string getStatus( void ) const
{
write( "<10>" ); // request status
return getReply();
}
// only first 16 status bits of "<10>"
string getShortStatus( void ) const
{
write( "<19>" ); // request motor status
return getReply();
}
bool isRunning( void ) const
{
return bitIsSet( getShortStatus(), 2 ); // would also work with getStatus()
}
string getPositionStr( void ) const
{
string status = getStatus();
if( status.empty() )
{
throw runtime_error( string( "Could not retrieve status" ) );
}
return status.substr( 11, 8 );
}
int getPosition( void ) const
{
int ipos;
MATRIX VISION GmbH