Example #1
0
def raiseLower(state, factory):

    # Purpose:  Raise or lower pneumatic lift

    # Assume:   None

    # End:      Pneumatics raised or lowered

    # Input:    Desired state (raise = true, lower = false)
    #           factory (IP address)

    # Output:   None

    # Set Pi pins for controlling two pneumatic solenoids
    Sol1 = gpiozero.DigitalOutputDevice(17,
                                        active_high=True,
                                        pin_factory=factory)
    Sol2 = gpiozero.DigitalOutputDevice(27,
                                        active_high=True,
                                        pin_factory=factory)

    # If True raise pneumatic actuators else lower them
    if state == True:
        Sol1.on()
        Sol2.off()
    else:
        Sol1.off()
        Sol2.on()
Example #2
0
    def __init__(self, objcfg):
        # Initiate mux control output pins using gpiozero
        self.coin = gpiozero.DigitalOutputDevice(objcfg.mux_coin, True, False,
                                                 None)
        self.tilt = gpiozero.DigitalOutputDevice(objcfg.mux_tilt, True, False,
                                                 None)
        self.action = gpiozero.DigitalOutputDevice(objcfg.mux_action, True,
                                                   False, None)

        # Initiate mux input pins using gpiozero
        self.input = [None] * 8
        self.input[0] = gpiozero.InputDevice(objcfg.mux.input[0], True, None,
                                             None)
        self.input[1] = gpiozero.InputDevice(objcfg.mux.input[1], True, None,
                                             None)
        self.input[2] = gpiozero.InputDevice(objcfg.mux.input[2], True, None,
                                             None)
        self.input[3] = gpiozero.InputDevice(objcfg.mux.input[3], True, None,
                                             None)
        self.input[4] = gpiozero.InputDevice(objcfg.mux.input[4], True, None,
                                             None)
        self.input[5] = gpiozero.InputDevice(objcfg.mux.input[5], True, None,
                                             None)
        self.input[6] = gpiozero.InputDevice(objcfg.mux.input[6], True, None,
                                             None)
        self.input[7] = gpiozero.InputDevice(objcfg.mux.input[7], True, None,
                                             None)
Example #3
0
def vpump(state, factory):

    # Purpose:  Turn on and off vacuum
    #           Close vacuum solenoid when vacuum pump is on
    #           Open vacuum solenoid when vacuum pump is off (vent vacuum)

    # Assume:   None

    # End:      Vacuum turned on or off

    # Input:    Desired state (on = true, off = false)
    #           factory (IP address)

    # Output:   None

    # Set Pi pins for controlling vacuum pump and vacuum solenoid
    vPump = gpiozero.DigitalOutputDevice(19,
                                         active_high=True,
                                         pin_factory=factory)
    vSol = gpiozero.DigitalOutputDevice(15,
                                        active_high=True,
                                        pin_factory=factory)

    # If True enable vacuum else disable vacuum
    if state == True:
        vPump.on()
        vSol.off()
    else:
        vPump.off()
        vSol.on()
    def __init__(self, opin, cpin):
        self._open = gpiozero.DigitalOutputDevice(opin)
        self._close = gpiozero.DigitalOutputDevice(cpin)

        self._isOpen = None
        # Close the shutter, to put it into a known state.
        self.close()
Example #5
0
 def __init__(self, neutral=RELAY_3_PIN, up=RELAY_1_PIN, down=RELAY_2_PIN):
     if not MOCK:
         self._neutral = gpiozero.DigitalOutputDevice(neutral)
         self._up = gpiozero.DigitalOutputDevice(up)
         self._down = gpiozero.DigitalOutputDevice(down)
     else:
         self._neutral = GPIOMock(neutral)
         self._up = GPIOMock(up)
         self._down = GPIOMock(down)
     self.running_task = None  # Stores current async task being run
