summaryrefslogtreecommitdiff
path: root/javaSE/hello_sdl_java/src/main/java/com/smartdevicelink/java/SdlService.java
blob: 8c5eda17caef3342c057c5ddc08b144cbce2c585 (plain)
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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
/*
 *  Copyright (c) 2019. Livio, Inc.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice, this
 *  list of conditions and the following disclaimer.
 *
 *  Redistributions in binary form must reproduce the above copyright notice,
 *  this list of conditions and the following
 *  disclaimer in the documentation and/or other materials provided with the
 *  distribution.
 *
 *  Neither the name of the Livio Inc. nor the names of its contributors
 *  may be used to endorse or promote products derived from this software
 *  without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 *  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 *  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 *  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 *  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 *  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 *  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 *  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 *  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 */

package com.smartdevicelink.java;

import com.smartdevicelink.managers.CompletionListener;
import com.smartdevicelink.managers.screen.OnButtonListener;
import com.smartdevicelink.managers.SdlManager;
import com.smartdevicelink.managers.SdlManagerListener;
import com.smartdevicelink.managers.file.filetypes.SdlArtwork;
import com.smartdevicelink.managers.lifecycle.LifecycleConfigurationUpdate;
import com.smartdevicelink.managers.screen.choiceset.ChoiceCell;
import com.smartdevicelink.managers.screen.choiceset.ChoiceSet;
import com.smartdevicelink.managers.screen.choiceset.ChoiceSetSelectionListener;
import com.smartdevicelink.managers.screen.menu.MenuCell;
import com.smartdevicelink.managers.screen.menu.MenuSelectionListener;
import com.smartdevicelink.managers.screen.menu.VoiceCommand;
import com.smartdevicelink.managers.screen.menu.VoiceCommandSelectionListener;
import com.smartdevicelink.protocol.enums.FunctionID;
import com.smartdevicelink.proxy.RPCNotification;
import com.smartdevicelink.proxy.rpc.*;
import com.smartdevicelink.proxy.rpc.enums.*;
import com.smartdevicelink.proxy.rpc.listeners.OnRPCNotificationListener;
import com.smartdevicelink.transport.BaseTransportConfig;
import com.smartdevicelink.util.DebugTool;

import java.util.*;

public class SdlService {


    private static final String TAG 					= "SDL Service";

    private static final String APP_NAME 				= "Hello Sdl";
    private static final String APP_NAME_ES             = "Hola Sdl";
    private static final String APP_NAME_FR             = "Bonjour Sdl";
    private static final String APP_ID 					= "8678309";

    private static final String ICON_FILENAME 			= "hello_sdl_icon.png";
    private static final String SDL_IMAGE_FILENAME  	= "sdl_full_image.png";

    private static final String WELCOME_SHOW 			= "Welcome to HelloSDL";
    private static final String WELCOME_SPEAK 			= "Welcome to Hello S D L";

    private static final String TEST_COMMAND_NAME 		= "Test Command";

    private static final String IMAGE_DIR =             "assets/images/";

    // variable to create and call functions of the SyncProxy
    private SdlManager sdlManager = null;
    private List<ChoiceCell> choiceCellList;

    private SdlServiceCallback callback;

    public SdlService(BaseTransportConfig config, SdlServiceCallback callback){
        this.callback = callback;
        buildSdlManager(config);
    }

    public void start() {
        DebugTool.logInfo(TAG, "SdlService start() ");
        if(sdlManager != null){
            sdlManager.start();
        }
    }

    public void stop() {
        if (sdlManager != null) {
            sdlManager.dispose();
            sdlManager = null;
        }
    }

