Communicate within a device

PubSub is a service for bi-directional communication. In this tutorials, we show how PubSub enables communication between two apps installed on the same 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 named device:hello-world.

The subscriber

The subscriber program sets up a subscription on a device topic.

/// Subscribes to a device topic.

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

main:
  pubsub.subscribe topic: | msg/pubsub.Message |
    print "Received message '$msg.payload.to_string'"
    // Stop listening for other messages and exit 'main'.
    return

Save the above Toit program in a file named subscribe.toit.

The publisher

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

/// Publishes a message on the specified device topic.

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

main:
  pubsub.publish topic "Hello, World!"
  print "Message published on topic '$topic'"

Save the above Toit program in a file named publish.toit.

Running the example

Run the subscriber example with the CLI command

toit run subscribe.toit

on your default device.

Once the program has started, open another terminal window and run the publisher example with the CLI command

toit run publish.toit

also on your default device.

The output of both executions on the same device are shown below:

$ toit run subscribe.toit
2021-10-15T08:30:14.632498Z: <process initiated>
Received message 'Hello, World!'
2021-10-15T08:30:22.179783Z: <process terminated - exit code: 0>
$ toit run publish.toit
2021-10-15T08:30:22.126057Z: <process initiated>
Message published on topic 'device:hello-world'
2021-10-15T08:30:22.154862Z: <process terminated - exit code: 0>