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, spi_bus=0, spi_device=0, spi_freq=12000000, verbose_level=VerboseLevel.NONE): # -------------------Hardware modules init------------------------ # Instanciate a SPI controller. self.spi = spidev.SpiDev() # Open SPI device self.spi.open(spi_bus, spi_device) # Configure SPI speed self.spi.max_speed_hz = spi_freq # Init interrup pin self.int_pin = InputDevice("GPIO6") self.reset_pin = OutputDevice("GPIO5") self.reset_pin.on() # -------------------Private variables definition------------------ self.video_mode = VideoMode.OBP self.video_status = VideoStatus.IDLE self.verbose_level = verbose_level self.video_data_size = 6400 self.serial = (0, 0, 0) self.temp_raw = 0 self.temp = 0 self.brightness_live_change = False self.contrast_live_change = False self.brightness_live_value = 0 self.contrast_live_value = 0
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)
class Bistrobot: def __init__(self, feeder_pin, sensor_pin): self.feeder = OutputDevice(feeder_pin) self.sensor = Button(sensor_pin) def get_sensor_status(self): return self.sensor.is_pressed def reset_rotation(self): if not self.sensor.is_pressed: self.feeder.on() while not self.sensor.is_pressed: pass while self.sensor.is_pressed: pass feeder.off() def trigger_portion(self): if not self.sensor.is_pressed: self.feeder.on() while not self.sensor.is_pressed: pass sleep(0.2) self.feeder.off() self.feeder.on() while self.sensor.is_pressed: pass sleep(0.2) self.feeder.off() def serve_meal(self, portions, wait_time=100): for i in range(0, portions): self.trigger_portion() if i < portions - 1: sleep(wait_time)
class GPIOResource(resource.Resource): def get_link_description(self): # Publish additional data in .well-known/core return dict(**super().get_link_description(), title=f"GPIO Resource - pin: {self.pin}") def __init__(self, pin): super().__init__() self.pin = pin self.resource = OutputDevice(pin) async def render_get(self, request): print(f'GPIO {self.pin}: GET') payload = f"{self.resource.value}" return Message(payload=payload.encode(), code=Code.CONTENT) async def render_post(self, request): payload = request.payload.decode() print(f'GPIO {self.pin}: POST {payload}') if payload in ['0', 'off']: self.resource.off() elif payload in ['1', 'on']: self.resource.on() else: return Message(code=Code.BAD_REQUEST) return Message(code=Code.CHANGED)
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, 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, 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, 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, in1, in2, in3): self.direction = OutputDevice(in1, initial_value=True) # direction Pin self.speed = PWMOutputDevice(in2, initial_value=1, frequency=980) # speed Pin self.encoder = DigitalInputDevice(in3) #self.encoder = SmoothedInputDevice(in3, threshold=0.01, partial=True) self.total_time = 1.0 / (self.speed.frequency / 2.0)
class FIT_Motor: def __init__(self, in1, in2, in3): self.direction = OutputDevice(in1, initial_value=True) # direction Pin self.speed = PWMOutputDevice(in2, initial_value=1, frequency=980) # speed Pin self.encoder = DigitalInputDevice(in3) #self.encoder = SmoothedInputDevice(in3, threshold=0.01, partial=True) self.total_time = 1.0 / (self.speed.frequency / 2.0) def changeDirection(self): self.direction.toggle() def setStop(self): self.speed.on() def setSpeed(self, speed): speed_val = abs(speed) / 20.8 if speed_val < 0.01: self.setStop() else: self.speed.blink(on_time=self.total_time - speed_val * self.total_time, off_time=self.total_time * speed_val) def readEncoder(self, val): # print("Nothing") reading = self.encoder.value return reading
def __init__(self, node1, node2, node3, node4): self.anode = InputDevice(node1) self.cathode = InputDevice(node2) self.node1 = node1 self.node2 = node2 self.node3 = node3 self.node4 = node4
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, 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)
class Led: def __init__(self, pin): self._led_output = OutputDevice(pin) def on(self): self.state = True def off(self): self.state = False @property def state(self): return self._led_output.value @state.setter def state(self, value: bool): self._led_output.value = value def release(self): self.off() self._led_output.close() def __enter__(self) -> "Led": self.on() return self def __exit__(self, type, value, traceback): self.off()
class Letter: def __init__(self, index, on_plug_callback, on_unplug_callback, reaction_pin, led_pin, success_color): self._color = None self.index = index self.on_plug_callback = on_plug_callback self.on_unplug_callback = on_unplug_callback self.reaction_pin = InputDevice(reaction_pin, pull_up=True) self.is_chopstick_plugged = self.reaction_pin.is_active self.led_pin = OutputDevice(led_pin) self.success_color = success_color @property def color(self): return self._color @color.setter def color(self, value): self._color = value if value == 'blue': self.led_pin.on() else: self.led_pin.off() logger.info("Letter {}: {}".format(self.index, value)) def check_chopstick(self): if self.reaction_pin.is_active != self.is_chopstick_plugged: self.is_chopstick_plugged = self.reaction_pin.is_active if self.is_chopstick_plugged: self.on_plug_callback(self.index) else: self.on_unplug_callback(self.index) def reaction_do_nothing(self): pass def reaction_toggle_blue_orange(self): if self.color == "blue": self.color = "orange" elif self.color == "orange": self.color = "blue" else: logger.info("Color is {}: nothing to do".format(self.color)) def reaction_set_blue(self): self.color = "blue" def reaction_set_orange(self): self.color = "orange" def reaction_switch_off(self): self.color = "switched_off" def __bool__(self): return self.color == self.success_color
class RelayManager(): def __init__(self, pin): self.relay = OutputDevice(pin) def Switch(self, state): if state == True: self.relay.off() elif state == False: self.relay.on()
def blink(out: OutputDevice, count: int): for i in range(count): out.on() print(f'Output @ {out.pin} is ON [{i+1}/{count}]') time.sleep(1) out.off() print(f'Output @ {out.pin} is OFF') time.sleep(1)
class WaterGun(object): def __init__(self, gpio_num): self.gun = OutputDevice(gpio_num, active_high=False) def fire(self, shots_num): self.gun.on() time.sleep(shots_num) self.gun.off()
def _align(self, new_state: bool, output: OutputDevice, name: str): if new_state: if not output.is_active: output.on() self.log.info(f'{name}@{output.pin}:ON') else: if output.is_active: output.off() self.log.info(f'{name}@{output.pin}:OFF')
def __init__(self, pin, i2c_port=1): """ Configures the GPIO pin powering the magnetometer. Initializes I2C communication to HMC5883L magnetometer. """ self.gpio = OutputDevice(pin) logger.info("Configured GPIO pin %d for magnetometer power" % pin) self.hmc = i2c_hmc5883l(i2c_port, gauss=self.lower_bound) logger.info("Initialized I2C communication at port %d" % i2c_port)
def pwm_on(self, anode, cathode, fade_in, fade_out, n): self.last_off() self.anode = PWMOutputDevice(anode) self.cathode = OutputDevice(cathode) self.anode.pulse(fade_in_time=fade_in, fade_out_time=fade_out, n=n, background=False) self.cathode.off()
def __init__(self, reset_pin, increment_pin, change_time=0, background=True): self._reset_pin = OutputDevice(reset_pin) self._increment_pin = DigitalOutputDevice(increment_pin) self.change_time = change_time self.background = background self.reset()
def __init__(self, resetPin, readyPin, address=IQS5xx_DEFAULT_ADDRESS): self.address = address self._resetPinNum = resetPin self._readyPinNum = readyPin self._resetPin = OutputDevice(pin=self._resetPinNum, active_high=False, initial_value=True) self._readypin = DigitalInputDevice(pin=self._readyPinNum, active_state=True, pull_up=None)
class DoorRemote: def __init__(self): self._garageOpener = OutputDevice(18, active_high=False, initial_value=False) pass def click_door(self): logging.info("Clicking door") self._garageOpener.on() time.sleep(.5) self._garageOpener.off()
class Lock: def __init__(self, pin, pulse=100): self._output = OutputDevice(pin=pin, active_high=False, initial_value=False) self._pulse = pulse def unlock(self): self._output.on() sleep(self._pulse / 1000) self._output.off()
class RelayHeaterThermostat(Thermostat): def __init__(self, pin, hostname, port=5000): self.relay = OutputDevice(pin) super().__init__(hostname, port) def commandState(self, state): if state == True: self.relay.on() elif state == False: self.relay.off() super().commandState(state)
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, 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 __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 door_bell(motion_gpio, relay_gpio, sense_time=2): ms = MotionSensor(motion_gpio, threshold=0.4) doorbell = OutputDevice(relay_gpio) while True: if ms.motion_detected: x = time.time() while time.time() - x < sense_time: if not ms.motion_detected: break else: doorbell.on()
class Driver(object): """ Driver for siren modules; receives commands from SignalTowerServer """ def __init__(self, green_pin, red_pin, siren_pin): super(Driver, self).__init__() self.green_light = OutputDevice(green_pin) self.red_light = OutputDevice(red_pin) self.siren = OutputDevice(siren_pin) def exec_instr(self, instruction): if instruction[0]: self.green_light.on() else: self.green_light.off() if instruction[1]: self.red_light.on() else: self.red_light.off() if instruction[2]: self.siren.on() else: self.siren.off()
def __init__(self, green_pin, red_pin, siren_pin): super(Driver, self).__init__() self.green_light = OutputDevice(green_pin) self.red_light = OutputDevice(red_pin) self.siren = OutputDevice(siren_pin)
def __init__(self): self._garageOpener = OutputDevice(18, active_high=False, initial_value=False) pass