Esempio n. 1
0
    def __init__(self, voicesynthetizer):

        self.modulename = 'VoiceCommand'
        self.output = ""
        self.voicesynthetizer = voicesynthetizer
        self.voicerecognition = VoiceRecognition(self.voicesynthetizer)

        self.clock = Clock(voicesynthetizer)
        self.identification = Identification(voicesynthetizer)
        self.weather = Weather(self.voicesynthetizer)
Esempio n. 2
0
    def __init__(self, logAll=True):
        # конструктор
        self.logAll = logAll
        self.yandexStuff = YandexStuff()
        self.loop = True

        # создаем модули
        self.radio = Radio()
        self.anekdot = Anekdot()
        self.game = Game()
        self.weather = Weather()
        self.citygame = city_game()

        self.recognizer = speech.Recognizer()
        self.iamToken, self.iamTokenExpires = self.yandexStuff.create_token()

        self.play('audio/powerup.wav')
        time.sleep(0.5)
        # todo uncomment
        self.play('audio/jarvisHi.wav')
        time.sleep(0.5)
        self.playLowBeep()
Esempio n. 3
0
def main(fullscreen, resolution):
    logging.info('Started the mirror')
    logging.info('Loading modules')

    pygame.init()
    mode = 0
    if fullscreen:
        logging.info('Launching in full screen mode')
        mode = pygame.FULLSCREEN
        resolution = [0, 0]
    screen = pygame.display.set_mode(resolution, mode)
    screen.fill(COLORS['black'])

    modules = [
        Weather(),
        Clock(),
        Birthday(),
        Calendar(),
        Vasttrafik(),
        SystemInfo(),
    ]
    try:
        # Check if vcgencmd is installed, to see if it is running on a
        # raspberry pi with the requires software installed
        call("vcgencmd")
        # modules.append(DisplayOnOff())
    except FileNotFoundError:
        pass

    for module in modules:
        module.start()

    pygame.mouse.set_visible(MOUSE_VISIBLE)
    try:
        while True:
            screen.fill(COLORS['black'])
            for module in modules:
                data = module.data
                for surface, position in data:
                    screen.blit(surface, position)
            pygame.display.flip()
            # pygame.image.save(screen, 'screen_shot.jpg')
            sleep(1)
            if check_if_exit():
                return
    finally:
        logging.info('Stopping all threads')
        for module in modules:
            module.stop()
        logging.info('Stopped all threads')
Esempio n. 4
0
    def __init__(self, voicesynthetizer):

        self.modulename = 'Assistant'
        self.running = True
	self.introduced = False
        self.threads = []
	self.voicesynthetizer = voicesynthetizer

	self.voicerecognition = VoiceRecognition(self.voicesynthetizer)
	self.voicemail = VoiceMail(self.voicesynthetizer)
        self.clock = Clock(voicesynthetizer)
        self.identification = Identification(voicesynthetizer)
        self.weather = Weather(self.voicesynthetizer)
        self.messages = Messages(self.voicesynthetizer)
        self.seismology = Seismology(self.voicesynthetizer)
Esempio n. 5
0
async def test_weather(mocker):
    mocked_fetch = mocker.patch(
        "modules.weather.fetch", side_effect=("Amsterdam: -1", "Paris: -1")
    )

    assert [
        _
        async for _ in Weather(
            cities=(
                "Amsterdam",
                "Paris",
            )
        )
    ] == ["Amsterdam: -1", "Paris: -1"]
    assert mocked_fetch.call_count == 2
    assert mocked_fetch.call_args_list[0][0][0] == "https://wttr.in/Amsterdam?format=3"
    assert mocked_fetch.call_args_list[1][0][0] == "https://wttr.in/Paris?format=3"
Esempio n. 6
0
    def modules_setup(self):

        # Production Modules
        self.aprstracker = AprsTracker(self.voicesynthetizer)
        self.aprstt = Aprstt(self.voicesynthetizer)
        self.clock = Clock(self.voicesynthetizer)
        self.identification = Identification(self.voicesynthetizer)
        self.meteorology = Meteorology(self.voicesynthetizer)
        self.news = News(self.voicesynthetizer)
        self.selfie = Selfie(self.voicesynthetizer)
        self.voicecommand = VoiceCommand(self.voicesynthetizer)
        self.voicemail = VoiceMail(self.voicesynthetizer)
        self.weather = Weather(self.voicesynthetizer)
        self.wolframalpha = WolframAlpha(self.voicesynthetizer)

        # Experimental Modules
        self.assistant = Assistant(self.voicesynthetizer)
        self.messages = Messages(self.voicesynthetizer)
        self.morseteacher = MorseTeacher(self.voicesynthetizer)
        self.seismology = Seismology(self.voicesynthetizer)
        self.sstv = SSTV(self.voicesynthetizer)
        self.voiceapp = VoiceApp(self.voicesynthetizer)
        self.voiceexperimental = VoiceExperimental(self.voicesynthetizer)
        self.voicemailer = VoiceMailer(self.voicesynthetizer)
