示例#1
0
	def run(self):
		while(not self.kill):
			while(self.stoped):
				time.sleep(0)
				if self.kill:
					return
			outarr = []
			allzero = True
			#prev = time.time()
			for p in self.ports:
				d = self.gather(p)
				if d != 0:
					allzero = False
				outarr.append(d)
				gpio.output(self.led, d)
				#while(time.time()-prev < 0.1):
				#	time.sleep(0)
			if not allzero:
				self.savestart = True
			if self.savestart:
				#self.quelock.acquire()
				#self.savque.put(outarr)
				#self.quelock.release()
				self.dataarr.append(outarr)
				self.count = self.count + 1
示例#2
0
 def __init__(self):
     self._led = port.PA10
     self._ledstate = 0
     self._loop = False
     gpio.init()
     gpio.setcfg(self._led, gpio.OUTPUT)
     gpio.output(self._led, 0)
示例#3
0
def remedio():
   tomar = ""
   while True:
      horanow = datetime.now().strftime("%H:%M")
      remedios = db.child("pacientes/oZuB8VfohicfwT5unXiV7H8Mkpy2/remedios/").get()
      if(remedios.val()!=0):
         for lista in remedios.each():
            pathH = ("pacientes/oZuB8VfohicfwT5unXiV7H8Mkpy2/remedios/") + str(lista.key()) + ("/horario")
            pathD = ("pacientes/oZuB8VfohicfwT5unXiV7H8Mkpy2/remedios/") + str(lista.key()) + ("/doses")
            pathI = ("pacientes/oZuB8VfohicfwT5unXiV7H8Mkpy2/remedios/") + str(lista.key()) + ("/intervalo")
            hora = db.child(pathH).get()
            doses = db.child(pathD).get()
            intervalo = db.child(pathI).get()
            print hora.val() 
            if(hora.val()==horanow):
               print "tomar remedio"
               db.child("Alarme").set(1)
               tomar = str(lista.key())
               gpio.output(port.PA7, gpio.HIGH)
            if gpio.input(port.PA1):
               print "botao apertado"
               gpio.output(port.PA7, gpio.LOW)
               pathHtomar = ("pacientes/oZuB8VfohicfwT5unXiV7H8Mkpy2/remedios/") + tomar + ("/horario")
               pathDtomar = ("pacientes/oZuB8VfohicfwT5unXiV7H8Mkpy2/remedios/") + tomar + ("/doses")
               hora = db.child(pathHtomar).get()
               doses = db.child(pathDtomar).get()
               db.child("Alarme").set(0)
               db.child(pathHtomar).set("13:00")
#            db.child(pathDtomar).update(doses.val() - 1)
      else:
         print "Nao ha remedios!"
         sleep(1)
def shutdowner():

    if not os.getegid() == 0:
        sys.exit('Script must be run as root')

    delay = 5

    portToListen = port.PI2  #13
    portToWrite = port.PI1  #11

    gpio.init()
    gpio.setcfg(portToListen, gpio.INPUT)
    gpio.setcfg(portToWrite, gpio.OUTPUT)
    gpio.output(portToWrite,
                1)  #this tells EPS that shutdown script is running fine

    while 1:
        v = gpio.input(portToListen)
        print v
        if (v == 1):
            sleep(delay)
            v = gpio.input(portToListen)
            if (v == 1):
                print("shutdown of the Olimex")
                gpio.output(portToWrite, 1)
                os.system("sudo halt -p")
                break
        sleep(delay)
示例#5
0
def loop():
    global hero_pos, new_terrain_type, new_terrain_duration, playing, blink, distance

    if not playing:
        draw_hero(HERO_POSITION_OFF if blink else hero_pos, terrain_upper,
                  terrain_lower, distance >> 3)
        if blink:
            lcd.set_cursor(0, 0)
            lcd.prints("Press Start")
        time.sleep(0.25)
        blink = not blink
        if button_pushed(with_delay=True):
            initialize_graphics()
            hero_pos = HERO_POSITION_RUN_LOWER_1
            playing = True
            distance = 0
        return None

    advance_terrain(
        terrain_lower, SPRITE_TERRAIN_SOLID
        if new_terrain_type == TERRAIN_LOWER_BLOCK else SPRITE_TERRAIN_EMPTY)
    advance_terrain(
        terrain_upper, SPRITE_TERRAIN_SOLID
        if new_terrain_type == TERRAIN_UPPER_BLOCK else SPRITE_TERRAIN_EMPTY)

    new_terrain_duration -= 1
    if new_terrain_duration == 0:
        if new_terrain_type == TERRAIN_EMPTY:
            new_terrain_type = TERRAIN_UPPER_BLOCK if randint(
                0, 3) == 0 else TERRAIN_LOWER_BLOCK
            new_terrain_duration = 2 + randint(0, 10)
        else:
            new_terrain_type = TERRAIN_EMPTY
            new_terrain_duration = 10 + randint(0, 10)

    if button_pushed():
        if (hero_pos <= HERO_POSITION_RUN_LOWER_2):
            hero_pos = HERO_POSITION_JUMP_1

    if draw_hero(hero_pos, terrain_upper, terrain_lower, distance >> 3):
        playing = False
    else:
        if hero_pos == HERO_POSITION_RUN_LOWER_2 or hero_pos == HERO_POSITION_JUMP_8:
            hero_pos = HERO_POSITION_RUN_LOWER_1
        elif (hero_pos >= HERO_POSITION_JUMP_3 and hero_pos <= HERO_POSITION_JUMP_5) and \
                terrain_lower[HERO_HORIZONTAL_POSITION] != SPRITE_TERRAIN_EMPTY:
            hero_pos = HERO_POSITION_RUN_UPPER_1
        elif (hero_pos >= HERO_POSITION_RUN_UPPER_1 and
              terrain_lower[HERO_HORIZONTAL_POSITION] == SPRITE_TERRAIN_EMPTY):
            hero_pos = HERO_POSITION_JUMP_5
        elif hero_pos == HERO_POSITION_RUN_UPPER_2:
            hero_pos = HERO_POSITION_RUN_UPPER_1
        else:
            hero_pos += 1
        distance += 1

        gpio.output(
            PIN_AUTOPLAY, not terrain_lower[HERO_HORIZONTAL_POSITION + 2]
            == SPRITE_TERRAIN_EMPTY)
    time.sleep(0.1)
