Registers a function to process messages sent from the agent to the device
The name of the message with which the registered handler will be associated
The function that will be called when the named message is received.
This method works in partnership with device.send() to respond to messages and data sent from the agent to its imp-enabled device.
Call agent.on() to register interest in a particular named message. For example, if the device code includes:
and the agent code subsequently calls:
then the result will be a call to:
in the device code.
The call is made automatically by impOS™ in response to the arrival of the message — there is no need to poll for messages. This is an example of impOS’ event-driven architecture (see the Developer Guide ‘Event-Driven Programming’).
The message name can be any string, but it must be common to the specific agent.on and device.send() calls. Messages for which the device has not registered a callback are dropped; a warning is posted in the log. Each message name can have only one callback, but multiple messages names can share the same callback. Setting a new callback for an existing message name will prevent the old callback from being executed. As many different messages as required can be listened for by making multiple calls to agent.on().
The function passed into the callback parameter has the following parameter of its own:
|data||Any||The message’s data payload|
The callback parameter data will contain the data passed into device.send(). It can be a Squirrel table, array, string, integer, float or bool. Tables and arrays can be nested, and will appear in their entirety at the device end — with certain restrictions, listed in the Developer Guide ‘Serializable Squirrel’.
For more information on agent-device and device-agent messaging, see the Developer Guide ‘Managing app-agent-device Communications’.
For information on dealing with ‘no handler for device.send()’ errors, see this troubleshooting note.
For sample code that can be used to manage messaging between agent and device, see ‘imp API Cookbook: Agent-Device Communications’.
The following device code uses agent.on() to listen for ‘pong’ messages. When one is received, the function returnFromAgent() is called; it sends a ‘pong’ message back to the agent.