Beispiel #1
0
def stop_all():
    try:
        RPIO.output(up_pin, 1)
        RPIO.output(down_pin, 1)
        RPIO.cleanup()
    except:
        pass
Beispiel #2
0
    def _exit_handler_(self):
        if self.status == True:
            print('[EXIT] Turning OFF the fan.')
            RPIO.output(self.pin, False)

        print('[EXIT] Performing a RESET (cleanup) of the fan GPIO (pin: ' + str(self.PIN) + ')')
        RPIO.cleanup()
Beispiel #3
0
 def run(self):
   RPIO.setmode(RPIO.BCM)
   # now we'll define two threaded callback functions
   # these will run in another thread when our events are detected
   RPIO.add_interrupt_callback(
       gpio_id=self.lock_button_pin,
       callback=self.lock_button_cb,
       edge='falling',
       debounce_timeout_ms=100,
       threaded_callback=False,
       pull_up_down=RPIO.PUD_UP)
   RPIO.add_interrupt_callback(
       gpio_id=self.start_tx_pin,
       callback=self.serial_cb,
       edge='both',
       threaded_callback=False,
       pull_up_down=RPIO.PUD_UP)
   RPIO.setup(self.lock_pin, RPIO.OUT, initial=RPIO.LOW)
   RPIO.setup(self.unlock_pin, RPIO.OUT, initial=RPIO.LOW)
   try:
     RPIO.wait_for_interrupts()
   except KeyboardInterrupt:
     # Could we just use finally here instead?
     # Uncaught exceptions will leave RPIO uncleaned, is this intentional?
     RPIO.cleanup() # clean up RPIO on CTRL+C exit
   RPIO.cleanup()   # clean up RPIO on normal exit
Beispiel #4
0
def test():
	
	# setup logging
	FORMAT = '%(asctime)s %(levelname)s %(message)s'
	logging.basicConfig(format=FORMAT)
	logger = logging.getLogger()
	logger.setLevel(logging.INFO)
	if not logger.handlers:
		logger.addHandler(logging.StreamHandler())
	log_format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
	logging.basicConfig(format=log_format, level=logging.INFO)
	
	zwrs = ZwReadState(logger=logger)
	zwrs.startReadingState()
	zwrs.printData()
	zwrs.analyzeData()
	#if (zwrs.isMachineOff()):
		# turn on machine		
	err = zwrs.getError("John")
	if (err["isErr"]):
		logger.info( err)
	else:
		logger.info( "No error on getError()")
	logger.info("Done testing")
	sleep(10)
	
	RPIO.cleanup()
Beispiel #5
0
def stop_all():
    try:
        RPIO.output(up_pin, 1)
        RPIO.output(down_pin, 1)
        RPIO.cleanup()
    except:
        pass
Beispiel #6
0
def closeProgram(signal, frame):
	""" Close fonction"""
	print("\nResseting GPIO...", end="")
	RPIO.cleanup() #Reset every channel that has been set up by this program, and unexport interrupt gpio interfaces
	print(" ok")
	print("exiting")
	sys.exit(0)
Beispiel #7
0
  def start_run(self):

    if args.verbose: print "[%s] thread : start_run called" % (self.name)

    #Tell function which globals to look for (need time values as globals so that callback 
    #function sned_triggers can also see them)
    global bor_time_s
    global old_bof_time_s
    global old_eof_time_s
    global old_gpio_trig_time_s

    #Check not already running
    if self.running==False:

      if args.verbose: print "[%s] thread : Run started" % (self.name)
      print 'Starting run : Set t = 0 s : Waiting for triggers'

      #Init time values
      bor_time_s = time.time()  #Record BOR time
      old_bof_time_s = 0 #Init 'old' times
      old_eof_time_s = 0
      old_gpio_trig_time_s = 0

      #If in real triggers mode, setup RPIO listen
      if args.which == 'real':

        #Clean RPIO system before creating a new callback process
        #This removes any existing wait_for_interrupts threads, which otherwise lead to multiple 
        #simultaneous BOF signals being send for a single pin signal
        #Note: Must call this at start of evey run (otherwise get issues with first pin interrupt
        #when there is a long (a few seconds)wait between the socket connection forming and BOR) 
        RPIO.cleanup()

        #Define callback function for pin interrupts (e.g. function that is called when a 
        #pin interrupts). The callback function sends the BOF/EOF triggers to the socket.
        #Note: Must call this at start of evey run (otherwise get issues with first pin interrupt
        #when there is a long (a few seconds)wait between the socket connection forming and BOR) 
        RPIO.add_interrupt_callback(args.input_pin, send_fill, edge='both', pull_up_down=RPIO.PUD_UP, \
                                    threaded_callback=False, debounce_timeout_ms=args.debounce_timeout_ms)

        #Start thread listening for input signal on pins
        if args.verbose: print "[%s] thread : Starting GPIO wait_for_interrupts thread" % (self.name)
        RPIO.wait_for_interrupts(threaded=True) 

      #If in fake triggers mode, start fake trigger generation thread
      elif args.which == 'fake':

        #Create fake trigger thread and start it
        if args.verbose: print "[%s] thread : Starting fake triggers thread" % (self.name)
        self.fake_trigger_thread = FakeTriggerThread("FakeTriggers")
        self.fake_trigger_thread.start()


      #Update state
      self.running = True 

    #Can't start run if one already underway
    else:
      if args.verbose: print "[%s] thread : Could not start run, there is already a run underway" % (self.name)