Esempio n. 7
0
class Assistant(object):

    def __init__(self, voicesynthetizer):

        self.modulename = 'Assistant'
        self.running = True
	self.introduced = False
        self.threads = []
	self.voicesynthetizer = voicesynthetizer

	self.voicerecognition = VoiceRecognition(self.voicesynthetizer)
	self.voicemail = VoiceMail(self.voicesynthetizer)
        self.clock = Clock(voicesynthetizer)
        self.identification = Identification(voicesynthetizer)
        self.weather = Weather(self.voicesynthetizer)
        self.messages = Messages(self.voicesynthetizer)
        self.seismology = Seismology(self.voicesynthetizer)

    def demo1(self):
	self.introduction1()
	self.command()

    def demo2(self):
	self.introduction2()
	self.command()

    def introduction1(self):
        self.voicesynthetizer.speechit("Hola! Dime como puedo ayudarte?")
        self.introduced = True

    def introduction2(self):
	while True:
	        self.voicerecognition.record('5')
	        output = self.voicerecognition.recognize('False')
	        if re.search(r'hola', output, re.M|re.I) or re.search(r'nu', output, re.M|re.I):
	            self.voicesynthetizer.speechit("Hola! Dime como puedo ayudarte?")
		    self.introduced = True
		    break

    def command(self):
	while self.introduced:
		self.voicerecognition.record()
	        output = self.voicerecognition.recognize('False')
 	        if re.search(r'identif', output, re.M|re.I):
		    print '[NuupXe] Assistant Identification'
	            self.identification.identify()
	        elif re.search(r'hora', output, re.M|re.I) or re.search(r'ora', output, re.M|re.I) :
	            print '[NuupXe] Assistant Hour'
	            self.clock.hour()
	        elif re.search(r'fecha', output, re.M|re.I):
	            print '[NuupXe] Assistant Date'
	            self.clock.date()
	        elif re.search(r'reporte', output, re.M|re.I) or re.search(r'clima', output, re.M|re.I):
	            print '[NuupXe] Assistant Weather'
	            self.weather.report()
	        elif re.search(r'estaciones', output, re.M|re.I) or re.search(r'repetidores', output, re.M|re.I):
	            print '[NuupXe] Assistant Stations'
	            self.messages.stations()
	        elif re.search(r'sismo', output, re.M|re.I):
	            print '[NuupXe] Assistant Seismic'
	            self.seismology.SismologicoMX()
	        elif re.search(r'mensaje', output, re.M|re.I) or re.search(r'avis', output, re.M|re.I):
	            print '[NuupXe] Assistant Message'
		    if self.voicemail.status:
			    self.voicesynthetizer.speechit("Mensaje existente!")
			    while True:
				    self.voicesynthetizer.speechit("Quieres escucharlo, borrarlo o salir de esta opcion")
			            self.voicerecognition.record()
		        	    output = self.voicerecognition.recognize('False')
				    if re.search(r'escuchar', output, re.M|re.I):
					    print '[NuupXe] Assistant Message Play'
					    self.voicemail.play()
				    elif re.search(r'borrar', output, re.M|re.I):
					    print '[NuupXe] Assistant Message Erase'
					    self.voicemail.erase()
				    elif re.search(r'salir', output, re.M|re.I):
					    print '[NuupXe] Assistant Message Quit'
					    self.voicesynthetizer.speechit("Saliendo de Opcion Mensaje")
					    break
		    else:
		            self.voicemail.record()
		            self.voicemail.play()
	        elif re.search(r'dormir', output, re.M|re.I):
	            print '[NuupXe] Assistant Sleep'
		    self.voicesynthetizer.speechit("Perfecto! Gracias! Dormire por los proximos 30 segundos")
		    sleep(30)
		    self.voicesynthetizer.speechit("Ya desperte! Que rica siesta!")
		elif re.search(r'eventos', output, re.M|re.I):
		    print '[NuupXe] Assistant Bye'
		    self.voicesynthetizer.speechit("El radioclub tiene 2 eventos proximos")
		    self.voicesynthetizer.speechit("Boletin Tecnologico, Miercoles, 8:00 pm")
		    self.voicesynthetizer.speechit("Junta Mensual, Jueves 8:00 pm, recuerda traer galletas")
		elif re.search(r'nada', output, re.M|re.I) or re.search(r'dios', output, re.M|re.I) or re.search(r'ativo', output, re.M|re.I):
		    print '[NuupXe] Assistant Bye'
		    self.voicesynthetizer.speechit("Hasta pronto!")
	            self.running = False
		    break
        	else:
	            print '[NuupXe] Assistant? Unknown!'

		self.voicesynthetizer.speechit("Se ofrece algo mas?")

    def foo(self):
        while(self.running):
            print '[NuupXe] Assistante | Foo Hello'
            sleep(5)

    def get_user_input(self):
        while True:
            x = raw_input("Tupe any text, Enter 'e' for exit: ")
            if x.lower() == 'e':
               self.running = False
               break
	    else:
	       self.voicesynthetizer.speechit(x)

    def twitter(self):
	return
	self.twitterc = TwitterC('twython')
	self.oldstatus = ''
	self.newstatus = ''
	
	while (self.running):
            print '[NuupXe] Assistante | Twitter Hello'
	    #self.voicesynthetizer.speechit("Veamos")
	    tstatus = self.twitterc.timeline_get('xe1gyq', 1)
	    for status in tstatus:
	        self.newstatus = status['text']
		if self.newstatus != self.oldstatus:
			self.oldstatus = self.newstatus
			self.voicesynthetizer.speechit("Nuevo mensaje en cuenta de Twitter!")
			self.voicesynthetizer.speechit(self.newstatus)
	    sleep(5)

    def go(self):
        t1 = threading.Thread(target=self.foo)
        t2 = threading.Thread(target=self.get_user_input)
	t3 = threading.Thread(target=self.twitter)
	t4 = threading.Thread(target=self.demo1)
        # Make threads daemonic, i.e. terminate them when main thread
        # terminates. From: http://stackoverflow.com/a/3788243/145400
        t1.daemon = True
        t2.daemon = True
	t3.daemon = True
	t4.daemon = True
        t1.start()
        t2.start()
	t3.start()
	t4.start()
        self.threads.append(t1)
        self.threads.append(t2)
	self.threads.append(t3)
	self.threads.append(t4)
