# File for using Grove Relay (http://www.seeedstudio.com/wiki/Grove_-_Relay) # NOTE: Relay is normally open. LED will illuminate when closed and you will hear a definitive click sound from enum import Enum from grovepi import grovepi import logging class RelayMode(Enum): on = 1 off = 0 class Relay: def __init__(self, port, initial_position=RelayMode.off): """Constructor of a Relay instance :param int port: The port where is connected the relay :param RelayMode initial_position: The initial position. Should be an instance of RelayMode """ self.port = port self.initial_position = initial_position grovepi.pinMode(self.port, "OUTPUT") # Write the initial position to the relay if initial_position == RelayMode.on: self.on() else: self.off() def on(self): """Function to put the relay on on mode""" RelayInterface(self.port).on() def off(self): """Function to put the relay on off mode""" RelayInterface(self.port).off() def __enter__(self): logging.info( 'Relay on port {port} has started with mode {mode}'.format( port=self.port, mode=self.initial_position.name ) ) # We make accessible this relay instance return self def __exit__(self, exc_type, exc_val, exc_tb): # Always turn off the relay before leaving self.off() logging.info('Relay on port {port_number} has finished'.format(port_number=self.port)) class RelayInterface: def __init__(self, port): self.port = port def on(self): """Function to put the relay on on mode""" logging.debug('Relay on port {port_number} is now on'.format(port_number=self.port)) self.write(RelayMode.on) def off(self): """Function to put the relay on off mode""" logging.debug('Relay on port {port_number} is now off'.format(port_number=self.port)) self.write(RelayMode.off) def write(self, mode): """Write the mode on the relay :param RelayMode mode: the mode to write :return: """ grovepi.digitalWrite(self.port, mode.value)