示例#6
0
def play_audio(file=DETECT_DING, offset=0, overRideVolume=0):
    global currVolume
    if (file.find('radiotime.com') != -1):
        file = tuneinplaylist(file)
    global nav_token, p, audioplaying
    if debug:
        print("{}Play_Audio Request for:{} {}".format(bcolors.OKBLUE,
                                                      bcolors.ENDC, file))
    GPIO.output(plb_light, GPIO.HIGH)
    #i = vlc.Instance('--aout=alsa')  # , '--alsa-audio-device=mono', '--file-logging', '--logfile=vlc-log.txt')
    i = vlc.Instance('--aout=alsa', '--alsa-audio-device=hw:0,0')
    m = i.media_new(file)
    p = i.media_player_new()
    p.set_media(m)
    mm = m.event_manager()
    mm.event_attach(vlc.EventType.MediaStateChanged, state_callback, p)
    audioplaying = True

    if (overRideVolume == 0):
        p.audio_set_volume(currVolume)
    else:
        p.audio_set_volume(overRideVolume)

    p.play()
    while audioplaying:
        continue
    GPIO.output(plb_light, GPIO.LOW)
示例#7
0
 def on_message_start(self, client, userdata, msg):
     payload_string = msg.payload.decode('utf-8')
     print("Topic1111111: {}. Payload: {}".format(msg.topic,
                                                  payload_string))
     #     wiringpi.digitalWrite(PORT,not data['status'])
     status = gpio.input(port.PA13)
     gpio.output(port.PA10, not status)
示例#8
0
    def __init__(self, cs_pin, clock_pin, data_pin, units="c"):
        '''Initialize Soft (Bitbang) SPI bus

        Parameters:
        - cs_pin:    Chip Select (CS) / Slave Select (SS) pin (Any GPIO)  
        - clock_pin: Clock (SCLK / SCK) pin (Any GPIO)
        - data_pin:  Data input (SO / MOSI) pin (Any GPIO)
        - units:     (optional) unit of measurement to return. ("c" (default) | "k" | "f")

        '''
        self.cs_pin = port.PA9  #cs_pin
        self.clock_pin = port.PA8  #clock_pin
        self.data_pin = port.PA21  #data_pin
        self.units = units
        self.data = None

        # Initialize needed GPIO
        #GPIO.setmode(self.board)
        gpio.init()
        #GPIO.setup(self.cs_pin, GPIO.OUT)
        gpio.setcfg(self.cs_pin, gpio.OUTPUT)

        #GPIO.setup(self.clock_pin, GPIO.OUT)
        gpio.setcfg(self.clock_pin, gpio.OUTPUT)

        #GPIO.setup(self.data_pin, GPIO.IN)
        gpio.setcfg(self.data_pin, gpio.INPUT)

        # Pull chip select high to make chip inactive
        gpio.output(self.cs_pin, gpio.HIGH)
示例#9
0
def lcd_toggle_enable():
    # toggle enable
    sleep(E_DELAY)
    gpio.output(LCD_E, True)
    sleep(E_PULSE)
    gpio.output(LCD_E, False)
    sleep(E_DELAY)
示例#10
0
def start():
    global audioplaying, p
    while True:
        print("{}Ready to Record.{}".format(bcolors.OKBLUE, bcolors.ENDC))
        #		GPIO.wait_for_edge(button, GPIO.FALLING) # we wait for the button to be pressed
        if audioplaying: p.stop()
        print("{}Recording...{}".format(bcolors.OKBLUE, bcolors.ENDC))
        #		GPIO.output(rec_light, GPIO.HIGH)
        #		gpio.output(rec_light, gpio.HIGH)
        inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NORMAL,
                            device)
        inp.setchannels(1)
        inp.setrate(16000)
        inp.setformat(alsaaudio.PCM_FORMAT_S16_LE)
        inp.setperiodsize(500)
        audio = ""
        #		while(GPIO.input(button)==0): # we keep recording while the button is pressed
        while (gpio.input(button) == 0
               ):  # we keep recording while the button is pressed
            gpio.output(rec_light, gpio.HIGH)
            l, data = inp.read()
            if l:
                audio += data
        print("{}Recording Finished.{}".format(bcolors.OKBLUE, bcolors.ENDC))
        rf = open(path + 'recording.wav', 'w')
        rf.write(audio)
        rf.close()
        inp = None
        alexa_speech_recognizer()
示例#11
0
def on_mqtt_message(mosq, obj, msg):
    """
    Handle incoming messages
    """

    if msg.topic == MONITOR_REFRESH:
        logging.debug("Refreshing the state of all monitored pins...")
        refresh()
        return

    logging.debug("Received message %s, %s" % (msg.topic, msg.payload))

    topicparts = msg.topic.split("/")
    pin = int(topicparts[len(topicparts) - 1])
    value = int(msg.payload)

    try:
        changedPort = PINS[pin]
        logging.debug("Incoming message for pin %d -> %d" % (pin, value))
        print("Incoming message for pin %d -> %d" % (pin, value))
        print("change port is %s" % (changedPort))
        if value == 1:
            gpio.setcfg(changedPort, gpio.OUTPUT)
            gpio.output(changedPort, gpio.HIGH)
        else:
            gpio.setcfg(changedPort, gpio.OUTPUT)
            gpio.output(changedPort, gpio.LOW)
    except Exception as e:
        logging.error("Error %s" % (str(e)))
 def fancontrol(self, state):
     if self.pin1 != 0:
         if (self.fanworking != state):
             self.fanworking = state
             if (state == 1):
                 self.fanstart = time.time()
             gpio.output(self.pin1, state)
