cisstOSAbstraction API

cisstOSAbstraction provides cross-platform OS primitives: threads, mutexes, serial ports, sockets, dynamic loading, and timers.

Key classes

class osaThread

Define a thread object.

The thread class is just a wrapper on the OS-specific thread management functions. For now, wraps functions such as CreateThread, DeleteThread, GetThreadPriority, SetThreadPriority and so on. Additional functionality, such as inter-thread communication, maintenance of state information, etc., are provided by the mtsTask class.

See also

mtsTask

Public Functions

osaThread()

Default constructor. Does nothing.

~osaThread()

Default destructor. Does nothing.

inline void Create(void *(*threadStart)(void), const char *name = 0, int priority = 0, int policy = 0)

Creates a new thread that will execute the specified function, with no parameters.

Parameters:

policy – No Scheduling Policy available in Windows

template<class _userDataType>
inline void Create(void *(*threadStart)(_userDataType), _userDataType userData = _userDataType(), const char *name = 0, int priority = 0, int policy = 0)

Creates a new thread that will execute the specified function, taking a single parameter.

Parameters:

policy – No Scheduling Policy available in Windows

template<class _entryType, class _userDataType>
inline void Create(_entryType *obj, void *(_entryType::* threadStart)(_userDataType), _userDataType userData = _userDataType(), const char *name = 0, int priority = 0, int policy = 0)

Creates a new thread that will execute the specified class member function. Note that the object is copied to the heap so it remains valid, even if the original object is destroyed.

Parameters:

policy – No Scheduling Policy available in Windows

inline void CreateFromCurrentThread(const char *name = 0, int priority = 0, int policy = 0)

Initialize the thread object so that it refers to the calling thread, rather than creating a new thread. This allows existing threads to intermix with newly created threads.

Parameters:

policy – No Scheduling Policy available in Windows

inline void CreateFromThreadId(const osaThreadId &threadId, const char *name = 0, int priority = 0, int policy = 0)
Parameters:

policy – No Scheduling Policy available in Windows

void Delete(void)

Deletes a thread. Deletes (removes from memory) everything associated with a thread, e.g. stack, local data, static variables.

void Wait(void)

Wait for the thread to exit.

inline void WaitForWakeup(void)

Wait for thread to receive a “wakeup” signal/event.

inline void WaitForWakeup(double timeoutInSec)

Wait for thread to receive a “wakeup” signal/event.

inline void Wakeup(void)

Signal the thread to wake up.

inline const char *GetName(void) const

Return the thread name.

inline osaThreadId GetId(void) const

Return the thread id.

PriorityType GetPriority(void) const

Get the OS independent priority of the thread.

void SetPriority(PriorityType priority)

Set the OS independent priority of the thread.

SchedulingPolicyType GetSchedulingPolicy(void)

Get the OS independent scheduling policy of the thread. Will not be available on all platforms or will return a constant.

void SetSchedulingPolicy(SchedulingPolicyType policy)

Set the OS independent scheduling policy of the thread. Will not be available on all platforms.

void Sleep(double timeInSeconds)

Delay/suspend execution of the calling thread for the specified time. On some platforms, this method provides a better implementation of osaSleep, provided that it is called from the thread associated with this instance of the class. In this case, the Sleep will also be terminated by any call to Wakeup. If called from a different thread, it just calls osaSleep and is therefore not affected by any calls to Wakeup.

Parameters:

timeInSeconds – The amount of time the task is suspended (in seconds)

inline bool IsRunning(void) const

Returns if this thread is running.

inline bool IsValid(void) const

Returns whether the thread exists (is valid).

class osaMutex

Define a Mutex object.

Mutex class provided to create mutual exclusion around critical sections. This class relies on Posix threads mutex when possible. On Windows, it uses an actual Mutex which provides a locking mechanism between threads as well as processes. It doesn’t rely on the more specialized CriticalSection type (between threads only).

Public Types

enum TimeoutType

Values:

enumerator WAIT_FOREVER
enumerator NO_WAIT

The calling function will be blocked till the function returns

enum LockStateType

Enum type for return values of a lock operation.

Enum type for current lock state

Values:

enumerator LOCKED
enumerator UNLOCKED

Public Functions

osaMutex(void)

Default constructor. Initialize the underlying mutex.

~osaMutex(void)

Default destructor. Cleanup the underlying mutex.

void Lock(void)

Mutex lock operation. This class doesn’t use recursive mutexes therefore you must make sure the mutex is not already locked. Locking the same mutex twice from the same threads leads to undefined results.

