first commit

This commit is contained in:
Jimmie Matsson 2017-06-01 12:19:16 +02:00
commit 14c482e4c3
31 changed files with 1093 additions and 0 deletions

48
.gitignore vendored Normal file
View file

@ -0,0 +1,48 @@
# Built application files
*.apk
*.ap_
# Files for the ART/Dalvik VM
*.dex
# Java class files
*.class
# Generated files
bin/
gen/
out/
# Gradle files
.gradle/
build/
# Local configuration file (sdk path, etc)
local.properties
# Proguard folder generated by Eclipse
proguard/
# Log Files
*.log
# Android Studio Navigation editor temp files
.navigation/
# Android Studio captures folder
captures/
# Intellij
*.iml
.idea/workspace.xml
.idea/modules.xml
.idea/misc.xml
.idea/libraries
.idea/vcs.xml
.idea/codeStyleSettings.xml
# Keystore files
*.jks
# External native build folder generated in Android Studio 2.2 and later
.externalNativeBuild

22
.idea/compiler.xml generated Normal file
View file

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<resourceExtensions />
<wildcardResourcePatterns>
<entry name="!?*.java" />
<entry name="!?*.form" />
<entry name="!?*.class" />
<entry name="!?*.groovy" />
<entry name="!?*.scala" />
<entry name="!?*.flex" />
<entry name="!?*.kt" />
<entry name="!?*.clj" />
<entry name="!?*.aj" />
</wildcardResourcePatterns>
<annotationProcessing>
<profile default="true" name="Default" enabled="false">
<processorPath useClasspath="true" />
</profile>
</annotationProcessing>
</component>
</project>

3
.idea/copyright/profiles_settings.xml generated Normal file
View file

@ -0,0 +1,3 @@
<component name="CopyrightManager">
<settings default="" />
</component>

6
.idea/encodings.xml generated Normal file
View file

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="PROJECT" charset="UTF-8" />
</component>
</project>

19
.idea/gradle.xml generated Normal file
View file

@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="distributionType" value="DEFAULT_WRAPPED" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$/../dixitmobile-common/library" />
<option value="$PROJECT_DIR$" />
<option value="$PROJECT_DIR$/vxt-speaker-next" />
</set>
</option>
<option name="resolveModulePerSourceSet" value="false" />
</GradleProjectSettings>
</option>
</component>
</project>

12
.idea/runConfigurations.xml generated Normal file
View file

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RunConfigurationProducerService">
<option name="ignoredProducers">
<set>
<option value="org.jetbrains.plugins.gradle.execution.test.runner.AllInPackageGradleConfigurationProducer" />
<option value="org.jetbrains.plugins.gradle.execution.test.runner.TestClassGradleConfigurationProducer" />
<option value="org.jetbrains.plugins.gradle.execution.test.runner.TestMethodGradleConfigurationProducer" />
</set>
</option>
</component>
</project>

23
build.gradle Normal file
View file

@ -0,0 +1,23 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}

17
gradle.properties Normal file
View file

@ -0,0 +1,17 @@
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx1536m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View file

@ -0,0 +1,6 @@
#Tue May 30 15:38:37 CEST 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip

160
gradlew vendored Executable file
View file

@ -0,0 +1,160 @@
#!/usr/bin/env bash
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
esac
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
JVM_OPTS=("$@")
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"

90
gradlew.bat vendored Normal file
View file

@ -0,0 +1,90 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windowz variants
if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
goto execute
:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
set CMD_LINE_ARGS=%$
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

3
settings.gradle Normal file
View file

@ -0,0 +1,3 @@
include ':vxt-speaker-next'
include ':library'
project(':library').projectDir = new File('../dixitmobile-common/library')

1
vxt-speaker-next/.gitignore vendored Normal file
View file

@ -0,0 +1 @@
/build

View file

@ -0,0 +1,37 @@
apply plugin: 'com.android.application'
repositories {
maven {
url "http://clojars.org/repo"
}
}
android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
applicationId "com.dixitmobile.websocket"
minSdkVersion 17
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha9'
testCompile 'junit:junit:4.12'
compile "org.java-websocket:java-websocket:1.3.3"
compile project (':library')
}

25
vxt-speaker-next/proguard-rules.pro vendored Normal file
View file

@ -0,0 +1,25 @@
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in /AndroidSDK/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile

View file

@ -0,0 +1,26 @@
package com.voixtreme.speakernext;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.dixitmobile.websocket", appContext.getPackageName());
}
}

View file

@ -0,0 +1,30 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.voixtreme.speakernext">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/Theme.Transparent">
<activity android:name="com.voixtreme.speakernext.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<service
android:name=".SpeakerNextService"
android:enabled="true"
android:launchMode="singleTask" >
</service>
</application>
</manifest>

View file

@ -0,0 +1,96 @@
package com.voixtreme.speakernext;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import com.dixitmobile.common.Common;
import com.dixitmobile.common.VerifyPermissions;
public class MainActivity extends AppCompatActivity {
private VerifyPermissions mVerifyPermissions;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mVerifyPermissions = new VerifyPermissions(this);
if(mVerifyPermissions.checkPermissionReadExternalStorage()) {
startWebSocketServer();
}
}
private void startWebSocketServer() {
if (Common.isServiceRunning(this, SpeakerNextService.class.getName())) {
askToRestartService();
} else {
Intent intent = new Intent(this, SpeakerNextService.class);
startService(intent);
finish();
}
}
private void askToRestartService() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.ask_restart);
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(MainActivity.this, SpeakerNextService.class);
stopService(intent);
int failSafe = 0;
int maxTries = 50;
while (Common.isServiceRunning(MainActivity.this, SpeakerNextService.class.getName())) {
try {
Log.v("main", "service still running...: " + failSafe);
Thread.sleep(100);
} catch (InterruptedException e) {
}
if (failSafe++ > maxTries) {
break;
}
}
startWebSocketServer();
dialogInterface.dismiss();
finish();
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
finish();
}
});
builder.create().show();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == VerifyPermissions.REQUEST_CODE_PERMISSIONS) {
if (mVerifyPermissions.onRequestPermissionResult(requestCode, permissions, grantResults)) {
startWebSocketServer();
} else {
mVerifyPermissions.showErrorDialog(R.string.error_no_permission, true);
}
}
}
}

View file

@ -0,0 +1,129 @@
package com.voixtreme.speakernext;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;
import com.dixitmobile.common.voixtreme.VxtCommon;
import com.dixitmobile.common.voixtreme.json.MainJSON;
import org.java_websocket.WebSocket;
import org.java_websocket.server.WebSocketServer;
import java.io.IOException;
import java.net.InetSocketAddress;
/**
* Created by jima on 30/05/17.
*/
public class SpeakerNextService extends Service {
private static final String TAG = "SpeakerNextService";
private MyServerThread mWSServerThread;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_STICKY;
}
@Override
public void onCreate() {
super.onCreate();
if (initialize()) {
myToast(R.string.start_ok, true, false);
}
}
@Override
public void onDestroy() {
Log.i(TAG, "onDestroy()");
if (mWSServerThread != null) {
mWSServerThread.interrupt();
mWSServerThread = null;
}
super.onDestroy();
}
/**
* Load all important stuff and exit if anything fails...
*/
private boolean initialize() {
MainJSON mainJSON = VxtCommon.readJsonConfiguration(VxtCommon.getDefaultConfigurationPath());
if (mainJSON == null) {
myToast(R.string.error_read_json, true, true);
stopSelf();
return false;
}
mWSServerThread = new MyServerThread(this, mainJSON);
mWSServerThread.start();
return true;
}
private void myToast(int msgId, boolean toast, boolean isError) {
if (isError) {
Log.e(TAG, getString(msgId));
} else {
Log.i(TAG, getString(msgId));
}
if (toast) {
Toast.makeText(this, msgId, Toast.LENGTH_LONG).show();
}
}
/**
* Thread running the Web Socket Server
*/
private class MyServerThread extends Thread implements Runnable {
private MainJSON mMainJSON;
private Context mContext;
MyServerThread(Context context, MainJSON mainJSON) {
mContext = context;
mMainJSON = mainJSON;
}
@Override
public void run() {
InetSocketAddress address = new InetSocketAddress(mMainJSON.speakerNext.host, mMainJSON.speakerNext.port);
SpeakerNextWSServer server = new SpeakerNextWSServer(address, mContext, mMainJSON);
server.run();
try {
server.closeAll();
server.stop();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
stopSelf();
}
}
}

View file

@ -0,0 +1,224 @@
package com.voixtreme.speakernext;
/**
* Created by jima on 30/05/17.
*/
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.annotation.Nullable;
import android.util.Log;
import com.dixitmobile.common.BroadcastParams;
import com.dixitmobile.common.voixtreme.json.MainJSON;
import java.net.InetSocketAddress;
import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
class SpeakerNextWSServer extends WebSocketServer {
private static final String TAG = "SpeakerNextWSServer";
private static final String COMMAND_CLOSE = "<CLOSE>";
private static final String COMMAND_OPEN_KEYBOARD = "<OPENKB>";
private static final String COMMAND_OPEN_QA = "<OPENQA>";
private static final String COMMAND_PING = "<PING>";
private static final String COMMAND_SPEAK = "<TTSO>";
private static final String COMMAND_INPUT = "<ASR>";
private MainJSON mMainJSON;
private boolean mSendToKeyboard = false;
private Context mContext;
private VxtEngineReceiver mReceiver;
private WebSocket mWebSocket;
SpeakerNextWSServer(InetSocketAddress address, Context context, MainJSON mainJSON) {
super(address);
mContext = context;
mMainJSON = mainJSON;
mReceiver = new VxtEngineReceiver(this);
context.registerReceiver(mReceiver, new IntentFilter(BroadcastParams.INTENT_ACTION_RESPONSE_SPEAKER_NEXT));
}
@Override
public void onOpen(WebSocket conn, ClientHandshake handshake) {
Log.v(TAG, "new connection to " + conn.getRemoteSocketAddress());
}
@Override
public void onClose(WebSocket conn, int code, String reason, boolean remote) {
Log.v(TAG, "closed " + conn.getRemoteSocketAddress() + " with exit code " + code + " additional info: " + reason);
}
@Override
public void onMessage(WebSocket socket, String command) {
Log.v(TAG, "received message from " + socket.getRemoteSocketAddress() + ": " + command);
checkCommand(socket, command.trim());
}
@Override
public void onError(WebSocket conn, Exception ex) {
System.err.println("an error occurred on connection " + conn.getRemoteSocketAddress() + ":" + ex);
}
@Override
public void onStart() {
Log.i(TAG, "SpeakerNext Web Socket Service started");
}
/**
* Close all connections and do some cleanup.
*/
void closeAll() {
Log.i(TAG, "SpeakerNext Web Socket Service stopped");
for (WebSocket socket : connections()) {
socket.close();
}
if (mReceiver != null) {
mContext.unregisterReceiver(mReceiver);
mReceiver = null;
}
}
/**
* What to do with the commands received from the other end of the socket...
*
* @param socket Socket connection
* @param command The command
*/
private void checkCommand(WebSocket socket, String command) {
if (command.startsWith(COMMAND_CLOSE)) {
Log.i(TAG, "Command " + COMMAND_CLOSE + " found");
finalizeVxtEngine();
mWebSocket = null;
} else if (command.startsWith(COMMAND_OPEN_QA)) {
Log.i(TAG, "Command " + COMMAND_OPEN_QA + " found");
if (isAvailable(socket, command)) {
mSendToKeyboard = false;
openCalibrate(socket);
}
} else if (command.startsWith(COMMAND_OPEN_KEYBOARD)) {
Log.i(TAG, "Command " + COMMAND_OPEN_KEYBOARD + " found");
if (isAvailable(socket, command)) {
mSendToKeyboard = true;
openCalibrate(socket);
}
} else if (command.startsWith(COMMAND_PING)) {
Log.i(TAG, "Command " + COMMAND_PING + " found");
socket.send("ping");
} else if (command.startsWith(COMMAND_SPEAK)) {
Log.i(TAG, "Command " + COMMAND_SPEAK + " found");
if (isAvailable(socket, command)) {
vxtSay(command);
}
} else if (command.startsWith(COMMAND_INPUT)) {
Log.i(TAG, "Command " + COMMAND_INPUT + " found");
if (isAvailable(socket, command)) {
vxtInput(command);
}
} else {
mWebSocket = socket;
sendResponse("ERROR; Unknown Command: " + command);
}
}
private boolean isAvailable(WebSocket socket, String command) {
if (mWebSocket == null) {
mWebSocket = socket;
return true;
} else {
Log.e(TAG, "VxtEngine busy, command discarded...: " + command);
return false;
}
}
/**
* Open voiXtreme Calibrate
*/
private void openCalibrate(WebSocket socket) {
Intent intent = mContext.getPackageManager().getLaunchIntentForPackage(mMainJSON.speakerNext.pkgCalibrate);
if (intent == null) {
socket.send("Missing package: " + mMainJSON.speakerNext.pkgCalibrate);
} else {
intent.putExtra(BroadcastParams.EXTRAS_RESPONSE_ACTION, BroadcastParams.INTENT_ACTION_RESPONSE_SPEAKER_NEXT);
mContext.startActivity(intent);
}
}
private void finalizeVxtEngine() {
Intent intent = new Intent(BroadcastParams.INTENT_ACTION_VOIXTREME);
intent.putExtra(BroadcastParams.EXTRAS_ACTION, BroadcastParams.COMMAND_FINALIZE);
intent.putExtra(BroadcastParams.EXTRAS_RESPONSE_ACTION, BroadcastParams.INTENT_ACTION_RESPONSE_SPEAKER_NEXT);
mContext.sendBroadcast(intent);
}
private void vxtSay(String text) {
Intent intent = new Intent(BroadcastParams.INTENT_ACTION_VOIXTREME);
intent.putExtra(BroadcastParams.EXTRAS_ACTION, BroadcastParams.COMMAND_SPEECH);
intent.putExtra(BroadcastParams.EXTRAS_TEXT, text);
intent.putExtra(BroadcastParams.EXTRAS_RESPONSE_ACTION, BroadcastParams.INTENT_ACTION_RESPONSE_SPEAKER_NEXT);
intent.putExtra(BroadcastParams.EXTRAS_ID, "socketSayID");
mContext.sendBroadcast(intent);
}
private void vxtInput(String text) {
Intent intent = new Intent(BroadcastParams.INTENT_ACTION_VOIXTREME);
intent.putExtra(BroadcastParams.EXTRAS_ACTION, BroadcastParams.COMMAND_SPEECH);
intent.putExtra(BroadcastParams.EXTRAS_TEXT, text);
intent.putExtra(BroadcastParams.EXTRAS_RESPONSE_ACTION, BroadcastParams.INTENT_ACTION_RESPONSE_SPEAKER_NEXT);
intent.putExtra(BroadcastParams.EXTRAS_ID, "socketAsrID");
mContext.sendBroadcast(intent);
}
/**
* Terminate ongoing command and prepare to be able to treat other commands.
*
* @param text null to declare that command was finished, or text to also send a response to the socket client
* @param keepLock true if to keep lock (for sending status messages while waiting for the command to finish.
*/
void sendResponse(@Nullable String text, boolean keepLock) {
Log.i(TAG, "sendResponse: " + text);
if (text != null) {
if (mSendToKeyboard) {
// TODO: implement me
} else {
mWebSocket.send(text);
}
}
if (!keepLock) {
mWebSocket = null;
}
}
/**
* Terminate ongoing command and prepare to be able to treat other commands.
*
* @param text null to declare that command was finished, or text to also send a response to the socket client
*/
void sendResponse(@Nullable String text) {
sendResponse(text, false);
}
}