示例#13
0
def start():
	global audioplaying, p
	while True:
		print("{}Ready to Record.{}".format(bcolors.OKBLUE, bcolors.ENDC))
#		GPIO.wait_for_edge(button, GPIO.FALLING) # we wait for the button to be pressed
		if audioplaying: p.stop()
		print("{}Recording...{}".format(bcolors.OKBLUE, bcolors.ENDC))
#		GPIO.output(rec_light, GPIO.HIGH)
#		gpio.output(rec_light, gpio.HIGH)
		inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NORMAL, device)
		inp.setchannels(1)
		inp.setrate(16000)
		inp.setformat(alsaaudio.PCM_FORMAT_S16_LE)
		inp.setperiodsize(500)
		audio = ""
#		while(GPIO.input(button)==0): # we keep recording while the button is pressed
		while(gpio.input(button)==0): # we keep recording while the button is pressed
			gpio.output(rec_light, gpio.HIGH)
			l, data = inp.read()
			if l:
				audio += data
		print("{}Recording Finished.{}".format(bcolors.OKBLUE, bcolors.ENDC))
		rf = open(path+'recording.wav', 'w')
		rf.write(audio)
		rf.close()
		inp = None
		alexa_speech_recognizer()
示例#14
0
def RUN_INIT():
    print "--> RUN_INIT : "
    gpio.init()
    gpio.setcfg(port.PA6, gpio.OUTPUT)
    gpio.pullup(port.PA6, gpio.PULLDOWN)
    gpio.output(port.PA6, gpio.HIGH)
    time.sleep(0.1)
示例#15
0
 def message(self, msg):
     print("msg:%s\n" % msg)
     if str(msg['from']).split('/')[0] in ('*****@*****.**',
                                           '*****@*****.**',
                                           '*****@*****.**',
                                           '*****@*****.**',
                                           '*****@*****.**'):
         #if msg['type'] in ('chat', 'normal'):
         txt = "%(body)s" % (msg)
         retxt = txt
         if (txt == "拍照"):
             retxt = "正在拍照"
             timestamp = int(time())
             pic_file_name = "/home/pi/pics/%s.jpg" % (timestamp)
             system("fswebcam %s" % (pic_file_name))
             #base64_content=base64.b64encode(open(pic_file_name).read())
             img_url = popen(
                 "curl -F 'file=@%s;filename=%s.jpg;type=image/jpeg' http://47.52.16.64:3000/upload"
                 % (pic_file_name, timestamp)).read()
             #img_url="data:image/x-icon;base64,%s" % (base64_content)
             #retxt="<image xmlns='http://mangga.me/protocol/image' type='image/jpeg'>%s</image>" % (base64_content)
             retxt = "http://47.52.16.64:3000%s" % (img_url)
         if (txt == "关机"):
             retxt = "正在关机"
         if (txt == "开灯"):
             gpio.output(port.PA7, gpio.HIGH)
             retxt = "已开启"
         if (txt == "关灯"):
             gpio.output(port.PA7, gpio.LOW)
             retxt = "已关闭"
         if (txt[0:1] == "#"):
             #cmd=txt[1:len(txt)]
             cmd = txt.split("#")[1]
             retxt = popen(cmd).read()
         msg.reply("\n%s" % retxt).send()
示例#16
0
 def indicate_setup_failure(self):
     while True:
         for x in range(0, 5):
             time.sleep(.1)
             GPIO.output(self.__pconfig['rec_light'], GPIO.HIGH)
             time.sleep(.1)
             GPIO.output(self.__pconfig['rec_light'], GPIO.LOW)
示例#17
0
def main():
    myLogger.info("System Fan - Loop routine started.")
    gpio.output(outputPort, gpio.LOW)

    while True:
        fan_state(get_temp())
        sleep(2)
示例#18
0
文件: pin.py 项目: aaaler/k9
 def __init__ (self, pin_id, direction = 1, value = 0):
     self._pinid = pin_id
     self._direction = direction
     self._value = value
     gpio.init()
     gpio.setcfg (pin_id, direction)
     gpio.output (pin_id, value)
示例#19
0
def listen_card():
    while True:
        '''cardnumber = 0
        bit_count = 0
        for x in range(0, 26):
            data0 = gpio.input(D0)
            data1 = gpio.input(D1)
            while (data0 == 1 and data1 == 1):
                if bit_count == 0:
                    time.sleep(0.00005)
                data0 = gpio.input(D0)
                data1 = gpio.input(D1)

            cardnumber = cardnumber << 1
            if data1 == 1:
                cardnumber = cardnumber | 0x01
            bit_count += 1

            while (data0 == 0 or data1 == 0):
                data0 = gpio.input(D0)
                data1 = gpio.input(D1)
        cardnumber = cardnumber >> 1
        cardnumber = cardnumber & 0x00ffffff
        print cardnumber'''
        gpio.output(COM, 0)
        time.sleep(2)
        gpio.output(COM, 1)
示例#20
0
文件: pin.py 项目: aaaler/k9
 def value (self, value):
     if self._direction == 1: #output
         self._value = value
         gpio.output (self._pinid, value)
         return True
     else:
         return False
def switch_relay(rel):
    if rel.state:
        rel.state = False
        gpio.output(rel.port, gpio.HIGH)
    else:
        rel.state = True
        gpio.output(rel.port, gpio.LOW)