void Unlock(void)

Mutex unlock operation. Be careful, one should never unlock an already unlocked mutex, this would lead to undefined results.

bool IsLocker(void) const

Mutex lock operation with timeout

Check if the current thread locked this mutex earlier

Parameters:

timeout – If timeout == WAIT_FOREVER then the calling thread is blocked (this is same as calling Lock()). If timeout == NO_WAIT then the function returns after checking if the mutex can be locked or not. If timeout > 0 then the function waits for the specified amount of time (units to be specified later) before returning.

Returns:

An enumerated type representing if a lock was obtained, or operation timed out or lock failed

LockStateType GetLockState(void) const

Get current lock state

class osaCriticalSection

Public Functions

osaCriticalSection()
~osaCriticalSection()
bool TryEnter(void)
void Enter(void)
void Leave(void)
class osaSocket : public cmnGenericObject

Public Types

enum SocketTypes

Values:

enumerator UDP
enumerator TCP

Public Functions

osaSocket(SocketTypes type = TCP)

Default constructor.

~osaSocket(void)

Destructor.

inline int GetIdentifier(void) const
Returns:

Socket file descriptor

bool AssignPort(unsigned short port)

Sets the port of a UDP server.

void SetDestination(const std::string &host, unsigned short port)

Set the destination address for UDP or TCP socket.

Parameters:
  • host – Server’s hostname or IP address (e.g. localhost, 127.0.0.1)

  • port – Server’s port number

void SetDestination(const osaIPandPort &ip_port)

Set the destination address for UDP or TCP socket.

Parameters:

ip_port – Server’s hostname or IP address (e.g. localhost, 127.0.0.1) and port number

bool GetDestination(std::string &host, unsigned short &port) const

Get the destination address for UDP or TCP socket. This is particularly useful for programs using UDP because the the Receive method automatically updates the destination based on the address from which the packet was received. Thus, subsequent Send commands will send to this address.

Parameters:
  • host – Reference for returning server’s IP address (e.g. “127.0.0.1”)

  • port – Reference for returning server’s port number

Returns:

true if destination address was returned

bool GetDestination(osaIPandPort &ip_port) const

Get the destination address for UDP or TCP socket. This is particularly useful for programs using UDP because the the Receive method automatically updates the destination based on the address from which the packet was received. Thus, subsequent Send commands will send to this address.

Parameters:

ip_port – Reference for returning server’s IP address (e.g. “127.0.0.1”) and port number

Returns:

true if destination address was returned

bool Connect(void)

Connect to the server; required for TCP sockets and should be used after SetDestination()

Returns:

true if the connection was successful

bool Connect(const std::string &host, unsigned short port)

Connect to the server; required for TCP sockets; includes call to SetDestination()

Parameters:
  • host – Server’s hostname or IP address (e.g. localhost, 127.0.0.1)

  • port – Server’s port number

Returns:

true if the connection was successful

bool Connect(const osaIPandPort &ip_port)

Connect to the server; required for TCP sockets; includes call to SetDestination()

Parameters:

ip_port – Server’s hostname or IP address (e.g. localhost, 127.0.0.1) and port number

Returns:

true if the connection was successful

int Send(const char *bufsend, unsigned int msglen, double timeoutSec = 0.0)

Send a byte array via the socket.

Note

Since this is a nonblocking call the socket might not be ready to send right away so a short timeout will help in cases when large amount of data is sent around. If the socket is not ready within the timeout then the connection will be closed

Parameters:
  • bufsend – Buffer holding bytes to be sent

  • msglen – Number of bytes to send

  • timeoutSec – is the longest time we should wait to send something

Returns:

Number of bytes sent (-1 if error)

int Send(const std::string &bufsend, double timeoutSec = 0.0)

Send a string via the socket.

Parameters:
  • bufsend – String to be sent

  • timeoutSec – is the longest time we should wait to send something

Returns:

Number of bytes sent (-1 if error)

int SendAsPackets(const char *bufsend, unsigned int msglen, unsigned int packetSize, double timeoutSec = 0.0)

Send a byte array via the socket, possibly in multiple packets based on the specified maximum packet_size. This method can be used with both UDP and TCP, though it is intended for UDP.

Note

This function aborts if any error occurs and returns the number of bytes actually sent (if any).

Parameters:
  • bufsend – Buffer holding bytes to be sent

  • packetSize – Maximum packet size

  • timeoutSec – is the longest time we should wait to send something

Returns:

Number of bytes sent (-1 if error)