Esempio n. 8
0
class Jarvis:
    def __init__(self, logAll=True):
        # конструктор
        self.logAll = logAll
        self.yandexStuff = YandexStuff()
        self.loop = True

        # создаем модули
        self.radio = Radio()
        self.anekdot = Anekdot()
        self.game = Game()
        self.weather = Weather()
        self.citygame = city_game()

        self.recognizer = speech.Recognizer()
        self.iamToken, self.iamTokenExpires = self.yandexStuff.create_token()

        self.play('audio/powerup.wav')
        time.sleep(0.5)
        # todo uncomment
        self.play('audio/jarvisHi.wav')
        time.sleep(0.5)
        self.playLowBeep()

    def destroy(self):
        self.play('audio/jarvisBye.wav')
        time.sleep(1)
        self.play('audio/powerdown.wav')
        self.loop = False

    def checkActive(self):

        result = False
        t = ""

        with speech.WavFile("audio/tmp/send.wav") as source:
            audio = self.recognizer.record(source)

        # используем возможности библиотеки Spinx
        try:
            t = self.recognizer.recognize_sphinx(
                audio)  # todo check, language='ru-RU/cmusphinx-ru-5.2')
            if t != "" or self.logAll:
                print("Sphinx thinks you said: [" + t + "]")
        except speech.UnknownValueError:
            result = 0
            if self.logAll:
                print("Sphinx could not understand audio")
        except speech.RequestError as e:
            print("Sphinx error; {0}".format(e))

        if t == "jarvis":
            result = True

        if result:
            self.playHiBeep()

        return result

    def playHiBeep(self):
        Jarvis.sysCommand("aplay audio/beep_hi.wav", self.logAll)

    def playLowBeep(self):
        Jarvis.sysCommand("aplay audio/beep_lo.wav", self.logAll)

    def listen(self, n, useOgg=False):
        # записываем n секунд эфира с микрофона
        Jarvis.sysCommand('arecord -fcd -d' + str(n) + ' audio/tmp/send.wav',
                          self.logAll)

        if useOgg:
            Jarvis.sysCommand(
                'opusenc --bitrate 48 audio/tmp/send.wav audio/tmp/send.ogg',
                self.logAll)

        # with self.r.Microphone() as source:
        #    audio = self.r.listen(source)

    def mainLoop(self):
        try:
            while self.loop:
                self.listen(2)
                res = self.checkActive()
                if res:
                    # записываем основной запрос пользователя
                    self.listen(3, True)
                    self.playLowBeep()

                    time.sleep(0.5)

                    words = self.yandexRecognize()
                    command = CommandChecker.checkForCommand(words.lower())

                    print('команда: ' + command)
                    if (command == "exit"):
                        loop = False
                        self.destroy()

                    elif (command == "game"):
                        self.game.GameLoop()

                    elif (command == "weather"):
                        self.weather.getWeather()

                    elif (command == "radio"):
                        self.radio.listen()

                    elif (command == "radiostop"):
                        self.radio.stop()

                    elif command == "cities":
                        self.citygame.citi_function()

                    elif (command == "anekdot"):
                        try:
                            joke = self.anekdot.getJoke()
                            print(joke)
                            self.say(joke)
                        except:
                            self.say("Что-то я не в настроении шутить")

        except Exception as e:
            print("Глобальная ошибка; {0}".format(e))
            self.play('audio/error.wav')

    # статические функции для использования в других классах
    @staticmethod
    def sysCommand(command, logAll=False):
        #c = "{}{}".format(command, self.devNull)
        #os.system(c)
        subprocess.run(command, shell=True, capture_output=not logAll)

    @staticmethod
    def play(file):
        Jarvis.sysCommand('aplay ' + file)

    @staticmethod
    def playmp3(file):
        Jarvis.sysCommand('mpg123  ' + file)

    def say(self, text):
        # print(text)
        self.yandexStuff.createSynthAudio(self.iamToken, text, "tts.wav")
        Jarvis.play("audio/tmp/tts.wav")

    def yandexRecognize(self):
        # speech-to-text от старины Яндекса
        #print('token: ' + self.iamToken);
        recognizedText = self.yandexStuff.recognize(self.iamToken)
        result = recognizedText['result']
        print(result)
        return result