示例#22
0
def main(argv):

    initial_button_state = 0

    gpio.init()
    gpio.setcfg(POWER_BUTTON, gpio.INPUT)
    gpio.pullup(POWER_BUTTON, gpio.PULLUP)
    gpio.setcfg(LED, gpio.OUTPUT)

    while True:
        # Returns a 1 if open and a 0 if pressed/closed
        current_button_state = gpio.input(POWER_BUTTON)

        #print(initial_button_state, current_button_state)
        #sys.stdout.flush()

        # Check if button state has changed
        if current_button_state != initial_button_state:
            #print('Button pressed')
            gpio.output(LED, 1)
            subprocess.call(CMD,
                            shell=True,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE)

        time.sleep(0.1)
示例#23
0
def shutdowner():
  rospy.init_node('shutdown_node')
  rate = rospy.Rate(10) # 10hz

  if not os.getegid() == 0:
    sys.exit('Script must be run as root')

  delay=5

  portToListen = port.PE5
  portToWrite = port.PE4

  gpio.init()
  gpio.setcfg(portToListen, gpio.INPUT)
  gpio.setcfg(portToWrite, gpio.OUTPUT)

  while not rospy.is_shutdown():
    try:
      print ("Press CTRL+C to exit")
      while True:
        v=gpio.input(portToListen)
        if(v==1):
            sleep(2)
            v=gpio.input(portToListen)
            if(v==1):
              print("shutdown of the Olimex")
              gpio.output(portToWrite, 1)
              os.system("sudo halt -p")
              break
        sleep(delay)
    except KeyboardInterrupt:
      print ("Goodbye.")
示例#24
0
def alexa_speech_recognizer():
    # https://developer.amazon.com/public/solutions/alexa/alexa-voice-service/rest/speechrecognizer-requests
    if debug:
        print("{}Sending Speech Request...{}".format(bcolors.OKBLUE,
                                                     bcolors.ENDC))
    #	GPIO.output(plb_light, GPIO.HIGH)
    gpio.output(plb_light, gpio.HIGH)
    url = 'https://access-alexa-na.amazon.com/v1/avs/speechrecognizer/recognize'
    headers = {'Authorization': 'Bearer %s' % gettoken()}
    d = {
        "messageHeader": {
            "deviceContext": [{
                "name": "playbackState",
                "namespace": "AudioPlayer",
                "payload": {
                    "streamId": "",
                    "offsetInMilliseconds": "0",
                    "playerActivity": "IDLE"
                }
            }]
        },
        "messageBody": {
            "profile": "alexa-close-talk",
            "locale": "en-us",
            "format": "audio/L16; rate=16000; channels=1"
        }
    }
    with open(path + 'recording.wav') as inf:
        files = [('file', ('request', json.dumps(d),
                           'application/json; charset=UTF-8')),
                 ('file', ('audio', inf, 'audio/L16; rate=16000; channels=1'))]
        r = requests.post(url, headers=headers, files=files)
    process_response(r)
示例#25
0
 def __init__(self, dev='/dev/spidev1.0', spd=1000000):
     spi.openSPI(device=dev, speed=spd)
     #    GPIO.setmode(GPIO.BOARD)
     GPIO.setcfg(22, GPIO.OUTPUT)
     GPIO.output(self.NRSTPD, 1)
     self.Write_MFRC522(self.RFCfgReg, (0x07 << 4))
     self.MFRC522_Init()
示例#26
0
def change_led_state():
    try:
        global led_state
        led_state = not led_state
        gpio.output(led, led_state)
    except Exception:
        save_err('led')
示例#27
0
def blink2():
    gpio.init()
    blink = port.PA10
    gpio.setcfg(blink, gpio.OUTPUT)
    gpio.output(blink, gpio.HIGH)
    sleep(1)
    gpio.output(blink, gpio.LOW)
示例#28
0
def speakerOff():
    global bSpeakerOn
    bSpeakerOn = False
    DisplayClear()
    #GPIO.output(ledPin, GPIO.LOW)
    gpio.output(relayPin, gpio.HIGH)
    print "speaker off"
示例#29
0
def run():

    ErrorMessage = "ERROR : arguments is not true! "
    gpio.init()
    try:
        #print ("Press CTRL+C to exit")
        if len(sys.argv) != 3:
            print(ErrorMessage)
            return ErrorMessage
        else:
            pin = pinName(sys.argv[1])
            if int(sys.argv[2]) == 2:
                gpio.setcfg(pin, GPIO.INPUT)
                status = gpio.input(pin)
                print("status => ", status)
                return status
            elif int(sys.argv[2]) == 1 or int(sys.argv[2]) == 0:
                gpio.setcfg(pin, gpio.OUTPUT)
                gpio.output(pin, int(sys.argv[2]))
                print("output => OK")
                return "OK"
            else:
                return ErrorMessage

    except KeyboardInterrupt:
        #print ("Goodbye.")
        return ErrorMessage
示例#30
0
def shutdowner():
    rospy.init_node('shutdown_node')
    rate = rospy.Rate(10)  # 10hz

    if not os.getegid() == 0:
        sys.exit('Script must be run as root')

    delay = 5

    portToListen = port.PE5
    portToWrite = port.PE4

    gpio.init()
    gpio.setcfg(portToListen, gpio.INPUT)
    gpio.setcfg(portToWrite, gpio.OUTPUT)

    while not rospy.is_shutdown():
        try:
            print("Press CTRL+C to exit")
            while True:
                v = gpio.input(portToListen)
                if (v == 1):
                    sleep(2)
                    v = gpio.input(portToListen)
                    if (v == 1):
                        print("shutdown of the Olimex")
                        gpio.output(portToWrite, 1)
                        os.system("sudo halt -p")
                        break
                sleep(delay)
        except KeyboardInterrupt:
            print("Goodbye.")
示例#31
0
def alexa_speech_recognizer():
	# https://developer.amazon.com/public/solutions/alexa/alexa-voice-service/rest/speechrecognizer-requests
	if debug: print("{}Sending Speech Request...{}".format(bcolors.OKBLUE, bcolors.ENDC))