Example #6
0
    def __init__(self, DO_DIRECTION_PIN, DO_RESET_PIN, DI_FAULT_PIN, ARGS):

        self.REG = {  # AMIS-30543 Registers
            'WR': 0x00,
            'CR0': 0x01,
            'CR1': 0x02,
            'CR2': 0x03,
            'CR3': 0x09,
            'SR0': 0x04,
            'SR1': 0x05,
            'SR2': 0x06,
            'SR3': 0x07,
            'SR4': 0x0A
        }

        self.CMD = {  # AMIS-30543 Command constants
            'READ': 0x00,
            'WRITE': 0x80
        }

        self.dirctrl = ARGS[0]
        self.pwmf = ARGS[1]
        self.pwmj = ARGS[2]
        self.sm = ARGS[3]
        self.mult = ARGS[4]
        self.dist = ARGS[5]
        self.step = ARGS[6]

        self.VAL = {
            'WR': 0b00000000,  # no watchdog
            'CR0': 0b00010111 | self.sm,  # & 2.7 A current limit
            'CR1': 0b00000000 | self.dirctrl | self.pwmf
            | self.pwmj,  # & step on rising edge & fast slopes
            'CR2':
            0b00000000,  # motor off & no sleep & SLA gain @ 0.5 & SLA no transparent
            'CR3':
            0b00000000  #,                                         # no extended step mode
            #'dist': self.dist,
            #'step': self.step
        }

        # InitGPIO

        PWM.setup(5, 0)  # 5 us pulse_incr, 0 delay_hw
        PWM.init_channel(0, 3000)  # DMA channel 0, 3000 us subcycle time

        self.DO_RESET = gpiozero.DigitalOutputDevice(DO_RESET_PIN)
        self.DO_DIRECTION = gpiozero.DigitalOutputDevice(DO_DIRECTION_PIN)
        self.DI_NO_FAULT = gpiozero.DigitalInputDevice(DI_FAULT_PIN)

        self.spi = SpiDev()
        self.spi.open(0, 0)
        self.spi.max_speed_hz = 1000000

        self.RegisterSet()
Example #7
0
 def __init__(self, mass, cd, motor_right_pin, motor_left_pin, solenoid_pin):
     self.mass = mass
     self.cd = cd
     self.motor_right = gpiozero.DigitalOutputDevice(motor_right_pin)
     self.motor_left = gpiozero.DigitalOutputDevice(motor_left_pin)
     self.solenoid = gpiozero.DigitalOutputDevice(solenoid_pin)
     self.motor_left.off()
     self.motor_right.off()
     self.solenoid.off()
     self.main_valve_open = False
     self.fill_drain_open = False
 def __init__(self,jp,logger):
     # Initlize sensor interface, datalogger, & controller settings
     self.jp     = jp
     self.logger = logger
     self.settings = ControlSettings()
     # Sets up the GPIO interface for valve control.
     self.inlet = gpiozero.DigitalOutputDevice(17, active_high=True, initial_value=True) #starts open
     self.inspir = gpiozero.PWMOutputDevice(22, active_high=True, initial_value=0, frequency = 20) #starts closed
     self.expir = gpiozero.DigitalOutputDevice(27, active_high=False, initial_value=True) #Starts open
     # Initialize control state (assume I.C. is inhale) 
     self._state = 0
     self.__inhale()
     # Keep's track of how long each state lasts
     self.state_time = time.time()
Example #9
0
    def __init__(self, name, **kwargs):
        """
        Same as :class:`Relay`, but also requires kwarg `gpio_pin`, which
        refers to the GPIO pin number connected to the relay. Optionally,
        pass a `duty_cycle` and `cycle_time` parameter to enable duty-cycling
        of the relay. `duty_cycle` should be a floating-point percentage of on time
        and `cycle_time` should be the total time for each duty cycle in
        floating-point seconds. You can also provide `active_high` (boolean) to
        determine whether or not the relay will be sent a high (1) signal to
        turn on, or a low(0), defaults to True.

        .. warning::

            This class has no error checking for duty cycle config. If you use
            short cycle times you could, at the very least, prematurely wear out
            your relay, or do much worse to anything connected on the other side
            of it (such as refrigeration units). Use at your own risk.

        """
        if "gpio_pin" not in kwargs:
            raise ConfigurationError(
                "No gpio_pin specified in relay configuration")
        self._output_device = gpiozero.DigitalOutputDevice(
            pin=int(kwargs['gpio_pin']),
            active_high=kwargs['active_high'],
            initial_value=False # keep relay turned off initially
        )
        super(GPIORelay, self).__init__(name, **kwargs)
