Goals

Familiarize yourself with the publish-subscribe architectural style, the MQTT protocol, its messages, topics, and subscriptions. Finally, implement communication using the protocol.

Examples

Exercises

Introduction

Context

Event-driven Architectures

An event-driven architecture is a type of software architecture that is based on producing, detecting and responding to events. Whenever something significant occurs, clients emit an event. Depending on the type of server, the event is either dispatched to all participants (Relay), a few interested participants (Publish-Subscribe) or a single recipient (Queue).

Example

In the following example, Alice has placed an order with the ID 5. She notifies other participants of the system, by sending an event ****with a unique id 69688550-5be2-41e4-a057-b9da2d59eb03 and event type order_placed. Bob checks every placed order and confirmes it, if valid, with an order_confirmed event.

event_driven_architecture.svg

The initial event at 1 sent by Alice could look like this:

{
  "id": "69688550-5be2-41e4-a057-b9da2d59eb03",
	"type": "order_placed",
  "created": "1676554735324",
  "source": "alice",
  "data": {
    "id": 5
  }
}

Publish-Subscribe Architectural Style

In a publish-subscribe architectural style, clients only communicate with a single server - also known as the middleware or broker. Clients do not know anything about other clients - they are referentially decoupled.

Clients communicate by publishing messages to the server. To receive messages, clients can subscribe to certain types of messages. The server ensures that each published message is delivered to all clients that have subscribed - if the subscription criteria is met.

Therefore, the communication is fully asynchronous. A client does not know if a message it published was received by any other client.

pubsub.webp

Introduction to MQTT Publish-Subscribe Pattern

MQTT

Message Queuing Telemetry Transport

What is MQTT?

MQTT is an OASIS standard messaging protocol for the Internet of Things (IoT). It is designed as an extremely lightweight publish/subscribe messaging transport that is ideal for connecting remote devices with a small code footprint and minimal network bandwidth. MQTT today is used in a wide variety of industries, such as automotive, manufacturing, telecommunications, oil and gas, etc.

MQTT uses topics to match messages between publishers and subscribers:

mqtt-publish-subscribe.png

MQTT - The Standard for IoT Messaging

It is an open OASIS and ISO standard (ISO/IEC PRF 20922)

MQTT Version 5.0

Server or Broker

To use the MQTT protocol, a central server, also called broker, is needed. The job of the server is to accept connections from clients and deliver published messages.

Example