class Motor: def __init__(self, forward, backward, active_high=True, initial_value=False, pin_factory=None, name=''): self.forward_motor = DigitalOutputDevice(pin=forward, active_high=active_high) self.backward_motor = DigitalOutputDevice(pin=backward, active_high=active_high) self.name = name def forward(self): self.forward_motor.on() self.backward_motor.off() print(self.name, 'forward') def backward(self): self.forward_motor.off() self.backward_motor.on() print(self.name, 'backward') def stop(self): self.forward_motor.off() self.backward_motor.off() print(self.name, 'stop') def close(self): self.forward_motor.close() self.backward_motor.close()
class Motor: """Klasse for å kontrollere en motor""" def __init__(self, forward, backward, pwm): // Disse er inn signalene til h-blokken self.forward = DigitalOutputDevice(forward) self.backward = DigitalOutputDevice(backward) self.pwm = PWMOutputDevice(pwm, True, 0, 1000) def speed(self, speed): """Justerer hastigheten og rettningen til motoren""" self.direction(speed) self.pwm.value = norm(speed) def direction(self, speed): """Bestemmer rettningen basert på hastigheten""" if speed > 0: self.forward.on() self.backward.off() else: self.forward.off() self.backward.on() def close(self): """Frigjør og rydder opp""" self.forward.close() self.backward.close() self.pwm.close()
def get_pressed(self): # don't want to reactivate this function, within this function: for obj in self._col_objects: obj.when_activated = None # have to close outputs to make them tristates for obj in self._row_objects: obj.close() row_tristates = [ DigitalInputDevice(pin, pull_up=None, active_state=True) for pin in self.row_pins ] # store the keypresses in pressed_keys pressed_keys = [] for row, pin in enumerate(self.row_pins): row_tristates[row].close() output = DigitalOutputDevice(pin) for col, obj in enumerate(self._col_objects): if obj.is_active: pressed_keys.append(self.keymap[row][col]) output.close() row_tristates[row] = DigitalInputDevice(pin, pull_up=None, active_state=True) # cleanup for obj in row_tristates: obj.close() self._reset_internal_objects() return pressed_keys
def wait_dup_ready(self): """ Function waits for DUP to indicate that it is ready. The DUP will pulls DD line low when it is ready. Requires DD to be input when function is called. Return: Returns 0 if function timed out waiting for DD line to go low Returns 1 when DUP has indicated it is ready. """ count = 0 dev_dd = DigitalOutputDevice(pin=self.pin_dd) dev_dd.on() dev_dd.close() self._wait() dev_dd = DigitalInputDevice(pin=self.pin_dd) while ((dev_dd.value == 1) and count < 16): # Clock out 8 bits before checking if DD is low again for _ in range(8): self.dev_dc.on() self._wait() self.dev_dc.off() self._wait() count += 1 dev_dd.close() if count == 16: raise FlashError("Timeout for wait dup read")
class TB6612FNG: def __init__(self, pin_fig_in1, pin_fig_in2, pin_fig_pwm, frequency=None): self.in1 = DigitalOutputDevice(pin=pin_fig_in1) self.in2 = DigitalOutputDevice(pin=pin_fig_in2) if frequency is None: # Not PWM mode self.pwm = DigitalOutputDevice(pin=pin_fig_pwm) else: # PWM mode self.pwm = PWMOutputDevice(pin=pin_fig_pwm, frequency=frequency) def cw(self): self.in1.on() self.in2.off() self.pwm.on() def ccw(self): self.in1.off() self.in2.on() self.pwm.on() def stop(self): self.in1.off() self.in2.off() self.pwm.off() def stop_and_close(self): self.stop() self.in1.close() self.in2.close() self.pwm.close()
def turn_on_the_light(duration, actor): logging.info('New light request by {} for {} seconds'.format( actor, duration)) relay = DigitalOutputDevice(17) relay.on() time.sleep(float(duration)) relay.off() relay.close()
class Escape: def __init__(self): self.motor_escape = DigitalOutputDevice(pin=pin_fig.escape_relayswitch) def on(self): self.motor_escape.on() print("escape on") def off(self): self.motor_escape.off() self.motor_escape.close() print("escape off")
class RelayClient(): relay1 = None relay2 = None client = None currentState = 'off' def __init__(self): self.client = mqtt.Client() self.client.on_connect = self.on_connect self.client.on_message = self.on_message def start(self): self.client.connect("localhost", 1883, 60) self.client.loop_forever() # The callback for when the client receives a CONNACK response from the server. def on_connect(self, client, userdata, flags, rc): print("Connected with result code " + str(rc)) # Subscribing in on_connect() means that if we lose the connection and # reconnect then subscriptions will be renewed. self.client.subscribe("/Relays") # The callback for when a PUBLISH message is received from the server. def on_message(self, client, userdata, msg): print(msg.topic + " " + str(msg.payload)) payload = Payload(msg.payload) print("id:" + str(payload.id)) print("state:" + str(payload.state)) if payload.state == 'on': print("turning on") if self.currentState == 'off': self.currentState = 'on' self.relay1 = DigitalOutputDevice(pin=17) self.relay1.on() self.relay2 = DigitalOutputDevice(pin=27) self.relay2.on() if payload.state == 'off': print("turning off") self.currentState = 'off' if self.relay1 != None: self.relay1.close() else: print("self.relay1 is null") if self.relay2 != None: self.relay2.close() else: print("self.relay2 is null")
class Motor: """ The class takes three pin numbers as the input to control one of the motor connected to TB6612FNG module. """ def __init__(self, in1, in2, pwm): self.in1 = DigitalOutputDevice(in1) self.in1.off() self.in2 = DigitalOutputDevice(in2) self.in2.on() self.pwm = PWMOutputDevice(pwm, frequency=1000) def set_throttle(self, val): """Control the orientation and the speed of the motor. Arguments: val: a number between -1.0 and 1.0. The motor rotates in forward direction if val > 1, otherwise in reverse direction. Setting val to None will set the motor to stop mode. """ # Set the motor to stop mode. if val is None: self.in1.off() self.in2.off() self.pwm.value = 1.0 else: # Determine the orientation of the motor. if val > 0.0: self.in1.off() self.in2.on() else: self.in1.on() self.in2.off() # Clamp the pwm signal (throttle) to [0, 1]. pwm = max(0.0, min(abs(val), 1.0)) # Note that setting PWM to low will brake the motor no matter what # in1 and in2 input is. self.pwm.value = pwm def close(self): self.in1.close() self.in2.close() self.pwm.close()
def main(): """Run a loop.""" # Wire DC IN to 5V # Wire DC OUT to GND # Wire VCC to GPIO 23 output_pin = 23 relay = DigitalOutputDevice(output_pin) try: while True: relay.on() time.sleep(0.5) relay.off() time.sleep(0.5) except KeyboardInterrupt: pass finally: relay.close()
class Motor: def __init__(self, name='', pin_factory=None, active_high=False): forward_port = int(DataBase.select(name + '_forward_port')) backward_port = int(DataBase.select(name + '_backward_port')) time = float(DataBase.select(name + '_time')) self.forward_motor = DigitalOutputDevice(pin=forward_port, active_high=active_high) self.backward_motor = DigitalOutputDevice(pin=backward_port, active_high=active_high) self.time = time self.name = name print(self.name, 'ready') def forward(self, timer=False): self.backward_motor.off() self.forward_motor.on() if timer: self.timer = Timer(self.time, self.stop) self.timer.start() print(self.name, 'forward') def backward(self, timer=False): self.forward_motor.off() self.backward_motor.on() if timer: self.timer = Timer(self.time, self.stop) self.timer.start() print(self.name, 'backward') def stop(self): self.forward_motor.off() self.backward_motor.off() print(self.name, 'stop') def close(self): self.forward_motor.close() self.backward_motor.close() print(self.name, 'close')
class cBLDC(QtCore.QObject): def __init__(self, pinArah, pinPWM): super(cBLDC, self).__init__() self.zf = DigitalOutputDevice(pinArah) self.pwm = PWMOutputDevice(pinPWM) def setDirection(self, direction): self.zf.value = direction def setSpeed(self, speed): self.pwm.value = speed def accellerate(self): """ buat kecepatan meningkat sampai maksimum, tapi untuk sekarang hanya dibuat kecematan konstan """ self.pwm.value = MAX_SPEED def decellerate(self): """ buat kecepatannya menurun sampai berhenti, tapi sekarang dibuat konstan dulu """ self.pwm.value = 0.0 def hold(self): """ digunakan untuk menghentikan/menahan nilai pwm ketika motor di accelerate/decellerate """ def close(self): """ digunakan untuk closing pin gpiozero. Apakah perlu dicek kecepatan saat itu? """ # this is abrupt stop: self.pwm.value = 0 self.pwm.close() self.zf.close()
def _run(screen: Array, die: Value, rowclk: int, rowsdi: int, oe: int, colsdi: int, colclk: int, le: int, showhz: bool): print("Connecting to display...") ROWSDI = DigitalOutputDevice(rowsdi) ROWCLK = DigitalOutputDevice(rowclk) COLSDI = DigitalOutputDevice(colsdi) COLCLK = DigitalOutputDevice(colclk) OE = DigitalOutputDevice(oe, initial_value=True) LE = DigitalOutputDevice(le) try: OE.pin.state = False cnt, last = 0, time() width = 2**MatrixDriver.DIM while not die.value: for row in range(MatrixDriver.DIM): LE.pin.state = False ROWSDI.pin.state = row != 0 _pulse(ROWCLK) bit = 1 value = screen[row] while bit < width: COLSDI.pin.state = bool(value & bit) _pulse(COLCLK) bit <<= 1 _pulse(LE) if showhz: cnt += 1 now = time() if now - last > .5: print("Refresh rate: %.1fHz" % (cnt / (now - last))) cnt, last = 0, now finally: print("Releasing display...") ROWSDI.close() ROWCLK.close() COLSDI.close() COLCLK.close() LE.close() OE.close()
class CHFSM: # Normal operation IDLE_COLOUR = (1.5, 1.5, (0, 0, 0), (1.0, 1.0, 1.0)) # off to White CH_ONLY_COLOUR = (1.5, 1.5, (0, 0, 0), (0, 0.9, 0.4) ) # off to Reddy-purple HW_ONLY_COLOUR = (1.5, 1.5, (0, 0, 0), (0.9, 0.0, 0.1) ) # off to Greeny-cyan CH_AND_HW_COLOUR = (1.5, 1.5, (0, 0, 0), (0.9, 0.1, 0.0)) # off to Orange # INHIBIT_MODE = (1.5, 1.5, (0,0,0), (1, 0, 0.5)) # Off to purple # Errors NO_GATEWAY_CONNECTION = (1.5, 1.5, (1, 0, 0), (0.9, 0, 0.9) ) # Red to purple SCHEDULE_MISSING = (1.5, 1.5, (1, 0, 0), (1, 0.3, 0.0) ) # red to yellow/orange BAD_SCHEDULE = (1.5, 1.5, (1, 0, 0), (1, 1, 0)) # red to cyan # Maintainance mode BLUETOOTH_MODE = (1.5, 1.5, (0, 0, 1), (0, 1, 1)) # blue to cyan UPDATING = (1.5, 1.5, (0, 0, 1), (0, 1, 0)) #blue to Green update_time = config[r"update_time"] # Update and reboot time (day_of_month, hour, minute, second) UPDATE_REBOOT_TIME = (update_time["day_of_month"], update_time["hour"], update_time["minute"], update_time["second"]) PULSE_UP_TIME = 1.5 PULSE_DOWN_TIME = 1.5 BUTTON_BOUNCE_TIME = None # The duration of a CH or HW boost, in seconds BOOST_DURATION = config["boost_duration"] def __init__(self, red, green, blue, hw_relay, ch_relay, hw_button, ch_button, rgb_active_high, ch_relay_active_high, hw_relay_active_high): # Setup push buttons self.ch_button = BetterButton(ch_button, self.chPressed, self.BUTTON_BOUNCE_TIME, None, True) self.hw_button = BetterButton(hw_button, self.hwPressed, self.BUTTON_BOUNCE_TIME, None, True) # Setup relay self.hw_relay = DigitalOutputDevice(hw_relay, hw_relay_active_high) self.ch_relay = DigitalOutputDevice(ch_relay, ch_relay_active_high) # Setup RGB status LED self.status_led = RGBLED(red, green, blue, active_high=rgb_active_high) self.commands_file_path = config["commands_path"] self.schedule_file_path = config["schedule_path"] # Setup HW boost objects self.hw_boost_start = None self.ch_boost_on = False self.hw_pressed_flag = False self.ch_pressed_flag = False # Load first state self.state = IdleState(self) self.state.enter() # self.last_gateway_ping = datetime.now() def close(self): self.status_led.close() self.hw_relay.close() self.ch_relay.close() def setState(self, state): self.state.leave() self.state = state logging.debug("State change: %s", type(state)) self.state.enter() def process(self): self.state.process() def getState(self): return self.state def chPressed(self): logging.debug("CH button press") self.ch_pressed_flag = True def hwPressed(self): logging.debug("HW button press") self.hw_pressed_flag = True def setStatusLed(self, colour): self.status_led.pulse(colour[0], colour[1], off_color=colour[2], on_color=colour[3]) def parent_folder(): return os.path.dirname(os.path.dirname(__file__))
from gpiozero import DigitalOutputDevice from time import sleep pinAred = DigitalOutputDevice(17) pinByellow = DigitalOutputDevice(27) pinCgreen = DigitalOutputDevice(22) pinDblack = DigitalOutputDevice(23) pinEred = DigitalOutputDevice(13) pinFyellow = DigitalOutputDevice(6) pinGgreen = DigitalOutputDevice(5) pinHblack = DigitalOutputDevice(12) pinAred.on() pinByellow.on() pinCgreen.off() pinDblack.off() pinEred.off() pinFyellow.off() pinGgreen.off() pinHblack.on() sleep(1) pinAred.close() pinByellow.close() pinCgreen.close() pinDblack.close() pinEred.close() pinFyellow.close() pinGgreen.close() pinHblack.close()
class iodevice: def __init__(self, pin: int, mode: iostate, pin_factory = None, pull_up_in: bool = False, active_state_in = None, bounce_time_in = None, active_high_out : bool = True, initial_value_out = False): self.pin = pin self.mode = mode self.device = None self.current_value = initial_value_out self.pin_factory = pin_factory self.active_state_in = active_state_in self.bounce_time_in = None self.active_high_out = active_high_out self.pull_up_in = pull_up_in if (mode == iostate.Input): self.device = DigitalInputDevice(self.pin, pull_up = self.pull_up_in, pin_factory = self.pin_factory) elif (mode == iostate.Output): self.device = DigitalOutputDevice(self.pin, active_high = True, initial_value = self.current_value, pin_factory = self.pin_factory) def state(self): value = self.value() mode = 'O' if self.mode == iostate.Output else 'I' if self.mode == iostate.Input else 'F' val = '-' if self.mode == iostate.Float else '?' if value is None else '1' if value else '0' resistor = ' ' if self.mode == iostate.Float or self.mode == iostate.Output \ else '-' if self.device.pull_up is None \ else 'u' if self.device.pull_up else 'd' return f'({self.pin:2})={mode}{val}{resistor}' def value(self): if (self.mode == iostate.Output): return self.current_value if (self.mode == iostate.Input): return self.device.value return None def high(self): if (self.mode == iostate.Output): self.current_value = True self.device.on() else: print("Output failed. Not in Output state") def low(self): if (self.mode == iostate.Output): self.current_value = False self.device.off() else: print("Output failed. Not in Output state") def set(self, value: bool): if (value): self.high() else: self.low() def inputMode(self): if (self.mode == iostate.Input): return if (self.mode == iostate.Output): self.device.close() self.device = None self.device = DigitalInputDevice(self.pin, pull_up = self.pull_up_in, active_state = self.active_state_in, bounce_time = self.bounce_time_in, pin_factory = self.pin_factory) self.current_value = self.device.value self.mode = iostate.Input def outputMode(self, initial_value: bool = None): if (self.mode == iostate.Output): if (initial_value != None): self.current_value = initial_value self.set(self.current_value) return if (self.mode == iostate.Input): self.device.close() self.device = None self.device = DigitalOutputDevice(self.pin, active_high = self.active_high_out, initial_value = initial_value, pin_factory = self.pin_factory) self.current_value = initial_value self.mode = iostate.Output def close(self): if (self.mode == iostate.Input or self.mode == iostate.Output): self.device.close() self.device = None self.mode = iostate.Float self.current_value = None def blink(self, on_time=1, off_time=0, n=None, background=True): self.outputMode() value = self.current_value self.device.blink(on_time,off_time,n,background) set(value) def wait_for_active(self, timeout = None): self.inputMode() self.device.wait_for_active(timeout) def wait_for_inactive(self, timeout = None): self.inputMode() self.device.wait_for_inactive(timeout) @property def active_time(self): self.inputMode() return self.device.active_time @property def inactive_time(self): self.inputMode() return self.device.inactive_time @property def when_activated(self): self.inputMode() return self.device.when_activated @when_activated.setter def when_activated(self, x): self.inputMode() self.device.when_activated = x @property def when_deactivated(self): self.inputMode() return self.device.when_deactivated @when_deactivated.setter def when_deactivated(self, x): self.inputMode() self.device.when_deactivated = x
#!/usr/bin/env python print("Loading...")\ from gpiozero import DigitalOutputDevice from time import sleep pin = DigitalOutputDevice(21) print("Turning fan on for 20 seconds, turn potentiometer to test.") pin.on() sleep(20) print("Turning fan off") pin.off() print("Exiting") pin.close() exit()
eyesPin.on() a.play_audio() else: raise ValueError( 'PROP_TRIGGER set to improper value for MICROPHONE source') elif c.SOURCE == 'FILES': # Loop forewver, when timer or PIR trigger occurs, call audio # If ambient tracks are set to play, then play them in between tracks = Tracks() if c.PROP_TRIGGER == 'TIMER': start_time = time.time() while True: current_time = time.time() if current_time > start_time + c.DELAY: event_handler() start_time = time.time() elif c.PROP_TRIGGER == 'PIR': while True: pir.wait_for_press() event_handler() else: raise ValueError( 'PROP_TRIGGER set to improper value for FILES source') except Exception as e: print(e) finally: pir.close() eyesPin.close() triggerOut.close() a.jaw.close()
from gpiozero import DigitalOutputDevice from gpiozero.pins.pigpio import PiGPIOFactory from Logger import Logger from RoPiConfiguration import RoPiConfiguration as _conf log = Logger(_conf['DEVEL_LOG']) # set used pins used_pins = [4, 27, 17, 22, 18, 12, 23, 24, 26, 25, 20, 21, 16, 5, 6, 16, 2, 4, 10, 9, 19, 8, 7, 11, 13] log.log("Resetting all used PINs") log.log("> " + str(used_pins)) rem_pi = PiGPIOFactory(host=_conf['remote_address']) # reset used PINs for pin in used_pins : log.debug("Closing PIN: " + str(pin)) _p = DigitalOutputDevice(pin, pin_factory=rem_pi) _p.off() _p.close() log.log("RESET DONE!")
if value == '0': gpio_out.off() else: gpio_out.on() time.sleep(cycle_time) # Interpret all the 0s and 1s we've collected binary_incoming = [] current_edge = edges[0] current_time = edges[0][0] + dt.timedelta(seconds=(cycle_time / 2)) while edges: if edges[0][0] < current_time: current_edge = edges.pop(0) # This is far from a realtime system, we'll just correct any # timing drift sync every time we see an edge. current_time = current_edge[0] + dt.timedelta(seconds=(cycle_time / 2)) binary_incoming.append(current_edge[1]) current_time += dt.timedelta(seconds=cycle_time) binary_received = ''.join(binary_incoming[:-len(end_of_file)]) print("Received binary: " + binary_received) message_received = Morse.from_binary(binary_received) print("Received message: " + message_received.plain_text) finally: gpio_in.close() gpio_out.close()
class ShiftRegister(Device): def __init__(self, SER, SRCLK, RCLK, outputs=8, SRCLR=None, OE=None, pin_factory=None): super().__init__(pin_factory=pin_factory) self.SER = DigitalOutputDevice(SER, pin_factory=pin_factory) self.SRCLK = DigitalOutputDevice(SRCLK, pin_factory=pin_factory) self.RCLK = DigitalOutputDevice(RCLK, pin_factory=pin_factory) self.SRCLR = DigitalOutputDevice(SRCLR, active_high=False, pin_factory=pin_factory) if SRCLR else None self.OE = DigitalOutputDevice(OE, active_high=False, pin_factory=pin_factory) if OE else None self._closed = False if not isinstance(outputs, int): raise TypeError("Number of outputs must be an int.") self.outputs = outputs self._state = [False] * outputs self.clear() def close(self): if self._closed: return self.clear() self.SER.close() self.SRCLK.close() self.RCLK.close() self.SRCLR is None or self.SRCLR.close() self.OE is None or self.OE.close() self._closed = True def clear(self): # If we connected the clearing pin we can just pulse it. if self.SRCLR is not None: pulse(self.SRCLR) pulse(self.RCLK) self._state = [False] * self.outputs # Nope, pipe in false signals for as many outputs as we have. else: self.shiftin([False]*self.outputs) def shiftin(self, bits): bits = [bool(b) for b in bits] for bit in bits: self.SER.value = bit pulse(self.SRCLK) pulse(self.RCLK) # Shift the previous state to the right and plug these bits in. self._state = bits[self.outputs-1::-1] + self._state[:-len(bits)] def write(self, bits): if len(bits) != self.outputs: raise OutputDeviceError( "Device initialized with {} outputs, but {} passed in.".format( self.outputs, len(bits))) self.shiftin(list(reversed(bits))) @property def value(self): return self._state @value.setter def value(self, bits): self.write(bits)
def run(window, device, host, port): run_window = window factory = PiGPIOFactory(host=host, port=port) if device in (N_DigitalOutputDevice, N_LED, N_Buzzer): run_window.Layout(led_layout()) switch = False device_open = False while True: event, values = run_window.read() if event == '-pin-': if device_open: sg.popup_no_titlebar("Close device first!") if event == '-open-': if not device_open: if values['-pin-'] == 'Select pin': sg.popup_no_titlebar("Select your pin!") continue else: d = DigitalOutputDevice(values['-pin-'], pin_factory=factory) device_open = True run_window['-open-'].update(image_data=icon_close) else: device_open = False switch = False run_window['-open-'].update(image_data=icon_open) run_window['-switch-'].update(image_data=icon_switch_off) d.close() if event == '-switch-': if device_open: switch = not switch run_window['-switch-'].update(image_data=icon_switch_on if switch else icon_switch_off) d.on() if switch else d.off() else: sg.popup_no_titlebar("Open device first!") if event in (sg.WIN_CLOSED, 'Exit'): break elif device in (N_PWMOutputDevice, N_PWMLED): run_window.Layout(pwmled_layout()) device_open = False while True: event, values = run_window.read() if event in (sg.WIN_CLOSED, 'Exit'): break # if not exit-event, get param cycle = 0 if str(values['-cycle-']).startswith('Select') else values['-cycle-'] frequency = 100 if values['-frequency-'].startswith('Select') else int( values['-frequency-'].replace('Hz', '')) if event == '-pin-': if device_open: sg.popup_no_titlebar("Close device first!") if event == '-frequency-': if device_open: d.frequency = frequency if event == '-cycle-': if device_open: d.value = cycle if event == '-open-': if not device_open: if values['-pin-'] == 'Select pin': sg.popup_no_titlebar("Select your pin!") continue else: d = PWMOutputDevice(values['-pin-'], initial_value=cycle, frequency=frequency, pin_factory=factory) device_open = True run_window['-open-'].update(image_data=icon_close) else: device_open = False d.close() run_window['-open-'].update(image_data=icon_open) if event == '-pulse-': if device_open: d.pulse() else: sg.popup_no_titlebar("Open device first!") elif device == N_Servo: run_window.Layout(servo_layout()) device_open = False while True: event, values = run_window.read() if event in (sg.WIN_CLOSED, 'Exit'): break value = 0 if str(values['-value-']).startswith('Select') else values['-value-'] min_pulse_width = (1 if values['-min_pulse_width-'].startswith('Select') else float( values['-min_pulse_width-'].replace('ms', ''))) / 1000 max_pulse_width = (2 if values['-max_pulse_width-'].startswith('Select') else float( values['-max_pulse_width-'].replace('ms', ''))) / 1000 if event == '-pin-': if device_open: sg.popup_no_titlebar("Close device first!") if event == '-value-': if device_open: d.value = value if event in ('-min_pulse_width-', '-max_pulse_width-'): if device_open: sg.popup_no_titlebar('Pulse-width param only work before open!') if event == '-open-': if not device_open: if values['-pin-'] == 'Select pin': sg.popup_no_titlebar("Select your pin!") continue else: d = Servo(values['-pin-'], initial_value=value, min_pulse_width=min_pulse_width, max_pulse_width=max_pulse_width, pin_factory=factory) device_open = True run_window['-open-'].update(image_data=icon_close) else: device_open = False d.close() run_window['-open-'].update(image_data=icon_open) elif device == N_AngularServo: run_window.Layout(angularservo_layout()) device_open = False while True: event, values = run_window.read() if event in (sg.WIN_CLOSED, 'Exit'): break angle = 0 if str(values['-angle-']).startswith('Select') else values['-angle-'] min_angle = -90 if str(values['-min_angle-']).startswith('Select') else values['-min_angle-'] max_angle = 90 if str(values['-max_angle-']).startswith('Select') else values['-max_angle-'] min_pulse_width = (1 if values['-min_pulse_width-'].startswith('Select') else float( values['-min_pulse_width-'].replace('ms', ''))) / 1000 max_pulse_width = (2 if values['-max_pulse_width-'].startswith('Select') else float( values['-max_pulse_width-'].replace('ms', ''))) / 1000 if event == '-pin-': if device_open: sg.popup_no_titlebar("Close device first!") if event == '-angle-': if device_open: d.angle = angle if event in ('-min_pulse_width-', '-max_pulse_width-', '-min_angle-', '-max_angle-'): if device_open: sg.popup_no_titlebar('Pulse-width param only work before open!') if event == '-open-': if not device_open: if values['-pin-'] == 'Select pin': sg.popup_no_titlebar("Select your pin!") continue else: d = AngularServo(values['-pin-'], initial_angle=angle, min_angle=min_angle, max_angle=max_angle, min_pulse_width=min_pulse_width, max_pulse_width=max_pulse_width, pin_factory=factory) device_open = True run_window['-open-'].update(image_data=icon_close) else: device_open = False d.close() run_window['-open-'].update(image_data=icon_open) elif device == N_PhaseEnableMotor: run_window.Layout(phaseenablemotor_layout()) device_open = False while True: event, values = run_window.read() if event in (sg.WIN_CLOSED, 'Exit'): break # if not exit-event, get param speed = 0 if str(values['-speed-']).startswith('Select') else values['-speed-'] if event == '-direction_pin-': if device_open: sg.popup_no_titlebar("Close device first!") if event == '-speed_pin-': if device_open: sg.popup_no_titlebar("Close device first!") if event == '-speed-': if device_open: d.value = speed if event == '-open-': if not device_open: select = 'Select direction pin' if values['-direction_pin-'] == select or values['-speed_pin-'] == select: sg.popup_no_titlebar("Select your pin!") continue else: d = PhaseEnableMotor(phase=values['-direction_pin-'], enable=values['-speed_pin-'], pin_factory=factory) d.value = 0 device_open = True run_window['-open-'].update(image_data=icon_close) else: device_open = False d.close() run_window['-open-'].update(image_data=icon_open) elif device == N_Button: run_window.Layout(button_layout()) device_open = False while True: event, values = run_window.read() if event in (sg.WIN_CLOSED, 'Exit'): break # if not exit-event, get param if event == '-pin-': if device_open: sg.popup_no_titlebar("Close device first!") if event == '-pull_up-': if device_open: sg.popup_no_titlebar('pull-up param only work before open!') if event == '-test-': if device_open: sg.popup_no_titlebar('Now you can test button!') d.wait_for_press() sg.popup_no_titlebar('Yuu pressed button!') d.wait_for_release() sg.popup_no_titlebar('Yuu released button!') else: sg.popup_no_titlebar("Open device first!") if event == '-open-': if not device_open: if values['-pin-'] == 'Select pin': sg.popup_no_titlebar("Select your pin!") continue else: pull_up = True if str(values['-pull_up-']).startswith('Select') else values['-pull_up-'] d = Button(values['-pin-'], pull_up=pull_up, bounce_time=0.1, pin_factory=factory) device_open = True run_window['-open-'].update(image_data=icon_close) else: device_open = False d.close() run_window['-open-'].update(image_data=icon_open) elif device in (N_LineSensor, N_MotionSensor, N_LightSensor): run_window.Layout(linesensor_layout()) device_open = False while True: event, values = run_window.read() if event in (sg.WIN_CLOSED, 'Exit'): break if event == '-pin-': if device_open: sg.popup_no_titlebar("Close device first!") if event == '-test-': if device_open: sg.popup_no_titlebar('Now you can test sensor!') d.wait_for_active() sg.popup_no_titlebar('device now is active!') d.wait_for_inactive() sg.popup_no_titlebar('device now is inactive, Test over!') else: sg.popup_no_titlebar("Open device first!") if event == '-open-': if not device_open: if values['-pin-'] == 'Select pin': sg.popup_no_titlebar("Select your pin!") continue else: d = eval(device)(pin=values['-pin-'], pin_factory=factory) device_open = True run_window['-open-'].update(image_data=icon_close) else: device_open = False d.close() run_window['-open-'].update(image_data=icon_open)
class TestScenario(Thread): """ Base class with tools to define a test scenarios Add custom methods for things like REST calls Or data-loading, uses serial port to parse messages """ TIMEOUT = 30 FLASH_SETTLE_TIME = 5 FLASH_SETTLE_TIMEOUT = 60 RST_SETTLE_TIME = 3 RST_PIN = 23 STATUS_IDLE = 0 STATUS_RUNNING = 1 STATUS_ERROR = 2 STATUS_FINISHED = 3 ENABLE_DEBUG = False def __init__(self, name, config, channel): super().__init__() self.name = name self.config = config self.channel = channel self.blocked = False self.events = [] self.total_events = 0 self.current_progress = 0 self.total_progress = 0 self.rst_pin = DigitalOutputDevice(self.RST_PIN, active_high=False) self.check_channel = False self.output_stream = None self.status = TestScenario.STATUS_IDLE self.power_cycle() def print(self, msg): """PRIVATE: Outputs to a queue, array, stream, and print""" if self.ENABLE_DEBUG: print(msg) if self.output_stream is not None: self.output_stream.append(msg) def test_pass(self): """ PRIVATE: Prints a pass message in a format thunder_test understands """ self.print("Test {} passed.".format(self.name)) self.print("Test summary: {} passed," " {} failed, and {} skipped," " out of {} tests.".format(1, 0, 0, 1)) self.status = TestScenario.STATUS_FINISHED def test_fail(self, assertion): """ PRIVATE: Prints a failure message in a format thunder_test understands """ self.print("Assertion {}: {}".format(self.name, assertion)) self.print("Test {} failed.".format(self.name)) self.print("Test summary: {} passed," " {} failed, and {} skipped," " out of {} test(s).".format(0, 1, 0, 1)) self.status = TestScenario.STATUS_FINISHED def test_error(self, message): """ PRIVATE: Prints a failure message""" self.print("Assertion {}: {}".format(self.name, message)) self.print("Test {} failed.".format(self.name)) self.print("Test summary: {} passed," " {} failed, and {} skipped," " out of {} test(s).".format(0, 1, 0, 1)) self.status = TestScenario.STATUS_ERROR def unblock(self): """ PRIVATE: Sets blocked to false, bound function """ self.blocked = False def cleanup(self): """ Closes threads, pins, and other resources""" self.rst_pin.close() def block_until_device_idle(self): """ Loops until the device boots back into good state """ self.print("Waiting for devce...") start = time() sleep(self.FLASH_SETTLE_TIME) while not self.channel.open() and (time() - start) < self.FLASH_SETTLE_TIMEOUT: sleep(self.FLASH_SETTLE_TIME) self.print("Device opened") def wait_for(self, event): """ PRIVATE: Runs a loop with a timeout waiting for a positive event result """ error_count = 0 self.blocked = True start = time() self.current_progress = 0 self.total_progress = self.TIMEOUT while self.current_progress < self.TIMEOUT: if error_count > 3: self.test_fail("Repeated Errors on SerialPort") self.current_progress = (time() - start) self.render_progress() if not self.check_comms(error_count): return False if event.run(): self.unblock() return True return False def wait_message(self, message, error_msg="Message Timeout"): """ Waits for a specific message on the serial port """ def _message_wait(): if not self.channel.input.empty() and self.channel.alive(): msg = self.channel.input.get() self.channel.input.task_done() if msg == message: return True return False event = TestEvent(_message_wait, error_msg) self.events.append(event) return event def wait_regex(self, regex, error_msg="RegEx Timeout"): """ Waits for a regex to be matched on the serial port """ prog = re.compile(regex) def _regex_wait(): if not self.channel.input.empty() and self.channel.alive(): msg = self.channel.input.get() self.print(msg) self.channel.input.task_done() return prog.search(msg) is not None return False event = TestEvent(_regex_wait, error_msg) self.events.append(event) return event def send_message(self, message, error_msg="Could not send Message"): """ Attempts to send a message to the channel """ def _message_send(): if self.channel.alive(): self.channel.output.put(message) return True return False event = TestEvent(_message_send, error_msg) self.events.append(event) return event def wait_seconds(self, seconds, error_msg="Error Waiting"): """ Waits for a number of seconds that must be less than TIMEOUT """ def _second_wait(): if seconds > self.TIMEOUT: self.print("Test Design Error: Wait exceeds timeout") return False sleep(seconds) return True event = TestEvent(_second_wait, error_msg) self.events.append(event) return event def power_cycle(self): """ Gives a pulse (active low) on the RST pin """ self.power_off() self.power_on() def power_off(self): """ Drive RST ON """ def _power_off(): self.check_channel = False self.channel.close() self.rst_pin.on() sleep(self.RST_SETTLE_TIME) return True event = TestEvent(_power_off) self.events.append(event) return event def power_on(self): """ Drive RST OFF """ def _power_on(): self.check_channel = True self.rst_pin.off() sleep(self.FLASH_SETTLE_TIME) return self.channel.open() event = TestEvent(_power_on) self.events.append(event) return event def check_comms(self, error_count): """ Checks and regenerates comm channels""" if self.check_channel and not self.channel.alive(): error_count += 1 self.channel.close() if not self.channel.open(): self.print("Unexpected communication failure") sleep(self.FLASH_SETTLE_TIME) else: error_count = 0 if error_count > 3: self.test_error("Too many errors, aborting") return False return True def run(self): """ Runs the test """ error_count = 0 self.total_events = len(self.events) self.print("Starting {}".format(self.name)) self.status = TestScenario.STATUS_RUNNING self.block_until_device_idle() while self.events and self.status == TestScenario.STATUS_RUNNING: self.render_progress() if not self.blocked: event = self.events.pop(0) if not self.wait_for(event): self.test_fail(event.error()) return if not self.check_comms(error_count): return self.test_pass() def flash_firmware(self, binfile, error_msg="Failed to flash"): """ Flashes a bin file to device """ flasher = BaseFlasher.factory(binfile, self.config) def _flash_new_fw(): self.check_channel = False return flasher.flash() event = TestEvent(_flash_new_fw, error_msg) self.events.append(event) return event def wait_device(self, error_msg="Device did not connect within timeout"): """ Waits for device to connect to host """ started = False def _wait_device(): nonlocal started if not started: started = True self.check_channel = False else: if self.channel.open(): self.check_channel = True return True return False event = TestEvent(_wait_device, error_msg) self.events.append(event) return event def debug(self, msg="DEBUG"): """ Emits a debug message to the console """ def _print_debug(): if self.ENABLE_DEBUG: print(msg) return True event = TestEvent(_print_debug, "debug print failed") self.events.append(event) return event def render_progress(self): """ Draws task progress and overall progress """ if self.ENABLE_DEBUG: return def render_bar(progress): sys.stdout.write('[') step = 3 for i in range(step, 100 + step, step): if (progress / i) > 1: sys.stdout.write("=") else: if (progress - i + step) > 0: character = int(time() % 4) if character == 0: character = '|' elif character == 1: character = '/' elif character == 2: character = '-' elif character == 3: character = '\\' else: character = '*' sys.stdout.write(character) else: sys.stdout.write(' ') sys.stdout.write(']') if self.total_progress == 0: self.total_progress = 1 if self.total_events == 0: self.total_events = 1 overall = int( 100 * ((self.total_events - len(self.events)) / self.total_events)) task = int(100 * (self.current_progress / self.total_progress)) render_bar(overall) sys.stdout.write(':') render_bar(task) sys.stdout.write("\r")
def collector(sample_length=45, dout=LOAD_CELL_DOUT, sck=LOAD_CELL_SCK, gain=LOAD_CELL_GAIN, loadcell_threshold=-200000, fsr_threshold=0.5): start_time = time() d_out = DigitalInputDevice(pin=dout, pull_up=True) sck = DigitalOutputDevice(pin=sck) adc = MCP3008(channel=0) load_cell_results = [] fsr_results = [] sck.off() timeout = 2 while time() - start_time < sample_length: # Retrieve data from MCP3008 fsr_results.append(adc.value) # Retrieve data from HX711 loop_start_time = time() while not d_out.is_active: if time() - loop_start_time > timeout: break data = 0 for j in range(24): data = data << 1 sck.on() sck.off() if d_out.value == 0: data = data + 1 #print("data", data, hex(data), convert_twos_complement(data)) # load_cell_results.append(data) load_cell_results.append((hex(data), convert_twos_complement(data))) # 25th pulse sck.on() sck.off() # 128 pulses for i in range(gain): sck.on() sck.off() # Process data loadcell_data = ','.join(str(e) for e in load_cell_results) fsr_data = ','.join(str(e) for e in fsr_results) loadcell_results = [e[1] for e in load_cell_results if e[0] != '0xffffff'] loadcell_result = 1 if data_processor(loadcell_results, loadcell_threshold) else 0 fsr_result = 1 if data_processor(fsr_results, fsr_threshold) else 0 final_result = 1 if fsr_result == 1 or loadcell_result == 1 else 0 # Send data to remote server # firebase_values = { # 'isSitting': final_result, # 'datetime': datetime.fromtimestamp(start_time, get_localzone()), # 'timestamp': int(start_time) # } # sender.sendToFirebase(firebase_values=firebase_values) resp = send(final_result, datetime.fromtimestamp(start_time, get_localzone())) print(resp) # Save data into local database db.insert((int(start_time), fsr_data, fsr_result, loadcell_data, loadcell_result, final_result)) adc.close() d_out.close() sck.close() return (load_cell_results, fsr_results)
from gpiozero import DigitalOutputDevice from time import sleep sol = DigitalOutputDevice(20) sLED = DigitalOutputDevice(21) for i in range(10): sol.on() sLED.on() sleep(0.5) sol.off() sLED.off() sleep(0.5) sol.close()