Example #10
0
    def __init__(self, pins=[0, 0, 0, 0], port=None, resol=1, cogfact=1.0):
        self.en = None
        self.step = None
        self.chop = None
        self.dir = None
        self.en = gpiozero.DigitalOutputDevice(pins[0], initial_value=True)
        self.step = gpiozero.PWMOutputDevice(pins[1], initial_value=0)
        self.chop = gpiozero.DigitalOutputDevice(pins[2], initial_value=True)
        self.dir = gpiozero.DigitalOutputDevice(pins[3], initial_value=False)
        self.resol = resol
        self.cogfact = cogfact
        self.pulse = 3e-6

        self.port = port
        if self.port:
            self._setup()
Example #11
0
 def __init__(self, name, config, config_filepath):
     self.i = 0
     super().__init__(name, config, config_filepath)
     self.recording = False
     self.temps = collections.deque(maxlen=500)
     self.set_temp = 0
     self.row = []
     #time.sleep(30)
     # initialize clients
     self._heater_client = gpiozero.DigitalOutputDevice(pin=18)  #yaqc.Client(38455)
     self._heater_client.value = 0
     self._temp_client = yaqc.Client(39001)
     self._temp_client.measure(loop=True)
     self._pressure_client_a = yaqc.Client(39100)
     #self._pressure_client_a.set_state(gain=2, size=16)
     self._pressure_client_a.measure(loop=True)
     self._pressure_client_b = yaqc.Client(39101)
     #self._pressure_client_b.set_state(gain=2, size=16)
     self._pressure_client_b.measure(loop=True)
     self._pressure_client_c = yaqc.Client(39102)
     #self._pressure_client_c.set_state(gain=2, size=16)
     self._pressure_client_c.measure(loop=True)
     # begin looping
     self._pid = PID(Kp=0.2, Ki=0.001, Kd=0.01, setpoint=0, proportional_on_measurement=True)
     self._loop.create_task(self._runner())
Example #12
0
    def __init__(self, spi, cs_pin, pwm_pin) -> None:
        '''
        `UI_LEDs(spi, cs, pwm)` initializes the UI LEDs with the given SPI core
        `spi`, Chip Select pin number `cs`, and PWM pin number `pwm`, and finally
        turns all the LEDs off.

        Args:
            `spi` (gpiozero.SPIDevice): the SPI device to use
            `cs_pin` (int): the GPIO pin number to use for Chip Select
            `pwm_pin`(int): the GPIO pin number to use for the PWM brightness control

        Note:
            prefer pins 12, 13, 18, or 19 for the PWM pin, these are hardware
            PWM pins, other pins will use software PWM.

        Side effects:
            turns all the LEDs off

        Raises:
            PinInvalidPin if either the `cs` or `pwm` pins are not valid pin numbers.
        '''
        self.spi = spi
        self.chip_sel = gpiozero.DigitalOutputDevice(cs_pin, active_high=False)
        self.pwm = gpiozero.PWMOutputDevice(
            pwm_pin, active_high=False, initial_value=0.0)

        self.all_off()
        self._cached_write = 0
