diff options
author | Brett <3911458+BrettyWhite@users.noreply.github.com> | 2019-03-12 10:32:41 -0400 |
---|---|---|
committer | GitHub <noreply@github.com> | 2019-03-12 10:32:41 -0400 |
commit | ed59f1ff4f0a392105b59aee66a8fbe8926177b5 (patch) | |
tree | 7b3279b7535ee305af928005a9dd22200056118c | |
parent | 7818603f7f7b59637e060a96452b0d2db3384ec4 (diff) | |
parent | 204e4f7c63aebc8f0b7041a5f56dc4baf6a29af8 (diff) | |
download | sdl_android-ed59f1ff4f0a392105b59aee66a8fbe8926177b5.tar.gz |
Merge pull request #986 from smartdevicelink/feature/removeAndroidFilesPart1
Feature/remove android files part1
203 files changed, 5954 insertions, 15006 deletions
diff --git a/.travis.yml b/.travis.yml index 2d82df726..f467de76a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -46,6 +46,8 @@ before_script: script: - android list target - ./android/gradlew -p ./android :sdl_android:connectedCheck + - ./javaSE/gradlew -p ./javaSE test + - ./javaEE/gradlew -p ./javaEE test before_install: - echo yes | sdkmanager "build-tools;27.0.3" diff --git a/android/sdl_android/src/androidTest/java/com/smartdevicelink/protocol/SdlProtocolTests.java b/android/sdl_android/src/androidTest/java/com/smartdevicelink/protocol/SdlProtocolTests.java index 896c7af6d..4c53e9b58 100644 --- a/android/sdl_android/src/androidTest/java/com/smartdevicelink/protocol/SdlProtocolTests.java +++ b/android/sdl_android/src/androidTest/java/com/smartdevicelink/protocol/SdlProtocolTests.java @@ -5,7 +5,6 @@ import android.util.Log; import com.smartdevicelink.AndroidTestCase2; import com.smartdevicelink.SdlConnection.SdlConnection; import com.smartdevicelink.protocol.enums.SessionType; -import com.smartdevicelink.protocol.SdlProtocol.MessageFrameAssembler; import com.smartdevicelink.security.SdlSecurityBase; import com.smartdevicelink.streaming.video.VideoStreamingParameters; import com.smartdevicelink.test.SampleRpc; @@ -74,7 +73,7 @@ public class SdlProtocolTests extends AndroidTestCase2 { @Override public void shutdown(String info) {} @Override - public void onTransportDisconnected(String info, boolean altTransportAvailable, MultiplexTransportConfig transportConfig) {} + public void onTransportDisconnected(String info, boolean altTransportAvailable, BaseTransportConfig transportConfig) {} @Override public SdlSecurityBase getSdlSecurity() {return null;} @Override @@ -171,7 +170,7 @@ public class SdlProtocolTests extends AndroidTestCase2 { public void testHandleFrame(){ SampleRpc sampleRpc = new SampleRpc(4); SdlProtocol sdlProtocol = new SdlProtocol(defaultListener,config); - MessageFrameAssembler assembler = sdlProtocol.new MessageFrameAssembler(); + SdlProtocolBase.MessageFrameAssembler assembler = sdlProtocol.new MessageFrameAssembler(); try{ assembler.handleFrame(sampleRpc.toSdlPacket()); }catch(Exception e){ @@ -184,7 +183,7 @@ public class SdlProtocolTests extends AndroidTestCase2 { header.setJsonSize(Integer.MAX_VALUE); sampleRpc.setBinaryFrameHeader(header); SdlProtocol sdlProtocol = new SdlProtocol(defaultListener,config); - MessageFrameAssembler assembler = sdlProtocol.new MessageFrameAssembler(); + SdlProtocolBase.MessageFrameAssembler assembler = sdlProtocol.new MessageFrameAssembler(); try{ assembler.handleFrame(sampleRpc.toSdlPacket()); }catch(Exception e){ @@ -195,7 +194,7 @@ public class SdlProtocolTests extends AndroidTestCase2 { public void testHandleSingleFrameMessageFrame(){ SampleRpc sampleRpc = new SampleRpc(4); SdlProtocol sdlProtocol = new SdlProtocol(defaultListener,config); - MessageFrameAssembler assembler = sdlProtocol.new MessageFrameAssembler(); + SdlProtocolBase.MessageFrameAssembler assembler = sdlProtocol.new MessageFrameAssembler(); try{ @@ -254,7 +253,7 @@ public class SdlProtocolTests extends AndroidTestCase2 { int messageID = 1; boolean encrypted = false; SdlPacket sdlPacket = SdlPacketFactory.createMultiSendDataFirst(SessionType.RPC, sessionID, messageID, version, payload, encrypted); - MessageFrameAssembler assembler = protocol.getFrameAssemblerForFrame(sdlPacket); + SdlProtocolBase.MessageFrameAssembler assembler = protocol.getFrameAssemblerForFrame(sdlPacket); assertNotNull(assembler); @@ -302,7 +301,7 @@ public class SdlProtocolTests extends AndroidTestCase2 { int messageID = 1; boolean encrypted = false; SdlPacket sdlPacket = SdlPacketFactory.createMultiSendDataFirst(SessionType.RPC, sessionID, messageID, version, payload, encrypted); - MessageFrameAssembler assembler = protocol.getFrameAssemblerForFrame(sdlPacket); + SdlProtocolBase.MessageFrameAssembler assembler = protocol.getFrameAssemblerForFrame(sdlPacket); OutOfMemoryError oom_error = null; NullPointerException np_exception = null; diff --git a/android/sdl_android/src/androidTest/java/com/smartdevicelink/test/proxy/SystemCapabilityManagerTests.java b/android/sdl_android/src/androidTest/java/com/smartdevicelink/test/proxy/SystemCapabilityManagerTests.java index 91fbf6dde..a7b49489e 100644 --- a/android/sdl_android/src/androidTest/java/com/smartdevicelink/test/proxy/SystemCapabilityManagerTests.java +++ b/android/sdl_android/src/androidTest/java/com/smartdevicelink/test/proxy/SystemCapabilityManagerTests.java @@ -3,6 +3,7 @@ package com.smartdevicelink.test.proxy; import com.smartdevicelink.AndroidTestCase2; import com.smartdevicelink.protocol.enums.FunctionID; import com.smartdevicelink.protocol.enums.SessionType; +import com.smartdevicelink.proxy.RPCMessage; import com.smartdevicelink.proxy.RPCRequest; import com.smartdevicelink.proxy.SystemCapabilityManager; import com.smartdevicelink.proxy.interfaces.IAudioStreamListener; @@ -173,7 +174,7 @@ public class SystemCapabilityManagerTests extends AndroidTestCase2 { public void sendRPCRequest(RPCRequest message) {} @Override - public void sendRPC(RPCRequest message) {} + public void sendRPC(RPCMessage message) {} @Override public void sendRequests(List<? extends RPCRequest> rpcs, OnMultipleRequestListener listener) { diff --git a/android/sdl_android/src/androidTest/java/com/smartdevicelink/test/security/SdlSecurityBaseTest.java b/android/sdl_android/src/androidTest/java/com/smartdevicelink/test/security/SdlSecurityBaseTest.java index 82a042b81..d665dbd54 100644 --- a/android/sdl_android/src/androidTest/java/com/smartdevicelink/test/security/SdlSecurityBaseTest.java +++ b/android/sdl_android/src/androidTest/java/com/smartdevicelink/test/security/SdlSecurityBaseTest.java @@ -68,7 +68,7 @@ public class SdlSecurityBaseTest extends AndroidTestCase2 { } @Override - public void onTransportDisconnected(String info, boolean availablePrimary, MultiplexTransportConfig transportConfig) { + public void onTransportDisconnected(String info, boolean availablePrimary, BaseTransportConfig transportConfig) { } diff --git a/android/sdl_android/src/androidTest/java/com/smartdevicelink/test/streaming/MockInterfaceBroker.java b/android/sdl_android/src/androidTest/java/com/smartdevicelink/test/streaming/MockInterfaceBroker.java index f548560a9..da7ebf52a 100644 --- a/android/sdl_android/src/androidTest/java/com/smartdevicelink/test/streaming/MockInterfaceBroker.java +++ b/android/sdl_android/src/androidTest/java/com/smartdevicelink/test/streaming/MockInterfaceBroker.java @@ -3,6 +3,7 @@ package com.smartdevicelink.test.streaming; import com.smartdevicelink.SdlConnection.ISdlConnectionListener; import com.smartdevicelink.protocol.ProtocolMessage; import com.smartdevicelink.protocol.enums.SessionType; +import com.smartdevicelink.transport.BaseTransportConfig; import com.smartdevicelink.transport.MultiplexTransportConfig; import com.smartdevicelink.transport.enums.TransportType; @@ -22,7 +23,7 @@ public class MockInterfaceBroker implements ISdlConnectionListener { } @Override - public void onTransportDisconnected(String info, boolean availablePrimary, MultiplexTransportConfig transportConfig) { + public void onTransportDisconnected(String info, boolean availablePrimary, BaseTransportConfig transportConfig) { } diff --git a/android/sdl_android/src/androidTest/java/com/smartdevicelink/test/transport/TransportTypeTests.java b/android/sdl_android/src/androidTest/java/com/smartdevicelink/test/transport/TransportTypeTests.java index 7e3b894e5..58319ad10 100644 --- a/android/sdl_android/src/androidTest/java/com/smartdevicelink/test/transport/TransportTypeTests.java +++ b/android/sdl_android/src/androidTest/java/com/smartdevicelink/test/transport/TransportTypeTests.java @@ -11,13 +11,13 @@ import junit.framework.TestCase; /** * This is a unit test class for the SmartDeviceLink library project class : - * {@link com.smartdevicelink.transport.TransportType} + * {@link com.smartdevicelink.transport.enums.TransportType} */ public class TransportTypeTests extends TestCase { /** * This is a unit test for the following enum : - * {@link com.smartdevicelink.transport.TransportType} + * {@link com.smartdevicelink.transport.enums.TransportType} */ public void testTransportTypeEnum () { @@ -27,6 +27,7 @@ public class TransportTypeTests extends TestCase { String testInvalid = "INVALID"; String testBluetooth = "BLUETOOTH"; String testMultiplexing = "MULTIPLEX"; + String testWebSocketServer = "WEB_SOCKET_SERVER"; try { // Comparison Values @@ -34,12 +35,14 @@ public class TransportTypeTests extends TestCase { TransportType expectedUsbEnum = TransportType.USB; TransportType expectedBluetoothEnum = TransportType.BLUETOOTH; TransportType expectedMultiplexingEnum = TransportType.MULTIPLEX; + TransportType expectedWebSocketServerEnum = TransportType.WEB_SOCKET_SERVER; List<TransportType> expectedEnumList = new ArrayList<TransportType>(); expectedEnumList.add(TransportType.BLUETOOTH); expectedEnumList.add(TransportType.TCP); expectedEnumList.add(TransportType.USB); expectedEnumList.add(TransportType.MULTIPLEX); + expectedEnumList.add(TransportType.WEB_SOCKET_SERVER); TransportType actualNullEnum = TransportType.valueForString(null); TransportType actualTcpEnum = TransportType.valueForString(testTcp); @@ -47,6 +50,7 @@ public class TransportTypeTests extends TestCase { TransportType actualInvalidEnum = TransportType.valueForString(testInvalid); TransportType actualBluetoothEnum = TransportType.valueForString(testBluetooth); TransportType actualMultiplexingEnum = TransportType.valueForString(testMultiplexing); + TransportType actualWebSocketServerEnum = TransportType.valueForString(testWebSocketServer); List<TransportType> actualEnumList = Arrays.asList(TransportType.values()); @@ -55,6 +59,7 @@ public class TransportTypeTests extends TestCase { assertEquals(Test.MATCH, expectedUsbEnum, actualUsbEnum); assertEquals(Test.MATCH, expectedBluetoothEnum, actualBluetoothEnum); assertEquals(Test.MATCH, expectedMultiplexingEnum, actualMultiplexingEnum); + assertEquals(Test.MATCH, expectedWebSocketServerEnum, actualWebSocketServerEnum); assertTrue(Test.ARRAY, expectedEnumList.containsAll(actualEnumList) && actualEnumList.containsAll(expectedEnumList)); // Invalid/Null Tests diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/Dispatcher/IDispatchingStrategy.java b/android/sdl_android/src/main/java/com/smartdevicelink/Dispatcher/IDispatchingStrategy.java deleted file mode 100644 index a4cfc150b..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/Dispatcher/IDispatchingStrategy.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.smartdevicelink.Dispatcher;
-
-public interface IDispatchingStrategy<T> {
- public void dispatch(T message);
-
- public void handleDispatchingError(String info, Exception ex);
-
- public void handleQueueingError(String info, Exception ex);
-}
diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/Dispatcher/ProxyMessageDispatcher.java b/android/sdl_android/src/main/java/com/smartdevicelink/Dispatcher/ProxyMessageDispatcher.java deleted file mode 100644 index 8db6f51e7..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/Dispatcher/ProxyMessageDispatcher.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.smartdevicelink.Dispatcher;
-
-import java.util.concurrent.LinkedBlockingQueue;
-
-import com.smartdevicelink.util.DebugTool;
-
-public class ProxyMessageDispatcher<T> {
- LinkedBlockingQueue<T> _queue = null;
- private Thread _messageDispatchingThread = null;
- IDispatchingStrategy<T> _strategy = null;
-
- // Boolean to track if disposed
- private Boolean dispatcherDisposed = false;
-
- public ProxyMessageDispatcher(String THREAD_NAME, IDispatchingStrategy<T> strategy) {
- _queue = new LinkedBlockingQueue<T>();
-
- _strategy = strategy;
-
- // Create dispatching thread
- _messageDispatchingThread = new Thread(new Runnable() {public void run(){handleMessages();}});
- _messageDispatchingThread.setName(THREAD_NAME);
- _messageDispatchingThread.setDaemon(true);
- _messageDispatchingThread.start();
- }
-
- public void dispose() {
- dispatcherDisposed = true;
-
- if(_messageDispatchingThread != null) {
- _messageDispatchingThread.interrupt();
- _messageDispatchingThread = null;
- }
- }
-
- private void handleMessages() {
-
- try {
- T thisMessage;
-
- while(dispatcherDisposed == false) {
- thisMessage = _queue.take();
- _strategy.dispatch(thisMessage);
- }
- } catch (InterruptedException e) {
- // Thread was interrupted by dispose() method, no action required
- return;
- } catch (Exception e) {
- DebugTool.logError("Error occurred dispating message.", e);
- _strategy.handleDispatchingError("Error occurred dispating message.", e);
- }
- }
-
- public void queueMessage(T message) {
- try {
- _queue.put(message);
- } catch(ClassCastException e) {
- _strategy.handleQueueingError("ClassCastException encountered when queueing message.", e);
- } catch(Exception e) {
- _strategy.handleQueueingError("Exception encountered when queueing message.", e);
- }
- }
-}
diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/SdlConnection/ISdlConnectionListener.java b/android/sdl_android/src/main/java/com/smartdevicelink/SdlConnection/ISdlConnectionListener.java deleted file mode 100644 index 627c6eca9..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/SdlConnection/ISdlConnectionListener.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.smartdevicelink.SdlConnection;
-
-import com.smartdevicelink.protocol.ProtocolMessage;
-import com.smartdevicelink.protocol.enums.SessionType;
-import com.smartdevicelink.transport.MultiplexTransportConfig;
-
-import java.util.List;
-
-
-public interface ISdlConnectionListener {
- @Deprecated
- public void onTransportDisconnected(String info);
-
- public void onTransportDisconnected(String info, boolean availablePrimary, MultiplexTransportConfig transportConfig);
-
-
- public void onTransportError(String info, Exception e);
-
- public void onProtocolMessageReceived(ProtocolMessage msg);
-
- public void onProtocolSessionStartedNACKed(SessionType sessionType,
- byte sessionID, byte version, String correlationID, List<String> rejectedParams);
-
- public void onProtocolSessionStarted(SessionType sessionType,
- byte sessionID, byte version, String correlationID, int hashID, boolean isEncrypted);
-
- public void onProtocolSessionEnded(SessionType sessionType,
- byte sessionID, String correlationID);
-
- public void onProtocolSessionEndedNACKed(SessionType sessionType,
- byte sessionID, String correlationID);
-
- public void onProtocolError(String info, Exception e);
-
- public void onHeartbeatTimedOut(byte sessionID);
-
- public void onProtocolServiceDataACK(SessionType sessionType, int dataSize, byte sessionID);
-
- void onAuthTokenReceived(String authToken, byte sessionID);
-}
diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/SdlConnection/SdlConnection.java b/android/sdl_android/src/main/java/com/smartdevicelink/SdlConnection/SdlConnection.java index f67ac66af..a06392709 100644 --- a/android/sdl_android/src/main/java/com/smartdevicelink/SdlConnection/SdlConnection.java +++ b/android/sdl_android/src/main/java/com/smartdevicelink/SdlConnection/SdlConnection.java @@ -53,7 +53,6 @@ public class SdlConnection implements IProtocolListener, ITransportListener { /**
* Constructor.
*
- * @param listener Sdl connection listener.
* @param transportConfig Transport configuration for this connection.
*/
public SdlConnection(BaseTransportConfig transportConfig) {
@@ -382,7 +381,7 @@ public class SdlConnection implements IProtocolListener, ITransportListener { }
@Override
- public void onTransportDisconnected(String info, boolean availablePrimary, MultiplexTransportConfig transportConfig) {
+ public void onTransportDisconnected(String info, boolean availablePrimary, BaseTransportConfig transportConfig) {
onTransportDisconnected(info);
}
diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/SdlConnection/SdlSession.java b/android/sdl_android/src/main/java/com/smartdevicelink/SdlConnection/SdlSession.java index 44df5f64c..8c35be8e2 100644 --- a/android/sdl_android/src/main/java/com/smartdevicelink/SdlConnection/SdlSession.java +++ b/android/sdl_android/src/main/java/com/smartdevicelink/SdlConnection/SdlSession.java @@ -29,7 +29,6 @@ import com.smartdevicelink.streaming.video.RTPH264Packetizer; import com.smartdevicelink.streaming.video.VideoStreamingParameters;
import com.smartdevicelink.transport.BaseTransportConfig;
import com.smartdevicelink.transport.MultiplexTransport;
-import com.smartdevicelink.transport.MultiplexTransportConfig;
import com.smartdevicelink.transport.enums.TransportType;
import com.smartdevicelink.util.Version;
@@ -530,7 +529,7 @@ public class SdlSession implements ISdlConnectionListener, IHeartbeatMonitorList }
@Override
- public void onTransportDisconnected(String info, boolean availablePrimary, MultiplexTransportConfig transportConfig) {
+ public void onTransportDisconnected(String info, boolean availablePrimary, BaseTransportConfig transportConfig) {
this.sessionListener.onTransportDisconnected(info);
}
diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/SdlConnection/SdlSession2.java b/android/sdl_android/src/main/java/com/smartdevicelink/SdlConnection/SdlSession2.java index 913c8d5ee..c0294b1a3 100644 --- a/android/sdl_android/src/main/java/com/smartdevicelink/SdlConnection/SdlSession2.java +++ b/android/sdl_android/src/main/java/com/smartdevicelink/SdlConnection/SdlSession2.java @@ -174,8 +174,8 @@ public class SdlSession2 extends SdlSession implements ISdlProtocol{ } @Override - public void onTransportDisconnected(String info, boolean altTransportAvailable, MultiplexTransportConfig transportConfig) { - this.sessionListener.onTransportDisconnected(info, altTransportAvailable, (MultiplexTransportConfig)this.transportConfig); + public void onTransportDisconnected(String info, boolean altTransportAvailable, BaseTransportConfig transportConfig) { + this.sessionListener.onTransportDisconnected(info, altTransportAvailable, this.transportConfig); } /** diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/exception/SdlException.java b/android/sdl_android/src/main/java/com/smartdevicelink/exception/SdlException.java deleted file mode 100644 index a67549515..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/exception/SdlException.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.smartdevicelink.exception;
-
-
-public class SdlException extends Exception {
-
- private static final long serialVersionUID = 5922492291870772815L;
-
- protected Throwable detail = null;
- private SdlExceptionCause _sdlExceptionCause = null;
-
- public SdlException(String msg, SdlExceptionCause exceptionCause) {
- super(msg);
- _sdlExceptionCause = exceptionCause;
- }
-
- public SdlException(String msg, Throwable ex, SdlExceptionCause exceptionCause) {
- super(msg + " --- Check inner exception for diagnostic details");
- detail = ex;
- _sdlExceptionCause = exceptionCause;
- }
-
- public SdlException(Throwable ex) {
- super(ex.getMessage());
- detail = ex;
- }
-
- public SdlExceptionCause getSdlExceptionCause() {
- return _sdlExceptionCause;
- }
-
- public Throwable getInnerException() {
- return detail;
- }
-
- public String toString() {
- String ret = this.getClass().getName();
- ret += ": " + this.getMessage();
- if(this.getSdlExceptionCause() != null){
- ret += "\nSdlExceptionCause: " + this.getSdlExceptionCause().name();
- }
- if (detail != null) {
- ret += "\nnested: " + detail.toString();
- detail.printStackTrace();
- }
- return ret;
- }
-}
diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/exception/SdlExceptionCause.java b/android/sdl_android/src/main/java/com/smartdevicelink/exception/SdlExceptionCause.java deleted file mode 100644 index 4894ceca3..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/exception/SdlExceptionCause.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.smartdevicelink.exception;
-
-public enum SdlExceptionCause {
- BLUETOOTH_ADAPTER_NULL,
- BLUETOOTH_DISABLED,
- BLUETOOTH_SOCKET_UNAVAILABLE,
- HEARTBEAT_PAST_DUE,
- INCORRECT_LIFECYCLE_MODEL,
- INVALID_ARGUMENT,
- INVALID_RPC_PARAMETER,
- PERMISSION_DENIED,
- RESERVED_CORRELATION_ID,
- SDL_CONNECTION_FAILED,
- SDL_PROXY_CYCLED,
- SDL_PROXY_DISPOSED,
- SDL_PROXY_OBSOLETE,
- SDL_REGISTRATION_ERROR,
- SDL_UNAVAILABLE,
- INVALID_HEADER,
- DATA_BUFFER_NULL,
- SDL_USB_DETACHED,
- SDL_USB_PERMISSION_DENIED,
- LOCK_SCREEN_ICON_NOT_SUPPORTED,
- ;
-}
diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/managers/SdlManager.java b/android/sdl_android/src/main/java/com/smartdevicelink/managers/SdlManager.java index c96a3d237..4aa848782 100644 --- a/android/sdl_android/src/main/java/com/smartdevicelink/managers/SdlManager.java +++ b/android/sdl_android/src/main/java/com/smartdevicelink/managers/SdlManager.java @@ -688,7 +688,7 @@ public class SdlManager extends BaseSdlManager{ } @Override - public void sendRPC(RPCRequest message) { + public void sendRPC(RPCMessage message) { try { proxy.sendRPC(message); } catch (SdlException e) { diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/marshal/JsonRPCMarshaller.java b/android/sdl_android/src/main/java/com/smartdevicelink/marshal/JsonRPCMarshaller.java deleted file mode 100644 index 89f4d1ef7..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/marshal/JsonRPCMarshaller.java +++ /dev/null @@ -1,127 +0,0 @@ -package com.smartdevicelink.marshal;
-
-import java.util.ArrayList;
-import java.util.Hashtable;
-import java.util.Iterator;
-import java.util.List;
-
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.JSONObject;
-
-import com.smartdevicelink.proxy.RPCMessage;
-import com.smartdevicelink.proxy.RPCStruct;
-import com.smartdevicelink.trace.*;
-import com.smartdevicelink.trace.enums.InterfaceActivityDirection;
-import com.smartdevicelink.util.DebugTool;
-
-/*
- * Responsible for marshalling and unmarshing between RPC Objects and byte streams that are sent
- * over transmission
- */
-
-public class JsonRPCMarshaller {
-
- private static final String SDL_LIB_PRIVATE_KEY = "42baba60-eb57-11df-98cf-0800200c9a66";
-
- /**
- * @param msg RPC message to be marshaled
- * @param version protocol version
- * @return byte array of the marshalled message
- */
- public static byte[] marshall(RPCMessage msg, byte version) {
- byte[] jsonBytes = null;
- try {
- JSONObject jsonObject = msg.serializeJSON(version);
- jsonBytes = jsonObject.toString().getBytes();
-
- SdlTrace.logMarshallingEvent(InterfaceActivityDirection.Transmit, jsonBytes, SDL_LIB_PRIVATE_KEY);
- } catch (JSONException e) {
- DebugTool.logError("Failed to encode messages to JSON.", e);
- }
- return jsonBytes;
- }
-
- public static Hashtable<String, Object> unmarshall(byte[] message) {
- SdlTrace.logMarshallingEvent(InterfaceActivityDirection.Receive, message, SDL_LIB_PRIVATE_KEY);
- Hashtable<String, Object> ret = null;
- try {
- String jsonString = new String(message);
- JSONObject jsonObject = new JSONObject(jsonString);
- ret = deserializeJSONObject(jsonObject);
- } catch (JSONException e) {
- DebugTool.logError("Failed to parse JSON", e);
- }
- return ret;
- }
-
- @SuppressWarnings("unchecked")
- public static Hashtable<String, Object> deserializeJSONObject(JSONObject jsonObject)
- throws JSONException {
- Hashtable<String, Object> ret = new Hashtable<String, Object>();
- Iterator<String> it = jsonObject.keys();
- String key = null;
- while (it.hasNext()) {
- key = it.next();
- Object value = jsonObject.get(key);
- if (value instanceof JSONObject) {
- ret.put(key, deserializeJSONObject((JSONObject)value));
- } else if (value instanceof JSONArray) {
- JSONArray arrayValue = (JSONArray) value;
- List<Object> putList = new ArrayList<Object>(arrayValue.length());
- for (int i = 0; i < arrayValue.length(); i++) {
- Object anObject = arrayValue.get(i);
- if (anObject instanceof JSONObject) {
- Hashtable<String, Object> deserializedObject = deserializeJSONObject((JSONObject)anObject);
- putList.add(deserializedObject);
- } else {
- putList.add(anObject);
- }
- }
- ret.put(key, putList);
- } else {
- ret.put(key, value);
- }
- }
- return ret;
- }
-
- @SuppressWarnings("unchecked" )
- private static JSONArray serializeList(List<?> list) throws JSONException{
- JSONArray toPut = new JSONArray();
- Iterator<Object> valueIterator = (Iterator<Object>) list.iterator();
- while(valueIterator.hasNext()){
- Object anObject = valueIterator.next();
- if (anObject instanceof RPCStruct) {
- RPCStruct toSerialize = (RPCStruct) anObject;
- toPut.put(toSerialize.serializeJSON());
- } else if(anObject instanceof Hashtable){
- Hashtable<String, Object> toSerialize = (Hashtable<String, Object>)anObject;
- toPut.put(serializeHashtable(toSerialize));
- } else {
- toPut.put(anObject);
- }
- }
- return toPut;
- }
-
- @SuppressWarnings({"unchecked" })
- public static JSONObject serializeHashtable(Hashtable<String, Object> hash) throws JSONException{
- JSONObject obj = new JSONObject();
- Iterator<String> hashKeyIterator = hash.keySet().iterator();
- while (hashKeyIterator.hasNext()){
- String key = (String) hashKeyIterator.next();
- Object value = hash.get(key);
- if (value instanceof RPCStruct) {
- obj.put(key, ((RPCStruct) value).serializeJSON());
- } else if (value instanceof List<?>) {
- obj.put(key, serializeList((List<?>) value));
- } else if (value instanceof Hashtable) {
- obj.put(key, serializeHashtable((Hashtable<String, Object>)value));
- } else {
- obj.put(key, value);
- }
- }
- return obj;
- }
-}
diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/protocol/BinaryFrameHeader.java b/android/sdl_android/src/main/java/com/smartdevicelink/protocol/BinaryFrameHeader.java deleted file mode 100644 index 5848b9f5a..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/protocol/BinaryFrameHeader.java +++ /dev/null @@ -1,118 +0,0 @@ -package com.smartdevicelink.protocol;
-
-import android.util.Log;
-
-import com.smartdevicelink.util.BitConverter;
-
-public class BinaryFrameHeader {
- private static final String TAG = "BinaryFrameHeader";
-
- private byte _rpcType;
- private int _functionID;
- private int _correlationID;
- private int _jsonSize;
-
- private byte[] _jsonData;
- private byte[] _bulkData;
-
- public BinaryFrameHeader() {}
-
- public static BinaryFrameHeader parseBinaryHeader(byte[] binHeader) {
- BinaryFrameHeader msg = new BinaryFrameHeader();
-
- byte RPC_Type = (byte) (binHeader[0] >>> 4);
- msg.setRPCType(RPC_Type);
-
- int _functionID = (BitConverter.intFromByteArray(binHeader, 0) & 0x0FFFFFFF);
- msg.setFunctionID(_functionID);
-
- int corrID = BitConverter.intFromByteArray(binHeader, 4);
- msg.setCorrID(corrID);
-
- int _jsonSize = BitConverter.intFromByteArray(binHeader, 8);
- msg.setJsonSize(_jsonSize);
-
- try {
- if (_jsonSize > 0) {
- byte[] _jsonData = new byte[_jsonSize];
- System.arraycopy(binHeader, 12, _jsonData, 0, _jsonSize);
- msg.setJsonData(_jsonData);
- }
-
- if (binHeader.length - _jsonSize - 12 > 0) {
- byte[] _bulkData = new byte[binHeader.length - _jsonSize - 12];
- System.arraycopy(binHeader, 12 + _jsonSize, _bulkData, 0, _bulkData.length);
- msg.setBulkData(_bulkData);
- }
- } catch (OutOfMemoryError|ArrayIndexOutOfBoundsException e){
- Log.e(TAG, "Unable to process data to form header");
- return null;
- }
-
- return msg;
- }
-
- public byte[] assembleHeaderBytes() {
- int binHeader = _functionID;
- // reset the 4 leftmost bits, for _rpcType
- binHeader &= 0xFFFFFFFF >>> 4;
- binHeader |= (_rpcType << 28);
-
- byte[] ret = new byte[12];
- System.arraycopy(BitConverter.intToByteArray(binHeader), 0, ret, 0, 4);
- System.arraycopy(BitConverter.intToByteArray(_correlationID), 0, ret, 4, 4);
- System.arraycopy(BitConverter.intToByteArray(_jsonSize), 0, ret, 8, 4);
-
- return ret;
- }
-
- public byte getRPCType() {
- return _rpcType;
- }
-
- public void setRPCType(byte _rpcType) {
- this._rpcType = _rpcType;
- }
-
- public int getFunctionID() {
- return _functionID;
- }
-
- public void setFunctionID(int _functionID) {
- this._functionID = _functionID;
- }
-
- public int getCorrID() {
- return _correlationID;
- }
-
- public void setCorrID(int _correlationID) {
- this._correlationID = _correlationID;
- }
-
- public int getJsonSize() {
- return _jsonSize;
- }
-
- public void setJsonSize(int _jsonSize) {
- this._jsonSize = _jsonSize;
- }
-
- public byte[] getJsonData() {
- return _jsonData;
- }
-
- public void setJsonData(byte[] _jsonData) {
- this._jsonData = new byte[this._jsonSize];
- System.arraycopy(_jsonData, 0, this._jsonData, 0, _jsonSize);
- //this._jsonData = _jsonData;
- }
-
- public byte[] getBulkData() {
- return _bulkData;
- }
-
- public void setBulkData(byte[] _bulkData) {
- this._bulkData = _bulkData;
- }
-}
diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/protocol/IProtocolListener.java b/android/sdl_android/src/main/java/com/smartdevicelink/protocol/IProtocolListener.java deleted file mode 100644 index e0c6808e1..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/protocol/IProtocolListener.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.smartdevicelink.protocol;
-
-
-import com.smartdevicelink.protocol.enums.*;
-
-import java.util.List;
-
-public interface IProtocolListener {
- // Called to indicate that these bytes are to be sent as part of a message.
- // This call includes the part of the message.
- void onProtocolMessageBytesToSend(SdlPacket packet);
-
- // Called to indicate that a complete message (RPC, BULK, etc.) has been
- // received. This call includes the message.
- void onProtocolMessageReceived(ProtocolMessage msg);
-
- // Called to indicate that a protocol session has been started (from either side)
- void onProtocolSessionStarted(SessionType sessionType, byte sessionID, byte version, String correlationID, int hashID, boolean isEncrypted);
-
- void onProtocolSessionNACKed(SessionType sessionType, byte sessionID, byte version,
- String correlationID, List<String> rejectedParams);
-
- // Called to indicate that a protocol session has ended (from either side)
- void onProtocolSessionEnded(SessionType sessionType, byte sessionID, String correlationID /*, String info, Exception ex*/);
-
- void onProtocolSessionEndedNACKed(SessionType sessionType, byte sessionID, String correlationID /*, String info, Exception ex*/);
-
- void onProtocolHeartbeat(SessionType sessionType, byte sessionID);
-
- /**
- * Called when a protocol heartbeat ACK message has been received from SDL.
- */
- void onProtocolHeartbeatACK(SessionType sessionType, byte sessionID);
-
- void onProtocolServiceDataACK(SessionType sessionType, int dataSize, byte sessionID);
-
- void onResetOutgoingHeartbeat(SessionType sessionType, byte sessionID);
-
- void onResetIncomingHeartbeat(SessionType sessionType, byte sessionID);
-
- // Called to indicate that a protocol error was detected in received data.
- void onProtocolError(String info, Exception e);
-
-} // end-interfCe
diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/protocol/ISdlProtocol.java b/android/sdl_android/src/main/java/com/smartdevicelink/protocol/ISdlProtocol.java deleted file mode 100644 index 32a21ec2a..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/protocol/ISdlProtocol.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) 2018 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.protocol; - - -import com.smartdevicelink.protocol.enums.SessionType; -import com.smartdevicelink.security.SdlSecurityBase; -import com.smartdevicelink.streaming.video.VideoStreamingParameters; -import com.smartdevicelink.transport.MultiplexTransportConfig; - -public interface ISdlProtocol extends IProtocolListener { - - byte getSessionId(); - - void shutdown(String info); - - void onTransportDisconnected(String info, boolean altTransportAvailable, MultiplexTransportConfig transportConfig); - - SdlSecurityBase getSdlSecurity(); - - VideoStreamingParameters getDesiredVideoParams(); - - void setAcceptedVideoParams(VideoStreamingParameters acceptedVideoParams); - - void stopStream(SessionType serviceType); - - void onAuthTokenReceived(String authToken); -} diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/protocol/ISecondaryTransportListener.java b/android/sdl_android/src/main/java/com/smartdevicelink/protocol/ISecondaryTransportListener.java deleted file mode 100644 index 17db7ad11..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/protocol/ISecondaryTransportListener.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.smartdevicelink.protocol; - -import com.smartdevicelink.transport.utl.TransportRecord; - -public interface ISecondaryTransportListener { - void onConnectionSuccess(TransportRecord transportRecord); - void onConnectionFailure(); -} diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/protocol/ProtocolMessage.java b/android/sdl_android/src/main/java/com/smartdevicelink/protocol/ProtocolMessage.java deleted file mode 100644 index cb5ad3a74..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/protocol/ProtocolMessage.java +++ /dev/null @@ -1,151 +0,0 @@ -package com.smartdevicelink.protocol;
-
-import com.smartdevicelink.protocol.enums.MessageType;
-import com.smartdevicelink.protocol.enums.SessionType;
-
-public class ProtocolMessage {
- private byte version = 1;
- private SessionType _sessionType = SessionType.RPC;
- private MessageType _messageType = MessageType.UNDEFINED;
- private byte _sessionID = 0;
- private byte _rpcType;
- private int _functionID;
- private int _correlationID;
- private int _jsonSize;
- private boolean payloadProtected = false;
-
- int priorityCoefficient = 0;
-
- private byte[] _data = null;
- private byte[] _bulkData = null;
-
- public ProtocolMessage() {}
-
- public byte getVersion() {
- return version;
- }
-
- public void setVersion(byte version) {
- this.version = version;
- }
-
- public byte getSessionID() {
- return _sessionID;
- }
-
- public void setSessionID(byte sessionID) {
- this._sessionID = sessionID;
- }
-
- public byte[] getData() {
- return _data;
- }
-
- public void setData(byte[] data) {
- this._data = data;
- this._jsonSize = data.length;
- }
-
- public void setData(byte[] data, int length) {
- setData(data, 0, length);
- }
-
- public void setData(byte[] data, int offset, int length) {
- if (this._data != null)
- this._data = null;
- this._data = new byte[length];
- System.arraycopy(data, offset, this._data, 0, length);
- this._jsonSize = 0;
- }
-
- public byte[] getBulkData() {
- return _bulkData;
- }
-
- public void setBulkDataNoCopy(byte[] bulkData) {
- this._bulkData = bulkData;
- }
-
- public void setBulkData(byte[] bulkData) {
- if (this._bulkData != null)
- this._bulkData = null;
- this._bulkData = new byte[bulkData.length];
- System.arraycopy(bulkData, 0, this._bulkData, 0, bulkData.length);
- //this._bulkData = bulkData;
- }
-
- public void setBulkData(byte[] bulkData, int length) {
- if (this._bulkData != null)
- this._bulkData = null;
- this._bulkData = new byte[length];
- System.arraycopy(bulkData, 0, this._bulkData, 0, length);
- //this._bulkData = bulkData;
- }
-
- public SessionType getSessionType() {
- return _sessionType;
- }
-
- public void setSessionType(SessionType sessionType) {
- this._sessionType = sessionType;
- }
-
- public MessageType getMessageType() {
- return _messageType;
- }
-
- public void setMessageType(MessageType messageType) {
- this._messageType = messageType;
- }
-
- public byte getRPCType() {
- return _rpcType;
- }
-
- public void setRPCType(byte _rpcType) {
- this._rpcType = _rpcType;
- }
-
- public int getFunctionID() {
- return _functionID;
- }
-
- public void setFunctionID(int _functionID) {
- this._functionID = _functionID;
- }
-
- public int getCorrID() {
- return _correlationID;
- }
-
- public void setCorrID(int _correlationID) {
- this._correlationID = _correlationID;
- }
-
- public int getJsonSize() {
- return _jsonSize;
- }
-
- public void setJsonSize(int _jsonSize) {
- this._jsonSize = _jsonSize;
- }
-
- public void setPayloadProtected(boolean bVal) {
- payloadProtected = bVal;
- }
-
- public boolean getPayloadProtected() {
- return payloadProtected;
- }
-
- /**
- * Set the priority for this packet. The lower the number the higher the priority. <br>0 is the highest priority and the default.
- * @param priority
- */
- public void setPriorityCoefficient(int priority){
- this.priorityCoefficient = priority;
- }
- public int getPrioirtyCoefficient(){
- return this.priorityCoefficient;
- }
-} // end-class
\ No newline at end of file diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/protocol/SdlPacket.java b/android/sdl_android/src/main/java/com/smartdevicelink/protocol/SdlPacket.java deleted file mode 100644 index b635ab3f5..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/protocol/SdlPacket.java +++ /dev/null @@ -1,437 +0,0 @@ -package com.smartdevicelink.protocol; - -import java.nio.ByteBuffer; -import java.util.HashMap; - -import com.livio.BSON.BsonEncoder; -import com.smartdevicelink.protocol.enums.FrameType; -import com.smartdevicelink.transport.utl.TransportRecord; - -import android.os.Parcel; -import android.os.ParcelFormatException; -import android.os.Parcelable; - -/** - * This class is only intended to be parcelable from the transport broker to the SDL Router Service. - * Any other binder transactions must include an additional int flag into their bundle or the parsing - * of this object will fail. - */ -public class SdlPacket implements Parcelable{ - - /** - * This is the amount of bytes added to the bundle from the router service for a specific int - * flag; this data will always and must be included. This flag is the - * TransportConstants.BYTES_TO_SEND_FLAGS. - * - * @see com.smartdevicelink.transport.TransportConstants#BYTES_TO_SEND_FLAGS - */ - private static final int EXTRA_PARCEL_DATA_LENGTH = 24; - - public static final int HEADER_SIZE = 12; - public static final int HEADER_SIZE_V1 = 8;//Backwards - - private static final int ENCRYPTION_MASK = 0x08; //4th lowest bit - - public static final int FRAME_TYPE_CONTROL = 0x00; - public static final int FRAME_TYPE_SINGLE = 0x01; - public static final int FRAME_TYPE_FIRST = 0x02; - public static final int FRAME_TYPE_CONSECUTIVE = 0x03; - - /* - * Service Type - */ - public static final int SERVICE_TYPE_CONTROL = 0x00; - //RESERVED 0x01 - 0x06 - public static final int SERVICE_TYPE_RPC = 0x07; - //RESERVED 0x08 - 0x09 - public static final int SERVICE_TYPE_PCM = 0x0A; - public static final int SERVICE_TYPE_VIDEO = 0x0B; - //RESERVED 0x0C - 0x0E - public static final int SERVICE_TYPE_BULK_DATA = 0x0F; - //RESERVED 0x10 - 0xFF - - - /* - * Frame Info - */ - //Control Frame Info - public static final int FRAME_INFO_HEART_BEAT = 0x00; - public static final int FRAME_INFO_START_SERVICE = 0x01; - public static final int FRAME_INFO_START_SERVICE_ACK = 0x02; - public static final int FRAME_INFO_START_SERVICE_NAK = 0x03; - public static final int FRAME_INFO_END_SERVICE = 0x04; - public static final int FRAME_INFO_END_SERVICE_ACK = 0x05; - public static final int FRAME_INFO_END_SERVICE_NAK = 0x06; - public static final int FRAME_INFO_REGISTER_SECONDARY_TRANSPORT = 0x07; - public static final int FRAME_INFO_REGISTER_SECONDARY_TRANSPORT_ACK = 0x08; - public static final int FRAME_INFO_REGISTER_SECONDARY_TRANSPORT_NAK = 0x09; - //0x0A-0xFC are reserved - public static final int FRAME_INFO_TRANSPORT_EVENT_UPDATE = 0xFD; - public static final int FRAME_INFO_SERVICE_DATA_ACK = 0xFE; - public static final int FRAME_INFO_HEART_BEAT_ACK = 0xFF; - - public static final int FRAME_INFO_FINAL_CONNESCUTIVE_FRAME = 0x00; - - //Most others - public static final int FRAME_INFO_RESERVED = 0x00; - - - int version; - boolean encryption; - int frameType; - int serviceType; - int frameInfo; - int sessionId; - int dataSize; - int messageId; - int priorityCoefficient; - byte[] payload = null; - HashMap<String, Object> bsonPayload; - - int messagingVersion = 1; - TransportRecord transportRecord; - - public SdlPacket(int version, boolean encryption, int frameType, - int serviceType, int frameInfo, int sessionId, - int dataSize, int messageId, byte[] payload) { - this.version = version; - this.encryption = encryption; - this.frameType = frameType; - this.serviceType = serviceType; - this.frameInfo = frameInfo; - this.sessionId = sessionId; - this.dataSize = dataSize; - this.messageId = messageId; - this.priorityCoefficient = 0; - if(payload!=null){ - this.payload = new byte[payload.length]; - System.arraycopy(payload, 0, this.payload, 0, payload.length); - } - } - - public SdlPacket(int version, boolean encryption, int frameType, - int serviceType, int frameInfo, int sessionId, - int dataSize, int messageId, byte[] payload, int offset,int bytesToWrite) { - this.version = version; - this.encryption = encryption; - this.frameType = frameType; - this.serviceType = serviceType; - this.frameInfo = frameInfo; - this.sessionId = sessionId; - this.dataSize = dataSize; - this.messageId = messageId; - this.priorityCoefficient = 0; - if(payload!=null){ - this.payload = new byte[bytesToWrite]; - System.arraycopy(payload, offset, this.payload, 0, bytesToWrite); - } - } - /** - * This constructor is available as a protected method. A few defaults have been set, however a few things <b>MUST</b> be set before use. The rest will "work" - * however, it won't be valid data. - * - * <p>Frame Type - * <p>Service Type - * <p>Frame Info - * <p> - */ - protected SdlPacket(){ - //Package only empty constructor - //TODO add defaults - this.version = 1; - this.encryption = false; - this.frameType = -1; //This NEEDS to be set - this.serviceType = -1; - this.frameInfo = -1; - this.sessionId = 0; - this.dataSize = 0; - this.messageId = 0; - - } - - /** - * Creates a new packet based on previous packet definitions - * @param packet - */ - protected SdlPacket(SdlPacket packet){ - this.version = packet.version; - this.encryption = packet.encryption; - this.frameType = packet.frameType; - this.serviceType = packet.serviceType; - this.frameInfo = packet.frameInfo; - this.sessionId = packet.sessionId; - this.dataSize = 0; - this.messageId = 0; - } - - public int getVersion() { - return version; - } - - public boolean isEncrypted() { - return encryption; - } - - public FrameType getFrameType() { - switch(frameType){ - case FRAME_TYPE_CONTROL: - return FrameType.Control; - case FRAME_TYPE_FIRST: - return FrameType.First; - case FRAME_TYPE_CONSECUTIVE: - return FrameType.Consecutive; - case FRAME_TYPE_SINGLE: - default: - return FrameType.Single; - } - } - - public int getServiceType() { - return serviceType; - } - - public int getFrameInfo() { - return frameInfo; - } - - public int getSessionId() { - return sessionId; - } - - public int getMessageId() { - return messageId; - } - - public long getDataSize() { - return dataSize; - } - - public byte[] getPayload() { - return payload; - } - - public byte[] constructPacket() { - if (bsonPayload != null && !bsonPayload.isEmpty()) { - byte[] bsonBytes = BsonEncoder.encodeToBytes(bsonPayload); - payload = bsonBytes; - dataSize = bsonBytes.length; - } - return constructPacket(version, encryption, frameType, - serviceType, frameInfo, sessionId, - dataSize, messageId, payload); - } - public void setPayload(byte[] bytes){ - this.payload = bytes; - } - /** - * Set the priority for this packet. The lower the number the higher the priority. <br>0 is the highest priority and the default. - * @param priority - */ - public void setPriorityCoefficient(int priority){ - this.priorityCoefficient = priority; - } - public int getPrioirtyCoefficient(){ - return this.priorityCoefficient; - } - - public void setTransportRecord(TransportRecord transportRecord){ - this.transportRecord = transportRecord; - } - - public TransportRecord getTransportRecord() { - return this.transportRecord; - } - - /** - * This method takes in the various components to the SDL packet structure and creates a new byte array that can be sent via the transport - * @param version - * @param encryption - * @param frameType - * @param serviceType - * @param controlFrameInfo - * @param sessionId - * @param dataSize - * @param messageId - * @param payload - * @return - */ - public static byte[] constructPacket(int version, boolean encryption, int frameType, - int serviceType, int controlFrameInfo, int sessionId, - int dataSize, int messageId, byte[] payload){ - - ByteBuffer builder; - switch(version){ - case 1: - builder = ByteBuffer.allocate(HEADER_SIZE_V1 + dataSize); - break; - default: - builder = ByteBuffer.allocate(HEADER_SIZE + dataSize); - break; - } - - builder.put((byte)((version<<4) + getEncryptionBit(encryption) + frameType)); - builder.put((byte)serviceType); - builder.put((byte)controlFrameInfo); - builder.put((byte)sessionId); - - builder.put((byte)((dataSize&0xFF000000)>>24)); - builder.put((byte)((dataSize&0x00FF0000)>>16)); - builder.put((byte)((dataSize&0x0000FF00)>>8)); - builder.put((byte)((dataSize&0x000000FF))); - - if(version>1){ //Version 1 did not include this part of the header - builder.put((byte)((messageId&0xFF000000)>>24)); - builder.put((byte)((messageId&0x00FF0000)>>16)); - builder.put((byte)((messageId&0x0000FF00)>>8)); - builder.put((byte)((messageId&0x000000FF))); - } - - if(payload!=null && payload.length>0){ - builder.put(payload); - } - - return builder.array(); - } - - - public static int getEncryptionBit(boolean encryption){ - if(encryption){ - return ENCRYPTION_MASK; - }else{ - return 0; - } - } - - - -@Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("***** Sdl Packet ******"); - builder.append( "\nVersion: " +version); - builder.append( "\nEncryption: " +encryption); - builder.append( "\nFrameType: " +frameType); - builder.append( "\nServiceType: " +serviceType); - builder.append( "\nFrameInfo: " +frameInfo); - builder.append( "\nSessionId: " +sessionId); - builder.append( "\nDataSize: " +dataSize); - if(version>1){ - builder.append( "\nMessageId: " +messageId); - } - builder.append("\n***** Sdl Packet End******"); - - - return builder.toString(); - } - - public void setMessagingVersion(int version){ - this.messagingVersion = version; - } - - - - /* *************************************************************************************************************************************************** - * *********************************************************** Parceable Overrides ***************************************************************** - *****************************************************************************************************************************************************/ - - - - //I think this is FIFO...right? - public SdlPacket(Parcel p) { - this.version = p.readInt(); - this.encryption = (p.readInt() == 0) ? false : true; - this.frameType = p.readInt(); - this.serviceType = p.readInt(); - this.frameInfo = p.readInt(); - this.sessionId = p.readInt(); - this.dataSize = p.readInt(); - this.messageId = p.readInt(); - if(p.readInt() == 1){ //We should have a payload attached - payload = new byte[dataSize]; - p.readByteArray(payload); - } - - this.priorityCoefficient = p.readInt(); - - if(p.dataAvail() > EXTRA_PARCEL_DATA_LENGTH) { //See note on constant for why not 0 - try { - messagingVersion = p.readInt(); - if (messagingVersion >= 2) { - if (p.readInt() == 1) { //We should have a transport type attached - this.transportRecord = p.readParcelable(TransportRecord.class.getClassLoader()); - } - } - }catch (ParcelFormatException e){ - - } - } - } - - - @Override - public int describeContents() { - return 0; - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - - dest.writeInt(version); - dest.writeInt(encryption? 1 : 0); - dest.writeInt(frameType); - dest.writeInt(serviceType); - dest.writeInt(frameInfo); - dest.writeInt(sessionId); - dest.writeInt(dataSize); - dest.writeInt(messageId); - dest.writeInt(payload!=null? 1 : 0); - if(payload!=null){ - dest.writeByteArray(payload); - } - dest.writeInt(priorityCoefficient); - - ///Additions after initial creation - if(messagingVersion > 1){ - dest.writeInt(messagingVersion); - - dest.writeInt(transportRecord!=null? 1 : 0); - if(transportRecord != null){ - dest.writeParcelable(transportRecord,0); - } - } - - } - - public static final Parcelable.Creator<SdlPacket> CREATOR = new Parcelable.Creator<SdlPacket>() { - public SdlPacket createFromParcel(Parcel in) { - return new SdlPacket(in); - } - - @Override - public SdlPacket[] newArray(int size) { - return new SdlPacket[size]; - } - - }; - - public void putTag(String tag, Object data){ - if(bsonPayload == null){ - bsonPayload = new HashMap<>(); - } - bsonPayload.put(tag, data); - } - - public Object getTag(String tag){ - if(payload == null){ - return null; - }else if(bsonPayload == null || bsonPayload.isEmpty()){ - bsonPayload = BsonEncoder.decodeFromBytes(payload); - } - - if(bsonPayload == null){ - return null; - } - - return bsonPayload.get(tag); - } -} diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/protocol/SdlPacketFactory.java b/android/sdl_android/src/main/java/com/smartdevicelink/protocol/SdlPacketFactory.java deleted file mode 100644 index 5a8500336..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/protocol/SdlPacketFactory.java +++ /dev/null @@ -1,114 +0,0 @@ -package com.smartdevicelink.protocol; - -import com.smartdevicelink.protocol.enums.ControlFrameTags; -import com.smartdevicelink.protocol.enums.FrameDataControlFrameType; -import com.smartdevicelink.protocol.enums.SessionType; -import com.smartdevicelink.util.BitConverter; - -public class SdlPacketFactory { - - /* - * public SdlPacket(int version, boolean compression, int frameType, - int serviceType, int frameInfo, int sessionId, - int dataSize, int messageId, byte[] payload) { - */ - public static SdlPacket createStartSession(SessionType serviceType, int messageID, byte version, byte sessionID, boolean encrypted) { - SdlPacket packet = new SdlPacket(version,encrypted,SdlPacket.FRAME_TYPE_CONTROL, - serviceType.getValue(),SdlPacket.FRAME_INFO_START_SERVICE,sessionID, - 0,messageID,null); - - return packet; - } - - public static SdlPacket createHeartbeat(SessionType serviceType, byte sessionID, byte version) { - - return new SdlPacket(version,false,SdlPacket.FRAME_TYPE_CONTROL, - serviceType.getValue(),FrameDataControlFrameType.Heartbeat.value(),sessionID, - 0,0,null); - - } - - public static SdlPacket createHeartbeatACK(SessionType serviceType, byte sessionID, byte version) { - return new SdlPacket(version,false,SdlPacket.FRAME_TYPE_CONTROL, - serviceType.getValue(),FrameDataControlFrameType.HeartbeatACK.value(),sessionID, - 0,0,null); - } - - public static SdlPacket createStartSessionACK(SessionType serviceType, byte sessionID, int messageID, byte version) { - - return new SdlPacket(version,false,SdlPacket.FRAME_TYPE_CONTROL, - serviceType.getValue(),FrameDataControlFrameType.StartSessionACK.value(),sessionID, - 0,messageID,null); - - } - - public static SdlPacket createStartSessionNACK(SessionType serviceType, byte sessionID, int messageID, byte version) { - - return new SdlPacket(version,false,SdlPacket.FRAME_TYPE_CONTROL, - serviceType.getValue(),SdlPacket.FRAME_INFO_START_SERVICE_NAK,sessionID, - 0,messageID,null); - } - - public static SdlPacket createEndSession(SessionType serviceType, byte sessionID, int messageID, byte version, byte[] payload) { - return new SdlPacket(version,false,SdlPacket.FRAME_TYPE_CONTROL, - serviceType.getValue(),SdlPacket.FRAME_INFO_END_SERVICE,sessionID, - payload.length,messageID,payload); - } - - public static SdlPacket createEndSession(SessionType serviceType, byte sessionID, int messageID, byte version, int hashID) { - if (version < 5) { - byte[] payload = BitConverter.intToByteArray(hashID); - return new SdlPacket(version, false, SdlPacket.FRAME_TYPE_CONTROL, - serviceType.getValue(), SdlPacket.FRAME_INFO_END_SERVICE, sessionID, - payload.length, messageID, payload); - } else { - SdlPacket endSession = new SdlPacket(version, false, SdlPacket.FRAME_TYPE_CONTROL, - serviceType.getValue(), SdlPacket.FRAME_INFO_END_SERVICE, sessionID, - 0, messageID, null); - endSession.putTag(ControlFrameTags.RPC.EndService.HASH_ID, hashID); - return endSession; - } - } - - public static SdlPacket createSingleSendData(SessionType serviceType, byte sessionID, - int dataLength, int messageID, byte version, byte[] payload, boolean encrypted) { - - return new SdlPacket(version,encrypted,SdlPacket.FRAME_TYPE_SINGLE, - serviceType.getValue(),0,sessionID, - payload.length,messageID,payload); - } - - public static SdlPacket createMultiSendDataFirst(SessionType serviceType, byte sessionID, - int messageID, byte version, byte[] payload, boolean encrypted) { - - return new SdlPacket(version,encrypted,SdlPacket.FRAME_TYPE_FIRST, - serviceType.getValue(),0,sessionID, - 8,messageID,payload); - - } - - public static SdlPacket createMultiSendDataRest(SessionType serviceType, byte sessionID, - int dataLength, byte frameSequenceNumber, int messageID, byte version, byte[] payload,int offset,int length, boolean encrypted) { - - return new SdlPacket(version,encrypted,SdlPacket.FRAME_TYPE_CONSECUTIVE, - serviceType.getValue(),frameSequenceNumber,sessionID, - length,messageID,payload,offset,length); - } - - public static SdlPacket createRegisterSecondaryTransport(byte sessionID, byte version) { - return new SdlPacket(version, false, SdlPacket.FRAME_TYPE_CONTROL, - SessionType.CONTROL.getValue(), SdlPacket.FRAME_INFO_REGISTER_SECONDARY_TRANSPORT, - sessionID, 0, 0x01, null); - } - - public static BinaryFrameHeader createBinaryFrameHeader(byte rpcType, int functionID, int corrID, int jsonSize) { - BinaryFrameHeader msg = new BinaryFrameHeader(); - msg.setRPCType(rpcType); - msg.setFunctionID(functionID); - msg.setCorrID(corrID); - msg.setJsonSize(jsonSize); - - return msg; - } - -} diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/protocol/SdlProtocol.java b/android/sdl_android/src/main/java/com/smartdevicelink/protocol/SdlProtocol.java index 55715637f..da3696443 100644 --- a/android/sdl_android/src/main/java/com/smartdevicelink/protocol/SdlProtocol.java +++ b/android/sdl_android/src/main/java/com/smartdevicelink/protocol/SdlProtocol.java @@ -32,415 +32,26 @@ package com.smartdevicelink.protocol; -import android.os.Bundle; import android.support.annotation.NonNull; -import android.util.Log; -import com.smartdevicelink.exception.SdlException; -import com.smartdevicelink.exception.SdlExceptionCause; -import com.smartdevicelink.protocol.enums.ControlFrameTags; -import com.smartdevicelink.protocol.enums.FrameDataControlFrameType; -import com.smartdevicelink.protocol.enums.FrameType; -import com.smartdevicelink.protocol.enums.MessageType; import com.smartdevicelink.protocol.enums.SessionType; -import com.smartdevicelink.proxy.rpc.ImageResolution; -import com.smartdevicelink.proxy.rpc.VideoStreamingFormat; -import com.smartdevicelink.proxy.rpc.enums.VideoStreamingCodec; -import com.smartdevicelink.proxy.rpc.enums.VideoStreamingProtocol; -import com.smartdevicelink.security.SdlSecurityBase; -import com.smartdevicelink.streaming.video.VideoStreamingParameters; import com.smartdevicelink.transport.MultiplexTransportConfig; -import com.smartdevicelink.transport.TransportConstants; + import com.smartdevicelink.transport.TransportManager; -import com.smartdevicelink.transport.enums.TransportType; -import com.smartdevicelink.transport.utl.TransportRecord; -import com.smartdevicelink.util.BitConverter; -import com.smartdevicelink.util.DebugTool; -import com.smartdevicelink.util.Version; -import java.io.ByteArrayOutputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Hashtable; -import java.util.List; -import java.util.Map; @SuppressWarnings("WeakerAccess") -public class SdlProtocol { +public class SdlProtocol extends SdlProtocolBase { private static final String TAG ="SdlProtocol"; - private final static String FailurePropagating_Msg = "Failure propagating "; - - private static final int TLS_MAX_RECORD_SIZE = 16384; - - private static final int PRIMARY_TRANSPORT_ID = 1; - private static final int SECONDARY_TRANSPORT_ID = 2; - - /** - * Original header size based on version 1.0.0 only - */ - public static final int V1_HEADER_SIZE = 8; - /** - * Larger header size that is used by versions 2.0.0 and up - */ - public static final int V2_HEADER_SIZE = 12; - - //If increasing MAX PROTOCOL VERSION major version, make sure to alter it in SdlPsm - private static final Version MAX_PROTOCOL_VERSION = new Version("5.1.0"); - - public static final int V1_V2_MTU_SIZE = 1500; - public static final int V3_V4_MTU_SIZE = 131072; - - private static final List<SessionType> HIGH_BANDWIDTH_SERVICES - = Arrays.asList(SessionType.NAV, SessionType.PCM); - - // Lock to ensure all frames are sent uninterrupted - private final Object FRAME_LOCK = new Object(); - - private final ISdlProtocol iSdlProtocol; - private final MultiplexTransportConfig transportConfig; - private final Hashtable<Integer, MessageFrameAssembler> _assemblerForMessageID = new Hashtable<>(); - private final Hashtable<Byte, Object> _messageLocks = new Hashtable<>(); - private final HashMap<SessionType, Long> mtus = new HashMap<>(); - private final HashMap<SessionType, TransportRecord> activeTransports = new HashMap<>(); - private final Map<TransportType, List<ISecondaryTransportListener>> secondaryTransportListeners = new HashMap<>(); - - - private TransportManager transportManager; - private Version protocolVersion = new Version("1.0.0"); - private int hashID = 0; - private int messageID = 0; - private int headerSize = V1_HEADER_SIZE; - - /** - * Requested transports for primary and secondary - */ - List<TransportType> requestedPrimaryTransports, requestedSecondaryTransports; - - /** - * List of secondary transports supported by the module - */ - List<TransportType> supportedSecondaryTransports; - - /** - * Holds the priority of transports for a specific service when that service can be started - * on a primary or secondary transport. - */ - Map<SessionType, List<Integer>> transportPriorityForServiceMap; - boolean requiresHighBandwidth; - Map<TransportType, Bundle> secondaryTransportParams; - TransportRecord connectedPrimaryTransport; @SuppressWarnings("ConstantConditions") public SdlProtocol(@NonNull ISdlProtocol iSdlProtocol, @NonNull MultiplexTransportConfig config) { - if (iSdlProtocol == null ) { - throw new IllegalArgumentException("Provided protocol listener interface reference is null"); - } // end-if - - this.iSdlProtocol = iSdlProtocol; - this.transportConfig = config; - this.requestedPrimaryTransports = this.transportConfig.getPrimaryTransports(); - this.requestedSecondaryTransports = this.transportConfig.getSecondaryTransports(); - this.requiresHighBandwidth = this.transportConfig.requiresHighBandwidth(); - this.transportManager = new TransportManager(transportConfig, transportEventListener); - - - mtus.put(SessionType.RPC, (long) (V1_V2_MTU_SIZE - headerSize)); - } // end-ctor - - - public void start(){ - transportManager.start(); - - } - /** - * Retrieves the max payload size for a packet to be sent to the module - * @return the max transfer unit - */ - public int getMtu(){ - return mtus.get(SessionType.RPC).intValue(); - } - - public long getMtu(SessionType type){ - Long mtu = mtus.get(type); - if(mtu == null){ - mtu = mtus.get(SessionType.RPC); - } - return mtu; - } - - public void resetSession (){ - transportManager.resetSession(); - } - - public boolean isConnected(){ - return transportManager != null && transportManager.isConnected(null,null); - } - - /** - * Resets the protocol to init status - */ - protected void reset(){ - protocolVersion = new Version("1.0.0"); - hashID = 0; - messageID = 0; - headerSize = V1_HEADER_SIZE; - this.activeTransports.clear(); - this.mtus.clear(); - mtus.put(SessionType.RPC, (long) (V1_V2_MTU_SIZE - headerSize)); - this.secondaryTransportParams = null; - this._assemblerForMessageID.clear(); - this._messageLocks.clear(); - } - - /** - * For logging purposes, prints active services on each connected transport - */ - protected void printActiveTransports(){ - StringBuilder activeTransportString = new StringBuilder(); - activeTransportString.append("Active transports --- \n"); - - for(Map.Entry entry : activeTransports.entrySet()){ - String sessionString = null; - if(entry.getKey().equals(SessionType.NAV)) { - sessionString = "NAV"; - }else if(entry.getKey().equals(SessionType.PCM)) { - sessionString = "PCM"; - }else if(entry.getKey().equals(SessionType.RPC)) { - sessionString = "RPC"; - } - if(sessionString != null){ - activeTransportString.append("Session: "); - - activeTransportString.append(sessionString); - activeTransportString.append(" Transport: "); - activeTransportString.append(entry.getValue().toString()); - activeTransportString.append("\n"); - } - } - Log.d(TAG, activeTransportString.toString()); - } - - protected void printSecondaryTransportDetails(List<String> secondary, List<Integer> audio, List<Integer> video){ - StringBuilder secondaryDetailsBldr = new StringBuilder(); - secondaryDetailsBldr.append("Checking secondary transport details \n"); - - if(secondary != null){ - secondaryDetailsBldr.append("Supported secondary transports: "); - for(String s : secondary){ - secondaryDetailsBldr.append(" ").append(s); - } - secondaryDetailsBldr.append("\n"); - }else{ - Log.d(TAG, "Supported secondary transports list is empty!"); - } - if(audio != null){ - secondaryDetailsBldr.append("Supported audio transports: "); - for(int a : audio){ - secondaryDetailsBldr.append(" ").append(a); - } - secondaryDetailsBldr.append("\n"); - } - if(video != null){ - secondaryDetailsBldr.append("Supported video transports: "); - for(int v : video){ - secondaryDetailsBldr.append(" ").append(v); - } - secondaryDetailsBldr.append("\n"); - } - - Log.d(TAG, secondaryDetailsBldr.toString()); - } - - - private TransportRecord getTransportForSession(SessionType type){ - return activeTransports.get(type); - } - - private void setTransportPriorityForService(SessionType serviceType, List<Integer> order){ - if(transportPriorityForServiceMap == null){ - transportPriorityForServiceMap = new HashMap<>(); - } - this.transportPriorityForServiceMap.put(serviceType, order); - for(SessionType service : HIGH_BANDWIDTH_SERVICES){ - if (transportPriorityForServiceMap.get(service) != null - && transportPriorityForServiceMap.get(service).contains(PRIMARY_TRANSPORT_ID)) { - if(connectedPrimaryTransport != null) { - activeTransports.put(service, connectedPrimaryTransport); - } - } - } - } - - /** - * Handles when a secondary transport can be used to start services on or when the request as failed. - * @param transportRecord the transport type that the event has taken place on - * @param registered if the transport was successfully registered on - */ - private void handleSecondaryTransportRegistration(TransportRecord transportRecord, boolean registered){ - if(registered) { - //Session has been registered on secondary transport - Log.d(TAG, transportRecord.getType().toString() + " transport was registered!"); - if (supportedSecondaryTransports.contains(transportRecord.getType())) { - // If the transport type that is now available to be used it should be checked - // against the list of services that might be able to be started on it - - for(SessionType secondaryService : HIGH_BANDWIDTH_SERVICES){ - if (transportPriorityForServiceMap.containsKey(secondaryService)) { - // If this service type has extra information from the RPC StartServiceACK - // parse through it to find which transport should be used to start this - // specific service type - for(int transportNum : transportPriorityForServiceMap.get(secondaryService)){ - if(transportNum == PRIMARY_TRANSPORT_ID){ - break; // Primary is favored for this service type, break out... - }else if(transportNum == SECONDARY_TRANSPORT_ID){ - // The secondary transport can be used to start this service - activeTransports.put(secondaryService, transportRecord); - break; - } - } - } - } - } - }else{ - Log.d(TAG, transportRecord.toString() + " transport was NOT registered!"); - } - //Notify any listeners for this secondary transport - List<ISecondaryTransportListener> listenerList = secondaryTransportListeners.remove(transportRecord.getType()); - if(listenerList != null){ - for(ISecondaryTransportListener listener : listenerList){ - if(registered) { - listener.onConnectionSuccess(transportRecord); - }else{ - listener.onConnectionFailure(); - } - } - } - - if(DebugTool.isDebugEnabled()){ - printActiveTransports(); - } - } - - private void onTransportsConnectedUpdate(List<TransportRecord> transports){ - //Log.d(TAG, "Connected transport update"); - - //Temporary: this logic should all be changed to handle multiple transports of the same type - ArrayList<TransportType> connectedTransports = new ArrayList<>(); - if(transports != null) { - for (TransportRecord record : transports) { - connectedTransports.add(record.getType()); - } - } - - if(connectedPrimaryTransport != null && !connectedTransports.contains(connectedPrimaryTransport.getType())){ - //The primary transport being used is no longer part of the connected transports - //The transport manager callbacks should handle the disconnect code - connectedPrimaryTransport = null; - notifyDevTransportListener(); - return; - } - - if(activeTransports.get(SessionType.RPC) == null){ - //There is no currently active transport for the RPC service meaning no primary transport - TransportRecord preferredPrimaryTransport = getPreferredTransport(requestedPrimaryTransports,transports); - if(preferredPrimaryTransport != null) { - connectedPrimaryTransport = preferredPrimaryTransport; - startService(SessionType.RPC, (byte) 0x00, false); - }else{ - onTransportNotAccepted("No transports match requested primary transport"); - } - //Return to that the developer does not receive the transport callback at this time - // as it is better to wait until the RPC service is registered and secondary transport - //information is available - return; - }else if(secondaryTransportListeners != null - && transports != null - && iSdlProtocol!= null){ - // Check to see if there is a listener for a given transport. - // If a listener exists, it can be assumed that the transport should be registered on - for(TransportRecord record: transports){ - if(secondaryTransportListeners.get(record.getType()) != null - && !secondaryTransportListeners.get(record.getType()).isEmpty()){ - registerSecondaryTransport(iSdlProtocol.getSessionId(), record); - } - } - } - //Update the developer that a new transport has become available - notifyDevTransportListener(); - } - - - /** - * Check to see if a transport is available to start/use the supplied service. - * @param serviceType the session that should be checked for transport availability - * @return true if there is either a supported - * transport currently connected or a transport is - * available to connect with for the supplied service type. - * <br>false if there is no - * transport connected to support the service type in question and - * no possibility in the foreseeable future. - */ - public boolean isTransportForServiceAvailable(@NonNull SessionType serviceType){ - if(connectedPrimaryTransport == null){ - //If there is no connected primary then there is no transport available for any service - return false; - }else if(activeTransports!= null && activeTransports.containsKey(serviceType)){ - //There is an active transport that this service can be used on - //This should catch RPC, Bulk, and Control service types - return true; - } - - if(transportPriorityForServiceMap != null) { - List<Integer> transportPriority = transportPriorityForServiceMap.get(serviceType); - - if (transportPriority != null && !transportPriority.isEmpty()) { - if (transportPriority.contains(PRIMARY_TRANSPORT_ID)) { - //If the transport priority for this service type contains primary then - // the service can be used/started - return true; - } else if (transportPriority.contains(SECONDARY_TRANSPORT_ID)) { - //This would mean only secondary transport is supported for this service - return isSecondaryTransportAvailable(false); - } - } - } - - //No transport priority for this service type - if(connectedPrimaryTransport.getType() == TransportType.USB || connectedPrimaryTransport.getType() == TransportType.TCP){ - //Since the only service type that should reach this point are ones that require a high - //bandwidth, true can be returned if the primary transport is a high bandwidth transport - return true; - }else{ - //Since the only service type that should reach this point are ones that require a high - //bandwidth, true can be returned if a secondary transport is a high bandwidth transport - return isSecondaryTransportAvailable(true); - } - } - - /** - * Checks to see if a secondary transport is available for this session - * @param onlyHighBandwidth if only high bandwidth transports should be included in this check - * @return true if any connected or potential transport meets the criteria to be a secondary - * transport - */ - private boolean isSecondaryTransportAvailable(boolean onlyHighBandwidth){ - if (supportedSecondaryTransports != null) { - for (TransportType supportedSecondary : supportedSecondaryTransports) { - if(!onlyHighBandwidth || supportedSecondary == TransportType.USB || supportedSecondary == TransportType.TCP) { - if (transportManager.isConnected(supportedSecondary, null)) { - //A supported secondary transport is already connected - return true; - } else if (secondaryTransportParams != null && secondaryTransportParams.containsKey(supportedSecondary)) { - //A secondary transport is available to connect to - return true; - } - } - } - } - // No supported secondary transports - return false; + super(iSdlProtocol,config); + this.requestedPrimaryTransports = config.getPrimaryTransports(); + this.requestedSecondaryTransports = config.getSecondaryTransports(); + this.requiresHighBandwidth = config.requiresHighBandwidth(); + this.setTransportManager(new TransportManager(config,transportEventListener)); } @@ -448,994 +59,13 @@ public class SdlProtocol { * If there was a TransportListener attached to the supplied multiplex config, this method will * call the onTransportEvent method. */ - private void notifyDevTransportListener (){ + @Override + void notifyDevTransportListener (){ + MultiplexTransportConfig transportConfig = (MultiplexTransportConfig)this.transportConfig; if(transportConfig.getTransportListener() != null && transportManager != null) { transportConfig.getTransportListener().onTransportEvent(transportManager.getConnectedTransports(), isTransportForServiceAvailable(SessionType.PCM),isTransportForServiceAvailable(SessionType.NAV)); } } - /** - * Retrieves the preferred transport for the given connected transport - * @param preferredList the list of preferred transports (primary or secondary) - * @param connectedTransports the current list of connected transports - * @return the preferred connected transport - */ - private TransportRecord getPreferredTransport(List<TransportType> preferredList, List<TransportRecord> connectedTransports) { - for (TransportType transportType : preferredList) { - for(TransportRecord record: connectedTransports) { - if (record.getType().equals(transportType)) { - return record; - } - } - } - return null; - } - - private void onTransportNotAccepted(String info){ - if(iSdlProtocol != null) { - iSdlProtocol.shutdown(info); - } - } - - - public Version getProtocolVersion(){ - return this.protocolVersion; - } - - /** - * This method will set the major protocol version that we should use. It will also set the default MTU based on version. - * @param version major version to use - */ - protected void setVersion(byte version) { - if (version > 5) { - this.protocolVersion = new Version("5.0.0"); //protect for future, proxy only supports v5 or lower - headerSize = V2_HEADER_SIZE; - mtus.put(SessionType.RPC, (long) V3_V4_MTU_SIZE); - } else if (version == 5) { - this.protocolVersion = new Version("5.0.0"); - headerSize = V2_HEADER_SIZE; - mtus.put(SessionType.RPC, (long) V3_V4_MTU_SIZE); - }else if (version == 4) { - this.protocolVersion = new Version("4.0.0"); - headerSize = V2_HEADER_SIZE; - mtus.put(SessionType.RPC, (long) V3_V4_MTU_SIZE); //versions 4 supports 128k MTU - } else if (version == 3) { - this.protocolVersion = new Version("3.0.0"); - headerSize = V2_HEADER_SIZE; - mtus.put(SessionType.RPC, (long) V3_V4_MTU_SIZE); //versions 3 supports 128k MTU - } else if (version == 2) { - this.protocolVersion = new Version("2.0.0"); - headerSize = V2_HEADER_SIZE; - mtus.put(SessionType.RPC, (long) (V1_V2_MTU_SIZE - headerSize)); - } else if (version == 1){ - this.protocolVersion = new Version("1.0.0"); - headerSize = V1_HEADER_SIZE; - mtus.put(SessionType.RPC, (long) (V1_V2_MTU_SIZE - headerSize)); - } - } - - public void endSession(byte sessionID, int hashId) { - SdlPacket header = SdlPacketFactory.createEndSession(SessionType.RPC, sessionID, hashId, (byte)protocolVersion.getMajor(), hashId); - handlePacketToSend(header); - - } // end-method - - public void sendPacket(SdlPacket packet){ - if(transportManager != null){ - transportManager.sendPacket(packet); - } - } - - public void sendMessage(ProtocolMessage protocolMsg) { - SessionType sessionType = protocolMsg.getSessionType(); - byte sessionID = protocolMsg.getSessionID(); - - byte[] data; - if (protocolVersion.getMajor() > 1 && sessionType != SessionType.NAV && sessionType != SessionType.PCM) { - if (sessionType.eq(SessionType.CONTROL)) { - final byte[] secureData = protocolMsg.getData().clone(); - data = new byte[headerSize + secureData.length]; - - final BinaryFrameHeader binFrameHeader = - SdlPacketFactory.createBinaryFrameHeader(protocolMsg.getRPCType(),protocolMsg.getFunctionID(), protocolMsg.getCorrID(), 0); - System.arraycopy(binFrameHeader.assembleHeaderBytes(), 0, data, 0, headerSize); - System.arraycopy(secureData, 0, data, headerSize, secureData.length); - } - else if (protocolMsg.getBulkData() != null) { - data = new byte[12 + protocolMsg.getJsonSize() + protocolMsg.getBulkData().length]; - sessionType = SessionType.BULK_DATA; - } else { - data = new byte[12 + protocolMsg.getJsonSize()]; - } - if (!sessionType.eq(SessionType.CONTROL)) { - BinaryFrameHeader binFrameHeader = SdlPacketFactory.createBinaryFrameHeader(protocolMsg.getRPCType(), protocolMsg.getFunctionID(), protocolMsg.getCorrID(), protocolMsg.getJsonSize()); - System.arraycopy(binFrameHeader.assembleHeaderBytes(), 0, data, 0, 12); - System.arraycopy(protocolMsg.getData(), 0, data, 12, protocolMsg.getJsonSize()); - if (protocolMsg.getBulkData() != null) { - System.arraycopy(protocolMsg.getBulkData(), 0, data, 12 + protocolMsg.getJsonSize(), protocolMsg.getBulkData().length); - } - } - } else { - data = protocolMsg.getData(); - } - - if (iSdlProtocol != null && protocolMsg.getPayloadProtected()){ - - if (data != null && data.length > 0) { - byte[] dataToRead = new byte[TLS_MAX_RECORD_SIZE]; - SdlSecurityBase sdlSec = iSdlProtocol.getSdlSecurity(); - if (sdlSec == null) - return; - - Integer iNumBytes = sdlSec.encryptData(data, dataToRead); - if ((iNumBytes == null) || (iNumBytes <= 0)) - return; - - byte[] encryptedData = new byte[iNumBytes]; - System.arraycopy(dataToRead, 0, encryptedData, 0, iNumBytes); - data = encryptedData; - } - } - - // Get the message lock for this protocol session - Object messageLock = _messageLocks.get(sessionID); - if (messageLock == null) { - handleProtocolError("Error sending protocol message to SDL.", - new SdlException("Attempt to send protocol message prior to startSession ACK.", SdlExceptionCause.SDL_UNAVAILABLE)); - return; - } - - synchronized(messageLock) { - if (data.length > getMtu(sessionType)) { - - messageID++; - - // Assemble first frame. - Long mtu = getMtu(sessionType); - int frameCount = Long.valueOf(data.length / mtu).intValue(); - if (data.length % mtu > 0) { - frameCount++; - } - byte[] firstFrameData = new byte[8]; - // First four bytes are data size. - System.arraycopy(BitConverter.intToByteArray(data.length), 0, firstFrameData, 0, 4); - // Second four bytes are frame count. - System.arraycopy(BitConverter.intToByteArray(frameCount), 0, firstFrameData, 4, 4); - - SdlPacket firstHeader = SdlPacketFactory.createMultiSendDataFirst(sessionType, sessionID, messageID, (byte)protocolVersion.getMajor(),firstFrameData,protocolMsg.getPayloadProtected()); - firstHeader.setPriorityCoefficient(1+protocolMsg.priorityCoefficient); - firstHeader.setTransportRecord(activeTransports.get(sessionType)); - //Send the first frame - handlePacketToSend(firstHeader); - - int currentOffset = 0; - byte frameSequenceNumber = 0; - - for (int i = 0; i < frameCount; i++) { - if (i < (frameCount - 1)) { - ++frameSequenceNumber; - if (frameSequenceNumber == - SdlPacket.FRAME_INFO_FINAL_CONNESCUTIVE_FRAME) { - // we can't use 0x00 as frameSequenceNumber, because - // it's reserved for the last frame - ++frameSequenceNumber; - } - } else { - frameSequenceNumber = SdlPacket.FRAME_INFO_FINAL_CONNESCUTIVE_FRAME; - } // end-if - - int bytesToWrite = data.length - currentOffset; - if (bytesToWrite > mtu) { - bytesToWrite = mtu.intValue(); - } - SdlPacket consecHeader = SdlPacketFactory.createMultiSendDataRest(sessionType, sessionID, bytesToWrite, frameSequenceNumber , messageID, (byte)protocolVersion.getMajor(),data, currentOffset, bytesToWrite, protocolMsg.getPayloadProtected()); - consecHeader.setTransportRecord(activeTransports.get(sessionType)); - consecHeader.setPriorityCoefficient(i+2+protocolMsg.priorityCoefficient); - handlePacketToSend(consecHeader); - currentOffset += bytesToWrite; - } - } else { - messageID++; - SdlPacket header = SdlPacketFactory.createSingleSendData(sessionType, sessionID, data.length, messageID, (byte)protocolVersion.getMajor(),data, protocolMsg.getPayloadProtected()); - header.setPriorityCoefficient(protocolMsg.priorityCoefficient); - header.setTransportRecord(activeTransports.get(sessionType)); - handlePacketToSend(header); - } - } - } - - protected void handlePacketReceived(SdlPacket packet){ - //Check for a version difference - if (protocolVersion == null || protocolVersion.getMajor() == 1) { - setVersion((byte)packet.version); - } - - MessageFrameAssembler assembler = getFrameAssemblerForFrame(packet); - assembler.handleFrame(packet); - - } - - - protected MessageFrameAssembler getFrameAssemblerForFrame(SdlPacket packet) { - Integer iSessionId = packet.getSessionId(); - Byte bySessionId = iSessionId.byteValue(); - - MessageFrameAssembler ret = _assemblerForMessageID.get(packet.getMessageId()); - if (ret == null) { - ret = new MessageFrameAssembler(); - _assemblerForMessageID.put(packet.getMessageId(), ret); - } // end-if - - return ret; - } // end-method - - - - private void registerSecondaryTransport(byte sessionId, TransportRecord transportRecord) { - SdlPacket header = SdlPacketFactory.createRegisterSecondaryTransport(sessionId, (byte)protocolVersion.getMajor()); - header.setTransportRecord(transportRecord); - handlePacketToSend(header); - } - - public void startService(SessionType serviceType, byte sessionID, boolean isEncrypted) { - final SdlPacket header = SdlPacketFactory.createStartSession(serviceType, 0x00, (byte)protocolVersion.getMajor(), sessionID, isEncrypted); - if(SessionType.RPC.equals(serviceType)){ - if(connectedPrimaryTransport != null) { - header.setTransportRecord(connectedPrimaryTransport); - } - //This is going to be our primary transport - header.putTag(ControlFrameTags.RPC.StartService.PROTOCOL_VERSION, MAX_PROTOCOL_VERSION.toString()); - handlePacketToSend(header); - return; // We don't need to go any further - }else if(serviceType.equals(SessionType.NAV)){ - if(iSdlProtocol != null){ - VideoStreamingParameters videoStreamingParameters = iSdlProtocol.getDesiredVideoParams(); - if(videoStreamingParameters != null) { - ImageResolution desiredResolution = videoStreamingParameters.getResolution(); - VideoStreamingFormat desiredFormat = videoStreamingParameters.getFormat(); - if (desiredResolution != null) { - header.putTag(ControlFrameTags.Video.StartService.WIDTH, desiredResolution.getResolutionWidth()); - header.putTag(ControlFrameTags.Video.StartService.HEIGHT, desiredResolution.getResolutionHeight()); - } - if (desiredFormat != null) { - header.putTag(ControlFrameTags.Video.StartService.VIDEO_CODEC, desiredFormat.getCodec().toString()); - header.putTag(ControlFrameTags.Video.StartService.VIDEO_PROTOCOL, desiredFormat.getProtocol().toString()); - } - } - } - } - if(transportPriorityForServiceMap == null - || transportPriorityForServiceMap.get(serviceType) == null - || transportPriorityForServiceMap.get(serviceType).isEmpty()){ - //If there is no transport priority for this service it can be assumed it's primary - header.setTransportRecord(connectedPrimaryTransport); - handlePacketToSend(header); - return; - } - int transportPriority = transportPriorityForServiceMap.get(serviceType).get(0); - if(transportPriority == PRIMARY_TRANSPORT_ID){ - // Primary is favored, and we're already connected... - header.setTransportRecord(connectedPrimaryTransport); - handlePacketToSend(header); - }else if(transportPriority == SECONDARY_TRANSPORT_ID) { - // Secondary is favored - for(TransportType secondaryTransportType : supportedSecondaryTransports) { - - if(!requestedSecondaryTransports.contains(secondaryTransportType)){ - // Secondary transport is not accepted by the client - continue; - } - - if(activeTransports.get(serviceType) != null - && activeTransports.get(serviceType).getType() !=null - && activeTransports.get(serviceType).getType().equals(secondaryTransportType)){ - // Transport is already active and accepted - header.setTransportRecord(activeTransports.get(serviceType)); - handlePacketToSend(header); - return; - } - - - - //If the secondary transport isn't connected yet that will have to be performed first - - List<ISecondaryTransportListener> listenerList = secondaryTransportListeners.get(secondaryTransportType); - if(listenerList == null){ - listenerList = new ArrayList<>(); - secondaryTransportListeners.put(secondaryTransportType, listenerList); - } - - //Check to see if the primary transport can also be used as a backup - final boolean primaryTransportBackup = transportPriorityForServiceMap.get(serviceType).contains(PRIMARY_TRANSPORT_ID); - - ISecondaryTransportListener secondaryListener = new ISecondaryTransportListener() { - @Override - public void onConnectionSuccess(TransportRecord transportRecord) { - header.setTransportRecord(transportRecord); - handlePacketToSend(header); - } - - @Override - public void onConnectionFailure() { - if(primaryTransportBackup) { - // Primary is also supported as backup - header.setTransportRecord(connectedPrimaryTransport); - handlePacketToSend(header); - }else{ - Log.d(TAG, "Failed to connect secondary transport, threw away StartService"); - } - } - }; - - if(transportManager.isConnected(secondaryTransportType,null)){ - //The transport is actually connected, however no service has been registered - listenerList.add(secondaryListener); - registerSecondaryTransport(sessionID,transportManager.getTransportRecord(secondaryTransportType,null)); - }else if(secondaryTransportParams != null && secondaryTransportParams.containsKey(secondaryTransportType)) { - //No acceptable secondary transport is connected, so first one must be connected - header.setTransportRecord(new TransportRecord(secondaryTransportType,"")); - listenerList.add(secondaryListener); - transportManager.requestSecondaryTransportConnection(sessionID,secondaryTransportParams.get(secondaryTransportType)); - }else{ - Log.w(TAG, "No params to connect to secondary transport"); - //Unable to register or start a secondary connection. Use the callback in case - //there is a chance to use the primary transport for this service. - secondaryListener.onConnectionFailure(); - } - - } - } - } - - private void sendHeartBeatACK(SessionType sessionType, byte sessionID) { - final SdlPacket heartbeat = SdlPacketFactory.createHeartbeatACK(SessionType.CONTROL, sessionID, (byte)protocolVersion.getMajor()); - heartbeat.setTransportRecord(activeTransports.get(sessionType)); - handlePacketToSend(heartbeat); - } - - public void endService(SessionType serviceType, byte sessionID) { - if(serviceType.equals(SessionType.RPC)){ //RPC session will close all other sessions so we want to make sure we use the correct EndProtocolSession method - endSession(sessionID,hashID); - }else { - SdlPacket header = SdlPacketFactory.createEndSession(serviceType, sessionID, hashID, (byte)protocolVersion.getMajor(), new byte[0]); - TransportRecord transportRecord = activeTransports.get(serviceType); - if(transportRecord != null){ - header.setTransportRecord(transportRecord); - handlePacketToSend(header); - } - } - } - - /* -------------------------------------------------------------------------------------------- - ----------------------------------- OLD ABSTRACT PROTOCOL --------------------------------- - -------------------------------------------------------------------------------------------*/ - - - // This method is called whenever a protocol has an entire frame to send - /** - * SdlPacket should have included payload at this point. - * @param packet packet that will be sent to the router service - */ - protected void handlePacketToSend(SdlPacket packet) { - synchronized(FRAME_LOCK) { - - if(packet!=null){ - iSdlProtocol.onProtocolMessageBytesToSend(packet); - } - - } - } - - /** This method handles the end of a protocol session. A callback is - * sent to the protocol listener. - **/ - protected void handleServiceEndedNAK(SdlPacket packet, SessionType serviceType) { - if(packet.version >= 5){ - if(DebugTool.isDebugEnabled()) { - //Currently this is only during a debugging session. Might pass back in the future - String rejectedTag = null; - if (serviceType.equals(SessionType.RPC)) { - rejectedTag = ControlFrameTags.RPC.EndServiceNAK.REJECTED_PARAMS; - } else if (serviceType.equals(SessionType.PCM)) { - rejectedTag = ControlFrameTags.Audio.EndServiceNAK.REJECTED_PARAMS; - } else if (serviceType.equals(SessionType.NAV)) { - rejectedTag = ControlFrameTags.Video.EndServiceNAK.REJECTED_PARAMS; - } - - List<String> rejectedParams = (List<String>) packet.getTag(rejectedTag); - if(rejectedParams != null && rejectedParams.size() > 0){ - StringBuilder builder = new StringBuilder(); - builder.append("Rejected params for service type "); - builder.append(serviceType.getName()); - builder.append(" :"); - for(String rejectedParam : rejectedParams){ - builder.append(rejectedParam); - builder.append(" "); - } - DebugTool.logWarning(builder.toString()); - } - - } - } - - iSdlProtocol.onProtocolSessionEndedNACKed(serviceType, (byte)packet.getSessionId(), ""); - } - - // This method handles the end of a protocol session. A callback is - // sent to the protocol listener. - protected void handleServiceEnded(SdlPacket packet, SessionType sessionType) { - - iSdlProtocol.onProtocolSessionEnded(sessionType, (byte)packet.getSessionId(), ""); - - } - - /** - * This method handles the startup of a protocol session. A callback is sent - * to the protocol listener. - * @param packet StarServiceACK packet - * @param serviceType the service type that has just been started - */ - protected void handleProtocolSessionStarted(SdlPacket packet, SessionType serviceType) { - // Use this sessionID to create a message lock - Object messageLock = _messageLocks.get((byte)packet.getSessionId()); - if (messageLock == null) { - messageLock = new Object(); - _messageLocks.put((byte)packet.getSessionId(), messageLock); - } - if(packet.version >= 5){ - String mtuTag = null; - if(serviceType.equals(SessionType.RPC)){ - mtuTag = ControlFrameTags.RPC.StartServiceACK.MTU; - }else if(serviceType.equals(SessionType.PCM)){ - mtuTag = ControlFrameTags.Audio.StartServiceACK.MTU; - }else if(serviceType.equals(SessionType.NAV)){ - mtuTag = ControlFrameTags.Video.StartServiceACK.MTU; - } - Object mtu = packet.getTag(mtuTag); - if(mtu!=null){ - mtus.put(serviceType,(Long) packet.getTag(mtuTag)); - } - if(serviceType.equals(SessionType.RPC)){ - hashID = (Integer) packet.getTag(ControlFrameTags.RPC.StartServiceACK.HASH_ID); - Object version = packet.getTag(ControlFrameTags.RPC.StartServiceACK.PROTOCOL_VERSION); - - if(version!=null) { - //At this point we have confirmed the negotiated version between the module and the proxy - protocolVersion = new Version((String) version); - }else{ - protocolVersion = new Version("5.0.0"); - } - - //Check to make sure this is a transport we are willing to accept - TransportRecord transportRecord = packet.getTransportRecord(); - - if(transportRecord == null || !requestedPrimaryTransports.contains(transportRecord.getType())){ - onTransportNotAccepted("Transport is not in requested primary transports"); - return; - } - - - // This enables custom behavior based on protocol version specifics - if (protocolVersion.isNewerThan(new Version("5.1.0")) >= 0) { - - if (activeTransports.get(SessionType.RPC) == null) { //Might be a better way to handle this - - ArrayList<String> secondary = (ArrayList<String>) packet.getTag(ControlFrameTags.RPC.StartServiceACK.SECONDARY_TRANSPORTS); - ArrayList<Integer> audio = (ArrayList<Integer>) packet.getTag(ControlFrameTags.RPC.StartServiceACK.AUDIO_SERVICE_TRANSPORTS); - ArrayList<Integer> video = (ArrayList<Integer>) packet.getTag(ControlFrameTags.RPC.StartServiceACK.VIDEO_SERVICE_TRANSPORTS); - - activeTransports.put(SessionType.RPC, transportRecord); - activeTransports.put(SessionType.BULK_DATA, transportRecord); - activeTransports.put(SessionType.CONTROL, transportRecord); - - //Build out the supported secondary transports received from the - // RPC start service ACK. - supportedSecondaryTransports = new ArrayList<>(); - if (secondary == null) { - // If no secondary transports were attached we should assume - // the Video and Audio services can be used on primary - if (requiresHighBandwidth - && TransportType.BLUETOOTH.equals(transportRecord.getType())) { - //transport can't support high bandwidth - onTransportNotAccepted(transportRecord.getType() + " can't support high bandwidth requirement, and secondary transport not supported."); - return; - } - - if (video == null || video.contains(PRIMARY_TRANSPORT_ID)) { - activeTransports.put(SessionType.NAV, transportRecord); - } - if (audio == null || audio.contains(PRIMARY_TRANSPORT_ID)) { - activeTransports.put(SessionType.PCM, transportRecord); - } - }else{ - - if(DebugTool.isDebugEnabled()){ - printSecondaryTransportDetails(secondary,audio,video); - } - for (String s : secondary) { - switch (s) { - case TransportConstants.TCP_WIFI: - supportedSecondaryTransports.add(TransportType.TCP); - break; - case TransportConstants.AOA_USB: - supportedSecondaryTransports.add(TransportType.USB); - break; - case TransportConstants.SPP_BLUETOOTH: - supportedSecondaryTransports.add(TransportType.BLUETOOTH); - break; - } - } - } - - setTransportPriorityForService(SessionType.PCM, audio); - setTransportPriorityForService(SessionType.NAV, video); - - //Update the developer on the transport status - notifyDevTransportListener(); - - } else { - Log.w(TAG, "Received a start service ack for RPC service while already active on a different transport."); - return; - } - - if(protocolVersion.isNewerThan(new Version(5,2,0)) >= 0){ - String authToken = (String)packet.getTag(ControlFrameTags.RPC.StartServiceACK.AUTH_TOKEN); - if(authToken != null){ - iSdlProtocol.onAuthTokenReceived(authToken); - } - } - }else { - - //Version is either not included or lower than 5.1.0 - if (requiresHighBandwidth - && TransportType.BLUETOOTH.equals(transportRecord.getType())) { - //transport can't support high bandwidth - onTransportNotAccepted(transportRecord.getType() + " can't support high bandwidth requirement, and secondary transport not supported in this protocol version: " + version); - return; - } - - activeTransports.put(SessionType.RPC, transportRecord); - activeTransports.put(SessionType.BULK_DATA, transportRecord); - activeTransports.put(SessionType.CONTROL, transportRecord); - activeTransports.put(SessionType.NAV, transportRecord); - activeTransports.put(SessionType.PCM, transportRecord); - - //Inform the developer of the initial transport connection - notifyDevTransportListener(); - } - - - }else if(serviceType.equals(SessionType.NAV)){ - if(iSdlProtocol != null) { - ImageResolution acceptedResolution = new ImageResolution(); - VideoStreamingFormat acceptedFormat = new VideoStreamingFormat(); - acceptedResolution.setResolutionHeight((Integer) packet.getTag(ControlFrameTags.Video.StartServiceACK.HEIGHT)); - acceptedResolution.setResolutionWidth((Integer) packet.getTag(ControlFrameTags.Video.StartServiceACK.WIDTH)); - acceptedFormat.setCodec(VideoStreamingCodec.valueForString((String) packet.getTag(ControlFrameTags.Video.StartServiceACK.VIDEO_CODEC))); - acceptedFormat.setProtocol(VideoStreamingProtocol.valueForString((String) packet.getTag(ControlFrameTags.Video.StartServiceACK.VIDEO_PROTOCOL))); - VideoStreamingParameters agreedVideoParams = iSdlProtocol.getDesiredVideoParams(); - agreedVideoParams.setResolution(acceptedResolution); - agreedVideoParams.setFormat(acceptedFormat); - iSdlProtocol.setAcceptedVideoParams(agreedVideoParams); - } - } - } else { - TransportRecord transportRecord = packet.getTransportRecord(); - if(transportRecord == null || (requiresHighBandwidth - && TransportType.BLUETOOTH.equals(transportRecord.getType()))){ - //transport can't support high bandwidth - onTransportNotAccepted((transportRecord != null ? transportRecord.getType().toString() : "Transport") + "can't support high bandwidth requirement, and secondary transport not supported in this protocol version"); - return; - } - //If version < 5 and transport is acceptable we need to just add these - activeTransports.put(SessionType.RPC, transportRecord); - activeTransports.put(SessionType.BULK_DATA, transportRecord); - activeTransports.put(SessionType.CONTROL, transportRecord); - activeTransports.put(SessionType.NAV, transportRecord); - activeTransports.put(SessionType.PCM, transportRecord); - - if (protocolVersion.getMajor() > 1){ - if (packet.payload!= null && packet.dataSize == 4){ //hashid will be 4 bytes in length - hashID = BitConverter.intFromByteArray(packet.payload, 0); - } - } - } - - iSdlProtocol.onProtocolSessionStarted(serviceType, (byte) packet.getSessionId(), (byte)protocolVersion.getMajor(), "", hashID, packet.isEncrypted()); - } - - protected void handleProtocolSessionNAKed(SdlPacket packet, SessionType serviceType) { - List<String> rejectedParams = null; - if(packet.version >= 5){ - if(DebugTool.isDebugEnabled()) { - //Currently this is only during a debugging session. Might pass back in the future - String rejectedTag = null; - if (serviceType.equals(SessionType.RPC)) { - rejectedTag = ControlFrameTags.RPC.StartServiceNAK.REJECTED_PARAMS; - } else if (serviceType.equals(SessionType.PCM)) { - rejectedTag = ControlFrameTags.Audio.StartServiceNAK.REJECTED_PARAMS; - } else if (serviceType.equals(SessionType.NAV)) { - rejectedTag = ControlFrameTags.Video.StartServiceNAK.REJECTED_PARAMS; - } - - rejectedParams = (List<String>) packet.getTag(rejectedTag); - if(rejectedParams != null && rejectedParams.size() > 0){ - StringBuilder builder = new StringBuilder(); - builder.append("Rejected params for service type "); - builder.append(serviceType.getName()); - builder.append(" :"); - for(String rejectedParam : rejectedParams){ - builder.append(rejectedParam); - builder.append(" "); - } - DebugTool.logWarning(builder.toString()); - } - - } - } - if (serviceType.eq(SessionType.NAV) || serviceType.eq(SessionType.PCM)) { - iSdlProtocol.onProtocolSessionNACKed(serviceType, (byte)packet.sessionId, (byte)protocolVersion.getMajor(), "", rejectedParams); - - } else { - handleProtocolError("Got StartSessionNACK for protocol sessionID = " + packet.getSessionId(), null); - } - } - - // This method handles protocol errors. A callback is sent to the protocol - // listener. - protected void handleProtocolError(String string, Exception ex) { - iSdlProtocol.onProtocolError(string, ex); - } - - protected void handleProtocolHeartbeat(SessionType sessionType, byte sessionID) { - sendHeartBeatACK(sessionType,sessionID); - } - - protected void handleServiceDataACK(SdlPacket packet, SessionType sessionType) { - - if (packet.getPayload() != null && packet.getDataSize() == 4){ //service data ack will be 4 bytes in length - int serviceDataAckSize = BitConverter.intFromByteArray(packet.getPayload(), 0); - iSdlProtocol.onProtocolServiceDataACK(sessionType, serviceDataAckSize, (byte)packet.getSessionId ()); - - } - } - - /* -------------------------------------------------------------------------------------------- - ----------------------------------- TRANSPORT_TYPE LISTENER --------------------------------- - -------------------------------------------------------------------------------------------*/ - - @SuppressWarnings("FieldCanBeLocal") - private final TransportManager.TransportEventListener transportEventListener = new TransportManager.TransportEventListener() { - private boolean requestedSession = false; - - @Override - public void onPacketReceived(SdlPacket packet) { - handlePacketReceived(packet); - } - - @Override - public void onTransportConnected(List<TransportRecord> connectedTransports) { - Log.d(TAG, "onTransportConnected"); - //In the future we should move this logic into the Protocol Layer - TransportRecord transportRecord = getTransportForSession(SessionType.RPC); - if(transportRecord == null && !requestedSession){ //There is currently no transport registered - requestedSession = true; - transportManager.requestNewSession(getPreferredTransport(requestedPrimaryTransports,connectedTransports)); - } - onTransportsConnectedUpdate(connectedTransports); - if(DebugTool.isDebugEnabled()){ - printActiveTransports(); - } - } - - @Override - public void onTransportDisconnected(String info, TransportRecord disconnectedTransport, List<TransportRecord> connectedTransports) { - if (disconnectedTransport == null) { - Log.d(TAG, "onTransportDisconnected"); - transportManager.close(iSdlProtocol.getSessionId()); - iSdlProtocol.shutdown("No transports left connected"); - return; - } else { - Log.d(TAG, "onTransportDisconnected - " + disconnectedTransport.getType().name()); - } - - //In the future we will actually compare the record but at this point we can assume only - //a single transport record per transport. - //TransportType type = disconnectedTransport.getType(); - if(disconnectedTransport.equals(getTransportForSession(SessionType.NAV))){ - //stopVideoStream(); - iSdlProtocol.stopStream(SessionType.NAV); - activeTransports.remove(SessionType.NAV); - } - if(disconnectedTransport.equals(getTransportForSession(SessionType.PCM))){ - //stopAudioStream(); - iSdlProtocol.stopStream(SessionType.PCM); - activeTransports.remove(SessionType.PCM); - } - - if(disconnectedTransport.equals(getTransportForSession(SessionType.RPC)) || disconnectedTransport.equals(connectedPrimaryTransport)){ - //transportTypes.remove(type); - boolean primaryTransportAvailable = false; - if(requestedPrimaryTransports != null && requestedPrimaryTransports.size() > 1){ - for (TransportType transportType: requestedPrimaryTransports){ Log.d(TAG, "Checking " + transportType.name()); - if(!disconnectedTransport.getType().equals(transportType) - && transportManager != null - && transportManager.isConnected(transportType,null)){ - primaryTransportAvailable = true; - ( transportConfig).setService(transportManager.getRouterService()); - break; - } - } - } - connectedPrimaryTransport = null; - transportManager.close(iSdlProtocol.getSessionId()); - transportManager = null; - requestedSession = false; - - activeTransports.clear(); - - iSdlProtocol.onTransportDisconnected(info, primaryTransportAvailable, transportConfig); - - } //else Transport was not primary, continuing to stay connected - - //Update the developer since a transport just disconnected - notifyDevTransportListener(); - - } - - @Override - public void onError(String info) { - iSdlProtocol.shutdown(info); - - } - - @Override - public boolean onLegacyModeEnabled(String info) { - //Await a connection from the legacy transport - if(requestedPrimaryTransports!= null && requestedPrimaryTransports.contains(TransportType.BLUETOOTH) - && !transportConfig.requiresHighBandwidth()){ - Log.d(TAG, "Entering legacy mode; creating new protocol instance"); - reset(); - return true; - }else{ - Log.d(TAG, "Bluetooth is not an acceptable transport; not moving to legacy mode"); - return false; - } - } - }; - -/* ------------------------------------------------------------------------------------------------- ------------------------------------ Internal Classes ------------------------------------------ ---------------------------------------------------------------------------------------------------*/ - - - protected class MessageFrameAssembler { - protected ByteArrayOutputStream accumulator = null; - protected int totalSize = 0; - - protected void handleFirstDataFrame(SdlPacket packet) { - //The message is new, so let's figure out how big it is. - totalSize = BitConverter.intFromByteArray(packet.payload, 0) - headerSize; - try { - accumulator = new ByteArrayOutputStream(totalSize); - }catch(OutOfMemoryError e){ - DebugTool.logError("OutOfMemory error", e); //Garbled bits were received - accumulator = null; - } - } - - protected void handleRemainingFrame(SdlPacket packet) { - accumulator.write(packet.payload, 0, (int)packet.getDataSize()); - notifyIfFinished(packet); - } - - protected void notifyIfFinished(SdlPacket packet) { - if (packet.getFrameType() == FrameType.Consecutive && packet.getFrameInfo() == 0x0) { - ProtocolMessage message = new ProtocolMessage(); - message.setPayloadProtected(packet.isEncrypted()); - message.setSessionType(SessionType.valueOf((byte)packet.getServiceType())); - message.setSessionID((byte)packet.getSessionId()); - //If it is WiPro 2.0 it must have binary header - if (protocolVersion.getMajor() > 1) { - BinaryFrameHeader binFrameHeader = BinaryFrameHeader. - parseBinaryHeader(accumulator.toByteArray()); - if(binFrameHeader == null) { - return; - } - message.setVersion((byte)protocolVersion.getMajor()); - message.setRPCType(binFrameHeader.getRPCType()); - message.setFunctionID(binFrameHeader.getFunctionID()); - message.setCorrID(binFrameHeader.getCorrID()); - if (binFrameHeader.getJsonSize() > 0) message.setData(binFrameHeader.getJsonData()); - if (binFrameHeader.getBulkData() != null) message.setBulkData(binFrameHeader.getBulkData()); - } else{ - message.setData(accumulator.toByteArray()); - } - - _assemblerForMessageID.remove(packet.getMessageId()); - - try { - iSdlProtocol.onProtocolMessageReceived(message); - } catch (Exception excp) { - DebugTool.logError(FailurePropagating_Msg + "onProtocolMessageReceived: " + excp.toString(), excp); - } // end-catch - - accumulator = null; - } // end-if - } // end-method - - protected void handleMultiFrameMessageFrame(SdlPacket packet) { - if (packet.getFrameType() == FrameType.First) { - handleFirstDataFrame(packet); - } - else{ - if(accumulator != null){ - handleRemainingFrame(packet); - } - } - - } // end-method - - protected void handleFrame(SdlPacket packet) { - - if (packet.getPayload() != null && packet.getDataSize() > 0 && packet.isEncrypted() ) { - - SdlSecurityBase sdlSec = iSdlProtocol.getSdlSecurity(); - byte[] dataToRead = new byte[4096]; - - Integer iNumBytes = sdlSec.decryptData(packet.getPayload(), dataToRead); - if ((iNumBytes == null) || (iNumBytes <= 0)){ - return; - } - - byte[] decryptedData = new byte[iNumBytes]; - System.arraycopy(dataToRead, 0, decryptedData, 0, iNumBytes); - packet.payload = decryptedData; - } - - if (packet.getFrameType().equals(FrameType.Control)) { - handleControlFrame(packet); - } else { - // Must be a form of data frame (single, first, consecutive, etc.) - if ( packet.getFrameType() == FrameType.First - || packet.getFrameType() == FrameType.Consecutive - ) { - handleMultiFrameMessageFrame(packet); - } else { - handleSingleFrameMessageFrame(packet); - } - } - } - - private void handleProtocolHeartbeatACK(SdlPacket packet) { - //Heartbeat is not supported in the SdlProtocol class beyond responding with ACKs to - //heartbeat messages. Receiving this ACK is suspicious and should be logged - DebugTool.logInfo("Received HeartbeatACK - " + packet.toString()); - } - - private void handleProtocolHeartbeat(SdlPacket packet) { - SdlProtocol.this.handleProtocolHeartbeat(SessionType.valueOf((byte)packet.getServiceType()),(byte)packet.getSessionId()); - } - - /** - * Directing method that will push the packet to the method that can handle it best - * @param packet a control frame packet - */ - private void handleControlFrame(SdlPacket packet) { - Integer frameTemp = packet.getFrameInfo(); - Byte frameInfo = frameTemp.byteValue(); - - SessionType serviceType = SessionType.valueOf((byte)packet.getServiceType()); - - if (frameInfo == FrameDataControlFrameType.Heartbeat.getValue()) { - - handleProtocolHeartbeat(packet); - - }else if (frameInfo == FrameDataControlFrameType.HeartbeatACK.getValue()) { - - handleProtocolHeartbeatACK(packet); - - }else if (frameInfo == FrameDataControlFrameType.StartSessionACK.getValue()) { - - handleProtocolSessionStarted(packet, serviceType); - - } else if (frameInfo == FrameDataControlFrameType.StartSessionNACK.getValue()) { - - handleProtocolSessionNAKed(packet, serviceType); - - } else if (frameInfo == FrameDataControlFrameType.EndSession.getValue() - || frameInfo == FrameDataControlFrameType.EndSessionACK.getValue()) { - - handleServiceEnded(packet,serviceType); - - } else if (frameInfo == FrameDataControlFrameType.EndSessionNACK.getValue()) { - - handleServiceEndedNAK(packet, serviceType); - - } else if (frameInfo == FrameDataControlFrameType.ServiceDataACK.getValue()) { - - handleServiceDataACK(packet, serviceType); - - } else if (frameInfo == FrameDataControlFrameType.RegisterSecondaryTransportACK.getValue()) { - - handleSecondaryTransportRegistration(packet.getTransportRecord(),true); - - } else if (frameInfo == FrameDataControlFrameType.RegisterSecondaryTransportNACK.getValue()) { - - String reason = (String) packet.getTag(ControlFrameTags.RPC.RegisterSecondaryTransportNAK.REASON); - DebugTool.logWarning(reason); - handleSecondaryTransportRegistration(packet.getTransportRecord(),false); - - } else if (frameInfo == FrameDataControlFrameType.TransportEventUpdate.getValue()) { - - // Get TCP params - String ipAddr = (String) packet.getTag(ControlFrameTags.RPC.TransportEventUpdate.TCP_IP_ADDRESS); - Integer port = (Integer) packet.getTag(ControlFrameTags.RPC.TransportEventUpdate.TCP_PORT); - - if(secondaryTransportParams == null){ - secondaryTransportParams = new HashMap<>(); - } - - if(ipAddr != null && port != null) { - Bundle bundle = new Bundle(); - bundle.putString(ControlFrameTags.RPC.TransportEventUpdate.TCP_IP_ADDRESS, ipAddr); - bundle.putInt(ControlFrameTags.RPC.TransportEventUpdate.TCP_PORT, port); - bundle.putString(TransportConstants.TRANSPORT_TYPE, TransportType.TCP.name()); - secondaryTransportParams.put(TransportType.TCP, bundle); - - //A new secondary transport just became available. Notify the developer. - notifyDevTransportListener(); - } - - } - - _assemblerForMessageID.remove(packet.getMessageId()); - - } // end-method - - private void handleSingleFrameMessageFrame(SdlPacket packet) { - ProtocolMessage message = new ProtocolMessage(); - message.setPayloadProtected(packet.isEncrypted()); - SessionType serviceType = SessionType.valueOf((byte)packet.getServiceType()); - if (serviceType == SessionType.RPC) { - message.setMessageType(MessageType.RPC); - } else if (serviceType == SessionType.BULK_DATA) { - message.setMessageType(MessageType.BULK); - } // end-if - message.setSessionType(serviceType); - message.setSessionID((byte)packet.getSessionId()); - //If it is WiPro 2.0 it must have binary header - boolean isControlService = message.getSessionType().equals(SessionType.CONTROL); - if (protocolVersion.getMajor() > 1 && !isControlService) { - BinaryFrameHeader binFrameHeader = BinaryFrameHeader. - parseBinaryHeader(packet.payload); - if(binFrameHeader == null) { - return; - } - message.setVersion((byte)protocolVersion.getMajor()); - message.setRPCType(binFrameHeader.getRPCType()); - message.setFunctionID(binFrameHeader.getFunctionID()); - message.setCorrID(binFrameHeader.getCorrID()); - if (binFrameHeader.getJsonSize() > 0){ - message.setData(binFrameHeader.getJsonData()); - } - if (binFrameHeader.getBulkData() != null){ - message.setBulkData(binFrameHeader.getBulkData()); - } - } else { - message.setData(packet.payload); - } - - _assemblerForMessageID.remove(packet.getMessageId()); - - try { - iSdlProtocol.onProtocolMessageReceived(message); - } catch (Exception ex) { - DebugTool.logError(FailurePropagating_Msg + "onProtocolMessageReceived: " + ex.toString(), ex); - handleProtocolError(FailurePropagating_Msg + "onProtocolMessageReceived: ", ex); - } // end-catch - } // end-method - } // end-class - } diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/IProxyListener.java b/android/sdl_android/src/main/java/com/smartdevicelink/proxy/IProxyListener.java deleted file mode 100644 index 2ef06c3b9..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/IProxyListener.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.smartdevicelink.proxy;
-
-import com.smartdevicelink.proxy.interfaces.IProxyListenerBase;
-import com.smartdevicelink.proxy.rpc.OnAppInterfaceUnregistered;
-import com.smartdevicelink.proxy.rpc.RegisterAppInterfaceResponse;
-import com.smartdevicelink.proxy.rpc.UnregisterAppInterfaceResponse;
-
-public interface IProxyListener extends IProxyListenerBase{
- // Adds Legacy Life-cycle Management call-backs to the IProxyListenerAbstract interface
-
- public void onProxyOpened();
-
- public void onRegisterAppInterfaceResponse(RegisterAppInterfaceResponse response);
-
- public void onOnAppInterfaceUnregistered(OnAppInterfaceUnregistered notification);
-
- public void onUnregisterAppInterfaceResponse(UnregisterAppInterfaceResponse response);
-
-}
diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/RPCMessage.java b/android/sdl_android/src/main/java/com/smartdevicelink/proxy/RPCMessage.java deleted file mode 100644 index ad7b8c68e..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/RPCMessage.java +++ /dev/null @@ -1,129 +0,0 @@ -package com.smartdevicelink.proxy;
-
-import java.util.Hashtable;
-
-public class RPCMessage extends RPCStruct {
- public static final String KEY_REQUEST = "request";
- public static final String KEY_RESPONSE = "response";
- public static final String KEY_NOTIFICATION = "notification";
- public static final String KEY_FUNCTION_NAME = "name";
- public static final String KEY_PARAMETERS = "parameters";
- public static final String KEY_CORRELATION_ID = "correlationID";
-
- public RPCMessage(String functionName) {
- this(functionName, "request");
- }
-
- protected RPCMessage(RPCMessage rpcm) {
- this(cloneStore(rpcm));
- }
-
- protected RPCMessage(RPCStruct rpcs) {
- this("", "");
- this.parameters = cloneStore(rpcs);
- }
-
- public RPCMessage(String functionName, String messageType) {
- function = new Hashtable<String, Object>();
- parameters = new Hashtable<String, Object>();
-
- this.messageType = messageType;
- function.put(KEY_PARAMETERS, parameters);
-
- if (messageType != null)
- store.put(messageType, function);
- if (functionName != null)
- function.put(KEY_FUNCTION_NAME, functionName);
- }
-
- @SuppressWarnings("unchecked")
- public RPCMessage(Hashtable<String, Object> hash) {
- store = hash;
- messageType = getMessageTypeName(hash.keySet());
- function = (Hashtable<String, Object>) hash.get(messageType);
- parameters = (Hashtable<String, Object>) function.get(KEY_PARAMETERS);
- if (hasKey(hash.keySet(), RPCStruct.KEY_BULK_DATA)) {
- setBulkData((byte[]) hash.get(RPCStruct.KEY_BULK_DATA));
- }
- if (hasKey(hash.keySet(), RPCStruct.KEY_PROTECTED)) {
- setPayloadProtected((Boolean) hash.get(RPCStruct.KEY_PROTECTED));
- }
- }
-
- protected String messageType;
- protected Hashtable<String, Object> parameters;
- protected Hashtable<String, Object> function;
-
- public String getFunctionName() {
- return (String)function.get(KEY_FUNCTION_NAME);
- }
-
- protected void setFunctionName(String functionName) {
- function.put(KEY_FUNCTION_NAME, functionName);
- }
-
- public String getMessageType() {
- if (messageType.equals(KEY_REQUEST) ||
- messageType.equals(KEY_RESPONSE) ||
- messageType.equals(KEY_NOTIFICATION)) {
- return messageType;
- }
- return null;
- }
-
- // Generalized Getters and Setters
-
- public void setParameters(String key, Object value) {
- if (value != null) {
- parameters.put(key, value);
- } else {
- parameters.remove(key);
- }
- }
-
- public Object getParameters(String key) {
- return parameters.get(key);
- }
-
- @Override
- public Object getObject(Class tClass, String key) {
- Object obj = parameters.get(key);
- return formatObject(tClass, obj);
- }
-
- // Common Object Getters
-
- @Override
- public String getString(String key) {
- return (String) parameters.get(key);
- }
-
- @Override
- public Integer getInteger(String key) {
- return (Integer) parameters.get(key);
- }
-
- @Override
- public Float getFloat(String key) {
- return (Float) parameters.get(key);
- }
-
- @Override
- public Double getDouble(String key) {
- return (Double) parameters.get(key);
- }
-
- @Override
- public Boolean getBoolean(String key) { return (Boolean) parameters.get(key); }
-
- @Override
- public Long getLong(String key){
- Object result = parameters.get(key);
- if (result instanceof Integer) {
- return ((Integer) result).longValue();
- }else if(result instanceof Long){
- return (Long) result;
- }
- return null;
- }
-}
diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/RPCNotification.java b/android/sdl_android/src/main/java/com/smartdevicelink/proxy/RPCNotification.java deleted file mode 100644 index b9992e78b..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/RPCNotification.java +++ /dev/null @@ -1,29 +0,0 @@ -/**
- *
- */
-package com.smartdevicelink.proxy;
-
-import java.util.Hashtable;
-
-public class RPCNotification extends RPCMessage {
-
- public RPCNotification(String functionName) {
- super(functionName, RPCMessage.KEY_NOTIFICATION);
- }
-
- public RPCNotification(Hashtable<String, Object> hash) {
- super(hash);
- }
-
- public RPCNotification(RPCMessage rpcMsg) {
- super(preprocessMsg(rpcMsg));
- }
-
- static RPCMessage preprocessMsg (RPCMessage rpcMsg) {
- if (rpcMsg.getMessageType() != RPCMessage.KEY_NOTIFICATION) {
- rpcMsg.messageType = RPCMessage.KEY_NOTIFICATION;
- }
-
- return rpcMsg;
- }
-}
\ No newline at end of file diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/RPCRequest.java b/android/sdl_android/src/main/java/com/smartdevicelink/proxy/RPCRequest.java deleted file mode 100644 index d5117318d..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/RPCRequest.java +++ /dev/null @@ -1,53 +0,0 @@ -/**
- *
- */
-package com.smartdevicelink.proxy;
-
-import java.util.Hashtable;
-
-import com.smartdevicelink.proxy.rpc.listeners.OnRPCResponseListener;
-import com.smartdevicelink.util.CorrelationIdGenerator;
-
-public class RPCRequest extends RPCMessage {
-
- protected OnRPCResponseListener onResponseListener;
-
- public RPCRequest(String functionName) {
- super(functionName, RPCMessage.KEY_REQUEST);
- messageType = RPCMessage.KEY_REQUEST;
- }
-
- public RPCRequest(Hashtable<String, Object> hash) {
- super(hash);
- }
-
- public RPCRequest(RPCRequest request){
- super(request);
- if (request == null || request.getCorrelationID() == null) {
- setCorrelationID(CorrelationIdGenerator.generateId());
- }
- }
-
- public Integer getCorrelationID() {
- //First we check to see if a correlation ID is set. If not, create one.
- if(!function.containsKey(RPCMessage.KEY_CORRELATION_ID)){
- setCorrelationID(CorrelationIdGenerator.generateId());
- }
- return (Integer)function.get(RPCMessage.KEY_CORRELATION_ID);
- }
-
- public void setCorrelationID(Integer correlationID) {
- if (correlationID != null) {
- function.put(RPCMessage.KEY_CORRELATION_ID, correlationID );
- } else {
- function.remove(RPCMessage.KEY_CORRELATION_ID);
- }
- }
- public void setOnRPCResponseListener(OnRPCResponseListener listener){
- onResponseListener = listener;
- }
-
- public OnRPCResponseListener getOnRPCResponseListener(){
- return this.onResponseListener;
- }
-}
diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/RPCResponse.java b/android/sdl_android/src/main/java/com/smartdevicelink/proxy/RPCResponse.java deleted file mode 100644 index a7c0ed188..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/RPCResponse.java +++ /dev/null @@ -1,183 +0,0 @@ -/**
- *
- */
-package com.smartdevicelink.proxy;
-
-import android.support.annotation.NonNull;
-
-import java.util.Hashtable;
-
-import com.smartdevicelink.proxy.rpc.enums.Result;
-
-/**
- * Result sent by SDL after an RPC is processed, consists of four parts:
- * <ul>
- * <li>
- * CorrelationID:
- * <ul>
- * An integer value correlating the response to the corresponding request.
- * </ul>
- * </li> <li>Success:
- * <ul>
- * A Boolean indicating whether the original request was successfully processed.
- * </ul>
- * </li> <li>ResultCode:
- * <ul>
- *
- * <p>The result code provides additional information about a response returning a
- * failed outcome.</p>
- *
- *
- * <p>Any response can have at least one, or possibly more, of the following result
- * code values: SUCCESS, INVALID_DATA, OUT_OF_MEMORY, TOO_MANY_PENDING_REQUESTS,
- * APPLICATION_NOT_REGISTERED, GENERIC_ERROR,REJECTED.</p>
- *
- *
- * <p>Any additional result codes for a given operation can be found in related
- * RPCs</p>
- *
- * </ul>
- * </li> <li>Info:
- * <ul>
- * A string of text representing additional information returned from SDL. This
- * could be useful in debugging.
- * </ul>
- * </li>
- * </ul>
- */
-public class RPCResponse extends RPCMessage {
- public static final String KEY_SUCCESS = "success";
- public static final String KEY_INFO = "info";
- public static final String KEY_RESULT_CODE = "resultCode";
- /**
- *<p>Constructs a newly allocated RPCResponse object using function name</p>
- *@param functionName a string that indicates the function's name
- */
- public RPCResponse(String functionName) {
- super(functionName, RPCMessage.KEY_RESPONSE);
- }
- /**
- *<p>Constructs a newly allocated RPCResponse object indicated by the Hashtable parameter</p>
- *@param hash The Hashtable to use
- */
- public RPCResponse(Hashtable<String, Object> hash) {
- super(hash);
- }
- /**
- *<p>Constructs a newly allocated RPCResponse object using a RPCMessage object</p>
- *@param rpcMsg The {@linkplain RPCMessage} to use
- */
- public RPCResponse(RPCMessage rpcMsg) {
- super(preprocessMsg(rpcMsg));
- }
-
- static RPCMessage preprocessMsg (RPCMessage rpcMsg) {
- if (rpcMsg.getMessageType() != RPCMessage.KEY_RESPONSE) {
- rpcMsg.messageType = RPCMessage.KEY_RESPONSE;
- }
-
- return rpcMsg;
- }
-
- /**
- * <p>
- * Returns correlationID the ID of the request
- * </p>
- *
- * @return int the ID of the request
- */
- public Integer getCorrelationID() {
- return (Integer)function.get(RPCMessage.KEY_CORRELATION_ID);
- }
-
- /**
- * <p>
- * Set the correlationID
- * </p>
- *
- * @param correlationID
- * the ID of the response
- */
- public void setCorrelationID(Integer correlationID) {
- if (correlationID != null) {
- function.put(RPCMessage.KEY_CORRELATION_ID, correlationID );
- } else {
- function.remove(RPCMessage.KEY_CORRELATION_ID);
- }
- }
- /**
- * <p>
- * Returns Success whether the request is successfully processed
- * </p>
- *
- * @return Boolean the status of whether the request is successfully done
- */
- public Boolean getSuccess() {
- return (Boolean) parameters.get( RPCResponse.KEY_SUCCESS );
- }
- /**
- * <p>
- * Set the Success status
- * </p>
- *
- * @param success
- * whether the request is successfully processed
- */
- public void setSuccess( @NonNull Boolean success ) {
- if (success != null) {
- parameters.put(RPCResponse.KEY_SUCCESS, success );
- }
- }
- /**
- * <p>
- * Returns ResultCode additional information about a response returning a failed outcome
- * </p>
- *
- * @return {@linkplain Result} the status of whether the request is successfully done
- */
- public Result getResultCode() {
- Object obj = parameters.get(RPCResponse.KEY_RESULT_CODE);
- if (obj instanceof Result) {
- return (Result) obj;
- } else if (obj instanceof String) {
- return Result.valueForString((String) obj);
- }
- return null;
- }
- /**
- * <p>
- * Set the additional information about a response returning a failed outcome
- * </p>
- *
- * @param resultCode
- * whether the request is successfully processed
- */
- public void setResultCode( @NonNull Result resultCode ) {
- if (resultCode != null) {
- parameters.put(RPCResponse.KEY_RESULT_CODE, resultCode );
- }
- }
- /**
- * <p>
- * Returns a string of text representing additional information returned from SDL
- * </p>
- *
- * @return String A string of text representing additional information returned from SDL
- */
- public String getInfo() {
- return (String) parameters.get( RPCResponse.KEY_INFO );
- }
- /**
- * <p>
- * Set a string of text representing additional information returned from SDL
- * </p>
- *
- * @param info
- * a string of text representing additional information returned from SDL
- */
- public void setInfo( String info ) {
- if (info != null) {
- parameters.put(RPCResponse.KEY_INFO, info );
- }
- }
-}
diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/RPCStruct.java b/android/sdl_android/src/main/java/com/smartdevicelink/proxy/RPCStruct.java deleted file mode 100644 index dd96cdc9b..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/RPCStruct.java +++ /dev/null @@ -1,327 +0,0 @@ -package com.smartdevicelink.proxy;
-
-import com.smartdevicelink.marshal.JsonRPCMarshaller;
-import com.smartdevicelink.util.Version;
-
-import org.json.JSONException;
-import org.json.JSONObject;
-
-import java.lang.reflect.Constructor;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.util.ArrayList;
-import java.util.Hashtable;
-import java.util.List;
-import java.util.Set;
-
-public class RPCStruct {
- public static final String KEY_BULK_DATA = "bulkData";
- public static final String KEY_PROTECTED = "protected";
-
- private byte[] _bulkData = null;
- private Boolean protectedPayload = false;
-
- private boolean formatRequested = false;
- private Version rpcSpecVersion = null;
-
-
- protected Hashtable<String, Object> store = null;
-
- public boolean getStoreValue(String key) { // for unit testing
- return store.contains(key);
- }
-
- public Hashtable<String,Object> getStore () { // for unit testing
- return store;
- }
-
- public RPCStruct() {
- store = new Hashtable<String, Object>();
- }
-
- protected RPCStruct(RPCStruct rpcs) {
- this.store = cloneStore(rpcs);
- }
-
- public RPCStruct(Hashtable<String, Object> hashtable) {
- store = hashtable;
- //store = (Hashtable<String, Object>) ObjectCopier.copy(hashtable);
- }
-
- static Hashtable<String, Object> cloneStore(RPCStruct rpcStruct){
- if(rpcStruct!= null && rpcStruct.store !=null){
- return (Hashtable)rpcStruct.store.clone();
- }
- return null;
- }
-
- public void deserializeJSON(JSONObject jsonObject) throws JSONException {
- store = JsonRPCMarshaller.deserializeJSONObject(jsonObject);
-
- }
-
- // deserializeJSONObject method moved to JsonRPCMarshaller for consistency
- // Keep reference here for backwards compatibility
- @Deprecated
- public static Hashtable<String, Object> deserializeJSONObject(JSONObject jsonObject)
- throws JSONException {
- return JsonRPCMarshaller.deserializeJSONObject(jsonObject);
- }
-
- public JSONObject serializeJSON() throws JSONException {
- return JsonRPCMarshaller.serializeHashtable(store);
- }
-
- @SuppressWarnings("unchecked")
- public JSONObject serializeJSON(byte protocolVersion) throws JSONException {
- if (protocolVersion > 1) {
- String messageType = getMessageTypeName(store.keySet());
- Hashtable<String, Object> function = (Hashtable<String, Object>) store.get(messageType);
- Hashtable<String, Object> parameters = (Hashtable<String, Object>) function.get(RPCMessage.KEY_PARAMETERS);
- return JsonRPCMarshaller.serializeHashtable(parameters);
- } else return JsonRPCMarshaller.serializeHashtable(store);
- }
-
- /**
- * This method should clean the the RPC to make sure it is compliant with the spec.
- * <br><br><b> NOTE:</b> Super needs to be called at the END of the method
- *
- * @param rpcVersion the rpc spec version that has been negotiated. If value is null the
- * the max value of RPC spec version this library supports should be used.
- * @param formatParams if true, the format method will be called on subsequent params
- */
- public void format(Version rpcVersion, boolean formatParams){
- formatRequested = true;
- rpcSpecVersion = rpcVersion;
- //Should override this method when breaking changes are made to the RPC spec
- if(formatParams && store != null){
- Hashtable<String, Object> parameters;
-
- if(this instanceof RPCMessage) {
- //If this is a message (request, response, notification) the parameters have to be
- //retrieved from the store object.
- String messageType = getMessageTypeName(store.keySet());
- Hashtable<String, Object> function = (Hashtable<String, Object>) store.get(messageType);
- parameters = (Hashtable<String, Object>) function.get(RPCMessage.KEY_PARAMETERS);
- } else {
- //If this is just an RPC struct the store itself should be used
- parameters = store;
- }
-
- if (parameters != null) {
- for(Object value:parameters.values()){
- internalFormat(rpcVersion, value);
- }
- }
- }
- }
-
- /**
- * Cycles through parameters in this RPC to ensure they all get formated
- * @param rpcVersion version of the rpc spec that should be used to format this rpc
- * @param value the object to investigate if it needs to be formated
- */
- private void internalFormat(Version rpcVersion, Object value) {
- if(value instanceof RPCStruct) {
- ((RPCStruct)value).format(rpcVersion,true);
- } else if(value instanceof List<?>) {
- List<?> list = (List<?>)value;
- if(list != null && list.size() > 0) {
- for(Object listItem: list){
- internalFormat(rpcVersion, listItem);
- }
- }
- }
- }
-
-
- public byte[] getBulkData() {
- return this._bulkData;
- }
-
- public void setBulkData(byte[] bulkData) {
- if (bulkData != null) {
- this._bulkData = new byte[bulkData.length];
- System.arraycopy(bulkData, 0, _bulkData, 0, bulkData.length);
- }
- else{
- this._bulkData = null;
- }
- }
-
- public void setPayloadProtected(Boolean bVal) {
- protectedPayload = bVal;
- }
-
- public Boolean isPayloadProtected() {
- return protectedPayload;
- }
-
- protected String getMessageTypeName(Set<String> keys) {
- for (String key : keys) {
- if (key == null) {
- continue;
- }
- if (key.equals(RPCMessage.KEY_REQUEST) || key.equals(RPCMessage.KEY_RESPONSE) ||
- key.equals(RPCMessage.KEY_NOTIFICATION)) {
- return key;
- }
- }
- return null;
- }
-
- protected boolean hasKey(Set<String> keys, String keyName) {
- for (String key : keys) {
- if (key == null) {
- continue;
- }
- if (key.equals(keyName)) {
- return true;
- }
- }
- return false;
- }
-
- // Generalized Getters and Setters
-
- public void setValue(String key, Object value){
- if (value != null) {
- store.put(key, value);
- } else {
- store.remove(key);
- }
- }
-
- public Object getValue(String key) {
- return store.get(key);
- }
-
- public Object getObject(Class tClass, String key) {
- Object obj = store.get(key);
- return formatObject(tClass, obj);
- }
-
- // Helper methods
-
- /**
- * @param tClass a Class to cast Objects to
- * @param obj Object returned from a stored hashtable
- * @return A null object if obj is null or if none of the following is true:
- * a) obj is an instance of tClass
- * b) obj is an instance of String and it tClass has a valid `valueForString` method
- * c) obj is an instance of a Hashtable
- * d) obj is an instance of a List
- */
- protected Object formatObject(Class tClass, Object obj){
- if(obj == null){
- return null;
- } else if (tClass.isInstance(obj)) {
- return obj;
- } else if (obj instanceof String) {
- return getValueForString(tClass, (String) obj);
- } else if (obj instanceof Hashtable) {
- try {
- Constructor constructor = tClass.getConstructor(Hashtable.class);
- Object customObject = constructor.newInstance((Hashtable<String, Object>) obj);
- if(formatRequested && customObject instanceof RPCStruct){
- ((RPCStruct)customObject).format(rpcSpecVersion,true);
- }
-
- return customObject;
- } catch (Exception e) {
- e.printStackTrace();
- }
- } else if (obj instanceof List<?>) {
- List<?> list = (List<?>) obj;
- if (list != null && list.size() > 0) {
- Object item = list.get(0);
- if (tClass.isInstance(item)) {
- return list;
- } else if (item instanceof Hashtable) {
- List<Object> newList = new ArrayList<Object>();
- Object customObject;
- for (Object hashObj : list) {
- try {
- Constructor constructor = tClass.getConstructor(Hashtable.class);
- customObject = constructor.newInstance((Hashtable<String, Object>) hashObj);
- if(formatRequested
- && customObject != null
- && customObject instanceof RPCStruct){
- ((RPCStruct)customObject).format(rpcSpecVersion,true);
- }
- newList.add(customObject);
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- }
- }
- return newList;
- } else if (item instanceof String){
- List<Object> newList = new ArrayList<Object>();
- for (Object hashObj : list) {
- Object toAdd = getValueForString(tClass, (String) hashObj);
- if (toAdd != null) {
- newList.add(toAdd);
- }
- }
- return newList;
- }
- }
- }
- return null;
- }
-
- /**
- * @param tClass - a Class with a `valueForString(String s)` method that returns an Object for a given String
- * @param s - a String to be converted to an Object using a `valueForString(String s)` method
- * @return An Object converted using a `valueForString(String s)` method in the Class passed in, or a null object if such method does not exist
- */
- protected Object getValueForString(Class tClass, String s){
- Method valueForString = null;
- try {
- valueForString = tClass.getDeclaredMethod("valueForString", String.class);
- } catch (NoSuchMethodException e) {
- e.printStackTrace();
- }
- if(valueForString != null){
- try {
- Object value = valueForString.invoke(null, (String) s);
- return value;
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- } catch (InvocationTargetException e) {
- e.printStackTrace();
- }
- }
- return null;
- }
-
- // Common Object Getters
- public String getString(String key) {
- return (String) store.get(key);
- }
-
- public Integer getInteger(String key) {
- return (Integer) store.get(key);
- }
-
- public Double getDouble(String key) {
- return (Double) store.get(key);
- }
-
- public Float getFloat(String key) {
- return (Float) store.get(key);
- }
-
- public Boolean getBoolean(String key) { return (Boolean) store.get(key); }
-
- public Long getLong(String key){
- Object result = store.get(key);
- if (result instanceof Integer) {
- return ((Integer) result).longValue();
- }else if(result instanceof Long){
- return (Long) result;
- }
- return null;
- }
-}
diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/SdlProxyALM.java b/android/sdl_android/src/main/java/com/smartdevicelink/proxy/SdlProxyALM.java index d3690146c..d49a83e84 100644 --- a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/SdlProxyALM.java +++ b/android/sdl_android/src/main/java/com/smartdevicelink/proxy/SdlProxyALM.java @@ -6,6 +6,7 @@ import java.util.Vector; import android.app.Service;
import android.content.Context;
+import com.smartdevicelink.BuildConfig;
import com.smartdevicelink.proxy.rpc.TemplateColorScheme;
import com.smartdevicelink.exception.SdlException;
import com.smartdevicelink.exception.SdlExceptionCause;
@@ -1764,8 +1765,8 @@ public class SdlProxyALM extends SdlProxyBase<IProxyListenerALM> { throw new SdlException("This object has been disposed, it is no long capable of executing methods.", SdlExceptionCause.SDL_PROXY_DISPOSED);
}
- if (Version.VERSION != null)
- return Version.VERSION;
+ if (BuildConfig.VERSION_NAME != null)
+ return BuildConfig.VERSION_NAME;
return null;
}
diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/SdlProxyBase.java b/android/sdl_android/src/main/java/com/smartdevicelink/proxy/SdlProxyBase.java index 96e503ab6..bd11074f8 100644 --- a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/SdlProxyBase.java +++ b/android/sdl_android/src/main/java/com/smartdevicelink/proxy/SdlProxyBase.java @@ -335,9 +335,9 @@ public abstract class SdlProxyBase<proxyListenerType extends IProxyListenerBase> }
@Override
- public void sendRPC(RPCRequest message) {
+ public void sendRPC(RPCMessage message) {
try {
- SdlProxyBase.this.sendRPCRequest(message);
+ SdlProxyBase.this.sendRPC(message);
} catch (SdlException e) {
e.printStackTrace();
}
@@ -489,7 +489,7 @@ public abstract class SdlProxyBase<proxyListenerType extends IProxyListenerBase> }
@Override
- public void onTransportDisconnected(String info, boolean altTransportAvailable, MultiplexTransportConfig transportConfig) {
+ public void onTransportDisconnected(String info, boolean altTransportAvailable, BaseTransportConfig transportConfig) {
notifyPutFileStreamError(null, info);
if( altTransportAvailable){
@@ -784,7 +784,7 @@ public abstract class SdlProxyBase<proxyListenerType extends IProxyListenerBase> boolean callbackToUIThread, Boolean preRegister, String sHashID, Boolean bAppResumeEnab,
BaseTransportConfig transportConfig) throws SdlException
{
- Log.i(TAG, "SDL_LIB_VERSION: " + com.smartdevicelink.proxy.Version.VERSION);
+ Log.i(TAG, "SDL_LIB_VERSION: " + BuildConfig.VERSION_NAME);
setProtocolVersion(new Version(PROX_PROT_VER_ONE,0,0));
if (preRegister != null && preRegister)
diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/SystemCapabilityManager.java b/android/sdl_android/src/main/java/com/smartdevicelink/proxy/SystemCapabilityManager.java deleted file mode 100644 index 5020e4123..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/SystemCapabilityManager.java +++ /dev/null @@ -1,233 +0,0 @@ -package com.smartdevicelink.proxy; - -import com.smartdevicelink.proxy.interfaces.ISdl; -import com.smartdevicelink.proxy.interfaces.OnSystemCapabilityListener; -import com.smartdevicelink.proxy.rpc.GetSystemCapability; -import com.smartdevicelink.proxy.rpc.GetSystemCapabilityResponse; -import com.smartdevicelink.proxy.rpc.HMICapabilities; -import com.smartdevicelink.proxy.rpc.RegisterAppInterfaceResponse; -import com.smartdevicelink.proxy.rpc.enums.Result; -import com.smartdevicelink.proxy.rpc.enums.SystemCapabilityType; -import com.smartdevicelink.proxy.rpc.listeners.OnRPCResponseListener; -import com.smartdevicelink.util.CorrelationIdGenerator; -import com.smartdevicelink.util.DebugTool; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; - -public class SystemCapabilityManager { - private final HashMap<SystemCapabilityType, Object> cachedSystemCapabilities; - private final HashMap<SystemCapabilityType, CopyOnWriteArrayList<OnSystemCapabilityListener>> onSystemCapabilityListeners; - private final Object LISTENER_LOCK; - private final ISdl callback; - - public SystemCapabilityManager(ISdl callback){ - this.callback = callback; - this.LISTENER_LOCK = new Object(); - this.onSystemCapabilityListeners = new HashMap<>(); - this.cachedSystemCapabilities = new HashMap<>(); - } - - public void parseRAIResponse(RegisterAppInterfaceResponse response){ - if(response!=null && response.getSuccess()) { - setCapability(SystemCapabilityType.HMI, response.getHmiCapabilities()); - setCapability(SystemCapabilityType.DISPLAY, response.getDisplayCapabilities()); - setCapability(SystemCapabilityType.AUDIO_PASSTHROUGH, response.getAudioPassThruCapabilities()); - setCapability(SystemCapabilityType.PCM_STREAMING, response.getPcmStreamingCapabilities()); - setCapability(SystemCapabilityType.BUTTON, response.getButtonCapabilities()); - setCapability(SystemCapabilityType.HMI_ZONE, response.getHmiZoneCapabilities()); - setCapability(SystemCapabilityType.PRESET_BANK, response.getPresetBankCapabilities()); - setCapability(SystemCapabilityType.SOFTBUTTON, response.getSoftButtonCapabilities()); - setCapability(SystemCapabilityType.SPEECH, response.getSpeechCapabilities()); - setCapability(SystemCapabilityType.VOICE_RECOGNITION, response.getVrCapabilities()); - } - } - - /** - * Sets a capability in the cached map. This should only be done when an RPC is received and contains updates to the capability - * that is being cached in the SystemCapabilityManager. - * @param systemCapabilityType - * @param capability - */ - public synchronized void setCapability(SystemCapabilityType systemCapabilityType, Object capability){ - cachedSystemCapabilities.put(systemCapabilityType, capability); - notifyListeners(systemCapabilityType, capability); - } - - /** - * Notify listners in the list about the new retrieved capability - * @param systemCapabilityType - * @param capability - */ - private void notifyListeners(SystemCapabilityType systemCapabilityType, Object capability) { - synchronized(LISTENER_LOCK){ - CopyOnWriteArrayList<OnSystemCapabilityListener> listeners = onSystemCapabilityListeners.get(systemCapabilityType); - if(listeners != null && listeners.size() > 0) { - for (OnSystemCapabilityListener listener : listeners) { - listener.onCapabilityRetrieved(capability); - } - } - } - } - - /** - * Ability to see if the connected module supports the given capability. Useful to check before - * attempting to query for capabilities that require asynchronous calls to initialize. - * @param type the SystemCapabilityType that is to be checked - * @return if that capability is supported with the current, connected module - */ - public boolean isCapabilitySupported(SystemCapabilityType type){ - if(cachedSystemCapabilities.get(type) != null){ - //The capability exists in the map and is not null - return true; - }else if(cachedSystemCapabilities.containsKey(SystemCapabilityType.HMI)){ - HMICapabilities hmiCapabilities = ((HMICapabilities)cachedSystemCapabilities.get(SystemCapabilityType.HMI)); - switch (type) { - case NAVIGATION: - return hmiCapabilities.isNavigationAvailable(); - case PHONE_CALL: - return hmiCapabilities.isPhoneCallAvailable(); - case VIDEO_STREAMING: - return hmiCapabilities.isVideoStreamingAvailable(); - case REMOTE_CONTROL: - return hmiCapabilities.isRemoteControlAvailable(); - default: - return false; - } - }else{ - return false; - } - } - /** - * @param systemCapabilityType Type of capability desired - * @param scListener callback to execute upon retrieving capability - */ - public void getCapability(final SystemCapabilityType systemCapabilityType, final OnSystemCapabilityListener scListener){ - Object capability = cachedSystemCapabilities.get(systemCapabilityType); - if(capability != null){ - scListener.onCapabilityRetrieved(capability); - return; - }else if(scListener == null){ - return; - } - - retrieveCapability(systemCapabilityType, scListener); - } - - /** - * @param systemCapabilityType Type of capability desired - * @return Desired capability if it is cached in the manager, otherwise returns a null object - * and works in the background to retrieve the capability for the next call - */ - public Object getCapability(final SystemCapabilityType systemCapabilityType){ - Object capability = cachedSystemCapabilities.get(systemCapabilityType); - if(capability != null){ - return capability; - } - - retrieveCapability(systemCapabilityType, null); - return null; - } - - /** - * Add a listener to be called whenever a new capability is retrieved - * @param systemCapabilityType Type of capability desired - * @param listener callback to execute upon retrieving capability - */ - public void addOnSystemCapabilityListener(final SystemCapabilityType systemCapabilityType, final OnSystemCapabilityListener listener){ - getCapability(systemCapabilityType, listener); - synchronized(LISTENER_LOCK){ - if (systemCapabilityType != null && listener != null) { - if (onSystemCapabilityListeners.get(systemCapabilityType) == null) { - onSystemCapabilityListeners.put(systemCapabilityType, new CopyOnWriteArrayList<OnSystemCapabilityListener>()); - } - onSystemCapabilityListeners.get(systemCapabilityType).add(listener); - } - } - } - - /** - * Remove an OnSystemCapabilityListener that was previously added - * @param systemCapabilityType Type of capability - * @param listener the listener that should be removed - */ - public boolean removeOnSystemCapabilityListener(final SystemCapabilityType systemCapabilityType, final OnSystemCapabilityListener listener){ - synchronized(LISTENER_LOCK){ - if(onSystemCapabilityListeners!= null - && systemCapabilityType != null - && listener != null - && onSystemCapabilityListeners.get(systemCapabilityType) != null){ - return onSystemCapabilityListeners.get(systemCapabilityType).remove(listener); - } - } - return false; - } - - /** - * @param systemCapabilityType Type of capability desired - * passes GetSystemCapabilityType request to `callback` to be sent by proxy. - * this method will send RPC and call the listener's callback only if the systemCapabilityType is queryable - */ - private void retrieveCapability(final SystemCapabilityType systemCapabilityType, final OnSystemCapabilityListener scListener){ - if (!systemCapabilityType.isQueryable()){ - String message = "This systemCapabilityType cannot be queried for"; - DebugTool.logError(message); - scListener.onError(message); - return; - } - final GetSystemCapability request = new GetSystemCapability(); - request.setSystemCapabilityType(systemCapabilityType); - request.setOnRPCResponseListener(new OnRPCResponseListener() { - @Override - public void onResponse(int correlationId, RPCResponse response) { - if(response.getSuccess()){ - Object retrievedCapability = ((GetSystemCapabilityResponse) response).getSystemCapability().getCapabilityForType(systemCapabilityType); - cachedSystemCapabilities.put(systemCapabilityType, retrievedCapability); - if(scListener!=null){scListener.onCapabilityRetrieved(retrievedCapability); } - }else{ - if(scListener!=null){scListener.onError(response.getInfo());} - } - } - - @Override - public void onError(int correlationId, Result resultCode, String info) { - if(scListener!=null){scListener.onError(info);} - } - }); - request.setCorrelationID(CorrelationIdGenerator.generateId()); - - if(callback!=null){ - callback.sendRPCRequest(request); - } - } - - /** - * Converts a capability object into a list. - * @param object the capability that needs to be converted - * @param classType The class type of that should be contained in the list - * @return a List of capabilities if object is instance of List, otherwise it will return null. - */ - @SuppressWarnings({"unchecked"}) - public static <T> List<T> convertToList(Object object, Class<T> classType){ - if(classType!=null && object!=null && object instanceof List ){ - List list = (List)object; - if(!list.isEmpty()){ - if(classType.isInstance(list.get(0))){ - return (List<T>)object; - }else{ - //The list is not of the correct list type - return null; - } - }else { - //We return a new list of type T instead of null because while we don't know if - //the original list was of type T we want to ensure that we don't throw a cast class exception - //but still - return new ArrayList<T>(); - } - }else{ - return null; - } - } -} diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/TTSChunkFactory.java b/android/sdl_android/src/main/java/com/smartdevicelink/proxy/TTSChunkFactory.java deleted file mode 100644 index b8b847261..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/TTSChunkFactory.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.smartdevicelink.proxy;
-
-import java.util.Vector;
-
-import com.smartdevicelink.proxy.rpc.TTSChunk;
-import com.smartdevicelink.proxy.rpc.enums.SpeechCapabilities;
-
-public class TTSChunkFactory {
-
- public static TTSChunk createChunk(SpeechCapabilities type, String text) {
- TTSChunk ret = new TTSChunk();
- ret.setType(type);
- ret.setText(text);
- return ret;
- }
-
- public static Vector<TTSChunk> createSimpleTTSChunks(String simple) {
- if (simple == null) {
- return null;
- }
-
- Vector<TTSChunk> chunks = new Vector<TTSChunk>();
-
- TTSChunk chunk = createChunk(SpeechCapabilities.TEXT, simple);
- chunks.add(chunk);
- return chunks;
- }
-
- public static Vector<TTSChunk> createPrerecordedTTSChunks(String prerecorded) {
- if (prerecorded == null) {
- return null;
- }
-
- Vector<TTSChunk> chunks = new Vector<TTSChunk>();
- TTSChunk chunk = createChunk(SpeechCapabilities.PRE_RECORDED, prerecorded);
- chunks.add(chunk);
- return chunks;
- }
-}
diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/Version.java b/android/sdl_android/src/main/java/com/smartdevicelink/proxy/Version.java index d49d979fe..7460f6bca 100644 --- a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/Version.java +++ b/android/sdl_android/src/main/java/com/smartdevicelink/proxy/Version.java @@ -2,6 +2,7 @@ package com.smartdevicelink.proxy; import com.smartdevicelink.BuildConfig;
+@Deprecated
public class Version {
public static final String VERSION = BuildConfig.VERSION_NAME;
}
diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/callbacks/InternalProxyMessage.java b/android/sdl_android/src/main/java/com/smartdevicelink/proxy/callbacks/InternalProxyMessage.java deleted file mode 100644 index dc03f5c72..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/callbacks/InternalProxyMessage.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.smartdevicelink.proxy.callbacks;
-
-public class InternalProxyMessage {
- private String _functionName;
- public static final String OnProxyError = "OnProxyError";
- public static final String OnProxyOpened = "OnProxyOpened";
- public static final String OnProxyClosed = "OnProxyClosed";
- public static final String OnServiceEnded = "OnServiceEnded";
- public static final String OnServiceNACKed = "OnServiceNACKed";
-
- public InternalProxyMessage(String functionName) {
- //this(functionName, null, null);
- this._functionName = functionName;
- }
-
- public String getFunctionName() {
- return _functionName;
- }
-}
\ No newline at end of file diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/callbacks/OnError.java b/android/sdl_android/src/main/java/com/smartdevicelink/proxy/callbacks/OnError.java deleted file mode 100644 index 0323afa15..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/callbacks/OnError.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.smartdevicelink.proxy.callbacks;
-
-public class OnError extends InternalProxyMessage {
-
- private String _info;
- private Exception _e;
-
- public OnError() {
- super(InternalProxyMessage.OnProxyError);
- }
-
- public OnError(String info, Exception e) {
- super(InternalProxyMessage.OnProxyError);
- this._info = info;
- this._e = e;
- }
-
- public String getInfo() {
- return _info;
- }
-
- public Exception getException() {
- return _e;
- }
-}
\ No newline at end of file diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/callbacks/OnProxyClosed.java b/android/sdl_android/src/main/java/com/smartdevicelink/proxy/callbacks/OnProxyClosed.java deleted file mode 100644 index 9a32c4a8d..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/callbacks/OnProxyClosed.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.smartdevicelink.proxy.callbacks;
-
-import com.smartdevicelink.proxy.rpc.enums.SdlDisconnectedReason;
-
-public class OnProxyClosed extends InternalProxyMessage {
-
- private String _info;
- private Exception _e;
- private SdlDisconnectedReason _reason;
-
- public OnProxyClosed() {
- super(InternalProxyMessage.OnProxyClosed);
- }
-
- public OnProxyClosed(String info, Exception e, SdlDisconnectedReason reason) {
- super(InternalProxyMessage.OnProxyClosed);
- this._info = info;
- this._e = e;
- this._reason = reason;
- }
-
- public String getInfo() {
- return _info;
- }
-
- public SdlDisconnectedReason getReason() {
- return _reason;
- }
-
- public Exception getException() {
- return _e;
- }
-}
\ No newline at end of file diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/callbacks/OnProxyOpened.java b/android/sdl_android/src/main/java/com/smartdevicelink/proxy/callbacks/OnProxyOpened.java deleted file mode 100644 index 1fa9c19eb..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/callbacks/OnProxyOpened.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.smartdevicelink.proxy.callbacks;
-
-public class OnProxyOpened extends InternalProxyMessage {
-
- public OnProxyOpened() {
- super(InternalProxyMessage.OnProxyOpened);
- }
-}
diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/callbacks/OnServiceEnded.java b/android/sdl_android/src/main/java/com/smartdevicelink/proxy/callbacks/OnServiceEnded.java deleted file mode 100644 index d69802e0f..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/callbacks/OnServiceEnded.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.smartdevicelink.proxy.callbacks; - -import com.smartdevicelink.protocol.enums.SessionType; - -public class OnServiceEnded extends InternalProxyMessage { - private SessionType sessionType; - - public OnServiceEnded() { - super(InternalProxyMessage.OnServiceEnded); - } - - public OnServiceEnded(SessionType sessionType) { - super(InternalProxyMessage.OnServiceEnded); - this.sessionType = sessionType; - } - - public SessionType getSessionType() { - return this.sessionType; - } - -} diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/callbacks/OnServiceNACKed.java b/android/sdl_android/src/main/java/com/smartdevicelink/proxy/callbacks/OnServiceNACKed.java deleted file mode 100644 index 9eae5e4c4..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/callbacks/OnServiceNACKed.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.smartdevicelink.proxy.callbacks; - -import com.smartdevicelink.protocol.enums.SessionType; - -public class OnServiceNACKed extends InternalProxyMessage { - private SessionType sessionType; - - public OnServiceNACKed() { - super(InternalProxyMessage.OnServiceNACKed); - } - - public OnServiceNACKed(SessionType sessionType) { - super(InternalProxyMessage.OnServiceNACKed); - this.sessionType = sessionType; - } - - public SessionType getSessionType() { - return this.sessionType; - } - -} diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/constants/Jingles.java b/android/sdl_android/src/main/java/com/smartdevicelink/proxy/constants/Jingles.java deleted file mode 100644 index b029e55e8..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/constants/Jingles.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.smartdevicelink.proxy.constants;
-
-@Deprecated
-public class Jingles {
- public static final String POSITIVE_JINGLE = "POSITIVE_JINGLE";
-
- public static final String NEGATIVE_JINGLE = "NEGATIVE_JINGLE";
-
- public static final String INITIAL_JINGLE = "INITIAL_JINGLE";
-
- public static final String LISTEN_JINGLE = "LISTEN_JINGLE";
-
- public static final String HELP_JINGLE = "HELP_JINGLE";
-
-}
\ No newline at end of file diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/constants/Names.java b/android/sdl_android/src/main/java/com/smartdevicelink/proxy/constants/Names.java deleted file mode 100644 index 26729e997..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/constants/Names.java +++ /dev/null @@ -1,506 +0,0 @@ -package com.smartdevicelink.proxy.constants;
-
-@Deprecated
-public class Names {
- public static final String request = "request";
- public static final String response = "response";
- public static final String notification = "notification";
- public static final String function_name = "name";
- public static final String parameters = "parameters";
- public static final String bulkData = "bulkData";
-
- public static final String RegisterAppInterface = "RegisterAppInterface";
- public static final String UnregisterAppInterface = "UnregisterAppInterface";
- public static final String Alert = "Alert";
- public static final String Show = "Show";
- public static final String Speak = "Speak";
- public static final String AddCommand = "AddCommand";
- public static final String DeleteCommand = "DeleteCommand";
- public static final String AddSubMenu = "AddSubMenu";
- public static final String DeleteSubMenu = "DeleteSubMenu";
- public static final String CreateInteractionChoiceSet = "CreateInteractionChoiceSet";
- public static final String DeleteInteractionChoiceSet = "DeleteInteractionChoiceSet";
- public static final String PerformInteraction = "PerformInteraction";
- public static final String DialNumber = "DialNumber";
- public static final String EncodedSyncPData = "EncodedSyncPData";
- public static final String SyncPData = "SyncPData";
- public static final String SubscribeButton = "SubscribeButton";
- public static final String UnsubscribeButton = "UnsubscribeButton";
- public static final String SubscribeVehicleData = "SubscribeVehicleData";
- public static final String UnsubscribeVehicleData = "UnsubscribeVehicleData";
- public static final String SetMediaClockTimer = "SetMediaClockTimer";
- public static final String SetGlobalProperties = "SetGlobalProperties";
- public static final String GenericResponse = "GenericResponse";
- public static final String ScrollableMessage = "ScrollableMessage";
- public static final String GetDID = "GetDID";
- public static final String GetDTCs = "GetDTCs";
- public static final String DiagnosticMessage = "DiagnosticMessage";
- public static final String SystemRequest = "SystemRequest";
- public static final String ReadDID = "ReadDID";
- public static final String OnVehicleData = "OnVehicleData";
- public static final String GetFile = "GetFile";
- public static final String PutFile = "PutFile";
- public static final String DeleteFile = "DeleteFile";
- public static final String ListFiles = "ListFiles";
- public static final String EndAudioCapture = "EndAudioCapture";
- public static final String GetVehicleData = "GetVehicleData";
- public static final String ResetGlobalProperties = "ResetGlobalProperties";
- public static final String PerformAudioCapture = "PerformAudioCapture";
- public static final String SetAppIcon = "SetAppIcon";
- public static final String ChangeRegistration = "ChangeRegistration";
- public static final String SetDisplayLayout = "SetDisplayLayout";
- public static final String keypressMode = "keypressMode";
- public static final String keyboardLayout = "keyboardLayout";
- public static final String limitedCharacterList = "limitedCharacterList";
- public static final String autoCompleteText = "autoCompleteText";
- public static final String OnLanguageChange = "OnLanguageChange";
- public static final String hmiDisplayLanguage = "hmiDisplayLanguage";
- public static final String displayLayout = "displayLayout";
- public static final String ttsName = "ttsName";
- public static final String hmiDisplayLanguageDesired = "hmiDisplayLanguageDesired";
- public static final String appHMIType = "appHMIType";
- public static final String hashID = "hashID";
- public static final String appID = "appID";
- public static final String vrHelpTitle = "vrHelpTitle";
- public static final String graphic = "graphic";
- public static final String customPresets = "customPresets";
- public static final String softButtonCapabilities = "softButtonCapabilities";
- public static final String presetBankCapabilities = "presetBankCapabilities";
- public static final String vehicleType = "vehicleType";
- public static final String make = "make";
- public static final String model = "model";
- public static final String modelYear = "modelYear";
- public static final String trim = "trim";
- public static final String allowed = "allowed";
- public static final String userDisallowed = "userDisallowed";
- public static final String rpcName = "rpcName";
- public static final String hmiPermissions = "hmiPermissions";
- public static final String parameterPermissions = "parameterPermissions";
- public static final String permissionItem = "permissionItem";
- public static final String numTicks = "numTicks";
- public static final String sliderHeader = "sliderHeader";
- public static final String sliderFooter = "sliderFooter";
- public static final String PerformAudioPassThru = "PerformAudioPassThru";
- public static final String PerformAudioPassThruResponse = "PerformAudioPassThruResponse";
- public static final String EndAudioPassThru = "EndAudioPassThru";
- public static final String EndAudioPassThruResponse = "EndAudioPassThruResponse";
- public static final String OnAudioPassThru = "OnAudioPassThru";
- public static final String ShowConstantTBT = "ShowConstantTBT";
- public static final String AlertManeuver = "AlertManeuver";
- public static final String UpdateTurnList = "UpdateTurnList";
-
- public static final String OnCommand = "OnCommand";
- public static final String OnDataPublished = "OnDataPublished";
- public static final String OnButtonPress = "OnButtonPress";
- public static final String OnButtonEvent = "OnButtonEvent";
- public static final String OnHMIStatus = "OnHMIStatus";
- public static final String OnTBTClientState = "OnTBTClientState";
- public static final String OnEncodedSyncPData = "OnEncodedSyncPData";
- public static final String onEncodedSyncPDataResponse = "onEncodedSyncPDataResponse";
- public static final String OnSyncPData = "OnSyncPData";
- public static final String onOnSyncPData = "onOnSyncPData";
- public static final String OnDriverDistraction = "OnDriverDistraction";
- public static final String OnAppInterfaceUnregistered = "OnAppInterfaceUnregistered";
- public static final String OnKeyboardInput = "OnKeyboardInput";
- public static final String OnTouchEvent = "OnTouchEvent";
- public static final String OnSystemRequest = "OnSystemRequest";
- public static final String OnHashChange = "OnHashChange";
- public static final String OnProxyClosed = "OnProxyClosed";
- public static final String OnProxyError = "OnProxyError";
- public static final String OnProxyOpened = "OnProxyOpened";
- public static final String OnProxyUnusable = "OnProxyUnusable";
- public static final String OnHMILevelChange = "OnHMILevelChange";
- public static final String OnSdlChoiceChosen = "OnSdlChoiceChosen";
- public static final String OnPermissionsChange = "OnPermissionsChange";
- public static final String OnScreenPresetsAvailable = "OnScreenPresetsAvailable";
- public static final String isHighlighted = "isHighlighted";
- public static final String softButtonID = "softButtonID";
- public static final String fileType = "fileType";
- public static final String url = "url";
- public static final String requestType = "requestType";
- public static final String fileName = "fileName";
- public static final String persistentFile = "persistentFile";
- public static final String spaceAvailable = "spaceAvailable";
- public static final String filenames = "filenames";
- public static final String cmdIcon = "cmdIcon";
- public static final String Slider = "Slider";
- public static final String sliderPosition = "sliderPosition";
- public static final String samplingRate = "samplingRate";
- public static final String audioType = "audioType";
- public static final String satRadioESN = "satRadioESN";
- public static final String dtc = "dtc";
- public static final String tryAgainTime = "tryAgainTime";
-
- public static final String success = "success";
- public static final String resultCode = "resultCode";
- public static final String info = "info";
-
- public static final String payload = "payload";
- public static final String reason = "reason";
- public static final String state = "state";
- public static final String cmdID = "cmdID";
- public static final String menuParams = "menuParams";
- public static final String parentID = "parentID";
- public static final String position = "position";
- public static final String menuName = "menuName";
- public static final String vrCommands = "vrCommands";
- public static final String language = "language";
- public static final String languageDesired = "languageDesired";
- public static final String triggerSource = "triggerSource";
- public static final String subscriptionType = "subscriptionType";
- public static final String data = "data";
- public static final String event = "event";
- public static final String correlationID = "correlationID";
- public static final String sdlMsgVersion = "syncMsgVersion";
- public static final String deviceInfo = "deviceInfo";
- public static final String majorVersion = "majorVersion";
- public static final String minorVersion = "minorVersion";
- public static final String appName = "appName";
- public static final String ngnMediaScreenAppName = "ngnMediaScreenAppName";
- public static final String isMediaApplication = "isMediaApplication";
- public static final String vrSynonyms = "vrSynonyms";
- public static final String usesVehicleData = "usesVehicleData";
- public static final String text = "text";
- public static final String type = "type";
- public static final String ttsChunks = "ttsChunks";
- public static final String playTone = "playTone";
- public static final String duration = "duration";
- public static final String mainField1 = "mainField1";
- public static final String mainField2 = "mainField2";
- public static final String mainField3 = "mainField3";
- public static final String mainField4 = "mainField4";
- public static final String statusBar = "statusBar";
- public static final String name = "name";
- public static final String menuID = "menuID";
- public static final String longPress = "longPress";
- public static final String shortPress = "shortPress";
- public static final String buttonName = "buttonName";
- public static final String buttonPressMode = "buttonPressMode";
- public static final String buttonEventMode = "buttonEventMode";
- public static final String minutes = "minutes";
- public static final String seconds = "seconds";
- public static final String startTime = "startTime";
- public static final String endTime = "endTime";
- public static final String updateMode = "updateMode";
- public static final String mediaClock = "mediaClock";
- public static final String initialText = "initialText";
- public static final String initialPrompt = "initialPrompt";
- public static final String helpPrompt = "helpPrompt";
- public static final String timeoutPrompt = "timeoutPrompt";
- public static final String timeout = "timeout";
- public static final String choiceSet = "choiceSet";
- public static final String interactionMode = "interactionMode";
- public static final String result = "result";
- public static final String alertText1 = "alertText1";
- public static final String alertText2 = "alertText2";
- public static final String alertText3 = "alertText3";
- public static final String shortPressAvailable = "shortPressAvailable";
- public static final String longPressAvailable = "longPressAvailable";
- public static final String upDownAvailable = "upDownAvailable";
- public static final String width = "width";
- public static final String height = "height";
- public static final String resolutionWidth = "resolutionWidth";
- public static final String resolutionHeight = "resolutionHeight";
- public static final String characterSet = "characterSet";
- public static final String displayType = "displayType";
- public static final String mediaClockFormats = "mediaClockFormats";
- public static final String textFields = "textFields";
- public static final String imageFields = "imageFields";
- public static final String autoActivateID = "autoActivateID";
- public static final String vehicleDataCapabilities = "vehicleDataCapabilities";
- public static final String speechCapabilities = "speechCapabilities";
- public static final String vrCapabilities = "vrCapabilities";
- public static final String audioPassThruCapabilities = "audioPassThruCapabilities";
- public static final String buttonCapabilities = "buttonCapabilities";
- public static final String displayCapabilities = "displayCapabilities";
- public static final String hmiZoneCapabilities = "hmiZoneCapabilities";
- public static final String interactionChoiceSetID = "interactionChoiceSetID";
- public static final String interactionChoiceSetIDList = "interactionChoiceSetIDList";
- public static final String audioFileName = "audioFileName";
- public static final String gpsPositionValid = "gpsPositionValid";
- public static final String longitudeDegrees = "longitudeDegrees";
- public static final String latitudeDegrees = "latitudeDegrees";
- public static final String utcYear = "utcYear";
- public static final String utcMonth = "utcMonth";
- public static final String utcDay = "utcDay";
- public static final String utcHours = "utcHours";
- public static final String utcMinutes = "utcMinutes";
- public static final String utcSeconds = "utcSeconds";
- public static final String compassDirection = "compassDirection";
- public static final String pdop = "pdop";
- public static final String vdop = "vdop";
- public static final String hdop = "hdop";
- public static final String actual = "actual";
- public static final String satellites = "satellites";
- public static final String dimension = "dimension";
- public static final String altitude = "altitude";
- public static final String heading = "heading";
- public static final String speed = "speed";
- public static final String number = "number";
- public static final String smartDeviceLinkFileName = "syncFileName";
- public static final String localFileName = "localFileName";
- public static final String maxDuration = "maxDuration";
- public static final String timerMode = "timerMode";
- public static final String status = "status";
- public static final String pressure = "pressure";
- public static final String hours = "hours";
- public static final String rows = "rows";
- public static final String pressureTellTale = "pressureTellTale";
- public static final String leftFront = "leftFront";
- public static final String rightFront = "rightFront";
- public static final String leftRear = "leftRear";
- public static final String rightRear = "rightRear";
- public static final String innerLeftRear = "innerLeftRear";
- public static final String innerRightRear = "innerRightRear";
- public static final String VehicleData = "VehicleData";
- public static final String alignment = "alignment";
- public static final String mediaTrack = "mediaTrack";
- public static final String properties = "properties";
- public static final String choiceID = "choiceID";
- public static final String bitsPerSample = "bitsPerSample";
- public static final String hmiLevel = "hmiLevel";
- public static final String audioStreamingState = "audioStreamingState";
- public static final String systemContext = "systemContext";
- public static final String sdlChoice = "sdlChoice";
- public static final String sdlCommand = "sdlCommand";
- public static final String URL = "URL";
- public static final String Timeout = "Timeout";
- public static final String PermissionGroupName = "PermissionGroupName";
- public static final String PermissionGroupStatus = "PermissionGroupStatus";
- public static final String PermissionGroupItems = "PermissionGroupItems";
- public static final String audioPacket = "audioPacket";
- public static final String audioPassThruDisplayText1 = "audioPassThruDisplayText1";
- public static final String audioPassThruDisplayText2 = "audioPassThruDisplayText2";
- public static final String bitRate = "bitRate";
- public static final String rpm = "rpm";
- public static final String fuelLevel = "fuelLevel";
- public static final String avgFuelEconomy = "avgFuelEconomy";
- public static final String batteryVoltage = "batteryVoltage";
- public static final String externalTemperature = "externalTemperature";
- public static final String vin = "vin";
- public static final String prndl = "prndl";
- public static final String tirePressure = "tirePressure";
- public static final String batteryPackVoltage = "batteryPackVoltage";
- public static final String batteryPackCurrent = "batteryPackCurrent";
- public static final String batteryPackTemperature = "batteryPackTemperature";
- public static final String engineTorque = "engineTorque";
- public static final String odometer = "odometer";
- public static final String tripOdometer = "tripOdometer";
- public static final String genericbinary = "genericbinary";
- public static final String GPSData = "GPSData";
- public static final String gps = "gps";
- public static final String fuelLevel_State = "fuelLevel_State";
- public static final String instantFuelConsumption = "instantFuelConsumption";
- public static final String beltStatus = "beltStatus";
- public static final String bodyInformation = "bodyInformation";
- public static final String deviceStatus = "deviceStatus";
- public static final String driverBraking = "driverBraking";
- public static final String wiperStatus = "wiperStatus";
- public static final String fuelEconomy = "fuelEconomy";
- public static final String engineOilLife = "engineOilLife";
- public static final String headLampStatus = "headLampStatus";
- public static final String brakeTorque = "brakeTorque";
- public static final String turboBoost = "turboBoost";
- public static final String coolantTemp = "coolantTemp";
- public static final String airFuelRatio = "airFuelRatio";
- public static final String coolingHeadTemp = "coolingHeadTemp";
- public static final String oilTemp = "oilTemp";
- public static final String intakeAirTemp = "intakeAirTemp";
- public static final String gearShiftAdvice = "gearShiftAdvice";
- public static final String acceleration = "acceleration";
- public static final String accPedalPosition = "accPedalPosition";
- public static final String clutchPedalPosition = "clutchPedalPosition";
- public static final String reverseGearStatus = "reverseGearStatus";
- public static final String accTorque = "accTorque";
- public static final String ambientLightStatus = "ambientLightStatus";
- public static final String ambientLightSensorStatus = "ambientLightSensorStatus";
- public static final String dataType = "dataType";
- public static final String identifier = "identifier";
- public static final String statusByte = "statusByte";
- public static final String didResult = "didResult";
- public static final String ecuName = "ecuName";
- public static final String didLocation = "didLocation";
- public static final String value = "value";
- public static final String softButtonName = "softButtonName";
- public static final String imageSupported = "imageSupported";
- public static final String systemAction = "systemAction";
- public static final String image = "image";
- public static final String secondaryText = "secondaryText";
- public static final String tertiaryText = "tertiaryText";
- public static final String secondaryImage = "secondaryImage";
- public static final String imageType = "imageType";
- public static final String fileData = "fileData";
- public static final String scrollableMessageBody = "scrollableMessageBody";
- public static final String softButtons = "softButtons";
- public static final String customButtonID = "customButtonID";
- public static final String vrHelp = "vrHelp";
- public static final String interactionLayout = "interactionLayout";
- public static final String customButtonName = "customButtonName";
- public static final String navigationText = "navigationText";
- public static final String turnIcon = "turnIcon";
- public static final String nextTurnIcon = "nextTurnIcon";
- public static final String navigationText1 = "navigationText1";
- public static final String navigationText2 = "navigationText2";
- public static final String eta = "eta";
- public static final String totalDistance = "totalDistance";
- public static final String distanceToManeuver = "distanceToManeuver";
- public static final String distanceToManeuverScale = "distanceToManeuverScale";
- public static final String maneuverComplete = "maneuverComplete";
- public static final String turnList = "turnList";
- public static final String steeringWheelAngle = "steeringWheelAngle";
- public static final String menuTitle = "menuTitle";
- public static final String menuIcon = "menuIcon";
- public static final String keyboardProperties = "keyboardProperties";
- public static final String driverBeltDeployed = "driverBeltDeployed";
- public static final String passengerBeltDeployed = "passengerBeltDeployed";
- public static final String passengerBuckleBelted = "passengerBuckleBelted";
- public static final String driverBuckleBelted = "driverBuckleBelted";
- public static final String leftRow2BuckleBelted = "leftRow2BuckleBelted";
- public static final String passengerChildDetected = "passengerChildDetected";
- public static final String rightRow2BuckleBelted = "rightRow2BuckleBelted";
- public static final String middleRow2BuckleBelted = "middleRow2BuckleBelted";
- public static final String middleRow3BuckleBelted = "middleRow3BuckleBelted";
- public static final String leftRow3BuckleBelted = "leftRow3BuckleBelted";
- public static final String rightRow3BuckleBelted = "rightRow3BuckleBelted";
- public static final String rearInflatableBelted = "rearInflatableBelted";
- public static final String leftRearInflatableBelted = "leftRearInflatableBelted";
- public static final String rightRearInflatableBelted = "rightRearInflatableBelted";
- public static final String middleRow1BeltDeployed = "middleRow1BeltDeployed";
- public static final String middleRow1BuckleBelted = "middleRow1BuckleBelted";
-
- public static final String graphicSupported = "graphicSupported";
- public static final String screenParams = "screenParams";
- public static final String muteAudio = "muteAudio";
- public static final String parkBrakeActive = "parkBrakeActive";
- public static final String ignitionStableStatus = "ignitionStableStatus";
- public static final String ignitionStatus = "ignitionStatus";
- public static final String driverDoorAjar = "driverDoorAjar";
- public static final String passengerDoorAjar = "passengerDoorAjar";
- public static final String rearLeftDoorAjar = "rearLeftDoorAjar";
- public static final String rearRightDoorAjar = "rearRightDoorAjar";
- public static final String systemFile = "systemFile";
-
- public static final String voiceRecOn = "voiceRecOn";
- public static final String btIconOn = "btIconOn";
- public static final String callActive = "callActive";
- public static final String phoneRoaming = "phoneRoaming";
- public static final String textMsgAvailable = "textMsgAvailable";
- public static final String battLevelStatus = "battLevelStatus";
- public static final String stereoAudioOutputMuted = "stereoAudioOutputMuted";
- public static final String monoAudioOutputMuted = "monoAudioOutputMuted";
- public static final String signalLevelStatus = "signalLevelStatus";
- public static final String primaryAudioSource = "primaryAudioSource";
- public static final String eCallEventActive = "eCallEventActive";
-
- public static final String fuelEconomySinceLastReset = "fuelEconomySinceLastReset";
- public static final String currentTripFuelEconomy = "currentTripFuelEconomy";
- public static final String averageTripFuelEconomy = "averageTripFuelEconomy";
- public static final String currentCycleFuelEconomy = "currentCycleFuelEconomy";
-
- public static final String lightSwitchStatus = "lightSwitchStatus";
- public static final String highBeamsOn = "highBeamsOn";
- public static final String lowBeamsOn = "lowBeamsOn";
-
- public static final String electricFuelConsumption = "electricFuelConsumption";
- public static final String stateOfCharge = "stateOfCharge";
- public static final String fuelMaintenanceMode = "fuelMaintenanceMode";
- public static final String distanceToEmpty = "distanceToEmpty";
-
- public static final String dtcMask = "dtcMask";
- public static final String targetID = "targetID";
- public static final String messageLength = "messageLength";
- public static final String messageData = "messageData";
- public static final String messageDataResult = "messageDataResult";
-
- public static final String imageTypeSupported = "imageTypeSupported";
- public static final String imageResolution = "imageResolution";
- public static final String x = "x";
- public static final String y = "y";
- public static final String id = "id";
- public static final String ts = "ts";
- public static final String c = "c";
- public static final String resolution = "resolution";
- public static final String touchEventAvailable = "touchEventAvailable";
-
- public static final String pressAvailable = "pressAvailable";
- public static final String multiTouchAvailable = "multiTouchAvailable";
- public static final String doublePressAvailable = "doublePressAvailable";
- public static final String templatesAvailable = "templatesAvailable";
- public static final String numCustomPresetsAvailable = "numCustomPresetsAvailable";
- public static final String prerecordedSpeech = "prerecordedSpeech";
- public static final String manualTextEntry = "manualTextEntry";
- public static final String progressIndicator = "progressIndicator";
- public static final String secondaryGraphic = "secondaryGraphic";
- public static final String offset = "offset";
- public static final String length = "length";
-
- public static final String hardware = "hardware";
- public static final String firmwareRev = "firmwareRev";
- public static final String os = "os";
- public static final String osVersion = "osVersion";
- public static final String carrier = "carrier";
- public static final String maxNumberRFCOMMPorts = "maxNumberRFCOMMPorts";
-
- public static final String onReadDIDResponse = "onReadDIDResponse";
- public static final String onGetDTCsResponse = "onGetDTCsResponse";
- public static final String onOnKeyboardInput = "onOnKeyboardInput";
- public static final String onOnTouchEvent = "onOnTouchEvent";
- public static final String onOnSystemRequest = "onOnSystemRequest";
-
- public static final String onDiagnosticMessageResponse = "onDiagnosticMessageResponse";
- public static final String onSystemRequestResponse = "onSystemRequestResponse";
- public static final String onGetVehicleDataResponse = "onGetVehicleDataResponse";
- public static final String getSupportedDiagModes = "getSupportedDiagModes";
- public static final String supportedDiagModes = "supportedDiagModes";
-
- public static final String driverAirbagDeployed = "driverAirbagDeployed";
- public static final String driverSideAirbagDeployed = "driverSideAirbagDeployed";
- public static final String driverCurtainAirbagDeployed = "driverCurtainAirbagDeployed";
- public static final String passengerAirbagDeployed = "passengerAirbagDeployed";
- public static final String passengerCurtainAirbagDeployed = "passengerCurtainAirbagDeployed";
- public static final String driverKneeAirbagDeployed = "driverKneeAirbagDeployed";
- public static final String passengerSideAirbagDeployed = "passengerSideAirbagDeployed";
- public static final String passengerKneeAirbagDeployed = "passengerKneeAirbagDeployed";
-
- public static final String powerModeActive = "powerModeActive";
- public static final String powerModeQualificationStatus = "powerModeQualificationStatus";
- public static final String carModeStatus = "carModeStatus";
- public static final String powerModeStatus = "powerModeStatus";
-
- public static final String eCallNotificationStatus = "eCallNotificationStatus";
- public static final String auxECallNotificationStatus = "auxECallNotificationStatus";
- public static final String eCallConfirmationStatus = "eCallConfirmationStatus";
- public static final String e911Override = "e911Override";
-
- public static final String emergencyEventType = "emergencyEventType";
- public static final String fuelCutoffStatus = "fuelCutoffStatus";
- public static final String rolloverEvent = "rolloverEvent";
- public static final String maximumChangeVelocity = "maximumChangeVelocity";
- public static final String multipleEvents = "multipleEvents";
-
- public static final String eCallInfo = "eCallInfo";
- public static final String airbagStatus = "airbagStatus";
- public static final String emergencyEvent = "emergencyEvent";
- public static final String clusterModeStatus = "clusterModeStatus";
- public static final String myKey = "myKey";
- public static final String timeToDestination = "timeToDestination";
-
- public static final String driverDistraction = "driverDistraction";
- public static final String showLockScreen = "showLockScreen";
- public static final String userSelected = "userSelected";
- public static final String notSet = "notSet";
-
- public static final String headers = "headers";
- public static final String body = "body";
-
- public static final String ContentType = "ContentType";
- public static final String ConnectTimeout = "ConnectTimeout";
- public static final String DoOutput = "DoOutput";
- public static final String DoInput = "DoInput";
- public static final String UseCaches = "UseCaches";
- public static final String RequestMethod = "RequestMethod";
- public static final String ReadTimeout = "ReadTimeout";
- public static final String InstanceFollowRedirects = "InstanceFollowRedirects";
- public static final String charset = "charset";
- public static final String ContentLength = "Content-Length";
-}
diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/interfaces/IAudioStreamListener.java b/android/sdl_android/src/main/java/com/smartdevicelink/proxy/interfaces/IAudioStreamListener.java deleted file mode 100644 index 8d21b7615..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/interfaces/IAudioStreamListener.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (c) 2017, Xevo 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 copyright holder 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.proxy.interfaces; - -import java.nio.ByteBuffer; - -/** - * A listener that receives audio streaming data from app. - */ -public interface IAudioStreamListener { - /** - * Sends a chunk of audio data to SDL Core. - * <p> - * Note: this method must not be called after SdlProxyBase.endAudioStream() is called. - * - * @param data Byte array containing audio data - * @param offset Starting offset in 'data' - * @param length Length of the data - * @param presentationTimeUs (Reserved for future use) Presentation timestamp (PTS) of the - * last audio sample data included in this chunk, in microseconds. - * It must be greater than the previous timestamp. - * Specify -1 if unknown. - * @throws ArrayIndexOutOfBoundsException When offset does not satisfy - * {@code 0 <= offset && offset <= data.length} - * or length does not satisfy - * {@code 0 < length && offset + length <= data.length} - */ - void sendAudio(byte[] data, int offset, int length, long presentationTimeUs) - throws ArrayIndexOutOfBoundsException; - - /** - * Sends a chunk of audio data to SDL Core. - * <p> - * Note: this method must not be called after SdlProxyBase.endAudioStream() is called. - * - * @param data Data chunk to send. Its position will be updated upon return. - * @param presentationTimeUs (Reserved for future use) Presentation timestamp (PTS) of the - * last audio sample data included in this chunk, in microseconds. - * It must be greater than the previous timestamp. - * Specify -1 if unknown. - */ - void sendAudio(ByteBuffer data, long presentationTimeUs); -} diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/interfaces/IProxyListenerALM.java b/android/sdl_android/src/main/java/com/smartdevicelink/proxy/interfaces/IProxyListenerALM.java deleted file mode 100644 index 2fb5a4063..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/interfaces/IProxyListenerALM.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.smartdevicelink.proxy.interfaces;
-
-public interface IProxyListenerALM extends IProxyListenerBase {
- // Adds Advanced Life-cycle Management call-backs to the IProxyListenerAbstract interface
-
- /**
- * **MOVED TO IProxyListenerBase** - onOnHMIStatus() being called indicates that the proxy has entered a state in which the
- * application may create SDL related resources (addCommands, ChoiceSets).
- */
- //public void onOnHMIStatus(OnHMIStatus notification);
-
- /**
- * **MOVED TO IProxyListenerBase** - onProxyClosed() being called indicates that the app is no longer registered with SDL
- * All resources on SDL (addCommands and ChoiceSets) have been deleted and will have to be
- * recreated upon the next onReadyForInitialization() call-back.
- */
- //public void onProxyClosed(String info, Exception e);
-
- /**
- * **MOVED TO IProxyListenerBase** - onError() being called indicates that the proxy has experienced an unrecoverable error.
- * A new proxy object must be initiated to reestablish connection with SDL.
- *
- * @param info - Any info present about the error that occurred.
- * @param e - Any exception thrown by the error.
- */
- //public void onError(String info, Exception e);
-
- /**
- * **Deprecated** - onSdlInterfaceAvailable() being called indicates that the proxy now has access to SDL's HMI.
- * Monitor the onFocusChange call-back to determine which level of HMI is available to the proxy.
- *
- * @param isFirstAvailability - Indicates this is the first onSdlInterfaceAvailable in this lifecycle.
- */
- // HMI (Background, Limited, Full) from Unavailable = onSdlInterfaceAvailable(Boolean isFirstAvailability);
-
- /**
- * **Deprecated** - onSdlInterfaceUnavailable() being called indicates that the proxy does NOT have access to SDL's HIM.
- */
- // HMI None onSdlInterfaceUnavailable();
-
- /**
- * **Deprecated** - ALM HMI states converted back to HMI Levels
- *
- * HMI Full = onSdlInFocus(Boolean isFirstSdlInFocus);
- * HMI Limited = onSdlInFocusLimited();
- * HMI Background = onSdlLostFocus();
- */
-}
diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/interfaces/IProxyListenerBase.java b/android/sdl_android/src/main/java/com/smartdevicelink/proxy/interfaces/IProxyListenerBase.java deleted file mode 100644 index fc348faf5..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/interfaces/IProxyListenerBase.java +++ /dev/null @@ -1,386 +0,0 @@ -package com.smartdevicelink.proxy.interfaces;
-
-import com.smartdevicelink.proxy.callbacks.OnServiceEnded;
-import com.smartdevicelink.proxy.callbacks.OnServiceNACKed;
-import com.smartdevicelink.proxy.rpc.AddCommandResponse;
-import com.smartdevicelink.proxy.rpc.AddSubMenuResponse;
-import com.smartdevicelink.proxy.rpc.AlertManeuverResponse;
-import com.smartdevicelink.proxy.rpc.AlertResponse;
-import com.smartdevicelink.proxy.rpc.ButtonPressResponse;
-import com.smartdevicelink.proxy.rpc.ChangeRegistrationResponse;
-import com.smartdevicelink.proxy.rpc.CreateInteractionChoiceSetResponse;
-import com.smartdevicelink.proxy.rpc.DeleteCommandResponse;
-import com.smartdevicelink.proxy.rpc.DeleteFileResponse;
-import com.smartdevicelink.proxy.rpc.DeleteInteractionChoiceSetResponse;
-import com.smartdevicelink.proxy.rpc.DeleteSubMenuResponse;
-import com.smartdevicelink.proxy.rpc.DiagnosticMessageResponse;
-import com.smartdevicelink.proxy.rpc.DialNumberResponse;
-import com.smartdevicelink.proxy.rpc.EndAudioPassThruResponse;
-import com.smartdevicelink.proxy.rpc.GenericResponse;
-import com.smartdevicelink.proxy.rpc.GetAppServiceDataResponse;
-import com.smartdevicelink.proxy.rpc.GetCloudAppPropertiesResponse;
-import com.smartdevicelink.proxy.rpc.GetDTCsResponse;
-import com.smartdevicelink.proxy.rpc.GetFileResponse;
-import com.smartdevicelink.proxy.rpc.GetInteriorVehicleDataResponse;
-import com.smartdevicelink.proxy.rpc.GetSystemCapabilityResponse;
-import com.smartdevicelink.proxy.rpc.GetVehicleDataResponse;
-import com.smartdevicelink.proxy.rpc.GetWayPointsResponse;
-import com.smartdevicelink.proxy.rpc.ListFilesResponse;
-import com.smartdevicelink.proxy.rpc.OnAppServiceData;
-import com.smartdevicelink.proxy.rpc.OnAudioPassThru;
-import com.smartdevicelink.proxy.rpc.OnButtonEvent;
-import com.smartdevicelink.proxy.rpc.OnButtonPress;
-import com.smartdevicelink.proxy.rpc.OnCommand;
-import com.smartdevicelink.proxy.rpc.OnDriverDistraction;
-import com.smartdevicelink.proxy.rpc.OnHMIStatus;
-import com.smartdevicelink.proxy.rpc.OnHashChange;
-import com.smartdevicelink.proxy.rpc.OnInteriorVehicleData;
-import com.smartdevicelink.proxy.rpc.OnKeyboardInput;
-import com.smartdevicelink.proxy.rpc.OnLanguageChange;
-import com.smartdevicelink.proxy.rpc.OnLockScreenStatus;
-import com.smartdevicelink.proxy.rpc.OnPermissionsChange;
-import com.smartdevicelink.proxy.rpc.OnRCStatus;
-import com.smartdevicelink.proxy.rpc.OnStreamRPC;
-import com.smartdevicelink.proxy.rpc.OnSystemCapabilityUpdated;
-import com.smartdevicelink.proxy.rpc.OnSystemRequest;
-import com.smartdevicelink.proxy.rpc.OnTBTClientState;
-import com.smartdevicelink.proxy.rpc.OnTouchEvent;
-import com.smartdevicelink.proxy.rpc.OnVehicleData;
-import com.smartdevicelink.proxy.rpc.OnWayPointChange;
-import com.smartdevicelink.proxy.rpc.PerformAppServiceInteractionResponse;
-import com.smartdevicelink.proxy.rpc.PerformAudioPassThruResponse;
-import com.smartdevicelink.proxy.rpc.PerformInteractionResponse;
-import com.smartdevicelink.proxy.rpc.PublishAppServiceResponse;
-import com.smartdevicelink.proxy.rpc.PutFileResponse;
-import com.smartdevicelink.proxy.rpc.ReadDIDResponse;
-import com.smartdevicelink.proxy.rpc.ResetGlobalPropertiesResponse;
-import com.smartdevicelink.proxy.rpc.ScrollableMessageResponse;
-import com.smartdevicelink.proxy.rpc.SendHapticDataResponse;
-import com.smartdevicelink.proxy.rpc.SendLocationResponse;
-import com.smartdevicelink.proxy.rpc.SetAppIconResponse;
-import com.smartdevicelink.proxy.rpc.SetCloudAppPropertiesResponse;
-import com.smartdevicelink.proxy.rpc.SetDisplayLayoutResponse;
-import com.smartdevicelink.proxy.rpc.SetGlobalPropertiesResponse;
-import com.smartdevicelink.proxy.rpc.SetInteriorVehicleDataResponse;
-import com.smartdevicelink.proxy.rpc.SetMediaClockTimerResponse;
-import com.smartdevicelink.proxy.rpc.ShowConstantTbtResponse;
-import com.smartdevicelink.proxy.rpc.ShowResponse;
-import com.smartdevicelink.proxy.rpc.SliderResponse;
-import com.smartdevicelink.proxy.rpc.SpeakResponse;
-import com.smartdevicelink.proxy.rpc.StreamRPCResponse;
-import com.smartdevicelink.proxy.rpc.SubscribeButtonResponse;
-import com.smartdevicelink.proxy.rpc.SubscribeVehicleDataResponse;
-import com.smartdevicelink.proxy.rpc.SubscribeWayPointsResponse;
-import com.smartdevicelink.proxy.rpc.SystemRequestResponse;
-import com.smartdevicelink.proxy.rpc.UnsubscribeButtonResponse;
-import com.smartdevicelink.proxy.rpc.UnsubscribeVehicleDataResponse;
-import com.smartdevicelink.proxy.rpc.UnsubscribeWayPointsResponse;
-import com.smartdevicelink.proxy.rpc.UpdateTurnListResponse;
-import com.smartdevicelink.proxy.rpc.enums.SdlDisconnectedReason;
-
-
-public interface IProxyListenerBase {
-
- /**
- * onOnHMIStatus being called indicates that there has been an HMI Level change,
- * system context change or audio streaming state change.
- *
- * @param notification - Contains information about the HMI Level,
- * system context and audio streaming state.
- */
- public void onOnHMIStatus(OnHMIStatus notification);
-
- /**
- * onProxyClosed has different functionality for the different models.
- * In the non-ALM model this indicates that the proxy has experienced an unrecoverable error.
- * A new proxy object must be initiated to reestablish connection with SDL.
- * In the ALM model this indicates that the app is no longer registered with SDL
- * All resources on SDL (addCommands and ChoiceSets) have been deleted and will have to be
- * recreated upon the next onReadyForInitialization() call-back.
- *
- * @param info - Includes information about the reason the proxy has been closed.
- * @param e - The exception that occurred.
- */
- public void onProxyClosed(String info, Exception e, SdlDisconnectedReason reason);
-
- public void onServiceEnded(OnServiceEnded serviceEnded);
-
- public void onServiceNACKed(OnServiceNACKed serviceNACKed);
-
- public void onOnStreamRPC(OnStreamRPC notification);
-
- public void onStreamRPCResponse(StreamRPCResponse response);
-
- /**
- * onProxyError() being called indicates that the SDL Proxy experenced an error.
- *
- * @param info - Includes information about the Exception that occurred.
- * @param e - The exception that occurred.
- */
- public void onError(String info, Exception e);
-
- /**
- * onGenericResponse() being called indicates that SDL could not determine the
- * type of request it is responding to. This is usually result of an unknown RPC Request
- * being sent.
- *
- * @param response - Includes detailed information about the response.
- */
- public void onGenericResponse(GenericResponse response);
-
- /**
- * onOnCommand() being called indicates that the user selected a command on SDL.
- *
- * @param notification - Contains information about the command chosen.
- */
- public void onOnCommand(OnCommand notification);
-
- /**
- * onAddCommandResponse() being called indicates that SDL has responded to
- * a request to add a command.
- *
- * @param response - Contains information about the response sent from SDL.
- */
- public void onAddCommandResponse(AddCommandResponse response);
-
- /**
- * onAddSubMenuResponse() being called indicates that SDL has responded to
- * a request to add a command.
- *
- * @param response - Contains information about the response sent from SDL.
- */
- public void onAddSubMenuResponse(AddSubMenuResponse response);
-
- /**
- * onCreateInteractionChoiceSetResponse() being called indicates that SDL has
- * responded to a request to add an interactionChoiceSet.
- *
- * @param response - Contains information about the response sent from SDL.
- */
- public void onCreateInteractionChoiceSetResponse(CreateInteractionChoiceSetResponse response);
-
- /**
- * onAlertResponse being called indicates that SDL has
- * responded to a request to alert the user.
- *
- * @param response - Contains information about the response sent from SDL.
- */
- public void onAlertResponse(AlertResponse response);
-
- /**
- * onDeleteCommandResponse being called indicates that SDL has
- * responded to a request to delete a command.
- *
- * @param response - Contains information about the response sent from SDL.
- */
- public void onDeleteCommandResponse(DeleteCommandResponse response);
-
- /**
- * onDeleteCommandResponse being called indicates that SDL has
- * responded to a request to delete an interaction choice set.
- *
- * @param response - Contains information about the response sent from SDL.
- */
- public void onDeleteInteractionChoiceSetResponse(DeleteInteractionChoiceSetResponse response);
-
- /**
- * onDeleteCommandResponse being called indicates that SDL has
- * responded to a request to delete a submenu.
- *
- * @param response - Contains information about the response sent from SDL.
- */
- public void onDeleteSubMenuResponse(DeleteSubMenuResponse response);
-
- /**
- * onPerformInteractionResponse being called indicates that SDL has
- * responded to a request to perform an interaction.
- *
- * @param response - Contains information about the response sent from SDL.
- */
- public void onPerformInteractionResponse(PerformInteractionResponse response);
-
- /**
- * onResetGlobalPropertiesResponse being called indicates that SDL has
- * responded to a request to reset global properties.
- *
- * @param response - Contains information about the response sent from SDL.
- */
- public void onResetGlobalPropertiesResponse(ResetGlobalPropertiesResponse response);
-
- /**
- * onSetGlobalPropertiesResponse being called indicates that SDL has
- * responded to a request to set global properties.
- *
- * @param response - Contains information about the response sent from SDL.
- */
- public void onSetGlobalPropertiesResponse(SetGlobalPropertiesResponse response);
-
- /**
- * onSetMediaClockTimerResponse being called indicates that SDL has
- * responded to a request to set the media clock timer.
- *
- * @param response - Contains information about the response sent from SDL.
- */
- public void onSetMediaClockTimerResponse(SetMediaClockTimerResponse response);
-
- /**
- * onShowResponse being called indicates that SDL has
- * responded to a request to display information to the user.
- *
- * @param response - Contains information about the response sent from SDL.
- */
- public void onShowResponse(ShowResponse response);
-
- /**
- * onSpeakResponse being called indicates that SDL has
- * responded to a request to speak information to the user.
- *
- * @param response - Contains information about the response sent from SDL.
- */
- public void onSpeakResponse(SpeakResponse response);
-
- /**
- * onButtonEvent being called indicates that a button event has occurred.
- *
- * @param notification - Contains information about the notification sent from SDL.
- */
- public void onOnButtonEvent(OnButtonEvent notification);
-
- /**
- * onButtonPress being called indicates that SDL has a button has
- * been pressed by the user.
- *
- * @param notification - Contains information about the notification sent from SDL.
- */
- public void onOnButtonPress(OnButtonPress notification);
-
- /**
- * onSubscribeButtonResponse being called indicates that SDL has
- * responded to a request to subscribe to button events and button presses.
- *
- * @param response - Contains information about the response sent from SDL.
- */
- public void onSubscribeButtonResponse(SubscribeButtonResponse response);
-
- /**
- * onUnsubscribeButtonResponse being called indicates that SDL has
- * responded to a request to unsubscribe from button events and button presses.
- *
- * @param response - Contains information about the response sent from SDL.
- */
- public void onUnsubscribeButtonResponse(UnsubscribeButtonResponse response);
-
- /**
- * onOnPermissionsChange being called indicates that your app permissions have
- * changed due to a policy table change. This can mean your app has received additional
- * permissions OR lost permissions.
- *
- * @param notification - Contains information about the changed permissions.
- */
- public void onOnPermissionsChange(OnPermissionsChange notification);
-
- public void onSubscribeVehicleDataResponse(SubscribeVehicleDataResponse response);
-
- public void onUnsubscribeVehicleDataResponse(UnsubscribeVehicleDataResponse response);
-
- public void onGetVehicleDataResponse(GetVehicleDataResponse response);
-
- public void onOnVehicleData(OnVehicleData notification);
-
- public void onPerformAudioPassThruResponse(PerformAudioPassThruResponse response);
-
- public void onEndAudioPassThruResponse(EndAudioPassThruResponse response);
-
- public void onOnAudioPassThru(OnAudioPassThru notification);
-
- public void onPutFileResponse(PutFileResponse response);
-
- public void onDeleteFileResponse(DeleteFileResponse response);
-
- public void onListFilesResponse(ListFilesResponse response);
-
- public void onSetAppIconResponse(SetAppIconResponse response);
-
- public void onScrollableMessageResponse(ScrollableMessageResponse response);
-
- public void onChangeRegistrationResponse(ChangeRegistrationResponse response);
-
- public void onSetDisplayLayoutResponse(SetDisplayLayoutResponse response);
-
- public void onOnLanguageChange(OnLanguageChange notification);
-
- public void onOnHashChange(OnHashChange notification);
-
- public void onSliderResponse(SliderResponse response);
-
- public void onOnDriverDistraction(OnDriverDistraction notification);
-
- public void onOnTBTClientState(OnTBTClientState notification);
-
- public void onOnSystemRequest(OnSystemRequest notification);
-
- public void onSystemRequestResponse(SystemRequestResponse response);
-
- public void onOnKeyboardInput(OnKeyboardInput notification);
-
- public void onOnTouchEvent(OnTouchEvent notification);
-
- public void onDiagnosticMessageResponse(DiagnosticMessageResponse response);
-
- public void onReadDIDResponse(ReadDIDResponse response);
-
- public void onGetDTCsResponse(GetDTCsResponse response);
-
- public void onOnLockScreenNotification(OnLockScreenStatus notification);
-
- public void onDialNumberResponse(DialNumberResponse response);
-
- public void onSendLocationResponse(SendLocationResponse response);
-
- public void onShowConstantTbtResponse(ShowConstantTbtResponse response);
-
- public void onAlertManeuverResponse(AlertManeuverResponse response);
-
- public void onUpdateTurnListResponse(UpdateTurnListResponse response);
-
- public void onServiceDataACK(int dataSize);
-
- public void onGetWayPointsResponse(GetWayPointsResponse response);
-
- public void onSubscribeWayPointsResponse(SubscribeWayPointsResponse response);
-
- public void onUnsubscribeWayPointsResponse(UnsubscribeWayPointsResponse response);
-
- public void onOnWayPointChange(OnWayPointChange notification);
-
- public void onGetSystemCapabilityResponse(GetSystemCapabilityResponse response);
-
- public void onGetInteriorVehicleDataResponse(GetInteriorVehicleDataResponse response);
-
- public void onButtonPressResponse(ButtonPressResponse response);
-
- public void onSetInteriorVehicleDataResponse(SetInteriorVehicleDataResponse response);
-
- public void onOnInteriorVehicleData(OnInteriorVehicleData notification);
-
- public void onSendHapticDataResponse(SendHapticDataResponse response);
-
- public void onOnRCStatus(OnRCStatus notification);
-
- public void onSetCloudAppProperties(SetCloudAppPropertiesResponse response);
-
- public void onGetCloudAppProperties(GetCloudAppPropertiesResponse response);
-
- public void onPublishAppServiceResponse(PublishAppServiceResponse response);
-
- public void onGetAppServiceDataResponse(GetAppServiceDataResponse response);
-
- public void onGetFileResponse(GetFileResponse response);
-
- public void onPerformAppServiceInteractionResponse(PerformAppServiceInteractionResponse response);
-
- public void onOnAppServiceData(OnAppServiceData notification);
-
- public void onOnSystemCapabilityUpdated(OnSystemCapabilityUpdated notification);
-
-}
\ No newline at end of file diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/interfaces/IPutFileResponseListener.java b/android/sdl_android/src/main/java/com/smartdevicelink/proxy/interfaces/IPutFileResponseListener.java deleted file mode 100644 index 7929e86e6..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/interfaces/IPutFileResponseListener.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.smartdevicelink.proxy.interfaces; - -import com.smartdevicelink.proxy.rpc.PutFileResponse; - -public interface IPutFileResponseListener { - public void onPutFileResponse(PutFileResponse response); - - public void onPutFileStreamError(Exception e, String info); -} diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/interfaces/ISdl.java b/android/sdl_android/src/main/java/com/smartdevicelink/proxy/interfaces/ISdl.java deleted file mode 100644 index 9b55d4f17..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/interfaces/ISdl.java +++ /dev/null @@ -1,236 +0,0 @@ -package com.smartdevicelink.proxy.interfaces; - -import android.support.annotation.NonNull; - -import com.smartdevicelink.protocol.enums.FunctionID; -import com.smartdevicelink.protocol.enums.SessionType; -import com.smartdevicelink.proxy.RPCRequest; -import com.smartdevicelink.util.Version; -import com.smartdevicelink.proxy.rpc.SdlMsgVersion; -import com.smartdevicelink.proxy.rpc.enums.SystemCapabilityType; -import com.smartdevicelink.proxy.rpc.listeners.OnMultipleRequestListener; -import com.smartdevicelink.proxy.rpc.listeners.OnRPCListener; -import com.smartdevicelink.proxy.rpc.listeners.OnRPCNotificationListener; -import com.smartdevicelink.streaming.audio.AudioStreamingCodec; -import com.smartdevicelink.streaming.audio.AudioStreamingParams; -import com.smartdevicelink.streaming.video.VideoStreamingParameters; - -import java.util.List; - -/* - * Copyright (c) 2017 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. - */ -@SuppressWarnings("unused") -public interface ISdl { - - /** - * Starts the connection with the module - */ - void start(); - - /** - * Ends connection with the module - */ - void stop(); - - /** - * Method to check if the session is connected - * @return if there is a connected session - */ - boolean isConnected(); - - /** - * Add a service listener for a specific service type - * @param serviceType service type that the listener will be attached to - * @param sdlServiceListener listener for events that happen to the service - */ - void addServiceListener(SessionType serviceType, ISdlServiceListener sdlServiceListener); - - /** - * Remote a service listener for a specific service type - * @param serviceType service type that the listener was attached to - * @param sdlServiceListener service listener that was previously added for the service type - */ - void removeServiceListener(SessionType serviceType, ISdlServiceListener sdlServiceListener); - - /** - * Starts the video streaming service - * @param parameters desired video streaming params for this sevice to be started with - * @param encrypted flag to start this service with encryption or not - */ - void startVideoService(VideoStreamingParameters parameters, boolean encrypted); - - /** - * Stops the video service if open - */ - void stopVideoService(); - - /** - * Starts the video streaming service - * @param isEncrypted flag to start this service with encryption or not - * @param parameters desired video streaming params for this sevice to be started with - */ - IVideoStreamListener startVideoStream(boolean isEncrypted, VideoStreamingParameters parameters); - - /** - * Starts the Audio streaming service - * @param encrypted flag to start this service with encryption or not - */ - void startAudioService(boolean encrypted, AudioStreamingCodec codec, AudioStreamingParams params); - - /** - * Starts the Audio streaming service - * @param encrypted flag to start this service with encryption or not - */ - void startAudioService(boolean encrypted); - - /** - * Stops the audio service if open - */ - void stopAudioService(); - - /** - * Start Audio Stream and return IAudioStreamListener - * @param isEncrypted - * @param codec - * @param params - * @return IAudioStreamListener - */ - IAudioStreamListener startAudioStream(boolean isEncrypted, AudioStreamingCodec codec, AudioStreamingParams params); - - /** - * Pass an RPC message through the proxy to be sent to the connected module - * @param message RPCRequest that should be sent to the module - */ - @Deprecated - void sendRPCRequest(RPCRequest message); - - /** - * Pass an RPC message through the proxy to be sent to the connected module - * @param message RPCRequest that should be sent to the module - */ - void sendRPC(RPCRequest message); - - /** - * Pass a list of RPC requests through the proxy to be sent to core - * @param rpcs List of RPC requests - * @param listener OnMultipleRequestListener that is called between requests and after all are processed - */ - void sendRequests(List<? extends RPCRequest> rpcs, final OnMultipleRequestListener listener); - - /** - * Add an OnRPCNotificationListener for specified notification - * @param notificationId FunctionID of the notification that is to be listened for - * @param listener listener that should be added for the notification ID - */ - void addOnRPCNotificationListener(FunctionID notificationId, OnRPCNotificationListener listener); - - /** - * Removes an OnRPCNotificationListener for specified notification - * @param notificationId FunctionID of the notification that was to be listened for - * @param listener listener that was previously added for the notification ID - */ - boolean removeOnRPCNotificationListener(FunctionID notificationId, OnRPCNotificationListener listener); - - /** - * Add an OnRPCResponseListener for specified response - * @param responseId FunctionID of the response that is to be listened for - * @param listener listener that should be added for the response ID - */ - void addOnRPCListener(FunctionID responseId, OnRPCListener listener); - - /** - * Removes an OnRPCResponseListener for specified response - * @param responseId FunctionID of the response that was to be listened for - * @param listener listener that was previously added for the response ID - */ - boolean removeOnRPCListener(FunctionID responseId, OnRPCListener listener); - - /** - * Get SystemCapability Object - * @param systemCapabilityType - * @return Object - */ - Object getCapability(SystemCapabilityType systemCapabilityType); - - /** - * Get Capability - * @param systemCapabilityType - * @param scListener - */ - void getCapability(SystemCapabilityType systemCapabilityType, OnSystemCapabilityListener scListener); - - /** - * Check if capability is supported - * @param systemCapabilityType - * @return Boolean - */ - boolean isCapabilitySupported(SystemCapabilityType systemCapabilityType); - - /** - * Add a listener to be called whenever a new capability is retrieved - * @param systemCapabilityType Type of capability desired - * @param listener callback to execute upon retrieving capability - */ - void addOnSystemCapabilityListener(SystemCapabilityType systemCapabilityType, OnSystemCapabilityListener listener); - - /** - * Remove an OnSystemCapabilityListener that was previously added - * @param systemCapabilityType Type of capability - * @param listener the listener that should be removed - */ - boolean removeOnSystemCapabilityListener(SystemCapabilityType systemCapabilityType, OnSystemCapabilityListener listener); - - /** - * Check to see if a transport is available to start/use the supplied service. - * @param serviceType the session that should be checked for transport availability - * @return true if there is either a supported - * transport currently connected or a transport is - * available to connect with for the supplied service type. - * <br>false if there is no - * transport connected to support the service type in question and - * no possibility in the foreseeable future. - */ - boolean isTransportForServiceAvailable(SessionType serviceType); - - /** - * Get the RPC specification version currently being used for the SDL messages - * @return SdlMsgVersion the current RPC specification version - */ - @NonNull SdlMsgVersion getSdlMsgVersion(); - - /** - * Get the protocol version of this session - * @return byte value representing WiPro version - */ - @NonNull Version getProtocolVersion(); - -} diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/interfaces/ISdlServiceListener.java b/android/sdl_android/src/main/java/com/smartdevicelink/proxy/interfaces/ISdlServiceListener.java deleted file mode 100644 index db5179a73..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/interfaces/ISdlServiceListener.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.smartdevicelink.proxy.interfaces; - - -import com.smartdevicelink.SdlConnection.SdlSession; -import com.smartdevicelink.protocol.enums.SessionType; - -public interface ISdlServiceListener { - public void onServiceStarted(SdlSession session, SessionType type, boolean isEncrypted); - public void onServiceEnded(SdlSession session, SessionType type); - public void onServiceError(SdlSession session, SessionType type, String reason); -} diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/interfaces/IVideoStreamListener.java b/android/sdl_android/src/main/java/com/smartdevicelink/proxy/interfaces/IVideoStreamListener.java deleted file mode 100644 index f645b0d55..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/interfaces/IVideoStreamListener.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (c) 2017, Xevo 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 copyright holder 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.proxy.interfaces; - -import java.nio.ByteBuffer; - -/** - * A listener that receives video streaming data from app. - */ -public interface IVideoStreamListener { - - /** - * Sends a chunk of data which represents a frame to SDL Core. - * <p> - * The format of the chunk should align with MediaCodec's "Compressed Buffer" format, i.e. it - * should contain a single video frame, and it should start and end on frame boundaries. - * Please refer to https://developer.android.com/reference/android/media/MediaCodec.html - * Also, for H.264 codec case the stream must be in byte-stream format (also known as Annex-B - * format). This isn't explained in the document above, but MediaCodec does output in this - * format. - * <p> - * In short, you can just provide MediaCodec's data outputs to this method without tweaking - * any data. - * <p> - * Note: this method must not be called after SdlProxyBase.endVideoStream() is called. - * - * @param data Byte array containing a video frame - * @param offset Starting offset in 'data' - * @param length Length of the data - * @param presentationTimeUs Presentation timestamp (PTS) of this frame, in microseconds. - * It must be greater than the previous timestamp. - * Specify -1 if unknown. - * @throws ArrayIndexOutOfBoundsException When offset does not satisfy - * {@code 0 <= offset && offset <= data.length} - * or length does not satisfy - * {@code 0 < length && offset + length <= data.length} - */ - void sendFrame(byte[] data, int offset, int length, long presentationTimeUs) - throws ArrayIndexOutOfBoundsException; - - /** - * Sends chunks of data which represent a frame to SDL Core. - * <p> - * The format of the chunk should align with MediaCodec's "Compressed Buffer" format, i.e. it - * should contain a single video frame, and it should start and end on frame boundaries. - * Please refer to https://developer.android.com/reference/android/media/MediaCodec.html - * Also, for H.264 codec case the stream must be in byte-stream format (also known as Annex-B - * format). This isn't explained in the document above, but MediaCodec does output in this - * format. - * <p> - * In short, you can just provide MediaCodec's data outputs to this method without tweaking - * any data. - * <p> - * Note: this method must not be called after SdlProxyBase.endVideoStream() is called. - * - * @param data Data chunk to send. Its position will be updated upon return. - * @param presentationTimeUs Presentation timestamp (PTS) of this frame, in microseconds. - * It must be greater than the previous timestamp. - * Specify -1 if unknown. - */ - void sendFrame(ByteBuffer data, long presentationTimeUs); -} diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/interfaces/OnSystemCapabilityListener.java b/android/sdl_android/src/main/java/com/smartdevicelink/proxy/interfaces/OnSystemCapabilityListener.java deleted file mode 100644 index d6fb11b4d..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/proxy/interfaces/OnSystemCapabilityListener.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.smartdevicelink.proxy.interfaces; - -public interface OnSystemCapabilityListener { - void onCapabilityRetrieved(Object capability); - void onError(String info); -} diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/streaming/AbstractPacketizer.java b/android/sdl_android/src/main/java/com/smartdevicelink/streaming/AbstractPacketizer.java deleted file mode 100644 index 1a2c393cd..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/streaming/AbstractPacketizer.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.smartdevicelink.streaming;
-
-import java.io.IOException;
-import java.io.InputStream;
-
-import com.smartdevicelink.SdlConnection.SdlSession;
-import com.smartdevicelink.protocol.enums.SessionType;
-import com.smartdevicelink.proxy.RPCRequest;
-import com.smartdevicelink.util.Version;
-
-abstract public class AbstractPacketizer {
-
- protected IStreamListener _streamListener = null;
- protected byte _rpcSessionID = 0;
-
- protected SessionType _serviceType = null;
- protected SdlSession _session = null;
- protected InputStream is = null;
- protected int bufferSize;
- protected byte[] buffer;
- protected boolean upts = false;
- protected RPCRequest _request = null;
- protected Version _wiproVersion = new Version("1.0.0");
-
- //protected long ts = 0, intervalBetweenReports = 5000, delta = 0;
- protected long intervalBetweenReports = 5000, delta = 0;
-
- public AbstractPacketizer(IStreamListener streamListener, InputStream is, SessionType sType, byte rpcSessionID, SdlSession session) throws IOException, IllegalArgumentException {
- this._streamListener = streamListener;
- this.is = is;
- _rpcSessionID = rpcSessionID;
- _serviceType = sType;
- this._session = session;
- if (this._session != null) {
- bufferSize = this._session.getMtu();
- buffer = new byte[bufferSize];
- }else{
- throw new IllegalArgumentException("Session variable is null");
- }
- }
-
- @Deprecated
- public AbstractPacketizer(IStreamListener streamListener, InputStream is, RPCRequest request, SessionType sType, byte rpcSessionID, byte wiproVersion, SdlSession session) throws IOException, IllegalArgumentException {
- this._streamListener = streamListener;
- this.is = is;
- _rpcSessionID = rpcSessionID;
- _serviceType = sType;
- _request = request;
- _wiproVersion = new Version(wiproVersion+".0.0");
- this._session = session;
- if (this._session != null) {
- bufferSize = this._session.getMtu();
- buffer = new byte[bufferSize];
- }else{
- throw new IllegalArgumentException("Session variable is null");
- }
- }
-
- public AbstractPacketizer(IStreamListener streamListener, InputStream is, RPCRequest request, SessionType sType, byte rpcSessionID, Version protocolVersion, SdlSession session) throws IOException, IllegalArgumentException {
- this._streamListener = streamListener;
- this.is = is;
- _rpcSessionID = rpcSessionID;
- _serviceType = sType;
- _request = request;
- _wiproVersion = protocolVersion;
- this._session = session;
- if (this._session != null) {
- bufferSize = this._session.getMtu();
- buffer = new byte[bufferSize];
- }else{
- throw new IllegalArgumentException("Session variable is null");
- }
- }
-
- public abstract void start() throws IOException;
-
- public abstract void stop();
-
- public abstract void pause();
-
- public abstract void resume();
-}
\ No newline at end of file diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/streaming/IStreamListener.java b/android/sdl_android/src/main/java/com/smartdevicelink/streaming/IStreamListener.java deleted file mode 100644 index 2e19cf578..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/streaming/IStreamListener.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.smartdevicelink.streaming;
-
-import com.smartdevicelink.protocol.ProtocolMessage;
-
-public interface IStreamListener {
- void sendStreamPacket(ProtocolMessage pm);
-}
\ No newline at end of file diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/streaming/audio/AudioStreamingCodec.java b/android/sdl_android/src/main/java/com/smartdevicelink/streaming/audio/AudioStreamingCodec.java deleted file mode 100644 index bf69a792b..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/streaming/audio/AudioStreamingCodec.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2017, Xevo 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 copyright holder 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.streaming.audio; - -/** - * Enum for each type of audio streaming codec. - */ -public enum AudioStreamingCodec { - /** - * Linear-PCM without any compression. - */ - LPCM; - - public static AudioStreamingCodec valueForString(String value) { - try { - return valueOf(value); - } catch (Exception e) { - return null; - } - } -} diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/streaming/audio/AudioStreamingLPCMParams.java b/android/sdl_android/src/main/java/com/smartdevicelink/streaming/audio/AudioStreamingLPCMParams.java deleted file mode 100644 index bde6abc4c..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/streaming/audio/AudioStreamingLPCMParams.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (c) 2017, Xevo 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 copyright holder 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.streaming.audio; - -/** - * A struct to hold LPCM specific audio format information. - */ -public class AudioStreamingLPCMParams extends AudioStreamingParams { - /** - * Sample format of linear PCM data. - */ - public enum SampleFormat { - /** - * LPCM data is represented by 8-bit unsigned integers. Centerpoint is 128. - */ - LPCM_8BIT_UNSIGNED, - - /** - * LPCM data is represented by 16-bit signed integers, in little endian. - */ - LPCM_16BIT_SIGNED_LITTLE_ENDIAN, - } - - /** - * Sample format in which app will provide LPCM data to - * IAudioStreamListener.sendAudio() - * <p> - * This is reserved for future and not used right now. - */ - public SampleFormat sampleFormat; - - public AudioStreamingLPCMParams(SampleFormat sampleFormat, int samplingRate, int channels) { - super(samplingRate, channels); - this.sampleFormat = sampleFormat; - } -} diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/streaming/audio/AudioStreamingParams.java b/android/sdl_android/src/main/java/com/smartdevicelink/streaming/audio/AudioStreamingParams.java deleted file mode 100644 index fe0f7a981..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/streaming/audio/AudioStreamingParams.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) 2017, Xevo 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 copyright holder 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.streaming.audio; - -/** - * A struct to hold audio format information that are common to codecs. - */ -public class AudioStreamingParams { - /** - * Sampling rate in Hz, e.g. 44100 - * <p> - * This is reserved for future and not used right now. - */ - public int samplingRate; - - /** - * Number of channels in the audio stream - * <p> - * This is reserved for future and not used right now. - */ - public int channels; - - public AudioStreamingParams(int samplingRate, int channels) { - this.samplingRate = samplingRate; - this.channels = channels; - } -} diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/streaming/video/RTPH264Packetizer.java b/android/sdl_android/src/main/java/com/smartdevicelink/streaming/video/RTPH264Packetizer.java deleted file mode 100644 index b35fd61c4..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/streaming/video/RTPH264Packetizer.java +++ /dev/null @@ -1,503 +0,0 @@ -/* - * Copyright (c) 2017, Xevo 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 copyright holder 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.streaming.video; - -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.util.Random; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.LinkedBlockingQueue; - -import com.smartdevicelink.SdlConnection.SdlSession; -import com.smartdevicelink.protocol.ProtocolMessage; -import com.smartdevicelink.protocol.enums.SessionType; -import com.smartdevicelink.proxy.interfaces.IVideoStreamListener; -import com.smartdevicelink.streaming.AbstractPacketizer; -import com.smartdevicelink.streaming.IStreamListener; - -/* - * Note for testing. - * The RTP stream generated by this packetizer can be tested with GStreamer (1.4 or later). - * Assuming that "VideoStreamPort" is configured as 5050 in smartDeviceLink.ini, here is the - * GStreamer pipeline that receives the stream, decode it and render it: - * - * $ gst-launch-1.0 souphttpsrc location=http://127.0.0.1:5050 ! "application/x-rtp-stream" ! rtpstreamdepay ! "application/x-rtp,media=(string)video,clock-rate=90000,encoding-name=(string)H264" ! rtph264depay ! "video/x-h264, stream-format=(string)avc, alignment=(string)au" ! avdec_h264 ! autovideosink sync=false - */ - -/** - * This class receives H.264 byte stream (in Annex-B format), parses it, construct RTP packets - * from it based on RFC 6184, then frame the packets based on RFC 4571. - * The primary purpose of using RTP is to carry timestamp information along with the data. - * - * @author Sho Amano - */ -public class RTPH264Packetizer extends AbstractPacketizer implements IVideoStreamListener, Runnable { - - // Approximate size of data that mOutputQueue can hold in bytes. - // By adding a buffer, we accept underlying transport being stuck for a short time. By setting - // a limit of the buffer size, we avoid buffer overflows when underlying transport is too slow. - private static final int MAX_QUEUE_SIZE = 256 * 1024; - - private static final int FRAME_LENGTH_LEN = 2; - private static final int MAX_RTP_PACKET_SIZE = 65535; // because length field is two bytes (RFC 4571) - private static final int RTP_HEADER_LEN = 12; - private static final byte DEFAULT_RTP_PAYLOAD_TYPE = 96; - private static final int FU_INDICATOR_LEN = 1; - private static final int FU_HEADER_LEN = 1; - private static final byte TYPE_FU_A = 28; - - // To align with StreamPacketizer class - private final static int TLS_MAX_RECORD_SIZE = 16384; - private final static int TLS_RECORD_HEADER_SIZE = 5; - private final static int TLS_RECORD_MES_AUTH_CDE_SIZE = 32; - private final static int TLS_MAX_RECORD_PADDING_SIZE = 256; - - private final static int MAX_DATA_SIZE_FOR_ENCRYPTED_SERVICE = - TLS_MAX_RECORD_SIZE - TLS_RECORD_HEADER_SIZE - TLS_RECORD_MES_AUTH_CDE_SIZE- TLS_MAX_RECORD_PADDING_SIZE; - - private boolean mServiceProtected; - private Thread mThread; - private BlockingQueue<ByteBuffer> mOutputQueue; - private volatile boolean mPaused; - private boolean mWaitForIDR; - private NALUnitReader mNALUnitReader; - private byte mPayloadType = 0; - private int mSSRC = 0; - private char mSequenceNum = 0; - private int mInitialPTS = 0; - - /** - * Constructor - * - * @param streamListener The listener which this packetizer outputs SDL frames to - * @param serviceType The value of "Service Type" field in SDL frames - * @param sessionID The value of "Session ID" field in SDL frames - * @param session The SdlSession instance that this packetizer belongs to - */ - public RTPH264Packetizer(IStreamListener streamListener, - SessionType serviceType, byte sessionID, SdlSession session) throws IOException { - - super(streamListener, null, serviceType, sessionID, session); - - mServiceProtected = session.isServiceProtected(_serviceType); - - bufferSize = (int)this._session.getMtu(SessionType.NAV); - if (bufferSize == 0) { - // fail safe - bufferSize = MAX_DATA_SIZE_FOR_ENCRYPTED_SERVICE; - } - if (mServiceProtected && bufferSize > MAX_DATA_SIZE_FOR_ENCRYPTED_SERVICE) { - bufferSize = MAX_DATA_SIZE_FOR_ENCRYPTED_SERVICE; - } - - mOutputQueue = new LinkedBlockingQueue<ByteBuffer>(MAX_QUEUE_SIZE / bufferSize); - mNALUnitReader = new NALUnitReader(); - mPayloadType = DEFAULT_RTP_PAYLOAD_TYPE; - - Random r = new Random(); - mSSRC = r.nextInt(); - - // initial value of the sequence number and timestamp should be random ([5.1] in RFC3550) - mSequenceNum = (char)r.nextInt(65536); - mInitialPTS = r.nextInt(); - } - - /** - * Sets the Payload Type (PT) of RTP header field. - * - * Use this method if PT needs to be specified. The value should be between 0 and 127. - * Otherwise, a default value (96) is used. - * - * @param type A value indicating the Payload Type - */ - public void setPayloadType(byte type) { - if (type >= 0 && type <= 127) { - mPayloadType = type; - } else { - mPayloadType = DEFAULT_RTP_PAYLOAD_TYPE; - } - } - - /** - * Sets the SSRC of RTP header field. - * - * Use this method if SSRC needs to be specified. Otherwise, a random value is generated and - * used. - * - * @param ssrc An integer value representing SSRC - */ - public void setSSRC(int ssrc) { - mSSRC = ssrc; - } - - /** - * Starts this packetizer. - * - * It is recommended that the video encoder is started after the packetizer is started. - */ - @Override - public void start() throws IOException { - if (mThread != null) { - return; - } - - mThread = new Thread(this); - mThread.start(); - } - - /** - * Stops this packetizer. - * - * It is recommended that the video encoder is stopped prior to the packetizer. - */ - @Override - public void stop() { - if (mThread == null) { - return; - } - - mThread.interrupt(); - mThread = null; - - mPaused = false; - mWaitForIDR = false; - mOutputQueue.clear(); - } - - /** - * Pauses this packetizer. - * - * This pauses the packetizer but does not pause the video encoder. - */ - @Override - public void pause() { - mPaused = true; - } - - /** - * Resumes this packetizer. - */ - @Override - public void resume() { - mWaitForIDR = true; - mPaused = false; - } - - /** - * The thread routine. - */ - public void run() { - - while (mThread != null && !mThread.isInterrupted()) { - ByteBuffer frame; - try { - frame = mOutputQueue.take(); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - break; - } - - while (frame.hasRemaining()) { - int len = frame.remaining() > bufferSize ? bufferSize : frame.remaining(); - - ProtocolMessage pm = new ProtocolMessage(); - pm.setSessionID(_rpcSessionID); - pm.setSessionType(_serviceType); - pm.setFunctionID(0); - pm.setCorrID(0); - pm.setData(frame.array(), frame.arrayOffset() + frame.position(), len); - pm.setPayloadProtected(mServiceProtected); - - _streamListener.sendStreamPacket(pm); - - frame.position(frame.position() + len); - } - } - - // XXX: This is added to sync with StreamPacketizer. Actually it shouldn't be here since - // it's confusing that a packetizer takes care of End Service request. - if (_session != null) { - _session.endService(_serviceType, _rpcSessionID); - } - } - - /** - * Called by the app and encoder. - * - * @see com.smartdevicelink.proxy.interfaces.IVideoStreamListener#sendFrame(byte[], int, int, long) - */ - @Override - public void sendFrame(byte[] data, int offset, int length, long presentationTimeUs) - throws ArrayIndexOutOfBoundsException { - mNALUnitReader.init(data, offset, length); - onEncoderOutput(mNALUnitReader, presentationTimeUs); - } - - /** - * Called by the app and encoder. - * - * @see com.smartdevicelink.proxy.interfaces.IVideoStreamListener#sendFrame(ByteBuffer, long) - */ - @Override - public void sendFrame(ByteBuffer data, long presentationTimeUs) { - mNALUnitReader.init(data); - onEncoderOutput(mNALUnitReader, presentationTimeUs); - } - - private void onEncoderOutput(NALUnitReader nalUnitReader, long ptsInUs) { - if (mPaused) { - return; - } - - ByteBuffer nalUnit; - - while ((nalUnit = nalUnitReader.getNalUnit()) != null) { - if (mWaitForIDR) { - if (isIDR(nalUnit)) { - mWaitForIDR = false; - } else { - continue; - } - } - outputRTPFrames(nalUnit, ptsInUs, nalUnitReader.hasConsumedAll()); - } - } - - private boolean outputRTPFrames(ByteBuffer nalUnit, long ptsInUs, boolean isLast) { - if (RTP_HEADER_LEN + nalUnit.remaining() > MAX_RTP_PACKET_SIZE) { - // Split into multiple Fragmentation Units ([5.8] in RFC 6184) - byte firstByte = nalUnit.get(); - boolean firstFragment = true; - boolean lastFragment = false; - - while (nalUnit.remaining() > 0) { - int payloadLength = MAX_RTP_PACKET_SIZE - (RTP_HEADER_LEN + FU_INDICATOR_LEN + FU_HEADER_LEN); - if (nalUnit.remaining() <= payloadLength) { - payloadLength = nalUnit.remaining(); - lastFragment = true; - } - - ByteBuffer frame = allocateRTPFrame(FU_INDICATOR_LEN + FU_HEADER_LEN + payloadLength, - false, isLast, ptsInUs); - // FU indicator - frame.put((byte)((firstByte & 0xE0) | TYPE_FU_A)); - // FU header - frame.put((byte)((firstFragment ? 0x80 : lastFragment ? 0x40 : 0) | (firstByte & 0x1F))); - // FU payload - frame.put(nalUnit.array(), nalUnit.position(), payloadLength); - nalUnit.position(nalUnit.position() + payloadLength); - frame.flip(); - - try { - mOutputQueue.put(frame); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - return false; - } - - firstFragment = false; - } - } else { - // Use Single NAL Unit Packet ([5.6] in RFC 6184) - ByteBuffer frame = allocateRTPFrame(nalUnit.remaining(), false, isLast, ptsInUs); - frame.put(nalUnit); - frame.flip(); - - try { - mOutputQueue.put(frame); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - return false; - } - } - - return true; - } - - private ByteBuffer allocateRTPFrame(int rtpPayloadLen, - boolean hasPadding, boolean isLast, long ptsInUs) { - if (rtpPayloadLen <= 0) { - throw new IllegalArgumentException("Invalid rtpPayloadLen value: " + rtpPayloadLen); - } - if (ptsInUs < 0) { - throw new IllegalArgumentException("Invalid ptsInUs value: " + ptsInUs); - } - - int packetLength = RTP_HEADER_LEN + rtpPayloadLen; - if (packetLength > MAX_RTP_PACKET_SIZE) { - throw new IllegalArgumentException("Invalid rtpPayloadLen value: " + rtpPayloadLen); - } - int ptsIn90kHz = (int)(ptsInUs * 9 / 100) + mInitialPTS; - - ByteBuffer frame = ByteBuffer.allocate(FRAME_LENGTH_LEN + packetLength); - frame.order(ByteOrder.BIG_ENDIAN); - frame.putShort((short)packetLength); - - // Version = 2, Padding = hasPadding, Extension = 0, CSRC count = 0 - frame.put((byte)(0x80 | (hasPadding ? 0x20 : 0))) - // Marker = isLast, Payload type = mPayloadType - .put((byte)((isLast ? 0x80 : 0) | (mPayloadType & 0x7F))) - .putChar(mSequenceNum) - .putInt(ptsIn90kHz) - .putInt(mSSRC); - - if (frame.position() != FRAME_LENGTH_LEN + RTP_HEADER_LEN) { - throw new RuntimeException("Data size in ByteBuffer mismatch"); - } - - mSequenceNum++; - return frame; - } - - private static boolean isIDR(ByteBuffer nalUnit) { - if (nalUnit == null || !nalUnit.hasRemaining()) { - throw new IllegalArgumentException("Invalid nalUnit arg"); - } - - byte nalUnitType = (byte)(nalUnit.get(nalUnit.position()) & 0x1F); - return nalUnitType == 5; - } - - - private static int SKIP_TABLE[] = new int[256]; - static { - // Sunday's quick search algorithm is used to find the start code. - // Prepare the table (SKIP_TABLE[0] = 2, SKIP_TABLE[1] = 1 and other elements will be 4). - byte[] NAL_UNIT_START_CODE = {0, 0, 1}; - int searchStringLen = NAL_UNIT_START_CODE.length; - for (int i = 0; i < SKIP_TABLE.length; i++) { - SKIP_TABLE[i] = searchStringLen + 1; - } - for (int i = 0; i < searchStringLen; i++) { - SKIP_TABLE[NAL_UNIT_START_CODE[i] & 0xFF] = searchStringLen - i; - } - } - - private class NALUnitReader { - private byte[] mData; - private int mOffset; - private int mLimit; - - NALUnitReader() { - } - - void init(byte[] data) { - mData = data; - mOffset = 0; - mLimit = data.length; - } - - void init(byte[] data, int offset, int length) throws ArrayIndexOutOfBoundsException { - if (offset < 0 || offset > data.length || length <= 0 || offset + length > data.length) { - throw new ArrayIndexOutOfBoundsException(); - } - mData = data; - mOffset = offset; - mLimit = offset + length; - } - - void init(ByteBuffer data) { - if (data == null || data.remaining() == 0) { - mData = null; - mOffset = 0; - mLimit = 0; - return; - } - - if (data.hasArray()) { - mData = data.array(); - mOffset = data.position() + data.arrayOffset(); - mLimit = mOffset + data.remaining(); - - // mark the buffer as consumed - data.position(data.position() + data.remaining()); - } else { - byte[] buffer = new byte[data.remaining()]; - data.get(buffer); - - mData = buffer; - mOffset = 0; - mLimit = buffer.length; - } - } - - ByteBuffer getNalUnit() { - if (hasConsumedAll()) { - return null; - } - - int pos = mOffset; - int start = -1; - - while (mLimit - pos >= 3) { - if (mData[pos] == 0 && mData[pos+1] == 0 && mData[pos+2] == 1) { - if (start != -1) { - // We've found a start code, a NAL unit and then another start code. - mOffset = pos; - // remove 0x00s in front of the start code - while (pos > start && mData[pos-1] == 0) { - pos--; - } - if (pos > start) { - return ByteBuffer.wrap(mData, start, pos - start); - } else { - // No NAL unit between two start codes?! Forget it and search for - // another start code. - pos = mOffset; - } - } - // This is the first start code. - pos += 3; - start = pos; - } else { - try { - pos += SKIP_TABLE[mData[pos+3] & 0xFF]; - } catch (ArrayIndexOutOfBoundsException e) { - break; - } - } - } - - mOffset = mLimit; - if (start != -1 && mLimit > start) { - // We've found a start code and then reached to the end of array. - return ByteBuffer.wrap(mData, start, mLimit - start); - } - // A start code was not found - return null; - } - - boolean hasConsumedAll() { - return (mData == null) || (mLimit - mOffset < 4); - } - } -} diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/streaming/video/VideoStreamingParameters.java b/android/sdl_android/src/main/java/com/smartdevicelink/streaming/video/VideoStreamingParameters.java deleted file mode 100644 index 121176cc2..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/streaming/video/VideoStreamingParameters.java +++ /dev/null @@ -1,218 +0,0 @@ -/* - * Copyright (c) 2017 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.streaming.video; - -import android.util.DisplayMetrics; - -import com.smartdevicelink.proxy.rpc.ImageResolution; -import com.smartdevicelink.proxy.rpc.VideoStreamingCapability; -import com.smartdevicelink.proxy.rpc.VideoStreamingFormat; -import com.smartdevicelink.proxy.rpc.enums.VideoStreamingCodec; -import com.smartdevicelink.proxy.rpc.enums.VideoStreamingProtocol; - -import java.util.List; - -@SuppressWarnings("FieldCanBeLocal") -public class VideoStreamingParameters { - private final VideoStreamingProtocol DEFAULT_PROTOCOL = VideoStreamingProtocol.RAW; - private final VideoStreamingCodec DEFAULT_CODEC = VideoStreamingCodec.H264; - private final int DEFAULT_WIDTH = 1024; - private final int DEFAULT_HEIGHT = 576; - private final int DEFAULT_DENSITY = DisplayMetrics.DENSITY_HIGH; - private final int DEFAULT_FRAMERATE = 30; - private final int DEFAULT_BITRATE = 512000; - private final int DEFAULT_INTERVAL = 5; - - - private int displayDensity; - private int frameRate; - private int bitrate; - private int interval; - private ImageResolution resolution; - private VideoStreamingFormat format; - - public VideoStreamingParameters(){ - displayDensity = DEFAULT_DENSITY; - frameRate = DEFAULT_FRAMERATE; - bitrate = DEFAULT_BITRATE; - interval = DEFAULT_INTERVAL; - resolution = new ImageResolution(); - resolution.setResolutionWidth(DEFAULT_WIDTH); - resolution.setResolutionHeight(DEFAULT_HEIGHT); - format = new VideoStreamingFormat(); - format.setProtocol(DEFAULT_PROTOCOL); - format.setCodec(DEFAULT_CODEC); - } - - public VideoStreamingParameters(int displayDensity, int frameRate, int bitrate, int interval, - ImageResolution resolution, VideoStreamingFormat format){ - this.displayDensity = displayDensity; - this.frameRate = frameRate; - this.bitrate = bitrate; - this.interval = interval; - this.resolution = resolution; - this.format = format; - } - - /** - * Will only copy values that are not null or are greater than 0 - * @param params VideoStreamingParameters that should be copied into this new instants - */ - @SuppressWarnings("unused") - public VideoStreamingParameters(VideoStreamingParameters params){ - update(params); - } - - /** - * Will only copy values that are not null or are greater than 0 - * @param params VideoStreamingParameters that should be copied into this new instants - */ - public void update(VideoStreamingParameters params){ - if(params!=null) { - if (params.displayDensity > 0) { - this.displayDensity = params.displayDensity; - } - if (params.frameRate > 0) { - this.frameRate = params.frameRate; - } - if (params.bitrate > 0) { - this.bitrate = params.bitrate; - } - if (params.interval > 0) { - this.interval = params.interval; - } - if (params.resolution != null) { - if (params.resolution.getResolutionHeight() != null && params.resolution.getResolutionHeight() > 0) { - this.resolution.setResolutionHeight(params.resolution.getResolutionHeight()); - } - if (params.resolution.getResolutionWidth() != null && params.resolution.getResolutionWidth() > 0) { - this.resolution.setResolutionWidth(params.resolution.getResolutionWidth()); - } - } - if (params.format != null) { - this.format = params.format; - } - } - } - - /** - * Update the values contained in the capability that should have been returned through the SystemCapabilityManager. - * This update will use the most preferred streaming format from the module. - * @param capability the video streaming capability returned from the SystemCapabilityManager - * @see com.smartdevicelink.proxy.SystemCapabilityManager - * @see VideoStreamingCapability - */ - public void update(VideoStreamingCapability capability){ - if(capability.getMaxBitrate()!=null){ this.bitrate = capability.getMaxBitrate() * 1000; } // NOTE: the unit of maxBitrate in getSystemCapability is kbps. - ImageResolution resolution = capability.getPreferredResolution(); - if(resolution!=null){ - if(resolution.getResolutionHeight()!=null && resolution.getResolutionHeight() > 0){ this.resolution.setResolutionHeight(resolution.getResolutionHeight()); } - if(resolution.getResolutionWidth()!=null && resolution.getResolutionWidth() > 0){ this.resolution.setResolutionWidth(resolution.getResolutionWidth()); } - } - List<VideoStreamingFormat> formats = capability.getSupportedFormats(); - if(formats != null && formats.size()>0){ - this.format = formats.get(0); - } - - } - - @SuppressWarnings("unused") - public void setDisplayDensity(int displayDensity) { - this.displayDensity = displayDensity; - } - - public int getDisplayDensity() { - return displayDensity; - } - - public void setFrameRate(int frameRate) { - this.frameRate = frameRate; - } - - public int getFrameRate() { - return frameRate; - } - - public void setBitrate(int bitrate) { - this.bitrate = bitrate; - } - - public int getBitrate() { - return bitrate; - } - - public void setInterval(int interval) { - this.interval = interval; - } - - public int getInterval() { - return interval; - } - - public void setFormat(VideoStreamingFormat format){ - this.format = format; - } - - public VideoStreamingFormat getFormat(){ - return format; - } - - public void setResolution(ImageResolution resolution){ - this.resolution = resolution; - } - - public ImageResolution getResolution() { - return resolution; - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("VideoStreamingParams - format: {"); - builder.append(format.toString()); - builder.append("}, resolution: {"); - builder.append(resolution.getResolutionHeight()); - builder.append(" , "); - builder.append(resolution.getResolutionWidth()); - builder.append("}, frame rate {"); - builder.append(frameRate); - builder.append("}, displayDensity{ "); - builder.append(displayDensity); - builder.append("}, bitrate"); - builder.append(bitrate); - builder.append("}, IFrame interval{ "); - builder.append(interval); - builder.append("}"); - return builder.toString(); - } -} diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/trace/DiagLevel.java b/android/sdl_android/src/main/java/com/smartdevicelink/trace/DiagLevel.java deleted file mode 100644 index 26dfdebff..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/trace/DiagLevel.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.smartdevicelink.trace;
-
-import com.smartdevicelink.trace.enums.DetailLevel;
-import com.smartdevicelink.trace.enums.Mod;
-
-
-public class DiagLevel {
-
- static private DetailLevel[] levels;
-
- static { // this is a static c-tor!!
- levels = new DetailLevel[Mod.values().length];
- setAllLevels(DetailLevel.OFF);
- }
-
- public static void setAllLevels(DetailLevel thisDetail) {
- if (thisDetail != null) {
- for (int i = 0; i < levels.length; i++) {
- levels[i] = thisDetail; //
- }
- }
- }
-
- public static void setLevel(Mod thisMod, DetailLevel thisDetail) {
- if (thisMod != null && thisDetail != null) {
- levels[thisMod.ordinal()] = thisDetail;
- }
- }
-
- public static DetailLevel getLevel(Mod thisMod) {
- if (thisMod != null) {
- return levels[thisMod.ordinal()];
- }
- return null;
- }
-
- public static boolean isValidDetailLevel(String dtString) {
- // Assume false
- Boolean isValid = false;
-
- if (dtString != null) {
- if (dtString.equalsIgnoreCase("verbose"))
- isValid = true;
- else if (dtString.equalsIgnoreCase("terse"))
- isValid = true;
- else if (dtString.equalsIgnoreCase("off"))
- isValid = true;
- }
-
- return isValid;
- }
-
- public static DetailLevel toDetailLevel(String dtString) {
- DetailLevel dt = DetailLevel.OFF;
- if (dtString.equalsIgnoreCase("verbose"))
- dt = DetailLevel.VERBOSE;
- else if (dtString.equalsIgnoreCase("terse"))
- dt = DetailLevel.TERSE;
- return dt;
- }
-}
diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/trace/ISTListener.java b/android/sdl_android/src/main/java/com/smartdevicelink/trace/ISTListener.java deleted file mode 100644 index 3af7d5020..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/trace/ISTListener.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.smartdevicelink.trace;
-
-public interface ISTListener {
- void logXmlMsg(String msg, String token);
-} // end-interface
\ No newline at end of file diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/trace/Mime.java b/android/sdl_android/src/main/java/com/smartdevicelink/trace/Mime.java deleted file mode 100644 index 799ac98f4..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/trace/Mime.java +++ /dev/null @@ -1,100 +0,0 @@ -package com.smartdevicelink.trace;
-
-// Borrowed from Dave Boll's infamous SdlLinkRelay.java
-
-public class Mime {
-
- private static final String BASE_64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
-
- /**
- * @param str A String to encode into base64 String.
- * @return Base64 encoded String or a null String if input is null.
- */
- public static String base64Encode(String str) {
- if(str == null){
- return null;
- }
-
- String b64String = "";
- try {
- byte[] strBytes = str.getBytes("US-ASCII");
- b64String = base64Encode(strBytes);
- } catch (Exception ex) {
- // Don't care?
- }
- return b64String;
- }
-
- /**
- * @param bytesToEncode A byte array to encode into base64 String.
- * @return Base64 encoded String or a null String if input array is null.
- */
- public static String base64Encode(byte bytesToEncode[]) {
- if(bytesToEncode != null){
- return base64Encode(bytesToEncode, 0, bytesToEncode.length);
- }
- return null;
- }
-
- /**
- * @param bytesToEncode A byte array to encode into base64 String.
- * @param offset Offset to begin at
- * @param length Length to read
- * @return Base64 encoded String or a null String if input array is null or the input range is out of bounds.
- */
- public static String base64Encode(byte bytesToEncode[], int offset, int length) {
- if (bytesToEncode == null || bytesToEncode.length < length || bytesToEncode.length < offset + length) {
- return null;
- }
-
- StringBuilder sb = new StringBuilder();
-
- int idxin = 0;
- int b64idx = 0;
-
- for (idxin = offset; idxin < offset + length; idxin++) {
- switch ((idxin - offset) % 3) {
- case 0:
- b64idx = (bytesToEncode[idxin] >> 2) & 0x3f;
- break;
- case 1:
- b64idx = (bytesToEncode[idxin] >> 4) & 0x0f;
- b64idx |= ((bytesToEncode[idxin - 1] << 4) & 0x30);
- break;
- case 2:
- b64idx = (bytesToEncode[idxin] >> 6) & 0x03;
- b64idx |= ((bytesToEncode[idxin - 1] << 2) & 0x3c);
- sb.append(getBase64Char(b64idx));
- b64idx = bytesToEncode[idxin] & 0x3f;
- break;
- }
- sb.append(getBase64Char(b64idx));
- }
-
- switch ((idxin - offset) % 3) {
- case 0:
- break;
- case 1:
- b64idx = (bytesToEncode[idxin - 1] << 4) & 0x30;
- sb.append(getBase64Char(b64idx));
- sb.append("==");
- break;
- case 2:
- b64idx = ((bytesToEncode[idxin - 1] << 2) & 0x3c);
- sb.append(getBase64Char(b64idx));
- sb.append('=');
- break;
- }
-
- return sb.toString();
-
- }
-
- private static char getBase64Char(int b64idx){
- if(b64idx >= 0 && b64idx < BASE_64_CHARS.length()) {
- return BASE_64_CHARS.charAt(b64idx);
- }else{
- return 0x20;
- }
- }
-}
\ No newline at end of file diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/trace/OpenRPCMessage.java b/android/sdl_android/src/main/java/com/smartdevicelink/trace/OpenRPCMessage.java deleted file mode 100644 index 35a8de749..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/trace/OpenRPCMessage.java +++ /dev/null @@ -1,86 +0,0 @@ -package com.smartdevicelink.trace;
-
-import java.util.Hashtable;
-import java.util.Iterator;
-import java.util.List;
-
-import com.smartdevicelink.proxy.RPCMessage;
-import com.smartdevicelink.proxy.RPCStruct;
-
-class OpenRPCMessage extends RPCMessage {
- private OpenRPCMessage() {super("");}
- public OpenRPCMessage(RPCMessage rpcm) {
- super(rpcm);
- } // end-method
-
- public OpenRPCMessage(RPCStruct rpcs) {
- super(rpcs);
- } // end-method
-
- public String msgDump() {
- StringBuilder pd = new StringBuilder();
-
- pd.append(this.getFunctionName() + " " + this.getMessageType());
-
- msgDump(pd);
-
- return pd.toString();
- } // end-method
-
- public void msgDump(StringBuilder pd) {
- pd.append("[");
-
- dumpParams(parameters, pd);
-
- pd.append("]");
-
- return;
- } // end-method
-
- private void dumpParams(Hashtable<String, Object> ht, StringBuilder pd) {
- Iterator<String> keySet = ht.keySet().iterator();
- Object obj = null;
- String key = "";
- boolean isFirstParam = true;
-
- while (keySet.hasNext()) {
- key = (String)keySet.next();
- obj = ht.get(key);
- if (isFirstParam) {
- isFirstParam = false;
- } else {
- pd.append(", ");
- } // end-if
-
- dumpParamNode(key, obj, pd);
-
- } // end-while
- } // end-method
-
- @SuppressWarnings("unchecked")
- private void dumpParamNode(String key, Object obj, StringBuilder pd) {
-
- if (obj instanceof Hashtable) {
- pd.append("[");
- dumpParams((Hashtable<String, Object>)obj, pd);
- pd.append("]");
- } else if (obj instanceof RPCStruct) {
- pd.append("[");
- OpenRPCMessage orpcm = new OpenRPCMessage((RPCStruct)obj);
- orpcm.msgDump(pd);
- pd.append("]");
- } else if (obj instanceof List) {
- pd.append("[");
- List<?> list = (List<?>)obj;
- for (int idx=0;idx < list.size();idx++) {
- if (idx > 0) {
- pd.append(", ");
- }
- dumpParamNode(key, list.get(idx), pd);
- } // end-for
- pd.append("]");
- } else {
- pd.append("\"" + key + "\" = \"" + obj.toString() + "\"");
- }
- } // end-method
-} // end-class OpenRPCMessage
diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/trace/enums/DetailLevel.java b/android/sdl_android/src/main/java/com/smartdevicelink/trace/enums/DetailLevel.java deleted file mode 100644 index bd213679d..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/trace/enums/DetailLevel.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.smartdevicelink.trace.enums;
-
-
-public enum DetailLevel {
- OFF,
- TERSE,
- VERBOSE;
-
- public static DetailLevel valueForString(String value) {
- try{
- return valueOf(value);
- }catch(Exception e){
- return null;
- }
- }
-}
diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/trace/enums/InterfaceActivityDirection.java b/android/sdl_android/src/main/java/com/smartdevicelink/trace/enums/InterfaceActivityDirection.java deleted file mode 100644 index 0865d2e32..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/trace/enums/InterfaceActivityDirection.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.smartdevicelink.trace.enums;
-
-public enum InterfaceActivityDirection {
- Transmit,
- Receive,
- None;
-
- public static InterfaceActivityDirection valueForString(String value) {
- try{
- return valueOf(value);
- }catch(Exception e){
- return null;
- }
- }
-}
\ No newline at end of file diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/trace/enums/Mod.java b/android/sdl_android/src/main/java/com/smartdevicelink/trace/enums/Mod.java deleted file mode 100644 index b363473b2..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/trace/enums/Mod.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.smartdevicelink.trace.enums;
-
-public enum Mod {
- tran,
- proto,
- mar,
- rpc,
- app,
- proxy;
-
- public static Mod valueForString(String value) {
- try{
- return valueOf(value);
- }catch(Exception e){
- return null;
- }
- }
-};
\ No newline at end of file diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/transport/BaseTransportConfig.java b/android/sdl_android/src/main/java/com/smartdevicelink/transport/BaseTransportConfig.java deleted file mode 100644 index 4b7fe79be..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/transport/BaseTransportConfig.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.smartdevicelink.transport;
-
-import com.smartdevicelink.transport.enums.TransportType;
-
-/**
- * Defines base abstract class for transport configurations.
- */
-public abstract class BaseTransportConfig {
-
- protected boolean shareConnection = true;
- protected int iHeartBeatTimeout = Integer.MAX_VALUE;
- /**
- * Gets transport type for this transport configuration.
- *
- * @return One of {@link TransportType} enumeration values that represents type of this transport configuration.
- */
- public abstract TransportType getTransportType();
-
- /**
- * Indicate whether the application want to share connection with others.
- *
- * @return
- */
- public boolean shareConnection() {
- return shareConnection;
- }
-
- public int getHeartBeatTimeout() {
- return iHeartBeatTimeout;
- }
-
- public void setHeartBeatTimeout(int iTimeout) {
- iHeartBeatTimeout = iTimeout;
- }
-}
diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/transport/ITransportListener.java b/android/sdl_android/src/main/java/com/smartdevicelink/transport/ITransportListener.java deleted file mode 100644 index b4c4a9b33..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/transport/ITransportListener.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.smartdevicelink.transport;
-
-import com.smartdevicelink.protocol.SdlPacket;
-
-public interface ITransportListener {
- // Called to indicate and deliver a packet received from transport
- void onTransportPacketReceived(SdlPacket packet);
-
- // Called to indicate that transport connection was established
- void onTransportConnected();
-
- // Called to indicate that transport was disconnected (by either side)
- void onTransportDisconnected(String info);
-
- // Called to indicate that some error occurred on the transport
- void onTransportError(String info, Exception e);
-} // end-interface
\ No newline at end of file diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/transport/SdlPsm.java b/android/sdl_android/src/main/java/com/smartdevicelink/transport/SdlPsm.java deleted file mode 100644 index f5b650722..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/transport/SdlPsm.java +++ /dev/null @@ -1,261 +0,0 @@ -package com.smartdevicelink.transport; - -import com.smartdevicelink.protocol.SdlPacket; - -import static com.smartdevicelink.protocol.SdlProtocol.V1_HEADER_SIZE; -import static com.smartdevicelink.protocol.SdlProtocol.V1_V2_MTU_SIZE; - - -public class SdlPsm{ - //private static final String TAG = "Sdl PSM"; - //Each state represents the byte that should be incomming - - public static final int START_STATE = 0x0; - public static final int SERVICE_TYPE_STATE = 0x02; - public static final int CONTROL_FRAME_INFO_STATE = 0x03; - public static final int SESSION_ID_STATE = 0x04; - public static final int DATA_SIZE_1_STATE = 0x05; - public static final int DATA_SIZE_2_STATE = 0x06; - public static final int DATA_SIZE_3_STATE = 0x07; - public static final int DATA_SIZE_4_STATE = 0x08; - public static final int MESSAGE_1_STATE = 0x09; - public static final int MESSAGE_2_STATE = 0x0A; - public static final int MESSAGE_3_STATE = 0x0B; - public static final int MESSAGE_4_STATE = 0x0C; - public static final int DATA_PUMP_STATE = 0x0D; - public static final int FINISHED_STATE = 0xFF; - public static final int ERROR_STATE = -1; - - - private static final byte FIRST_FRAME_DATA_SIZE = 0x08; - - private static final int VERSION_MASK = 0xF0; //4 highest bits - private static final int COMPRESSION_MASK = 0x08; //4th lowest bit - private static final int FRAME_TYPE_MASK = 0x07; //3 lowest bits - - - - int state ; - - int version; - boolean compression; - int frameType; - int serviceType; - int controlFrameInfo; - int sessionId; - int dumpSize, dataLength; - int messageId = 0; - - byte[] payload; - - public SdlPsm(){ - reset(); - } - - public boolean handleByte(byte data) { - //Log.trace(TAG, data + " = incomming"); - state = transitionOnInput(data,state); - - if(state==ERROR_STATE){ - return false; - } - return true; - } - - private int transitionOnInput(byte rawByte, int state){ - switch(state){ - case START_STATE: - version = (rawByte&(byte)VERSION_MASK)>>4; - //Log.trace(TAG, "Version: " + version); - if(version==0){ //It should never be 0 - return ERROR_STATE; - } - compression = (1 == ((rawByte&(byte)COMPRESSION_MASK)>>3)); - - - frameType = rawByte&(byte)FRAME_TYPE_MASK; - //Log.trace(TAG, rawByte + " = Frame Type: " + frameType); - - if((version < 1 || version > 5) //These are known versions supported by this library. - && frameType!=SdlPacket.FRAME_TYPE_CONTROL){ - return ERROR_STATE; - } - - if(frameType<SdlPacket.FRAME_TYPE_CONTROL || frameType > SdlPacket.FRAME_TYPE_CONSECUTIVE){ - return ERROR_STATE; - } - - return SERVICE_TYPE_STATE; - - case SERVICE_TYPE_STATE: - serviceType = (int)(rawByte&0xFF); - return CONTROL_FRAME_INFO_STATE; - - case CONTROL_FRAME_INFO_STATE: - controlFrameInfo = (int)(rawByte&0xFF); - //Log.trace(TAG,"Frame Info: " + controlFrameInfo); - switch(frameType){ - case SdlPacket.FRAME_TYPE_CONTROL: - /*if(frameInfo<FRAME_INFO_HEART_BEAT - || (frameInfo>FRAME_INFO_END_SERVICE_ACK - && (frameInfo!=FRAME_INFO_SERVICE_DATA_ACK || frameInfo!=FRAME_INFO_HEART_BEAT_ACK))){ - return ERROR_STATE; - }*/ //Although some bits are reserved...whatever - break; - case SdlPacket.FRAME_TYPE_SINGLE: //Fall through since they are both the same - case SdlPacket.FRAME_TYPE_FIRST: - if(controlFrameInfo!=0x00){ - return ERROR_STATE; - } - break; - case SdlPacket.FRAME_TYPE_CONSECUTIVE: - //It might be a good idea to check packet sequence numbers here - break; - - default: - return ERROR_STATE; - } - return SESSION_ID_STATE; - - case SESSION_ID_STATE: - sessionId = (int)(rawByte&0xFF); - return DATA_SIZE_1_STATE; - - case DATA_SIZE_1_STATE: - //First data size byte - //Log.d(TAG, "Data byte 1: " + rawByte); - dataLength += ((int)(rawByte& 0xFF))<<24; //3 bytes x 8 bits - //Log.d(TAG, "Data Size 1 : " + dataLength); - return DATA_SIZE_2_STATE; - - case DATA_SIZE_2_STATE: - //Log.d(TAG, "Data byte 2: " + rawByte); - dataLength += ((int)(rawByte& 0xFF))<<16; //2 bytes x 8 bits - //Log.d(TAG, "Data Size 2 : " + dataLength); - return DATA_SIZE_3_STATE; - - case DATA_SIZE_3_STATE: - //Log.d(TAG, "Data byte 3: " + rawByte); - dataLength += ((int)(rawByte& 0xFF))<<8; //1 byte x 8 bits - //Log.d(TAG, "Data Size 3 : " + dataLength); - return DATA_SIZE_4_STATE; - - case DATA_SIZE_4_STATE: - //Log.d(TAG, "Data byte 4: " + rawByte); - dataLength+=((int)rawByte) & 0xFF; - //Log.trace(TAG, "Data Size: " + dataLength); - //We should have data length now for the pump state - switch(frameType){ //If all is correct we should break out of this switch statement - case SdlPacket.FRAME_TYPE_SINGLE: - case SdlPacket.FRAME_TYPE_CONSECUTIVE: - break; - case SdlPacket.FRAME_TYPE_CONTROL: - //Ok, well here's some interesting bit of knowledge. Because the start session request is from the phone with no knowledge of version it sends out - //a v1 packet. THEREFORE there is no message id field. **** Now you know and knowing is half the battle **** - if(version==1 && controlFrameInfo == SdlPacket.FRAME_INFO_START_SERVICE){ - if(dataLength==0){ - return FINISHED_STATE; //We are done if we don't have any payload - } - if(dataLength <= V1_V2_MTU_SIZE - V1_HEADER_SIZE){ // sizes from protocol/WiProProtocol.java - payload = new byte[dataLength]; - }else{ - return ERROR_STATE; - } - dumpSize = dataLength; - return DATA_PUMP_STATE; - } - break; - - case SdlPacket.FRAME_TYPE_FIRST: - if(dataLength==FIRST_FRAME_DATA_SIZE){ - break; - } - default: - return ERROR_STATE; - } - if(version==1){ //Version 1 packets will not have message id's - if(dataLength == 0){ - return FINISHED_STATE; //We are done if we don't have any payload - } - if(dataLength <= V1_V2_MTU_SIZE - V1_HEADER_SIZE){ // sizes from protocol/WiProProtocol.java - payload = new byte[dataLength]; - }else{ - return ERROR_STATE; - } - dumpSize = dataLength; - return DATA_PUMP_STATE; - }else{ - return MESSAGE_1_STATE; - } - - case MESSAGE_1_STATE: - messageId += ((int)(rawByte& 0xFF))<<24; //3 bytes x 8 bits - return MESSAGE_2_STATE; - - case MESSAGE_2_STATE: - messageId += ((int)(rawByte& 0xFF))<<16; //2 bytes x 8 bits - return MESSAGE_3_STATE; - - case MESSAGE_3_STATE: - messageId += ((int)(rawByte& 0xFF))<<8; //1 byte x 8 bits - return MESSAGE_4_STATE; - - case MESSAGE_4_STATE: - messageId+=((int)rawByte) & 0xFF; - - if(dataLength==0){ - return FINISHED_STATE; //We are done if we don't have any payload - } - try{ - payload = new byte[dataLength]; - }catch(OutOfMemoryError oom){ - return ERROR_STATE; - } - dumpSize = dataLength; - return DATA_PUMP_STATE; - - case DATA_PUMP_STATE: - payload[dataLength-dumpSize] = rawByte; - dumpSize--; - //Do we have any more bytes to read in? - if(dumpSize>0){ - return DATA_PUMP_STATE; - } - else if(dumpSize==0){ - return FINISHED_STATE; - }else{ - return ERROR_STATE; - } - case FINISHED_STATE: //We shouldn't be here...Should have been reset - default: - return ERROR_STATE; - - } - - } - - public SdlPacket getFormedPacket(){ - if(state==FINISHED_STATE){ - //Log.trace(TAG, "Finished packet."); - return new SdlPacket(version, compression, frameType, - serviceType, controlFrameInfo, sessionId, - dataLength, messageId, payload); - }else{ - return null; - } - } - - public int getState() { - return state; - } - - public void reset() { - version = 0; - state = START_STATE; - messageId = 0; - dataLength = 0; - frameType = 0x00; //Set it to null - payload = null; - } - -} diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/transport/SdlTransport.java b/android/sdl_android/src/main/java/com/smartdevicelink/transport/SdlTransport.java deleted file mode 100644 index 27c87bcef..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/transport/SdlTransport.java +++ /dev/null @@ -1,122 +0,0 @@ -package com.smartdevicelink.transport;
-
-import com.smartdevicelink.exception.SdlException;
-import com.smartdevicelink.protocol.SdlPacket;
-import com.smartdevicelink.trace.SdlTrace;
-import com.smartdevicelink.trace.enums.InterfaceActivityDirection;
-import com.smartdevicelink.transport.enums.TransportType;
-import com.smartdevicelink.util.DebugTool;
-
-public abstract class SdlTransport {
- private static final String SDL_LIB_TRACE_KEY = "42baba60-eb57-11df-98cf-0800200c9a66";
-
- private final static String FailurePropagating_Msg = "Failure propagating ";
- private Boolean isConnected = false;
-
- private String _sendLockObj = "lock";
-
-
- // Get status of transport connection
- public Boolean getIsConnected() {
- return isConnected;
- }
-
- //protected SdlTransport(String endpointName, String param2, ITransportListener transportListener)
- protected SdlTransport(ITransportListener transportListener) {
- if (transportListener == null) {
- throw new IllegalArgumentException("Provided transport listener interface reference is null");
- } // end-if
- _transportListener = transportListener;
- } // end-method
-
- // This method is called by the subclass to indicate that data has arrived from
- // the transport.
- protected void handleReceivedPacket(SdlPacket packet) {
- try {
- // Trace received data
- if (packet!=null) {
- // Send transport data to the siphon server
- //FIXME SiphonServer.sendBytesFromSDL(receivedBytes, 0, receivedBytesLength);
- //SdlTrace.logTransportEvent("", null, InterfaceActivityDirection.Receive, receivedBytes, receivedBytesLength, SDL_LIB_TRACE_KEY);
-
- _transportListener.onTransportPacketReceived(packet);
- } // end-if
- } catch (Exception excp) {
- DebugTool.logError(FailurePropagating_Msg + "handleBytesFromTransport: " + excp.toString(), excp);
- handleTransportError(FailurePropagating_Msg, excp);
- } // end-catch
- } // end-method
-
- // This method must be implemented by transport subclass, and is called by this
- // base class to actually send an array of bytes out over the transport. This
- // method is meant to only be callable within the class hierarchy.
- protected abstract boolean sendBytesOverTransport(SdlPacket packet);
-
- // This method is called by whomever has reference to transport to have bytes
- // sent out over transport.
- /* public boolean sendBytes(byte[] message) {
- return sendBytes(message, 0, message.length);
- }*/ // end-method
-
- // This method is called by whomever has reference to transport to have bytes
- // sent out over transport.
- public boolean sendBytes(SdlPacket packet) {
- boolean bytesWereSent = false;
- synchronized (_sendLockObj) {
- bytesWereSent = sendBytesOverTransport(packet);//message, offset, length);
- } // end-lock
- // Send transport data to the siphon server
- //FIXME SiphonServer.sendBytesFromAPP(message, offset, length);
-
- //FIXME SdlTrace.logTransportEvent("", null, InterfaceActivityDirection.Transmit, message, offset, length, SDL_LIB_TRACE_KEY);
- return bytesWereSent;
- } // end-method
-
- private ITransportListener _transportListener = null;
-
- // This method is called by the subclass to indicate that transport connection
- // has been established.
- protected void handleTransportConnected() {
- isConnected = true;
- try {
- SdlTrace.logTransportEvent("Transport.connected", null, InterfaceActivityDirection.Receive, null, 0, SDL_LIB_TRACE_KEY);
- _transportListener.onTransportConnected();
- } catch (Exception excp) {
- DebugTool.logError(FailurePropagating_Msg + "onTransportConnected: " + excp.toString(), excp);
- handleTransportError(FailurePropagating_Msg + "onTransportConnected", excp);
- } // end-catch
- } // end-method
-
- // This method is called by the subclass to indicate that transport disconnection
- // has occurred.
- protected void handleTransportDisconnected(final String info) {
- isConnected = false;
-
- try {
- SdlTrace.logTransportEvent("Transport.disconnect: " + info, null, InterfaceActivityDirection.Transmit, null, 0, SDL_LIB_TRACE_KEY);
- _transportListener.onTransportDisconnected(info);
- } catch (Exception excp) {
- DebugTool.logError(FailurePropagating_Msg + "onTransportDisconnected: " + excp.toString(), excp);
- } // end-catch
- } // end-method
-
- // This method is called by the subclass to indicate a transport error has occurred.
- protected void handleTransportError(final String message, final Exception ex) {
- isConnected = false;
- _transportListener.onTransportError(message, ex);
- }
-
- public abstract void openConnection() throws SdlException;
- public abstract void disconnect();
-
- /**
- * Abstract method which should be implemented by subclasses in order to return actual type of the transport.
- *
- * @return One of {@link TransportType} enumeration values.
- *
- * @see TransportType
- */
- public abstract TransportType getTransportType();
-
- public abstract String getBroadcastComment();
-} // end-class
diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/transport/SiphonServer.java b/android/sdl_android/src/main/java/com/smartdevicelink/transport/SiphonServer.java deleted file mode 100644 index ab8a8a7bd..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/transport/SiphonServer.java +++ /dev/null @@ -1,384 +0,0 @@ -package com.smartdevicelink.transport;
-
-import java.io.IOException;
-import java.io.OutputStream;
-import java.io.UnsupportedEncodingException;
-import java.net.BindException;
-import java.net.ServerSocket;
-import java.net.Socket;
-
-import com.smartdevicelink.util.*;
-
-public class SiphonServer {
- // Prohibit use of no-arg ctor
- private SiphonServer() {}
-
- enum SiphonDataType {
- fromSdl,
- fromApp,
- appLog,
- formattedTrace,
- baselineTimeStamp,
- traceSettings
- }
-
- // Boolean to enable/disable the siphon
- private static Boolean m_siphonEnabled = false;
-
- // Boolean to determine if the siphon has been initialized
- private static Boolean m_siphonInitialized = false;
- private static Boolean m_foundOpenSocket = false;
- private static Socket m_siphonSocket = null;
- private static Object m_siphonLock = new Object();
- private static ServerSocket m_listeningSocket = null;
- private static short m_listenPort = -1;
- private static OutputStream m_siphonSocketOutputStream = null;
- private static SiphonServerThread m_siphonClientThread = null;
-
- // Initial timestamp in MS
- private static long m_startTimeStamp = 0;
-
- // SDL Trace Message Version
- private static byte m_sdlTraceMsgVersionNumber = 1;
-
- // Max number of ports to attempt a connection on
- private final static Integer MAX_NUMBER_OF_PORT_ATTEMPTS = 20;
-
- // Starting port for future port attempts
- private final static short FIRST_PORT_TO_ATTEMPT_CONNECTION = 7474;
-
- // Boolean to determine if formatted trace is being sent
- private static Boolean m_sendingFormattedTrace = false;
-
- public static short enableSiphonServer() {
- m_siphonEnabled = true;
- SiphonServer.init();
- return m_listenPort;
- }
-
- public static Boolean getSiphonEnabledStatus() {
- return m_siphonEnabled;
- }
-
- public static short disableSiphonServer() {
- if (!m_siphonEnabled) {
- m_listenPort = -1;
- } else {
- m_siphonEnabled = false;
- }
-
- m_siphonInitialized = false;
-
- try {
- SiphonServer.closeServer();
- } catch (IOException e) {
- e.printStackTrace();
- }
-
- return m_listenPort;
- }
-
- public static boolean init() {
- // Only initialize if the siphon has not been initialized previously
-
- // Check here to be lean. If true, no need to sdlhronize
- if (m_siphonInitialized) {
- return true;
- }
-
- synchronized (m_siphonLock) {
- // To prevent a race condition, re-check m_siphonInitialized inside of sdlhronize block
- if (!m_siphonInitialized) {
- if (m_siphonClientThread == null) {
- // Set current time stamp
- m_startTimeStamp = System.currentTimeMillis();
-
- // Start Siphon Thread
- m_siphonClientThread = new SiphonServerThread();
- m_siphonClientThread.setName("Siphon");
- m_siphonClientThread.setDaemon(true);
- m_foundOpenSocket = m_siphonClientThread.findOpenSocket(FIRST_PORT_TO_ATTEMPT_CONNECTION);
- m_siphonClientThread.start();
-
- m_siphonInitialized = true;
- } // end-if
- } // end-lock
- }
-
- return m_siphonInitialized;
- } // end-method
-
- public static void closeServer() throws IOException {
-
- if (m_siphonClientThread != null) {
- m_siphonClientThread.halt();
- m_siphonClientThread = null;
- }
-
- if (m_listeningSocket != null) {
- m_listeningSocket.close();
- m_listeningSocket = null;
- }
-
- if (m_siphonSocket != null) {
- m_siphonSocket.close();
- m_siphonSocket = null;
- }
-
- if (m_siphonSocketOutputStream != null) {
- m_siphonSocketOutputStream.close();
- m_siphonSocketOutputStream = null;
- }
- }
-
- public static Boolean sendBytesFromAPP(byte[] msgBytes, int offset, int length) {
-
- if (m_sendingFormattedTrace) {
- return false;
- }
-
- return sendSiphonData(SiphonDataType.fromApp, msgBytes, offset, length);
- } // end-method
-
- public static Boolean sendBytesFromSDL(byte[] msgBytes, int offset, int length) {
-
- if (m_sendingFormattedTrace) {
- return false;
- }
-
- return sendSiphonData(SiphonDataType.fromSdl, msgBytes, offset, length);
- } // end-method
-
- public static Boolean sendSiphonLogData(String message) {
-
- if (m_sendingFormattedTrace) {
- return false;
- }
-
- if (message == null || message.length() == 0) {
- return false;
- }
-
- byte messageBytes[] = null;
- int messageLength = 0;
-
- try {
- messageBytes = message.getBytes("UTF-8");
- } catch (UnsupportedEncodingException e) {
- return false;
- }
-
- messageLength = messageBytes.length;
- return sendSiphonData(SiphonDataType.appLog, messageBytes, 0, messageLength);
-
- }
-
- public static Boolean sendFormattedTraceMessage(String message) {
-
- if (message == null || message.length() == 0) {
- return false;
- }
-
- byte messageBytes[] = null;
- int messageLength = 0;
-
- try {
- messageBytes = message.getBytes("UTF-8");
- } catch (UnsupportedEncodingException e) {
- return false;
- }
-
- messageLength = messageBytes.length;
- if (sendSiphonData(SiphonDataType.formattedTrace, messageBytes, 0, messageLength)) {
- m_sendingFormattedTrace = true;
- return true;
- } else {
- return false;
- }
- }
-
- private static Boolean sendSiphonData(SiphonDataType direction, byte[] msgBytes, int offset, int length) {
- byte siphonDataTypeIndicator = 0x00;
-
- long currentDateTime = System.currentTimeMillis();
- Integer deltaTimeMills = null;
-
- deltaTimeMills = (int)(currentDateTime - m_startTimeStamp);
-
- switch(direction) {
- case fromSdl:
- siphonDataTypeIndicator = 0x00;
- break;
- case fromApp:
- siphonDataTypeIndicator = 0x01;
- break;
- case appLog:
- siphonDataTypeIndicator = 0x02;
- break;
- case formattedTrace:
- siphonDataTypeIndicator = 0x03;
- break;
- case baselineTimeStamp:
- siphonDataTypeIndicator = 0x04;
- break;
- case traceSettings:
- siphonDataTypeIndicator = 0x05;
- break;
- default:
- siphonDataTypeIndicator = 0x00;
- break;
- }
-
- // Set high bit to indicate new format
- siphonDataTypeIndicator = (byte)((byte)0x80 | siphonDataTypeIndicator);
-
- return sendDataToSiphonSocket(siphonDataTypeIndicator, deltaTimeMills, msgBytes, offset, length);
- }
-
- private synchronized static Boolean sendDataToSiphonSocket(byte directionIndicator, Integer timeStamp,
- byte[] msgBytes, int offset, int length) {
- if (!m_siphonEnabled) {
- return false;
- }
-
- if (msgBytes == null || length == 0) {
- return false;
- }
-
- OutputStream siphonOutputStream = null;
-
- synchronized (m_siphonLock) {
- siphonOutputStream = m_siphonSocketOutputStream;
- } // end-lock
-
- if (siphonOutputStream == null) {
- return false;
- }
-
- try {
- // blobSize = length(of message) + 1(size of direction indicator)
- // + 1 (size of msgVersionNumber) + 4 (size of timeStamp)
- int blobSize = length + 1 + 1 + 4;
-
- siphonOutputStream.write(BitConverter.intToByteArray(blobSize));
- siphonOutputStream.write(new byte[] {directionIndicator});
- siphonOutputStream.write(new byte[] {m_sdlTraceMsgVersionNumber});
- siphonOutputStream.write(intToByteArray(timeStamp));
- siphonOutputStream.write(msgBytes, offset, length);
- } catch (Exception ex) {
- return false;
- } // end-catch
-
- return true;
- } // end-method
-
- private static class SiphonServerThread extends Thread {
-
- private Boolean isHalted = false;
- short listenPort;
-
- public void halt() {
- isHalted = true;
- }
-
- private boolean findOpenSocket(short port) {
- // Accept incoming sihpon connection from trace utility.
- Boolean foundOpenPort = false;
- listenPort = port;
-
- // Listen to accept incoming connection from SDL
- while (!foundOpenPort) {
- try {
- m_listeningSocket = new ServerSocket(listenPort);
- foundOpenPort = true;
- m_listenPort = listenPort;
- } catch (BindException ex) {
- listenPort++;
- if(listenPort > port + MAX_NUMBER_OF_PORT_ATTEMPTS) {
- return false;
- }
- } catch (IOException e) {
- return false;
- }
- }
-
- return foundOpenPort;
- }
-
- private void startServerOnPort() throws IOException {
- Socket newSocket = null;
-
- // Wait for a connection
- newSocket = m_listeningSocket.accept();
-
- // If isHalted after accept() delay, return
- if (isHalted) {
- return;
- }
-
- synchronized (m_siphonLock) {
- // Reset siphonSocketOutputStream
- if (m_siphonSocketOutputStream != null) {
- try {
- m_siphonSocketOutputStream.close();
- } catch (IOException e) {
- // Do nothing
- }
- m_siphonSocketOutputStream = null;
- }
-
- // Reset siphonSocket
- if (m_siphonSocket != null) {
- try {
- m_siphonSocket.close();
- } catch (IOException e) {
- // Do nothing
- }
- m_siphonSocket = null;
- }
-
- // Store the new socket
- m_siphonSocket = newSocket;
-
- // Set Socket Options
- m_siphonSocket.setKeepAlive(true);
-
- // Get the output stream of the connection
- m_siphonSocketOutputStream = m_siphonSocket.getOutputStream();
-
- // Output version number to the Siphon upon connection (version number prepending to logInfo)
- DebugTool.logInfo("Siphon connected.");
- } // end-lock
- } // end-method
-
- @Override
- public void run() {
- try {
- if (m_foundOpenSocket){
- while (!isHalted) {
- startServerOnPort();
- }
- }
- } catch (Exception ex) {
- // Do nothing
- } finally {
- if (m_listeningSocket != null) {
- try {
- m_listeningSocket.close();
- } catch (IOException e) {
- // Do nothing
- }
- m_listeningSocket = null;
- }
- }
- }
- }
-
- private static final byte[] intToByteArray(int value) {
- return new byte[] {
- (byte)(value >>> 24),
- (byte)(value >>> 16),
- (byte)(value >>> 8),
- (byte)value};
- }
-} // end-class
\ No newline at end of file diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/transport/TransportConstants.java b/android/sdl_android/src/main/java/com/smartdevicelink/transport/TransportConstants.java deleted file mode 100644 index a66651502..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/transport/TransportConstants.java +++ /dev/null @@ -1,263 +0,0 @@ -package com.smartdevicelink.transport; - - -/** - * These constants are shared between the router service and the SDL base service. - * They are defined as strings/actions/values that both of them can understand. - * Attempting to use standard HTTP error codes as definitions. - * @author Joey Grover - * - */ -public class TransportConstants { - public static final String START_ROUTER_SERVICE_ACTION ="sdl.router.startservice"; - public static final String ROUTER_SERVICE_ACTION = "com.smartdevicelink.router.service"; - public static final String FOREGROUND_EXTRA = "foreground"; - - public static final String BIND_LOCATION_PACKAGE_NAME_EXTRA = "BIND_LOCATION_PACKAGE_NAME_EXTRA"; - public static final String BIND_LOCATION_CLASS_NAME_EXTRA = "BIND_LOCATION_CLASS_NAME_EXTRA"; - - public static final String ALT_TRANSPORT_RECEIVER = "com.sdl.android.alttransport"; - public static final String ALT_TRANSPORT_CONNECTION_STATUS_EXTRA = "connection_status"; - public static final int ALT_TRANSPORT_DISCONNECTED = 0; - public static final int ALT_TRANSPORT_CONNECTED = 1; - public static final String ALT_TRANSPORT_READ = "read";//Read from the alt transport, goes to the app - public static final String ALT_TRANSPORT_WRITE = "write";//Write to the alt transport, comes from the app - public static final String ALT_TRANSPORT_ADDRESS_EXTRA = "altTransportAddress"; - - public static final String START_ROUTER_SERVICE_SDL_ENABLED_EXTRA = "sdl_enabled"; - public static final String START_ROUTER_SERVICE_SDL_ENABLED_APP_PACKAGE = "package_name"; - public static final String START_ROUTER_SERVICE_SDL_ENABLED_CMP_NAME = "component_name"; - public static final String START_ROUTER_SERVICE_TRANSPORT_CONNECTED = "transport_connected"; //Extra for the transport that just connected - public static final String START_ROUTER_SERVICE_SDL_ENABLED_PING = "ping"; - @Deprecated - public static final String FORCE_TRANSPORT_CONNECTED = "force_connect"; //This is legacy, do not refactor this. - public static final String ROUTER_SERVICE_VALIDATED = "router_service_validated"; - - @Deprecated - public static final String REPLY_TO_INTENT_EXTRA = "ReplyAddress"; - public static final String CONNECT_AS_CLIENT_BOOLEAN_EXTRA = "connectAsClient"; - public static final String PACKAGE_NAME_STRING = "package.name"; - public static final String APP_ID_EXTRA = "app.id";//Sent as a Long. This is no longer used - public static final String APP_ID_EXTRA_STRING = "app.id.string"; - public static final String ROUTER_MESSAGING_VERSION = "router.messaging.version"; - - public static final String SESSION_ID_EXTRA = "session.id"; - - public static final String ENABLE_LEGACY_MODE_EXTRA = "ENABLE_LEGACY_MODE_EXTRA"; - - @Deprecated - public static final String HARDWARE_DISCONNECTED = "hardware.disconect"; - public static final String TRANSPORT_DISCONNECTED = "transport.disconect"; - public static final String HARDWARE_CONNECTED = "hardware.connected"; - public static final String CURRENT_HARDWARE_CONNECTED = "current.hardware.connected"; - - public static final String SEND_PACKET_TO_APP_LOCATION_EXTRA_NAME = "senderintent"; - public static final String SEND_PACKET_TO_ROUTER_LOCATION_EXTRA_NAME = "routerintent"; - - - public static final String BIND_REQUEST_TYPE_CLIENT = "BIND_REQUEST_TYPE_CLIENT"; - public static final String BIND_REQUEST_TYPE_ALT_TRANSPORT = "BIND_REQUEST_TYPE_ALT_TRANSPORT"; - public static final String BIND_REQUEST_TYPE_STATUS = "BIND_REQUEST_TYPE_STATUS"; - public static final String BIND_REQUEST_TYPE_USB_PROVIDER = "BIND_REQUEST_TYPE_USB_PROVIDER"; - - - public static final String PING_ROUTER_SERVICE_EXTRA = "ping.router.service"; - - public static final String SDL_NOTIFICATION_CHANNEL_ID = "sdl_notification_channel"; - public static final String SDL_NOTIFICATION_CHANNEL_NAME = "SmartDeviceLink"; - - - - - /** - * This class houses all important router service versions - */ - public class RouterServiceVersions{ - /** - * This version of the router service is when app IDs went from Longs to Strings - */ - public static final int APPID_STRING = 4; - } - - - /* - * Alt transport - * - */ - - /** - * This will be the response when a hardware connect event comes through from an alt transport. - * This is because it only makes sense to register an alt transport when a connection is established with that - * transport, not waiting for one. - */ - public static final int ROUTER_REGISTER_ALT_TRANSPORT_RESPONSE = 0x02; - public static final int ROUTER_REGISTER_ALT_TRANSPORT_RESPONSE_SUCESS = 0x00; - /** - * There is already another alt transport connected, so we are unable to register this one - */ - public static final int ROUTER_REGISTER_ALT_TRANSPORT_ALREADY_CONNECTED = 0x01; - - /** - * This means the router service is shutting down for some reason. Most likely - */ - public static final int ROUTER_SHUTTING_DOWN_NOTIFICATION = 0x0F; - - /** - * There is a newer service to start up, so this one is shutting down - */ - public static final int ROUTER_SHUTTING_DOWN_REASON_NEWER_SERVICE = 0x00; - - /* - * Router to Client binding service - * - */ - - //WHATS - /** - * Command to the service to register a client, receiving callbacks - * from the service. The Message's replyTo field must be a Messenger of - * the client where callbacks should be sent. - */ - public static final int ROUTER_REGISTER_CLIENT = 0x01; - /** - * This response message will contain if the registration request was successful or not. If not, the reason will be - * great or equal to 1 and be descriptive of why it was denied. - */ - public static final int ROUTER_REGISTER_CLIENT_RESPONSE = 0x02; - //Response arguments - public static final int REGISTRATION_RESPONSE_SUCESS = 0x00; - public static final int REGISTRATION_RESPONSE_DENIED_AUTHENTICATION_FAILED = 0x01; - public static final int REGISTRATION_RESPONSE_DENIED_NO_CONNECTION = 0x02; - public static final int REGISTRATION_RESPONSE_DENIED_APP_ID_NOT_INCLUDED = 0x03; - public static final int REGISTRATION_RESPONSE_DENIED_LEGACY_MODE_ENABLED = 0x04; - public static final int REGISTRATION_RESPONSE_DENIED_UNKNOWN = 0xFF; - - /** - * Command to the service to unregister a client, to stop receiving callbacks - * from the service. The Message's replyTo field must be a Messenger of - * the client as previously given with MSG_REGISTER_CLIENT. Also include the app id as arg1. - */ - public static final int ROUTER_UNREGISTER_CLIENT = 0x03; - public static final int ROUTER_UNREGISTER_CLIENT_RESPONSE = 0x04; - //Response arguments - public static final int UNREGISTRATION_RESPONSE_SUCESS = 0x00; - public static final int UNREGISTRATION_RESPONSE_FAILED_APP_ID_NOT_FOUND = 0x01; - - - /** - * what message type to notify apps of a hardware connection event. The connection event will be placed in the bundle - * attached to the message - */ - public static final int HARDWARE_CONNECTION_EVENT = 0x05; - public static final int HARDWARE_CONNECTION_EVENT_CONNECTED = 0x10; - public static final int HARDWARE_CONNECTION_EVENT_DISCONNECTED = 0x30; - - - public static final int ROUTER_REQUEST_BT_CLIENT_CONNECT = 0x10; - public static final int ROUTER_REQUEST_BT_CLIENT_CONNECT_RESPONSE = 0x11; - - /** - * This provides the app with an ability to request another session within the router service. - * A replyTo must be provided or else there won't be a response - */ - public static final int ROUTER_REQUEST_NEW_SESSION = 0x12; - //Request arguments - //See TRANSPORT_TYPE & TRANSPORT_ADDRESS - - - public static final int ROUTER_REQUEST_NEW_SESSION_RESPONSE = 0x13; - //Response arguments - public static final int ROUTER_REQUEST_NEW_SESSION_RESPONSE_SUCESS = 0x00; - public static final int ROUTER_REQUEST_NEW_SESSION_RESPONSE_FAILED_APP_NOT_FOUND = 0x01; - public static final int ROUTER_REQUEST_NEW_SESSION_RESPONSE_FAILED_APP_ID_NOT_INCL = 0x02; - - /** - * This provides the app with an ability to request another session within the router service. - * A replyTo must be provided or else there won't be a response - */ - public static final int ROUTER_REMOVE_SESSION = 0x14; - public static final int ROUTER_REMOVE_SESSION_RESPONSE = 0x15; - //Response arguments - public static final int ROUTER_REMOVE_SESSION_RESPONSE_SUCESS = 0x00; - public static final int ROUTER_REMOVE_SESSION_RESPONSE_FAILED_APP_NOT_FOUND = 0x01; - public static final int ROUTER_REMOVE_SESSION_RESPONSE_FAILED_APP_ID_NOT_INCL = 0x02; - public static final int ROUTER_REMOVE_SESSION_RESPONSE_FAILED_SESSION_NOT_FOUND = 0x03; - public static final int ROUTER_REMOVE_SESSION_RESPONSE_FAILED_SESSION_ID_NOT_INCL = 0x04; - /** - * Command to have router service to send a packet - */ - public static final int ROUTER_SEND_PACKET = 0x20; - - //response - /** - * Router has received a packet and sent it to the client - */ - public static final int ROUTER_RECEIVED_PACKET = 0x26; - //response - - /** - * Command to tell router service details of secondary transport - */ - public static final int ROUTER_REQUEST_SECONDARY_TRANSPORT_CONNECTION = 0x30; - - //BUNDLE EXTRAS - - public static final String FORMED_PACKET_EXTRA_NAME = "packet"; - - public static final String BYTES_TO_SEND_EXTRA_NAME = "bytes"; - public static final String BYTES_TO_SEND_EXTRA_OFFSET = "offset"; - public static final String BYTES_TO_SEND_EXTRA_COUNT = "count"; - public static final String BYTES_TO_SEND_FLAGS = "flags"; - - public static final String PACKET_PRIORITY_COEFFICIENT = "priority_coefficient"; - - public static final String TRANSPORT_TYPE = "transport_type"; - public static final String TRANSPORT_ADDRESS = "transport_address"; - - public static final int BYTES_TO_SEND_FLAG_NONE = 0x00; - public static final int BYTES_TO_SEND_FLAG_SDL_PACKET_INCLUDED = 0x01; - public static final int BYTES_TO_SEND_FLAG_LARGE_PACKET_START = 0x02; - public static final int BYTES_TO_SEND_FLAG_LARGE_PACKET_CONT = 0x04; - public static final int BYTES_TO_SEND_FLAG_LARGE_PACKET_END = 0x08; - - public static final String CONNECTED_DEVICE_STRING_EXTRA_NAME = "devicestring"; - - public static final int PACKET_SENDING_ERROR_NOT_REGISTERED_APP = 0x00; - public static final int PACKET_SENDING_ERROR_NOT_CONNECTED = 0x01; - public static final int PACKET_SENDING_ERROR_UKNOWN = 0xFF; - - public static final String ROUTER_SERVICE_VERSION = "router_service_version"; - - /** - * Status binder - */ - - public static final int ROUTER_STATUS_CONNECTED_STATE_REQUEST = 0x01; - public static final int ROUTER_STATUS_CONNECTED_STATE_RESPONSE = 0x02; - /** - * This flag when used to check router status will trigger the router service in sending out a ping that if it is connected to a device - */ - public static final int ROUTER_STATUS_FLAG_TRIGGER_PING = 0x02; - - - /** - * Usb Transfer binder - */ - - public static final int USB_CONNECTED_WITH_DEVICE = 0x55; - public static final int ROUTER_USB_ACC_RECEIVED = 0x56; - - - /** - * Multiple-transports related constants - * - */ - public static final String IAP_BLUETOOTH = "IAP_BLUETOOTH"; - public static final String IAP_USB = "IAP_USB"; - public static final String IAP_USB_HOST_MODE = "TCP_WIFI"; - public static final String IAP_CARPLAY = "IAP_CARPLAY"; - public static final String SPP_BLUETOOTH = "SPP_BLUETOOTH"; - public static final String AOA_USB = "AOA_USB"; - public static final String TCP_WIFI = "TCP_WIFI"; - -} diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/transport/TransportManager.java b/android/sdl_android/src/main/java/com/smartdevicelink/transport/TransportManager.java index 5892390cd..75094a4b0 100644 --- a/android/sdl_android/src/main/java/com/smartdevicelink/transport/TransportManager.java +++ b/android/sdl_android/src/main/java/com/smartdevicelink/transport/TransportManager.java @@ -46,22 +46,19 @@ import android.os.Parcelable; import android.util.Log; import com.smartdevicelink.protocol.SdlPacket; +import com.smartdevicelink.protocol.enums.ControlFrameTags; import com.smartdevicelink.transport.enums.TransportType; import com.smartdevicelink.transport.utl.TransportRecord; import java.lang.ref.WeakReference; -import java.util.ArrayList; import java.util.List; @SuppressWarnings("unused") -public class TransportManager { +public class TransportManager extends TransportManagerBase{ private static final String TAG = "TransportManager"; - private final Object TRANSPORT_STATUS_LOCK; TransportBrokerImpl transport; - final List<TransportRecord> transportStatus; - final TransportEventListener transportListener; //Legacy Transport MultiplexBluetoothTransport legacyBluetoothTransport; @@ -77,12 +74,7 @@ public class TransportManager { */ public TransportManager(MultiplexTransportConfig config, TransportEventListener listener){ - - this.transportListener = listener; - this.TRANSPORT_STATUS_LOCK = new Object(); - synchronized (TRANSPORT_STATUS_LOCK){ - this.transportStatus = new ArrayList<>(); - } + super(config,listener); if(config.service == null) { config.service = SdlBroadcastReceiver.consumeQueuedRouterService(); @@ -98,6 +90,7 @@ public class TransportManager { } } + @Override public void start(){ if(transport != null){ transport.start(); @@ -106,6 +99,7 @@ public class TransportManager { } } + @Override public void close(long sessionId){ if(transport != null) { transport.removeSession(sessionId); @@ -116,6 +110,8 @@ public class TransportManager { } } + @Override + @Deprecated public void resetSession(){ transport.resetSession(); } @@ -129,6 +125,7 @@ public class TransportManager { * of supplied type will be used to return if connected. * @return if a transport is connected based on included variables */ + @Override public boolean isConnected(TransportType transportType, String address){ synchronized (TRANSPORT_STATUS_LOCK) { if (transportType == null) { @@ -156,6 +153,7 @@ public class TransportManager { * of supplied type will be returned. * @return the transport record for the transport type and address if supplied */ + @Override public TransportRecord getTransportRecord(TransportType transportType, String address){ synchronized (TRANSPORT_STATUS_LOCK) { if (transportType == null) { @@ -181,10 +179,12 @@ public class TransportManager { * Retrieves the currently connected transports * @return the currently connected transports */ + @Override public List<TransportRecord> getConnectedTransports(){ return this.transportStatus; } + @Override public boolean isHighBandwidthAvailable(){ synchronized (TRANSPORT_STATUS_LOCK) { for (TransportRecord record : transportStatus) { @@ -197,6 +197,15 @@ public class TransportManager { } } + @Override + public BaseTransportConfig updateTransportConfig(BaseTransportConfig config){ + if(transport != null && TransportType.MULTIPLEX.equals(config.getTransportType())){ + ((MultiplexTransportConfig)config).setService(transport.getRouterService()); + } + return config; + } + + @Deprecated public ComponentName getRouterService(){ if(transport != null) { return transport.getRouterService(); @@ -204,6 +213,7 @@ public class TransportManager { return null; } + @Override public void sendPacket(SdlPacket packet){ if(transport !=null){ transport.sendPacketToRouterService(packet); @@ -213,6 +223,7 @@ public class TransportManager { } } + @Override public void requestNewSession(TransportRecord transportRecord){ if(transport != null){ transport.requestNewSession(transportRecord); @@ -221,8 +232,32 @@ public class TransportManager { } } + @Deprecated public void requestSecondaryTransportConnection(byte sessionId, Bundle params){ - transport.requestSecondaryTransportConnection(sessionId, params); + transport.requestSecondaryTransportConnection(sessionId, (Bundle)params); + } + + @Override + public void requestSecondaryTransportConnection(byte sessionId, TransportRecord transportRecord){ + if(transportRecord != null){ + Bundle bundle = new Bundle(); + bundle.putString(TransportConstants.TRANSPORT_TYPE, transportRecord.getType().name()); + if(transportRecord.getType().equals(TransportType.TCP)) { + String address = transportRecord.getAddress(); + if(address.contains(":")){ + String[] split = address.split(":"); + if(split.length == 2) { + bundle.putString(ControlFrameTags.RPC.TransportEventUpdate.TCP_IP_ADDRESS, split[0]); + bundle.putInt(ControlFrameTags.RPC.TransportEventUpdate.TCP_PORT, Integer.valueOf(split[1])); + } //else {something went wrong;} + }else{ + bundle.putString(ControlFrameTags.RPC.TransportEventUpdate.TCP_IP_ADDRESS, address); + } + + + } + transport.requestSecondaryTransportConnection(sessionId, bundle); + } } protected class TransportBrokerImpl extends TransportBroker{ @@ -284,7 +319,8 @@ public class TransportManager { } } - private synchronized void enterLegacyMode(final String info){ + @Override + synchronized void enterLegacyMode(final String info){ if(legacyBluetoothTransport != null && legacyBluetoothHandler != null){ return; //Already in legacy mode } @@ -309,7 +345,8 @@ public class TransportManager { } } - protected synchronized void exitLegacyMode(String info ){ + @Override + synchronized void exitLegacyMode(String info ){ TransportRecord legacyTransportRecord = null; if(legacyBluetoothTransport != null){ legacyTransportRecord = legacyBluetoothTransport.getTransportRecord(); @@ -328,27 +365,6 @@ public class TransportManager { transportListener.onTransportDisconnected(info, legacyTransportRecord,null); } - public interface TransportEventListener{ - /** Called to indicate and deliver a packet received from transport */ - void onPacketReceived(SdlPacket packet); - - /** Called to indicate that transport connection was established */ - void onTransportConnected(List<TransportRecord> transports); - - /** Called to indicate that transport was disconnected (by either side) */ - void onTransportDisconnected(String info, TransportRecord type, List<TransportRecord> connectedTransports); - - // Called when the transport manager experiences an unrecoverable failure - void onError(String info); - /** - * Called when the transport manager has determined it needs to move towards a legacy style - * transport connection. It will always be bluetooth. - * @param info simple info string about the situation - * @return if the listener is ok with entering legacy mode - */ - boolean onLegacyModeEnabled(String info); - } - private BroadcastReceiver legacyDisconnectReceiver = new BroadcastReceiver() { @Override diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/transport/enums/TransportType.java b/android/sdl_android/src/main/java/com/smartdevicelink/transport/enums/TransportType.java deleted file mode 100644 index 2c09c72fc..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/transport/enums/TransportType.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.smartdevicelink.transport.enums;
-
-/**
- * Defines available types of the transports.
- */
-public enum TransportType {
- /**
- * Transport type will be anything the multiplexing service connects to.
- */
- MULTIPLEX,
- /**
- * Transport type is Bluetooth.
- */
- BLUETOOTH,
-
- /**
- * Transport type is TCP.
- */
- TCP,
- USB;
-
- public static TransportType valueForString(String value) {
- try{
- return valueOf(value);
- }catch(Exception e){
- return null;
- }
- }
-}
diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/transport/utl/TransportRecord.java b/android/sdl_android/src/main/java/com/smartdevicelink/transport/utl/TransportRecord.java deleted file mode 100644 index bcfc2e373..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/transport/utl/TransportRecord.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Copyright (c) 2018 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.transport.utl; - -import android.os.Parcel; -import android.os.Parcelable; - -import com.smartdevicelink.transport.enums.TransportType; - -public class TransportRecord implements Parcelable{ - - private TransportType type; - private String address; - - public TransportRecord(TransportType transportType, String address){ - this.type = transportType; - this.address = address; - } - - public TransportType getType() { - return type; - } - - public String getAddress() { - return address; - } - - @Override - public boolean equals(Object obj) { - if(obj == null) { - return false; - } - - if (obj instanceof TransportRecord) { - TransportRecord record = (TransportRecord) obj; - return record.type != null && record.type.equals(type) //Transport type is the same - && ((record.address == null && address == null) //Both addresses are null - || (record.address != null && record.address.equals(address))); //Or they match - } - - return super.equals(obj); - } - - @Override - public String toString(){ - StringBuilder builder = new StringBuilder(); - builder.append("Transport Type: "); - builder.append(type.name()); - builder.append(" Address: "); - builder.append(address); - return builder.toString(); - } - - public TransportRecord(Parcel p){ - if (p.readInt() == 1) { //We should have a transport type attached - String transportName = p.readString(); - if(transportName != null){ - this.type = TransportType.valueOf(transportName); - } - } - - if (p.readInt() == 1) { //We should have a transport address attached - address = p.readString(); - } - } - - @Override - public int describeContents() { - return 0; - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - dest.writeInt(type!=null? 1 : 0); - if(type != null){ - dest.writeString(type.name()); - } - - dest.writeInt(address !=null? 1 : 0); - if(address != null){ - dest.writeString(address); - } - } - - public static final Parcelable.Creator<TransportRecord> CREATOR = new Parcelable.Creator<TransportRecord>() { - public TransportRecord createFromParcel(Parcel in) { - return new TransportRecord(in); - } - - @Override - public TransportRecord[] newArray(int size) { - return new TransportRecord[size]; - } - - }; -} diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/util/BitConverter.java b/android/sdl_android/src/main/java/com/smartdevicelink/util/BitConverter.java deleted file mode 100644 index a681a75a8..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/util/BitConverter.java +++ /dev/null @@ -1,116 +0,0 @@ -package com.smartdevicelink.util;
-
-public class BitConverter {
- /**
- * @param bytes byte array that will be converted to hex
- * @return the String containing converted hex values or null if byte array is null
- */
- public static String bytesToHex(byte [] bytes) {
- if (bytes == null) { return null; }
- return bytesToHex(bytes, 0, bytes.length);
- } // end-method
-
- /**
- * @param bytes byte array that will be converted to hex
- * @param offset int representing the offset to begin conversion at
- * @param length int representing number of bytes in array to convert
- * @return the String containing converted hex values or null if byte array is null
- */
- public static String bytesToHex(byte[] bytes, int offset, int length) {
- if (bytes == null) { return null; }
- final char[] HexDigits = new char[] {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
- byte b;
- char[] hexChars = new char[2 * length];
- //StringBuffer sb = new StringBuffer();
- int upperBound = Math.min(bytes.length, (offset + length));
- int baidx = 0;
- int sidx = 0;
- for (baidx = offset; baidx < upperBound; baidx++) {
- // Get the byte from the array
- b = bytes[baidx];
- // Use nibbles as index into hex digit array (left nibble, then right)
- hexChars[sidx++] = HexDigits[(b & 0xf0) >> 4];
- hexChars[sidx++] = HexDigits[(b & 0x0f)];
- } // end-for
- return new String(hexChars);
- } // end-method
-
- /**
- * @param hexString the String containing converted hex values
- * @return byte array converted from input String or null if String is null
- */
- public static byte [] hexToBytes(String hexString) {
- if (hexString == null) { return null; }
- if (hexString.length() % 2 != 0) {
- hexString = "0" + hexString;
- }
- byte [] theBytes = new byte[hexString.length() / 2];
- for (int i = 0; i < hexString.length(); i += 2) {
- String byteString = hexString.substring(i, i + 2);
- byte theByte = (byte)Integer.parseInt(byteString, 16);
- theBytes[i/2] = theByte;
- }
- return theBytes;
- } // end-method
-
- public static final byte[] intToByteArray(int value) {
- return new byte[] {
- (byte)(value >>> 24),
- (byte)(value >>> 16),
- (byte)(value >>> 8),
- (byte)value};
- }
-
- /**
- * @param sizeBuf byte array that will be converted to int
- * @return int converted from byte array or -1 if byte array is null
- */
- public static int intFromByteArray(byte[] sizeBuf, int offset) {
- if (sizeBuf == null) { return -1; }
- int ret = 0;
- for (int i = offset; i < offset + 4; i++) {
- ret <<= 8;
- ret |= 0xFF & sizeBuf[i];
- }
- return ret;
- }
-
- public static final byte[] shortToByteArray(short value) {
- return new byte[] {
- (byte)(value >>> 8),
- (byte)value};
- }
-
- /**
- * @param sizeBuf byte array that will be converted to short
- * @return short converted from byte array or -1 if byte array is null
- */
- public static short shortFromByteArray(byte[] sizeBuf, int offset) {
- if (sizeBuf == null) { return -1; }
- short ret = 0;
- for (int i = offset; i < offset + 2; i++) {
- ret <<= 8;
- ret |= 0xFF & sizeBuf[i];
- }
- return ret;
- }
-
- /**
- * Converts the byte array into a string of hex values.
- * @param bytes byte array that will be converted to hex
- * @param end EXCLUSIVE so if it it receives 10 it will print 0-9
- * @return the String containing converted hex values or null if byte array is null
- */
- public static String bytesToHex(byte[] bytes,int end){
- if (bytes == null) { return null; }
- if(bytes.length<end){
- end = bytes.length;
- }
- StringBuilder sb = new StringBuilder();
- for(int i=0;i<end;i++){
- sb.append(" ");
- sb.append(String.format("%02X ", bytes[i]));
- }
- return sb.toString();
- }
-}
diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/util/ByteEnumer.java b/android/sdl_android/src/main/java/com/smartdevicelink/util/ByteEnumer.java deleted file mode 100644 index 0b67d9992..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/util/ByteEnumer.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.smartdevicelink.util;
-
-import java.util.Enumeration;
-import java.util.Vector;
-
-public abstract class ByteEnumer {
-
- protected ByteEnumer(byte value, String name) {
- this.value = value;
- this.name = name;
- }
-
- private byte value;
- private String name;
-
- public byte getValue() { return value; }
- public String getName() { return name; }
-
- public boolean equals(ByteEnumer other) {
- return name == other.getName();
- }
-
- public boolean eq(ByteEnumer other) {
- return equals(other);
- }
-
- public byte value() {
- return value;
- }
-
- public static ByteEnumer get(Vector<?> theList, byte value) {
- Enumeration<?> enumer = theList.elements();
- while (enumer.hasMoreElements()) {
- try {
- ByteEnumer current = (ByteEnumer)enumer.nextElement();
- if (current.getValue() == value) {
- return current;
- }
- } catch (ClassCastException e) {
- return null;
- }
- }
- return null;
- }
-
- public static ByteEnumer get(Vector<?> theList, String name) {
- Enumeration<?> enumer = theList.elements();
- while (enumer.hasMoreElements()) {
- try {
- ByteEnumer current = (ByteEnumer)enumer.nextElement();
- if (current.getName().equals(name)) {
- return current;
- }
- } catch (ClassCastException e) {
- return null;
- }
- }
- return null;
- }
-}
\ No newline at end of file diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/util/CorrelationIdGenerator.java b/android/sdl_android/src/main/java/com/smartdevicelink/util/CorrelationIdGenerator.java deleted file mode 100644 index 18ff93622..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/util/CorrelationIdGenerator.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.smartdevicelink.util; - -import java.util.concurrent.atomic.AtomicInteger; - -public class CorrelationIdGenerator { - - private static final int CORRELATION_ID_START = 0; - - private static final AtomicInteger sNextCorrelationId = new AtomicInteger(CORRELATION_ID_START); - - public static int generateId() { - for (;;) { - final int result = sNextCorrelationId.get(); - // aapt-generated IDs have the high byte nonzero; clamp to the range under that. - int newValue = result + 1; - - if (newValue > 0x00FFFFFF){ - newValue = CORRELATION_ID_START; // Roll over to 0. - } - if (sNextCorrelationId.compareAndSet(result, newValue)) { - return result; - } - } - } -} diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/util/DebugTool.java b/android/sdl_android/src/main/java/com/smartdevicelink/util/DebugTool.java deleted file mode 100644 index 2ea9cc938..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/util/DebugTool.java +++ /dev/null @@ -1,355 +0,0 @@ -package com.smartdevicelink.util;
-
-import android.util.Log;
-
-import com.smartdevicelink.exception.SdlException;
-import com.smartdevicelink.marshal.JsonRPCMarshaller;
-import com.smartdevicelink.protocol.BinaryFrameHeader;
-import com.smartdevicelink.protocol.ProtocolMessage;
-import com.smartdevicelink.protocol.SdlPacket;
-import com.smartdevicelink.protocol.enums.FunctionID;
-import com.smartdevicelink.protocol.enums.MessageType;
-import com.smartdevicelink.protocol.enums.SessionType;
-import com.smartdevicelink.proxy.RPCMessage;
-import com.smartdevicelink.proxy.RPCStruct;
-import com.smartdevicelink.proxy.Version;
-import com.smartdevicelink.transport.SiphonServer;
-
-import java.util.Hashtable;
-import java.util.Vector;
-
-public class DebugTool {
-
-
- public static final String TAG = "SdlProxy";
-
- private static boolean isErrorEnabled = false;
- private static boolean isWarningEnabled = false;
- private static boolean isInfoEnabled = false;
-
- public static void enableDebugTool() {
- isErrorEnabled = true;
- isWarningEnabled = true;
- isInfoEnabled = true;
- }
-
- public static void disableDebugTool() {
- isErrorEnabled = true;
- isWarningEnabled = false;
- isInfoEnabled = false;
- }
-
- public static boolean isDebugEnabled()
- {
- if (isWarningEnabled && isInfoEnabled) return true;
-
- return false;
- }
-
- private static String prependProxyVersionNumberToString(String string) {
- if (Version.VERSION != null && string != null) {
- string = Version.VERSION + ": " + string;
- }
-
- return string;
- }
-
- public static void logError(String msg) {
-
- Boolean wasWritten = false;
-
- msg = prependProxyVersionNumberToString(msg);
-
- wasWritten = logToSiphon(msg);
-
- if (isErrorEnabled && !wasWritten) {
- NativeLogTool.logError(TAG, msg);
- }
- }
-
- public static void logError(String msg, Throwable ex) {
- Boolean wasWritten = false;
-
- msg = prependProxyVersionNumberToString(msg);
-
- if (ex != null) {
- wasWritten = logToSiphon(msg + " Exception String: " + ex.toString());
- } else {
- wasWritten = logToSiphon(msg);
- }
-
- if (isErrorEnabled && !wasWritten) {
- NativeLogTool.logError(TAG, msg, ex);
- }
- }
-
- public static void logWarning(String msg) {
- Boolean wasWritten = false;
-
- msg = prependProxyVersionNumberToString(msg);
-
- wasWritten = logToSiphon(msg);
-
- if (isWarningEnabled && !wasWritten) {
- NativeLogTool.logWarning(TAG, msg);
- }
- }
-
- public static void logInfo(String msg) {
- Boolean wasWritten = false;
-
- msg = prependProxyVersionNumberToString(msg);
-
- wasWritten = logToSiphon(msg);
-
- if (isInfoEnabled && !wasWritten) {
- NativeLogTool.logInfo(TAG, msg);
- }
- }
-
- public static void logInfo(String msg, boolean bPrependVersion) {
- Boolean wasWritten = false;
-
- if (bPrependVersion) msg = prependProxyVersionNumberToString(msg);
-
- wasWritten = logToSiphon(msg);
-
- if (isInfoEnabled && !wasWritten) {
- NativeLogTool.logInfo(TAG, msg);
- }
- }
-
- protected static Boolean logToSiphon(String msg) {
- if (SiphonServer.getSiphonEnabledStatus()) {
- // Initialize the SiphonServer, will be ignored if already initialized
- SiphonServer.init();
-
- // Write to the SiphonServer
- return SiphonServer.sendSiphonLogData(msg);
- }
- return false;
- }
-
- protected static String getLine(Throwable ex) {
- if (ex == null) { return null; }
- String toPrint = ex.toString() + " :" + ex.getMessage();
- for (int i=0; i<ex.getStackTrace().length; i++) {
- StackTraceElement elem = ex.getStackTrace()[i];
- toPrint += "\n " + elem.toString();
- }
-
- if (ex instanceof SdlException) {
- SdlException sdlEx = (SdlException) ex;
- if (sdlEx.getInnerException() != null && sdlEx != sdlEx.getInnerException()) {
- toPrint += "\n nested:\n";
- toPrint += getLine(sdlEx.getInnerException());
- }
- }
-
- return toPrint;
- }
-
-
- protected static Vector<IConsole> consoleListenerList = new Vector<IConsole>();
-
- protected final static boolean isTransportEnabled = false;
- protected final static boolean isRPCEnabled = false;
-
- public static void addConsole(IConsole console) {
- synchronized(consoleListenerList) {
- consoleListenerList.addElement(console);
- }
- }
-
- public static void removeConsole(IConsole console) {
- synchronized(consoleListenerList) {
- consoleListenerList.removeElement(console);
- }
- }
-
- public static void clearConsoles() {
- synchronized(consoleListenerList) {
- consoleListenerList.removeAllElements();
- }
- }
-
- public static void logTransport(String msg) {
- if (isTransportEnabled) {
- Log.d(TAG, msg);
- logInfoToConsole(msg);
- }
- }
-
- public static void logRPCSend(String rpcMsg) {
- if (isRPCEnabled) {
- Log.d(TAG, "Sending RPC message: " + rpcMsg);
- logRPCSendToConsole(rpcMsg);
- }
- }
-
- public static void logRPCReceive(String rpcMsg) {
- if (isRPCEnabled) {
- Log.d(TAG, "Received RPC message: " + rpcMsg);
- logRPCSendToConsole(rpcMsg);
- }
- }
-
- @SuppressWarnings("unchecked")
- protected static void logInfoToConsole(String msg) {
- Vector<IConsole> localList;
- synchronized(consoleListenerList) {
- localList = (Vector<IConsole>) consoleListenerList.clone();
- }
-
- for (int i = 0; i < localList.size(); i++) {
- IConsole consoleListener = (IConsole) localList.elementAt(i);
- try {
- consoleListener.logInfo(msg);
- } catch (Exception ex) {
- Log.e(TAG, "Failure propagating logInfo: " + ex.toString(), ex);
- } // end-catch
- }
- }
-
- @SuppressWarnings("unchecked")
- protected static void logErrorToConsole(String msg) {
- Vector<IConsole> localList;
- synchronized(consoleListenerList) {
- localList = (Vector<IConsole>) consoleListenerList.clone();
- }
- for (int i = 0; i < localList.size(); i++) {
- IConsole consoleListener = (IConsole) localList.elementAt(i);
- try {
- consoleListener.logError(msg);
- } catch (Exception ex) {
- Log.e(TAG, "Failure propagating logError: " + ex.toString(), ex);
- } // end-catch
- }
- }
-
- @SuppressWarnings("unchecked")
- protected static void logErrorToConsole(String msg, Throwable e) {
- Vector<IConsole> localList;
- synchronized(consoleListenerList) {
- localList = (Vector<IConsole>) consoleListenerList.clone();
- }
-
- for (int i = 0; i < localList.size(); i++) {
- IConsole consoleListener = (IConsole) localList.elementAt(i);
- try {
- consoleListener.logError(msg, e);
- } catch (Exception ex) {
- Log.e(TAG, "Failure propagating logError: " + ex.toString(), ex);
- } // end-catch
- }
- }
-
- @SuppressWarnings("unchecked")
- protected static void logRPCSendToConsole(String msg) {
- Vector<IConsole> localList;
- synchronized(consoleListenerList) {
- localList = (Vector<IConsole>) consoleListenerList.clone();
- }
-
- for (int i = 0; i < localList.size(); i++) {
- IConsole consoleListener = (IConsole) localList.elementAt(i);
- try {
- consoleListener.logRPCSend(msg);
- } catch (Exception ex) {
- Log.e(TAG, "Failure propagating logRPCSend: " + ex.toString(), ex);
- } // end-catch
- }
- }
-
- @SuppressWarnings("unchecked")
- protected static void logRPCReceiveToConsole(String msg) {
- Vector<IConsole> localList;
- synchronized(consoleListenerList) {
- localList = (Vector<IConsole>) consoleListenerList.clone();
- }
-
- for (int i = 0; i < localList.size(); i++) {
- IConsole consoleListener = (IConsole) localList.elementAt(i);
- try {
- consoleListener.logRPCReceive(msg);
- } catch (Exception ex) {
- Log.e(TAG, "Failure propagating logRPCReceive: " + ex.toString(), ex);
- } // end-catch
- }
- }
-
- /**
- * Debug method to try to extract the RPC hash from the packet payload. Should only be used while debugging, not in production.
- * Currently it will only handle single frame RPCs
- * @param packet to inspect
- * @return The Hashtable to be used to construct an RPC
- */
- public static Hashtable<String, Object> getRPCHash(SdlPacket packet){
- if(packet == null ||
- packet.getFrameType().getValue() != SdlPacket.FRAME_TYPE_SINGLE ||
- packet.getServiceType()!=SdlPacket.SERVICE_TYPE_RPC){
- Log.w("Debug", "Unable to get hash");
- return null;
- }
- int version = packet.getVersion();
-
- ProtocolMessage message = new ProtocolMessage();
- SessionType serviceType = SessionType.valueOf((byte)packet.getServiceType());
- if (serviceType == SessionType.RPC) {
- message.setMessageType(MessageType.RPC);
- } else if (serviceType == SessionType.BULK_DATA) {
- message.setMessageType(MessageType.BULK);
- } // end-if
- message.setSessionType(serviceType);
- message.setSessionID((byte)packet.getSessionId());
- //If it is WiPro 2.0 it must have binary header
- if (version > 1) {
- BinaryFrameHeader binFrameHeader = BinaryFrameHeader.
- parseBinaryHeader(packet.getPayload());
- if(binFrameHeader == null) {
- return null;
- }
- message.setVersion((byte) version);
- message.setRPCType(binFrameHeader.getRPCType());
- message.setFunctionID(binFrameHeader.getFunctionID());
- message.setCorrID(binFrameHeader.getCorrID());
- if (binFrameHeader.getJsonSize() > 0){
- message.setData(binFrameHeader.getJsonData());
- }
- if (binFrameHeader.getBulkData() != null){
- message.setBulkData(binFrameHeader.getBulkData());
- }
- } else {
- message.setData(packet.getPayload());
- }
- Hashtable<String, Object> hash = new Hashtable<String, Object>();
- if (packet.getVersion() > 1) {
- Hashtable<String, Object> hashTemp = new Hashtable<String, Object>();
-
- hashTemp.put(RPCMessage.KEY_CORRELATION_ID, message.getCorrID());
- if (message.getJsonSize() > 0) {
- final Hashtable<String, Object> mhash = JsonRPCMarshaller.unmarshall(message.getData());
- hashTemp.put(RPCMessage.KEY_PARAMETERS, mhash);
- }
-
- String functionName = FunctionID.getFunctionName(message.getFunctionID());
- if (functionName != null) {
- hashTemp.put(RPCMessage.KEY_FUNCTION_NAME, functionName);
- } else {
- return null;
- }
- if (message.getRPCType() == 0x00) {
- hash.put(RPCMessage.KEY_REQUEST, hashTemp);
- } else if (message.getRPCType() == 0x01) {
- hash.put(RPCMessage.KEY_RESPONSE, hashTemp);
- } else if (message.getRPCType() == 0x02) {
- hash.put(RPCMessage.KEY_NOTIFICATION, hashTemp);
- }
- if (message.getBulkData() != null) hash.put(RPCStruct.KEY_BULK_DATA, message.getBulkData());
- } else {
- final Hashtable<String, Object> mhash = JsonRPCMarshaller.unmarshall(message.getData());
- hash = mhash;
- }
- return hash;
- }
-}
diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/util/HttpRequestTask.java b/android/sdl_android/src/main/java/com/smartdevicelink/util/HttpRequestTask.java deleted file mode 100644 index 5e8bba95c..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/util/HttpRequestTask.java +++ /dev/null @@ -1,180 +0,0 @@ -package com.smartdevicelink.util; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.io.Writer; -import java.net.HttpURLConnection; -import java.net.URL; - -import android.os.AsyncTask; -import android.util.Log; - -public class HttpRequestTask extends AsyncTask<String, String, String> { - private static final String TAG = "Http Request Task"; - - public static final String REQUEST_TYPE_POST = "POST"; - public static final String REQUEST_TYPE_GET = "GET"; - public static final String REQUEST_TYPE_DELETE = "DELETE"; - - HttpRequestTaskCallback cb; - - /** - * @param HttpRequestTaskCallback callback for when this task finishes - * <br><br><b> - When calling execute, params as followed: </b><br> - * 1. Url String<br> - * 2. Request type (Defined in this class) REQUEST_TYPE_POST, REQUEST_TYPE_GET, REQUEST_TYPE_DELETE<br> - * 3. (Optional) Data to be sent. <br> - * 4. (Optional) Content Type Default will be application/json<br> - * 5. (Optional) Accept Type default will be application/json - * - */ - public HttpRequestTask( HttpRequestTaskCallback hcb){ - this.cb = hcb; - } - - @Override - protected String doInBackground(String... params) { - int length = params.length; - String urlString = params[0]; - String request_type = params[1]; - - //Grab and set data to be written if included - String data; - if(length>2){ - data = params[2]; - }else{ - data = null; - } - - //Grab and set content type for the header if included - String contentType; - if(length>3){ - contentType = params[3]; - }else{ - contentType = "application/json"; - } - //Grab and set accept type for the header if included - String acceptType; - if(length>4){ - acceptType = params[4]; - }else{ - acceptType = "application/json"; - } - - if(urlString == null || request_type == null){ - Log.e(TAG, "Can't process request, param error"); - if(cb!=null){ - cb.httpFailure(-1); - cb = null; - } - return "Error"; - } - - HttpURLConnection urlConnection = null; - BufferedReader reader = null; - try { - URL url = new URL(urlString); - urlConnection = (HttpURLConnection) url.openConnection(); - urlConnection.setDoOutput(true); - urlConnection.setRequestMethod(request_type); - urlConnection.setRequestProperty("Content-Type", contentType); - urlConnection.setRequestProperty("Accept", acceptType); - //If we have data, we should write it out - if(data !=null){ - Writer writer = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8")); - writer.write(data); - writer.close(); - } - InputStream inputStream = urlConnection.getInputStream(); - - int responseCode = urlConnection.getResponseCode(); - if (responseCode == 200) { //Success - //input stream - StringBuffer buffer = new StringBuffer(); - if (inputStream == null) { - // Nothing to do. - if(cb!=null){ - cb.httpCallComplete(null); - cb = null; - } - return null; - } - reader = new BufferedReader(new InputStreamReader(inputStream)); - - String inputLine; - while ((inputLine = reader.readLine()) != null) - buffer.append(inputLine + "\n"); - if (buffer.length() == 0) { - // Stream was empty. No point in parsing. - if(cb!=null){ - cb.httpCallComplete(null); - cb = null; - } - return null; - } - String response = null; - - response = buffer.toString(); - //send to post execute - if(cb!=null){ - cb.httpCallComplete(response); - cb = null; - } - return response; - }else{ - if(cb!=null){ - cb.httpFailure(responseCode); - cb = null; - } - Log.e(TAG, "Failed to download file - " + responseCode); - return null; - } - - - } catch (IOException e) { - e.printStackTrace(); - } catch (NullPointerException e){ // Only to catch error in urlConnection.getOutputStream() - when servers are down - e.printStackTrace(); - urlConnection = null; - } - finally { - if (urlConnection != null) { - urlConnection.disconnect(); - } - if (reader != null) { - try { - reader.close(); - } catch (final IOException e) { - Log.e(TAG, "Error closing stream", e); - } - } - if(cb!=null){ - cb.httpFailure(-1); - } - } - return null; - } - - /** - * Callback interface for HTTP requests. - * @author Joey Grover - * - */ - public interface HttpRequestTaskCallback{ - /** - * Called when HTTP request is successfully completed. - * @param response The response to the HTTP request. - */ - public abstract void httpCallComplete(String response); - /** - * Called when HTTP request failed. - * @param statusCode The HTTP failure code. - */ - public abstract void httpFailure(int statusCode); - } - -} diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/util/IConsole.java b/android/sdl_android/src/main/java/com/smartdevicelink/util/IConsole.java deleted file mode 100644 index 8d6d4a0f1..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/util/IConsole.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.smartdevicelink.util;
-
-
-public interface IConsole {
- void logInfo(String msg);
- void logError(String msg);
- void logError(String msg, Throwable ex);
- void logRPCSend(String rpcMsg);
- void logRPCReceive(String rpcMsg);
-}
diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/util/NativeLogTool.java b/android/sdl_android/src/main/java/com/smartdevicelink/util/NativeLogTool.java deleted file mode 100644 index c89b970dc..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/util/NativeLogTool.java +++ /dev/null @@ -1,114 +0,0 @@ -package com.smartdevicelink.util;
-
-import android.util.Log;
-
-import com.smartdevicelink.proxy.SdlProxyBase;
-
-public class NativeLogTool {
-
- static private boolean logToSystemEnabled = true;
- private static final int ChunkSize = 4000;
-
- public enum LogTarget {
- Info
- ,Warning
- ,Error;
-
- public static LogTarget valueForString (String value) {
- try{
- return valueOf(value);
- } catch(Exception e) {
- return null;
- }
- }
- }
-
- public static void setEnableState(boolean en) {
- logToSystemEnabled = en;
- } // end-method
-
- public static boolean isEnabled() {
- return logToSystemEnabled;
- } // end-method
-
- public static boolean logInfo(String message) {
- return logInfo(SdlProxyBase.TAG, message);
- }
-
- public static boolean logInfo(String tag, String message) {
- if (logToSystemEnabled) {
- return log(LogTarget.Info, tag, message);
- }
- return false;
- }
-
- public static boolean logWarning(String message) {
- return logWarning(SdlProxyBase.TAG, message);
- }
-
- public static boolean logWarning(String tag, String message) {
- if (logToSystemEnabled) {
- return log(LogTarget.Warning, tag, message);
- }
- return false;
- }
-
- public static boolean logError(String message) {
- return logError(SdlProxyBase.TAG, message);
- }
-
- public static boolean logError(String tag, String message) {
- if (logToSystemEnabled) {
- return log(LogTarget.Error, tag, message);
- }
- return false;
- }
-
- public static boolean logError(String message, Throwable t) {
- return logError(SdlProxyBase.TAG, message, t);
- }
-
- public static boolean logError(String tag, String message, Throwable t) {
- // If the call to logError is passed a throwable, write directly to the system log
- if (logToSystemEnabled) {
- Log.e(tag, message, t);
- }
- return logToSystemEnabled;
- }
-
- private static boolean log(LogTarget ltarg, String source, String logMsg) {
- // Don't log empty messages
- if (logMsg == null || logMsg.length() == 0) {
- return false;
- }
-
- int bytesWritten = 0;
- int substrSize = 0;
- String tag = source;
- String chunk = null;
- try {
- for (int idx=0;idx < logMsg.length();idx += substrSize) {
- substrSize = Math.min(ChunkSize, logMsg.length() - idx);
- chunk = logMsg.substring(idx, idx + substrSize);
- switch (ltarg) {
- case Info:
- bytesWritten = Log.i(tag, chunk);
- break;
- case Warning:
- bytesWritten = Log.w(tag, chunk);
- break;
- case Error:
- bytesWritten = Log.e(tag, chunk);
- break;
- }
- if (bytesWritten < chunk.length()) {
- Log.e(SdlProxyBase.TAG, "Calling Log.e: msg length=" + chunk.length() + ", bytesWritten=" + bytesWritten);
- }
- }
- } catch (Exception ex) {
- Log.e(SdlProxyBase.TAG, "Failure writing " + ltarg.name() + " fragments to android log:" + ex.toString());
- return false;
- }
- return true;
- }
-} diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/util/SdlDataTypeConverter.java b/android/sdl_android/src/main/java/com/smartdevicelink/util/SdlDataTypeConverter.java deleted file mode 100644 index 0b47a59cd..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/util/SdlDataTypeConverter.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.smartdevicelink.util; - -/** - * This is a utility class to aid in handling values stored in the RPC classes. - */ -public class SdlDataTypeConverter { - - /** - * Converts values that are retrieved from an RPC parameters Hashtable as an - * Object into the standard number value of the mobile API, Double. - * - * @param originalValue The value retrieved from an RPC parameters Hashtable. - * @return The Double representation of an integer or double value stored in - * the Object, or null if the value could not be converted. - */ - public static Double objectToDouble(Object originalValue) { - - if (originalValue == null) { - return null; - } - - Double result = null; - - // Uses reflection to determine if the object is a valid type. - if (originalValue instanceof Integer) { - result = ((Integer) originalValue).doubleValue(); - } else if (originalValue instanceof Float){ - result = ((Float) originalValue).doubleValue(); - } else if (originalValue instanceof Double){ - result = (Double) originalValue; - } - - return result; - } - - /** - * Converts values that are retrieved from an RPC parameters Hashtable as an - * Object into the standard number value of the mobile API, Float. - * - * @param originalValue The value retrieved from an RPC parameters Hashtable. - * @return The Float representation of an integer or float value stored in - * the Object, or null if the value could not be converted. - */ - public static Float objectToFloat(Object originalValue) { - - if (originalValue == null) { - return null; - } - - Float result = null; - - // Uses reflection to determine if the object is a valid type. - if (originalValue instanceof Integer) { - result = ((Integer) originalValue).floatValue(); - } else if (originalValue instanceof Double){ - result = ((Double) originalValue).floatValue(); - } else if (originalValue instanceof Float){ - result = (Float) originalValue; - } - - return result; - } -} diff --git a/android/sdl_android/src/main/java/com/smartdevicelink/util/Version.java b/android/sdl_android/src/main/java/com/smartdevicelink/util/Version.java deleted file mode 100644 index 78eac8db4..000000000 --- a/android/sdl_android/src/main/java/com/smartdevicelink/util/Version.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.smartdevicelink.util; - - -public class Version { - - final int major,minor,patch; - - public Version(){ - major = 0; - minor = 0; - patch = 0; - } - - public Version(int major, int minor, int patch){ - this.major = major; - this.minor = minor; - this.patch = patch; - } - - public Version(String versionString){ - String[] versions = versionString.split("\\."); - if(versions.length!=3){ - throw new IllegalArgumentException("Incorrect version string format"); - } - major = Integer.valueOf(versions[0]); - minor = Integer.valueOf(versions[1]); - patch = Integer.valueOf(versions[2]); - - } - - public int getMajor() { - return major; - } - - public int getMinor() { - return minor; - } - - public int getPatch() { - return patch; - } - - /** - * Method to test if this instance of Version is newer than the supplied one. - * @param version the version to check against - * @return 1 if this instance is newer, -1 if supplied version is newer, and 0 if they are equal - */ - public int isNewerThan(Version version){ - if(this.major > version.major){ - return 1; - }else if(this.major == version.major){ - if(this.minor > version.minor){ - return 1; - } else if(this.minor == version.minor){ - if(this.patch > version.patch){ - return 1; - }else if(this.patch == version.patch){ - return 0; - } - } - } - return -1; - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append(major); - builder.append("."); - builder.append(minor); - builder.append("."); - builder.append(patch); - return builder.toString(); - } -} diff --git a/base/src/main/java/com/smartdevicelink/Dispatcher/IDispatchingStrategy.java b/base/src/main/java/com/smartdevicelink/Dispatcher/IDispatchingStrategy.java index 4ed8851ea..a4cfc150b 100644 --- a/base/src/main/java/com/smartdevicelink/Dispatcher/IDispatchingStrategy.java +++ b/base/src/main/java/com/smartdevicelink/Dispatcher/IDispatchingStrategy.java @@ -1,9 +1,9 @@ -package com.smartdevicelink.Dispatcher; - -public interface IDispatchingStrategy<T> { - public void dispatch(T message); - - public void handleDispatchingError(String info, Exception ex); - - public void handleQueueingError(String info, Exception ex); -} +package com.smartdevicelink.Dispatcher;
+
+public interface IDispatchingStrategy<T> {
+ public void dispatch(T message);
+
+ public void handleDispatchingError(String info, Exception ex);
+
+ public void handleQueueingError(String info, Exception ex);
+}
diff --git a/base/src/main/java/com/smartdevicelink/Dispatcher/ProxyMessageDispatcher.java b/base/src/main/java/com/smartdevicelink/Dispatcher/ProxyMessageDispatcher.java index e27f4bf8f..8db6f51e7 100644 --- a/base/src/main/java/com/smartdevicelink/Dispatcher/ProxyMessageDispatcher.java +++ b/base/src/main/java/com/smartdevicelink/Dispatcher/ProxyMessageDispatcher.java @@ -1,63 +1,63 @@ -package com.smartdevicelink.Dispatcher; - -import java.util.concurrent.LinkedBlockingQueue; - -import com.smartdevicelink.util.DebugTool; - -public class ProxyMessageDispatcher<T> { - LinkedBlockingQueue<T> _queue = null; - private Thread _messageDispatchingThread = null; - IDispatchingStrategy<T> _strategy = null; - - // Boolean to track if disposed - private Boolean dispatcherDisposed = false; - - public ProxyMessageDispatcher(String THREAD_NAME, IDispatchingStrategy<T> strategy) { - _queue = new LinkedBlockingQueue<T>(); - - _strategy = strategy; - - // Create dispatching thread - _messageDispatchingThread = new Thread(new Runnable() {public void run(){handleMessages();}}); - _messageDispatchingThread.setName(THREAD_NAME); - _messageDispatchingThread.setDaemon(true); - _messageDispatchingThread.start(); - } - - public void dispose() { - dispatcherDisposed = true; - - if(_messageDispatchingThread != null) { - _messageDispatchingThread.interrupt(); - _messageDispatchingThread = null; - } - } - - private void handleMessages() { - - try { - T thisMessage; - - while(dispatcherDisposed == false) { - thisMessage = _queue.take(); - _strategy.dispatch(thisMessage); - } - } catch (InterruptedException e) { - // Thread was interrupted by dispose() method, no action required - return; - } catch (Exception e) { - DebugTool.logError("Error occurred dispating message.", e); - _strategy.handleDispatchingError("Error occurred dispating message.", e); - } - } - - public void queueMessage(T message) { - try { - _queue.put(message); - } catch(ClassCastException e) { - _strategy.handleQueueingError("ClassCastException encountered when queueing message.", e); - } catch(Exception e) { - _strategy.handleQueueingError("Exception encountered when queueing message.", e); - } - } -} +package com.smartdevicelink.Dispatcher;
+
+import java.util.concurrent.LinkedBlockingQueue;
+
+import com.smartdevicelink.util.DebugTool;
+
+public class ProxyMessageDispatcher<T> {
+ LinkedBlockingQueue<T> _queue = null;
+ private Thread _messageDispatchingThread = null;
+ IDispatchingStrategy<T> _strategy = null;
+
+ // Boolean to track if disposed
+ private Boolean dispatcherDisposed = false;
+
+ public ProxyMessageDispatcher(String THREAD_NAME, IDispatchingStrategy<T> strategy) {
+ _queue = new LinkedBlockingQueue<T>();
+
+ _strategy = strategy;
+
+ // Create dispatching thread
+ _messageDispatchingThread = new Thread(new Runnable() {public void run(){handleMessages();}});
+ _messageDispatchingThread.setName(THREAD_NAME);
+ _messageDispatchingThread.setDaemon(true);
+ _messageDispatchingThread.start();
+ }
+
+ public void dispose() {
+ dispatcherDisposed = true;
+
+ if(_messageDispatchingThread != null) {
+ _messageDispatchingThread.interrupt();
+ _messageDispatchingThread = null;
+ }
+ }
+
+ private void handleMessages() {
+
+ try {
+ T thisMessage;
+
+ while(dispatcherDisposed == false) {
+ thisMessage = _queue.take();
+ _strategy.dispatch(thisMessage);
+ }
+ } catch (InterruptedException e) {
+ // Thread was interrupted by dispose() method, no action required
+ return;
+ } catch (Exception e) {
+ DebugTool.logError("Error occurred dispating message.", e);
+ _strategy.handleDispatchingError("Error occurred dispating message.", e);
+ }
+ }
+
+ public void queueMessage(T message) {
+ try {
+ _queue.put(message);
+ } catch(ClassCastException e) {
+ _strategy.handleQueueingError("ClassCastException encountered when queueing message.", e);
+ } catch(Exception e) {
+ _strategy.handleQueueingError("Exception encountered when queueing message.", e);
+ }
+ }
+}
diff --git a/base/src/main/java/com/smartdevicelink/SdlConnection/ISdlConnectionListener.java b/base/src/main/java/com/smartdevicelink/SdlConnection/ISdlConnectionListener.java index 34d4295b6..c059b6b16 100644 --- a/base/src/main/java/com/smartdevicelink/SdlConnection/ISdlConnectionListener.java +++ b/base/src/main/java/com/smartdevicelink/SdlConnection/ISdlConnectionListener.java @@ -1,38 +1,40 @@ -package com.smartdevicelink.SdlConnection; - -import com.smartdevicelink.protocol.ProtocolMessage; -import com.smartdevicelink.protocol.enums.SessionType; -import com.smartdevicelink.transport.BaseTransportConfig; - -import java.util.List; - - -public interface ISdlConnectionListener { - @Deprecated - public void onTransportDisconnected(String info); - - public void onTransportDisconnected(String info, boolean availablePrimary, BaseTransportConfig transportConfig); - - - public void onTransportError(String info, Exception e); - - public void onProtocolMessageReceived(ProtocolMessage msg); - - public void onProtocolSessionStartedNACKed(SessionType sessionType, - byte sessionID, byte version, String correlationID, List<String> rejectedParams); - - public void onProtocolSessionStarted(SessionType sessionType, - byte sessionID, byte version, String correlationID, int hashID, boolean isEncrypted); - - public void onProtocolSessionEnded(SessionType sessionType, - byte sessionID, String correlationID); - - public void onProtocolSessionEndedNACKed(SessionType sessionType, - byte sessionID, String correlationID); - - public void onProtocolError(String info, Exception e); - - public void onHeartbeatTimedOut(byte sessionID); - - public void onProtocolServiceDataACK(SessionType sessionType, int dataSize, byte sessionID); -} +package com.smartdevicelink.SdlConnection;
+
+import com.smartdevicelink.protocol.ProtocolMessage;
+import com.smartdevicelink.protocol.enums.SessionType;
+import com.smartdevicelink.transport.BaseTransportConfig;
+
+import java.util.List;
+
+
+public interface ISdlConnectionListener {
+ @Deprecated
+ public void onTransportDisconnected(String info);
+
+ public void onTransportDisconnected(String info, boolean availablePrimary, BaseTransportConfig transportConfig);
+
+
+ public void onTransportError(String info, Exception e);
+
+ public void onProtocolMessageReceived(ProtocolMessage msg);
+
+ public void onProtocolSessionStartedNACKed(SessionType sessionType,
+ byte sessionID, byte version, String correlationID, List<String> rejectedParams);
+
+ public void onProtocolSessionStarted(SessionType sessionType,
+ byte sessionID, byte version, String correlationID, int hashID, boolean isEncrypted);
+
+ public void onProtocolSessionEnded(SessionType sessionType,
+ byte sessionID, String correlationID);
+
+ public void onProtocolSessionEndedNACKed(SessionType sessionType,
+ byte sessionID, String correlationID);
+
+ public void onProtocolError(String info, Exception e);
+
+ public void onHeartbeatTimedOut(byte sessionID);
+
+ public void onProtocolServiceDataACK(SessionType sessionType, int dataSize, byte sessionID);
+
+ void onAuthTokenReceived(String authToken, byte sessionID);
+}
diff --git a/base/src/main/java/com/smartdevicelink/SdlConnection/SdlSession.java b/base/src/main/java/com/smartdevicelink/SdlConnection/SdlSession.java index 1c03ea57a..76c26e1a4 100644 --- a/base/src/main/java/com/smartdevicelink/SdlConnection/SdlSession.java +++ b/base/src/main/java/com/smartdevicelink/SdlConnection/SdlSession.java @@ -19,7 +19,6 @@ import com.smartdevicelink.security.SdlSecurityBase; import com.smartdevicelink.streaming.AbstractPacketizer; import com.smartdevicelink.streaming.IStreamListener; import com.smartdevicelink.streaming.StreamPacketizer; -import com.smartdevicelink.streaming.StreamRPCPacketizer; import com.smartdevicelink.streaming.video.RTPH264Packetizer; import com.smartdevicelink.streaming.video.VideoStreamingParameters; import com.smartdevicelink.transport.BaseTransportConfig; @@ -62,7 +61,6 @@ public class SdlSession implements ISdlProtocol, ISdlConnectionListener, IStream //FIXME IHeartbeatMonitor _outgoingHeartbeatMonitor = null; //FIXME IHeartbeatMonitor _incomingHeartbeatMonitor = null; - StreamRPCPacketizer mRPCPacketizer = null; AbstractPacketizer mVideoPacketizer = null; StreamPacketizer mAudioPacketizer = null; //FIXME SdlEncoder mSdlEncoder = null; @@ -190,51 +188,7 @@ public class SdlSession implements ISdlProtocol, ISdlConnectionListener, IStream } } - public void startRPCStream(InputStream is, RPCRequest request, SessionType sType, byte rpcSessionID, byte wiproVersion) { - try { - mRPCPacketizer = new StreamRPCPacketizer(null, this, is, request, sType, rpcSessionID, wiproVersion, 0, this); - mRPCPacketizer.start(); - } catch (Exception e) { - Log.e(TAG, "Unable to start streaming:" + e.toString()); - } - } - - public OutputStream startRPCStream(RPCRequest request, SessionType sType, byte rpcSessionID, byte wiproVersion) { - try { - OutputStream os = new PipedOutputStream(); - InputStream is = new PipedInputStream((PipedOutputStream) os); - mRPCPacketizer = new StreamRPCPacketizer(null, this, is, request, sType, rpcSessionID, wiproVersion, 0, this); - mRPCPacketizer.start(); - return os; - } catch (Exception e) { - Log.e(TAG, "Unable to start streaming:" + e.toString()); - } - return null; - } - - public void pauseRPCStream() - { - if (mRPCPacketizer != null) - { - mRPCPacketizer.pause(); - } - } - - public void resumeRPCStream() - { - if (mRPCPacketizer != null) - { - mRPCPacketizer.resume(); - } - } - public void stopRPCStream() - { - if (mRPCPacketizer != null) - { - mRPCPacketizer.stop(); - } - } public boolean stopAudioStream() { @@ -483,6 +437,13 @@ public class SdlSession implements ISdlProtocol, ISdlConnectionListener, IStream + @Override + public void onAuthTokenReceived(String token, byte sessionID) { + //This is not used in the base library. Will only be used in the Android library while it has the SdlConnection class + //See onAuthTokenReceived(String token) in this class instead + + } + public void addServiceListener(SessionType serviceType, ISdlServiceListener sdlServiceListener){ if(serviceListeners == null){ serviceListeners = new HashMap<>(); @@ -682,6 +643,10 @@ public class SdlSession implements ISdlProtocol, ISdlConnectionListener, IStream } } } + @Override + public void onAuthTokenReceived(String authToken) { + this.sessionListener.onAuthTokenReceived(authToken, sessionId); + } /* Not supported methods from IProtocolListener */ public void onProtocolHeartbeat(SessionType sessionType, byte sessionID) { /* Not supported */} @@ -725,6 +690,7 @@ public class SdlSession implements ISdlProtocol, ISdlConnectionListener, IStream } + /** * Check to see if a transport is available to start/use the supplied service. * @param sessionType the session that should be checked for transport availability diff --git a/base/src/main/java/com/smartdevicelink/exception/SdlException.java b/base/src/main/java/com/smartdevicelink/exception/SdlException.java index 852406155..a67549515 100644 --- a/base/src/main/java/com/smartdevicelink/exception/SdlException.java +++ b/base/src/main/java/com/smartdevicelink/exception/SdlException.java @@ -1,47 +1,47 @@ -package com.smartdevicelink.exception; - - -public class SdlException extends Exception { - - private static final long serialVersionUID = 5922492291870772815L; - - protected Throwable detail = null; - private SdlExceptionCause _sdlExceptionCause = null; - - public SdlException(String msg, SdlExceptionCause exceptionCause) { - super(msg); - _sdlExceptionCause = exceptionCause; - } - - public SdlException(String msg, Throwable ex, SdlExceptionCause exceptionCause) { - super(msg + " --- Check inner exception for diagnostic details"); - detail = ex; - _sdlExceptionCause = exceptionCause; - } - - public SdlException(Throwable ex) { - super(ex.getMessage()); - detail = ex; - } - - public SdlExceptionCause getSdlExceptionCause() { - return _sdlExceptionCause; - } - - public Throwable getInnerException() { - return detail; - } - - public String toString() { - String ret = this.getClass().getName(); - ret += ": " + this.getMessage(); - if(this.getSdlExceptionCause() != null){ - ret += "\nSdlExceptionCause: " + this.getSdlExceptionCause().name(); - } - if (detail != null) { - ret += "\nnested: " + detail.toString(); - detail.printStackTrace(); - } - return ret; - } -} +package com.smartdevicelink.exception;
+
+
+public class SdlException extends Exception {
+
+ private static final long serialVersionUID = 5922492291870772815L;
+
+ protected Throwable detail = null;
+ private SdlExceptionCause _sdlExceptionCause = null;
+
+ public SdlException(String msg, SdlExceptionCause exceptionCause) {
+ super(msg);
+ _sdlExceptionCause = exceptionCause;
+ }
+
+ public SdlException(String msg, Throwable ex, SdlExceptionCause exceptionCause) {
+ super(msg + " --- Check inner exception for diagnostic details");
+ detail = ex;
+ _sdlExceptionCause = exceptionCause;
+ }
+
+ public SdlException(Throwable ex) {
+ super(ex.getMessage());
+ detail = ex;
+ }
+
+ public SdlExceptionCause getSdlExceptionCause() {
+ return _sdlExceptionCause;
+ }
+
+ public Throwable getInnerException() {
+ return detail;
+ }
+
+ public String toString() {
+ String ret = this.getClass().getName();
+ ret += ": " + this.getMessage();
+ if(this.getSdlExceptionCause() != null){
+ ret += "\nSdlExceptionCause: " + this.getSdlExceptionCause().name();
+ }
+ if (detail != null) {
+ ret += "\nnested: " + detail.toString();
+ detail.printStackTrace();
+ }
+ return ret;
+ }
+}
diff --git a/base/src/main/java/com/smartdevicelink/exception/SdlExceptionCause.java b/base/src/main/java/com/smartdevicelink/exception/SdlExceptionCause.java index ee5ea8c9f..4894ceca3 100644 --- a/base/src/main/java/com/smartdevicelink/exception/SdlExceptionCause.java +++ b/base/src/main/java/com/smartdevicelink/exception/SdlExceptionCause.java @@ -1,25 +1,25 @@ -package com.smartdevicelink.exception; - -public enum SdlExceptionCause { - BLUETOOTH_ADAPTER_NULL, - BLUETOOTH_DISABLED, - BLUETOOTH_SOCKET_UNAVAILABLE, - HEARTBEAT_PAST_DUE, - INCORRECT_LIFECYCLE_MODEL, - INVALID_ARGUMENT, - INVALID_RPC_PARAMETER, - PERMISSION_DENIED, - RESERVED_CORRELATION_ID, - SDL_CONNECTION_FAILED, - SDL_PROXY_CYCLED, - SDL_PROXY_DISPOSED, - SDL_PROXY_OBSOLETE, - SDL_REGISTRATION_ERROR, - SDL_UNAVAILABLE, - INVALID_HEADER, - DATA_BUFFER_NULL, - SDL_USB_DETACHED, - SDL_USB_PERMISSION_DENIED, - LOCK_SCREEN_ICON_NOT_SUPPORTED, - ; -} +package com.smartdevicelink.exception;
+
+public enum SdlExceptionCause {
+ BLUETOOTH_ADAPTER_NULL,
+ BLUETOOTH_DISABLED,
+ BLUETOOTH_SOCKET_UNAVAILABLE,
+ HEARTBEAT_PAST_DUE,
+ INCORRECT_LIFECYCLE_MODEL,
+ INVALID_ARGUMENT,
+ INVALID_RPC_PARAMETER,
+ PERMISSION_DENIED,
+ RESERVED_CORRELATION_ID,
+ SDL_CONNECTION_FAILED,
+ SDL_PROXY_CYCLED,
+ SDL_PROXY_DISPOSED,
+ SDL_PROXY_OBSOLETE,
+ SDL_REGISTRATION_ERROR,
+ SDL_UNAVAILABLE,
+ INVALID_HEADER,
+ DATA_BUFFER_NULL,
+ SDL_USB_DETACHED,
+ SDL_USB_PERMISSION_DENIED,
+ LOCK_SCREEN_ICON_NOT_SUPPORTED,
+ ;
+}
diff --git a/base/src/main/java/com/smartdevicelink/marshal/JsonRPCMarshaller.java b/base/src/main/java/com/smartdevicelink/marshal/JsonRPCMarshaller.java index 493c21cee..89f4d1ef7 100644 --- a/base/src/main/java/com/smartdevicelink/marshal/JsonRPCMarshaller.java +++ b/base/src/main/java/com/smartdevicelink/marshal/JsonRPCMarshaller.java @@ -1,127 +1,127 @@ -package com.smartdevicelink.marshal; - -import java.util.ArrayList; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.List; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import com.smartdevicelink.proxy.RPCMessage; -import com.smartdevicelink.proxy.RPCStruct; -import com.smartdevicelink.trace.*; -import com.smartdevicelink.trace.enums.InterfaceActivityDirection; -import com.smartdevicelink.util.DebugTool; - -/* - * Responsible for marshalling and unmarshing between RPC Objects and byte streams that are sent - * over transmission - */ - -public class JsonRPCMarshaller { - - private static final String SDL_LIB_PRIVATE_KEY = "42baba60-eb57-11df-98cf-0800200c9a66"; - - /** - * @param msg RPC message to be marshaled - * @param version protocol version - * @return byte array of the marshalled message - */ - public static byte[] marshall(RPCMessage msg, byte version) { - byte[] jsonBytes = null; - try { - JSONObject jsonObject = msg.serializeJSON(version); - jsonBytes = jsonObject.toString().getBytes(); - - SdlTrace.logMarshallingEvent(InterfaceActivityDirection.Transmit, jsonBytes, SDL_LIB_PRIVATE_KEY); - } catch (JSONException e) { - DebugTool.logError("Failed to encode messages to JSON.", e); - } - return jsonBytes; - } - - public static Hashtable<String, Object> unmarshall(byte[] message) { - SdlTrace.logMarshallingEvent(InterfaceActivityDirection.Receive, message, SDL_LIB_PRIVATE_KEY); - Hashtable<String, Object> ret = null; - try { - String jsonString = new String(message); - JSONObject jsonObject = new JSONObject(jsonString); - ret = deserializeJSONObject(jsonObject); - } catch (JSONException e) { - DebugTool.logError("Failed to parse JSON", e); - } - return ret; - } - - @SuppressWarnings("unchecked") - public static Hashtable<String, Object> deserializeJSONObject(JSONObject jsonObject) - throws JSONException { - Hashtable<String, Object> ret = new Hashtable<String, Object>(); - Iterator<String> it = jsonObject.keys(); - String key = null; - while (it.hasNext()) { - key = it.next(); - Object value = jsonObject.get(key); - if (value instanceof JSONObject) { - ret.put(key, deserializeJSONObject((JSONObject)value)); - } else if (value instanceof JSONArray) { - JSONArray arrayValue = (JSONArray) value; - List<Object> putList = new ArrayList<Object>(arrayValue.length()); - for (int i = 0; i < arrayValue.length(); i++) { - Object anObject = arrayValue.get(i); - if (anObject instanceof JSONObject) { - Hashtable<String, Object> deserializedObject = deserializeJSONObject((JSONObject)anObject); - putList.add(deserializedObject); - } else { - putList.add(anObject); - } - } - ret.put(key, putList); - } else { - ret.put(key, value); - } - } - return ret; - } - - @SuppressWarnings("unchecked" ) - private static JSONArray serializeList(List<?> list) throws JSONException{ - JSONArray toPut = new JSONArray(); - Iterator<Object> valueIterator = (Iterator<Object>) list.iterator(); - while(valueIterator.hasNext()){ - Object anObject = valueIterator.next(); - if (anObject instanceof RPCStruct) { - RPCStruct toSerialize = (RPCStruct) anObject; - toPut.put(toSerialize.serializeJSON()); - } else if(anObject instanceof Hashtable){ - Hashtable<String, Object> toSerialize = (Hashtable<String, Object>)anObject; - toPut.put(serializeHashtable(toSerialize)); - } else { - toPut.put(anObject); - } - } - return toPut; - } - - @SuppressWarnings({"unchecked" }) - public static JSONObject serializeHashtable(Hashtable<String, Object> hash) throws JSONException{ - JSONObject obj = new JSONObject(); - Iterator<String> hashKeyIterator = hash.keySet().iterator(); - while (hashKeyIterator.hasNext()){ - String key = (String) hashKeyIterator.next(); - Object value = hash.get(key); - if (value instanceof RPCStruct) { - obj.put(key, ((RPCStruct) value).serializeJSON()); - } else if (value instanceof List<?>) { - obj.put(key, serializeList((List<?>) value)); - } else if (value instanceof Hashtable) { - obj.put(key, serializeHashtable((Hashtable<String, Object>)value)); - } else { - obj.put(key, value); - } - } - return obj; - } -} +package com.smartdevicelink.marshal;
+
+import java.util.ArrayList;
+import java.util.Hashtable;
+import java.util.Iterator;
+import java.util.List;
+
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import com.smartdevicelink.proxy.RPCMessage;
+import com.smartdevicelink.proxy.RPCStruct;
+import com.smartdevicelink.trace.*;
+import com.smartdevicelink.trace.enums.InterfaceActivityDirection;
+import com.smartdevicelink.util.DebugTool;
+
+/*
+ * Responsible for marshalling and unmarshing between RPC Objects and byte streams that are sent
+ * over transmission
+ */
+
+public class JsonRPCMarshaller {
+
+ private static final String SDL_LIB_PRIVATE_KEY = "42baba60-eb57-11df-98cf-0800200c9a66";
+
+ /**
+ * @param msg RPC message to be marshaled
+ * @param version protocol version
+ * @return byte array of the marshalled message
+ */
+ public static byte[] marshall(RPCMessage msg, byte version) {
+ byte[] jsonBytes = null;
+ try {
+ JSONObject jsonObject = msg.serializeJSON(version);
+ jsonBytes = jsonObject.toString().getBytes();
+
+ SdlTrace.logMarshallingEvent(InterfaceActivityDirection.Transmit, jsonBytes, SDL_LIB_PRIVATE_KEY);
+ } catch (JSONException e) {
+ DebugTool.logError("Failed to encode messages to JSON.", e);
+ }
+ return jsonBytes;
+ }
+
+ public static Hashtable<String, Object> unmarshall(byte[] message) {
+ SdlTrace.logMarshallingEvent(InterfaceActivityDirection.Receive, message, SDL_LIB_PRIVATE_KEY);
+ Hashtable<String, Object> ret = null;
+ try {
+ String jsonString = new String(message);
+ JSONObject jsonObject = new JSONObject(jsonString);
+ ret = deserializeJSONObject(jsonObject);
+ } catch (JSONException e) {
+ DebugTool.logError("Failed to parse JSON", e);
+ }
+ return ret;
+ }
+
+ @SuppressWarnings("unchecked")
+ public static Hashtable<String, Object> deserializeJSONObject(JSONObject jsonObject)
+ throws JSONException {
+ Hashtable<String, Object> ret = new Hashtable<String, Object>();
+ Iterator<String> it = jsonObject.keys();
+ String key = null;
+ while (it.hasNext()) {
+ key = it.next();
+ Object value = jsonObject.get(key);
+ if (value instanceof JSONObject) {
+ ret.put(key, deserializeJSONObject((JSONObject)value));
+ } else if (value instanceof JSONArray) {
+ JSONArray arrayValue = (JSONArray) value;
+ List<Object> putList = new ArrayList<Object>(arrayValue.length());
+ for (int i = 0; i < arrayValue.length(); i++) {
+ Object anObject = arrayValue.get(i);
+ if (anObject instanceof JSONObject) {
+ Hashtable<String, Object> deserializedObject = deserializeJSONObject((JSONObject)anObject);
+ putList.add(deserializedObject);
+ } else {
+ putList.add(anObject);
+ }
+ }
+ ret.put(key, putList);
+ } else {
+ ret.put(key, value);
+ }
+ }
+ return ret;
+ }
+
+ @SuppressWarnings("unchecked" )
+ private static JSONArray serializeList(List<?> list) throws JSONException{
+ JSONArray toPut = new JSONArray();
+ Iterator<Object> valueIterator = (Iterator<Object>) list.iterator();
+ while(valueIterator.hasNext()){
+ Object anObject = valueIterator.next();
+ if (anObject instanceof RPCStruct) {
+ RPCStruct toSerialize = (RPCStruct) anObject;
+ toPut.put(toSerialize.serializeJSON());
+ } else if(anObject instanceof Hashtable){
+ Hashtable<String, Object> toSerialize = (Hashtable<String, Object>)anObject;
+ toPut.put(serializeHashtable(toSerialize));
+ } else {
+ toPut.put(anObject);
+ }
+ }
+ return toPut;
+ }
+
+ @SuppressWarnings({"unchecked" })
+ public static JSONObject serializeHashtable(Hashtable<String, Object> hash) throws JSONException{
+ JSONObject obj = new JSONObject();
+ Iterator<String> hashKeyIterator = hash.keySet().iterator();
+ while (hashKeyIterator.hasNext()){
+ String key = (String) hashKeyIterator.next();
+ Object value = hash.get(key);
+ if (value instanceof RPCStruct) {
+ obj.put(key, ((RPCStruct) value).serializeJSON());
+ } else if (value instanceof List<?>) {
+ obj.put(key, serializeList((List<?>) value));
+ } else if (value instanceof Hashtable) {
+ obj.put(key, serializeHashtable((Hashtable<String, Object>)value));
+ } else {
+ obj.put(key, value);
+ }
+ }
+ return obj;
+ }
+}
diff --git a/base/src/main/java/com/smartdevicelink/protocol/BinaryFrameHeader.java b/base/src/main/java/com/smartdevicelink/protocol/BinaryFrameHeader.java index f15dea3d0..5848b9f5a 100644 --- a/base/src/main/java/com/smartdevicelink/protocol/BinaryFrameHeader.java +++ b/base/src/main/java/com/smartdevicelink/protocol/BinaryFrameHeader.java @@ -1,118 +1,118 @@ -package com.smartdevicelink.protocol; - -import android.util.Log; - -import com.smartdevicelink.util.BitConverter; - -public class BinaryFrameHeader { - private static final String TAG = "BinaryFrameHeader"; - - private byte _rpcType; - private int _functionID; - private int _correlationID; - private int _jsonSize; - - private byte[] _jsonData; - private byte[] _bulkData; - - public BinaryFrameHeader() {} - - public static BinaryFrameHeader parseBinaryHeader(byte[] binHeader) { - BinaryFrameHeader msg = new BinaryFrameHeader(); - - byte RPC_Type = (byte) (binHeader[0] >>> 4); - msg.setRPCType(RPC_Type); - - int _functionID = (BitConverter.intFromByteArray(binHeader, 0) & 0x0FFFFFFF); - msg.setFunctionID(_functionID); - - int corrID = BitConverter.intFromByteArray(binHeader, 4); - msg.setCorrID(corrID); - - int _jsonSize = BitConverter.intFromByteArray(binHeader, 8); - msg.setJsonSize(_jsonSize); - - try { - if (_jsonSize > 0) { - byte[] _jsonData = new byte[_jsonSize]; - System.arraycopy(binHeader, 12, _jsonData, 0, _jsonSize); - msg.setJsonData(_jsonData); - } - - if (binHeader.length - _jsonSize - 12 > 0) { - byte[] _bulkData = new byte[binHeader.length - _jsonSize - 12]; - System.arraycopy(binHeader, 12 + _jsonSize, _bulkData, 0, _bulkData.length); - msg.setBulkData(_bulkData); - } - } catch (OutOfMemoryError|ArrayIndexOutOfBoundsException e){ - Log.e(TAG, "Unable to process data to form header"); - return null; - } - - return msg; - } - - public byte[] assembleHeaderBytes() { - int binHeader = _functionID; - // reset the 4 leftmost bits, for _rpcType - binHeader &= 0xFFFFFFFF >>> 4; - binHeader |= (_rpcType << 28); - - byte[] ret = new byte[12]; - System.arraycopy(BitConverter.intToByteArray(binHeader), 0, ret, 0, 4); - System.arraycopy(BitConverter.intToByteArray(_correlationID), 0, ret, 4, 4); - System.arraycopy(BitConverter.intToByteArray(_jsonSize), 0, ret, 8, 4); - - return ret; - } - - public byte getRPCType() { - return _rpcType; - } - - public void setRPCType(byte _rpcType) { - this._rpcType = _rpcType; - } - - public int getFunctionID() { - return _functionID; - } - - public void setFunctionID(int _functionID) { - this._functionID = _functionID; - } - - public int getCorrID() { - return _correlationID; - } - - public void setCorrID(int _correlationID) { - this._correlationID = _correlationID; - } - - public int getJsonSize() { - return _jsonSize; - } - - public void setJsonSize(int _jsonSize) { - this._jsonSize = _jsonSize; - } - - public byte[] getJsonData() { - return _jsonData; - } - - public void setJsonData(byte[] _jsonData) { - this._jsonData = new byte[this._jsonSize]; - System.arraycopy(_jsonData, 0, this._jsonData, 0, _jsonSize); - //this._jsonData = _jsonData; - } - - public byte[] getBulkData() { - return _bulkData; - } - - public void setBulkData(byte[] _bulkData) { - this._bulkData = _bulkData; - } -} +package com.smartdevicelink.protocol;
+
+import android.util.Log;
+
+import com.smartdevicelink.util.BitConverter;
+
+public class BinaryFrameHeader {
+ private static final String TAG = "BinaryFrameHeader";
+
+ private byte _rpcType;
+ private int _functionID;
+ private int _correlationID;
+ private int _jsonSize;
+
+ private byte[] _jsonData;
+ private byte[] _bulkData;
+
+ public BinaryFrameHeader() {}
+
+ public static BinaryFrameHeader parseBinaryHeader(byte[] binHeader) {
+ BinaryFrameHeader msg = new BinaryFrameHeader();
+
+ byte RPC_Type = (byte) (binHeader[0] >>> 4);
+ msg.setRPCType(RPC_Type);
+
+ int _functionID = (BitConverter.intFromByteArray(binHeader, 0) & 0x0FFFFFFF);
+ msg.setFunctionID(_functionID);
+
+ int corrID = BitConverter.intFromByteArray(binHeader, 4);
+ msg.setCorrID(corrID);
+
+ int _jsonSize = BitConverter.intFromByteArray(binHeader, 8);
+ msg.setJsonSize(_jsonSize);
+
+ try {
+ if (_jsonSize > 0) {
+ byte[] _jsonData = new byte[_jsonSize];
+ System.arraycopy(binHeader, 12, _jsonData, 0, _jsonSize);
+ msg.setJsonData(_jsonData);
+ }
+
+ if (binHeader.length - _jsonSize - 12 > 0) {
+ byte[] _bulkData = new byte[binHeader.length - _jsonSize - 12];
+ System.arraycopy(binHeader, 12 + _jsonSize, _bulkData, 0, _bulkData.length);
+ msg.setBulkData(_bulkData);
+ }
+ } catch (OutOfMemoryError|ArrayIndexOutOfBoundsException e){
+ Log.e(TAG, "Unable to process data to form header");
+ return null;
+ }
+
+ return msg;
+ }
+
+ public byte[] assembleHeaderBytes() {
+ int binHeader = _functionID;
+ // reset the 4 leftmost bits, for _rpcType
+ binHeader &= 0xFFFFFFFF >>> 4;
+ binHeader |= (_rpcType << 28);
+
+ byte[] ret = new byte[12];
+ System.arraycopy(BitConverter.intToByteArray(binHeader), 0, ret, 0, 4);
+ System.arraycopy(BitConverter.intToByteArray(_correlationID), 0, ret, 4, 4);
+ System.arraycopy(BitConverter.intToByteArray(_jsonSize), 0, ret, 8, 4);
+
+ return ret;
+ }
+
+ public byte getRPCType() {
+ return _rpcType;
+ }
+
+ public void setRPCType(byte _rpcType) {
+ this._rpcType = _rpcType;
+ }
+
+ public int getFunctionID() {
+ return _functionID;
+ }
+
+ public void setFunctionID(int _functionID) {
+ this._functionID = _functionID;
+ }
+
+ public int getCorrID() {
+ return _correlationID;
+ }
+
+ public void setCorrID(int _correlationID) {
+ this._correlationID = _correlationID;
+ }
+
+ public int getJsonSize() {
+ return _jsonSize;
+ }
+
+ public void setJsonSize(int _jsonSize) {
+ this._jsonSize = _jsonSize;
+ }
+
+ public byte[] getJsonData() {
+ return _jsonData;
+ }
+
+ public void setJsonData(byte[] _jsonData) {
+ this._jsonData = new byte[this._jsonSize];
+ System.arraycopy(_jsonData, 0, this._jsonData, 0, _jsonSize);
+ //this._jsonData = _jsonData;
+ }
+
+ public byte[] getBulkData() {
+ return _bulkData;
+ }
+
+ public void setBulkData(byte[] _bulkData) {
+ this._bulkData = _bulkData;
+ }
+}
diff --git a/base/src/main/java/com/smartdevicelink/protocol/IProtocolListener.java b/base/src/main/java/com/smartdevicelink/protocol/IProtocolListener.java index 6a4065707..e0c6808e1 100644 --- a/base/src/main/java/com/smartdevicelink/protocol/IProtocolListener.java +++ b/base/src/main/java/com/smartdevicelink/protocol/IProtocolListener.java @@ -1,44 +1,44 @@ -package com.smartdevicelink.protocol; - - -import com.smartdevicelink.protocol.enums.*; - -import java.util.List; - -public interface IProtocolListener { - // Called to indicate that these bytes are to be sent as part of a message. - // This call includes the part of the message. - void onProtocolMessageBytesToSend(SdlPacket packet); - - // Called to indicate that a complete message (RPC, BULK, etc.) has been - // received. This call includes the message. - void onProtocolMessageReceived(ProtocolMessage msg); - - // Called to indicate that a protocol session has been started (from either side) - void onProtocolSessionStarted(SessionType sessionType, byte sessionID, byte version, String correlationID, int hashID, boolean isEncrypted); - - void onProtocolSessionNACKed(SessionType sessionType, byte sessionID, byte version, - String correlationID, List<String> rejectedParams); - - // Called to indicate that a protocol session has ended (from either side) - void onProtocolSessionEnded(SessionType sessionType, byte sessionID, String correlationID /*, String info, Exception ex*/); - - void onProtocolSessionEndedNACKed(SessionType sessionType, byte sessionID, String correlationID /*, String info, Exception ex*/); - - void onProtocolHeartbeat(SessionType sessionType, byte sessionID); - - /** - * Called when a protocol heartbeat ACK message has been received from SDL. - */ - void onProtocolHeartbeatACK(SessionType sessionType, byte sessionID); - - void onProtocolServiceDataACK(SessionType sessionType, int dataSize, byte sessionID); - - void onResetOutgoingHeartbeat(SessionType sessionType, byte sessionID); - - void onResetIncomingHeartbeat(SessionType sessionType, byte sessionID); - - // Called to indicate that a protocol error was detected in received data. - void onProtocolError(String info, Exception e); - -} // end-interfCe +package com.smartdevicelink.protocol;
+
+
+import com.smartdevicelink.protocol.enums.*;
+
+import java.util.List;
+
+public interface IProtocolListener {
+ // Called to indicate that these bytes are to be sent as part of a message.
+ // This call includes the part of the message.
+ void onProtocolMessageBytesToSend(SdlPacket packet);
+
+ // Called to indicate that a complete message (RPC, BULK, etc.) has been
+ // received. This call includes the message.
+ void onProtocolMessageReceived(ProtocolMessage msg);
+
+ // Called to indicate that a protocol session has been started (from either side)
+ void onProtocolSessionStarted(SessionType sessionType, byte sessionID, byte version, String correlationID, int hashID, boolean isEncrypted);
+
+ void onProtocolSessionNACKed(SessionType sessionType, byte sessionID, byte version,
+ String correlationID, List<String> rejectedParams);
+
+ // Called to indicate that a protocol session has ended (from either side)
+ void onProtocolSessionEnded(SessionType sessionType, byte sessionID, String correlationID /*, String info, Exception ex*/);
+
+ void onProtocolSessionEndedNACKed(SessionType sessionType, byte sessionID, String correlationID /*, String info, Exception ex*/);
+
+ void onProtocolHeartbeat(SessionType sessionType, byte sessionID);
+
+ /**
+ * Called when a protocol heartbeat ACK message has been received from SDL.
+ */
+ void onProtocolHeartbeatACK(SessionType sessionType, byte sessionID);
+
+ void onProtocolServiceDataACK(SessionType sessionType, int dataSize, byte sessionID);
+
+ void onResetOutgoingHeartbeat(SessionType sessionType, byte sessionID);
+
+ void onResetIncomingHeartbeat(SessionType sessionType, byte sessionID);
+
+ // Called to indicate that a protocol error was detected in received data.
+ void onProtocolError(String info, Exception e);
+
+} // end-interfCe
diff --git a/base/src/main/java/com/smartdevicelink/protocol/ISdlProtocol.java b/base/src/main/java/com/smartdevicelink/protocol/ISdlProtocol.java index 2e9dcb492..9875178f1 100644 --- a/base/src/main/java/com/smartdevicelink/protocol/ISdlProtocol.java +++ b/base/src/main/java/com/smartdevicelink/protocol/ISdlProtocol.java @@ -44,7 +44,7 @@ public interface ISdlProtocol extends IProtocolListener { void shutdown(String info); - void onTransportDisconnected(String info, boolean altTransportAvailable, BaseTransportConfig transportConfig); //FIXME config + void onTransportDisconnected(String info, boolean altTransportAvailable, BaseTransportConfig transportConfig); SdlSecurityBase getSdlSecurity(); @@ -53,4 +53,6 @@ public interface ISdlProtocol extends IProtocolListener { void setAcceptedVideoParams(VideoStreamingParameters acceptedVideoParams); void stopStream(SessionType serviceType); + + void onAuthTokenReceived(String authToken); } diff --git a/base/src/main/java/com/smartdevicelink/protocol/ProtocolMessage.java b/base/src/main/java/com/smartdevicelink/protocol/ProtocolMessage.java index 6fbbb0053..cb5ad3a74 100644 --- a/base/src/main/java/com/smartdevicelink/protocol/ProtocolMessage.java +++ b/base/src/main/java/com/smartdevicelink/protocol/ProtocolMessage.java @@ -1,151 +1,151 @@ -package com.smartdevicelink.protocol; - -import com.smartdevicelink.protocol.enums.MessageType; -import com.smartdevicelink.protocol.enums.SessionType; - -public class ProtocolMessage { - private byte version = 1; - private SessionType _sessionType = SessionType.RPC; - private MessageType _messageType = MessageType.UNDEFINED; - private byte _sessionID = 0; - private byte _rpcType; - private int _functionID; - private int _correlationID; - private int _jsonSize; - private boolean payloadProtected = false; - - int priorityCoefficient = 0; - - private byte[] _data = null; - private byte[] _bulkData = null; - - public ProtocolMessage() {} - - public byte getVersion() { - return version; - } - - public void setVersion(byte version) { - this.version = version; - } - - public byte getSessionID() { - return _sessionID; - } - - public void setSessionID(byte sessionID) { - this._sessionID = sessionID; - } - - public byte[] getData() { - return _data; - } - - public void setData(byte[] data) { - this._data = data; - this._jsonSize = data.length; - } - - public void setData(byte[] data, int length) { - setData(data, 0, length); - } - - public void setData(byte[] data, int offset, int length) { - if (this._data != null) - this._data = null; - this._data = new byte[length]; - System.arraycopy(data, offset, this._data, 0, length); - this._jsonSize = 0; - } - - public byte[] getBulkData() { - return _bulkData; - } - - public void setBulkDataNoCopy(byte[] bulkData) { - this._bulkData = bulkData; - } - - public void setBulkData(byte[] bulkData) { - if (this._bulkData != null) - this._bulkData = null; - this._bulkData = new byte[bulkData.length]; - System.arraycopy(bulkData, 0, this._bulkData, 0, bulkData.length); - //this._bulkData = bulkData; - } - - public void setBulkData(byte[] bulkData, int length) { - if (this._bulkData != null) - this._bulkData = null; - this._bulkData = new byte[length]; - System.arraycopy(bulkData, 0, this._bulkData, 0, length); - //this._bulkData = bulkData; - } - - public SessionType getSessionType() { - return _sessionType; - } - - public void setSessionType(SessionType sessionType) { - this._sessionType = sessionType; - } - - public MessageType getMessageType() { - return _messageType; - } - - public void setMessageType(MessageType messageType) { - this._messageType = messageType; - } - - public byte getRPCType() { - return _rpcType; - } - - public void setRPCType(byte _rpcType) { - this._rpcType = _rpcType; - } - - public int getFunctionID() { - return _functionID; - } - - public void setFunctionID(int _functionID) { - this._functionID = _functionID; - } - - public int getCorrID() { - return _correlationID; - } - - public void setCorrID(int _correlationID) { - this._correlationID = _correlationID; - } - - public int getJsonSize() { - return _jsonSize; - } - - public void setJsonSize(int _jsonSize) { - this._jsonSize = _jsonSize; - } - - public void setPayloadProtected(boolean bVal) { - payloadProtected = bVal; - } - - public boolean getPayloadProtected() { - return payloadProtected; - } - - /** - * Set the priority for this packet. The lower the number the higher the priority. <br>0 is the highest priority and the default. - * @param priority - */ - public void setPriorityCoefficient(int priority){ - this.priorityCoefficient = priority; - } - public int getPrioirtyCoefficient(){ - return this.priorityCoefficient; - } +package com.smartdevicelink.protocol;
+
+import com.smartdevicelink.protocol.enums.MessageType;
+import com.smartdevicelink.protocol.enums.SessionType;
+
+public class ProtocolMessage {
+ private byte version = 1;
+ private SessionType _sessionType = SessionType.RPC;
+ private MessageType _messageType = MessageType.UNDEFINED;
+ private byte _sessionID = 0;
+ private byte _rpcType;
+ private int _functionID;
+ private int _correlationID;
+ private int _jsonSize;
+ private boolean payloadProtected = false;
+
+ int priorityCoefficient = 0;
+
+ private byte[] _data = null;
+ private byte[] _bulkData = null;
+
+ public ProtocolMessage() {}
+
+ public byte getVersion() {
+ return version;
+ }
+
+ public void setVersion(byte version) {
+ this.version = version;
+ }
+
+ public byte getSessionID() {
+ return _sessionID;
+ }
+
+ public void setSessionID(byte sessionID) {
+ this._sessionID = sessionID;
+ }
+
+ public byte[] getData() {
+ return _data;
+ }
+
+ public void setData(byte[] data) {
+ this._data = data;
+ this._jsonSize = data.length;
+ }
+
+ public void setData(byte[] data, int length) {
+ setData(data, 0, length);
+ }
+
+ public void setData(byte[] data, int offset, int length) {
+ if (this._data != null)
+ this._data = null;
+ this._data = new byte[length];
+ System.arraycopy(data, offset, this._data, 0, length);
+ this._jsonSize = 0;
+ }
+
+ public byte[] getBulkData() {
+ return _bulkData;
+ }
+
+ public void setBulkDataNoCopy(byte[] bulkData) {
+ this._bulkData = bulkData;
+ }
+
+ public void setBulkData(byte[] bulkData) {
+ if (this._bulkData != null)
+ this._bulkData = null;
+ this._bulkData = new byte[bulkData.length];
+ System.arraycopy(bulkData, 0, this._bulkData, 0, bulkData.length);
+ //this._bulkData = bulkData;
+ }
+
+ public void setBulkData(byte[] bulkData, int length) {
+ if (this._bulkData != null)
+ this._bulkData = null;
+ this._bulkData = new byte[length];
+ System.arraycopy(bulkData, 0, this._bulkData, 0, length);
+ //this._bulkData = bulkData;
+ }
+
+ public SessionType getSessionType() {
+ return _sessionType;
+ }
+
+ public void setSessionType(SessionType sessionType) {
+ this._sessionType = sessionType;
+ }
+
+ public MessageType getMessageType() {
+ return _messageType;
+ }
+
+ public void setMessageType(MessageType messageType) {
+ this._messageType = messageType;
+ }
+
+ public byte getRPCType() {
+ return _rpcType;
+ }
+
+ public void setRPCType(byte _rpcType) {
+ this._rpcType = _rpcType;
+ }
+
+ public int getFunctionID() {
+ return _functionID;
+ }
+
+ public void setFunctionID(int _functionID) {
+ this._functionID = _functionID;
+ }
+
+ public int getCorrID() {
+ return _correlationID;
+ }
+
+ public void setCorrID(int _correlationID) {
+ this._correlationID = _correlationID;
+ }
+
+ public int getJsonSize() {
+ return _jsonSize;
+ }
+
+ public void setJsonSize(int _jsonSize) {
+ this._jsonSize = _jsonSize;
+ }
+
+ public void setPayloadProtected(boolean bVal) {
+ payloadProtected = bVal;
+ }
+
+ public boolean getPayloadProtected() {
+ return payloadProtected;
+ }
+
+ /**
+ * Set the priority for this packet. The lower the number the higher the priority. <br>0 is the highest priority and the default.
+ * @param priority
+ */
+ public void setPriorityCoefficient(int priority){
+ this.priorityCoefficient = priority;
+ }
+ public int getPrioirtyCoefficient(){
+ return this.priorityCoefficient;
+ }
} // end-class
\ No newline at end of file diff --git a/base/src/main/java/com/smartdevicelink/protocol/SdlPacket.java b/base/src/main/java/com/smartdevicelink/protocol/SdlPacket.java index 40ec54fb5..be7eec1fc 100644 --- a/base/src/main/java/com/smartdevicelink/protocol/SdlPacket.java +++ b/base/src/main/java/com/smartdevicelink/protocol/SdlPacket.java @@ -5,14 +5,26 @@ import java.util.HashMap; import com.livio.BSON.BsonEncoder; import com.smartdevicelink.protocol.enums.FrameType; -import com.smartdevicelink.transport.enums.TransportType; import com.smartdevicelink.transport.utl.TransportRecord; import android.os.Parcel; import android.os.Parcelable; +/** + * This class is only intended to be parcelable from the transport broker to the SDL Router Service. + * Any other binder transactions must include an additional int flag into their bundle or the parsing + * of this object will fail. + */ public class SdlPacket implements Parcelable{ + /** + * This is the amount of bytes added to the bundle from the router service for a specific int + * flag; this data will always and must be included. This flag is the + * TransportConstants.BYTES_TO_SEND_FLAGS. + * + * @see com.smartdevicelink.transport.TransportConstants#BYTES_TO_SEND_FLAGS + */ + private static final int EXTRA_PARCEL_DATA_LENGTH = 24; public static final int HEADER_SIZE = 12; public static final int HEADER_SIZE_V1 = 8;//Backwards @@ -62,7 +74,7 @@ public class SdlPacket implements Parcelable{ //Most others public static final int FRAME_INFO_RESERVED = 0x00; - + int version; boolean encryption; int frameType; @@ -342,12 +354,16 @@ public class SdlPacket implements Parcelable{ this.priorityCoefficient = p.readInt(); - if(p.dataAvail() > 0) { - messagingVersion = p.readInt(); - if(messagingVersion >= 2) { - if (p.readInt() == 1) { //We should have a transport type attached - this.transportRecord = (TransportRecord) p.readParcelable(TransportRecord.class.getClassLoader()); + if(p.dataAvail() > EXTRA_PARCEL_DATA_LENGTH) { //See note on constant for why not 0 + try { + messagingVersion = p.readInt(); + if (messagingVersion >= 2) { + if (p.readInt() == 1) { //We should have a transport type attached + this.transportRecord = (TransportRecord) p.readParcelable(TransportRecord.class.getClassLoader()); + } } + }catch (RuntimeException e){ + } } } diff --git a/base/src/main/java/com/smartdevicelink/protocol/SdlPacketFactory.java b/base/src/main/java/com/smartdevicelink/protocol/SdlPacketFactory.java index 31898175c..5a8500336 100644 --- a/base/src/main/java/com/smartdevicelink/protocol/SdlPacketFactory.java +++ b/base/src/main/java/com/smartdevicelink/protocol/SdlPacketFactory.java @@ -1,7 +1,9 @@ package com.smartdevicelink.protocol; +import com.smartdevicelink.protocol.enums.ControlFrameTags; import com.smartdevicelink.protocol.enums.FrameDataControlFrameType; import com.smartdevicelink.protocol.enums.SessionType; +import com.smartdevicelink.util.BitConverter; public class SdlPacketFactory { @@ -53,6 +55,21 @@ public class SdlPacketFactory { payload.length,messageID,payload); } + public static SdlPacket createEndSession(SessionType serviceType, byte sessionID, int messageID, byte version, int hashID) { + if (version < 5) { + byte[] payload = BitConverter.intToByteArray(hashID); + return new SdlPacket(version, false, SdlPacket.FRAME_TYPE_CONTROL, + serviceType.getValue(), SdlPacket.FRAME_INFO_END_SERVICE, sessionID, + payload.length, messageID, payload); + } else { + SdlPacket endSession = new SdlPacket(version, false, SdlPacket.FRAME_TYPE_CONTROL, + serviceType.getValue(), SdlPacket.FRAME_INFO_END_SERVICE, sessionID, + 0, messageID, null); + endSession.putTag(ControlFrameTags.RPC.EndService.HASH_ID, hashID); + return endSession; + } + } + public static SdlPacket createSingleSendData(SessionType serviceType, byte sessionID, int dataLength, int messageID, byte version, byte[] payload, boolean encrypted) { diff --git a/base/src/main/java/com/smartdevicelink/protocol/SdlProtocol.java b/base/src/main/java/com/smartdevicelink/protocol/SdlProtocol.java index 52feaadaa..b160bf0d2 100644 --- a/base/src/main/java/com/smartdevicelink/protocol/SdlProtocol.java +++ b/base/src/main/java/com/smartdevicelink/protocol/SdlProtocol.java @@ -32,1401 +32,20 @@ package com.smartdevicelink.protocol; -import android.util.Log; -import com.smartdevicelink.exception.SdlException; -import com.smartdevicelink.exception.SdlExceptionCause; -import com.smartdevicelink.protocol.enums.ControlFrameTags; -import com.smartdevicelink.protocol.enums.FrameDataControlFrameType; -import com.smartdevicelink.protocol.enums.FrameType; -import com.smartdevicelink.protocol.enums.MessageType; -import com.smartdevicelink.protocol.enums.SessionType; -import com.smartdevicelink.proxy.rpc.ImageResolution; -import com.smartdevicelink.proxy.rpc.VideoStreamingFormat; -import com.smartdevicelink.proxy.rpc.enums.VideoStreamingCodec; -import com.smartdevicelink.proxy.rpc.enums.VideoStreamingProtocol; -import com.smartdevicelink.security.SdlSecurityBase; -import com.smartdevicelink.streaming.video.VideoStreamingParameters; -import com.smartdevicelink.transport.TransportConstants; import com.smartdevicelink.transport.TransportManager; import com.smartdevicelink.transport.WebSocketServerConfig; -import com.smartdevicelink.transport.enums.TransportType; -import com.smartdevicelink.transport.utl.TransportRecord; -import com.smartdevicelink.util.BitConverter; -import com.smartdevicelink.util.DebugTool; -import com.smartdevicelink.util.Version; -import java.io.ByteArrayOutputStream; -import java.util.*; @SuppressWarnings("WeakerAccess") -public class SdlProtocol { +public class SdlProtocol extends SdlProtocolBase { private static final String TAG ="SdlProtocol"; - private final static String FailurePropagating_Msg = "Failure propagating "; - private static final int TLS_MAX_RECORD_SIZE = 16384; - - private static final int PRIMARY_TRANSPORT_ID = 1; - private static final int SECONDARY_TRANSPORT_ID = 2; - - /** - * Original header size based on version 1.0.0 only - */ - public static final int V1_HEADER_SIZE = 8; - /** - * Larger header size that is used by versions 2.0.0 and up - */ - public static final int V2_HEADER_SIZE = 12; - - //If increasing MAX PROTOCOL VERSION major version, make sure to alter it in SdlPsm - private static final Version MAX_PROTOCOL_VERSION = new Version("5.1.0"); - - public static final int V1_V2_MTU_SIZE = 1500; - public static final int V3_V4_MTU_SIZE = 131072; - - private static final List<SessionType> HIGH_BANDWIDTH_SERVICES - = Arrays.asList(SessionType.NAV, SessionType.PCM); - - // Lock to ensure all frames are sent uninterrupted - private final Object FRAME_LOCK = new Object(); - - private final ISdlProtocol iSdlProtocol; - private final WebSocketServerConfig transportConfig; - private final Hashtable<Integer, MessageFrameAssembler> _assemblerForMessageID = new Hashtable<>(); - private final Hashtable<Byte, Object> _messageLocks = new Hashtable<>(); - private final HashMap<SessionType, Long> mtus = new HashMap<>(); - private final HashMap<SessionType, TransportRecord> activeTransports = new HashMap<>(); - private final Map<TransportType, List<ISecondaryTransportListener>> secondaryTransportListeners = new HashMap<>(); - - - private TransportManager transportManager; - private Version protocolVersion = new Version("1.0.0"); - private int hashID = 0; - private int messageID = 0; - private int headerSize = V1_HEADER_SIZE; - - /** - * Requested transports for primary and secondary - */ - List<TransportType> requestedPrimaryTransports, requestedSecondaryTransports; - - /** - * List of secondary transports supported by the module - */ - List<TransportType> supportedSecondaryTransports; - - /** - * Holds the priority of transports for a specific service when that service can be started - * on a primary or secondary transport. - */ - Map<SessionType, List<Integer>> transportPriorityForServiceMap; - boolean requiresHighBandwidth; - Map<TransportType, Object> secondaryTransportParams; - TransportRecord connectedPrimaryTransport; - - - @SuppressWarnings("ConstantConditions") - public SdlProtocol( ISdlProtocol iSdlProtocol, WebSocketServerConfig config) { //FIXME to change config - if (iSdlProtocol == null ) { - throw new IllegalArgumentException("Provided protocol listener interface reference is null"); - } // end-if - - this.iSdlProtocol = iSdlProtocol; - this.transportConfig = config; - this.requestedPrimaryTransports = Collections.singletonList(TransportType.WEB_SOCKET_SERVER); //FIXME this.transportConfig.getPrimaryTransports(); - this.requestedSecondaryTransports = Collections.emptyList();//FIXME this.transportConfig.getSecondaryTransports(); - this.requiresHighBandwidth = false; //FIXME this.transportConfig.requiresHighBandwidth(); - this.transportManager = new TransportManager(transportConfig, transportEventListener); - - - mtus.put(SessionType.RPC, (long) (V1_V2_MTU_SIZE - headerSize)); - } // end-ctor - - - public void start(){ - transportManager.start(); - - } - /** - * Retrieves the max payload size for a packet to be sent to the module - * @return the max transfer unit - */ - public int getMtu(){ - return mtus.get(SessionType.RPC).intValue(); - } - - public long getMtu(SessionType type){ - Long mtu = mtus.get(type); - if(mtu == null){ - mtu = mtus.get(SessionType.RPC); - } - return mtu; - } - - public boolean isConnected(){ - return transportManager != null && transportManager.isConnected(null,null); - } - - /** - * Resets the protocol to init status - */ - protected void reset(){ - protocolVersion = new Version("1.0.0"); - hashID = 0; - messageID = 0; - headerSize = V1_HEADER_SIZE; - this.activeTransports.clear(); - this.mtus.clear(); - mtus.put(SessionType.RPC, (long) (V1_V2_MTU_SIZE - headerSize)); - this.secondaryTransportParams = null; - this._assemblerForMessageID.clear(); - this._messageLocks.clear(); - } - - /** - * For logging purposes, prints active services on each connected transport - */ - protected void printActiveTransports(){ - StringBuilder activeTransportString = new StringBuilder(); - activeTransportString.append("Active transports --- \n"); - - for(Map.Entry entry : activeTransports.entrySet()){ - String sessionString = null; - if(entry.getKey().equals(SessionType.NAV)) { - sessionString = "NAV"; - }else if(entry.getKey().equals(SessionType.PCM)) { - sessionString = "PCM"; - }else if(entry.getKey().equals(SessionType.RPC)) { - sessionString = "RPC"; - } - if(sessionString != null){ - activeTransportString.append("Session: "); - - activeTransportString.append(sessionString); - activeTransportString.append(" Transport: "); - activeTransportString.append(entry.getValue().toString()); - activeTransportString.append("\n"); - } - } - Log.d(TAG, activeTransportString.toString()); - } - - protected void printSecondaryTransportDetails(List<String> secondary, List<Integer> audio, List<Integer> video){ - StringBuilder secondaryDetailsBldr = new StringBuilder(); - secondaryDetailsBldr.append("Checking secondary transport details \n"); - - if(secondary != null){ - secondaryDetailsBldr.append("Supported secondary transports: "); - for(String s : secondary){ - secondaryDetailsBldr.append(" ").append(s); - } - secondaryDetailsBldr.append("\n"); - }else{ - Log.d(TAG, "Supported secondary transports list is empty!"); - } - if(audio != null){ - secondaryDetailsBldr.append("Supported audio transports: "); - for(int a : audio){ - secondaryDetailsBldr.append(" ").append(a); - } - secondaryDetailsBldr.append("\n"); - } - if(video != null){ - secondaryDetailsBldr.append("Supported video transports: "); - for(int v : video){ - secondaryDetailsBldr.append(" ").append(v); - } - secondaryDetailsBldr.append("\n"); - } - - Log.d(TAG, secondaryDetailsBldr.toString()); - } - - - private TransportRecord getTransportForSession(SessionType type){ - return activeTransports.get(type); - } - - private void setTransportPriorityForService(SessionType serviceType, List<Integer> order){ - if(transportPriorityForServiceMap == null){ - transportPriorityForServiceMap = new HashMap<>(); - } - this.transportPriorityForServiceMap.put(serviceType, order); - for(SessionType service : HIGH_BANDWIDTH_SERVICES){ - if (transportPriorityForServiceMap.get(service) != null - && transportPriorityForServiceMap.get(service).contains(PRIMARY_TRANSPORT_ID)) { - if(connectedPrimaryTransport != null) { - activeTransports.put(service, connectedPrimaryTransport); - } - } - } - } - - /** - * Handles when a secondary transport can be used to start services on or when the request as failed. - * @param transportRecord the transport type that the event has taken place on - * @param registered if the transport was successfully registered on - */ - private void handleSecondaryTransportRegistration(TransportRecord transportRecord, boolean registered){ - if(registered) { - //Session has been registered on secondary transport - Log.d(TAG, transportRecord.getType().toString() + " transport was registered!"); - if (supportedSecondaryTransports.contains(transportRecord.getType())) { - // If the transport type that is now available to be used it should be checked - // against the list of services that might be able to be started on it - - for(SessionType secondaryService : HIGH_BANDWIDTH_SERVICES){ - if (transportPriorityForServiceMap.containsKey(secondaryService)) { - // If this service type has extra information from the RPC StartServiceACK - // parse through it to find which transport should be used to start this - // specific service type - for(int transportNum : transportPriorityForServiceMap.get(secondaryService)){ - if(transportNum == PRIMARY_TRANSPORT_ID){ - break; // Primary is favored for this service type, break out... - }else if(transportNum == SECONDARY_TRANSPORT_ID){ - // The secondary transport can be used to start this service - activeTransports.put(secondaryService, transportRecord); - break; - } - } - } - } - } - }else{ - Log.d(TAG, transportRecord.toString() + " transport was NOT registered!"); - } - //Notify any listeners for this secondary transport - List<ISecondaryTransportListener> listenerList = secondaryTransportListeners.remove(transportRecord.getType()); - if(listenerList != null){ - for(ISecondaryTransportListener listener : listenerList){ - if(registered) { - listener.onConnectionSuccess(transportRecord); - }else{ - listener.onConnectionFailure(); - } - } - } - - if(DebugTool.isDebugEnabled()){ - printActiveTransports(); - } - } - - private void onTransportsConnectedUpdate(List<TransportRecord> transports){ - //Log.d(TAG, "Connected transport update"); - - //Temporary: this logic should all be changed to handle multiple transports of the same type - ArrayList<TransportType> connectedTransports = new ArrayList<>(); - if(transports != null) { - for (TransportRecord record : transports) { - connectedTransports.add(record.getType()); - } - } - - if(connectedPrimaryTransport != null && !connectedTransports.contains(connectedPrimaryTransport.getType())){ - //The primary transport being used is no longer part of the connected transports - //The transport manager callbacks should handle the disconnect code - connectedPrimaryTransport = null; - notifyDevTransportListener(); - return; - } - - if(activeTransports.get(SessionType.RPC) == null){ - //There is no currently active transport for the RPC service meaning no primary transport - TransportRecord preferredPrimaryTransport = getPreferredTransport(requestedPrimaryTransports,transports); - if(preferredPrimaryTransport != null) { - connectedPrimaryTransport = preferredPrimaryTransport; - startService(SessionType.RPC, (byte) 0x00, false); - }else{ - onTransportNotAccepted("No transports match requested primary transport"); - } - //Return to that the developer does not receive the transport callback at this time - // as it is better to wait until the RPC service is registered and secondary transport - //information is available - return; - }else if(secondaryTransportListeners != null - && transports != null - && iSdlProtocol!= null){ - // Check to see if there is a listener for a given transport. - // If a listener exists, it can be assumed that the transport should be registered on - for(TransportRecord record: transports){ - if(secondaryTransportListeners.get(record.getType()) != null - && !secondaryTransportListeners.get(record.getType()).isEmpty()){ - registerSecondaryTransport(iSdlProtocol.getSessionId(), record); - } - } - } - //Update the developer that a new transport has become available - notifyDevTransportListener(); - } - - - /** - * Check to see if a transport is available to start/use the supplied service. - * @param serviceType the session that should be checked for transport availability - * @return true if there is either a supported - * transport currently connected or a transport is - * available to connect with for the supplied service type. - * <br>false if there is no - * transport connected to support the service type in question and - * no possibility in the foreseeable future. - */ - public boolean isTransportForServiceAvailable( SessionType serviceType){ - if(connectedPrimaryTransport == null){ - //If there is no connected primary then there is no transport available for any service - return false; - }else if(activeTransports!= null && activeTransports.containsKey(serviceType)){ - //There is an active transport that this service can be used on - //This should catch RPC, Bulk, and Control service types - return true; - } - - if(transportPriorityForServiceMap != null) { - List<Integer> transportPriority = transportPriorityForServiceMap.get(serviceType); - - if (transportPriority != null && !transportPriority.isEmpty()) { - if (transportPriority.contains(PRIMARY_TRANSPORT_ID)) { - //If the transport priority for this service type contains primary then - // the service can be used/started - return true; - } else if (transportPriority.contains(SECONDARY_TRANSPORT_ID)) { - //This would mean only secondary transport is supported for this service - return isSecondaryTransportAvailable(false); - } - } - } - - //No transport priority for this service type - if(connectedPrimaryTransport.getType() == TransportType.USB || connectedPrimaryTransport.getType() == TransportType.TCP){ - //Since the only service type that should reach this point are ones that require a high - //bandwidth, true can be returned if the primary transport is a high bandwidth transport - return true; - }else{ - //Since the only service type that should reach this point are ones that require a high - //bandwidth, true can be returned if a secondary transport is a high bandwidth transport - return isSecondaryTransportAvailable(true); - } - } - - /** - * Checks to see if a secondary transport is available for this session - * @param onlyHighBandwidth if only high bandwidth transports should be included in this check - * @return true if any connected or potential transport meets the criteria to be a secondary - * transport - */ - private boolean isSecondaryTransportAvailable(boolean onlyHighBandwidth){ - if (supportedSecondaryTransports != null) { - for (TransportType supportedSecondary : supportedSecondaryTransports) { - if(!onlyHighBandwidth || supportedSecondary == TransportType.USB || supportedSecondary == TransportType.TCP) { - if (transportManager.isConnected(supportedSecondary, null)) { - //A supported secondary transport is already connected - return true; - } else if (secondaryTransportParams != null && secondaryTransportParams.containsKey(supportedSecondary)) { - //A secondary transport is available to connect to - return true; - } - } - } - } - // No supported secondary transports - return false; - } - - - /** - * If there was a TransportListener attached to the supplied multiplex config, this method will - * call the onTransportEvent method. - */ - private void notifyDevTransportListener (){ - //FIXME - /* if(transportConfig.getTransportListener() != null && transportManager != null) { - transportConfig.getTransportListener().onTransportEvent(transportManager.getConnectedTransports(), isTransportForServiceAvailable(SessionType.PCM),isTransportForServiceAvailable(SessionType.NAV)); - }*/ - } - - /** - * Retrieves the preferred transport for the given connected transport - * @param preferredList the list of preferred transports (primary or secondary) - * @param connectedTransports the current list of connected transports - * @return the preferred connected transport - */ - private TransportRecord getPreferredTransport(List<TransportType> preferredList, List<TransportRecord> connectedTransports) { - for (TransportType transportType : preferredList) { - for(TransportRecord record: connectedTransports) { - if (record.getType().equals(transportType)) { - return record; - } - } - } - return null; - } - - private void onTransportNotAccepted(String info){ - if(iSdlProtocol != null) { - iSdlProtocol.shutdown(info); - } - } - - - public Version getProtocolVersion(){ - return this.protocolVersion; - } - - /** - * This method will set the major protocol version that we should use. It will also set the default MTU based on version. - * @param version major version to use - */ - protected void setVersion(byte version) { - if (version > 5) { - this.protocolVersion = new Version("5.0.0"); //protect for future, proxy only supports v5 or lower - headerSize = V2_HEADER_SIZE; - mtus.put(SessionType.RPC, (long) V3_V4_MTU_SIZE); - } else if (version == 5) { - this.protocolVersion = new Version("5.0.0"); - headerSize = V2_HEADER_SIZE; - mtus.put(SessionType.RPC, (long) V3_V4_MTU_SIZE); - }else if (version == 4) { - this.protocolVersion = new Version("4.0.0"); - headerSize = V2_HEADER_SIZE; - mtus.put(SessionType.RPC, (long) V3_V4_MTU_SIZE); //versions 4 supports 128k MTU - } else if (version == 3) { - this.protocolVersion = new Version("3.0.0"); - headerSize = V2_HEADER_SIZE; - mtus.put(SessionType.RPC, (long) V3_V4_MTU_SIZE); //versions 3 supports 128k MTU - } else if (version == 2) { - this.protocolVersion = new Version("2.0.0"); - headerSize = V2_HEADER_SIZE; - mtus.put(SessionType.RPC, (long) (V1_V2_MTU_SIZE - headerSize)); - } else if (version == 1){ - this.protocolVersion = new Version("1.0.0"); - headerSize = V1_HEADER_SIZE; - mtus.put(SessionType.RPC, (long) (V1_V2_MTU_SIZE - headerSize)); - } - } - - public void endSession(byte sessionID, int hashId) { - SdlPacket header; - if(protocolVersion.getMajor() < 5){ - header = SdlPacketFactory.createEndSession(SessionType.RPC, sessionID, hashId, (byte)protocolVersion.getMajor(), BitConverter.intToByteArray(hashId)); - }else{ - header = SdlPacketFactory.createEndSession(SessionType.RPC, sessionID, hashId, (byte)protocolVersion.getMajor(), new byte[0]); - header.putTag(ControlFrameTags.RPC.EndService.HASH_ID, hashId); - } - - handlePacketToSend(header); - - } // end-method - - public void sendPacket(SdlPacket packet){ - if(transportManager != null){ - transportManager.sendPacket(packet); - } - } - - public void sendMessage(ProtocolMessage protocolMsg) { - protocolMsg.setRPCType((byte) 0x00); //always sending a request - SessionType sessionType = protocolMsg.getSessionType(); - byte sessionID = protocolMsg.getSessionID(); - - byte[] data; - if (protocolVersion.getMajor() > 1 && sessionType != SessionType.NAV && sessionType != SessionType.PCM) { - if (sessionType.eq(SessionType.CONTROL)) { - final byte[] secureData = protocolMsg.getData().clone(); - data = new byte[headerSize + secureData.length]; - - final BinaryFrameHeader binFrameHeader = - SdlPacketFactory.createBinaryFrameHeader(protocolMsg.getRPCType(),protocolMsg.getFunctionID(), protocolMsg.getCorrID(), 0); - System.arraycopy(binFrameHeader.assembleHeaderBytes(), 0, data, 0, headerSize); - System.arraycopy(secureData, 0, data, headerSize, secureData.length); - } - else if (protocolMsg.getBulkData() != null) { - data = new byte[12 + protocolMsg.getJsonSize() + protocolMsg.getBulkData().length]; - sessionType = SessionType.BULK_DATA; - } else { - data = new byte[12 + protocolMsg.getJsonSize()]; - } - if (!sessionType.eq(SessionType.CONTROL)) { - BinaryFrameHeader binFrameHeader = SdlPacketFactory.createBinaryFrameHeader(protocolMsg.getRPCType(), protocolMsg.getFunctionID(), protocolMsg.getCorrID(), protocolMsg.getJsonSize()); - System.arraycopy(binFrameHeader.assembleHeaderBytes(), 0, data, 0, 12); - System.arraycopy(protocolMsg.getData(), 0, data, 12, protocolMsg.getJsonSize()); - if (protocolMsg.getBulkData() != null) { - System.arraycopy(protocolMsg.getBulkData(), 0, data, 12 + protocolMsg.getJsonSize(), protocolMsg.getBulkData().length); - } - } - } else { - data = protocolMsg.getData(); - } - - if (iSdlProtocol != null && protocolMsg.getPayloadProtected()){ - - if (data != null && data.length > 0) { - byte[] dataToRead = new byte[TLS_MAX_RECORD_SIZE]; - SdlSecurityBase sdlSec = iSdlProtocol.getSdlSecurity(); - if (sdlSec == null) - return; - - Integer iNumBytes = sdlSec.encryptData(data, dataToRead); - if ((iNumBytes == null) || (iNumBytes <= 0)) - return; - - byte[] encryptedData = new byte[iNumBytes]; - System.arraycopy(dataToRead, 0, encryptedData, 0, iNumBytes); - data = encryptedData; - } - } - - // Get the message lock for this protocol session - Object messageLock = _messageLocks.get(sessionID); - if (messageLock == null) { - handleProtocolError("Error sending protocol message to SDL.", - new SdlException("Attempt to send protocol message prior to startSession ACK.", SdlExceptionCause.SDL_UNAVAILABLE)); - return; - } - - synchronized(messageLock) { - if (data.length > getMtu(sessionType)) { - - messageID++; - - // Assemble first frame. - Long mtu = getMtu(sessionType); - int frameCount = Long.valueOf(data.length / mtu).intValue(); - if (data.length % mtu > 0) { - frameCount++; - } - byte[] firstFrameData = new byte[8]; - // First four bytes are data size. - System.arraycopy(BitConverter.intToByteArray(data.length), 0, firstFrameData, 0, 4); - // Second four bytes are frame count. - System.arraycopy(BitConverter.intToByteArray(frameCount), 0, firstFrameData, 4, 4); - - SdlPacket firstHeader = SdlPacketFactory.createMultiSendDataFirst(sessionType, sessionID, messageID, (byte)protocolVersion.getMajor(),firstFrameData,protocolMsg.getPayloadProtected()); - firstHeader.setPriorityCoefficient(1+protocolMsg.priorityCoefficient); - firstHeader.setTransportRecord(activeTransports.get(sessionType)); - //Send the first frame - handlePacketToSend(firstHeader); - - int currentOffset = 0; - byte frameSequenceNumber = 0; - - for (int i = 0; i < frameCount; i++) { - if (i < (frameCount - 1)) { - ++frameSequenceNumber; - if (frameSequenceNumber == - SdlPacket.FRAME_INFO_FINAL_CONNESCUTIVE_FRAME) { - // we can't use 0x00 as frameSequenceNumber, because - // it's reserved for the last frame - ++frameSequenceNumber; - } - } else { - frameSequenceNumber = SdlPacket.FRAME_INFO_FINAL_CONNESCUTIVE_FRAME; - } // end-if - - int bytesToWrite = data.length - currentOffset; - if (bytesToWrite > mtu) { - bytesToWrite = mtu.intValue(); - } - SdlPacket consecHeader = SdlPacketFactory.createMultiSendDataRest(sessionType, sessionID, bytesToWrite, frameSequenceNumber , messageID, (byte)protocolVersion.getMajor(),data, currentOffset, bytesToWrite, protocolMsg.getPayloadProtected()); - consecHeader.setTransportRecord(activeTransports.get(sessionType)); - consecHeader.setPriorityCoefficient(i+2+protocolMsg.priorityCoefficient); - handlePacketToSend(consecHeader); - currentOffset += bytesToWrite; - } - } else { - messageID++; - SdlPacket header = SdlPacketFactory.createSingleSendData(sessionType, sessionID, data.length, messageID, (byte)protocolVersion.getMajor(),data, protocolMsg.getPayloadProtected()); - header.setPriorityCoefficient(protocolMsg.priorityCoefficient); - header.setTransportRecord(activeTransports.get(sessionType)); - handlePacketToSend(header); - } - } - } - - protected void handlePacketReceived(SdlPacket packet){ - //Check for a version difference - if (protocolVersion == null || protocolVersion.getMajor() == 1) { - setVersion((byte)packet.version); - } - - MessageFrameAssembler assembler = getFrameAssemblerForFrame(packet); - assembler.handleFrame(packet); - - } - - - protected MessageFrameAssembler getFrameAssemblerForFrame(SdlPacket packet) { - Integer iSessionId = packet.getSessionId(); - Byte bySessionId = iSessionId.byteValue(); - - MessageFrameAssembler ret = _assemblerForMessageID.get(packet.getMessageId()); - if (ret == null) { - ret = new MessageFrameAssembler(); - _assemblerForMessageID.put(packet.getMessageId(), ret); - } // end-if - - return ret; - } // end-method - - - - private void registerSecondaryTransport(byte sessionId, TransportRecord transportRecord) { - SdlPacket header = SdlPacketFactory.createRegisterSecondaryTransport(sessionId, (byte)protocolVersion.getMajor()); - header.setTransportRecord(transportRecord); - handlePacketToSend(header); - } - - public void startService(SessionType serviceType, byte sessionID, boolean isEncrypted) { - final SdlPacket header = SdlPacketFactory.createStartSession(serviceType, 0x00, (byte)protocolVersion.getMajor(), sessionID, isEncrypted); - if(SessionType.RPC.equals(serviceType)){ - if(connectedPrimaryTransport != null) { - header.setTransportRecord(connectedPrimaryTransport); - } - //This is going to be our primary transport - header.putTag(ControlFrameTags.RPC.StartService.PROTOCOL_VERSION, MAX_PROTOCOL_VERSION.toString()); - handlePacketToSend(header); - return; // We don't need to go any further - }else if(serviceType.equals(SessionType.NAV)){ - if(iSdlProtocol != null){ - VideoStreamingParameters videoStreamingParameters = iSdlProtocol.getDesiredVideoParams(); - if(videoStreamingParameters != null) { - ImageResolution desiredResolution = videoStreamingParameters.getResolution(); - VideoStreamingFormat desiredFormat = videoStreamingParameters.getFormat(); - if (desiredResolution != null) { - header.putTag(ControlFrameTags.Video.StartService.WIDTH, desiredResolution.getResolutionWidth()); - header.putTag(ControlFrameTags.Video.StartService.HEIGHT, desiredResolution.getResolutionHeight()); - } - if (desiredFormat != null) { - header.putTag(ControlFrameTags.Video.StartService.VIDEO_CODEC, desiredFormat.getCodec().toString()); - header.putTag(ControlFrameTags.Video.StartService.VIDEO_PROTOCOL, desiredFormat.getProtocol().toString()); - } - } - } - } - if(transportPriorityForServiceMap == null - || transportPriorityForServiceMap.get(serviceType) == null - || transportPriorityForServiceMap.get(serviceType).isEmpty()){ - //If there is no transport priority for this service it can be assumed it's primary - header.setTransportRecord(connectedPrimaryTransport); - handlePacketToSend(header); - return; - } - int transportPriority = transportPriorityForServiceMap.get(serviceType).get(0); - if(transportPriority == PRIMARY_TRANSPORT_ID){ - // Primary is favored, and we're already connected... - header.setTransportRecord(connectedPrimaryTransport); - handlePacketToSend(header); - }else if(transportPriority == SECONDARY_TRANSPORT_ID) { - // Secondary is favored - for(TransportType secondaryTransportType : supportedSecondaryTransports) { - - if(!requestedSecondaryTransports.contains(secondaryTransportType)){ - // Secondary transport is not accepted by the client - continue; - } - - if(activeTransports.get(serviceType) != null - && activeTransports.get(serviceType).getType() !=null - && activeTransports.get(serviceType).getType().equals(secondaryTransportType)){ - // Transport is already active and accepted - header.setTransportRecord(activeTransports.get(serviceType)); - handlePacketToSend(header); - return; - } - - - - //If the secondary transport isn't connected yet that will have to be performed first - - List<ISecondaryTransportListener> listenerList = secondaryTransportListeners.get(secondaryTransportType); - if(listenerList == null){ - listenerList = new ArrayList<>(); - secondaryTransportListeners.put(secondaryTransportType, listenerList); - } - - //Check to see if the primary transport can also be used as a backup - final boolean primaryTransportBackup = transportPriorityForServiceMap.get(serviceType).contains(PRIMARY_TRANSPORT_ID); - - ISecondaryTransportListener secondaryListener = new ISecondaryTransportListener() { - @Override - public void onConnectionSuccess(TransportRecord transportRecord) { - header.setTransportRecord(transportRecord); - handlePacketToSend(header); - } - - @Override - public void onConnectionFailure() { - if(primaryTransportBackup) { - // Primary is also supported as backup - header.setTransportRecord(connectedPrimaryTransport); - handlePacketToSend(header); - }else{ - Log.d(TAG, "Failed to connect secondary transport, threw away StartService"); - } - } - }; - - if(transportManager.isConnected(secondaryTransportType,null)){ - //The transport is actually connected, however no service has been registered - listenerList.add(secondaryListener); - registerSecondaryTransport(sessionID,transportManager.getTransportRecord(secondaryTransportType,null)); - }else if(secondaryTransportParams != null && secondaryTransportParams.containsKey(secondaryTransportType)) { - //No acceptable secondary transport is connected, so first one must be connected - header.setTransportRecord(new TransportRecord(secondaryTransportType,"")); - listenerList.add(secondaryListener); - transportManager.requestSecondaryTransportConnection(sessionID,secondaryTransportParams.get(secondaryTransportType)); - }else{ - Log.w(TAG, "No params to connect to secondary transport"); - //Unable to register or start a secondary connection. Use the callback in case - //there is a chance to use the primary transport for this service. - secondaryListener.onConnectionFailure(); - } - - } - } - } - - private void sendHeartBeatACK(SessionType sessionType, byte sessionID) { - final SdlPacket heartbeat = SdlPacketFactory.createHeartbeatACK(SessionType.CONTROL, sessionID, (byte)protocolVersion.getMajor()); - heartbeat.setTransportRecord(activeTransports.get(sessionType)); - handlePacketToSend(heartbeat); + public SdlProtocol( ISdlProtocol iSdlProtocol, WebSocketServerConfig config) { + super(iSdlProtocol, config); + this.setTransportManager(new TransportManager(config,transportEventListener)); } - public void endService(SessionType serviceType, byte sessionID) { - if(serviceType.equals(SessionType.RPC)){ //RPC session will close all other sessions so we want to make sure we use the correct EndProtocolSession method - endSession(sessionID,hashID); - }else { - SdlPacket header = SdlPacketFactory.createEndSession(serviceType, sessionID, hashID, (byte)protocolVersion.getMajor(), new byte[0]); - TransportRecord transportRecord = activeTransports.get(serviceType); - if(transportRecord != null){ - header.setTransportRecord(transportRecord); - handlePacketToSend(header); - } - } - } - - /* -------------------------------------------------------------------------------------------- - ----------------------------------- OLD ABSTRACT PROTOCOL --------------------------------- - -------------------------------------------------------------------------------------------*/ - - - // This method is called whenever a protocol has an entire frame to send - /** - * SdlPacket should have included payload at this point. - * @param packet packet that will be sent to the router service - */ - protected void handlePacketToSend(SdlPacket packet) { - synchronized(FRAME_LOCK) { - - if(packet!=null){ - iSdlProtocol.onProtocolMessageBytesToSend(packet); - } - - } - } - - /** This method handles the end of a protocol session. A callback is - * sent to the protocol listener. - **/ - protected void handleServiceEndedNAK(SdlPacket packet, SessionType serviceType) { - if(packet.version >= 5){ - if(DebugTool.isDebugEnabled()) { - //Currently this is only during a debugging session. Might pass back in the future - String rejectedTag = null; - if (serviceType.equals(SessionType.RPC)) { - rejectedTag = ControlFrameTags.RPC.EndServiceNAK.REJECTED_PARAMS; - } else if (serviceType.equals(SessionType.PCM)) { - rejectedTag = ControlFrameTags.Audio.EndServiceNAK.REJECTED_PARAMS; - } else if (serviceType.equals(SessionType.NAV)) { - rejectedTag = ControlFrameTags.Video.EndServiceNAK.REJECTED_PARAMS; - } - - List<String> rejectedParams = (List<String>) packet.getTag(rejectedTag); - if(rejectedParams != null && rejectedParams.size() > 0){ - StringBuilder builder = new StringBuilder(); - builder.append("Rejected params for service type "); - builder.append(serviceType.getName()); - builder.append(" :"); - for(String rejectedParam : rejectedParams){ - builder.append(rejectedParam); - builder.append(" "); - } - DebugTool.logWarning(builder.toString()); - } - - } - } - - iSdlProtocol.onProtocolSessionEndedNACKed(serviceType, (byte)packet.getSessionId(), ""); - } - - // This method handles the end of a protocol session. A callback is - // sent to the protocol listener. - protected void handleServiceEnded(SdlPacket packet, SessionType sessionType) { - - iSdlProtocol.onProtocolSessionEnded(sessionType, (byte)packet.getSessionId(), ""); - - } - - /** - * This method handles the startup of a protocol session. A callback is sent - * to the protocol listener. - * @param packet StarServiceACK packet - * @param serviceType the service type that has just been started - */ - protected void handleProtocolSessionStarted(SdlPacket packet, SessionType serviceType) { - // Use this sessionID to create a message lock - Object messageLock = _messageLocks.get((byte)packet.getSessionId()); - if (messageLock == null) { - messageLock = new Object(); - _messageLocks.put((byte)packet.getSessionId(), messageLock); - } - if(packet.version >= 5){ - String mtuTag = null; - if(serviceType.equals(SessionType.RPC)){ - mtuTag = ControlFrameTags.RPC.StartServiceACK.MTU; - }else if(serviceType.equals(SessionType.PCM)){ - mtuTag = ControlFrameTags.Audio.StartServiceACK.MTU; - }else if(serviceType.equals(SessionType.NAV)){ - mtuTag = ControlFrameTags.Video.StartServiceACK.MTU; - } - Object mtu = packet.getTag(mtuTag); - if(mtu!=null){ - mtus.put(serviceType,(Long) packet.getTag(mtuTag)); - } - if(serviceType.equals(SessionType.RPC)){ - hashID = (Integer) packet.getTag(ControlFrameTags.RPC.StartServiceACK.HASH_ID); - Object version = packet.getTag(ControlFrameTags.RPC.StartServiceACK.PROTOCOL_VERSION); - - if(version!=null) { - //At this point we have confirmed the negotiated version between the module and the proxy - protocolVersion = new Version((String) version); - }else{ - protocolVersion = new Version("5.0.0"); - } - - //Check to make sure this is a transport we are willing to accept - TransportRecord transportRecord = packet.getTransportRecord(); - - if(transportRecord == null || !requestedPrimaryTransports.contains(transportRecord.getType())){ - onTransportNotAccepted("Transport is not in requested primary transports"); - return; - } - - - // This enables custom behavior based on protocol version specifics - if (protocolVersion.isNewerThan(new Version("5.1.0")) >= 0) { - - if (activeTransports.get(SessionType.RPC) == null) { //Might be a better way to handle this - - ArrayList<String> secondary = (ArrayList<String>) packet.getTag(ControlFrameTags.RPC.StartServiceACK.SECONDARY_TRANSPORTS); - ArrayList<Integer> audio = (ArrayList<Integer>) packet.getTag(ControlFrameTags.RPC.StartServiceACK.AUDIO_SERVICE_TRANSPORTS); - ArrayList<Integer> video = (ArrayList<Integer>) packet.getTag(ControlFrameTags.RPC.StartServiceACK.VIDEO_SERVICE_TRANSPORTS); - - activeTransports.put(SessionType.RPC, transportRecord); - activeTransports.put(SessionType.BULK_DATA, transportRecord); - activeTransports.put(SessionType.CONTROL, transportRecord); - - //Build out the supported secondary transports received from the - // RPC start service ACK. - supportedSecondaryTransports = new ArrayList<>(); - if (secondary == null) { - // If no secondary transports were attached we should assume - // the Video and Audio services can be used on primary - if (requiresHighBandwidth - && TransportType.BLUETOOTH.equals(transportRecord.getType())) { - //transport can't support high bandwidth - onTransportNotAccepted(transportRecord.getType() + " can't support high bandwidth requirement, and secondary transport not supported."); - return; - } - - if (video == null || video.contains(PRIMARY_TRANSPORT_ID)) { - activeTransports.put(SessionType.NAV, transportRecord); - } - if (audio == null || audio.contains(PRIMARY_TRANSPORT_ID)) { - activeTransports.put(SessionType.PCM, transportRecord); - } - }else{ - - if(DebugTool.isDebugEnabled()){ - printSecondaryTransportDetails(secondary,audio,video); - } - for (String s : secondary) { - switch (s) { - case TransportConstants.TCP_WIFI: - supportedSecondaryTransports.add(TransportType.TCP); - break; - case TransportConstants.AOA_USB: - supportedSecondaryTransports.add(TransportType.USB); - break; - case TransportConstants.SPP_BLUETOOTH: - supportedSecondaryTransports.add(TransportType.BLUETOOTH); - break; - } - } - } - - setTransportPriorityForService(SessionType.PCM, audio); - setTransportPriorityForService(SessionType.NAV, video); - - //Update the developer on the transport status - notifyDevTransportListener(); - - } else { - Log.w(TAG, "Received a start service ack for RPC service while already active on a different transport."); - return; - } - }else { - - //Version is either not included or lower than 5.1.0 - if (requiresHighBandwidth - && TransportType.BLUETOOTH.equals(transportRecord.getType())) { - //transport can't support high bandwidth - onTransportNotAccepted(transportRecord.getType() + " can't support high bandwidth requirement, and secondary transport not supported in this protocol version: " + version); - return; - } - - activeTransports.put(SessionType.RPC, transportRecord); - activeTransports.put(SessionType.BULK_DATA, transportRecord); - activeTransports.put(SessionType.CONTROL, transportRecord); - activeTransports.put(SessionType.NAV, transportRecord); - activeTransports.put(SessionType.PCM, transportRecord); - - //Inform the developer of the initial transport connection - notifyDevTransportListener(); - } - - - }else if(serviceType.equals(SessionType.NAV)){ - if(iSdlProtocol != null) { - ImageResolution acceptedResolution = new ImageResolution(); - VideoStreamingFormat acceptedFormat = new VideoStreamingFormat(); - acceptedResolution.setResolutionHeight((Integer) packet.getTag(ControlFrameTags.Video.StartServiceACK.HEIGHT)); - acceptedResolution.setResolutionWidth((Integer) packet.getTag(ControlFrameTags.Video.StartServiceACK.WIDTH)); - acceptedFormat.setCodec(VideoStreamingCodec.valueForString((String) packet.getTag(ControlFrameTags.Video.StartServiceACK.VIDEO_CODEC))); - acceptedFormat.setProtocol(VideoStreamingProtocol.valueForString((String) packet.getTag(ControlFrameTags.Video.StartServiceACK.VIDEO_PROTOCOL))); - VideoStreamingParameters agreedVideoParams = iSdlProtocol.getDesiredVideoParams(); - agreedVideoParams.setResolution(acceptedResolution); - agreedVideoParams.setFormat(acceptedFormat); - iSdlProtocol.setAcceptedVideoParams(agreedVideoParams); - } - } - } else { - TransportRecord transportRecord = packet.getTransportRecord(); - if(transportRecord == null || (requiresHighBandwidth - && TransportType.BLUETOOTH.equals(transportRecord.getType()))){ - //transport can't support high bandwidth - onTransportNotAccepted((transportRecord != null ? transportRecord.getType().toString() : "Transport") + "can't support high bandwidth requirement, and secondary transport not supported in this protocol version"); - return; - } - //If version < 5 and transport is acceptable we need to just add these - activeTransports.put(SessionType.RPC, transportRecord); - activeTransports.put(SessionType.BULK_DATA, transportRecord); - activeTransports.put(SessionType.CONTROL, transportRecord); - activeTransports.put(SessionType.NAV, transportRecord); - activeTransports.put(SessionType.PCM, transportRecord); - - if (protocolVersion.getMajor() > 1){ - if (packet.payload!= null && packet.dataSize == 4){ //hashid will be 4 bytes in length - hashID = BitConverter.intFromByteArray(packet.payload, 0); - } - } - } - - iSdlProtocol.onProtocolSessionStarted(serviceType, (byte) packet.getSessionId(), (byte)protocolVersion.getMajor(), "", hashID, packet.isEncrypted()); - } - - protected void handleProtocolSessionNAKed(SdlPacket packet, SessionType serviceType) { - List<String> rejectedParams = null; - if(packet.version >= 5){ - if(DebugTool.isDebugEnabled()) { - //Currently this is only during a debugging session. Might pass back in the future - String rejectedTag = null; - if (serviceType.equals(SessionType.RPC)) { - rejectedTag = ControlFrameTags.RPC.StartServiceNAK.REJECTED_PARAMS; - } else if (serviceType.equals(SessionType.PCM)) { - rejectedTag = ControlFrameTags.Audio.StartServiceNAK.REJECTED_PARAMS; - } else if (serviceType.equals(SessionType.NAV)) { - rejectedTag = ControlFrameTags.Video.StartServiceNAK.REJECTED_PARAMS; - } - - rejectedParams = (List<String>) packet.getTag(rejectedTag); - if(rejectedParams != null && rejectedParams.size() > 0){ - StringBuilder builder = new StringBuilder(); - builder.append("Rejected params for service type "); - builder.append(serviceType.getName()); - builder.append(" :"); - for(String rejectedParam : rejectedParams){ - builder.append(rejectedParam); - builder.append(" "); - } - DebugTool.logWarning(builder.toString()); - } - - } - } - if (serviceType.eq(SessionType.NAV) || serviceType.eq(SessionType.PCM)) { - iSdlProtocol.onProtocolSessionNACKed(serviceType, (byte)packet.sessionId, (byte)protocolVersion.getMajor(), "", rejectedParams); - - } else { - handleProtocolError("Got StartSessionNACK for protocol sessionID = " + packet.getSessionId(), null); - } - } - - // This method handles protocol errors. A callback is sent to the protocol - // listener. - protected void handleProtocolError(String string, Exception ex) { - iSdlProtocol.onProtocolError(string, ex); - } - - protected void handleProtocolHeartbeat(SessionType sessionType, byte sessionID) { - sendHeartBeatACK(sessionType,sessionID); - } - - protected void handleServiceDataACK(SdlPacket packet, SessionType sessionType) { - - if (packet.getPayload() != null && packet.getDataSize() == 4){ //service data ack will be 4 bytes in length - int serviceDataAckSize = BitConverter.intFromByteArray(packet.getPayload(), 0); - iSdlProtocol.onProtocolServiceDataACK(sessionType, serviceDataAckSize, (byte)packet.getSessionId ()); - - } - } - - /* -------------------------------------------------------------------------------------------- - ----------------------------------- TRANSPORT_TYPE LISTENER --------------------------------- - -------------------------------------------------------------------------------------------*/ - - @SuppressWarnings("FieldCanBeLocal") - private final TransportManager.TransportEventListener transportEventListener = new TransportManager.TransportEventListener() { - private boolean requestedSession = false; - - @Override - public void onPacketReceived(SdlPacket packet) { - handlePacketReceived(packet); - } - - @Override - public void onTransportConnected(List<TransportRecord> connectedTransports) { - Log.d(TAG, "onTransportConnected"); - //In the future we should move this logic into the Protocol Layer - TransportRecord transportRecord = getTransportForSession(SessionType.RPC); - if(transportRecord == null && !requestedSession){ //There is currently no transport registered - requestedSession = true; - transportManager.requestNewSession(getPreferredTransport(requestedPrimaryTransports,connectedTransports)); - } - onTransportsConnectedUpdate(connectedTransports); - if(DebugTool.isDebugEnabled()){ - printActiveTransports(); - } - } - - @Override - public void onTransportDisconnected(String info, TransportRecord disconnectedTransport, List<TransportRecord> connectedTransports) { - if (disconnectedTransport == null) { - Log.d(TAG, "onTransportDisconnected"); - transportManager.close(iSdlProtocol.getSessionId()); - iSdlProtocol.shutdown("No transports left connected"); - return; - } else { - Log.d(TAG, "onTransportDisconnected - " + disconnectedTransport.getType().name()); - } - - //In the future we will actually compare the record but at this point we can assume only - //a single transport record per transport. - //TransportType type = disconnectedTransport.getType(); - if(disconnectedTransport.equals(getTransportForSession(SessionType.NAV))){ - //stopVideoStream(); - iSdlProtocol.stopStream(SessionType.NAV); - activeTransports.remove(SessionType.NAV); - } - if(disconnectedTransport.equals(getTransportForSession(SessionType.PCM))){ - //stopAudioStream(); - iSdlProtocol.stopStream(SessionType.PCM); - activeTransports.remove(SessionType.PCM); - } - - if(disconnectedTransport.equals(getTransportForSession(SessionType.RPC))){ - //transportTypes.remove(type); - boolean primaryTransportAvailable = false; - if(requestedPrimaryTransports != null && requestedPrimaryTransports.size() > 1){ - for (TransportType transportType: requestedPrimaryTransports){ Log.d(TAG, "Checking " + transportType.name()); - if(!disconnectedTransport.getType().equals(transportType) - && transportManager != null - && transportManager.isConnected(transportType,null)){ - primaryTransportAvailable = true; - //( transportConfig).setService(transportManager.getRouterService()); - break; - } - } - } - transportManager.close(iSdlProtocol.getSessionId()); - transportManager = null; - requestedSession = false; - - activeTransports.clear(); - - iSdlProtocol.onTransportDisconnected(info, primaryTransportAvailable, transportConfig); - - } //else Transport was not primary, continuing to stay connected - - //Update the developer since a transport just disconnected - notifyDevTransportListener(); - - } - - @Override - public void onError(String info) { - iSdlProtocol.shutdown(info); - - } - - @Override - public boolean onLegacyModeEnabled(String info) { - //Await a connection from the legacy transport - if(requestedPrimaryTransports!= null && requestedPrimaryTransports.contains(TransportType.BLUETOOTH) - ){//FIXME && !transportConfig.requiresHighBandwidth()){ - Log.d(TAG, "Entering legacy mode; creating new protocol instance"); - reset(); - return true; - }else{ - Log.d(TAG, "Bluetooth is not an acceptable transport; not moving to legacy mode"); - return false; - } - } - }; - -/* ------------------------------------------------------------------------------------------------- ------------------------------------ Internal Classes ------------------------------------------ ---------------------------------------------------------------------------------------------------*/ - - - protected class MessageFrameAssembler { - protected ByteArrayOutputStream accumulator = null; - protected int totalSize = 0; - - protected void handleFirstDataFrame(SdlPacket packet) { - //The message is new, so let's figure out how big it is. - totalSize = BitConverter.intFromByteArray(packet.payload, 0) - headerSize; - try { - accumulator = new ByteArrayOutputStream(totalSize); - }catch(OutOfMemoryError e){ - DebugTool.logError("OutOfMemory error", e); //Garbled bits were received - accumulator = null; - } - } - - protected void handleRemainingFrame(SdlPacket packet) { - accumulator.write(packet.payload, 0, (int)packet.getDataSize()); - notifyIfFinished(packet); - } - - protected void notifyIfFinished(SdlPacket packet) { - if (packet.getFrameType() == FrameType.Consecutive && packet.getFrameInfo() == 0x0) { - ProtocolMessage message = new ProtocolMessage(); - message.setPayloadProtected(packet.isEncrypted()); - message.setSessionType(SessionType.valueOf((byte)packet.getServiceType())); - message.setSessionID((byte)packet.getSessionId()); - //If it is WiPro 2.0 it must have binary header - if (protocolVersion.getMajor() > 1) { - BinaryFrameHeader binFrameHeader = BinaryFrameHeader. - parseBinaryHeader(accumulator.toByteArray()); - if(binFrameHeader == null) { - return; - } - message.setVersion((byte)protocolVersion.getMajor()); - message.setRPCType(binFrameHeader.getRPCType()); - message.setFunctionID(binFrameHeader.getFunctionID()); - message.setCorrID(binFrameHeader.getCorrID()); - if (binFrameHeader.getJsonSize() > 0) message.setData(binFrameHeader.getJsonData()); - if (binFrameHeader.getBulkData() != null) message.setBulkData(binFrameHeader.getBulkData()); - } else{ - message.setData(accumulator.toByteArray()); - } - - _assemblerForMessageID.remove(packet.getMessageId()); - - try { - iSdlProtocol.onProtocolMessageReceived(message); - } catch (Exception excp) { - DebugTool.logError(FailurePropagating_Msg + "onProtocolMessageReceived: " + excp.toString(), excp); - } // end-catch - - accumulator = null; - } // end-if - } // end-method - - protected void handleMultiFrameMessageFrame(SdlPacket packet) { - if (packet.getFrameType() == FrameType.First) { - handleFirstDataFrame(packet); - } - else{ - if(accumulator != null){ - handleRemainingFrame(packet); - } - } - - } // end-method - - protected void handleFrame(SdlPacket packet) { - - if (packet.getPayload() != null && packet.getDataSize() > 0 && packet.isEncrypted() ) { - - SdlSecurityBase sdlSec = iSdlProtocol.getSdlSecurity(); - byte[] dataToRead = new byte[4096]; - - Integer iNumBytes = sdlSec.decryptData(packet.getPayload(), dataToRead); - if ((iNumBytes == null) || (iNumBytes <= 0)){ - return; - } - - byte[] decryptedData = new byte[iNumBytes]; - System.arraycopy(dataToRead, 0, decryptedData, 0, iNumBytes); - packet.payload = decryptedData; - } - - if (packet.getFrameType().equals(FrameType.Control)) { - handleControlFrame(packet); - } else { - // Must be a form of data frame (single, first, consecutive, etc.) - if ( packet.getFrameType() == FrameType.First - || packet.getFrameType() == FrameType.Consecutive - ) { - handleMultiFrameMessageFrame(packet); - } else { - handleSingleFrameMessageFrame(packet); - } - } - } - - private void handleProtocolHeartbeatACK(SdlPacket packet) { - //Heartbeat is not supported in the SdlProtocol class beyond responding with ACKs to - //heartbeat messages. Receiving this ACK is suspicious and should be logged - DebugTool.logInfo("Received HeartbeatACK - " + packet.toString()); - } - - private void handleProtocolHeartbeat(SdlPacket packet) { - SdlProtocol.this.handleProtocolHeartbeat(SessionType.valueOf((byte)packet.getServiceType()),(byte)packet.getSessionId()); - } - - /** - * Directing method that will push the packet to the method that can handle it best - * @param packet a control frame packet - */ - private void handleControlFrame(SdlPacket packet) { - Integer frameTemp = packet.getFrameInfo(); - Byte frameInfo = frameTemp.byteValue(); - - SessionType serviceType = SessionType.valueOf((byte)packet.getServiceType()); - - if (frameInfo == FrameDataControlFrameType.Heartbeat.getValue()) { - - handleProtocolHeartbeat(packet); - - }else if (frameInfo == FrameDataControlFrameType.HeartbeatACK.getValue()) { - - handleProtocolHeartbeatACK(packet); - - }else if (frameInfo == FrameDataControlFrameType.StartSessionACK.getValue()) { - - handleProtocolSessionStarted(packet, serviceType); - - } else if (frameInfo == FrameDataControlFrameType.StartSessionNACK.getValue()) { - - handleProtocolSessionNAKed(packet, serviceType); - - } else if (frameInfo == FrameDataControlFrameType.EndSession.getValue() - || frameInfo == FrameDataControlFrameType.EndSessionACK.getValue()) { - - handleServiceEnded(packet,serviceType); - - } else if (frameInfo == FrameDataControlFrameType.EndSessionNACK.getValue()) { - - handleServiceEndedNAK(packet, serviceType); - - } else if (frameInfo == FrameDataControlFrameType.ServiceDataACK.getValue()) { - - handleServiceDataACK(packet, serviceType); - - } else if (frameInfo == FrameDataControlFrameType.RegisterSecondaryTransportACK.getValue()) { - - handleSecondaryTransportRegistration(packet.getTransportRecord(),true); - - } else if (frameInfo == FrameDataControlFrameType.RegisterSecondaryTransportNACK.getValue()) { - - String reason = (String) packet.getTag(ControlFrameTags.RPC.RegisterSecondaryTransportNAK.REASON); - DebugTool.logWarning(reason); - handleSecondaryTransportRegistration(packet.getTransportRecord(),false); - - } else if (frameInfo == FrameDataControlFrameType.TransportEventUpdate.getValue()) { - - // Get TCP params - String ipAddr = (String) packet.getTag(ControlFrameTags.RPC.TransportEventUpdate.TCP_IP_ADDRESS); - Integer port = (Integer) packet.getTag(ControlFrameTags.RPC.TransportEventUpdate.TCP_PORT); - - if(secondaryTransportParams == null){ - secondaryTransportParams = new HashMap<>(); - } - - if(ipAddr != null && port != null) { - //FIXME - /* Bundle bundle = new Bundle(); - bundle.putString(ControlFrameTags.RPC.TransportEventUpdate.TCP_IP_ADDRESS, ipAddr); - bundle.putInt(ControlFrameTags.RPC.TransportEventUpdate.TCP_PORT, port); - bundle.putString(TransportConstants.TRANSPORT_TYPE, TransportType.TCP.name()); - secondaryTransportParams.put(TransportType.TCP, bundle);*/ - - //A new secondary transport just became available. Notify the developer. - notifyDevTransportListener(); - } - - } - - _assemblerForMessageID.remove(packet.getMessageId()); - - } // end-method - - private void handleSingleFrameMessageFrame(SdlPacket packet) { - ProtocolMessage message = new ProtocolMessage(); - message.setPayloadProtected(packet.isEncrypted()); - SessionType serviceType = SessionType.valueOf((byte)packet.getServiceType()); - if (serviceType == SessionType.RPC) { - message.setMessageType(MessageType.RPC); - } else if (serviceType == SessionType.BULK_DATA) { - message.setMessageType(MessageType.BULK); - } // end-if - message.setSessionType(serviceType); - message.setSessionID((byte)packet.getSessionId()); - //If it is WiPro 2.0 it must have binary header - boolean isControlService = message.getSessionType().equals(SessionType.CONTROL); - if (protocolVersion.getMajor() > 1 && !isControlService) { - BinaryFrameHeader binFrameHeader = BinaryFrameHeader. - parseBinaryHeader(packet.payload); - if(binFrameHeader == null) { - return; - } - message.setVersion((byte)protocolVersion.getMajor()); - message.setRPCType(binFrameHeader.getRPCType()); - message.setFunctionID(binFrameHeader.getFunctionID()); - message.setCorrID(binFrameHeader.getCorrID()); - if (binFrameHeader.getJsonSize() > 0){ - message.setData(binFrameHeader.getJsonData()); - } - if (binFrameHeader.getBulkData() != null){ - message.setBulkData(binFrameHeader.getBulkData()); - } - } else { - message.setData(packet.payload); - } - - _assemblerForMessageID.remove(packet.getMessageId()); - - try { - iSdlProtocol.onProtocolMessageReceived(message); - } catch (Exception ex) { - DebugTool.logError(FailurePropagating_Msg + "onProtocolMessageReceived: " + ex.toString(), ex); - handleProtocolError(FailurePropagating_Msg + "onProtocolMessageReceived: ", ex); - } // end-catch - } // end-method - } // end-class } diff --git a/base/src/main/java/com/smartdevicelink/protocol/SdlProtocolBase.java b/base/src/main/java/com/smartdevicelink/protocol/SdlProtocolBase.java new file mode 100644 index 000000000..626f235f4 --- /dev/null +++ b/base/src/main/java/com/smartdevicelink/protocol/SdlProtocolBase.java @@ -0,0 +1,1451 @@ +/* + * 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.protocol; + +import android.support.annotation.NonNull; +import android.util.Log; + +import com.smartdevicelink.exception.SdlException; +import com.smartdevicelink.exception.SdlExceptionCause; +import com.smartdevicelink.protocol.enums.ControlFrameTags; +import com.smartdevicelink.protocol.enums.FrameDataControlFrameType; +import com.smartdevicelink.protocol.enums.FrameType; +import com.smartdevicelink.protocol.enums.MessageType; +import com.smartdevicelink.protocol.enums.SessionType; +import com.smartdevicelink.proxy.rpc.ImageResolution; +import com.smartdevicelink.proxy.rpc.VideoStreamingFormat; +import com.smartdevicelink.proxy.rpc.enums.VideoStreamingCodec; +import com.smartdevicelink.proxy.rpc.enums.VideoStreamingProtocol; +import com.smartdevicelink.security.SdlSecurityBase; +import com.smartdevicelink.streaming.video.VideoStreamingParameters; +import com.smartdevicelink.transport.BaseTransportConfig; +import com.smartdevicelink.transport.TransportConstants; +import com.smartdevicelink.transport.TransportManagerBase; +import com.smartdevicelink.transport.enums.TransportType; +import com.smartdevicelink.transport.utl.TransportRecord; +import com.smartdevicelink.util.BitConverter; +import com.smartdevicelink.util.DebugTool; +import com.smartdevicelink.util.Version; + +import java.io.ByteArrayOutputStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.Hashtable; +import java.util.List; +import java.util.Map; + +public class SdlProtocolBase { + private static final String TAG ="SdlProtocol"; + private final static String FailurePropagating_Msg = "Failure propagating "; + + private static final int TLS_MAX_RECORD_SIZE = 16384; + + private static final int PRIMARY_TRANSPORT_ID = 1; + private static final int SECONDARY_TRANSPORT_ID = 2; + + /** + * Original header size based on version 1.0.0 only + */ + public static final int V1_HEADER_SIZE = 8; + /** + * Larger header size that is used by versions 2.0.0 and up + */ + public static final int V2_HEADER_SIZE = 12; + + //If increasing MAX PROTOCOL VERSION major version, make sure to alter it in SdlPsm + private static final Version MAX_PROTOCOL_VERSION = new Version("5.1.0"); + + public static final int V1_V2_MTU_SIZE = 1500; + public static final int V3_V4_MTU_SIZE = 131072; + + private static final List<SessionType> HIGH_BANDWIDTH_SERVICES + = Arrays.asList(SessionType.NAV, SessionType.PCM); + + // Lock to ensure all frames are sent uninterrupted + private final Object FRAME_LOCK = new Object(); + + private final ISdlProtocol iSdlProtocol; + private final Hashtable<Integer, SdlProtocol.MessageFrameAssembler> _assemblerForMessageID = new Hashtable<>(); + private final Hashtable<Byte, Object> _messageLocks = new Hashtable<>(); + private final HashMap<SessionType, Long> mtus = new HashMap<>(); + private final HashMap<SessionType, TransportRecord> activeTransports = new HashMap<>(); + private final Map<TransportType, List<ISecondaryTransportListener>> secondaryTransportListeners = new HashMap<>(); + + + private Version protocolVersion = new Version("1.0.0"); + private int hashID = 0; + private int messageID = 0; + private int headerSize = V1_HEADER_SIZE; + + /** + * Transport config that this protocol instance should use along with the supplied transport manager + */ + final BaseTransportConfig transportConfig; + + /** + * The transport manager used for this protocol instance. + */ + TransportManagerBase transportManager; + + + /** + * Requested transports for primary and secondary + */ + List<TransportType> requestedPrimaryTransports, requestedSecondaryTransports; + + /** + * List of secondary transports supported by the module + */ + List<TransportType> supportedSecondaryTransports; + + /** + * Holds the priority of transports for a specific service when that service can be started + * on a primary or secondary transport. + */ + Map<SessionType, List<Integer>> transportPriorityForServiceMap; + boolean requiresHighBandwidth; + Map<TransportType, TransportRecord> secondaryTransportParams; + TransportRecord connectedPrimaryTransport; + + + public SdlProtocolBase(@NonNull ISdlProtocol iSdlProtocol, @NonNull BaseTransportConfig config) { + if (iSdlProtocol == null ) { + throw new IllegalArgumentException("Provided protocol listener interface reference is null"); + } // end-if + + this.iSdlProtocol = iSdlProtocol; + this.transportConfig = config; + if(!config.getTransportType().equals(TransportType.MULTIPLEX)) { + this.requestedPrimaryTransports = Collections.singletonList(transportConfig.getTransportType()); + this.requestedSecondaryTransports = Collections.emptyList(); + this.requiresHighBandwidth = false; + } + mtus.put(SessionType.RPC, (long) (V1_V2_MTU_SIZE - headerSize)); + + } // end-ctor + + void setTransportManager(TransportManagerBase transportManager){ + this.transportManager = transportManager; + } + + public void start(){ + if(transportManager == null){ + throw new IllegalStateException("Attempting to start without setting a transport manager."); + } + transportManager.start(); + + } + /** + * Retrieves the max payload size for a packet to be sent to the module + * @return the max transfer unit + */ + public int getMtu(){ + return mtus.get(SessionType.RPC).intValue(); + } + + public long getMtu(SessionType type){ + Long mtu = mtus.get(type); + if(mtu == null){ + mtu = mtus.get(SessionType.RPC); + } + return mtu; + } + + public void resetSession (){ + if(transportManager == null){ + throw new IllegalStateException("Attempting to reset session without setting a transport manager."); + } + transportManager.resetSession(); + } + + public boolean isConnected(){ + return transportManager != null && transportManager.isConnected(null,null); + } + + /** + * Resets the protocol to init status + */ + protected void reset(){ + protocolVersion = new Version("1.0.0"); + hashID = 0; + messageID = 0; + headerSize = V1_HEADER_SIZE; + this.activeTransports.clear(); + this.mtus.clear(); + mtus.put(SessionType.RPC, (long) (V1_V2_MTU_SIZE - headerSize)); + this.secondaryTransportParams = null; + this._assemblerForMessageID.clear(); + this._messageLocks.clear(); + } + + /** + * For logging purposes, prints active services on each connected transport + */ + protected void printActiveTransports(){ + StringBuilder activeTransportString = new StringBuilder(); + activeTransportString.append("Active transports --- \n"); + + for(Map.Entry entry : activeTransports.entrySet()){ + String sessionString = null; + if(entry.getKey().equals(SessionType.NAV)) { + sessionString = "NAV"; + }else if(entry.getKey().equals(SessionType.PCM)) { + sessionString = "PCM"; + }else if(entry.getKey().equals(SessionType.RPC)) { + sessionString = "RPC"; + } + if(sessionString != null){ + activeTransportString.append("Session: "); + + activeTransportString.append(sessionString); + activeTransportString.append(" Transport: "); + activeTransportString.append(entry.getValue().toString()); + activeTransportString.append("\n"); + } + } + Log.d(TAG, activeTransportString.toString()); + } + + protected void printSecondaryTransportDetails(List<String> secondary, List<Integer> audio, List<Integer> video){ + StringBuilder secondaryDetailsBldr = new StringBuilder(); + secondaryDetailsBldr.append("Checking secondary transport details \n"); + + if(secondary != null){ + secondaryDetailsBldr.append("Supported secondary transports: "); + for(String s : secondary){ + secondaryDetailsBldr.append(" ").append(s); + } + secondaryDetailsBldr.append("\n"); + }else{ + Log.d(TAG, "Supported secondary transports list is empty!"); + } + if(audio != null){ + secondaryDetailsBldr.append("Supported audio transports: "); + for(int a : audio){ + secondaryDetailsBldr.append(" ").append(a); + } + secondaryDetailsBldr.append("\n"); + } + if(video != null){ + secondaryDetailsBldr.append("Supported video transports: "); + for(int v : video){ + secondaryDetailsBldr.append(" ").append(v); + } + secondaryDetailsBldr.append("\n"); + } + + Log.d(TAG, secondaryDetailsBldr.toString()); + } + + + private TransportRecord getTransportForSession(SessionType type){ + return activeTransports.get(type); + } + + private void setTransportPriorityForService(SessionType serviceType, List<Integer> order){ + if(transportPriorityForServiceMap == null){ + transportPriorityForServiceMap = new HashMap<>(); + } + this.transportPriorityForServiceMap.put(serviceType, order); + for(SessionType service : HIGH_BANDWIDTH_SERVICES){ + if (transportPriorityForServiceMap.get(service) != null + && transportPriorityForServiceMap.get(service).contains(PRIMARY_TRANSPORT_ID)) { + if(connectedPrimaryTransport != null) { + activeTransports.put(service, connectedPrimaryTransport); + } + } + } + } + + /** + * Handles when a secondary transport can be used to start services on or when the request as failed. + * @param transportRecord the transport type that the event has taken place on + * @param registered if the transport was successfully registered on + */ + private void handleSecondaryTransportRegistration(TransportRecord transportRecord, boolean registered){ + if(registered) { + //Session has been registered on secondary transport + Log.d(TAG, transportRecord.getType().toString() + " transport was registered!"); + if (supportedSecondaryTransports.contains(transportRecord.getType())) { + // If the transport type that is now available to be used it should be checked + // against the list of services that might be able to be started on it + + for(SessionType secondaryService : HIGH_BANDWIDTH_SERVICES){ + if (transportPriorityForServiceMap.containsKey(secondaryService)) { + // If this service type has extra information from the RPC StartServiceACK + // parse through it to find which transport should be used to start this + // specific service type + for(int transportNum : transportPriorityForServiceMap.get(secondaryService)){ + if(transportNum == PRIMARY_TRANSPORT_ID){ + break; // Primary is favored for this service type, break out... + }else if(transportNum == SECONDARY_TRANSPORT_ID){ + // The secondary transport can be used to start this service + activeTransports.put(secondaryService, transportRecord); + break; + } + } + } + } + } + }else{ + Log.d(TAG, transportRecord.toString() + " transport was NOT registered!"); + } + //Notify any listeners for this secondary transport + List<ISecondaryTransportListener> listenerList = secondaryTransportListeners.remove(transportRecord.getType()); + if(listenerList != null){ + for(ISecondaryTransportListener listener : listenerList){ + if(registered) { + listener.onConnectionSuccess(transportRecord); + }else{ + listener.onConnectionFailure(); + } + } + } + + if(DebugTool.isDebugEnabled()){ + printActiveTransports(); + } + } + + private void onTransportsConnectedUpdate(List<TransportRecord> transports){ + //Log.d(TAG, "Connected transport update"); + + //Temporary: this logic should all be changed to handle multiple transports of the same type + ArrayList<TransportType> connectedTransports = new ArrayList<>(); + if(transports != null) { + for (TransportRecord record : transports) { + connectedTransports.add(record.getType()); + } + } + + if(connectedPrimaryTransport != null && !connectedTransports.contains(connectedPrimaryTransport.getType())){ + //The primary transport being used is no longer part of the connected transports + //The transport manager callbacks should handle the disconnect code + connectedPrimaryTransport = null; + notifyDevTransportListener(); + return; + } + + if(activeTransports.get(SessionType.RPC) == null){ + //There is no currently active transport for the RPC service meaning no primary transport + TransportRecord preferredPrimaryTransport = getPreferredTransport(requestedPrimaryTransports,transports); + if(preferredPrimaryTransport != null) { + connectedPrimaryTransport = preferredPrimaryTransport; + startService(SessionType.RPC, (byte) 0x00, false); + }else{ + onTransportNotAccepted("No transports match requested primary transport"); + } + //Return to that the developer does not receive the transport callback at this time + // as it is better to wait until the RPC service is registered and secondary transport + //information is available + return; + }else if(secondaryTransportListeners != null + && transports != null + && iSdlProtocol!= null){ + // Check to see if there is a listener for a given transport. + // If a listener exists, it can be assumed that the transport should be registered on + for(TransportRecord record: transports){ + if(secondaryTransportListeners.get(record.getType()) != null + && !secondaryTransportListeners.get(record.getType()).isEmpty()){ + registerSecondaryTransport(iSdlProtocol.getSessionId(), record); + } + } + } + //Update the developer that a new transport has become available + notifyDevTransportListener(); + } + + + /** + * Check to see if a transport is available to start/use the supplied service. + * @param serviceType the session that should be checked for transport availability + * @return true if there is either a supported + * transport currently connected or a transport is + * available to connect with for the supplied service type. + * <br>false if there is no + * transport connected to support the service type in question and + * no possibility in the foreseeable future. + */ + public boolean isTransportForServiceAvailable(@NonNull SessionType serviceType){ + if(connectedPrimaryTransport == null){ + //If there is no connected primary then there is no transport available for any service + return false; + }else if(activeTransports!= null && activeTransports.containsKey(serviceType)){ + //There is an active transport that this service can be used on + //This should catch RPC, Bulk, and Control service types + return true; + } + + if(transportPriorityForServiceMap != null) { + List<Integer> transportPriority = transportPriorityForServiceMap.get(serviceType); + + if (transportPriority != null && !transportPriority.isEmpty()) { + if (transportPriority.contains(PRIMARY_TRANSPORT_ID)) { + //If the transport priority for this service type contains primary then + // the service can be used/started + return true; + } else if (transportPriority.contains(SECONDARY_TRANSPORT_ID)) { + //This would mean only secondary transport is supported for this service + return isSecondaryTransportAvailable(false); + } + } + } + + //No transport priority for this service type + if(connectedPrimaryTransport.getType() == TransportType.USB || connectedPrimaryTransport.getType() == TransportType.TCP){ + //Since the only service type that should reach this point are ones that require a high + //bandwidth, true can be returned if the primary transport is a high bandwidth transport + return true; + }else{ + //Since the only service type that should reach this point are ones that require a high + //bandwidth, true can be returned if a secondary transport is a high bandwidth transport + return isSecondaryTransportAvailable(true); + } + } + + /** + * Checks to see if a secondary transport is available for this session + * @param onlyHighBandwidth if only high bandwidth transports should be included in this check + * @return true if any connected or potential transport meets the criteria to be a secondary + * transport + */ + private boolean isSecondaryTransportAvailable(boolean onlyHighBandwidth){ + if (supportedSecondaryTransports != null) { + for (TransportType supportedSecondary : supportedSecondaryTransports) { + if(!onlyHighBandwidth || supportedSecondary == TransportType.USB || supportedSecondary == TransportType.TCP) { + if (transportManager.isConnected(supportedSecondary, null)) { + //A supported secondary transport is already connected + return true; + } else if (secondaryTransportParams != null && secondaryTransportParams.containsKey(supportedSecondary)) { + //A secondary transport is available to connect to + return true; + } + } + } + } + // No supported secondary transports + return false; + } + + + /** + * If the library allows for multiple transports per session this should be handled + */ + void notifyDevTransportListener (){ + //Does nothing in base class + } + + /** + * Retrieves the preferred transport for the given connected transport + * @param preferredList the list of preferred transports (primary or secondary) + * @param connectedTransports the current list of connected transports + * @return the preferred connected transport + */ + private TransportRecord getPreferredTransport(List<TransportType> preferredList, List<TransportRecord> connectedTransports) { + for (TransportType transportType : preferredList) { + for(TransportRecord record: connectedTransports) { + if (record.getType().equals(transportType)) { + return record; + } + } + } + return null; + } + + private void onTransportNotAccepted(String info){ + if(iSdlProtocol != null) { + iSdlProtocol.shutdown(info); + } + } + + + public Version getProtocolVersion(){ + return this.protocolVersion; + } + + /** + * This method will set the major protocol version that we should use. It will also set the default MTU based on version. + * @param version major version to use + */ + protected void setVersion(byte version) { + if (version > 5) { + this.protocolVersion = new Version("5.0.0"); //protect for future, proxy only supports v5 or lower + headerSize = V2_HEADER_SIZE; + mtus.put(SessionType.RPC, (long) V3_V4_MTU_SIZE); + } else if (version == 5) { + this.protocolVersion = new Version("5.0.0"); + headerSize = V2_HEADER_SIZE; + mtus.put(SessionType.RPC, (long) V3_V4_MTU_SIZE); + }else if (version == 4) { + this.protocolVersion = new Version("4.0.0"); + headerSize = V2_HEADER_SIZE; + mtus.put(SessionType.RPC, (long) V3_V4_MTU_SIZE); //versions 4 supports 128k MTU + } else if (version == 3) { + this.protocolVersion = new Version("3.0.0"); + headerSize = V2_HEADER_SIZE; + mtus.put(SessionType.RPC, (long) V3_V4_MTU_SIZE); //versions 3 supports 128k MTU + } else if (version == 2) { + this.protocolVersion = new Version("2.0.0"); + headerSize = V2_HEADER_SIZE; + mtus.put(SessionType.RPC, (long) (V1_V2_MTU_SIZE - headerSize)); + } else if (version == 1){ + this.protocolVersion = new Version("1.0.0"); + headerSize = V1_HEADER_SIZE; + mtus.put(SessionType.RPC, (long) (V1_V2_MTU_SIZE - headerSize)); + } + } + + public void endSession(byte sessionID, int hashId) { + SdlPacket header = SdlPacketFactory.createEndSession(SessionType.RPC, sessionID, hashId, (byte)protocolVersion.getMajor(), hashId); + handlePacketToSend(header); + + } // end-method + + public void sendPacket(SdlPacket packet){ + if(transportManager != null){ + transportManager.sendPacket(packet); + } + } + + public void sendMessage(ProtocolMessage protocolMsg) { + SessionType sessionType = protocolMsg.getSessionType(); + byte sessionID = protocolMsg.getSessionID(); + + byte[] data; + if (protocolVersion.getMajor() > 1 && sessionType != SessionType.NAV && sessionType != SessionType.PCM) { + if (sessionType.eq(SessionType.CONTROL)) { + final byte[] secureData = protocolMsg.getData().clone(); + data = new byte[headerSize + secureData.length]; + + final BinaryFrameHeader binFrameHeader = + SdlPacketFactory.createBinaryFrameHeader(protocolMsg.getRPCType(),protocolMsg.getFunctionID(), protocolMsg.getCorrID(), 0); + System.arraycopy(binFrameHeader.assembleHeaderBytes(), 0, data, 0, headerSize); + System.arraycopy(secureData, 0, data, headerSize, secureData.length); + } + else if (protocolMsg.getBulkData() != null) { + data = new byte[12 + protocolMsg.getJsonSize() + protocolMsg.getBulkData().length]; + sessionType = SessionType.BULK_DATA; + } else { + data = new byte[12 + protocolMsg.getJsonSize()]; + } + if (!sessionType.eq(SessionType.CONTROL)) { + BinaryFrameHeader binFrameHeader = SdlPacketFactory.createBinaryFrameHeader(protocolMsg.getRPCType(), protocolMsg.getFunctionID(), protocolMsg.getCorrID(), protocolMsg.getJsonSize()); + System.arraycopy(binFrameHeader.assembleHeaderBytes(), 0, data, 0, 12); + System.arraycopy(protocolMsg.getData(), 0, data, 12, protocolMsg.getJsonSize()); + if (protocolMsg.getBulkData() != null) { + System.arraycopy(protocolMsg.getBulkData(), 0, data, 12 + protocolMsg.getJsonSize(), protocolMsg.getBulkData().length); + } + } + } else { + data = protocolMsg.getData(); + } + + if (iSdlProtocol != null && protocolMsg.getPayloadProtected()){ + + if (data != null && data.length > 0) { + byte[] dataToRead = new byte[TLS_MAX_RECORD_SIZE]; + SdlSecurityBase sdlSec = iSdlProtocol.getSdlSecurity(); + if (sdlSec == null) + return; + + Integer iNumBytes = sdlSec.encryptData(data, dataToRead); + if ((iNumBytes == null) || (iNumBytes <= 0)) + return; + + byte[] encryptedData = new byte[iNumBytes]; + System.arraycopy(dataToRead, 0, encryptedData, 0, iNumBytes); + data = encryptedData; + } + } + + // Get the message lock for this protocol session + Object messageLock = _messageLocks.get(sessionID); + if (messageLock == null) { + handleProtocolError("Error sending protocol message to SDL.", + new SdlException("Attempt to send protocol message prior to startSession ACK.", SdlExceptionCause.SDL_UNAVAILABLE)); + return; + } + + synchronized(messageLock) { + if (data.length > getMtu(sessionType)) { + + messageID++; + + // Assemble first frame. + Long mtu = getMtu(sessionType); + int frameCount = Long.valueOf(data.length / mtu).intValue(); + if (data.length % mtu > 0) { + frameCount++; + } + byte[] firstFrameData = new byte[8]; + // First four bytes are data size. + System.arraycopy(BitConverter.intToByteArray(data.length), 0, firstFrameData, 0, 4); + // Second four bytes are frame count. + System.arraycopy(BitConverter.intToByteArray(frameCount), 0, firstFrameData, 4, 4); + + SdlPacket firstHeader = SdlPacketFactory.createMultiSendDataFirst(sessionType, sessionID, messageID, (byte)protocolVersion.getMajor(),firstFrameData,protocolMsg.getPayloadProtected()); + firstHeader.setPriorityCoefficient(1+protocolMsg.priorityCoefficient); + firstHeader.setTransportRecord(activeTransports.get(sessionType)); + //Send the first frame + handlePacketToSend(firstHeader); + + int currentOffset = 0; + byte frameSequenceNumber = 0; + + for (int i = 0; i < frameCount; i++) { + if (i < (frameCount - 1)) { + ++frameSequenceNumber; + if (frameSequenceNumber == + SdlPacket.FRAME_INFO_FINAL_CONNESCUTIVE_FRAME) { + // we can't use 0x00 as frameSequenceNumber, because + // it's reserved for the last frame + ++frameSequenceNumber; + } + } else { + frameSequenceNumber = SdlPacket.FRAME_INFO_FINAL_CONNESCUTIVE_FRAME; + } // end-if + + int bytesToWrite = data.length - currentOffset; + if (bytesToWrite > mtu) { + bytesToWrite = mtu.intValue(); + } + SdlPacket consecHeader = SdlPacketFactory.createMultiSendDataRest(sessionType, sessionID, bytesToWrite, frameSequenceNumber , messageID, (byte)protocolVersion.getMajor(),data, currentOffset, bytesToWrite, protocolMsg.getPayloadProtected()); + consecHeader.setTransportRecord(activeTransports.get(sessionType)); + consecHeader.setPriorityCoefficient(i+2+protocolMsg.priorityCoefficient); + handlePacketToSend(consecHeader); + currentOffset += bytesToWrite; + } + } else { + messageID++; + SdlPacket header = SdlPacketFactory.createSingleSendData(sessionType, sessionID, data.length, messageID, (byte)protocolVersion.getMajor(),data, protocolMsg.getPayloadProtected()); + header.setPriorityCoefficient(protocolMsg.priorityCoefficient); + header.setTransportRecord(activeTransports.get(sessionType)); + handlePacketToSend(header); + } + } + } + + protected void handlePacketReceived(SdlPacket packet){ + //Check for a version difference + if (protocolVersion == null || protocolVersion.getMajor() == 1) { + setVersion((byte)packet.version); + } + + SdlProtocolBase.MessageFrameAssembler assembler = getFrameAssemblerForFrame(packet); + assembler.handleFrame(packet); + + } + + + protected SdlProtocolBase.MessageFrameAssembler getFrameAssemblerForFrame(SdlPacket packet) { + Integer iSessionId = packet.getSessionId(); + Byte bySessionId = iSessionId.byteValue(); + + SdlProtocolBase.MessageFrameAssembler ret = _assemblerForMessageID.get(packet.getMessageId()); + if (ret == null) { + ret = new SdlProtocolBase.MessageFrameAssembler(); + _assemblerForMessageID.put(packet.getMessageId(), ret); + } // end-if + + return ret; + } // end-method + + + + private void registerSecondaryTransport(byte sessionId, TransportRecord transportRecord) { + SdlPacket header = SdlPacketFactory.createRegisterSecondaryTransport(sessionId, (byte)protocolVersion.getMajor()); + header.setTransportRecord(transportRecord); + handlePacketToSend(header); + } + + public void startService(SessionType serviceType, byte sessionID, boolean isEncrypted) { + final SdlPacket header = SdlPacketFactory.createStartSession(serviceType, 0x00, (byte)protocolVersion.getMajor(), sessionID, isEncrypted); + if(SessionType.RPC.equals(serviceType)){ + if(connectedPrimaryTransport != null) { + header.setTransportRecord(connectedPrimaryTransport); + } + //This is going to be our primary transport + header.putTag(ControlFrameTags.RPC.StartService.PROTOCOL_VERSION, MAX_PROTOCOL_VERSION.toString()); + handlePacketToSend(header); + return; // We don't need to go any further + }else if(serviceType.equals(SessionType.NAV)){ + if(iSdlProtocol != null){ + VideoStreamingParameters videoStreamingParameters = iSdlProtocol.getDesiredVideoParams(); + if(videoStreamingParameters != null) { + ImageResolution desiredResolution = videoStreamingParameters.getResolution(); + VideoStreamingFormat desiredFormat = videoStreamingParameters.getFormat(); + if (desiredResolution != null) { + header.putTag(ControlFrameTags.Video.StartService.WIDTH, desiredResolution.getResolutionWidth()); + header.putTag(ControlFrameTags.Video.StartService.HEIGHT, desiredResolution.getResolutionHeight()); + } + if (desiredFormat != null) { + header.putTag(ControlFrameTags.Video.StartService.VIDEO_CODEC, desiredFormat.getCodec().toString()); + header.putTag(ControlFrameTags.Video.StartService.VIDEO_PROTOCOL, desiredFormat.getProtocol().toString()); + } + } + } + } + if(transportPriorityForServiceMap == null + || transportPriorityForServiceMap.get(serviceType) == null + || transportPriorityForServiceMap.get(serviceType).isEmpty()){ + //If there is no transport priority for this service it can be assumed it's primary + header.setTransportRecord(connectedPrimaryTransport); + handlePacketToSend(header); + return; + } + int transportPriority = transportPriorityForServiceMap.get(serviceType).get(0); + if(transportPriority == PRIMARY_TRANSPORT_ID){ + // Primary is favored, and we're already connected... + header.setTransportRecord(connectedPrimaryTransport); + handlePacketToSend(header); + }else if(transportPriority == SECONDARY_TRANSPORT_ID) { + // Secondary is favored + for(TransportType secondaryTransportType : supportedSecondaryTransports) { + + if(!requestedSecondaryTransports.contains(secondaryTransportType)){ + // Secondary transport is not accepted by the client + continue; + } + + if(activeTransports.get(serviceType) != null + && activeTransports.get(serviceType).getType() !=null + && activeTransports.get(serviceType).getType().equals(secondaryTransportType)){ + // Transport is already active and accepted + header.setTransportRecord(activeTransports.get(serviceType)); + handlePacketToSend(header); + return; + } + + + + //If the secondary transport isn't connected yet that will have to be performed first + + List<ISecondaryTransportListener> listenerList = secondaryTransportListeners.get(secondaryTransportType); + if(listenerList == null){ + listenerList = new ArrayList<>(); + secondaryTransportListeners.put(secondaryTransportType, listenerList); + } + + //Check to see if the primary transport can also be used as a backup + final boolean primaryTransportBackup = transportPriorityForServiceMap.get(serviceType).contains(PRIMARY_TRANSPORT_ID); + + ISecondaryTransportListener secondaryListener = new ISecondaryTransportListener() { + @Override + public void onConnectionSuccess(TransportRecord transportRecord) { + header.setTransportRecord(transportRecord); + handlePacketToSend(header); + } + + @Override + public void onConnectionFailure() { + if(primaryTransportBackup) { + // Primary is also supported as backup + header.setTransportRecord(connectedPrimaryTransport); + handlePacketToSend(header); + }else{ + Log.d(TAG, "Failed to connect secondary transport, threw away StartService"); + } + } + }; + + if(transportManager.isConnected(secondaryTransportType,null)){ + //The transport is actually connected, however no service has been registered + listenerList.add(secondaryListener); + registerSecondaryTransport(sessionID,transportManager.getTransportRecord(secondaryTransportType,null)); + }else if(secondaryTransportParams != null && secondaryTransportParams.containsKey(secondaryTransportType)) { + //No acceptable secondary transport is connected, so first one must be connected + header.setTransportRecord(new TransportRecord(secondaryTransportType,"")); + listenerList.add(secondaryListener); + transportManager.requestSecondaryTransportConnection(sessionID,secondaryTransportParams.get(secondaryTransportType)); + }else{ + Log.w(TAG, "No params to connect to secondary transport"); + //Unable to register or start a secondary connection. Use the callback in case + //there is a chance to use the primary transport for this service. + secondaryListener.onConnectionFailure(); + } + + } + } + } + + private void sendHeartBeatACK(SessionType sessionType, byte sessionID) { + final SdlPacket heartbeat = SdlPacketFactory.createHeartbeatACK(SessionType.CONTROL, sessionID, (byte)protocolVersion.getMajor()); + heartbeat.setTransportRecord(activeTransports.get(sessionType)); + handlePacketToSend(heartbeat); + } + + public void endService(SessionType serviceType, byte sessionID) { + if(serviceType.equals(SessionType.RPC)){ //RPC session will close all other sessions so we want to make sure we use the correct EndProtocolSession method + endSession(sessionID,hashID); + }else { + SdlPacket header = SdlPacketFactory.createEndSession(serviceType, sessionID, hashID, (byte)protocolVersion.getMajor(), new byte[0]); + TransportRecord transportRecord = activeTransports.get(serviceType); + if(transportRecord != null){ + header.setTransportRecord(transportRecord); + handlePacketToSend(header); + } + } + } + + /* -------------------------------------------------------------------------------------------- + ----------------------------------- OLD ABSTRACT PROTOCOL --------------------------------- + -------------------------------------------------------------------------------------------*/ + + + // This method is called whenever a protocol has an entire frame to send + /** + * SdlPacket should have included payload at this point. + * @param packet packet that will be sent to the router service + */ + protected void handlePacketToSend(SdlPacket packet) { + synchronized(FRAME_LOCK) { + + if(packet!=null){ + iSdlProtocol.onProtocolMessageBytesToSend(packet); + } + + } + } + + /** This method handles the end of a protocol session. A callback is + * sent to the protocol listener. + **/ + protected void handleServiceEndedNAK(SdlPacket packet, SessionType serviceType) { + if(packet.version >= 5){ + if(DebugTool.isDebugEnabled()) { + //Currently this is only during a debugging session. Might pass back in the future + String rejectedTag = null; + if (serviceType.equals(SessionType.RPC)) { + rejectedTag = ControlFrameTags.RPC.EndServiceNAK.REJECTED_PARAMS; + } else if (serviceType.equals(SessionType.PCM)) { + rejectedTag = ControlFrameTags.Audio.EndServiceNAK.REJECTED_PARAMS; + } else if (serviceType.equals(SessionType.NAV)) { + rejectedTag = ControlFrameTags.Video.EndServiceNAK.REJECTED_PARAMS; + } + + List<String> rejectedParams = (List<String>) packet.getTag(rejectedTag); + if(rejectedParams != null && rejectedParams.size() > 0){ + StringBuilder builder = new StringBuilder(); + builder.append("Rejected params for service type "); + builder.append(serviceType.getName()); + builder.append(" :"); + for(String rejectedParam : rejectedParams){ + builder.append(rejectedParam); + builder.append(" "); + } + DebugTool.logWarning(builder.toString()); + } + + } + } + + iSdlProtocol.onProtocolSessionEndedNACKed(serviceType, (byte)packet.getSessionId(), ""); + } + + // This method handles the end of a protocol session. A callback is + // sent to the protocol listener. + protected void handleServiceEnded(SdlPacket packet, SessionType sessionType) { + + iSdlProtocol.onProtocolSessionEnded(sessionType, (byte)packet.getSessionId(), ""); + + } + + /** + * This method handles the startup of a protocol session. A callback is sent + * to the protocol listener. + * @param packet StarServiceACK packet + * @param serviceType the service type that has just been started + */ + protected void handleProtocolSessionStarted(SdlPacket packet, SessionType serviceType) { + // Use this sessionID to create a message lock + Object messageLock = _messageLocks.get((byte)packet.getSessionId()); + if (messageLock == null) { + messageLock = new Object(); + _messageLocks.put((byte)packet.getSessionId(), messageLock); + } + if(packet.version >= 5){ + String mtuTag = null; + if(serviceType.equals(SessionType.RPC)){ + mtuTag = ControlFrameTags.RPC.StartServiceACK.MTU; + }else if(serviceType.equals(SessionType.PCM)){ + mtuTag = ControlFrameTags.Audio.StartServiceACK.MTU; + }else if(serviceType.equals(SessionType.NAV)){ + mtuTag = ControlFrameTags.Video.StartServiceACK.MTU; + } + Object mtu = packet.getTag(mtuTag); + if(mtu!=null){ + mtus.put(serviceType,(Long) packet.getTag(mtuTag)); + } + if(serviceType.equals(SessionType.RPC)){ + hashID = (Integer) packet.getTag(ControlFrameTags.RPC.StartServiceACK.HASH_ID); + Object version = packet.getTag(ControlFrameTags.RPC.StartServiceACK.PROTOCOL_VERSION); + + if(version!=null) { + //At this point we have confirmed the negotiated version between the module and the proxy + protocolVersion = new Version((String) version); + }else{ + protocolVersion = new Version("5.0.0"); + } + + //Check to make sure this is a transport we are willing to accept + TransportRecord transportRecord = packet.getTransportRecord(); + + if(transportRecord == null || !requestedPrimaryTransports.contains(transportRecord.getType())){ + onTransportNotAccepted("Transport is not in requested primary transports"); + return; + } + + + // This enables custom behavior based on protocol version specifics + if (protocolVersion.isNewerThan(new Version("5.1.0")) >= 0) { + + if (activeTransports.get(SessionType.RPC) == null) { //Might be a better way to handle this + + ArrayList<String> secondary = (ArrayList<String>) packet.getTag(ControlFrameTags.RPC.StartServiceACK.SECONDARY_TRANSPORTS); + ArrayList<Integer> audio = (ArrayList<Integer>) packet.getTag(ControlFrameTags.RPC.StartServiceACK.AUDIO_SERVICE_TRANSPORTS); + ArrayList<Integer> video = (ArrayList<Integer>) packet.getTag(ControlFrameTags.RPC.StartServiceACK.VIDEO_SERVICE_TRANSPORTS); + + activeTransports.put(SessionType.RPC, transportRecord); + activeTransports.put(SessionType.BULK_DATA, transportRecord); + activeTransports.put(SessionType.CONTROL, transportRecord); + + //Build out the supported secondary transports received from the + // RPC start service ACK. + supportedSecondaryTransports = new ArrayList<>(); + if (secondary == null) { + // If no secondary transports were attached we should assume + // the Video and Audio services can be used on primary + if (requiresHighBandwidth + && TransportType.BLUETOOTH.equals(transportRecord.getType())) { + //transport can't support high bandwidth + onTransportNotAccepted(transportRecord.getType() + " can't support high bandwidth requirement, and secondary transport not supported."); + return; + } + + if (video == null || video.contains(PRIMARY_TRANSPORT_ID)) { + activeTransports.put(SessionType.NAV, transportRecord); + } + if (audio == null || audio.contains(PRIMARY_TRANSPORT_ID)) { + activeTransports.put(SessionType.PCM, transportRecord); + } + }else{ + + if(DebugTool.isDebugEnabled()){ + printSecondaryTransportDetails(secondary,audio,video); + } + for (String s : secondary) { + switch (s) { + case TransportConstants.TCP_WIFI: + supportedSecondaryTransports.add(TransportType.TCP); + break; + case TransportConstants.AOA_USB: + supportedSecondaryTransports.add(TransportType.USB); + break; + case TransportConstants.SPP_BLUETOOTH: + supportedSecondaryTransports.add(TransportType.BLUETOOTH); + break; + } + } + } + + setTransportPriorityForService(SessionType.PCM, audio); + setTransportPriorityForService(SessionType.NAV, video); + + //Update the developer on the transport status + notifyDevTransportListener(); + + } else { + Log.w(TAG, "Received a start service ack for RPC service while already active on a different transport."); + return; + } + + if(protocolVersion.isNewerThan(new Version(5,2,0)) >= 0){ + String authToken = (String)packet.getTag(ControlFrameTags.RPC.StartServiceACK.AUTH_TOKEN); + if(authToken != null){ + iSdlProtocol.onAuthTokenReceived(authToken); + } + } + }else { + + //Version is either not included or lower than 5.1.0 + if (requiresHighBandwidth + && TransportType.BLUETOOTH.equals(transportRecord.getType())) { + //transport can't support high bandwidth + onTransportNotAccepted(transportRecord.getType() + " can't support high bandwidth requirement, and secondary transport not supported in this protocol version: " + version); + return; + } + + activeTransports.put(SessionType.RPC, transportRecord); + activeTransports.put(SessionType.BULK_DATA, transportRecord); + activeTransports.put(SessionType.CONTROL, transportRecord); + activeTransports.put(SessionType.NAV, transportRecord); + activeTransports.put(SessionType.PCM, transportRecord); + + //Inform the developer of the initial transport connection + notifyDevTransportListener(); + } + + + }else if(serviceType.equals(SessionType.NAV)){ + if(iSdlProtocol != null) { + ImageResolution acceptedResolution = new ImageResolution(); + VideoStreamingFormat acceptedFormat = new VideoStreamingFormat(); + acceptedResolution.setResolutionHeight((Integer) packet.getTag(ControlFrameTags.Video.StartServiceACK.HEIGHT)); + acceptedResolution.setResolutionWidth((Integer) packet.getTag(ControlFrameTags.Video.StartServiceACK.WIDTH)); + acceptedFormat.setCodec(VideoStreamingCodec.valueForString((String) packet.getTag(ControlFrameTags.Video.StartServiceACK.VIDEO_CODEC))); + acceptedFormat.setProtocol(VideoStreamingProtocol.valueForString((String) packet.getTag(ControlFrameTags.Video.StartServiceACK.VIDEO_PROTOCOL))); + VideoStreamingParameters agreedVideoParams = iSdlProtocol.getDesiredVideoParams(); + agreedVideoParams.setResolution(acceptedResolution); + agreedVideoParams.setFormat(acceptedFormat); + iSdlProtocol.setAcceptedVideoParams(agreedVideoParams); + } + } + } else { + TransportRecord transportRecord = packet.getTransportRecord(); + if(transportRecord == null || (requiresHighBandwidth + && TransportType.BLUETOOTH.equals(transportRecord.getType()))){ + //transport can't support high bandwidth + onTransportNotAccepted((transportRecord != null ? transportRecord.getType().toString() : "Transport") + "can't support high bandwidth requirement, and secondary transport not supported in this protocol version"); + return; + } + //If version < 5 and transport is acceptable we need to just add these + activeTransports.put(SessionType.RPC, transportRecord); + activeTransports.put(SessionType.BULK_DATA, transportRecord); + activeTransports.put(SessionType.CONTROL, transportRecord); + activeTransports.put(SessionType.NAV, transportRecord); + activeTransports.put(SessionType.PCM, transportRecord); + + if (protocolVersion.getMajor() > 1){ + if (packet.payload!= null && packet.dataSize == 4){ //hashid will be 4 bytes in length + hashID = BitConverter.intFromByteArray(packet.payload, 0); + } + } + } + + iSdlProtocol.onProtocolSessionStarted(serviceType, (byte) packet.getSessionId(), (byte)protocolVersion.getMajor(), "", hashID, packet.isEncrypted()); + } + + protected void handleProtocolSessionNAKed(SdlPacket packet, SessionType serviceType) { + List<String> rejectedParams = null; + if(packet.version >= 5){ + if(DebugTool.isDebugEnabled()) { + //Currently this is only during a debugging session. Might pass back in the future + String rejectedTag = null; + if (serviceType.equals(SessionType.RPC)) { + rejectedTag = ControlFrameTags.RPC.StartServiceNAK.REJECTED_PARAMS; + } else if (serviceType.equals(SessionType.PCM)) { + rejectedTag = ControlFrameTags.Audio.StartServiceNAK.REJECTED_PARAMS; + } else if (serviceType.equals(SessionType.NAV)) { + rejectedTag = ControlFrameTags.Video.StartServiceNAK.REJECTED_PARAMS; + } + + rejectedParams = (List<String>) packet.getTag(rejectedTag); + if(rejectedParams != null && rejectedParams.size() > 0){ + StringBuilder builder = new StringBuilder(); + builder.append("Rejected params for service type "); + builder.append(serviceType.getName()); + builder.append(" :"); + for(String rejectedParam : rejectedParams){ + builder.append(rejectedParam); + builder.append(" "); + } + DebugTool.logWarning(builder.toString()); + } + + } + } + if (serviceType.eq(SessionType.NAV) || serviceType.eq(SessionType.PCM)) { + iSdlProtocol.onProtocolSessionNACKed(serviceType, (byte)packet.sessionId, (byte)protocolVersion.getMajor(), "", rejectedParams); + + } else { + handleProtocolError("Got StartSessionNACK for protocol sessionID = " + packet.getSessionId(), null); + } + } + + // This method handles protocol errors. A callback is sent to the protocol + // listener. + protected void handleProtocolError(String string, Exception ex) { + iSdlProtocol.onProtocolError(string, ex); + } + + protected void handleProtocolHeartbeat(SessionType sessionType, byte sessionID) { + sendHeartBeatACK(sessionType,sessionID); + } + + protected void handleServiceDataACK(SdlPacket packet, SessionType sessionType) { + + if (packet.getPayload() != null && packet.getDataSize() == 4){ //service data ack will be 4 bytes in length + int serviceDataAckSize = BitConverter.intFromByteArray(packet.getPayload(), 0); + iSdlProtocol.onProtocolServiceDataACK(sessionType, serviceDataAckSize, (byte)packet.getSessionId ()); + + } + } + + /* -------------------------------------------------------------------------------------------- + ----------------------------------- TRANSPORT_TYPE LISTENER --------------------------------- + -------------------------------------------------------------------------------------------*/ + + @SuppressWarnings("FieldCanBeLocal") + final TransportManagerBase.TransportEventListener transportEventListener = new TransportManagerBase.TransportEventListener() { + private boolean requestedSession = false; + + @Override + public void onPacketReceived(SdlPacket packet) { + handlePacketReceived(packet); + } + + @Override + public void onTransportConnected(List<TransportRecord> connectedTransports) { + Log.d(TAG, "onTransportConnected"); + //In the future we should move this logic into the Protocol Layer + TransportRecord transportRecord = getTransportForSession(SessionType.RPC); + if(transportRecord == null && !requestedSession){ //There is currently no transport registered + requestedSession = true; + transportManager.requestNewSession(getPreferredTransport(requestedPrimaryTransports,connectedTransports)); + } + onTransportsConnectedUpdate(connectedTransports); + if(DebugTool.isDebugEnabled()){ + printActiveTransports(); + } + } + + @Override + public void onTransportDisconnected(String info, TransportRecord disconnectedTransport, List<TransportRecord> connectedTransports) { + if (disconnectedTransport == null) { + Log.d(TAG, "onTransportDisconnected"); + transportManager.close(iSdlProtocol.getSessionId()); + iSdlProtocol.shutdown("No transports left connected"); + return; + } else { + Log.d(TAG, "onTransportDisconnected - " + disconnectedTransport.getType().name()); + } + + //In the future we will actually compare the record but at this point we can assume only + //a single transport record per transport. + //TransportType type = disconnectedTransport.getType(); + if(disconnectedTransport.equals(getTransportForSession(SessionType.NAV))){ + //stopVideoStream(); + iSdlProtocol.stopStream(SessionType.NAV); + activeTransports.remove(SessionType.NAV); + } + if(disconnectedTransport.equals(getTransportForSession(SessionType.PCM))){ + //stopAudioStream(); + iSdlProtocol.stopStream(SessionType.PCM); + activeTransports.remove(SessionType.PCM); + } + + if(disconnectedTransport.equals(getTransportForSession(SessionType.RPC)) || disconnectedTransport.equals(connectedPrimaryTransport)){ + //transportTypes.remove(type); + boolean primaryTransportAvailable = false; + if(requestedPrimaryTransports != null && requestedPrimaryTransports.size() > 1){ + for (TransportType transportType: requestedPrimaryTransports){ Log.d(TAG, "Checking " + transportType.name()); + if(!disconnectedTransport.getType().equals(transportType) + && transportManager != null + && transportManager.isConnected(transportType,null)){ + primaryTransportAvailable = true; + //TODO change to update the transport config + transportManager.updateTransportConfig(transportConfig); + break; + } + } + } + connectedPrimaryTransport = null; + transportManager.close(iSdlProtocol.getSessionId()); + transportManager = null; + requestedSession = false; + + activeTransports.clear(); + + iSdlProtocol.onTransportDisconnected(info, primaryTransportAvailable, transportConfig); + + } //else Transport was not primary, continuing to stay connected + + //Update the developer since a transport just disconnected + notifyDevTransportListener(); + + } + + @Override + public void onError(String info) { + iSdlProtocol.shutdown(info); + + } + + @Override + public boolean onLegacyModeEnabled(String info) { + //Await a connection from the legacy transport + if(requestedPrimaryTransports!= null && requestedPrimaryTransports.contains(TransportType.BLUETOOTH) + && !SdlProtocolBase.this.requiresHighBandwidth){ + Log.d(TAG, "Entering legacy mode; creating new protocol instance"); + reset(); + return true; + }else{ + Log.d(TAG, "Bluetooth is not an acceptable transport; not moving to legacy mode"); + return false; + } + } + }; + +/* ------------------------------------------------------------------------------------------------- +----------------------------------- Internal Classes ------------------------------------------ +--------------------------------------------------------------------------------------------------*/ + + + protected class MessageFrameAssembler { + protected ByteArrayOutputStream accumulator = null; + protected int totalSize = 0; + + protected void handleFirstDataFrame(SdlPacket packet) { + //The message is new, so let's figure out how big it is. + totalSize = BitConverter.intFromByteArray(packet.payload, 0) - headerSize; + try { + accumulator = new ByteArrayOutputStream(totalSize); + }catch(OutOfMemoryError e){ + DebugTool.logError("OutOfMemory error", e); //Garbled bits were received + accumulator = null; + } + } + + protected void handleRemainingFrame(SdlPacket packet) { + accumulator.write(packet.payload, 0, (int)packet.getDataSize()); + notifyIfFinished(packet); + } + + protected void notifyIfFinished(SdlPacket packet) { + if (packet.getFrameType() == FrameType.Consecutive && packet.getFrameInfo() == 0x0) { + ProtocolMessage message = new ProtocolMessage(); + message.setPayloadProtected(packet.isEncrypted()); + message.setSessionType(SessionType.valueOf((byte)packet.getServiceType())); + message.setSessionID((byte)packet.getSessionId()); + //If it is WiPro 2.0 it must have binary header + if (protocolVersion.getMajor() > 1) { + BinaryFrameHeader binFrameHeader = BinaryFrameHeader. + parseBinaryHeader(accumulator.toByteArray()); + if(binFrameHeader == null) { + return; + } + message.setVersion((byte)protocolVersion.getMajor()); + message.setRPCType(binFrameHeader.getRPCType()); + message.setFunctionID(binFrameHeader.getFunctionID()); + message.setCorrID(binFrameHeader.getCorrID()); + if (binFrameHeader.getJsonSize() > 0) message.setData(binFrameHeader.getJsonData()); + if (binFrameHeader.getBulkData() != null) message.setBulkData(binFrameHeader.getBulkData()); + } else{ + message.setData(accumulator.toByteArray()); + } + + _assemblerForMessageID.remove(packet.getMessageId()); + + try { + iSdlProtocol.onProtocolMessageReceived(message); + } catch (Exception excp) { + DebugTool.logError(FailurePropagating_Msg + "onProtocolMessageReceived: " + excp.toString(), excp); + } // end-catch + + accumulator = null; + } // end-if + } // end-method + + protected void handleMultiFrameMessageFrame(SdlPacket packet) { + if (packet.getFrameType() == FrameType.First) { + handleFirstDataFrame(packet); + } + else{ + if(accumulator != null){ + handleRemainingFrame(packet); + } + } + + } // end-method + + protected void handleFrame(SdlPacket packet) { + + if (packet.getPayload() != null && packet.getDataSize() > 0 && packet.isEncrypted() ) { + + SdlSecurityBase sdlSec = iSdlProtocol.getSdlSecurity(); + byte[] dataToRead = new byte[4096]; + + Integer iNumBytes = sdlSec.decryptData(packet.getPayload(), dataToRead); + if ((iNumBytes == null) || (iNumBytes <= 0)){ + return; + } + + byte[] decryptedData = new byte[iNumBytes]; + System.arraycopy(dataToRead, 0, decryptedData, 0, iNumBytes); + packet.payload = decryptedData; + } + + if (packet.getFrameType().equals(FrameType.Control)) { + handleControlFrame(packet); + } else { + // Must be a form of data frame (single, first, consecutive, etc.) + if ( packet.getFrameType() == FrameType.First + || packet.getFrameType() == FrameType.Consecutive + ) { + handleMultiFrameMessageFrame(packet); + } else { + handleSingleFrameMessageFrame(packet); + } + } + } + + private void handleProtocolHeartbeatACK(SdlPacket packet) { + //Heartbeat is not supported in the SdlProtocol class beyond responding with ACKs to + //heartbeat messages. Receiving this ACK is suspicious and should be logged + DebugTool.logInfo("Received HeartbeatACK - " + packet.toString()); + } + + private void handleProtocolHeartbeat(SdlPacket packet) { + SdlProtocolBase.this.handleProtocolHeartbeat(SessionType.valueOf((byte)packet.getServiceType()),(byte)packet.getSessionId()); + } + + /** + * Directing method that will push the packet to the method that can handle it best + * @param packet a control frame packet + */ + private void handleControlFrame(SdlPacket packet) { + Integer frameTemp = packet.getFrameInfo(); + Byte frameInfo = frameTemp.byteValue(); + + SessionType serviceType = SessionType.valueOf((byte)packet.getServiceType()); + + if (frameInfo == FrameDataControlFrameType.Heartbeat.getValue()) { + + handleProtocolHeartbeat(packet); + + }else if (frameInfo == FrameDataControlFrameType.HeartbeatACK.getValue()) { + + handleProtocolHeartbeatACK(packet); + + }else if (frameInfo == FrameDataControlFrameType.StartSessionACK.getValue()) { + + handleProtocolSessionStarted(packet, serviceType); + + } else if (frameInfo == FrameDataControlFrameType.StartSessionNACK.getValue()) { + + handleProtocolSessionNAKed(packet, serviceType); + + } else if (frameInfo == FrameDataControlFrameType.EndSession.getValue() + || frameInfo == FrameDataControlFrameType.EndSessionACK.getValue()) { + + handleServiceEnded(packet,serviceType); + + } else if (frameInfo == FrameDataControlFrameType.EndSessionNACK.getValue()) { + + handleServiceEndedNAK(packet, serviceType); + + } else if (frameInfo == FrameDataControlFrameType.ServiceDataACK.getValue()) { + + handleServiceDataACK(packet, serviceType); + + } else if (frameInfo == FrameDataControlFrameType.RegisterSecondaryTransportACK.getValue()) { + + handleSecondaryTransportRegistration(packet.getTransportRecord(),true); + + } else if (frameInfo == FrameDataControlFrameType.RegisterSecondaryTransportNACK.getValue()) { + + String reason = (String) packet.getTag(ControlFrameTags.RPC.RegisterSecondaryTransportNAK.REASON); + DebugTool.logWarning(reason); + handleSecondaryTransportRegistration(packet.getTransportRecord(),false); + + } else if (frameInfo == FrameDataControlFrameType.TransportEventUpdate.getValue()) { + + // Get TCP params + String ipAddr = (String) packet.getTag(ControlFrameTags.RPC.TransportEventUpdate.TCP_IP_ADDRESS); + Integer port = (Integer) packet.getTag(ControlFrameTags.RPC.TransportEventUpdate.TCP_PORT); + + if(secondaryTransportParams == null){ + secondaryTransportParams = new HashMap<>(); + } + + if(ipAddr != null && port != null) { + String address = (port != null && port > 0) ? ipAddr + ":" + port : ipAddr; + secondaryTransportParams.put(TransportType.TCP, new TransportRecord(TransportType.TCP,address)); + + //A new secondary transport just became available. Notify the developer. + notifyDevTransportListener(); + } + + } + + _assemblerForMessageID.remove(packet.getMessageId()); + + } // end-method + + private void handleSingleFrameMessageFrame(SdlPacket packet) { + ProtocolMessage message = new ProtocolMessage(); + message.setPayloadProtected(packet.isEncrypted()); + SessionType serviceType = SessionType.valueOf((byte)packet.getServiceType()); + if (serviceType == SessionType.RPC) { + message.setMessageType(MessageType.RPC); + } else if (serviceType == SessionType.BULK_DATA) { + message.setMessageType(MessageType.BULK); + } // end-if + message.setSessionType(serviceType); + message.setSessionID((byte)packet.getSessionId()); + //If it is WiPro 2.0 it must have binary header + boolean isControlService = message.getSessionType().equals(SessionType.CONTROL); + if (protocolVersion.getMajor() > 1 && !isControlService) { + BinaryFrameHeader binFrameHeader = BinaryFrameHeader. + parseBinaryHeader(packet.payload); + if(binFrameHeader == null) { + return; + } + message.setVersion((byte)protocolVersion.getMajor()); + message.setRPCType(binFrameHeader.getRPCType()); + message.setFunctionID(binFrameHeader.getFunctionID()); + message.setCorrID(binFrameHeader.getCorrID()); + if (binFrameHeader.getJsonSize() > 0){ + message.setData(binFrameHeader.getJsonData()); + } + if (binFrameHeader.getBulkData() != null){ + message.setBulkData(binFrameHeader.getBulkData()); + } + } else { + message.setData(packet.payload); + } + + _assemblerForMessageID.remove(packet.getMessageId()); + + try { + iSdlProtocol.onProtocolMessageReceived(message); + } catch (Exception ex) { + DebugTool.logError(FailurePropagating_Msg + "onProtocolMessageReceived: " + ex.toString(), ex); + handleProtocolError(FailurePropagating_Msg + "onProtocolMessageReceived: ", ex); + } // end-catch + } // end-method + } // end-class + + +} diff --git a/base/src/main/java/com/smartdevicelink/proxy/IProxyListener.java b/base/src/main/java/com/smartdevicelink/proxy/IProxyListener.java index 665a2c9e8..2ef06c3b9 100644 --- a/base/src/main/java/com/smartdevicelink/proxy/IProxyListener.java +++ b/base/src/main/java/com/smartdevicelink/proxy/IProxyListener.java @@ -1,19 +1,19 @@ -package com.smartdevicelink.proxy; - -import com.smartdevicelink.proxy.interfaces.IProxyListenerBase; -import com.smartdevicelink.proxy.rpc.OnAppInterfaceUnregistered; -import com.smartdevicelink.proxy.rpc.RegisterAppInterfaceResponse; -import com.smartdevicelink.proxy.rpc.UnregisterAppInterfaceResponse; - -public interface IProxyListener extends IProxyListenerBase{ - // Adds Legacy Life-cycle Management call-backs to the IProxyListenerAbstract interface - - public void onProxyOpened(); - - public void onRegisterAppInterfaceResponse(RegisterAppInterfaceResponse response); - - public void onOnAppInterfaceUnregistered(OnAppInterfaceUnregistered notification); - - public void onUnregisterAppInterfaceResponse(UnregisterAppInterfaceResponse response); - -} +package com.smartdevicelink.proxy;
+
+import com.smartdevicelink.proxy.interfaces.IProxyListenerBase;
+import com.smartdevicelink.proxy.rpc.OnAppInterfaceUnregistered;
+import com.smartdevicelink.proxy.rpc.RegisterAppInterfaceResponse;
+import com.smartdevicelink.proxy.rpc.UnregisterAppInterfaceResponse;
+
+public interface IProxyListener extends IProxyListenerBase{
+ // Adds Legacy Life-cycle Management call-backs to the IProxyListenerAbstract interface
+
+ public void onProxyOpened();
+
+ public void onRegisterAppInterfaceResponse(RegisterAppInterfaceResponse response);
+
+ public void onOnAppInterfaceUnregistered(OnAppInterfaceUnregistered notification);
+
+ public void onUnregisterAppInterfaceResponse(UnregisterAppInterfaceResponse response);
+
+}
diff --git a/base/src/main/java/com/smartdevicelink/proxy/RPCMessage.java b/base/src/main/java/com/smartdevicelink/proxy/RPCMessage.java index 8135424fc..f4beb9d38 100644 --- a/base/src/main/java/com/smartdevicelink/proxy/RPCMessage.java +++ b/base/src/main/java/com/smartdevicelink/proxy/RPCMessage.java @@ -1,138 +1,138 @@ -package com.smartdevicelink.proxy; - -import com.smartdevicelink.protocol.enums.FunctionID; - -import java.util.Hashtable; - -public class RPCMessage extends RPCStruct { - public static final String KEY_REQUEST = "request"; - public static final String KEY_RESPONSE = "response"; - public static final String KEY_NOTIFICATION = "notification"; - public static final String KEY_FUNCTION_NAME = "name"; - public static final String KEY_PARAMETERS = "parameters"; - public static final String KEY_CORRELATION_ID = "correlationID"; - - public RPCMessage(String functionName) { - this(functionName, "request"); - } - - protected RPCMessage(RPCMessage rpcm) { - this(rpcm.store); - } - - protected RPCMessage(RPCStruct rpcs) { - this("", ""); - this.parameters = rpcs.store; - } - - public RPCMessage(String functionName, String messageType) { - function = new Hashtable<String, Object>(); - parameters = new Hashtable<String, Object>(); - - this.messageType = messageType; - function.put(KEY_PARAMETERS, parameters); - - if (messageType != null) - store.put(messageType, function); - if (functionName != null) - function.put(KEY_FUNCTION_NAME, functionName); - } - - @SuppressWarnings("unchecked") - public RPCMessage(Hashtable<String, Object> hash) { - store = hash; - messageType = getMessageTypeName(hash.keySet()); - function = (Hashtable<String, Object>) hash.get(messageType); - parameters = (Hashtable<String, Object>) function.get(KEY_PARAMETERS); - if (hasKey(hash.keySet(), RPCStruct.KEY_BULK_DATA)) { - setBulkData((byte[]) hash.get(RPCStruct.KEY_BULK_DATA)); - } - if (hasKey(hash.keySet(), RPCStruct.KEY_PROTECTED)) { - setPayloadProtected((Boolean) hash.get(RPCStruct.KEY_PROTECTED)); - } - } - - public FunctionID getFunctionID(){ - if(function.containsKey(KEY_FUNCTION_NAME)){ - return FunctionID.getEnumForString((String)function.get(KEY_FUNCTION_NAME)); - } - return null; - } - - protected String messageType; - protected Hashtable<String, Object> parameters; - protected Hashtable<String, Object> function; - - public String getFunctionName() { - return (String)function.get(KEY_FUNCTION_NAME); - } - - protected void setFunctionName(String functionName) { - function.put(KEY_FUNCTION_NAME, functionName); - } - - public String getMessageType() { - if (messageType.equals(KEY_REQUEST) || - messageType.equals(KEY_RESPONSE) || - messageType.equals(KEY_NOTIFICATION)) { - return messageType; - } - return null; - } - - // Generalized Getters and Setters - - public void setParameters(String key, Object value) { - if (value != null) { - parameters.put(key, value); - } else { - parameters.remove(key); - } - } - - public Object getParameters(String key) { - return parameters.get(key); - } - - @Override - public Object getObject(Class tClass, String key) { - Object obj = parameters.get(key); - return formatObject(tClass, obj); - } - - // Common Object Getters - - @Override - public String getString(String key) { - return (String) parameters.get(key); - } - - @Override - public Integer getInteger(String key) { - return (Integer) parameters.get(key); - } - - @Override - public Float getFloat(String key) { - return (Float) parameters.get(key); - } - - @Override - public Double getDouble(String key) { - return (Double) parameters.get(key); - } - - @Override - public Boolean getBoolean(String key) { return (Boolean) parameters.get(key); } - - @Override - public Long getLong(String key){ - Object result = parameters.get(key); - if (result instanceof Integer) { - return ((Integer) result).longValue(); - }else if(result instanceof Long){ - return (Long) result; - } - return null; - } -} +package com.smartdevicelink.proxy;
+
+import com.smartdevicelink.protocol.enums.FunctionID;
+
+import java.util.Hashtable;
+
+public class RPCMessage extends RPCStruct {
+ public static final String KEY_REQUEST = "request";
+ public static final String KEY_RESPONSE = "response";
+ public static final String KEY_NOTIFICATION = "notification";
+ public static final String KEY_FUNCTION_NAME = "name";
+ public static final String KEY_PARAMETERS = "parameters";
+ public static final String KEY_CORRELATION_ID = "correlationID";
+
+ public RPCMessage(String functionName) {
+ this(functionName, "request");
+ }
+
+ protected RPCMessage(RPCMessage rpcm) {
+ this(cloneStore(rpcm));
+ }
+
+ protected RPCMessage(RPCStruct rpcs) {
+ this("", "");
+ this.parameters = cloneStore(rpcs);
+ }
+
+ public RPCMessage(String functionName, String messageType) {
+ function = new Hashtable<String, Object>();
+ parameters = new Hashtable<String, Object>();
+
+ this.messageType = messageType;
+ function.put(KEY_PARAMETERS, parameters);
+
+ if (messageType != null)
+ store.put(messageType, function);
+ if (functionName != null)
+ function.put(KEY_FUNCTION_NAME, functionName);
+ }
+
+ @SuppressWarnings("unchecked")
+ public RPCMessage(Hashtable<String, Object> hash) {
+ store = hash;
+ messageType = getMessageTypeName(hash.keySet());
+ function = (Hashtable<String, Object>) hash.get(messageType);
+ parameters = (Hashtable<String, Object>) function.get(KEY_PARAMETERS);
+ if (hasKey(hash.keySet(), RPCStruct.KEY_BULK_DATA)) {
+ setBulkData((byte[]) hash.get(RPCStruct.KEY_BULK_DATA));
+ }
+ if (hasKey(hash.keySet(), RPCStruct.KEY_PROTECTED)) {
+ setPayloadProtected((Boolean) hash.get(RPCStruct.KEY_PROTECTED));
+ }
+ }
+
+ public FunctionID getFunctionID(){
+ if(function.containsKey(KEY_FUNCTION_NAME)){
+ return FunctionID.getEnumForString((String)function.get(KEY_FUNCTION_NAME));
+ }
+ return null;
+ }
+
+ protected String messageType;
+ protected Hashtable<String, Object> parameters;
+ protected Hashtable<String, Object> function;
+
+ public String getFunctionName() {
+ return (String)function.get(KEY_FUNCTION_NAME);
+ }
+
+ protected void setFunctionName(String functionName) {
+ function.put(KEY_FUNCTION_NAME, functionName);
+ }
+
+ public String getMessageType() {
+ if (messageType.equals(KEY_REQUEST) ||
+ messageType.equals(KEY_RESPONSE) ||
+ messageType.equals(KEY_NOTIFICATION)) {
+ return messageType;
+ }
+ return null;
+ }
+
+ // Generalized Getters and Setters
+
+ public void setParameters(String key, Object value) {
+ if (value != null) {
+ parameters.put(key, value);
+ } else {
+ parameters.remove(key);
+ }
+ }
+
+ public Object getParameters(String key) {
+ return parameters.get(key);
+ }
+
+ @Override
+ public Object getObject(Class tClass, String key) {
+ Object obj = parameters.get(key);
+ return formatObject(tClass, obj);
+ }
+
+ // Common Object Getters
+
+ @Override
+ public String getString(String key) {
+ return (String) parameters.get(key);
+ }
+
+ @Override
+ public Integer getInteger(String key) {
+ return (Integer) parameters.get(key);
+ }
+
+ @Override
+ public Float getFloat(String key) {
+ return (Float) parameters.get(key);
+ }
+
+ @Override
+ public Double getDouble(String key) {
+ return (Double) parameters.get(key);
+ }
+
+ @Override
+ public Boolean getBoolean(String key) { return (Boolean) parameters.get(key); }
+
+ @Override
+ public Long getLong(String key){
+ Object result = parameters.get(key);
+ if (result instanceof Integer) {
+ return ((Integer) result).longValue();
+ }else if(result instanceof Long){
+ return (Long) result;
+ }
+ return null;
+ }
+}
diff --git a/base/src/main/java/com/smartdevicelink/proxy/RPCNotification.java b/base/src/main/java/com/smartdevicelink/proxy/RPCNotification.java index fdb7761df..b9992e78b 100644 --- a/base/src/main/java/com/smartdevicelink/proxy/RPCNotification.java +++ b/base/src/main/java/com/smartdevicelink/proxy/RPCNotification.java @@ -1,29 +1,29 @@ -/** - * - */ -package com.smartdevicelink.proxy; - -import java.util.Hashtable; - -public class RPCNotification extends RPCMessage { - - public RPCNotification(String functionName) { - super(functionName, RPCMessage.KEY_NOTIFICATION); - } - - public RPCNotification(Hashtable<String, Object> hash) { - super(hash); - } - - public RPCNotification(RPCMessage rpcMsg) { - super(preprocessMsg(rpcMsg)); - } - - static RPCMessage preprocessMsg (RPCMessage rpcMsg) { - if (rpcMsg.getMessageType() != RPCMessage.KEY_NOTIFICATION) { - rpcMsg.messageType = RPCMessage.KEY_NOTIFICATION; - } - - return rpcMsg; - } +/**
+ *
+ */
+package com.smartdevicelink.proxy;
+
+import java.util.Hashtable;
+
+public class RPCNotification extends RPCMessage {
+
+ public RPCNotification(String functionName) {
+ super(functionName, RPCMessage.KEY_NOTIFICATION);
+ }
+
+ public RPCNotification(Hashtable<String, Object> hash) {
+ super(hash);
+ }
+
+ public RPCNotification(RPCMessage rpcMsg) {
+ super(preprocessMsg(rpcMsg));
+ }
+
+ static RPCMessage preprocessMsg (RPCMessage rpcMsg) {
+ if (rpcMsg.getMessageType() != RPCMessage.KEY_NOTIFICATION) {
+ rpcMsg.messageType = RPCMessage.KEY_NOTIFICATION;
+ }
+
+ return rpcMsg;
+ }
}
\ No newline at end of file diff --git a/base/src/main/java/com/smartdevicelink/proxy/RPCRequest.java b/base/src/main/java/com/smartdevicelink/proxy/RPCRequest.java index fa4700a81..d5117318d 100644 --- a/base/src/main/java/com/smartdevicelink/proxy/RPCRequest.java +++ b/base/src/main/java/com/smartdevicelink/proxy/RPCRequest.java @@ -1,50 +1,53 @@ -/** - * - */ -package com.smartdevicelink.proxy; - -import java.util.Hashtable; - -import com.smartdevicelink.proxy.rpc.listeners.OnRPCResponseListener; -import com.smartdevicelink.util.CorrelationIdGenerator; - -public class RPCRequest extends RPCMessage { - - protected OnRPCResponseListener onResponseListener; - - public RPCRequest(String functionName) { - super(functionName, RPCMessage.KEY_REQUEST); - messageType = RPCMessage.KEY_REQUEST; - } - - public RPCRequest(Hashtable<String, Object> hash) { - super(hash); - } - - public RPCRequest(RPCRequest request){ - super(request); - setCorrelationID(CorrelationIdGenerator.generateId()); - } - public Integer getCorrelationID() { - //First we check to see if a correlation ID is set. If not, create one. - if(!function.containsKey(RPCMessage.KEY_CORRELATION_ID)){ - setCorrelationID(CorrelationIdGenerator.generateId()); - } - return (Integer)function.get(RPCMessage.KEY_CORRELATION_ID); - } - - public void setCorrelationID(Integer correlationID) { - if (correlationID != null) { - function.put(RPCMessage.KEY_CORRELATION_ID, correlationID ); - } else { - function.remove(RPCMessage.KEY_CORRELATION_ID); - } - } - public void setOnRPCResponseListener(OnRPCResponseListener listener){ - onResponseListener = listener; - } - - public OnRPCResponseListener getOnRPCResponseListener(){ - return this.onResponseListener; - } -} +/**
+ *
+ */
+package com.smartdevicelink.proxy;
+
+import java.util.Hashtable;
+
+import com.smartdevicelink.proxy.rpc.listeners.OnRPCResponseListener;
+import com.smartdevicelink.util.CorrelationIdGenerator;
+
+public class RPCRequest extends RPCMessage {
+
+ protected OnRPCResponseListener onResponseListener;
+
+ public RPCRequest(String functionName) {
+ super(functionName, RPCMessage.KEY_REQUEST);
+ messageType = RPCMessage.KEY_REQUEST;
+ }
+
+ public RPCRequest(Hashtable<String, Object> hash) {
+ super(hash);
+ }
+
+ public RPCRequest(RPCRequest request){
+ super(request);
+ if (request == null || request.getCorrelationID() == null) {
+ setCorrelationID(CorrelationIdGenerator.generateId());
+ }
+ }
+
+ public Integer getCorrelationID() {
+ //First we check to see if a correlation ID is set. If not, create one.
+ if(!function.containsKey(RPCMessage.KEY_CORRELATION_ID)){
+ setCorrelationID(CorrelationIdGenerator.generateId());
+ }
+ return (Integer)function.get(RPCMessage.KEY_CORRELATION_ID);
+ }
+
+ public void setCorrelationID(Integer correlationID) {
+ if (correlationID != null) {
+ function.put(RPCMessage.KEY_CORRELATION_ID, correlationID );
+ } else {
+ function.remove(RPCMessage.KEY_CORRELATION_ID);
+ }
+ }
+ public void setOnRPCResponseListener(OnRPCResponseListener listener){
+ onResponseListener = listener;
+ }
+
+ public OnRPCResponseListener getOnRPCResponseListener(){
+ return this.onResponseListener;
+ }
+}
diff --git a/base/src/main/java/com/smartdevicelink/proxy/RPCResponse.java b/base/src/main/java/com/smartdevicelink/proxy/RPCResponse.java index 0e6388570..a7c0ed188 100644 --- a/base/src/main/java/com/smartdevicelink/proxy/RPCResponse.java +++ b/base/src/main/java/com/smartdevicelink/proxy/RPCResponse.java @@ -1,183 +1,183 @@ -/** - * - */ -package com.smartdevicelink.proxy; - -import android.support.annotation.NonNull; - -import java.util.Hashtable; - -import com.smartdevicelink.proxy.rpc.enums.Result; - -/** - * Result sent by SDL after an RPC is processed, consists of four parts: - * <ul> - * <li> - * CorrelationID: - * <ul> - * An integer value correlating the response to the corresponding request. - * </ul> - * </li> <li>Success: - * <ul> - * A Boolean indicating whether the original request was successfully processed. - * </ul> - * </li> <li>ResultCode: - * <ul> - * - * <p>The result code provides additional information about a response returning a - * failed outcome.</p> - * - * - * <p>Any response can have at least one, or possibly more, of the following result - * code values: SUCCESS, INVALID_DATA, OUT_OF_MEMORY, TOO_MANY_PENDING_REQUESTS, - * APPLICATION_NOT_REGISTERED, GENERIC_ERROR,REJECTED.</p> - * - * - * <p>Any additional result codes for a given operation can be found in related - * RPCs</p> - * - * </ul> - * </li> <li>Info: - * <ul> - * A string of text representing additional information returned from SDL. This - * could be useful in debugging. - * </ul> - * </li> - * </ul> - */ -public class RPCResponse extends RPCMessage { - public static final String KEY_SUCCESS = "success"; - public static final String KEY_INFO = "info"; - public static final String KEY_RESULT_CODE = "resultCode"; - /** - *<p>Constructs a newly allocated RPCResponse object using function name</p> - *@param functionName a string that indicates the function's name - */ - public RPCResponse(String functionName) { - super(functionName, RPCMessage.KEY_RESPONSE); - } - /** - *<p>Constructs a newly allocated RPCResponse object indicated by the Hashtable parameter</p> - *@param hash The Hashtable to use - */ - public RPCResponse(Hashtable<String, Object> hash) { - super(hash); - } - /** - *<p>Constructs a newly allocated RPCResponse object using a RPCMessage object</p> - *@param rpcMsg The {@linkplain RPCMessage} to use - */ - public RPCResponse(RPCMessage rpcMsg) { - super(preprocessMsg(rpcMsg)); - } - - static RPCMessage preprocessMsg (RPCMessage rpcMsg) { - if (rpcMsg.getMessageType() != RPCMessage.KEY_RESPONSE) { - rpcMsg.messageType = RPCMessage.KEY_RESPONSE; - } - - return rpcMsg; - } - - /** - * <p> - * Returns correlationID the ID of the request - * </p> - * - * @return int the ID of the request - */ - public Integer getCorrelationID() { - return (Integer)function.get(RPCMessage.KEY_CORRELATION_ID); - } - - /** - * <p> - * Set the correlationID - * </p> - * - * @param correlationID - * the ID of the response - */ - public void setCorrelationID(Integer correlationID) { - if (correlationID != null) { - function.put(RPCMessage.KEY_CORRELATION_ID, correlationID ); - } else { - function.remove(RPCMessage.KEY_CORRELATION_ID); - } - } - /** - * <p> - * Returns Success whether the request is successfully processed - * </p> - * - * @return Boolean the status of whether the request is successfully done - */ - public Boolean getSuccess() { - return (Boolean) parameters.get( RPCResponse.KEY_SUCCESS ); - } - /** - * <p> - * Set the Success status - * </p> - * - * @param success - * whether the request is successfully processed - */ - public void setSuccess( @NonNull Boolean success ) { - if (success != null) { - parameters.put(RPCResponse.KEY_SUCCESS, success ); - } - } - /** - * <p> - * Returns ResultCode additional information about a response returning a failed outcome - * </p> - * - * @return {@linkplain Result} the status of whether the request is successfully done - */ - public Result getResultCode() { - Object obj = parameters.get(RPCResponse.KEY_RESULT_CODE); - if (obj instanceof Result) { - return (Result) obj; - } else if (obj instanceof String) { - return Result.valueForString((String) obj); - } - return null; - } - /** - * <p> - * Set the additional information about a response returning a failed outcome - * </p> - * - * @param resultCode - * whether the request is successfully processed - */ - public void setResultCode( @NonNull Result resultCode ) { - if (resultCode != null) { - parameters.put(RPCResponse.KEY_RESULT_CODE, resultCode ); - } - } - /** - * <p> - * Returns a string of text representing additional information returned from SDL - * </p> - * - * @return String A string of text representing additional information returned from SDL - */ - public String getInfo() { - return (String) parameters.get( RPCResponse.KEY_INFO ); - } - /** - * <p> - * Set a string of text representing additional information returned from SDL - * </p> - * - * @param info - * a string of text representing additional information returned from SDL - */ - public void setInfo( String info ) { - if (info != null) { - parameters.put(RPCResponse.KEY_INFO, info ); - } - } -} +/**
+ *
+ */
+package com.smartdevicelink.proxy;
+
+import android.support.annotation.NonNull;
+
+import java.util.Hashtable;
+
+import com.smartdevicelink.proxy.rpc.enums.Result;
+
+/**
+ * Result sent by SDL after an RPC is processed, consists of four parts:
+ * <ul>
+ * <li>
+ * CorrelationID:
+ * <ul>
+ * An integer value correlating the response to the corresponding request.
+ * </ul>
+ * </li> <li>Success:
+ * <ul>
+ * A Boolean indicating whether the original request was successfully processed.
+ * </ul>
+ * </li> <li>ResultCode:
+ * <ul>
+ *
+ * <p>The result code provides additional information about a response returning a
+ * failed outcome.</p>
+ *
+ *
+ * <p>Any response can have at least one, or possibly more, of the following result
+ * code values: SUCCESS, INVALID_DATA, OUT_OF_MEMORY, TOO_MANY_PENDING_REQUESTS,
+ * APPLICATION_NOT_REGISTERED, GENERIC_ERROR,REJECTED.</p>
+ *
+ *
+ * <p>Any additional result codes for a given operation can be found in related
+ * RPCs</p>
+ *
+ * </ul>
+ * </li> <li>Info:
+ * <ul>
+ * A string of text representing additional information returned from SDL. This
+ * could be useful in debugging.
+ * </ul>
+ * </li>
+ * </ul>
+ */
+public class RPCResponse extends RPCMessage {
+ public static final String KEY_SUCCESS = "success";
+ public static final String KEY_INFO = "info";
+ public static final String KEY_RESULT_CODE = "resultCode";
+ /**
+ *<p>Constructs a newly allocated RPCResponse object using function name</p>
+ *@param functionName a string that indicates the function's name
+ */
+ public RPCResponse(String functionName) {
+ super(functionName, RPCMessage.KEY_RESPONSE);
+ }
+ /**
+ *<p>Constructs a newly allocated RPCResponse object indicated by the Hashtable parameter</p>
+ *@param hash The Hashtable to use
+ */
+ public RPCResponse(Hashtable<String, Object> hash) {
+ super(hash);
+ }
+ /**
+ *<p>Constructs a newly allocated RPCResponse object using a RPCMessage object</p>
+ *@param rpcMsg The {@linkplain RPCMessage} to use
+ */
+ public RPCResponse(RPCMessage rpcMsg) {
+ super(preprocessMsg(rpcMsg));
+ }
+
+ static RPCMessage preprocessMsg (RPCMessage rpcMsg) {
+ if (rpcMsg.getMessageType() != RPCMessage.KEY_RESPONSE) {
+ rpcMsg.messageType = RPCMessage.KEY_RESPONSE;
+ }
+
+ return rpcMsg;
+ }
+
+ /**
+ * <p>
+ * Returns correlationID the ID of the request
+ * </p>
+ *
+ * @return int the ID of the request
+ */
+ public Integer getCorrelationID() {
+ return (Integer)function.get(RPCMessage.KEY_CORRELATION_ID);
+ }
+
+ /**
+ * <p>
+ * Set the correlationID
+ * </p>
+ *
+ * @param correlationID
+ * the ID of the response
+ */
+ public void setCorrelationID(Integer correlationID) {
+ if (correlationID != null) {
+ function.put(RPCMessage.KEY_CORRELATION_ID, correlationID );
+ } else {
+ function.remove(RPCMessage.KEY_CORRELATION_ID);
+ }
+ }
+ /**
+ * <p>
+ * Returns Success whether the request is successfully processed
+ * </p>
+ *
+ * @return Boolean the status of whether the request is successfully done
+ */
+ public Boolean getSuccess() {
+ return (Boolean) parameters.get( RPCResponse.KEY_SUCCESS );
+ }
+ /**
+ * <p>
+ * Set the Success status
+ * </p>
+ *
+ * @param success
+ * whether the request is successfully processed
+ */
+ public void setSuccess( @NonNull Boolean success ) {
+ if (success != null) {
+ parameters.put(RPCResponse.KEY_SUCCESS, success );
+ }
+ }
+ /**
+ * <p>
+ * Returns ResultCode additional information about a response returning a failed outcome
+ * </p>
+ *
+ * @return {@linkplain Result} the status of whether the request is successfully done
+ */
+ public Result getResultCode() {
+ Object obj = parameters.get(RPCResponse.KEY_RESULT_CODE);
+ if (obj instanceof Result) {
+ return (Result) obj;
+ } else if (obj instanceof String) {
+ return Result.valueForString((String) obj);
+ }
+ return null;
+ }
+ /**
+ * <p>
+ * Set the additional information about a response returning a failed outcome
+ * </p>
+ *
+ * @param resultCode
+ * whether the request is successfully processed
+ */
+ public void setResultCode( @NonNull Result resultCode ) {
+ if (resultCode != null) {
+ parameters.put(RPCResponse.KEY_RESULT_CODE, resultCode );
+ }
+ }
+ /**
+ * <p>
+ * Returns a string of text representing additional information returned from SDL
+ * </p>
+ *
+ * @return String A string of text representing additional information returned from SDL
+ */
+ public String getInfo() {
+ return (String) parameters.get( RPCResponse.KEY_INFO );
+ }
+ /**
+ * <p>
+ * Set a string of text representing additional information returned from SDL
+ * </p>
+ *
+ * @param info
+ * a string of text representing additional information returned from SDL
+ */
+ public void setInfo( String info ) {
+ if (info != null) {
+ parameters.put(RPCResponse.KEY_INFO, info );
+ }
+ }
+}
diff --git a/base/src/main/java/com/smartdevicelink/proxy/RPCStreamController.java b/base/src/main/java/com/smartdevicelink/proxy/RPCStreamController.java deleted file mode 100644 index 0e2af0bc6..000000000 --- a/base/src/main/java/com/smartdevicelink/proxy/RPCStreamController.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.smartdevicelink.proxy; - -import com.smartdevicelink.streaming.StreamRPCPacketizer; - -public class RPCStreamController { - private StreamRPCPacketizer rpcPacketizer; - private Integer iCorrelationID; - - public RPCStreamController(StreamRPCPacketizer rpcPacketizer, Integer iCorrelationID) - { - this.rpcPacketizer = rpcPacketizer; - this.iCorrelationID = iCorrelationID; - } - - public Integer getCorrelationID() - { - return iCorrelationID; - } - - public void pause() - { - rpcPacketizer.pause(); - } - public void resume() - { - rpcPacketizer.resume(); - } - public void stop() - { - rpcPacketizer.onPutFileStreamError(null, "Stop Putfile Stream Requested"); - } -} diff --git a/base/src/main/java/com/smartdevicelink/proxy/RPCStruct.java b/base/src/main/java/com/smartdevicelink/proxy/RPCStruct.java index 2d8c8ce3b..dd96cdc9b 100644 --- a/base/src/main/java/com/smartdevicelink/proxy/RPCStruct.java +++ b/base/src/main/java/com/smartdevicelink/proxy/RPCStruct.java @@ -1,322 +1,327 @@ -package com.smartdevicelink.proxy; - -import android.util.Log; - -import com.smartdevicelink.marshal.JsonRPCMarshaller; -import com.smartdevicelink.util.Version; - -import org.json.JSONException; -import org.json.JSONObject; - -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Hashtable; -import java.util.List; -import java.util.Set; - -public class RPCStruct { - public static final String KEY_BULK_DATA = "bulkData"; - public static final String KEY_PROTECTED = "protected"; - - private byte[] _bulkData = null; - private Boolean protectedPayload = false; - - private boolean formatRequested = false; - private Version rpcSpecVersion = null; - - - protected Hashtable<String, Object> store = null; - - public boolean getStoreValue(String key) { // for unit testing - return store.contains(key); - } - - public Hashtable<String,Object> getStore () { // for unit testing - return store; - } - - public RPCStruct() { - store = new Hashtable<String, Object>(); - } - - protected RPCStruct(RPCStruct rpcs) { - this.store = rpcs.store; - } - - public RPCStruct(Hashtable<String, Object> hashtable) { - store = hashtable; - //store = (Hashtable<String, Object>) ObjectCopier.copy(hashtable); - } - - public void deserializeJSON(JSONObject jsonObject) throws JSONException { - store = JsonRPCMarshaller.deserializeJSONObject(jsonObject); - - } - - // deserializeJSONObject method moved to JsonRPCMarshaller for consistency - // Keep reference here for backwards compatibility - @Deprecated - public static Hashtable<String, Object> deserializeJSONObject(JSONObject jsonObject) - throws JSONException { - return JsonRPCMarshaller.deserializeJSONObject(jsonObject); - } - - public JSONObject serializeJSON() throws JSONException { - return JsonRPCMarshaller.serializeHashtable(store); - } - - @SuppressWarnings("unchecked") - public JSONObject serializeJSON(byte protocolVersion) throws JSONException { - if (protocolVersion > 1) { - String messageType = getMessageTypeName(store.keySet()); - Hashtable<String, Object> function = (Hashtable<String, Object>) store.get(messageType); - Hashtable<String, Object> parameters = (Hashtable<String, Object>) function.get(RPCMessage.KEY_PARAMETERS); - return JsonRPCMarshaller.serializeHashtable(parameters); - } else return JsonRPCMarshaller.serializeHashtable(store); - } - - /** - * This method should clean the the RPC to make sure it is compliant with the spec. - * <br><br><b> NOTE:</b> Super needs to be called at the END of the method - * - * @param rpcVersion the rpc spec version that has been negotiated. If value is null the - * the max value of RPC spec version this library supports should be used. - * @param formatParams if true, the format method will be called on subsequent params - */ - public void format(Version rpcVersion, boolean formatParams){ - formatRequested = true; - rpcSpecVersion = rpcVersion; - //Should override this method when breaking changes are made to the RPC spec - if(formatParams && store != null){ - Hashtable<String, Object> parameters; - - if(this instanceof RPCMessage) { - //If this is a message (request, response, notification) the parameters have to be - //retrieved from the store object. - String messageType = getMessageTypeName(store.keySet()); - Hashtable<String, Object> function = (Hashtable<String, Object>) store.get(messageType); - parameters = (Hashtable<String, Object>) function.get(RPCMessage.KEY_PARAMETERS); - } else { - //If this is just an RPC struct the store itself should be used - parameters = store; - } - - if (parameters != null) { - for(Object value:parameters.values()){ - internalFormat(rpcVersion, value); - } - } - } - } - - /** - * Cycles through parameters in this RPC to ensure they all get formated - * @param rpcVersion version of the rpc spec that should be used to format this rpc - * @param value the object to investigate if it needs to be formated - */ - private void internalFormat(Version rpcVersion, Object value) { - if(value instanceof RPCStruct) { - ((RPCStruct)value).format(rpcVersion,true); - } else if(value instanceof List<?>) { - List<?> list = (List<?>)value; - if(list != null && list.size() > 0) { - for(Object listItem: list){ - internalFormat(rpcVersion, listItem); - } - } - } - } - - - public byte[] getBulkData() { - return this._bulkData; - } - - public void setBulkData(byte[] bulkData) { - if (bulkData != null) { - this._bulkData = new byte[bulkData.length]; - System.arraycopy(bulkData, 0, _bulkData, 0, bulkData.length); - } - else{ - this._bulkData = null; - } - } - - public void setPayloadProtected(Boolean bVal) { - protectedPayload = bVal; - } - - public Boolean isPayloadProtected() { - return protectedPayload; - } - - protected String getMessageTypeName(Set<String> keys) { - for (String key : keys) { - if (key == null) { - continue; - } - if (key.equals(RPCMessage.KEY_REQUEST) || key.equals(RPCMessage.KEY_RESPONSE) || - key.equals(RPCMessage.KEY_NOTIFICATION)) { - return key; - } - } - return null; - } - - protected boolean hasKey(Set<String> keys, String keyName) { - for (String key : keys) { - if (key == null) { - continue; - } - if (key.equals(keyName)) { - return true; - } - } - return false; - } - - // Generalized Getters and Setters - - public void setValue(String key, Object value){ - if (value != null) { - store.put(key, value); - } else { - store.remove(key); - } - } - - public Object getValue(String key) { - return store.get(key); - } - - public Object getObject(Class tClass, String key) { - Object obj = store.get(key); - return formatObject(tClass, obj); - } - - // Helper methods - - /** - * @param tClass a Class to cast Objects to - * @param obj Object returned from a stored hashtable - * @return A null object if obj is null or if none of the following is true: - * a) obj is an instance of tClass - * b) obj is an instance of String and it tClass has a valid `valueForString` method - * c) obj is an instance of a Hashtable - * d) obj is an instance of a List - */ - protected Object formatObject(Class tClass, Object obj){ - if(obj == null){ - return null; - } else if (tClass.isInstance(obj)) { - return obj; - } else if (obj instanceof String) { - return getValueForString(tClass, (String) obj); - } else if (obj instanceof Hashtable) { - try { - Constructor constructor = tClass.getConstructor(Hashtable.class); - Object customObject = constructor.newInstance((Hashtable<String, Object>) obj); - if(formatRequested && customObject instanceof RPCStruct){ - ((RPCStruct)customObject).format(rpcSpecVersion,true); - } - - return customObject; - } catch (Exception e) { - e.printStackTrace(); - } - } else if (obj instanceof List<?>) { - List<?> list = (List<?>) obj; - if (list != null && list.size() > 0) { - Object item = list.get(0); - if (tClass.isInstance(item)) { - return list; - } else if (item instanceof Hashtable) { - List<Object> newList = new ArrayList<Object>(); - Object customObject; - for (Object hashObj : list) { - try { - Constructor constructor = tClass.getConstructor(Hashtable.class); - customObject = constructor.newInstance((Hashtable<String, Object>) hashObj); - if(formatRequested - && customObject != null - && customObject instanceof RPCStruct){ - ((RPCStruct)customObject).format(rpcSpecVersion,true); - } - newList.add(customObject); - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - return newList; - } else if (item instanceof String){ - List<Object> newList = new ArrayList<Object>(); - for (Object hashObj : list) { - Object toAdd = getValueForString(tClass, (String) hashObj); - if (toAdd != null) { - newList.add(toAdd); - } - } - return newList; - } - } - } - return null; - } - - /** - * @param tClass - a Class with a `valueForString(String s)` method that returns an Object for a given String - * @param s - a String to be converted to an Object using a `valueForString(String s)` method - * @return An Object converted using a `valueForString(String s)` method in the Class passed in, or a null object if such method does not exist - */ - protected Object getValueForString(Class tClass, String s){ - Method valueForString = null; - try { - valueForString = tClass.getDeclaredMethod("valueForString", String.class); - } catch (NoSuchMethodException e) { - e.printStackTrace(); - } - if(valueForString != null){ - try { - Object value = valueForString.invoke(null, (String) s); - return value; - } catch (IllegalAccessException e) { - e.printStackTrace(); - } catch (InvocationTargetException e) { - e.printStackTrace(); - } - } - return null; - } - - // Common Object Getters - public String getString(String key) { - return (String) store.get(key); - } - - public Integer getInteger(String key) { - return (Integer) store.get(key); - } - - public Double getDouble(String key) { - return (Double) store.get(key); - } - - public Float getFloat(String key) { - return (Float) store.get(key); - } - - public Boolean getBoolean(String key) { return (Boolean) store.get(key); } - - public Long getLong(String key){ - Object result = store.get(key); - if (result instanceof Integer) { - return ((Integer) result).longValue(); - }else if(result instanceof Long){ - return (Long) result; - } - return null; - } -} +package com.smartdevicelink.proxy;
+
+import com.smartdevicelink.marshal.JsonRPCMarshaller;
+import com.smartdevicelink.util.Version;
+
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.Hashtable;
+import java.util.List;
+import java.util.Set;
+
+public class RPCStruct {
+ public static final String KEY_BULK_DATA = "bulkData";
+ public static final String KEY_PROTECTED = "protected";
+
+ private byte[] _bulkData = null;
+ private Boolean protectedPayload = false;
+
+ private boolean formatRequested = false;
+ private Version rpcSpecVersion = null;
+
+
+ protected Hashtable<String, Object> store = null;
+
+ public boolean getStoreValue(String key) { // for unit testing
+ return store.contains(key);
+ }
+
+ public Hashtable<String,Object> getStore () { // for unit testing
+ return store;
+ }
+
+ public RPCStruct() {
+ store = new Hashtable<String, Object>();
+ }
+
+ protected RPCStruct(RPCStruct rpcs) {
+ this.store = cloneStore(rpcs);
+ }
+
+ public RPCStruct(Hashtable<String, Object> hashtable) {
+ store = hashtable;
+ //store = (Hashtable<String, Object>) ObjectCopier.copy(hashtable);
+ }
+
+ static Hashtable<String, Object> cloneStore(RPCStruct rpcStruct){
+ if(rpcStruct!= null && rpcStruct.store !=null){
+ return (Hashtable)rpcStruct.store.clone();
+ }
+ return null;
+ }
+
+ public void deserializeJSON(JSONObject jsonObject) throws JSONException {
+ store = JsonRPCMarshaller.deserializeJSONObject(jsonObject);
+
+ }
+
+ // deserializeJSONObject method moved to JsonRPCMarshaller for consistency
+ // Keep reference here for backwards compatibility
+ @Deprecated
+ public static Hashtable<String, Object> deserializeJSONObject(JSONObject jsonObject)
+ throws JSONException {
+ return JsonRPCMarshaller.deserializeJSONObject(jsonObject);
+ }
+
+ public JSONObject serializeJSON() throws JSONException {
+ return JsonRPCMarshaller.serializeHashtable(store);
+ }
+
+ @SuppressWarnings("unchecked")
+ public JSONObject serializeJSON(byte protocolVersion) throws JSONException {
+ if (protocolVersion > 1) {
+ String messageType = getMessageTypeName(store.keySet());
+ Hashtable<String, Object> function = (Hashtable<String, Object>) store.get(messageType);
+ Hashtable<String, Object> parameters = (Hashtable<String, Object>) function.get(RPCMessage.KEY_PARAMETERS);
+ return JsonRPCMarshaller.serializeHashtable(parameters);
+ } else return JsonRPCMarshaller.serializeHashtable(store);
+ }
+
+ /**
+ * This method should clean the the RPC to make sure it is compliant with the spec.
+ * <br><br><b> NOTE:</b> Super needs to be called at the END of the method
+ *
+ * @param rpcVersion the rpc spec version that has been negotiated. If value is null the
+ * the max value of RPC spec version this library supports should be used.
+ * @param formatParams if true, the format method will be called on subsequent params
+ */
+ public void format(Version rpcVersion, boolean formatParams){
+ formatRequested = true;
+ rpcSpecVersion = rpcVersion;
+ //Should override this method when breaking changes are made to the RPC spec
+ if(formatParams && store != null){
+ Hashtable<String, Object> parameters;
+
+ if(this instanceof RPCMessage) {
+ //If this is a message (request, response, notification) the parameters have to be
+ //retrieved from the store object.
+ String messageType = getMessageTypeName(store.keySet());
+ Hashtable<String, Object> function = (Hashtable<String, Object>) store.get(messageType);
+ parameters = (Hashtable<String, Object>) function.get(RPCMessage.KEY_PARAMETERS);
+ } else {
+ //If this is just an RPC struct the store itself should be used
+ parameters = store;
+ }
+
+ if (parameters != null) {
+ for(Object value:parameters.values()){
+ internalFormat(rpcVersion, value);
+ }
+ }
+ }
+ }
+
+ /**
+ * Cycles through parameters in this RPC to ensure they all get formated
+ * @param rpcVersion version of the rpc spec that should be used to format this rpc
+ * @param value the object to investigate if it needs to be formated
+ */
+ private void internalFormat(Version rpcVersion, Object value) {
+ if(value instanceof RPCStruct) {
+ ((RPCStruct)value).format(rpcVersion,true);
+ } else if(value instanceof List<?>) {
+ List<?> list = (List<?>)value;
+ if(list != null && list.size() > 0) {
+ for(Object listItem: list){
+ internalFormat(rpcVersion, listItem);
+ }
+ }
+ }
+ }
+
+
+ public byte[] getBulkData() {
+ return this._bulkData;
+ }
+
+ public void setBulkData(byte[] bulkData) {
+ if (bulkData != null) {
+ this._bulkData = new byte[bulkData.length];
+ System.arraycopy(bulkData, 0, _bulkData, 0, bulkData.length);
+ }
+ else{
+ this._bulkData = null;
+ }
+ }
+
+ public void setPayloadProtected(Boolean bVal) {
+ protectedPayload = bVal;
+ }
+
+ public Boolean isPayloadProtected() {
+ return protectedPayload;
+ }
+
+ protected String getMessageTypeName(Set<String> keys) {
+ for (String key : keys) {
+ if (key == null) {
+ continue;
+ }
+ if (key.equals(RPCMessage.KEY_REQUEST) || key.equals(RPCMessage.KEY_RESPONSE) ||
+ key.equals(RPCMessage.KEY_NOTIFICATION)) {
+ return key;
+ }
+ }
+ return null;
+ }
+
+ protected boolean hasKey(Set<String> keys, String keyName) {
+ for (String key : keys) {
+ if (key == null) {
+ continue;
+ }
+ if (key.equals(keyName)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ // Generalized Getters and Setters
+
+ public void setValue(String key, Object value){
+ if (value != null) {
+ store.put(key, value);
+ } else {
+ store.remove(key);
+ }
+ }
+
+ public Object getValue(String key) {
+ return store.get(key);
+ }
+
+ public Object getObject(Class tClass, String key) {
+ Object obj = store.get(key);
+ return formatObject(tClass, obj);
+ }
+
+ // Helper methods
+
+ /**
+ * @param tClass a Class to cast Objects to
+ * @param obj Object returned from a stored hashtable
+ * @return A null object if obj is null or if none of the following is true:
+ * a) obj is an instance of tClass
+ * b) obj is an instance of String and it tClass has a valid `valueForString` method
+ * c) obj is an instance of a Hashtable
+ * d) obj is an instance of a List
+ */
+ protected Object formatObject(Class tClass, Object obj){
+ if(obj == null){
+ return null;
+ } else if (tClass.isInstance(obj)) {
+ return obj;
+ } else if (obj instanceof String) {
+ return getValueForString(tClass, (String) obj);
+ } else if (obj instanceof Hashtable) {
+ try {
+ Constructor constructor = tClass.getConstructor(Hashtable.class);
+ Object customObject = constructor.newInstance((Hashtable<String, Object>) obj);
+ if(formatRequested && customObject instanceof RPCStruct){
+ ((RPCStruct)customObject).format(rpcSpecVersion,true);
+ }
+
+ return customObject;
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ } else if (obj instanceof List<?>) {
+ List<?> list = (List<?>) obj;
+ if (list != null && list.size() > 0) {
+ Object item = list.get(0);
+ if (tClass.isInstance(item)) {
+ return list;
+ } else if (item instanceof Hashtable) {
+ List<Object> newList = new ArrayList<Object>();
+ Object customObject;
+ for (Object hashObj : list) {
+ try {
+ Constructor constructor = tClass.getConstructor(Hashtable.class);
+ customObject = constructor.newInstance((Hashtable<String, Object>) hashObj);
+ if(formatRequested
+ && customObject != null
+ && customObject instanceof RPCStruct){
+ ((RPCStruct)customObject).format(rpcSpecVersion,true);
+ }
+ newList.add(customObject);
+ } catch (Exception e) {
+ e.printStackTrace();
+ return null;
+ }
+ }
+ return newList;
+ } else if (item instanceof String){
+ List<Object> newList = new ArrayList<Object>();
+ for (Object hashObj : list) {
+ Object toAdd = getValueForString(tClass, (String) hashObj);
+ if (toAdd != null) {
+ newList.add(toAdd);
+ }
+ }
+ return newList;
+ }
+ }
+ }
+ return null;
+ }
+
+ /**
+ * @param tClass - a Class with a `valueForString(String s)` method that returns an Object for a given String
+ * @param s - a String to be converted to an Object using a `valueForString(String s)` method
+ * @return An Object converted using a `valueForString(String s)` method in the Class passed in, or a null object if such method does not exist
+ */
+ protected Object getValueForString(Class tClass, String s){
+ Method valueForString = null;
+ try {
+ valueForString = tClass.getDeclaredMethod("valueForString", String.class);
+ } catch (NoSuchMethodException e) {
+ e.printStackTrace();
+ }
+ if(valueForString != null){
+ try {
+ Object value = valueForString.invoke(null, (String) s);
+ return value;
+ } catch (IllegalAccessException e) {
+ e.printStackTrace();
+ } catch (InvocationTargetException e) {
+ e.printStackTrace();
+ }
+ }
+ return null;
+ }
+
+ // Common Object Getters
+ public String getString(String key) {
+ return (String) store.get(key);
+ }
+
+ public Integer getInteger(String key) {
+ return (Integer) store.get(key);
+ }
+
+ public Double getDouble(String key) {
+ return (Double) store.get(key);
+ }
+
+ public Float getFloat(String key) {
+ return (Float) store.get(key);
+ }
+
+ public Boolean getBoolean(String key) { return (Boolean) store.get(key); }
+
+ public Long getLong(String key){
+ Object result = store.get(key);
+ if (result instanceof Integer) {
+ return ((Integer) result).longValue();
+ }else if(result instanceof Long){
+ return (Long) result;
+ }
+ return null;
+ }
+}
diff --git a/base/src/main/java/com/smartdevicelink/proxy/SystemCapabilityManager.java b/base/src/main/java/com/smartdevicelink/proxy/SystemCapabilityManager.java index 6cf2d496c..5cb798869 100644 --- a/base/src/main/java/com/smartdevicelink/proxy/SystemCapabilityManager.java +++ b/base/src/main/java/com/smartdevicelink/proxy/SystemCapabilityManager.java @@ -9,12 +9,15 @@ import com.smartdevicelink.proxy.rpc.enums.SystemCapabilityType; import com.smartdevicelink.proxy.rpc.listeners.OnRPCListener; import com.smartdevicelink.proxy.rpc.listeners.OnRPCResponseListener; import com.smartdevicelink.util.CorrelationIdGenerator; +import com.smartdevicelink.util.DebugTool; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; +import static com.smartdevicelink.protocol.enums.FunctionID.SET_DISPLAY_LAYOUT; + public class SystemCapabilityManager { private final HashMap<SystemCapabilityType, Object> cachedSystemCapabilities; private final HashMap<SystemCapabilityType, CopyOnWriteArrayList<OnSystemCapabilityListener>> onSystemCapabilityListeners; @@ -191,9 +194,16 @@ public class SystemCapabilityManager { /** * @param systemCapabilityType Type of capability desired - * passes GetSystemCapabilityType request to `callback` to be sent by proxy + * passes GetSystemCapabilityType request to `callback` to be sent by proxy. + * this method will send RPC and call the listener's callback only if the systemCapabilityType is queryable */ private void retrieveCapability(final SystemCapabilityType systemCapabilityType, final OnSystemCapabilityListener scListener){ + if (!systemCapabilityType.isQueryable()){ + String message = "This systemCapabilityType cannot be queried for"; + DebugTool.logError(message); + scListener.onError(message); + return; + } final GetSystemCapability request = new GetSystemCapability(); request.setSystemCapabilityType(systemCapabilityType); request.setOnRPCResponseListener(new OnRPCResponseListener() { diff --git a/base/src/main/java/com/smartdevicelink/proxy/TTSChunkFactory.java b/base/src/main/java/com/smartdevicelink/proxy/TTSChunkFactory.java index 75305bbd0..b8b847261 100644 --- a/base/src/main/java/com/smartdevicelink/proxy/TTSChunkFactory.java +++ b/base/src/main/java/com/smartdevicelink/proxy/TTSChunkFactory.java @@ -1,39 +1,39 @@ -package com.smartdevicelink.proxy; - -import java.util.Vector; - -import com.smartdevicelink.proxy.rpc.TTSChunk; -import com.smartdevicelink.proxy.rpc.enums.SpeechCapabilities; - -public class TTSChunkFactory { - - public static TTSChunk createChunk(SpeechCapabilities type, String text) { - TTSChunk ret = new TTSChunk(); - ret.setType(type); - ret.setText(text); - return ret; - } - - public static Vector<TTSChunk> createSimpleTTSChunks(String simple) { - if (simple == null) { - return null; - } - - Vector<TTSChunk> chunks = new Vector<TTSChunk>(); - - TTSChunk chunk = createChunk(SpeechCapabilities.TEXT, simple); - chunks.add(chunk); - return chunks; - } - - public static Vector<TTSChunk> createPrerecordedTTSChunks(String prerecorded) { - if (prerecorded == null) { - return null; - } - - Vector<TTSChunk> chunks = new Vector<TTSChunk>(); - TTSChunk chunk = createChunk(SpeechCapabilities.PRE_RECORDED, prerecorded); - chunks.add(chunk); - return chunks; - } -} +package com.smartdevicelink.proxy;
+
+import java.util.Vector;
+
+import com.smartdevicelink.proxy.rpc.TTSChunk;
+import com.smartdevicelink.proxy.rpc.enums.SpeechCapabilities;
+
+public class TTSChunkFactory {
+
+ public static TTSChunk createChunk(SpeechCapabilities type, String text) {
+ TTSChunk ret = new TTSChunk();
+ ret.setType(type);
+ ret.setText(text);
+ return ret;
+ }
+
+ public static Vector<TTSChunk> createSimpleTTSChunks(String simple) {
+ if (simple == null) {
+ return null;
+ }
+
+ Vector<TTSChunk> chunks = new Vector<TTSChunk>();
+
+ TTSChunk chunk = createChunk(SpeechCapabilities.TEXT, simple);
+ chunks.add(chunk);
+ return chunks;
+ }
+
+ public static Vector<TTSChunk> createPrerecordedTTSChunks(String prerecorded) {
+ if (prerecorded == null) {
+ return null;
+ }
+
+ Vector<TTSChunk> chunks = new Vector<TTSChunk>();
+ TTSChunk chunk = createChunk(SpeechCapabilities.PRE_RECORDED, prerecorded);
+ chunks.add(chunk);
+ return chunks;
+ }
+}
diff --git a/base/src/main/java/com/smartdevicelink/proxy/callbacks/InternalProxyMessage.java b/base/src/main/java/com/smartdevicelink/proxy/callbacks/InternalProxyMessage.java index 1f6598f23..dc03f5c72 100644 --- a/base/src/main/java/com/smartdevicelink/proxy/callbacks/InternalProxyMessage.java +++ b/base/src/main/java/com/smartdevicelink/proxy/callbacks/InternalProxyMessage.java @@ -1,19 +1,19 @@ -package com.smartdevicelink.proxy.callbacks; - -public class InternalProxyMessage { - private String _functionName; - public static final String OnProxyError = "OnProxyError"; - public static final String OnProxyOpened = "OnProxyOpened"; - public static final String OnProxyClosed = "OnProxyClosed"; - public static final String OnServiceEnded = "OnServiceEnded"; - public static final String OnServiceNACKed = "OnServiceNACKed"; - - public InternalProxyMessage(String functionName) { - //this(functionName, null, null); - this._functionName = functionName; - } - - public String getFunctionName() { - return _functionName; - } +package com.smartdevicelink.proxy.callbacks;
+
+public class InternalProxyMessage {
+ private String _functionName;
+ public static final String OnProxyError = "OnProxyError";
+ public static final String OnProxyOpened = "OnProxyOpened";
+ public static final String OnProxyClosed = "OnProxyClosed";
+ public static final String OnServiceEnded = "OnServiceEnded";
+ public static final String OnServiceNACKed = "OnServiceNACKed";
+
+ public InternalProxyMessage(String functionName) {
+ //this(functionName, null, null);
+ this._functionName = functionName;
+ }
+
+ public String getFunctionName() {
+ return _functionName;
+ }
}
\ No newline at end of file diff --git a/base/src/main/java/com/smartdevicelink/proxy/callbacks/OnError.java b/base/src/main/java/com/smartdevicelink/proxy/callbacks/OnError.java index e93fc684c..0323afa15 100644 --- a/base/src/main/java/com/smartdevicelink/proxy/callbacks/OnError.java +++ b/base/src/main/java/com/smartdevicelink/proxy/callbacks/OnError.java @@ -1,25 +1,25 @@ -package com.smartdevicelink.proxy.callbacks; - -public class OnError extends InternalProxyMessage { - - private String _info; - private Exception _e; - - public OnError() { - super(InternalProxyMessage.OnProxyError); - } - - public OnError(String info, Exception e) { - super(InternalProxyMessage.OnProxyError); - this._info = info; - this._e = e; - } - - public String getInfo() { - return _info; - } - - public Exception getException() { - return _e; - } +package com.smartdevicelink.proxy.callbacks;
+
+public class OnError extends InternalProxyMessage {
+
+ private String _info;
+ private Exception _e;
+
+ public OnError() {
+ super(InternalProxyMessage.OnProxyError);
+ }
+
+ public OnError(String info, Exception e) {
+ super(InternalProxyMessage.OnProxyError);
+ this._info = info;
+ this._e = e;
+ }
+
+ public String getInfo() {
+ return _info;
+ }
+
+ public Exception getException() {
+ return _e;
+ }
}
\ No newline at end of file diff --git a/base/src/main/java/com/smartdevicelink/proxy/callbacks/OnProxyClosed.java b/base/src/main/java/com/smartdevicelink/proxy/callbacks/OnProxyClosed.java index 2e82ee325..9a32c4a8d 100644 --- a/base/src/main/java/com/smartdevicelink/proxy/callbacks/OnProxyClosed.java +++ b/base/src/main/java/com/smartdevicelink/proxy/callbacks/OnProxyClosed.java @@ -1,33 +1,33 @@ -package com.smartdevicelink.proxy.callbacks; - -import com.smartdevicelink.proxy.rpc.enums.SdlDisconnectedReason; - -public class OnProxyClosed extends InternalProxyMessage { - - private String _info; - private Exception _e; - private SdlDisconnectedReason _reason; - - public OnProxyClosed() { - super(InternalProxyMessage.OnProxyClosed); - } - - public OnProxyClosed(String info, Exception e, SdlDisconnectedReason reason) { - super(InternalProxyMessage.OnProxyClosed); - this._info = info; - this._e = e; - this._reason = reason; - } - - public String getInfo() { - return _info; - } - - public SdlDisconnectedReason getReason() { - return _reason; - } - - public Exception getException() { - return _e; - } +package com.smartdevicelink.proxy.callbacks;
+
+import com.smartdevicelink.proxy.rpc.enums.SdlDisconnectedReason;
+
+public class OnProxyClosed extends InternalProxyMessage {
+
+ private String _info;
+ private Exception _e;
+ private SdlDisconnectedReason _reason;
+
+ public OnProxyClosed() {
+ super(InternalProxyMessage.OnProxyClosed);
+ }
+
+ public OnProxyClosed(String info, Exception e, SdlDisconnectedReason reason) {
+ super(InternalProxyMessage.OnProxyClosed);
+ this._info = info;
+ this._e = e;
+ this._reason = reason;
+ }
+
+ public String getInfo() {
+ return _info;
+ }
+
+ public SdlDisconnectedReason getReason() {
+ return _reason;
+ }
+
+ public Exception getException() {
+ return _e;
+ }
}
\ No newline at end of file diff --git a/base/src/main/java/com/smartdevicelink/proxy/callbacks/OnProxyOpened.java b/base/src/main/java/com/smartdevicelink/proxy/callbacks/OnProxyOpened.java index 82a1ed706..1fa9c19eb 100644 --- a/base/src/main/java/com/smartdevicelink/proxy/callbacks/OnProxyOpened.java +++ b/base/src/main/java/com/smartdevicelink/proxy/callbacks/OnProxyOpened.java @@ -1,8 +1,8 @@ -package com.smartdevicelink.proxy.callbacks; - -public class OnProxyOpened extends InternalProxyMessage { - - public OnProxyOpened() { - super(InternalProxyMessage.OnProxyOpened); - } -} +package com.smartdevicelink.proxy.callbacks;
+
+public class OnProxyOpened extends InternalProxyMessage {
+
+ public OnProxyOpened() {
+ super(InternalProxyMessage.OnProxyOpened);
+ }
+}
diff --git a/base/src/main/java/com/smartdevicelink/proxy/constants/Jingles.java b/base/src/main/java/com/smartdevicelink/proxy/constants/Jingles.java index a47572317..b029e55e8 100644 --- a/base/src/main/java/com/smartdevicelink/proxy/constants/Jingles.java +++ b/base/src/main/java/com/smartdevicelink/proxy/constants/Jingles.java @@ -1,15 +1,15 @@ -package com.smartdevicelink.proxy.constants; - -@Deprecated -public class Jingles { - public static final String POSITIVE_JINGLE = "POSITIVE_JINGLE"; - - public static final String NEGATIVE_JINGLE = "NEGATIVE_JINGLE"; - - public static final String INITIAL_JINGLE = "INITIAL_JINGLE"; - - public static final String LISTEN_JINGLE = "LISTEN_JINGLE"; - - public static final String HELP_JINGLE = "HELP_JINGLE"; - +package com.smartdevicelink.proxy.constants;
+
+@Deprecated
+public class Jingles {
+ public static final String POSITIVE_JINGLE = "POSITIVE_JINGLE";
+
+ public static final String NEGATIVE_JINGLE = "NEGATIVE_JINGLE";
+
+ public static final String INITIAL_JINGLE = "INITIAL_JINGLE";
+
+ public static final String LISTEN_JINGLE = "LISTEN_JINGLE";
+
+ public static final String HELP_JINGLE = "HELP_JINGLE";
+
}
\ No newline at end of file diff --git a/base/src/main/java/com/smartdevicelink/proxy/constants/Names.java b/base/src/main/java/com/smartdevicelink/proxy/constants/Names.java index f578dce18..26729e997 100644 --- a/base/src/main/java/com/smartdevicelink/proxy/constants/Names.java +++ b/base/src/main/java/com/smartdevicelink/proxy/constants/Names.java @@ -1,506 +1,506 @@ -package com.smartdevicelink.proxy.constants; - -@Deprecated -public class Names { - public static final String request = "request"; - public static final String response = "response"; - public static final String notification = "notification"; - public static final String function_name = "name"; - public static final String parameters = "parameters"; - public static final String bulkData = "bulkData"; - - public static final String RegisterAppInterface = "RegisterAppInterface"; - public static final String UnregisterAppInterface = "UnregisterAppInterface"; - public static final String Alert = "Alert"; - public static final String Show = "Show"; - public static final String Speak = "Speak"; - public static final String AddCommand = "AddCommand"; - public static final String DeleteCommand = "DeleteCommand"; - public static final String AddSubMenu = "AddSubMenu"; - public static final String DeleteSubMenu = "DeleteSubMenu"; - public static final String CreateInteractionChoiceSet = "CreateInteractionChoiceSet"; - public static final String DeleteInteractionChoiceSet = "DeleteInteractionChoiceSet"; - public static final String PerformInteraction = "PerformInteraction"; - public static final String DialNumber = "DialNumber"; - public static final String EncodedSyncPData = "EncodedSyncPData"; - public static final String SyncPData = "SyncPData"; - public static final String SubscribeButton = "SubscribeButton"; - public static final String UnsubscribeButton = "UnsubscribeButton"; - public static final String SubscribeVehicleData = "SubscribeVehicleData"; - public static final String UnsubscribeVehicleData = "UnsubscribeVehicleData"; - public static final String SetMediaClockTimer = "SetMediaClockTimer"; - public static final String SetGlobalProperties = "SetGlobalProperties"; - public static final String GenericResponse = "GenericResponse"; - public static final String ScrollableMessage = "ScrollableMessage"; - public static final String GetDID = "GetDID"; - public static final String GetDTCs = "GetDTCs"; - public static final String DiagnosticMessage = "DiagnosticMessage"; - public static final String SystemRequest = "SystemRequest"; - public static final String ReadDID = "ReadDID"; - public static final String OnVehicleData = "OnVehicleData"; - public static final String GetFile = "GetFile"; - public static final String PutFile = "PutFile"; - public static final String DeleteFile = "DeleteFile"; - public static final String ListFiles = "ListFiles"; - public static final String EndAudioCapture = "EndAudioCapture"; - public static final String GetVehicleData = "GetVehicleData"; - public static final String ResetGlobalProperties = "ResetGlobalProperties"; - public static final String PerformAudioCapture = "PerformAudioCapture"; - public static final String SetAppIcon = "SetAppIcon"; - public static final String ChangeRegistration = "ChangeRegistration"; - public static final String SetDisplayLayout = "SetDisplayLayout"; - public static final String keypressMode = "keypressMode"; - public static final String keyboardLayout = "keyboardLayout"; - public static final String limitedCharacterList = "limitedCharacterList"; - public static final String autoCompleteText = "autoCompleteText"; - public static final String OnLanguageChange = "OnLanguageChange"; - public static final String hmiDisplayLanguage = "hmiDisplayLanguage"; - public static final String displayLayout = "displayLayout"; - public static final String ttsName = "ttsName"; - public static final String hmiDisplayLanguageDesired = "hmiDisplayLanguageDesired"; - public static final String appHMIType = "appHMIType"; - public static final String hashID = "hashID"; - public static final String appID = "appID"; - public static final String vrHelpTitle = "vrHelpTitle"; - public static final String graphic = "graphic"; - public static final String customPresets = "customPresets"; - public static final String softButtonCapabilities = "softButtonCapabilities"; - public static final String presetBankCapabilities = "presetBankCapabilities"; - public static final String vehicleType = "vehicleType"; - public static final String make = "make"; - public static final String model = "model"; - public static final String modelYear = "modelYear"; - public static final String trim = "trim"; - public static final String allowed = "allowed"; - public static final String userDisallowed = "userDisallowed"; - public static final String rpcName = "rpcName"; - public static final String hmiPermissions = "hmiPermissions"; - public static final String parameterPermissions = "parameterPermissions"; - public static final String permissionItem = "permissionItem"; - public static final String numTicks = "numTicks"; - public static final String sliderHeader = "sliderHeader"; - public static final String sliderFooter = "sliderFooter"; - public static final String PerformAudioPassThru = "PerformAudioPassThru"; - public static final String PerformAudioPassThruResponse = "PerformAudioPassThruResponse"; - public static final String EndAudioPassThru = "EndAudioPassThru"; - public static final String EndAudioPassThruResponse = "EndAudioPassThruResponse"; - public static final String OnAudioPassThru = "OnAudioPassThru"; - public static final String ShowConstantTBT = "ShowConstantTBT"; - public static final String AlertManeuver = "AlertManeuver"; - public static final String UpdateTurnList = "UpdateTurnList"; - - public static final String OnCommand = "OnCommand"; - public static final String OnDataPublished = "OnDataPublished"; - public static final String OnButtonPress = "OnButtonPress"; - public static final String OnButtonEvent = "OnButtonEvent"; - public static final String OnHMIStatus = "OnHMIStatus"; - public static final String OnTBTClientState = "OnTBTClientState"; - public static final String OnEncodedSyncPData = "OnEncodedSyncPData"; - public static final String onEncodedSyncPDataResponse = "onEncodedSyncPDataResponse"; - public static final String OnSyncPData = "OnSyncPData"; - public static final String onOnSyncPData = "onOnSyncPData"; - public static final String OnDriverDistraction = "OnDriverDistraction"; - public static final String OnAppInterfaceUnregistered = "OnAppInterfaceUnregistered"; - public static final String OnKeyboardInput = "OnKeyboardInput"; - public static final String OnTouchEvent = "OnTouchEvent"; - public static final String OnSystemRequest = "OnSystemRequest"; - public static final String OnHashChange = "OnHashChange"; - public static final String OnProxyClosed = "OnProxyClosed"; - public static final String OnProxyError = "OnProxyError"; - public static final String OnProxyOpened = "OnProxyOpened"; - public static final String OnProxyUnusable = "OnProxyUnusable"; - public static final String OnHMILevelChange = "OnHMILevelChange"; - public static final String OnSdlChoiceChosen = "OnSdlChoiceChosen"; - public static final String OnPermissionsChange = "OnPermissionsChange"; - public static final String OnScreenPresetsAvailable = "OnScreenPresetsAvailable"; - public static final String isHighlighted = "isHighlighted"; - public static final String softButtonID = "softButtonID"; - public static final String fileType = "fileType"; - public static final String url = "url"; - public static final String requestType = "requestType"; - public static final String fileName = "fileName"; - public static final String persistentFile = "persistentFile"; - public static final String spaceAvailable = "spaceAvailable"; - public static final String filenames = "filenames"; - public static final String cmdIcon = "cmdIcon"; - public static final String Slider = "Slider"; - public static final String sliderPosition = "sliderPosition"; - public static final String samplingRate = "samplingRate"; - public static final String audioType = "audioType"; - public static final String satRadioESN = "satRadioESN"; - public static final String dtc = "dtc"; - public static final String tryAgainTime = "tryAgainTime"; - - public static final String success = "success"; - public static final String resultCode = "resultCode"; - public static final String info = "info"; - - public static final String payload = "payload"; - public static final String reason = "reason"; - public static final String state = "state"; - public static final String cmdID = "cmdID"; - public static final String menuParams = "menuParams"; - public static final String parentID = "parentID"; - public static final String position = "position"; - public static final String menuName = "menuName"; - public static final String vrCommands = "vrCommands"; - public static final String language = "language"; - public static final String languageDesired = "languageDesired"; - public static final String triggerSource = "triggerSource"; - public static final String subscriptionType = "subscriptionType"; - public static final String data = "data"; - public static final String event = "event"; - public static final String correlationID = "correlationID"; - public static final String sdlMsgVersion = "syncMsgVersion"; - public static final String deviceInfo = "deviceInfo"; - public static final String majorVersion = "majorVersion"; - public static final String minorVersion = "minorVersion"; - public static final String appName = "appName"; - public static final String ngnMediaScreenAppName = "ngnMediaScreenAppName"; - public static final String isMediaApplication = "isMediaApplication"; - public static final String vrSynonyms = "vrSynonyms"; - public static final String usesVehicleData = "usesVehicleData"; - public static final String text = "text"; - public static final String type = "type"; - public static final String ttsChunks = "ttsChunks"; - public static final String playTone = "playTone"; - public static final String duration = "duration"; - public static final String mainField1 = "mainField1"; - public static final String mainField2 = "mainField2"; - public static final String mainField3 = "mainField3"; - public static final String mainField4 = "mainField4"; - public static final String statusBar = "statusBar"; - public static final String name = "name"; - public static final String menuID = "menuID"; - public static final String longPress = "longPress"; - public static final String shortPress = "shortPress"; - public static final String buttonName = "buttonName"; - public static final String buttonPressMode = "buttonPressMode"; - public static final String buttonEventMode = "buttonEventMode"; - public static final String minutes = "minutes"; - public static final String seconds = "seconds"; - public static final String startTime = "startTime"; - public static final String endTime = "endTime"; - public static final String updateMode = "updateMode"; - public static final String mediaClock = "mediaClock"; - public static final String initialText = "initialText"; - public static final String initialPrompt = "initialPrompt"; - public static final String helpPrompt = "helpPrompt"; - public static final String timeoutPrompt = "timeoutPrompt"; - public static final String timeout = "timeout"; - public static final String choiceSet = "choiceSet"; - public static final String interactionMode = "interactionMode"; - public static final String result = "result"; - public static final String alertText1 = "alertText1"; - public static final String alertText2 = "alertText2"; - public static final String alertText3 = "alertText3"; - public static final String shortPressAvailable = "shortPressAvailable"; - public static final String longPressAvailable = "longPressAvailable"; - public static final String upDownAvailable = "upDownAvailable"; - public static final String width = "width"; - public static final String height = "height"; - public static final String resolutionWidth = "resolutionWidth"; - public static final String resolutionHeight = "resolutionHeight"; - public static final String characterSet = "characterSet"; - public static final String displayType = "displayType"; - public static final String mediaClockFormats = "mediaClockFormats"; - public static final String textFields = "textFields"; - public static final String imageFields = "imageFields"; - public static final String autoActivateID = "autoActivateID"; - public static final String vehicleDataCapabilities = "vehicleDataCapabilities"; - public static final String speechCapabilities = "speechCapabilities"; - public static final String vrCapabilities = "vrCapabilities"; - public static final String audioPassThruCapabilities = "audioPassThruCapabilities"; - public static final String buttonCapabilities = "buttonCapabilities"; - public static final String displayCapabilities = "displayCapabilities"; - public static final String hmiZoneCapabilities = "hmiZoneCapabilities"; - public static final String interactionChoiceSetID = "interactionChoiceSetID"; - public static final String interactionChoiceSetIDList = "interactionChoiceSetIDList"; - public static final String audioFileName = "audioFileName"; - public static final String gpsPositionValid = "gpsPositionValid"; - public static final String longitudeDegrees = "longitudeDegrees"; - public static final String latitudeDegrees = "latitudeDegrees"; - public static final String utcYear = "utcYear"; - public static final String utcMonth = "utcMonth"; - public static final String utcDay = "utcDay"; - public static final String utcHours = "utcHours"; - public static final String utcMinutes = "utcMinutes"; - public static final String utcSeconds = "utcSeconds"; - public static final String compassDirection = "compassDirection"; - public static final String pdop = "pdop"; - public static final String vdop = "vdop"; - public static final String hdop = "hdop"; - public static final String actual = "actual"; - public static final String satellites = "satellites"; - public static final String dimension = "dimension"; - public static final String altitude = "altitude"; - public static final String heading = "heading"; - public static final String speed = "speed"; - public static final String number = "number"; - public static final String smartDeviceLinkFileName = "syncFileName"; - public static final String localFileName = "localFileName"; - public static final String maxDuration = "maxDuration"; - public static final String timerMode = "timerMode"; - public static final String status = "status"; - public static final String pressure = "pressure"; - public static final String hours = "hours"; - public static final String rows = "rows"; - public static final String pressureTellTale = "pressureTellTale"; - public static final String leftFront = "leftFront"; - public static final String rightFront = "rightFront"; - public static final String leftRear = "leftRear"; - public static final String rightRear = "rightRear"; - public static final String innerLeftRear = "innerLeftRear"; - public static final String innerRightRear = "innerRightRear"; - public static final String VehicleData = "VehicleData"; - public static final String alignment = "alignment"; - public static final String mediaTrack = "mediaTrack"; - public static final String properties = "properties"; - public static final String choiceID = "choiceID"; - public static final String bitsPerSample = "bitsPerSample"; - public static final String hmiLevel = "hmiLevel"; - public static final String audioStreamingState = "audioStreamingState"; - public static final String systemContext = "systemContext"; - public static final String sdlChoice = "sdlChoice"; - public static final String sdlCommand = "sdlCommand"; - public static final String URL = "URL"; - public static final String Timeout = "Timeout"; - public static final String PermissionGroupName = "PermissionGroupName"; - public static final String PermissionGroupStatus = "PermissionGroupStatus"; - public static final String PermissionGroupItems = "PermissionGroupItems"; - public static final String audioPacket = "audioPacket"; - public static final String audioPassThruDisplayText1 = "audioPassThruDisplayText1"; - public static final String audioPassThruDisplayText2 = "audioPassThruDisplayText2"; - public static final String bitRate = "bitRate"; - public static final String rpm = "rpm"; - public static final String fuelLevel = "fuelLevel"; - public static final String avgFuelEconomy = "avgFuelEconomy"; - public static final String batteryVoltage = "batteryVoltage"; - public static final String externalTemperature = "externalTemperature"; - public static final String vin = "vin"; - public static final String prndl = "prndl"; - public static final String tirePressure = "tirePressure"; - public static final String batteryPackVoltage = "batteryPackVoltage"; - public static final String batteryPackCurrent = "batteryPackCurrent"; - public static final String batteryPackTemperature = "batteryPackTemperature"; - public static final String engineTorque = "engineTorque"; - public static final String odometer = "odometer"; - public static final String tripOdometer = "tripOdometer"; - public static final String genericbinary = "genericbinary"; - public static final String GPSData = "GPSData"; - public static final String gps = "gps"; - public static final String fuelLevel_State = "fuelLevel_State"; - public static final String instantFuelConsumption = "instantFuelConsumption"; - public static final String beltStatus = "beltStatus"; - public static final String bodyInformation = "bodyInformation"; - public static final String deviceStatus = "deviceStatus"; - public static final String driverBraking = "driverBraking"; - public static final String wiperStatus = "wiperStatus"; - public static final String fuelEconomy = "fuelEconomy"; - public static final String engineOilLife = "engineOilLife"; - public static final String headLampStatus = "headLampStatus"; - public static final String brakeTorque = "brakeTorque"; - public static final String turboBoost = "turboBoost"; - public static final String coolantTemp = "coolantTemp"; - public static final String airFuelRatio = "airFuelRatio"; - public static final String coolingHeadTemp = "coolingHeadTemp"; - public static final String oilTemp = "oilTemp"; - public static final String intakeAirTemp = "intakeAirTemp"; - public static final String gearShiftAdvice = "gearShiftAdvice"; - public static final String acceleration = "acceleration"; - public static final String accPedalPosition = "accPedalPosition"; - public static final String clutchPedalPosition = "clutchPedalPosition"; - public static final String reverseGearStatus = "reverseGearStatus"; - public static final String accTorque = "accTorque"; - public static final String ambientLightStatus = "ambientLightStatus"; - public static final String ambientLightSensorStatus = "ambientLightSensorStatus"; - public static final String dataType = "dataType"; - public static final String identifier = "identifier"; - public static final String statusByte = "statusByte"; - public static final String didResult = "didResult"; - public static final String ecuName = "ecuName"; - public static final String didLocation = "didLocation"; - public static final String value = "value"; - public static final String softButtonName = "softButtonName"; - public static final String imageSupported = "imageSupported"; - public static final String systemAction = "systemAction"; - public static final String image = "image"; - public static final String secondaryText = "secondaryText"; - public static final String tertiaryText = "tertiaryText"; - public static final String secondaryImage = "secondaryImage"; - public static final String imageType = "imageType"; - public static final String fileData = "fileData"; - public static final String scrollableMessageBody = "scrollableMessageBody"; - public static final String softButtons = "softButtons"; - public static final String customButtonID = "customButtonID"; - public static final String vrHelp = "vrHelp"; - public static final String interactionLayout = "interactionLayout"; - public static final String customButtonName = "customButtonName"; - public static final String navigationText = "navigationText"; - public static final String turnIcon = "turnIcon"; - public static final String nextTurnIcon = "nextTurnIcon"; - public static final String navigationText1 = "navigationText1"; - public static final String navigationText2 = "navigationText2"; - public static final String eta = "eta"; - public static final String totalDistance = "totalDistance"; - public static final String distanceToManeuver = "distanceToManeuver"; - public static final String distanceToManeuverScale = "distanceToManeuverScale"; - public static final String maneuverComplete = "maneuverComplete"; - public static final String turnList = "turnList"; - public static final String steeringWheelAngle = "steeringWheelAngle"; - public static final String menuTitle = "menuTitle"; - public static final String menuIcon = "menuIcon"; - public static final String keyboardProperties = "keyboardProperties"; - public static final String driverBeltDeployed = "driverBeltDeployed"; - public static final String passengerBeltDeployed = "passengerBeltDeployed"; - public static final String passengerBuckleBelted = "passengerBuckleBelted"; - public static final String driverBuckleBelted = "driverBuckleBelted"; - public static final String leftRow2BuckleBelted = "leftRow2BuckleBelted"; - public static final String passengerChildDetected = "passengerChildDetected"; - public static final String rightRow2BuckleBelted = "rightRow2BuckleBelted"; - public static final String middleRow2BuckleBelted = "middleRow2BuckleBelted"; - public static final String middleRow3BuckleBelted = "middleRow3BuckleBelted"; - public static final String leftRow3BuckleBelted = "leftRow3BuckleBelted"; - public static final String rightRow3BuckleBelted = "rightRow3BuckleBelted"; - public static final String rearInflatableBelted = "rearInflatableBelted"; - public static final String leftRearInflatableBelted = "leftRearInflatableBelted"; - public static final String rightRearInflatableBelted = "rightRearInflatableBelted"; - public static final String middleRow1BeltDeployed = "middleRow1BeltDeployed"; - public static final String middleRow1BuckleBelted = "middleRow1BuckleBelted"; - - public static final String graphicSupported = "graphicSupported"; - public static final String screenParams = "screenParams"; - public static final String muteAudio = "muteAudio"; - public static final String parkBrakeActive = "parkBrakeActive"; - public static final String ignitionStableStatus = "ignitionStableStatus"; - public static final String ignitionStatus = "ignitionStatus"; - public static final String driverDoorAjar = "driverDoorAjar"; - public static final String passengerDoorAjar = "passengerDoorAjar"; - public static final String rearLeftDoorAjar = "rearLeftDoorAjar"; - public static final String rearRightDoorAjar = "rearRightDoorAjar"; - public static final String systemFile = "systemFile"; - - public static final String voiceRecOn = "voiceRecOn"; - public static final String btIconOn = "btIconOn"; - public static final String callActive = "callActive"; - public static final String phoneRoaming = "phoneRoaming"; - public static final String textMsgAvailable = "textMsgAvailable"; - public static final String battLevelStatus = "battLevelStatus"; - public static final String stereoAudioOutputMuted = "stereoAudioOutputMuted"; - public static final String monoAudioOutputMuted = "monoAudioOutputMuted"; - public static final String signalLevelStatus = "signalLevelStatus"; - public static final String primaryAudioSource = "primaryAudioSource"; - public static final String eCallEventActive = "eCallEventActive"; - - public static final String fuelEconomySinceLastReset = "fuelEconomySinceLastReset"; - public static final String currentTripFuelEconomy = "currentTripFuelEconomy"; - public static final String averageTripFuelEconomy = "averageTripFuelEconomy"; - public static final String currentCycleFuelEconomy = "currentCycleFuelEconomy"; - - public static final String lightSwitchStatus = "lightSwitchStatus"; - public static final String highBeamsOn = "highBeamsOn"; - public static final String lowBeamsOn = "lowBeamsOn"; - - public static final String electricFuelConsumption = "electricFuelConsumption"; - public static final String stateOfCharge = "stateOfCharge"; - public static final String fuelMaintenanceMode = "fuelMaintenanceMode"; - public static final String distanceToEmpty = "distanceToEmpty"; - - public static final String dtcMask = "dtcMask"; - public static final String targetID = "targetID"; - public static final String messageLength = "messageLength"; - public static final String messageData = "messageData"; - public static final String messageDataResult = "messageDataResult"; - - public static final String imageTypeSupported = "imageTypeSupported"; - public static final String imageResolution = "imageResolution"; - public static final String x = "x"; - public static final String y = "y"; - public static final String id = "id"; - public static final String ts = "ts"; - public static final String c = "c"; - public static final String resolution = "resolution"; - public static final String touchEventAvailable = "touchEventAvailable"; - - public static final String pressAvailable = "pressAvailable"; - public static final String multiTouchAvailable = "multiTouchAvailable"; - public static final String doublePressAvailable = "doublePressAvailable"; - public static final String templatesAvailable = "templatesAvailable"; - public static final String numCustomPresetsAvailable = "numCustomPresetsAvailable"; - public static final String prerecordedSpeech = "prerecordedSpeech"; - public static final String manualTextEntry = "manualTextEntry"; - public static final String progressIndicator = "progressIndicator"; - public static final String secondaryGraphic = "secondaryGraphic"; - public static final String offset = "offset"; - public static final String length = "length"; - - public static final String hardware = "hardware"; - public static final String firmwareRev = "firmwareRev"; - public static final String os = "os"; - public static final String osVersion = "osVersion"; - public static final String carrier = "carrier"; - public static final String maxNumberRFCOMMPorts = "maxNumberRFCOMMPorts"; - - public static final String onReadDIDResponse = "onReadDIDResponse"; - public static final String onGetDTCsResponse = "onGetDTCsResponse"; - public static final String onOnKeyboardInput = "onOnKeyboardInput"; - public static final String onOnTouchEvent = "onOnTouchEvent"; - public static final String onOnSystemRequest = "onOnSystemRequest"; - - public static final String onDiagnosticMessageResponse = "onDiagnosticMessageResponse"; - public static final String onSystemRequestResponse = "onSystemRequestResponse"; - public static final String onGetVehicleDataResponse = "onGetVehicleDataResponse"; - public static final String getSupportedDiagModes = "getSupportedDiagModes"; - public static final String supportedDiagModes = "supportedDiagModes"; - - public static final String driverAirbagDeployed = "driverAirbagDeployed"; - public static final String driverSideAirbagDeployed = "driverSideAirbagDeployed"; - public static final String driverCurtainAirbagDeployed = "driverCurtainAirbagDeployed"; - public static final String passengerAirbagDeployed = "passengerAirbagDeployed"; - public static final String passengerCurtainAirbagDeployed = "passengerCurtainAirbagDeployed"; - public static final String driverKneeAirbagDeployed = "driverKneeAirbagDeployed"; - public static final String passengerSideAirbagDeployed = "passengerSideAirbagDeployed"; - public static final String passengerKneeAirbagDeployed = "passengerKneeAirbagDeployed"; - - public static final String powerModeActive = "powerModeActive"; - public static final String powerModeQualificationStatus = "powerModeQualificationStatus"; - public static final String carModeStatus = "carModeStatus"; - public static final String powerModeStatus = "powerModeStatus"; - - public static final String eCallNotificationStatus = "eCallNotificationStatus"; - public static final String auxECallNotificationStatus = "auxECallNotificationStatus"; - public static final String eCallConfirmationStatus = "eCallConfirmationStatus"; - public static final String e911Override = "e911Override"; - - public static final String emergencyEventType = "emergencyEventType"; - public static final String fuelCutoffStatus = "fuelCutoffStatus"; - public static final String rolloverEvent = "rolloverEvent"; - public static final String maximumChangeVelocity = "maximumChangeVelocity"; - public static final String multipleEvents = "multipleEvents"; - - public static final String eCallInfo = "eCallInfo"; - public static final String airbagStatus = "airbagStatus"; - public static final String emergencyEvent = "emergencyEvent"; - public static final String clusterModeStatus = "clusterModeStatus"; - public static final String myKey = "myKey"; - public static final String timeToDestination = "timeToDestination"; - - public static final String driverDistraction = "driverDistraction"; - public static final String showLockScreen = "showLockScreen"; - public static final String userSelected = "userSelected"; - public static final String notSet = "notSet"; - - public static final String headers = "headers"; - public static final String body = "body"; - - public static final String ContentType = "ContentType"; - public static final String ConnectTimeout = "ConnectTimeout"; - public static final String DoOutput = "DoOutput"; - public static final String DoInput = "DoInput"; - public static final String UseCaches = "UseCaches"; - public static final String RequestMethod = "RequestMethod"; - public static final String ReadTimeout = "ReadTimeout"; - public static final String InstanceFollowRedirects = "InstanceFollowRedirects"; - public static final String charset = "charset"; - public static final String ContentLength = "Content-Length"; -} +package com.smartdevicelink.proxy.constants;
+
+@Deprecated
+public class Names {
+ public static final String request = "request";
+ public static final String response = "response";
+ public static final String notification = "notification";
+ public static final String function_name = "name";
+ public static final String parameters = "parameters";
+ public static final String bulkData = "bulkData";
+
+ public static final String RegisterAppInterface = "RegisterAppInterface";
+ public static final String UnregisterAppInterface = "UnregisterAppInterface";
+ public static final String Alert = "Alert";
+ public static final String Show = "Show";
+ public static final String Speak = "Speak";
+ public static final String AddCommand = "AddCommand";
+ public static final String DeleteCommand = "DeleteCommand";
+ public static final String AddSubMenu = "AddSubMenu";
+ public static final String DeleteSubMenu = "DeleteSubMenu";
+ public static final String CreateInteractionChoiceSet = "CreateInteractionChoiceSet";
+ public static final String DeleteInteractionChoiceSet = "DeleteInteractionChoiceSet";
+ public static final String PerformInteraction = "PerformInteraction";
+ public static final String DialNumber = "DialNumber";
+ public static final String EncodedSyncPData = "EncodedSyncPData";
+ public static final String SyncPData = "SyncPData";
+ public static final String SubscribeButton = "SubscribeButton";
+ public static final String UnsubscribeButton = "UnsubscribeButton";
+ public static final String SubscribeVehicleData = "SubscribeVehicleData";
+ public static final String UnsubscribeVehicleData = "UnsubscribeVehicleData";
+ public static final String SetMediaClockTimer = "SetMediaClockTimer";
+ public static final String SetGlobalProperties = "SetGlobalProperties";
+ public static final String GenericResponse = "GenericResponse";
+ public static final String ScrollableMessage = "ScrollableMessage";
+ public static final String GetDID = "GetDID";
+ public static final String GetDTCs = "GetDTCs";
+ public static final String DiagnosticMessage = "DiagnosticMessage";
+ public static final String SystemRequest = "SystemRequest";
+ public static final String ReadDID = "ReadDID";
+ public static final String OnVehicleData = "OnVehicleData";
+ public static final String GetFile = "GetFile";
+ public static final String PutFile = "PutFile";
+ public static final String DeleteFile = "DeleteFile";
+ public static final String ListFiles = "ListFiles";
+ public static final String EndAudioCapture = "EndAudioCapture";
+ public static final String GetVehicleData = "GetVehicleData";
+ public static final String ResetGlobalProperties = "ResetGlobalProperties";
+ public static final String PerformAudioCapture = "PerformAudioCapture";
+ public static final String SetAppIcon = "SetAppIcon";
+ public static final String ChangeRegistration = "ChangeRegistration";
+ public static final String SetDisplayLayout = "SetDisplayLayout";
+ public static final String keypressMode = "keypressMode";
+ public static final String keyboardLayout = "keyboardLayout";
+ public static final String limitedCharacterList = "limitedCharacterList";
+ public static final String autoCompleteText = "autoCompleteText";
+ public static final String OnLanguageChange = "OnLanguageChange";
+ public static final String hmiDisplayLanguage = "hmiDisplayLanguage";
+ public static final String displayLayout = "displayLayout";
+ public static final String ttsName = "ttsName";
+ public static final String hmiDisplayLanguageDesired = "hmiDisplayLanguageDesired";
+ public static final String appHMIType = "appHMIType";
+ public static final String hashID = "hashID";
+ public static final String appID = "appID";
+ public static final String vrHelpTitle = "vrHelpTitle";
+ public static final String graphic = "graphic";
+ public static final String customPresets = "customPresets";
+ public static final String softButtonCapabilities = "softButtonCapabilities";
+ public static final String presetBankCapabilities = "presetBankCapabilities";
+ public static final String vehicleType = "vehicleType";
+ public static final String make = "make";
+ public static final String model = "model";
+ public static final String modelYear = "modelYear";
+ public static final String trim = "trim";
+ public static final String allowed = "allowed";
+ public static final String userDisallowed = "userDisallowed";
+ public static final String rpcName = "rpcName";
+ public static final String hmiPermissions = "hmiPermissions";
+ public static final String parameterPermissions = "parameterPermissions";
+ public static final String permissionItem = "permissionItem";
+ public static final String numTicks = "numTicks";
+ public static final String sliderHeader = "sliderHeader";
+ public static final String sliderFooter = "sliderFooter";
+ public static final String PerformAudioPassThru = "PerformAudioPassThru";
+ public static final String PerformAudioPassThruResponse = "PerformAudioPassThruResponse";
+ public static final String EndAudioPassThru = "EndAudioPassThru";
+ public static final String EndAudioPassThruResponse = "EndAudioPassThruResponse";
+ public static final String OnAudioPassThru = "OnAudioPassThru";
+ public static final String ShowConstantTBT = "ShowConstantTBT";
+ public static final String AlertManeuver = "AlertManeuver";
+ public static final String UpdateTurnList = "UpdateTurnList";
+
+ public static final String OnCommand = "OnCommand";
+ public static final String OnDataPublished = "OnDataPublished";
+ public static final String OnButtonPress = "OnButtonPress";
+ public static final String OnButtonEvent = "OnButtonEvent";
+ public static final String OnHMIStatus = "OnHMIStatus";
+ public static final String OnTBTClientState = "OnTBTClientState";
+ public static final String OnEncodedSyncPData = "OnEncodedSyncPData";
+ public static final String onEncodedSyncPDataResponse = "onEncodedSyncPDataResponse";
+ public static final String OnSyncPData = "OnSyncPData";
+ public static final String onOnSyncPData = "onOnSyncPData";
+ public static final String OnDriverDistraction = "OnDriverDistraction";
+ public static final String OnAppInterfaceUnregistered = "OnAppInterfaceUnregistered";
+ public static final String OnKeyboardInput = "OnKeyboardInput";
+ public static final String OnTouchEvent = "OnTouchEvent";
+ public static final String OnSystemRequest = "OnSystemRequest";
+ public static final String OnHashChange = "OnHashChange";
+ public static final String OnProxyClosed = "OnProxyClosed";
+ public static final String OnProxyError = "OnProxyError";
+ public static final String OnProxyOpened = "OnProxyOpened";
+ public static final String OnProxyUnusable = "OnProxyUnusable";
+ public static final String OnHMILevelChange = "OnHMILevelChange";
+ public static final String OnSdlChoiceChosen = "OnSdlChoiceChosen";
+ public static final String OnPermissionsChange = "OnPermissionsChange";
+ public static final String OnScreenPresetsAvailable = "OnScreenPresetsAvailable";
+ public static final String isHighlighted = "isHighlighted";
+ public static final String softButtonID = "softButtonID";
+ public static final String fileType = "fileType";
+ public static final String url = "url";
+ public static final String requestType = "requestType";
+ public static final String fileName = "fileName";
+ public static final String persistentFile = "persistentFile";
+ public static final String spaceAvailable = "spaceAvailable";
+ public static final String filenames = "filenames";
+ public static final String cmdIcon = "cmdIcon";
+ public static final String Slider = "Slider";
+ public static final String sliderPosition = "sliderPosition";
+ public static final String samplingRate = "samplingRate";
+ public static final String audioType = "audioType";
+ public static final String satRadioESN = "satRadioESN";
+ public static final String dtc = "dtc";
+ public static final String tryAgainTime = "tryAgainTime";
+
+ public static final String success = "success";
+ public static final String resultCode = "resultCode";
+ public static final String info = "info";
+
+ public static final String payload = "payload";
+ public static final String reason = "reason";
+ public static final String state = "state";
+ public static final String cmdID = "cmdID";
+ public static final String menuParams = "menuParams";
+ public static final String parentID = "parentID";
+ public static final String position = "position";
+ public static final String menuName = "menuName";
+ public static final String vrCommands = "vrCommands";
+ public static final String language = "language";
+ public static final String languageDesired = "languageDesired";
+ public static final String triggerSource = "triggerSource";
+ public static final String subscriptionType = "subscriptionType";
+ public static final String data = "data";
+ public static final String event = "event";
+ public static final String correlationID = "correlationID";
+ public static final String sdlMsgVersion = "syncMsgVersion";
+ public static final String deviceInfo = "deviceInfo";
+ public static final String majorVersion = "majorVersion";
+ public static final String minorVersion = "minorVersion";
+ public static final String appName = "appName";
+ public static final String ngnMediaScreenAppName = "ngnMediaScreenAppName";
+ public static final String isMediaApplication = "isMediaApplication";
+ public static final String vrSynonyms = "vrSynonyms";
+ public static final String usesVehicleData = "usesVehicleData";
+ public static final String text = "text";
+ public static final String type = "type";
+ public static final String ttsChunks = "ttsChunks";
+ public static final String playTone = "playTone";
+ public static final String duration = "duration";
+ public static final String mainField1 = "mainField1";
+ public static final String mainField2 = "mainField2";
+ public static final String mainField3 = "mainField3";
+ public static final String mainField4 = "mainField4";
+ public static final String statusBar = "statusBar";
+ public static final String name = "name";
+ public static final String menuID = "menuID";
+ public static final String longPress = "longPress";
+ public static final String shortPress = "shortPress";
+ public static final String buttonName = "buttonName";
+ public static final String buttonPressMode = "buttonPressMode";
+ public static final String buttonEventMode = "buttonEventMode";
+ public static final String minutes = "minutes";
+ public static final String seconds = "seconds";
+ public static final String startTime = "startTime";
+ public static final String endTime = "endTime";
+ public static final String updateMode = "updateMode";
+ public static final String mediaClock = "mediaClock";
+ public static final String initialText = "initialText";
+ public static final String initialPrompt = "initialPrompt";
+ public static final String helpPrompt = "helpPrompt";
+ public static final String timeoutPrompt = "timeoutPrompt";
+ public static final String timeout = "timeout";
+ public static final String choiceSet = "choiceSet";
+ public static final String interactionMode = "interactionMode";
+ public static final String result = "result";
+ public static final String alertText1 = "alertText1";
+ public static final String alertText2 = "alertText2";
+ public static final String alertText3 = "alertText3";
+ public static final String shortPressAvailable = "shortPressAvailable";
+ public static final String longPressAvailable = "longPressAvailable";
+ public static final String upDownAvailable = "upDownAvailable";
+ public static final String width = "width";
+ public static final String height = "height";
+ public static final String resolutionWidth = "resolutionWidth";
+ public static final String resolutionHeight = "resolutionHeight";
+ public static final String characterSet = "characterSet";
+ public static final String displayType = "displayType";
+ public static final String mediaClockFormats = "mediaClockFormats";
+ public static final String textFields = "textFields";
+ public static final String imageFields = "imageFields";
+ public static final String autoActivateID = "autoActivateID";
+ public static final String vehicleDataCapabilities = "vehicleDataCapabilities";
+ public static final String speechCapabilities = "speechCapabilities";
+ public static final String vrCapabilities = "vrCapabilities";
+ public static final String audioPassThruCapabilities = "audioPassThruCapabilities";
+ public static final String buttonCapabilities = "buttonCapabilities";
+ public static final String displayCapabilities = "displayCapabilities";
+ public static final String hmiZoneCapabilities = "hmiZoneCapabilities";
+ public static final String interactionChoiceSetID = "interactionChoiceSetID";
+ public static final String interactionChoiceSetIDList = "interactionChoiceSetIDList";
+ public static final String audioFileName = "audioFileName";
+ public static final String gpsPositionValid = "gpsPositionValid";
+ public static final String longitudeDegrees = "longitudeDegrees";
+ public static final String latitudeDegrees = "latitudeDegrees";
+ public static final String utcYear = "utcYear";
+ public static final String utcMonth = "utcMonth";
+ public static final String utcDay = "utcDay";
+ public static final String utcHours = "utcHours";
+ public static final String utcMinutes = "utcMinutes";
+ public static final String utcSeconds = "utcSeconds";
+ public static final String compassDirection = "compassDirection";
+ public static final String pdop = "pdop";
+ public static final String vdop = "vdop";
+ public static final String hdop = "hdop";
+ public static final String actual = "actual";
+ public static final String satellites = "satellites";
+ public static final String dimension = "dimension";
+ public static final String altitude = "altitude";
+ public static final String heading = "heading";
+ public static final String speed = "speed";
+ public static final String number = "number";
+ public static final String smartDeviceLinkFileName = "syncFileName";
+ public static final String localFileName = "localFileName";
+ public static final String maxDuration = "maxDuration";
+ public static final String timerMode = "timerMode";
+ public static final String status = "status";
+ public static final String pressure = "pressure";
+ public static final String hours = "hours";
+ public static final String rows = "rows";
+ public static final String pressureTellTale = "pressureTellTale";
+ public static final String leftFront = "leftFront";
+ public static final String rightFront = "rightFront";
+ public static final String leftRear = "leftRear";
+ public static final String rightRear = "rightRear";
+ public static final String innerLeftRear = "innerLeftRear";
+ public static final String innerRightRear = "innerRightRear";
+ public static final String VehicleData = "VehicleData";
+ public static final String alignment = "alignment";
+ public static final String mediaTrack = "mediaTrack";
+ public static final String properties = "properties";
+ public static final String choiceID = "choiceID";
+ public static final String bitsPerSample = "bitsPerSample";
+ public static final String hmiLevel = "hmiLevel";
+ public static final String audioStreamingState = "audioStreamingState";
+ public static final String systemContext = "systemContext";
+ public static final String sdlChoice = "sdlChoice";
+ public static final String sdlCommand = "sdlCommand";
+ public static final String URL = "URL";
+ public static final String Timeout = "Timeout";
+ public static final String PermissionGroupName = "PermissionGroupName";
+ public static final String PermissionGroupStatus = "PermissionGroupStatus";
+ public static final String PermissionGroupItems = "PermissionGroupItems";
+ public static final String audioPacket = "audioPacket";
+ public static final String audioPassThruDisplayText1 = "audioPassThruDisplayText1";
+ public static final String audioPassThruDisplayText2 = "audioPassThruDisplayText2";
+ public static final String bitRate = "bitRate";
+ public static final String rpm = "rpm";
+ public static final String fuelLevel = "fuelLevel";
+ public static final String avgFuelEconomy = "avgFuelEconomy";
+ public static final String batteryVoltage = "batteryVoltage";
+ public static final String externalTemperature = "externalTemperature";
+ public static final String vin = "vin";
+ public static final String prndl = "prndl";
+ public static final String tirePressure = "tirePressure";
+ public static final String batteryPackVoltage = "batteryPackVoltage";
+ public static final String batteryPackCurrent = "batteryPackCurrent";
+ public static final String batteryPackTemperature = "batteryPackTemperature";
+ public static final String engineTorque = "engineTorque";
+ public static final String odometer = "odometer";
+ public static final String tripOdometer = "tripOdometer";
+ public static final String genericbinary = "genericbinary";
+ public static final String GPSData = "GPSData";
+ public static final String gps = "gps";
+ public static final String fuelLevel_State = "fuelLevel_State";
+ public static final String instantFuelConsumption = "instantFuelConsumption";
+ public static final String beltStatus = "beltStatus";
+ public static final String bodyInformation = "bodyInformation";
+ public static final String deviceStatus = "deviceStatus";
+ public static final String driverBraking = "driverBraking";
+ public static final String wiperStatus = "wiperStatus";
+ public static final String fuelEconomy = "fuelEconomy";
+ public static final String engineOilLife = "engineOilLife";
+ public static final String headLampStatus = "headLampStatus";
+ public static final String brakeTorque = "brakeTorque";
+ public static final String turboBoost = "turboBoost";
+ public static final String coolantTemp = "coolantTemp";
+ public static final String airFuelRatio = "airFuelRatio";
+ public static final String coolingHeadTemp = "coolingHeadTemp";
+ public static final String oilTemp = "oilTemp";
+ public static final String intakeAirTemp = "intakeAirTemp";
+ public static final String gearShiftAdvice = "gearShiftAdvice";
+ public static final String acceleration = "acceleration";
+ public static final String accPedalPosition = "accPedalPosition";
+ public static final String clutchPedalPosition = "clutchPedalPosition";
+ public static final String reverseGearStatus = "reverseGearStatus";
+ public static final String accTorque = "accTorque";
+ public static final String ambientLightStatus = "ambientLightStatus";
+ public static final String ambientLightSensorStatus = "ambientLightSensorStatus";
+ public static final String dataType = "dataType";
+ public static final String identifier = "identifier";
+ public static final String statusByte = "statusByte";
+ public static final String didResult = "didResult";
+ public static final String ecuName = "ecuName";
+ public static final String didLocation = "didLocation";
+ public static final String value = "value";
+ public static final String softButtonName = "softButtonName";
+ public static final String imageSupported = "imageSupported";
+ public static final String systemAction = "systemAction";
+ public static final String image = "image";
+ public static final String secondaryText = "secondaryText";
+ public static final String tertiaryText = "tertiaryText";
+ public static final String secondaryImage = "secondaryImage";
+ public static final String imageType = "imageType";
+ public static final String fileData = "fileData";
+ public static final String scrollableMessageBody = "scrollableMessageBody";
+ public static final String softButtons = "softButtons";
+ public static final String customButtonID = "customButtonID";
+ public static final String vrHelp = "vrHelp";
+ public static final String interactionLayout = "interactionLayout";
+ public static final String customButtonName = "customButtonName";
+ public static final String navigationText = "navigationText";
+ public static final String turnIcon = "turnIcon";
+ public static final String nextTurnIcon = "nextTurnIcon";
+ public static final String navigationText1 = "navigationText1";
+ public static final String navigationText2 = "navigationText2";
+ public static final String eta = "eta";
+ public static final String totalDistance = "totalDistance";
+ public static final String distanceToManeuver = "distanceToManeuver";
+ public static final String distanceToManeuverScale = "distanceToManeuverScale";
+ public static final String maneuverComplete = "maneuverComplete";
+ public static final String turnList = "turnList";
+ public static final String steeringWheelAngle = "steeringWheelAngle";
+ public static final String menuTitle = "menuTitle";
+ public static final String menuIcon = "menuIcon";
+ public static final String keyboardProperties = "keyboardProperties";
+ public static final String driverBeltDeployed = "driverBeltDeployed";
+ public static final String passengerBeltDeployed = "passengerBeltDeployed";
+ public static final String passengerBuckleBelted = "passengerBuckleBelted";
+ public static final String driverBuckleBelted = "driverBuckleBelted";
+ public static final String leftRow2BuckleBelted = "leftRow2BuckleBelted";
+ public static final String passengerChildDetected = "passengerChildDetected";
+ public static final String rightRow2BuckleBelted = "rightRow2BuckleBelted";
+ public static final String middleRow2BuckleBelted = "middleRow2BuckleBelted";
+ public static final String middleRow3BuckleBelted = "middleRow3BuckleBelted";
+ public static final String leftRow3BuckleBelted = "leftRow3BuckleBelted";
+ public static final String rightRow3BuckleBelted = "rightRow3BuckleBelted";
+ public static final String rearInflatableBelted = "rearInflatableBelted";
+ public static final String leftRearInflatableBelted = "leftRearInflatableBelted";
+ public static final String rightRearInflatableBelted = "rightRearInflatableBelted";
+ public static final String middleRow1BeltDeployed = "middleRow1BeltDeployed";
+ public static final String middleRow1BuckleBelted = "middleRow1BuckleBelted";
+
+ public static final String graphicSupported = "graphicSupported";
+ public static final String screenParams = "screenParams";
+ public static final String muteAudio = "muteAudio";
+ public static final String parkBrakeActive = "parkBrakeActive";
+ public static final String ignitionStableStatus = "ignitionStableStatus";
+ public static final String ignitionStatus = "ignitionStatus";
+ public static final String driverDoorAjar = "driverDoorAjar";
+ public static final String passengerDoorAjar = "passengerDoorAjar";
+ public static final String rearLeftDoorAjar = "rearLeftDoorAjar";
+ public static final String rearRightDoorAjar = "rearRightDoorAjar";
+ public static final String systemFile = "systemFile";
+
+ public static final String voiceRecOn = "voiceRecOn";
+ public static final String btIconOn = "btIconOn";
+ public static final String callActive = "callActive";
+ public static final String phoneRoaming = "phoneRoaming";
+ public static final String textMsgAvailable = "textMsgAvailable";
+ public static final String battLevelStatus = "battLevelStatus";
+ public static final String stereoAudioOutputMuted = "stereoAudioOutputMuted";
+ public static final String monoAudioOutputMuted = "monoAudioOutputMuted";
+ public static final String signalLevelStatus = "signalLevelStatus";
+ public static final String primaryAudioSource = "primaryAudioSource";
+ public static final String eCallEventActive = "eCallEventActive";
+
+ public static final String fuelEconomySinceLastReset = "fuelEconomySinceLastReset";
+ public static final String currentTripFuelEconomy = "currentTripFuelEconomy";
+ public static final String averageTripFuelEconomy = "averageTripFuelEconomy";
+ public static final String currentCycleFuelEconomy = "currentCycleFuelEconomy";
+
+ public static final String lightSwitchStatus = "lightSwitchStatus";
+ public static final String highBeamsOn = "highBeamsOn";
+ public static final String lowBeamsOn = "lowBeamsOn";
+
+ public static final String electricFuelConsumption = "electricFuelConsumption";
+ public static final String stateOfCharge = "stateOfCharge";
+ public static final String fuelMaintenanceMode = "fuelMaintenanceMode";
+ public static final String distanceToEmpty = "distanceToEmpty";
+
+ public static final String dtcMask = "dtcMask";
+ public static final String targetID = "targetID";
+ public static final String messageLength = "messageLength";
+ public static final String messageData = "messageData";
+ public static final String messageDataResult = "messageDataResult";
+
+ public static final String imageTypeSupported = "imageTypeSupported";
+ public static final String imageResolution = "imageResolution";
+ public static final String x = "x";
+ public static final String y = "y";
+ public static final String id = "id";
+ public static final String ts = "ts";
+ public static final String c = "c";
+ public static final String resolution = "resolution";
+ public static final String touchEventAvailable = "touchEventAvailable";
+
+ public static final String pressAvailable = "pressAvailable";
+ public static final String multiTouchAvailable = "multiTouchAvailable";
+ public static final String doublePressAvailable = "doublePressAvailable";
+ public static final String templatesAvailable = "templatesAvailable";
+ public static final String numCustomPresetsAvailable = "numCustomPresetsAvailable";
+ public static final String prerecordedSpeech = "prerecordedSpeech";
+ public static final String manualTextEntry = "manualTextEntry";
+ public static final String progressIndicator = "progressIndicator";
+ public static final String secondaryGraphic = "secondaryGraphic";
+ public static final String offset = "offset";
+ public static final String length = "length";
+
+ public static final String hardware = "hardware";
+ public static final String firmwareRev = "firmwareRev";
+ public static final String os = "os";
+ public static final String osVersion = "osVersion";
+ public static final String carrier = "carrier";
+ public static final String maxNumberRFCOMMPorts = "maxNumberRFCOMMPorts";
+
+ public static final String onReadDIDResponse = "onReadDIDResponse";
+ public static final String onGetDTCsResponse = "onGetDTCsResponse";
+ public static final String onOnKeyboardInput = "onOnKeyboardInput";
+ public static final String onOnTouchEvent = "onOnTouchEvent";
+ public static final String onOnSystemRequest = "onOnSystemRequest";
+
+ public static final String onDiagnosticMessageResponse = "onDiagnosticMessageResponse";
+ public static final String onSystemRequestResponse = "onSystemRequestResponse";
+ public static final String onGetVehicleDataResponse = "onGetVehicleDataResponse";
+ public static final String getSupportedDiagModes = "getSupportedDiagModes";
+ public static final String supportedDiagModes = "supportedDiagModes";
+
+ public static final String driverAirbagDeployed = "driverAirbagDeployed";
+ public static final String driverSideAirbagDeployed = "driverSideAirbagDeployed";
+ public static final String driverCurtainAirbagDeployed = "driverCurtainAirbagDeployed";
+ public static final String passengerAirbagDeployed = "passengerAirbagDeployed";
+ public static final String passengerCurtainAirbagDeployed = "passengerCurtainAirbagDeployed";
+ public static final String driverKneeAirbagDeployed = "driverKneeAirbagDeployed";
+ public static final String passengerSideAirbagDeployed = "passengerSideAirbagDeployed";
+ public static final String passengerKneeAirbagDeployed = "passengerKneeAirbagDeployed";
+
+ public static final String powerModeActive = "powerModeActive";
+ public static final String powerModeQualificationStatus = "powerModeQualificationStatus";
+ public static final String carModeStatus = "carModeStatus";
+ public static final String powerModeStatus = "powerModeStatus";
+
+ public static final String eCallNotificationStatus = "eCallNotificationStatus";
+ public static final String auxECallNotificationStatus = "auxECallNotificationStatus";
+ public static final String eCallConfirmationStatus = "eCallConfirmationStatus";
+ public static final String e911Override = "e911Override";
+
+ public static final String emergencyEventType = "emergencyEventType";
+ public static final String fuelCutoffStatus = "fuelCutoffStatus";
+ public static final String rolloverEvent = "rolloverEvent";
+ public static final String maximumChangeVelocity = "maximumChangeVelocity";
+ public static final String multipleEvents = "multipleEvents";
+
+ public static final String eCallInfo = "eCallInfo";
+ public static final String airbagStatus = "airbagStatus";
+ public static final String emergencyEvent = "emergencyEvent";
+ public static final String clusterModeStatus = "clusterModeStatus";
+ public static final String myKey = "myKey";
+ public static final String timeToDestination = "timeToDestination";
+
+ public static final String driverDistraction = "driverDistraction";
+ public static final String showLockScreen = "showLockScreen";
+ public static final String userSelected = "userSelected";
+ public static final String notSet = "notSet";
+
+ public static final String headers = "headers";
+ public static final String body = "body";
+
+ public static final String ContentType = "ContentType";
+ public static final String ConnectTimeout = "ConnectTimeout";
+ public static final String DoOutput = "DoOutput";
+ public static final String DoInput = "DoInput";
+ public static final String UseCaches = "UseCaches";
+ public static final String RequestMethod = "RequestMethod";
+ public static final String ReadTimeout = "ReadTimeout";
+ public static final String InstanceFollowRedirects = "InstanceFollowRedirects";
+ public static final String charset = "charset";
+ public static final String ContentLength = "Content-Length";
+}
diff --git a/base/src/main/java/com/smartdevicelink/proxy/interfaces/IProxyListenerALM.java b/base/src/main/java/com/smartdevicelink/proxy/interfaces/IProxyListenerALM.java index 980ded6df..2fb5a4063 100644 --- a/base/src/main/java/com/smartdevicelink/proxy/interfaces/IProxyListenerALM.java +++ b/base/src/main/java/com/smartdevicelink/proxy/interfaces/IProxyListenerALM.java @@ -1,48 +1,48 @@ -package com.smartdevicelink.proxy.interfaces; - -public interface IProxyListenerALM extends IProxyListenerBase { - // Adds Advanced Life-cycle Management call-backs to the IProxyListenerAbstract interface - - /** - * **MOVED TO IProxyListenerBase** - onOnHMIStatus() being called indicates that the proxy has entered a state in which the - * application may create SDL related resources (addCommands, ChoiceSets). - */ - //public void onOnHMIStatus(OnHMIStatus notification); - - /** - * **MOVED TO IProxyListenerBase** - onProxyClosed() being called indicates that the app is no longer registered with SDL - * All resources on SDL (addCommands and ChoiceSets) have been deleted and will have to be - * recreated upon the next onReadyForInitialization() call-back. - */ - //public void onProxyClosed(String info, Exception e); - - /** - * **MOVED TO IProxyListenerBase** - onError() being called indicates that the proxy has experienced an unrecoverable error. - * A new proxy object must be initiated to reestablish connection with SDL. - * - * @param info - Any info present about the error that occurred. - * @param e - Any exception thrown by the error. - */ - //public void onError(String info, Exception e); - - /** - * **Deprecated** - onSdlInterfaceAvailable() being called indicates that the proxy now has access to SDL's HMI. - * Monitor the onFocusChange call-back to determine which level of HMI is available to the proxy. - * - * @param isFirstAvailability - Indicates this is the first onSdlInterfaceAvailable in this lifecycle. - */ - // HMI (Background, Limited, Full) from Unavailable = onSdlInterfaceAvailable(Boolean isFirstAvailability); - - /** - * **Deprecated** - onSdlInterfaceUnavailable() being called indicates that the proxy does NOT have access to SDL's HIM. - */ - // HMI None onSdlInterfaceUnavailable(); - - /** - * **Deprecated** - ALM HMI states converted back to HMI Levels - * - * HMI Full = onSdlInFocus(Boolean isFirstSdlInFocus); - * HMI Limited = onSdlInFocusLimited(); - * HMI Background = onSdlLostFocus(); - */ -} +package com.smartdevicelink.proxy.interfaces;
+
+public interface IProxyListenerALM extends IProxyListenerBase {
+ // Adds Advanced Life-cycle Management call-backs to the IProxyListenerAbstract interface
+
+ /**
+ * **MOVED TO IProxyListenerBase** - onOnHMIStatus() being called indicates that the proxy has entered a state in which the
+ * application may create SDL related resources (addCommands, ChoiceSets).
+ */
+ //public void onOnHMIStatus(OnHMIStatus notification);
+
+ /**
+ * **MOVED TO IProxyListenerBase** - onProxyClosed() being called indicates that the app is no longer registered with SDL
+ * All resources on SDL (addCommands and ChoiceSets) have been deleted and will have to be
+ * recreated upon the next onReadyForInitialization() call-back.
+ */
+ //public void onProxyClosed(String info, Exception e);
+
+ /**
+ * **MOVED TO IProxyListenerBase** - onError() being called indicates that the proxy has experienced an unrecoverable error.
+ * A new proxy object must be initiated to reestablish connection with SDL.
+ *
+ * @param info - Any info present about the error that occurred.
+ * @param e - Any exception thrown by the error.
+ */
+ //public void onError(String info, Exception e);
+
+ /**
+ * **Deprecated** - onSdlInterfaceAvailable() being called indicates that the proxy now has access to SDL's HMI.
+ * Monitor the onFocusChange call-back to determine which level of HMI is available to the proxy.
+ *
+ * @param isFirstAvailability - Indicates this is the first onSdlInterfaceAvailable in this lifecycle.
+ */
+ // HMI (Background, Limited, Full) from Unavailable = onSdlInterfaceAvailable(Boolean isFirstAvailability);
+
+ /**
+ * **Deprecated** - onSdlInterfaceUnavailable() being called indicates that the proxy does NOT have access to SDL's HIM.
+ */
+ // HMI None onSdlInterfaceUnavailable();
+
+ /**
+ * **Deprecated** - ALM HMI states converted back to HMI Levels
+ *
+ * HMI Full = onSdlInFocus(Boolean isFirstSdlInFocus);
+ * HMI Limited = onSdlInFocusLimited();
+ * HMI Background = onSdlLostFocus();
+ */
+}
diff --git a/base/src/main/java/com/smartdevicelink/proxy/interfaces/IProxyListenerBase.java b/base/src/main/java/com/smartdevicelink/proxy/interfaces/IProxyListenerBase.java index f5bfeaf57..fc348faf5 100644 --- a/base/src/main/java/com/smartdevicelink/proxy/interfaces/IProxyListenerBase.java +++ b/base/src/main/java/com/smartdevicelink/proxy/interfaces/IProxyListenerBase.java @@ -1,359 +1,386 @@ -package com.smartdevicelink.proxy.interfaces; - -import com.smartdevicelink.proxy.callbacks.OnServiceEnded; -import com.smartdevicelink.proxy.callbacks.OnServiceNACKed; -import com.smartdevicelink.proxy.rpc.AddCommandResponse; -import com.smartdevicelink.proxy.rpc.AddSubMenuResponse; -import com.smartdevicelink.proxy.rpc.AlertManeuverResponse; -import com.smartdevicelink.proxy.rpc.AlertResponse; -import com.smartdevicelink.proxy.rpc.ButtonPressResponse; -import com.smartdevicelink.proxy.rpc.ChangeRegistrationResponse; -import com.smartdevicelink.proxy.rpc.CreateInteractionChoiceSetResponse; -import com.smartdevicelink.proxy.rpc.DeleteCommandResponse; -import com.smartdevicelink.proxy.rpc.DeleteFileResponse; -import com.smartdevicelink.proxy.rpc.DeleteInteractionChoiceSetResponse; -import com.smartdevicelink.proxy.rpc.DeleteSubMenuResponse; -import com.smartdevicelink.proxy.rpc.DiagnosticMessageResponse; -import com.smartdevicelink.proxy.rpc.DialNumberResponse; -import com.smartdevicelink.proxy.rpc.EndAudioPassThruResponse; -import com.smartdevicelink.proxy.rpc.GenericResponse; -import com.smartdevicelink.proxy.rpc.GetDTCsResponse; -import com.smartdevicelink.proxy.rpc.GetInteriorVehicleDataResponse; -import com.smartdevicelink.proxy.rpc.GetSystemCapabilityResponse; -import com.smartdevicelink.proxy.rpc.GetVehicleDataResponse; -import com.smartdevicelink.proxy.rpc.GetWayPointsResponse; -import com.smartdevicelink.proxy.rpc.ListFilesResponse; -import com.smartdevicelink.proxy.rpc.OnAudioPassThru; -import com.smartdevicelink.proxy.rpc.OnButtonEvent; -import com.smartdevicelink.proxy.rpc.OnButtonPress; -import com.smartdevicelink.proxy.rpc.OnCommand; -import com.smartdevicelink.proxy.rpc.OnDriverDistraction; -import com.smartdevicelink.proxy.rpc.OnHMIStatus; -import com.smartdevicelink.proxy.rpc.OnHashChange; -import com.smartdevicelink.proxy.rpc.OnInteriorVehicleData; -import com.smartdevicelink.proxy.rpc.OnKeyboardInput; -import com.smartdevicelink.proxy.rpc.OnLanguageChange; -import com.smartdevicelink.proxy.rpc.OnLockScreenStatus; -import com.smartdevicelink.proxy.rpc.OnPermissionsChange; -import com.smartdevicelink.proxy.rpc.OnRCStatus; -import com.smartdevicelink.proxy.rpc.OnStreamRPC; -import com.smartdevicelink.proxy.rpc.OnSystemRequest; -import com.smartdevicelink.proxy.rpc.OnTBTClientState; -import com.smartdevicelink.proxy.rpc.OnTouchEvent; -import com.smartdevicelink.proxy.rpc.OnVehicleData; -import com.smartdevicelink.proxy.rpc.OnWayPointChange; -import com.smartdevicelink.proxy.rpc.PerformAudioPassThruResponse; -import com.smartdevicelink.proxy.rpc.PerformInteractionResponse; -import com.smartdevicelink.proxy.rpc.PutFileResponse; -import com.smartdevicelink.proxy.rpc.ReadDIDResponse; -import com.smartdevicelink.proxy.rpc.ResetGlobalPropertiesResponse; -import com.smartdevicelink.proxy.rpc.ScrollableMessageResponse; -import com.smartdevicelink.proxy.rpc.SendHapticDataResponse; -import com.smartdevicelink.proxy.rpc.SendLocationResponse; -import com.smartdevicelink.proxy.rpc.SetAppIconResponse; -import com.smartdevicelink.proxy.rpc.SetDisplayLayoutResponse; -import com.smartdevicelink.proxy.rpc.SetGlobalPropertiesResponse; -import com.smartdevicelink.proxy.rpc.SetInteriorVehicleDataResponse; -import com.smartdevicelink.proxy.rpc.SetMediaClockTimerResponse; -import com.smartdevicelink.proxy.rpc.ShowConstantTbtResponse; -import com.smartdevicelink.proxy.rpc.ShowResponse; -import com.smartdevicelink.proxy.rpc.SliderResponse; -import com.smartdevicelink.proxy.rpc.SpeakResponse; -import com.smartdevicelink.proxy.rpc.StreamRPCResponse; -import com.smartdevicelink.proxy.rpc.SubscribeButtonResponse; -import com.smartdevicelink.proxy.rpc.SubscribeVehicleDataResponse; -import com.smartdevicelink.proxy.rpc.SubscribeWayPointsResponse; -import com.smartdevicelink.proxy.rpc.SystemRequestResponse; -import com.smartdevicelink.proxy.rpc.UnsubscribeButtonResponse; -import com.smartdevicelink.proxy.rpc.UnsubscribeVehicleDataResponse; -import com.smartdevicelink.proxy.rpc.UnsubscribeWayPointsResponse; -import com.smartdevicelink.proxy.rpc.UpdateTurnListResponse; -import com.smartdevicelink.proxy.rpc.enums.SdlDisconnectedReason; - - -public interface IProxyListenerBase { - - /** - * onOnHMIStatus being called indicates that there has been an HMI Level change, - * system context change or audio streaming state change. - * - * @param notification - Contains information about the HMI Level, - * system context and audio streaming state. - */ - public void onOnHMIStatus(OnHMIStatus notification); - - /** - * onProxyClosed has different functionality for the different models. - * In the non-ALM model this indicates that the proxy has experienced an unrecoverable error. - * A new proxy object must be initiated to reestablish connection with SDL. - * In the ALM model this indicates that the app is no longer registered with SDL - * All resources on SDL (addCommands and ChoiceSets) have been deleted and will have to be - * recreated upon the next onReadyForInitialization() call-back. - * - * @param info - Includes information about the reason the proxy has been closed. - * @param e - The exception that occurred. - */ - public void onProxyClosed(String info, Exception e, SdlDisconnectedReason reason); - - public void onServiceEnded(OnServiceEnded serviceEnded); - - public void onServiceNACKed(OnServiceNACKed serviceNACKed); - - public void onOnStreamRPC(OnStreamRPC notification); - - public void onStreamRPCResponse(StreamRPCResponse response); - - /** - * onProxyError() being called indicates that the SDL Proxy experenced an error. - * - * @param info - Includes information about the Exception that occurred. - * @param e - The exception that occurred. - */ - public void onError(String info, Exception e); - - /** - * onGenericResponse() being called indicates that SDL could not determine the - * type of request it is responding to. This is usually result of an unknown RPC Request - * being sent. - * - * @param response - Includes detailed information about the response. - */ - public void onGenericResponse(GenericResponse response); - - /** - * onOnCommand() being called indicates that the user selected a command on SDL. - * - * @param notification - Contains information about the command chosen. - */ - public void onOnCommand(OnCommand notification); - - /** - * onAddCommandResponse() being called indicates that SDL has responded to - * a request to add a command. - * - * @param response - Contains information about the response sent from SDL. - */ - public void onAddCommandResponse(AddCommandResponse response); - - /** - * onAddSubMenuResponse() being called indicates that SDL has responded to - * a request to add a command. - * - * @param response - Contains information about the response sent from SDL. - */ - public void onAddSubMenuResponse(AddSubMenuResponse response); - - /** - * onCreateInteractionChoiceSetResponse() being called indicates that SDL has - * responded to a request to add an interactionChoiceSet. - * - * @param response - Contains information about the response sent from SDL. - */ - public void onCreateInteractionChoiceSetResponse(CreateInteractionChoiceSetResponse response); - - /** - * onAlertResponse being called indicates that SDL has - * responded to a request to alert the user. - * - * @param response - Contains information about the response sent from SDL. - */ - public void onAlertResponse(AlertResponse response); - - /** - * onDeleteCommandResponse being called indicates that SDL has - * responded to a request to delete a command. - * - * @param response - Contains information about the response sent from SDL. - */ - public void onDeleteCommandResponse(DeleteCommandResponse response); - - /** - * onDeleteCommandResponse being called indicates that SDL has - * responded to a request to delete an interaction choice set. - * - * @param response - Contains information about the response sent from SDL. - */ - public void onDeleteInteractionChoiceSetResponse(DeleteInteractionChoiceSetResponse response); - - /** - * onDeleteCommandResponse being called indicates that SDL has - * responded to a request to delete a submenu. - * - * @param response - Contains information about the response sent from SDL. - */ - public void onDeleteSubMenuResponse(DeleteSubMenuResponse response); - - /** - * onPerformInteractionResponse being called indicates that SDL has - * responded to a request to perform an interaction. - * - * @param response - Contains information about the response sent from SDL. - */ - public void onPerformInteractionResponse(PerformInteractionResponse response); - - /** - * onResetGlobalPropertiesResponse being called indicates that SDL has - * responded to a request to reset global properties. - * - * @param response - Contains information about the response sent from SDL. - */ - public void onResetGlobalPropertiesResponse(ResetGlobalPropertiesResponse response); - - /** - * onSetGlobalPropertiesResponse being called indicates that SDL has - * responded to a request to set global properties. - * - * @param response - Contains information about the response sent from SDL. - */ - public void onSetGlobalPropertiesResponse(SetGlobalPropertiesResponse response); - - /** - * onSetMediaClockTimerResponse being called indicates that SDL has - * responded to a request to set the media clock timer. - * - * @param response - Contains information about the response sent from SDL. - */ - public void onSetMediaClockTimerResponse(SetMediaClockTimerResponse response); - - /** - * onShowResponse being called indicates that SDL has - * responded to a request to display information to the user. - * - * @param response - Contains information about the response sent from SDL. - */ - public void onShowResponse(ShowResponse response); - - /** - * onSpeakResponse being called indicates that SDL has - * responded to a request to speak information to the user. - * - * @param response - Contains information about the response sent from SDL. - */ - public void onSpeakResponse(SpeakResponse response); - - /** - * onButtonEvent being called indicates that a button event has occurred. - * - * @param notification - Contains information about the notification sent from SDL. - */ - public void onOnButtonEvent(OnButtonEvent notification); - - /** - * onButtonPress being called indicates that SDL has a button has - * been pressed by the user. - * - * @param notification - Contains information about the notification sent from SDL. - */ - public void onOnButtonPress(OnButtonPress notification); - - /** - * onSubscribeButtonResponse being called indicates that SDL has - * responded to a request to subscribe to button events and button presses. - * - * @param response - Contains information about the response sent from SDL. - */ - public void onSubscribeButtonResponse(SubscribeButtonResponse response); - - /** - * onUnsubscribeButtonResponse being called indicates that SDL has - * responded to a request to unsubscribe from button events and button presses. - * - * @param response - Contains information about the response sent from SDL. - */ - public void onUnsubscribeButtonResponse(UnsubscribeButtonResponse response); - - /** - * onOnPermissionsChange being called indicates that your app permissions have - * changed due to a policy table change. This can mean your app has received additional - * permissions OR lost permissions. - * - * @param notification - Contains information about the changed permissions. - */ - public void onOnPermissionsChange(OnPermissionsChange notification); - - public void onSubscribeVehicleDataResponse(SubscribeVehicleDataResponse response); - - public void onUnsubscribeVehicleDataResponse(UnsubscribeVehicleDataResponse response); - - public void onGetVehicleDataResponse(GetVehicleDataResponse response); - - public void onOnVehicleData(OnVehicleData notification); - - public void onPerformAudioPassThruResponse(PerformAudioPassThruResponse response); - - public void onEndAudioPassThruResponse(EndAudioPassThruResponse response); - - public void onOnAudioPassThru(OnAudioPassThru notification); - - public void onPutFileResponse(PutFileResponse response); - - public void onDeleteFileResponse(DeleteFileResponse response); - - public void onListFilesResponse(ListFilesResponse response); - - public void onSetAppIconResponse(SetAppIconResponse response); - - public void onScrollableMessageResponse(ScrollableMessageResponse response); - - public void onChangeRegistrationResponse(ChangeRegistrationResponse response); - - public void onSetDisplayLayoutResponse(SetDisplayLayoutResponse response); - - public void onOnLanguageChange(OnLanguageChange notification); - - public void onOnHashChange(OnHashChange notification); - - public void onSliderResponse(SliderResponse response); - - public void onOnDriverDistraction(OnDriverDistraction notification); - - public void onOnTBTClientState(OnTBTClientState notification); - - public void onOnSystemRequest(OnSystemRequest notification); - - public void onSystemRequestResponse(SystemRequestResponse response); - - public void onOnKeyboardInput(OnKeyboardInput notification); - - public void onOnTouchEvent(OnTouchEvent notification); - - public void onDiagnosticMessageResponse(DiagnosticMessageResponse response); - - public void onReadDIDResponse(ReadDIDResponse response); - - public void onGetDTCsResponse(GetDTCsResponse response); - - public void onOnLockScreenNotification(OnLockScreenStatus notification); - - public void onDialNumberResponse(DialNumberResponse response); - - public void onSendLocationResponse(SendLocationResponse response); - - public void onShowConstantTbtResponse(ShowConstantTbtResponse response); - - public void onAlertManeuverResponse(AlertManeuverResponse response); - - public void onUpdateTurnListResponse(UpdateTurnListResponse response); - - public void onServiceDataACK(int dataSize); - public void onGetWayPointsResponse(GetWayPointsResponse response); - - public void onSubscribeWayPointsResponse(SubscribeWayPointsResponse response); - - public void onUnsubscribeWayPointsResponse(UnsubscribeWayPointsResponse response); - public void onOnWayPointChange(OnWayPointChange notification); - - public void onGetSystemCapabilityResponse(GetSystemCapabilityResponse response); - - public void onGetInteriorVehicleDataResponse(GetInteriorVehicleDataResponse response); - - public void onButtonPressResponse(ButtonPressResponse response); - - public void onSetInteriorVehicleDataResponse(SetInteriorVehicleDataResponse response); - - public void onOnInteriorVehicleData(OnInteriorVehicleData notification); - - public void onSendHapticDataResponse(SendHapticDataResponse response); - - public void onOnRCStatus(OnRCStatus notification); -} +package com.smartdevicelink.proxy.interfaces;
+
+import com.smartdevicelink.proxy.callbacks.OnServiceEnded;
+import com.smartdevicelink.proxy.callbacks.OnServiceNACKed;
+import com.smartdevicelink.proxy.rpc.AddCommandResponse;
+import com.smartdevicelink.proxy.rpc.AddSubMenuResponse;
+import com.smartdevicelink.proxy.rpc.AlertManeuverResponse;
+import com.smartdevicelink.proxy.rpc.AlertResponse;
+import com.smartdevicelink.proxy.rpc.ButtonPressResponse;
+import com.smartdevicelink.proxy.rpc.ChangeRegistrationResponse;
+import com.smartdevicelink.proxy.rpc.CreateInteractionChoiceSetResponse;
+import com.smartdevicelink.proxy.rpc.DeleteCommandResponse;
+import com.smartdevicelink.proxy.rpc.DeleteFileResponse;
+import com.smartdevicelink.proxy.rpc.DeleteInteractionChoiceSetResponse;
+import com.smartdevicelink.proxy.rpc.DeleteSubMenuResponse;
+import com.smartdevicelink.proxy.rpc.DiagnosticMessageResponse;
+import com.smartdevicelink.proxy.rpc.DialNumberResponse;
+import com.smartdevicelink.proxy.rpc.EndAudioPassThruResponse;
+import com.smartdevicelink.proxy.rpc.GenericResponse;
+import com.smartdevicelink.proxy.rpc.GetAppServiceDataResponse;
+import com.smartdevicelink.proxy.rpc.GetCloudAppPropertiesResponse;
+import com.smartdevicelink.proxy.rpc.GetDTCsResponse;
+import com.smartdevicelink.proxy.rpc.GetFileResponse;
+import com.smartdevicelink.proxy.rpc.GetInteriorVehicleDataResponse;
+import com.smartdevicelink.proxy.rpc.GetSystemCapabilityResponse;
+import com.smartdevicelink.proxy.rpc.GetVehicleDataResponse;
+import com.smartdevicelink.proxy.rpc.GetWayPointsResponse;
+import com.smartdevicelink.proxy.rpc.ListFilesResponse;
+import com.smartdevicelink.proxy.rpc.OnAppServiceData;
+import com.smartdevicelink.proxy.rpc.OnAudioPassThru;
+import com.smartdevicelink.proxy.rpc.OnButtonEvent;
+import com.smartdevicelink.proxy.rpc.OnButtonPress;
+import com.smartdevicelink.proxy.rpc.OnCommand;
+import com.smartdevicelink.proxy.rpc.OnDriverDistraction;
+import com.smartdevicelink.proxy.rpc.OnHMIStatus;
+import com.smartdevicelink.proxy.rpc.OnHashChange;
+import com.smartdevicelink.proxy.rpc.OnInteriorVehicleData;
+import com.smartdevicelink.proxy.rpc.OnKeyboardInput;
+import com.smartdevicelink.proxy.rpc.OnLanguageChange;
+import com.smartdevicelink.proxy.rpc.OnLockScreenStatus;
+import com.smartdevicelink.proxy.rpc.OnPermissionsChange;
+import com.smartdevicelink.proxy.rpc.OnRCStatus;
+import com.smartdevicelink.proxy.rpc.OnStreamRPC;
+import com.smartdevicelink.proxy.rpc.OnSystemCapabilityUpdated;
+import com.smartdevicelink.proxy.rpc.OnSystemRequest;
+import com.smartdevicelink.proxy.rpc.OnTBTClientState;
+import com.smartdevicelink.proxy.rpc.OnTouchEvent;
+import com.smartdevicelink.proxy.rpc.OnVehicleData;
+import com.smartdevicelink.proxy.rpc.OnWayPointChange;
+import com.smartdevicelink.proxy.rpc.PerformAppServiceInteractionResponse;
+import com.smartdevicelink.proxy.rpc.PerformAudioPassThruResponse;
+import com.smartdevicelink.proxy.rpc.PerformInteractionResponse;
+import com.smartdevicelink.proxy.rpc.PublishAppServiceResponse;
+import com.smartdevicelink.proxy.rpc.PutFileResponse;
+import com.smartdevicelink.proxy.rpc.ReadDIDResponse;
+import com.smartdevicelink.proxy.rpc.ResetGlobalPropertiesResponse;
+import com.smartdevicelink.proxy.rpc.ScrollableMessageResponse;
+import com.smartdevicelink.proxy.rpc.SendHapticDataResponse;
+import com.smartdevicelink.proxy.rpc.SendLocationResponse;
+import com.smartdevicelink.proxy.rpc.SetAppIconResponse;
+import com.smartdevicelink.proxy.rpc.SetCloudAppPropertiesResponse;
+import com.smartdevicelink.proxy.rpc.SetDisplayLayoutResponse;
+import com.smartdevicelink.proxy.rpc.SetGlobalPropertiesResponse;
+import com.smartdevicelink.proxy.rpc.SetInteriorVehicleDataResponse;
+import com.smartdevicelink.proxy.rpc.SetMediaClockTimerResponse;
+import com.smartdevicelink.proxy.rpc.ShowConstantTbtResponse;
+import com.smartdevicelink.proxy.rpc.ShowResponse;
+import com.smartdevicelink.proxy.rpc.SliderResponse;
+import com.smartdevicelink.proxy.rpc.SpeakResponse;
+import com.smartdevicelink.proxy.rpc.StreamRPCResponse;
+import com.smartdevicelink.proxy.rpc.SubscribeButtonResponse;
+import com.smartdevicelink.proxy.rpc.SubscribeVehicleDataResponse;
+import com.smartdevicelink.proxy.rpc.SubscribeWayPointsResponse;
+import com.smartdevicelink.proxy.rpc.SystemRequestResponse;
+import com.smartdevicelink.proxy.rpc.UnsubscribeButtonResponse;
+import com.smartdevicelink.proxy.rpc.UnsubscribeVehicleDataResponse;
+import com.smartdevicelink.proxy.rpc.UnsubscribeWayPointsResponse;
+import com.smartdevicelink.proxy.rpc.UpdateTurnListResponse;
+import com.smartdevicelink.proxy.rpc.enums.SdlDisconnectedReason;
+
+
+public interface IProxyListenerBase {
+
+ /**
+ * onOnHMIStatus being called indicates that there has been an HMI Level change,
+ * system context change or audio streaming state change.
+ *
+ * @param notification - Contains information about the HMI Level,
+ * system context and audio streaming state.
+ */
+ public void onOnHMIStatus(OnHMIStatus notification);
+
+ /**
+ * onProxyClosed has different functionality for the different models.
+ * In the non-ALM model this indicates that the proxy has experienced an unrecoverable error.
+ * A new proxy object must be initiated to reestablish connection with SDL.
+ * In the ALM model this indicates that the app is no longer registered with SDL
+ * All resources on SDL (addCommands and ChoiceSets) have been deleted and will have to be
+ * recreated upon the next onReadyForInitialization() call-back.
+ *
+ * @param info - Includes information about the reason the proxy has been closed.
+ * @param e - The exception that occurred.
+ */
+ public void onProxyClosed(String info, Exception e, SdlDisconnectedReason reason);
+
+ public void onServiceEnded(OnServiceEnded serviceEnded);
+
+ public void onServiceNACKed(OnServiceNACKed serviceNACKed);
+
+ public void onOnStreamRPC(OnStreamRPC notification);
+
+ public void onStreamRPCResponse(StreamRPCResponse response);
+
+ /**
+ * onProxyError() being called indicates that the SDL Proxy experenced an error.
+ *
+ * @param info - Includes information about the Exception that occurred.
+ * @param e - The exception that occurred.
+ */
+ public void onError(String info, Exception e);
+
+ /**
+ * onGenericResponse() being called indicates that SDL could not determine the
+ * type of request it is responding to. This is usually result of an unknown RPC Request
+ * being sent.
+ *
+ * @param response - Includes detailed information about the response.
+ */
+ public void onGenericResponse(GenericResponse response);
+
+ /**
+ * onOnCommand() being called indicates that the user selected a command on SDL.
+ *
+ * @param notification - Contains information about the command chosen.
+ */
+ public void onOnCommand(OnCommand notification);
+
+ /**
+ * onAddCommandResponse() being called indicates that SDL has responded to
+ * a request to add a command.
+ *
+ * @param response - Contains information about the response sent from SDL.
+ */
+ public void onAddCommandResponse(AddCommandResponse response);
+
+ /**
+ * onAddSubMenuResponse() being called indicates that SDL has responded to
+ * a request to add a command.
+ *
+ * @param response - Contains information about the response sent from SDL.
+ */
+ public void onAddSubMenuResponse(AddSubMenuResponse response);
+
+ /**
+ * onCreateInteractionChoiceSetResponse() being called indicates that SDL has
+ * responded to a request to add an interactionChoiceSet.
+ *
+ * @param response - Contains information about the response sent from SDL.
+ */
+ public void onCreateInteractionChoiceSetResponse(CreateInteractionChoiceSetResponse response);
+
+ /**
+ * onAlertResponse being called indicates that SDL has
+ * responded to a request to alert the user.
+ *
+ * @param response - Contains information about the response sent from SDL.
+ */
+ public void onAlertResponse(AlertResponse response);
+
+ /**
+ * onDeleteCommandResponse being called indicates that SDL has
+ * responded to a request to delete a command.
+ *
+ * @param response - Contains information about the response sent from SDL.
+ */
+ public void onDeleteCommandResponse(DeleteCommandResponse response);
+
+ /**
+ * onDeleteCommandResponse being called indicates that SDL has
+ * responded to a request to delete an interaction choice set.
+ *
+ * @param response - Contains information about the response sent from SDL.
+ */
+ public void onDeleteInteractionChoiceSetResponse(DeleteInteractionChoiceSetResponse response);
+
+ /**
+ * onDeleteCommandResponse being called indicates that SDL has
+ * responded to a request to delete a submenu.
+ *
+ * @param response - Contains information about the response sent from SDL.
+ */
+ public void onDeleteSubMenuResponse(DeleteSubMenuResponse response);
+
+ /**
+ * onPerformInteractionResponse being called indicates that SDL has
+ * responded to a request to perform an interaction.
+ *
+ * @param response - Contains information about the response sent from SDL.
+ */
+ public void onPerformInteractionResponse(PerformInteractionResponse response);
+
+ /**
+ * onResetGlobalPropertiesResponse being called indicates that SDL has
+ * responded to a request to reset global properties.
+ *
+ * @param response - Contains information about the response sent from SDL.
+ */
+ public void onResetGlobalPropertiesResponse(ResetGlobalPropertiesResponse response);
+
+ /**
+ * onSetGlobalPropertiesResponse being called indicates that SDL has
+ * responded to a request to set global properties.
+ *
+ * @param response - Contains information about the response sent from SDL.
+ */
+ public void onSetGlobalPropertiesResponse(SetGlobalPropertiesResponse response);
+
+ /**
+ * onSetMediaClockTimerResponse being called indicates that SDL has
+ * responded to a request to set the media clock timer.
+ *
+ * @param response - Contains information about the response sent from SDL.
+ */
+ public void onSetMediaClockTimerResponse(SetMediaClockTimerResponse response);
+
+ /**
+ * onShowResponse being called indicates that SDL has
+ * responded to a request to display information to the user.
+ *
+ * @param response - Contains information about the response sent from SDL.
+ */
+ public void onShowResponse(ShowResponse response);
+
+ /**
+ * onSpeakResponse being called indicates that SDL has
+ * responded to a request to speak information to the user.
+ *
+ * @param response - Contains information about the response sent from SDL.
+ */
+ public void onSpeakResponse(SpeakResponse response);
+
+ /**
+ * onButtonEvent being called indicates that a button event has occurred.
+ *
+ * @param notification - Contains information about the notification sent from SDL.
+ */
+ public void onOnButtonEvent(OnButtonEvent notification);
+
+ /**
+ * onButtonPress being called indicates that SDL has a button has
+ * been pressed by the user.
+ *
+ * @param notification - Contains information about the notification sent from SDL.
+ */
+ public void onOnButtonPress(OnButtonPress notification);
+
+ /**
+ * onSubscribeButtonResponse being called indicates that SDL has
+ * responded to a request to subscribe to button events and button presses.
+ *
+ * @param response - Contains information about the response sent from SDL.
+ */
+ public void onSubscribeButtonResponse(SubscribeButtonResponse response);
+
+ /**
+ * onUnsubscribeButtonResponse being called indicates that SDL has
+ * responded to a request to unsubscribe from button events and button presses.
+ *
+ * @param response - Contains information about the response sent from SDL.
+ */
+ public void onUnsubscribeButtonResponse(UnsubscribeButtonResponse response);
+
+ /**
+ * onOnPermissionsChange being called indicates that your app permissions have
+ * changed due to a policy table change. This can mean your app has received additional
+ * permissions OR lost permissions.
+ *
+ * @param notification - Contains information about the changed permissions.
+ */
+ public void onOnPermissionsChange(OnPermissionsChange notification);
+
+ public void onSubscribeVehicleDataResponse(SubscribeVehicleDataResponse response);
+
+ public void onUnsubscribeVehicleDataResponse(UnsubscribeVehicleDataResponse response);
+
+ public void onGetVehicleDataResponse(GetVehicleDataResponse response);
+
+ public void onOnVehicleData(OnVehicleData notification);
+
+ public void onPerformAudioPassThruResponse(PerformAudioPassThruResponse response);
+
+ public void onEndAudioPassThruResponse(EndAudioPassThruResponse response);
+
+ public void onOnAudioPassThru(OnAudioPassThru notification);
+
+ public void onPutFileResponse(PutFileResponse response);
+
+ public void onDeleteFileResponse(DeleteFileResponse response);
+
+ public void onListFilesResponse(ListFilesResponse response);
+
+ public void onSetAppIconResponse(SetAppIconResponse response);
+
+ public void onScrollableMessageResponse(ScrollableMessageResponse response);
+
+ public void onChangeRegistrationResponse(ChangeRegistrationResponse response);
+
+ public void onSetDisplayLayoutResponse(SetDisplayLayoutResponse response);
+
+ public void onOnLanguageChange(OnLanguageChange notification);
+
+ public void onOnHashChange(OnHashChange notification);
+
+ public void onSliderResponse(SliderResponse response);
+
+ public void onOnDriverDistraction(OnDriverDistraction notification);
+
+ public void onOnTBTClientState(OnTBTClientState notification);
+
+ public void onOnSystemRequest(OnSystemRequest notification);
+
+ public void onSystemRequestResponse(SystemRequestResponse response);
+
+ public void onOnKeyboardInput(OnKeyboardInput notification);
+
+ public void onOnTouchEvent(OnTouchEvent notification);
+
+ public void onDiagnosticMessageResponse(DiagnosticMessageResponse response);
+
+ public void onReadDIDResponse(ReadDIDResponse response);
+
+ public void onGetDTCsResponse(GetDTCsResponse response);
+
+ public void onOnLockScreenNotification(OnLockScreenStatus notification);
+
+ public void onDialNumberResponse(DialNumberResponse response);
+
+ public void onSendLocationResponse(SendLocationResponse response);
+
+ public void onShowConstantTbtResponse(ShowConstantTbtResponse response);
+
+ public void onAlertManeuverResponse(AlertManeuverResponse response);
+
+ public void onUpdateTurnListResponse(UpdateTurnListResponse response);
+
+ public void onServiceDataACK(int dataSize);
+
+ public void onGetWayPointsResponse(GetWayPointsResponse response);
+
+ public void onSubscribeWayPointsResponse(SubscribeWayPointsResponse response);
+
+ public void onUnsubscribeWayPointsResponse(UnsubscribeWayPointsResponse response);
+
+ public void onOnWayPointChange(OnWayPointChange notification);
+
+ public void onGetSystemCapabilityResponse(GetSystemCapabilityResponse response);
+
+ public void onGetInteriorVehicleDataResponse(GetInteriorVehicleDataResponse response);
+
+ public void onButtonPressResponse(ButtonPressResponse response);
+
+ public void onSetInteriorVehicleDataResponse(SetInteriorVehicleDataResponse response);
+
+ public void onOnInteriorVehicleData(OnInteriorVehicleData notification);
+
+ public void onSendHapticDataResponse(SendHapticDataResponse response);
+
+ public void onOnRCStatus(OnRCStatus notification);
+
+ public void onSetCloudAppProperties(SetCloudAppPropertiesResponse response);
+
+ public void onGetCloudAppProperties(GetCloudAppPropertiesResponse response);
+
+ public void onPublishAppServiceResponse(PublishAppServiceResponse response);
+
+ public void onGetAppServiceDataResponse(GetAppServiceDataResponse response);
+
+ public void onGetFileResponse(GetFileResponse response);
+
+ public void onPerformAppServiceInteractionResponse(PerformAppServiceInteractionResponse response);
+
+ public void onOnAppServiceData(OnAppServiceData notification);
+
+ public void onOnSystemCapabilityUpdated(OnSystemCapabilityUpdated notification);
+
+}
\ No newline at end of file diff --git a/base/src/main/java/com/smartdevicelink/proxy/interfaces/ISdl.java b/base/src/main/java/com/smartdevicelink/proxy/interfaces/ISdl.java index 5eb8ff36a..d97d64735 100644 --- a/base/src/main/java/com/smartdevicelink/proxy/interfaces/ISdl.java +++ b/base/src/main/java/com/smartdevicelink/proxy/interfaces/ISdl.java @@ -4,6 +4,7 @@ import android.support.annotation.NonNull; import com.smartdevicelink.protocol.enums.FunctionID; import com.smartdevicelink.protocol.enums.SessionType; +import com.smartdevicelink.proxy.RPCMessage; import com.smartdevicelink.proxy.RPCRequest; import com.smartdevicelink.util.Version; import com.smartdevicelink.proxy.rpc.SdlMsgVersion; @@ -130,9 +131,16 @@ public interface ISdl { * Pass an RPC message through the proxy to be sent to the connected module * @param message RPCRequest that should be sent to the module */ + @Deprecated void sendRPCRequest(RPCRequest message); /** + * Pass an RPC message through the proxy to be sent to the connected module + * @param message RPCMessage that should be sent to the module + */ + void sendRPC(RPCMessage message); + + /** * Pass a list of RPC requests through the proxy to be sent to core * @param rpcs List of RPC requests * @param listener OnMultipleRequestListener that is called between requests and after all are processed diff --git a/base/src/main/java/com/smartdevicelink/streaming/AbstractPacketizer.java b/base/src/main/java/com/smartdevicelink/streaming/AbstractPacketizer.java index d50964bff..1a2c393cd 100644 --- a/base/src/main/java/com/smartdevicelink/streaming/AbstractPacketizer.java +++ b/base/src/main/java/com/smartdevicelink/streaming/AbstractPacketizer.java @@ -1,82 +1,82 @@ -package com.smartdevicelink.streaming; - -import java.io.IOException; -import java.io.InputStream; - -import com.smartdevicelink.SdlConnection.SdlSession; -import com.smartdevicelink.protocol.enums.SessionType; -import com.smartdevicelink.proxy.RPCRequest; -import com.smartdevicelink.util.Version; - -abstract public class AbstractPacketizer { - - protected IStreamListener _streamListener = null; - protected byte _rpcSessionID = 0; - - protected SessionType _serviceType = null; - protected SdlSession _session = null; - protected InputStream is = null; - protected int bufferSize; - protected byte[] buffer; - protected boolean upts = false; - protected RPCRequest _request = null; - protected Version _wiproVersion = new Version("1.0.0"); - - //protected long ts = 0, intervalBetweenReports = 5000, delta = 0; - protected long intervalBetweenReports = 5000, delta = 0; - - public AbstractPacketizer(IStreamListener streamListener, InputStream is, SessionType sType, byte rpcSessionID, SdlSession session) throws IOException, IllegalArgumentException { - this._streamListener = streamListener; - this.is = is; - _rpcSessionID = rpcSessionID; - _serviceType = sType; - this._session = session; - if (this._session != null) { - bufferSize = this._session.getMtu(); - buffer = new byte[bufferSize]; - }else{ - throw new IllegalArgumentException("Session variable is null"); - } - } - - @Deprecated - public AbstractPacketizer(IStreamListener streamListener, InputStream is, RPCRequest request, SessionType sType, byte rpcSessionID, byte wiproVersion, SdlSession session) throws IOException, IllegalArgumentException { - this._streamListener = streamListener; - this.is = is; - _rpcSessionID = rpcSessionID; - _serviceType = sType; - _request = request; - _wiproVersion = new Version(wiproVersion+".0.0"); - this._session = session; - if (this._session != null) { - bufferSize = this._session.getMtu(); - buffer = new byte[bufferSize]; - }else{ - throw new IllegalArgumentException("Session variable is null"); - } - } - - public AbstractPacketizer(IStreamListener streamListener, InputStream is, RPCRequest request, SessionType sType, byte rpcSessionID, Version protocolVersion, SdlSession session) throws IOException, IllegalArgumentException { - this._streamListener = streamListener; - this.is = is; - _rpcSessionID = rpcSessionID; - _serviceType = sType; - _request = request; - _wiproVersion = protocolVersion; - this._session = session; - if (this._session != null) { - bufferSize = this._session.getMtu(); - buffer = new byte[bufferSize]; - }else{ - throw new IllegalArgumentException("Session variable is null"); - } - } - - public abstract void start() throws IOException; - - public abstract void stop(); - - public abstract void pause(); - - public abstract void resume(); +package com.smartdevicelink.streaming;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+import com.smartdevicelink.SdlConnection.SdlSession;
+import com.smartdevicelink.protocol.enums.SessionType;
+import com.smartdevicelink.proxy.RPCRequest;
+import com.smartdevicelink.util.Version;
+
+abstract public class AbstractPacketizer {
+
+ protected IStreamListener _streamListener = null;
+ protected byte _rpcSessionID = 0;
+
+ protected SessionType _serviceType = null;
+ protected SdlSession _session = null;
+ protected InputStream is = null;
+ protected int bufferSize;
+ protected byte[] buffer;
+ protected boolean upts = false;
+ protected RPCRequest _request = null;
+ protected Version _wiproVersion = new Version("1.0.0");
+
+ //protected long ts = 0, intervalBetweenReports = 5000, delta = 0;
+ protected long intervalBetweenReports = 5000, delta = 0;
+
+ public AbstractPacketizer(IStreamListener streamListener, InputStream is, SessionType sType, byte rpcSessionID, SdlSession session) throws IOException, IllegalArgumentException {
+ this._streamListener = streamListener;
+ this.is = is;
+ _rpcSessionID = rpcSessionID;
+ _serviceType = sType;
+ this._session = session;
+ if (this._session != null) {
+ bufferSize = this._session.getMtu();
+ buffer = new byte[bufferSize];
+ }else{
+ throw new IllegalArgumentException("Session variable is null");
+ }
+ }
+
+ @Deprecated
+ public AbstractPacketizer(IStreamListener streamListener, InputStream is, RPCRequest request, SessionType sType, byte rpcSessionID, byte wiproVersion, SdlSession session) throws IOException, IllegalArgumentException {
+ this._streamListener = streamListener;
+ this.is = is;
+ _rpcSessionID = rpcSessionID;
+ _serviceType = sType;
+ _request = request;
+ _wiproVersion = new Version(wiproVersion+".0.0");
+ this._session = session;
+ if (this._session != null) {
+ bufferSize = this._session.getMtu();
+ buffer = new byte[bufferSize];
+ }else{
+ throw new IllegalArgumentException("Session variable is null");
+ }
+ }
+
+ public AbstractPacketizer(IStreamListener streamListener, InputStream is, RPCRequest request, SessionType sType, byte rpcSessionID, Version protocolVersion, SdlSession session) throws IOException, IllegalArgumentException {
+ this._streamListener = streamListener;
+ this.is = is;
+ _rpcSessionID = rpcSessionID;
+ _serviceType = sType;
+ _request = request;
+ _wiproVersion = protocolVersion;
+ this._session = session;
+ if (this._session != null) {
+ bufferSize = this._session.getMtu();
+ buffer = new byte[bufferSize];
+ }else{
+ throw new IllegalArgumentException("Session variable is null");
+ }
+ }
+
+ public abstract void start() throws IOException;
+
+ public abstract void stop();
+
+ public abstract void pause();
+
+ public abstract void resume();
}
\ No newline at end of file diff --git a/base/src/main/java/com/smartdevicelink/streaming/IStreamListener.java b/base/src/main/java/com/smartdevicelink/streaming/IStreamListener.java index 5ec12bbaf..2e19cf578 100644 --- a/base/src/main/java/com/smartdevicelink/streaming/IStreamListener.java +++ b/base/src/main/java/com/smartdevicelink/streaming/IStreamListener.java @@ -1,7 +1,7 @@ -package com.smartdevicelink.streaming; - -import com.smartdevicelink.protocol.ProtocolMessage; - -public interface IStreamListener { - void sendStreamPacket(ProtocolMessage pm); +package com.smartdevicelink.streaming;
+
+import com.smartdevicelink.protocol.ProtocolMessage;
+
+public interface IStreamListener {
+ void sendStreamPacket(ProtocolMessage pm);
}
\ No newline at end of file diff --git a/base/src/main/java/com/smartdevicelink/streaming/StreamRPCPacketizer.java b/base/src/main/java/com/smartdevicelink/streaming/StreamRPCPacketizer.java deleted file mode 100644 index 1e3821ff8..000000000 --- a/base/src/main/java/com/smartdevicelink/streaming/StreamRPCPacketizer.java +++ /dev/null @@ -1,308 +0,0 @@ -package com.smartdevicelink.streaming; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Hashtable; - -import com.smartdevicelink.SdlConnection.SdlSession; - -import com.smartdevicelink.marshal.JsonRPCMarshaller; -import com.smartdevicelink.protocol.ProtocolMessage; -import com.smartdevicelink.protocol.enums.FunctionID; -import com.smartdevicelink.protocol.enums.MessageType; -import com.smartdevicelink.protocol.enums.SessionType; -import com.smartdevicelink.proxy.RPCRequest; -import com.smartdevicelink.proxy.RPCResponse; -import com.smartdevicelink.proxy.interfaces.IProxyListenerBase; -import com.smartdevicelink.proxy.interfaces.IPutFileResponseListener; -import com.smartdevicelink.proxy.rpc.OnStreamRPC; -import com.smartdevicelink.proxy.rpc.PutFile; -import com.smartdevicelink.proxy.rpc.PutFileResponse; -import com.smartdevicelink.proxy.rpc.StreamRPCResponse; -import com.smartdevicelink.proxy.rpc.enums.Result; -import com.smartdevicelink.proxy.rpc.listeners.OnPutFileUpdateListener; -import com.smartdevicelink.util.Version; - -public class StreamRPCPacketizer extends AbstractPacketizer implements IPutFileResponseListener, Runnable{ - - private Integer iInitialCorrID = 0; - private Hashtable<Integer, OnStreamRPC> notificationList = new Hashtable<Integer, OnStreamRPC>(); - private Thread thread = null; - private long lFileSize = 0; - private String sFileName; - private Object proxy; //FIXME SdlProxyBase<IProxyListenerBase> _proxy; - private IProxyListenerBase _proxyListener; - - private Object mPauseLock; - private boolean mPaused; - private boolean isRPCProtected = false; - private OnPutFileUpdateListener callBack; - - private Version rpcSpecVersion; - - //public StreamRPCPacketizer(SdlProxyBase<IProxyListenerBase> proxy, IStreamListener streamListener, InputStream is, RPCRequest request, SessionType sType, byte rpcSessionID, byte wiproVersion, long lLength, SdlSession session) throws IOException { - public StreamRPCPacketizer(Object proxy, IStreamListener streamListener, InputStream is, RPCRequest request, SessionType sType, byte rpcSessionID, byte wiproVersion, long lLength, SdlSession session) throws IOException { - super(streamListener, is, request, sType, rpcSessionID, wiproVersion, session); - lFileSize = lLength; - iInitialCorrID = request.getCorrelationID(); - mPauseLock = new Object(); - mPaused = false; - isRPCProtected = request.isPayloadProtected(); - /* FIXME if (proxy != null) - { - _proxy = proxy; - _proxyListener = _proxy.getProxyListener(); - _proxy.addPutFileResponseListener(this); - }*/ - if(_request.getFunctionName().equalsIgnoreCase(FunctionID.PUT_FILE.toString())){ - callBack = ((PutFile)_request).getOnPutFileUpdateListener(); - } - } - - //public StreamRPCPacketizer(SdlProxyBase<IProxyListenerBase> proxy, IStreamListener streamListener, InputStream is, RPCRequest request, SessionType sType, byte rpcSessionID, Version wiproVersion, Version rpcSpecVersion, long lLength, SdlSession session) throws IOException { - public StreamRPCPacketizer(Object proxy, IStreamListener streamListener, InputStream is, RPCRequest request, SessionType sType, byte rpcSessionID, Version wiproVersion, Version rpcSpecVersion, long lLength, SdlSession session) throws IOException { - super(streamListener, is, request, sType, rpcSessionID, wiproVersion, session); - this.rpcSpecVersion = rpcSpecVersion; - lFileSize = lLength; - iInitialCorrID = request.getCorrelationID(); - mPauseLock = new Object(); - mPaused = false; - isRPCProtected = request.isPayloadProtected(); - /* FIXME if (proxy != null) { - _proxy = proxy; - _proxyListener = _proxy.getProxyListener(); - _proxy.addPutFileResponseListener(this); - }*/ - if(_request.getFunctionName().equalsIgnoreCase(FunctionID.PUT_FILE.toString())){ - callBack = ((PutFile)_request).getOnPutFileUpdateListener(); - } - } - - @Override - public void start() throws IOException { - if (thread == null) { - thread = new Thread(this); - thread.start(); - } - } - - @Override - public void stop() { - try { - is.close(); - } catch (IOException ignore) {} - if (thread != null) - { - thread.interrupt(); - thread = null; - } - } - - private void handleStreamSuccess(RPCResponse rpc, Long iSize) - { - StreamRPCResponse result = new StreamRPCResponse(); - result.setSuccess(rpc.getSuccess()); - result.setResultCode(rpc.getResultCode()); - result.setInfo(rpc.getInfo()); - result.setFileName(sFileName); - result.setFileSize(iSize); - result.setCorrelationID(iInitialCorrID); - if (_proxyListener != null) - _proxyListener.onStreamRPCResponse(result); - stop(); - //FIXME _proxy.remPutFileResponseListener(this); - return; - } - - private void handleStreamException(RPCResponse rpc, Exception e, String error) - { - StreamRPCResponse result = new StreamRPCResponse(); - result.setFileName(sFileName); - result.setCorrelationID(iInitialCorrID); - if (rpc != null) - { - result.setSuccess(rpc.getSuccess()); - result.setResultCode(rpc.getResultCode()); - result.setInfo(rpc.getInfo()); - } - else - { - result.setSuccess(false); - result.setResultCode(Result.GENERIC_ERROR); - String sException = ""; - - if (e != null) - sException = sException + " " + e.toString(); - - sException = sException + " " + error; - result.setInfo(sException); - } - if (_proxyListener != null) - _proxyListener.onStreamRPCResponse(result); - if (e != null) - e.printStackTrace(); - stop(); - //FIXME _proxy.remPutFileResponseListener(this); - return; - } - - @Override - public void pause() { - synchronized (mPauseLock) { - mPaused = true; - } - } - - @Override - public void resume() { - synchronized (mPauseLock) { - mPaused = false; - mPauseLock.notifyAll(); - } - } - - public void run() { - int length; - byte[] msgBytes; - ProtocolMessage pm; - OnStreamRPC notification; - - // Moves the current Thread into the background - //FIXME android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND); - - try { - - int iCorrID = 0; - PutFile msg = (PutFile) _request; - sFileName = msg.getSdlFileName(); - long iOffsetCounter = msg.getOffset(); - - int priorityCoefficient = 1; - - if (lFileSize != 0) - { - Long iFileSize = (long) lFileSize; - //TODO: PutFile RPC needs to be updated to accept Long as we might run into overflows since a Long can store a wider range than an Integer - msg.setLength(iFileSize); - } - Long iFileLength = msg.getLength(); - - notificationList.clear(); - - //start reading from the stream at the given offset - long iSkipBytes = is.skip(iOffsetCounter); - - if (iOffsetCounter != iSkipBytes) - { - handleStreamException(null,null," Error, PutFile offset invalid for file: " + sFileName); - } - if(callBack!=null){ - callBack.onStart(_request.getCorrelationID(), lFileSize); - } - while (!Thread.interrupted()) { - - synchronized (mPauseLock) - { - while (mPaused) - { - try - { - mPauseLock.wait(); - } - catch (InterruptedException e) {} - } - } - - length = is.read(buffer, 0, bufferSize); - - if (length == -1) - stop(); - - if (length >= 0) { - - if (msg.getOffset() != 0) - msg.setLength((Long)null); //only need to send length when offset 0 - - msg.format(rpcSpecVersion,true); - msgBytes = JsonRPCMarshaller.marshall(msg, (byte)_wiproVersion.getMajor()); - pm = new ProtocolMessage(); - pm.setData(msgBytes); - - pm.setSessionID(_rpcSessionID); - pm.setMessageType(MessageType.RPC); - pm.setSessionType(_serviceType); - pm.setFunctionID(FunctionID.getFunctionId(msg.getFunctionName())); - - if (buffer.length != length) - pm.setBulkData(buffer, length); - else - pm.setBulkDataNoCopy(buffer); - - pm.setCorrID(msg.getCorrelationID()); - pm.setPayloadProtected(isRPCProtected); - priorityCoefficient++; - pm.setPriorityCoefficient(priorityCoefficient); - - notification = new OnStreamRPC(); - notification.setFileName(msg.getSdlFileName()); - notification.setFileSize(iFileLength); - iOffsetCounter = iOffsetCounter + length; - notification.setBytesComplete(iOffsetCounter); - notificationList.put(msg.getCorrelationID(),notification); - - msg.setOffset(iOffsetCounter); - iCorrID = msg.getCorrelationID() + 1; - msg.setCorrelationID(iCorrID); - - _streamListener.sendStreamPacket(pm); - } - } - } catch (Exception e) { - handleStreamException(null, e, ""); - } - } - - @Override - public void onPutFileResponse(PutFileResponse response) - { - - OnStreamRPC streamNote = notificationList.get(response.getCorrelationID()); - if (streamNote == null) return; - - if (response.getSuccess()) - { - if(callBack!=null){ - callBack.onUpdate(response.getCorrelationID(), streamNote.getBytesComplete(), lFileSize); - } - if (_proxyListener != null){ - _proxyListener.onOnStreamRPC(streamNote); - } - - } - else - { - if(callBack!=null){ - callBack.onError(response.getCorrelationID(), response.getResultCode(), response.getInfo()); - } - handleStreamException(response, null, ""); - - } - - if (response.getSuccess() && streamNote.getBytesComplete().equals(streamNote.getFileSize()) ) - { - if(callBack!=null){ - callBack.onResponse(iInitialCorrID, response, streamNote.getBytesComplete()); - } - handleStreamSuccess(response, streamNote.getBytesComplete()); - - } - } - - @Override - public void onPutFileStreamError(Exception e, String info) - { - if (thread != null) - handleStreamException(null, e, info); - - } -} diff --git a/base/src/main/java/com/smartdevicelink/streaming/video/VideoStreamingParameters.java b/base/src/main/java/com/smartdevicelink/streaming/video/VideoStreamingParameters.java index 0d16f7281..09919c598 100644 --- a/base/src/main/java/com/smartdevicelink/streaming/video/VideoStreamingParameters.java +++ b/base/src/main/java/com/smartdevicelink/streaming/video/VideoStreamingParameters.java @@ -32,8 +32,6 @@ package com.smartdevicelink.streaming.video; -//import android.util.DisplayMetrics; - import com.smartdevicelink.proxy.rpc.ImageResolution; import com.smartdevicelink.proxy.rpc.VideoStreamingCapability; import com.smartdevicelink.proxy.rpc.VideoStreamingFormat; @@ -48,7 +46,7 @@ public class VideoStreamingParameters { private final VideoStreamingCodec DEFAULT_CODEC = VideoStreamingCodec.H264; private final int DEFAULT_WIDTH = 1024; private final int DEFAULT_HEIGHT = 576; - private final int DEFAULT_DENSITY = 100; //FIXME DisplayMetrics.DENSITY_HIGH; + private final int DEFAULT_DENSITY = 240; private final int DEFAULT_FRAMERATE = 30; private final int DEFAULT_BITRATE = 512000; private final int DEFAULT_INTERVAL = 5; diff --git a/base/src/main/java/com/smartdevicelink/trace/DiagLevel.java b/base/src/main/java/com/smartdevicelink/trace/DiagLevel.java index c88751378..26dfdebff 100644 --- a/base/src/main/java/com/smartdevicelink/trace/DiagLevel.java +++ b/base/src/main/java/com/smartdevicelink/trace/DiagLevel.java @@ -1,61 +1,61 @@ -package com.smartdevicelink.trace; - -import com.smartdevicelink.trace.enums.DetailLevel; -import com.smartdevicelink.trace.enums.Mod; - - -public class DiagLevel { - - static private DetailLevel[] levels; - - static { // this is a static c-tor!! - levels = new DetailLevel[Mod.values().length]; - setAllLevels(DetailLevel.OFF); - } - - public static void setAllLevels(DetailLevel thisDetail) { - if (thisDetail != null) { - for (int i = 0; i < levels.length; i++) { - levels[i] = thisDetail; // - } - } - } - - public static void setLevel(Mod thisMod, DetailLevel thisDetail) { - if (thisMod != null && thisDetail != null) { - levels[thisMod.ordinal()] = thisDetail; - } - } - - public static DetailLevel getLevel(Mod thisMod) { - if (thisMod != null) { - return levels[thisMod.ordinal()]; - } - return null; - } - - public static boolean isValidDetailLevel(String dtString) { - // Assume false - Boolean isValid = false; - - if (dtString != null) { - if (dtString.equalsIgnoreCase("verbose")) - isValid = true; - else if (dtString.equalsIgnoreCase("terse")) - isValid = true; - else if (dtString.equalsIgnoreCase("off")) - isValid = true; - } - - return isValid; - } - - public static DetailLevel toDetailLevel(String dtString) { - DetailLevel dt = DetailLevel.OFF; - if (dtString.equalsIgnoreCase("verbose")) - dt = DetailLevel.VERBOSE; - else if (dtString.equalsIgnoreCase("terse")) - dt = DetailLevel.TERSE; - return dt; - } -} +package com.smartdevicelink.trace;
+
+import com.smartdevicelink.trace.enums.DetailLevel;
+import com.smartdevicelink.trace.enums.Mod;
+
+
+public class DiagLevel {
+
+ static private DetailLevel[] levels;
+
+ static { // this is a static c-tor!!
+ levels = new DetailLevel[Mod.values().length];
+ setAllLevels(DetailLevel.OFF);
+ }
+
+ public static void setAllLevels(DetailLevel thisDetail) {
+ if (thisDetail != null) {
+ for (int i = 0; i < levels.length; i++) {
+ levels[i] = thisDetail; //
+ }
+ }
+ }
+
+ public static void setLevel(Mod thisMod, DetailLevel thisDetail) {
+ if (thisMod != null && thisDetail != null) {
+ levels[thisMod.ordinal()] = thisDetail;
+ }
+ }
+
+ public static DetailLevel getLevel(Mod thisMod) {
+ if (thisMod != null) {
+ return levels[thisMod.ordinal()];
+ }
+ return null;
+ }
+
+ public static boolean isValidDetailLevel(String dtString) {
+ // Assume false
+ Boolean isValid = false;
+
+ if (dtString != null) {
+ if (dtString.equalsIgnoreCase("verbose"))
+ isValid = true;
+ else if (dtString.equalsIgnoreCase("terse"))
+ isValid = true;
+ else if (dtString.equalsIgnoreCase("off"))
+ isValid = true;
+ }
+
+ return isValid;
+ }
+
+ public static DetailLevel toDetailLevel(String dtString) {
+ DetailLevel dt = DetailLevel.OFF;
+ if (dtString.equalsIgnoreCase("verbose"))
+ dt = DetailLevel.VERBOSE;
+ else if (dtString.equalsIgnoreCase("terse"))
+ dt = DetailLevel.TERSE;
+ return dt;
+ }
+}
diff --git a/base/src/main/java/com/smartdevicelink/trace/ISTListener.java b/base/src/main/java/com/smartdevicelink/trace/ISTListener.java index 35cc55de5..3af7d5020 100644 --- a/base/src/main/java/com/smartdevicelink/trace/ISTListener.java +++ b/base/src/main/java/com/smartdevicelink/trace/ISTListener.java @@ -1,5 +1,5 @@ -package com.smartdevicelink.trace; - -public interface ISTListener { - void logXmlMsg(String msg, String token); +package com.smartdevicelink.trace;
+
+public interface ISTListener {
+ void logXmlMsg(String msg, String token);
} // end-interface
\ No newline at end of file diff --git a/base/src/main/java/com/smartdevicelink/trace/Mime.java b/base/src/main/java/com/smartdevicelink/trace/Mime.java index 173a017d6..799ac98f4 100644 --- a/base/src/main/java/com/smartdevicelink/trace/Mime.java +++ b/base/src/main/java/com/smartdevicelink/trace/Mime.java @@ -1,100 +1,100 @@ -package com.smartdevicelink.trace; - -// Borrowed from Dave Boll's infamous SdlLinkRelay.java - -public class Mime { - - private static final String BASE_64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - - /** - * @param str A String to encode into base64 String. - * @return Base64 encoded String or a null String if input is null. - */ - public static String base64Encode(String str) { - if(str == null){ - return null; - } - - String b64String = ""; - try { - byte[] strBytes = str.getBytes("US-ASCII"); - b64String = base64Encode(strBytes); - } catch (Exception ex) { - // Don't care? - } - return b64String; - } - - /** - * @param bytesToEncode A byte array to encode into base64 String. - * @return Base64 encoded String or a null String if input array is null. - */ - public static String base64Encode(byte bytesToEncode[]) { - if(bytesToEncode != null){ - return base64Encode(bytesToEncode, 0, bytesToEncode.length); - } - return null; - } - - /** - * @param bytesToEncode A byte array to encode into base64 String. - * @param offset Offset to begin at - * @param length Length to read - * @return Base64 encoded String or a null String if input array is null or the input range is out of bounds. - */ - public static String base64Encode(byte bytesToEncode[], int offset, int length) { - if (bytesToEncode == null || bytesToEncode.length < length || bytesToEncode.length < offset + length) { - return null; - } - - StringBuilder sb = new StringBuilder(); - - int idxin = 0; - int b64idx = 0; - - for (idxin = offset; idxin < offset + length; idxin++) { - switch ((idxin - offset) % 3) { - case 0: - b64idx = (bytesToEncode[idxin] >> 2) & 0x3f; - break; - case 1: - b64idx = (bytesToEncode[idxin] >> 4) & 0x0f; - b64idx |= ((bytesToEncode[idxin - 1] << 4) & 0x30); - break; - case 2: - b64idx = (bytesToEncode[idxin] >> 6) & 0x03; - b64idx |= ((bytesToEncode[idxin - 1] << 2) & 0x3c); - sb.append(getBase64Char(b64idx)); - b64idx = bytesToEncode[idxin] & 0x3f; - break; - } - sb.append(getBase64Char(b64idx)); - } - - switch ((idxin - offset) % 3) { - case 0: - break; - case 1: - b64idx = (bytesToEncode[idxin - 1] << 4) & 0x30; - sb.append(getBase64Char(b64idx)); - sb.append("=="); - break; - case 2: - b64idx = ((bytesToEncode[idxin - 1] << 2) & 0x3c); - sb.append(getBase64Char(b64idx)); - sb.append('='); - break; - } - - return sb.toString(); - - } - - private static char getBase64Char(int b64idx){ - if(b64idx >= 0 && b64idx < BASE_64_CHARS.length()) { - return BASE_64_CHARS.charAt(b64idx); - }else{ - return 0x20; - } - } +package com.smartdevicelink.trace;
+
+// Borrowed from Dave Boll's infamous SdlLinkRelay.java
+
+public class Mime {
+
+ private static final String BASE_64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+
+ /**
+ * @param str A String to encode into base64 String.
+ * @return Base64 encoded String or a null String if input is null.
+ */
+ public static String base64Encode(String str) {
+ if(str == null){
+ return null;
+ }
+
+ String b64String = "";
+ try {
+ byte[] strBytes = str.getBytes("US-ASCII");
+ b64String = base64Encode(strBytes);
+ } catch (Exception ex) {
+ // Don't care?
+ }
+ return b64String;
+ }
+
+ /**
+ * @param bytesToEncode A byte array to encode into base64 String.
+ * @return Base64 encoded String or a null String if input array is null.
+ */
+ public static String base64Encode(byte bytesToEncode[]) {
+ if(bytesToEncode != null){
+ return base64Encode(bytesToEncode, 0, bytesToEncode.length);
+ }
+ return null;
+ }
+
+ /**
+ * @param bytesToEncode A byte array to encode into base64 String.
+ * @param offset Offset to begin at
+ * @param length Length to read
+ * @return Base64 encoded String or a null String if input array is null or the input range is out of bounds.
+ */
+ public static String base64Encode(byte bytesToEncode[], int offset, int length) {
+ if (bytesToEncode == null || bytesToEncode.length < length || bytesToEncode.length < offset + length) {
+ return null;
+ }
+
+ StringBuilder sb = new StringBuilder();
+
+ int idxin = 0;
+ int b64idx = 0;
+
+ for (idxin = offset; idxin < offset + length; idxin++) {
+ switch ((idxin - offset) % 3) {
+ case 0:
+ b64idx = (bytesToEncode[idxin] >> 2) & 0x3f;
+ break;
+ case 1:
+ b64idx = (bytesToEncode[idxin] >> 4) & 0x0f;
+ b64idx |= ((bytesToEncode[idxin - 1] << 4) & 0x30);
+ break;
+ case 2:
+ b64idx = (bytesToEncode[idxin] >> 6) & 0x03;
+ b64idx |= ((bytesToEncode[idxin - 1] << 2) & 0x3c);
+ sb.append(getBase64Char(b64idx));
+ b64idx = bytesToEncode[idxin] & 0x3f;
+ break;
+ }
+ sb.append(getBase64Char(b64idx));
+ }
+
+ switch ((idxin - offset) % 3) {
+ case 0:
+ break;
+ case 1:
+ b64idx = (bytesToEncode[idxin - 1] << 4) & 0x30;
+ sb.append(getBase64Char(b64idx));
+ sb.append("==");
+ break;
+ case 2:
+ b64idx = ((bytesToEncode[idxin - 1] << 2) & 0x3c);
+ sb.append(getBase64Char(b64idx));
+ sb.append('=');
+ break;
+ }
+
+ return sb.toString();
+
+ }
+
+ private static char getBase64Char(int b64idx){
+ if(b64idx >= 0 && b64idx < BASE_64_CHARS.length()) {
+ return BASE_64_CHARS.charAt(b64idx);
+ }else{
+ return 0x20;
+ }
+ }
}
\ No newline at end of file diff --git a/base/src/main/java/com/smartdevicelink/trace/OpenRPCMessage.java b/base/src/main/java/com/smartdevicelink/trace/OpenRPCMessage.java index 13b690d91..35a8de749 100644 --- a/base/src/main/java/com/smartdevicelink/trace/OpenRPCMessage.java +++ b/base/src/main/java/com/smartdevicelink/trace/OpenRPCMessage.java @@ -1,86 +1,86 @@ -package com.smartdevicelink.trace; - -import java.util.Hashtable; -import java.util.Iterator; -import java.util.List; - -import com.smartdevicelink.proxy.RPCMessage; -import com.smartdevicelink.proxy.RPCStruct; - -class OpenRPCMessage extends RPCMessage { - private OpenRPCMessage() {super("");} - public OpenRPCMessage(RPCMessage rpcm) { - super(rpcm); - } // end-method - - public OpenRPCMessage(RPCStruct rpcs) { - super(rpcs); - } // end-method - - public String msgDump() { - StringBuilder pd = new StringBuilder(); - - pd.append(this.getFunctionName() + " " + this.getMessageType()); - - msgDump(pd); - - return pd.toString(); - } // end-method - - public void msgDump(StringBuilder pd) { - pd.append("["); - - dumpParams(parameters, pd); - - pd.append("]"); - - return; - } // end-method - - private void dumpParams(Hashtable<String, Object> ht, StringBuilder pd) { - Iterator<String> keySet = ht.keySet().iterator(); - Object obj = null; - String key = ""; - boolean isFirstParam = true; - - while (keySet.hasNext()) { - key = (String)keySet.next(); - obj = ht.get(key); - if (isFirstParam) { - isFirstParam = false; - } else { - pd.append(", "); - } // end-if - - dumpParamNode(key, obj, pd); - - } // end-while - } // end-method - - @SuppressWarnings("unchecked") - private void dumpParamNode(String key, Object obj, StringBuilder pd) { - - if (obj instanceof Hashtable) { - pd.append("["); - dumpParams((Hashtable<String, Object>)obj, pd); - pd.append("]"); - } else if (obj instanceof RPCStruct) { - pd.append("["); - OpenRPCMessage orpcm = new OpenRPCMessage((RPCStruct)obj); - orpcm.msgDump(pd); - pd.append("]"); - } else if (obj instanceof List) { - pd.append("["); - List<?> list = (List<?>)obj; - for (int idx=0;idx < list.size();idx++) { - if (idx > 0) { - pd.append(", "); - } - dumpParamNode(key, list.get(idx), pd); - } // end-for - pd.append("]"); - } else { - pd.append("\"" + key + "\" = \"" + obj.toString() + "\""); - } - } // end-method -} // end-class OpenRPCMessage +package com.smartdevicelink.trace;
+
+import java.util.Hashtable;
+import java.util.Iterator;
+import java.util.List;
+
+import com.smartdevicelink.proxy.RPCMessage;
+import com.smartdevicelink.proxy.RPCStruct;
+
+class OpenRPCMessage extends RPCMessage {
+ private OpenRPCMessage() {super("");}
+ public OpenRPCMessage(RPCMessage rpcm) {
+ super(rpcm);
+ } // end-method
+
+ public OpenRPCMessage(RPCStruct rpcs) {
+ super(rpcs);
+ } // end-method
+
+ public String msgDump() {
+ StringBuilder pd = new StringBuilder();
+
+ pd.append(this.getFunctionName() + " " + this.getMessageType());
+
+ msgDump(pd);
+
+ return pd.toString();
+ } // end-method
+
+ public void msgDump(StringBuilder pd) {
+ pd.append("[");
+
+ dumpParams(parameters, pd);
+
+ pd.append("]");
+
+ return;
+ } // end-method
+
+ private void dumpParams(Hashtable<String, Object> ht, StringBuilder pd) {
+ Iterator<String> keySet = ht.keySet().iterator();
+ Object obj = null;
+ String key = "";
+ boolean isFirstParam = true;
+
+ while (keySet.hasNext()) {
+ key = (String)keySet.next();
+ obj = ht.get(key);
+ if (isFirstParam) {
+ isFirstParam = false;
+ } else {
+ pd.append(", ");
+ } // end-if
+
+ dumpParamNode(key, obj, pd);
+
+ } // end-while
+ } // end-method
+
+ @SuppressWarnings("unchecked")
+ private void dumpParamNode(String key, Object obj, StringBuilder pd) {
+
+ if (obj instanceof Hashtable) {
+ pd.append("[");
+ dumpParams((Hashtable<String, Object>)obj, pd);
+ pd.append("]");
+ } else if (obj instanceof RPCStruct) {
+ pd.append("[");
+ OpenRPCMessage orpcm = new OpenRPCMessage((RPCStruct)obj);
+ orpcm.msgDump(pd);
+ pd.append("]");
+ } else if (obj instanceof List) {
+ pd.append("[");
+ List<?> list = (List<?>)obj;
+ for (int idx=0;idx < list.size();idx++) {
+ if (idx > 0) {
+ pd.append(", ");
+ }
+ dumpParamNode(key, list.get(idx), pd);
+ } // end-for
+ pd.append("]");
+ } else {
+ pd.append("\"" + key + "\" = \"" + obj.toString() + "\"");
+ }
+ } // end-method
+} // end-class OpenRPCMessage
diff --git a/base/src/main/java/com/smartdevicelink/trace/enums/DetailLevel.java b/base/src/main/java/com/smartdevicelink/trace/enums/DetailLevel.java index 841711ff4..bd213679d 100644 --- a/base/src/main/java/com/smartdevicelink/trace/enums/DetailLevel.java +++ b/base/src/main/java/com/smartdevicelink/trace/enums/DetailLevel.java @@ -1,16 +1,16 @@ -package com.smartdevicelink.trace.enums; - - -public enum DetailLevel { - OFF, - TERSE, - VERBOSE; - - public static DetailLevel valueForString(String value) { - try{ - return valueOf(value); - }catch(Exception e){ - return null; - } - } -} +package com.smartdevicelink.trace.enums;
+
+
+public enum DetailLevel {
+ OFF,
+ TERSE,
+ VERBOSE;
+
+ public static DetailLevel valueForString(String value) {
+ try{
+ return valueOf(value);
+ }catch(Exception e){
+ return null;
+ }
+ }
+}
diff --git a/base/src/main/java/com/smartdevicelink/trace/enums/InterfaceActivityDirection.java b/base/src/main/java/com/smartdevicelink/trace/enums/InterfaceActivityDirection.java index cef1532e5..0865d2e32 100644 --- a/base/src/main/java/com/smartdevicelink/trace/enums/InterfaceActivityDirection.java +++ b/base/src/main/java/com/smartdevicelink/trace/enums/InterfaceActivityDirection.java @@ -1,15 +1,15 @@ -package com.smartdevicelink.trace.enums; - -public enum InterfaceActivityDirection { - Transmit, - Receive, - None; - - public static InterfaceActivityDirection valueForString(String value) { - try{ - return valueOf(value); - }catch(Exception e){ - return null; - } - } +package com.smartdevicelink.trace.enums;
+
+public enum InterfaceActivityDirection {
+ Transmit,
+ Receive,
+ None;
+
+ public static InterfaceActivityDirection valueForString(String value) {
+ try{
+ return valueOf(value);
+ }catch(Exception e){
+ return null;
+ }
+ }
}
\ No newline at end of file diff --git a/base/src/main/java/com/smartdevicelink/trace/enums/Mod.java b/base/src/main/java/com/smartdevicelink/trace/enums/Mod.java index 330c3b616..b363473b2 100644 --- a/base/src/main/java/com/smartdevicelink/trace/enums/Mod.java +++ b/base/src/main/java/com/smartdevicelink/trace/enums/Mod.java @@ -1,18 +1,18 @@ -package com.smartdevicelink.trace.enums; - -public enum Mod { - tran, - proto, - mar, - rpc, - app, - proxy; - - public static Mod valueForString(String value) { - try{ - return valueOf(value); - }catch(Exception e){ - return null; - } - } +package com.smartdevicelink.trace.enums;
+
+public enum Mod {
+ tran,
+ proto,
+ mar,
+ rpc,
+ app,
+ proxy;
+
+ public static Mod valueForString(String value) {
+ try{
+ return valueOf(value);
+ }catch(Exception e){
+ return null;
+ }
+ }
};
\ No newline at end of file diff --git a/base/src/main/java/com/smartdevicelink/transport/BaseTransportConfig.java b/base/src/main/java/com/smartdevicelink/transport/BaseTransportConfig.java index 939a18bcf..4b7fe79be 100644 --- a/base/src/main/java/com/smartdevicelink/transport/BaseTransportConfig.java +++ b/base/src/main/java/com/smartdevicelink/transport/BaseTransportConfig.java @@ -1,35 +1,35 @@ -package com.smartdevicelink.transport; - -import com.smartdevicelink.transport.enums.TransportType; - -/** - * Defines base abstract class for transport configurations. - */ -public abstract class BaseTransportConfig { - - protected boolean shareConnection = true; - protected int iHeartBeatTimeout = Integer.MAX_VALUE; - /** - * Gets transport type for this transport configuration. - * - * @return One of {@link TransportType} enumeration values that represents type of this transport configuration. - */ - public abstract TransportType getTransportType(); - - /** - * Indicate whether the application want to share connection with others. - * - * @return - */ - public boolean shareConnection() { - return shareConnection; - } - - public int getHeartBeatTimeout() { - return iHeartBeatTimeout; - } - - public void setHeartBeatTimeout(int iTimeout) { - iHeartBeatTimeout = iTimeout; - } -} +package com.smartdevicelink.transport;
+
+import com.smartdevicelink.transport.enums.TransportType;
+
+/**
+ * Defines base abstract class for transport configurations.
+ */
+public abstract class BaseTransportConfig {
+
+ protected boolean shareConnection = true;
+ protected int iHeartBeatTimeout = Integer.MAX_VALUE;
+ /**
+ * Gets transport type for this transport configuration.
+ *
+ * @return One of {@link TransportType} enumeration values that represents type of this transport configuration.
+ */
+ public abstract TransportType getTransportType();
+
+ /**
+ * Indicate whether the application want to share connection with others.
+ *
+ * @return
+ */
+ public boolean shareConnection() {
+ return shareConnection;
+ }
+
+ public int getHeartBeatTimeout() {
+ return iHeartBeatTimeout;
+ }
+
+ public void setHeartBeatTimeout(int iTimeout) {
+ iHeartBeatTimeout = iTimeout;
+ }
+}
diff --git a/base/src/main/java/com/smartdevicelink/transport/ITransportListener.java b/base/src/main/java/com/smartdevicelink/transport/ITransportListener.java index b9ea2cf30..b4c4a9b33 100644 --- a/base/src/main/java/com/smartdevicelink/transport/ITransportListener.java +++ b/base/src/main/java/com/smartdevicelink/transport/ITransportListener.java @@ -1,17 +1,17 @@ -package com.smartdevicelink.transport; - -import com.smartdevicelink.protocol.SdlPacket; - -public interface ITransportListener { - // Called to indicate and deliver a packet received from transport - void onTransportPacketReceived(SdlPacket packet); - - // Called to indicate that transport connection was established - void onTransportConnected(); - - // Called to indicate that transport was disconnected (by either side) - void onTransportDisconnected(String info); - - // Called to indicate that some error occurred on the transport - void onTransportError(String info, Exception e); +package com.smartdevicelink.transport;
+
+import com.smartdevicelink.protocol.SdlPacket;
+
+public interface ITransportListener {
+ // Called to indicate and deliver a packet received from transport
+ void onTransportPacketReceived(SdlPacket packet);
+
+ // Called to indicate that transport connection was established
+ void onTransportConnected();
+
+ // Called to indicate that transport was disconnected (by either side)
+ void onTransportDisconnected(String info);
+
+ // Called to indicate that some error occurred on the transport
+ void onTransportError(String info, Exception e);
} // end-interface
\ No newline at end of file diff --git a/base/src/main/java/com/smartdevicelink/transport/SdlTransport.java b/base/src/main/java/com/smartdevicelink/transport/SdlTransport.java index 21429841f..27c87bcef 100644 --- a/base/src/main/java/com/smartdevicelink/transport/SdlTransport.java +++ b/base/src/main/java/com/smartdevicelink/transport/SdlTransport.java @@ -1,122 +1,122 @@ -package com.smartdevicelink.transport; - -import com.smartdevicelink.exception.SdlException; -import com.smartdevicelink.protocol.SdlPacket; -import com.smartdevicelink.trace.SdlTrace; -import com.smartdevicelink.trace.enums.InterfaceActivityDirection; -import com.smartdevicelink.transport.enums.TransportType; -import com.smartdevicelink.util.DebugTool; - -public abstract class SdlTransport { - private static final String SDL_LIB_TRACE_KEY = "42baba60-eb57-11df-98cf-0800200c9a66"; - - private final static String FailurePropagating_Msg = "Failure propagating "; - private Boolean isConnected = false; - - private String _sendLockObj = "lock"; - - - // Get status of transport connection - public Boolean getIsConnected() { - return isConnected; - } - - //protected SdlTransport(String endpointName, String param2, ITransportListener transportListener) - protected SdlTransport(ITransportListener transportListener) { - if (transportListener == null) { - throw new IllegalArgumentException("Provided transport listener interface reference is null"); - } // end-if - _transportListener = transportListener; - } // end-method - - // This method is called by the subclass to indicate that data has arrived from - // the transport. - protected void handleReceivedPacket(SdlPacket packet) { - try { - // Trace received data - if (packet!=null) { - // Send transport data to the siphon server - //FIXME SiphonServer.sendBytesFromSDL(receivedBytes, 0, receivedBytesLength); - //SdlTrace.logTransportEvent("", null, InterfaceActivityDirection.Receive, receivedBytes, receivedBytesLength, SDL_LIB_TRACE_KEY); - - _transportListener.onTransportPacketReceived(packet); - } // end-if - } catch (Exception excp) { - DebugTool.logError(FailurePropagating_Msg + "handleBytesFromTransport: " + excp.toString(), excp); - handleTransportError(FailurePropagating_Msg, excp); - } // end-catch - } // end-method - - // This method must be implemented by transport subclass, and is called by this - // base class to actually send an array of bytes out over the transport. This - // method is meant to only be callable within the class hierarchy. - protected abstract boolean sendBytesOverTransport(SdlPacket packet); - - // This method is called by whomever has reference to transport to have bytes - // sent out over transport. - /* public boolean sendBytes(byte[] message) { - return sendBytes(message, 0, message.length); - }*/ // end-method - - // This method is called by whomever has reference to transport to have bytes - // sent out over transport. - public boolean sendBytes(SdlPacket packet) { - boolean bytesWereSent = false; - synchronized (_sendLockObj) { - bytesWereSent = sendBytesOverTransport(packet);//message, offset, length); - } // end-lock - // Send transport data to the siphon server - //FIXME SiphonServer.sendBytesFromAPP(message, offset, length); - - //FIXME SdlTrace.logTransportEvent("", null, InterfaceActivityDirection.Transmit, message, offset, length, SDL_LIB_TRACE_KEY); - return bytesWereSent; - } // end-method - - private ITransportListener _transportListener = null; - - // This method is called by the subclass to indicate that transport connection - // has been established. - protected void handleTransportConnected() { - isConnected = true; - try { - SdlTrace.logTransportEvent("Transport.connected", null, InterfaceActivityDirection.Receive, null, 0, SDL_LIB_TRACE_KEY); - _transportListener.onTransportConnected(); - } catch (Exception excp) { - DebugTool.logError(FailurePropagating_Msg + "onTransportConnected: " + excp.toString(), excp); - handleTransportError(FailurePropagating_Msg + "onTransportConnected", excp); - } // end-catch - } // end-method - - // This method is called by the subclass to indicate that transport disconnection - // has occurred. - protected void handleTransportDisconnected(final String info) { - isConnected = false; - - try { - SdlTrace.logTransportEvent("Transport.disconnect: " + info, null, InterfaceActivityDirection.Transmit, null, 0, SDL_LIB_TRACE_KEY); - _transportListener.onTransportDisconnected(info); - } catch (Exception excp) { - DebugTool.logError(FailurePropagating_Msg + "onTransportDisconnected: " + excp.toString(), excp); - } // end-catch - } // end-method - - // This method is called by the subclass to indicate a transport error has occurred. - protected void handleTransportError(final String message, final Exception ex) { - isConnected = false; - _transportListener.onTransportError(message, ex); - } - - public abstract void openConnection() throws SdlException; - public abstract void disconnect(); - - /** - * Abstract method which should be implemented by subclasses in order to return actual type of the transport. - * - * @return One of {@link TransportType} enumeration values. - * - * @see TransportType - */ - public abstract TransportType getTransportType(); - - public abstract String getBroadcastComment(); -} // end-class +package com.smartdevicelink.transport;
+
+import com.smartdevicelink.exception.SdlException;
+import com.smartdevicelink.protocol.SdlPacket;
+import com.smartdevicelink.trace.SdlTrace;
+import com.smartdevicelink.trace.enums.InterfaceActivityDirection;
+import com.smartdevicelink.transport.enums.TransportType;
+import com.smartdevicelink.util.DebugTool;
+
+public abstract class SdlTransport {
+ private static final String SDL_LIB_TRACE_KEY = "42baba60-eb57-11df-98cf-0800200c9a66";
+
+ private final static String FailurePropagating_Msg = "Failure propagating ";
+ private Boolean isConnected = false;
+
+ private String _sendLockObj = "lock";
+
+
+ // Get status of transport connection
+ public Boolean getIsConnected() {
+ return isConnected;
+ }
+
+ //protected SdlTransport(String endpointName, String param2, ITransportListener transportListener)
+ protected SdlTransport(ITransportListener transportListener) {
+ if (transportListener == null) {
+ throw new IllegalArgumentException("Provided transport listener interface reference is null");
+ } // end-if
+ _transportListener = transportListener;
+ } // end-method
+
+ // This method is called by the subclass to indicate that data has arrived from
+ // the transport.
+ protected void handleReceivedPacket(SdlPacket packet) {
+ try {
+ // Trace received data
+ if (packet!=null) {
+ // Send transport data to the siphon server
+ //FIXME SiphonServer.sendBytesFromSDL(receivedBytes, 0, receivedBytesLength);
+ //SdlTrace.logTransportEvent("", null, InterfaceActivityDirection.Receive, receivedBytes, receivedBytesLength, SDL_LIB_TRACE_KEY);
+
+ _transportListener.onTransportPacketReceived(packet);
+ } // end-if
+ } catch (Exception excp) {
+ DebugTool.logError(FailurePropagating_Msg + "handleBytesFromTransport: " + excp.toString(), excp);
+ handleTransportError(FailurePropagating_Msg, excp);
+ } // end-catch
+ } // end-method
+
+ // This method must be implemented by transport subclass, and is called by this
+ // base class to actually send an array of bytes out over the transport. This
+ // method is meant to only be callable within the class hierarchy.
+ protected abstract boolean sendBytesOverTransport(SdlPacket packet);
+
+ // This method is called by whomever has reference to transport to have bytes
+ // sent out over transport.
+ /* public boolean sendBytes(byte[] message) {
+ return sendBytes(message, 0, message.length);
+ }*/ // end-method
+
+ // This method is called by whomever has reference to transport to have bytes
+ // sent out over transport.
+ public boolean sendBytes(SdlPacket packet) {
+ boolean bytesWereSent = false;
+ synchronized (_sendLockObj) {
+ bytesWereSent = sendBytesOverTransport(packet);//message, offset, length);
+ } // end-lock
+ // Send transport data to the siphon server
+ //FIXME SiphonServer.sendBytesFromAPP(message, offset, length);
+
+ //FIXME SdlTrace.logTransportEvent("", null, InterfaceActivityDirection.Transmit, message, offset, length, SDL_LIB_TRACE_KEY);
+ return bytesWereSent;
+ } // end-method
+
+ private ITransportListener _transportListener = null;
+
+ // This method is called by the subclass to indicate that transport connection
+ // has been established.
+ protected void handleTransportConnected() {
+ isConnected = true;
+ try {
+ SdlTrace.logTransportEvent("Transport.connected", null, InterfaceActivityDirection.Receive, null, 0, SDL_LIB_TRACE_KEY);
+ _transportListener.onTransportConnected();
+ } catch (Exception excp) {
+ DebugTool.logError(FailurePropagating_Msg + "onTransportConnected: " + excp.toString(), excp);
+ handleTransportError(FailurePropagating_Msg + "onTransportConnected", excp);
+ } // end-catch
+ } // end-method
+
+ // This method is called by the subclass to indicate that transport disconnection
+ // has occurred.
+ protected void handleTransportDisconnected(final String info) {
+ isConnected = false;
+
+ try {
+ SdlTrace.logTransportEvent("Transport.disconnect: " + info, null, InterfaceActivityDirection.Transmit, null, 0, SDL_LIB_TRACE_KEY);
+ _transportListener.onTransportDisconnected(info);
+ } catch (Exception excp) {
+ DebugTool.logError(FailurePropagating_Msg + "onTransportDisconnected: " + excp.toString(), excp);
+ } // end-catch
+ } // end-method
+
+ // This method is called by the subclass to indicate a transport error has occurred.
+ protected void handleTransportError(final String message, final Exception ex) {
+ isConnected = false;
+ _transportListener.onTransportError(message, ex);
+ }
+
+ public abstract void openConnection() throws SdlException;
+ public abstract void disconnect();
+
+ /**
+ * Abstract method which should be implemented by subclasses in order to return actual type of the transport.
+ *
+ * @return One of {@link TransportType} enumeration values.
+ *
+ * @see TransportType
+ */
+ public abstract TransportType getTransportType();
+
+ public abstract String getBroadcastComment();
+} // end-class
diff --git a/base/src/main/java/com/smartdevicelink/transport/SiphonServer.java b/base/src/main/java/com/smartdevicelink/transport/SiphonServer.java index 68107f407..ab8a8a7bd 100644 --- a/base/src/main/java/com/smartdevicelink/transport/SiphonServer.java +++ b/base/src/main/java/com/smartdevicelink/transport/SiphonServer.java @@ -1,384 +1,384 @@ -package com.smartdevicelink.transport; - -import java.io.IOException; -import java.io.OutputStream; -import java.io.UnsupportedEncodingException; -import java.net.BindException; -import java.net.ServerSocket; -import java.net.Socket; - -import com.smartdevicelink.util.*; - -public class SiphonServer { - // Prohibit use of no-arg ctor - private SiphonServer() {} - - enum SiphonDataType { - fromSdl, - fromApp, - appLog, - formattedTrace, - baselineTimeStamp, - traceSettings - } - - // Boolean to enable/disable the siphon - private static Boolean m_siphonEnabled = false; - - // Boolean to determine if the siphon has been initialized - private static Boolean m_siphonInitialized = false; - private static Boolean m_foundOpenSocket = false; - private static Socket m_siphonSocket = null; - private static Object m_siphonLock = new Object(); - private static ServerSocket m_listeningSocket = null; - private static short m_listenPort = -1; - private static OutputStream m_siphonSocketOutputStream = null; - private static SiphonServerThread m_siphonClientThread = null; - - // Initial timestamp in MS - private static long m_startTimeStamp = 0; - - // SDL Trace Message Version - private static byte m_sdlTraceMsgVersionNumber = 1; - - // Max number of ports to attempt a connection on - private final static Integer MAX_NUMBER_OF_PORT_ATTEMPTS = 20; - - // Starting port for future port attempts - private final static short FIRST_PORT_TO_ATTEMPT_CONNECTION = 7474; - - // Boolean to determine if formatted trace is being sent - private static Boolean m_sendingFormattedTrace = false; - - public static short enableSiphonServer() { - m_siphonEnabled = true; - SiphonServer.init(); - return m_listenPort; - } - - public static Boolean getSiphonEnabledStatus() { - return m_siphonEnabled; - } - - public static short disableSiphonServer() { - if (!m_siphonEnabled) { - m_listenPort = -1; - } else { - m_siphonEnabled = false; - } - - m_siphonInitialized = false; - - try { - SiphonServer.closeServer(); - } catch (IOException e) { - e.printStackTrace(); - } - - return m_listenPort; - } - - public static boolean init() { - // Only initialize if the siphon has not been initialized previously - - // Check here to be lean. If true, no need to sdlhronize - if (m_siphonInitialized) { - return true; - } - - synchronized (m_siphonLock) { - // To prevent a race condition, re-check m_siphonInitialized inside of sdlhronize block - if (!m_siphonInitialized) { - if (m_siphonClientThread == null) { - // Set current time stamp - m_startTimeStamp = System.currentTimeMillis(); - - // Start Siphon Thread - m_siphonClientThread = new SiphonServerThread(); - m_siphonClientThread.setName("Siphon"); - m_siphonClientThread.setDaemon(true); - m_foundOpenSocket = m_siphonClientThread.findOpenSocket(FIRST_PORT_TO_ATTEMPT_CONNECTION); - m_siphonClientThread.start(); - - m_siphonInitialized = true; - } // end-if - } // end-lock - } - - return m_siphonInitialized; - } // end-method - - public static void closeServer() throws IOException { - - if (m_siphonClientThread != null) { - m_siphonClientThread.halt(); - m_siphonClientThread = null; - } - - if (m_listeningSocket != null) { - m_listeningSocket.close(); - m_listeningSocket = null; - } - - if (m_siphonSocket != null) { - m_siphonSocket.close(); - m_siphonSocket = null; - } - - if (m_siphonSocketOutputStream != null) { - m_siphonSocketOutputStream.close(); - m_siphonSocketOutputStream = null; - } - } - - public static Boolean sendBytesFromAPP(byte[] msgBytes, int offset, int length) { - - if (m_sendingFormattedTrace) { - return false; - } - - return sendSiphonData(SiphonDataType.fromApp, msgBytes, offset, length); - } // end-method - - public static Boolean sendBytesFromSDL(byte[] msgBytes, int offset, int length) { - - if (m_sendingFormattedTrace) { - return false; - } - - return sendSiphonData(SiphonDataType.fromSdl, msgBytes, offset, length); - } // end-method - - public static Boolean sendSiphonLogData(String message) { - - if (m_sendingFormattedTrace) { - return false; - } - - if (message == null || message.length() == 0) { - return false; - } - - byte messageBytes[] = null; - int messageLength = 0; - - try { - messageBytes = message.getBytes("UTF-8"); - } catch (UnsupportedEncodingException e) { - return false; - } - - messageLength = messageBytes.length; - return sendSiphonData(SiphonDataType.appLog, messageBytes, 0, messageLength); - - } - - public static Boolean sendFormattedTraceMessage(String message) { - - if (message == null || message.length() == 0) { - return false; - } - - byte messageBytes[] = null; - int messageLength = 0; - - try { - messageBytes = message.getBytes("UTF-8"); - } catch (UnsupportedEncodingException e) { - return false; - } - - messageLength = messageBytes.length; - if (sendSiphonData(SiphonDataType.formattedTrace, messageBytes, 0, messageLength)) { - m_sendingFormattedTrace = true; - return true; - } else { - return false; - } - } - - private static Boolean sendSiphonData(SiphonDataType direction, byte[] msgBytes, int offset, int length) { - byte siphonDataTypeIndicator = 0x00; - - long currentDateTime = System.currentTimeMillis(); - Integer deltaTimeMills = null; - - deltaTimeMills = (int)(currentDateTime - m_startTimeStamp); - - switch(direction) { - case fromSdl: - siphonDataTypeIndicator = 0x00; - break; - case fromApp: - siphonDataTypeIndicator = 0x01; - break; - case appLog: - siphonDataTypeIndicator = 0x02; - break; - case formattedTrace: - siphonDataTypeIndicator = 0x03; - break; - case baselineTimeStamp: - siphonDataTypeIndicator = 0x04; - break; - case traceSettings: - siphonDataTypeIndicator = 0x05; - break; - default: - siphonDataTypeIndicator = 0x00; - break; - } - - // Set high bit to indicate new format - siphonDataTypeIndicator = (byte)((byte)0x80 | siphonDataTypeIndicator); - - return sendDataToSiphonSocket(siphonDataTypeIndicator, deltaTimeMills, msgBytes, offset, length); - } - - private synchronized static Boolean sendDataToSiphonSocket(byte directionIndicator, Integer timeStamp, - byte[] msgBytes, int offset, int length) { - if (!m_siphonEnabled) { - return false; - } - - if (msgBytes == null || length == 0) { - return false; - } - - OutputStream siphonOutputStream = null; - - synchronized (m_siphonLock) { - siphonOutputStream = m_siphonSocketOutputStream; - } // end-lock - - if (siphonOutputStream == null) { - return false; - } - - try { - // blobSize = length(of message) + 1(size of direction indicator) - // + 1 (size of msgVersionNumber) + 4 (size of timeStamp) - int blobSize = length + 1 + 1 + 4; - - siphonOutputStream.write(BitConverter.intToByteArray(blobSize)); - siphonOutputStream.write(new byte[] {directionIndicator}); - siphonOutputStream.write(new byte[] {m_sdlTraceMsgVersionNumber}); - siphonOutputStream.write(intToByteArray(timeStamp)); - siphonOutputStream.write(msgBytes, offset, length); - } catch (Exception ex) { - return false; - } // end-catch - - return true; - } // end-method - - private static class SiphonServerThread extends Thread { - - private Boolean isHalted = false; - short listenPort; - - public void halt() { - isHalted = true; - } - - private boolean findOpenSocket(short port) { - // Accept incoming sihpon connection from trace utility. - Boolean foundOpenPort = false; - listenPort = port; - - // Listen to accept incoming connection from SDL - while (!foundOpenPort) { - try { - m_listeningSocket = new ServerSocket(listenPort); - foundOpenPort = true; - m_listenPort = listenPort; - } catch (BindException ex) { - listenPort++; - if(listenPort > port + MAX_NUMBER_OF_PORT_ATTEMPTS) { - return false; - } - } catch (IOException e) { - return false; - } - } - - return foundOpenPort; - } - - private void startServerOnPort() throws IOException { - Socket newSocket = null; - - // Wait for a connection - newSocket = m_listeningSocket.accept(); - - // If isHalted after accept() delay, return - if (isHalted) { - return; - } - - synchronized (m_siphonLock) { - // Reset siphonSocketOutputStream - if (m_siphonSocketOutputStream != null) { - try { - m_siphonSocketOutputStream.close(); - } catch (IOException e) { - // Do nothing - } - m_siphonSocketOutputStream = null; - } - - // Reset siphonSocket - if (m_siphonSocket != null) { - try { - m_siphonSocket.close(); - } catch (IOException e) { - // Do nothing - } - m_siphonSocket = null; - } - - // Store the new socket - m_siphonSocket = newSocket; - - // Set Socket Options - m_siphonSocket.setKeepAlive(true); - - // Get the output stream of the connection - m_siphonSocketOutputStream = m_siphonSocket.getOutputStream(); - - // Output version number to the Siphon upon connection (version number prepending to logInfo) - DebugTool.logInfo("Siphon connected."); - } // end-lock - } // end-method - - @Override - public void run() { - try { - if (m_foundOpenSocket){ - while (!isHalted) { - startServerOnPort(); - } - } - } catch (Exception ex) { - // Do nothing - } finally { - if (m_listeningSocket != null) { - try { - m_listeningSocket.close(); - } catch (IOException e) { - // Do nothing - } - m_listeningSocket = null; - } - } - } - } - - private static final byte[] intToByteArray(int value) { - return new byte[] { - (byte)(value >>> 24), - (byte)(value >>> 16), - (byte)(value >>> 8), - (byte)value}; - } +package com.smartdevicelink.transport;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.UnsupportedEncodingException;
+import java.net.BindException;
+import java.net.ServerSocket;
+import java.net.Socket;
+
+import com.smartdevicelink.util.*;
+
+public class SiphonServer {
+ // Prohibit use of no-arg ctor
+ private SiphonServer() {}
+
+ enum SiphonDataType {
+ fromSdl,
+ fromApp,
+ appLog,
+ formattedTrace,
+ baselineTimeStamp,
+ traceSettings
+ }
+
+ // Boolean to enable/disable the siphon
+ private static Boolean m_siphonEnabled = false;
+
+ // Boolean to determine if the siphon has been initialized
+ private static Boolean m_siphonInitialized = false;
+ private static Boolean m_foundOpenSocket = false;
+ private static Socket m_siphonSocket = null;
+ private static Object m_siphonLock = new Object();
+ private static ServerSocket m_listeningSocket = null;
+ private static short m_listenPort = -1;
+ private static OutputStream m_siphonSocketOutputStream = null;
+ private static SiphonServerThread m_siphonClientThread = null;
+
+ // Initial timestamp in MS
+ private static long m_startTimeStamp = 0;
+
+ // SDL Trace Message Version
+ private static byte m_sdlTraceMsgVersionNumber = 1;
+
+ // Max number of ports to attempt a connection on
+ private final static Integer MAX_NUMBER_OF_PORT_ATTEMPTS = 20;
+
+ // Starting port for future port attempts
+ private final static short FIRST_PORT_TO_ATTEMPT_CONNECTION = 7474;
+
+ // Boolean to determine if formatted trace is being sent
+ private static Boolean m_sendingFormattedTrace = false;
+
+ public static short enableSiphonServer() {
+ m_siphonEnabled = true;
+ SiphonServer.init();
+ return m_listenPort;
+ }
+
+ public static Boolean getSiphonEnabledStatus() {
+ return m_siphonEnabled;
+ }
+
+ public static short disableSiphonServer() {
+ if (!m_siphonEnabled) {
+ m_listenPort = -1;
+ } else {
+ m_siphonEnabled = false;
+ }
+
+ m_siphonInitialized = false;
+
+ try {
+ SiphonServer.closeServer();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+
+ return m_listenPort;
+ }
+
+ public static boolean init() {
+ // Only initialize if the siphon has not been initialized previously
+
+ // Check here to be lean. If true, no need to sdlhronize
+ if (m_siphonInitialized) {
+ return true;
+ }
+
+ synchronized (m_siphonLock) {
+ // To prevent a race condition, re-check m_siphonInitialized inside of sdlhronize block
+ if (!m_siphonInitialized) {
+ if (m_siphonClientThread == null) {
+ // Set current time stamp
+ m_startTimeStamp = System.currentTimeMillis();
+
+ // Start Siphon Thread
+ m_siphonClientThread = new SiphonServerThread();
+ m_siphonClientThread.setName("Siphon");
+ m_siphonClientThread.setDaemon(true);
+ m_foundOpenSocket = m_siphonClientThread.findOpenSocket(FIRST_PORT_TO_ATTEMPT_CONNECTION);
+ m_siphonClientThread.start();
+
+ m_siphonInitialized = true;
+ } // end-if
+ } // end-lock
+ }
+
+ return m_siphonInitialized;
+ } // end-method
+
+ public static void closeServer() throws IOException {
+
+ if (m_siphonClientThread != null) {
+ m_siphonClientThread.halt();
+ m_siphonClientThread = null;
+ }
+
+ if (m_listeningSocket != null) {
+ m_listeningSocket.close();
+ m_listeningSocket = null;
+ }
+
+ if (m_siphonSocket != null) {
+ m_siphonSocket.close();
+ m_siphonSocket = null;
+ }
+
+ if (m_siphonSocketOutputStream != null) {
+ m_siphonSocketOutputStream.close();
+ m_siphonSocketOutputStream = null;
+ }
+ }
+
+ public static Boolean sendBytesFromAPP(byte[] msgBytes, int offset, int length) {
+
+ if (m_sendingFormattedTrace) {
+ return false;
+ }
+
+ return sendSiphonData(SiphonDataType.fromApp, msgBytes, offset, length);
+ } // end-method
+
+ public static Boolean sendBytesFromSDL(byte[] msgBytes, int offset, int length) {
+
+ if (m_sendingFormattedTrace) {
+ return false;
+ }
+
+ return sendSiphonData(SiphonDataType.fromSdl, msgBytes, offset, length);
+ } // end-method
+
+ public static Boolean sendSiphonLogData(String message) {
+
+ if (m_sendingFormattedTrace) {
+ return false;
+ }
+
+ if (message == null || message.length() == 0) {
+ return false;
+ }
+
+ byte messageBytes[] = null;
+ int messageLength = 0;
+
+ try {
+ messageBytes = message.getBytes("UTF-8");
+ } catch (UnsupportedEncodingException e) {
+ return false;
+ }
+
+ messageLength = messageBytes.length;
+ return sendSiphonData(SiphonDataType.appLog, messageBytes, 0, messageLength);
+
+ }
+
+ public static Boolean sendFormattedTraceMessage(String message) {
+
+ if (message == null || message.length() == 0) {
+ return false;
+ }
+
+ byte messageBytes[] = null;
+ int messageLength = 0;
+
+ try {
+ messageBytes = message.getBytes("UTF-8");
+ } catch (UnsupportedEncodingException e) {
+ return false;
+ }
+
+ messageLength = messageBytes.length;
+ if (sendSiphonData(SiphonDataType.formattedTrace, messageBytes, 0, messageLength)) {
+ m_sendingFormattedTrace = true;
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ private static Boolean sendSiphonData(SiphonDataType direction, byte[] msgBytes, int offset, int length) {
+ byte siphonDataTypeIndicator = 0x00;
+
+ long currentDateTime = System.currentTimeMillis();
+ Integer deltaTimeMills = null;
+
+ deltaTimeMills = (int)(currentDateTime - m_startTimeStamp);
+
+ switch(direction) {
+ case fromSdl:
+ siphonDataTypeIndicator = 0x00;
+ break;
+ case fromApp:
+ siphonDataTypeIndicator = 0x01;
+ break;
+ case appLog:
+ siphonDataTypeIndicator = 0x02;
+ break;
+ case formattedTrace:
+ siphonDataTypeIndicator = 0x03;
+ break;
+ case baselineTimeStamp:
+ siphonDataTypeIndicator = 0x04;
+ break;
+ case traceSettings:
+ siphonDataTypeIndicator = 0x05;
+ break;
+ default:
+ siphonDataTypeIndicator = 0x00;
+ break;
+ }
+
+ // Set high bit to indicate new format
+ siphonDataTypeIndicator = (byte)((byte)0x80 | siphonDataTypeIndicator);
+
+ return sendDataToSiphonSocket(siphonDataTypeIndicator, deltaTimeMills, msgBytes, offset, length);
+ }
+
+ private synchronized static Boolean sendDataToSiphonSocket(byte directionIndicator, Integer timeStamp,
+ byte[] msgBytes, int offset, int length) {
+ if (!m_siphonEnabled) {
+ return false;
+ }
+
+ if (msgBytes == null || length == 0) {
+ return false;
+ }
+
+ OutputStream siphonOutputStream = null;
+
+ synchronized (m_siphonLock) {
+ siphonOutputStream = m_siphonSocketOutputStream;
+ } // end-lock
+
+ if (siphonOutputStream == null) {
+ return false;
+ }
+
+ try {
+ // blobSize = length(of message) + 1(size of direction indicator)
+ // + 1 (size of msgVersionNumber) + 4 (size of timeStamp)
+ int blobSize = length + 1 + 1 + 4;
+
+ siphonOutputStream.write(BitConverter.intToByteArray(blobSize));
+ siphonOutputStream.write(new byte[] {directionIndicator});
+ siphonOutputStream.write(new byte[] {m_sdlTraceMsgVersionNumber});
+ siphonOutputStream.write(intToByteArray(timeStamp));
+ siphonOutputStream.write(msgBytes, offset, length);
+ } catch (Exception ex) {
+ return false;
+ } // end-catch
+
+ return true;
+ } // end-method
+
+ private static class SiphonServerThread extends Thread {
+
+ private Boolean isHalted = false;
+ short listenPort;
+
+ public void halt() {
+ isHalted = true;
+ }
+
+ private boolean findOpenSocket(short port) {
+ // Accept incoming sihpon connection from trace utility.
+ Boolean foundOpenPort = false;
+ listenPort = port;
+
+ // Listen to accept incoming connection from SDL
+ while (!foundOpenPort) {
+ try {
+ m_listeningSocket = new ServerSocket(listenPort);
+ foundOpenPort = true;
+ m_listenPort = listenPort;
+ } catch (BindException ex) {
+ listenPort++;
+ if(listenPort > port + MAX_NUMBER_OF_PORT_ATTEMPTS) {
+ return false;
+ }
+ } catch (IOException e) {
+ return false;
+ }
+ }
+
+ return foundOpenPort;
+ }
+
+ private void startServerOnPort() throws IOException {
+ Socket newSocket = null;
+
+ // Wait for a connection
+ newSocket = m_listeningSocket.accept();
+
+ // If isHalted after accept() delay, return
+ if (isHalted) {
+ return;
+ }
+
+ synchronized (m_siphonLock) {
+ // Reset siphonSocketOutputStream
+ if (m_siphonSocketOutputStream != null) {
+ try {
+ m_siphonSocketOutputStream.close();
+ } catch (IOException e) {
+ // Do nothing
+ }
+ m_siphonSocketOutputStream = null;
+ }
+
+ // Reset siphonSocket
+ if (m_siphonSocket != null) {
+ try {
+ m_siphonSocket.close();
+ } catch (IOException e) {
+ // Do nothing
+ }
+ m_siphonSocket = null;
+ }
+
+ // Store the new socket
+ m_siphonSocket = newSocket;
+
+ // Set Socket Options
+ m_siphonSocket.setKeepAlive(true);
+
+ // Get the output stream of the connection
+ m_siphonSocketOutputStream = m_siphonSocket.getOutputStream();
+
+ // Output version number to the Siphon upon connection (version number prepending to logInfo)
+ DebugTool.logInfo("Siphon connected.");
+ } // end-lock
+ } // end-method
+
+ @Override
+ public void run() {
+ try {
+ if (m_foundOpenSocket){
+ while (!isHalted) {
+ startServerOnPort();
+ }
+ }
+ } catch (Exception ex) {
+ // Do nothing
+ } finally {
+ if (m_listeningSocket != null) {
+ try {
+ m_listeningSocket.close();
+ } catch (IOException e) {
+ // Do nothing
+ }
+ m_listeningSocket = null;
+ }
+ }
+ }
+ }
+
+ private static final byte[] intToByteArray(int value) {
+ return new byte[] {
+ (byte)(value >>> 24),
+ (byte)(value >>> 16),
+ (byte)(value >>> 8),
+ (byte)value};
+ }
} // end-class
\ No newline at end of file diff --git a/base/src/main/java/com/smartdevicelink/transport/TransportManager.java b/base/src/main/java/com/smartdevicelink/transport/TransportManager.java index b816655cd..2029d91a3 100644 --- a/base/src/main/java/com/smartdevicelink/transport/TransportManager.java +++ b/base/src/main/java/com/smartdevicelink/transport/TransportManager.java @@ -44,16 +44,10 @@ import java.util.Collections; import java.util.List; @SuppressWarnings("unused") -public class TransportManager { +public class TransportManager extends TransportManagerBase{ private static final String TAG = "TransportManager"; - private final Object TRANSPORT_STATUS_LOCK; - WebSocketServer2 transport; - final List<TransportRecord> transportStatus; - final TransportEventListener transportListener; - - /** * Managing transports @@ -62,12 +56,8 @@ public class TransportManager { */ public TransportManager(WebSocketServerConfig config, TransportEventListener listener){ + super(config, listener); - this.transportListener = listener; - this.TRANSPORT_STATUS_LOCK = new Object(); - synchronized (TRANSPORT_STATUS_LOCK){ - this.transportStatus = new ArrayList<>(); - } final TransportRecord record = new TransportRecord(TransportType.WEB_SOCKET_SERVER,"127.0.0.1:"+config.port); final List<TransportRecord> finalList = Collections.singletonList(record); //Start the new transport @@ -122,6 +112,7 @@ public class TransportManager { } + @Override public void start(){ if(transport != null){ transport.start(); @@ -130,12 +121,19 @@ public class TransportManager { } } + @Override public void close(long sessionId){ if(transport != null) { transport.stop(); } } + @Deprecated + @Override + public void resetSession(){ + + } + /** * Check to see if a transport is connected. * @param transportType the transport to have its connection status returned. If `null` is @@ -145,6 +143,7 @@ public class TransportManager { * of supplied type will be used to return if connected. * @return if a transport is connected based on included variables */ + @Override public boolean isConnected(TransportType transportType, String address){ synchronized (TRANSPORT_STATUS_LOCK) { if (transportType == null) { @@ -172,6 +171,7 @@ public class TransportManager { * of supplied type will be returned. * @return the transport record for the transport type and address if supplied */ + @Override public TransportRecord getTransportRecord(TransportType transportType, String address){ synchronized (TRANSPORT_STATUS_LOCK) { if (transportType == null) { @@ -193,31 +193,8 @@ public class TransportManager { } } - /** - * Retrieves the currently connected transports - * @return the currently connected transports - */ - public List<TransportRecord> getConnectedTransports(){ - return this.transportStatus; - } - - public boolean isHighBandwidthAvailable(){ - synchronized (TRANSPORT_STATUS_LOCK) { - for (TransportRecord record : transportStatus) { - if (record.getType().equals(TransportType.USB) - || record.getType().equals(TransportType.TCP)) { - return true; - } - } - return false; - } - } - - //FIXME - public Object getRouterService(){ - return null; - } + @Override public void sendPacket(SdlPacket packet){ if(transport !=null){ transport.write(packet); @@ -226,44 +203,4 @@ public class TransportManager { } } - public void requestNewSession(TransportRecord transportRecord){ - //FIXME do nothing - } - - public void requestSecondaryTransportConnection(byte sessionId, Object params){ - //FIXME do nothing - } - - private synchronized void enterLegacyMode(final String info){ - //FIXME do nothing - } - - protected synchronized void exitLegacyMode(String info ){ - //FIXME do nothing - } - - public interface TransportEventListener{ - /** Called to indicate and deliver a packet received from transport */ - void onPacketReceived(SdlPacket packet); - - /** Called to indicate that transport connection was established */ - void onTransportConnected(List<TransportRecord> transports); - - /** Called to indicate that transport was disconnected (by either side) */ - void onTransportDisconnected(String info, TransportRecord type, List<TransportRecord> connectedTransports); - - // Called when the transport manager experiences an unrecoverable failure - void onError(String info); - /** - * Called when the transport manager has determined it needs to move towards a legacy style - * transport connection. It will always be bluetooth. - * @param info simple info string about the situation - * @return if the listener is ok with entering legacy mode - */ - boolean onLegacyModeEnabled(String info); - } - - - - } diff --git a/base/src/main/java/com/smartdevicelink/transport/TransportManagerBase.java b/base/src/main/java/com/smartdevicelink/transport/TransportManagerBase.java new file mode 100644 index 000000000..211269fd2 --- /dev/null +++ b/base/src/main/java/com/smartdevicelink/transport/TransportManagerBase.java @@ -0,0 +1,156 @@ +/* + * 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.transport; + +import com.smartdevicelink.protocol.SdlPacket; +import com.smartdevicelink.transport.enums.TransportType; +import com.smartdevicelink.transport.utl.TransportRecord; + +import java.util.ArrayList; +import java.util.List; + +public abstract class TransportManagerBase { + private static final String TAG = "TransportManagerBase"; + + final Object TRANSPORT_STATUS_LOCK; + + //WebSocketServer2 transport; + final List<TransportRecord> transportStatus; + final TransportEventListener transportListener; + + public TransportManagerBase(BaseTransportConfig config,TransportEventListener listener){ + transportListener = listener; + this.TRANSPORT_STATUS_LOCK = new Object(); + synchronized (TRANSPORT_STATUS_LOCK){ + this.transportStatus = new ArrayList<>(); + } + } + + public abstract void start(); + + public abstract void close(long sessionId); + + @Deprecated + public abstract void resetSession(); + + /** + * Check to see if a transport is connected. + * @param transportType the transport to have its connection status returned. If `null` is + * passed in, all transports will be checked and if any are connected a + * true value will be returned. + * @param address the address associated with the transport type. If null, the first transport + * of supplied type will be used to return if connected. + * @return if a transport is connected based on included variables + */ + public abstract boolean isConnected(TransportType transportType, String address); + /** + * Retrieve a transport record with the supplied params + * @param transportType the transport to have its connection status returned. + * @param address the address associated with the transport type. If null, the first transport + * of supplied type will be returned. + * @return the transport record for the transport type and address if supplied + */ + public abstract TransportRecord getTransportRecord(TransportType transportType, String address); + + + /** + * Retrieves the currently connected transports + * @return the currently connected transports + */ + public List<TransportRecord> getConnectedTransports(){ + return this.transportStatus; + } + + + public boolean isHighBandwidthAvailable(){ + synchronized (TRANSPORT_STATUS_LOCK) { + for (TransportRecord record : transportStatus) { + if (record.getType().equals(TransportType.USB) + || record.getType().equals(TransportType.TCP) + || record.getType().equals(TransportType.WEB_SOCKET_SERVER)) { + return true; + } + } + return false; + } + } + + public BaseTransportConfig updateTransportConfig(BaseTransportConfig config){ + return config; + } + + public abstract void sendPacket(SdlPacket packet); + + /** + * Base implementation does nothing and assumes it is not necssary. This method should be + * overridden in children classes that need to add a prerequest to their transports to make + * space ready for a new session. + * @param transportRecord the transport that the new session should be assigned to + */ + public void requestNewSession(TransportRecord transportRecord){ + //Base implementation does nothing + } + + public void requestSecondaryTransportConnection(byte sessionId, TransportRecord transportRecord){ + //Base implementation does nothing + } + + synchronized void enterLegacyMode(final String info){ + //Base implementation does nothing + } + + synchronized void exitLegacyMode(String info ){ + //Base implementation does nothing + } + + public interface TransportEventListener{ + /** Called to indicate and deliver a packet received from transport */ + void onPacketReceived(SdlPacket packet); + + /** Called to indicate that transport connection was established */ + void onTransportConnected(List<TransportRecord> transports); + + /** Called to indicate that transport was disconnected (by either side) */ + void onTransportDisconnected(String info, TransportRecord type, List<TransportRecord> connectedTransports); + + // Called when the transport manager experiences an unrecoverable failure + void onError(String info); + /** + * Called when the transport manager has determined it needs to move towards a legacy style + * transport connection. It will always be bluetooth. + * @param info simple info string about the situation + * @return if the listener is ok with entering legacy mode + */ + boolean onLegacyModeEnabled(String info); + } +} diff --git a/base/src/main/java/com/smartdevicelink/transport/enums/TransportType.java b/base/src/main/java/com/smartdevicelink/transport/enums/TransportType.java index 5c2dbb23d..43e462ab2 100644 --- a/base/src/main/java/com/smartdevicelink/transport/enums/TransportType.java +++ b/base/src/main/java/com/smartdevicelink/transport/enums/TransportType.java @@ -1,33 +1,33 @@ -package com.smartdevicelink.transport.enums; - -/** - * Defines available types of the transports. - */ -public enum TransportType { - /** - * Transport type will be anything the multiplexing service connects to. - */ - MULTIPLEX, - /** - * Transport type is Bluetooth. - */ - BLUETOOTH, - - /** - * Transport type is TCP. - */ - TCP, +package com.smartdevicelink.transport.enums;
+
+/**
+ * Defines available types of the transports.
+ */
+public enum TransportType {
+ /**
+ * Transport type will be anything the multiplexing service connects to.
+ */
+ MULTIPLEX,
+ /**
+ * Transport type is Bluetooth.
+ */
+ BLUETOOTH,
+
+ /**
+ * Transport type is TCP.
+ */
+ TCP,
USB, /** * Used for cloud and embedded */ WEB_SOCKET_SERVER; - - public static TransportType valueForString(String value) { - try{ - return valueOf(value); - }catch(Exception e){ - return null; - } - } -} +
+ public static TransportType valueForString(String value) {
+ try{
+ return valueOf(value);
+ }catch(Exception e){
+ return null;
+ }
+ }
+}
diff --git a/base/src/main/java/com/smartdevicelink/util/BitConverter.java b/base/src/main/java/com/smartdevicelink/util/BitConverter.java index 153418c8a..a681a75a8 100644 --- a/base/src/main/java/com/smartdevicelink/util/BitConverter.java +++ b/base/src/main/java/com/smartdevicelink/util/BitConverter.java @@ -1,116 +1,116 @@ -package com.smartdevicelink.util; - -public class BitConverter { - /** - * @param bytes byte array that will be converted to hex - * @return the String containing converted hex values or null if byte array is null - */ - public static String bytesToHex(byte [] bytes) { - if (bytes == null) { return null; } - return bytesToHex(bytes, 0, bytes.length); - } // end-method - - /** - * @param bytes byte array that will be converted to hex - * @param offset int representing the offset to begin conversion at - * @param length int representing number of bytes in array to convert - * @return the String containing converted hex values or null if byte array is null - */ - public static String bytesToHex(byte[] bytes, int offset, int length) { - if (bytes == null) { return null; } - final char[] HexDigits = new char[] {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; - byte b; - char[] hexChars = new char[2 * length]; - //StringBuffer sb = new StringBuffer(); - int upperBound = Math.min(bytes.length, (offset + length)); - int baidx = 0; - int sidx = 0; - for (baidx = offset; baidx < upperBound; baidx++) { - // Get the byte from the array - b = bytes[baidx]; - // Use nibbles as index into hex digit array (left nibble, then right) - hexChars[sidx++] = HexDigits[(b & 0xf0) >> 4]; - hexChars[sidx++] = HexDigits[(b & 0x0f)]; - } // end-for - return new String(hexChars); - } // end-method - - /** - * @param hexString the String containing converted hex values - * @return byte array converted from input String or null if String is null - */ - public static byte [] hexToBytes(String hexString) { - if (hexString == null) { return null; } - if (hexString.length() % 2 != 0) { - hexString = "0" + hexString; - } - byte [] theBytes = new byte[hexString.length() / 2]; - for (int i = 0; i < hexString.length(); i += 2) { - String byteString = hexString.substring(i, i + 2); - byte theByte = (byte)Integer.parseInt(byteString, 16); - theBytes[i/2] = theByte; - } - return theBytes; - } // end-method - - public static final byte[] intToByteArray(int value) { - return new byte[] { - (byte)(value >>> 24), - (byte)(value >>> 16), - (byte)(value >>> 8), - (byte)value}; - } - - /** - * @param sizeBuf byte array that will be converted to int - * @return int converted from byte array or -1 if byte array is null - */ - public static int intFromByteArray(byte[] sizeBuf, int offset) { - if (sizeBuf == null) { return -1; } - int ret = 0; - for (int i = offset; i < offset + 4; i++) { - ret <<= 8; - ret |= 0xFF & sizeBuf[i]; - } - return ret; - } - - public static final byte[] shortToByteArray(short value) { - return new byte[] { - (byte)(value >>> 8), - (byte)value}; - } - - /** - * @param sizeBuf byte array that will be converted to short - * @return short converted from byte array or -1 if byte array is null - */ - public static short shortFromByteArray(byte[] sizeBuf, int offset) { - if (sizeBuf == null) { return -1; } - short ret = 0; - for (int i = offset; i < offset + 2; i++) { - ret <<= 8; - ret |= 0xFF & sizeBuf[i]; - } - return ret; - } - - /** - * Converts the byte array into a string of hex values. - * @param bytes byte array that will be converted to hex - * @param end EXCLUSIVE so if it it receives 10 it will print 0-9 - * @return the String containing converted hex values or null if byte array is null - */ - public static String bytesToHex(byte[] bytes,int end){ - if (bytes == null) { return null; } - if(bytes.length<end){ - end = bytes.length; - } - StringBuilder sb = new StringBuilder(); - for(int i=0;i<end;i++){ - sb.append(" "); - sb.append(String.format("%02X ", bytes[i])); - } - return sb.toString(); - } -} +package com.smartdevicelink.util;
+
+public class BitConverter {
+ /**
+ * @param bytes byte array that will be converted to hex
+ * @return the String containing converted hex values or null if byte array is null
+ */
+ public static String bytesToHex(byte [] bytes) {
+ if (bytes == null) { return null; }
+ return bytesToHex(bytes, 0, bytes.length);
+ } // end-method
+
+ /**
+ * @param bytes byte array that will be converted to hex
+ * @param offset int representing the offset to begin conversion at
+ * @param length int representing number of bytes in array to convert
+ * @return the String containing converted hex values or null if byte array is null
+ */
+ public static String bytesToHex(byte[] bytes, int offset, int length) {
+ if (bytes == null) { return null; }
+ final char[] HexDigits = new char[] {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
+ byte b;
+ char[] hexChars = new char[2 * length];
+ //StringBuffer sb = new StringBuffer();
+ int upperBound = Math.min(bytes.length, (offset + length));
+ int baidx = 0;
+ int sidx = 0;
+ for (baidx = offset; baidx < upperBound; baidx++) {
+ // Get the byte from the array
+ b = bytes[baidx];
+ // Use nibbles as index into hex digit array (left nibble, then right)
+ hexChars[sidx++] = HexDigits[(b & 0xf0) >> 4];
+ hexChars[sidx++] = HexDigits[(b & 0x0f)];
+ } // end-for
+ return new String(hexChars);
+ } // end-method
+
+ /**
+ * @param hexString the String containing converted hex values
+ * @return byte array converted from input String or null if String is null
+ */
+ public static byte [] hexToBytes(String hexString) {
+ if (hexString == null) { return null; }
+ if (hexString.length() % 2 != 0) {
+ hexString = "0" + hexString;
+ }
+ byte [] theBytes = new byte[hexString.length() / 2];
+ for (int i = 0; i < hexString.length(); i += 2) {
+ String byteString = hexString.substring(i, i + 2);
+ byte theByte = (byte)Integer.parseInt(byteString, 16);
+ theBytes[i/2] = theByte;
+ }
+ return theBytes;
+ } // end-method
+
+ public static final byte[] intToByteArray(int value) {
+ return new byte[] {
+ (byte)(value >>> 24),
+ (byte)(value >>> 16),
+ (byte)(value >>> 8),
+ (byte)value};
+ }
+
+ /**
+ * @param sizeBuf byte array that will be converted to int
+ * @return int converted from byte array or -1 if byte array is null
+ */
+ public static int intFromByteArray(byte[] sizeBuf, int offset) {
+ if (sizeBuf == null) { return -1; }
+ int ret = 0;
+ for (int i = offset; i < offset + 4; i++) {
+ ret <<= 8;
+ ret |= 0xFF & sizeBuf[i];
+ }
+ return ret;
+ }
+
+ public static final byte[] shortToByteArray(short value) {
+ return new byte[] {
+ (byte)(value >>> 8),
+ (byte)value};
+ }
+
+ /**
+ * @param sizeBuf byte array that will be converted to short
+ * @return short converted from byte array or -1 if byte array is null
+ */
+ public static short shortFromByteArray(byte[] sizeBuf, int offset) {
+ if (sizeBuf == null) { return -1; }
+ short ret = 0;
+ for (int i = offset; i < offset + 2; i++) {
+ ret <<= 8;
+ ret |= 0xFF & sizeBuf[i];
+ }
+ return ret;
+ }
+
+ /**
+ * Converts the byte array into a string of hex values.
+ * @param bytes byte array that will be converted to hex
+ * @param end EXCLUSIVE so if it it receives 10 it will print 0-9
+ * @return the String containing converted hex values or null if byte array is null
+ */
+ public static String bytesToHex(byte[] bytes,int end){
+ if (bytes == null) { return null; }
+ if(bytes.length<end){
+ end = bytes.length;
+ }
+ StringBuilder sb = new StringBuilder();
+ for(int i=0;i<end;i++){
+ sb.append(" ");
+ sb.append(String.format("%02X ", bytes[i]));
+ }
+ return sb.toString();
+ }
+}
diff --git a/base/src/main/java/com/smartdevicelink/util/ByteEnumer.java b/base/src/main/java/com/smartdevicelink/util/ByteEnumer.java index 8ed58420a..0b67d9992 100644 --- a/base/src/main/java/com/smartdevicelink/util/ByteEnumer.java +++ b/base/src/main/java/com/smartdevicelink/util/ByteEnumer.java @@ -1,60 +1,60 @@ -package com.smartdevicelink.util; - -import java.util.Enumeration; -import java.util.Vector; - -public abstract class ByteEnumer { - - protected ByteEnumer(byte value, String name) { - this.value = value; - this.name = name; - } - - private byte value; - private String name; - - public byte getValue() { return value; } - public String getName() { return name; } - - public boolean equals(ByteEnumer other) { - return name == other.getName(); - } - - public boolean eq(ByteEnumer other) { - return equals(other); - } - - public byte value() { - return value; - } - - public static ByteEnumer get(Vector<?> theList, byte value) { - Enumeration<?> enumer = theList.elements(); - while (enumer.hasMoreElements()) { - try { - ByteEnumer current = (ByteEnumer)enumer.nextElement(); - if (current.getValue() == value) { - return current; - } - } catch (ClassCastException e) { - return null; - } - } - return null; - } - - public static ByteEnumer get(Vector<?> theList, String name) { - Enumeration<?> enumer = theList.elements(); - while (enumer.hasMoreElements()) { - try { - ByteEnumer current = (ByteEnumer)enumer.nextElement(); - if (current.getName().equals(name)) { - return current; - } - } catch (ClassCastException e) { - return null; - } - } - return null; - } +package com.smartdevicelink.util;
+
+import java.util.Enumeration;
+import java.util.Vector;
+
+public abstract class ByteEnumer {
+
+ protected ByteEnumer(byte value, String name) {
+ this.value = value;
+ this.name = name;
+ }
+
+ private byte value;
+ private String name;
+
+ public byte getValue() { return value; }
+ public String getName() { return name; }
+
+ public boolean equals(ByteEnumer other) {
+ return name == other.getName();
+ }
+
+ public boolean eq(ByteEnumer other) {
+ return equals(other);
+ }
+
+ public byte value() {
+ return value;
+ }
+
+ public static ByteEnumer get(Vector<?> theList, byte value) {
+ Enumeration<?> enumer = theList.elements();
+ while (enumer.hasMoreElements()) {
+ try {
+ ByteEnumer current = (ByteEnumer)enumer.nextElement();
+ if (current.getValue() == value) {
+ return current;
+ }
+ } catch (ClassCastException e) {
+ return null;
+ }
+ }
+ return null;
+ }
+
+ public static ByteEnumer get(Vector<?> theList, String name) {
+ Enumeration<?> enumer = theList.elements();
+ while (enumer.hasMoreElements()) {
+ try {
+ ByteEnumer current = (ByteEnumer)enumer.nextElement();
+ if (current.getName().equals(name)) {
+ return current;
+ }
+ } catch (ClassCastException e) {
+ return null;
+ }
+ }
+ return null;
+ }
}
\ No newline at end of file diff --git a/base/src/main/java/com/smartdevicelink/util/DebugTool.java b/base/src/main/java/com/smartdevicelink/util/DebugTool.java index 0d005070b..21bbe537c 100644 --- a/base/src/main/java/com/smartdevicelink/util/DebugTool.java +++ b/base/src/main/java/com/smartdevicelink/util/DebugTool.java @@ -1,354 +1,355 @@ -package com.smartdevicelink.util; - -import android.util.Log; - -import com.smartdevicelink.exception.SdlException; -import com.smartdevicelink.marshal.JsonRPCMarshaller; -import com.smartdevicelink.protocol.BinaryFrameHeader; -import com.smartdevicelink.protocol.ProtocolMessage; -import com.smartdevicelink.protocol.SdlPacket; -import com.smartdevicelink.protocol.enums.FunctionID; -import com.smartdevicelink.protocol.enums.MessageType; -import com.smartdevicelink.protocol.enums.SessionType; -import com.smartdevicelink.proxy.RPCMessage; -import com.smartdevicelink.proxy.RPCStruct; -import com.smartdevicelink.transport.SiphonServer; - -import java.util.Hashtable; -import java.util.Vector; - -public class DebugTool { - - - public static final String TAG = "SdlProxy"; - - private static boolean isErrorEnabled = false; - private static boolean isWarningEnabled = false; - private static boolean isInfoEnabled = false; - - public static void enableDebugTool() { - isErrorEnabled = true; - isWarningEnabled = true; - isInfoEnabled = true; - } - - public static void disableDebugTool() { - isErrorEnabled = true; - isWarningEnabled = false; - isInfoEnabled = false; - } - - public static boolean isDebugEnabled() - { - if (isWarningEnabled && isInfoEnabled) return true; - - return false; - } - - private static String prependProxyVersionNumberToString(String string) { - /* FIXME if (Version.VERSION != null && string != null) { - string = Version.VERSION + ": " + string; - }*/ - - return string; - } - - public static void logError(String msg) { - - Boolean wasWritten = false; - - msg = prependProxyVersionNumberToString(msg); - - wasWritten = logToSiphon(msg); - - if (isErrorEnabled && !wasWritten) { - NativeLogTool.logError(TAG, msg); - } - } - - public static void logError(String msg, Throwable ex) { - Boolean wasWritten = false; - - msg = prependProxyVersionNumberToString(msg); - - if (ex != null) { - wasWritten = logToSiphon(msg + " Exception String: " + ex.toString()); - } else { - wasWritten = logToSiphon(msg); - } - - if (isErrorEnabled && !wasWritten) { - NativeLogTool.logError(TAG, msg, ex); - } - } - - public static void logWarning(String msg) { - Boolean wasWritten = false; - - msg = prependProxyVersionNumberToString(msg); - - wasWritten = logToSiphon(msg); - - if (isWarningEnabled && !wasWritten) { - NativeLogTool.logWarning(TAG, msg); - } - } - - public static void logInfo(String msg) { - Boolean wasWritten = false; - - msg = prependProxyVersionNumberToString(msg); - - wasWritten = logToSiphon(msg); - - if (isInfoEnabled && !wasWritten) { - NativeLogTool.logInfo(TAG, msg); - } - } - - public static void logInfo(String msg, boolean bPrependVersion) { - Boolean wasWritten = false; - - if (bPrependVersion) msg = prependProxyVersionNumberToString(msg); - - wasWritten = logToSiphon(msg); - - if (isInfoEnabled && !wasWritten) { - NativeLogTool.logInfo(TAG, msg); - } - } - - protected static Boolean logToSiphon(String msg) { - if (SiphonServer.getSiphonEnabledStatus()) { - // Initialize the SiphonServer, will be ignored if already initialized - SiphonServer.init(); - - // Write to the SiphonServer - return SiphonServer.sendSiphonLogData(msg); - } - return false; - } - - protected static String getLine(Throwable ex) { - if (ex == null) { return null; } - String toPrint = ex.toString() + " :" + ex.getMessage(); - for (int i=0; i<ex.getStackTrace().length; i++) { - StackTraceElement elem = ex.getStackTrace()[i]; - toPrint += "\n " + elem.toString(); - } - - if (ex instanceof SdlException) { - SdlException sdlEx = (SdlException) ex; - if (sdlEx.getInnerException() != null && sdlEx != sdlEx.getInnerException()) { - toPrint += "\n nested:\n"; - toPrint += getLine(sdlEx.getInnerException()); - } - } - - return toPrint; - } - - - protected static Vector<IConsole> consoleListenerList = new Vector<IConsole>(); - - protected final static boolean isTransportEnabled = false; - protected final static boolean isRPCEnabled = false; - - public static void addConsole(IConsole console) { - synchronized(consoleListenerList) { - consoleListenerList.addElement(console); - } - } - - public static void removeConsole(IConsole console) { - synchronized(consoleListenerList) { - consoleListenerList.removeElement(console); - } - } - - public static void clearConsoles() { - synchronized(consoleListenerList) { - consoleListenerList.removeAllElements(); - } - } - - public static void logTransport(String msg) { - if (isTransportEnabled) { - Log.d(TAG, msg); - logInfoToConsole(msg); - } - } - - public static void logRPCSend(String rpcMsg) { - if (isRPCEnabled) { - Log.d(TAG, "Sending RPC message: " + rpcMsg); - logRPCSendToConsole(rpcMsg); - } - } - - public static void logRPCReceive(String rpcMsg) { - if (isRPCEnabled) { - Log.d(TAG, "Received RPC message: " + rpcMsg); - logRPCSendToConsole(rpcMsg); - } - } - - @SuppressWarnings("unchecked") - protected static void logInfoToConsole(String msg) { - Vector<IConsole> localList; - synchronized(consoleListenerList) { - localList = (Vector<IConsole>) consoleListenerList.clone(); - } - - for (int i = 0; i < localList.size(); i++) { - IConsole consoleListener = (IConsole) localList.elementAt(i); - try { - consoleListener.logInfo(msg); - } catch (Exception ex) { - Log.e(TAG, "Failure propagating logInfo: " + ex.toString(), ex); - } // end-catch - } - } - - @SuppressWarnings("unchecked") - protected static void logErrorToConsole(String msg) { - Vector<IConsole> localList; - synchronized(consoleListenerList) { - localList = (Vector<IConsole>) consoleListenerList.clone(); - } - for (int i = 0; i < localList.size(); i++) { - IConsole consoleListener = (IConsole) localList.elementAt(i); - try { - consoleListener.logError(msg); - } catch (Exception ex) { - Log.e(TAG, "Failure propagating logError: " + ex.toString(), ex); - } // end-catch - } - } - - @SuppressWarnings("unchecked") - protected static void logErrorToConsole(String msg, Throwable e) { - Vector<IConsole> localList; - synchronized(consoleListenerList) { - localList = (Vector<IConsole>) consoleListenerList.clone(); - } - - for (int i = 0; i < localList.size(); i++) { - IConsole consoleListener = (IConsole) localList.elementAt(i); - try { - consoleListener.logError(msg, e); - } catch (Exception ex) { - Log.e(TAG, "Failure propagating logError: " + ex.toString(), ex); - } // end-catch - } - } - - @SuppressWarnings("unchecked") - protected static void logRPCSendToConsole(String msg) { - Vector<IConsole> localList; - synchronized(consoleListenerList) { - localList = (Vector<IConsole>) consoleListenerList.clone(); - } - - for (int i = 0; i < localList.size(); i++) { - IConsole consoleListener = (IConsole) localList.elementAt(i); - try { - consoleListener.logRPCSend(msg); - } catch (Exception ex) { - Log.e(TAG, "Failure propagating logRPCSend: " + ex.toString(), ex); - } // end-catch - } - } - - @SuppressWarnings("unchecked") - protected static void logRPCReceiveToConsole(String msg) { - Vector<IConsole> localList; - synchronized(consoleListenerList) { - localList = (Vector<IConsole>) consoleListenerList.clone(); - } - - for (int i = 0; i < localList.size(); i++) { - IConsole consoleListener = (IConsole) localList.elementAt(i); - try { - consoleListener.logRPCReceive(msg); - } catch (Exception ex) { - Log.e(TAG, "Failure propagating logRPCReceive: " + ex.toString(), ex); - } // end-catch - } - } - - /** - * Debug method to try to extract the RPC hash from the packet payload. Should only be used while debugging, not in production. - * Currently it will only handle single frame RPCs - * @param packet to inspect - * @return The Hashtable to be used to construct an RPC - */ - public static Hashtable<String, Object> getRPCHash(SdlPacket packet){ - if(packet == null || - packet.getFrameType().getValue() != SdlPacket.FRAME_TYPE_SINGLE || - packet.getServiceType()!=SdlPacket.SERVICE_TYPE_RPC){ - Log.w("Debug", "Unable to get hash"); - return null; - } - int version = packet.getVersion(); - - ProtocolMessage message = new ProtocolMessage(); - SessionType serviceType = SessionType.valueOf((byte)packet.getServiceType()); - if (serviceType == SessionType.RPC) { - message.setMessageType(MessageType.RPC); - } else if (serviceType == SessionType.BULK_DATA) { - message.setMessageType(MessageType.BULK); - } // end-if - message.setSessionType(serviceType); - message.setSessionID((byte)packet.getSessionId()); - //If it is WiPro 2.0 it must have binary header - if (version > 1) { - BinaryFrameHeader binFrameHeader = BinaryFrameHeader. - parseBinaryHeader(packet.getPayload()); - if(binFrameHeader == null) { - return null; - } - message.setVersion((byte) version); - message.setRPCType(binFrameHeader.getRPCType()); - message.setFunctionID(binFrameHeader.getFunctionID()); - message.setCorrID(binFrameHeader.getCorrID()); - if (binFrameHeader.getJsonSize() > 0){ - message.setData(binFrameHeader.getJsonData()); - } - if (binFrameHeader.getBulkData() != null){ - message.setBulkData(binFrameHeader.getBulkData()); - } - } else { - message.setData(packet.getPayload()); - } - Hashtable<String, Object> hash = new Hashtable<String, Object>(); - if (packet.getVersion() > 1) { - Hashtable<String, Object> hashTemp = new Hashtable<String, Object>(); - - hashTemp.put(RPCMessage.KEY_CORRELATION_ID, message.getCorrID()); - if (message.getJsonSize() > 0) { - final Hashtable<String, Object> mhash = JsonRPCMarshaller.unmarshall(message.getData()); - hashTemp.put(RPCMessage.KEY_PARAMETERS, mhash); - } - - String functionName = FunctionID.getFunctionName(message.getFunctionID()); - if (functionName != null) { - hashTemp.put(RPCMessage.KEY_FUNCTION_NAME, functionName); - } else { - return null; - } - if (message.getRPCType() == 0x00) { - hash.put(RPCMessage.KEY_REQUEST, hashTemp); - } else if (message.getRPCType() == 0x01) { - hash.put(RPCMessage.KEY_RESPONSE, hashTemp); - } else if (message.getRPCType() == 0x02) { - hash.put(RPCMessage.KEY_NOTIFICATION, hashTemp); - } - if (message.getBulkData() != null) hash.put(RPCStruct.KEY_BULK_DATA, message.getBulkData()); - } else { - final Hashtable<String, Object> mhash = JsonRPCMarshaller.unmarshall(message.getData()); - hash = mhash; - } - return hash; - } -} +package com.smartdevicelink.util;
+
+import android.util.Log;
+
+import com.smartdevicelink.BuildConfig;
+import com.smartdevicelink.exception.SdlException;
+import com.smartdevicelink.marshal.JsonRPCMarshaller;
+import com.smartdevicelink.protocol.BinaryFrameHeader;
+import com.smartdevicelink.protocol.ProtocolMessage;
+import com.smartdevicelink.protocol.SdlPacket;
+import com.smartdevicelink.protocol.enums.FunctionID;
+import com.smartdevicelink.protocol.enums.MessageType;
+import com.smartdevicelink.protocol.enums.SessionType;
+import com.smartdevicelink.proxy.RPCMessage;
+import com.smartdevicelink.proxy.RPCStruct;
+import com.smartdevicelink.transport.SiphonServer;
+
+import java.util.Hashtable;
+import java.util.Vector;
+
+public class DebugTool {
+
+
+ public static final String TAG = "SdlProxy";
+
+ private static boolean isErrorEnabled = false;
+ private static boolean isWarningEnabled = false;
+ private static boolean isInfoEnabled = false;
+
+ public static void enableDebugTool() {
+ isErrorEnabled = true;
+ isWarningEnabled = true;
+ isInfoEnabled = true;
+ }
+
+ public static void disableDebugTool() {
+ isErrorEnabled = true;
+ isWarningEnabled = false;
+ isInfoEnabled = false;
+ }
+
+ public static boolean isDebugEnabled()
+ {
+ if (isWarningEnabled && isInfoEnabled) return true;
+
+ return false;
+ }
+
+ private static String prependProxyVersionNumberToString(String string) {
+ if (BuildConfig.VERSION_NAME != null && string != null) {
+ string = BuildConfig.VERSION_NAME + ": " + string;
+ }
+
+ return string;
+ }
+
+ public static void logError(String msg) {
+
+ Boolean wasWritten = false;
+
+ msg = prependProxyVersionNumberToString(msg);
+
+ wasWritten = logToSiphon(msg);
+
+ if (isErrorEnabled && !wasWritten) {
+ NativeLogTool.logError(TAG, msg);
+ }
+ }
+
+ public static void logError(String msg, Throwable ex) {
+ Boolean wasWritten = false;
+
+ msg = prependProxyVersionNumberToString(msg);
+
+ if (ex != null) {
+ wasWritten = logToSiphon(msg + " Exception String: " + ex.toString());
+ } else {
+ wasWritten = logToSiphon(msg);
+ }
+
+ if (isErrorEnabled && !wasWritten) {
+ NativeLogTool.logError(TAG, msg, ex);
+ }
+ }
+
+ public static void logWarning(String msg) {
+ Boolean wasWritten = false;
+
+ msg = prependProxyVersionNumberToString(msg);
+
+ wasWritten = logToSiphon(msg);
+
+ if (isWarningEnabled && !wasWritten) {
+ NativeLogTool.logWarning(TAG, msg);
+ }
+ }
+
+ public static void logInfo(String msg) {
+ Boolean wasWritten = false;
+
+ msg = prependProxyVersionNumberToString(msg);
+
+ wasWritten = logToSiphon(msg);
+
+ if (isInfoEnabled && !wasWritten) {
+ NativeLogTool.logInfo(TAG, msg);
+ }
+ }
+
+ public static void logInfo(String msg, boolean bPrependVersion) {
+ Boolean wasWritten = false;
+
+ if (bPrependVersion) msg = prependProxyVersionNumberToString(msg);
+
+ wasWritten = logToSiphon(msg);
+
+ if (isInfoEnabled && !wasWritten) {
+ NativeLogTool.logInfo(TAG, msg);
+ }
+ }
+
+ protected static Boolean logToSiphon(String msg) {
+ if (SiphonServer.getSiphonEnabledStatus()) {
+ // Initialize the SiphonServer, will be ignored if already initialized
+ SiphonServer.init();
+
+ // Write to the SiphonServer
+ return SiphonServer.sendSiphonLogData(msg);
+ }
+ return false;
+ }
+
+ protected static String getLine(Throwable ex) {
+ if (ex == null) { return null; }
+ String toPrint = ex.toString() + " :" + ex.getMessage();
+ for (int i=0; i<ex.getStackTrace().length; i++) {
+ StackTraceElement elem = ex.getStackTrace()[i];
+ toPrint += "\n " + elem.toString();
+ }
+
+ if (ex instanceof SdlException) {
+ SdlException sdlEx = (SdlException) ex;
+ if (sdlEx.getInnerException() != null && sdlEx != sdlEx.getInnerException()) {
+ toPrint += "\n nested:\n";
+ toPrint += getLine(sdlEx.getInnerException());
+ }
+ }
+
+ return toPrint;
+ }
+
+
+ protected static Vector<IConsole> consoleListenerList = new Vector<IConsole>();
+
+ protected final static boolean isTransportEnabled = false;
+ protected final static boolean isRPCEnabled = false;
+
+ public static void addConsole(IConsole console) {
+ synchronized(consoleListenerList) {
+ consoleListenerList.addElement(console);
+ }
+ }
+
+ public static void removeConsole(IConsole console) {
+ synchronized(consoleListenerList) {
+ consoleListenerList.removeElement(console);
+ }
+ }
+
+ public static void clearConsoles() {
+ synchronized(consoleListenerList) {
+ consoleListenerList.removeAllElements();
+ }
+ }
+
+ public static void logTransport(String msg) {
+ if (isTransportEnabled) {
+ Log.d(TAG, msg);
+ logInfoToConsole(msg);
+ }
+ }
+
+ public static void logRPCSend(String rpcMsg) {
+ if (isRPCEnabled) {
+ Log.d(TAG, "Sending RPC message: " + rpcMsg);
+ logRPCSendToConsole(rpcMsg);
+ }
+ }
+
+ public static void logRPCReceive(String rpcMsg) {
+ if (isRPCEnabled) {
+ Log.d(TAG, "Received RPC message: " + rpcMsg);
+ logRPCSendToConsole(rpcMsg);
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ protected static void logInfoToConsole(String msg) {
+ Vector<IConsole> localList;
+ synchronized(consoleListenerList) {
+ localList = (Vector<IConsole>) consoleListenerList.clone();
+ }
+
+ for (int i = 0; i < localList.size(); i++) {
+ IConsole consoleListener = (IConsole) localList.elementAt(i);
+ try {
+ consoleListener.logInfo(msg);
+ } catch (Exception ex) {
+ Log.e(TAG, "Failure propagating logInfo: " + ex.toString(), ex);
+ } // end-catch
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ protected static void logErrorToConsole(String msg) {
+ Vector<IConsole> localList;
+ synchronized(consoleListenerList) {
+ localList = (Vector<IConsole>) consoleListenerList.clone();
+ }
+ for (int i = 0; i < localList.size(); i++) {
+ IConsole consoleListener = (IConsole) localList.elementAt(i);
+ try {
+ consoleListener.logError(msg);
+ } catch (Exception ex) {
+ Log.e(TAG, "Failure propagating logError: " + ex.toString(), ex);
+ } // end-catch
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ protected static void logErrorToConsole(String msg, Throwable e) {
+ Vector<IConsole> localList;
+ synchronized(consoleListenerList) {
+ localList = (Vector<IConsole>) consoleListenerList.clone();
+ }
+
+ for (int i = 0; i < localList.size(); i++) {
+ IConsole consoleListener = (IConsole) localList.elementAt(i);
+ try {
+ consoleListener.logError(msg, e);
+ } catch (Exception ex) {
+ Log.e(TAG, "Failure propagating logError: " + ex.toString(), ex);
+ } // end-catch
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ protected static void logRPCSendToConsole(String msg) {
+ Vector<IConsole> localList;
+ synchronized(consoleListenerList) {
+ localList = (Vector<IConsole>) consoleListenerList.clone();
+ }
+
+ for (int i = 0; i < localList.size(); i++) {
+ IConsole consoleListener = (IConsole) localList.elementAt(i);
+ try {
+ consoleListener.logRPCSend(msg);
+ } catch (Exception ex) {
+ Log.e(TAG, "Failure propagating logRPCSend: " + ex.toString(), ex);
+ } // end-catch
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ protected static void logRPCReceiveToConsole(String msg) {
+ Vector<IConsole> localList;
+ synchronized(consoleListenerList) {
+ localList = (Vector<IConsole>) consoleListenerList.clone();
+ }
+
+ for (int i = 0; i < localList.size(); i++) {
+ IConsole consoleListener = (IConsole) localList.elementAt(i);
+ try {
+ consoleListener.logRPCReceive(msg);
+ } catch (Exception ex) {
+ Log.e(TAG, "Failure propagating logRPCReceive: " + ex.toString(), ex);
+ } // end-catch
+ }
+ }
+
+ /**
+ * Debug method to try to extract the RPC hash from the packet payload. Should only be used while debugging, not in production.
+ * Currently it will only handle single frame RPCs
+ * @param packet to inspect
+ * @return The Hashtable to be used to construct an RPC
+ */
+ public static Hashtable<String, Object> getRPCHash(SdlPacket packet){
+ if(packet == null ||
+ packet.getFrameType().getValue() != SdlPacket.FRAME_TYPE_SINGLE ||
+ packet.getServiceType()!=SdlPacket.SERVICE_TYPE_RPC){
+ Log.w("Debug", "Unable to get hash");
+ return null;
+ }
+ int version = packet.getVersion();
+
+ ProtocolMessage message = new ProtocolMessage();
+ SessionType serviceType = SessionType.valueOf((byte)packet.getServiceType());
+ if (serviceType == SessionType.RPC) {
+ message.setMessageType(MessageType.RPC);
+ } else if (serviceType == SessionType.BULK_DATA) {
+ message.setMessageType(MessageType.BULK);
+ } // end-if
+ message.setSessionType(serviceType);
+ message.setSessionID((byte)packet.getSessionId());
+ //If it is WiPro 2.0 it must have binary header
+ if (version > 1) {
+ BinaryFrameHeader binFrameHeader = BinaryFrameHeader.
+ parseBinaryHeader(packet.getPayload());
+ if(binFrameHeader == null) {
+ return null;
+ }
+ message.setVersion((byte) version);
+ message.setRPCType(binFrameHeader.getRPCType());
+ message.setFunctionID(binFrameHeader.getFunctionID());
+ message.setCorrID(binFrameHeader.getCorrID());
+ if (binFrameHeader.getJsonSize() > 0){
+ message.setData(binFrameHeader.getJsonData());
+ }
+ if (binFrameHeader.getBulkData() != null){
+ message.setBulkData(binFrameHeader.getBulkData());
+ }
+ } else {
+ message.setData(packet.getPayload());
+ }
+ Hashtable<String, Object> hash = new Hashtable<String, Object>();
+ if (packet.getVersion() > 1) {
+ Hashtable<String, Object> hashTemp = new Hashtable<String, Object>();
+
+ hashTemp.put(RPCMessage.KEY_CORRELATION_ID, message.getCorrID());
+ if (message.getJsonSize() > 0) {
+ final Hashtable<String, Object> mhash = JsonRPCMarshaller.unmarshall(message.getData());
+ hashTemp.put(RPCMessage.KEY_PARAMETERS, mhash);
+ }
+
+ String functionName = FunctionID.getFunctionName(message.getFunctionID());
+ if (functionName != null) {
+ hashTemp.put(RPCMessage.KEY_FUNCTION_NAME, functionName);
+ } else {
+ return null;
+ }
+ if (message.getRPCType() == 0x00) {
+ hash.put(RPCMessage.KEY_REQUEST, hashTemp);
+ } else if (message.getRPCType() == 0x01) {
+ hash.put(RPCMessage.KEY_RESPONSE, hashTemp);
+ } else if (message.getRPCType() == 0x02) {
+ hash.put(RPCMessage.KEY_NOTIFICATION, hashTemp);
+ }
+ if (message.getBulkData() != null) hash.put(RPCStruct.KEY_BULK_DATA, message.getBulkData());
+ } else {
+ final Hashtable<String, Object> mhash = JsonRPCMarshaller.unmarshall(message.getData());
+ hash = mhash;
+ }
+ return hash;
+ }
+}
diff --git a/base/src/main/java/com/smartdevicelink/util/HttpRequestTask.java b/base/src/main/java/com/smartdevicelink/util/HttpRequestTask.java index be7542000..5e8bba95c 100644 --- a/base/src/main/java/com/smartdevicelink/util/HttpRequestTask.java +++ b/base/src/main/java/com/smartdevicelink/util/HttpRequestTask.java @@ -23,7 +23,7 @@ public class HttpRequestTask extends AsyncTask<String, String, String> { HttpRequestTaskCallback cb; /** - * @param hcb callback for when this task finishes + * @param HttpRequestTaskCallback callback for when this task finishes * <br><br><b> - When calling execute, params as followed: </b><br> * 1. Url String<br> * 2. Request type (Defined in this class) REQUEST_TYPE_POST, REQUEST_TYPE_GET, REQUEST_TYPE_DELETE<br> diff --git a/base/src/main/java/com/smartdevicelink/util/IConsole.java b/base/src/main/java/com/smartdevicelink/util/IConsole.java index b388f77f9..8d6d4a0f1 100644 --- a/base/src/main/java/com/smartdevicelink/util/IConsole.java +++ b/base/src/main/java/com/smartdevicelink/util/IConsole.java @@ -1,10 +1,10 @@ -package com.smartdevicelink.util; - - -public interface IConsole { - void logInfo(String msg); - void logError(String msg); - void logError(String msg, Throwable ex); - void logRPCSend(String rpcMsg); - void logRPCReceive(String rpcMsg); -} +package com.smartdevicelink.util;
+
+
+public interface IConsole {
+ void logInfo(String msg);
+ void logError(String msg);
+ void logError(String msg, Throwable ex);
+ void logRPCSend(String rpcMsg);
+ void logRPCReceive(String rpcMsg);
+}
diff --git a/base/src/main/java/com/smartdevicelink/util/NativeLogTool.java b/base/src/main/java/com/smartdevicelink/util/NativeLogTool.java index 488ddac29..d9e39ae07 100644 --- a/base/src/main/java/com/smartdevicelink/util/NativeLogTool.java +++ b/base/src/main/java/com/smartdevicelink/util/NativeLogTool.java @@ -1,112 +1,112 @@ -package com.smartdevicelink.util; - -import android.util.Log; - -public class NativeLogTool { - private static String TAG = "NativeLogTool"; - static private boolean logToSystemEnabled = true; - private static final int ChunkSize = 4000; - - public enum LogTarget { - Info - ,Warning - ,Error; - - public static LogTarget valueForString (String value) { - try{ - return valueOf(value); - } catch(Exception e) { - return null; - } - } - } - - public static void setEnableState(boolean en) { - logToSystemEnabled = en; - } // end-method - - public static boolean isEnabled() { - return logToSystemEnabled; - } // end-method - - public static boolean logInfo(String message) { +package com.smartdevicelink.util;
+
+import android.util.Log;
+
+public class NativeLogTool {
+ private static String TAG = "NativeLogTool";
+ static private boolean logToSystemEnabled = true;
+ private static final int ChunkSize = 4000;
+
+ public enum LogTarget {
+ Info
+ ,Warning
+ ,Error;
+
+ public static LogTarget valueForString (String value) {
+ try{
+ return valueOf(value);
+ } catch(Exception e) {
+ return null;
+ }
+ }
+ }
+
+ public static void setEnableState(boolean en) {
+ logToSystemEnabled = en;
+ } // end-method
+
+ public static boolean isEnabled() {
+ return logToSystemEnabled;
+ } // end-method
+
+ public static boolean logInfo(String message) {
return logInfo(TAG, message); - } - - public static boolean logInfo(String tag, String message) { - if (logToSystemEnabled) { - return log(LogTarget.Info, tag, message); - } - return false; - } - - public static boolean logWarning(String message) { + }
+
+ public static boolean logInfo(String tag, String message) {
+ if (logToSystemEnabled) {
+ return log(LogTarget.Info, tag, message);
+ }
+ return false;
+ }
+
+ public static boolean logWarning(String message) {
return logWarning(TAG, message); - } - - public static boolean logWarning(String tag, String message) { - if (logToSystemEnabled) { - return log(LogTarget.Warning, tag, message); - } - return false; - } - - public static boolean logError(String message) { + }
+
+ public static boolean logWarning(String tag, String message) {
+ if (logToSystemEnabled) {
+ return log(LogTarget.Warning, tag, message);
+ }
+ return false;
+ }
+
+ public static boolean logError(String message) {
return logError(TAG, message); - } - - public static boolean logError(String tag, String message) { - if (logToSystemEnabled) { - return log(LogTarget.Error, tag, message); - } - return false; - } - - public static boolean logError(String message, Throwable t) { + }
+
+ public static boolean logError(String tag, String message) {
+ if (logToSystemEnabled) {
+ return log(LogTarget.Error, tag, message);
+ }
+ return false;
+ }
+
+ public static boolean logError(String message, Throwable t) {
return logError(TAG, message, t); - } - - public static boolean logError(String tag, String message, Throwable t) { - // If the call to logError is passed a throwable, write directly to the system log - if (logToSystemEnabled) { - Log.e(tag, message, t); - } - return logToSystemEnabled; - } - - private static boolean log(LogTarget ltarg, String source, String logMsg) { - // Don't log empty messages - if (logMsg == null || logMsg.length() == 0) { - return false; - } - - int bytesWritten = 0; - int substrSize = 0; - String tag = source; - String chunk = null; - try { - for (int idx=0;idx < logMsg.length();idx += substrSize) { - substrSize = Math.min(ChunkSize, logMsg.length() - idx); - chunk = logMsg.substring(idx, idx + substrSize); - switch (ltarg) { - case Info: - bytesWritten = Log.i(tag, chunk); - break; - case Warning: - bytesWritten = Log.w(tag, chunk); - break; - case Error: - bytesWritten = Log.e(tag, chunk); - break; - } - if (bytesWritten < chunk.length()) { - //Log.e(TAG, "Calling Log.e: msg length=" + chunk.length() + ", bytesWritten=" + bytesWritten); - } - } - } catch (Exception ex) { + }
+
+ public static boolean logError(String tag, String message, Throwable t) {
+ // If the call to logError is passed a throwable, write directly to the system log
+ if (logToSystemEnabled) {
+ Log.e(tag, message, t);
+ }
+ return logToSystemEnabled;
+ }
+
+ private static boolean log(LogTarget ltarg, String source, String logMsg) {
+ // Don't log empty messages
+ if (logMsg == null || logMsg.length() == 0) {
+ return false;
+ }
+
+ int bytesWritten = 0;
+ int substrSize = 0;
+ String tag = source;
+ String chunk = null;
+ try {
+ for (int idx=0;idx < logMsg.length();idx += substrSize) {
+ substrSize = Math.min(ChunkSize, logMsg.length() - idx);
+ chunk = logMsg.substring(idx, idx + substrSize);
+ switch (ltarg) {
+ case Info:
+ bytesWritten = Log.i(tag, chunk);
+ break;
+ case Warning:
+ bytesWritten = Log.w(tag, chunk);
+ break;
+ case Error:
+ bytesWritten = Log.e(tag, chunk);
+ break;
+ }
+ if (bytesWritten < chunk.length()) {
+ Log.e(TAG, "Calling Log.e: msg length=" + chunk.length() + ", bytesWritten=" + bytesWritten); + }
+ }
+ } catch (Exception ex) {
Log.e(TAG, "Failure writing " + ltarg.name() + " fragments to android log:" + ex.toString()); - return false; - } - return true; - } + return false;
+ }
+ return true;
+ }
} diff --git a/baseAndroid/src/main/java/com/smartdevicelink/Dispatcher b/baseAndroid/src/main/java/com/smartdevicelink/Dispatcher new file mode 120000 index 000000000..2af882be4 --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/Dispatcher @@ -0,0 +1 @@ +../../../../../../base/src/main/java/com/smartdevicelink/Dispatcher/
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/SdlConnection/ISdlConnectionListener.java b/baseAndroid/src/main/java/com/smartdevicelink/SdlConnection/ISdlConnectionListener.java new file mode 120000 index 000000000..0e22d9dc9 --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/SdlConnection/ISdlConnectionListener.java @@ -0,0 +1 @@ +../../../../../../../base/src/main/java/com/smartdevicelink/SdlConnection/ISdlConnectionListener.java
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/exception b/baseAndroid/src/main/java/com/smartdevicelink/exception new file mode 120000 index 000000000..d5d048354 --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/exception @@ -0,0 +1 @@ +../../../../../../base/src/main/java/com/smartdevicelink/exception/
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/marshal b/baseAndroid/src/main/java/com/smartdevicelink/marshal new file mode 120000 index 000000000..c86064e2f --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/marshal @@ -0,0 +1 @@ +../../../../../../base/src/main/java/com/smartdevicelink/marshal/
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/protocol/BinaryFrameHeader.java b/baseAndroid/src/main/java/com/smartdevicelink/protocol/BinaryFrameHeader.java new file mode 120000 index 000000000..c2b9f5a5d --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/protocol/BinaryFrameHeader.java @@ -0,0 +1 @@ +../../../../../../../base/src/main/java/com/smartdevicelink/protocol/BinaryFrameHeader.java
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/protocol/IProtocolListener.java b/baseAndroid/src/main/java/com/smartdevicelink/protocol/IProtocolListener.java new file mode 120000 index 000000000..05acb054b --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/protocol/IProtocolListener.java @@ -0,0 +1 @@ +../../../../../../../base/src/main/java/com/smartdevicelink/protocol/IProtocolListener.java
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/protocol/ISdlProtocol.java b/baseAndroid/src/main/java/com/smartdevicelink/protocol/ISdlProtocol.java new file mode 120000 index 000000000..37bba1630 --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/protocol/ISdlProtocol.java @@ -0,0 +1 @@ +../../../../../../../base/src/main/java/com/smartdevicelink/protocol/ISdlProtocol.java
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/protocol/ISecondaryTransportListener.java b/baseAndroid/src/main/java/com/smartdevicelink/protocol/ISecondaryTransportListener.java new file mode 120000 index 000000000..92bbe53bf --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/protocol/ISecondaryTransportListener.java @@ -0,0 +1 @@ +../../../../../../../base/src/main/java/com/smartdevicelink/protocol/ISecondaryTransportListener.java
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/protocol/ProtocolMessage.java b/baseAndroid/src/main/java/com/smartdevicelink/protocol/ProtocolMessage.java new file mode 120000 index 000000000..530ee50b1 --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/protocol/ProtocolMessage.java @@ -0,0 +1 @@ +../../../../../../../base/src/main/java/com/smartdevicelink/protocol/ProtocolMessage.java
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/protocol/SdlPacket.java b/baseAndroid/src/main/java/com/smartdevicelink/protocol/SdlPacket.java new file mode 120000 index 000000000..8408c2728 --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/protocol/SdlPacket.java @@ -0,0 +1 @@ +../../../../../../../base/src/main/java/com/smartdevicelink/protocol/SdlPacket.java
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/protocol/SdlPacketFactory.java b/baseAndroid/src/main/java/com/smartdevicelink/protocol/SdlPacketFactory.java new file mode 120000 index 000000000..aded79f74 --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/protocol/SdlPacketFactory.java @@ -0,0 +1 @@ +../../../../../../../base/src/main/java/com/smartdevicelink/protocol/SdlPacketFactory.java
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/protocol/SdlProtocolBase.java b/baseAndroid/src/main/java/com/smartdevicelink/protocol/SdlProtocolBase.java new file mode 120000 index 000000000..12d9192e9 --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/protocol/SdlProtocolBase.java @@ -0,0 +1 @@ +../../../../../../../base/src/main/java/com/smartdevicelink/protocol/SdlProtocolBase.java
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/proxy/IProxyListener.java b/baseAndroid/src/main/java/com/smartdevicelink/proxy/IProxyListener.java new file mode 120000 index 000000000..e79a51ef6 --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/proxy/IProxyListener.java @@ -0,0 +1 @@ +../../../../../../../base/src/main/java/com/smartdevicelink/proxy/IProxyListener.java
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/proxy/RPCMessage.java b/baseAndroid/src/main/java/com/smartdevicelink/proxy/RPCMessage.java new file mode 120000 index 000000000..97e44408d --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/proxy/RPCMessage.java @@ -0,0 +1 @@ +../../../../../../../base/src/main/java/com/smartdevicelink/proxy/RPCMessage.java
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/proxy/RPCNotification.java b/baseAndroid/src/main/java/com/smartdevicelink/proxy/RPCNotification.java new file mode 120000 index 000000000..8713d52e3 --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/proxy/RPCNotification.java @@ -0,0 +1 @@ +../../../../../../../base/src/main/java/com/smartdevicelink/proxy/RPCNotification.java
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/proxy/RPCRequest.java b/baseAndroid/src/main/java/com/smartdevicelink/proxy/RPCRequest.java new file mode 120000 index 000000000..c1e2f4a27 --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/proxy/RPCRequest.java @@ -0,0 +1 @@ +../../../../../../../base/src/main/java/com/smartdevicelink/proxy/RPCRequest.java
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/proxy/RPCResponse.java b/baseAndroid/src/main/java/com/smartdevicelink/proxy/RPCResponse.java new file mode 120000 index 000000000..afcfd9e15 --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/proxy/RPCResponse.java @@ -0,0 +1 @@ +../../../../../../../base/src/main/java/com/smartdevicelink/proxy/RPCResponse.java
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/proxy/RPCStruct.java b/baseAndroid/src/main/java/com/smartdevicelink/proxy/RPCStruct.java new file mode 120000 index 000000000..683ec16a9 --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/proxy/RPCStruct.java @@ -0,0 +1 @@ +../../../../../../../base/src/main/java/com/smartdevicelink/proxy/RPCStruct.java
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/proxy/SystemCapabilityManager.java b/baseAndroid/src/main/java/com/smartdevicelink/proxy/SystemCapabilityManager.java new file mode 120000 index 000000000..3d03c008f --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/proxy/SystemCapabilityManager.java @@ -0,0 +1 @@ +../../../../../../../base/src/main/java/com/smartdevicelink/proxy/SystemCapabilityManager.java
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/proxy/TTSChunkFactory.java b/baseAndroid/src/main/java/com/smartdevicelink/proxy/TTSChunkFactory.java new file mode 120000 index 000000000..ba944a202 --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/proxy/TTSChunkFactory.java @@ -0,0 +1 @@ +../../../../../../../base/src/main/java/com/smartdevicelink/proxy/TTSChunkFactory.java
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/proxy/callbacks b/baseAndroid/src/main/java/com/smartdevicelink/proxy/callbacks new file mode 120000 index 000000000..74653ae9f --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/proxy/callbacks @@ -0,0 +1 @@ +../../../../../../../base/src/main/java/com/smartdevicelink/proxy/callbacks/
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/proxy/constants b/baseAndroid/src/main/java/com/smartdevicelink/proxy/constants new file mode 120000 index 000000000..ced1d41aa --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/proxy/constants @@ -0,0 +1 @@ +../../../../../../../base/src/main/java/com/smartdevicelink/proxy/constants/
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/proxy/interfaces/IAudioStreamListener.java b/baseAndroid/src/main/java/com/smartdevicelink/proxy/interfaces/IAudioStreamListener.java new file mode 120000 index 000000000..02570d2f8 --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/proxy/interfaces/IAudioStreamListener.java @@ -0,0 +1 @@ +../../../../../../../../base/src/main/java/com/smartdevicelink/proxy/interfaces/IAudioStreamListener.java
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/proxy/interfaces/IProxyListenerALM.java b/baseAndroid/src/main/java/com/smartdevicelink/proxy/interfaces/IProxyListenerALM.java new file mode 120000 index 000000000..cede25df1 --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/proxy/interfaces/IProxyListenerALM.java @@ -0,0 +1 @@ +../../../../../../../../base/src/main/java/com/smartdevicelink/proxy/interfaces/IProxyListenerALM.java
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/proxy/interfaces/IProxyListenerBase.java b/baseAndroid/src/main/java/com/smartdevicelink/proxy/interfaces/IProxyListenerBase.java new file mode 120000 index 000000000..32895d7fe --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/proxy/interfaces/IProxyListenerBase.java @@ -0,0 +1 @@ +../../../../../../../../base/src/main/java/com/smartdevicelink/proxy/interfaces/IProxyListenerBase.java
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/proxy/interfaces/IPutFileResponseListener.java b/baseAndroid/src/main/java/com/smartdevicelink/proxy/interfaces/IPutFileResponseListener.java new file mode 120000 index 000000000..41112b9e7 --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/proxy/interfaces/IPutFileResponseListener.java @@ -0,0 +1 @@ +../../../../../../../../base/src/main/java/com/smartdevicelink/proxy/interfaces/IPutFileResponseListener.java
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/proxy/interfaces/ISdl.java b/baseAndroid/src/main/java/com/smartdevicelink/proxy/interfaces/ISdl.java new file mode 120000 index 000000000..9b79b4afc --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/proxy/interfaces/ISdl.java @@ -0,0 +1 @@ +../../../../../../../../base/src/main/java/com/smartdevicelink/proxy/interfaces/ISdl.java
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/proxy/interfaces/ISdlServiceListener.java b/baseAndroid/src/main/java/com/smartdevicelink/proxy/interfaces/ISdlServiceListener.java new file mode 120000 index 000000000..87f717597 --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/proxy/interfaces/ISdlServiceListener.java @@ -0,0 +1 @@ +../../../../../../../../base/src/main/java/com/smartdevicelink/proxy/interfaces/ISdlServiceListener.java
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/proxy/interfaces/IVideoStreamListener.java b/baseAndroid/src/main/java/com/smartdevicelink/proxy/interfaces/IVideoStreamListener.java new file mode 120000 index 000000000..c817900a3 --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/proxy/interfaces/IVideoStreamListener.java @@ -0,0 +1 @@ +../../../../../../../../base/src/main/java/com/smartdevicelink/proxy/interfaces/IVideoStreamListener.java
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/proxy/interfaces/OnSystemCapabilityListener.java b/baseAndroid/src/main/java/com/smartdevicelink/proxy/interfaces/OnSystemCapabilityListener.java new file mode 120000 index 000000000..ea2302aa4 --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/proxy/interfaces/OnSystemCapabilityListener.java @@ -0,0 +1 @@ +../../../../../../../../base/src/main/java/com/smartdevicelink/proxy/interfaces/OnSystemCapabilityListener.java
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/streaming/AbstractPacketizer.java b/baseAndroid/src/main/java/com/smartdevicelink/streaming/AbstractPacketizer.java new file mode 120000 index 000000000..ce7fd47d9 --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/streaming/AbstractPacketizer.java @@ -0,0 +1 @@ +../../../../../../../base/src/main/java/com/smartdevicelink/streaming/AbstractPacketizer.java
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/streaming/IStreamListener.java b/baseAndroid/src/main/java/com/smartdevicelink/streaming/IStreamListener.java new file mode 120000 index 000000000..f703ac149 --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/streaming/IStreamListener.java @@ -0,0 +1 @@ +../../../../../../../base/src/main/java/com/smartdevicelink/streaming/IStreamListener.java
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/streaming/audio b/baseAndroid/src/main/java/com/smartdevicelink/streaming/audio new file mode 120000 index 000000000..b91099bd1 --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/streaming/audio @@ -0,0 +1 @@ +../../../../../../../base/src/main/java/com/smartdevicelink/streaming/audio/
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/streaming/video/RTPH264Packetizer.java b/baseAndroid/src/main/java/com/smartdevicelink/streaming/video/RTPH264Packetizer.java new file mode 120000 index 000000000..1eec0a104 --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/streaming/video/RTPH264Packetizer.java @@ -0,0 +1 @@ +../../../../../../../../base/src/main/java/com/smartdevicelink/streaming/video/RTPH264Packetizer.java
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/streaming/video/VideoStreamingParameters.java b/baseAndroid/src/main/java/com/smartdevicelink/streaming/video/VideoStreamingParameters.java new file mode 120000 index 000000000..8b18e72b2 --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/streaming/video/VideoStreamingParameters.java @@ -0,0 +1 @@ +../../../../../../../../base/src/main/java/com/smartdevicelink/streaming/video/VideoStreamingParameters.java
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/trace/DiagLevel.java b/baseAndroid/src/main/java/com/smartdevicelink/trace/DiagLevel.java new file mode 120000 index 000000000..1bc9b65d1 --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/trace/DiagLevel.java @@ -0,0 +1 @@ +../../../../../../../base/src/main/java/com/smartdevicelink/trace/DiagLevel.java
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/trace/ISTListener.java b/baseAndroid/src/main/java/com/smartdevicelink/trace/ISTListener.java new file mode 120000 index 000000000..2ac262989 --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/trace/ISTListener.java @@ -0,0 +1 @@ +../../../../../../../base/src/main/java/com/smartdevicelink/trace/ISTListener.java
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/trace/Mime.java b/baseAndroid/src/main/java/com/smartdevicelink/trace/Mime.java new file mode 120000 index 000000000..8dc93a328 --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/trace/Mime.java @@ -0,0 +1 @@ +../../../../../../../base/src/main/java/com/smartdevicelink/trace/Mime.java
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/trace/OpenRPCMessage.java b/baseAndroid/src/main/java/com/smartdevicelink/trace/OpenRPCMessage.java new file mode 120000 index 000000000..8d7260eb5 --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/trace/OpenRPCMessage.java @@ -0,0 +1 @@ +../../../../../../../base/src/main/java/com/smartdevicelink/trace/OpenRPCMessage.java
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/trace/enums b/baseAndroid/src/main/java/com/smartdevicelink/trace/enums new file mode 120000 index 000000000..6c0343907 --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/trace/enums @@ -0,0 +1 @@ +../../../../../../../base/src/main/java/com/smartdevicelink/trace/enums/
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/transport/BaseTransportConfig.java b/baseAndroid/src/main/java/com/smartdevicelink/transport/BaseTransportConfig.java new file mode 120000 index 000000000..92effaf36 --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/transport/BaseTransportConfig.java @@ -0,0 +1 @@ +../../../../../../../base/src/main/java/com/smartdevicelink/transport/BaseTransportConfig.java
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/transport/ITransportListener.java b/baseAndroid/src/main/java/com/smartdevicelink/transport/ITransportListener.java new file mode 120000 index 000000000..587a7a3de --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/transport/ITransportListener.java @@ -0,0 +1 @@ +../../../../../../../base/src/main/java/com/smartdevicelink/transport/ITransportListener.java
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/transport/SdlPsm.java b/baseAndroid/src/main/java/com/smartdevicelink/transport/SdlPsm.java new file mode 120000 index 000000000..22d69d1cd --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/transport/SdlPsm.java @@ -0,0 +1 @@ +../../../../../../../base/src/main/java/com/smartdevicelink/transport/SdlPsm.java
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/transport/SdlTransport.java b/baseAndroid/src/main/java/com/smartdevicelink/transport/SdlTransport.java new file mode 120000 index 000000000..2fb44bcf3 --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/transport/SdlTransport.java @@ -0,0 +1 @@ +../../../../../../../base/src/main/java/com/smartdevicelink/transport/SdlTransport.java
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/transport/SiphonServer.java b/baseAndroid/src/main/java/com/smartdevicelink/transport/SiphonServer.java new file mode 120000 index 000000000..b28f2965d --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/transport/SiphonServer.java @@ -0,0 +1 @@ +../../../../../../../base/src/main/java/com/smartdevicelink/transport/SiphonServer.java
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/transport/TransportConstants.java b/baseAndroid/src/main/java/com/smartdevicelink/transport/TransportConstants.java new file mode 120000 index 000000000..61f953de2 --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/transport/TransportConstants.java @@ -0,0 +1 @@ +../../../../../../../base/src/main/java/com/smartdevicelink/transport/TransportConstants.java
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/transport/TransportManagerBase.java b/baseAndroid/src/main/java/com/smartdevicelink/transport/TransportManagerBase.java new file mode 120000 index 000000000..f89613939 --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/transport/TransportManagerBase.java @@ -0,0 +1 @@ +../../../../../../../base/src/main/java/com/smartdevicelink/transport/TransportManagerBase.java
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/transport/enums b/baseAndroid/src/main/java/com/smartdevicelink/transport/enums new file mode 120000 index 000000000..c5b0467f6 --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/transport/enums @@ -0,0 +1 @@ +../../../../../../../base/src/main/java/com/smartdevicelink/transport/enums/
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/transport/utl/TransportRecord.java b/baseAndroid/src/main/java/com/smartdevicelink/transport/utl/TransportRecord.java new file mode 120000 index 000000000..6fec751ec --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/transport/utl/TransportRecord.java @@ -0,0 +1 @@ +../../../../../../../../base/src/main/java/com/smartdevicelink/transport/utl/TransportRecord.java
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/util/BitConverter.java b/baseAndroid/src/main/java/com/smartdevicelink/util/BitConverter.java new file mode 120000 index 000000000..ace3985f9 --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/util/BitConverter.java @@ -0,0 +1 @@ +../../../../../../../base/src/main/java/com/smartdevicelink/util/BitConverter.java
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/util/ByteEnumer.java b/baseAndroid/src/main/java/com/smartdevicelink/util/ByteEnumer.java new file mode 120000 index 000000000..8cc7d9ac8 --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/util/ByteEnumer.java @@ -0,0 +1 @@ +../../../../../../../base/src/main/java/com/smartdevicelink/util/ByteEnumer.java
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/util/CorrelationIdGenerator.java b/baseAndroid/src/main/java/com/smartdevicelink/util/CorrelationIdGenerator.java new file mode 120000 index 000000000..4d9cfea49 --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/util/CorrelationIdGenerator.java @@ -0,0 +1 @@ +../../../../../../../base/src/main/java/com/smartdevicelink/util/CorrelationIdGenerator.java
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/util/DebugTool.java b/baseAndroid/src/main/java/com/smartdevicelink/util/DebugTool.java new file mode 120000 index 000000000..2c9f91906 --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/util/DebugTool.java @@ -0,0 +1 @@ +../../../../../../../base/src/main/java/com/smartdevicelink/util/DebugTool.java
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/util/HttpRequestTask.java b/baseAndroid/src/main/java/com/smartdevicelink/util/HttpRequestTask.java new file mode 120000 index 000000000..1733992ae --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/util/HttpRequestTask.java @@ -0,0 +1 @@ +../../../../../../../base/src/main/java/com/smartdevicelink/util/HttpRequestTask.java
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/util/IConsole.java b/baseAndroid/src/main/java/com/smartdevicelink/util/IConsole.java new file mode 120000 index 000000000..2cf061029 --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/util/IConsole.java @@ -0,0 +1 @@ +../../../../../../../base/src/main/java/com/smartdevicelink/util/IConsole.java
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/util/NativeLogTool.java b/baseAndroid/src/main/java/com/smartdevicelink/util/NativeLogTool.java new file mode 120000 index 000000000..3e1645508 --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/util/NativeLogTool.java @@ -0,0 +1 @@ +../../../../../../../base/src/main/java/com/smartdevicelink/util/NativeLogTool.java
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/util/SdlDataTypeConverter.java b/baseAndroid/src/main/java/com/smartdevicelink/util/SdlDataTypeConverter.java new file mode 120000 index 000000000..d44a2b6e0 --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/util/SdlDataTypeConverter.java @@ -0,0 +1 @@ +../../../../../../../base/src/main/java/com/smartdevicelink/util/SdlDataTypeConverter.java
\ No newline at end of file diff --git a/baseAndroid/src/main/java/com/smartdevicelink/util/Version.java b/baseAndroid/src/main/java/com/smartdevicelink/util/Version.java new file mode 120000 index 000000000..e21ea0440 --- /dev/null +++ b/baseAndroid/src/main/java/com/smartdevicelink/util/Version.java @@ -0,0 +1 @@ +../../../../../../../base/src/main/java/com/smartdevicelink/util/Version.java
\ No newline at end of file diff --git a/javaEE/build.gradle b/javaEE/build.gradle index 7eec15c81..7d8a433e7 100644 --- a/javaEE/build.gradle +++ b/javaEE/build.gradle @@ -3,7 +3,7 @@ plugins { } group 'com.smartdevicelink' -version '1.0' +version '4.7.2' sourceCompatibility = 1.8 diff --git a/javaSE/build.gradle b/javaSE/build.gradle index 264be4bf6..1477d9094 100644 --- a/javaSE/build.gradle +++ b/javaSE/build.gradle @@ -3,7 +3,7 @@ plugins { } group 'com.smartdevicelink' -version '1.0' +version '4.7.2' sourceCompatibility = 1.8 @@ -35,3 +35,18 @@ jar { } } +task generateSources { + File outputDir = file("$buildDir/../src/main/java/com/smartdevicelink/") + outputs.dir outputDir + doFirst { + def srcFile = new File(outputDir, "BuildConfig.java") + srcFile.parentFile.mkdirs() + srcFile.write( +"""package com.smartdevicelink; + +public final class BuildConfig { + public static final String VERSION_NAME = "$project.version"; +}""") + } +} +compileJava.dependsOn generateSources
\ No newline at end of file diff --git a/javaSE/src/main/java/com/smartdevicelink/BuildConfig.java b/javaSE/src/main/java/com/smartdevicelink/BuildConfig.java new file mode 100644 index 000000000..52a8868e7 --- /dev/null +++ b/javaSE/src/main/java/com/smartdevicelink/BuildConfig.java @@ -0,0 +1,5 @@ +package com.smartdevicelink; + +public final class BuildConfig { + public static final String VERSION_NAME = "4.7.2"; +}
\ No newline at end of file diff --git a/javaSE/src/main/java/com/smartdevicelink/managers/SdlManager.java b/javaSE/src/main/java/com/smartdevicelink/managers/SdlManager.java index 8d3791b94..83b988cc5 100644 --- a/javaSE/src/main/java/com/smartdevicelink/managers/SdlManager.java +++ b/javaSE/src/main/java/com/smartdevicelink/managers/SdlManager.java @@ -12,7 +12,6 @@ import com.smartdevicelink.protocol.enums.FunctionID; import com.smartdevicelink.protocol.enums.SessionType; import com.smartdevicelink.proxy.RPCMessage; import com.smartdevicelink.proxy.RPCRequest; -import com.smartdevicelink.proxy.RPCStreamController; import com.smartdevicelink.proxy.SystemCapabilityManager; import com.smartdevicelink.proxy.callbacks.OnServiceEnded; import com.smartdevicelink.proxy.callbacks.OnServiceNACKed; @@ -397,174 +396,6 @@ public class SdlManager extends BaseSdlManager{ return null; } - /* ******************************************************************************************************* - ************************************* FileStream Methods - START **************************************** - *********************************************************************************************************/ - - /** - * Used to push a binary stream of file data onto the module from a mobile device. - * - * @param inputStream The input stream of byte data that will be read from. - * @param fileName The SDL file reference name used by the RPC. - * @param offset The data offset in bytes. A value of zero is used to - * indicate data starting from the beginning of the file and a value greater - * than zero is used for resuming partial data chunks. - * @param length The total length of the file being sent. - */ - public void putFileStream(InputStream inputStream, @NonNull String fileName, Long offset, Long length) { - if (proxy != null){ - proxy.putFileStream(inputStream, fileName, offset, length); - } - } - - /** - * Used to push a binary stream of file data onto the module from a mobile device. - * - * @param inputStream The input stream of byte data that will be read from. - * @param fileName The SDL file reference name used by the RPC. - * @param offset The data offset in bytes. A value of zero is used to - * indicate data starting from the beginning of the file and a value greater - * than zero is used for resuming partial data chunks. - * @param length The total length of the file being sent. - * @param fileType The selected file type. See the {@link FileType} enum for - * details. - * @param isPersistentFile Indicates if the file is meant to persist between - * sessions / ignition cycles. - * @param isSystemFile Indicates if the file is meant to be passed through - * core to elsewhere in the system. - */ - public void putFileStream(InputStream inputStream, @NonNull String fileName, Long offset, Long length, FileType fileType, Boolean isPersistentFile, Boolean isSystemFile, OnPutFileUpdateListener cb) { - if (proxy != null){ - proxy.putFileStream(inputStream, fileName, offset, length, fileType, isPersistentFile, isSystemFile, cb); - } - } - - - /** - * Used to push a binary stream of file data onto the module from a mobile device. - * - * @param fileName The SDL file reference name used by the RPC. - * @param offset The data offset in bytes. A value of zero is used to - * indicate data starting from the beginning of the file and a value greater - * than zero is used for resuming partial data chunks. - * @param length The total length of the file being sent. - */ - public OutputStream putFileStream(@NonNull String fileName, Long offset, Long length) { - if (proxy != null){ - return proxy.putFileStream(fileName, offset, length); - } - return null; - } - - /** - * Used to push a binary stream of file data onto the module from a mobile device. - * - * @param fileName The SDL file reference name used by the RPC. - * @param offset The data offset in bytes. A value of zero is used to - * indicate data starting from the beginning of the file and a value greater - * than zero is used for resuming partial data chunks. - * @param length The total length of the file being sent. - * @param fileType The selected file type. See the {@link FileType} enum for - * details. - * @param isPersistentFile Indicates if the file is meant to persist between - * sessions / ignition cycles. - * @param isSystemFile Indicates if the file is meant to be passed through - * core to elsewhere in the system. - */ - public OutputStream putFileStream(@NonNull String fileName, Long offset, Long length, FileType fileType, Boolean isPersistentFile, Boolean isSystemFile, OnPutFileUpdateListener cb) { - if (proxy != null){ - return proxy.putFileStream(fileName, offset, length, fileType, isPersistentFile, isSystemFile, cb); - } - return null; - } - - /** - * Used to push a binary stream of file data onto the module from a mobile device. - * - * @param path The physical file path on the mobile device. - * @param fileName The SDL file reference name used by the RPC. - * @param offset The data offset in bytes. A value of zero is used to - * indicate data starting from the beginning of the file and a value greater - * than zero is used for resuming partial data chunks. - * @param fileType The selected file type. See the {@link FileType} enum for - * details. - * @param isPersistentFile Indicates if the file is meant to persist between - * sessions / ignition cycles. - * @param isSystemFile Indicates if the file is meant to be passed through - * core to elsewhere in the system. - * @param correlationId A unique id that correlates each RPCRequest and - * RPCResponse. - * @return RPCStreamController If the putFileStream was not started - * successfully null is returned, otherwise a valid object reference is - * returned . - */ - public RPCStreamController putFileStream(String path, @NonNull String fileName, Long offset, @NonNull FileType fileType, Boolean isPersistentFile, Boolean isSystemFile, Boolean isPayloadProtected, Integer correlationId, OnPutFileUpdateListener cb) { - if (proxy != null){ - return proxy.putFileStream(path, fileName, offset, fileType, isPersistentFile, isSystemFile, isPayloadProtected, correlationId, cb); - } - return null; - } - - /** - * Used to push a binary stream of file data onto the module from a mobile device. - * - * @param inputStream The input stream of byte data that will be read from. - * @param fileName The SDL file reference name used by the RPC. - * @param offset The data offset in bytes. A value of zero is used to - * indicate data starting from the beginning of the file and a value greater - * than zero is used for resuming partial data chunks. - * @param length The total length of the file being sent. - * @param fileType The selected file type. See the {@link FileType} enum for - * details. - * @param isPersistentFile Indicates if the file is meant to persist between - * sessions / ignition cycles. - * @param isSystemFile Indicates if the file is meant to be passed through - * core to elsewhere in the system. - * @param correlationId A unique id that correlates each RPCRequest and - * RPCResponse. - */ - public RPCStreamController putFileStream(InputStream inputStream, @NonNull String fileName, Long offset, Long length, @NonNull FileType fileType, Boolean isPersistentFile, Boolean isSystemFile, Boolean isPayloadProtected, Integer correlationId) { - if (proxy != null){ - return proxy.putFileStream(inputStream, fileName, offset, length, fileType, isPersistentFile, isSystemFile, isPayloadProtected, correlationId); - } - return null; - - } - - /** - * Used to end an existing putFileStream that was previously initiated with any putFileStream method. - */ - public void endPutFileStream() { - if (proxy != null){ - proxy.endPutFileStream(); - } - } - - public void endRPCStream() { - if (proxy != null){ - proxy.endRPCStream(); - } - } - - public boolean startRPCStream(InputStream is, RPCRequest msg) { - if (proxy != null){ - return proxy.startRPCStream(is, msg); - } - return false; - } - - public OutputStream startRPCStream(RPCRequest msg) { - if (proxy != null){ - return proxy.startRPCStream(msg); - } - return null; - } - - /* ******************************************************************************************************* - ************************************** FileStream Methods - END ***************************************** - *********************************************************************************************************/ - - // PROTECTED GETTERS protected String getAppName() { return appName; } @@ -826,6 +657,13 @@ public class SdlManager extends BaseSdlManager{ } @Override + public void sendRPC(RPCMessage message) { + if(message != null){ + proxy.sendRpc(message); + } + } + + @Override public void sendRequests(List<? extends RPCRequest> rpcs, OnMultipleRequestListener listener) { proxy.sendRpcs(rpcs, listener); } @@ -888,7 +726,7 @@ public class SdlManager extends BaseSdlManager{ @Override public SdlMsgVersion getSdlMsgVersion(){ //FIXME this should be a breaking change to support our version - Version rpcSepcVersion = proxy.getRpcSepcVersion(); + Version rpcSepcVersion = proxy.getRpcSpecVersion(); if(rpcSepcVersion != null){ SdlMsgVersion sdlMsgVersion = new SdlMsgVersion(); sdlMsgVersion.setMajorVersion(rpcSepcVersion.getMajor()); diff --git a/javaSE/src/main/java/com/smartdevicelink/managers/lifecycle/LifecycleManager.java b/javaSE/src/main/java/com/smartdevicelink/managers/lifecycle/LifecycleManager.java index 81933e588..7ea248101 100644 --- a/javaSE/src/main/java/com/smartdevicelink/managers/lifecycle/LifecycleManager.java +++ b/javaSE/src/main/java/com/smartdevicelink/managers/lifecycle/LifecycleManager.java @@ -17,7 +17,6 @@ import com.smartdevicelink.proxy.rpc.*; import com.smartdevicelink.proxy.rpc.enums.*; import com.smartdevicelink.proxy.rpc.listeners.*; import com.smartdevicelink.security.SdlSecurityBase; -import com.smartdevicelink.streaming.StreamRPCPacketizer; import com.smartdevicelink.streaming.audio.AudioStreamingCodec; import com.smartdevicelink.streaming.audio.AudioStreamingParams; import com.smartdevicelink.streaming.video.VideoStreamingParameters; @@ -112,7 +111,7 @@ public class LifecycleManager extends BaseLifecycleManager { } return new Version(1,0,0); } - public Version getRpcSepcVersion(){ + public Version getRpcSpecVersion(){ return rpcSpecVersion; } @@ -649,6 +648,12 @@ public class LifecycleManager extends BaseLifecycleManager { } + + @Override + public void onAuthTokenReceived(String token, byte sessionID) { + + } + /* ******************************************************************************************************* *************************************** ISdlConnectionListener END ************************************ *********************************************************************************************************/ @@ -726,6 +731,11 @@ public class LifecycleManager extends BaseLifecycleManager { } @Override + public void sendRPC(RPCMessage message) { + LifecycleManager.this.sendRPCMessagePrivate(message); + } + + @Override public void sendRequests(List<? extends RPCRequest> rpcs, OnMultipleRequestListener listener) { //FIXME } @@ -941,242 +951,4 @@ public class LifecycleManager extends BaseLifecycleManager { } } } - - - /* ******************************************************************************************************* - ************************************* FileStream Methods - START **************************************** - *********************************************************************************************************/ - - /** - * Used to push a binary stream of file data onto the module from a mobile device. - * - * @param inputStream The input stream of byte data that will be read from. - * @param fileName The SDL file reference name used by the RPC. - * @param offset The data offset in bytes. A value of zero is used to - * indicate data starting from the beginning of the file and a value greater - * than zero is used for resuming partial data chunks. - * @param length The total length of the file being sent. - */ - public void putFileStream(InputStream inputStream, @NonNull String fileName, Long offset, Long length) { - PutFile msg = new PutFile(fileName, FileType.BINARY); - msg.setCorrelationID(10000); - msg.setSystemFile(true); - msg.setOffset(offset); - msg.setLength(length); - - startRPCStream(inputStream, msg); - } - - /** - * Used to push a binary stream of file data onto the module from a mobile device. - * - * @param inputStream The input stream of byte data that will be read from. - * @param fileName The SDL file reference name used by the RPC. - * @param offset The data offset in bytes. A value of zero is used to - * indicate data starting from the beginning of the file and a value greater - * than zero is used for resuming partial data chunks. - * @param length The total length of the file being sent. - * @param fileType The selected file type. See the {@link FileType} enum for - * details. - * @param isPersistentFile Indicates if the file is meant to persist between - * sessions / ignition cycles. - * @param isSystemFile Indicates if the file is meant to be passed through - * core to elsewhere in the system. - */ - public void putFileStream(InputStream inputStream, @NonNull String fileName, Long offset, Long length, FileType fileType, Boolean isPersistentFile, Boolean isSystemFile, OnPutFileUpdateListener cb) { - PutFile msg = new PutFile(fileName, FileType.BINARY); - msg.setCorrelationID(10000); - msg.setSystemFile(true); - msg.setOffset(offset); - msg.setLength(length); - msg.setOnPutFileUpdateListener(cb); - startRPCStream(inputStream, msg); - } - - - /** - * Used to push a binary stream of file data onto the module from a mobile device. - * - * @param fileName The SDL file reference name used by the RPC. - * @param offset The data offset in bytes. A value of zero is used to - * indicate data starting from the beginning of the file and a value greater - * than zero is used for resuming partial data chunks. - * @param length The total length of the file being sent. - */ - public OutputStream putFileStream(@NonNull String fileName, Long offset, Long length) { - PutFile msg = new PutFile(fileName, FileType.BINARY); - msg.setCorrelationID(10000); - msg.setSystemFile(true); - msg.setOffset(offset); - msg.setLength(length); - - return startRPCStream(msg); - } - - /** - * Used to push a binary stream of file data onto the module from a mobile device. - * - * @param fileName The SDL file reference name used by the RPC. - * @param offset The data offset in bytes. A value of zero is used to - * indicate data starting from the beginning of the file and a value greater - * than zero is used for resuming partial data chunks. - * @param length The total length of the file being sent. - * @param fileType The selected file type. See the {@link FileType} enum for - * details. - * @param isPersistentFile Indicates if the file is meant to persist between - * sessions / ignition cycles. - * @param isSystemFile Indicates if the file is meant to be passed through - * core to elsewhere in the system. - */ - public OutputStream putFileStream(@NonNull String fileName, Long offset, Long length, FileType fileType, Boolean isPersistentFile, Boolean isSystemFile, OnPutFileUpdateListener cb) { - PutFile msg = new PutFile(fileName, FileType.BINARY); - msg.setCorrelationID(10000); - msg.setSystemFile(true); - msg.setOffset(offset); - msg.setLength(length); - msg.setOnPutFileUpdateListener(cb); - - return startRPCStream(msg); - } - - /** - * Used to push a binary stream of file data onto the module from a mobile device. - * - * @param path The physical file path on the mobile device. - * @param fileName The SDL file reference name used by the RPC. - * @param offset The data offset in bytes. A value of zero is used to - * indicate data starting from the beginning of the file and a value greater - * than zero is used for resuming partial data chunks. - * @param fileType The selected file type. See the {@link FileType} enum for - * details. - * @param isPersistentFile Indicates if the file is meant to persist between - * sessions / ignition cycles. - * @param isSystemFile Indicates if the file is meant to be passed through - * core to elsewhere in the system. - * @param correlationId A unique id that correlates each RPCRequest and - * RPCResponse. - * @return RPCStreamController If the putFileStream was not started - * successfully null is returned, otherwise a valid object reference is - * returned . - */ - public RPCStreamController putFileStream(String path, @NonNull String fileName, Long offset, @NonNull FileType fileType, Boolean isPersistentFile, Boolean isSystemFile, Boolean isPayloadProtected, Integer correlationId, OnPutFileUpdateListener cb) { - PutFile msg = new PutFile(fileName, fileType); - msg.setCorrelationID(correlationId); - msg.setPersistentFile(isPersistentFile); - msg.setSystemFile(isSystemFile); - msg.setOffset(offset); - msg.setLength(0L); - msg.setPayloadProtected(isPayloadProtected); - msg.setOnPutFileUpdateListener(cb); - - if (session == null) return null; - - FileInputStream is = null; - try { - is = new FileInputStream(path); - } catch (IOException e1) { - e1.printStackTrace(); - } - - - if (is == null) return null; - - Long lSize = null; - - try { - lSize = is.getChannel().size(); - } catch (IOException e) { - e.printStackTrace(); - } - - if (lSize == null) { - try { - is.close(); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - try { - StreamRPCPacketizer rpcPacketizer = new StreamRPCPacketizer(this, session, is, msg, SessionType.RPC, session.getSessionId(), getProtocolVersion(), rpcSpecVersion, lSize, session); - rpcPacketizer.start(); - return new RPCStreamController(rpcPacketizer, msg.getCorrelationID()); - } catch (Exception e) { - Log.e("SyncConnection", "Unable to start streaming:" + e.toString()); - return null; - } - } - - /** - * Used to push a binary stream of file data onto the module from a mobile device. - * - * @param inputStream The input stream of byte data that will be read from. - * @param fileName The SDL file reference name used by the RPC. - * @param offset The data offset in bytes. A value of zero is used to - * indicate data starting from the beginning of the file and a value greater - * than zero is used for resuming partial data chunks. - * @param length The total length of the file being sent. - * @param fileType The selected file type. See the {@link FileType} enum for - * details. - * @param isPersistentFile Indicates if the file is meant to persist between - * sessions / ignition cycles. - * @param isSystemFile Indicates if the file is meant to be passed through - * core to elsewhere in the system. - * @param correlationId A unique id that correlates each RPCRequest and - * RPCResponse. - */ - public RPCStreamController putFileStream(InputStream inputStream, @NonNull String fileName, Long offset, Long length, @NonNull FileType fileType, Boolean isPersistentFile, Boolean isSystemFile, Boolean isPayloadProtected, Integer correlationId) { - PutFile msg = new PutFile(fileName, fileType); - msg.setCorrelationID(correlationId); - msg.setPersistentFile(isPersistentFile); - msg.setSystemFile(isSystemFile); - msg.setOffset(offset); - msg.setLength(length); - msg.setPayloadProtected(isPayloadProtected); - - if (session == null) return null; - Long lSize = msg.getLength(); - - if (lSize == null) { - return null; - } - - try { - StreamRPCPacketizer rpcPacketizer = new StreamRPCPacketizer(this, session, inputStream, msg, SessionType.RPC, session.getSessionId(), getProtocolVersion(), rpcSpecVersion, lSize, session); - rpcPacketizer.start(); - return new RPCStreamController(rpcPacketizer, msg.getCorrelationID()); - } catch (Exception e) { - Log.e("SyncConnection", "Unable to start streaming:" + e.toString()); - return null; - } - } - - /** - * Used to end an existing putFileStream that was previously initiated with any putFileStream method. - */ - public void endPutFileStream() { - endRPCStream(); - } - - public void endRPCStream() { - if (this.session == null) return; - session.stopRPCStream(); - } - - public boolean startRPCStream(InputStream is, RPCRequest msg) { - if (session == null) return false; - session.startRPCStream(is, msg, SessionType.RPC, session.getSessionId(), (byte) getProtocolVersion().getMajor()); - return true; - } - - public OutputStream startRPCStream(RPCRequest msg) { - if (session == null) return null; - return session.startRPCStream(msg, SessionType.RPC, session.getSessionId(), (byte) getProtocolVersion().getMajor()); - } - - /* ******************************************************************************************************* - ************************************** FileStream Methods - END ***************************************** - *********************************************************************************************************/ - } |