Skip to main content

device.on(messageName, callback)

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

Availability

Agent

Parameters

Name Type Description
messageName String The name of the message with which the 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 agent.send() to respond to messages and data sent from the imp to its agent.

Call device.on() to register interest in a particular named message. For example, if the agent code includes:

device.on("setspeed", messageHandler);

and the device code subsequently calls:

agent.send("setspeed", data);

then the result will be a call to:

messageHandler(data)

in the agent code.

The message name can be any string, but it must be common to the specific device.on and agent.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 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 device.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 is the data passed into agent.send(). It can be 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 guide Squirrel Data Serialization.

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

Example Code

This code uses device.on() to tell the agent to listen for a ‘ping’ message from the device. When such a message is received, the agent calls the function startTime() to send a message back to the imp.