Example #13
0
    def __init__(self, player):
        """Initalise I/O"""
        try:
            # Setup the MCLK out of GPIO 4 for DAC
            call([
                "/home/pi/XTEC-PiPlayer/minimal_clk/minimal_clk", "19.23M",
                "-q"
            ])

            self.player = player
            self.input_1 = gpiozero.DigitalInputDevice(pin="GPIO16",
                                                       pull_up=True)
            self.input_2 = gpiozero.DigitalInputDevice(pin="GPIO17",
                                                       pull_up=True)
            self.input_1.when_activated = self.input_1_active
            self.input_1.when_deactivated = self.input_1_inactive
            self.input_2.when_activated = self.input_2_active
            self.input_2.when_deactivated = self.input_2_inactive

            self.output_1 = gpiozero.DigitalOutputDevice(pin="GPIO12",
                                                         initial_value=False)
            self.output_2 = gpiozero.DigitalOutputDevice(pin="GPIO13",
                                                         initial_value=False)

            self.player.bind_to_playing(
                self.player_playing_event)  # Player "playing" callback
            self.player.bind_to_not_playing(
                self.player_not_playing_event)  # Player "not playing" callback

        except Exception as ex:
            print('Digital I/O: Error starting: ' + str(ex))

        # Check boot options
        try:
            config = configparser.ConfigParser()
            config.read(config_path)
            if config['MP2']['output1'] == 'on_boot':
                self.output_1.on()
            if config['MP2']['output1'] == 'pulse_boot':
                self.output_1.blink()
            if config['MP2']['output2'] == 'on_boot':
                self.output_2.on()
            if config['MP2']['output2'] == 'pulse_boot':
                self.output_2.blink()

        except Exception as ex:
            print('Digital I/O: Player play error: ' + str(ex))
Example #14
0
    def __init__(self, steprefresh=1):
        # Variables
        self.servotime = 0.5
        self.steptime = 0.01  # 100 Hz step frequency
        self.steprefresh = steprefresh  # timespan of stepping sequence [s]
        self.just_length = 24  # justification length

        # Initialization
        self.SERVO_1 = gpiozero.Servo(24)
        self.SERVO_2 = gpiozero.Servo(25)

        self.MOSFET1_G = gpiozero.DigitalOutputDevice(12, initial_value=False)
        self.MOSFET2_G = gpiozero.DigitalOutputDevice(16, initial_value=False)
        self.MOSFET3_G = gpiozero.DigitalOutputDevice(20, initial_value=False)
        self.MOSFET4_G = gpiozero.DigitalOutputDevice(21, initial_value=False)

        self.COIL_1 = gpiozero.DigitalOutputDevice(17, initial_value=False)
        self.COIL_2 = gpiozero.DigitalOutputDevice(27, initial_value=False)
        self.COIL_3 = gpiozero.DigitalOutputDevice(22, initial_value=False)
        self.COIL_4 = gpiozero.DigitalOutputDevice(5, initial_value=False)

        self.LIGHT = gpiozero.DigitalOutputDevice(13, initial_value=False)
        self.BUZZER = gpiozero.DigitalOutputDevice(6, initial_value=False)

        self.SWITCH_1 = gpiozero.Button(14)
        self.SWITCH_2 = gpiozero.Button(15)
        self.SWITCH_3 = gpiozero.Button(18)
        self.SWITCH_4 = gpiozero.Button(23)
        self.SWITCH_5 = gpiozero.Button(26)  # BCM 26 (Mission Cont Shutdown)
        self.SWITCH_6 = gpiozero.Button(19)  # BCM 19 (Limit switch input)

        self.BATTERY = gpiozero.MCP3008(channel=0)
        self.AMBIENT = gpiozero.MCP3008(channel=1)
        self.BUTTON1 = gpiozero.MCP3008(channel=2)
        self.BUTTON2 = gpiozero.MCP3008(channel=3)
        self.POTMETR = gpiozero.MCP3008(channel=4)
        self.SWITCH_7 = gpiozero.MCP3008(channel=5)  # Spare limit switch input
        self.SWITCH_8 = gpiozero.MCP3008(channel=6)  # Spare limit switch input

        self.COILS_FWD = [self.COIL_1, self.COIL_2, self.COIL_3, self.COIL_4]
        self.COILS_REV = [self.COIL_4, self.COIL_3, self.COIL_2, self.COIL_1]
        self.SWITCHES = [
            self.SWITCH_1, self.SWITCH_2, self.SWITCH_3, self.SWITCH_4
        ]
        self.MOSFETS = [
            self.MOSFET1_G, self.MOSFET2_G, self.MOSFET3_G, self.MOSFET4_G
        ]
