Skip to content

Instantly share code, notes, and snippets.

@bphermansson
Last active June 11, 2017 18:19
Show Gist options
  • Save bphermansson/757b9317e28564ca8b81a5fc6765ef34 to your computer and use it in GitHub Desktop.
Save bphermansson/757b9317e28564ca8b81a5fc6765ef34 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
#
# tvonoff.py
# This script uses a Pir sensor and a IR diode to turn on a tv when motion is detected.
# It uses time to only turn on tv at daytime.
# It also has a time out, if no motion is detected for a set period the tv is turned off.
# Another function is to send Mqtt messages when tv is turned on or off.
#
# The software irsend from Lirc is used to send codes.
# /usr/bin/irsend SEND_ONCE Samsung_BN59-00685A KEY_POWER
from time import time, sleep
import datetime
import os # For running external commands
import RPi.GPIO as GPIO
import paho.mqtt.client as paho
import urlparse
# Mqtt
mqttc = paho.Client()
url_str = 'mqtt://192.168.1.79:1883'
url = urlparse.urlparse(url_str)
mqttc.username_pw_set("emonpi", "pass")
# Setup Gpio
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(13, GPIO.IN) #Output from PIR motion sensor connected to pin 13
hour=0
def sendmqtt(mess):
#print "Send mqtt"
now = datetime.datetime.now()
mqttc.connect(url.hostname, url.port)
mqttc.publish("pir/hallway", str(now) + mess)
def printtime():
# Current time
global hour
now = datetime.datetime.now()
hour = str(now.hour)
min = str(now.minute)
print "Time now: " + hour + ":" + min
# time()
# Return the time in seconds since the epoch as a floating point number.
starttime = int(round(time() * 1000)) # Store start time
print "Starttime:"
print starttime
sendmqtt("Tvonoff started")
tvstatus="on"
printtime()
while True:
i=GPIO.input(13)
if i==0: #When output from motion sensor is LOW, no movement
timenow = int(round(time() * 1000))
if timenow - starttime > 1000000: # 100000 millis * 60 = 10 minutes
printtime()
print "Time out, set tv off (if on)"
if tvstatus=="on":
# Tv off
os.system('/usr/bin/irsend SEND_ONCE -#3 Samsung_BN59-00685A KEY_POWER')
tvstatus="off"
print "Tv off"
sendmqtt("Tv off")
starttime = timenow # Reset counter
elif i==1: #When output from motion sensor is HIGH, movement detected
printtime()
#print hour
print "Movement detected",i
print "Tv status: " + tvstatus
timenow = int(round(time() * 1000))
print timenow - starttime
if tvstatus=="off":
print "Movement and tv is off"
# Check if its daytime, ie ok to turn on tv
print "Hour now: ", hour
print type(hour)
if int(hour)>7 and int(hour) < 21:
# Turn tv on and change status
print "Tv turns on";
os.system('/usr/bin/irsend SEND_ONCE -#3 Samsung_BN59-00685A KEY_POWER')
tvstatus="on"
print "Tv on"
sendmqtt("Tv on")
# Reset timer
starttime = int(round(time() * 1000))
#print tvstatus # For debug
sleep(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment