Skip to content

Instantly share code, notes, and snippets.

@davidwowa
Created September 21, 2019 22:51
Show Gist options
  • Save davidwowa/5b531e9e39b96bcdeea4246874b1865c to your computer and use it in GitHub Desktop.
Save davidwowa/5b531e9e39b96bcdeea4246874b1865c to your computer and use it in GitHub Desktop.
import os
import sys
import paho.mqtt.client as mqtt
import RPi.GPIO as GPIO
import time
import Adafruit_DHT
import threading
pid = str(os.getpid())
pidfile = "/tmp/3dprinter.pid"
print("init DHT22")
sensor = Adafruit_DHT.DHT22
pin=23
# voltage 3.5V
relais_pin=17
#GPIO.cleanup()
GPIO.setwarnings(True)
GPIO.setmode(GPIO.BCM)
GPIO.setup(relais_pin,GPIO.OUT)
def on_connect(client, userdata, flags, rc):
print("Connected with result code " + str(rc))
client.subscribe("3dprinter/voltage")
def on_message(client, userdata, msg):
#print(str(msg.payload))
if 'true' in str(msg.payload):
GPIO.output(relais_pin,0)
time.sleep(0.4)
print("3d printer voltage on")
elif 'false' in str(msg.payload):
GPIO.output(relais_pin,1)
time.sleep(0.3)
print("3d printer voltage off")
else:
print("no allowed message for 3d printer voltage")
def state_loop():
while True:
humidity,temperature = Adafruit_DHT.read_retry(sensor, pin)
if humidity is not None and temperature is not None:
print("Temp={0:0.1f}*C Humidity={1:0.1f}%".format(temperature, humidity))
client.publish("3dprinter/state", str(temperature)+":"+str(humidity)+":"+str(GPIO.input(relais_pin)))
else:
print("Failed to get reading. Try again!")
if GPIO.input(relais_pin) == GPIO.LOW:
print("Printer is on")
else:
print("Printer is off")
time.sleep(2)
def pidloop():
if os.path.isfile(pidfile):
print("exit, subscriber works")
sys.exit()
f=open(pidfile,'w')
print("write pid")
f.write(pid)
try:
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("server", 1883, 60)
thread = threading.Thread(target=state_loop)
thread.start()
thread2 = threading.Thread(target=pidloop)
thread2.start()
client.loop_start()
client.loop_forever()
except KeyboardInterrupt:
GPIO.cleanup()
os.unlink(pidfile)
print("end")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment