def get_question(ar, wd): while True: if not ar.read_button(): time.sleep(0.1) continue logging.info('button pushed') words = wd.detect() print(words) if len(words) < 2: logging.info('question not found') play_statement(random.choice(no_question)) ar.flush_serial() continue if words in all_questions[-5:]: logging.info('question ask in the last 5 times') play_statement(random.choice(asked_recently)) ar.flush_serial() continue if 4 <= datetime.datetime.now().hour <= 7: logging.info('push in the night') tts.say('I will answer you, but you should go to sleep afterward') all_questions.append(words) logging.info('question %s' % words) logging.info( "number of questions from the begining of the world is %d" % len(all_questions)) return words
def math(self): if self.DEBUG: print 'EQUATION:', self.cmd #Check for valid command again if len(self.cmd) == 3 or len(self.cmd) == 4: pass else: for i in range(0, 2): self.cmd.append(None) say('Invalid Command') #Solve problem self.answer = None try: if self.cmd[1] == 'plus': self.answer = int(self.cmd[0]) + int(self.cmd[2]) elif self.cmd[1] == 'minus': self.answer = int(self.cmd[0]) - int(self.cmd[2]) elif self.cmd[1] == 'times': self.answer = int(self.cmd[0]) * int(self.cmd[2]) elif self.cmd[1] == 'divided': self.answer = int(self.cmd[0]) / int(self.cmd[3]) except: if self.DEBUG: print 'Not, math, looking elsewhere...' if self.DEBUG: print 'ANSWER = ', str(self.answer)
def mic2(): while True: with sr.Microphone() as source: r.adjust_for_ambient_noise(source) try: GPIO.output(27, GPIO.HIGH) audio = r.listen(source, timeout=2) GPIO.output(27, GPIO.LOW) except sr.WaitTimeoutError: continue except KeyboardInterrupt: GPIO.output(27, GPIO.LOW) try: a = str(r.recognize_google(audio)) a = a.lower() if (a.find('no') > -1): mic() else: GPIO.output(17, GPIO.HIGH) command(a) GPIO.output(17, GPIO.LOW) say("Is there anything else I can do for you?") except sr.UnknownValueError: say("I do not understand what you said.") continue except sr.RequestError as e: continue
def getConfig(path): try: global ID, TITLE, NAME, LINKEDROOM, PROVIDERTTS, APIKEYTTS, PROVIDERSTT, APIKEYSTT, SENSITIVITY1, ALARMKWACTIVATED, ALARMTTS, ALARMSTT, IP, IP_SERVER, FIRSTBOOT config.read(path) #ID = config.get("Settings", "ID") #номер терминала TITLE = config.get("Settings", "TITLE") #навазние терминала NAME = config.get("Settings", "NAME") #Системное имя LINKEDROOM = config.get("Settings", "LINKEDROOM") #Расположение IP = config.get("Settings", "IP") PROVIDERTTS = config.get("Settings", "PROVIDERTTS") # Сервис синтеза речи APIKEYTTS = config.get("Settings", "APIKEYTTS") #Ключ API сервиса синтеза речи: PROVIDERSTT = config.get("Settings", "PROVIDERSTT") #Сервис распознования речи APIKEYSTT = config.get( "Settings", "APIKEYSTT") #Ключ API сервиса распознования речи: SENSITIVITY1 = config.get( "Settings", "SENSITIVITY") #Чувствительность реагирования на ключевое слово ALARMKWACTIVATED = config.get( "Settings", "ALARMKWACTIVATED") #Сигнал о распозновании ключевого слова ALARMTTS = config.get("Settings", "ALARMTTS") #Сигнал перед сообщением ALARMSTT = config.get( "Settings", "ALARMSTT") #Сигнал перед начале распознования речи IP_SERVER = config.get("Settings", "IP_SERVER") #Сервер МДМ FIRSTBOOT = config.get("Boot", "firstboot") print("Конфигурация загружена") except: say("Не создан файл конфигурации или ошибка в файле, загрузите данные через модуль в МДМ" )
def getConfig(path): try: global PROVIDERTTS, APIKEYTTS, PROVIDERSTT, APIKEYSTT, ALARMKWACTIVATED, ALARMTTS, ALARMSTT, IP_SERVER, FIRSTBOOT config = configparser.ConfigParser() config.read(path) PROVIDERTTS = config.get("Settings", "PROVIDERTTS") # Сервис синтеза речи APIKEYTTS = config.get("Settings", "APIKEYTTS") #Ключ API сервиса синтеза речи: PROVIDERSTT = config.get("Settings", "PROVIDERSTT") #Сервис распознования речи APIKEYSTT = config.get( "Settings", "APIKEYSTT") #Ключ API сервиса распознования речи: #SENSITIVITY = config.get("Settings", "SENSITIVITY") #Чувствительность реагирования на ключевое слово ALARMKWACTIVATED = config.get( "Settings", "ALARMKWACTIVATED") #Сигнал о распозновании ключевого слова ALARMTTS = config.get("Settings", "ALARMTTS") #Сигнал перед сообщением ALARMSTT = config.get( "Settings", "ALARMSTT") #Сигнал перед начале распознования речи IP_SERVER = config.get("Settings", "IP_SERVER") #Сервер МДМ FIRSTBOOT = config.get("Boot", "firstboot") print("Конфигурация загружена") except: say("Не создан файл конфигурации или ошибка в файле, загрузите данные через модуль в МДМ" ) sys.exit(0)
def math(self): if self.DEBUG: print('EQUATION:', self.cmd) #Check for valid command again if len(self.cmd) == 3 or len(self.cmd) == 4: pass else: for i in range(0, 2): self.cmd.append(None) say('Invalid Command') #Solve problem self.answer = None try: if self.cmd[1] == 'plus': self.answer = int(self.cmd[0]) + int(self.cmd[2]) elif self.cmd[1] == 'minus': self.answer = int(self.cmd[0]) - int(self.cmd[2]) elif self.cmd[1] == 'times': self.answer = int(self.cmd[0]) * int(self.cmd[2]) elif self.cmd[1] == 'divided': self.answer = int(self.cmd[0]) / int(self.cmd[3]) except: if self.DEBUG: print('Not, math, looking elsewhere...') if self.DEBUG: print('ANSWER = ', str(self.answer))
def play_answer(answer): number, text = answer mp3_file = '%s.mp3' % number if mp3_file in answers_files: logging.info('answer mp3 file exist') party.play_a_file(os.path.join(answers_dir, mp3_file)) else: tts.say(answer[1])
def __init__(self, cmd, DEBUG=False): self.cmd = cmd self.database = Database() if len(self.cmd) > 2: self.cmd.pop(0) self.cmd.pop(0) self.get_info(self.cmd[0]) else: say("I am sorry. I do not know who you are talking about.")
def blipsay(text): if type(text) == bytes: text = text.decode() m = re.match('[\d\s,]*', text) blips = [int(x) / 100 for x in re.findall('\d+', m.group())] text = text[m.end():] audio.shortjblips(400, *blips) tts.say(Dplayer, text, eq_filter, "en-US") audio.shortjblips(400, *reversed(blips))
def world(): response = urllib2.urlopen( 'https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=1bb66d8bf0e94f449381d101ab3e4f9c' ) data = json.load(response) for x in range(0, 5): a = data["articles"][x]["title"] a = str(a) say(a)
def local(): response = urllib2.urlopen( 'https://newsapi.org/v1/articles?source=the-times-of-india&sortBy=latest&apiKey=1bb66d8bf0e94f449381d101ab3e4f9c' ) data = json.load(response) for x in range(0, 5): a = data["articles"][x]["title"] a = str(a) say(a)
def sayTweets(tweets = None): '''Says tweets Args: a list containing the found statuses ''' if(tweets!=None): #iterate over tweets for tweet in tweets: # remove the non-ascii characters text = tweet.encode('ascii', 'replace') #read the status text tts.say(urllib.quote_plus(text),'en') time.sleep(2)
def sayTweets(tweets=None): '''Says tweets Args: a list containing the found statuses ''' if (tweets != None): #iterate over tweets for tweet in tweets: # remove the non-ascii characters text = tweet.encode('ascii', 'replace') #read the status text tts.say(urllib.quote_plus(text), 'en') time.sleep(2)
def riddle(self): a = 'What gets wetter and wetter the more it dries?' b = 'You throw away the outside and cook the inside. Then you eat the outside and throw away the inside. What did you eat?' c = 'What goes up and down the stairs without moving?' d = 'What can you catch but not throw?' e = 'I can run but not walk. Wherever I go, thought follows close behind. What am I?' f = "What's black and white and red all over?" g = 'What goes around the world but stays in a corner?' riddles = [a, b, c, d, e, f, g] riddle = random.choice(riddles) say(riddle)
def response(text, speed="1.14"): import tts import config if config.speech_on: # 由于我树莓派声音蓝牙音箱播放语音时前几个字声音特别小,听不见,所以使用延迟修正声音 try: import config_private if config_private.speech_delay: text = '啊啊,' + text except ImportError: pass tts.say(text, speed=speed)
def time(self): #Get current time self.raw_time = str(datetime.datetime.now()).split() #Say time if selected command if self.cmd[0].lower() == 'time': time = str(self.raw_time[1]) say('It is ' + time[0] + time[1] + time[2] + time[3] + time[4] + ' AM.') #TODO: Fix time to say it in 12hr time not 24hr time #Say day if selected command if self.cmd[0].lower() == 'day': time = str(self.raw_time[0]) month = self.get_month(time[5], time[6]) say('Today is ' + month + ' ' + time[-2] + time[-1] + ', ' + time[0] + time[1] + time[2] + time[3])
def detected(): try: getConfig(path) if ALARMKWACTIVATED == "1": subprocess.Popen(["aplay", home + "/snd/ding.wav"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) index = pyaudio.PyAudio().get_device_count() - 1 print(index) r = sr.Recognizer() with sr.Microphone(index) as source: r.adjust_for_ambient_noise( source ) # Слушаем шум 1 секунду, потом распознаем, если раздажает задержка можно закомментировать. audio = r.listen(source, timeout=10) if ALARMTTS == "1": subprocess.Popen(["aplay", home + "/snd/dong.wav"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) #snowboydecoder.play_audio_file(snowboydecoder.DETECT_DONG) print("Processing ... Для распознования используем " + PROVIDERSTT) # if PROVIDERSTT == "Google": command = r.recognize_google(audio, language="ru-RU") elif PROVIDERSTT == "Wit.ai": command = r.recognize_wit(audio, key=APIKEYSTT) elif PROVIDERSTT == "Microsoft": command = r.recognize_bing(audio, key=APIKEYSTT) print(command) if ALARMTTS == "1": subprocess.Popen(["aplay", home + "/snd/dong.wav"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) link = "http://" + IP_SERVER + '/command.php?qry=' + urllib.parse.quote_plus( command) f = urllib.request.urlopen(link) except sr.UnknownValueError as e: print("Произошла ошибка {0}".format(e)) #detected () except sr.RequestError as e: print("Произошла ошибка {0}".format(e)) say("Произошла ошибка {0}".format(e)) except sr.WaitTimeoutError: print("Я ничего не услышала") say("Я ничего не услышала")
def say(msg) -> str: """Performs tts command""" text = msg.command_body cost = 10 price = cost*len(text) if not text: return (f"TTS requires points to use. The current cost is {cost} points per letter. " "Warning: users who misuse this command will be punished. Example Usage: !tts hello") if get_points(msg.username) < price: return f"You don't have enough points to say this. TTS costs {cost} points per letter." tts.say(f"{msg.username} says: {text}") increment_points_without_update(msg.username, price, '-') return ''
def __init__(self): self.config = Configure() self.start_server, self.client_ip, self.server_name, self.server_pass = self.config.read_server() if self.start_server == False: sys.exit() say('Starting Server') self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.host = '' self.port = 5150 self.server.bind((self.host, self.port)) self.server.listen(5) print 'Listing for a client...' self.client, self.addr = self.server.accept() print 'Accepted connection from ', self.addr self.client.send(str.encode('Connection made with Andy'))
def trigger_change(new_state, session): if new_state == "failure": say("Who broke the build! Ah, it's {}!".format(get_last_commiter(session)), sync=True) say("Bad, bad, bad developer! See what you've done! Shame on you!") elif new_state == "pending": say("I hope it was deliberate decision to push.") elif new_state == "success": say("Your repository looks well. For now.")
def __init__(self): self.config = Configure() self.start_server, self.client_ip, self.server_name, self.server_pass = self.config.read_server( ) if self.start_server == False: sys.exit() say('Starting Server') self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.host = '' self.port = 5150 self.server.bind((self.host, self.port)) self.server.listen(5) print('Listing for a client...') self.client, self.addr = self.server.accept() print('Accepted connection from ', self.addr) self.client.send(str.encode('Connection made with Andy'))
def me(self): if self.cmd[0] == 'name': say('My name is Cyclops of course.') if self.cmd[0] == 'phone': say("I don't think I should tell you that.") if self.cmd[0] == 'email': say('My email is [email protected].') if self.cmd[0] == 'problem': say("Whatever it is, I don't care.")
def sayTweets(tweets = None): '''Says tweets Args: tweets: the dictionary containing the tweets to read, keys represents the follower name, values are arrays of statuses ''' if(tweets!=None): #iterate over the dictionary keys for key in tweets.keys(): #say the tweet author at first tts.say('Tweet from %s'%key, 'en') #iterate over tweets for tweet in tweets[key]: #encode the tweet text to be suitable for urls tweet_text = urllib.urlencode({'text':tweet}) #cut-off "text:" tweet_text = tweet_text[5:] #read the status text tts.say(tweet_text,'it')
def sayTweets(tweets = None): '''Says tweets Args: tweets: the dictionary containing the tweets to read, keys represent the follower name, values are arrays of statuses ''' if(tweets!=None): #iterate over the dictionary keys for key in tweets.keys(): #say the tweet author at first tts.say('Tweet from %s'%key, 'en') #iterate over tweets for tweet in tweets[key]: #encode the tweet text to be suitable for urls tweet_text = urllib.urlencode({'text':tweet}) #cut-off "text:" tweet_text = tweet_text[5:] #read the status text tts.say(tweet_text,'it')
def mic(): while True: with sr.Microphone() as source: r.adjust_for_ambient_noise(source) try: GPIO.output(18, GPIO.HIGH) audio = r.listen(source, timeout=2) GPIO.output(18, GPIO.LOW) except sr.WaitTimeoutError: continue except KeyboardInterrupt: GPIO.output(18, GPIO.LOW) try: a = str(r.recognize_google(audio)) c = int(len(a.split())) if (a.find('hello') > -1 or a.find('ok') > -1 or a.find('hey') > -1 or a.find('namaste') > -1) and a.find('alpha') > -1: if c == 2: if (a.find('hello') > -1 or a.find('ok') > -1 or a.find('hey') > -1): say( random.choice(greet) + " Sir! What can I do for you?") beep() mic2() elif (a.find('namaste') > -1): sayhindi("Namaste! Mai aapki kya madad kar sakti hu?") beep() mic2() else: GPIO.output(17, GPIO.HIGH) command(a) GPIO.output(17, GPIO.LOW) except sr.UnknownValueError: continue except sr.RequestError as e: continue
def __init__(self, cmd, DEBUG): cmd.pop(0) if len(cmd) >= 1: meet = 'Hello ' + str(cmd[0]) + '... It is nice to meet you.' say(meet) Database().add_person(cmd[0]) say('How old are you?') self.age(cmd[0]) say('What is your favorite color?') self.color(cmd[0]) say('What is your favorite ice cream?') self.ice_cream(cmd[0])
def joke(self): a = ['Canoe.', 'Canoe help me with my homework?'] b = ['Anee.', 'Anee one you like!'] c = ['Arfur.', 'Arfur got!'] d = ['Nana.', 'Nana your business.'] e = ['Ya.', 'Wow. You sure are excited to see me!'] f = ['Cows go', 'Cows don’t go who, they go moo!'] g = ['Etch.', 'Bless you!'] jokes = [a, b, c, d, e, f, g] joke = random.choice(jokes) #say('Knock Knock.') #time.sleep(4) #say(joke[0]) #time.sleep(4) #say(joke[1]) say('Why cant your nose be 12 inches long?') time.sleep(3) say('Because then it would be a foot!')
def pic(self): #Speak and open pic.txt file say('Taking Picture') self.pic_file = open('/home/pi/ANDY/src/temp/pic.txt', 'r') self.num = self.pic_file.readline().rstrip() self.pic_file.close() #Start camera and take picture with picamera.PiCamera() as camera: camera.resolution = (1024, 768) camera.start_preview() time.sleep(2) #Take pic camera.capture('/home/pi/ANDY/pictures/' + str(self.num) + '.jpg') camera.stop_preview() self.pic_file = open('/home/pi/ANDY/src/temp/pic.txt', 'w') self.pic_file.write(str(int(self.num) + 1)) self.pic_file.close() #Upload to Dropbox try: os.system('/home/pi/Dropbox-Uploader/./dropbox_uploader.sh upload ' + '/home/pi/ANDY/pictures/' + str(self.num) + '.jpg ' + str(self.num) + '.jpg') except: say('Failed to upload to drop box')#Upload to Dropbox try: os.system('/home/pi/Dropbox-Uploader/./dropbox_uploader.sh upload ' + '/home/pi/ANDY/pictures/' + str(self.num) + '.jpg ' + str(self.num) + '.jpg') except: say('Failed to upload to drop box')
def video(self): #Open file and get video number self.vid_file = open('/home/pi/ANDY/src/temp/vid.txt', 'r') self.vid_num = self.vid_file.readline().rstrip() self.vid_file.close() say('Recording Video in 3') time.sleep(1) say('two') time.sleep(1) say('one') time.sleep(1) #Record Video with picamera.PiCamera() as camera: camera.resolution = (640, 480) camera.start_preview() camera.start_recording('/home/pi/ANDY/videos/' + str(self.vid_num) + '.h264') camera.wait_recording(10) camera.stop_recording() camera.stop_preview() self.vid_file = open('/home/pi/ANDY/src/temp/vid.txt', 'w') self.vid_file.write(str(int(self.vid_num) + 1)) self.vid_file.close()
def handle_spdt_change(spdt, state): if state == SPDT.SPDT_ON_TOP: say("Sound and voice on") elif state == SPDT.SPDT_OFF: say("Sound on, voice off") elif state == SPDT.SPDT_ON_BOTTOM: say("Sound and voice off")
def wolfram(query): res = client.query(query) try: tts.say(res.pods[0].text) except: try: tts.say(res.pods[1].text) except: tts.say("Sorry, I don't get it.")
def get_info(self, name): name = name.lower() name = name.capitalize() self.color = Database().get_people_data(name, 'favorite_color') self.iceCream = Database().get_people_data(name, 'favorite_ice_cream') self.age = Database().get_people_data(name, 'age') self.food = Database().get_people_data(name, 'favorite_food') if self.age != None: if self.age == 'None': self.age_string = 'I do not know how old ' + name + ' is. ' else: self.age_string = name + ' is ' + self.age + ' years old. ' if self.color == 'None': self.color_string = 'I do not know ' + name + 's favorite color. ' else: self.color_string = name + 's favorite color is ' + self.color if self.iceCream == 'None': self.cream_string = 'I do not know ' + name + 's favorite ice cream.' else: self.cream_string = name + 's favorite ice cream is ' + self.iceCream if self.food == 'None': self.food_string = 'I do not know ' + name + 's favorite food.' else: self.food_string = name + 's favorite food is ' + self.food say(self.age_string) say(self.color_string) say(self.cream_string) say(self.food_string) else: string = 'I do not know ' + name say(string)
def command(data): b = data if (b.find('weather') > -1): say(weather.d) elif (b.find('temperature') > -1): say(weather.temp) elif (b.find('news') > -1) or b.find('headlines') > -1: if (b.find('international') > -1): world() else: local() elif (b.find('light') > -1) and ((b.find('on') > -1) or (b.find('on') > -1) or (b.find('khol') > -1) or (b.find('cool') > -1) or (b.find('holder') > -1)): GPIO.output(16, GPIO.HIGH) elif (b.find('light') > -1) and (b.find('off') > -1 or b.find('of') > -1 or b.find('band') > -1 or b.find('bandh') > -1): GPIO.output(16, GPIO.LOW) elif (b.find('door') > -1 or b.find('darwaza') > -1) and ( b.find('on') > -1 or b.find('khol') > -1 or b.find('cool') > -1 or b.find('holder') > -1): GPIO.output(20, GPIO.HIGH) GPIO.output(21, GPIO.LOW) elif (b.find('door') > -1 or b.find('darwaza') > -1) and (b.find('close') > -1 or b.find('band') > -1 or b.find('bandh') > -1): GPIO.output(21, GPIO.HIGH) GPIO.output(20, GPIO.LOW) elif (b.find('how') > -1) and b.find('you') > -1: say("I am fine! Thank you") elif (b.find('kesi') > -1 or b.find('kese') > -1) and b.find('ho') > -1: sayhindi("Me achchi hu, Shukriya!")
elif cmd[0] == 'tell': cmds.Tell(cmd, DEBUG) elif cmd[0] == 'who': cmds.Who(cmd, DEBUG) elif cmd[0] == 'shutdown': cmds.shutdown() elif cmd[0] == 'sleep': cmds.sleep() elif cmd[0] == 'meet': Meet(cmd, DEBUG) else: say('Not valid command') write(None) time.sleep(1) if __name__ == '__main__': try: main(DEBUG=DEBUG) except SystemExit: pass except: write('error') #If error occurs, save it to file error = traceback.format_exc() error_log = open('/home/pi/ANDY/src/temp/error.txt', 'w') error_log.write(error) print 'An error occurred. Please check error.txt for more details.' say('An error occurred.. Please check error dot text for more details.') time.sleep(4) write(None)
self.stationDict = stationDict self.indexDict = indexDict def __str__(self): self.updateTrack() return 'Currently playing ' + self.track + " by " + self.artist + " on " + self.album # Cool shit to show you that shit works! if __name == "__main__": import time import tts player = Player() player.playByIndex(7) print player time.sleep(3) player.playByIndex(3) time.sleep(5) player.next() player.next() print player tts.say(player.__str__()) time.sleep(5) player.quit()
def write(self, keys): # keys = raw_input() # End of sentence: if keys == "": tts.say(self.output) printStr(self.output + "\n" + self.braille) return -1 # Space: elif keys == " ": tts.say(self.word) printStr(self.output + "\n" + self.braille) self.output += " " self.braille += " " self.word = "" return 1 # Backspace: elif ";" in keys: for key in keys: if key == ";": if (len(self.braille) > 0): self.braille = self.braille[:-1] if (len(self.output) > 0): self.output = self.output[:-1] if (len(self.output) >= 0): i = -1 word = "" while (len(self.output) >= i * -1 and self.output[i] != " "): word = self.output[i] + word i -= 1 self.word = word tts.say(self.word) printStr(self.output + "\n" + self.braille) return 1 # Line space: elif keys == "a": self.output += "\n" self.word = "" self.braille += "\n" return 1 # Uppercase: elif keys == "l": self.braille += u"\u2820" return 1 # Letter: else: keysPressed = self.setKeys(keys) if alpha.has_key(keysPressed): letter = alpha[keysPressed] if len(self.braille) > 0 and self.braille[-1] == u"\u2820": if letter.isalpha(): letter = letter.upper() else: self.braille = self.braille[:-1] tts.say(letter) printKey(letter, keysPressed) self.output += letter self.braille += braille[letter.lower()] self.word += letter return 1 else: return 1
# if abort wished, then stop really if (xbmc.abortRequested): raise # check if we lost connection, then we will try to reconnect if (not os.path.exists(_processPID)): try: openbm.start() xbmc.executebuiltin("XBMC.Notification(%s,%s,500,%s)"%("Reconnected", "BMW I-Bus connected...", bmwLogoSmallImg)) file( _processPID , "w" ).write( "" ) except: pass # check if current time reached a full hour, then notice if (__settings__.getSetting( "speech.hourly") == 'true'): now = datetime.datetime.now() if (now.hour == nextHour and now.minute == 0): tts.say(now.strftime("It is now %H o clock")) nextHour = (now.hour + 1) % 24 except: pass # clear pid file if os.path.exists(_processPID): os.remove(_processPID)
def say_current(): current = wunderground.conditions('San Francisco', 'CA')['current_observation'] say("It is %.1f degrees Fairenheit. That's %.1f sell sea us, Pete" % (current['temp_f'], current['temp_c']))
def write(self, keys): # keys = raw_input() # End of sentence: if keys == "": tts.say(self.output) printStr(self.output+"\n"+self.braille) return -1 # Space: elif keys == " ": tts.say(self.word) printStr(self.output + "\n" + self.braille) self.output += " " self.braille += " " self.word = "" return 1 # Backspace: elif ";" in keys: for key in keys: if key == ";": if(len(self.braille) > 0): self.braille = self.braille[:-1] if(len(self.output) > 0): self.output = self.output[:-1] if(len(self.output) >= 0): i=-1 word = "" while(len(self.output) >= i*-1 and self.output[i] != " "): word = self.output[i] + word i-=1 self.word = word tts.say(self.word) printStr(self.output+"\n"+self.braille) return 1 # Line space: elif keys == "a": self.output += "\n" self.word = "" self.braille += "\n" return 1 # Uppercase: elif keys == "l": self.braille += u"\u2820" return 1 # Letter: else: keysPressed = self.setKeys(keys) if alpha.has_key(keysPressed): letter = alpha[keysPressed] if len(self.braille) > 0 and self.braille[-1] == u"\u2820": if letter.isalpha(): letter = letter.upper() else: self.braille = self.braille[:-1] tts.say(letter) printKey(letter,keysPressed) self.output += letter self.braille += braille[letter.lower()] self.word += letter return 1 else: return 1
def check_mail(user, pwd): ''' Checks a gmail mailbox for new messages, and if any unread mail is found provides a vocal rendering of the mail sender and subject ''' # define the mail server (IMAP) in our case #mail = imaplib.IMAP4_SSL('imap.gmail.com') mail = imaplib.IMAP4_SSL('mail.polito.it') # set the login parameters mail.login(user, pwd) # select the inbox mail.select('inbox') # Search for all new mail status, email_ids = mail.search(None, '(UNSEEN)') # get the e-mail ids if (len(email_ids[0].strip()) > 0): ids = email_ids[0].split(" ") # if there are unseen e-mails unreadcount = len(ids) if (unreadcount > 0): if (unreadcount > 1): tts.say("There are %d new messages" % (len(ids))) else: tts.say("There is one new message") # iterate over unread messages for i in range(0, unreadcount): # message number tts.say("Message %d:" % (i + 1)) # get the full email contents status, data = mail.fetch(ids[i], "(RFC822)") # get the raw mail message raw_email = data[0][1] # parse the mail message msg = email.message_from_string(raw_email) # warn about the message tts.say("You've got a new message from ") # render sender names for sender in msg.get_all('from', []): tts.say(sender) # render subject tts.say("with subject") tts.say(msg.get('Subject', '')) mail.logout()
for i in range (0,20): #get the current power consumption status = dog_zwave.getStatus('MeteringPowerOutlet_6') power_1 = float(status['status']['SinglePhaseActivePowerMeasurementState'][0]['value'][:-1]) status = dog_zigbee.getStatus('MeteringPowerOutlet_3781220529323341') power_2 = float(status['status']['SinglePhaseActivePowerMeasurementState'][0]['value'][:-1]) print '%d W + %d W = %d W'%(power_1,power_2,(power_1+power_2)) total_power = power_1+power_2 if(total_power < (power_peak -10)) or (total_power > (power_peak +10)): #store the new maximum power_peak = total_power #warn the user tts.say("Reached a new power peak of %s Watt"%power_peak, "en") time.sleep(1) dog_zwave.sendCommand('MeteringPowerOutlet_6', 'off') dog_zigbee.sendCommand('MeteringPowerOutlet_3781220529323341', 'off') for i in range (0,20): #get the current power consumption status = dog_zwave.getStatus('MeteringPowerOutlet_6') power_1 = float(status['status']['SinglePhaseActivePowerMeasurementState'][0]['value'][:-1]) status = dog_zigbee.getStatus('MeteringPowerOutlet_3781220529323341') power_2 = float(status['status']['SinglePhaseActivePowerMeasurementState'][0]['value'][:-1]) print '%d W + %d W = %d W'%(power_1,power_2,(power_1+power_2))
def main(DEBUG=False): #Start LEDs write('load') subprocess.Popen(['python', 'LED.py']) #Read from configuration files and apply settings. config = Configure() start_andy_on_boot, social_mode, rebel_mode, wander_mode = config.read() if start_andy_on_boot == False: sys.exit() #Say start up slogan and check for command. say('Hello. My name is Andy. Please wait while my system starts up.') getit = Get_cmd() #Start server process subprocess.Popen(['python', 'server.py']) write(None) #Enter main loop while True: print #Get the command and convert it to a list cmd = getit.get().split() write('load') if DEBUG: print 'COMMAND:', cmd #Remove unused words from command num = 0 for word in cmd: cmd[num] = word.lower() num += 1 if len(cmd) == 0: cmd.append('') #Determin master command if cmd[0] == 'what': cmds.What(cmd, DEBUG) elif cmd[0] == 'walk' or cmd[0] == 'turn': cmds.Walk(cmd, DEBUG) elif cmd[0] == 'stop': cmds.Walk(cmd, DEBUG).stop() elif cmd[0] == 'pickup' or cmd[0] == 'pick' and cmd[1] == 'up': cmds.Arm(cmd, DEBUG).pickup() elif cmd[0] == 'set' and cmd[1] == 'down': cmds.Arm(cmd, DEBUG).setdown() elif cmd[0] == 'where': cmds.Where(cmd, DEBUG) elif cmd[0] == 'take': cmds.Take(cmd, DEBUG) elif cmd[0] == 'set': pass #TODO elif cmd[0] == 'tell': cmds.Tell(cmd, DEBUG) elif cmd[0] == 'who': cmds.Who(cmd, DEBUG) elif cmd[0] == 'shutdown': cmds.shutdown() elif cmd[0] == 'sleep': cmds.sleep() elif cmd[0] == 'meet': Meet(cmd, DEBUG) else: say('Not valid command') write(None) time.sleep(1)
else: sleep(2) def trigger_change(new_state, session): if new_state == "failure": say("Who broke the build! Ah, it's {}!".format(get_last_commiter(session)), sync=True) say("Bad, bad, bad developer! See what you've done! Shame on you!") elif new_state == "pending": say("I hope it was deliberate decision to push.") elif new_state == "success": say("Your repository looks well. For now.") if __name__ == "__main__": say("Hello, my little developers.", sync=True) say("I am blame machine, push only good code and you will not be ashamed by the red light.", sync=True) setup_gpio() t = threading.Thread(target=blink_worker) t.start() s = requests.Session() while True: new_state = test(s) if new_state: if new_state != state_: trigger_change(new_state, s) state_ = new_state sleep(3)
def say_forecast(): forecast = wunderground.forecast('San Francisco', 'CA')['forecast'] say('The forecast for today is ' + forecast['txt_forecast']['forecastday'][0]['fcttext'])
def check_mail(user, pwd): ''' Checks a gmail mailbox for new messages, and if any unread mail is found provides a vocal rendering of the mail sender and subject ''' # define the mail server (IMAP) in our case mail = imaplib.IMAP4_SSL('imap.gmail.com') # set the login parameters mail.login(user, pwd) # select the inbox mail.select('inbox') # Search for all new mail status, email_ids = mail.search(None, '(UNSEEN)') # get the e-mail ids if(len(email_ids[0].strip()) > 0): ids = email_ids[0].split(" ") # if there are unseen e-mails unreadcount = len(ids) if(unreadcount > 0): if(unreadcount > 1): tts.say("There are %d new messages" % (len(ids))) else: tts.say("There is one new message") # iterate over unread messages for i in range(0, unreadcount): # message number tts.say("Message %d:" % (i + 1)) # get the full email contents status, data = mail.fetch(ids[i], "(RFC822)") # get the raw mail message raw_email = data[0][1] # parse the mail message msg = email.message_from_string(raw_email) # warn about the message tts.say("You've got a new message from ") # render sender names for sender in msg.get_all('from', []): tts.say(sender) # render subject tts.say("with subject") tts.say(msg.get('Subject', '')) mail.logout()
return bytes.decode(self.data) def end(self): print 'Closing connection...' self.client.close() def start(): serv = Server() while True: files = open('/home/pi/ANDY/src/temp/cmd.txt', 'w+') os.system('sudo chmod 777 /home/pi/ANDY/src/temp/cmd.txt') cmd = serv.get_cmd() if cmd == None: break files.write(cmd) files.close() while True: if os.path.isfile('/home/pi/ANDY/src/temp/cmd.txt') == False: break serv.end() if __name__ == '__main__': while True: try: start() except: say('Server Already Running') sys.exit()
'''test IR Remote ''' import time from sensor import IRRemote from tts import say ir = IRRemote() value_description = {#0: 'none', 1: 'red up', 2: 'red down', 3: 'blue up', 4: 'blue down', 5: 'red up and blue up', 6: 'red up and blue down', 7: 'red down and blue up', 8: 'red down and blue down', 9: 'beacon mode on', 10: 'red up and red down', 11: 'blue up and blue down', } while True: bt = ir.button if bt in value_description.keys(): say(value_description[bt]) time.sleep(0.5)
#print the number of reads and corresponding bytes print "Reads: %d (%d bytes)"%(disk_io.read_count,disk_io.read_bytes) #print the number of writes and the corresponding bytes print "Writes: %d (%d bytes)"%(disk_io.write_count, disk_io.write_bytes) ''' Monitors the cpu occupation and if raises over a given threshold, calls a specified function ''' def monitor_cpu(threshold,interval,callback=None): while(True): #get the cpu percentage percent = psutil.cpu_percent() #check the thrashold if(percent > threshold): #callback callback(percent) #debug print "calling callback: %s"%percent #wait for the given time time.sleep(interval) if __name__ == '__main__': print_sys_metrics() monitor_cpu(10, 1, lambda x: tts.say("warning, CPU percent raised up to %s"%x))
__author__ = 'Kyle Konrad' import sys import wunderground from tts import say def say_forecast(): forecast = wunderground.forecast('San Francisco', 'CA')['forecast'] say('The forecast for today is ' + forecast['txt_forecast']['forecastday'][0]['fcttext']) def say_current(): current = wunderground.conditions('San Francisco', 'CA')['current_observation'] say("It is %.1f degrees Fairenheit. That's %.1f sell sea us, Pete" % (current['temp_f'], current['temp_c'])) if __name__ == '__main__': try: action = sys.argv[1] except IndexError: action = 'forecast' if action == 'forecast': say_forecast() elif action == 'current': say_current() else: say("I don't know how to tell you about " + action)
def writer(b): bw = b.write() while bw!=-1: print bw tts.say(bw) bw = b.write()