Example #15
0
def configure_digital_outputs(configured_devices, output_devices):
    digital_outputs = pull_end_devices('digital', output_devices, 'output')

    for gpio in digital_outputs:
        try:
            configured_devices[gpio['id']] = gpiozero.DigitalOutputDevice(gpio['pin'])
        except gpiozero.GPIOPinInUse:
            logging.error('Pin %s is already in use and cannot be assigned to %s!', gpio['pin'], gpio['name'])
Example #16
0
def init():
    global pumpPowerIO, heaterPowerIO, heaterEnableIO, valve1DirIO, valve2DirIO
    global sparePowerIO, activityLedIO, activityLedRtnIO

    try:
        # set up I/O pins
        pumpPowerIO = gz.DigitalOutputDevice(config.PUMP_PIN,
                                             active_high=True,
                                             initial_value=False)
        heaterPowerIO = gz.DigitalOutputDevice(config.HEATER_PIN,
                                               active_high=True,
                                               initial_value=False)
        heaterEnableIO = gz.DigitalOutputDevice(config.HEATER_EN_PIN,
                                                active_high=True,
                                                initial_value=False)
        valve1DirIO = gz.DigitalOutputDevice(config.VALVE1_DIR_PIN,
                                             active_high=True,
                                             initial_value=False)
        valve2DirIO = gz.DigitalOutputDevice(config.VALVE2_DIR_PIN,
                                             active_high=True,
                                             initial_value=False)
        sparePowerIO = gz.DigitalOutputDevice(config.SPARE_PIN,
                                              active_high=True,
                                              initial_value=False)
        activityLedIO = gz.DigitalOutputDevice(config.LED_PIN,
                                               active_high=True,
                                               initial_value=False)
        activityLedRtnIO = gz.DigitalOutputDevice(config.LED_RTN_PIN,
                                                  active_high=True,
                                                  initial_value=False)

        # ensure all are off
        pumpPowerIO.off()
        heaterPowerIO.off()
        heaterEnableIO.off()
        valve1DirIO.off()
        valve2DirIO.off()
        sparePowerIO.off()
        activityLedIO.off()
        activityLedRtnIO.off()

    except:
        log.log(log.ERROR, "Error initializing equipment")
        return ERROR

    # initialize project globals
    gv.pumpPower = OFF
    gv.heatPower = OFF
    gv.heatEnable = OFF
    gv.valveMode = VALVE_POOL_MODE
    gv.sparePower = OFF

    log.log(log.ALWAYS, "Equipment init complete")
    return NOERROR
Example #17
0
    def CreateIO( self, name:str, pin:int):
        if len(name) > 10:
            return False

        if DEBUG:
            self.__ioData.append([name, pin, False])
        else:
            self.__ioData.append([name, gpiozero.DigitalOutputDevice(pin),False])

        return True
Example #18
0
def alert(event):
    buzzer = gpio.DigitalOutputDevice("GPIO4", active_high=False)
    while True:
        event.wait()
        for i in range(0,4):
            buzzer.on()
            #print("buzzing...")#debug
            sleep(0.2)#sleep(cfg.alert_interval)
            buzzer.off()
            sleep(0.2)

        event.clear()
Example #19
0
 def __init__(self):
     AbstractSensor.__init__(self)
     self.measurements = {
         "O2": [-1, "%"],
         "O2voltage": [-1, "V"],
     }
     self._spi = SpiDev(0, 0)
     self._CS = gpiozero.DigitalOutputDevice(5, initial_value=True)
     #self._MISO = gpiozero.DigitalInputDevice(9)
     self._spi.open(0, 0)
     self._spi.max_speed_hz = 500
     self._spi.no_cs = True
     self.generateCalibCurve()
