def main():
    global assistant

    pixels.wakeup()

    #    GPIO.setmode(GPIO.BCM)
    #    GPIO.setup(PIN_LAMP, GPIO.OUT)
    #    for p in PIN_BUTTON:
    #        GPIO.setup(p, GPIO.IN, GPIO.PUD_UP)
    #        if p == 13: # toggle button
    #            GPIO.add_event_detect(p, GPIO.BOTH, callback=procButton, \
    #                    bouncetime=BOUNCE_MSEC)
    #        else:
    #            GPIO.add_event_detect(p, GPIO.FALLING, callback=procButton, \
    #                    bouncetime=BOUNCE_MSEC)

    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawTextHelpFormatter)
    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('--device_model_id',
                        type=str,
                        metavar='DEVICE_MODEL_ID',
                        required=True,
                        help='The device model ID registered with Google')
    parser.add_argument(
        '--project_id',
        type=str,
        metavar='PROJECT_ID',
        required=False,
        help='The project ID used to register device instances.')
    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))

    with Assistant(credentials, args.device_model_id) as assistant:
        events = assistant.start()

        print('device_model_id:', args.device_model_id + '\n' + 'device_id:',
              assistant.device_id + '\n')

        if args.project_id:
            register_device(args.project_id, credentials, args.device_model_id,
                            assistant.device_id)

        for event in events:
            process_event(event, assistant.device_id)
Beispiel #2
0
def main():
    while (1):
        if (os.system("ping -c 1 " + "google.com")) == 0:
            break

    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawTextHelpFormatter)
    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('--device_model_id',
                        type=str,
                        metavar='DEVICE_MODEL_ID',
                        required=True,
                        help='The device model ID registered with Google')
    parser.add_argument(
        '--project_id',
        type=str,
        metavar='PROJECT_ID',
        required=False,
        help='The project ID used to register device instances.')
    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))

    with Assistant(credentials, args.device_model_id) as assistant:
        events = assistant.start()

        print('device_model_id:', args.device_model_id + '\n' + 'device_id:',
              assistant.device_id + '\n')

        GPIO.setmode(GPIO.BCM)
        GPIO.setup(redP, GPIO.OUT, initial=GPIO.LOW)
        GPIO.setup(blueP, GPIO.OUT, initial=GPIO.LOW)
        GPIO.setup(greenP, GPIO.OUT, initial=GPIO.LOW)

        if args.project_id:
            register_device(args.project_id, credentials, args.device_model_id,
                            assistant.device_id)

        GPIO.output(redP, 1)
        time.sleep(2)
        GPIO.output(redP, 0)

        for event in events:
            process_event(event, assistant.device_id)
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()

    socket_server_obj = socket.socket(socket.AF_INET, socket.SOCK_DGRAM,
                                      socket.IPPROTO_UDP)
    socket_server_obj.bind(('localhost', 6969))
    data, client_address = socket_server_obj.recvfrom(1024)
    print("Received data from Client_address = " + str(client_address))
    smartcities_assistant = MyAssistant(args.credentials, args.device_config,
                                        "smartcitiesandiot", args.project_id,
                                        args.query, args.nickname,
                                        socket_server_obj, client_address)
    smartcities_assistant.start()
Beispiel #4
0
def main():
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawTextHelpFormatter)
    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('--device_model_id', type=str,
                        metavar='DEVICE_MODEL_ID', required=True,
                        help='The device model ID registered with Google')
    parser.add_argument(
        '--project_id',
        type=str,
        metavar='PROJECT_ID',
        required=False,
        help='The project ID used to register device instances.')
    parser.add_argument(
        '-v',
        '--version',
        action='version',
        version='%(prog)s ' +
        Assistant.__version_str__())
    parser.add_argument(
        '-p',
        '--port',
        required=True,
        help='The USB port to connect to the sign over')

    args = parser.parse_args()
    with open(args.credentials, 'r') as f:
        credentials = google.oauth2.credentials.Credentials(token=None,
                                                            **json.load(f))

    print('Starting flipdot')
    global flipapps
    flipapps = FlipApps(args.port)
    flipapps.add_sign('dev', 1, 84, 7)

    with Assistant(credentials, args.device_model_id) as assistant:
        events = assistant.start()

        print('device_model_id:', args.device_model_id + '\n' +
              'device_id:', assistant.device_id + '\n')

        if args.project_id:
            register_device(args.project_id, credentials,
                            args.device_model_id, assistant.device_id)

        for event in events:
            process_event(event, assistant.device_id)
