0

There are many instances of this problem here, but all of them list an error when attempting to run the script. When I try to run my script from the terminal, it thinks for about a second, then just goes back to a normal terminal prompt (without an error message).

I am new to Python, so forgive me if I'm simply doing something wrong, but for the life of me . . . this runs perfectly fine when opening/running in IDLE.

import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish
import RPi.GPIO as GPIO

RELAY_PIN_1 = 23
RELAY_PIN_2 = 24

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(RELAY_PIN_1, GPIO.OUT, initial=GPIO.HIGH)
GPIO.setup(RELAY_PIN_2, GPIO.OUT, initial=GPIO.HIGH)

def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))

    client.subscribe("/amber/1/1")
    client.subscribe("/amber/1/2")

def on_message(client, userdata, msg):
    if msg.topic == "/amber/1/1":
        if msg.payload == b'ON':
            GPIO.output(RELAY_PIN_1, GPIO.LOW)
        elif msg.payload == b'OFF':
            GPIO.output(RELAY_PIN_1, GPIO.HIGH)

    if msg.topic == "/amber/1/2":
        if msg.payload == b'ON':
            GPIO.output(RELAY_PIN_2, GPIO.LOW)
        elif msg.payload == b'OFF':
            GPIO.output(RELAY_PIN_2, GPIO.HIGH)

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("10.0.0.163", 1883, 60)

client.loop_start()

In case anyone is wondering, I have been trying to run this using the command python mqtt.py (with mqtt.py being the file name). Also, I am using Python2.7 in both IDLE and from the terminal.

2
  • If it thinks about it for a second then goes back to the prompt without error that normally means it's run to completion. May 3, 2017 at 17:30
  • That's one thought I had, but the client.loop_start line should keep it going until canceled . . . or at least I thought it should. Either way, it continues to run and listen for MQTT posts when running from IDLE. May 3, 2017 at 17:33

1 Answer 1

1

When you call loop_start() you start the client on another thread, but right after that the script ends and the process terminates and so nothing happens.

If you want the client to keep running, either sleep() in your main thread after loop_start(), or instead, call loop_forever(), which will loop in the current thread and so your script will not terminate.

See the network loop section in the documentation.

1
  • That was it. Thank you! I knew it had to be something simple. The tutorial I was working with showed nothing about calling loop_forever(). Just goes to show I should read the documentation closer. May 3, 2017 at 19:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.