#	GPIO.output(plb_light, GPIO.HIGH)
	gpio.output(plb_light, gpio.HIGH)
	url = 'https://access-alexa-na.amazon.com/v1/avs/speechrecognizer/recognize'
	headers = {'Authorization' : 'Bearer %s' % gettoken()}
	d = {
		"messageHeader": {
			"deviceContext": [
				{
					"name": "playbackState",
					"namespace": "AudioPlayer",
					"payload": {
					"streamId": "",
						"offsetInMilliseconds": "0",
						"playerActivity": "IDLE"
					}
				}
			]
		},
		"messageBody": {
			"profile": "alexa-close-talk",
			"locale": "en-us",
			"format": "audio/L16; rate=16000; channels=1"
		}
	}
	with open(path+'recording.wav') as inf:
		files = [
				('file', ('request', json.dumps(d), 'application/json; charset=UTF-8')),
				('file', ('audio', inf, 'audio/L16; rate=16000; channels=1'))
				]
		r = requests.post(url, headers=headers, files=files)
	process_response(r)
示例#32
0
def lcd_toggle_enable():
    # Toggle enable
    time.sleep(E_DELAY)
    gpio.output(LCD_E, True)
    time.sleep(E_PULSE)
    gpio.output(LCD_E, False)
    time.sleep(E_DELAY)
示例#33
0
def silence_listener(triggeredbyvoice):
    # Reenable reading microphone raw data
    stream = audio.open(format=FORMAT,
                        channels=CHANNELS,
                        rate=RATE,
                        input=True,
                        frames_per_buffer=CHUNK,
                        input_device_index=0)
    framerec = []

    # Buffer as long as we haven't heard enough silence or the total size is within max size
    # thresholdSilenceMet = False
    # frames = 0
    # numSilenceRuns = 0
    # silenceRun = 0
    start = time.time()
    play_audio(DETECT_DING)
    print("Start recording")
    # #do not count first 10 frames when doing VAD
    # while (frames < throwaway_frames):  # VAD_THROWAWAY_FRAMES):
    #     data = stream.read(CHUNK, exception_on_overflow=False)
    #     frames = frames + 1
    #     framerec.append(data)
    # now do VAD
    if triggeredbyvoice:
        for i in range(0, int(RATE / CHUNK * MAX_RECORDING_LENGTH)):
            #data = stream.read(CHUNK, exception_on_overflow=False)
            try:
                data = stream.read(CHUNK)
            except IOError as ex:
                if ex[1] != pyaudio.paInputOverflowed:
                    raise
                data = ''
            framerec.append(data)
    else:
        while ((time.time() - start) < MAX_RECORDING_LENGTH):
            #data = stream.read(CHUNK, exception_on_overflow=False)
            try:
                data = stream.read(CHUNK)
            except IOError as ex:
                if ex[1] != pyaudio.paInputOverflowed:
                    raise
                data = ''
            framerec.append(data)
            GPIO.output(rec_light, GPIO.HIGH)

    print("End recording")
    play_audio(path + 'resources/r2-ok.mp3')

    if debug: play_audio(path + 'beep.wav', 0, 100)
    stream.close()

    GPIO.output(rec_light, GPIO.LOW)
    waveFile = wave.open(path + WAVE_OUTPUT_FILENAME, 'wb')
    waveFile.setnchannels(CHANNELS)
    waveFile.setsampwidth(audio.get_sample_size(FORMAT))
    waveFile.setframerate(RATE)
    waveFile.writeframes(b''.join(framerec))
    waveFile.close()
示例#34
0
 def cleanup(self, clean_up=False):
     """ cleanup all GPIO connections used in event of error by lib user"""
     if self.verbose:
         print("rpi_dc_lib.py : Cleaning up")
     GPIO.output(self.pin_one, False)
     GPIO.output(self.pin_two, False)
     self.my_pwm.ChangeDutyCycle(0)
     self.my_pwm.stop()
示例#35
0
 def cmd( self, params ):
     if self.type == 'switch':
         if params['cmd'] == 'toggle':
             self.setState( not self.state )
         elif params['cmd'] == 'set':
             self.setState( params['state'] )
     elif self.type == 'pulse':
         if params['cmd'] == 'pulse':
             gpio.output( self.pin, 1 )
             reactor.callLater( self.interval, gpio.output, self.pin, 0 )
示例#36
0
def play_audio(file):
    global nav_token, p, audioplaying, flag #<-added flag here
    if debug: print("{}Play_Audio Request for:{} {}".format(bcolors.OKBLUE, bcolors.ENDC, file))
#    GPIO.output(24, GPIO.HIGH)
    gpio.output(plb_light, gpio.HIGH)
    ext = (file.rpartition(".")[2])[:3]
    #subprocess.Popen(['mpg123', '-q', '{}{}'.format(path, file)]).wait()
    i = vlc.Instance('--aout=alsa', '--alsa-audio-device=hw:CARD=audiocodec,DEV=0')
    mrl = ""
    print(ext)
    if file == "response.mp3" or file == "hello.mp3":
        mrl = "{}{}".format(path, file)
    else:
        mrl = "{}".format(file)

    if mrl != "":
        if ext in playlists:

            #Replaced code here
            p=i.media_player_new() # Create new media player
            event_manager = p.event_manager() # Attach event to player (next 3 lines)
            event=vlc.EventType()
            event_manager.event_attach(event.MediaPlayerEndReached, end_reached)
            m=i.media_new(mrl) # Create new media
            p.set_media(m) # Set URL as the player's media
            m.release()
            p.play() # play it
            while flag == 0: # Wait until the end of the first media has been reached.$
                time.sleep(0.5)
                if debug: print("{}Loading Playlist...{}".format(bcolors.OKBLUE, bcolors.ENDC))
            sub_list = m.subitems() # .. and get the sub itmes in the playlist
            sub_list.lock()
            sub = sub_list.item_at_index(0) # Get the first sub item
            sub_list.unlock()
            sub_list.release()
            p.set_media(sub) # Set it as the new media in the player
            #End of replaced Code
        else:
            m = i.media_new(mrl)
            p = i.media_player_new()
            p.set_media(m)
            mm = m.event_manager()
            #mm.event_attach(vlc.EventType.MediaPlayerTimeChanged, pos_callback)
            #mm.event_attach(vlc.EventType.MediaParsedChanged, meta_callback, m)
            mm.event_attach(vlc.EventType.MediaStateChanged, state_callback, p)
            p.audio_set_volume(100)
            if debug: print("{}Requesting Stream...{}".format(bcolors.OKBLUE, bcolors.ENDC))
        audioplaying = True
        p.play()
        while audioplaying:
            continue