Beispiel #5
0
def main():
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawTextHelpFormatter)
    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('--device_model_id',
                        type=str,
                        metavar='DEVICE_MODEL_ID',
                        required=True,
                        help='The device model ID registered with Google')
    parser.add_argument(
        '--project_id',
        type=str,
        metavar='PROJECT_ID',
        required=False,
        help='The project ID used to register device instances.')
    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))

    parent_conn, child_conn = Pipe()
    parent_conn2, child_conn2 = Pipe()
    #    p = Process(target=f, args=(child_conn,))
    #    p.start()
    #    p2 = Process(target=assistant_process, args=(parent_conn2, credentials, args,))
    #    p2.start()
    start_server = websockets.serve(
        functools.partial(handler,
                          parent_conn=parent_conn,
                          child_conn2=child_conn2), '127.0.0.1', 8765)

    t = threading.Thread(target=assistant_process,
                         args=(
                             parent_conn2,
                             credentials,
                             args,
                         ))
    t.start()

    asyncio.get_event_loop().run_until_complete(start_server)
    asyncio.get_event_loop().run_forever()
Beispiel #6
0
def main():
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawTextHelpFormatter)
    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('--device_model_id',
                        type=str,
                        metavar='DEVICE_MODEL_ID',
                        required=True,
                        help='The device model ID registered with Google')
    parser.add_argument(
        '--project_id',
        type=str,
        metavar='PROJECT_ID',
        required=False,
        help='The project ID used to register device instances.')
    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))

    with Assistant(credentials, args.device_model_id) as assistant:
        events = assistant.start()

        print('device_model_id:', args.device_model_id + '\n' + 'device_id:',
              assistant.device_id + '\n')

        # setup the PWM for the LED
        GPIO.setmode(GPIO.BOARD)
        GPIO.setup(12, GPIO.OUT)
        global pwm, duty_cycle
        pwm = GPIO.PWM(12, 50)
        pwm.start(duty_cycle)

        if args.project_id:
            register_device(args.project_id, credentials, args.device_model_id,
                            assistant.device_id)

        for event in events:
            process_event(event, assistant.device_id)
Beispiel #7
0
def main():
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument(constants.CREDENTIALS_ARG,
                        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(constants.DEVICE_MODEL_ARG,
                        type=str,
                        metavar='DEVICE_MODEL_ID',
                        required=True,
                        help='The device model ID registered with Google')
    parser.add_argument(
        constants.PROJECT_ARG,
        type=str,
        metavar='PROJECT_ID',
        required=False,
        help='The project ID used to register device instances.')
    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))

    with Assistant(credentials, args.device_model_id) as assistant:
        # Play intro audio
        playWavFile(dir_path + configData[constants.STARTUP_AUDIO_FILE_KEY])
        say(configData[constants.STARTUP_MESSAGE_KEY],
            configData[constants.SAY_FILE_KEY])
        events = assistant.start()

        print('device_model_id:', args.device_model_id + '\n' + 'device_id:',
              assistant.device_id + '\n')

        if args.project_id:
            register_device(args.project_id, credentials, args.device_model_id,
                            assistant.device_id)

        #indicate that we are ready now...
        playWavFile(dir_path +
                    configData[constants.HOTWORD_WAITING_AUDIO_FILE_KEY])
        for event in events:
            process_event(event, assistant.device_id)
def main():
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawTextHelpFormatter)
    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('--device_model_id',
                        type=str,
                        metavar='DEVICE_MODEL_ID',
                        required=True,
                        help='The device model ID registered with Google')

    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))

    # Set up the sound thread
    sound_queue = Queue()
    sound_thread = Process(target=sound_playback_thread, args=(sound_queue, ))
    sound_thread.start()

    # Set up the process that will play sounds for other processes. This
    #   is needed until we get a shared PulseAudio system up and running
    #   s.t. all elements can play their own sounds
    sound_element = Process(target=sound_element_thread, args=(sound_queue, ))
    sound_element.start()

    with Assistant(credentials, args.device_model_id) as assistant:

        # Create our element
        element = Element("voice")

        # Start the assistant
        events = assistant.start()

        for event in events:
            process_event(event, assistant, element, sound_queue)