Esempio n. 9
0
class VoiceCommand(object):

    def __init__(self, voicesynthetizer):

        self.modulename = 'VoiceCommand'
        self.output = ""
        self.voicesynthetizer = voicesynthetizer
        self.voicerecognition = VoiceRecognition(self.voicesynthetizer)

        self.clock = Clock(voicesynthetizer)
        self.identification = Identification(voicesynthetizer)
        self.weather = Weather(self.voicesynthetizer)

    def presentation(self):

        logging.info('Voice Command Presentation')
        self.voicesynthetizer.speechit("Hola! Como puedo ayudarte?")

    def decode(self, output):

        logging.info('Voice Command Decode')

        if re.search(r'coman', output, re.M|re.I) or re.search(r'disponi', output, re.M|re.I):
            logging.info('Voice Command Decode Available Commands')
            self.voicesynthetizer.speechit("Comandos Disponibles? Identificacion, Hora, Fecha, Clima")
        elif re.search(r'identif', output, re.M|re.I):
            logging.info('Voice Command Decode Identification')
            self.identification.identify()
        elif re.search(r'hora', output, re.M|re.I):
            logging.info('Voice Command Decode Hour')
            self.clock.hour()
        elif re.search(r'fecha', output, re.M|re.I):
            logging.info('Voice Command Decode Date')
            self.clock.date()
        elif re.search(r'clima', output, re.M|re.I):
            logging.info('Voice Command Decode Weather')
            self.weather.report()
        elif re.search(r'tempe', output, re.M|re.I) or re.search(r'tura', output, re.M|re.I):
            logging.info('Voice Command Decode Temperature')
            self.weather.temperature()
        else:
            logging.error('Voice Command Unknown!')
            self.voicesynthetizer.speechit("No entendimos tu comando!")

    def listen(self):

        logging.info('Voice Command Listen')
        self.presentation()
        self.voicerecognition.record()
        output = self.voicerecognition.recognize('False')
        self.decode(output)
        alive(modulename=self.modulename, modulemessage=' Command ' + output.capitalize())

    def background(self):

        logging.info('Voice Command Background')
	while True:
	        self.voicerecognition.record()
        	output = self.voicerecognition.recognize('False')
                if re.search(r'canc', output, re.M|re.I):
                    self.voicesynthetizer.speechit("Alguien me hablo?. Soy NuupXe... Hasta pronto!")
                    break
                print output
    def getLastEntry(self, collection_name):
        database = self.__client["weathercrawler"]
        collection = database[str(collection_name)]
        lastEntry = collection.find_one(sort=[('$natural',-1)])

        #return lastEntry
        #lastEntry = collection.find().sort([('$natural',-1)]).limit(1)
        weatherObj = Weather()
        weatherObj.set_tstamp(lastEntry['tstamp'])
        weatherObj.set_temp(lastEntry['temp'])
        weatherObj.set_temp_max(lastEntry['temp_max'])
        weatherObj.set_temp_min(lastEntry['temp_min'])
        weatherObj.set_feels_like(lastEntry['feels_like'])
        weatherObj.set_description(lastEntry['description'])
        weatherObj.set_pressure(lastEntry['pressure'])
        weatherObj.set_humidity(lastEntry['humidity'])
        weatherObj.set_wind_speed(lastEntry['wind_speed'])
        weatherObj.set_wind_speed(lastEntry['wind_deg'])
        
        if lastEntry['wind_deg'] != None:
            weatherObj.set_wind_deg(float(lastEntry['wind_deg']))
        weatherObj.set_clouds_all(lastEntry['clouds_all'])
        if lastEntry['rain1h'] != None:
            weatherObj.set_rain1h(lastEntry['rain1h'])
        if lastEntry['rain3h'] != None:
            weatherObj.set_rain3h(lastEntry['rain3h'])
        if lastEntry['snow1h'] != None:
            weatherObj.set_snow1h(lastEntry['snow1h'])
        if lastEntry['snow3h'] != None:
            weatherObj.set_snow3h(lastEntry['snow3h'])
        if lastEntry['visibility'] != None:
            weatherObj.set_visibility(lastEntry['visibility'])
        weatherObj.set_sunrise(lastEntry['sunrise'])
        weatherObj.set_sunset(lastEntry['sunset'])
        weatherObj.set_main(lastEntry['main'])
        weatherObj.set_description(lastEntry['description'])
        weatherObj.set_tstamp(lastEntry['tstamp'])
        
        return weatherObj
db_host = '127.0.0.1'
db_port = '27017'
db_user = '******'
db_pass = '******'

