Last active
September 21, 2021 10:14
-
-
Save bphermansson/3fd1ce0fa41bfc4ca2600d5cf4b41504 to your computer and use it in GitHub Desktop.
Python script to send Mqtt message when Gpio on Raspberry Pi changes, for example triggered by a motion sensor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
# Read a Pir-sensor and send a Mqtt message when motion detected | |
# Uses edge detection to limit the rate of Mqtt-messages | |
import paho.mqtt.client as paho | |
import time | |
import urlparse | |
import RPi.GPIO as GPIO | |
import datetime | |
# Mqtt | |
mqttc = paho.Client() | |
url_str = 'mqtt://192.168.1.79:1883' | |
url = urlparse.urlparse(url_str) | |
mqttc.username_pw_set("emonpi", "emonpimqtt2016") | |
# Setup Gpio | |
GPIO.setwarnings(False) | |
GPIO.setmode(GPIO.BOARD) | |
GPIO.setup(13, GPIO.IN) # Output from PIR motion sensor connected to pin 13 | |
def printtime(): # Used for debug | |
# Current time | |
global hour, minute, wholetime | |
now = datetime.datetime.now() | |
hour = str(now.hour) | |
minute = int(now.minute) | |
minute = '%02d' % minute | |
wholetime = hour + ":" + minute | |
def sendmqtt(mess): | |
try: | |
mqttc.connect(url.hostname, url.port) | |
mqttc.publish("pir/hallway", mess) | |
sleep(5) | |
except: | |
pass | |
sendmqtt("Pirmqtt started") | |
while True: | |
try: | |
GPIO.wait_for_edge(13, GPIO.RISING) | |
#printtime() | |
#print "Time now: " + wholetime | |
#print("Motion detected") | |
sendmqtt("on") | |
time.sleep(5) | |
sendmqtt("off") | |
time.sleep(5) | |
except KeyboardInterrupt: | |
# quit | |
sys.exit() |
vargatomy
commented
Aug 12, 2021
via email
Thanks! :)
…On 2021. 08. 12. 14:44, Patrik Hermansson wrote:
***@***.**** commented on this gist.
------------------------------------------------------------------------
You have to be careful with indentation with Python.
It has to look like this:
|def sendmqtt(mess): try: mqttc.connect(url.hostname, url.port) |
and not like this:
|def sendmqtt(mess): try: mqttc.connect(url.hostname, url.port) |
—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
<https://gist.github.com/3fd1ce0fa41bfc4ca2600d5cf4b41504#gistcomment-3858098>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/AMC6CGISZJSB3AQE7HCGWSTT4O64LANCNFSM5B7OPTAQ>.
Triage notifications on the go with GitHub Mobile for iOS
<https://apps.apple.com/app/apple-store/id1477376905?ct=notification-email&mt=8&pt=524675>
or Android
<https://play.google.com/store/apps/details?id=com.github.android&utm_campaign=notification-email>.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment