mti840-projet/device/device/things.py

69 lines
1.4 KiB
Python

import time
import atexit
import logging
import threading
import RPi.GPIO as GPIO
TRIG = 11 # gpio pin 17
ECHO = 12 # gpio pin 18
CLOSED = 16 # gpio pin 23
OPEN = 18 # gpio pin 24
logger = logging.getLogger('device')
door_state = 'closed'
def setup():
logger.info('Setting up GPIO')
GPIO.setmode(GPIO.BOARD)
GPIO.setup(TRIG, GPIO.OUT)
GPIO.setup(ECHO, GPIO.IN)
GPIO.setup(CLOSED, GPIO.OUT)
GPIO.setup(OPEN, GPIO.OUT)
default_states()
def default_states():
change_door_state(door_state, True)
@atexit.register
def cleanup():
logger.info('Cleaning up')
GPIO.cleanup()
def distance():
GPIO.output(TRIG, 0)
time.sleep(0.000002)
GPIO.output(TRIG, 1)
time.sleep(0.00001)
GPIO.output(TRIG, 0)
while GPIO.input(ECHO) == 0:
a = 0
time1 = time.time()
while GPIO.input(ECHO) == 1:
a = 1
time2 = time.time()
during = time2 - time1
return during * 340 / 2 * 100
def change_door_state(state, force=False):
global door_state
if state == door_state and not force:
return
if state == 'open':
GPIO.output(OPEN, 1)
GPIO.output(CLOSED, 0)
timer = threading.Timer(10.0, change_door_state, args=('closed',))
timer.start()
elif state == 'closed':
GPIO.output(OPEN, 0)
GPIO.output(CLOSED, 1)
door_state = state
logger.info('Door state changed to %s', state)