#        GPIO.output(24, GPIO.LOW)
        gpio.output(plb_light, gpio.LOW)
    else:
        print("(play_audio) mrl = Nothing!")
示例#37
0
 def alarm_handler(self, signum, frame):
     if self.s2s>0 and self.steps>0:
         self.value=1-self.value
         if self.value==0:
             self.s2s-=1
             self.steps-=1
         gpio.output(self.steps_pin, self.value)
     else:
         signal.setitimer(signal.ITIMER_REAL, 0)
         self.stop=1
         if self.steps==0:
             self.buzy=0
示例#38
0
    def run(self):
        self.buzy=1
        self.stop=0
        self.s2s=self.steps2sync
        gpio.output(self.dir_pin, self.dir)
	if self.interval==0:
            self.buzy=0
        else:
            signal.setitimer(signal.ITIMER_REAL, self.interval, self.interval)
            while not self.stop:
                signal.pause()
        return self.buzy
示例#39
0
 def __init__( self, id, params ):
     self.id = id
     self.name = params['name']
     self.pin = getPin( params['pin'] )
     self.type = params['type']
     devices['id'] = self
     if self.type == 'switch' or self.type == 'pulse':
         gpio.setcfg( self.pin, gpio.OUTPUT )
         if self.type == 'pulse':
             self.interval = params['interval']
             gpio.output( self.pin, 0)
         elif self.type == 'switch':
             self.state = gpio.input( self.pin ) == 1
示例#40
0
	def goTop(self):
		self.setDirectionUp()
		self.endSleep()
		
		self.doRamp()
		
		for i in range(0, self.height-50):
			gpio.output(self.stepPin, 1)
			time.sleep(0.001)
			gpio.output(self.stepPin, 0)
			time.sleep(0.001)
		
		self.startSleep()	
示例#41
0
	def doStep(self, steps=200):
		self.endSleep()
		if steps > 50:
			self.doRamp(steps=50)
			for i in range(0, steps-50):
				gpio.output(self.stepPin, 1)
				time.sleep(0.001) 
				gpio.output(self.stepPin, 0)
				time.sleep(0.001) 
		else:
			self.doRamp(steps=steps)
	
		self.startSleep()
示例#42
0
 def getKey(self):
     key_found = None
     for column in self.columns:
         gpio.output(column, gpio.HIGH)
         for row in self.rows:
             tmp = gpio.input(row)
             if tmp:
                 for key in self.mapping.keys():
                     if self.mapping[key][0] == column and self.mapping[key][1] == row:
                         key_found = key
                         break
         gpio.output(column, gpio.LOW)
         if key_found:
             break
     return key_found
示例#43
0
def alexa_getnextitem(nav_token):
	# https://developer.amazon.com/public/solutions/alexa/alexa-voice-service/rest/audioplayer-getnextitem-request
	time.sleep(0.5)
        if audioplaying == False:
		if debug: print("{}Sending GetNextItem Request...{}".format(bcolors.OKBLUE, bcolors.ENDC))
#		GPIO.output(plb_light, GPIO.HIGH)
#		gpio.output(plb_light, gpio.HIGH)
		gpio.output(rec_light, gpio.HIGH)
		url = 'https://access-alexa-na.amazon.com/v1/avs/audioplayer/getNextItem'
		headers = {'Authorization' : 'Bearer %s' % gettoken(), 'content-type' : 'application/json; charset=UTF-8'}
		d = {
			"messageHeader": {},
			"messageBody": {
				"navigationToken": nav_token
			}
		}
		r = requests.post(url, headers=headers, data=json.dumps(d))
		process_response(r)
示例#44
0
	def goBottom(self):
		self.setDirectionDown()
		self.endSleep()
		self.doRamp()
		
		debounce = 0
		for i in range(0, self.height-50):
			if gpio.input(self.sensorPin) == 0: debounce += 1
			else: debounce = 0
			
			if debounce > 5:
				self.goUp(steps=50) #Move the sledge out of the sensor
				self.startSleep()
				break
			
			gpio.output(self.stepPin, 1)
			time.sleep(0.001)
			gpio.output(self.stepPin, 0)
			time.sleep(0.001)
		
		self.startSleep()
示例#45
0
    def __init__(self, params):
        self.value=0
        self.steps_pin = params['steps_pin'] if 'steps_pin' in params else 1
        self.dir_pin = params['dir_pin'] if 'dir_pin' in params else 2
        self.steps = params['steps'] if 'steps' in params else 0
        self.dir = params['dir'] if 'dir' in params else 0
        self.interval = params['interval'] if 'interval' in params else 0.25
        self.steps2sync = params['steps2sync'] if 'steps2sync' in params else 100
        self.stop=1
        if self.steps:
            self.buzy=1
        else:
            self.buzy=0

        signal.signal(signal.SIGALRM, self.alarm_handler)

        gpio.init()
        gpio.setcfg(self.steps_pin, gpio.OUTPUT)
        gpio.setcfg(self.dir_pin, gpio.OUTPUT)
        gpio.output(self.steps_pin, 0)
        gpio.output(self.dir_pin, 0)
