Search code examples
toit

How does PubSub work with multiple ESP32s?


Let's pretend that:

  1. I added "cloud:demo/INP" to my account topic with the name INP.
  2. I've several ESP32 devices and each of them an application subscribed to receive some message on "cloud:demo/INP":
import pubsub
topic ::= "cloud:demo/INP"

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"
  1. I've an application written in go/java/python/c#/dart/SCALA ... using the toit api, that sends a message to topic "cloud:demo/INP". Will the message be received by all ESP32 devices subscribed to receive messages or only one of them? I guess everyone, although not sure about it.
  2. Now let add one more topic "cloud:demo/OUT" named OUT.
  3. Let's change the toit application so that when it receives a message on the "cloud:demo/INP" topic, it sends a message to the "cloud:demo/OUT" topic and deploy this application on several ESP32s:
import pubsub

INCOMING_TOPIC ::= "cloud:demo/INP"
OUTGOING_TOPIC ::= "cloud:demo/OUT"

main:
  print "app is started"
  pubsub.subscribe INCOMING_TOPIC --auto_acknowledge: | msg/pubsub.Message |
    print "received: $msg.payload.to_string"
    pubsub.publish OUTGOING_TOPIC msg.payload
    print "sent: $msg.payload.to_string"
  1. Let's change the go/dart/python ... application that uses the toit api so that it can not only send messages, but also receive them. If I now send some message to topic "cloud:demo/INP", will I receive messages from all ESP32s? If this is true, is there a way to determine which ESP32 device received message belongs to?

Thanks in advance for your reply


Solution

  • Toit PubSub does broadcasting - all devices will receive the message.

    Every message sent on a topic contains a publisher which can either be an external or a device.

    A device who publishes will have the hardware_id and the job_id which is a unique way to determine what device sent the message. to external subscribers we also send device_id.

    An external who publishes will contain the name which is the identifier of the external application that published the message. For example in the CLI you can write a message using: toit pubsub write <topic> <external-name> -- <msg> here the <external-name> will be what is filled into the publisher.external.name property.