    private void buildSdlManager(BaseTransportConfig transport) {
        // This logic is to select the correct transport and security levels defined in the selected build flavor
        // Build flavors are selected by the "build variants" tab typically located in the bottom left of Android Studio
        // Typically in your app, you will only set one of these.
        if (sdlManager == null) {
            DebugTool.logInfo(TAG, "Creating SDL Manager");

            //FIXME add the transport type
            // The app type to be used
            Vector<AppHMIType> appType = new Vector<>();
            appType.add(AppHMIType.MEDIA);

            // The manager listener helps you know when certain events that pertain to the SDL Manager happen
            // Here we will listen for ON_HMI_STATUS and ON_COMMAND notifications
            SdlManagerListener listener = new SdlManagerListener() {
                @Override
                public void onStart(SdlManager sdlManager) {
                    DebugTool.logInfo(TAG, "SdlManager onStart");
                }

                @Override
                public void onDestroy(SdlManager sdlManager) {
                    DebugTool.logInfo(TAG, "SdlManager onDestroy ");
                    SdlService.this.sdlManager = null;
                    if(SdlService.this.callback != null){
                        SdlService.this.callback.onEnd();
                        stop();
                    }
                }

                @Override
                public void onError(SdlManager sdlManager, String info, Exception e) {
                }

                @Override
                public LifecycleConfigurationUpdate managerShouldUpdateLifecycle(Language language, Language hmiLanguage) {
                    boolean isNeedUpdate = false;
                    String appName = APP_NAME;
                    String ttsName = APP_NAME;
                    switch (language) {
                        case ES_MX:
                            isNeedUpdate = true;
                            ttsName = APP_NAME_ES;
                            break;
                        case FR_CA:
                            isNeedUpdate = true;
                            ttsName = APP_NAME_FR;
                            break;
                        default:
                            break;
                    }
                    switch (hmiLanguage) {
                        case ES_MX:
                            isNeedUpdate = true;
                            appName = APP_NAME_ES;
                            break;
                        case FR_CA:
                            isNeedUpdate = true;
                            appName = APP_NAME_FR;
                            break;
                        default:
                            break;
                    }
                    if (isNeedUpdate) {
                        Vector<TTSChunk> chunks = new Vector<>(Collections.singletonList(new TTSChunk(ttsName, SpeechCapabilities.TEXT)));
                        return new LifecycleConfigurationUpdate(appName, null, chunks, null);
                    } else {
                        return null;
                    }
                }
            };


            HashMap<FunctionID,OnRPCNotificationListener> notificationListenerHashMap = new HashMap<FunctionID,OnRPCNotificationListener>();
            notificationListenerHashMap.put(FunctionID.ON_HMI_STATUS, new OnRPCNotificationListener() {
                @Override
                public void onNotified(RPCNotification notification) {
                    OnHMIStatus status = (OnHMIStatus) notification;
                    if (status.getHmiLevel() == HMILevel.HMI_FULL && ((OnHMIStatus) notification).getFirstRun()) {
                        setVoiceCommands();
                        sendMenus();
                        performWelcomeSpeak();
                        performWelcomeShow();
                        preloadChoices();
                        subscribeToButtons();
                    }
                }
            });

            // Create App Icon, this is set in the SdlManager builder
            SdlArtwork appIcon = new SdlArtwork(ICON_FILENAME, FileType.GRAPHIC_PNG, IMAGE_DIR+"sdl_s_green.png", true);

            // The manager builder sets options for your session
            SdlManager.Builder builder = new SdlManager.Builder(APP_ID, APP_NAME, listener);
            builder.setAppTypes(appType);
            builder.setTransportType(transport);
            builder.setAppIcon(appIcon);
            builder.setRPCNotificationListeners(notificationListenerHashMap);
            sdlManager = builder.build();
        }
    }

    /**
     * Send some voice commands
     */
    private void setVoiceCommands(){

        List<String> list1 = Collections.singletonList("Command One");
        List<String> list2 = Collections.singletonList("Command two");

        VoiceCommand voiceCommand1 = new VoiceCommand(list1, new VoiceCommandSelectionListener() {
            @Override
            public void onVoiceCommandSelected() {
                DebugTool.logInfo(TAG, "Voice Command 1 triggered");
            }
        });

        VoiceCommand voiceCommand2 = new VoiceCommand(list2, new VoiceCommandSelectionListener() {
            @Override
            public void onVoiceCommandSelected() {
                DebugTool.logInfo(TAG, "Voice Command 2 triggered");
            }
        });

        sdlManager.getScreenManager().setVoiceCommands(Arrays.asList(voiceCommand1,voiceCommand2));
    }