def soft_pwm(conn):
    freq = 222 # Hz, mimic Panasonic output
    duty = 0.5 # Start by doing everything

    pwm_port = port.PI19
    gpio.setcfg(pwm_port, gpio.OUTPUT)

    period = 1.0/freq

    period_high = period*duty
    period_low = period*(1-duty)

    while True:
        if conn.poll():
            duty = conn.recv()
            period_high = period*duty
            period_low = period*(1-duty)

        if duty:
            gpio.output(pwm_port, gpio.LOW)
            sleep(period_low)
            gpio.output(pwm_port, gpio.HIGH)
            sleep(period_high)
        else:
            # No pulsing, wait a while and recheck
            gpio.output(pwm_port, gpio.LOW)
            sleep(period)
示例#47
0
def start_old():
	global audioplaying, p
	inp = None
#	last = GPIO.input(button)
	last = gpio.input(button)
	print("{}Ready to Record.{}".format(bcolors.OKBLUE, bcolors.ENDC))
	while True:
#		val = GPIO.input(button)
		val = gpio.input(button)
		if val != last:
			last = val
			if val == 1 and recorded == True:
				print("{}Recording Finished.{}".format(bcolors.OKBLUE, bcolors.ENDC))
				rf = open(path+'recording.wav', 'w')
				rf.write(audio)
				rf.close()
				inp = None
				alexa_speech_recognizer()
			elif val == 0:
#				GPIO.output(rec_light, GPIO.HIGH)
				gpio.output(rec_light, gpio.HIGH)
				print("{}Recording...{}".format(bcolors.OKBLUE, bcolors.ENDC))
				inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NORMAL, device)
				inp.setchannels(1)
				inp.setrate(16000)
				inp.setformat(alsaaudio.PCM_FORMAT_S16_LE)
				inp.setperiodsize(500)
				audio = ""
				if audioplaying:
					p.stop()
				l, data = inp.read()
				if l:
					audio += data
				recorded = True
		elif val == 0:
			l, data = inp.read()
			if l:
				audio += data
示例#48
0
	def __init__(self):
		self.pos = 0
		self.testmode = False
		try:
			from pyA20.gpio import gpio
			from pyA20.gpio import port
			from pyA20.gpio import connector
			global pins

			gpio.init() #Initialize module. Always called first
			pins = [ port.PA8, port.PA9, port.PA10, port.PA20 ]

		
			for p in pins:
				gpio.setcfg(p, gpio.OUTPUT)  #Configure LED1 as output
				gpio.output(p, 1)
				time.sleep(0.01)
				gpio.output(p, 0)
		
			gpio.output(pins[0], 1)
			self.gpio = gpio
		except:
			print "Focuser test mode"
			self.testmode = True
示例#49
0
__credits__ = ["Stefan Mavrodiev"]
__license__ = "GPL"
__version__ = "2.0"
__maintainer__ = __author__
__email__ = "*****@*****.**"

led = connector.gpio0p0     # This is the same as port.PH2
button = connector.gpio3p40

"""Init gpio module"""
gpio.init()

"""Set directions"""
gpio.setcfg(led, gpio.OUTPUT)
gpio.setcfg(button, gpio.INPUT)

"""Enable pullup resistor"""
gpio.pullup(button, gpio.PULLUP)
#gpio.pullup(button, gpio.PULLDOWN)     # Optionally you can use pull-down resistor

try:
    print ("Press CTRL+C to exit")
    while True:
        state = gpio.input(button)      # Read button state

        """Since we use pull-up the logic will be inverted"""
        gpio.output(led, not state)

except KeyboardInterrupt:
    print ("Goodbye.")
示例#50
0
#!/usr/bin/env python

from pyA20.gpio import gpio
from pyA20.gpio import port
from pyA20.gpio import connector
from time import sleep


gpio.init()
gpio.setcfg(port.PI0,gpio.OUTPUT)
#gpio.pullup(port.PI0,gpio.PULLUP)

gpio.output(port.PI0,gpio.HIGH)
sleep(0.1)
gpio.output(port.PI0,gpio.LOW)
gpio.output(port.PI0,gpio.HIGH)



示例#51
0
	def setDirectionDown(self): gpio.output(self.dirPin, 1)
	
		
	def __init__(self):
 def _state_stopped(self):
     gpio.output(self._relay_port, gpio.LOW)
     #pwm_conn.send(0)
     # TODO: Keep the light on for a few seconds
     gpio.output(self._extra_port, gpio.LOW)
示例#53
0
__author__ = "Stefan Mavrodiev"
__copyright__ = "Copyright 2014, Olimex LTD"
__credits__ = ["Stefan Mavrodiev"]
__license__ = "GPL"
__version__ = "2.0"
__maintainer__ = __author__
__email__ = "*****@*****.**"


led = port.PH2

gpio.init()
gpio.setcfg(led, gpio.OUTPUT)

try:
    print ("Press CTRL+C to exit")
    while True:
        gpio.output(led, 1)
        sleep(0.1)
        gpio.output(led, 0)
        sleep(0.1)

        gpio.output(led, 1)
        sleep(0.1)
        gpio.output(led, 0)
        sleep(0.1)

        sleep(0.6)
except KeyboardInterrupt:
    print ("Goodbye.")
 def _start(self):
     gpio.output(self._extra_port, gpio.HIGH)
     # Power is set elsewhere, that triggers the PWM
     gpio.output(self._relay_port, gpio.HIGH)
示例#55
0
		rf.close()
		inp = None
		alexa_speech_recognizer()

