hakkoso/actuators.py

59 lines
1.7 KiB
Python

import atexit
try:
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
rpi = True
except:
rpi = False
class Actuator():
def __init__(self):
pass
class GPIOPin(Actuator):
def __init__(self, *args, **kwargs):
self.pin = (kwargs.pop('pin'))
self.initial = (kwargs.pop('initial'))
self.onstate = (kwargs.pop('onstate'))
self.offstate = (kwargs.pop('offstate'))
GPIO.setup(self.pin, GPIO.OUT, initial=self.initial)
atexit.register(self.deinit)
super().__init__(*args, **kwargs)
def deinit(self):
# Be sure everything is off at exit
print('Cleaning before exit')
GPIO.output(self.pin, self.initial)
GPIO.cleanup()
def enable(self, enable=True):
GPIO.output(self.pin, self.onstate) if enable else self.disable()
def disable(self):
GPIO.output(self.pin, self.offstate)
class MockPIN(Actuator):
def __init__(self, *args, **kwargs):
self.pin = (kwargs.pop('pin'))
self.initial = (kwargs.pop('initial'))
self.onstate = (kwargs.pop('onstate'))
self.offstate = (kwargs.pop('offstate'))
super().__init__(*args, **kwargs)
def enable(self, enable=True):
pass
# print('FAKE ENABLE') if enable else self.disable()
def disable(self):
pass
# print('FAKE DISABLE')
actuators = {
'heater': (GPIOPin if rpi else MockPIN)(pin=22, initial=GPIO.HIGH, onstate=GPIO.LOW, offstate=GPIO.HIGH),
'fan': (GPIOPin if rpi else MockPIN)(pin=27, initial=GPIO.HIGH, onstate=GPIO.LOW, offstate=GPIO.HIGH),
'humidifier': (GPIOPin if rpi else MockPIN)(pin=17, initial=GPIO.HIGH, onstate=GPIO.LOW, offstate=GPIO.HIGH),
}