def _run_task(self): with open(self.credentials, 'r') as f: credentials = google.oauth2.credentials.Credentials(token=None, **json.load(f)) device_model_id = None last_device_id = None try: with open(self.device_config) as f: device_config = json.load(f) device_model_id = device_config['model_id'] last_device_id = device_config.get('last_device_id', None) except FileNotFoundError: pass if not self.device_model_id and not device_model_id: raise Exception('Missing --device-model-id option') # Re-register if "device_model_id" is given by the user and it differs # from what we previously registered with. should_register = (self.device_model_id and self.device_model_id != device_model_id) device_model_id = self.device_model_id or device_model_id with Assistant(credentials, device_model_id) as assistant: events = assistant.start() device_id = assistant.device_id print('device_model_id:', device_model_id) print('device_id:', device_id + '\n') # Re-register if "device_id" is different from the last "device_id": if should_register or (device_id != last_device_id): if self.project_id: register_device(self.project_id, credentials, device_model_id, device_id, self.nickname) pathlib.Path(os.path.dirname( self.device_config)).mkdir(exist_ok=True) with open(self.device_config, 'w') as f: json.dump( { 'last_device_id': device_id, 'model_id': device_model_id, }, f) else: print(WARNING_NOT_REGISTERED) for event in events: if event.type == EventType.ON_START_FINISHED and self.query: assistant.send_text_query(self.query) self._process_event(event)
def main(self): parser = argparse.ArgumentParser( formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('--device-model-id', '--device_model_id', type=str, metavar='DEVICE_MODEL_ID', required=False, help='the device model ID registered with Google') parser.add_argument('--project-id', '--project_id', type=str, metavar='PROJECT_ID', required=False, help='the project ID used to register this device') parser.add_argument('--device-config', type=str, metavar='DEVICE_CONFIG_FILE', default=os.path.join( os.path.expanduser('~/.config'), 'googlesamples-assistant', 'device_config_library.json'), help='path to store and read device configuration') parser.add_argument('--credentials', type=existing_file, metavar='OAUTH2_CREDENTIALS_FILE', default=os.path.join( os.path.expanduser('~/.config'), 'google-oauthlib-tool', 'credentials.json'), help='path to store and read OAuth2 credentials') parser.add_argument('-v', '--version', action='version', version='%(prog)s ' + Assistant.__version_str__()) args = parser.parse_args() with open(args.credentials, 'r') as f: credentials = google.oauth2.credentials.Credentials(token=None, **json.load(f)) device_model_id = None last_device_id = None try: with open(args.device_config) as f: device_config = json.load(f) device_model_id = device_config['model_id'] last_device_id = device_config.get('last_device_id', None) except FileNotFoundError: pass if not args.device_model_id and not device_model_id: raise Exception('Missing --device-model-id option') # Re-register if "device_model_id" is given by the user and it differs # from what we previously registered with. should_register = (args.device_model_id and args.device_model_id != device_model_id) device_model_id = args.device_model_id or device_model_id with Assistant(credentials, device_model_id) as assistant: self.assistant = assistant subprocess.Popen( ["aplay", "/home/pi/GassistPi/sample-audio-files/Startup.wav"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) events = assistant.start() device_id = assistant.device_id print('device_model_id:', device_model_id) print('device_id:', device_id + '\n') # Re-register if "device_id" is different from the last "device_id": if should_register or (device_id != last_device_id): if args.project_id: register_device(args.project_id, credentials, device_model_id, device_id) pathlib.Path(os.path.dirname( args.device_config)).mkdir(exist_ok=True) with open(args.device_config, 'w') as f: json.dump( { 'last_device_id': device_id, 'model_id': device_model_id, }, f) else: print(WARNING_NOT_REGISTERED) for event in events: self.process_event(event) usrcmd = event.args with open('/home/pi/GassistPi/src/diyHue/config.json', 'r') as config: hueconfig = json.load(config) for i in range(1, len(hueconfig['lights']) + 1): try: if str(hueconfig['lights'][str(i)] ['name']).lower() in str(usrcmd).lower(): assistant.stop_conversation() hue_control( str(usrcmd).lower(), str(i), str(hueconfig['lights_address'][str(i)]['ip'])) break except Keyerror: say('Unable to help, please check your config file') for num, name in enumerate(tasmota_devicelist): if name.lower() in str(usrcmd).lower(): assistant.stop_conversation() tasmota_control( str(usrcmd).lower(), name.lower(), tasmota_deviceip[num]) break if commands['magic_mirror']['name'].lower() in str( usrcmd).lower(): assistant.stop_conversation() self.magic_mirror_treatment(usrcmd) if 'ingredients'.lower() in str(usrcmd).lower(): assistant.stop_conversation() ingrequest = str(usrcmd).lower() ingredientsidx = ingrequest.find('for') ingrequest = ingrequest[ingredientsidx:] ingrequest = ingrequest.replace('for', "", 1) ingrequest = ingrequest.replace("'}", "", 1) ingrequest = ingrequest.strip() ingrequest = ingrequest.replace(" ", "%20", 1) getrecipe(ingrequest) if 'kickstarter'.lower() in str(usrcmd).lower(): assistant.stop_conversation() kickstarter_tracker(str(usrcmd).lower()) if 'trigger'.lower() in str(usrcmd).lower(): assistant.stop_conversation() Action(str(usrcmd).lower()) if 'stream'.lower() in str(usrcmd).lower(): assistant.stop_conversation() vlcplayer.stop_vlc() if 'autoplay'.lower() in str(usrcmd).lower(): YouTube_Autoplay(str(usrcmd).lower()) else: YouTube_No_Autoplay(str(usrcmd).lower()) if 'stop'.lower() in str(usrcmd).lower(): stop() if 'radio'.lower() in str(usrcmd).lower(): assistant.stop_conversation() radio(str(usrcmd).lower()) if 'wireless'.lower() in str(usrcmd).lower(): assistant.stop_conversation() ESP(str(usrcmd).lower()) if 'parcel'.lower() in str(usrcmd).lower(): assistant.stop_conversation() track() if 'feed'.lower() in str(usrcmd).lower() or 'quote'.lower( ) in str(usrcmd).lower(): assistant.stop_conversation() feed(str(usrcmd).lower()) if 'on kodi'.lower() in str(usrcmd).lower(): assistant.stop_conversation() kodiactions(str(usrcmd).lower()) # Google Assistant now comes built in with chromecast control, so custom function has been commented # if 'chromecast'.lower() in str(usrcmd).lower(): # assistant.stop_conversation() # if 'play'.lower() in str(usrcmd).lower(): # chromecast_play_video(str(usrcmd).lower()) # else: # chromecast_control(usrcmd) if 'pause music'.lower() in str(usrcmd).lower( ) or 'resume music'.lower() in str(usrcmd).lower(): assistant.stop_conversation() if vlcplayer.is_vlc_playing(): if 'pause music'.lower() in str(usrcmd).lower(): vlcplayer.pause_vlc() if checkvlcpaused(): if 'resume music'.lower() in str(usrcmd).lower(): vlcplayer.play_vlc() elif vlcplayer.is_vlc_playing( ) == False and checkvlcpaused() == False: say("Sorry nothing is playing right now") if 'play next'.lower() in str(usrcmd).lower( ) or 'play next track'.lower() in str(usrcmd).lower( ) or 'play next song'.lower() in str(usrcmd).lower(): assistant.stop_conversation() if vlcplayer.is_vlc_playing() or checkvlcpaused() == True: vlcplayer.stop_vlc() vlcplayer.change_media_next() elif vlcplayer.is_vlc_playing( ) == False and checkvlcpaused() == False: say("Sorry nothing is playing right now") if 'play previous'.lower() in str(usrcmd).lower( ) or 'play previous track'.lower() in str(usrcmd).lower( ) or 'play previous song'.lower() in str(usrcmd).lower(): assistant.stop_conversation() if vlcplayer.is_vlc_playing() or checkvlcpaused() == True: vlcplayer.stop_vlc() vlcplayer.change_media_previous() elif vlcplayer.is_vlc_playing( ) == False and checkvlcpaused() == False: say("Sorry nothing is playing right now") if 'music volume'.lower() in str(usrcmd).lower(): assistant.stop_conversation() if vlcplayer.is_vlc_playing() == True or checkvlcpaused( ) == True: if 'set'.lower() in str(usrcmd).lower( ) or 'change'.lower() in str(usrcmd).lower(): if 'hundred'.lower() in str(usrcmd).lower( ) or 'maximum' in str(usrcmd).lower(): settingvollevel = 100 with open('/home/pi/.mediavolume.json', 'w') as vol: json.dump(settingvollevel, vol) elif 'zero'.lower() in str(usrcmd).lower( ) or 'minimum' in str(usrcmd).lower(): settingvollevel = 0 with open('/home/pi/.mediavolume.json', 'w') as vol: json.dump(settingvollevel, vol) else: for settingvollevel in re.findall( r"[-+]?\d*\.\d+|\d+", str(usrcmd)): with open('/home/pi/.mediavolume.json', 'w') as vol: json.dump(settingvollevel, vol) print('Setting volume to: ' + str(settingvollevel)) vlcplayer.set_vlc_volume(int(settingvollevel)) elif 'increase'.lower() in str(usrcmd).lower( ) or 'decrease'.lower() in str(usrcmd).lower( ) or 'reduce'.lower() in str(usrcmd).lower(): if os.path.isfile("/home/pi/.mediavolume.json"): with open('/home/pi/.mediavolume.json', 'r') as vol: oldvollevel = json.load(vol) for oldvollevel in re.findall( r'\b\d+\b', str(oldvollevel)): oldvollevel = int(oldvollevel) else: oldvollevel = vlcplayer.get_vlc_volume for oldvollevel in re.findall( r"[-+]?\d*\.\d+|\d+", str(output)): oldvollevel = int(oldvollevel) if 'increase'.lower() in str(usrcmd).lower(): if any(char.isdigit() for char in str(usrcmd)): for changevollevel in re.findall( r'\b\d+\b', str(usrcmd)): changevollevel = int(changevollevel) else: changevollevel = 10 newvollevel = oldvollevel + changevollevel print(newvollevel) if int(newvollevel) > 100: settingvollevel == 100 elif int(newvollevel) < 0: settingvollevel == 0 else: settingvollevel = newvollevel with open('/home/pi/.mediavolume.json', 'w') as vol: json.dump(settingvollevel, vol) print('Setting volume to: ' + str(settingvollevel)) vlcplayer.set_vlc_volume(int(settingvollevel)) if 'decrease'.lower() in str(usrcmd).lower( ) or 'reduce'.lower() in str(usrcmd).lower(): if any(char.isdigit() for char in str(usrcmd)): for changevollevel in re.findall( r'\b\d+\b', str(usrcmd)): changevollevel = int(changevollevel) else: changevollevel = 10 newvollevel = oldvollevel - changevollevel print(newvollevel) if int(newvollevel) > 100: settingvollevel == 100 elif int(newvollevel) < 0: settingvollevel == 0 else: settingvollevel = newvollevel with open('/home/pi/.mediavolume.json', 'w') as vol: json.dump(settingvollevel, vol) print('Setting volume to: ' + str(settingvollevel)) vlcplayer.set_vlc_volume(int(settingvollevel)) else: say("Sorry I could not help you") else: say("Sorry nothing is playing right now") if 'refresh'.lower() in str(usrcmd).lower() and 'music'.lower( ) in str(usrcmd).lower(): assistant.stop_conversation() refreshlists() if 'google music'.lower() in str(usrcmd).lower(): assistant.stop_conversation() vlcplayer.stop_vlc() gmusicselect(str(usrcmd).lower()) if 'spotify'.lower() in str(usrcmd).lower(): assistant.stop_conversation() vlcplayer.stop_vlc() spotify_playlist_select(str(usrcmd).lower()) if custom_wakeword: self.detector.terminate()
def main(): with open('args.json') as f: data = json.load(f) # parser = argparse.ArgumentParser( # formatter_class=argparse.RawTextHelpFormatter) # parser.add_argument('--device-model-id', '--device_model_id', type=str, # metavar='DEVICE_MODEL_ID', required=False, # help='the device model ID registered with Google') # parser.add_argument('--project-id', '--project_id', type=str, # metavar='PROJECT_ID', required=False, # help='the project ID used to register this device') # parser.add_argument('--device-config', type=str, # metavar='DEVICE_CONFIG_FILE', # default=os.path.join( # os.path.expanduser('~/.config'), # 'googlesamples-assistant', # 'device_config_library.json' # ), # help='path to store and read device configuration') # parser.add_argument('--credentials', type=existing_file, # metavar='OAUTH2_CREDENTIALS_FILE', # default=os.path.join( # os.path.expanduser('~/.config'), # 'google-oauthlib-tool', # 'credentials.json' # ), # help='path to store and read OAuth2 credentials') # parser.add_argument('-v', '--version', action='version', # version='%(prog)s ' + Assistant.__version_str__()) # args = parser.parse_args() with open( os.path.join(os.path.expanduser('~/.config'), 'google-oauthlib-tool', 'credentials.json'), 'r') as f: credentials = google.oauth2.credentials.Credentials(token=None, **json.load(f)) device_model_id = None last_device_id = None try: with open( os.path.join(os.path.expanduser('~/.config'), 'googlesamples-assistant', 'device_config_library.json')) as f: device_config = json.load(f) device_model_id = device_config['model_id'] last_device_id = device_config.get('last_device_id', None) except FileNotFoundError: pass if not data["device-model-id"] and not device_model_id: raise Exception('Missing --device-model-id option') # Re-register if "device_model_id" is given by the user and it differs # from what we previously registered with. should_register = (data["device-model-id"] and data["device-model-id"] != device_model_id) device_model_id = data["device-model-id"] or device_model_id deviceConfig = os.path.join(os.path.expanduser('~/.config'), 'googlesamples-assistant', 'device_config_library.json') with Assistant(credentials, device_model_id) as assistant: events = assistant.start() print("events is of type " + str(type(events))) device_id = assistant.device_id print('device_model_id:', device_model_id) print('device_id:', device_id + '\n') # Re-register if "device_id" is different from the last "device_id": if should_register or (device_id != last_device_id): if data['project-id']: register_device(data['project-id'], credentials, device_model_id, device_id) pathlib.Path( os.path.dirname(deviceConfig)).mkdir(exist_ok=True) with open(deviceConfig, 'w') as f: json.dump( { 'last_device_id': device_id, 'model_id': device_model_id, }, f) else: print(WARNING_NOT_REGISTERED) for event in events: print("event is of type " + str(type(event))) process_event(event)
def main(): parser = argparse.ArgumentParser( formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('--device-model-id', '--device_model_id', type=str, metavar='DEVICE_MODEL_ID', required=False, help='the device model ID registered with Google') parser.add_argument('--project-id', '--project_id', type=str, metavar='PROJECT_ID', required=False, help='the project ID used to register this device') parser.add_argument('--device-config', type=str, metavar='DEVICE_CONFIG_FILE', default=os.path.join(os.path.expanduser('~/.config'), 'googlesamples-assistant', 'device_config_library.json'), help='path to store and read device configuration') parser.add_argument('--credentials', type=existing_file, metavar='OAUTH2_CREDENTIALS_FILE', default=os.path.join(os.path.expanduser('~/.config'), 'google-oauthlib-tool', 'credentials.json'), help='path to store and read OAuth2 credentials') parser.add_argument('-v', '--version', action='version', version='%(prog)s ' + Assistant.__version_str__()) args = parser.parse_args() with open(args.credentials, 'r') as f: credentials = google.oauth2.credentials.Credentials(token=None, **json.load(f)) device_model_id = None last_device_id = None try: with open(args.device_config) as f: device_config = json.load(f) device_model_id = device_config['model_id'] last_device_id = device_config.get('last_device_id', None) except FileNotFoundError: pass if not args.device_model_id and not device_model_id: raise Exception('Missing --device-model-id option') # Re-register if "device_model_id" is given by the user and it differs # from what we previously registered with. should_register = (args.device_model_id and args.device_model_id != device_model_id) device_model_id = args.device_model_id or device_model_id with Assistant(credentials, device_model_id) as assistant: events = assistant.start() device_id = assistant.device_id print('device_model_id:', device_model_id) print('device_id:', device_id + '\n') # Re-register if "device_id" is different from the last "device_id": if should_register or (device_id != last_device_id): if args.project_id: register_device(args.project_id, credentials, device_model_id, device_id) pathlib.Path(os.path.dirname( args.device_config)).mkdir(exist_ok=True) with open(args.device_config, 'w') as f: json.dump( { 'last_device_id': device_id, 'model_id': device_model_id, }, f) else: print(WARNING_NOT_REGISTERED) pixel_ring.off() for event in events: process_event(event) usrcmd = event.args if "update yourself" in str(usrcmd).lower(): assistant.stop_conversation() process = subprocess.Popen( ["git", "-C", "~/piassistant", "pull"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout = process.communicate()[0] print(stdout) subprocess.call( ["sudo", "systemctl", "restart", "piassistant.service"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) if "turn" and "on" and "pc" in str(usrcmd).lower(): assistant.stop_conversation() subprocess.call(["wakeonlan", "D0:50:99:1B:03:5D"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
device_model_id = device_info['model_id'] last_device_id = device_info.get('last_device_id', None) else: device_model_id = sys.argv[3] last_device_id = None # run assistant print("Run Google Assistant SDK") with Assistant(credentials, device_model_id) as assistant: events = assistant.start() device_id = assistant.device_id print("device_model_id: {}".format(device_model_id)) print("device_id: {}".format(device_id)) # Register device if last_device_id != device_id: register_device(sys.argv[2], credentials, device_model_id, device_id) with device_json.open('w') as dev_file: json.dump( { 'last_device_id': device_id, 'model_id': device_model_id, }, dev_file) for event in events: process_event(event) print("Close Google Assistant SDK")
def main(self): parser = argparse.ArgumentParser( formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('--device-model-id', '--device_model_id', type=str, metavar='DEVICE_MODEL_ID', required=False, help='the device model ID registered with Google') parser.add_argument('--project-id', '--project_id', type=str, metavar='PROJECT_ID', required=False, help='the project ID used to register this device') parser.add_argument('--nickname', type=str, metavar='NICKNAME', required=False, help='the nickname used to register this device') parser.add_argument('--device-config', type=str, metavar='DEVICE_CONFIG_FILE', default=os.path.join( os.path.expanduser('~/.config'), 'googlesamples-assistant', 'device_config_library.json'), help='path to store and read device configuration') parser.add_argument('--credentials', type=existing_file, metavar='OAUTH2_CREDENTIALS_FILE', default=os.path.join( os.path.expanduser('~/.config'), 'google-oauthlib-tool', 'credentials.json'), help='path to store and read OAuth2 credentials') parser.add_argument( '--query', type=str, metavar='QUERY', help='query to send as soon as the Assistant starts') parser.add_argument('-v', '--version', action='version', version='%(prog)s ' + Assistant.__version_str__()) args = parser.parse_args() with open(args.credentials, 'r') as f: credentials = google.oauth2.credentials.Credentials(token=None, **json.load(f)) device_model_id = None last_device_id = None try: with open(args.device_config) as f: device_config = json.load(f) device_model_id = device_config['model_id'] last_device_id = device_config.get('last_device_id', None) except FileNotFoundError: pass if not args.device_model_id and not device_model_id: raise Exception('Missing --device-model-id option') # Re-register if "device_model_id" is given by the user and it differs # from what we previously registered with. should_register = (args.device_model_id and args.device_model_id != device_model_id) device_model_id = args.device_model_id or device_model_id with Assistant(credentials, device_model_id) as assistant: self.assistant = assistant if gender == 'Male': subprocess.Popen([ "aplay", "{}/sample-audio-files/Startup-Male.wav".format(ROOT_PATH) ], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) else: subprocess.Popen([ "aplay", "{}/sample-audio-files/Startup-Female.wav".format( ROOT_PATH) ], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) events = assistant.start() device_id = assistant.device_id print('device_model_id:', device_model_id) print('device_id:', device_id + '\n') # Re-register if "device_id" is different from the last "device_id": if should_register or (device_id != last_device_id): if args.project_id: register_device(args.project_id, credentials, device_model_id, device_id, args.nickname) pathlib.Path(os.path.dirname( args.device_config)).mkdir(exist_ok=True) with open(args.device_config, 'w') as f: json.dump( { 'last_device_id': device_id, 'model_id': device_model_id, }, f) else: print(WARNING_NOT_REGISTERED) for event in events: if event.type == EventType.ON_START_FINISHED and args.query: assistant.send_text_query(args.query) self.process_event(event) if custom_wakeword: self.detector.terminate()
def main(): init_pubnub() parser = argparse.ArgumentParser( formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('--device-model-id', '--device_model_id', type=str, metavar='DEVICE_MODEL_ID', required=False, help='the device model ID registered with Google') parser.add_argument('--project-id', '--project_id', type=str, metavar='PROJECT_ID', required=False, help='the project ID used to register this device') parser.add_argument('--device-config', type=str, metavar='DEVICE_CONFIG_FILE', default=os.path.join(os.path.expanduser('~/.config'), 'googlesamples-assistant', 'device_config_library.json'), help='path to store and read device configuration') parser.add_argument('--credentials', type=existing_file, metavar='OAUTH2_CREDENTIALS_FILE', default=os.path.join(os.path.expanduser('~/.config'), 'google-oauthlib-tool', 'credentials.json'), help='path to store and read OAuth2 credentials') parser.add_argument('-v', '--version', action='version', version='%(prog)s ' + Assistant.__version_str__()) args = parser.parse_args() with open(args.credentials, 'r') as f: credentials = google.oauth2.credentials.Credentials(token=None, **json.load(f)) device_model_id = None last_device_id = None try: with open(args.device_config) as f: device_config = json.load(f) device_model_id = device_config['model_id'] last_device_id = device_config.get('last_device_id', None) except FileNotFoundError: pass if not args.device_model_id and not device_model_id: raise Exception('Missing --device-model-id option') # Re-register if "device_model_id" is given by the user and it differs # from what we previously registered with. should_register = (args.device_model_id and args.device_model_id != device_model_id) device_model_id = args.device_model_id or device_model_id with Assistant(credentials, device_model_id) as assistant: #adding startup sound subprocess.Popen(["aplay", audiodir + "Startup.wav"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) events = assistant.start() device_id = assistant.device_id print('device_model_id:', device_model_id) print('device_id:', device_id + '\n') # Re-register if "device_id" is different from the last "device_id": if should_register or (device_id != last_device_id): if args.project_id: register_device(args.project_id, credentials, device_model_id, device_id) pathlib.Path(os.path.dirname( args.device_config)).mkdir(exist_ok=True) with open(args.device_config, 'w') as f: json.dump( { 'last_device_id': device_id, 'model_id': device_model_id, }, f) else: print(WARNING_NOT_REGISTERED) for event in events: process_event(event) #----------------------- music control for lms usrcmd = event.args if ('stop music').lower() in str(usrcmd).lower() or ( 'music stop').lower() in str(usrcmd).lower(): assistant.stop_conversation() lmsstop() if ('play music').lower() in str(usrcmd).lower() or ( 'music play').lower() in str(usrcmd).lower(): assistant.stop_conversation() lmsplay() if ('next song').lower() in str(usrcmd).lower() or ( 'next track').lower() in str(usrcmd).lower(): assistant.stop_conversation() lmsnext() if ('previous song').lower() in str(usrcmd).lower() or ( 'previous track').lower() in str(usrcmd).lower(): assistant.stop_conversation() lmsprev() ### volume control for lms if ('set music').lower() in str(usrcmd).lower() and ( 'volume to').lower() in str(usrcmd).lower(): for volume in re.findall(r'\b\d+\b', str(usrcmd)): setvol(volume) if ('set music volume to maximum').lower() in str(usrcmd).lower( ) or ('set music volume to 100').lower() in str(usrcmd).lower(): assistant.stop_conversation() volmax() if ('make music louder').lower() in str(usrcmd).lower() or ( 'increase music volume').lower() in str(usrcmd).lower(): assistant.stop_conversation() incvol() if ('make music quiet').lower() in str(usrcmd).lower() or ( 'decrease music volume').lower() in str(usrcmd).lower(): assistant.stop_conversation() decvol() ### homeassistant commands listen if ('room ligh').lower() in str(usrcmd).lower() and ( 'switch').lower() in str(usrcmd).lower(): assistant.stop_conversation() hass_action_main_light() if ('heat living room').lower() in str(usrcmd).lower() or ( 'increase living room temperature' ).lower() in str(usrcmd).lower(): assistant.stop_conversation() hass_action_ac_heat() if ('turn off living room conditioner').lower() in str( usrcmd).lower() or ('living room air conditioner off' ).lower() in str(usrcmd).lower(): assistant.stop_conversation() hass_action_ac_off() if ('heat bedroom').lower() in str(usrcmd).lower() or ( 'increase bedroom temperature' ).lower() in str(usrcmd).lower(): assistant.stop_conversation() hass_action_ac_heat_bed() if ('turn off bedroom conditioner').lower() in str( usrcmd).lower() or ('bedroom air conditioner off' ).lower() in str(usrcmd).lower(): assistant.stop_conversation() hass_action_ac_off_bed() ### magic mirror on/off if ('mirror off').lower() in str(usrcmd).lower() or ( 'go away').lower() in str(usrcmd).lower(): assistant.stop_conversation() subprocess.call( 'XAUTHORITY=~pi/.Xauthority DISPLAY=:0 xset dpms force on && xset -dpms && xset s off', shell=True) if ('mirror on').lower() in str(usrcmd).lower() or ( 'wake up').lower() in str(usrcmd).lower(): assistant.stop_conversation() subprocess.call( 'XAUTHORITY=~pi/.Xauthority DISPLAY=:0 xset dpms force on && xset -dpms && xset s off', shell=True)
def main(self): parser = argparse.ArgumentParser( formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('--device-model-id', '--device_model_id', type=str, metavar='DEVICE_MODEL_ID', required=False, help='the device model ID registered with Google') parser.add_argument('--project-id', '--project_id', type=str, metavar='PROJECT_ID', required=False, help='the project ID used to register this device') parser.add_argument('--device-config', type=str, metavar='DEVICE_CONFIG_FILE', default=os.path.join( os.path.expanduser('~/.config'), 'googlesamples-assistant', 'device_config_library.json'), help='path to store and read device configuration') parser.add_argument('--credentials', type=existing_file, metavar='OAUTH2_CREDENTIALS_FILE', default=os.path.join( os.path.expanduser('~/.config'), 'google-oauthlib-tool', 'credentials.json'), help='path to store and read OAuth2 credentials') parser.add_argument('-v', '--version', action='version', version='%(prog)s ' + Assistant.__version_str__()) args = parser.parse_args() with open(args.credentials, 'r') as f: credentials = google.oauth2.credentials.Credentials(token=None, **json.load(f)) device_model_id = None last_device_id = None try: with open(args.device_config) as f: device_config = json.load(f) device_model_id = device_config['model_id'] last_device_id = device_config.get('last_device_id', None) except FileNotFoundError: pass if not args.device_model_id and not device_model_id: raise Exception('Missing --device-model-id option') # Re-register if "device_model_id" is given by the user and it differs # from what we previously registered with. should_register = (args.device_model_id and args.device_model_id != device_model_id) device_model_id = args.device_model_id or device_model_id with Assistant(credentials, device_model_id) as assistant: self.assistant = assistant subprocess.Popen([ "aplay", "{}/sample-audio-files/Startup.wav".format(ROOT_PATH) ], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) events = assistant.start() device_id = assistant.device_id print('device_model_id:', device_model_id) print('device_id:', device_id + '\n') # Re-register if "device_id" is different from the last "device_id": if should_register or (device_id != last_device_id): if args.project_id: register_device(args.project_id, credentials, device_model_id, device_id) pathlib.Path(os.path.dirname( args.device_config)).mkdir(exist_ok=True) with open(args.device_config, 'w') as f: json.dump( { 'last_device_id': device_id, 'model_id': device_model_id, }, f) else: print(WARNING_NOT_REGISTERED) for event in events: self.process_event(event) usrcmd = event.args with open('{}/src/diyHue/config.json'.format(ROOT_PATH), 'r') as config: hueconfig = json.load(config) for i in range(1, len(hueconfig['lights']) + 1): try: if str(hueconfig['lights'][str(i)] ['name']).lower() in str(usrcmd).lower(): assistant.stop_conversation() hue_control( str(usrcmd).lower(), str(i), str(hueconfig['lights_address'][str(i)]['ip'])) break except Keyerror: say('Unable to help, please check your config file') for num, name in enumerate(tasmota_devicelist): if name.lower() in str(usrcmd).lower(): assistant.stop_conversation() tasmota_control( str(usrcmd).lower(), name.lower(), tasmota_deviceip[num], tasmota_deviceportid[num]) break for i in range(1, numques + 1): try: if str(configuration['Conversation']['question'][i] [0]).lower() in str(usrcmd).lower(): assistant.stop_conversation() selectedans = random.sample( configuration['Conversation']['answer'][i], 1) say(selectedans[0]) break except Keyerror: say('Please check if the number of questions matches the number of answers' ) if Domoticz_Device_Control == True and len( domoticz_devices['result']) > 0: for i in range(0, len(domoticz_devices['result'])): if str( domoticz_devices['result'][i] ['HardwareName']).lower() in str(usrcmd).lower(): assistant.stop_conversation() domoticz_control( i, str(usrcmd).lower(), domoticz_devices['result'][i]['idx'], domoticz_devices['result'][i]['HardwareName']) break if (custom_action_keyword['Keywords']['Magic_mirror'][0] ).lower() in str(usrcmd).lower(): assistant.stop_conversation() try: mmmcommand = str(usrcmd).lower() if 'weather'.lower() in mmmcommand: if 'show'.lower() in mmmcommand: mmreq_one = requests.get( "http://" + mmmip + ":8080/remote?action=SHOW&module=module_2_currentweather" ) mmreq_two = requests.get( "http://" + mmmip + ":8080/remote?action=SHOW&module=module_3_currentweather" ) if 'hide'.lower() in mmmcommand: mmreq_one = requests.get( "http://" + mmmip + ":8080/remote?action=HIDE&module=module_2_currentweather" ) mmreq_two = requests.get( "http://" + mmmip + ":8080/remote?action=HIDE&module=module_3_currentweather" ) if 'power off'.lower() in mmmcommand: mmreq = requests.get( "http://" + mmmip + ":8080/remote?action=SHUTDOWN") if 'reboot'.lower() in mmmcommand: mmreq = requests.get("http://" + mmmip + ":8080/remote?action=REBOOT") if 'restart'.lower() in mmmcommand: mmreq = requests.get("http://" + mmmip + ":8080/remote?action=RESTART") if 'display on'.lower() in mmmcommand: mmreq = requests.get( "http://" + mmmip + ":8080/remote?action=MONITORON") if 'display off'.lower() in mmmcommand: mmreq = requests.get( "http://" + mmmip + ":8080/remote?action=MONITOROFF") except requests.exceptions.ConnectionError: say("Magic mirror not online") if (custom_action_keyword['Keywords']['Recipe_pushbullet'][0] ).lower() in str(usrcmd).lower(): assistant.stop_conversation() ingrequest = str(usrcmd).lower() ingredientsidx = ingrequest.find('for') ingrequest = ingrequest[ingredientsidx:] ingrequest = ingrequest.replace('for', "", 1) ingrequest = ingrequest.replace("'}", "", 1) ingrequest = ingrequest.strip() ingrequest = ingrequest.replace(" ", "%20", 1) getrecipe(ingrequest) if (custom_action_keyword['Keywords']['Kickstarter_tracking'] [0]).lower() in str(usrcmd).lower(): assistant.stop_conversation() kickstarter_tracker(str(usrcmd).lower()) if (custom_action_keyword['Keywords']['Pi_GPIO_control'][0] ).lower() in str(usrcmd).lower(): assistant.stop_conversation() Action(str(usrcmd).lower()) if (custom_action_keyword['Keywords']['YouTube_music_stream'] [0]).lower() in str(usrcmd).lower(): assistant.stop_conversation() vlcplayer.stop_vlc() if 'autoplay'.lower() in str(usrcmd).lower(): YouTube_Autoplay(str(usrcmd).lower()) else: YouTube_No_Autoplay(str(usrcmd).lower()) if (custom_action_keyword['Keywords']['Stop_music'][0] ).lower() in str(usrcmd).lower(): stop() if 'radio'.lower() in str(usrcmd).lower(): assistant.stop_conversation() radio(str(usrcmd).lower()) if (custom_action_keyword['Keywords']['ESP_control'][0] ).lower() in str(usrcmd).lower(): assistant.stop_conversation() ESP(str(usrcmd).lower()) if (custom_action_keyword['Keywords']['Parcel_tracking'][0] ).lower() in str(usrcmd).lower(): assistant.stop_conversation() track() if (custom_action_keyword['Keywords']['RSS'][0] ).lower() in str(usrcmd).lower() or ( custom_action_keyword['Keywords']['RSS'][1] ).lower() in str(usrcmd).lower(): assistant.stop_conversation() feed(str(usrcmd).lower()) if (custom_action_keyword['Keywords']['Kodi_actions'][0] ).lower() in str(usrcmd).lower(): assistant.stop_conversation() kodiactions(str(usrcmd).lower()) # Google Assistant now comes built in with chromecast control, so custom function has been commented # if 'chromecast'.lower() in str(usrcmd).lower(): # assistant.stop_conversation() # if 'play'.lower() in str(usrcmd).lower(): # chromecast_play_video(str(usrcmd).lower()) # else: # chromecast_control(usrcmd) if (custom_action_keyword['Keywords']['Pause_resume'][0] ).lower() in str(usrcmd).lower() or ( custom_action_keyword['Keywords']['Pause_resume'][1] ).lower() in str(usrcmd).lower(): assistant.stop_conversation() if vlcplayer.is_vlc_playing(): if (custom_action_keyword['Keywords']['Pause_resume'] [0]).lower() in str(usrcmd).lower(): vlcplayer.pause_vlc() if checkvlcpaused(): if (custom_action_keyword['Keywords']['Pause_resume'] [1]).lower() in str(usrcmd).lower(): vlcplayer.play_vlc() elif vlcplayer.is_vlc_playing( ) == False and checkvlcpaused() == False: say("Sorry nothing is playing right now") if (custom_action_keyword['Keywords']['Track_change']['Next'] [0]).lower() in str(usrcmd).lower() or ( custom_action_keyword['Keywords']['Track_change'] ['Next'][1]).lower() in str(usrcmd).lower() or ( custom_action_keyword['Keywords']['Track_change'] ['Next'][2]).lower() in str(usrcmd).lower(): assistant.stop_conversation() if vlcplayer.is_vlc_playing() or checkvlcpaused() == True: vlcplayer.stop_vlc() vlcplayer.change_media_next() elif vlcplayer.is_vlc_playing( ) == False and checkvlcpaused() == False: say("Sorry nothing is playing right now") if (custom_action_keyword['Keywords']['Track_change'] ['Previous'][0]).lower() in str(usrcmd).lower() or ( custom_action_keyword['Keywords']['Track_change'] ['Previous'][1]).lower() in str(usrcmd).lower() or ( custom_action_keyword['Keywords']['Track_change'] ['Previous'][2]).lower() in str(usrcmd).lower(): assistant.stop_conversation() if vlcplayer.is_vlc_playing() or checkvlcpaused() == True: vlcplayer.stop_vlc() vlcplayer.change_media_previous() elif vlcplayer.is_vlc_playing( ) == False and checkvlcpaused() == False: say("Sorry nothing is playing right now") if (custom_action_keyword['Keywords']['VLC_music_volume'][0] ).lower() in str(usrcmd).lower(): assistant.stop_conversation() if vlcplayer.is_vlc_playing() == True or checkvlcpaused( ) == True: if 'set'.lower() in str(usrcmd).lower( ) or 'change'.lower() in str(usrcmd).lower(): if 'hundred'.lower() in str(usrcmd).lower( ) or 'maximum' in str(usrcmd).lower(): settingvollevel = 100 with open( '{}/.mediavolume.json'.format( USER_PATH), 'w') as vol: json.dump(settingvollevel, vol) elif 'zero'.lower() in str(usrcmd).lower( ) or 'minimum' in str(usrcmd).lower(): settingvollevel = 0 with open( '{}/.mediavolume.json'.format( USER_PATH), 'w') as vol: json.dump(settingvollevel, vol) else: for settingvollevel in re.findall( r"[-+]?\d*\.\d+|\d+", str(usrcmd)): with open( '{}/.mediavolume.json'.format( USER_PATH), 'w') as vol: json.dump(settingvollevel, vol) print('Setting volume to: ' + str(settingvollevel)) vlcplayer.set_vlc_volume(int(settingvollevel)) elif 'increase'.lower() in str(usrcmd).lower( ) or 'decrease'.lower() in str(usrcmd).lower( ) or 'reduce'.lower() in str(usrcmd).lower(): if os.path.isfile( "{}/.mediavolume.json".format(USER_PATH)): with open( '{}/.mediavolume.json'.format( USER_PATH), 'r') as vol: oldvollevel = json.load(vol) for oldvollevel in re.findall( r'\b\d+\b', str(oldvollevel)): oldvollevel = int(oldvollevel) else: oldvollevel = vlcplayer.get_vlc_volume for oldvollevel in re.findall( r"[-+]?\d*\.\d+|\d+", str(output)): oldvollevel = int(oldvollevel) if 'increase'.lower() in str(usrcmd).lower(): if any(char.isdigit() for char in str(usrcmd)): for changevollevel in re.findall( r'\b\d+\b', str(usrcmd)): changevollevel = int(changevollevel) else: changevollevel = 10 newvollevel = oldvollevel + changevollevel print(newvollevel) if int(newvollevel) > 100: settingvollevel == 100 elif int(newvollevel) < 0: settingvollevel == 0 else: settingvollevel = newvollevel with open( '{}/.mediavolume.json'.format( USER_PATH), 'w') as vol: json.dump(settingvollevel, vol) print('Setting volume to: ' + str(settingvollevel)) vlcplayer.set_vlc_volume(int(settingvollevel)) if 'decrease'.lower() in str(usrcmd).lower( ) or 'reduce'.lower() in str(usrcmd).lower(): if any(char.isdigit() for char in str(usrcmd)): for changevollevel in re.findall( r'\b\d+\b', str(usrcmd)): changevollevel = int(changevollevel) else: changevollevel = 10 newvollevel = oldvollevel - changevollevel print(newvollevel) if int(newvollevel) > 100: settingvollevel == 100 elif int(newvollevel) < 0: settingvollevel == 0 else: settingvollevel = newvollevel with open( '{}/.mediavolume.json'.format( USER_PATH), 'w') as vol: json.dump(settingvollevel, vol) print('Setting volume to: ' + str(settingvollevel)) vlcplayer.set_vlc_volume(int(settingvollevel)) else: say("Sorry I could not help you") else: say("Sorry nothing is playing right now") if (custom_action_keyword['Keywords']['Music_index_refresh'][0] ).lower() in str(usrcmd).lower() and ( custom_action_keyword['Keywords'] ['Music_index_refresh'][1] ).lower() in str(usrcmd).lower(): assistant.stop_conversation() refreshlists() if (custom_action_keyword['Keywords']['Google_music_streaming'] [0]).lower() in str(usrcmd).lower(): assistant.stop_conversation() vlcplayer.stop_vlc() gmusicselect(str(usrcmd).lower()) if (custom_action_keyword['Keywords'] ['Spotify_music_streaming'][0] ).lower() in str(usrcmd).lower(): assistant.stop_conversation() vlcplayer.stop_vlc() spotify_playlist_select(str(usrcmd).lower()) if (custom_action_keyword['Keywords']['Gaana_music_streaming'] [0]).lower() in str(usrcmd).lower(): assistant.stop_conversation() vlcplayer.stop_vlc() gaana_playlist_select(str(usrcmd).lower()) if (custom_action_keyword['Keywords']['Deezer_music_streaming'] [0]).lower() in str(usrcmd).lower(): assistant.stop_conversation() vlcplayer.stop_vlc() deezer_playlist_select(str(usrcmd).lower()) if custom_wakeword: self.detector.terminate()
def main(): print("HOTWORD.PY MAIN ACCESSED.") parser = argparse.ArgumentParser( formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('--device-model-id', '--device_model_id', type=str, metavar='DEVICE_MODEL_ID', required=False, help='the device model ID registered with Google') parser.add_argument('--project-id', '--project_id', type=str, metavar='PROJECT_ID', required=False, help='the project ID used to register this device') parser.add_argument('--device-config', type=str, metavar='DEVICE_CONFIG_FILE', default=os.path.join(os.path.expanduser('~/.config'), 'googlesamples-assistant', 'device_config_library.json'), help='path to store and read device configuration') parser.add_argument('--credentials', type=existing_file, metavar='OAUTH2_CREDENTIALS_FILE', default=os.path.join(os.path.expanduser('~/.config'), 'google-oauthlib-tool', 'credentials.json'), help='path to store and read OAuth2 credentials') parser.add_argument('-v', '--version', action='version', version='%(prog)s ' + Assistant.__version_str__()) args = parser.parse_args() with open(args.credentials, 'r') as f: credentials = google.oauth2.credentials.Credentials(token=None, **json.load(f)) device_model_id = None last_device_id = None try: with open(args.device_config) as f: device_config = json.load(f) device_model_id = device_config['model_id'] last_device_id = device_config.get('last_device_id', None) except FileNotFoundError: pass if not args.device_model_id and not device_model_id: raise Exception('Missing --device-model-id option') # Re-register if "device_model_id" is given by the user and it differs # from what we previously registered with. should_register = (args.device_model_id and args.device_model_id != device_model_id) device_model_id = args.device_model_id or device_model_id with Assistant(credentials, device_model_id) as assistant: events = assistant.start() try: device_id = assistant.device_id print('device_model_id:', device_model_id) print('device_id:', device_id + '\n') # Re-register if "device_id" is different from the last "device_id": if should_register or (device_id != last_device_id): if args.project_id: register_device(args.project_id, credentials, device_model_id, device_id) pathlib.Path(os.path.dirname( args.device_config)).mkdir(exist_ok=True) with open(args.device_config, 'w') as f: json.dump( { 'last_device_id': device_id, 'model_id': device_model_id, }, f) else: print(WARNING_NOT_REGISTERED) # Added 10/14/18 # Control the GPIO pins #GPIO.setmode(GPIO.BOARD) #GPIO.setup(PIN_ON, GPIO.OUT, initial=0) #GPIO.setup(PIN_OFF, GPIO.OUT, initial=0) # END GPIO for event in events: process_event(event) except Exception as e: print("EXIT: %s" % e) exit(0)
def main(): parser = argparse.ArgumentParser( formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('--device-model-id', '--device_model_id', type=str, metavar='DEVICE_MODEL_ID', required=False, help='the device model ID registered with Google') parser.add_argument('--project-id', '--project_id', type=str, metavar='PROJECT_ID', required=False, help='the project ID used to register this device') parser.add_argument('--device-config', type=str, metavar='DEVICE_CONFIG_FILE', default=os.path.join( os.path.expanduser('~/.config'), 'googlesamples-assistant', 'device_config_library.json' ), help='path to store and read device configuration') parser.add_argument('--credentials', type=existing_file, metavar='OAUTH2_CREDENTIALS_FILE', default=os.path.join( os.path.expanduser('~/.config'), 'google-oauthlib-tool', 'credentials.json' ), help='path to store and read OAuth2 credentials') parser.add_argument('-v', '--version', action='version', version='%(prog)s ' + Assistant.__version_str__()) args = parser.parse_args() with open(args.credentials, 'r') as f: credentials = google.oauth2.credentials.Credentials(token=None, **json.load(f)) device_model_id = None last_device_id = None try: with open(args.device_config) as f: device_config = json.load(f) device_model_id = device_config['model_id'] last_device_id = device_config.get('last_device_id', None) except FileNotFoundError: pass if not args.device_model_id and not device_model_id: raise Exception('Missing --device-model-id option') # Re-register if "device_model_id" is given by the user and it differs # from what we previously registered with. should_register = ( args.device_model_id and args.device_model_id != device_model_id) device_model_id = args.device_model_id or device_model_id with Assistant(credentials, device_model_id) as assistant: subprocess.Popen(["aplay", "/home/pi/GassistPi/sample-audio-files/Startup.wav"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) events = assistant.start() device_id = assistant.device_id print('device_model_id:', device_model_id) print('device_id:', device_id + '\n') # Re-register if "device_id" is different from the last "device_id": if should_register or (device_id != last_device_id): if args.project_id: register_device(args.project_id, credentials, device_model_id, device_id) pathlib.Path(os.path.dirname(args.device_config)).mkdir( exist_ok=True) with open(args.device_config, 'w') as f: json.dump({ 'last_device_id': device_id, 'model_id': device_model_id, }, f) else: print(WARNING_NOT_REGISTERED) for event in events: process_event(event) usrcmd=event.args with open('/home/pi/GassistPi/src/diyHue/config.json', 'r') as config: hueconfig = json.load(config) for i in range(1,len(hueconfig['lights'])+1): try: if str(hueconfig['lights'][str(i)]['name']).lower() in str(usrcmd).lower(): assistant.stop_conversation() hue_control(str(usrcmd).lower(),str(i),str(hueconfig['lights_address'][str(i)]['ip'])) break except KeyError: say('Unable to help, please check your config file') for num, name in enumerate(tasmota_devicelist): if name.lower() in str(usrcmd).lower(): assistant.stop_conversation() tasmota_control(str(usrcmd).lower(), name.lower(),tasmota_deviceip[num]) break if 'magic mirror'.lower() in str(usrcmd).lower(): assistant.stop_conversation() try: mmmcommand=str(usrcmd).lower() if 'weather'.lower() in mmmcommand: if 'show'.lower() in mmmcommand: mmreq_one=requests.get("http://"+mmmip+":8080/remote?action=SHOW&module=module_2_currentweather") mmreq_two=requests.get("http://"+mmmip+":8080/remote?action=SHOW&module=module_3_currentweather") if 'hide'.lower() in mmmcommand: mmreq_one=requests.get("http://"+mmmip+":8080/remote?action=HIDE&module=module_2_currentweather") mmreq_two=requests.get("http://"+mmmip+":8080/remote?action=HIDE&module=module_3_currentweather") if 'power off'.lower() in mmmcommand: mmreq=requests.get("http://"+mmmip+":8080/remote?action=SHUTDOWN") if 'reboot'.lower() in mmmcommand: mmreq=requests.get("http://"+mmmip+":8080/remote?action=REBOOT") if 'restart'.lower() in mmmcommand: mmreq=requests.get("http://"+mmmip+":8080/remote?action=RESTART") if 'display on'.lower() in mmmcommand: mmreq=requests.get("http://"+mmmip+":8080/remote?action=MONITORON") if 'display off'.lower() in mmmcommand: mmreq=requests.get("http://"+mmmip+":8080/remote?action=MONITOROFF") except requests.exceptions.ConnectionError: say("Magic mirror not online") if 'ingredients'.lower() in str(usrcmd).lower(): assistant.stop_conversation() ingrequest=str(usrcmd).lower() ingredientsidx=ingrequest.find('for') ingrequest=ingrequest[ingredientsidx:] ingrequest=ingrequest.replace('for',"",1) ingrequest=ingrequest.replace("'}","",1) ingrequest=ingrequest.strip() ingrequest=ingrequest.replace(" ","%20",1) getrecipe(ingrequest) if 'kickstarter'.lower() in str(usrcmd).lower(): assistant.stop_conversation() kickstarter_tracker(str(usrcmd).lower()) if 'trigger'.lower() in str(usrcmd).lower(): assistant.stop_conversation() Action(str(usrcmd).lower()) if 'wireless'.lower() in str(usrcmd).lower(): assistant.stop_conversation() ESP(str(usrcmd).lower()) if 'parcel'.lower() in str(usrcmd).lower(): assistant.stop_conversation() track() if 'news'.lower() in str(usrcmd).lower() or 'feed'.lower() in str(usrcmd).lower() or 'quote'.lower() in str(usrcmd).lower(): assistant.stop_conversation() feed(str(usrcmd).lower()) if 'update'.lower() in str(usrcmd).lower(): assistant.stop_conversation() if 'magic mirror'.lower() in str(usrcmd).lower(): # update magic mirror also pass say("Päivitetään", "fi") subprocess.Popen(["sudo systemctl stop gassistpi-ok-google && git -C /home/pi/GassistPi pull " "&& sudo systemctl start gassistpi-ok-google"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
def main(): parser = argparse.ArgumentParser( formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('--device-model-id', '--device_model_id', type=str, metavar='DEVICE_MODEL_ID', required=False, help='the device model ID registered with Google') parser.add_argument('--project-id', '--project_id', type=str, metavar='PROJECT_ID', required=False, help='the project ID used to register this device') parser.add_argument('--nickname', type=str, metavar='NICKNAME', required=False, help='the nickname used to register this device') parser.add_argument('--device-config', type=str, metavar='DEVICE_CONFIG_FILE', default=os.path.join( os.path.expanduser('~/.config'), 'googlesamples-assistant', 'device_config_library.json' ), help='path to store and read device configuration') parser.add_argument('--credentials', type=existing_file, metavar='OAUTH2_CREDENTIALS_FILE', default=os.path.join( os.path.expanduser('~/.config'), 'google-oauthlib-tool', 'credentials.json' ), help='path to store and read OAuth2 credentials') parser.add_argument('--query', type=str, metavar='QUERY', help='query to send as soon as the Assistant starts') parser.add_argument('-v', '--version', action='version', version='%(prog)s ' + Assistant.__version_str__()) args = parser.parse_args() with open(args.credentials, 'r') as f: credentials = google.oauth2.credentials.Credentials(token=None, **json.load(f)) device_model_id = None last_device_id = None try: with open(args.device_config) as f: device_config = json.load(f) device_model_id = device_config['model_id'] last_device_id = device_config.get('last_device_id', None) except FileNotFoundError: pass if not args.device_model_id and not device_model_id: raise Exception('Missing --device-model-id option') should_register = ( args.device_model_id and args.device_model_id != device_model_id) device_model_id = args.device_model_id or device_model_id note = Notify.Notification.new(Notify.get_app_name(),'Micno with Assistant は動作中です','mic-volume-high') note.set_urgency(Notify.Urgency.NORMAL) note.show() with Assistant(credentials, device_model_id) as assistant: global device_id_global, device_model_id_global events = assistant.start() device_id = assistant.device_id print('device_model_id:', device_model_id) print('device_id:', device_id + '\n') device_id_global = device_id device_model_id_global = device_model_id if should_register or (device_id != last_device_id): if args.project_id: register_device(args.project_id, credentials, device_model_id, device_id, args.nickname) pathlib.Path(os.path.dirname(args.device_config)).mkdir( exist_ok=True) with open(args.device_config, 'w') as f: json.dump({ 'last_device_id': device_id, 'model_id': device_model_id, }, f) else: print(WARNING_NOT_REGISTERED) for event in events: if event.type == EventType.ON_START_FINISHED and args.query: assistant.send_text_query(args.query) process_event(event)
def main(): parser = argparse.ArgumentParser( formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('--device-model-id', '--device_model_id', type=str, metavar='DEVICE_MODEL_ID', required=False, help='the device model ID registered with Google') parser.add_argument('--project-id', '--project_id', type=str, metavar='PROJECT_ID', required=False, help='the project ID used to register this device') parser.add_argument('--device-config', type=str, metavar='DEVICE_CONFIG_FILE', default=os.path.join( os.path.expanduser('~/.config'), 'googlesamples-assistant', 'device_config_library.json' ), help='path to store and read device configuration') parser.add_argument('--credentials', type=existing_file, metavar='OAUTH2_CREDENTIALS_FILE', default=os.path.join( os.path.expanduser('~/.config'), 'google-oauthlib-tool', 'credentials.json' ), help='path to store and read OAuth2 credentials') parser.add_argument('-v', '--version', action='version', version='%(prog)s ' + Assistant.__version_str__()) args = parser.parse_args() with open(args.credentials, 'r') as f: credentials = google.oauth2.credentials.Credentials(token=None, **json.load(f)) device_model_id = None last_device_id = None try: with open(args.device_config) as f: device_config = json.load(f) device_model_id = device_config['model_id'] last_device_id = device_config.get('last_device_id', None) except FileNotFoundError: pass if not args.device_model_id and not device_model_id: raise Exception('Missing --device-model-id option') # Re-register if "device_model_id" is given by the user and it differs # from what we previously registered with. should_register = ( args.device_model_id and args.device_model_id != device_model_id) device_model_id = args.device_model_id or device_model_id with Assistant(credentials, device_model_id) as assistant: events = assistant.start() subprocess.Popen(["omxplayer", "/home/pi/pi_assistant/bin/audio/hangout_message.mp3"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) FANa = 35 GPIO.setup(FANa,GPIO.OUT,initial = 1) FANb = 31 GPIO.setup(FANb,GPIO.OUT, initial = 1) LIGHTa = 33 GPIO.setup(LIGHTa,GPIO.OUT, initial = 1) LIGHTb = 37 GPIO.setup(LIGHTb,GPIO.OUT, initial = 1) appliance = [FANa,FANb,LIGHTa,LIGHTb] switch = 1 device_id = assistant.device_id print('device_model_id:', device_model_id) print('device_id:', device_id + '\n') # Re-register if "device_id" is different from the last "device_id": if should_register or (device_id != last_device_id): if args.project_id: register_device(args.project_id, credentials, device_model_id, device_id) pathlib.Path(os.path.dirname(args.device_config)).mkdir( exist_ok=True) with open(args.device_config, 'w') as f: json.dump({ 'last_device_id': device_id, 'model_id': device_model_id, }, f) else: print(WARNING_NOT_REGISTERED) for event in events: process_event(event) command = event.args try : command = str(command["text"]).lower() except: pass print(command) if command is not None : if 'turn' in command or 'switch' in command or 'start' in command or 'shut' in command: assistant.stop_conversation() if 'on' in command or 'start' in command : switch = 0 elif 'off' or 'stop' in command : switch = 1 if 'bed' in command : appliance = [FANa,LIGHTa] elif 'fan' in command : if ('one' in command) or ('1' in command): appliance = FANa if ('two' in command) or ('2' in command): appliance = FANb elif 'light' in command : if ('one' in command) or ('1' in command): appliance = LIGHTa if ('two' in command) or ('2' in command): appliance = LIGHTb GPIO.output(appliance,switch) appliance = [FANa,FANb,LIGHTa,LIGHTb]
def main(): parser = argparse.ArgumentParser( formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('--device-model-id', '--device_model_id', type=str, metavar='DEVICE_MODEL_ID', required=False, help='the device model ID registered with Google') parser.add_argument('--project-id', '--project_id', type=str, metavar='PROJECT_ID', required=False, help='the project ID used to register this device') parser.add_argument('--device-config', type=str, metavar='DEVICE_CONFIG_FILE', default=os.path.join(os.path.expanduser('~/.config'), 'googlesamples-assistant', 'device_config_library.json'), help='path to store and read device configuration') parser.add_argument('--credentials', type=existing_file, metavar='OAUTH2_CREDENTIALS_FILE', default=os.path.join(os.path.expanduser('~/.config'), 'google-oauthlib-tool', 'credentials.json'), help='path to store and read OAuth2 credentials') parser.add_argument('-v', '--version', action='version', version='%(prog)s ' + Assistant.__version_str__()) args = parser.parse_args() with open(args.credentials, 'r') as f: credentials = google.oauth2.credentials.Credentials(token=None, **json.load(f)) device_model_id = None last_device_id = None try: with open(args.device_config) as f: device_config = json.load(f) device_model_id = device_config['model_id'] last_device_id = device_config.get('last_device_id', None) except FileNotFoundError: pass if not args.device_model_id and not device_model_id: raise Exception('Missing --device-model-id option') # Re-register if "device_model_id" is given by the user and it differs # from what we previously registered with. should_register = (args.device_model_id and args.device_model_id != device_model_id) device_model_id = args.device_model_id or device_model_id with Assistant(credentials, device_model_id) as assistant: subprocess.Popen( ["aplay", "/home/pi/GassistPi/sample-audio-files/Startup.wav"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) events = assistant.start() device_id = assistant.device_id print('device_model_id:', device_model_id) print('device_id:', device_id + '\n') # Re-register if "device_id" is different from the last "device_id": if should_register or (device_id != last_device_id): if args.project_id: register_device(args.project_id, credentials, device_model_id, device_id) pathlib.Path(os.path.dirname( args.device_config)).mkdir(exist_ok=True) with open(args.device_config, 'w') as f: json.dump( { 'last_device_id': device_id, 'model_id': device_model_id, }, f) else: print(WARNING_NOT_REGISTERED) for event in events: process_event(event) usrcmd = event.args with open('/home/pi/GassistPi/src/diyHue/config.json', 'r') as config: hueconfig = json.load(config) for i in range(1, len(hueconfig['lights']) + 1): try: if str(hueconfig['lights'][str(i)]['name']).lower() in str( usrcmd).lower(): assistant.stop_conversation() hue_control( str(usrcmd).lower(), str(i), str(hueconfig['lights_address'][str(i)]['ip'])) break except Keyerror: say('Unable to help, please check your config file') for num, name in enumerate(tasmota_devicelist): if name.lower() in str(usrcmd).lower(): assistant.stop_conversation() tasmota_control( str(usrcmd).lower(), name.lower(), tasmota_deviceip[num]) break if 'magic mirror'.lower() in str(usrcmd).lower(): assistant.stop_conversation() try: mmmcommand = str(usrcmd).lower() if 'weather'.lower() in mmmcommand: if 'show'.lower() in mmmcommand: mmreq_one = requests.get( "http://" + mmmip + ":8080/remote?action=SHOW&module=module_2_currentweather" ) mmreq_two = requests.get( "http://" + mmmip + ":8080/remote?action=SHOW&module=module_3_currentweather" ) if 'hide'.lower() in mmmcommand: mmreq_one = requests.get( "http://" + mmmip + ":8080/remote?action=HIDE&module=module_2_currentweather" ) mmreq_two = requests.get( "http://" + mmmip + ":8080/remote?action=HIDE&module=module_3_currentweather" ) if 'power off'.lower() in mmmcommand: mmreq = requests.get("http://" + mmmip + ":8080/remote?action=SHUTDOWN") if 'reboot'.lower() in mmmcommand: mmreq = requests.get("http://" + mmmip + ":8080/remote?action=REBOOT") if 'restart'.lower() in mmmcommand: mmreq = requests.get("http://" + mmmip + ":8080/remote?action=RESTART") if 'display on'.lower() in mmmcommand: mmreq = requests.get("http://" + mmmip + ":8080/remote?action=MONITORON") if 'display off'.lower() in mmmcommand: mmreq = requests.get("http://" + mmmip + ":8080/remote?action=MONITOROFF") except requests.exceptions.ConnectionError: say("Magic mirror not online") if 'ingredients'.lower() in str(usrcmd).lower(): assistant.stop_conversation() ingrequest = str(usrcmd).lower() ingredientsidx = ingrequest.find('for') ingrequest = ingrequest[ingredientsidx:] ingrequest = ingrequest.replace('for', "", 1) ingrequest = ingrequest.replace("'}", "", 1) ingrequest = ingrequest.strip() ingrequest = ingrequest.replace(" ", "%20", 1) getrecipe(ingrequest) if 'kickstarter'.lower() in str(usrcmd).lower(): assistant.stop_conversation() kickstarter_tracker(str(usrcmd).lower()) if 'trigger'.lower() in str(usrcmd).lower(): assistant.stop_conversation() Action(str(usrcmd).lower()) if 'stream'.lower() in str(usrcmd).lower(): assistant.stop_conversation() os.system('pkill mpv') if os.path.isfile("/home/pi/GassistPi/src/trackchange.py"): os.system('rm /home/pi/GassistPi/src/trackchange.py') if 'autoplay'.lower() in str(usrcmd).lower(): os.system( 'echo "from actions import youtubeplayer\n\n" >> /home/pi/GassistPi/src/trackchange.py' ) os.system( 'echo "youtubeplayer()\n" >> /home/pi/GassistPi/src/trackchange.py' ) YouTube_Autoplay(str(usrcmd).lower()) else: YouTube_No_Autoplay(str(usrcmd).lower()) else: if 'autoplay'.lower() in str(usrcmd).lower(): os.system( 'echo "from actions import youtubeplayer\n\n" >> /home/pi/GassistPi/src/trackchange.py' ) os.system( 'echo "youtubeplayer()\n" >> /home/pi/GassistPi/src/trackchange.py' ) YouTube_Autoplay(str(usrcmd).lower()) else: YouTube_No_Autoplay(str(usrcmd).lower()) if 'stop'.lower() in str(usrcmd).lower(): stop() if 'radio'.lower() in str(usrcmd).lower(): assistant.stop_conversation() radio(str(usrcmd).lower()) if 'wireless'.lower() in str(usrcmd).lower(): assistant.stop_conversation() ESP(str(usrcmd).lower()) if 'parcel'.lower() in str(usrcmd).lower(): assistant.stop_conversation() track() if 'news'.lower() in str(usrcmd).lower() or 'feed'.lower() in str( usrcmd).lower() or 'quote'.lower() in str(usrcmd).lower(): assistant.stop_conversation() feed(str(usrcmd).lower()) if 'on kodi'.lower() in str(usrcmd).lower(): assistant.stop_conversation() kodiactions(str(usrcmd).lower()) if 'chromecast'.lower() in str(usrcmd).lower(): assistant.stop_conversation() if 'play'.lower() in str(usrcmd).lower(): chromecast_play_video(str(usrcmd).lower()) else: chromecast_control(usrcmd) if 'pause music'.lower() in str(usrcmd).lower( ) or 'resume music'.lower() in str(usrcmd).lower(): assistant.stop_conversation() if ismpvplaying(): if 'pause music'.lower() in str(usrcmd).lower(): playstatus = os.system("echo '" + json.dumps( {"command": ["set_property", "pause", True]}) + "' | socat - /tmp/mpvsocket") elif 'resume music'.lower() in str(usrcmd).lower(): playstatus = os.system("echo '" + json.dumps( {"command": ["set_property", "pause", False]}) + "' | socat - /tmp/mpvsocket") else: say("Sorry nothing is playing right now") if 'music volume'.lower() in str(usrcmd).lower(): if ismpvplaying(): if 'set'.lower() in str(usrcmd).lower() or 'change'.lower( ) in str(usrcmd).lower(): if 'hundred'.lower() in str(usrcmd).lower( ) or 'maximum' in str(usrcmd).lower(): settingvollevel = 100 with open('/home/pi/.mediavolume.json', 'w') as vol: json.dump(settingvollevel, vol) mpvsetvol = os.system("echo '" + json.dumps({ "command": [ "set_property", "volume", str(settingvollevel) ] }) + "' | socat - /tmp/mpvsocket") elif 'zero'.lower() in str(usrcmd).lower( ) or 'minimum' in str(usrcmd).lower(): settingvollevel = 0 with open('/home/pi/.mediavolume.json', 'w') as vol: json.dump(settingvollevel, vol) mpvsetvol = os.system("echo '" + json.dumps({ "command": [ "set_property", "volume", str(settingvollevel) ] }) + "' | socat - /tmp/mpvsocket") else: for settingvollevel in re.findall( r"[-+]?\d*\.\d+|\d+", str(usrcmd)): with open('/home/pi/.mediavolume.json', 'w') as vol: json.dump(settingvollevel, vol) mpvsetvol = os.system("echo '" + json.dumps({ "command": [ "set_property", "volume", str(settingvollevel) ] }) + "' | socat - /tmp/mpvsocket") elif 'increase'.lower() in str(usrcmd).lower( ) or 'decrease'.lower() in str(usrcmd).lower( ) or 'reduce'.lower() in str(usrcmd).lower(): if os.path.isfile("/home/pi/.mediavolume.json"): with open('/home/pi/.mediavolume.json', 'r') as vol: oldvollevel = json.load(vol) for oldvollevel in re.findall( r'\b\d+\b', str(oldvollevel)): oldvollevel = int(oldvollevel) else: mpvgetvol = subprocess.Popen( [("echo '" + json.dumps( {"command": ["get_property", "volume"]}) + "' | socat - /tmp/mpvsocket")], shell=True, stdout=subprocess.PIPE) output = mpvgetvol.communicate()[0] for oldvollevel in re.findall( r"[-+]?\d*\.\d+|\d+", str(output)): oldvollevel = int(oldvollevel) if 'increase'.lower() in str(usrcmd).lower(): if any(char.isdigit() for char in str(usrcmd)): for changevollevel in re.findall( r'\b\d+\b', str(usrcmd)): changevollevel = int(changevollevel) else: changevollevel = 10 newvollevel = oldvollevel + changevollevel print(newvollevel) if newvollevel > 100: settingvollevel == 100 elif newvollevel < 0: settingvollevel == 0 else: settingvollevel = newvollevel with open('/home/pi/.mediavolume.json', 'w') as vol: json.dump(settingvollevel, vol) mpvsetvol = os.system("echo '" + json.dumps({ "command": [ "set_property", "volume", str(settingvollevel) ] }) + "' | socat - /tmp/mpvsocket") if 'decrease'.lower() in str(usrcmd).lower( ) or 'reduce'.lower() in str(usrcmd).lower(): if any(char.isdigit() for char in str(usrcmd)): for changevollevel in re.findall( r'\b\d+\b', str(usrcmd)): changevollevel = int(changevollevel) else: changevollevel = 10 newvollevel = oldvollevel - changevollevel print(newvollevel) if newvollevel > 100: settingvollevel == 100 elif newvollevel < 0: settingvollevel == 0 else: settingvollevel = newvollevel with open('/home/pi/.mediavolume.json', 'w') as vol: json.dump(settingvollevel, vol) mpvsetvol = os.system("echo '" + json.dumps({ "command": [ "set_property", "volume", str(settingvollevel) ] }) + "' | socat - /tmp/mpvsocket") else: say("Sorry I could not help you") else: say("Sorry nothing is playing right now") if 'refresh'.lower() in str( usrcmd).lower() and 'music'.lower() in str(usrcmd).lower(): assistant.stop_conversation() refreshlists() if 'google music'.lower() in str(usrcmd).lower(): assistant.stop_conversation() os.system('pkill mpv') if os.path.isfile("/home/pi/GassistPi/src/trackchange.py"): os.system('rm /home/pi/GassistPi/src/trackchange.py') gmusicselect(str(usrcmd).lower()) else: gmusicselect(str(usrcmd).lower())
def main(self): parser = argparse.ArgumentParser( formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('--device-model-id', '--device_model_id', type=str, metavar='DEVICE_MODEL_ID',default="abcdefghi", required=False, help='the device model ID registered with Google') parser.add_argument('--project-id', '--project_id', type=str, metavar='PROJECT_ID',default="finalassistant", required=False, help='the project ID used to register this device') parser.add_argument('--device-config', type=str, metavar='DEVICE_CONFIG_FILE', default=os.path.join( os.path.expanduser('~/.config'), 'googlesamples-assistant', 'device_config_library.json' ), help='path to store and read device configuration') parser.add_argument('--credentials', type=existing_file, metavar='OAUTH2_CREDENTIALS_FILE', default=os.path.join( os.path.expanduser('~/.config'), 'google-oauthlib-tool', 'credentials.json' ), help='path to store and read OAuth2 credentials') parser.add_argument('-v', '--version', action='version', version='%(prog)s ' + Assistant.__version_str__()) parser.add_argument('-x','--abcd') args = parser.parse_args() with open(args.credentials, 'r') as f: credentials = google.oauth2.credentials.Credentials(token=None, **json.load(f)) device_model_id = None last_device_id = None try: with open(args.device_config) as f: device_config = json.load(f) device_model_id = device_config['model_id'] last_device_id = device_config.get('last_device_id', None) except FileNotFoundError: pass if not args.device_model_id and not device_model_id: raise Exception('Missing --device-model-id option') # Re-register if "device_model_id" is given by the user and it differs # from what we previously registered with. should_register = ( args.device_model_id and args.device_model_id != device_model_id) device_model_id = args.device_model_id or device_model_id with Assistant(credentials, device_model_id) as assistant: self.assistant = assistant self.actions = Actions(self.assistant) events = self.assistant.start() device_id = assistant.device_id print('device_model_id:', device_model_id) print('device_id:', device_id + '\n') # Re-register if "device_id" is different from the last "device_id": if should_register or (device_id != last_device_id): if args.project_id: register_device(args.project_id, credentials, device_model_id, device_id) pathlib.Path(os.path.dirname(args.device_config)).mkdir( exist_ok=True) with open(args.device_config, 'w') as f: json.dump({ 'last_device_id': device_id, 'model_id': device_model_id, }, f) else: print(WARNING_NOT_REGISTERED) self.m = Mode(self) #x = threading.Thread(target=m.start) #x.daemon = True #x.start() for event in events: self.process_event(event) self.m.changeVoiceMode(event)
def main(): parser = argparse.ArgumentParser( formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('--device-model-id', '--device_model_id', type=str, metavar='DEVICE_MODEL_ID', required=False, help='the device model ID registered with Google') parser.add_argument('--project-id', '--project_id', type=str, metavar='PROJECT_ID', required=False, help='the project ID used to register this device') parser.add_argument('--device-config', type=str, metavar='DEVICE_CONFIG_FILE', default=os.path.join(os.path.expanduser('~/.config'), 'googlesamples-assistant', 'device_config_library.json'), help='path to store and read device configuration') parser.add_argument('--credentials', type=existing_file, metavar='OAUTH2_CREDENTIALS_FILE', default=os.path.join(os.path.expanduser('~/.config'), 'google-oauthlib-tool', 'credentials.json'), help='path to store and read OAuth2 credentials') parser.add_argument('-v', '--version', action='version', version='%(prog)s ' + Assistant.__version_str__()) parser.add_argument('--logfile', type=str, required=False, help='file to write the log to') parser.add_argument('--home_control_credentials', type=str, required=True, help='path of home control credentials') args = parser.parse_args() if args.logfile: sys.stdout = sys.stderr = Logger(args.logfile) with open(args.credentials, 'r') as f: credentials = google.oauth2.credentials.Credentials(token=None, **json.load(f)) device_model_id = None last_device_id = None try: with open(args.device_config) as f: device_config = json.load(f) device_model_id = device_config['model_id'] last_device_id = device_config.get('last_device_id', None) except FileNotFoundError: pass if not args.device_model_id and not device_model_id: raise Exception('Missing --device-model-id option') # Re-register if "device_model_id" is given by the user and it differs # from what we previously registered with. should_register = (args.device_model_id and args.device_model_id != device_model_id) device_model_id = args.device_model_id or device_model_id with Assistant(credentials, device_model_id) as assistant: events = assistant.start() device_id = assistant.device_id log({ "type": "starting up", "device_model_id": device_model_id, "device_id": device_id }) # Re-register if "device_id" is different from the last "device_id": if should_register or (device_id != last_device_id): if args.project_id: register_device(args.project_id, credentials, device_model_id, device_id) pathlib.Path(os.path.dirname( args.device_config)).mkdir(exist_ok=True) with open(args.device_config, 'w') as f: json.dump( { 'last_device_id': device_id, 'model_id': device_model_id, }, f) else: print(WARNING_NOT_REGISTERED) setup_controllers(args.home_control_credentials) setup_speech(assistant) for event in events: process_event(event)
def main(): parser = argparse.ArgumentParser( formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('--device-model-id', '--device_model_id', type=str, metavar='DEVICE_MODEL_ID', required=False, help='the device model ID registered with Google') parser.add_argument('--project-id', '--project_id', type=str, metavar='PROJECT_ID', required=False, help='the project ID used to register this device') parser.add_argument('--device-config', type=str, metavar='DEVICE_CONFIG_FILE', default=os.path.join(os.path.expanduser('~/.config'), 'googlesamples-assistant', 'device_config_library.json'), help='path to store and read device configuration') parser.add_argument('--credentials', type=existing_file, metavar='OAUTH2_CREDENTIALS_FILE', default=os.path.join(os.path.expanduser('~/.config'), 'google-oauthlib-tool', 'credentials.json'), help='path to store and read OAuth2 credentials') parser.add_argument('-v', '--version', action='version', version='%(prog)s ' + Assistant.__version_str__()) args = parser.parse_args() with open(args.credentials, 'r') as f: credentials = google.oauth2.credentials.Credentials(token=None, **json.load(f)) device_model_id = None last_device_id = None try: with open(args.device_config) as f: device_config = json.load(f) device_model_id = device_config['model_id'] last_device_id = device_config.get('last_device_id', None) except FileNotFoundError: pass if not args.device_model_id and not device_model_id: raise Exception('Missing --device-model-id option') # Re-register if "device_model_id" is given by the user and it differs # from what we previously registered with. should_register = (args.device_model_id and args.device_model_id != device_model_id) device_model_id = args.device_model_id or device_model_id with Assistant(credentials, device_model_id) as assistant: events = assistant.start() device_id = assistant.device_id print('device_model_id:', device_model_id) print('device_id:', device_id + '\n') # Re-register if "device_id" is different from the last "device_id": if should_register or (device_id != last_device_id): if args.project_id: register_device(args.project_id, credentials, device_model_id, device_id) pathlib.Path(os.path.dirname( args.device_config)).mkdir(exist_ok=True) with open(args.device_config, 'w') as f: json.dump( { 'last_device_id': device_id, 'model_id': device_model_id, }, f) else: print(WARNING_NOT_REGISTERED) assistant.set_mic_mute(True) class BroadcastMessage(Resource): def get(self): message = request.args.get('message', default='This is a test!') text_query = 'broadcast ' + message assistant.send_text_query(text_query) return {'status': 'OK'} api.add_resource(BroadcastMessage, '/broadcast_message') class Command(Resource): def get(self): message = request.args.get('message', default='This is a test!') assistant.send_text_query(message) return {'status': 'OK'} api.add_resource(Command, '/command') server = threading.Thread(target=start_server, args=()) server.setDaemon(True) server.start() for event in events: process_event(event)
def main(): parser = argparse.ArgumentParser( formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('--device-model-id', '--device_model_id', type=str, metavar='DEVICE_MODEL_ID', required=False, help='the device model ID registered with Google') parser.add_argument('--project-id', '--project_id', type=str, metavar='PROJECT_ID', required=False, help='the project ID used to register this device') parser.add_argument('--nickname', type=str, metavar='NICKNAME', required=False, help='the nickname used to register this device') parser.add_argument('--device-config', type=str, metavar='DEVICE_CONFIG_FILE', default=os.path.join(os.path.expanduser('~/.config'), 'googlesamples-assistant', 'device_config_library.json'), help='path to store and read device configuration') parser.add_argument('--credentials', type=existing_file, metavar='OAUTH2_CREDENTIALS_FILE', default=os.path.join(os.path.expanduser('~/.config'), 'google-oauthlib-tool', 'credentials.json'), help='path to store and read OAuth2 credentials') parser.add_argument('--lang', type=str, metavar='LANGUAGE_CODE', default='en-US', required=False, help='Language code of the Assistant') parser.add_argument('--query', type=str, metavar='QUERY', help='query to send as soon as the Assistant starts') parser.add_argument('-v', '--version', action='version', version='%(prog)s ' + Assistant.__version_str__()) args = parser.parse_args() with open(args.credentials, 'r') as f: credentials = google.oauth2.credentials.Credentials(token=None, **json.load(f)) device_model_id = None last_device_id = None try: with open(args.device_config) as f: device_config = json.load(f) device_model_id = device_config['model_id'] last_device_id = device_config.get('last_device_id', None) except FileNotFoundError: pass if not args.device_model_id and not device_model_id: raise Exception('Missing --device-model-id option') # Re-register if "device_model_id" is given by the user and it differs # from what we previously registered with. should_register = (args.device_model_id and args.device_model_id != device_model_id) device_model_id = args.device_model_id or device_model_id new_assistant = init_assistant(device_model_id=device_model_id, project_id=args.project_id) with Assistant(credentials, device_model_id) as assistant: events = assistant.start() device_id = assistant.device_id print('device_model_id:', device_model_id) print('device_id:', device_id + '\n') # Re-register if "device_id" is different from the last "device_id": if should_register or (device_id != last_device_id): if args.project_id: register_device(args.project_id, credentials, device_model_id, device_id, args.nickname) pathlib.Path(os.path.dirname( args.device_config)).mkdir(exist_ok=True) with open(args.device_config, 'w') as f: json.dump( { 'last_device_id': device_id, 'model_id': device_model_id, }, f) else: print(WARNING_NOT_REGISTERED) for event in events: if event.type == EventType.ON_START_FINISHED and args.query: assistant.send_text_query(args.query) # switching to the new library if event.type == EventType.ON_CONVERSATION_TURN_STARTED: assistant.stop_conversation() new_assistant.assist() process_event(event)
def main(): parser = argparse.ArgumentParser( formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('--device-model-id', '--device_model_id', type=str, metavar='DEVICE_MODEL_ID', required=False, help='the device model ID registered with Google') parser.add_argument('--project-id', '--project_id', type=str, metavar='PROJECT_ID', required=False, help='the project ID used to register this device') parser.add_argument('--nickname', type=str, metavar='NICKNAME', required=False, help='the nickname used to register this device') parser.add_argument('--device-config', type=str, metavar='DEVICE_CONFIG_FILE', default=os.path.join( os.path.expanduser('~/.config'), 'googlesamples-assistant', 'device_config_library.json' ), help='path to store and read device configuration') parser.add_argument('--credentials', type=existing_file, metavar='OAUTH2_CREDENTIALS_FILE', default=os.path.join( os.path.expanduser('~/.config'), 'google-oauthlib-tool', 'credentials.json' ), help='path to store and read OAuth2 credentials') parser.add_argument('--query', type=str, metavar='QUERY', help='query to send as soon as the Assistant starts') parser.add_argument('-v', '--version', action='version', version='%(prog)s ' + Assistant.__version_str__()) args = parser.parse_args() with open(args.credentials, 'r') as f: credentials = google.oauth2.credentials.Credentials(token=None, **json.load(f)) device_model_id = None last_device_id = None try: with open(args.device_config) as f: device_config = json.load(f) device_model_id = device_config['model_id'] last_device_id = device_config.get('last_device_id', None) except FileNotFoundError: pass if not args.device_model_id and not device_model_id: raise Exception('Missing --device-model-id option') # Re-register if "device_model_id" is given by the user and it differs # from what we previously registered with. should_register = ( args.device_model_id and args.device_model_id != device_model_id) device_model_id = args.device_model_id or device_model_id with Assistant(credentials, device_model_id) as assistant: events = assistant.start() device_id = assistant.device_id print('device_model_id:', device_model_id) print('device_id:', device_id + '\n') # Re-register if "device_id" is different from the last "device_id": if should_register or (device_id != last_device_id): if args.project_id: register_device(args.project_id, credentials, device_model_id, device_id, args.nickname) pathlib.Path(os.path.dirname(args.device_config)).mkdir( exist_ok=True) with open(args.device_config, 'w') as f: json.dump({ 'last_device_id': device_id, 'model_id': device_model_id, }, f) else: print(WARNING_NOT_REGISTERED) for event in events: if event.type == EventType.ON_START_FINISHED and args.query: assistant.send_text_query(args.query) process_event(event) try: while True: # Continuous Sensing of Temperature and light sensors. ## Sensing Temperature and humidity [temperature, humidity] = grovepi.dht(digital_humidity_temperature_sensor_port, 0) print("Temperature = %.02f C, Humidity = %.02f %%" % (temperature, humidity)) temperature_humidity_sensor_data['temperature'] = temperature temperature_humidity_sensor_data['humidity'] = humidity # Sensing light threshold. light_sensor_value = grovepi.analogRead(light_sensor_port) resistance = (float)(1023 - light_sensor_value) * 10 / light_sensor_value # Decision making and actuating. if(temperature < 15): plugwise_Circle_1.switch_on() else: plugwise_Circle_1.switch_off() if(resistance > threshold_light_sensor): plugwise_Circle_2.switch_on() grovepi.digitalWrite(indicator_led, 1) # temporary as of now, delete when we have plugwise. else: plugwise_Circle_2.switch_off() grovepi.digitalWrite(indicator_led, 0) # temporary as of now, delete when we have plugwise. #client.publish('v1/devices/me/telemetry', json.dumps(temperature_humidity_sensor_data), 1) #next_reading += INTERVAL #sleep_time = next_reading - time.time() #if sleep_time > 0: # time.sleep(sleep_time) except KeyboardInterrupt: pass
def main(): parser = argparse.ArgumentParser( formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('--device-model-id', '--device_model_id', type=str, metavar='DEVICE_MODEL_ID', required=False, help='the device model ID registered with Google') parser.add_argument('--project-id', '--project_id', type=str, metavar='PROJECT_ID', required=False, help='the project ID used to register this device') parser.add_argument('--device-config', type=str, metavar='DEVICE_CONFIG_FILE', default=os.path.join(os.path.expanduser('~/.config'), 'googlesamples-assistant', 'device_config_library.json'), help='path to store and read device configuration') parser.add_argument('--credentials', type=existing_file, metavar='OAUTH2_CREDENTIALS_FILE', default=os.path.join(os.path.expanduser('~/.config'), 'google-oauthlib-tool', 'credentials.json'), help='path to store and read OAuth2 credentials') parser.add_argument('-v', '--version', action='version', version='%(prog)s ' + Assistant.__version_str__()) args = parser.parse_args() with open(args.credentials, 'r') as f: credentials = google.oauth2.credentials.Credentials(token=None, **json.load(f)) device_model_id = None last_device_id = None try: with open(args.device_config) as f: device_config = json.load(f) device_model_id = device_config['model_id'] last_device_id = device_config.get('last_device_id', None) except FileNotFoundError: pass if not args.device_model_id and not device_model_id: raise Exception('Missing --device-model-id option') # Re-register if "device_model_id" is given by the user and it differs # from what we previously registered with. should_register = (args.device_model_id and args.device_model_id != device_model_id) device_model_id = args.device_model_id or device_model_id while True: with Assistant(credentials, device_model_id) as assistant: events = assistant.start() device_id = assistant.device_id print('device_model_id:', device_model_id) print('device_id:', device_id + '\n') # Re-register if "device_id" is different from the last "device_id": if should_register or (device_id != last_device_id): if args.project_id: register_device(args.project_id, credentials, device_model_id, device_id) pathlib.Path(os.path.dirname( args.device_config)).mkdir(exist_ok=True) with open(args.device_config, 'w') as f: json.dump( { 'last_device_id': device_id, 'model_id': device_model_id, }, f) else: print(WARNING_NOT_REGISTERED) # start smile detection for activating assistant is_smiled = detect_smile() # if smile is detected, start ordering session if is_smiled is True: assistant.set_mic_mute(False) for event in events: is_over = process_event(event, assistant) if is_over: # Restart a new session of ordering break
def main(self): parser = argparse.ArgumentParser( formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('--device-model-id', '--device_model_id', type=str, metavar='DEVICE_MODEL_ID', required=False, help='the device model ID registered with Google') parser.add_argument('--project-id', '--project_id', type=str, metavar='PROJECT_ID', required=False, help="the project ID used to register this device") parser.add_argument('--nickname', type=str, metavar='NICKNAME', required=False, help="the nickname used to register this device") parser.add_argument('--device-config', '--device_config', type=str, metavar='DEVICE_CONFIG_FILE', default="/data/client.json", help="path to store and read OAuth2 credentials") parser.add_argument('--credentials', type=existing_file, metavar='OAUTH2_CREDENTIALS_FILE', default="/data/cred.json", help="path to store and read OAuth2 credentials") parser.add_argument( '--query', type=str, metavar='QUERY', help='query to send as soon as the Assistant starts') parser.add_argument('-v', '--version', action='version', version='%(prog)s ' + Assistant.__version_str__()) args = parser.parse_args() with open(args.credentials, 'r') as f: credentials = google.oauth2.credentials.Credentials(token=None, **json.load(f)) device_model_id = None last_device_id = None try: with open(args.device_config) as f: device_config = json.load(f) device_model_id = device_config['model_id'] last_device_id = device_config.get('last_device_id', None) except FileNotFoundError: print("Device config file not found.") if not args.device_model_id and not device_model_id: raise Exception("Missing --device-model-id option") # Re-register if 'device_model_id" is given by the user and it differs from what we previously registered with. should_register = (args.device_model_id and args.device_model_id != device_model_id) device_model_id = args.device_model_id or device_model_id with Assistant(credentials, device_model_id) as assistant: self.assistant = assistant if gender == 'Male': subprocess.Popen([ 'aplay', "/resources/sample-audio-files/Startup-Male.wav" ], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) else: subprocess.Popen([ 'aplay', "/resources/sample-audio-files/Startup-Female.wav" ], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) events = assistant.start() device_id = assistant.device_id print('device_model_id: ', device_model_id) print('device_id: ', device_id + '\n') # Re-register if 'device_id' is different from the last 'device_id': if should_register or (device_id != last_device_id): if args.project_id: register_device(args.project_id, credentials, device_model_id, device_id, args.nickname) pathlib.Path(os.path.dirname( args.device_config)).mkdir(exist_ok=True) with open(args.device_config, 'w') as f: json.dump( { 'last_device_id': device_id, 'model_id': device_model_id, }, f) else: print(WARNING_NOT_REGISTERED) for event in events: if event.type == EventType.ON_START_FINISHED and args.query: assistant.send_text_query(args.query) self.process_event(event) usr_cmd = event.args if configuration['Conversation'][ 'Conversation_Control'] == 'Enabled': for i in range(1, num_ques + 1): try: if str(configuration['Conversation']['question'][i] [0]).lower() in str(usr_cmd).lower(): assistant.stop_conversation() selected_ans = random.sample( configuration['Conversation']['answer'][i], 1) say(selected_ans[0]) break except KeyError: say('Please check if the number of questions matches the number of answers in your config file' ) if (custom_action_keyword['Keywords']['Magic_mirror'][0] ).lower() in str(usr_cmd).lower(): assistant.stop_conversation() try: mmcommand = str(usr_cmd).lower() if 'weather'.lower() in mmcommand: if 'show'.lower() in mmcommand: mmreq1 = requests.get( "http://" + mmip + ":8080/remote?action=SHOW&module=module_2_currentweather" ) mmreq2 = requests.get( "http://" + mmip + ":8080/remote?action=SHOW&module=module_3_currentweather" ) if 'hide'.lower() in mmcommand: mmreq1 = requests.get( "http://" + mmip + ":8080/remote?action=HIDE&module=module_2_currentweather" ) mmreq2 = requests.get( "http://" + mmip + ":8080/remote?action=HIDE&module=module_3_currentweather" ) if 'power off'.lower() in mmcommand: mmreq = requests.get( "http://" + mmip + ":8080/remote?/action=SHUTDOWN") if 'reboot'.lower() in mmcommand: mmreq = requests.get('http://' + mmip + ":8080/remote?action=REBOOT") if 'restart'.lower() in mmcommand: mmreq = requests.get('http://' + mmip + ":8080/remote?action=RESTART") if 'display on'.lower() in mmcommand: mmreq = requests.get( 'http://' + mmip + ":8080/remote?action=MONITORON") if 'display off'.lower() in mmcommand: mmreq = requests.get( 'http://' + mmip + ":8080/remote?action=MONITOROFF") except requests.exceptions.ConnectionError: say("Magic Mirror is offline") if configuration['Raspberrypi_GPIO_Control'][ 'GPIO_Control'] == 'Enabled': if (custom_action_keyword['Keywords']['Pi_GPIO_control'][0] ).lower() in str(usr_cmd).lower(): assistant.stop_conversation() Action(str(usr_cmd).lower()) if custom_wakeword: self.detector.terminate()