int SendAsPackets(const std::string &bufsend, unsigned int packetSize, double timeoutSec = 0.0)

Send a string via the socket, possibly in multiple packets based on the specified maximum packet_size. This method can be used with both UDP and TCP, though it is intended for UDP (only for reliable UDP connections, since there is no check for missing or out of sequence packets).

Note

This function aborts if any error occurs and returns the number of bytes actually sent (if any).

Parameters:
  • bufsend – String to be sent

  • packetSize – Maximum packet size

  • timeoutSec – is the longest time we should wait to send something

Returns:

Number of bytes sent (-1 if error)

int Receive(char *bufrecv, unsigned int maxlen, double timeoutSec = 0.0)

Receive a byte array via the socket.

Parameters:
  • bufrecv – Buffer to store received data

  • maxlen – Maximum number of bytes to receive

  • timeoutSec – Timeout in seconds

Returns:

Number of bytes received. 0 if timeout is reached and/or no data is received.

int ReceiveAsPackets(std::string &bufrecv, char *packetBuffer, unsigned int packetSize, double timeoutStartSec = 0.0, double timeoutNextSec = 0.0)

Receive a string via the socket, possibly in multiple packets. This method can be used with both UDP and TCP, though it is intended for UDP (only for reliable UDP connections, since there is no check for missing or out of sequence packets).

Note

It can be difficult to determine when a complete set of packets has been received. This function is intended primarily to receive the packet stream produced by SendAsPackets, so it terminates reception in the following cases: (1) when a received packet is smaller than the specified packetSize, (2) on any socket error, and (3) when a timeout occurs. The first condition is best, since it avoids the possibility of appending data from an unrelated packet. Thus, the caller can ensure that the total number of bytes transmitted is not a multiple of the packetSize (e.g., by appending an extra byte).

Parameters:
  • bufrecv – String to store received data

  • packetBuffer – Buffer to store one packet

  • packetSize – Maximum packet size, should equal sizeof(packetBuffer)

  • timeoutStartSec – Timeout for receiving first packet, in seconds

  • timeoutNextSec – Timeout for receiving subsequent packets (after first), in seconds

Returns:

Number of bytes received. 0 if timeout is reached and/or no data is received.

bool Close(void)

Close the socket.

Returns:

False if close fails

bool IsConnected(void)

\ brief Connection state (only works for TCP)

Returns:

Returns true if the socket thinks it is connected

Public Static Functions

static std::string GetLocalhostIP(void)
Returns:

The first IP address of the localhost as a string

static int GetLocalhostIP(std::vector<std::string> &IPaddress)

Retrieve IP address of the localhost as string from each network interface (which may be more than two)

Parameters:

IPaddresses – container for IP address as string

Returns:

Number of IP address retrieved with IPaddresses filled

class osaSerialPort : public cmnGenericObject

Serial port.

Create a serial port for sending and receiving data.

Public Types

enum BaudRateType

Values:

enumerator BaudRate300
enumerator BaudRate1200
enumerator BaudRate9600
enumerator BaudRate19200
enumerator BaudRate38400
enumerator BaudRate57600
enumerator BaudRate115200
enumerator BaudRate230400
enumerator BaudRate460800
enum CharacterSizeType

Type used to define the character size.

See also

SetCharacterSize

Values:

enumerator CharacterSize5
enumerator CharacterSize6
enumerator CharacterSize7
enumerator CharacterSize8
enum ParityCheckingType

Type used to define the parity checking.

Values:

enumerator ParityCheckingNone
enumerator ParityCheckingEven
enumerator ParityCheckingOdd
enum FlowControlType

Type used to define the flow control.

See also

SetFlowControl

Values:

enumerator FlowControlNone
enumerator FlowControlSoftware
enumerator FlowControlHardware
enum StopBitsType

Type used to define stop bits.

See also

SetStopBits

Values:

enumerator StopBitsOne
enumerator StopBitsTwo

Public Functions

inline osaSerialPort(void)

Default constructor. Set parameters to default 8N1 (8 bits per character, no parity checking, 1 stop bit) and 9600 baud rate. This constructor doesn’t start anything, use Open() to actually start the serial port connection.

virtual ~osaSerialPort(void)

Destructor.

inline void SetBaudRate(const BaudRateType &baudRate)

Set a different baud rate.

inline void SetCharacterSize(const CharacterSizeType &characterSize)

Set a different character size.

inline void SetParityChecking(const ParityCheckingType &parityChecking)

Set a different parity checking.

