Registers a function to process messages sent from the device to the agent
The name of the message with which the handler will be associated
The function that will be called when the named message is received
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:
and the device code subsequently calls:
then the result will be a call to:
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:
|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().
For a more in-depth look at the imp’s use of events and event triggers, please see Event-Driven Programming.
For more information on agent-device and device-agent messaging, please see Effective Internet-agent-device Communication.
For sample code that can be used to manage messaging between agent and device, see the imp API Cookbook recipe Agent-Device Communications.
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.