-
Notifications
You must be signed in to change notification settings - Fork 147
/
AssistantActivity.java
366 lines (334 loc) · 15.2 KB
/
AssistantActivity.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
/*
* Copyright 2017, The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.androidthings.assistant;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.media.AudioDeviceInfo;
import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import com.example.androidthings.assistant.EmbeddedAssistant.ConversationCallback;
import com.example.androidthings.assistant.EmbeddedAssistant.RequestCallback;
import com.google.android.things.contrib.driver.button.Button;
import com.google.android.things.contrib.driver.voicehat.Max98357A;
import com.google.android.things.contrib.driver.voicehat.VoiceHat;
import com.google.android.things.pio.Gpio;
import com.google.android.things.pio.PeripheralManager;
import com.google.assistant.embedded.v1alpha2.SpeechRecognitionResult;
import com.google.auth.oauth2.UserCredentials;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
public class AssistantActivity extends Activity implements Button.OnButtonEventListener {
private static final String TAG = AssistantActivity.class.getSimpleName();
// Peripheral and drivers constants.
private static final int BUTTON_DEBOUNCE_DELAY_MS = 20;
// Default on using the Voice Hat on Raspberry Pi 3.
private static final boolean USE_VOICEHAT_I2S_DAC = Build.DEVICE.equals(BoardDefaults.DEVICE_RPI3);
// Audio constants.
private static final String PREF_CURRENT_VOLUME = "current_volume";
private static final int SAMPLE_RATE = 16000;
private static final int DEFAULT_VOLUME = 100;
// Assistant SDK constants.
private static final String DEVICE_MODEL_ID = "PLACEHOLDER";
private static final String DEVICE_INSTANCE_ID = "PLACEHOLDER";
private static final String LANGUAGE_CODE = "en-US";
// Hardware peripherals.
private Button mButton;
private android.widget.Button mButtonWidget;
private Gpio mLed;
private Max98357A mDac;
private Handler mMainHandler;
// List & adapter to store and display the history of Assistant Requests.
private EmbeddedAssistant mEmbeddedAssistant;
private ArrayList<String> mAssistantRequests = new ArrayList<>();
private ArrayAdapter<String> mAssistantRequestsAdapter;
private CheckBox mHtmlOutputCheckbox;
private WebView mWebView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "starting assistant demo");
setContentView(R.layout.activity_main);
final ListView assistantRequestsListView = findViewById(R.id.assistantRequestsListView);
mAssistantRequestsAdapter =
new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,
mAssistantRequests);
assistantRequestsListView.setAdapter(mAssistantRequestsAdapter);
mHtmlOutputCheckbox = findViewById(R.id.htmlOutput);
mHtmlOutputCheckbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean useHtml) {
mWebView.setVisibility(useHtml ? View.VISIBLE : View.GONE);
assistantRequestsListView.setVisibility(useHtml ? View.GONE : View.VISIBLE);
mEmbeddedAssistant.setResponseFormat(useHtml
? EmbeddedAssistant.HTML : EmbeddedAssistant.TEXT);
}
});
mWebView = findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mMainHandler = new Handler(getMainLooper());
mButtonWidget = findViewById(R.id.assistantQueryButton);
mButtonWidget.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
mEmbeddedAssistant.startConversation();
}
});
// Audio routing configuration: use default routing.
AudioDeviceInfo audioInputDevice = null;
AudioDeviceInfo audioOutputDevice = null;
if (USE_VOICEHAT_I2S_DAC) {
audioInputDevice = findAudioDevice(AudioManager.GET_DEVICES_INPUTS, AudioDeviceInfo.TYPE_BUS);
if (audioInputDevice == null) {
Log.e(TAG, "failed to find I2S audio input device, using default");
}
audioOutputDevice = findAudioDevice(AudioManager.GET_DEVICES_OUTPUTS, AudioDeviceInfo.TYPE_BUS);
if (audioOutputDevice == null) {
Log.e(TAG, "failed to found I2S audio output device, using default");
}
}
try {
if (USE_VOICEHAT_I2S_DAC) {
Log.i(TAG, "initializing DAC trigger");
mDac = VoiceHat.openDac();
mDac.setSdMode(Max98357A.SD_MODE_SHUTDOWN);
mButton = VoiceHat.openButton();
mLed = VoiceHat.openLed();
} else {
PeripheralManager pioManager = PeripheralManager.getInstance();
mButton = new Button(BoardDefaults.getGPIOForButton(),
Button.LogicState.PRESSED_WHEN_LOW);
mLed = pioManager.openGpio(BoardDefaults.getGPIOForLED());
}
mButton.setDebounceDelay(BUTTON_DEBOUNCE_DELAY_MS);
mButton.setOnButtonEventListener(this);
mLed.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW);
mLed.setActiveType(Gpio.ACTIVE_HIGH);
} catch (IOException e) {
Log.e(TAG, "error configuring peripherals:", e);
return;
}
// Set volume from preferences
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
int initVolume = preferences.getInt(PREF_CURRENT_VOLUME, DEFAULT_VOLUME);
Log.i(TAG, "setting audio track volume to: " + initVolume);
UserCredentials userCredentials = null;
try {
userCredentials =
EmbeddedAssistant.generateCredentials(this, R.raw.credentials);
} catch (IOException | JSONException e) {
Log.e(TAG, "error getting user credentials", e);
}
mEmbeddedAssistant = new EmbeddedAssistant.Builder()
.setCredentials(userCredentials)
.setDeviceInstanceId(DEVICE_INSTANCE_ID)
.setDeviceModelId(DEVICE_MODEL_ID)
.setLanguageCode(LANGUAGE_CODE)
.setAudioInputDevice(audioInputDevice)
.setAudioOutputDevice(audioOutputDevice)
.setAudioSampleRate(SAMPLE_RATE)
.setAudioVolume(initVolume)
.setRequestCallback(new RequestCallback() {
@Override
public void onRequestStart() {
Log.i(TAG, "starting assistant request, enable microphones");
mButtonWidget.setText(R.string.button_listening);
mButtonWidget.setEnabled(false);
}
@Override
public void onSpeechRecognition(List<SpeechRecognitionResult> results) {
for (final SpeechRecognitionResult result : results) {
Log.i(TAG, "assistant request text: " + result.getTranscript() +
" stability: " + Float.toString(result.getStability()));
mAssistantRequestsAdapter.add(result.getTranscript());
}
}
})
.setConversationCallback(new ConversationCallback() {
@Override
public void onResponseStarted() {
super.onResponseStarted();
// When bus type is switched, the AudioManager needs to reset the stream volume
if (mDac != null) {
try {
mDac.setSdMode(Max98357A.SD_MODE_LEFT);
} catch (IOException e) {
Log.e(TAG, "error enabling DAC", e);
}
}
}
@Override
public void onResponseFinished() {
super.onResponseFinished();
if (mDac != null) {
try {
mDac.setSdMode(Max98357A.SD_MODE_SHUTDOWN);
} catch (IOException e) {
Log.e(TAG, "error disabling DAC", e);
}
}
if (mLed != null) {
try {
mLed.setValue(false);
} catch (IOException e) {
Log.e(TAG, "cannot turn off LED", e);
}
}
}
@Override
public void onError(Throwable throwable) {
Log.e(TAG, "assist error: " + throwable.getMessage(), throwable);
}
@Override
public void onVolumeChanged(int percentage) {
Log.i(TAG, "assistant volume changed: " + percentage);
// Update our shared preferences
Editor editor = PreferenceManager
.getDefaultSharedPreferences(AssistantActivity.this)
.edit();
editor.putInt(PREF_CURRENT_VOLUME, percentage);
editor.apply();
}
@Override
public void onConversationFinished() {
Log.i(TAG, "assistant conversation finished");
mButtonWidget.setText(R.string.button_new_request);
mButtonWidget.setEnabled(true);
}
@Override
public void onAssistantResponse(final String response) {
if(!response.isEmpty()) {
mMainHandler.post(new Runnable() {
@Override
public void run() {
mAssistantRequestsAdapter.add("Google Assistant: " + response);
}
});
}
}
@Override
public void onAssistantDisplayOut(final String html) {
mMainHandler.post(new Runnable() {
@Override
public void run() {
// Need to convert to base64
try {
final byte[] data = html.getBytes("UTF-8");
final String base64String =
Base64.encodeToString(data, Base64.DEFAULT);
mWebView.loadData(base64String, "text/html; charset=utf-8",
"base64");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
});
}
public void onDeviceAction(String intentName, JSONObject parameters) {
if (parameters != null) {
Log.d(TAG, "Get device action " + intentName + " with parameters: " +
parameters.toString());
} else {
Log.d(TAG, "Get device action " + intentName + " with no paramete"
+ "rs");
}
if (intentName.equals("action.devices.commands.OnOff")) {
try {
boolean turnOn = parameters.getBoolean("on");
mLed.setValue(turnOn);
} catch (JSONException e) {
Log.e(TAG, "Cannot get value of command", e);
} catch (IOException e) {
Log.e(TAG, "Cannot set value of LED", e);
}
}
}
})
.build();
mEmbeddedAssistant.connect();
}
private AudioDeviceInfo findAudioDevice(int deviceFlag, int deviceType) {
AudioManager manager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
AudioDeviceInfo[] adis = manager.getDevices(deviceFlag);
for (AudioDeviceInfo adi : adis) {
if (adi.getType() == deviceType) {
return adi;
}
}
return null;
}
@Override
public void onButtonEvent(Button button, boolean pressed) {
try {
if (mLed != null) {
mLed.setValue(pressed);
}
} catch (IOException e) {
Log.d(TAG, "error toggling LED:", e);
}
if (pressed) {
mEmbeddedAssistant.startConversation();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.i(TAG, "destroying assistant demo");
if (mLed != null) {
try {
mLed.close();
} catch (IOException e) {
Log.w(TAG, "error closing LED", e);
}
mLed = null;
}
if (mButton != null) {
try {
mButton.close();
} catch (IOException e) {
Log.w(TAG, "error closing button", e);
}
mButton = null;
}
if (mDac != null) {
try {
mDac.close();
} catch (IOException e) {
Log.w(TAG, "error closing voice hat trigger", e);
}
mDac = null;
}
mEmbeddedAssistant.destroy();
}
}