Example #20
0
    def __init__(self):
        """Create an instance of the main video player application class"""
        print("Player: Creating instance")
        # First, we create a player that plays a black screen and stops. This is a little bit of a hacky way to get
        # a black background which we still have control over, but it works, and performance is good
        self.black = OMXPlayer('/home/pi/XTEC-PiPlayer/black.mp4', dbus_name='org.mpris.MediaPlayer2.omxplayerblack', \
            args=['--no-osd', '--no-keys', '-b', '--end-paused', '--layer='+str(LAYER_UNMUTE)])

        # Set OMX players (None until a video is loaded)
        self.omxplayer_playing = None
        self.omxplayer_loaded = None

        # Variables tracking videos playing and loaded
        self.playing_video_number = None  # Playing video file number
        self.loaded_video_number = None  # Loaded video file number
        self.playing_video_path = None  # Playing video file path
        self.loaded_video_path = None  # Loaded video file path
        self.is_playing = False  # If we're currently playing something (i.e. not paused)
        self.is_looping = False  # If we're looping
        self._dbus_id = 0  # Increments whenever a video is loaded, to ensure videos don't clash in dbus name
        self._check_end_thread = None  # Thread that is used for checking end of video

        # Events for anyone observing playing and not playing events
        self.playing_observers = []
        self.not_playing_observers = []
        # self.playing_event = Event()        # Playing event. Called when player starts playing
        # self.not_playing_event = Event()    # Not playing event. Called when player isn't playing.

        # GPIO for DAC mute. Starts unmuted
        self.gpio_unmute = gpiozero.DigitalOutputDevice(pin="GPIO22",
                                                        initial_value=True)
        # Setup operation status led outputs
        self.led_red = gpiozero.DigitalOutputDevice(pin="GPIO44",
                                                    initial_value=False)
        self.led_green = gpiozero.DigitalOutputDevice(pin="GPIO45",
                                                      initial_value=False)

        # Main folder where SD card is mounted, and where videos are stored
        self.video_folder = storage.SD_STORAGE_PATH
Example #21
0
def LAMove(move, factory):

    # Purpose:  Move LA to the move location
    #           Wait until movement has been carried out
    #           Can only move LA away from home

    # Assume:   None

    # End:      LA moved to input location

    # Input:    move = [x, y, z, a, b]
    #           factory (IP address)

    # Output:   True = moved to location
    #           False = couldn't move to location

    # Print y destination
    y = move[1]
    print('LA moving to ' + str(y))

    # Set Pi pin for direction
    DIR = gpiozero.DigitalOutputDevice(20,
                                       active_high=False,
                                       pin_factory=factory)
    DIR.off()  # Sets direction to away from home

    # Conversion constants
    d2p = 400 / 5  # 400 pulses per rev / 5mm lead
    p2t = 1 / 1600  # frequency is 1600Hz

    # Calculate time to sleep and print it
    # If time calculated is too great return False
    t = abs(y) * d2p * p2t
    print('Time: ' + str(t))
    if t > 16:
        return False

    # Start step pulse and sleep for calculated time
    STEP = gpiozero.PWMOutputDevice(21,
                                    active_high=False,
                                    initial_value=0.5,
                                    frequency=1600,
                                    pin_factory=factory)
    sleep(t)

    # End step pulse
    STEP.off()

    # Print destination reached
    print('LA moved to ' + str(y))
    return True