View file

@ -0,0 +1,73 @@
package com.voixtreme.speakernext;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import com.dixitmobile.common.BroadcastParams;
import com.dixitmobile.common.Common;
/**
* Created by jima on 31/05/17.
*/
public class VxtEngineReceiver extends BroadcastReceiver {
private static final String TAG = "VxtEngineReceiver";
private SpeakerNextWSServer mServer;
public VxtEngineReceiver(SpeakerNextWSServer server) {
mServer = server;
}
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "received: -------------------------------------------");
Log.d(TAG, "received: ACTION: " + intent.getAction());
if (!intent.getAction().equals(BroadcastParams.INTENT_ACTION_RESPONSE_SPEAKER_NEXT)) {
return;
}
Bundle bundle = intent.getExtras();
int reliability = bundle.getInt(BroadcastParams.EXTRAS_RELIABILITY, 0);
int command = bundle.getInt(BroadcastParams.EXTRAS_ACTION, -1);
String text = bundle.getString(BroadcastParams.EXTRAS_TEXT, "");
int status = bundle.getInt(BroadcastParams.EXTRAS_STATUS, -1);
if (status > -1) {
switch (status) {
case Common.Calibrate.CALIBRATE_STATUS_STARTED:
mServer.sendResponse("Calibrate started.", true);
break;
case Common.Calibrate.CALIBRATE_STATUS_TERMINATED:
mServer.sendResponse("Calibrate done.");
break;
case Common.Calibrate.CALIBRATE_STATUS_VOIXTREME_SERVICE_MISSING:
mServer.sendResponse("VoiXtreme Engine missing.");
break;
case Common.Calibrate.CALIBRATE_STATUS_VOIXTREME_CALIBRATE_MISSING:
case Common.Calibrate.CALIBRATE_STATUS_TIMEOUT:
case Common.Calibrate.CALIBRATE_STATUS_PERMISSION_DENIED:
case Common.Calibrate.CALIBRATE_STATUS_JSON_FILE_ERROR:
case Common.Calibrate.CALIBRATE_STATUS_CONFIGURATION_ERROR:
case Common.Calibrate.CALIBRATE_STATUS_ASR_ERROR:
case Common.Calibrate.CALIBRATE_STATUS_INTERNAL_ERROR:
mServer.sendResponse("Calibrate unrecoverable error.");
break;
}
} else if (!text.trim().isEmpty()) {
mServer.sendResponse(reliability + ": " + text);
} else if (reliability == 0 && command == BroadcastParams.COMMAND_SPEECH) {
mServer.sendResponse(null);
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

View file

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorAccent">#FF4081</color>
</resources>

View file

@ -0,0 +1,9 @@
<resources>
<string name="app_name">SpeakerNext</string>
<string name="error_read_json">Error: Couldn\'t read json configuration file.</string>
<string name="start_ok">SpeakerNext Web Socket Server started correctly</string>
<string name="ask_restart">The Server is already running, would you like to restart it?</string>
<string name="ok">OK</string>
<string name="cancel">Cancel</string>
</resources>

View file

@ -0,0 +1,11 @@
<resources>
<style name="Theme.Transparent" parent="Theme.AppCompat">
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowIsFloating">true</item>
<item name="android:backgroundDimEnabled">false</item>
</style>
</resources>

View file

@ -0,0 +1,17 @@
package com.voixtreme.speakernext;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
}