41 lines
1.3 KiB
Python
Executable File
41 lines
1.3 KiB
Python
Executable File
import paho.mqtt.client as mqtt
|
|
import logging
|
|
|
|
# Configure logging
|
|
logging.basicConfig(filename="mqtt_messages.log", level=logging.INFO, format="%(asctime)s - %(message)s")
|
|
|
|
# MQTT Broker details
|
|
BROKER = "bonnie.pattinson.org" # Change to your broker address
|
|
PORT = 1883 # Default MQTT port
|
|
TOPIC = "msh/EU_868/2/json/#" # Change to your topic
|
|
USERNAME = "mesh" # Change to your MQTT username
|
|
PASSWORD = "Welcome123" # Change to your MQTT password
|
|
|
|
print("Script Loaded!")
|
|
|
|
def on_connect(client, userdata, flags, reason_code, properties):
|
|
if reason_code == 0:
|
|
print("Connected to MQTT Broker!")
|
|
client.subscribe(TOPIC)
|
|
else:
|
|
print(f"Failed to connect, return code {reason_code}")
|
|
|
|
# Callback when a message is received
|
|
def on_message(client, userdata, msg):
|
|
message = msg.payload.decode("utf-8", errors="replace")
|
|
log_entry = f"Topic: {msg.topic}, Message: {message}"
|
|
print(log_entry) # Print to console
|
|
logging.info(log_entry) # Log to file
|
|
|
|
# Setup MQTT client
|
|
client = mqtt.Client(callback_api_version=mqtt.CallbackAPIVersion.VERSION2)
|
|
client.username_pw_set(USERNAME, PASSWORD)
|
|
client.on_connect = on_connect
|
|
client.on_message = on_message
|
|
|
|
# Connect to the broker
|
|
client.connect(BROKER, PORT, 60)
|
|
|
|
# Keep listening for messages
|
|
client.loop_forever()
|