    /**
     *  Add menus for the app on SDL.
     */
    private void sendMenus(){

        // some arts
        SdlArtwork livio = new SdlArtwork(ICON_FILENAME, FileType.GRAPHIC_PNG, IMAGE_DIR+"sdl_s_green.png", true);

        // some voice commands
        List<String> voice2 = Collections.singletonList("Cell two");

        MenuCell mainCell1 = new MenuCell("Test Cell 1 (speak)", livio, null, new MenuSelectionListener() {
            @Override
            public void onTriggered(TriggerSource trigger) {
                DebugTool.logInfo(TAG, "Test cell 1 triggered. Source: "+ trigger.toString());
                showTest();
            }
        });

        MenuCell mainCell2 = new MenuCell("Test Cell 2", null, voice2, new MenuSelectionListener() {
            @Override
            public void onTriggered(TriggerSource trigger) {
                DebugTool.logInfo(TAG, "Test cell 2 triggered. Source: "+ trigger.toString());
            }
        });

        // SUB MENU

        MenuCell subCell1 = new MenuCell("SubCell 1",null, null, new MenuSelectionListener() {
            @Override
            public void onTriggered(TriggerSource trigger) {
                DebugTool.logInfo(TAG, "Sub cell 1 triggered. Source: "+ trigger.toString());
            }
        });

        MenuCell subCell2 = new MenuCell("SubCell 2",null, null, new MenuSelectionListener() {
            @Override
            public void onTriggered(TriggerSource trigger) {
                DebugTool.logInfo(TAG, "Sub cell 2 triggered. Source: "+ trigger.toString());
            }
        });

        // sub menu parent cell
        MenuCell mainCell3 = new MenuCell("Test Cell 3 (sub menu)", MenuLayout.LIST, null, Arrays.asList(subCell1,subCell2));

        MenuCell mainCell4 = new MenuCell("Show Perform Interaction", null, null, new MenuSelectionListener() {
            @Override
            public void onTriggered(TriggerSource trigger) {
                showPerformInteraction();
            }
        });

        MenuCell mainCell5 = new MenuCell("Clear the menu",null, null, new MenuSelectionListener() {
            @Override
            public void onTriggered(TriggerSource trigger) {
                DebugTool.logInfo(TAG, "Clearing Menu. Source: "+ trigger.toString());
                // Clear this thing
                sdlManager.getScreenManager().setMenu(Collections.<MenuCell>emptyList());
                showAlert("Menu Cleared");
            }
        });

        // Send the entire menu off to be created
        sdlManager.getScreenManager().setMenu(Arrays.asList(mainCell1, mainCell2, mainCell3, mainCell4, mainCell5));
    }

    /**
     * Will speak a sample welcome message
     */
    private void performWelcomeSpeak(){
        List<TTSChunk> chunks = Collections.singletonList(new TTSChunk(WELCOME_SPEAK, SpeechCapabilities.TEXT));
        sdlManager.sendRPC(new Speak(chunks));
    }

    /**
     * Use the Screen Manager to set the initial screen text and set the image.
     * Because we are setting multiple items, we will call beginTransaction() first,
     * and finish with commit() when we are done.
     */
    private void performWelcomeShow() {
        sdlManager.getScreenManager().beginTransaction();
        sdlManager.getScreenManager().setTextField1(APP_NAME);
        sdlManager.getScreenManager().setTextField2(WELCOME_SHOW);
        sdlManager.getScreenManager().setPrimaryGraphic(new SdlArtwork(SDL_IMAGE_FILENAME, FileType.GRAPHIC_PNG, IMAGE_DIR+"sdl.png", true));
        sdlManager.getScreenManager().commit(new CompletionListener() {
            @Override
            public void onComplete(boolean success) {
                if (success){
                    DebugTool.logInfo(TAG, "welcome show successful");
                }
            }
        });
    }