if __name__ == "__main__":
#	GPIO.setwarnings(False)
#	GPIO.cleanup()
#	GPIO.setmode(GPIO.BCM)
	gpio.init()
#	GPIO.setup(button, GPIO.IN, pull_up_down=GPIO.PUD_UP)
        gpio.setcfg(button, gpio.INPUT)
        gpio.pullup(button, gpio.PULLUP)
#	GPIO.setup(lights, GPIO.OUT)
        gpio.setcfg(lights[0], gpio.OUTPUT)
        gpio.setcfg(lights[1], gpio.OUTPUT)
#	GPIO.output(lights, GPIO.LOW)
        gpio.output(lights[0], gpio.LOW)
        gpio.output(lights[1], gpio.LOW)
	while internet_on() == False:
		print(".")
	token = gettoken()
	play_audio("hello.mp3")
	for x in range(0, 3):
		time.sleep(.1)
#		GPIO.output(plb_light, GPIO.HIGH)
		gpio.output(plb_light, gpio.HIGH)
		time.sleep(.1)
#		GPIO.output(plb_light, GPIO.LOW)
		gpio.output(plb_light, gpio.LOW)
	start()
示例#56
0
def process_response(r):
	global nav_token, streamurl, streamid
	if debug: print("{}Processing Request Response...{}".format(bcolors.OKBLUE, bcolors.ENDC))
	nav_token = ""
	streamurl = ""
	streamid = ""
	if r.status_code == 200:
		for v in r.headers['content-type'].split(";"):
			if re.match('.*boundary.*', v):
				boundary = v.split("=")[1]
		data = r.content.split(boundary)
		n = re.search('(?=audio\/mpeg)(.*?)(?=\r\n)', r.content)
		r.connection.close()
		audio = ""
		for d in data:
			m = re.search('(?<=Content\-Type: )(.*?)(?=\r\n)', d)
			if m:
				c_type = m.group(0)
				if c_type == 'application/json':
					json_r = d.split('\r\n\r\n')[1].rstrip('\r\n--')
					if debug: print("{}JSON String Returned:{} {}".format(bcolors.OKBLUE, bcolors.ENDC, json_r))
					nav_token = json_string_value(json_r, "navigationToken")
					streamurl = json_string_value(json_r, "streamUrl")
					if json_r.find('"progressReportRequired":false') == -1:
						streamid = json_string_value(json_r, "streamId")
					if streamurl.find("cid:") == 0:					
						streamurl = ""
					playBehavior = json_string_value(json_r, "playBehavior")
					if n == None and streamurl != "" and streamid.find("cid:") == -1:
						pThread = threading.Thread(target=play_audio, args=(streamurl,))
						streamurl = ""
						pThread.start()
						return
				elif c_type == 'audio/mpeg':
					audio = d.split('\r\n\r\n')[1].rstrip('--')
					if audio != "":
						with open(path + "response.mp3", 'wb') as f:
							f.write(audio)
#						GPIO.output(rec_light, GPIO.LOW)
						gpio.output(rec_light, gpio.LOW)
						play_audio("response.mp3")
	elif r.status_code == 204:
		if debug: print("{}Request Response is null {}(This is OKAY!){}".format(bcolors.OKBLUE, bcolors.OKGREEN, bcolors.ENDC))
		gpio.output(lights[0], gpio.LOW)
		gpio.output(lights[1], gpio.LOW)
	else:
		print("{}(process_response Error){} Status Code: {}".format(bcolors.WARNING, bcolors.ENDC, r.status_code))
		r.connection.close()
#		GPIO.output(lights, GPIO.LOW)
		gpio.output(lights[0], gpio.LOW)
		gpio.output(lights[1], gpio.LOW)
		for x in range(0, 3):
			time.sleep(.2)
#			GPIO.output(rec_light, GPIO.HIGH)
			gpio.output(rec_light, gpio.HIGH)
			time.sleep(.2)
#			GPIO.output(lights, GPIO.LOW)
			gpio.output(lights[0], gpio.LOW)
			gpio.output(lights[1], gpio.LOW)
示例#57
0
#!/usr/bin/python
from pyA20.gpio import gpio as GPIO
from pyA20.gpio import port
import sys

# Check if there are 2 parameters
if len(sys.argv) == 3:

    # Arguments
    ledPin = int(sys.argv[1])
    state = int(sys.argv[2])

    # Setup GPIO
    GPIO.init()

    # Setup led
    if state == 1:
        # Setup LED as OUTPUT
        GPIO.setcfg(ledPin, GPIO.OUTPUT)
        # Turn on LED (we keep the state)
        GPIO.output(ledPin, True)
    if state == 0:
        # Setup LED as OUTPUT
        # Clean state (this will turn off the led)
        GPIO.setcfg(ledPin, GPIO.OUTPUT)
        GPIO.output(ledPin, False)

else:
    print "usage:onoff_orange.py pin state"
示例#58
0
def readadc(adcnum, CLK, MOSI, MISO, CS):
        if ((adcnum > 7) or (adcnum < 0)):
                return -1
        gpio.output(CS, 1)
 
        gpio.output(CLK, 0)  # start clock low
        gpio.output(CS, 0)     # bring CS low
 
        commandout = adcnum
        commandout |= 0x18  # start bit + single-ended bit
        commandout <<= 3    # we only need to send 5 bits here
        for i in range(5):
                if (commandout & 0x80):
                        gpio.output(MOSI, 1)
                else:
                        gpio.output(MOSI, 0)
                commandout <<= 1
                gpio.output(CLK, 1)
                gpio.output(CLK, 0)
 
        adcout = 0

        for i in range(14):
                gpio.output(CLK, 1)
                gpio.output(CLK, 0)
                adcout <<= 1
                if (gpio.input(MISO)):
                        adcout |= 0x1
 
        gpio.output(CS, 1)
        
        adcout >>= 1       # first bit is 'null' so drop it
        return adcout