Example #22
0
    def MoveRel(self, moveDist_steps):
        # Set up move
        distMoved_steps = 0

        try:
            # Assign pin that pulse train will be on
            pulse = gpiozero.DigitalOutputDevice(self.stepPin)
            # Assign pin based on direction of move (positive/clockwise, negative/counterclockwise)
            if moveDist_steps > 0:
                dir = gpiozero.DigitalOutputDevice(self.dirPin,
                                                   initial_value=True)
            else:
                dir = gpiozero.DigitalOutputDevice(
                    self.dirPin)  # initial_value = False
            # Do move
            while distMoved_steps < abs(moveDist_steps):
                # Generate pulse train
                pulse.on()
                sleep(1 / (self.frequency * 2))
                pulse.off()
                sleep(1.0 / (self.frequency * 2))
                # Update relevant values
                distMoved_steps += 1

        except Exception as e:
            # Re-raise exception
            raise
        finally:
            # Update current position with actual distance moved
            if dir.value > 0:
                self.currentPosition += distMoved_steps
            else:
                self.currentPosition -= distMoved_steps
            # Cleanup
            pulse.off()
            dir.off()
            pulse.close()
            dir.close()
Example #23
0
def __wait_and_squirt(should_stop, predictions, labels):
    output = gpiozero.DigitalOutputDevice('GPIO14')

    while not should_stop.is_set():
        class_predictions = dict(zip(labels, predictions))
        bad_cat_detected = class_predictions['black-cat'] >= 0.9

        if bad_cat_detected:
            log_info('Squirting cat')
            output.on()
            time.sleep(2.0)
            output.off()
        
        should_stop.wait(timeout=0.1)
    def __init__(self, guizero_app, direction_pin, pwm_pin):
        self.guizero_app = guizero_app

        self.accelerometer = mpu6050(0x68)

        # The way my accereometer is oriented:
        #  9.8 Gs on Z axis -->     slat is flat --> blinds open
        # zero Gs on Z axis --> slat is vertical --> blinds closed
        self.accelerometer_z_Gs_blinds_closed = 5.5
        self.accelerometer_z_Gs_blinds_open = 9.7

        self.gpio_device_motor_direction = gpiozero.DigitalOutputDevice(
            direction_pin)
        self.gpio_device_motor_speed = gpiozero.PWMOutputDevice(
            pwm_pin, initial_value=0, frequency=20_000)
Example #25
0
def toggle_relay(pin=RELAY_PIN, new_state=False):
    """Toggle a generic relay connected via GPIO on or off."""

    # Hack to avoid pins being reset, until this is fixed in gpiozero
    def close(self):  # pylint: disable=unused-argument
        pass

    gpiozero.pins.rpigpio.RPiGPIOPin.close = close

    print(f"Turning relay {'on' if new_state else 'off'}")
    relay = gpiozero.DigitalOutputDevice(
        pin,
        active_high=False,
        initial_value=new_state,
        pin_factory=gpiozero.pins.rpigpio.RPiGPIOFactory())
    return relay
Example #26
0
 def setup(self, port, direction):
     try:
         p = hal.GPIOActor.getPin(self, port)
         if str(p) in self.Pins:
             gpio = self.Pins[str(p)]
             gpio.close()
             self.Pins[str(p)] = None
         if direction == 'in':
             self.Pins[str(p)] = gpiozero.DigitalInputDevice(p)
         if direction == 'out':
             self.Pins[str(p)] = gpiozero.DigitalOutputDevice(p)
         if direction == 'tristate':
             self.Pins[str(p)] = gpiozero.DigitalInputDevice(p)
         return True
     except BaseException as e:
         logging.debug("Exception:" + str(e))
         return False
