Chapter 4. Asynchronous operations

Most of the messages received from the URBI server are the results of previously sent commands and can be emitted at any time, for example as a reaction to particular sensor configurations. The mechanism of Urbi channels makes it possible to associate a channel with each message. Callback functions can then be launched automatically when a message is received through a given channel.

The urbiSetCallback function associates a function to a channel: each time a message will be received from the server in this channel, the callback function will be called with a umessage struct as a parameter. The urbiSetCallback function returns an id that can be later used to remove the callback with the urbiDeleteCallback function.

>>urbiSetCallback(myrobot,@callbackfct,'callbackchan')
ans =
     0

Where the callbackfct function should process the umessage corresponding to the received message. It the function returns 0, the callback function will run only once and then the callback will be deleted. If the function returns 1, the callback function will be executed for each message. Here is the code saved in the callbackfct.m file:

function cont=callbackfct(umessage)

x = umessage.value ;
disp(['I got the value : ' num2str(x)]) ;
cont = 1 ;

Once all the necessary callbacks are registered, Urbi code that produce the messages that will trigger the callbacks should be sent to the server. For example:

>> urbiSend(myrobot,'callbackchan << time(); wait(1s);callbackchan << time();');

Then, the urbiProcessEvents function should be called, that will process the messages coming from the Urbi server and lanch the appropriate callback functions. The first parameter specifies an upper limit of the number of messages which can be processed in one call of processEvents (this is for allowing to give the control back if there are too many messages). The second parameter specifies the number of milliseconds during which the function waits before returning when there are no messages on the input. If it is set to -1, then the function returns immediately if there are no messages and returns the number of callBacks that have been called. If it is set to -2, then the function never returns.

>> urbiProcessEvents(2,-1)
I got the value : 64892240
I got the value : 64893240
ans =
     2

The callback system can be reseted with the urbiResetCallbacks function.