def __init__(self, motor_id, polarity=1): self.motor_id = motor_id if polarity < 0: self.DIRECTION_POLARITY = -1 if self.motor_id: self.pwm = Pwm(1) self.pin_a = Gpio(26) self.pin_b = Gpio(47) self.encoder = Eqep(2) else: self.pwm = Pwm(0) self.pin_a = Gpio(36) self.pin_b = Gpio(62) self.encoder = Eqep(1) self.pwm.export() self.pwm.set_period(self.MAX_VOLTAGE_LEVEL * self.___VOLTAGE_FACTOR) self.pwm.set_duty_cycle(0) self.pwm.enable() self.pin_a.export() self.pin_a.set_direction_out() self.pin_a.set_low() self.pin_b.export() self.pin_b.set_direction_out() self.pin_b.set_low() self.set_encoder(0) self.encoder.enable()
def __init__(self, config): self.connection = None self.exchange = None self.queues = [] self.config = config self._init_rabbitmq() self.gpio = Gpio(config)
class Daemon(ConsumerMixin): def __init__(self, config): self.connection = None self.exchange = None self.queues = [] self.config = config self._init_rabbitmq() self.gpio = Gpio(config) def _init_rabbitmq(self): """ connect to rabbitmq and init the queues """ self.connection = kombu.Connection(self.config.rabbitmq['broker-url']) exchange_name = self.config.rabbitmq['exchange-name'] exchange = kombu.Exchange(exchange_name, type="direct") queue_name = self.config.rabbitmq['queue-name'] logging.getLogger(__name__).info("listen following exchange: {exchange}, queue name: {queue}". format(exchange=exchange_name, queue=queue_name)) queue = kombu.Queue(queue_name, exchange=exchange, durable=True) self.queues.append(queue) def get_consumers(self, Consumer, channel): return [Consumer(queues=self.queues, callbacks=[self.process_task])] def handle_data(self, data): if data.IsInitialized(): self.gpio.manage_lights(data) else: logging.getLogger(__name__).warn("protobuff query not initialized") def process_task(self, body, message): # logging.getLogger(__name__).debug("Message received") # Here, add the receipt of protobuf data_message = stat_pb2.StatRequest() try: data_message.ParseFromString(body) #logging.getLogger(__name__).debug('query received: %s' % str(data_message)) except DecodeError as e: logging.getLogger(__name__).warn("message is not a valid " "protobuf task: {}".format(str(e))) message.ack() return try: self.handle_data(data_message) message.ack() except: logging.getLogger(__name__).exception("error while treating data.") message.requeue() time.sleep(10) def __del__(self): self.close() def close(self): if self.connection and self.connection.connected: self.connection.release() self.gpio.finalize()
def __init__(self, arduino_id): if isinstance(arduino_id, int): arduino_id = "IO%d" % arduino_id pin = DIO_MAPPINGS[arduino_id] pin.select() Gpio.__init__(self, pin.gpio_linux_id)
def unexport(self): try: LOG.info("%s > %s" % (str(self.pwm_linux_id), "/sys/class/pwm/pwmchip0/unexport")) with open("/sys/class/pwm/pwmchip0/unexport", 'w') as f: f.write(str(self.pwm_linux_id)) except Exception as e: LOG.warning("%s" % e) Gpio.unexport(self)
def __init__(self, port, delay=0.1): ''' Constructor @param port: GPIO port number where the LED is connected to @param delay: Time the LED is on and off. Default 0.1s ''' self._port = Gpio(port, Gpio.OUT) self._delay = delay self._isRunning = False self._doBlinkThread = None
def export(self): Gpio.export(self) # FIXME rli9 error handling is required # FIxME rli9 only export pwm when pwm() is called LOG.info("%s > %s" % (str(self.pwm_linux_id), "/sys/class/pwm/pwmchip0/export")) with open("/sys/class/pwm/pwmchip0/export", 'w') as f: f.write(str(self.pwm_linux_id)) with open("/sys/class/pwm/pwmchip0/pwm%s/enable" % self.pwm_linux_id, 'w') as f: f.write("1")
def start(self, items, active=0, ok=None, back=None): logger.debug('start') max_width = self.device.width if isinstance(items, list): for item in items: max_width = max(max_width, len(item) * 8 + 1) self.gpio = Gpio(down=self.down, up=self.up, ok=self.__ok, back=self.__back) elif isinstance(items, str): max_width = max(max_width, len(items) * 8 + 1) self.gpio = Gpio(ok=self.__ok, back=self.__back) # self.gpio.start() self.virtual = viewport(self.device, width=max_width, height=(len(items) * 8)) self.active = 0 if ok: self.ok = ok if back: self.back = back with canvas(self.virtual) as draw: if isinstance(items, list): for i, item in enumerate(items): text(draw, (1, i * 8), item, fill="white", font=proportional(LCD_FONT)) if (item == active): self.active = i self.items = items elif isinstance(items, str): text(draw, (1, 0), items, fill="white", font=proportional(LCD_FONT)) self.items = [items] self.virtual.set_position((0, self.active * 8)) threading.Thread.start(self)
def start(self, ok=None, back=None): logger.debug('start') self.gpio = Gpio(ok=self.__ok, back=self.__back) # self.gpio.start() if ok: self.ok = ok if back: self.back = back threading.Thread.start(self)
def run(self): try: self._init_menu() self.music = Music(self.core, self.config['default_tracks'], self.config['default_preset']) self.display = DisplayWithPowerSaving( self.config['display_min_brightness'], self.config['display_max_brightness'], self.config['display_off_time_from'], self.config['display_off_time_to']) self.gpio = Gpio( self.config['buttons_enabled'], self.play_stop_music, self._on_menu_click, self._on_menu_click_left, self._on_menu_click_right, self.config['light_sensor_enabled'], self._on_light_sensor, self.config['relay_enabled']) self.ir_sender = IrSender(self.config['ir_remote'], self.gpio.switch_relay) self.ir_receiver = IrReceiver( self.config['ir_receiver_enabled'], self.play_stop_music, self._on_menu_click, self._on_menu_click_left, self._on_menu_click_right, self.music.decrease_volume, self.music.increase_volume, self.run_alert, self._on_change_preset) self.timer_on = TimerOn(self.play_music) self.timer_off = TimerOff(self.stop_music) self.alert = Alert(self.music, self.ir_sender, self.config['alert_files']) self.timer_alert = TimerAlert(self.run_alert) self.time = Time() self.date = Date([self.timer_on, self.timer_off, self.timer_alert]) self.menu = Menu(self.display, self.MENU, [ self.time, self.date, self.timer_on, self.timer_off, self.timer_alert ]) while True: self.menu.run() if (self.stopped()): break else: sleep(1) except Exception as inst: logging.error(inst) finally: self.ir_sender.stop() self.ir_receiver.stop() self.display.shutdown() self.gpio.cleanup()
class Wh1602: def __init__(self): self.reserve_gpios() self.rw.set_value(0) sleep(0.05) def __del__(self): pass def reserve_gpios(self): self.rs = Gpio(2, "out") self.rw = Gpio(3, "out") self.e = Gpio(4, "out") self.d = [Gpio(17, "out"), Gpio(27, "out"), Gpio(22, "out"), Gpio(23, "out")] def lcd_write_nibble(self, val): for i, p in enumerate(self.d): p.set_value(0 if (val & 1 << i) == 0 else 1) self.e.set_value(1) sleep(0.02) self.e.set_value(0) def lcd_write_data(self, data): self.lcd_write_nibble(data >> 4) self.lcd_write_nibble(data & 0xF) def init_lcd(self): self.rs.set_value(0) sleep(0.2) self.lcd_write_nibble(0x03) sleep(0.05) self.lcd_write_nibble(0x03) sleep(0.05) self.lcd_write_nibble(0x02) sleep(0.02) self.lcd_write_data(0x08) sleep(0.02) self.lcd_write_data(0x01) sleep(0.02) self.lcd_write_data(0x06) sleep(0.02) self.lcd_write_data(0x0D) sleep(0.02) self.rs.set_value(1) def lcd_write_string(self, str): for s in str: self.lcd_write_data(s)
def __init__(self, triggerPort, echoPort, nSamples=5): ''' Constructor @param triggerPort: Port number of the trigger signal @param echoPort: Port number of the echo port @param nSamples: Number of samples to measure the distance ''' self._nSamples = nSamples #Configure ports self._trigger = Gpio(triggerPort, Gpio.OUT) self._trigger.setValue(Gpio.LOW) self._echo = Gpio(echoPort, Gpio.IN) time.sleep(2)
def __init__(self, arduino_id): if isinstance(arduino_id, int): arduino_id = "PWM%d" % arduino_id pin = PWMIO_MAPPINGS[arduino_id] pin.select() self.pwm_linux_id = pin.pwm_linux_id Gpio.__init__(self, pin.gpio_pin.gpio_linux_id) self.period = 700000 self.pwm_dir_name = "/sys/class/pwm/pwmchip0/pwm%s" % str(self.pwm_linux_id) LOG.info("%s > %s" % (str(self.period), "%s/period" % self.pwm_dir_name)) with open("%s/period" % self.pwm_dir_name, "w") as f: f.write(str(self.period))
def __init__(self, config: Config): self.config = config self.gpio: GpioStub if config.debug: from dummy_gpio import DummyGpio self.gpio: GpioStub = DummyGpio(config.gpio_out) else: from gpio import Gpio self.gpio: GpioStub = Gpio(config.gpio_out)
class RgbLed: def __init__(self, red_pin, green_pin, blue_pin): self._red = Gpio(red_pin) self._green = Gpio(green_pin) self._blue = Gpio(blue_pin) def red(self, value): self._red.set(value) def green(self, value): self._green.set(value) def blue(self, value): self._blue.set(value)
def main(): ''' Makes a LED to blink according to the distance meassured by an ultrasonic sensor. Finish when user press a toggle key. ''' blinker = Blinker(27, MAX_DELAY) #P8.17 ultrasonic = Ultrasonic(66, 69) #P8.7, P8.9 key = Gpio(65, Gpio.IN) #P8.18 try: print("Ready. Press toggle key to start.") #Wait for key down event while key.getValue() == Gpio.LOW: sleep(0.2) #Wait for key up event while key.getValue() == Gpio.HIGH: sleep(0.2) print("Started. Press toggle key again to finish.") blinker.start() while key.getValue() == Gpio.LOW: dist = ultrasonic.read() delay = calculateDelay(dist) blinker.setDelay(delay) sleep(0.2) print("Bye!") finally: key.cleanup() blinker.stop() blinker.cleanup() ultrasonic.cleanup()
def reserve_gpios(self): self.rs = Gpio(2, "out") self.rw = Gpio(3, "out") self.e = Gpio(4, "out") self.d = [Gpio(17, "out"), Gpio(27, "out"), Gpio(22, "out"), Gpio(23, "out")]
class Daemon(ConsumerMixin): def __init__(self, config): self.connection = None self.exchange = None self.queues = [] self.config = config self._init_rabbitmq() self.gpio = Gpio(config) def _init_rabbitmq(self): """ connect to rabbitmq and init the queues """ self.connection = kombu.Connection(self.config.rabbitmq['broker-url']) exchange_name = self.config.rabbitmq['exchange-name'] exchange = kombu.Exchange(exchange_name, type="topic") queue = kombu.Queue('', exchange=exchange, routing_key='v1.journeys', durable=False, exclusive=True, auto_delete=True) logging.getLogger(__name__).info( "listen following exchange: {exchange}, queue name: {queue}". format(exchange=exchange_name, queue=queue.name)) self.queues.append(queue) def get_consumers(self, Consumer, channel): return [Consumer(queues=self.queues, callbacks=[self.process_task])] def handle_data(self, data): if data.IsInitialized(): self.gpio.manage_lights(data) else: logging.getLogger(__name__).warn("protobuff query not initialized") def process_task(self, body, message): # logging.getLogger(__name__).debug("Message received") # Here, add the receipt of protobuf data_message = stat_pb2.StatRequest() try: data_message.ParseFromString(body) #logging.getLogger(__name__).debug('query received: %s' % str(data_message)) except DecodeError as e: logging.getLogger(__name__).warn("message is not a valid " "protobuf task: {}".format( str(e))) message.ack() return try: self.handle_data(data_message) message.ack() except: logging.getLogger(__name__).exception("error while treating data.") message.requeue() time.sleep(10) def __del__(self): self.close() def close(self): if self.connection and self.connection.connected: self.connection.release() self.gpio.finalize()
def execute(self): print("executing slowdown command") Gpio.slowdown()
class Worker(Threader): core = None music = None display = None gpio = None ir_sender = None ir_receiver = None timer_on = None timer_off = None alert = None timer_alert = None time = None date = None menu = None response_code = None def start(self, config, core): self.config = config self.core = core super(Worker, self).start() def run(self): try: self._init_menu() self.music = Music(self.core, self.config['default_tracks'], self.config['default_preset']) self.display = DisplayWithPowerSaving( self.config['display_min_brightness'], self.config['display_max_brightness'], self.config['display_off_time_from'], self.config['display_off_time_to']) self.gpio = Gpio( self.config['buttons_enabled'], self.play_stop_music, self._on_menu_click, self._on_menu_click_left, self._on_menu_click_right, self.config['light_sensor_enabled'], self._on_light_sensor, self.config['relay_enabled']) self.ir_sender = IrSender(self.config['ir_remote'], self.gpio.switch_relay) self.ir_receiver = IrReceiver( self.config['ir_receiver_enabled'], self.play_stop_music, self._on_menu_click, self._on_menu_click_left, self._on_menu_click_right, self.music.decrease_volume, self.music.increase_volume, self.run_alert, self._on_change_preset) self.timer_on = TimerOn(self.play_music) self.timer_off = TimerOff(self.stop_music) self.alert = Alert(self.music, self.ir_sender, self.config['alert_files']) self.timer_alert = TimerAlert(self.run_alert) self.time = Time() self.date = Date([self.timer_on, self.timer_off, self.timer_alert]) self.menu = Menu(self.display, self.MENU, [ self.time, self.date, self.timer_on, self.timer_off, self.timer_alert ]) while True: self.menu.run() if (self.stopped()): break else: sleep(1) except Exception as inst: logging.error(inst) finally: self.ir_sender.stop() self.ir_receiver.stop() self.display.shutdown() self.gpio.cleanup() def _init_menu(self): self.MENU = { "get_sub_menu": lambda: [{ "get_sub_menu": lambda: [ self.MENU_TIMER, self.MENU_PLAY_1, self.MENU_RUN_SH, self. MENU_VOLUME, self.MENU_STYLE, self.MENU_DEMO, self. MENU_SYSTEM ] }] } self.MENU_TIMER = { "get_buffer": lambda: [ 0, Symbols.T1, Symbols.T2, Symbols.I, Symbols.M1, Symbols.M2, Symbols.E, Symbols.R ], "get_sub_menu": lambda: [self.MENU_ALERT, self.MENU_TIMER_OFF, self.MENU_TIMER_ON] } self.MENU_ALERT = { "get_buffer": lambda: [ 0, Symbols.A, Symbols.L, Symbols.E, Symbols.R, Symbols.T1, Symbols.T2, 0 ], "get_sub_menu": lambda: [self.MENU_ALERT_ADD, self.MENU_ALERT_CLEAR, self.MENU_ALERT_RUN] } self.MENU_ALERT_ADD = { "get_buffer": lambda: [0, 0, 0, Symbols.A, Symbols.D, Symbols.D, 0, 0], "get_sub_menu": lambda: [{ "get_buffer": self.timer_alert.get_draw_menu_buffer, "click": lambda: (self.timer_alert.add_timer(), self.display.draw(self.timer_alert.get_draw_menu_buffer())), "click_left": self.timer_alert.decrease, "click_right": self.timer_alert.increase }] } self.MENU_ALERT_CLEAR = { "get_buffer": lambda: [0, 0, Symbols.C, Symbols.L, Symbols.E, Symbols.A, Symbols.R, 0], "click": lambda: self.timer_alert.reset(), "click_animation": True } self.MENU_ALERT_RUN = { "get_buffer": lambda: [0, 0, 0, Symbols.R, Symbols.U, Symbols.N, 0, 0], "click": lambda: self.run_alert(), "click_animation": True } self.MENU_TIMER_OFF = { "group": "timer_off", "get_buffer": lambda: [0, 0, 0, Symbols.O, Symbols.F, Symbols.F, 0, 0], "get_sub_menu": lambda: [{ "get_buffer": self.timer_off.get_draw_buffer, "click_left": self.timer_off.decrease, "click_right": self.timer_off.increase }] } self.MENU_TIMER_ON = { "group": "timer_on", "get_buffer": lambda: [0, 0, 0, Symbols.O, Symbols.N, 0, 0, 0], "get_sub_menu": lambda: [{ "get_buffer": self.timer_on.get_draw_buffer, "click_left": self.timer_on.decrease, "click_right": self.timer_on.increase }] } self.MENU_PLAY_1 = { "get_buffer": lambda: [ 0, Symbols.P, Symbols.L, Symbols.A, Symbols.Y, 0, Symbols. NUMBER[1], 0 ], "click": lambda: self.play_music(self.music.get_default_tracks()) } self.MENU_VOLUME = { "group": "volume", "get_buffer": lambda: [ 0, Symbols.U, Symbols.O, Symbols.L, Symbols.U, Symbols.M1, Symbols.M2, Symbols.E ], "get_sub_menu": lambda: [{ "get_buffer": self.music.get_draw_volume, "click_left": self.music.decrease_volume, "click_right": self.music.increase_volume }] } self.MENU_STYLE = { "group": "style", "get_buffer": lambda: [ 0, Symbols.S, Symbols.T1, Symbols.T2, Symbols.Y, Symbols.L, Symbols.E, 0 ], "get_sub_menu": lambda: list( map( lambda x: { "get_buffer": lambda: x["buffer"], "on_draw": lambda: self.music.set_preset(x["name"]) }, self.music.get_presets())) } self.MENU_RUN_SH = { "get_buffer": lambda: [0, Symbols.R, Symbols.U, Symbols.N, 0, Symbols.S, Symbols.H, 0], "click": lambda: self.music.run_sh(), "click_animation": True } self.MENU_DEMO = { "get_buffer": lambda: [0, 0, Symbols.D, Symbols.E, Symbols.M1, Symbols.M2, Symbols.O, 0], "click": lambda: (self.menu.draw_sub_menu_animation( self.music.get_draw_equalizer_animation()), self.menu.reset_sub_menu()) } self.MENU_SYSTEM = { "get_buffer": lambda: [ Symbols.S, Symbols.Y, Symbols.S, Symbols.T1, Symbols.T2, Symbols.E, Symbols.M1, Symbols.M2 ], "get_sub_menu": lambda: [self.MENU_REBOOT, self.MENU_HALT] } self.MENU_REBOOT = { "get_buffer": lambda: [ 0, Symbols.R, Symbols.E, Symbols.B, Symbols.O, Symbols.O, Symbols.T1, Symbols.T2 ], "click": lambda: self.music.reboot(), "click_animation": True } self.MENU_HALT = { "get_buffer": lambda: [0, 0, Symbols.H, Symbols.A, Symbols.L, Symbols.T1, Symbols.T2, 0], "click": lambda: self.music.halt(), "click_animation": True } def _on_menu_click(self): self.menu.click() def _on_menu_click_left(self): if (self.menu.is_sub_menu_visible()): self.menu.click_left() else: self._decrease_timer() def _on_menu_click_right(self): if (self.menu.is_sub_menu_visible()): self.menu.click_right() else: self._increase_timer() def _on_light_sensor(self, now, is_dark): if (self.music.is_playing() and (now.hour >= self.config['light_sensor_time_from'] or now.hour < self.config['light_sensor_time_to'])): if (is_dark): if (self.music.get_volume() > self.config['light_sensor_volume']): self.music.set_volume(self.config['light_sensor_volume']) self.music.set_preset(self.config['light_sensor_preset']) self.timer_off.reset() self.timer_off.increase() self.timer_off.increase() self.timer_off.increase() self.timer_off.increase() self.menu.draw_sub_menu_animation( self.gpio.get_draw_sleep_animation()) else: self.timer_off.reset() def _on_change_preset(self, value): self.music.set_preset(value) if (value < 0): self.menu.click_left(self.MENU_STYLE) else: self.menu.click_right(self.MENU_STYLE) def _increase_timer(self): if (self.music.is_playing()): self.timer_off.increase() self.menu.draw_sub_menu(self.MENU_TIMER_OFF) else: self.timer_on.increase() self.menu.draw_sub_menu(self.MENU_TIMER_ON) def _decrease_timer(self): if (self.music.is_playing()): self.timer_off.decrease() self.menu.draw_sub_menu(self.MENU_TIMER_OFF) else: self.timer_on.decrease() self.menu.draw_sub_menu(self.MENU_TIMER_ON) def run_alert(self): self.menu.draw_sub_menu_animation( self.alert.get_draw_alert_animation()) self.alert.run() def get_presets(self): return self.music.get_presets() def set_preset(self, value): self.music.set_preset(value) def get_volume(self): return self.music.get_volume() def set_volume(self, volume): self.music.set_volume(volume) def get_state(self): return self.music.get_state() def play_stop_music(self): if (self.music.is_playing()): self.stop_music() else: self.play_music() def play_music(self, tracks=None): self.music.set_volume(self.config['default_volume']) self.music.set_preset(self.config['default_preset']) self.music.play(tracks) self.on_started() def pause_music(self): self.music.pause() self.on_paused() def stop_music(self): self.music.stop() self.on_stopped() def on_started(self): self.menu.draw_sub_menu_animation( self.music.get_draw_start_animation()) def on_stopped(self): self.menu.draw_sub_menu_animation(self.music.get_draw_stop_animation()) self.timer_off.reset() self.ir_sender.power(False) def on_playing(self): self.menu.draw_sub_menu_animation(self.music.get_draw_play_animation()) self.timer_on.reset() if (self.music.is_playing()): self.ir_sender.power(True) def on_paused(self): self.menu.draw_sub_menu_animation( self.music.get_draw_pause_animation()) def on_seeked(self): self.menu.draw_sub_menu_animation(self.music.get_draw_seek_animation()) def on_mute(self, mute): if mute: self.on_volume_changed(0) else: self.on_volume_changed() def on_volume_changed(self, volume=None): if (self.menu is not None and self.music is not None and self.music.is_volume_changed(volume)): self.menu.draw_sub_menu(self.MENU_VOLUME) def on_playback_state_changed(self, old_state, new_state): if (old_state != new_state): if (self.music.is_playing(new_state)): self.on_playing() elif (self.music.is_paused(new_state)): self.on_paused()
class Ultrasonic(object): PULSE2CM = 17241.3793 # cm/s MAX_RANGE = 3500 # cm OUT_OF_RANGE = 0xffffffff def __init__(self, triggerPort, echoPort, nSamples=5): ''' Constructor @param triggerPort: Port number of the trigger signal @param echoPort: Port number of the echo port @param nSamples: Number of samples to measure the distance ''' self._nSamples = nSamples #Configure ports self._trigger = Gpio(triggerPort, Gpio.OUT) self._trigger.setValue(Gpio.LOW) self._echo = Gpio(echoPort, Gpio.IN) time.sleep(2) def read(self): ''' Measures distance @return: Distance as centimeters ''' MAX_POLL = 1000 i = 0 dist = 0 while i < self._nSamples and dist != Ultrasonic.OUT_OF_RANGE: self._trigger.setValue(Gpio.HIGH) time.sleep(0.001) self._trigger.setValue(Gpio.LOW) #TODO: use system's poll mechanism or event to wait for GPIO-level change nPoll = 0 while nPoll < MAX_POLL and self._echo.getValue() == Gpio.LOW: nPoll += 1 if nPoll == MAX_POLL: raise ReadGpioException( "Max poll reached: waiting for echo HIGH") pulseStart = time.time() nPoll = 0 while nPoll < MAX_POLL and self._echo.getValue() == Gpio.HIGH: nPoll += 1 if nPoll == MAX_POLL: raise ReadGpioException( "Max poll reached: waiting for echo LOW") pulseEnd = time.time() pulseDuration = pulseEnd - pulseStart distSample = round(pulseDuration * Ultrasonic.PULSE2CM, 0) #cm if distSample < Ultrasonic.MAX_RANGE: dist = (dist + distSample) / 2.0 if i != 0 else distSample else: dist = Ultrasonic.OUT_OF_RANGE i += 1 return dist def cleanup(self): ''' Frees ressources ''' self._trigger.cleanup() self._echo.cleanup()
def __init__(self): self.gpio = Gpio(self.context) self.live = TelldusLive(self.context) self.gpio.initPin('status:red') self.gpio.initPin('status:green') self.setNetworkLed()
def execute(self): print("executing steer command") Gpio.steer(self.x, self.y)
def __init__(self, linux_id, v): Gpio.__init__(self, linux_id) self.v = v
class Motor: MAX_VOLTAGE_LEVEL = 100 MIN_VOLTAGE_LEVEL = 0 ENCODER_RESOLUTION = 1200 ___VOLTAGE_FACTOR = 10000 DIRECTION_POLARITY = 1 def __init__(self, motor_id, polarity=1): self.motor_id = motor_id if polarity < 0: self.DIRECTION_POLARITY = -1 if self.motor_id: self.pwm = Pwm(1) self.pin_a = Gpio(26) self.pin_b = Gpio(47) self.encoder = Eqep(2) else: self.pwm = Pwm(0) self.pin_a = Gpio(36) self.pin_b = Gpio(62) self.encoder = Eqep(1) self.pwm.export() self.pwm.set_period(self.MAX_VOLTAGE_LEVEL * self.___VOLTAGE_FACTOR) self.pwm.set_duty_cycle(0) self.pwm.enable() self.pin_a.export() self.pin_a.set_direction_out() self.pin_a.set_low() self.pin_b.export() self.pin_b.set_direction_out() self.pin_b.set_low() self.set_encoder(0) self.encoder.enable() def close(self): self.pwm.set_duty_cycle(0) self.pwm.disable() self.pwm.unexport() self.pin_a.unexport() self.pin_b.unexport() self.encoder.disable() def __set_absolute_v_level(self, new_level): if new_level > self.MAX_VOLTAGE_LEVEL: new_level = self.MAX_VOLTAGE_LEVEL elif new_level < 0: new_level = self.MIN_VOLTAGE_LEVEL new_level *= self.___VOLTAGE_FACTOR self.pwm.set_duty_cycle(new_level) def __get_absolute_v_level(self): return int(self.pwm.get_duty_cycle() / self.___VOLTAGE_FACTOR) def __set_direction(self, direction): direction *= self.DIRECTION_POLARITY if direction > 0: self.pin_a.set_low() self.pin_b.set_high() elif direction < 0: self.pin_a.set_high() self.pin_b.set_low() else: self.pin_a.set_low() self.pin_b.set_low() def __get_direction(self): a = int(self.pin_a.get_value()) b = int(self.pin_b.get_value()) return (b - a) * self.DIRECTION_POLARITY def set_encoder(self, value): self.encoder.set_position(value) def get_encoder(self): return int(self.encoder.get_position()) def get_radians(self): return self.get_encoder() * 2 * 3.14159265359 / self.ENCODER_RESOLUTION def set_voltage(self, level): self.__set_direction(level) self.__set_absolute_v_level(int(abs(level))) def get_voltage(self): return self.__get_absolute_v_level() * self.__get_direction()
def __init__(self, red_pin, green_pin, blue_pin): self._red = Gpio(red_pin) self._green = Gpio(green_pin) self._blue = Gpio(blue_pin)
def get_gpio(pin): gpio = Gpio(pin) return gpio
class Clock(threading.Thread): def __init__(self): global level logger.debug('__init__') threading.Thread.__init__(self) if platform.machine().startswith('arm'): # create matrix device serial = spi(port=0, device=1, gpio=noop()) self.device = max7219(serial, cascaded=4, block_orientation=-90) else: # create emulator device self.device = pygame(width=32, height=8, rotate=0, mode='RGB', transform='led_matrix', scale=2, frame_rate=60) self.device.contrast(level) self.exit = False def start(self, ok=None, back=None): logger.debug('start') self.gpio = Gpio(ok=self.__ok, back=self.__back) # self.gpio.start() if ok: self.ok = ok if back: self.back = back threading.Thread.start(self) def run(self): logger.debug('run') semicolon = False while True: clock = time.localtime() with canvas(self.device) as draw: text(draw, (3, 0), time.strftime("%H", clock), fill="white", font=proportional(LCD_FONT)) text(draw, (20, 0), time.strftime("%M", clock), fill="white", font=proportional(LCD_FONT)) if semicolon: text(draw, (15, 0), ":", fill="white", font=proportional(LCD_FONT)) semicolon = not semicolon time.sleep(0.5) if self.exit: return def stop(self): logger.debug('stop') self.gpio.stop() self.exit = True def __ok(self): logger.debug('ok') if self.ok: self.ok(self) def __back(self): logger.debug('back') if self.back: self.back(self)
def main(argv): device_name = None server_url = None gpio_number = None rgb = [] key = None lock_id = None logfile = None mode = 'single_lock' def help(cmd): print cmd + '-i <input device> -u <server url> -g <gpio number> -k <secret key> -l <lock number> -o <logfile>' try: opts, args = getopt.getopt(argv, "hi:u:b:g:r:k:l:o:m:", [ "input=", "url=", "gpio=", "rgb=", "key=", "lock=", "logfile=", "mode=" ]) except getopt.GetoptError: help(sys.argv[0]) sys.exit(2) for opt, arg in opts: if opt == '-h': help(sys.argv[0]) sys.exit() elif opt in ("-i", "--input"): device_name = arg elif opt in ("-u", "--url"): server_url = arg elif opt in ("-g", "--gpio"): gpio_number = arg elif opt in ("-r", "--rgb"): rgb.extend(arg.split(',')) elif opt in ("-k", "--key"): key = arg elif opt in ("-l", "--lock"): lock_id = arg elif opt in ("-o", "--logfile"): logfile = arg elif opt in ("-m", "--mode"): mode = arg if not server_url or not key: help(sys.argv[0]) sys.exit(2) if mode != 'single_lock' and mode != 'open_all': print('unknown mode %s' % mode) sys.exit(2) # create lock if gpio_number: lock = Lock(lock_id, Gpio(gpio_number)) else: lock = DummyLock(lock_id) # create logger if logfile: logger = create_file_logger(logfile, lock) else: logger = create_stdout_logger(lock) # create authenticator logger.info("server url: %s" % server_url) authenticator = Authenticator(server_url, key) # create reader if device_name: reader = Reader(device_name) else: reader = DummyReader() rgb_led = None if rgb: rgb_led = RgbLed(int(rgb[0]), int(rgb[1]), int(rgb[2])) # read loop for user_id in reader.read(): if mode == 'single_lock': if authenticator.auth(lock, user_id): if rgb_led: rgb_led.green(1) lock.open(pulse_time_s=1) logger.info("%s: valid" % user_id) if rgb_led: rgb_led.green(0) else: if rgb_led: rgb_led.red(1) logger.info("%s: invalid" % user_id) time.sleep(1) if rgb_led: rgb_led.red(0) elif mode == 'open_all': state = authenticator.auth(lock, user_id) if state: logger.info("%s: valid" % user_id) if state == 'on': logger.info("all on") if rgb_led: rgb_led.green(1) rgb_led.red(0) elif state == 'off': logger.info("all off") if rgb_led: rgb_led.green(0) rgb_led.red(1) else: logger.info("unknown state: %s" % state) else: logger.info("%s: invalid" % user_id)
class Display(threading.Thread): def __init__(self): global level logger.debug('__init__') threading.Thread.__init__(self) if platform.machine().startswith('arm'): # create matrix7219 device serial = spi(port=0, device=1, gpio=noop()) self.device = max7219(serial, cascaded=4, block_orientation=-90) else: # create emulator device self.device = pygame(width=32, height=8, rotate=0, mode='RGB', transform='led_matrix', scale=2, frame_rate=60) self.device.contrast(level) def start(self, items, active=0, ok=None, back=None): logger.debug('start') max_width = self.device.width if isinstance(items, list): for item in items: max_width = max(max_width, len(item) * 8 + 1) self.gpio = Gpio(down=self.down, up=self.up, ok=self.__ok, back=self.__back) elif isinstance(items, str): max_width = max(max_width, len(items) * 8 + 1) self.gpio = Gpio(ok=self.__ok, back=self.__back) # self.gpio.start() self.virtual = viewport(self.device, width=max_width, height=(len(items) * 8)) self.active = 0 if ok: self.ok = ok if back: self.back = back with canvas(self.virtual) as draw: if isinstance(items, list): for i, item in enumerate(items): text(draw, (1, i * 8), item, fill="white", font=proportional(LCD_FONT)) if (item == active): self.active = i self.items = items elif isinstance(items, str): text(draw, (1, 0), items, fill="white", font=proportional(LCD_FONT)) self.items = [items] self.virtual.set_position((0, self.active * 8)) threading.Thread.start(self) def run(self): logger.debug('run') active = self.active i = 0 while True: while (active == self.active): if (i < (textsize(self.items[active], font=proportional(LCD_FONT))[0] + 3 - self.device.width)): self.virtual.set_position((i, active * 8)) i += 1 else: i = 0 break time.sleep(0.2) if (self.active == 255): return if (self.active > active): for j in range(9): self.virtual.set_position((0, (active * 8) + j)) time.sleep(0.05) if (self.active < active): for j in range(9): self.virtual.set_position((0, (active * 8) - j)) time.sleep(0.05) active = self.active i = 0 def stop(self): logger.debug('stop') self.gpio.stop() self.active = 255 def down(self): logger.debug('down') if (self.active < (len(self.items) - 1)): self.active += 1 def up(self): logger.debug('up') if (self.active > 0): self.active -= 1 def __ok(self): logger.debug('ok') if self.ok: self.ok(self, self.items[self.active]) def __back(self): logger.debug('back') if self.back: self.back(self, self.items[self.active])
from gpio import Gpio from time import sleep led = Gpio(27, Gpio.OUT) #P8.17 key = Gpio(65, Gpio.IN) #P8.18 try: light = Gpio.LOW led.setValue(light) lastKeyState = Gpio.LOW print("Ready.\nPress toggle key to change led state or Ctrl+C to exit.") while True: keyState = key.getValue() if lastKeyState != keyState and keyState == Gpio.HIGH: light = not light led.setValue(light) print("Led state changed to {0}.".format("ON" if light else "OFF")) lastKeyState = keyState sleep(0.2) except KeyboardInterrupt: print("\nBye!") finally:
def execute(self): print("executing throttle command") Gpio.throttle(self.x, self.y)
class Blinker(object): ''' Makes a LED to blink ''' def __init__(self, port, delay=0.1): ''' Constructor @param port: GPIO port number where the LED is connected to @param delay: Time the LED is on and off. Default 0.1s ''' self._port = Gpio(port, Gpio.OUT) self._delay = delay self._isRunning = False self._doBlinkThread = None def start(self): ''' Starts the LED to be blinking ''' if self._doBlinkThread == None or not self._doBlinkThread.isAlive(): self._isRunning = True self._doBlinkThread = Thread(target=self._doBlink) self._doBlinkThread.start() def stop(self): ''' Stops the LED blinking ''' self._isRunning = False if self._doBlinkThread != None and self._doBlinkThread.isAlive(): self._doBlinkThread.join() def setDelay(self, delay): ''' Set the time the LED is on and off @param delay: seconds ''' self._delay = delay def _doBlink(self): ''' Thread action to be the LED blinking ''' status = True while self._isRunning: self._port.setValue(status) status = not status time.sleep(self._delay) self._port.setValue(False) def cleanup(self): ''' Frees ressources ''' self._port.cleanup()
def execute(self): print("executing reverse command") Gpio.reverse(self.x, self.y)
def __init__(self, logger): Logger.log.debug('{} initializing....'.format(__name__)) self.logger = logger self.config = Config(logger=self.logger) self.support = Support(config=self.config, logger=self.logger) self.gpio = Gpio(config=self.config, logger=self.logger) self.pollperm = Pollperm(logger=self.logger) self.decoder = Decoder(config=self.config, logger=self.logger, gpio=self.gpio) self.spi = SPI(config=self.config, logger=self.logger, decoder=self.decoder, pollperm=self.pollperm) self.codegen = Codegen(config=self.config, logger=self.logger, gpio=self.gpio, spi=self.spi) self.securitylevel = SecurityLevel(logger=self.logger) self.gui = Mainwindow(self, codegen=self.codegen, config=self.config, logger=self.logger, support=self.support, securitylevel=self.securitylevel) self.switches = Switches(config=self.config, logger=self.logger, spi=self.spi, gui=self.gui) self.currentsense = CurrentSense(logger=self.logger, spi=self.spi, decoder=self.decoder, gui=self.gui, config=self.config) self.pollvalues = Pollvalues(pollperm=self.pollperm, logger=logger, config=self.config, currentsense=self.currentsense, switches=self.switches, sense_callback=self.poll_sense_callback, switch_callback=self.poll_switch_callback) self.securitywindow = SecurityWindow(logger=self.logger, securitylevel=self.securitylevel) self.window = self.gui.window self.log = self.logger.log self.knob_values = 0 self.rotary_0_pins = None self.rotary_1_pins = None self.rotary_2_pins = None self.rotary_3_pins = None self.rotary_0_pin_0_debounce = None self.rotary_0_pin_1_debounce = None self.rotary_1_pin_0_debounce = None self.rotary_1_pin_1_debounce = None self.rotary_2_pin_0_debounce = None self.rotary_2_pin_1_debounce = None self.rotary_3_pin_0_debounce = None self.rotary_3_pin_1_debounce = None self.gain0_val = 0 self.gain1_val = 0 self.gain_0_name = None self.gain_1_name = None self.gain_0_spi_channel = None self.gain_1_spi_channel = None self.gain_0_thresholds = None self.gain_1_thresholds = None self.GAIN_0_CS = None self.GAIN_1_CS = None self.speed0_val = 0 self.speed1_val = 0 self.speed_0_name = None self.speed_1_name = None self.speed_0_shape = None self.speed_1_shape = None self.speed_0_spi_channel = None self.speed_1_spi_channel = None self.speed_0_thresholds = None self.speed_1_thresholds = None self.screen_brightness_max = None self.screen_brightness_min = None self.display_brightness = None self.spi_log_pause = False self.SPEED_0_CS = None # 6 # SPEED SIMULATION TACH 1 self.SPEED_1_CS = None # 7 # SPEED SIMULATION TACH 2 self.load_from_config() self.adc_scale = None self.sense_amp_max_amps = None self.sense_ad_vin = None # LM4128CQ1MF3.3/NOPB voltage reference self.sense_ad_max_bits = 0 # AD7940 ADC self.sense_scaling_factor_mv_amp = None # 110 milivolts per amp self.sense_ad_max_scaled_value = None self.speed0 = Speedgen( pollperm=self.pollperm, logger=self.logger, config=self.config, decoder=self.decoder, spi=self.spi, gpio=self.gpio, name=self.speed_0_name, shape=self.speed_0_shape, spi_channel=self.speed_0_spi_channel, chip_select=self.SPEED_0_CS, pin_0=self.rotary_0_pins[0], pin_1=self.rotary_0_pins[1], pin_0_debounce=self.rotary_0_pin_0_debounce, pin_1_debounce=self.rotary_0_pin_1_debounce, thresholds=self.speed_0_thresholds, callback=self.speed_callback, commander_speed_move_callback=self.speed_move_callback) self.speed1 = Speedgen( pollperm=self.pollperm, logger=self.logger, config=self.config, decoder=self.decoder, spi=self.spi, gpio=self.gpio, name=self.speed_1_name, shape=self.speed_1_shape, spi_channel=self.speed_1_spi_channel, chip_select=self.SPEED_1_CS, pin_0=self.rotary_1_pins[0], pin_1=self.rotary_1_pins[1], pin_0_debounce=self.rotary_1_pin_0_debounce, pin_1_debounce=self.rotary_1_pin_1_debounce, thresholds=self.speed_1_thresholds, callback=self.speed_callback, commander_speed_move_callback=self.speed_move_callback) self.gain0 = Gains( pollperm=self.pollperm, config=self.config, logger=self.logger, decoder=self.decoder, spi=self.spi, gpio=self.gpio, name=self.gain_0_name, spi_channel=self.gain_0_spi_channel, chip_select=self.GAIN_0_CS, pin_0=self.rotary_2_pins[0], pin_1=self.rotary_2_pins[1], pin_0_debounce=self.rotary_2_pin_0_debounce, pin_1_debounce=self.rotary_2_pin_1_debounce, thresholds=self.gain_0_thresholds, callback=self.gains_callback, commander_gain_move_callback=self.gain_move_callback) self.gain1 = Gains( pollperm=self.pollperm, config=self.config, logger=self.logger, decoder=self.decoder, spi=self.spi, gpio=self.gpio, name=self.gain_1_name, spi_channel=self.gain_1_spi_channel, chip_select=self.GAIN_1_CS, pin_0=self.rotary_3_pins[0], pin_1=self.rotary_3_pins[1], pin_0_debounce=self.rotary_3_pin_0_debounce, pin_1_debounce=self.rotary_3_pin_1_debounce, thresholds=self.gain_1_thresholds, callback=self.gains_callback, commander_gain_move_callback=self.gain_move_callback) self.startup_processes()
class Led(Plugin): implements(ITelldusLiveObserver) def __init__(self): self.gpio = Gpio(self.context) self.live = TelldusLive(self.context) self.gpio.initPin('status:red') self.gpio.initPin('status:green') self.setNetworkLed() def liveConnected(self): self.setNetworkLed() def liveRegistered(self, __msg, __refreshRequired): self.setNetworkLed() def liveDisconnected(self): self.setNetworkLed() def setNetworkLed(self): if self.live.isRegistered(): # We check live status first since we might have connection on another network interface self.gpio.setPin('status:red', 0) self.gpio.setPin('status:green', 1, brightness=50) return if self.live.isConnected(): self.gpio.setPin('status:red', 0) self.gpio.setPin('status:green', 1, brightness=50, freq=1) return if Led.__getIp(Board.networkInterface()) is None: self.gpio.setPin('status:red', 1, freq=1) self.gpio.setPin('status:green', 0) return self.gpio.setPin('status:red', 1, brightness=50) self.gpio.setPin('status:green', 0) @staticmethod def __getIp(iface): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sockfd = sock.fileno() SIOCGIFADDR = 0x8915 # pylint:disable=C0103 ifreq = struct.pack('16sH14s', str(iface), socket.AF_INET, '\x00' * 14) try: res = fcntl.ioctl(sockfd, SIOCGIFADDR, ifreq) except Exception as __error: return None ipAddr = struct.unpack('16sH2x4s8x', res)[2] return socket.inet_ntoa(ipAddr)
#!/usr/bin/python '''Test switch hardware with output to local oled.''' import os import sys # required for sys.exit() import time, datetime, argparse, logging import RPi.GPIO as GPIO from gpio import Gpio from oled import Oled myGpio=Gpio() myOled=Oled(4) myGpio.setup() myOled.writerow(1,'Switch test') a = [17,18,21,22,23,24,25,4] b = [0,0,0,0,0,0,0,0] for i in range(len(a)): GPIO.setup(a[i],GPIO.IN) print a[i]," ", print print 'Next Stop Vol+ Vol- - - - -' time.sleep(1) myOled.writerow(1,str(a[0])+' '+str(a[1])+' '+str(a[2])+' '+str(a[3])+' '+str(a[4])+' '+str(a[5])) myOled.writerow(3,str(a[6])+' '+str(a[7])) while True: for i in range(len(a)): print GPIO.input(a[i])," ", b[i] = GPIO.input(a[i]) print
# Default game parameters GAME_TOTAL_LINKS = 15 GAME_FIRST_LINK_0 = 10 GAME_FIRST_LINK_1 = 4 GAME_STEP_DELAY = 8 # Diagnostic parameters DIAG_PATH_SEARCH_SRC = 0 DIAG_PATH_SEARCH_DST = len(ALL_NODE_NAMES) - 1 # Mock parameters MOCK_FIRST_LINK_MIDDLE_NODE = 2 MOCK_SECOND_LINK_MIDDLE_NODE = 3 # Connectors representing GPIO groupings NODE_0 = Connectors(Gpio(Gpio.BUS_ADDR_0, Gpio.GPB0), [ Gpio(Gpio.BUS_ADDR_0, Gpio.GPB1), Gpio(Gpio.BUS_ADDR_0, Gpio.GPB2), Gpio(Gpio.BUS_ADDR_0, Gpio.GPB3), Gpio(Gpio.BUS_ADDR_0, Gpio.GPB4) ], DEBUG_MODE) NODE_1 = Connectors(Gpio(Gpio.BUS_ADDR_0, Gpio.GPB5), [ Gpio(Gpio.BUS_ADDR_0, Gpio.GPB6), Gpio(Gpio.BUS_ADDR_0, Gpio.GPA0), Gpio(Gpio.BUS_ADDR_0, Gpio.GPA1), Gpio(Gpio.BUS_ADDR_0, Gpio.GPA2) ], DEBUG_MODE) NODE_2 = Connectors(Gpio(Gpio.BUS_ADDR_0, Gpio.GPA7), [ Gpio(Gpio.BUS_ADDR_0, Gpio.GPA6), Gpio(Gpio.BUS_ADDR_0, Gpio.GPA5), Gpio(Gpio.BUS_ADDR_0, Gpio.GPA4),
def __init__(self): Pyro.core.ObjBase.__init__(self) self.adc = Adc() #adc.Adc() self.pwm = Pwm() #pwm.OmapPwm() self.gpio = Gpio() #gpio.Gpio()