Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 5091

Python • Re: Help Request: Loading Python Script at Boot / Script Behaves Erratically

$
0
0
I appreciate the continued attention on this. This isn't a problem I can solve myself, and I am grateful for your help.

I edited my script to capture full traceback:

Code:

import RPi.GPIO as GPIOimport osimport timeimport randomimport paho.mqtt.client as mqttimport subprocess# ---------------------# for loggingimport loggingimport tracebackimport sys logging.basicConfig(filename='/home/pi/touch_play_random.log', level=logging.ERROR)def log_exception(exc_type, exc_value, exc_tb):    error_message = ''.join(traceback.format_exception(exc_type, exc_value, exc_tb))    logging.error(error_message)sys.excepthook = log_exception# ---------------------# MQTT SetupMQTT_BROKER = '192.168.1.35'MQTT_PORT = 1883MQTT_TOPIC = 'home/ham_radio_touch'MQTT_USERNAME = <redacted>MQTT_PASSWORD = <redacted>MQTT_KEEPALIVE = 60client = mqtt.Client()client.username_pw_set(MQTT_USERNAME, MQTT_PASSWORD)client.will_set(MQTT_TOPIC, 'DISCONNECTED', qos=1, retain=True)def on_connect(client, userdata, flags, rc):    if rc == 0:        print("Connected to MQTT Broker!")    else:        print("Failed to connect, return code %d\n", rc)def on_disconnect(client, userdata, rc):    print("Disconnected from MQTT Broker")    if rc != 0:        print("Unexpected disconnection, trying to reconnect")        try:            client.reconnect()        except Exception as e:            print(f"Reconnection failed: {e}")client.on_connect = on_connectclient.on_disconnect = on_disconnectclient.connect(MQTT_BROKER, MQTT_PORT, MQTT_KEEPALIVE)client.loop_start()# GPIO SetupTOUCH_PIN = 17  # The GPIO pin connected to the sensor outputAUDIO_FILES_DIR = "/home/pi/audio"  # Directory containing the audio filesAUDIO_FILES = [f"{i:02}.mp3" for i in range(1, 29)]  # List of audio files (01.mp3, 02.mp3, ..., 28.mp3)GPIO.setmode(GPIO.BCM)GPIO.setup(TOUCH_PIN, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)# State definitionsIDLE = 0TOUCH_DETECTED = 1DEBOUNCE_TIME = 2  # secondsprevious_state = IDLElast_touch_time = time.time()def play_audio():    selected_file = random.choice(AUDIO_FILES)    file_path = os.path.join(AUDIO_FILES_DIR, selected_file)    subprocess.run(['mpg123', file_path])try:    while True:        current_state = GPIO.input(TOUCH_PIN)        current_time = time.time()                if current_state == GPIO.HIGH and previous_state == IDLE and (current_time - last_touch_time > DEBOUNCE_TIME):            client.publish(MQTT_TOPIC, 'ON', qos=1)            play_audio()            previous_state = TOUCH_DETECTED            last_touch_time = current_time                    elif current_state == GPIO.LOW and previous_state == TOUCH_DETECTED and (current_time - last_touch_time > DEBOUNCE_TIME):            client.publish(MQTT_TOPIC, 'OFF', qos=1)            previous_state = IDLE            last_touch_time = current_time                time.sleep(0.1)except KeyboardInterrupt:    GPIO.cleanup()    client.disconnect()
Had some problems with my pi account having access to write the .log files but got those straightened out and rebooted.

Waited about 3 minutes, checked via terminal:

Code:

pi@hallicrafterss20r:~ $ python3 /home/pi/touch_play_random.pyConnected to MQTT Broker!
Then I grabbed the two log files. I had trouble attaching those here -- the forum is giving me an error message. So here they are in Dropbox:

touch_play_random.service.log: https://www.dropbox.com/scl/fi/dm23kob4 ... 0xb98&dl=1

touch_play_random.log:
https://www.dropbox.com/scl/fi/0fwel5um ... 2nns7&dl=1

Statistics: Posted by grantalewis — Thu Jul 25, 2024 11:53 am



Viewing all articles
Browse latest Browse all 5091

Trending Articles