def main():
    """ main function """
    # get environment variable(s)
    try:
        opencpn_pkill_delay = int(os.environ[PKILL_DELAY])
    except KeyError:
        print("{} environment variable not defined, quitting".format(PKILL_DELAY))
        sys.exit(1)
    try:
        opencpn_user = os.environ[PKILL_USER]
    except KeyError:
        print("{} environment variable not defined, quitting".format(PKILL_USER))
        sys.exit(1)

    # the shutdown pin, active state is high
    shutdown_button = gpiozero.Button(SHUTDOWN_PIN,
                                      pull_up=None,
                                      active_state=True,
                                      hold_time=SHUTDOWN_PULSE_MINIMUM/1000.0)

    # the "i am running" pin
    running_device = gpiozero.DigitalOutputDevice(MCU_RUNNING_PIN,
                                                  active_high=True,
                                                  initial_value=True)

    # set initial state
    running_device.on()

    sleep_interval = 1                             # start out with 1 second sleep
    while True:
        if shutdown_button.is_pressed:
            sleep_interval = SHUTDOWN_WAIT_DELAY / 1000.0
            if shutdown_button.is_held:
                print("Detected shutdown signal, powering off..")
                os.system("/usr/bin/pkill -u {} opencpn".format(opencpn_user))
                time.sleep(opencpn_pkill_delay)
                # execute the shutdown command
                os.system("/usr/bin/sudo /sbin/poweroff")
                sys.exit(0)
        else:
            sleep_interval = 1
        time.sleep(sleep_interval)
Example #28
0
def LAHome(factory):

    # Purpose:  Send LA to home position

    # Assume:   None

    # End:      LA located in its home position

    # Input:    factory (IP address)

    # Output:   True = reached home
    #           False = failed to reach home

    print('LA going home')

    # Set Pi pins for reading limit switch, controlling direction, and outputting a step pulse
    HOME = gpiozero.Button(14, pull_up=False, pin_factory=factory)
    DIR = gpiozero.DigitalOutputDevice(20,
                                       active_high=False,
                                       pin_factory=factory)
    DIR.on()  # Sets direction towards home
    STEP = gpiozero.PWMOutputDevice(21,
                                    active_high=False,
                                    initial_value=0.5,
                                    frequency=1600,
                                    pin_factory=factory)

    tStart = time.time()

    # Wait until limit switch is triggered then disable step pulse and return True
    # If limit switch isn't triggered for 30 sec disable step pulse and return False
    while HOME.value == 1:
        STEP.off()
        DIR.off()
        tCurr = time.time()
        if tCurr - tStart > 16:
            STEP.off()
            DIR.off()
            return False
    print('LA home')
    return True
Example #29
0
def drop(factory):

    # Purpose:  Trigger Heina drop

    # Assume:   Phone mounted on carriage in correct orientation

    # End:      Phone dropped and in drop box

    # Input:    factory (IP address)

    # Output:   None

    # Set Pi pin for triggering drop
    drop = gpiozero.DigitalOutputDevice(26,
                                        active_high=True,
                                        pin_factory=factory)

    # Trigger drop then wait and reset
    drop.on()
    sleep(1)
    drop.off()
Example #30
0
def main(argv):
    fanPin = 23
    tempThres = 55
    hysteresis = 5
    fan_is_off = True
    try:
        opts, args = getopt.getopt(argv, "hp:t:b:",
                                   ["pin=", "threshold_temp=", "hysteresis="])
    except getopt.GetoptError:
        print(
            'autoFan.py -p <fan_GPIO> -t<threshold_temp(\'C)> -b <hysteresis>')
        sys.exit()
    for opt, arg in opts:
        if opt == '-h':
            print(
                'autoFan.py -p <fan_GPIO> -t<threshold_temp(\'C)> -b <hysteresis>'
            )
        elif opt in ("-p", "--pin"):
            fanPin = arg
        elif opt in ("-t", "--threshold_temp"):
            tempThres = float(arg)
        elif opt in ("-b", "--hysteresis"):
            hysteresis = float(arg)

    fan = gpiozero.DigitalOutputDevice(fanPin)
    while (True):
        curr_temp = float(getCPUtemperature())
        if curr_temp >= tempThres:
            if fan_is_off:
                fan.on()
                fan_is_off = False
        else:
            if not fan_is_off:
                if curr_temp <= tempThres - hysteresis:
                    fan.off()
                    fan_is_off = True

        #print(f'CPU Temperature is :{curr_temp}')
        sleep(2)