def __init__(self, *args, **kwargs): super(SecureFloor, self).__init__(*args, **kwargs) self.status = 'playing' self.success = False self.clear_alarm_delay = self.config['clear_alarm_delay'] self.clear_alarm_task = None self.tare = OutputDevice(self.config['load_cells']['tare_pin']) self.tare.off() self.leds = {} self.cells = [] self.toggle_tasks = {} for cell in self.config['load_cells']['cells']: self.cells.append((Cell(cell['pin'], self.on_load_cell_toggle, cell['led_strip']))) self.toggle_tasks[cell['pin']] = None if cell['led_strip']: self.leds[cell['led_strip']] = 'black' self.sleep_mode_task = None # Init once we are sure the serial port will be able to receive data reactor.callLater(3, self.set_led_color, "black", sum(self.leds.keys()))
def __init__(self, up_pin, down_pin, up_down_minimum_delay): # Never have those the two pins active at the same time or the electronics might crash self.motor_up = OutputDevice(up_pin, active_high=False) self.motor_up.off() self.motor_down = OutputDevice(down_pin, active_high=False) self.motor_down.off() self.up_down_minimum_delay = up_down_minimum_delay
def __init__(self, server_connection, tree_id, moisture_channel=0, water_channel=1, water_pump_gpio=26, sensor_switch_gpio=7, dht_gpio=17): super().__init__(server_connection) self.moisture = MCP3008(channel=moisture_channel) self.water_level = MCP3008(channel=water_channel) self.water_pump = OutputDevice(pin=water_pump_gpio, active_high=False) self.dht_sensor = DHT22(dht_gpio) self.current_moisture_level = 0 self.sensor_switch = OutputDevice(pin=sensor_switch_gpio, active_high=True) self.server_connection = server_connection self.current_temperature = 0 self.current_humidity = 0 self.tree_id = tree_id self.hx = HX711(5, 6) self.hx.set_reading_format("MSB", "MSB") referenceUnit = 261 * 1.34 * 0.9 * 1.05 self.hx.set_reference_unit(referenceUnit) self.hx.set_offset(-5600) self.current_weight = 0 self.watering_mode = False
def __init__(self): self.running = True self.current_temp = 0 # Restore last set temperature from file (if exists) if STATE_PATH.is_file(): with open(STATE_PATH) as f: try: self.goal_temp = float(f.read()) # Set default if state file is empty except ValueError: self.goal_temp = DEFAULT_GOAL_TEMP else: self.goal_temp = DEFAULT_GOAL_TEMP # Relay I/O self.circulation_pump_relay = OutputDevice(17) self.jets_pump_relay = OutputDevice(22) self.heater_relay = OutputDevice(27) # Circulation pump always on self.circulation_pump_relay.on() # Background threads self.read_temp_thread = Thread(target=self.read_temp) self.manage_temp_thread = Thread(target=self.manage_temp) self.read_temp_thread.start() self.manage_temp_thread.start() # Handle SIGTERM signal(SIGTERM, self.stop)
def arm_bomb(self): if gpioctrl: explode = OutputDevice(gpioexplode, active_high=False) explode2 = OutputDevice(gpioexplode2, active_high=False) takephoto() logging.debug("ARM button pressed! Arming bomb now!") self.statusled.blink(on_time=0.05, off_time=0.05) self.buzzer.source = self.statusled.values else: logging.debug("Arming bomb now!") stoptimers(1) if gpioctrl: time.sleep(2.5) explode.on() time.sleep(0.8) explode2.on() takephoto() time.sleep(2) takephoto() explode.off() time.sleep(1) explode2.off() takephoto() closeall(0, 0)
class DiscreteFan: """ Represents a fan with 3 discrete power levels. Power levels can be chosen mechanically with buttons on the fan or via the software. The fan itself is controlled by rewiring the incoming AC to one of 3 inputs (PL1, PL2, PL3) To control the rewiring we use the 4 NC-relays R1, R2, R3 and R4. AC | R1 _1/ 0______ | | R4 _1/ 0_ | | | | MC off R2 _1/ 0____ | | | R3 _1/ 0_ | | | PL2 PL1 PL3 Layout is mainly due to place restriction inside of the AC-Box of the fan and is designed to use the MC in case the program is not running. So R4 switches between 1=mechanical control (MC) and 0=software control (SC). Note: R4 is hardwired to GND so its always off as long as the pi is powered R2 and R3 are used to set the power level as: R2 | R3 || PL 0 | 0 || 3 0 | 1 || 1 1 | 0 || 2 1 | 1 || 2 """ # GPIO pins __r1 = OutputDevice(16) __r2 = OutputDevice(20) __r3 = OutputDevice(21) def __init__(self): self.current_power_level = None self.set_power_level(0) def say_hallo(self): logger.info('hi') self.__r3.value = True sleep(0.25) self.__r2.value = True sleep(0.25) self.__r3.value = False sleep(0.25) self.__r2.value = False def set_power_level(self, power_level): if power_level == self.current_power_level or power_level > 3 or power_level < 0: return None logger.info(f'changing power level to {power_level}') self.current_power_level = power_level self.__r1.value = power_level == 0 self.__r2.value = power_level == 2 self.__r3.value = power_level == 1
def __init__(self, in1, in2, in3, in4): self._in1 = OutputDevice(in1) # blue self._in2 = OutputDevice(in2) # pink self._in3 = OutputDevice(in3) # yellow self._in4 = OutputDevice(in4) # orange self._pins = [self._in1, self._in2, self._in3, self._in4] self.steps = 0 self._direction = -1 self._currentStep = 0 self._sequence = [ # from datasheet, in sequence as is: CW # reverse sequence will just go CCW [0, 0, 0, 1], [0, 0, 1, 1], [0, 0, 1, 0], [0, 1, 1, 0], [0, 1, 0, 0], [1, 1, 0, 0], [1, 0, 0, 0], [1, 0, 0, 1] ] self._maxStep = len(self._sequence)
def __init__(self, remote_address): # set PINs on BOARD log.debug("Initializing Motors...") log.debug("> back left PIN: " + str(_conf['motor_back_left_pin'])) log.debug("> back right PIN: " + str(_conf['motor_back_right_pin'])) log.debug("> front left PIN: " + str(_conf['motor_front_left_pin'])) log.debug("> front right PIN: " + str(_conf['motor_front_right_pin'])) # using OutputDevice rem_pi = PiGPIOFactory(host=remote_address) # left self.motor2_back = OutputDevice(pin=_conf['motor_back_left_pin'], pin_factory=rem_pi) self.motor2_front = OutputDevice(pin=_conf['motor_front_left_pin'], pin_factory=rem_pi) # right self.motor1_back = OutputDevice(pin=_conf['motor_back_right_pin'], pin_factory=rem_pi) self.motor1_front = OutputDevice(pin=_conf['motor_front_right_pin'], pin_factory=rem_pi) # directions self.motor1_direction = Value("i", 0) self.motor2_direction = Value("i", 0) # queues and processes log.debug("Initializing Motors queues and processes...") self.queue1 = Queue() self.queue2 = Queue() self.process1 = Process(target=self.M1) self.process2 = Process(target=self.M2) self.process1.start() self.process2.start() log.debug("...init done!")
def __init__(self, ip=None, alias='gpio_monitor', listen_pins=[21, 20], trigger_pins=[16, 26], log_filename='/home/guy/Documents/AlarmMonitor.log'): # listen_pins = [sys.arm, alarm.on], trigger_pins=[full, home] self.last_state = [None for i in range(4)] self.cbit = cbit.CBit(1000) if ip is not None: self.factory = PiGPIOFactory(host=ip) else: self.factory = None self.ip_pi = getip.get_ip()[0] self.alias = alias self.fullarm_hw = OutputDevice(trigger_pins[0], pin_factory=self.factory) self.homearm_hw = OutputDevice(trigger_pins[1], pin_factory=self.factory) self.sysarm_hw = Button(listen_pins[0], pin_factory=self.factory) self.alarm_hw = Button(listen_pins[1], pin_factory=self.factory) self.logger = Log2File(log_filename, name_of_master=self.alias, time_in_log=1, screen=1) self.check_state_on_boot(trigger_pins, listen_pins) self.monitor_state()
def __init__(self, winch: Winch): logger.debug("IO : Initialize Hardware...") super().__init__(winch) # Power self.__power_cmd = OutputDevice(OUT_PWR) self.__power_cmd.off() # Reverse self.__reverse_cmd = OutputDevice(OUT_REVERSE) # Speed mode (Lo, Medium, Hi) self.__speed_cmd = OutputDevice(OUT_SPD) # Throlle self.__throttle_cmd = PWMOutputDevice(OUT_THROTTLE) # Move self.__key_enter_btn = Button(IN_KEY_ENTER) self.__key_left_btn = Button(IN_KEY_LEFT) self.__key_right_btn = Button(IN_KEY_RIGHT) # Register event self.__key_enter_btn.when_pressed = self.__pressedEnter self.__key_left_btn = self.__pressedLeft self.__key_right_btn = self.__pressedRight
def __init__(self, remote_address): # set PINs on BOARD log.debug("Initializing Distance...") log.debug("> echo 1 pin: " + str(_conf['echo_1_pin'])) log.debug("> trig 1 pin: " + str(_conf['trig_1_pin'])) log.debug("> echo 2 pin: " + str(_conf['echo_2_pin'])) log.debug("> trig 2 pin: " + str(_conf['trig_2_pin'])) # using InputDevice and OutputDevice rem_pi = PiGPIOFactory(host=remote_address) self.distance1_trig = OutputDevice(pin=_conf['trig_1_pin'], pin_factory=rem_pi) self.distance1_echo = InputDevice(pin=_conf['echo_1_pin'], pin_factory=rem_pi) self.distance2_trig = OutputDevice(pin=_conf['trig_2_pin'], pin_factory=rem_pi) self.distance2_echo = InputDevice(pin=_conf['echo_2_pin'], pin_factory=rem_pi) # values self.distance1 = Value('i', 0) self.distance2 = Value('i', 0) # processes log.debug("Initializing Distance processes...") self.process1 = Process(target=self.D1) self.process2 = Process(target=self.D2) self.process1.start() self.process2.start() log.debug("...init done!")
def __init__(self, enablePin, directionPin, pulsePin, stepsPerRev=3200.0): self.stepsPerDeg = stepsPerRev / 360.0 self.enable = OutputDevice(enablePin) self.direction = OutputDevice(directionPin) self.pulse = OutputDevice(pulsePin) self.pos = 0 self.home = 0 self.on()
def __init__(self, IN1, IN2, PWM, STBY): self.input_1 = OutputDevice(IN1) self.input_2 = OutputDevice(IN2) self.speed_control = PWMOutputDevice(PWM) self.standby = OutputDevice(STBY) self.standby.on() self.speed_control.value = 1
def __init__( self, name, pins, min_angle=-5, max_angle=365, positive=1, vend=5000, vstart=20, skewness=0.75, # accel_steps=4000, accel_steps=500, skewnessbra=0.9, bra_steps=500, ): def _accel_velocity(x): """ calculate the acceleration/deceleration velocity in the interval [0,1] """ return (0.5 - 0.5 * cos(x * pi)) * (vend - vstart) + vstart def _accel_skewing(x): """ skew the velocity cosine by a parabolic function """ return pow(x, skewness) / pow(accel_steps, skewness) def _bra_skewing(x): """ skew the velocity cosine by a parabolic function """ return pow(x, skewnessbra) / pow(bra_steps, skewnessbra) self.logger = logging.getLogger(__name__) self.name = name self._steps_per_rev = 0 self._enabled = True self._angle = 0 self._min_angle = min_angle self._max_angle = max_angle self._steps = 0 self._stop = True self._delay = 1.0 / vend self._positive = positive self._brake_steps = accel_steps self.PUL = OutputDevice(pins[0]) self.DIR = OutputDevice(pins[1]) self.ENBL = OutputDevice(pins[2]) self._accel_curve = [ 1.0 / _accel_velocity(_accel_skewing(x)) for x in range(accel_steps) ] # self._accel_curve = np.linspace(.05, 1./vend, bra_steps) self._bra_curve = [ 1.0 / _accel_velocity(_bra_skewing(x)) for x in range(bra_steps) ]
def __init__(self, stepDir, mode): self.stepPins_ = [ OutputDevice(gpios['MOTORIN1']), OutputDevice(gpioPins['MOTORIN2']), OutputDevice(gpioPins['MOTORIN3']), OutputDevice(gpioPins['MOTORIN4']) ] self.stepDir_ = stepDir #Set 1 for clockwise self.mode_ = mode # mode = 1: Low Speed ==> Higher Power # mode = 0: High Speed ==> Lower Power self.stepCount = len(sequence()) self.stepCounter_ = 0
def hardware_gpio(self, trigger_pins, listen_pins): self.fullarm_hw = OutputDevice(trigger_pins[0], pin_factory=self.factory, initial_value=None) self.homearm_hw = OutputDevice(trigger_pins[1], pin_factory=self.factory, initial_value=None) self.sysarm_hw = Button(listen_pins[0], pin_factory=self.factory) self.alarm_hw = Button(listen_pins[1], pin_factory=self.factory) self.check_state_on_boot(trigger_pins, listen_pins)
def __init__(self, pin, remotehost=None): if remotehost == None: self.relay = OutputDevice(pin, active_high=False, initial_value=False) else: factory = PiGPIOFactory(host=remotehost) self.relay = OutputDevice(pin, active_high=False, initial_value=False, pin_factory=factory)
def __init__(self, initial_value, pin_1, pin_2, pin_3, pin_4): self.pins = [ OutputDevice(pin_1), OutputDevice(pin_2), OutputDevice(pin_3), OutputDevice(pin_4) ] self.pin_states = [False, False, False, False] self._value = initial_value self.value = initial_value self.on = False
def __init__( self, # sleep_pin: int, step_pin: int, direction_pin: int, reverse: bool = False, step_type: StepType = StepType.FULL): # self.enable = OutputDevice(config.enable) # self.sleep = OutputDevice(sleep_pin, initial_value=True) self.step = OutputDevice(step_pin) self.direction = OutputDevice(direction_pin, initial_value=reverse) self.step_type: StepType = step_type
def __init__(self): if not is_raspberry_pi(): raise Exception("This class works only on Raspberry Pi") from gpiozero import PWMOutputDevice, OutputDevice self._yaw = 0.0 self._speed = 0.0 self._pwm_left = PWMOutputDevice(18, frequency=440) self._forward_left = OutputDevice(4) self._backward_left = OutputDevice(3) self._forward_right = OutputDevice(17) self._backward_right = OutputDevice(27) self._pwm_right = PWMOutputDevice(22, frequency=440)
def __init__(self): SOLENOID_PIN = [13, 16, 19, 21, 26, 20] for i in SOLENOID_PIN: self.SOLENOID.append(OutputDevice(i)) # for i in range(2, 6): # self.SOLENOID[i].on() self.off_all()
def grunt(): out = OutputDevice(6, False) out.on() sleep(0.126) out.toggle()
def whine(): out = OutputDevice(13, False) out.on() sleep(0.126) out.toggle()
def snore(): out = OutputDevice(19, False) out.on() sleep(0.126) out.toggle()
def hello(): out = OutputDevice(26, False) out.on() sleep(0.126) out.toggle()
def clean(): # PARAMS: pin, *, active_high=True, initial_value=0, frequency=100, pin_factory=None print("Starting cleaning time") with OutputDevice(4) as motor: motor.on() time.sleep(10) motor.off()
def main(argv): global ON_THRESHOLD, OFF_THRESHOLD, GPIO_PIN, SLEEP_INTERVAL parser = argparse.ArgumentParser(description='Fan control') parser.add_argument( '--on-threshold', dest='on_threshold', default=os.environ.get('ON_THRESHOLD'), help='(degrees Celsius) Fan kicks on at this temperature.') parser.add_argument( '--off-threshold', dest='off_threshold', default=os.environ.get('OFF_THRESHOLD'), help='(degress Celsius) Fan shuts off at this temperature.') parser.add_argument( '--sleep-interval', dest='sleep_interval', default=os.environ.get('SLEEP_INTERVAL'), help='(seconds) How often we check the core temperature.') parser.add_argument( '--gpio-pin', dest='gpio_pin', default=os.environ.get('GPIO_PIN'), help='Which GPIO pin you\'re using to control the fan.') args = parser.parse_args(args=argv) # Read input if args.on_threshold is not None: ON_THRESHOLD = int(args.on_threshold) if args.off_threshold is not None: OFF_THRESHOLD = int(args.off_threshold) if args.sleep_interval is not None: SLEEP_INTERVAL = int(args.sleep_interval) if args.gpio_pin is not None: GPIO_PIN = int(args.gpio_pin) # Validate the on and off thresholds if OFF_THRESHOLD >= ON_THRESHOLD: raise RuntimeError('OFF_THRESHOLD must be less than ON_THRESHOLD') print( f'Starting thresholds (OFF-ON): [{OFF_THRESHOLD},{ON_THRESHOLD}], poll interval: {SLEEP_INTERVAL}s and GPIO pin {GPIO_PIN}' ) fan = OutputDevice(GPIO_PIN) while True: temp = get_temp() # Start the fan if the temperature has reached the limit and the fan # isn't already running. # NOTE: `fan.value` returns 1 for "on" and 0 for "off" if temp > ON_THRESHOLD and not fan.value: fan.on() # Stop the fan if the fan is running and the temperature has dropped # to 10 degrees below the limit. elif fan.value and temp < OFF_THRESHOLD: fan.off() time.sleep(SLEEP_INTERVAL)
def __init__(self, day_temp, night_temp): self.set_day_temperature(day_temp) self.set_night_temperature(night_temp) self.set_temperature = self.day_temperature self.hc_thread = threading.Thread(target=self.heat_control_loop) self.hc_thread.start() self.heater = OutputDevice(HEATER_GPIO)
def __init__(self, pin_light_spruce: int, pin_light_oak_middle: int, pin_light_oak_sides: int, pin_led: int): """ Constructor. Initializes the class members responsible for controlling output devices. May throw ugly exceptions if the pins are already allocated by other systems. """ self.led = LED(pin_led, initial_value=False) self.light_spruce = OutputDevice(pin_light_spruce, active_high=False, initial_value=False) self.light_oak_middle = OutputDevice(pin_light_oak_middle, active_high=False, initial_value=False) self.light_oak_sides = OutputDevice(pin_light_oak_sides, active_high=False, initial_value=False)
class Buzzer: speaker = OutputDevice(13) sound = True t = None buzzing = False def __init__(self): self.t = Thread(target=self.run) def run(self): self.buzzing = True print("Starting sound") self.speaker.on() while self.buzzing: self.speaker.toggle() time.sleep(1 / 660) print("Stopping sound") self.speaker.off() self.buzzing = False def start(self): if not self.buzzing: self.t.start() def stop(self): if self.buzzing: self.buzzing = False print("Stopped sound") self.t = Thread(target=self.run)