inline void SetStopBits(const StopBitsType &stopBits)

Set different stop bits.

inline void SetFlowControl(const FlowControlType &flowControl)

Set different flow control.

inline void SetPortName(const std::string &portName)

Set the port name. For a more portable code, use SetPortNumber.

inline std::string GetPortName(void) const

Get the current port name.

std::string SetPortNumber(unsigned int portNumber)

Set the serial port name based on a number, starting from 1.

bool Open(bool blocking = false)

Open the serial port. This method starts the serial port based on the parameters previously set (either the defaults of those defined by SetBaudRate, SetCharacterSize, SetParityChecking, SetHardwareFlowControl, …).

bool Configure(void)
bool Close(void)
inline bool IsOpened(void) const

Indicates if the port has been opened or closed correctly.

int Write(const char *data, int nBytes)

Send raw data.

int Write(const unsigned char *data, int nBytes)
inline int Write(const std::string &data)
int Read(char *data, int nBytes)

Receive raw data.

int Read(unsigned char *data, int nBytes)
bool WriteBreak(double breakLengthInSeconds)

Sends a serial break for a given duration in seconds.

On Linux, if the break duration is set to 0, the actual duration will be at least 0.25 seconds and at most 0.5 seconds.

On Mac OS, the implementation doesn’t use the breakLengthInSeconds. To provide a similar runtime, osaSleep is used internaly. As the default duration on MacOS it 0.4 seconds, the actual sleep time is breakLengthInSeconds - 0.4.

On Windows, this method is implemented using SetCommBreak, osaSleep and ClearCommBreak.

bool Flush(void)

Flush.

class osaStopwatch

Implement a simple stopwatch mechanism, which is helpful in profiling, debugging, and performance estimation.

The osaStopwatch class uses system calls to obtain time at the finest granularity available in the system. Note that a system call may sometimes invoke a context switch, and use them only when needed to interfere the least with the normal performance of the program.

To reduce overhead (for more efficient time polling), all the methods are inlined.

Public Types

typedef unsigned long MillisecondsCounter
typedef double SecondsCounter

Public Functions

inline osaStopwatch(void)
double GetTimeGranularity(void) const

Return the granularity of time in the system, in seconds. The fraction part is the fraction of second that the system time granularity supports

inline void Reset(void)

Reset all the counters to zero, and stop the watch

inline void Start(void)

Start the stopwatch from its current counter state. If the watch is already running, do nothing

inline void Stop(void)

Stop the stopwatch so that its counter state is kept until a Start or a Reset

inline bool IsRunning(void) const

Returns true if the stopwatch is running and counting continues (i.e., if Start was called last). Returns false if the watch is stopped, i.e., if Stop or Reset was called last.

inline MillisecondsCounter CISST_DEPRECATED GetCurrentRead (void) const

Return the current read of the stopwatch without changing the running state. This method is now deprecated as it returns a time interval in milliseconds (integer). Use GetElapsedTime() instead.

inline SecondsCounter GetElapsedTime(void) const

Return the current read of the stopwatch without changing the running state. Return a time interval in seconds using a “double” precision floating point number.

class osaDynamicLoader

Dynamically load a shared library file.

This class is used to dynamically load a shared library file. If a path is specified, the library file must exist on that path; otherwise, the “standard” library paths are used.

This class should be used to dynamically load a library file if it contains classes that are derived from cmnGenericObject, assuming that they are set up for dynamic creation (e.g., CMN_DYNAMIC_CREATION flag used with CMN_DECLARE_SERVICES). For example, if the class “derivedClass” exists in a library file with the same name, the file can be dynamically loaded and a new instance created as follows:

osaDynamicLoader dload;
dload.Load("derivedClass");
cmnGenericObject *obj = cmnObjectRegister::Instance()->Create("derivedClass");
Note that dynamic_cast can be used to cast obj up the hierarchy.

Subclassed by osaDynamicLoaderAndFactoryBase

Public Functions

inline osaDynamicLoader()

Default constructor. Does nothing.

inline virtual ~osaDynamicLoader()

Destructor. Does not unload library in case any objects created from within the library still exist. To unload library, call Unload().

bool Load(const char *file, const char *path = 0)

Dynamically load the specified shared library.

Parameters:
  • file – Name of shared library file to load (do not include extension)

  • path – Path to file (0 -> use default library load paths)

Returns:

true if file successfully loaded; false otherwise

inline bool Load(const std::string &file, const std::string &path = "")
void UnLoad(void)

Unload the shared library file (if supported by operating system).