Skip to main content

Agent-Device Communications

Recommended Code Flow For Agent-device Communication

Agent-device messaging lies at the heart of the Electric Imp Platform. It is both powerful and easy to apply.

The agent-only method device.send() is used to message the device, which must incorporate code to process any data packaged with the message. The device needs to register this handler function before any messages are sent by the agent. If it doesn’t, the messages will be effectively ignored and a warning posted in the device log. The functions is registered using the device-only method agent.on().

Each message is identified by a name string passed as each of these methods’ first parameter. Both methods have a second parameter: in the case of device.send() it is a variable which will be serialized and sent with the message. See the Developer Guide ‘Data Serialization in Squirrel’ to learn what Squirrel data types and entities can be serialized.

The second parameter of agent.on() is the name of a function — or an inline function definition — to be called on receipt of the named message. This function must take a single parameter: a variable in which the incoming data will be stored. Even if you don’t plan to send or use data, you must include a value when the message is sent and a variable to receive it.

Sending messages from the device and registering agent functions to deal with them is almost identical to the process described above. This time the handler function is registered with device.on(), and agent.send() is used to send the message whose data payload the function will process.

Example Code

The following code shows these processes in action. Both agent and device register functions at the start of their code to be called on receipt of messages bearing the appropriate name.

API Methods Used

Further Reading