Publisher
subscriber

subscribers = []


def publish(message):
    for subscriber in subscribers:
        subscriber(message)

        
def print_out(message):
    print("Got message:", message)

    
def backup_to_file(message):
    print(f"Backing up message to file:", message)

    
def send_sms(message):
    print("Sending SMS message:", message)

    
subscribers.append(print_out)
subscribers.append(backup_to_file)
subscribers.append(send_sms)
  • real-time vykreslování do grafu
  • skórování
  • nahrávání do souboru
  • přehrávání ze souboru
  • proxy do WebSocketu
# publisher.py

import zmq
import serial
import struct

with zmq.Context().socket(zmq.PUB) as socket:
    socket.bind("tcp://*:8137")
    with serial.Serial("/dev/tty.usbserial2") as tty:
        for line in tty:
            fields = line.strip().decode().split()
            time, x, y, z = list(map(int, fields))
            message = struct.pack("4i", time, x, y, z)
            socket.send(message)
# file_logger.py

import zmq
import struct

with zmq.Context().socket(zmq.SUB) as socket:
    socket.connect("tcp://127.0.0.1:8137")
    with open("output.csv", "a") as f:
        while True:
            raw = socket.recv()
            time, x, y, z = struct.unpack("4i", raw)
            print(time, x, y, z, sep=",", file=f)

Závěr

  • vlastní implementace
  • ZeroMQ, RabbitMQ
  • Kafka
  • AWS SNS, Google Cloud Pub/Sub
  • MQTT

Publisher-subscriber

By Tomáš Bedřich

Publisher-subscriber

  • 85
Loading comments...

More from Tomáš Bedřich