Beispiel #8
0
def loop():
    try:
        while True:
            flicker()
    except KeyboardInterrupt:
        pass
    finally:
        GPIO.cleanup()
Beispiel #9
0
def closeProgram(signal, frame):
    """ Close fonction"""
    print("\nResseting GPIO...", end="")
    RPIO.cleanup(
    )  #Reset every channel that has been set up by this program, and unexport interrupt gpio interfaces
    print(" ok")
    print("exiting")
    sys.exit(0)
def main():
    print 'Pi voice alert v1.1.0 publisher started'
    global settings
    settings = setup()
    print settings

    register_gpio(settings)

    RPIO.wait_for_interrupts()
    RPIO.cleanup()
Beispiel #11
0
    def __del__(self):
        self._adcManager.stop()
        self._adcManager.join()

        self._thermostat.stop()
        self._thermostat.join()

        self._kegManager.stop()
        self._kegManager.join()
        RPIO.cleanup()
Beispiel #12
0
def updown(thrust, air_time):  # Thrust is a value between 0 and 1
    if 0 <= thrust <= 1:
        pwm(updown_pin, 1)
        time.sleep(air_time)
        pwm(updown_pin, 0)
    else:
        print("Error at function updown")
        GPIO.cleanup()
        exit()
    return
Beispiel #13
0
    def __del__(self):
        self._adcManager.stop()
        self._adcManager.join()

        self._thermostat.stop()
        self._thermostat.join()

        self._kegManager.stop()
        self._kegManager.join()
        RPIO.cleanup()
	def closeEvent(self, event):
		reply = QtGui.QMessageBox.question(self,'Message',"Are you sure to quit?", QtGui.QMessageBox.Yes|QtGui.QMessageBox.No,QtGui.QMessageBox.No)
		if reply == QtGui.QMessageBox.Yes:
			#closing serial thread list	
			for thread in self.reader_list:	
				thread.terminate()
			RPIO.stop_waiting_for_interrupts()
			RPIO.cleanup()
			event.accept()
	    	else:
			event.ignore()     
Beispiel #15
0
    def __init__(self):
        RPIO.cleanup()
        RPIO.setmode(RPIO.BCM)
        RPIO.setup(BLUE, RPIO.OUT)
        RPIO.setup(GREEN, RPIO.OUT) 
        RPIO.setup(RED, RPIO.OUT)
        RPIO.output(BLUE, False)
	RPIO.PWM.setup()
        for index, colorPin in enumerate(colorPins):
            RPIO.PWM.init_channel(dmaChannels[index], 10000)
            RPIO.PWM.add_channel_pulse(dmaChannels[index], colorPin, 0, 0)
Beispiel #16
0
def move(direction, duration):
    RPIO.setup(up_pin, RPIO.OUT, initial=RPIO.HIGH)
    RPIO.setup(down_pin, RPIO.OUT, initial=RPIO.HIGH)
    if direction == UP:
        RPIO.output(up_pin, 0)
        time.sleep(float(duration))
        RPIO.output(up_pin, 1)
    if direction == DOWN:
        RPIO.output(down_pin, 0)
        time.sleep(float(duration))
        RPIO.output(down_pin, 1)
    RPIO.cleanup()
