def wait_for_print_finish(led_button): while subprocess.check_output(['lpstat', '-R']): # print queue is not empty GPIO.output(led_button, 1) sleep(0.1) GPIO.output(led_button, 0) sleep(0.1)
def controler(): if request.method == 'POST': valid = True if valid: led_states = [] led_states.append(str(request.form.get('led2'))) led_states.append(str(request.form.get('led3'))) led_states.append(str(request.form.get('led4'))) for p in range(len(pines)): if led_states[p] == '1': GPIO.output(pines[p].pin, GPIO.HIGH) pines[p].state = "ON" db.update_pin(pines[p]) elif led_states[p] == '2': GPIO.output(pines[p].pin, GPIO.LOW) pines[p].state = "OFF" db.update_pin(pines[p]) return redirect(url_for('panel_control')) form = request.form return render_template('error.html', form='') else: return redirect(url_for('panel_control'))
def server_busy(): try: resp = req.get("http://localhost/api/status", timeout=5) try: response = json.loads(resp.text) last_op_timestamp = int(response["last_op_at"]) last_op_period = int(time.time()) - last_op_timestamp if screen_always_on_flag or last_op_period < SCREEN_OFF_TIMEOUT: GPIO.output(LCD_LED, 1) else: GPIO.output(LCD_LED, 0) if last_op_period < SERVER_BUSY_TIMEOUT: return "BUSY" return "FREE" except Exception as pe: print("\nERR parsing response:", pe) return "ERR" except req.exceptions.Timeout: print("\nERR Timeout") return "BUSY" except req.exceptions.ConnectionError as ce: print("\nERR Connecting:", ce) return "ERR" except req.exceptions.RequestException as re: print("\nERR other exception:", re) return "ERR" except Exception as ge: print("ERR general exception: ", ge) return "ERR"
def light_up(sec): # GPIO.setwarnings(False) # GPIO.setup("PC7",GPIO.OUT) # GPIO.setwarnings(True) GPIO.output("PC7", GPIO.HIGH) time.sleep(sec) GPIO.output("PC7", GPIO.LOW)
def light_down(sec): # GPIO.setmode(GPIO.SUNXI) # GPIO.setwarnings(False) # GPIO.setup("PC7",GPIO.OUT) # GPIO.setwarnings(True) GPIO.output("PC7", GPIO.LOW) time.sleep(sec)
async def initial_task(): """Background logic. """ app.ps_executor = ProcessPoolExecutor( max_workers=env_var_int("WORKERS_PS_EXECUTER") or 4 ) logger.info(f"Pins: {PINS}") pins = list(map(int, PINS)) PINS.clear() PINS.extend(pins) app.current_state = { "active": True, "last_image": None, "image_events": [], "pins": {pin: False for pin in pins}, "pins_time": {}, "pins_schedule": [] } if GPIO: for pin in pins: GPIO.setup(pin, GPIO.OUT) GPIO.output(pin, GPIO_STATA_OFF) logger.info("Setup service tasks..") loop = asyncio.get_running_loop() loop.create_task(temperature_watcher(app.current_state)) loop.create_task(temperature_storage_watcher(app.current_state)) loop.create_task(network_watcher(app.current_state)) loop.create_task(watch_image_changes(app.current_state, app.ps_executor)) loop.create_task(gpio_watcher(app.current_state))
def lcd_toggle_enable(): # Toggle enable time.sleep(E_DELAY) GPIO.output(LCD_E, 1) time.sleep(E_PULSE) GPIO.output(LCD_E, 0) time.sleep(E_DELAY)
def on(self): """ Turn on the LED if necessary. """ if not self.is_on: self.is_on = True GPIO.output(self.pin, 1)
def chip_select(value): """ Enable/Disable Chip Select via NSS pin :return: value """ if BOARD.NSS is not None: GPIO.output(BOARD.NSS, value == False) return value
def test_input_not_configured_for_output(): with patch("OPi.GPIO.sysfs"): GPIO.setmode(GPIO.BOARD) GPIO.setup(23, GPIO.IN) with pytest.raises(RuntimeError) as ex: GPIO.output(23, GPIO.LOW) assert str(ex.value) == "Channel 23 is configured for input"
def resetModem(): try: GPIO.setmode(GPIO.BOARD) GPIO.setup(onPin, GPIO.OUT) GPIO.setup(pwrKey, GPIO.OUT) GPIO.setup(statusPin, GPIO.IN) except Exception as e: pass GPIO.output(onPin, GPIO.LOW) # set the GSM ON/OFF pin to low to turn off the modem time.sleep(10) GPIO.output(onPin, GPIO.HIGH) # set the GSM ON/OFF pin to high to turn on the modem time.sleep(5) # Then Toggle the power key GPIO.output(pwrKey, GPIO.HIGH) GPIO.output(pwrKey, GPIO.LOW) time.sleep(5) GPIO.output(pwrKey, GPIO.HIGH) time.sleep(30) status = GPIO.input(statusPin) try: if status == 1: subprocess.call(['sudo sakis3g "connect" DNS="8.8.8.8" APN="CUSTOM_APN" CUSTOM_APN="airtelgprs.com" APN_USER="******" APN_PASS="******" USBINTERFACE="3" OTHER="USBMODEM" USBMODEM="1e0e:9001"'], shell=True) except Exception as e: print(e) time.sleep(5) print('GSM Status: ', GPIO.input(statusPin))
def turnRelayOff(): """Выключение реле.""" logger.info('Relay Off') try: GPIO.output(PIN_NUM, GPIO.LOW if INVERT_PIN else GPIO.HIGH) except Exception: pass
def resetModem(): GPIO.output( onPin, GPIO.LOW) # set the GSM ON/OFF pin to low to turn off the modem time.sleep(10) GPIO.output( onPin, GPIO.HIGH) # set the GSM ON/OFF pin to high to turn on the modem time.sleep(5) # Then Toggle the power key GPIO.output(pwrKey, GPIO.HIGH) GPIO.output(pwrKey, GPIO.LOW) time.sleep(5) GPIO.output(pwrKey, GPIO.HIGH) time.sleep(30) status = GPIO.input(statusPin) dns = '8.8.8.8' if gsmConf.get('DNS') is None else gsmConf.get('DNS') apn = 'airtelgprs.com' if gsmConf.get('APN') is None else gsmConf.get( 'APN') apnUser = '******' if gsmConf.get('APN_USER') is None else gsmConf.get( 'APN_USER') apnPass = '******' if gsmConf.get('APN_PASS') is None else gsmConf.get( 'APN_PASS') usbInterface = '3' if gsmConf.get('USBINTERFACE') is None else gsmConf.get( 'USBINTERFACE') usbModem = '1e0e:9001' if gsmConf.get('USBMODEM') is None else gsmConf.get( 'USBMODEM') command = f'sudo sakis3g "connect" DNS="{dns}" APN="CUSTOM_APN" CUSTOM_APN="{apn}" APN_USER="******" APN_PASS="******" USBINTERFACE="{usbInterface}" OTHER="USBMODEM" USBMODEM="{usbModem}"' try: if status == 1: subprocess.call([command], shell=True) except Exception as e: LOG.error('Error resetting modem : %s', e) time.sleep(5) LOG.info('GSM Status: %s', GPIO.input(statusPin))
def off(self): """ Turn off the LED if necessary. """ if self.is_on: self.is_on = False GPIO.output(self.pin, 0)
def display_char(char, font=FONT): try: GPIO.output(DC, GPIO.HIGH) spi.writebytes(font[char] + [0]) except KeyError: pass # Ignore undefined characters.
def test_input_and_output(): with patch("OPi.GPIO.sysfs") as mock: mock.input.return_value = GPIO.HIGH GPIO.setmode(GPIO.BOARD) GPIO.setup(23, GPIO.OUT) GPIO.output(23, not GPIO.input(23)) mock.input.assert_called_with(14) mock.output.assert_called_with(14, GPIO.LOW)
def writeCommand(self, command, *bytes): "Send command byte to display" GPIO.output(self.pinDataCommand, 0) self.spi.writebytes([command]) if len(bytes) > 0: GPIO.output(self.pinDataCommand, 1) self.spi.writebytes(list(bytes))
def led_on(value=1): """ Switch the proto shields LED :param value: 0/1 for off/on. Default is 1. :return: value :rtype : int """ GPIO.output(BOARD.LED, value) return value
def __init__(self, dev='/dev/spidev0.0', spd=1000000): global spidev spidev = spi.openSPI(device=dev, speed=spd) #GPIO.setboard(GPIO.PCPCPLUS) GPIO.setmode(GPIO.BOARD) GPIO.setup(22, GPIO.OUT) GPIO.output(self.NRSTPD, 1) self.MFRC522_Init()
def activedaily(id): now = datetime.now() active = DailySchedule.query.filter_by(id=id).first() db.session.commit() GPIO.output(active.pin, False) off_pin[active.pin] = now + timedelta(minutes=active.duration) flash(f'Sucessfully active!', 'primary') return redirect(url_for('index'))
def test_multiple_output(): with patch("OPi.GPIO.sysfs") as mock: GPIO.setmode(GPIO.BOARD) GPIO.setup([23, 13, 3], GPIO.OUT) GPIO.output([23, 13, 3], GPIO.LOW) mock.output.assert_has_calls( [call(14, GPIO.LOW), call(0, GPIO.LOW), call(12, GPIO.LOW)])
def reset(): """ manual reset :return: 0 """ GPIO.output(BOARD.RST, 0) time.sleep(.01) GPIO.output(BOARD.RST, 1) time.sleep(.01) return 0
def writeBulk(self, color, reps, count=1): "Sends a 24-bit color many times" self.writeCommand(SPICommand.RAMWR) GPIO.output(self.pinDataCommand, 1) color = self.packColor(color) byteArray = [color >> 8, color & 0xFF] * reps for a in range(count): self.spi.writebytes(byteArray)
def rotate_right_motor(self): if is_arm_platform: for halfstep in range(512): for halfstep in range(8): for pin in range(4): GPIO.output(self.right_control_pins[pin], self.right_halfstep_seq[halfstep][pin]) time.sleep(0.001) else: print("moving")
def tx_waveform(self, highpulses, lowpulses): """Send basic waveform.""" if not self.tx_enabled: _LOGGER.error("TX is not enabled, not sending data") return False GPIO.output(self.gpio, GPIO.HIGH) self._sleep((highpulses * self.tx_pulselength) / 1000000) GPIO.output(self.gpio, GPIO.LOW) self._sleep((lowpulses * self.tx_pulselength) / 1000000) return True
def readNextBit(self): # Clock HX711 Digital Serial Clock (PD_SCK). DOUT will be # ready 1us after PD_SCK rising edge, so we sample after # lowering PD_SCL, when we know DOUT will be stable. GPIO.output(self.PD_SCK, True) GPIO.output(self.PD_SCK, False) value = GPIO.input(self.DOUT) # Convert Boolean to int and return it. return int(value)
async def gpio_watcher(state: dict): """Gpio timer. """ on_pins = [] off_pins = [] while state.get("active"): await asyncio.sleep(DEFAULT_WATCH_ITER_TIME) now = current_datetime() day = now.date() off_pins.clear() off_pins.extend( pin for pin, limit in (state.get("pins_time") or {}).items() if limit and limit < now ) on_pins.clear() # from schedule for pin, begin_time, end_time in state.get("pins_schedule") or []: begin = datetime.combine(day, begin_time) end = datetime.combine(day, end_time) if begin <= now <= end: on_pins.append(pin) else: off_pins.append(pin) if off_pins: for pin in off_pins: if pin in on_pins: continue if not state["pins"][pin]: continue try: GPIO.output(pin, GPIO_STATA_OFF) if pin in state["pins_time"]: del state["pins_time"][pin] except Exception as err: logger.error(f"Problem with PIN {pin}: {err}") continue logger.info(f"PIN {pin} turned off automatically") state["pins"][pin] = False if on_pins: for pin in on_pins: if state["pins"][pin]: continue try: GPIO.output(pin, GPIO_STATA_ON) except Exception as err: logger.error(f"Problem with PIN {pin}: {err}") continue logger.info(f"PIN {pin} turned on automatically by schedule") state["pins"][pin] = True
def on_message(client, userdata, message): print("message received ", str(message.payload.decode("utf-8"))) print("message topic=", message.topic) print("message qos=", message.qos) print("message retain flag=", message.retain) if (str(message.payload.decode("utf-8")) == "ON"): print("led ON") GPIO.output(5, 1) elif (str(message.payload.decode("utf-8")) == "OFF"): print("led OFF") GPIO.output(5, 0)
def stop(self): """ Stops PWM output. """ self.toTerminate = True while self.terminated == False: # Just wait time.sleep(0.01) GPIO.output(self.gpioPin, GPIO.LOW) GPIO.cleanup()
def writeGPIO(self,gpio,value): try: GPIO.output(gpio, value) if self._settings.get(["debug"]) == True: self._logger.info("Writing on gpio: %s value %s", gpio,value) self.updateOutputUI() except Exception as ex: template = "An exception of type {0} occurred on writeGPIO. Arguments:\n{1!r}" message = template.format(type(ex).__name__, ex.args) self._logger.warn(message) pass
def MFRC522_Init(self): GPIO.output(self.NRSTPD, 1) self.MFRC522_Reset(); self.Write_MFRC522(self.TModeReg, 0x8D) self.Write_MFRC522(self.TPrescalerReg, 0x3E) self.Write_MFRC522(self.TReloadRegL, 30) self.Write_MFRC522(self.TReloadRegH, 0) self.Write_MFRC522(self.TxAutoReg, 0x40) self.Write_MFRC522(self.ModeReg, 0x3D) self.AntennaOn()
def __init__(self, dev='/dev/spidev1.0', spd=1000000): spi.openSPI(device=dev,speed=spd) GPIO.setmode(GPIO.BOARD) GPIO.setup(22, GPIO.OUT) GPIO.output(self.NRSTPD, 1) self.MFRC522_Init()