import sys import paho.mqtt.client as mqtt import logging # Set up logging configuration log_file = '/home/lucas/logfile.log' # Replace with your desired log file location logging.basicConfig( filename=log_file, # Log file location level=logging.DEBUG, # Log level: DEBUG, INFO, WARNING, ERROR, CRITICAL format='%(asctime)s - %(levelname)s - %(message)s', # Log format filemode='a' # 'a' to append logs, 'w' to overwrite logs each time ) logging.info(f"Start") # Define the MQTT broker connection details MQTT_BROKER_HOST = "homeassistant" MQTT_BROKER_PORT = 1883 MQTT_USERNAME = "MQTTBrokerUser" MQTT_PASSWORD = "mqtt1510##" MQTT_TOPIC = "serverhost_torrent_sensor/topic" # Set the desired topic # Define the on_connect callback def on_connect(client, userdata, flags, rc): print(f"Connected with result code {rc}") # Define callback functions def on_connect(client, userdata, flags, rc): """Callback when the client connects to the broker.""" print(f"Connected with result code {rc}") # Subscribe to a topic if needed client.subscribe(MQTT_TOPIC) def on_message(client, userdata, msg): """Callback when a message is received from the broker.""" print(f"Received message: {msg.payload.decode()} on topic: {msg.topic}") def on_subscribe(client, userdata, mid, granted_qos): """Callback when a subscription is successful.""" print(f"Subscribed to topic with QoS {granted_qos}") try: # Your code that is causing the error # Create an MQTT client instance mqttc = mqtt.Client() # Set username and password for authentication mqttc.username_pw_set(username=MQTT_USERNAME, password=MQTT_PASSWORD) # Connect to the MQTT broker mqttc.connect(MQTT_BROKER_HOST, MQTT_BROKER_PORT, 60) # Attach the callback functions mqttc.on_connect = on_connect mqttc.on_message = on_message mqttc.on_subscribe = on_subscribe # Start the MQTT client loop in the background mqttc.loop_start() # Prepare the message from command-line arguments message = ' '.join(sys.argv[1:]) # Collect all arguments except the script name logging.info(f"Message: {message}") if message: # Publish the message to the specified topic mqttc.publish(MQTT_TOPIC, message) print(f"Message sent: {message}") else: print("No message provided. Please provide some arguments to send.") # Disconnect from the broker mqttc.disconnect() # Stop the MQTT client loop mqttc.loop_stop() pass except AttributeError as e: logging.error(f"Error: {e}")