Toggle relay with push button and remote control?

Hello,

I have a 3d printer with octoprint and i want to improve its control.
I want a way to turn on and off the printer by pushing a button next to the printer or using the telegram bot when I'm far from the printer.

I came from C++ and Arduino so i'm not very familiar with python and raspberry.
I created a script Toggle_Relay.py that reverse the state of a pin to turn on and off the printer and it works. Now i want to add the push button but I have some problem to develop the script because it works only one time I push the button, then the file "Toggle_Relay.py" is already imported and I can't reuse it. Do you have any suggestions? Maybe this is not the best forum where ask something like this but who knows :stuck_out_tongue:

These are the scripts:

Toggle_Relay.py:

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

GPIO.setup(17,GPIO.OUT)

GPIO.output(17, not(GPIO.input(17)))

time.sleep(1)

Button.py:

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

GPIO.setup(27,GPIO.IN,pull_up_down=GPIO.PUD_UP)

while True:
	buttonState = GPIO.input(27)
	if buttonState == False: #false = pressed
		import Toggle_Relay
		print("pressed")
		time.sleep(1)

thanks
jackyjoy

Export the button on Pi startup by /etc/rc* and create a shell script with the switch command.
From OctoPrint call that shell script.
Works pritty well. I drive multiple "things" attached directly to Pi's GPIO.

There is almost no need to use Python to do it. You can just use the Pi internal support and do it by shell commands.

thanks my issue has been fixed.

if you are familiar with C / C++ / programming on system level, it might be much easier for you to do it directly ahead Pi's OS.
Some weeks ago I did an upload with some code snippets how it can be done.

https://community.octoprint.org/t/manual-plugin-installation-pi-gpiosupport/26561?u=bastelulli

... and it depands of the switch, but it might be good to debounce.