forked from testcontainers/testcontainers-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_basic.py
More file actions
51 lines (36 loc) · 1.39 KB
/
Copy pathexample_basic.py
File metadata and controls
51 lines (36 loc) · 1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import time
import paho.mqtt.client as mqtt
from testcontainers.mqtt import MqttContainer
def basic_example():
with MqttContainer() as mqtt_container:
# Get connection parameters
host = mqtt_container.get_container_host_ip()
port = mqtt_container.get_exposed_port(mqtt_container.port)
# Create MQTT client
client = mqtt.Client()
# Define callback functions
def on_connect(client, userdata, flags, rc):
print(f"Connected with result code {rc}")
# Subscribe to topics
client.subscribe("test/topic")
def on_message(client, userdata, msg):
print(f"Received message on topic {msg.topic}: {msg.payload.decode()}")
# Set callbacks
client.on_connect = on_connect
client.on_message = on_message
# Connect to broker
client.connect(host, port)
client.loop_start()
# Publish test messages
test_messages = ["Hello MQTT!", "This is a test message", "MQTT is working!"]
for msg in test_messages:
client.publish("test/topic", msg)
print(f"Published message: {msg}")
time.sleep(1) # Wait a bit between messages
# Wait for messages to be processed
time.sleep(2)
# Clean up
client.loop_stop()
client.disconnect()
if __name__ == "__main__":
basic_example()