Skip to content
This repository was archived by the owner on Oct 19, 2023. It is now read-only.

Commit 8e1c653

Browse files
committed
Replaces raw JSON output with a more user-friendly output
Developers can still get verbose JSON printing with `--verbose` Bug: 67062248 Change-Id: I804f7e47febfb10b4e6caa39ee3a972f4f874cdb
1 parent 4a176c4 commit 8e1c653

File tree

1 file changed

+63
-17
lines changed

1 file changed

+63
-17
lines changed

google-assistant-sdk/googlesamples/assistant/grpc/devicetool.py

Lines changed: 63 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
"""Sample that implements device registration for the Google Assistant API."""
1616

1717
import json
18+
import logging
1819
import os
1920

2021
import click
@@ -40,6 +41,27 @@ def failed_request_exception(message, r):
4041
r.text))
4142

4243

44+
# Prints out a device model in the terminal by parsing dict
45+
def pretty_print_model(devicemodel):
46+
PRETTY_PRINT_MODEL = """Device Model Id: %(deviceModelId)s
47+
Project Id: %(projectId)s
48+
Device Type: %(deviceType)s"""
49+
logging.info(PRETTY_PRINT_MODEL % devicemodel)
50+
for trait in devicemodel['traits']:
51+
logging.info(' Trait %s' % trait)
52+
logging.info('') # Newline
53+
54+
55+
# Prints out a device instance in the terminal by parsing dict
56+
def pretty_print_device(device):
57+
logging.info('Device Instance Id: %s' % device['id'])
58+
if 'nickname' in device:
59+
logging.info(' Nickname: %s' % device['nickname'])
60+
if 'modelId' in device:
61+
logging.info(' Model: %s' % device['modelId'])
62+
logging.info('') # Newline
63+
64+
4365
@click.group()
4466
@click.option('--project',
4567
help='Enter the Google Developer Project ID that you want to '
@@ -56,6 +78,8 @@ def failed_request_exception(message, r):
5678
'tool will look for this file in the current directory (by '
5779
'searching for a file named after the client_id stored in the '
5880
'credentials file).')
81+
@click.option('--verbose', flag_value=True,
82+
help='Shows detailed JSON response')
5983
@click.option('--api-endpoint', default='embeddedassistant.googleapis.com',
6084
show_default=True,
6185
help='Hostname for the Google Assistant API. Do not use this '
@@ -70,7 +94,7 @@ def failed_request_exception(message, r):
7094
'API. You can use this flag if the credentials were generated '
7195
'in a location that is different than the default.')
7296
@click.pass_context
73-
def cli(ctx, project, client_secret, api_endpoint, credentials):
97+
def cli(ctx, project, client_secret, verbose, api_endpoint, credentials):
7498
try:
7599
with open(credentials, 'r') as f:
76100
c = google.oauth2.credentials.Credentials(token=None,
@@ -90,16 +114,18 @@ def cli(ctx, project, client_secret, api_endpoint, credentials):
90114
project = secret['installed']['project_id']
91115
except Exception as e:
92116
raise click.ClickException('Error loading client secret: %s.\n'
93-
'Run the register tool'
117+
'Run the register tool '
94118
'with --client-secret '
95119
'or --project option.\n'
96-
'Or copy the %s file'
120+
'Or copy the %s file '
97121
'in the current directory.'
98122
% (e, client_secret))
99123
ctx.obj['SESSION'] = google.auth.transport.requests.AuthorizedSession(c)
100124
ctx.obj['API_URL'] = ('https://%s/v1alpha2/projects/%s'
101125
% (api_endpoint, project))
102126
ctx.obj['PROJECT_ID'] = project
127+
logging.basicConfig(format='',
128+
level=logging.DEBUG if verbose else logging.INFO)
103129

104130

105131
@cli.command()
@@ -204,18 +230,20 @@ def register_model(ctx, model, type, trait,
204230
payload.setdefault('manifest', {})['productName'] = product_name
205231
if description:
206232
payload.setdefault('manifest', {})['deviceDescription'] = description
233+
logging.debug(json.dumps(payload))
207234
r = session.get(model_url)
235+
logging.debug(r.text)
208236
if r.status_code == 200:
209-
click.echo('updating existing device model: %s' % model)
237+
click.echo('Updating existing device model: %s' % model)
210238
r = session.put(model_url, data=json.dumps(payload))
211239
elif r.status_code in (400, 404):
212-
click.echo('creating new device model')
240+
click.echo('Creating new device model')
213241
r = session.post(model_base_url, data=json.dumps(payload))
214242
else:
215-
raise failed_request_exception('failed to check existing model', r)
243+
raise failed_request_exception('Unknown error occurred', r)
216244
if r.status_code != 200:
217-
raise failed_request_exception('failed to register model', r)
218-
click.echo(r.text)
245+
raise failed_request_exception('Failed to register model', r)
246+
click.echo('Model %s successfully registered' % model)
219247

220248

221249
@cli.command('register-device')
@@ -248,19 +276,21 @@ def register_device(ctx, device, model, nickname):
248276
if nickname:
249277
payload['nickname'] = nickname
250278

279+
logging.debug(json.dumps(payload))
251280
r = session.get(device_url)
252281
if r.status_code == 200:
253-
click.echo('updating existing device: %s' % device)
282+
click.echo('Updating existing device: %s' % device)
254283
session.delete(device_url)
255284
r = session.post(device_base_url, data=json.dumps(payload))
256285
elif r.status_code in (400, 404):
257-
click.echo('creating new device')
286+
click.echo('Creating new device')
258287
r = session.post(device_base_url, data=json.dumps(payload))
259288
else:
260-
raise failed_request_exception('failed to check existing device', r)
289+
raise failed_request_exception('Failed to check existing device', r)
261290
if r.status_code != 200:
262-
raise failed_request_exception('failed to register device', r)
263-
click.echo(r.text)
291+
raise failed_request_exception('Failed to register device', r)
292+
click.echo('Device instance %s successfully registered' % device)
293+
logging.debug(r.text)
264294

265295

266296
@cli.command()
@@ -275,11 +305,18 @@ def get(ctx, resource, id):
275305
instance.
276306
"""
277307
session = ctx.obj['SESSION']
308+
278309
url = '/'.join([ctx.obj['API_URL'], resource, id])
279310
r = session.get(url)
280311
if r.status_code != 200:
281-
raise failed_request_exception('failed to get resource', r)
282-
click.echo(r.text)
312+
raise failed_request_exception('Failed to get resource', r)
313+
314+
response = json.loads(r.text)
315+
if resource == 'deviceModels':
316+
pretty_print_model(response)
317+
elif resource == 'devices':
318+
pretty_print_device(response)
319+
logging.debug(r.text)
283320

284321

285322
@cli.command()
@@ -292,11 +329,20 @@ def list(ctx, resource):
292329
devicetool's --project flag.
293330
"""
294331
session = ctx.obj['SESSION']
332+
295333
url = '/'.join([ctx.obj['API_URL'], resource])
296334
r = session.get(url)
297335
if r.status_code != 200:
298-
raise failed_request_exception('failed to list resources', r)
299-
click.echo(r.text)
336+
raise failed_request_exception('Failed to list resources', r)
337+
338+
response = json.loads(r.text)
339+
logging.debug(r.text)
340+
if resource == 'deviceModels':
341+
for devicemodel in response['deviceModels']:
342+
pretty_print_model(devicemodel)
343+
elif resource == 'devices':
344+
for device in response['devices']:
345+
pretty_print_device(device)
300346

301347

302348
def main():

0 commit comments

Comments
 (0)