try:

    # initialize database
    mongo = MongoDriver(db_host, db_port, db_user, db_pass)

    entries = mongo.getAll('Vellberg')

    entry_list = []

    for x in entries:
        entry = Weather()
        entry.set_temp(x['temp'])
        entry.set_temp_max(x['temp_max'])
        entry.set_temp_min(x['temp_min'])
        entry.set_feels_like(x['feels_like'])
        entry.set_pressure(x['pressure'])
        entry.set_humidity(x['humidity'])
        entry.set_wind_speed(x['wind_speed'])
        if x['wind_deg'] != None:
            entry.set_wind_deg(float(x['wind_deg']))
        entry.set_clouds_all(x['clouds_all'])
        if x['rain1h'] != None:
            entry.set_rain1h(x['rain1h'])
        if x['rain3h'] != None:
            entry.set_rain3h(x['rain3h'])
        if x['snow1h'] != None:
def get_station_data(location):

    try:
        # initialize database
        mongo = MongoDriver(db_host, db_port, db_user, db_pass)

        entries = mongo.getAll(location)

        entry_list = []

        for x in entries:
            entry = Weather()
            entry.set_temp(x['temp'])
            entry.set_temp_max(x['temp_max'])
            entry.set_temp_min(x['temp_min'])
            entry.set_feels_like(x['feels_like'])
            entry.set_pressure(x['pressure'])
            entry.set_humidity(x['humidity'])
            entry.set_wind_speed(x['wind_speed'])
            if x['wind_deg'] != None:
                entry.set_wind_deg(float(x['wind_deg']))
            entry.set_clouds_all(x['clouds_all'])
            if x['rain1h'] != None:
                entry.set_rain1h(x['rain1h'])
            if x['rain3h'] != None:
                entry.set_rain3h(x['rain3h'])
            if x['snow1h'] != None:
                entry.set_snow1h(x['snow1h'])
            if x['snow3h'] != None:
                entry.set_snow3h(x['snow3h'])
            if x['visibility'] != None:
                entry.set_visibility(x['visibility'])
            entry.set_sunrise(x['sunrise'])
            entry.set_sunset(x['sunset'])
            entry.set_main(x['main'])
            entry.set_description(x['description'])
            entry.set_tstamp(x['tstamp'])

            entry_list.append(entry)
        # end of foor loop

        return entry_list
    except Exception as err:
        print(f'{err}')
        return []
Esempio n. 13
0
    def update_weather(self, url):
        # print('[debug] checking for updates ...')
        try:
            html = urllib.request.urlopen(url).read()
        except:
            print('[error] cannot open URL')
            sys.exit(1)

        dom = lxml.html.fromstring(html.decode('utf-8'))
        updated_time_str = dom.xpath(
            WeatherForecastManager.XPATH_UPDATED_TIME)[0]
        point_info = dom.xpath(WeatherForecastManager.XPATH_POINT_INFO)[0]
        self.point_name = re.match(r'(.+)の天気', point_info).group(1)

        # 更新日時を設定
        comment = dom.xpath(
            WeatherForecastManager.XPATH_UPDATED_TIME_DETAIL_COMMENT)[0]
        comment = lxml.html.tostring(comment,
                                     method='html',
                                     encoding='unicode')
        mat = re.match(
            r'.*generate at (\d{4})\-(\d{2})\-\d{2} \d{2}\:\d{2}\:\d{2}',
            comment)
        year = int(mat.group(1))
        month = int(mat.group(2))
        mat = re.match(r'(\d+)日(\d+):(\d+)発表', updated_time_str)
        day = int(mat.group(1))
        hour = int(mat.group(2))
        minute = int(mat.group(3))
        self.updated_time = datetime.datetime(year, month, day, hour, minute)

        self.weathers = []

        for k in range(3):
            w = Weather()
            w.date = dom.xpath(WeatherForecastManager.XPATH_WEATHER_DATES %
                               (k + 1))[0][:-1]
            tds_weather = dom.xpath(WeatherForecastManager.XPATH_WEATHER_TD %
                                    (k + 1))
            tds_temperature = dom.xpath(
                WeatherForecastManager.XPATH_TEMPERATURE_TD % (k + 1))
            tds_probability_of_rain = dom.xpath(
                WeatherForecastManager.XPATH_PROB_RAIN_TD % (k + 1))
            tds_amount_of_rain = dom.xpath(
                WeatherForecastManager.XPATH_AMOUNT_RAIN_TD % (k + 1))
            tds_humidity = dom.xpath(WeatherForecastManager.XPATH_HUMIDITY_TD %
                                     (k + 1))

            w.weathers = list(map(lambda td: td[1].text, tds_weather))
            w.is_past = list(
                map(lambda td: ('past' in td[0].attrib['src']), tds_weather))
            w.temperatures = list(
                map(lambda td: float(td[0].text), tds_temperature))
            w.probability_of_rains = list(
                map(
                    lambda td: None
                    if td[0].text == '---' else int(td[0].text),
                    tds_probability_of_rain))
            w.amount_of_rains = list(
                map(lambda td: float(td[0].text), tds_amount_of_rain))
            w.humidities = list(map(lambda td: int(td[0].text), tds_humidity))

            self.weathers.append(w)

        self.pickle_data()
