Communicate through the cloud

PubSub is a service for bi-directional communication. In this tutorial, we show how two apps can communicate with each other through the Toit cloud.

Communicating through the cloud allows apps installed on different devices to communicate with each other. Note that in this scenario, the publish/subscribe events relies on the Max Offline value set for the device(s) involved.

The subscriber

In this tutorial, we will implement the subscriber as an application that will be installed on your device as a long-lived application. In the app specification file, we subscribe to the cloud topic. A new message received on this topic will trigger running the Toit program which then consumes the message. This means that the message has been acknowledged and removed from the cloud topic. This process ensures that one message cannot trigger the app more than once.

The Toit program for subscribing to a cloud topic is shown below:

/// Subscribes to a cloud topic.

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

main:
  print "wakeup - checking messages"
  pubsub.subscribe topic --blocking=false: | msg/pubsub.Message |
    sender := ?
    if msg.sender.is_device:
      sender = "Device($msg.sender.hardware_id)"
    else:
      sender = "ExternalSystem($msg.sender.external_name)"
    print "Received message '$msg.payload.to_string' from $sender"
  print "done processing all messages"

Save the program in a file named subscribe_cloud.toit.

The corresponding app specification file for the subscriber that defines the pubsub trigger, and which is deployed on your device as a Toit application, is specified below:

# The pubsub trigger specifies that the subscribe_cloud program runs
# every time a message is received on the given cloud topic.

name: Subscribe
entrypoint: subscribe_cloud.toit

triggers:
  on_pubsub_topic:
    - "cloud:hello-world"

Save the above content in a file named subscribe_cloud.yaml.

Deploy the subscriber app using the CLI with

toit deploy subscribe_cloud.yaml

The output will look like this:

$ toit deploy subscribe_cloud.yaml
Successfully deployed the job Subscribe on 'my-device'
The job will be installed on 'my-device' next time it connects to the Toit console

The publisher

Run the publisher program on another device by pasting the following Toit program in the Code tab of the given device in the Toit console:

/// Publishes a message on the same cloud topic as used in the subscriber

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

main:
  pubsub.publish topic "Hello from another device"
  print "Message published on topic '$topic'"

You can also send a message directly from the CLI with

toit pubsub write cloud:hello-world "Mr. CLI" -- Hello from the CLI

Confirm the output

Navigate to the Toit console, and choose the device on which the subscriber app was installed on.

Open the Logs tab of the device to confirm that the message has been received.

Screenshot of pubsub
Screenshot of pubsub