Skip to content

Apps, communicate within a device#

PubSub is a service for bi-directional communication. In this tutorials, we show how PubSub can be used so that two apps can communicate with each other within a device. In this scenario, the data does not need to be sent out to the cloud to be received by the other app. We will be communicating on the device topic device:hello-world.

The subscriber#

The subscriber sets up a subscription on a topic.

// filename: pubsub/subscribe_device.toit

/// Subscribes to a device topic.

import pubsub
topic ::= "device:hello-world"

  pubsub.subscribe topic: | msg/pubsub.Message |
    sender := msg.sender.is_device ? "Device($msg.sender.hardware_id)" : "ExternalSystem($msg.sender.external_name)"

    print "Received message '$msg.payload.to_string' from $sender"

The publisher#

The publisher publishes the message "Hello, World!" on the topic and then terminates.

// filename: pubsub/publish_device.toit

/// Publishes a message in the appropriate device topic.

import pubsub
topic ::= "device:hello-world"

  pubsub.publish topic "Hello, World!"

Running the example#

To run the example, run subscribe.toit on your default device in a terminal window. Once the program is started, open a second terminal window and run publish.toit.

Both windows are depicted here:

toit run subscribe.toit 2020-06-12T09:11:49.689210Z: <process initiated> Received message 'Hello, World!' from Device(82df15db-4c03-4516-b846-df714577960c) 2020-08-04T10:45:46.397975Z: <process terminated - exit code: 0>

toit run publish.toit 2020-08-04T10:45:46.120857Z: <process initiated> Hello, World! 2020-08-04T10:45:46.267676Z: <process terminated - exit code: 0> [1]+ Done toit run subscribe.toit