    /**
     * Attempts to Subscribe to all preset buttons
     */
    private void subscribeToButtons() {
        ButtonName[] buttonNames = {ButtonName.PLAY_PAUSE, ButtonName.SEEKLEFT, ButtonName.SEEKRIGHT, ButtonName.AC_MAX, ButtonName.AC, ButtonName.RECIRCULATE,
                ButtonName.FAN_UP, ButtonName.FAN_DOWN, ButtonName.TEMP_UP, ButtonName.TEMP_DOWN, ButtonName.FAN_DOWN, ButtonName.DEFROST_MAX, ButtonName.DEFROST_REAR, ButtonName.DEFROST,
                ButtonName.UPPER_VENT, ButtonName.LOWER_VENT, ButtonName.VOLUME_UP, ButtonName.VOLUME_DOWN, ButtonName.EJECT, ButtonName.SOURCE, ButtonName.SHUFFLE, ButtonName.REPEAT};

       OnButtonListener onButtonListener = new OnButtonListener() {
            @Override
            public void onPress(ButtonName buttonName, OnButtonPress buttonPress) {
                sdlManager.getScreenManager().setTextField1(buttonName +  "  pressed");
                DebugTool.logInfo(TAG, "onPress: " + buttonName);
            }

            @Override
            public void onEvent(ButtonName buttonName, OnButtonEvent buttonEvent) {
                sdlManager.getScreenManager().setTextField2(buttonName + " " + buttonEvent.getButtonEventMode());
            }

            @Override
            public void onError(String info) {
                DebugTool.logInfo(TAG, "onError: " + info);
            }
        };

        for (ButtonName buttonName : buttonNames) {
            sdlManager.getScreenManager().addButtonListener(buttonName, onButtonListener);
        }
    }

    /**
     * Will show a sample test message on screen as well as speak a sample test message
     */
    private void showTest(){
        sdlManager.getScreenManager().beginTransaction();
        sdlManager.getScreenManager().setTextField1("Test Cell 1 has been selected");
        sdlManager.getScreenManager().setTextField2("");
        sdlManager.getScreenManager().commit(null);

        List<TTSChunk> chunks = Collections.singletonList(new TTSChunk(TEST_COMMAND_NAME, SpeechCapabilities.TEXT));
        sdlManager.sendRPC(new Speak(chunks));
    }

    private void showAlert(String text){
        Alert alert = new Alert();
        alert.setAlertText1(text);
        alert.setDuration(5000);
        sdlManager.sendRPC(alert);
    }

    public interface SdlServiceCallback{
        void onEnd();
    }

    // Choice Set

    private void preloadChoices(){
        ChoiceCell cell1 = new ChoiceCell("Item 1");
        ChoiceCell cell2 = new ChoiceCell("Item 2");
        ChoiceCell cell3 = new ChoiceCell("Item 3");
        choiceCellList = new ArrayList<>(Arrays.asList(cell1,cell2,cell3));
        sdlManager.getScreenManager().preloadChoices(choiceCellList, null);
    }

    private void showPerformInteraction(){
        if (choiceCellList != null) {
            ChoiceSet choiceSet = new ChoiceSet("Choose an Item from the list", choiceCellList, new ChoiceSetSelectionListener() {
                @Override
                public void onChoiceSelected(ChoiceCell choiceCell, TriggerSource triggerSource, int rowIndex) {
                    showAlert(choiceCell.getText() + " was selected");
                }

                @Override
                public void onError(String error) {
                    DebugTool.logError(TAG, "There was an error showing the perform interaction: "+ error);
                }
            });
            sdlManager.getScreenManager().presentChoiceSet(choiceSet, InteractionMode.MANUAL_ONLY);
        }
    }
}