Beispiel #17
0
def int_communication(data_dir, freq, single, adr_change, backend, skip_meas,
                      clk_enable):
    GPIO_DR = 6
    i = 0
    while os.path.exists(os.path.join(data_dir, 'data_' + str(i) + '.dat')):
        i += 1
    global write_file
    if not skip_meas:
        import te_setup
        #import RPi.GPIO as GPIO
        import RPIO as GPIO
        import spidev

        spi = spidev.SpiDev()
        write_file = open(os.path.join(data_dir, 'data_' + str(i) + '.dat'),
                          'w')
        global spi
        spi.open(0, 0)
        spi.max_speed_hz = (freq)
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(GPIO_DR, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
        GPIO.add_event_detect(GPIO_DR, GPIO.RISING)

        if not adr_change:
            GPIO.add_event_callback(GPIO_DR, callback)
        else:
            GPIO.add_event_callback(GPIO_DR, callback_adr)
        if single:
            if not adr_change:
                callback(6)
            else:
                callback_adr(6)
        else:
            try:
                if clk_enable:
                    GPIO.setup(5, RPIO.ALT0)
                while True:
                    time.sleep(1)
            except KeyboardInterrupt:
                GPIO.setup(5, RPIO.INPUT)
                GPIO.cleanup()
                #global write_file
        time.sleep(0.1)
        write_file.close()
        print('Written to data_' + str(i) + '.dat')

    if backend == 'display_graph':
        data_manager.data_manager(directory=data_dir,
                                  data_size=1000,
                                  train_size=100,
                                  split_mode=False,
                                  attenate_flag=False,
                                  save_as_png=False).plot()
Beispiel #18
0
def move(direction, duration):
    RPIO.setup(up_pin, RPIO.OUT, initial=RPIO.HIGH)
    RPIO.setup(down_pin, RPIO.OUT, initial=RPIO.HIGH)
    if direction == UP:
        RPIO.output(up_pin, 0)
        time.sleep(float(duration))
        RPIO.output(up_pin, 1)
    if direction == DOWN:
        RPIO.output(down_pin, 0)
        time.sleep(float(duration))
        RPIO.output(down_pin, 1)
    RPIO.cleanup()
Beispiel #19
0
def birdistheword():
    pygame.mixer.music.play()
    RPIO.output(17, True)
    set_angle(0)
    set_angle(90)
    set_angle(0)
    RPIO.output(17, False)
    RPIO.cleanup()
    #wait for music to play
    if (wait_for_completion):
        print 'waiting'
        while (pygame.mixer.music.get_busy()):
            pass
Beispiel #20
0
 def sendMessage(self, message):
     # set up GPIO output channel
     RPIO.setup(self.txPin, RPIO.OUT)
     for i in range(1, self.nbEnvois):
         RPIO.output(self.txPin, False)
         for data in range(0, 6):
             RPIO.output(self.txPin, True)
             sleep(self.dureeInterDonnees)
             for bit in range(0, 11):
                 self.__sendBit(str(message)[data][bit == '1'])
         RPIO.output(self.txPin, False)
         sleep(self.dureeInterMessage)
     RPIO.cleanup()
 def closeEvent(self, event):
     reply = QtGui.QMessageBox.question(
         self, 'Message', "Are you sure to quit?",
         QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.No)
     if reply == QtGui.QMessageBox.Yes:
         #closing serial thread list
         for thread in self.reader_list:
             thread.terminate()
         RPIO.stop_waiting_for_interrupts()
         RPIO.cleanup()
         event.accept()
     else:
         event.ignore()
Beispiel #22
0
 def setActive(self, state):
     logger.info("GPIOManager %s, %s", "setActive", str(state))
     if state:
         self.usageCount += 1
         # print("activate RPIO system")
         # RPIO.setmode(RPIO.BCM)
         # RPIO.setwarnings(True)
         if debug:
             print(RPIO.version())
     else:
         self.usageCount -= 1
         if self.usageCount == 0:
             RPIO.cleanup()
 def setActive(self, state):
     logger.info("GPIOManager %s, %s", "setActive", str(state))
     if state:
         self.usageCount += 1
         # print("activate RPIO system")
         # RPIO.setmode(RPIO.BCM)
         # RPIO.setwarnings(True)
         if debug:
             print(RPIO.version())
     else:
         self.usageCount -= 1
         if self.usageCount == 0:
             RPIO.cleanup()
Beispiel #24
0
def birdistheword():
  pygame.mixer.music.play()
  RPIO.output(17, True)
  set_angle(0)
  set_angle(90)
  set_angle(0) 
  RPIO.output(17,False)
  RPIO.cleanup()
  #wait for music to play
  if( wait_for_completion ):
    print 'waiting'
    while( pygame.mixer.music.get_busy()):
      pass
Beispiel #25
0
    def shutdown_cb(self):

        rospy.loginfo(rospy.get_caller_id() + ": Shutdown callback")

        GPIO.setmode(GPIO.BCM)  # Broadcom pin-numbering scheme

        self._servo.stop_servo(self.left_ia)
        self._servo.stop_servo(self.right_ia)

        GPIO.output(self.left_ib, GPIO.LOW)
        GPIO.output(self.right_ib, GPIO.LOW)
        GPIO.cleanup()
        RPIO.cleanup()
Beispiel #26
0
 def sendMessage(self, message):
     # set up GPIO output channel
     RPIO.setup(self.txPin, RPIO.OUT)
     for i in range(1,self.nbEnvois) :
         RPIO.output(self.txPin, False)
         for data in range(0,6):
             RPIO.output(self.txPin, True)
             sleep(self.dureeInterDonnees)
             for bit in range(0,11):
                 self.__sendBit(str(message)[data][bit == '1'])                    
         RPIO.output(self.txPin, False)
         sleep(self.dureeInterMessage)
     RPIO.cleanup()
Beispiel #27
0
def int_communication(data_dir, freq, single, adr_change, backend, skip_meas, clk_enable):
    GPIO_DR = 6
    i = 0
    while os.path.exists(os.path.join(data_dir, 'data_' + str(i) + '.dat')):
        i += 1
    global write_file
    if not skip_meas:
        import te_setup
        #import RPi.GPIO as GPIO
        import RPIO as GPIO
        import spidev

        spi = spidev.SpiDev()
        write_file = open(os.path.join(data_dir, 'data_' + str(i) + '.dat'), 'w')
        global spi
        spi.open(0,0)
        spi.max_speed_hz=(freq)
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(GPIO_DR, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
        GPIO.add_event_detect(GPIO_DR, GPIO.RISING)

        if not adr_change:
            GPIO.add_event_callback(GPIO_DR, callback)
        else:
            GPIO.add_event_callback(GPIO_DR, callback_adr)
        if single:
            if not adr_change:
                callback(6)
            else:
                callback_adr(6)
        else:
            try:
                if clk_enable:
                    GPIO.setup(5, RPIO.ALT0)
                while True:
                    time.sleep(1)
            except KeyboardInterrupt:
                GPIO.setup(5, RPIO.INPUT)
                GPIO.cleanup()
                #global write_file
        time.sleep(0.1)
        write_file.close()
        print('Written to data_' + str(i) + '.dat')

    if backend == 'display_graph':
        data_manager.data_manager(directory=data_dir,
                     data_size=1000,
                     train_size=100,
                     split_mode=False,
                     attenate_flag=False,
                     save_as_png=False).plot()
Beispiel #28
0
def TurnMotor(gpio_pin_pwm,gpio_pin_dir,speed,direction,duration):
  RPIO.setup(gpio_pin_pwm, RPIO.OUT)
  RPIO.setup(gpio_pin_dir, RPIO.OUT)

  if direction:
    print "Turning Motor on pin: " + str(gpio_pin_pwm) + "UP"

  else:
    print "Turning Motor on pin: " + str(gpio_pin_pwm) + "DOWN"
  RPIO.output(gpio_pin_dir, direction)
  RPIO.output(gpio_pin_pwm, True)
  sleep(duration)
  RPIO.output(gpio_pin_pwm, False)
  print "Done Moving"
  RPIO.cleanup()
Beispiel #29
0
    def turn_off(self):
        """
        Turn off and clean up.
        """

        print('Shut down controller objects')
        self.D_0.stop()
        self.D_1.stop()
        self.D_2.stop()
        self.D_3.stop()
        self.D_4.stop()


        RPIO.cleanup()

        print('Done.')
Beispiel #30
0
def actualizo_contador(tid, itemID=None, threshold=None):
    global sentido
    global contador1
    contador1 = 0
    global contador2
    contador2 = 0

    global PI
    PI = 3.14

    global dos_pi_R
    dos_pi_R = 34.5575

    global TOTAL_TICKS_VUELTA_IZQ
    TOTAL_TICKS_VUELTA_IZQ = 86
    global TOTAL_TICKS_VUELTA_DER
    TOTAL_TICKS_VUELTA_DER = 89

    global tolerancia
    tolerancia = abs(TOTAL_TICKS_VUELTA_DER - TOTAL_TICKS_VUELTA_IZQ)

    global TICKS_POR_GRADO_IZQ
    TICKS_POR_GRADO_IZQ = 0.3752 * 2

    global TICKS_POR_GRADO_DER
    TICKS_POR_GRADO_DER = 0.3883 * 2

    if (sys.argv[1] == 'F'):
        sentido = "ADELANTE"
        resultados = adelante()

    elif (sys.argv[1] == 'B'):
        sentido = "ATRAS"
        resultados = atras()
        #servo = 'D'
        #accion_servo(servo)

    elif (sys.argv[1] == 'L' or sys.argv[1] == 'R'):
        sentido = "IZQUIERDA"
        if (sys.argv[1] == 'R'):
            sentido = "DERECHA"
        resultados = giro()

    RPIO.cleanup()
    print(resultados)
Beispiel #31
0
def move(direction):
    RPIO.cleanup()
    RPIO.setup(up_pin, RPIO.OUT, initial=RPIO.HIGH)
    RPIO.setup(down_pin, RPIO.OUT, initial=RPIO.HIGH)

    if direction == UP:
        try:
            RPIO.output(up_pin, 0)
        except:
            pass
        time.sleep(1)

    if direction == DOWN:
        try:
            RPIO.output(down_pin, 0)
        except:
            pass
        time.sleep(1)
Beispiel #32
0
def move(direction):
    RPIO.cleanup()
    RPIO.setup(up_pin, RPIO.OUT, initial=RPIO.HIGH)
    RPIO.setup(down_pin, RPIO.OUT, initial=RPIO.HIGH)

    if direction == UP:
        try:
            RPIO.output(up_pin, 0)
        except:
            pass
        time.sleep(1)


    if direction == DOWN:
        try:
            RPIO.output(down_pin, 0)
        except:
            pass
        time.sleep(1)
Beispiel #33
0
def leftright(direction, air_time):
    if direction == "left":
        GPIO.output(updown_pin, 1)
        GPIO.output(neutral_pin, 0)
        time.sleep(air_time)
        GPIO.output(neutral_pin, 1)
        GPIO.output(updown_pin, 0)
    elif direction == "right":
        GPIO.output(updown_pin, 1)
        GPIO.output(neutral_pin, 0)
        GPIO.output(right_pin, 1)
        time.sleep(air_time)
        GPIO.output(right_pin, 0)
        GPIO.output(neutral_pin, 1)
        GPIO.output(updown_pin, 0)
    else:
        print("Error at function leftright")
        GPIO.cleanup()
        exit()
    return
Beispiel #34
0
def forwardbackward(direction, air_time):
    if direction == "forward":
        GPIO.output(updown_pin, 1)
        GPIO.output(stationary_pin, 0)
        time.sleep(air_time)
        GPIO.output(stationary_pin, 1)
        GPIO.output(updown_pin, 0)
    elif direction == "backward":
        GPIO.output(updown_pin, 1)
        GPIO.output(stationary_pin, 0)
        GPIO.output(backward_pin, 1)
        time.sleep(air_time)
        GPIO.output(backward_pin, 0)
        GPIO.output(stationary_pin, 1)
        GPIO.output(updown_pin, 0)
    else:
        print("Error at function forwardbackward")
        GPIO.cleanup()
        exit()
    return
Beispiel #35
0
def readCard():
    global errorCount
    try:
        LED("blue")
        while True:
            conf.ser.flushInput()
            LED("blue")
            rfidData = conf.ser.readline().strip()
            print "Line: "
            if len(rfidData) > 0:
                rfidData = rfidData[1:13]
                print "Card Scanned: ", rfidData
                print findTag(rfidData)

    except:
        errorLog.classErrorLog(sys.exc_info())

    finally:
        conf.ser.close()
        conf.db.close()
        RPIO.cleanup()
Beispiel #36
0
def main():
	import RPIO
	import RPIO.PWM
	argv=sys.argv[1:]
	pulse=int(argv[0])
	pin=int(argv[1])
	switch=argv[2]
	switchpin=int(argv[3])
	RPIO.setmode(RPIO.BCM)		
	if switch=="1":
                RPIO.setup(switchpin, RPIO.OUT)
		RPIO.output(switchpin,True)
	
	servo = RPIO.PWM.Servo()
	servo.set_servo(pin, pulse)
	time.sleep(1)
	servo.stop_servo(pin)
	
	if switch=="1":
                RPIO.output(switchpin,False)
	RPIO.cleanup()
Beispiel #37
0
def readCard():
    global errorCount
    try:
        LED("blue")
        while True:
            conf.ser.flushInput()
            LED("blue")
            rfidData = conf.ser.readline().strip()
            print "Line: "
            if len(rfidData) > 0:
                rfidData = rfidData[1:13]
                print "Card Scanned: ", rfidData
                print findTag(rfidData)

    except:
        errorLog.classErrorLog(sys.exc_info())

    finally:
        conf.ser.close()
        conf.db.close()
        RPIO.cleanup()
Beispiel #38
0
def main():
    import RPIO
    import RPIO.PWM
    argv = sys.argv[1:]
    pulse = int(argv[0])
    pin = int(argv[1])
    switch = argv[2]
    switchpin = int(argv[3])
    RPIO.setmode(RPIO.BCM)
    if switch == "1":
        RPIO.setup(switchpin, RPIO.OUT)
        RPIO.output(switchpin, True)

    servo = RPIO.PWM.Servo()
    servo.set_servo(pin, pulse)
    time.sleep(1)
    servo.stop_servo(pin)

    if switch == "1":
        RPIO.output(switchpin, False)
    RPIO.cleanup()
def main():
    state_machine.add_relay(RelayState(10, 5, 5, 10, 1))
    state_machine.add_relay(RelayState(10, 5, 5, 9, 2))
    state_machine.add_relay(RelayState(10, 5, 5, 11, 3))
    state_machine.add_relay(RelayState(10, 5, 5, 22, 4))
    state_machine.start()

    tmp = None
    while not (tmp == "exit" or tmp == ""):
        tmp = input("kW? ")
        try:
            tmp2 = float(tmp)
            state_machine.next(tmp2, None)
        except (TypeError, ValueError):
            print("Error happened!!!")
        if tmp == "update":
            state_machine.add_relay(RelayState(8, 2, 5, 10, 1))
            state_machine.add_relay(RelayState(8, 2, 5, 9, 2))
            state_machine.add_relay(RelayState(8, 2, 5, 11, 3))
            state_machine.add_relay(RelayState(9, 2, 5, 22, 4))

    state_machine.stop()
    GPIO.cleanup()
Beispiel #40
0
def main():
    config = get_config()
    try:
        for service, service_config in config.iteritems():
            init_button_led(service_config)
        # There is actually an endpoint to get the status of the
        # world which should be used here.
        while True:
            for service, service_config in config.iteritems():
                resp = requests.get(service_config['status_url'])
                color = resp.json()['color']
                config[service]['comms'] = decode_color(color)
                print color
            time.sleep(30)
    except KeyboardInterrupt:
        pass
    except Exception as e:
        logging.exception("bailing!")
    finally:
        RPIO.cleanup()
        for _, service_config in config.iteritems():
            if service_config['led']:
                servo.stop_servo(service_config['led'])
Beispiel #41
0
def main():
	config = get_config()
	try:
		for service, service_config in config.iteritems():
			init_button_led(service_config)
		# There is actually an endpoint to get the status of the
		# world which should be used here.
		while True:
			for service, service_config in config.iteritems():
				resp = requests.get(service_config['status_url'])
				color = resp.json()['color']
				config[service]['comms'] = decode_color(color)
				print color
			time.sleep(30)
	except KeyboardInterrupt:
		pass
	except Exception as e:
		logging.exception("bailing!")
	finally:
		RPIO.cleanup()
		for _, service_config in config.iteritems():
			if service_config['led']:
				servo.stop_servo(service_config['led'])
Beispiel #42
0
def readCard():
    global rfidData, errorCount
    try:
        classLED("blue")
        while True:
            ser.flushInput()
            classLED("blue")
            rfidData = ser.readline().strip()
            print "Line: "
            if len(rfidData) > 0:
                rfidData = rfidData[1:13]
                print "Card Scanned: ", rfidData
                print findTag(rfidData)

    except SerialException:
        print "Serial Exception error"
        errorCount+=1
        readCard()

    except termios.error:
        print "Termios error"
        errorCount+=1
        readCard()

    except OSError as e:
        if e.errno == 11:
            errorCount+=1
            readCard()
        else:
            raise

    finally:
        ser.close()
        con.close()
        RPIO.cleanup()
        pass
Beispiel #43
0
def readCard():
    global errorCount
    try:
#        LED("blue")
        while True:
            # Scan for cards    
            (status,TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL)

            # If a card is found
            if status == MIFAREReader.MI_OK:
                print "Card detected"
            
            # Get the UID of the card
            (status,uid) = MIFAREReader.MFRC522_Anticoll()

            # If we have the UID, continue
            if status == MIFAREReader.MI_OK:

#            conf.ser.flushInput()
            LED("blue")
#            rfidData = conf.ser.readline().strip()
            #print "Line: "
            if len(rfidData) > 0:
                #rfidData = rfidData[1:13]
                rfidData =  uid
                print "Card read UID: "+str(uid[0])+","+str(uid[1])+","+str(uid[2])+","+str(uid[3])
                print "Card Scanned: ", rfidData
                print findTag(rfidData)

    except:
        errorLog.classErrorLog(sys.exc_info())

    finally:
#        conf.ser.close()
        conf.db.close()
        RPIO.cleanup()
Beispiel #44
0
RPIO.setmode(RPIO.BCM)

"""
ngpio=17
GPIO.setup(ngpio, GPIO.OUT)     #конфигурируем GPIO 7 как выход
GPIO.output(ngpio, True)               #выводим на GPIO 7 логическую "1" (3.3 V)
sleep(1)
GPIO.output(ngpio, False)              #выводим на GPIO 7 логический "0"
sleep(2)
GPIO.output(ngpio, True)               #выводим на GPIO 7 логическую "1" (3.3 V)
"""

def gpio_callback(gpio_id, val):
    print("gpio %s: %s" % (gpio_id, val))

ngpio=14

RPIO.setup(ngpio, RPIO.IN, pull_up_down=RPIO.PUD_DOWN)
RPIO.add_interrupt_callback(ngpio, gpio_callback, edge='rising', debounce_timeout_ms=2000, pull_up_down=RPIO.PUD_DOWN)
#        , threaded_callback=True)

RPIO.wait_for_interrupts(threaded=True)

n = 0
while True:
    sleep(1)
    n += 1
    print n

RPIO.cleanup() 
Beispiel #45
0
def reset():
    RPIO.cleanup()
Beispiel #46
0
# Starts waiting for interrupts (exit with Ctrl+C)
# RPIO.wait_for_interrupts()   # blocks until interrupt, never proceeds beyond this point

RPIO.wait_for_interrupts(threaded=True)  # non-blocking, separate thread

try:
    while (1):
        now1 = datetime.datetime.now()
        dstr1 = str(now1.strftime("%Y-%m-%d_%H:%M:%S"))
        if (dCount1 > 0):
            dAvg1 = dSum1 / dCount1
        print("Time555: %s Avg: %08.6f Min: %08.6f Max: %08.6f Total: %d" %
              (dstr1, dAvg1, dMin1, dMax1, dCount1))

        now2 = datetime.datetime.now()
        dstr2 = str(now2.strftime("%Y-%m-%d_%H:%M:%S"))
        if (dCount2 > 0):
            dAvg2 = dSum2 / dCount2
        print("Time4017: %s Avg: %08.6f Min: %08.6f Max: %08.6f Total: %d" %
              (dstr2, dAvg2, dMin2, dMax2, dCount2))

        time.sleep(2.5)  #con (1) Stampa 1 volta ogni secondo
    #con (10) stampa ogni 10 secondi

except KeyboardInterrupt:
    print " "
    print "Ciao !"
    RPIO.cleanup()
RPIO.cleanup()
def finish():
    setLedColour(OFF)
    RPIO.cleanup()
Beispiel #48
0
 def cleanup(self):
     if self.__backlight:
         PWM.clear_channel_gpio(0, self.__backlight)
         PWM.cleanup()
     GPIO.cleanup()
	def deInit(self):
		RPIO.cleanup()
Beispiel #50
0
 def close(self):
     RPIO.PWM.cleanup()
     RPIO.stop_waiting_for_interrupts()
     RPIO.cleanup()
Beispiel #51
0
 def cleanup(self):
     RPIO.cleanup()
Beispiel #52
0
    def test6_interrupts(self):
        logging.info(" ")
        logging.info(" ")
        logging.info("=== INTERRUPT TESTS ==")

        def test_callback(*args):
            logging.info("- interrupt callback received: %s", (args))

        def stop_interrupts(timeout=3):
            time.sleep(timeout)
            RPIO.stop_waiting_for_interrupts()
            logging.info("- called `stop_waiting_for_interrupts()`")

        PORT = 8080

        def socket_callback(socket, msg):
            logging.info("Socket [%s] msg received: %s", socket.fileno(), msg)

        def socket_client(timeout=3):
            logging.info("Socket client connecting in 3 seconds...")
            time.sleep(timeout)
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.connect(("localhost", PORT))
            s.sendall("Hello, world".encode('utf-8'))
            s.close()
            logging.info("Socket client done...")

        #
        # Interrupt test with socket comm
        #
        logging.info(" ")
        logging.info("Testing interrupts on GPIO-%s and socket comm", GPIO_IN)
        RPIO.add_tcp_callback(PORT, socket_callback)

        with self.assertRaises(AttributeError):
            RPIO.add_tcp_callback(8081, None)

        RPIO.add_interrupt_callback(GPIO_IN, test_callback, edge='both', \
                pull_up_down=RPIO.PUD_DOWN)
        RPIO.add_interrupt_callback(GPIO_IN, test_callback, edge='both', \
                pull_up_down=RPIO.PUD_DOWN, threaded_callback=True)

        # Add a number of TCP clients
        Thread(target=socket_client).start()
        Thread(target=socket_client, args=(4,)).start()
        Thread(target=socket_client, args=(4,)).start()
        Thread(target=socket_client, args=(4,)).start()
        Thread(target=socket_client, args=(4,)).start()

        # One stop interrupts thread
        Thread(target=stop_interrupts, args=(10,)).start()

        logging.info("- waiting 10s for interrupts on GPIO-%s...", GPIO_IN)
        RPIO.wait_for_interrupts()

        logging.info("-")
        RPIO.cleanup()

        #
        # Auto interrupt shutdown with thread and stop_waiting_for_interrupts
        #
        logging.info("start second ")
        RPIO.add_interrupt_callback(GPIO_IN, test_callback, edge='both', \
                pull_up_down=RPIO.PUD_OFF)
        RPIO.add_interrupt_callback(GPIO_OUT, test_callback, edge='falling', \
                pull_up_down=RPIO.PUD_UP, debounce_timeout_ms=100)
        logging.info("- waiting 3s for interrupts on gpio %s and %s...", \
                GPIO_IN, GPIO_OUT)
        Thread(target=stop_interrupts, args=(3,)).start()
        RPIO.wait_for_interrupts()
        logging.info("-")
        RPIO.cleanup()

        logging.info("ALL DONE :)")
def off(gpio, value):
        print ("[Info] RaspiShield requesting shutdown on pin 17")
        RPIO.setup(27, RPIO.HIGH)
        os.system("sudo shutdown -h now")
        RPIO.cleanup()
        time.sleep(0.5)
Beispiel #54
0
#!/usr/bin/python
import RPIO as GPIO
import time


def blink(pin):
    GPIO.output(pin, GPIO.HIGH)
    time.sleep(1)
    GPIO.output(pin, GPIO.LOW)
    time.sleep(1)
    return


GPIO.setmode(GPIO.BOARD)

GPIO.setup(3, GPIO.OUT)

for i in range(0, 50):
    blink(3)

GPIO.cleanup()
Beispiel #55
0
def cleanupgpio():
    """Release all GPIO resources."""
    RPIO.cleanup_interrupts()
    RPIO.cleanup()
def gpio_reset():
    RPIO.cleanup()
Beispiel #57
0
# This is how to import modules in python. There are other modules, like 
# 'time' and 'os'.  There are documentation available to use for those too!
import RPIO as rpio

# Changes the numbering system for the GPIO ports.  There is another 
# numbering method, but you cannot mix them.  Unexpected behavior would
# happen.
rpio.setmode(rpio.BOARD)

# This is how to set up set up pin #8 as an output channel.
# This is also how you can use a method from a module, using the '.'
rpio.setup(8, rpio.OUT)

# Set the pin to "high"
rpio.output(8, True)

# CODE HERE

# Here is a cleanup method, many modules include one of these
# and they are suggested to be used.
rpio.cleanup()
Beispiel #58
0
def end_WiRobot(): ########## end_WiRobot_begin
	gpio.cleanup()
	sys.exit()
Beispiel #59
0
	def cleanup(self):
		RPIO.cleanup()