Eg: connect a wire to GPIO pin 21 and the other end to ground and it will detect it as being closed, remove the wire and it detects as open.
Good for using with Magnetic reed switches around the house which are simple open or closed circuits.
Script sends status of switch to Domoticz on first launch and any time the state changes.
Instructions:
1) Change the GPIO Pin variable if you are using a GPIO other than 21
2) Set Domoticz ipaddress, username, password and IDX in the requests.get sections
3) Install the requirements for Python requests: apt-get install python-requests python3-requests
Code: Select all
# Requirements (covers multiple versions of Python):
# apt-get install python-requests python3-requests
import RPi.GPIO as GPIO
import time
import requests
from time import sleep
from requests.auth import HTTPBasicAuth
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
# Raspberry GPIO Configuration
gpiopin = 21
GPIO.setmode(GPIO.BCM)
GPIO.setup(gpiopin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
previous = "null"
while True:
state = GPIO.input(gpiopin)
if state == False and previous == "open" or state == False and previous == "null":
print('Circuit Closed.')
requests.get('https://IPADDRESS/json.htm?type=command¶m=switchlight&idx=IDX&switchcmd=Off', auth=('USERNAME', 'PASSWORD'), verify=False)
previous = "closed"
if state != False and previous == "closed" or state != False and previous == "null":
print('Circuit Open.')
requests.get('https://IPADDRESS/json.htm?type=command¶m=switchlight&idx=IDX&switchcmd=On', auth=('USERNAME', 'PASSWORD'), verify=False)
previous = "open"
sleep(1)
GPIO.cleanup(gpiopin)