Beispiel #9
0
        def main():
            parser = argparse.ArgumentParser(
                formatter_class=argparse.RawTextHelpFormatter)
            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(
                '--device_model_id',
                type=str,
                metavar='DEVICE_MODEL_ID',
                required=True,
                help='The device model ID registered with Google.')
            parser.add_argument(
                '--project_id',
                type=str,
                metavar='PROJECT_ID',
                required=False,
                help='The project ID used to register device instances.')
            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))
            with Assistant(credentials, args.device_model_id) as assistant:
                subprocess.Popen([
                    "aplay", "/home/pi/Omega-AI/sample-audio-files/Startup.wav"
                ],
                                 stdin=subprocess.PIPE,
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE)
                events = assistant.start()
                print('device_model_id:',
                      args.device_model_id + '\n' + 'device_id:',
                      assistant.device_id + '\n')
                if args.project_id:
                    register_device(args.project_id, credentials,
                                    args.device_model_id, assistant.device_id)
Beispiel #10
0
def main():
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawTextHelpFormatter)
    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('--device_model_id',
                        type=str,
                        metavar='DEVICE_MODEL_ID',
                        required=True,
                        default='assistantsdk-170114-project-diva-jy6ql4',
                        help='The device model ID registered with Google')
    parser.add_argument(
        '--project_id',
        type=str,
        metavar='PROJECT_ID',
        required=False,
        default='',
        help='The project ID used to register device instances.')
    parser.add_argument('-v',
                        '--version',
                        action='version',
                        version='%(prog)s ' + Assistant.__version_str__())
    args = parser.parse_args()

    assistant = MyAssistant(args.credentials, args.project_id,
                            args.device_model_id)

    assistant.start()

    while True:
        m = input()
        try:
            m = COMMANDS[m]
        except:
            pass
        assistant.send_text(m)
Beispiel #11
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('--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(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()
Beispiel #13
0
    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()
Beispiel #14
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__())

    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)
Beispiel #15
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:
        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)
Beispiel #16
0
def main():
    init_pubnub()
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawTextHelpFormatter)
    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('--device_model_id', type=str,
                        metavar='DEVICE_MODEL_ID', required=True,
                        help='The device model ID registered with Google.')
    parser.add_argument(
        '--project_id',
        type=str,
        metavar='PROJECT_ID',
        required=False,
        help='The project ID used to register device instances.')
    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))
    with Assistant(credentials, args.device_model_id) as assistant:
        subprocess.Popen(["aplay", "/home/pi/GassistPi-IT/sample-audio-files/Startup.wav"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        events = assistant.start()
        print('device_model_id:', args.device_model_id + '\n' +
              'device_id:', assistant.device_id + '\n')
        if args.project_id:
            register_device(args.project_id, credentials,
                            args.device_model_id, assistant.device_id)
        for event in events:
            process_event(event, assistant.device_id)
            usrcmd=event.args
            with open('/home/pi/GassistPi-IT/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 'lampadina'.lower() in str(usrcmd).lower():		
                assistant.stop_conversation()
                if 'accendi'.lower() in str(usrcmd).lower():
                    url = ''
                    r = requests.post(url, data="")
                    say("Lampadina Accesa")
                elif 'spegni'.lower() in str(usrcmd).lower():
                    url = ''
                    r = requests.post(url, data="")
                    say("Lampadina Spenta")        
            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 'avvia'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                os.system('pkill mpv')
                if os.path.isfile("/home/pi/GassistPi-IT/src/trackchange.py"):
                    os.system('rm /home/pi/GassistPi-IT/src/trackchange.py')
                    if 'autoplay'.lower() in str(usrcmd).lower():
                        os.system('echo "from actions import youtubeplayer\n\n" >> /home/pi/GassistPi-IT/src/trackchange.py')
                        os.system('echo "youtubeplayer()\n" >> /home/pi/GassistPi-IT/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-IT/src/trackchange.py')
                        os.system('echo "youtubeplayer()\n" >> /home/pi/GassistPi-IT/src/trackchange.py')
                        YouTube_Autoplay(str(usrcmd).lower())
                    else:
                        YouTube_No_Autoplay(str(usrcmd).lower())

            if 'ferma'.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-IT/src/trackchange.py"):
                    os.system('rm /home/pi/GassistPi-IT/src/trackchange.py')
                    gmusicselect(str(usrcmd).lower())
                else:
                    gmusicselect(str(usrcmd).lower())
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
Beispiel #18
0
    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()
Beispiel #19
0
    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()
Beispiel #20
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:
        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]
Beispiel #21
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:
        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('--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)
Beispiel #23
0
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)
Beispiel #24
0
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)
Beispiel #25
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)
Beispiel #26
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

    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
Beispiel #27
0
    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)