Esempio n. 14
0
class ServiceManager(object):

    def __init__(self, irlp):

        self.irlp = irlp
        self.pidfile = None
        self.scheduler_status = False
        self.pidfile = "/tmp/nuupxe.pid"

    def __del__(self):
        pass

    def voicesynthetizer(self):
        self.voicesynthetizer = VoiceSynthetizer("google", "spanish")

    def voicesynthetizerget(self):
        return self.voicesynthetizer

    def modules_setup(self):

        # Production Modules
        self.aprstracker = AprsTracker(self.voicesynthetizer)
        self.aprstt = Aprstt(self.voicesynthetizer)
        self.clock = Clock(self.voicesynthetizer)
        self.identification = Identification(self.voicesynthetizer)
        self.meteorology = Meteorology(self.voicesynthetizer)
        self.news = News(self.voicesynthetizer)
        self.selfie = Selfie(self.voicesynthetizer)
        self.voicecommand = VoiceCommand(self.voicesynthetizer)
        self.voicemail = VoiceMail(self.voicesynthetizer)
        self.weather = Weather(self.voicesynthetizer)
        self.wolframalpha = WolframAlpha(self.voicesynthetizer)

        # Experimental Modules
        self.assistant = Assistant(self.voicesynthetizer)
        self.messages = Messages(self.voicesynthetizer)
        self.morseteacher = MorseTeacher(self.voicesynthetizer)
        self.seismology = Seismology(self.voicesynthetizer)
        self.sstv = SSTV(self.voicesynthetizer)
        self.voiceapp = VoiceApp(self.voicesynthetizer)
        self.voiceexperimental = VoiceExperimental(self.voicesynthetizer)
        self.voicemailer = VoiceMailer(self.voicesynthetizer)

    def dtmf_setup(self,dtmf):
        dtmf_codes = {
        'PS0'  : 'alive',
        'PS1'  : 'aprstracker',
        'PS2'  : 'news',
        'PS3'  : 'meteorology',
        'PS4'  : 'seismology',
        'PS5'  : 'selfie',
        'PS6'  : 'voicecommand',
        'PS7'  : 'voiceexperimental',
        'PS8'  : 'wolframalpha',
        'PS9'  : 'voicemail',
        'PS10' : 'sstv',
        'PS11' : 'voiceapp',
        }
        return dtmf_codes.get(dtmf)

    def enabled(self):
        return os.path.isfile(self.pidfile)

    def enable(self):

        pid = str(os.getpid())
        logging.info('Process Id' + pid)
        file(self.pidfile, 'w').write(pid)

    def disable(self):

        if self.enabled():
            os.unlink(self.pidfile)
        if self.scheduler_status:
            self.scheduler.shutdown()

    def bing_mode(self):

        logging.info('Mode Bing')
        self.sstv = SSTV(self.voicesynthetizer)
        self.sstv.download()

    def observer_mode(self):

        logging.info('Mode Observer')
        pub = Publisher(['text', 'voice'])

        # Radio, Twitter, Email, Telegram, Whatsapp

        radio = Subscriber('radio')
        twitter = Subscriber('twitter')
        email = Subscriber('email')
        telegram = Subscriber('telegram')

        pub.register("text", radio)
        pub.register("voice", radio)
        pub.register("text", twitter)
        pub.register("text", email)
        pub.register("text", telegram)
        pub.register("voice", telegram)

        pub.dispatch("text", "this is text")
        pub.dispatch("voice", "this is voice")

    def scheduler_mode(self):

        logging.info('Mode Scheduler')
        self.voicesynthetizer.speechit("Modo Planificador")
        self.scheduler = Scheduler(misfire_grace_time=900, coalesce=True, threadpool=ThreadPool(max_threads=1))
        self.schedule()
        self.scheduler.start()
        self.schedule_print()
        self.scheduler_status = True

        while True:
            time.sleep(5)
            if self.irlp.active():
                time.sleep(5)
                self.irlp.busy()
                self.voicesynthetizer.speechit("Se ha activado el nodo, Proyecto NuupXe dice hasta pronto!")
                break

        self.disable()

    def writing_mode(self):

        logging.info('Mode Writing')
        # self.voicesynthetizer.speechit("Modo Escritura")

        while True:
            print " Type any text to make use of Text to Speech infraestructure"
            x = raw_input(" Type 'e' for exit: ")
            if x.lower() == 'e':
                self.disable()
                break;
            else:
                self.voicesynthetizer.speechit(x)
            time.sleep(1)

    def module_mode(self, module, dtmf=None):

        logging.info('Mode Module ' + module)

        # Custom Decode Activated Modules

        if module == 'identification':
            self.identification = Identification(self.voicesynthetizer)
            self.identification.identify()
        elif module == 'date':
            self.clock = Clock(self.voicesynthetizer)
            self.clock.date()
        elif module == 'hour':
            self.clock = Clock(self.voicesynthetizer)
            self.clock.hour()
        elif module == 'temperature':
            self.weather = Weather(self.voicesynthetizer)
            self.weather.temperature()
        elif module == 'weather':
            self.weather = Weather(self.voicesynthetizer)
            self.weather.report()

        # PS Activated Modules

        elif module == 'alive':
            alive()
        elif module == 'aprstracker':
            self.aprstracker = AprsTracker(self.voicesynthetizer)
            self.aprstracker.localize()
        elif module == 'news':
            self.news = News(self.voicesynthetizer)
            self.news.getitems()
        elif module == 'meteorology':
            self.meteorology = Meteorology(self.voicesynthetizer)
            self.meteorology.conagua_clima()
        elif module == 'selfie':
            self.selfie = Selfie(self.voicesynthetizer)
            self.selfie.get()
        elif module == 'voicecommand':
            self.voicecommand = VoiceCommand(self.voicesynthetizer)
            self.voicecommand.listen()
        elif module == 'voiceapp':
            self.voiceapp = VoiceApp(self.voicesynthetizer)
            self.voiceapp.application()
        elif module == 'voicemail':
            self.voicemail = VoiceMail(self.voicesynthetizer)
            self.voicemail.run(dtmf)
        elif module == 'wolframalpha':
            self.wolframalpha = WolframAlpha(self.voicesynthetizer)
            self.wolframalpha.ask()

        # SS Activated Modules

        # Experimental Modules

        elif module == 'aprstt':
            self.aprstt = Aprstt(self.voicesynthetizer)
            self.aprstt.query(dtmf)
        elif module == 'seismology':
            self.seismology = Seismology(self.voicesynthetizer)
            self.seismology.SismologicoMX()
        elif module == 'morselearn':
            self.morseteacher = MorseTeacher(self.voicesynthetizer)
            self.morseteacher.learn()
        elif module == 'morsecontest'	:
            self.morseteacher = MorseTeacher(self.voicesynthetizer)
            self.morseteacher.contest()
	elif module == 'regulations':
            self.messages = Messages(self.voicesynthetizer)
            self.messages.readfile('learning/reglamentos.1')
	elif module == 'radioclub':
            self.messages = Messages(self.voicesynthetizer)
            self.messages.readfile('learning/arej.radioclubs')
        elif module == 'stations':
            self.messages = Messages(self.voicesynthetizer)
            self.messages.stations()
        elif module == 'sstv':
            self.sstv = SSTV(self.voicesynthetizer)
            self.sstv.decode()
        elif module == 'assistant':
            self.assistant = Assistant(self.voicesynthetizer)
            self.assistant.demo1()
        elif module == 'voicebackground':
            self.voicecommand = VoiceCommand(self.voicesynthetizer)
            self.voicecommand.background()
        elif module == 'voiceexperimental':
            self.voiceexperimental = VoiceExperimental(self.voicesynthetizer)
            self.voiceexperimental.listen()
        elif module == 'voicemailer':
            self.voicemailer = VoiceMailer(self.voicesynthetizer)
            self.voicemailer.attend(dtmf)
        else:
            self.voicesynthetizer.speechit("No hemos implementado tu comando! Lo siento!")

        self.disable()

    def voice_mode(self, text):
        logging.info('Voice Mode')
        try:
            self.voicesynthetizer.speechit(text)
        except (StopIteration, KeyboardInterrupt, SystemExit):
            pass

    def phonetic_mode(self, text):
        logging.info('Phonetic Mode')
        phonetic = Phonetic()
        try:
            text = ' '.join(phonetic.decode(text))
            self.voicesynthetizer.speechit(text)
        except (StopIteration, KeyboardInterrupt, SystemExit):
            pass

    def schedule_print(self):
        self.scheduler.print_jobs()

    def schedule(self):

        # Production Modules
        self.scheduler.add_cron_job(self.clock.date, month='*', day_of_week='*', hour='06,12,22', minute ='00', second='00')
        self.scheduler.add_cron_job(self.clock.hour, month='*', day_of_week='*', hour='*', minute ='*/15', second='00')
        self.scheduler.add_cron_job(self.identification.identify, month='*', day_of_week='*', hour='*', minute ='*/30', second='00')
        self.scheduler.add_cron_job(self.selfie.get, month='*', day_of_week='*', hour='00,04,08,14,19', minute ='00', second='00')
        self.scheduler.add_cron_job(self.weather.report, month='*', day_of_week='*', hour='*/2', minute ='00', second='00')

        # Experimental Modules
        self.scheduler.add_cron_job(self.seismology.SismologicoMX, month='*', day='*', hour='*/4', minute ='00', second='00')
        self.scheduler.add_cron_job(self.news.getitems, month='*', day='*', hour='*/4', minute ='00', second='00')
        self.scheduler.add_cron_job(self.meteorology.conagua_clima, month='*', day='*', hour='*', minute ='15', second='00')
        self.scheduler.add_cron_job(self.messages.stations, month='*', day='*', hour='*/4', minute ='00', second='00')
        self.scheduler.add_cron_job(self.sstv.decode, month='*', day='*', hour='00,04,08,14,19', minute ='00', second='00')

	# Learning Modules, AREJ
        self.scheduler.add_cron_job(self.messages.readfile,args=['learning/arej.radioclubs'],month='*',day_of_week='*',hour='7,12,17',minute ='00',second='00')

        # Learning Modules, Morse
        self.scheduler.add_cron_job(self.morseteacher.learn, month='*', day='*', hour='07,12,17', minute ='30', second='00')
        self.scheduler.add_cron_job(self.morseteacher.contest, month='*', day='*', hour='07,12,17', minute ='45', second='00')

        # Learning Modules, Reglamentos
        self.scheduler.add_cron_job(self.messages.readfile,args=['learning/reglamentos.1'], month='*', day_of_week='mon', hour='08,13,18', minute ='00', second='00')
        self.scheduler.add_cron_job(self.messages.readfile,args=['learning/reglamentos.2'], month='*', day_of_week='tue', hour='08,13,18', minute ='00', second='00')
        self.scheduler.add_cron_job(self.messages.readfile,args=['learning/reglamentos.3'], month='*', day_of_week='wed', hour='08,13,18', minute ='00', second='00')
        self.scheduler.add_cron_job(self.messages.readfile,args=['learning/reglamentos.4'], month='*', day_of_week='thu', hour='08,13,18', minute ='00', second='00')
        self.scheduler.add_cron_job(self.messages.readfile,args=['learning/reglamentos.5'], month='*', day_of_week='fri', hour='08,13,18', minute ='00', second='00')
