Skip to main content

agent.on(messageName, callback)

Registers a function to process messages sent from the agent to the device

Availability

Device

Parameters

Name Type Description
messageName String The name of the message with which the registered handler will be associated
callback Function The function that will be called when the named message is received.

Returns

Nothing

Description

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:

agent.on("setspeed", messageHandler);

and the agent code subsequently calls:

device.send("setspeed", data);

then the result will be a call to:

messageHandler(data)

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:

Parameter Type Description
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’.

Messages can be passed in the other direction — from device to agent — using the analogously-named device.on() and agent.send().

Example Code

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.