Esempio n. 15
0
    def module_mode(self, module, dtmf=None):

        logging.info('Mode Module ' + module)

        # Custom Decode Activated Modules

        if module == 'identification':
            self.identification = Identification(self.voicesynthetizer)
            self.identification.identify()
        elif module == 'date':
            self.clock = Clock(self.voicesynthetizer)
            self.clock.date()
        elif module == 'hour':
            self.clock = Clock(self.voicesynthetizer)
            self.clock.hour()
        elif module == 'temperature':
            self.weather = Weather(self.voicesynthetizer)
            self.weather.temperature()
        elif module == 'weather':
            self.weather = Weather(self.voicesynthetizer)
            self.weather.report()

        # PS Activated Modules

        elif module == 'alive':
            alive()
        elif module == 'aprstracker':
            self.aprstracker = AprsTracker(self.voicesynthetizer)
            self.aprstracker.localize()
        elif module == 'news':
            self.news = News(self.voicesynthetizer)
            self.news.getitems()
        elif module == 'meteorology':
            self.meteorology = Meteorology(self.voicesynthetizer)
            self.meteorology.conagua_clima()
        elif module == 'selfie':
            self.selfie = Selfie(self.voicesynthetizer)
            self.selfie.get()
        elif module == 'voicecommand':
            self.voicecommand = VoiceCommand(self.voicesynthetizer)
            self.voicecommand.listen()
        elif module == 'voiceapp':
            self.voiceapp = VoiceApp(self.voicesynthetizer)
            self.voiceapp.application()
        elif module == 'voicemail':
            self.voicemail = VoiceMail(self.voicesynthetizer)
            self.voicemail.run(dtmf)
        elif module == 'wolframalpha':
            self.wolframalpha = WolframAlpha(self.voicesynthetizer)
            self.wolframalpha.ask()

        # SS Activated Modules

        # Experimental Modules

        elif module == 'aprstt':
            self.aprstt = Aprstt(self.voicesynthetizer)
            self.aprstt.query(dtmf)
        elif module == 'seismology':
            self.seismology = Seismology(self.voicesynthetizer)
            self.seismology.SismologicoMX()
        elif module == 'morselearn':
            self.morseteacher = MorseTeacher(self.voicesynthetizer)
            self.morseteacher.learn()
        elif module == 'morsecontest'	:
            self.morseteacher = MorseTeacher(self.voicesynthetizer)
            self.morseteacher.contest()
	elif module == 'regulations':
            self.messages = Messages(self.voicesynthetizer)
            self.messages.readfile('learning/reglamentos.1')
	elif module == 'radioclub':
            self.messages = Messages(self.voicesynthetizer)
            self.messages.readfile('learning/arej.radioclubs')
        elif module == 'stations':
            self.messages = Messages(self.voicesynthetizer)
            self.messages.stations()
        elif module == 'sstv':
            self.sstv = SSTV(self.voicesynthetizer)
            self.sstv.decode()
        elif module == 'assistant':
            self.assistant = Assistant(self.voicesynthetizer)
            self.assistant.demo1()
        elif module == 'voicebackground':
            self.voicecommand = VoiceCommand(self.voicesynthetizer)
            self.voicecommand.background()
        elif module == 'voiceexperimental':
            self.voiceexperimental = VoiceExperimental(self.voicesynthetizer)
            self.voiceexperimental.listen()
        elif module == 'voicemailer':
            self.voicemailer = VoiceMailer(self.voicesynthetizer)
            self.voicemailer.attend(dtmf)
        else:
            self.voicesynthetizer.speechit("No hemos implementado tu comando! Lo siento!")

        self.disable()