diff --git a/app/build.gradle b/app/build.gradle index b99a779..ac7d2f1 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -1,22 +1,19 @@ apply plugin: 'com.android.application' -apply plugin: 'me.tatarka.retrolambda' android { - compileSdkVersion 24 - buildToolsVersion "24.0.0" + compileSdkVersion 27 + buildToolsVersion "27.0.3" + defaultConfig { applicationId "com.dataart.obd2" - minSdkVersion 18 - targetSdkVersion 24 + minSdkVersion 19 + targetSdkVersion 27 versionCode 1 versionName "0.1" - multiDexEnabled true } - dexOptions { - javaMaxHeapSize "4g" - } + buildTypes { release { minifyEnabled false @@ -27,20 +24,43 @@ android { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } - useLibrary 'org.apache.http.legacy' +} + +ext { + devicehive = "3.1.2" + commons = "1.11" + rxandroid = "2.0.1" + rxjava = "2.1.7" + guava = "23.6-android" + gson = "2.8.2" + timber = "4.6.0" + support = "27.0.2" + gms = "11.8.0" + multidex = "1.0.2" } dependencies { - compile fileTree(dir: 'libs', include: ['*.jar']) - compile 'com.android.support:appcompat-v7:24.0.0' - compile 'com.android.support:design:24.0.0' - compile 'com.google.code.gson:gson:2.4' - compile 'com.jakewharton.timber:timber:2.7.1' - provided "org.projectlombok:lombok:1.12.6" - compile 'commons-codec:commons-codec:1.5' - compile 'com.google.android.gms:play-services:9.0.2' - compile 'io.reactivex:rxandroid:1.1.0' - compile 'com.google.guava:guava:19.0' - - compile 'com.android.support:multidex:1.0.1' + implementation fileTree(dir: 'libs', include: ['*.jar']) + + implementation "com.android.support:appcompat-v7:${support}" + implementation "com.android.support:design:${support}" + + implementation "com.google.code.gson:gson:${gson}" + + implementation "com.jakewharton.timber:timber:${timber}" + + implementation "commons-codec:commons-codec:${commons}" + + implementation "io.reactivex.rxjava2:rxandroid:${rxandroid}" + // Because RxAndroid releases are few and far between, it is recommended you also + // explicitly depend on RxJava's latest version for bug fixes and new features. + implementation "io.reactivex.rxjava2:rxjava:${rxjava}" + + implementation "com.google.android.gms:play-services-location:${gms}" + + implementation "com.google.guava:guava:${guava}" + + implementation "com.github.devicehive:devicehive-java:${devicehive}" + implementation "com.android.support:multidex:${multidex}" + } diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index a87ef4b..e3551d1 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -1,9 +1,9 @@ + package="com.dataart.obd2"> - - + + @@ -18,24 +18,16 @@ + android:windowSoftInputMode="stateHidden"> - - - - - + android:name=".obd2_gateway.OBD2Service" + android:enabled="true" /> diff --git a/app/src/main/java/com/dataart/android/devicehive/ApiInfo.java b/app/src/main/java/com/dataart/android/devicehive/ApiInfo.java deleted file mode 100644 index f6d66cc..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/ApiInfo.java +++ /dev/null @@ -1,90 +0,0 @@ -package com.dataart.android.devicehive; - -import android.os.Parcel; -import android.os.Parcelable; - -/** - * Represents meta-information about the current API. - */ -public class ApiInfo implements Parcelable { - private String apiVersion; - private String serverTimestamp; - private String webSocketServerUrl; - - /** - * Constructs API info object with given parameters. - * - * @param apiVersion - * API version. - * @param serverTimestamp - * Current server timestamp. - * @param webSocketServerUrl - * WebSocket server URL. - */ - public ApiInfo(String apiVersion, String serverTimestamp, - String webSocketServerUrl) { - this.apiVersion = apiVersion; - this.serverTimestamp = serverTimestamp; - this.webSocketServerUrl = webSocketServerUrl; - } - - /** - * Get API version. - * - * @return API version string. - */ - public String getApiVersion() { - return apiVersion; - } - - /** - * Get current server timestamp. - * - * @return Network key. - */ - public String getServerTimestamp() { - return serverTimestamp; - } - - /** - * Get WebSocket server URL. - * - * @return WebSocket server URL. - */ - public String getWebSocketServerUrl() { - return webSocketServerUrl; - } - - @Override - public int describeContents() { - return 0; - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - dest.writeString(apiVersion); - dest.writeString(serverTimestamp); - dest.writeString(webSocketServerUrl); - } - - public static Creator CREATOR = new Creator() { - - @Override - public ApiInfo[] newArray(int size) { - return new ApiInfo[size]; - } - - @Override - public ApiInfo createFromParcel(Parcel source) { - return new ApiInfo(source.readString(), source.readString(), - source.readString()); - } - }; - - @Override - public String toString() { - return "ApiInfo [apiVersion=" + apiVersion + ", serverTimestamp=" - + serverTimestamp + ", webSocketServerUrl=" - + webSocketServerUrl + "]"; - } -} diff --git a/app/src/main/java/com/dataart/android/devicehive/Command.java b/app/src/main/java/com/dataart/android/devicehive/Command.java deleted file mode 100644 index a31779f..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/Command.java +++ /dev/null @@ -1,192 +0,0 @@ -package com.dataart.android.devicehive; - -import java.io.Serializable; - -import android.os.Parcel; -import android.os.Parcelable; - -import com.dataart.android.devicehive.device.CommandResult; - -/** - * Represents a device command, a unit of information sent to devices. - */ -public class Command implements Parcelable { - private int id; - private String timestamp; - private String command; - private ObjectWrapper parameters; - private int lifetime; - private int flags; - private String status; - private String result; - private UpdateCommandStatusCallback commandStatusCallback; - - public void setCommandStatusCallback(UpdateCommandStatusCallback commandStatusCallback) { - this.commandStatusCallback = commandStatusCallback; - } - -// called from place where command status updated - public UpdateCommandStatusCallback getCommandStatusCallback() { - return commandStatusCallback; - } - - /* package */Command(int id, String timestamp, String command, - Serializable parameters, int lifetime, int flags, String status, - String result) { - this.id = id; - this.timestamp = timestamp; - this.command = command; - this.parameters = new ObjectWrapper(parameters); - this.lifetime = lifetime; - this.flags = flags; - this.status = status; - this.result = result; - } - - public Command(String command, Serializable parameters, int lifetime, - int flags) { - this(-1, null, command, parameters, lifetime, flags, null, null); - } - - /** - * Create command with given name and parameters. - * - * @param command - * Command name. - * @param parameters - * Parameters dictionary. - */ - public Command(String command, Serializable parameters) { - this(-1, null, command, parameters, 0, 0, null, null); - } - - /** - * Get command identifier. - * - * @return Command identifier set by the server. - */ - public int getId() { - return id; - } - - /** - * Get command timestamp (UTC). - * - * @return Datetime timestamp associated with this command. - */ - public String getTimestamp() { - return timestamp; - } - - /** - * Get command name. - * - * @return Command name. - */ - public String getCommand() { - return command; - } - - /** - * Get command parameters dictionary. - * - * @return Command parameters dictionary. - */ - public Serializable getParameters() { - return parameters != null ? parameters.getObject() : null; - } - - /** - * Get command lifetime. - * - * @return Number of seconds until this command expires. - */ - public int getLifetime() { - return lifetime; - } - - /** - * Get command flags. It's optional. - * - * @return Value that could be supplied for device or related - * infrastructure. - */ - public int getFlags() { - return flags; - } - - /** - * Get command status, as reported by device or related infrastructure. - * - * @return Command status. - */ - public String getStatus() { - return status; - } - - /** - * Get command execution result. It's optional value that could be provided - * by device. - * - * @return Command execution result. - */ - public String getResult() { - return result; - } - - @Override - public int describeContents() { - return 0; - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - dest.writeInt(id); - dest.writeString(timestamp); - dest.writeString(command); - dest.writeSerializable(parameters != null ? parameters.getObject() - : parameters); - dest.writeInt(lifetime); - dest.writeInt(flags); - dest.writeString(status); - dest.writeString(result); - } - - public static Creator CREATOR = new Creator() { - - @Override - public Command[] newArray(int size) { - return new Command[size]; - } - - @Override - public Command createFromParcel(Parcel source) { - return new Command(source.readInt(), source.readString(), - source.readString(), source.readSerializable(), - source.readInt(), source.readInt(), source.readString(), - source.readString()); - } - }; - - @Override - public String toString() { - return "Command [id=" + id + ", timestamp=" + timestamp + ", command=" - + command + ", parameters=" + parameters + ", lifetime=" - + lifetime + ", flags=" + flags + ", status=" + status - + ", result=" + result + "]"; - } - - abstract public static class UpdateCommandStatusCallback { - private Object tag; - - public Object getTag() { - return tag; - } - - public void setTag(Object tag) { - this.tag = tag; - } - - abstract public void call(CommandResult result); - } -} diff --git a/app/src/main/java/com/dataart/android/devicehive/DataContainer.java b/app/src/main/java/com/dataart/android/devicehive/DataContainer.java deleted file mode 100644 index a87fbae..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/DataContainer.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.dataart.android.devicehive; - -import java.io.Serializable; - -import android.os.Parcel; -import android.os.Parcelable; - -/* package */abstract class DataContainer implements Parcelable { - - protected ObjectWrapper data; - - protected DataContainer() { - this(null); - } - - protected DataContainer(Serializable data) { - setData(data); - } - - /** - * Set equipment data, an object with an arbitrary structure that can be - * serialized to JSON. Equipment data can only be set/changed before device - * registration. - * - * @param data - * An object that can be serialized to JSON. - */ - public void setData(Serializable data) { - this.data = new ObjectWrapper(data); - } - - /** - * Get device data. - * - * @return An object with arbitrary structure. Typically, an object is - * constructed using StringMaps, ArrayLists and primitives. - */ - public Object getData() { - return data != null ? data.getObject() : data; - } - - @Override - public int describeContents() { - return 0; - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - dest.writeSerializable(data != null ? data.getObject() : data); - } - -} diff --git a/app/src/main/java/com/dataart/android/devicehive/DeviceClass.java b/app/src/main/java/com/dataart/android/devicehive/DeviceClass.java deleted file mode 100644 index e3a77e7..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/DeviceClass.java +++ /dev/null @@ -1,126 +0,0 @@ -package com.dataart.android.devicehive; - -import java.io.Serializable; - -import android.os.Parcel; -import android.os.Parcelable; - -/** - * Represents a device class which holds meta-information about {@link Client}s. - */ -public class DeviceClass extends DataContainer { - private String name; - private String version; - private boolean isPermanent; - private Integer offlineTimeout; - - /** - * Construct a new device class with given parameters. This method is - * intended for internal use. - * - * @param name - * Device class display name. - * @param version - * Device class version. - * @param isPermanent - * Whether this device class is permanent. - * @param offlineTimeout - * If set, specifies inactivity timeout in seconds before the - * framework changes device status to "Offline". - */ - public DeviceClass(String name, String version, - boolean isPermanent, Integer offlineTimeout) { - this(null, name, version, isPermanent, offlineTimeout); - } - - /* package */DeviceClass(Serializable data, String name, - String version, boolean isPermanent, Integer offlineTimeout) { - super(data); - this.name = name; - this.version = version; - this.isPermanent = isPermanent; - this.offlineTimeout = offlineTimeout; - } - - /** - * Constructs a new device class with given parameters. - * - * @param name - * Device class display name. - * @param version - * Device class version. - */ - public DeviceClass(String name, String version) { - this(-1, name, version, false, null); - } - - /** - * Get device class display name. - * - * @return Device class display name. - */ - public String getName() { - return name; - } - - /** - * Get device class version. - * - * @return Device class version. - */ - public String getVersion() { - return version; - } - - /** - * Check whether the device class is permanent. Permanent device classes - * could not be modified by devices during registration. - * - * @return true if device class is permanent, otherwise returns false. - */ - public boolean isPermanent() { - return isPermanent; - } - - /** - * Get offline timeout. If set, specifies inactivity timeout in seconds - * before the framework changes device status to "Offline". - * - * @return Inactivity timeout value in seconds. - */ - public Integer getOfflineTimeout() { - return offlineTimeout; - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - super.writeToParcel(dest, flags); - dest.writeString(name); - dest.writeString(version); - dest.writeInt(isPermanent ? 1 : 0); - dest.writeValue(offlineTimeout); - } - - public static Parcelable.Creator CREATOR = new Parcelable.Creator() { - - @Override - public DeviceClass[] newArray(int size) { - return new DeviceClass[size]; - } - - @Override - public DeviceClass createFromParcel(Parcel source) { - return new DeviceClass(source.readSerializable(), - source.readString(), source.readString(), - source.readInt() > 0, (Integer) source.readValue(null)); - } - }; - - @Override - public String toString() { - return "DeviceClass [name=" + name + ", version=" - + version + ", isPermanent=" + isPermanent - + ", offlineTimeout=" + offlineTimeout + ", data=" + data + "]"; - } - -} diff --git a/app/src/main/java/com/dataart/android/devicehive/DeviceData.java b/app/src/main/java/com/dataart/android/devicehive/DeviceData.java deleted file mode 100644 index bde8fe3..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/DeviceData.java +++ /dev/null @@ -1,163 +0,0 @@ -package com.dataart.android.devicehive; - -import java.io.Serializable; -import java.util.LinkedList; -import java.util.List; - -import android.os.Parcel; -import android.os.Parcelable; - -/** - * Represents device data. - */ -public class DeviceData extends DataContainer { - - /** - * "Online" device status. - */ - public static final String DEVICE_STATUS_ONLINE = "Online"; - - /** - * "OK" device status. - */ - public static final String DEVICE_STATUS_OK = "OK"; - - private String id; - private String key; - private String name; - private String status; - private DeviceClass deviceClass; - - private final static ClassLoader CLASS_LOADER = DeviceData.class - .getClassLoader(); - - /** - * Construct device data with given parameters. - * - * @param id - * Device unique identifier. - * @param key - * Device authentication key. The key maximum length is 64 - * characters. - * @param name - * Device display name. - * @param status - * Device operation status. - * @param deviceClass - * Associated {@link DeviceClass}. - */ - public DeviceData(String id, String key, String name, String status, - DeviceClass deviceClass) { - this(null, id, key, name, status, deviceClass); - } - - /* package */DeviceData(Serializable data, String id, String key, - String name, String status, - DeviceClass deviceClass) { - super(data); - this.id = id; - this.key = key; - this.name = name; - this.status = status; - this.deviceClass = deviceClass; -// // FIXME: 10/15/15 netowrk and equipment are disabled since october update for DeviceHive Playground - } - - /** - * Get device identifier. - * - * @return Device identifier. - */ - public String getId() { - return id; - } - - /** - * Get device authentication key. - * - * @return Device authentication key. - */ - public String getKey() { - return key; - } - - /** - * Get device display name. - * - * @return Device display name. - */ - public String getName() { - return name; - } - - /** - * Get device status. - * - * @return Device status. - */ - public String getStatus() { - return status; - } - - /** - * Get device class. - * - * @return Associated {@link DeviceClass} object. - */ - public DeviceClass getDeviceClass() { - return deviceClass; - } - - /** - * Add equipment to the device. - * - * @param equipmentData - * Equipment to be added. - */ - public void addEquipment(EquipmentData equipmentData) { -// // FIXME: 10/15/15 empty stub - } - - @Override - public int describeContents() { - return 0; - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - super.writeToParcel(dest, flags); - dest.writeString(id); - dest.writeString(key); - dest.writeString(name); - dest.writeString(status); - dest.writeParcelable(deviceClass, 0); - } - - public static Parcelable.Creator CREATOR = new Parcelable.Creator() { - - @Override - public DeviceData[] newArray(int size) { - return new DeviceData[size]; - } - - @Override - public DeviceData createFromParcel(Parcel source) { - Serializable data = source.readSerializable(); - String id = source.readString(); - String key = source.readString(); - String name = source.readString(); - String status = source.readString(); - DeviceClass deviceClass = source.readParcelable(CLASS_LOADER); - return new DeviceData(data, id, key, name, status, deviceClass); - } - }; - - @Override - public String toString() { - return "DeviceData [id=" + id + ", key=" + key + ", name=" + name - + ", status=" + status - + ", deviceClass=" + deviceClass - + ", data=" + data + "]"; - } - -} diff --git a/app/src/main/java/com/dataart/android/devicehive/DeviceHive.java b/app/src/main/java/com/dataart/android/devicehive/DeviceHive.java deleted file mode 100644 index b6b43ab..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/DeviceHive.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.dataart.android.devicehive; - -/** - * Some declarations which are intended for internal use. - */ -public class DeviceHive { - /** - * Logging TAG. - */ - public final static String TAG = "DeviceHive"; -} diff --git a/app/src/main/java/com/dataart/android/devicehive/EquipmentData.java b/app/src/main/java/com/dataart/android/devicehive/EquipmentData.java deleted file mode 100644 index 45805a5..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/EquipmentData.java +++ /dev/null @@ -1,94 +0,0 @@ -package com.dataart.android.devicehive; - -import java.io.Serializable; - -import android.os.Parcel; -import android.os.Parcelable; - -import com.dataart.android.devicehive.device.Equipment; - -/** - * Represents equipment data. Used to initialize {@link com.dataart.android.devicehive.device.Equipment} object. - */ -public class EquipmentData extends DataContainer { - private String name; - private String code; - private String type; - - /** - * Construct equipment data with given name, code and type. - * - * @param name - * Equipment display name. - * @param code - * Equipment code. It's used to reference particular equipment - * and it should be unique within a device class. - * @param type - * Equipment type. An arbitrary string representing equipment - * capabilities. - */ - public EquipmentData(String name, String code, String type) { - this(null, name, code, type); - } - - /* package */EquipmentData(Serializable data, String name, - String code, String type) { - super(data); - this.name = name; - this.code = code; - this.type = type; - } - - /** - * Get equipment display name. - * - * @return Equipment display name. - */ - public String getName() { - return name; - } - - /** - * Get equipment code. It's used to reference particular equipment and it - * should be unique within a {@link com.dataart.android.devicehive.DeviceClass}. - * - * @return Equipment code. - */ - public String getCode() { - return code; - } - - /** - * Get equipment type. It's an arbitrary string representing equipment - * capabilities. - * - * @return Equipment type. - */ - public String getType() { - return type; - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - super.writeToParcel(dest, flags); - dest.writeString(name); - dest.writeString(code); - dest.writeString(type); - } - - public static Creator CREATOR = new Creator() { - - @Override - public EquipmentData[] newArray(int size) { - return new EquipmentData[size]; - } - - @Override - public EquipmentData createFromParcel(Parcel source) { - return new EquipmentData(source.readSerializable(), - source.readString(), source.readString(), - source.readString()); - } - }; - -} diff --git a/app/src/main/java/com/dataart/android/devicehive/EquipmentState.java b/app/src/main/java/com/dataart/android/devicehive/EquipmentState.java deleted file mode 100644 index c57c6ad..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/EquipmentState.java +++ /dev/null @@ -1,95 +0,0 @@ -package com.dataart.android.devicehive; - -import java.io.Serializable; - -import android.os.Parcel; -import android.os.Parcelable; - -import com.google.gson.annotations.SerializedName; - -/** - * Represents equipment state. - */ -public class EquipmentState implements Parcelable { - @SerializedName("id") - private String equipmentCode; - private String timestamp; - private ObjectWrapper parameters; - - /** - * Construct equipment state with given parameters. - * - * @param code - * Equipment code. - * @param timestamp - * @param parameters - */ - /* package */EquipmentState(String code, String timestamp, - Serializable parameters) { - this.equipmentCode = code; - this.timestamp = timestamp; - this.parameters = new ObjectWrapper(parameters); - } - - /** - * Get equipment code. - * - * @return Equipment code value. - */ - public String getEquipmentCode() { - return equipmentCode; - } - - /** - * Get equipment state timestamp. - * - * @return Equipment state timestamp. - */ - public String getTimestamp() { - return timestamp; - } - - /** - * Get current equipment state. - * - * @return Equipment state parameters. - */ - public Object getParameters() { - return parameters != null ? parameters.getObject() : parameters; - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - dest.writeString(equipmentCode); - dest.writeString(timestamp); - dest.writeSerializable(parameters != null ? parameters.getObject() - : parameters); - } - - public static Creator CREATOR = new Creator() { - - @Override - public EquipmentState[] newArray(int size) { - return new EquipmentState[size]; - } - - @Override - public EquipmentState createFromParcel(Parcel source) { - return new EquipmentState(source.readString(), source.readString(), - source.readSerializable()); - } - }; - - @Override - public int describeContents() { - return 0; - } - - @Override - public String toString() { - return String.format( - "EquipmentState(code = %s, timestamp = %s, parameters = %s)", - equipmentCode, timestamp, parameters); - } - -} diff --git a/app/src/main/java/com/dataart/android/devicehive/Network.java b/app/src/main/java/com/dataart/android/devicehive/Network.java deleted file mode 100644 index c015104..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/Network.java +++ /dev/null @@ -1,92 +0,0 @@ -package com.dataart.android.devicehive; - -import android.os.Parcel; -import android.os.Parcelable; - -/** - * Represents a network, an isolated area where {@link Client}s reside. - */ -public class Network implements Parcelable { - private String key; - private String name; - private String description; - - public Network(String key, String name, String description) { - this.key = key; - this.name = name; - this.description = description; - } - - /** - * Constructs network object with given name and description. - * - * @param name - * Network display name. - * @param description - * Network description. - */ - public Network(String name, String description) { - this(null, name, description); - } - - /** - * Get network key. Optional key that is used to protect the network from - * unauthorized device registrations. - * - * @return Network key. - */ - public String getKey() { - return key; - } - - /** - * Get network display name. - * - * @return Network display name. - */ - public String getName() { - return name; - } - - /** - * Get network description. - * - * @return Network description. - */ - public String getDescription() { - return description; - } - - @Override - public int describeContents() { - return 0; - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - dest.writeString(key); - dest.writeString(name); - dest.writeString(description); - } - - public static Creator CREATOR = new Creator() { - - @Override - public Network[] newArray(int size) { - return new Network[size]; - } - - @Override - public Network createFromParcel(Parcel source) { - return new Network(source.readString(), - source.readString(), source.readString()); - } - }; - - @Override - public String toString() { - return "Network [key=" + key + ", name=" + name - + ", description=" + description + "]"; - } - -} diff --git a/app/src/main/java/com/dataart/android/devicehive/Notification.java b/app/src/main/java/com/dataart/android/devicehive/Notification.java deleted file mode 100644 index eec51b3..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/Notification.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.dataart.android.devicehive; - -import java.io.Serializable; - -import android.os.Parcel; -import android.os.Parcelable; - -import com.google.gson.annotations.SerializedName; - -/** - * Represents a device notification, a unit of information dispatched from - * {@link Client}s. - */ -public class Notification implements Parcelable { - @SerializedName("notification") - private String name; - private String timestamp; - private ObjectWrapper parameters; - - protected Notification(String name, String timestamp, - Serializable parameters) { - this.name = name; - this.timestamp = timestamp; - this.parameters = new ObjectWrapper(parameters); - } - - /** - * Construct a new notification with given name and parameters. - * - * @param name - * Notification name. - * @param parameters - * Notification parameters. - */ - public Notification(String name, Serializable parameters) { - this(name, null, parameters); - } - - /** - * Get notification name. - * - * @return Notification name. - */ - public String getName() { - return name; - } - - /** - * Get notification timestamp(UTC). - * - * @return Notification timestamp(UTC). - */ - public String getTimestamp() { - return timestamp; - } - - /** - * Get notification parameters dictionary. - * - * @return Notification parameters dictionary. - */ - public Serializable getParameters() { - return parameters != null ? parameters.getObject() : parameters; - } - - @Override - public int describeContents() { - return 0; - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - dest.writeString(name); - dest.writeString(timestamp); - dest.writeSerializable(parameters != null ? parameters.getObject() - : parameters); - } - - public static Creator CREATOR = new Creator() { - - @Override - public Notification[] newArray(int size) { - return new Notification[size]; - } - - @Override - public Notification createFromParcel(Parcel source) { - return new Notification( source.readString(), - source.readString(), source.readSerializable()); - } - }; - - @Override - public String toString() { - return "Notification [name=" + name + ", timestamp=" - + timestamp + ", parameters=" + parameters + "]"; - } - -} diff --git a/app/src/main/java/com/dataart/android/devicehive/ObjectWrapper.java b/app/src/main/java/com/dataart/android/devicehive/ObjectWrapper.java deleted file mode 100644 index 6938f88..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/ObjectWrapper.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.dataart.android.devicehive; - -import java.io.Serializable; - -public class ObjectWrapper implements Serializable { - - private static final long serialVersionUID = -7373759268902337088L; - - private final T object; - - public ObjectWrapper(T object) { - this.object = object; - } - - public T getObject() { - return object; - } - - @Override - public String toString() { - if (object == null) { - return "" + object; - } else { - return object.toString(); - } - } - -} diff --git a/app/src/main/java/com/dataart/android/devicehive/client/ClientServiceConnection.java b/app/src/main/java/com/dataart/android/devicehive/client/ClientServiceConnection.java deleted file mode 100644 index a959126..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/client/ClientServiceConnection.java +++ /dev/null @@ -1,244 +0,0 @@ -package com.dataart.android.devicehive.client; - -import java.util.LinkedList; -import java.util.List; -import java.util.Queue; - -import android.content.Context; -import android.os.Bundle; -import android.util.Log; - -import com.dataart.android.devicehive.ApiInfo; -import com.dataart.android.devicehive.Command; -import com.dataart.android.devicehive.DeviceData; -import com.dataart.android.devicehive.DeviceHive; -import com.dataart.android.devicehive.Notification; -import com.dataart.android.devicehive.client.commands.GetDeviceCommand; -import com.dataart.android.devicehive.client.commands.NotificationsRetrivalCommand; -import com.dataart.android.devicehive.client.commands.PollDeviceNotificationsCommand; -import com.dataart.android.devicehive.client.commands.PollMultipleDeviceNotificationsCommand; -import com.dataart.android.devicehive.client.commands.SendDeviceCommandCommand; -import com.dataart.android.devicehive.commands.GetApiInfoCommand; -import com.dataart.android.devicehive.network.DeviceHiveResultReceiver; -import com.dataart.android.devicehive.network.NetworkCommand; -import com.dataart.android.devicehive.network.NetworkCommandConfig; -import com.dataart.android.devicehive.network.ServiceConnection; - -/* package */abstract class ClientServiceConnection extends ServiceConnection { - - private DeviceClient client; - - private final Queue notificationQueue = new LinkedList(); - - private boolean isReceivingNotifications = false; - - private boolean isPollRequestInProgress = false; - private String accessKey; - - private String lastNotificationPollTimestamp; - private Integer notificationPollWaitTimeout; - - public ClientServiceConnection(Context context) { - super(context); - } - - /* package */void setAuthorisation(String accessKey) { - this.accessKey=accessKey; - } - - /* package */void setLastNotificationPollTimestamp(String timestamp) { - this.lastNotificationPollTimestamp = timestamp; - } - - /* package */String getLastNotificationPollTimestamp() { - return lastNotificationPollTimestamp; - } - - /* package */void setNotificationPollWaitTimeout(Integer timeout) { - this.notificationPollWaitTimeout = timeout; - } - - /* package */void sendCommand(DeviceData deviceData, Command command) { - logD("Sending command: " + command.getCommand()); - client.onStartSendingCommand(command); - startNetworkCommand(new SendDeviceCommandCommand(deviceData.getId(), command)); - } - - /* package */void reloadDeviceData(DeviceData deviceData) { - startNetworkCommand(new GetDeviceCommand(deviceData.getId())); - } - - /* package */void startReceivingNotifications() { - if (isReceivingNotifications) { - stopReceivingNotifications(); - } - isReceivingNotifications = true; - handleNextNotification(); - } - - /* package */void stopReceivingNotifications() { - detachResultReceiver(); - isReceivingNotifications = false; - isPollRequestInProgress = false; - } - - /* package */void setClient(DeviceClient client) { - this.client = client; - } - - /* package */boolean isReceivingNotifications() { - return isReceivingNotifications; - } - - private void handleNotification(final Notification notification) { - if (client.shouldReceiveNotificationAsynchronously(notification)) { - asyncHandler.post(new Runnable() { - @Override - public void run() { - didReceiveNotification(notification); - mainThreadHandler.post(new Runnable() { - @Override - public void run() { - if (isReceivingNotifications) { - handleNextNotification(); - } - } - }); - } - }); - } else { - didReceiveNotification(notification); - if (isReceivingNotifications) { - handleNextNotification(); - } - } - } - - private void handleNextNotification() { - final Notification notification = notificationQueue.poll(); - if (notification != null) { - handleNotification(notification); - } else { - if (!isPollRequestInProgress) { - isPollRequestInProgress = true; - if (lastNotificationPollTimestamp == null) { - // timestamp wasn't specified. Request and use server - // timestamp instead. - logD("Starting Get API info command"); - startNetworkCommand(new GetApiInfoCommand()); - } else { - startPollNotificationsRequest(); - } - } - } - } - - protected abstract NotificationsRetrivalCommand getPollNotificationsCommand( - String lastNotificationPollTimestamp, Integer waitTimeout); - - protected abstract void didReceiveNotification(Notification notification); - - private void startPollNotificationsRequest() { - logD("Starting polling request with lastNotificationPollTimestamp = " - + lastNotificationPollTimestamp); - startNetworkCommand(getPollNotificationsCommand( - lastNotificationPollTimestamp, notificationPollWaitTimeout)); - } - - private int enqueueNotifications(List notifications) { - if (notifications == null || notifications.isEmpty()) { - return 0; - } - int enqueuedCount = 0; - for (Notification notification : notifications) { - boolean added = notificationQueue.offer(notification); - if (!added) { - Log.e(DeviceHive.TAG, "Failed to add notification to the queue"); - } else { - enqueuedCount++; - } - } - return enqueuedCount; - } - - @Override - protected void onReceiveResult(final int resultCode, final int tagId, - final Bundle resultData) { - switch (resultCode) { - case DeviceHiveResultReceiver.MSG_HANDLED_RESPONSE: - logD("Handled response"); - if (tagId == TAG_SEND_COMMAND) { - Command command = SendDeviceCommandCommand - .getSentCommand(resultData); - logD("Command sent with response: " + command); - client.onFinishSendingCommand(command); - } else if (tagId == TAG_POLL_NOTIFICATIONS - || tagId == TAG_POLL_MULTIPLE_NOTIFICATIONS) { - logD("Poll request finished"); - isPollRequestInProgress = false; - List notifications = PollDeviceNotificationsCommand - .getNotifications(resultData); - logD("-------Received notifications: " + notifications); - logD("Notifications count: " + notifications.size()); - int enqueuedCount = enqueueNotifications(notifications); - logD("Enqueued notifications count: " + enqueuedCount); - if (!notifications.isEmpty()) { - lastNotificationPollTimestamp = notifications.get( - notifications.size() - 1).getTimestamp(); - } - if (isReceivingNotifications) { - handleNextNotification(); - } - } else if (tagId == TAG_GET_DEVICE) { - logD("Get device request finished"); - final DeviceData deviceData = GetDeviceCommand - .getDevice(resultData); - client.onReloadDeviceDataFinishedInternal(deviceData); - } else if (tagId == TAG_GET_API_INFO) { - final ApiInfo apiInfo = GetApiInfoCommand - .getApiInfo(resultData); - logD("Get API info request finished: " + apiInfo); - lastNotificationPollTimestamp = apiInfo.getServerTimestamp(); - logD("Starting polling request with lastNotificationPollTimestamp = " - + lastNotificationPollTimestamp); - startPollNotificationsRequest(); - } - break; - case DeviceHiveResultReceiver.MSG_EXCEPTION: - final Throwable exception = NetworkCommand.getThrowable(resultData); - Log.e(DeviceHive.TAG, "DeviceHiveResultReceiver.MSG_EXCEPTION", - exception); - case DeviceHiveResultReceiver.MSG_STATUS_FAILURE: - if (tagId == TAG_SEND_COMMAND) { - SendDeviceCommandCommand command = (SendDeviceCommandCommand) NetworkCommand - .getCommand(resultData); - client.onFailSendingCommand(command.getCommand()); - } else if (tagId == TAG_POLL_NOTIFICATIONS - || tagId == TAG_POLL_MULTIPLE_NOTIFICATIONS - || tagId == TAG_GET_API_INFO) { - Log.d(DeviceHive.TAG, "Failed to poll notifications"); - isPollRequestInProgress = false; - if (isReceivingNotifications) { - handleNextNotification(); - } - } else if (tagId == TAG_GET_DEVICE) { - client.onReloadDeviceDataFailedInternal(); - } - break; - } - - } - - @Override - protected NetworkCommandConfig getCommandConfig() { - final NetworkCommandConfig config = super.getCommandConfig(); - config.setAuthorisation(accessKey); - return config; - } - - private final static int TAG_SEND_COMMAND = getTagId(SendDeviceCommandCommand.class); - private final static int TAG_POLL_NOTIFICATIONS = getTagId(PollDeviceNotificationsCommand.class); - private final static int TAG_POLL_MULTIPLE_NOTIFICATIONS = getTagId(PollMultipleDeviceNotificationsCommand.class); - private final static int TAG_GET_DEVICE = getTagId(GetDeviceCommand.class); - private static final int TAG_GET_API_INFO = getTagId(GetApiInfoCommand.class); -} diff --git a/app/src/main/java/com/dataart/android/devicehive/client/DeviceClient.java b/app/src/main/java/com/dataart/android/devicehive/client/DeviceClient.java deleted file mode 100644 index d111878..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/client/DeviceClient.java +++ /dev/null @@ -1,245 +0,0 @@ -package com.dataart.android.devicehive.client; - -import android.content.Context; - -import com.dataart.android.devicehive.Command; -import com.dataart.android.devicehive.DeviceData; -import com.dataart.android.devicehive.Notification; - -/** - * An abstract device client which provides basic API for clients. This class is - * abstract and designed to be subclassed. - */ -/* package */abstract class DeviceClient { - - protected final Context context; - protected ClientServiceConnection serviceConnection; - - /** - * Construct client with given {@link android.content.Context}. - * - * @param context - * {@link android.content.Context} object. In most cases this should be - * application context which stays alive during the entire life - * of an application. - */ - protected DeviceClient(Context context) { - this.context = context; - } - - /** - * Set Device Hive service URL. This method MUST be called before - * performing registration and other subsequent network communications. - * - * @param url - * URL of Device Hive service. - */ - public void setApiEnpointUrl(String url) { - serviceConnection.setApiEndpointUrl(url); - } - - /** - * Get previously set Device Hive service URL. - * - * @return URL of Device Hive service. - */ - public String getApiEndpointUrl() { - return serviceConnection.getApiEndpointUrl(); - } - - /** - * Set Basic Authorisation credentials. - * - * @param accessKey - * accessKey - */ - public void setAuthorisation(String accessKey) { - serviceConnection.setAuthorisation(accessKey); - } - - /** - * Enable or disable debug log messages. - * - * @param enabled - * Whether debug log messages enabled or not. - */ - public void setDebugLoggingEnabled(boolean enabled) { - serviceConnection.setDebugLoggingEnabled(enabled); - } - - /** - * Set timestamp of the last received notification. This value is used to - * reduce amount of notifications received from the server as a result of - * poll request to only those of them which were received by the server - * later than the time defined by given timestamp. If not specified, the - * server's timestamp is taken instead. - * - * @param timestamp - * Timestamp of the last received notification. - */ - public void setLastNotificationPollTimestamp(String timestamp) { - serviceConnection.setLastNotificationPollTimestamp(timestamp); - } - - /** - * Get the timestamp of the last received notification. - * @return Timestamp of the last received notification. - */ - public String getLastNotificationPollTimestamp() { - return serviceConnection.getLastNotificationPollTimestamp(); - } - - /** - * Set notification poll waiting timeout in seconds (default: 30 seconds, - * maximum: 60 seconds). Specify 0 to disable waiting. - * - * @param timeout - * Notification poll waiting timeout in seconds. - */ - public void setNotificationPollWaitTimeout(Integer timeout) { - this.serviceConnection.setNotificationPollWaitTimeout(timeout); - } - - /** - * Check if this client is receiving notifications, i.e. performs - * notification polling. - * - * @return true, if this client is performing notification polling, - * otherwise returns false. - */ - public boolean isReceivingNotifications() { - return serviceConnection.isReceivingNotifications(); - } - - /** - * Start receiving notifications. Client will start polling server for new - * notifications. - */ - public void startReceivingNotifications() { - onStartReceivingNotifications(); - serviceConnection.startReceivingNotifications(); - } - - /** - * Stop receiving notifications. - */ - public void stopReceivingNotifications() { - serviceConnection.stopReceivingNotifications(); - onStopReceivingNotifications(); - } - - /** - * Get context which was used to create this client. - * - * @return {@link android.content.Context} was used to create this client. - */ - public Context getContext() { - return serviceConnection.getContext(); - } - - /** - * Run given runnable on main thread. Helper method. - * - * @param runnable - * Instance which implements {@link Runnable} interface. - */ - protected void runOnMainThread(Runnable runnable) { - serviceConnection.runOnMainThread(runnable); - } - - /** - * Called right after {@link #startReceivingNotifications()} method is - * called. Override this method to perform additional actions before the - * client starts receiving notifications. - */ - protected void onStartReceivingNotifications() { - // no op - } - - /** - * Called right after {@link #stopReceivingNotifications()} method is - * called. Override this method to perform additional actions right after - * the device stops receiving notifications. - */ - protected void onStopReceivingNotifications() { - // no op - } - - /** - * Called when {@link Command} is about to be sent. Override this method to - * perform additional actions before a command is sent. - * - * @param command - * {@link Command} object. - */ - protected void onStartSendingCommand(Command command) { - // no op - } - - /** - * Called when {@link Command} has been sent to the device. Override this - * method to perform additional actions after a command is sent to the - * device. - * - * @param command - * {@link Command} object. - */ - protected void onFinishSendingCommand(Command command) { - // no op - } - - /** - * Called when client failed to send command to the device. Override this - * method to perform any extra actions. - * - * @param command - * {@link Command} object. - */ - protected void onFailSendingCommand(Command command) { - // no op - } - - /** - * Called when device client finishes reloading device data from the server. - * - * @param deviceData - * {@link DeviceData} instance returned by the server. - */ - protected void onFinishReloadingDeviceData(DeviceData deviceData) { - // no op - } - - /** - * Called when device client fails to reload device data from the server. - */ - protected void onFailReloadingDeviceData() { - // no op - } - - /** - * Check whether given notification should be handled asynchronously. If so - * {@link #onReceiveNotification(Notification)} method is called on some - * other, not UI thread. - * - * @param notification - * {@link Notification} instance. - * @return true, if given notification should be handled asynchronously, - * otherwise return false. - */ - protected abstract boolean shouldReceiveNotificationAsynchronously( - final Notification notification); - - /* package */void onReloadDeviceDataFinishedInternal(DeviceData deviceData) { - onFinishReloadingDeviceData(deviceData); - } - - /* package */void onReloadDeviceDataFailedInternal() { - onFailReloadingDeviceData(); - } - - /* package */void setServiceConnection( - ClientServiceConnection serviceConnection) { - this.serviceConnection = serviceConnection; - this.serviceConnection.setClient(this); - } -} diff --git a/app/src/main/java/com/dataart/android/devicehive/client/MultipleDeviceClient.java b/app/src/main/java/com/dataart/android/devicehive/client/MultipleDeviceClient.java deleted file mode 100644 index 045f83f..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/client/MultipleDeviceClient.java +++ /dev/null @@ -1,133 +0,0 @@ -package com.dataart.android.devicehive.client; - -import java.util.LinkedList; -import java.util.List; - -import android.content.Context; - -import com.dataart.android.devicehive.Command; -import com.dataart.android.devicehive.DeviceData; -import com.dataart.android.devicehive.Notification; -import com.dataart.android.devicehive.client.commands.NotificationsRetrivalCommand; -import com.dataart.android.devicehive.client.commands.PollMultipleDeviceNotificationsCommand; -import com.dataart.android.devicehive.client.commands.PollMultipleDeviceNotificationsCommand.DeviceNotification; - -/** - * Represents a device client which provides high-level API for communication - * and receive notifications from several devices. This class is abstract and - * designed to be subclassed in order to handle incoming notifications. Also - * this class provides a number of various callbacks: - * {@link #onStartReceivingNotifications()}, - * {@link #onStopReceivingNotifications()}, - * {@link #onStartSendingCommand(Command)}, - * {@link #onFinishSendingCommand(Command)}, - * {@link #onFailSendingCommand(Command)}, etc. - * - */ -public abstract class MultipleDeviceClient extends DeviceClient { - - private List devices; - - /** - * Construct client with given {@link android.content.Context} and {@link DeviceData} - * objects. - * - * @param context - * {@link android.content.Context} object. In most cases this should be - * application context which stays alive during the entire life - * of an application. - * @param deviceData - * {@link DeviceData} object which describes device to - * communicate with. - */ - public MultipleDeviceClient(Context context, final List devices) { - super(context); - this.devices = devices; - setServiceConnection(new MultipleDeviceClientServiceConnection(context)); - } - - private class MultipleDeviceClientServiceConnection extends - ClientServiceConnection { - - public MultipleDeviceClientServiceConnection(Context context) { - super(context); - } - - @Override - protected NotificationsRetrivalCommand getPollNotificationsCommand( - String lastNotificationPollTimestamp, Integer waitTimeout) { - return new PollMultipleDeviceNotificationsCommand(getDeviceGuids(), - lastNotificationPollTimestamp, waitTimeout); - } - - @Override - protected void didReceiveNotification(Notification notification) { - DeviceNotification deviceNotification = (DeviceNotification) notification; - onReceiveNotification(deviceNotification.getDeviceGuid(), - notification); - } - - private List getDeviceGuids() { - if (devices != null && !devices.isEmpty()) { - final List guids = new LinkedList(); - for (DeviceData device : devices) { - guids.add(device.getId()); - } - return guids; - } else { - return null; - } - } - } - - /** - * Send command to the given device. - * - * @param device - * Target device. - * @param command - * {@link Command} to be sent. - */ - public void sendCommand(DeviceData device, final Command command) { - this.sendCommand(device, command); - } - - /** - * Reload device data. Current device data is updated with instance of - * {@link DeviceData} retrieved from the server. - * - * @see #onFinishReloadingDeviceData(DeviceData) - * @see #onFailReloadingDeviceData() - */ - public void reloadDeviceData(DeviceData device) { - serviceConnection.reloadDeviceData(device); - } - - /* package */void onReloadDeviceDataFinishedInternal(DeviceData deviceData) { - final DeviceData device = getDeviceDataWithId(deviceData.getId()); - devices.remove(device); - devices.add(deviceData); - onFinishReloadingDeviceData(deviceData); - } - - private DeviceData getDeviceDataWithId(String deviceId) { - for (DeviceData device : devices) { - if (device.getId().equals(deviceId)) { - return device; - } - } - return null; - } - - /** - * Handle received notification. Can be called either on main (UI) thread or - * some background thread depending on - * {@link #shouldReceiveNotificationAsynchronously(Notification)} method - * return value. - * - * @param notification - * {@link Notification} instance to handle by the client. - */ - protected abstract void onReceiveNotification(String deviceId, - final Notification notification); -} diff --git a/app/src/main/java/com/dataart/android/devicehive/client/SingleDeviceClient.java b/app/src/main/java/com/dataart/android/devicehive/client/SingleDeviceClient.java deleted file mode 100644 index 35b0e59..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/client/SingleDeviceClient.java +++ /dev/null @@ -1,111 +0,0 @@ -package com.dataart.android.devicehive.client; - -import android.content.Context; - -import com.dataart.android.devicehive.Command; -import com.dataart.android.devicehive.DeviceData; -import com.dataart.android.devicehive.Notification; -import com.dataart.android.devicehive.client.commands.NotificationsRetrivalCommand; -import com.dataart.android.devicehive.client.commands.PollDeviceNotificationsCommand; - -/** - * Represents a single device client which provides high-level API for - * communication with particular device. This class is abstract and designed to - * be subclassed in order to handle incoming notifications. Also this class - * provides a number of various callbacks: - * {@link #onStartReceivingNotifications()}, - * {@link #onStopReceivingNotifications()}, - * {@link #onStartSendingCommand(Command)}, - * {@link #onFinishSendingCommand(Command)}, - * {@link #onFailSendingCommand(Command)}, etc. - * - */ -public abstract class SingleDeviceClient extends DeviceClient { - - private DeviceData device; - - /** - * Construct client with given {@link android.content.Context} and {@link DeviceData} - * objects. - * - * @param context - * {@link android.content.Context} object. In most cases this should be - * application context which stays alive during the entire life - * of an application. - * @param deviceData - * {@link DeviceData} object which describes device to - * communicate with. - */ - public SingleDeviceClient(Context context, final DeviceData device) { - super(context); - this.device = device; - setServiceConnection(new SingleDeviceClientServiceConnection(context)); - } - - private class SingleDeviceClientServiceConnection extends - ClientServiceConnection { - - public SingleDeviceClientServiceConnection(Context context) { - super(context); - } - - @Override - protected NotificationsRetrivalCommand getPollNotificationsCommand( - String lastNotificationPollTimestamp, Integer waitTimeout) { - return new PollDeviceNotificationsCommand(device.getId(), - lastNotificationPollTimestamp, waitTimeout); - } - - @Override - protected void didReceiveNotification(Notification notification) { - onReceiveNotification(notification); - } - } - - /** - * Get corresponding device. - * - * @return {@link DeviceData} object. - */ - public DeviceData getDevice() { - return device; - } - - /** - * Send command to the device. - * - * @param command - * {@link Command} to be sent. - */ - public void sendCommand(final Command command) { - serviceConnection.sendCommand(device, command); - } - - /** - * Reload device data. Current device data is updated with instance of - * {@link DeviceData} retrieved from the server. - * - * @see #onFinishReloadingDeviceData(DeviceData) - * @see #onFailReloadingDeviceData() - */ - public void reloadDeviceData() { - serviceConnection.reloadDeviceData(device); - } - - /* package */void onReloadDeviceDataFinishedInternal(DeviceData deviceData) { - this.device = deviceData; - onFinishReloadingDeviceData(deviceData); - } - - /** - * Handle received notification. Can be called either on main (UI) thread or - * some background thread depending on - * {@link #shouldReceiveNotificationAsynchronously(Notification)} method - * return value. - * - * @param notification - * {@link Notification} instance to handle by the client. - */ - protected abstract void onReceiveNotification( - final Notification notification); -} diff --git a/app/src/main/java/com/dataart/android/devicehive/client/commands/DeviceClientCommand.java b/app/src/main/java/com/dataart/android/devicehive/client/commands/DeviceClientCommand.java deleted file mode 100644 index e1416a2..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/client/commands/DeviceClientCommand.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.dataart.android.devicehive.client.commands; - -import android.os.Parcel; - -import com.dataart.android.devicehive.network.JsonNetworkCommand; - -/** - * Base command for Device Hive device client commands. - */ -public abstract class DeviceClientCommand extends JsonNetworkCommand { - - @Override - public int describeContents() { - return 0; - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - - } - -} diff --git a/app/src/main/java/com/dataart/android/devicehive/client/commands/GetCommandCommand.java b/app/src/main/java/com/dataart/android/devicehive/client/commands/GetCommandCommand.java deleted file mode 100644 index 92a16f8..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/client/commands/GetCommandCommand.java +++ /dev/null @@ -1,98 +0,0 @@ -package com.dataart.android.devicehive.client.commands; - -import android.os.Bundle; -import android.os.Parcel; -import android.os.Parcelable; - -import com.dataart.android.devicehive.Command; -import com.dataart.android.devicehive.network.DeviceHiveResultReceiver; -import com.google.gson.Gson; - -/** - * Get device command with given identifier. As a result returns {@link Command} - * instance. - */ -public class GetCommandCommand extends DeviceClientCommand { - - private final static String NAMESPACE = GetCommandCommand.class.getName(); - - private static final String COMMAND_KEY = NAMESPACE.concat(".COMMAND_KEY"); - - private final String deviceId; - private final int commandId; - - /** - * Construct a new command. - * - * @param deviceId - * Device unique identifier. - * @param commandId - * Command identifier. - */ - public GetCommandCommand(String deviceId, int commandId) { - this.deviceId = deviceId; - this.commandId = commandId; - } - - @Override - protected String toJson(Gson gson) { - return null; - } - - @Override - protected RequestType getRequestType() { - return RequestType.GET; - } - - @Override - protected String getRequestPath() { - String requestPath = String.format("device/%s/command/%d", - encodedString(deviceId), commandId); - return requestPath; - } - - public static Parcelable.Creator CREATOR = new Parcelable.Creator() { - - @Override - public GetCommandCommand[] newArray(int size) { - return new GetCommandCommand[size]; - } - - @Override - public GetCommandCommand createFromParcel(Parcel source) { - return new GetCommandCommand(source.readString(), source.readInt()); - } - }; - - @Override - public int describeContents() { - return 0; - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - dest.writeString(deviceId); - dest.writeInt(commandId); - } - - @Override - protected int fromJson(final String response, final Gson gson, - final Bundle resultData) { - - final Command command = gson.fromJson(response, Command.class); - resultData.putParcelable(COMMAND_KEY, command); - return DeviceHiveResultReceiver.MSG_HANDLED_RESPONSE; - } - - /** - * Get {@link Command} object from response {@link android.os.Bundle} container. - * - * @param resultData - * {@link android.os.Bundle} object containing required response data. - * @return {@link Command} instance. - */ - public final static Command getDeviceCommand(Bundle resultData) { - return resultData.getParcelable(COMMAND_KEY); - } - -} diff --git a/app/src/main/java/com/dataart/android/devicehive/client/commands/GetDeviceClassEquipmentCommand.java b/app/src/main/java/com/dataart/android/devicehive/client/commands/GetDeviceClassEquipmentCommand.java deleted file mode 100644 index bd3b502..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/client/commands/GetDeviceClassEquipmentCommand.java +++ /dev/null @@ -1,115 +0,0 @@ -package com.dataart.android.devicehive.client.commands; - -import java.util.ArrayList; -import java.util.List; - -import android.os.Bundle; -import android.os.Parcel; -import android.os.Parcelable; - -import com.dataart.android.devicehive.DeviceClass; -import com.dataart.android.devicehive.EquipmentData; -import com.dataart.android.devicehive.network.DeviceHiveResultReceiver; -import com.google.gson.Gson; - -/** - * Command which retrieves equipment for {@link DeviceClass}. As a result - * returns list of {@link EquipmentData}. - */ -public class GetDeviceClassEquipmentCommand extends DeviceClientCommand { - - private final static String NAMESPACE = GetDeviceClassEquipmentCommand.class - .getName(); - - private static final String DEVICE_CLASS_KEY = NAMESPACE - .concat(".DEVICE_CLASS_KEY"); - private static final String EQUIPMENT_KEY = NAMESPACE - .concat(".EQUIPMENT_KEY"); - - private final int deviceClassId; - - /** - * Construct a new command with given {@link DeviceClass}. - * - * @param deviceClassId - * {@link DeviceClass} identifier. - */ - public GetDeviceClassEquipmentCommand(int deviceClassId) { - this.deviceClassId = deviceClassId; - } - - @Override - protected RequestType getRequestType() { - return RequestType.GET; - } - - @Override - protected String getRequestPath() { - return String.format("device/class/%d", deviceClassId); - } - - @Override - protected String toJson(Gson gson) { - return null; - } - - private class DeviceClassEquipment extends DeviceClass { - - ArrayList equipment; - - DeviceClassEquipment(String name, String version, - boolean isPermanent, int offlineTimeout) { - super(name, version, isPermanent, offlineTimeout); - } - - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - dest.writeInt(deviceClassId); - } - - public static Parcelable.Creator CREATOR = new Parcelable.Creator() { - - @Override - public GetDeviceClassEquipmentCommand[] newArray(int size) { - return new GetDeviceClassEquipmentCommand[size]; - } - - @Override - public GetDeviceClassEquipmentCommand createFromParcel(Parcel source) { - return new GetDeviceClassEquipmentCommand( - source.readInt()); - } - }; - - @Override - protected int fromJson(final String response, final Gson gson, - final Bundle resultData) { - - final DeviceClassEquipment deviceClassEquipment = gson.fromJson( - response, DeviceClassEquipment.class); - resultData.putParcelable(DEVICE_CLASS_KEY, deviceClassEquipment); - resultData.putParcelableArrayList(EQUIPMENT_KEY, - deviceClassEquipment.equipment); - return DeviceHiveResultReceiver.MSG_HANDLED_RESPONSE; - } - - public final static DeviceClass getDeviceClass(Bundle resultData) { - return resultData.getParcelable(DEVICE_CLASS_KEY); - } - - /** - * Get a list of {@link EquipmentData} which belong to target - * {@link DeviceClass} object. - * - * @param resultData - * {@link android.os.Bundle} object containing required response data. - * @return A list of {@link EquipmentData} which belong to target - * {@link DeviceClass} object. - */ - public final static List getEquipment(Bundle resultData) { - return resultData.getParcelableArrayList(EQUIPMENT_KEY); - } - -} diff --git a/app/src/main/java/com/dataart/android/devicehive/client/commands/GetDeviceCommand.java b/app/src/main/java/com/dataart/android/devicehive/client/commands/GetDeviceCommand.java deleted file mode 100644 index ebda0be..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/client/commands/GetDeviceCommand.java +++ /dev/null @@ -1,94 +0,0 @@ -package com.dataart.android.devicehive.client.commands; - -import android.os.Bundle; -import android.os.Parcel; -import android.os.Parcelable; - -import com.dataart.android.devicehive.DeviceData; -import com.dataart.android.devicehive.network.DeviceHiveResultReceiver; -import com.google.gson.Gson; - -/** - * Get device object with given identifier. As a result returns - * {@link DeviceData} instance. - */ -public class GetDeviceCommand extends DeviceClientCommand { - - private final static String NAMESPACE = GetDeviceCommand.class.getName(); - - private static final String DEVICE_KEY = NAMESPACE.concat(".DEVICE_KEY"); - - private final String deviceId; - - /** - * Construct a new command. - * - * @param deviceId - * Device unique identifier. - */ - public GetDeviceCommand(String deviceId) { - this.deviceId = deviceId; - } - - @Override - protected String toJson(Gson gson) { - return null; - } - - @Override - protected RequestType getRequestType() { - return RequestType.GET; - } - - @Override - protected String getRequestPath() { - String requestPath = String.format("/device/%s", - encodedString(deviceId)); - return requestPath; - } - - public static Parcelable.Creator CREATOR = new Parcelable.Creator() { - - @Override - public GetDeviceCommand[] newArray(int size) { - return new GetDeviceCommand[size]; - } - - @Override - public GetDeviceCommand createFromParcel(Parcel source) { - return new GetDeviceCommand(source.readString()); - } - }; - - @Override - public int describeContents() { - return 0; - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - dest.writeString(deviceId); - } - - @Override - protected int fromJson(final String response, final Gson gson, - final Bundle resultData) { - - final DeviceData device = gson.fromJson(response, - DeviceData.class); - resultData.putParcelable(DEVICE_KEY, device); - return DeviceHiveResultReceiver.MSG_HANDLED_RESPONSE; - } - - /** - * Get {@link DeviceData} object from response {@link android.os.Bundle} container. - * - * @param resultData - * {@link android.os.Bundle} object containing required response data. - * @return {@link DeviceData} instance. - */ - public final static DeviceData getDevice(Bundle resultData) { - return resultData.getParcelable(DEVICE_KEY); - } - -} diff --git a/app/src/main/java/com/dataart/android/devicehive/client/commands/GetDeviceEquipmentStateCommand.java b/app/src/main/java/com/dataart/android/devicehive/client/commands/GetDeviceEquipmentStateCommand.java deleted file mode 100644 index e9cb4f4..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/client/commands/GetDeviceEquipmentStateCommand.java +++ /dev/null @@ -1,112 +0,0 @@ -package com.dataart.android.devicehive.client.commands; - -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.List; - -import android.os.Bundle; -import android.os.Parcel; -import android.os.Parcelable; - -import com.dataart.android.devicehive.DeviceData; -import com.dataart.android.devicehive.EquipmentState; -import com.dataart.android.devicehive.network.DeviceHiveResultReceiver; -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; - -/** - * Get state information for equipment of given {@link DeviceData}. As a result - * returns list of {@link EquipmentState} objects. - */ -public class GetDeviceEquipmentStateCommand extends DeviceClientCommand { - - private final static String NAMESPACE = GetDeviceEquipmentStateCommand.class - .getName(); - - private static final String DEVICE_KEY = NAMESPACE.concat(".DEVICE_KEY"); - private static final String EQUIPMENT_STATE_KEY = NAMESPACE - .concat(".EQUIPMENT_STATE_KEY"); - - private final String deviceId; - - /** - * Construct a new command with given device identifier. - * - * @param deviceId - * Device identifier. - */ - public GetDeviceEquipmentStateCommand(String deviceId) { - this.deviceId = deviceId; - } - - @Override - protected RequestType getRequestType() { - return RequestType.GET; - } - - @Override - protected String getRequestPath() { - return String.format("device/%s/equipment", encodedString(deviceId)); - } - - @Override - protected String toJson(Gson gson) { - return null; - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - dest.writeString(deviceId); - } - - public static Parcelable.Creator CREATOR = new Parcelable.Creator() { - - @Override - public GetDeviceEquipmentStateCommand[] newArray(int size) { - return new GetDeviceEquipmentStateCommand[size]; - } - - @Override - public GetDeviceEquipmentStateCommand createFromParcel(Parcel source) { - return new GetDeviceEquipmentStateCommand(source.readString()); - } - }; - - @Override - protected int fromJson(final String response, final Gson gson, - final Bundle resultData) { - - Type listType = new TypeToken>() { - }.getType(); - final ArrayList equipmentStates = gson.fromJson( - response, listType); - resultData.putString(DEVICE_KEY, deviceId); - resultData.putParcelableArrayList(EQUIPMENT_STATE_KEY, equipmentStates); - return DeviceHiveResultReceiver.MSG_HANDLED_RESPONSE; - } - - /** - * Get target device identifier. - * - * @param resultData - * {@link android.os.Bundle} object containing required response data. - * @return Device identifier. - */ - public final static String getDeviceId(Bundle resultData) { - return resultData.getParcelable(DEVICE_KEY); - } - - /** - * Get a list of {@link EquipmentState} which determine current state of - * device equipment. - * - * @param resultData - * {@link android.os.Bundle} object containing required response data. - * @return A list of {@link EquipmentState} which determine current state of - * device equipment. - */ - public final static List getEquipmentState(Bundle resultData) { - return resultData.getParcelableArrayList(EQUIPMENT_STATE_KEY); - } - -} diff --git a/app/src/main/java/com/dataart/android/devicehive/client/commands/GetDeviceNotificationsCommand.java b/app/src/main/java/com/dataart/android/devicehive/client/commands/GetDeviceNotificationsCommand.java deleted file mode 100644 index 9e78581..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/client/commands/GetDeviceNotificationsCommand.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.dataart.android.devicehive.client.commands; - -import android.os.Parcel; -import android.os.Parcelable; - -import com.dataart.android.devicehive.Notification; - -/** - * Get all device {@link Notification}s starting from given timestamp. This - * request returns immediately regardless of whether there have been any - * notifications since given timestamp or not. As a result returns list of - * {@link Notification}. - */ -public class GetDeviceNotificationsCommand extends NotificationsRetrivalCommand { - - private final String deviceId; - - /** - * Construct a new command. - * - * @param deviceId - * Device identifier. - * @param lastNotificationPollTimestamp - * Timestamp which defines starting point in the past for - * notifications. - */ - public GetDeviceNotificationsCommand(String deviceId, - String lastNotificationPollTimestamp) { - super(lastNotificationPollTimestamp); - this.deviceId = deviceId; - } - - @Override - protected String getRequestPath() { - String requestPath = String.format("device/%s/notification", - encodedString(deviceId)); - if (lastNotificationPollTimestamp != null) { - requestPath += "?start=" - + encodedString(lastNotificationPollTimestamp); - } - return requestPath; - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - dest.writeString(deviceId); - super.writeToParcel(dest, flags); - } - - public static Parcelable.Creator CREATOR = new Parcelable.Creator() { - - @Override - public GetDeviceNotificationsCommand[] newArray(int size) { - return new GetDeviceNotificationsCommand[size]; - } - - @Override - public GetDeviceNotificationsCommand createFromParcel(Parcel source) { - return new GetDeviceNotificationsCommand(source.readString(), - source.readString()); - } - }; -} diff --git a/app/src/main/java/com/dataart/android/devicehive/client/commands/GetDevicesCommand.java b/app/src/main/java/com/dataart/android/devicehive/client/commands/GetDevicesCommand.java deleted file mode 100644 index 9a6baf7..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/client/commands/GetDevicesCommand.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.dataart.android.devicehive.client.commands; - -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.List; - -import android.os.Bundle; -import android.os.Parcel; -import android.os.Parcelable; - -import com.dataart.android.devicehive.DeviceData; -import com.dataart.android.devicehive.network.DeviceHiveResultReceiver; -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; - -/** - * Get all existing devices. As a result returns a list of {@link DeviceData}. - * Can be executed only by users with administrative privileges. - * - */ -public class GetDevicesCommand extends DeviceClientCommand { - - private final static String NAMESPACE = GetDevicesCommand.class.getName(); - - private static final String DEVICES_KEY = NAMESPACE.concat(".DEVICES_KEY"); - - /** - * Create a new command. - */ - public GetDevicesCommand() { - super(); - } - - @Override - protected RequestType getRequestType() { - return RequestType.GET; - } - - @Override - protected String getRequestPath() { - return "device"; - } - - public static Parcelable.Creator CREATOR = new Parcelable.Creator() { - - @Override - public GetDevicesCommand[] newArray(int size) { - return new GetDevicesCommand[size]; - } - - @Override - public GetDevicesCommand createFromParcel(Parcel source) { - return new GetDevicesCommand(); - } - }; - - @Override - protected int fromJson(final String response, final Gson gson, - final Bundle resultData) { - - Type listType = new TypeToken>() { - }.getType(); - final ArrayList devices = gson.fromJson(response, - listType); - resultData.putParcelableArrayList(DEVICES_KEY, devices); - return DeviceHiveResultReceiver.MSG_HANDLED_RESPONSE; - } - - /** - * Get a list of all existing devices from response {@link android.os.Bundle} - * container. - * - * @param resultData - * {@link android.os.Bundle} object containing required response data. - * @return A list of {@link DeviceData}. - */ - public final static List getDevices(Bundle resultData) { - return resultData.getParcelableArrayList(DEVICES_KEY); - } - - @Override - protected String toJson(Gson gson) { - return null; - } -} diff --git a/app/src/main/java/com/dataart/android/devicehive/client/commands/GetNetworkDevicesCommand.java b/app/src/main/java/com/dataart/android/devicehive/client/commands/GetNetworkDevicesCommand.java deleted file mode 100644 index f3c78e4..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/client/commands/GetNetworkDevicesCommand.java +++ /dev/null @@ -1,118 +0,0 @@ -package com.dataart.android.devicehive.client.commands; - -import java.util.ArrayList; -import java.util.List; - -import android.os.Bundle; -import android.os.Parcel; -import android.os.Parcelable; - -import com.dataart.android.devicehive.DeviceData; -import com.dataart.android.devicehive.Network; -import com.dataart.android.devicehive.network.DeviceHiveResultReceiver; -import com.google.gson.Gson; - -/** - * Get all devices which belong to given network. As a result returns a list of - * {@link DeviceData} objects. - * - */ -public class GetNetworkDevicesCommand extends DeviceClientCommand { - - private final static String NAMESPACE = GetNetworkDevicesCommand.class - .getName(); - - private static final String NETWORK_KEY = NAMESPACE.concat(".NETWORK_KEY"); - private static final String DEVICES_KEY = NAMESPACE.concat(".DEVICES_KEY"); - - private final int networkId; - - /** - * Construct a new command with given {@link Network} identifier. - * - * @param networkId - * {@link Network} identifier. - */ - public GetNetworkDevicesCommand(int networkId) { - this.networkId = networkId; - } - - @Override - protected RequestType getRequestType() { - return RequestType.GET; - } - - @Override - protected String getRequestPath() { - return String.format("network/%d", networkId); - } - - @Override - protected String toJson(Gson gson) { - return null; - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - dest.writeInt(networkId); - } - - public static Parcelable.Creator CREATOR = new Parcelable.Creator() { - - @Override - public GetNetworkDevicesCommand[] newArray(int size) { - return new GetNetworkDevicesCommand[size]; - } - - @Override - public GetNetworkDevicesCommand createFromParcel(Parcel source) { - return new GetNetworkDevicesCommand(source.readInt()); - } - }; - - private class NetworkExtended extends Network { - - ArrayList devices; - - NetworkExtended(String key, String name, String description) { - super(key, name, description); - } - - } - - @Override - protected int fromJson(final String response, final Gson gson, - final Bundle resultData) { - - final NetworkExtended networkExtended = gson.fromJson(response, - NetworkExtended.class); - resultData.putParcelable(NETWORK_KEY, networkExtended); - resultData.putParcelableArrayList(DEVICES_KEY, networkExtended.devices); - return DeviceHiveResultReceiver.MSG_HANDLED_RESPONSE; - } - - /** - * Get target {@link Network} object. - * - * @param resultData - * {@link android.os.Bundle} object containing required response data. - * @return {@link Network} instance. - */ - public final static Network getNetwork(Bundle resultData) { - return resultData.getParcelable(NETWORK_KEY); - } - - /** - * Get a list of {@link DeviceData} which belong to target {@link Network} - * object. - * - * @param resultData - * {@link android.os.Bundle} object containing required response data. - * @return A list of {@link DeviceData} which belong to target - * {@link Network} object. - */ - public final static List getNetworkDevices(Bundle resultData) { - return resultData.getParcelableArrayList(DEVICES_KEY); - } - -} diff --git a/app/src/main/java/com/dataart/android/devicehive/client/commands/GetNetworksCommand.java b/app/src/main/java/com/dataart/android/devicehive/client/commands/GetNetworksCommand.java deleted file mode 100644 index 9a53c58..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/client/commands/GetNetworksCommand.java +++ /dev/null @@ -1,80 +0,0 @@ -package com.dataart.android.devicehive.client.commands; - -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.List; - -import android.os.Bundle; -import android.os.Parcel; -import android.os.Parcelable; - -import com.dataart.android.devicehive.Network; -import com.dataart.android.devicehive.network.DeviceHiveResultReceiver; -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; - -/** - * Get a list of {@link Network} available for current user. - * - */ -public class GetNetworksCommand extends DeviceClientCommand { - - private final static String NAMESPACE = GetNetworksCommand.class.getName(); - - private static final String NETWORKS_KEY = NAMESPACE - .concat(".NETWORKS_KEY"); - - public GetNetworksCommand() { - super(); - } - - @Override - protected RequestType getRequestType() { - return RequestType.GET; - } - - @Override - protected String getRequestPath() { - return "network"; - } - - public static Parcelable.Creator CREATOR = new Parcelable.Creator() { - - @Override - public GetNetworksCommand[] newArray(int size) { - return new GetNetworksCommand[size]; - } - - @Override - public GetNetworksCommand createFromParcel(Parcel source) { - return new GetNetworksCommand(); - } - }; - - @Override - protected int fromJson(final String response, final Gson gson, - final Bundle resultData) { - Type listType = new TypeToken>() { - }.getType(); - final ArrayList networks = gson.fromJson(response, - listType); - resultData.putParcelableArrayList(NETWORKS_KEY, networks); - return DeviceHiveResultReceiver.MSG_HANDLED_RESPONSE; - } - - /** - * Get a list of {@link Network} available for current user. - * - * @param resultData - * {@link android.os.Bundle} object containing required response data. - * @return A list of {@link Network} available for current user. - */ - public final static List getNetworks(Bundle resultData) { - return resultData.getParcelableArrayList(NETWORKS_KEY); - } - - @Override - protected String toJson(Gson gson) { - return null; - } -} diff --git a/app/src/main/java/com/dataart/android/devicehive/client/commands/NotificationsRetrivalCommand.java b/app/src/main/java/com/dataart/android/devicehive/client/commands/NotificationsRetrivalCommand.java deleted file mode 100644 index 5300419..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/client/commands/NotificationsRetrivalCommand.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.dataart.android.devicehive.client.commands; - -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.List; - -import android.os.Bundle; -import android.os.Parcel; - -import com.dataart.android.devicehive.DeviceData; -import com.dataart.android.devicehive.Notification; -import com.dataart.android.devicehive.network.DeviceHiveResultReceiver; -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; - -/** - * Abstract base class for commands which retrieve notifications for given - * device. - * - */ -public abstract class NotificationsRetrivalCommand extends DeviceClientCommand { - - private final static String NAMESPACE = NotificationsRetrivalCommand.class - .getName(); - - protected static final String NOTIFICATIONS_KEY = NAMESPACE - .concat(".NOTIFICATIONS_KEY"); - - protected final String lastNotificationPollTimestamp; - - /** - * Construct command for given device and last received notification - * timestamp. - * - * @param deviceData - * {@link DeviceData} instance. - * @param lastNotificationPollTimestamp - * Last received notification timestamp. - */ - public NotificationsRetrivalCommand(String lastNotificationPollTimestamp) { - this.lastNotificationPollTimestamp = lastNotificationPollTimestamp; - } - - @Override - protected RequestType getRequestType() { - return RequestType.GET; - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - dest.writeString(lastNotificationPollTimestamp); - } - - @Override - protected String toJson(Gson gson) { - return null; - } - - @Override - protected int fromJson(String response, Gson gson, Bundle resultData) { - Type listType = new TypeToken>() { - }.getType(); - - ArrayList notifications = gson.fromJson(response, - listType); - resultData.putParcelableArrayList(NOTIFICATIONS_KEY, notifications); - return DeviceHiveResultReceiver.MSG_HANDLED_RESPONSE; - } - - /** - * Get a list of {@link Notification} sent from given {@link DeviceData} - * object. - * - * @param resultData - * {@link android.os.Bundle} object containing required response data. - * @return A list of {@link Notification} sent from given {@link DeviceData} - * . - */ - public final static List getNotifications(Bundle resultData) { - return resultData.getParcelableArrayList(NOTIFICATIONS_KEY); - } -} diff --git a/app/src/main/java/com/dataart/android/devicehive/client/commands/PollDeviceNotificationsCommand.java b/app/src/main/java/com/dataart/android/devicehive/client/commands/PollDeviceNotificationsCommand.java deleted file mode 100644 index 66aeaa3..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/client/commands/PollDeviceNotificationsCommand.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.dataart.android.devicehive.client.commands; - -import android.os.Parcel; -import android.os.Parcelable; - -import com.dataart.android.devicehive.Notification; - -/** - * Get all existing device {@link Notification}s starting from given timestamp. - * This request returns immediately if there have been any notifications since - * given timestamp. In the case when no notifications were found, the method - * blocks until new notification is received. The blocking period is limited - * (currently 30 seconds). As a result returns list of {@link Notification}. - */ -public class PollDeviceNotificationsCommand extends PollNotificationsCommand { - - private final String deviceId; - - /** - * Construct a new command. - * - * @param deviceId - * Device identifier. - * @param lastNotificationPollTimestamp - * Timestamp which defines starting point in the past for - * notifications. - */ - public PollDeviceNotificationsCommand(String deviceId, - String lastNotificationPollTimestamp) { - this(deviceId, lastNotificationPollTimestamp, null); - } - - /** - * Construct a new command. - * - * @param deviceId - * Device identifier. - * @param lastNotificationPollTimestamp - * Timestamp which defines starting point in the past for - * notifications. - * @param waitTimeout - * Waiting timeout in seconds. - */ - public PollDeviceNotificationsCommand(String deviceId, - String lastNotificationPollTimestamp, Integer waitTimeout) { - super(lastNotificationPollTimestamp, waitTimeout); - this.deviceId = deviceId; - } - - @Override - protected String getRequestPath() { - String requestPath = String.format("device/%s/notification/poll", - encodedString(deviceId)); - if (lastNotificationPollTimestamp != null) { - requestPath += "?timestamp=" - + encodedString(lastNotificationPollTimestamp); - } - if (waitTimeout != null) { - requestPath += lastNotificationPollTimestamp != null ? "&" : "?"; - requestPath += "waitTimeout=" + waitTimeout; - } - return requestPath; - } - - public static Parcelable.Creator CREATOR = new Parcelable.Creator() { - - @Override - public PollDeviceNotificationsCommand[] newArray(int size) { - return new PollDeviceNotificationsCommand[size]; - } - - @Override - public PollDeviceNotificationsCommand createFromParcel(Parcel source) { - return new PollDeviceNotificationsCommand(source.readString(), - source.readString(), - (Integer) source.readValue(CLASS_LOADER)); - } - }; - - @Override - public void writeToParcel(Parcel dest, int flags) { - dest.writeString(deviceId); - super.writeToParcel(dest, flags); - } -} diff --git a/app/src/main/java/com/dataart/android/devicehive/client/commands/PollMultipleDeviceNotificationsCommand.java b/app/src/main/java/com/dataart/android/devicehive/client/commands/PollMultipleDeviceNotificationsCommand.java deleted file mode 100644 index 652a6d3..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/client/commands/PollMultipleDeviceNotificationsCommand.java +++ /dev/null @@ -1,173 +0,0 @@ -package com.dataart.android.devicehive.client.commands; - -import java.io.Serializable; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; - -import android.os.Bundle; -import android.os.Parcel; -import android.os.Parcelable; - -import com.dataart.android.devicehive.Notification; -import com.dataart.android.devicehive.network.DeviceHiveResultReceiver; -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; - -/** - * Poll {@link Notification}s from given devices starting from given timestamp. - * This request returns immediately if there have been any notifications since - * given timestamp. In the case when no notifications were found, the method - * blocks until new notification is received. The blocking period is limited - * (currently 30 seconds). As a result returns list of {@link Notification}. - */ -public class PollMultipleDeviceNotificationsCommand extends - PollNotificationsCommand { - - protected final List deviceIds; - - /** - * Construct command for given device and last received notification - * timestamp. - * - * @param deviceIds - * List of device identifiers. - * @param lastNotificationPollTimestamp - * Last received notification timestamp. - */ - public PollMultipleDeviceNotificationsCommand(List deviceIds, - String lastNotificationPollTimestamp) { - this(deviceIds, lastNotificationPollTimestamp, null); - } - - /** - * Construct a new command. - * - * @param deviceIds - * List of device identifiers. - * @param lastNotificationPollTimestamp - * Timestamp which defines starting point in the past for - * notifications. - * @param waitTimeout - * Waiting timeout in seconds. - */ - public PollMultipleDeviceNotificationsCommand(List deviceIds, - String lastNotificationPollTimestamp, Integer waitTimeout) { - super(lastNotificationPollTimestamp, waitTimeout); - this.deviceIds = deviceIds; - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - dest.writeStringList(deviceIds); - super.writeToParcel(dest, flags); - } - - public static Parcelable.Creator CREATOR = new Parcelable.Creator() { - - @Override - public PollMultipleDeviceNotificationsCommand[] newArray(int size) { - return new PollMultipleDeviceNotificationsCommand[size]; - } - - @Override - public PollMultipleDeviceNotificationsCommand createFromParcel( - Parcel source) { - List deviceIds = new LinkedList(); - source.readStringList(deviceIds); - return new PollMultipleDeviceNotificationsCommand(deviceIds, - source.readString(), - (Integer) source.readValue(CLASS_LOADER)); - } - }; - - @Override - protected String getRequestPath() { - String requestPath = "device/notification/poll"; - if (isDeviceGuidsPresent()) { - requestPath += String.format("?deviceGuids=%s", - prepareGuidsString(deviceIds)); - } - if (lastNotificationPollTimestamp != null) { - requestPath += isDeviceGuidsPresent() ? "&" : "?"; - requestPath += "timestamp=" - + encodedString(lastNotificationPollTimestamp); - } - if (waitTimeout != null) { - requestPath += (isDeviceGuidsPresent() || lastNotificationPollTimestamp != null) ? "&" - : "?"; - requestPath += "waitTimeout=" + waitTimeout; - } - return requestPath; - } - - private boolean isDeviceGuidsPresent() { - return deviceIds != null && !deviceIds.isEmpty(); - } - - private String prepareGuidsString(List guids) { - if (deviceIds == null || deviceIds.isEmpty()) { - return null; - } else { - final StringBuilder builder = new StringBuilder(""); - String separator = ""; - for (String guid : guids) { - builder.append(separator).append(guid); - separator = ","; - } - return builder.toString(); - } - } - - public static class DeviceNotification extends Notification { - - private String deviceGuid; - - public String getDeviceGuid() { - return deviceGuid; - } - - /* package */DeviceNotification(String name, String timestamp, - Serializable parameters) { - super(name, timestamp, parameters); - } - - /* package */DeviceNotification(String deviceGuid, - Notification notification) { - super(notification.getName(), notification - .getTimestamp(), notification.getParameters()); - this.deviceGuid = deviceGuid; - } - } - - private static class DeviceGuidNotification { - String deviceGuid; - Notification notification; - } - - @Override - protected int fromJson(final String response, final Gson gson, - final Bundle resultData) { - - Type listType = new TypeToken>() { - }.getType(); - - ArrayList notifications = gson.fromJson( - response, listType); - resultData.putParcelableArrayList(NOTIFICATIONS_KEY, - asDeviceNotificationList(notifications)); - return DeviceHiveResultReceiver.MSG_HANDLED_RESPONSE; - } - - private static ArrayList asDeviceNotificationList( - List notifications) { - ArrayList result = new ArrayList( - notifications.size()); - for (DeviceGuidNotification guidNotification : notifications) { - result.add(new DeviceNotification(guidNotification.deviceGuid, - guidNotification.notification)); - } - return result; - } -} diff --git a/app/src/main/java/com/dataart/android/devicehive/client/commands/PollNotificationsCommand.java b/app/src/main/java/com/dataart/android/devicehive/client/commands/PollNotificationsCommand.java deleted file mode 100644 index 17b8ca6..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/client/commands/PollNotificationsCommand.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.dataart.android.devicehive.client.commands; - -import android.os.Parcel; - -import com.google.gson.Gson; - -/** - * Abstract base class for commands which poll notifications for given device. - * - */ -public abstract class PollNotificationsCommand extends - NotificationsRetrivalCommand { - - protected final Integer waitTimeout; - - /** - * Construct a new command with last received notification timestamp. - * - * @param lastNotificationPollTimestamp - * Last received notification timestamp. - */ - public PollNotificationsCommand(String lastNotificationPollTimestamp) { - this(lastNotificationPollTimestamp, null); - } - - /** - * Construct a new command with last received notification timestamp and - * wait timeout. - * - * @param lastNotificationPollTimestamp - * Last received notification timestamp. - * @param waitTimeout - * Waiting timeout in seconds. - */ - public PollNotificationsCommand(String lastNotificationPollTimestamp, - Integer waitTimeout) { - super(lastNotificationPollTimestamp); - this.waitTimeout = waitTimeout; - } - - @Override - protected RequestType getRequestType() { - return RequestType.GET; - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - super.writeToParcel(dest, flags); - dest.writeValue(waitTimeout); - } - - @Override - protected String toJson(Gson gson) { - return null; - } -} diff --git a/app/src/main/java/com/dataart/android/devicehive/client/commands/SendDeviceCommandCommand.java b/app/src/main/java/com/dataart/android/devicehive/client/commands/SendDeviceCommandCommand.java deleted file mode 100644 index b8a5d2b..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/client/commands/SendDeviceCommandCommand.java +++ /dev/null @@ -1,106 +0,0 @@ -package com.dataart.android.devicehive.client.commands; - -import android.os.Bundle; -import android.os.Parcel; -import android.os.Parcelable; - -import com.dataart.android.devicehive.Command; -import com.dataart.android.devicehive.Notification; -import com.dataart.android.devicehive.network.DeviceHiveResultReceiver; -import com.google.gson.Gson; - -/** - * Send a new command to the given device. As a result returns {@link Command} - * instance from the server response. - * - */ -public class SendDeviceCommandCommand extends DeviceClientCommand { - - private final static String NAMESPACE = SendDeviceCommandCommand.class - .getName(); - - private static final String COMMAND_KEY = NAMESPACE.concat(".COMMAND_KEY"); - - private final String deviceId; - private final Command command; - - /** - * Construct a new command with given device identifier and {@link Command} - * instance. - * - * @param deviceId - * Device unique identifier. - * @param command - * {@link Command} instance. - * @param notification - * {@link Notification} to be sent on behalf of given device. - */ - public SendDeviceCommandCommand(String deviceId, Command command) { - this.deviceId = deviceId; - this.command = command; - } - - /** - * Get {@link Command} to be sent. - * - * @return {@link Command} instance. - */ - public Command getCommand() { - return command; - } - - @Override - protected RequestType getRequestType() { - return RequestType.POST; - } - - @Override - protected String getRequestPath() { - return String.format("device/%s/command", encodedString(deviceId)); - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - super.writeToParcel(dest, flags); - dest.writeString(deviceId); - dest.writeParcelable(command, 0); - } - - public static Parcelable.Creator CREATOR = new Parcelable.Creator() { - - @Override - public SendDeviceCommandCommand[] newArray(int size) { - return new SendDeviceCommandCommand[size]; - } - - @Override - public SendDeviceCommandCommand createFromParcel(Parcel source) { - return new SendDeviceCommandCommand(source.readString(), - (Command) source.readParcelable(CLASS_LOADER)); - } - }; - - @Override - protected String toJson(Gson gson) { - return gson.toJson(command); - } - - @Override - protected int fromJson(final String response, final Gson gson, - final Bundle resultData) { - final Command command = gson.fromJson(response, Command.class); - resultData.putParcelable(COMMAND_KEY, command); - return DeviceHiveResultReceiver.MSG_HANDLED_RESPONSE; - } - - /** - * Get sent {@link Command} instance returned by the server. - * - * @param resultData - * {@link android.os.Bundle} object containing required response data. - * @return {@link Command} instance returned by the server. - */ - public final static Command getSentCommand(Bundle resultData) { - return resultData.getParcelable(COMMAND_KEY); - } -} diff --git a/app/src/main/java/com/dataart/android/devicehive/commands/GetApiInfoCommand.java b/app/src/main/java/com/dataart/android/devicehive/commands/GetApiInfoCommand.java deleted file mode 100644 index 8528784..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/commands/GetApiInfoCommand.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.dataart.android.devicehive.commands; - -import android.os.Bundle; -import android.os.Parcel; -import android.os.Parcelable; - -import com.dataart.android.devicehive.ApiInfo; -import com.dataart.android.devicehive.network.DeviceHiveResultReceiver; -import com.dataart.android.devicehive.network.JsonNetworkCommand; -import com.google.gson.Gson; - -/** - * Gets meta-information of the current API. As a result returns {@link ApiInfo} - * instance. - */ -public class GetApiInfoCommand extends JsonNetworkCommand { - - private final static String NAMESPACE = GetApiInfoCommand.class.getName(); - - private static final String API_INFO_KEY = NAMESPACE - .concat(".API_INFO_KEY"); - - /** - * Construct a new command. - */ - public GetApiInfoCommand() { - - } - - @Override - protected String toJson(Gson gson) { - return null; - } - - @Override - protected RequestType getRequestType() { - return RequestType.GET; - } - - @Override - protected String getRequestPath() { - return "info"; - } - - public static Creator CREATOR = new Creator() { - - @Override - public GetApiInfoCommand[] newArray(int size) { - return new GetApiInfoCommand[size]; - } - - @Override - public GetApiInfoCommand createFromParcel(Parcel source) { - return new GetApiInfoCommand(); - } - }; - - @Override - public int describeContents() { - return 0; - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - - } - - @Override - protected int fromJson(final String response, final Gson gson, - final Bundle resultData) { - - final ApiInfo apiInfo = gson.fromJson(response, ApiInfo.class); - resultData.putParcelable(API_INFO_KEY, apiInfo); - return DeviceHiveResultReceiver.MSG_HANDLED_RESPONSE; - } - - /** - * Get {@link ApiInfo} object from response {@link android.os.Bundle} container. - * - * @param resultData - * {@link android.os.Bundle} object containing required response data. - * @return {@link ApiInfo} instance. - */ - public final static ApiInfo getApiInfo(Bundle resultData) { - return resultData.getParcelable(API_INFO_KEY); - } - -} diff --git a/app/src/main/java/com/dataart/android/devicehive/device/CommandResult.java b/app/src/main/java/com/dataart/android/devicehive/device/CommandResult.java deleted file mode 100644 index a7f4609..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/device/CommandResult.java +++ /dev/null @@ -1,110 +0,0 @@ -package com.dataart.android.devicehive.device; - -import java.io.Serializable; - -import com.dataart.android.devicehive.ObjectWrapper; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -import android.os.Parcel; -import android.os.Parcelable; - -import timber.log.Timber; - -/** - * Command execution result which is reported to the server. - */ -public class CommandResult implements Parcelable { - - /** - * Command status "Completed" value. - */ - public static final String STATUS_COMLETED = "Completed"; - - /** - * Command status "Failed" value. - */ - public static final String STATUS_FAILED = "Failed"; - - /** - * Command status "Failed" value. - */ - public static final String STATUS_WAITING = "Waiting"; - - private final String status; - private final String result; - - /** - * Constructs command result with given status and result. - * - * @param status - * Command status. - * @param result - * Command execution result. - */ - public CommandResult(String status, String result) { - this.status = status; - this.result = result; - Timber.d("CommandResult constructor: r="+result+", this.r="+this.result); - } - - /** - * Get command status. - * - * @return Command status. - */ - public String getStatus() { - return status; - } - - /** - * Get command execution result. - * - * @return Command execution result. - */ - public Serializable getResult() { - return result; - } - - @Override - public int describeContents() { - return 0; - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - dest.writeString(status); - dest.writeString(result); - } - - public static Creator CREATOR = new Creator() { - - @Override - public CommandResult[] newArray(int size) { - return new CommandResult[size]; - } - - @Override - public CommandResult createFromParcel(Parcel source) { - return new CommandResult(source.readString(), - source.readString()); - } - }; - - public String toJson() { -// FIXME: should be implemented with serializable or custom gson serializer - String json = "{\"result\":"+ result +",\"status\":\""+status+"\"}"; - return json; - } - - public static boolean isValidJson(String json){ - Gson gson = new Gson(); - try { - Object o = gson.fromJson(json, Object.class); - String reversed = new GsonBuilder().setPrettyPrinting().create().toJson(o); - } catch (Exception e) { - return false; - } - return true; - } -} diff --git a/app/src/main/java/com/dataart/android/devicehive/device/CommandRunner.java b/app/src/main/java/com/dataart/android/devicehive/device/CommandRunner.java deleted file mode 100644 index 4e9a05a..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/device/CommandRunner.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.dataart.android.devicehive.device; - -import com.dataart.android.devicehive.Command; -import com.dataart.android.devicehive.device.future.SimpleCallableFuture; - -/** - * Common interface for objects able to execute commands. Usually these are - * {@link com.dataart.android.devicehive.device.Device} and {@link com.dataart.android.devicehive.device.Equipment}. - */ -public interface CommandRunner { - - /** - * Called right before command is executed either by the device itself or - * one of its equipment. This method is called for the device before each - * command execution (either by the device itself or one of its equipment). - * - * @param command - * {@link Command} to be executed. - */ - void onBeforeRunCommand(Command command); - - /** - * Check whether receiver of the command should execute command on some - * other thread, not on the main (UI) thread. - * - * @param command - * Command to be executed. - * @return true if {@link #runCommand(Command)} should be called - * asynchronously, otherwise returns false. - */ - boolean shouldRunCommandAsynchronously(final Command command); - - /** - * Execute given command. Cab be called either on the main thread or some - * other thread. It depends on the value that is returned by - * {@link #shouldRunCommandAsynchronously(Command)} method. - * - * @param command - * Command to be executed. - * @return {@link com.dataart.android.devicehive.device.CommandResult} object describing command execution result - * and status. - */ - SimpleCallableFuture runCommand(final Command command); -} diff --git a/app/src/main/java/com/dataart/android/devicehive/device/Device.java b/app/src/main/java/com/dataart/android/devicehive/device/Device.java deleted file mode 100644 index 5d503a4..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/device/Device.java +++ /dev/null @@ -1,435 +0,0 @@ -package com.dataart.android.devicehive.device; - -import android.content.Context; - -import com.dataart.android.devicehive.DeviceData; -import com.dataart.android.devicehive.Notification; - -import java.io.Serializable; -import java.util.LinkedList; -import java.util.List; - -/** - * Represents a device, a unit that executes commands and communicates to the - * server. This class is abstract and designed to be subclassed in order to - * represent specific device. Descendants should implement abstract methods of - * {@link CommandRunner} interface in order to execute commands. Also they may - * override various callbacks: {@link #onStartRegistration()}, - * {@link #onFinishRegistration()}, {@link #onStartProcessingCommands()}, - * {@link #onStopProcessingCommands()}, - * {@link #onStartSendingNotification(Notification)}, - * {@link #onFinishSendingNotification(Notification)}, etc. - * - */ -public abstract class Device implements CommandRunner { - - private DeviceData deviceData; - private final DeviceServiceConnection serviceConnection; - - protected boolean isRegistered = false; - - private final List equipmentList = new LinkedList(); - - /** - * Construct device with given {@link android.content.Context} and {@link DeviceData} - * objects. - * - * @param context - * {@link android.content.Context} object. In most cases this should be - * application context which stays alive during the entire life - * of an application. - * @param deviceData - * {@link DeviceData} object which describes various device - * parameters. - */ - public Device(Context context, DeviceData deviceData) { - this.serviceConnection = new DeviceServiceConnection(context); - serviceConnection.setDevice(this); - this.deviceData = deviceData; - } - - /** - * Get {@link DeviceData} object which describes various device parameters. - * - * @return {@link DeviceData} object. - */ - public DeviceData getDeviceData() { - return deviceData; - } - - /** - * Set Device Hive service URL. This method MUST be called before - * performing registration and other subsequent network communications. - * - * @param url - * URL of Device Hive service. - */ - public void setApiEnpointUrl(String url) { - serviceConnection.setApiEndpointUrl(url); - } - - /** - * Get previously set Device Hive service URL. - * - * @return URL of Device Hive service. - */ - public String getApiEndpointUrl() { - return serviceConnection.getApiEndpointUrl(); - } - - /** - * Enable or disable debug log messages. - * - * @param enabled - * Whether debug log messages enabled or not. - */ - public void setDebugLoggingEnabled(boolean enabled) { - this.serviceConnection.setDebugLoggingEnabled(enabled); - } - - /** - * Set timestamp of the last received command. This value is used to reduce - * amount of commands received from the server as a result of poll request - * to only those of them which were received by the server later than the - * time defined by given timestamp. - * - * @param timestamp - * Timestamp of the last received command. - */ - public void setLastCommandPollTimestamp(String timestamp) { - this.serviceConnection.setLastCommandPollTimestamp(timestamp); - } - - /** - * Set command poll waiting timeout in seconds (default: 30 seconds, - * maximum: 60 seconds). Specify 0 to disable waiting. - * - * @param timeout - * Command poll waiting timeout in seconds. - */ - public void setCommandPollWaitTimeout(Integer timeout) { - this.serviceConnection.setCommandPollWaitTimeout(timeout); - } - - /** - * Initiate device registration. You should set Device Hive service URL - * before performing device registration. - * - * @see {@link #setApiEnpointUrl(String)}, {@link #onStartRegistration()}, - * {@link #onFinishRegistration()}, {@link #onFailRegistration()}. - */ - public void registerDevice() { - if (getApiEndpointUrl() == null) { - throw new IllegalStateException( - "API Endpoint URL should be set before registering device"); - } - isRegistered = false; - onStartRegistration(); - serviceConnection.registerDevice(); - } - - /** - * Unregister device. Also unregisters all attached equipment. - */ - public void unregisterDevice() { - if (isProcessingCommands()) { - stopProcessingCommands(); - } - isRegistered = false; - serviceConnection.unregisterDevice(); - } - - /** - * Check if this device is registered. - * - * @return true, if this device is registered, otherwise returns false. - */ - public boolean isRegistered() { - return isRegistered; - } - - /** - * Check if this device is processing command, i.e. performs commands - * polling and execution. - * - * @return true, if this device is performing commands polling and - * execution, otherwise returns false. - */ - public boolean isProcessingCommands() { - return serviceConnection.isProcessingCommands(); - } - - /** - * Send device notification. Device should registered to be able to send - * notifications. - * - * @param notification - * {@link Notification} to be sent. - * @see {@link #registerDevice()}. - */ - public void sendNotification(Notification notification) { -// if (!isRegistered) { -// Log.w(DeviceHive.TAG, -// "Device should be registered before sending notifications"); -// } else - { - serviceConnection.sendNotification(notification); - } - } - - /** - * Start processing commands. Device will start performing commands polling - * and execution. Device should be registered before processing commands. - * - * @see {@link #registerDevice()}. - */ - public void startProcessingCommands() { -// if (!isRegistered || false) { -// Log.w(DeviceHive.TAG, -// "Device should be registered before starting receiving commands"); -// } else - { - onStartProcessingCommandsInternal(); - serviceConnection.startProcessingCommands(); - } - } - - /** - * Stop processing commands. - */ - public void stopProcessingCommands() { - serviceConnection.stopProcessingCommands(); - onStopProcessingCommandsInternal(); - } - - /** - * Reload device data. Current device data is updated with instance of - * {@link DeviceData} retrieved from the server. - * - * @see #onFinishReloadingDeviceData(DeviceData) - * @see #onFailReloadingDeviceData() - */ - public void reloadDeviceData() { - serviceConnection.reloadDeviceData(); - } - - /** - * Attach given {@link Equipment} to the device. {@link Equipment} should be - * attached to the device in order to be able to process commands, send - * notifications and receive various callback method calls. Equipment - * MUST NOT be attached to any other device. Device MUST NOT - * be registered. Changing device equipment after registration isn't - * supported. - * - * @param equipment - * {@link Equipment} to attach. - */ - public void attachEquipment(Equipment equipment) { - if (equipment.getDevice() != null) { - throw new IllegalArgumentException( - "Equiment has already been attached to other device"); - } else if (isRegistered) { - throw new IllegalStateException( - "Device has already been registered. You cannot attach equipment after a device is registered"); - } else { - equipment.setDevice(this); - this.equipmentList.add(equipment); - this.deviceData.addEquipment(equipment.getEquipmentData()); - } - } - - /** - * Get equipment list of the device. - * - * @return All previously attached {@link Equipment} objects. - */ - public List getEquipment() { - return equipmentList; - } - - /** - * Whether this device should perform attached {@link Equipment}'s - * registration/unregistration callbacks on some other thread. - * - * @return true, if attached {@link Equipment}'s registration/unregistration - * callbacks should be performed on some other thread, otherwise - * return true. - * @see {@link Equipment#onRegisterEquipment()}, - * {@link Equipment#onUnregisterEquipment()}. - */ - protected boolean performsEquipmentRegistrationCallbacksAsynchronously() { - return false; - } - - /** - * Called at the very beginning of device registration process before - * sending network requests to the server. Override this method if you need - * to perform any additional actions right before registration. - */ - protected void onStartRegistration() { - // no op - } - - /** - * Called right after device registration process is finished. Override this - * method if you need to perform any additional actions right after - * registration. - */ - protected void onFinishRegistration() { - // no op - } - - /** - * Called if device fails to register. Override this method if you need to - * perform additional actions such as restarting registration. - */ - protected void onFailRegistration() { - // no op - } - - /** - * Called right after {@link #startProcessingCommands()} method is called. - * Override this method to perform additional actions before the device - * starts processing commands. - */ - protected void onStartProcessingCommands() { - // no op - } - - /** - * Called right after {@link #stopProcessingCommands()} method is called. - * Override this method to perform additional actions right after the device - * stops processing commands. - */ - protected void onStopProcessingCommands() { - // no op - } - - /** - * Called when device finishes reloading device data from the server. - * - * @param deviceData - * {@link DeviceData} instance returned by the server. - */ - protected void onFinishReloadingDeviceData(DeviceData deviceData) { - // no op - } - - /** - * Called when device to reload device data from the server. - */ - protected void onFailReloadingDeviceData() { - // no op - } - - /** - * Called when device or equipment notification is about to be sent. - * Override this method to perform additional actions before a notification - * is sent. - * - * @param notification - * {@link Notification} object. - */ - protected void onStartSendingNotification(Notification notification) { - // no op - } - - /** - * Called when device or equipment notification has been sent. Override this - * method to perform additional actions after a notification is sent. - * - * @param notification - * {@link Notification} object. - */ - protected void onFinishSendingNotification(Notification notification) { - // no op - } - - /** - * Called when device failed to send notification. Override this method to - * perform any additional initialization or customization. - * - * @param notification - * {@link Notification} object. - */ - protected void onFailSendingNotification(Notification notification) { - // no op - } - - /** - * Get {@link android.content.Context} which was used to create {@link Device} object. - * - * @return {@link android.content.Context} which was used to create {@link Device} object. - */ - protected Context getContext() { - return serviceConnection.getContext(); - } - - /** - * Run given {@link Runnable} on the main thread. Helper method. - * - * @param runnable - * {@link Runnable} to execute on the main thread. - */ - protected void runOnMainThread(Runnable runnable) { - serviceConnection.runOnMainThread(runnable); - } - - /* package */Equipment getEquipmentWithCode(String equipmentCode) { - if (equipmentCode != null) { - for (Equipment eq : equipmentList) { - if (equipmentCode.equals(eq.getEquipmentData().getCode())) { - return eq; - } - } - } - return null; - } - - /* package */void equipmentRegistrationFinished(boolean result) { - isRegistered = result; - if (result) { - onFinishRegistration(); - } else { - onFailRegistration(); - } - } - - /* package */void equipmentUnregistrationFinished(boolean result) { - // no op - } - - /* package */void onReloadDeviceDataFinishedInternal(DeviceData deviceData) { - updateDeviceData(deviceData); - onFinishReloadingDeviceData(deviceData); - } - - private void updateDeviceData(DeviceData newDeviceData) { - this.deviceData = new DeviceData(deviceData.getId(), - deviceData.getKey(), newDeviceData.getName(), - newDeviceData.getStatus(), - newDeviceData.getDeviceClass()); - this.deviceData.setData((Serializable) newDeviceData.getData()); - for (Equipment equipment : equipmentList) { - this.deviceData.addEquipment(equipment.getEquipmentData()); - } - } - - /* package */void onReloadDeviceDataFailedInternal() { - onFailReloadingDeviceData(); - } - - private void onStartProcessingCommandsInternal() { - onStartProcessingCommands(); - for (Equipment equipment : equipmentList) { - equipment.onStartProcessingCommands(); - } - } - - private void onStopProcessingCommandsInternal() { - for (Equipment equipment : equipmentList) { - equipment.onStopProcessingCommands(); - } - onStopProcessingCommands(); - } -} diff --git a/app/src/main/java/com/dataart/android/devicehive/device/DeviceServiceConnection.java b/app/src/main/java/com/dataart/android/devicehive/device/DeviceServiceConnection.java deleted file mode 100644 index 9cfa8c9..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/device/DeviceServiceConnection.java +++ /dev/null @@ -1,379 +0,0 @@ -package com.dataart.android.devicehive.device; - -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Queue; -import java.util.concurrent.ExecutionException; - -import android.content.Context; -import android.os.Bundle; -import android.text.TextUtils; -import android.util.Log; - -import com.dataart.android.devicehive.ApiInfo; -import com.dataart.android.devicehive.Command; -import com.dataart.android.devicehive.DeviceData; -import com.dataart.android.devicehive.DeviceHive; -import com.dataart.android.devicehive.Notification; -import com.dataart.android.devicehive.commands.GetApiInfoCommand; -import com.dataart.android.devicehive.device.commands.GetDeviceCommand; -import com.dataart.android.devicehive.device.commands.PollDeviceCommandsCommand; -import com.dataart.android.devicehive.device.commands.RegisterDeviceCommand; -import com.dataart.android.devicehive.device.commands.SendNotificationCommand; -import com.dataart.android.devicehive.device.commands.UpdateCommandStatusCommand; -import com.dataart.android.devicehive.network.DeviceHiveResultReceiver; -import com.dataart.android.devicehive.network.NetworkCommand; -import com.dataart.android.devicehive.network.ServiceConnection; -import com.dataart.android.devicehive.device.future.SimpleCallableFuture; - -/* package */class DeviceServiceConnection extends ServiceConnection { - - private final static String EQUIPMENT_PARAMETER = "equipment"; - - private Device device; - - private final Queue commandQueue = new LinkedList(); - - private boolean isProcessingCommands = false; - private boolean isPollRequestInProgress = false; - - private String lastCommandPollTimestamp; - private Integer commandPollWaitTimeout; - - public DeviceServiceConnection(Context context) { - super(context); - } - - public void setLastCommandPollTimestamp(String timestamp) { - this.lastCommandPollTimestamp = timestamp; - } - - /* package */void setCommandPollWaitTimeout(Integer timeout) { - this.commandPollWaitTimeout = timeout; - } - - @Override - public void setApiEndpointUrl(String url) { - if (apiEndpointUrl != null && !apiEndpointUrl.equals(url)) { - isPollRequestInProgress = false; - } - super.setApiEndpointUrl(url); - } - - /* package */void sendNotification(Notification notification) { - logD("Sending notification: " + notification.getName()); - device.onStartSendingNotification(notification); - final DeviceData deviceData = device.getDeviceData(); - startNetworkCommand(new SendNotificationCommand(deviceData.getId(), - deviceData.getKey(), notification)); - } - - /* package */void startProcessingCommands() { - if (isProcessingCommands) { - stopProcessingCommands(); - } - isProcessingCommands = true; - executeNextCommand(); - } - - /* package */void stopProcessingCommands() { - detachResultReceiver(); - isProcessingCommands = false; - isPollRequestInProgress = false; - } - - /* package */void setDevice(Device device) { - this.device = device; - } - - /* package */boolean isProcessingCommands() { - return isProcessingCommands; - } - - /* package */void registerDevice() { - startNetworkCommand(new RegisterDeviceCommand(device.getDeviceData())); - } - - /* package */void unregisterDevice() { - logD("Unregistering device"); - unregisterEquipment(); - } - - /* package */void reloadDeviceData() { - final DeviceData deviceData = device.getDeviceData(); - startNetworkCommand(new GetDeviceCommand(deviceData.getId(), - deviceData.getKey())); - } - - private void runCommandOnRunner(final CommandRunner commandRunner, - final Command command) { - if (commandRunner.shouldRunCommandAsynchronously(command)) { - - asyncHandler.post(new Runnable() { - @Override - public void run() { - final SimpleCallableFuture future = commandRunner.runCommand(command); - -// Future.get() will block - so we call it in another thread, to keep normal command processing flow - new Thread(new Runnable() { - @Override - public void run() { - try { - final CommandResult result = future.get(); - mainThreadHandler.post(new Runnable() { - @Override - public void run() { - updateCommandStatus(command, result); - } - }); - } catch (InterruptedException e) { - e.printStackTrace(); - } catch (ExecutionException e) { - e.printStackTrace(); - } - } - }).start(); - } - }); - } else { - SimpleCallableFuture future = commandRunner.runCommand(command); - try { - CommandResult result = future.get(); - updateCommandStatus(command, result); - } catch (InterruptedException e) { - e.printStackTrace(); - } catch (ExecutionException e) { - e.printStackTrace(); - } - } - } - - @SuppressWarnings("rawtypes") - private void executeNextCommand() { - final Command command = commandQueue.poll(); - if (command != null) { - device.onBeforeRunCommand(command); - Object parameters = command.getParameters(); - if (parameters == null || !(parameters instanceof Map) - || !((Map) parameters).containsKey(EQUIPMENT_PARAMETER)) { - runCommandOnRunner(device, command); - } else { - Equipment equipment = device - .getEquipmentWithCode((String) ((Map) parameters) - .get(EQUIPMENT_PARAMETER)); - if (equipment != null) { - equipment.onBeforeRunCommand(command); - runCommandOnRunner(equipment, command); - } else { - updateCommandStatus(command, new CommandResult( - CommandResult.STATUS_FAILED, "Equipment not found")); - } - } - } else { - if (!isPollRequestInProgress) { - isPollRequestInProgress = true; - if (lastCommandPollTimestamp == null) { - // timestamp wasn't specified. Request and use server - // timestamp instead. - logD("Starting Get API info command"); - startNetworkCommand(new GetApiInfoCommand()); - } else { - startPollCommandsRequest(); - } - } - } - } - - private void startPollCommandsRequest() { - logD("Starting polling request with lastCommandPollTimestamp = " - + lastCommandPollTimestamp); - final DeviceData deviceData = device.getDeviceData(); - startNetworkCommand(new PollDeviceCommandsCommand(deviceData.getId(), - deviceData.getKey(), lastCommandPollTimestamp, - commandPollWaitTimeout)); - } - - private void updateCommandStatus(Command deviceCommand, CommandResult result) { - logD(String.format("Update command(%s) status(%s) and result(%s)", - deviceCommand.getCommand(), result.getStatus(), - result.getResult())); - final DeviceData deviceData = device.getDeviceData(); - startNetworkCommand(new UpdateCommandStatusCommand(deviceData.getId(), - deviceData.getKey(), deviceCommand.getId(), result)); - } - - private int enqueueCommands(List commands) { - if (commands == null || commands.isEmpty()) { - return 0; - } - int enqueuedCount = 0; - for (Command command : commands) { - if (TextUtils.isEmpty(command.getStatus())) { - boolean added = commandQueue.offer(command); - if (!added) { - Log.e(DeviceHive.TAG, - "Failed to add command to the command queue"); - } else { - enqueuedCount++; - } - } - } - return enqueuedCount; - } - - @Override - protected void onReceiveResult(final int resultCode, final int tagId, - final Bundle resultData) { - switch (resultCode) { - case DeviceHiveResultReceiver.MSG_HANDLED_RESPONSE: - logD("Handled response"); - if (tagId == TAG_REGISTER) { - DeviceData deviceData = RegisterDeviceCommand - .getDeviceData(resultData); - logD("Device registration finished with data: " + deviceData); - sendNotification(DeviceStatusNotification.STATUS_ONLINE); - } else if (tagId == TAG_SEND_NOTIFICATION) { - Notification notification = SendNotificationCommand - .getNotification(resultData); - logD("Notification sent with response: " + notification); - device.onFinishSendingNotification(notification); - if (!device.isRegistered()) { - registerEquipment(); - } - } else if (tagId == TAG_POLL_COMMANDS) { - logD("Poll request finished"); - isPollRequestInProgress = false; - List commands = PollDeviceCommandsCommand - .getCommands(resultData); - logD("-------Received commands: " + commands); - logD("Commands count: " + commands.size()); - int enqueuedCount = enqueueCommands(commands); - logD("Enqueued commands count: " + enqueuedCount); - if (!commands.isEmpty()) { - lastCommandPollTimestamp = commands - .get(commands.size() - 1).getTimestamp(); - } - if (isProcessingCommands) { - executeNextCommand(); - } - } else if (tagId == TAG_UPDATE_COMMAND_STATUS) { - Command command = UpdateCommandStatusCommand - .getUpdatedCommand(resultData); - logD("Updated command: " + command); - if (isProcessingCommands) { - executeNextCommand(); - } - } else if (tagId == TAG_GET_DEVICE) { - logD("Get device request finished"); - final DeviceData deviceData = GetDeviceCommand - .getDevice(resultData); - device.onReloadDeviceDataFinishedInternal(deviceData); - } else if (tagId == TAG_GET_API_INFO) { - final ApiInfo apiInfo = GetApiInfoCommand - .getApiInfo(resultData); - logD("Get API info request finished: " + apiInfo); - lastCommandPollTimestamp = apiInfo.getServerTimestamp(); - startPollCommandsRequest(); - } - break; - case DeviceHiveResultReceiver.MSG_EXCEPTION: - final Throwable exception = NetworkCommand.getThrowable(resultData); - Log.e(DeviceHive.TAG, "DeviceHiveResultReceiver.MSG_EXCEPTION", - exception); - case DeviceHiveResultReceiver.MSG_STATUS_FAILURE: - if (tagId == TAG_REGISTER) { - device.onFailRegistration(); - } - if (tagId == TAG_POLL_COMMANDS || tagId == TAG_GET_API_INFO) { - isPollRequestInProgress = false; - if (isProcessingCommands) { - executeNextCommand(); - } - } else if (tagId == TAG_UPDATE_COMMAND_STATUS) { - logD("Failed to update command status"); - // for now skip this command and try to execute next - if (isProcessingCommands) { - executeNextCommand(); - } - } else if (tagId == TAG_SEND_NOTIFICATION) { - SendNotificationCommand command = (SendNotificationCommand) NetworkCommand - .getCommand(resultData); - Notification notification = command.getNotification(); - device.onFailSendingNotification(notification); - if (!device.isRegistered()) { - device.onFailRegistration(); - } - } else if (tagId == TAG_GET_DEVICE) { - device.onReloadDeviceDataFailedInternal(); - } - break; - } - - } - - private final Runnable registerEquipmentRunnable = new Runnable() { - @Override - public void run() { - boolean equipmentRegistrationResult = true; - for (Equipment eq : device.getEquipment()) { - equipmentRegistrationResult = equipmentRegistrationResult - && eq.onRegisterEquipment(); - if (!equipmentRegistrationResult) { - break; - } - } - final boolean result = equipmentRegistrationResult; - mainThreadHandler.post(new Runnable() { - @Override - public void run() { - device.equipmentRegistrationFinished(result); - } - }); - } - }; - - private final Runnable unregisterEquipmentRunnable = new Runnable() { - @Override - public void run() { - boolean equipmentUnregistrationResult = true; - for (Equipment eq : device.getEquipment()) { - equipmentUnregistrationResult = equipmentUnregistrationResult - && eq.onUnregisterEquipment(); - if (!equipmentUnregistrationResult) { - break; - } - } - final boolean result = equipmentUnregistrationResult; - mainThreadHandler.post(new Runnable() { - @Override - public void run() { - device.equipmentUnregistrationFinished(result); - } - }); - } - }; - - private void registerEquipment() { - if (device.performsEquipmentRegistrationCallbacksAsynchronously()) { - asyncHandler.post(registerEquipmentRunnable); - } else { - registerEquipmentRunnable.run(); - } - } - - private void unregisterEquipment() { - if (device.performsEquipmentRegistrationCallbacksAsynchronously()) { - asyncHandler.post(unregisterEquipmentRunnable); - } else { - unregisterEquipmentRunnable.run(); - } - } - - private final static int TAG_REGISTER = getTagId(RegisterDeviceCommand.class); - private final static int TAG_SEND_NOTIFICATION = getTagId(SendNotificationCommand.class); - private final static int TAG_POLL_COMMANDS = getTagId(PollDeviceCommandsCommand.class); - private final static int TAG_UPDATE_COMMAND_STATUS = getTagId(UpdateCommandStatusCommand.class); - private final static int TAG_GET_DEVICE = getTagId(GetDeviceCommand.class); - private static final int TAG_GET_API_INFO = getTagId(GetApiInfoCommand.class); -} diff --git a/app/src/main/java/com/dataart/android/devicehive/device/DeviceStatusNotification.java b/app/src/main/java/com/dataart/android/devicehive/device/DeviceStatusNotification.java deleted file mode 100644 index e633ff5..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/device/DeviceStatusNotification.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.dataart.android.devicehive.device; - -import java.util.HashMap; - -import com.dataart.android.devicehive.DeviceData; -import com.dataart.android.devicehive.Notification; - -/** - * Represents a device status notification which is sent by {@link com.dataart.android.devicehive.device.Device} when - * its status changes. - */ -public class DeviceStatusNotification extends Notification { - - /** - * Predefined "Online" device status notification. - */ - public static final DeviceStatusNotification STATUS_ONLINE = new DeviceStatusNotification( - DeviceData.DEVICE_STATUS_ONLINE); - - /** - * Predefined "OK" device status notification. - */ - public static final DeviceStatusNotification STATUS_OK = new DeviceStatusNotification( - DeviceData.DEVICE_STATUS_OK); - - /** - * Construct device status notification with given device status. - * - * @param deviceStatus - * Device status value. - */ - public DeviceStatusNotification(String deviceStatus) { - super("DeviceStatus", parametersWithDeviceStatus(deviceStatus)); - } - - private static HashMap parametersWithDeviceStatus( - String deviceStatus) { - HashMap parameters = new HashMap(); - parameters.put("status", deviceStatus); - return parameters; - } -} diff --git a/app/src/main/java/com/dataart/android/devicehive/device/Equipment.java b/app/src/main/java/com/dataart/android/devicehive/device/Equipment.java deleted file mode 100644 index fd006af..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/device/Equipment.java +++ /dev/null @@ -1,119 +0,0 @@ -package com.dataart.android.devicehive.device; - -import com.dataart.android.devicehive.DeviceHive; -import com.dataart.android.devicehive.EquipmentData; - -import android.util.Log; - -/** - * Represents an abstract equipment which is installed on devices. This class is - * designed to be subclassed in order to represent specific equipment. - * Descendants should implement abstract methods of {@link CommandRunner} - * interface in order to execute commands. Also they may override various - * callbacks: {@link #onRegisterEquipment()}, {@link #onUnregisterEquipment()}, - * {@link #onStartProcessingCommands()}, {@link #onStopProcessingCommands()}, - * etc. - */ -public abstract class Equipment implements CommandRunner { - - private final EquipmentData equipmentData; - private Device device; - - /** - * Construct equipment with given {@link EquipmentData}. - * - * @param equipmentData - * {@link EquipmentData} object which describes equipment - * parameters. - */ - public Equipment(EquipmentData equipmentData) { - this.equipmentData = equipmentData; - } - - /** - * Get equipment data which describes equipment parameters. - * - * @return - */ - public EquipmentData getEquipmentData() { - return equipmentData; - } - - /** - * Get device which this equipment attached to. - * - * @return Corresponding {@link com.dataart.android.devicehive.device.Device} object or null, if - * equipment isn't attached to any device. - */ - public Device getDevice() { - return device; - } - - /* package */void setDevice(Device device) { - this.device = device; - } - - /** - * Send equipment notification. Equipment should be attached to a - * {@link com.dataart.android.devicehive.device.Device} and device should be registered in order for notification - * to be successfully sent. - * - * @param notification - * Notification to be sent. - */ - public void sendNotification(EquipmentNotification notification) { - if (device == null) { - Log.w(DeviceHive.TAG, "Equipment should be attached to a device in order to be able to send notifications"); - } else { - device.sendNotification(notification); - } - } - - /** - * Called as a part of device registration process. Override this method to - * perform any additional initialization. This method can be called either - * on main thread or some other thread. It depends on - * {@link com.dataart.android.devicehive.device.Device#performsEquipmentRegistrationCallbacksAsynchronously()} - * method's return value. - * - * @return true, if equipment is registered successfully, otherwise returns - * false. - */ - protected boolean onRegisterEquipment() { - return true; - } - - /** - * Called as a part of device deregistration process. Usually happens during - * connection loss. Override this method to perform any additional - * deinitialization. This method can be called either on main thread or some - * other thread. It depends on - * {@link com.dataart.android.devicehive.device.Device#performsEquipmentRegistrationCallbacksAsynchronously()} - * method's return value. - * - * @return true, if equipment is unregistered successfully, otherwise return - * false. - */ - protected boolean onUnregisterEquipment() { - return true; - } - - /** - * Called right after {@link com.dataart.android.devicehive.device.Device#startProcessingCommands()} method is - * called. Override this method to perform additional initialization or - * other actions. - */ - protected void onStartProcessingCommands() { - // no op - } - - /** - * Called right after {@link com.dataart.android.devicehive.device.Device#stopProcessingCommands()} method is - * called. Override this method to perform additional actions when device - * stops processing commands. - */ - protected void onStopProcessingCommands() { - // no op - } - -} diff --git a/app/src/main/java/com/dataart/android/devicehive/device/EquipmentNotification.java b/app/src/main/java/com/dataart/android/devicehive/device/EquipmentNotification.java deleted file mode 100644 index 3f29315..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/device/EquipmentNotification.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.dataart.android.devicehive.device; - -import java.util.HashMap; - -import com.dataart.android.devicehive.Notification; - -/** - * Represents a {@link Notification} which is usually sent by an - * {@link com.dataart.android.devicehive.device.Equipment} to update its state. - */ -public class EquipmentNotification extends Notification { - - /** - * Construct a notification with given equipment code and additional - * equipment parameters dictionary. - * - * @param equipmentCode - * Equipment code. - * @param parameters - * Equipment parameters dictionary. - */ - public EquipmentNotification(String equipmentCode, - HashMap parameters) { - super("equipment", equipmentParameters(equipmentCode, parameters)); - } - - private static HashMap equipmentParameters( - String equipmentCode, HashMap parameters) { - final HashMap equipmentParameters = new HashMap( - parameters); - parameters.put("equipment", equipmentCode); - return equipmentParameters; - } -} diff --git a/app/src/main/java/com/dataart/android/devicehive/device/commands/DeviceCommand.java b/app/src/main/java/com/dataart/android/devicehive/device/commands/DeviceCommand.java deleted file mode 100644 index abd68a2..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/device/commands/DeviceCommand.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.dataart.android.devicehive.device.commands; - -import java.util.Map; - -import android.os.Parcel; - -import com.dataart.android.devicehive.network.JsonNetworkCommand; - -/** - * Base command for Device Hive device-related commands. - */ -public abstract class DeviceCommand extends JsonNetworkCommand { - - protected final String deviceId; - protected final String deviceKey; - - /** - * Construct new command with given device data. - * - * @param deviceId - * Device identifier. - * @param deviceKey - * Device key. - */ - public DeviceCommand(String deviceId, String deviceKey) { - this.deviceId = deviceId; - this.deviceKey = deviceKey; - } - - /** - * Construct new command with given device data. - * - * @param deviceId - * Device identifier. - */ - public DeviceCommand(String deviceId) { - this(deviceId, null); - } - - protected boolean deviceAuthenticationRequired() { - return true; - } - - @Override - protected Map getHeaders() { - final Map headers = super.getHeaders(); - if (deviceAuthenticationRequired()) { - addDeviceAuthentication(headers); - } - return headers; - } - - protected String getEncodedDeviceId() { - return encodedString(deviceId); - } - - private void addDeviceAuthentication(Map headers) { -// headers.put("Auth-DeviceID", deviceId); -// headers.put("Auth-DeviceKey", deviceKey); - } - - @Override - public int describeContents() { - return 0; - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - dest.writeString(deviceId); - dest.writeString(deviceKey); - } - -} diff --git a/app/src/main/java/com/dataart/android/devicehive/device/commands/DeviceCommandsRetrivalCommand.java b/app/src/main/java/com/dataart/android/devicehive/device/commands/DeviceCommandsRetrivalCommand.java deleted file mode 100644 index a7a135c..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/device/commands/DeviceCommandsRetrivalCommand.java +++ /dev/null @@ -1,77 +0,0 @@ -package com.dataart.android.devicehive.device.commands; - -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.List; - -import android.os.Bundle; -import android.os.Parcel; - -import com.dataart.android.devicehive.Command; -import com.dataart.android.devicehive.DeviceData; -import com.dataart.android.devicehive.network.DeviceHiveResultReceiver; -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; - -/** - * Abstract base class for command retrieval-related commands. - */ -public abstract class DeviceCommandsRetrivalCommand extends DeviceCommand { - - private final static String NAMESPACE = DeviceCommandsRetrivalCommand.class - .getName(); - - private static final String COMMANDS_KEY = NAMESPACE - .concat(".COMMANDS_KEY"); - - protected final String lastCommandPollTimestamp; - - /** - * Construct a new command with given {@link DeviceData} and last received - * command timestamp. - * - * @param deviceId - * Device unique identifier. - * @param deviceKey - * Device key. - * @param lastCommandPollTimestamp - * Timestamp of the last received command. - */ - public DeviceCommandsRetrivalCommand(String deviceId, String deviceKey, - String lastCommandPollTimestamp) { - super(deviceId, deviceKey); - this.lastCommandPollTimestamp = lastCommandPollTimestamp; - } - - @Override - protected RequestType getRequestType() { - return RequestType.GET; - } - - @Override - protected String toJson(Gson gson) { - return null; - } - - @Override - protected int fromJson(final String response, final Gson gson, - final Bundle resultData) { - - Type listType = new TypeToken>() { - }.getType(); - - ArrayList commands = gson.fromJson(response, listType); - resultData.putParcelableArrayList(COMMANDS_KEY, commands); - return DeviceHiveResultReceiver.MSG_HANDLED_RESPONSE; - } - - public final static List getCommands(Bundle resultData) { - return resultData.getParcelableArrayList(COMMANDS_KEY); - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - super.writeToParcel(dest, flags); - dest.writeString(lastCommandPollTimestamp); - } -} diff --git a/app/src/main/java/com/dataart/android/devicehive/device/commands/GetDeviceCommand.java b/app/src/main/java/com/dataart/android/devicehive/device/commands/GetDeviceCommand.java deleted file mode 100644 index 9215ad5..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/device/commands/GetDeviceCommand.java +++ /dev/null @@ -1,93 +0,0 @@ -package com.dataart.android.devicehive.device.commands; - -import android.os.Bundle; -import android.os.Parcel; -import android.os.Parcelable; - -import com.dataart.android.devicehive.DeviceData; -import com.dataart.android.devicehive.network.DeviceHiveResultReceiver; -import com.google.gson.Gson; - -/** - * Get device object with given identifier. As a result returns - * {@link DeviceData} instance. - */ -public class GetDeviceCommand extends DeviceCommand { - - private final static String NAMESPACE = GetDeviceCommand.class.getName(); - - private static final String DEVICE_KEY = NAMESPACE.concat(".DEVICE_KEY"); - - /** - * Construct a new command. - * - * @param deviceId - * Device unique identifier. - * @param deviceKey - * Device key. - */ - public GetDeviceCommand(String deviceId, String deviceKey) { - super(deviceId, deviceKey); - } - - @Override - protected String toJson(Gson gson) { - return null; - } - - @Override - protected RequestType getRequestType() { - return RequestType.GET; - } - - @Override - protected String getRequestPath() { - String requestPath = String.format("/device/%s", getEncodedDeviceId()); - return requestPath; - } - - public static Parcelable.Creator CREATOR = new Parcelable.Creator() { - - @Override - public GetDeviceCommand[] newArray(int size) { - return new GetDeviceCommand[size]; - } - - @Override - public GetDeviceCommand createFromParcel(Parcel source) { - return new GetDeviceCommand(source.readString(), - source.readString()); - } - }; - - @Override - public int describeContents() { - return 0; - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - super.writeToParcel(dest, flags); - } - - @Override - protected int fromJson(final String response, final Gson gson, - final Bundle resultData) { - - final DeviceData device = gson.fromJson(response, DeviceData.class); - resultData.putParcelable(DEVICE_KEY, device); - return DeviceHiveResultReceiver.MSG_HANDLED_RESPONSE; - } - - /** - * Get {@link DeviceData} object from response {@link android.os.Bundle} container. - * - * @param resultData - * {@link android.os.Bundle} object containing required response data. - * @return {@link DeviceData} instance. - */ - public final static DeviceData getDevice(Bundle resultData) { - return resultData.getParcelable(DEVICE_KEY); - } - -} diff --git a/app/src/main/java/com/dataart/android/devicehive/device/commands/GetDeviceCommandsCommand.java b/app/src/main/java/com/dataart/android/devicehive/device/commands/GetDeviceCommandsCommand.java deleted file mode 100644 index 4102aa5..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/device/commands/GetDeviceCommandsCommand.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.dataart.android.devicehive.device.commands; - -import android.os.Parcel; -import android.os.Parcelable; - -import com.dataart.android.devicehive.DeviceData; - -/** - * Get commands for given device starting from given date timestamp. Server - * returns response immediately regardless of whether there are any commands for - * given device. - */ -public class GetDeviceCommandsCommand extends DeviceCommandsRetrivalCommand { - - /** - * Construct a new command with given {@link DeviceData} and last received - * command timestamp. - * - * @param deviceId - * Device unique identifier. - * @param deviceKey - * Device key. - * @param lastCommandPollTimestamp - * Timestamp of the last received command. If null value is - * passed then server will return all command it's received so - * far. - */ - public GetDeviceCommandsCommand(String deviceId, String deviceKey, - String lastCommandPollTimestamp) { - super(deviceId, deviceKey, lastCommandPollTimestamp); - } - - @Override - protected String getRequestPath() { - String requestPath = String.format("device/%s/command", - getEncodedDeviceId()); - if (lastCommandPollTimestamp != null) { - requestPath += "?start=" + encodedString(lastCommandPollTimestamp); - } - return requestPath; - } - - public static Parcelable.Creator CREATOR = new Parcelable.Creator() { - - @Override - public GetDeviceCommandsCommand[] newArray(int size) { - return new GetDeviceCommandsCommand[size]; - } - - @Override - public GetDeviceCommandsCommand createFromParcel(Parcel source) { - return new GetDeviceCommandsCommand(source.readString(), - source.readString(), source.readString()); - } - }; - -} diff --git a/app/src/main/java/com/dataart/android/devicehive/device/commands/PollDeviceCommandsCommand.java b/app/src/main/java/com/dataart/android/devicehive/device/commands/PollDeviceCommandsCommand.java deleted file mode 100644 index 70c070d..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/device/commands/PollDeviceCommandsCommand.java +++ /dev/null @@ -1,90 +0,0 @@ -package com.dataart.android.devicehive.device.commands; - -import android.os.Parcel; -import android.os.Parcelable; - -import com.dataart.android.devicehive.DeviceData; - -/** - * Poll for commands for given device starting from given date timestamp. In the - * case when no commands were found, the server doesn't return response until a - * new command is received. The blocking period is limited. - */ -public class PollDeviceCommandsCommand extends DeviceCommandsRetrivalCommand { - - private final Integer waitTimeout; - - /** - * Construct a new command with given {@link DeviceData} and last received - * command timestamp. - * - * @param deviceId - * Device unique identifier. - * @param deviceKey - * Device key. - * @param lastCommandPollTimestamp - * Timestamp of the last received command. If null value is - * passed then server's timestamp will be used instead. - */ - public PollDeviceCommandsCommand(String deviceId, String deviceKey, - String lastCommandPollTimestamp) { - this(deviceId, deviceKey, lastCommandPollTimestamp, null); - } - - /** - * Construct a new command with given {@link DeviceData} and last received - * command timestamp. - * - * @param deviceId - * Device unique identifier. - * @param deviceKey - * Device key. - * @param lastCommandPollTimestamp - * Timestamp of the last received command. If null value is - * passed then server's timestamp will be used instead. - * @param waitTimeout - * Waiting timeout in seconds. - */ - public PollDeviceCommandsCommand(String deviceId, String deviceKey, - String lastCommandPollTimestamp, Integer waitTimeout) { - super(deviceId, deviceKey, lastCommandPollTimestamp); - this.waitTimeout = waitTimeout; - } - - @Override - protected String getRequestPath() { - String requestPath = String.format("device/%s/command/poll", - getEncodedDeviceId()); - if (lastCommandPollTimestamp != null) { - requestPath += "?timestamp=" - + encodedString(lastCommandPollTimestamp); - } - if (waitTimeout != null) { - requestPath += lastCommandPollTimestamp != null ? "&" : "?"; - requestPath += "waitTimeout=" + waitTimeout; - } - return requestPath; - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - super.writeToParcel(dest, flags); - dest.writeValue(waitTimeout); - } - - public static Parcelable.Creator CREATOR = new Parcelable.Creator() { - - @Override - public PollDeviceCommandsCommand[] newArray(int size) { - return new PollDeviceCommandsCommand[size]; - } - - @Override - public PollDeviceCommandsCommand createFromParcel(Parcel source) { - return new PollDeviceCommandsCommand(source.readString(), - source.readString(), source.readString(), - (Integer) source.readValue(CLASS_LOADER)); - } - }; - -} diff --git a/app/src/main/java/com/dataart/android/devicehive/device/commands/RegisterDeviceCommand.java b/app/src/main/java/com/dataart/android/devicehive/device/commands/RegisterDeviceCommand.java deleted file mode 100644 index 5b5f26c..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/device/commands/RegisterDeviceCommand.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.dataart.android.devicehive.device.commands; - -import android.os.Bundle; -import android.os.Parcel; -import android.os.Parcelable; - -import com.dataart.android.devicehive.DeviceData; -import com.dataart.android.devicehive.network.DeviceHiveResultReceiver; -import com.google.gson.Gson; - -/** - * Register a new device which parameters are described by given - * {@link DeviceData} instance. - * - */ -public class RegisterDeviceCommand extends DeviceCommand { - - private final static String NAMESPACE = RegisterDeviceCommand.class - .getName(); - - private static final String DEVICE_DATA_KEY = NAMESPACE - .concat(".DEVICE_DATA_KEY"); - - private final DeviceData deviceData; - - /** - * Construct a new command with given {@link DeviceData}. - * - * @param deviceData - * {@link DeviceData} instance. - */ - public RegisterDeviceCommand(DeviceData deviceData) { - super(deviceData.getId(), deviceData.getKey()); - this.deviceData = deviceData; - } - - @Override - protected RequestType getRequestType() { - return RequestType.PUT; - } - - @Override - protected String getRequestPath() { - return String.format("device/%s", getEncodedDeviceId()); - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - dest.writeParcelable(deviceData, 0); - } - - public static Parcelable.Creator CREATOR = new Parcelable.Creator() { - - @Override - public RegisterDeviceCommand[] newArray(int size) { - return new RegisterDeviceCommand[size]; - } - - @Override - public RegisterDeviceCommand createFromParcel(Parcel source) { - return new RegisterDeviceCommand( - (DeviceData) source.readParcelable(CLASS_LOADER)); - } - }; - - @Override - protected String toJson(Gson gson) { - return gson.toJson(deviceData); - } - - @Override - protected int fromJson(final String response, final Gson gson, - final Bundle resultData) { - final DeviceData deviceData = gson.fromJson(response, DeviceData.class); - resultData.putParcelable(DEVICE_DATA_KEY, deviceData); - return DeviceHiveResultReceiver.MSG_HANDLED_RESPONSE; - } - - public final static DeviceData getDeviceData(Bundle resultData) { - return resultData.getParcelable(DEVICE_DATA_KEY); - } -} diff --git a/app/src/main/java/com/dataart/android/devicehive/device/commands/SendNotificationCommand.java b/app/src/main/java/com/dataart/android/devicehive/device/commands/SendNotificationCommand.java deleted file mode 100644 index 9ae3bee..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/device/commands/SendNotificationCommand.java +++ /dev/null @@ -1,101 +0,0 @@ -package com.dataart.android.devicehive.device.commands; - -import android.os.Bundle; -import android.os.Parcel; -import android.os.Parcelable; - -import com.dataart.android.devicehive.DeviceData; -import com.dataart.android.devicehive.Notification; -import com.dataart.android.devicehive.network.DeviceHiveResultReceiver; -import com.google.gson.Gson; - -/** - * Send a new notification from the given device. As a result returns - * {@link Notification} instance from the server response. - * - */ -public class SendNotificationCommand extends DeviceCommand { - - private final static String NAMESPACE = SendNotificationCommand.class - .getName(); - - private static final String NOTIFICATION_DATA_KEY = NAMESPACE - .concat(".NOTIFICATION_DATA_KEY"); - - private final Notification notification; - - /** - * Construct a new command with given {@link DeviceData} and last received - * command timestamp. - * - * @param deviceId - * Device unique identifier. - * @param deviceKey - * Device key. - * @param notification - * {@link Notification} to be sent on behalf of given device. - */ - public SendNotificationCommand(String deviceId, String deviceKey, - Notification notification) { - super(deviceId, deviceKey); - this.notification = notification; - } - - /** - * Get {@link Notification} to be sent. - * @return {@link Notification} instance. - */ - public Notification getNotification() { - return notification; - } - - @Override - protected RequestType getRequestType() { - return RequestType.POST; - } - - @Override - protected String getRequestPath() { - return String.format("device/%s/notification", getEncodedDeviceId()); - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - super.writeToParcel(dest, flags); - dest.writeParcelable(notification, 0); - } - - public static Parcelable.Creator CREATOR = new Parcelable.Creator() { - - @Override - public SendNotificationCommand[] newArray(int size) { - return new SendNotificationCommand[size]; - } - - @Override - public SendNotificationCommand createFromParcel(Parcel source) { - return new SendNotificationCommand( - source.readString(), - source.readString(), - (Notification) source.readParcelable(CLASS_LOADER)); - } - }; - - @Override - protected String toJson(Gson gson) { - return gson.toJson(notification); - } - - @Override - protected int fromJson(final String response, final Gson gson, - final Bundle resultData) { - final Notification notification = gson.fromJson(response, - Notification.class); - resultData.putParcelable(NOTIFICATION_DATA_KEY, notification); - return DeviceHiveResultReceiver.MSG_HANDLED_RESPONSE; - } - - public final static Notification getNotification(Bundle resultData) { - return resultData.getParcelable(NOTIFICATION_DATA_KEY); - } -} diff --git a/app/src/main/java/com/dataart/android/devicehive/device/commands/UpdateCommandStatusCommand.java b/app/src/main/java/com/dataart/android/devicehive/device/commands/UpdateCommandStatusCommand.java deleted file mode 100644 index 4ad918b..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/device/commands/UpdateCommandStatusCommand.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.dataart.android.devicehive.device.commands; - -import android.os.Bundle; -import android.os.Parcel; -import android.os.Parcelable; - -import com.dataart.android.devicehive.Command; -import com.dataart.android.devicehive.DeviceData; -import com.dataart.android.devicehive.device.CommandResult; -import com.dataart.android.devicehive.network.DeviceHiveResultReceiver; -import com.google.gson.Gson; - -/** - * Update status of given command with given {@link #commandResult}. As a result - * returns updated {@link Command} instance returned by the server. - * - */ -public class UpdateCommandStatusCommand extends DeviceCommand { - - private final static String NAMESPACE = UpdateCommandStatusCommand.class - .getName(); - - private static final String COMMAND_KEY = NAMESPACE.concat(".COMMAND_KEY"); - - private final int commandId; - private final CommandResult commandResult; - - /** - * Construct a new update command with given {@link DeviceData} and - * identifier of the command to update with {@link CommandResult}. - * - * @param deviceId - * Device unique identifier. - * @param deviceKey - * Device key. - * @param commandId - * {@link Command} to be updated. - * @param commandResult - * {@link CommandResult} object describing command status. - */ - public UpdateCommandStatusCommand(String deviceId, String deviceKey, int commandId, - CommandResult commandResult) { - super(deviceId, deviceKey); - this.commandId = commandId; - this.commandResult = commandResult; - } - - @Override - protected RequestType getRequestType() { - return RequestType.PUT; - } - - @Override - protected String getRequestPath() { - return String.format("device/%s/command/%d", getEncodedDeviceId(), - commandId); - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - super.writeToParcel(dest, flags); - dest.writeInt(commandId); - dest.writeParcelable(commandResult, 0); - } - - public static Parcelable.Creator CREATOR = new Parcelable.Creator() { - - @Override - public UpdateCommandStatusCommand[] newArray(int size) { - return new UpdateCommandStatusCommand[size]; - } - - @Override - public UpdateCommandStatusCommand createFromParcel(Parcel source) { - return new UpdateCommandStatusCommand( - source.readString(), - source.readString(), - source.readInt(), - (CommandResult) source.readParcelable(CLASS_LOADER)); - } - }; - - @Override - protected String toJson(Gson gson) { - return commandResult.toJson(); - } - - @Override - protected int fromJson(final String response, final Gson gson, - final Bundle resultData) { - final Command command = gson.fromJson(response, Command.class); - resultData.putParcelable(COMMAND_KEY, command); - return DeviceHiveResultReceiver.MSG_HANDLED_RESPONSE; - } - - public final static Command getUpdatedCommand(Bundle resultData) { - return resultData.getParcelable(COMMAND_KEY); - } -} diff --git a/app/src/main/java/com/dataart/android/devicehive/device/future/CallableFuture.java b/app/src/main/java/com/dataart/android/devicehive/device/future/CallableFuture.java deleted file mode 100644 index 579fc5d..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/device/future/CallableFuture.java +++ /dev/null @@ -1,103 +0,0 @@ -package com.dataart.android.devicehive.device.future; - -import java.util.concurrent.ExecutionException; -import java.util.concurrent.RunnableFuture; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - -/** - * Created by Constantine Mars on 4/1/15. - * - * Can be called and can return future result - * This implementation of callable future blocks on .get() and returns only after notification from any thread about result by calling .call(arg) - * It also can be used as simple wrapper for value in case of construction with argument or setting arg by .setArg(arg) - - * in that case CallableFuture will not block on .get() and return immediately - */ -public class CallableFuture implements RunnableFuture { - - private CallableWithArg callable; - private T result; - private U arg; - private boolean done; - private boolean getDone = false; - - public CallableFuture(CallableWithArg callable) { this.callable = callable; } - - public void call(U arg) { - this.arg = arg; - new Thread(this).start(); - } - -// Unlocks .get() immediately - public void setArg(U arg) { - this.arg = arg; - result = this.callable.call(this.arg); - } - - public CallableFuture(CallableWithArg callable, U arg) { - this.callable = callable; - this.arg = arg; - result = this.callable.call(this.arg); - } - - @Override - public boolean cancel(boolean mayInterruptIfRunning) { - return false; - } - - @Override - public boolean isCancelled() { - return false; - } - - @Override - public boolean isDone() { - return done; - } - - public boolean isGetDone() { - return getDone; - } - - @Override - public T get() throws InterruptedException, ExecutionException { - if (result == null) { - synchronized (this) { - wait(); - } - } - - getDone = true; - return result; - } - - @Override - public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException - { - if (result == null) { - synchronized (this) { - wait(); - } - } - - getDone = true; - return result; - } - - @Override - public void run() { - done = false; - try { - result = callable.call(arg); - } catch (Exception e) { - e.printStackTrace(); - } - done = true; - - synchronized (this) { notifyAll(); } - } - - public interface CallableWithArg { - T call(U u); - } -} diff --git a/app/src/main/java/com/dataart/android/devicehive/device/future/CmdResFuture.java b/app/src/main/java/com/dataart/android/devicehive/device/future/CmdResFuture.java deleted file mode 100644 index 3cc7353..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/device/future/CmdResFuture.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.dataart.android.devicehive.device.future; - -import com.dataart.android.devicehive.device.CommandResult; - -/** - * Created by Constantine Mars on 4/9/15. - * - * CallableFuture implementation for single type - CommandResult - */ -public class CmdResFuture extends SimpleCallableFuture { - public CmdResFuture(CommandResult arg) { - super(arg); - } - - public CmdResFuture() { - super(null); - } -} diff --git a/app/src/main/java/com/dataart/android/devicehive/device/future/SimpleCallableFuture.java b/app/src/main/java/com/dataart/android/devicehive/device/future/SimpleCallableFuture.java deleted file mode 100644 index 8785e24..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/device/future/SimpleCallableFuture.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.dataart.android.devicehive.device.future; - -/** - * Created by Constantine Mars on 4/1/15. - * - * Simplified version of CallableFuture for use with single type for in and out parameters - */ -public class SimpleCallableFuture extends CallableFuture { - public SimpleCallableFuture() { - super(new SimpleCallableWithArg()); - } - - public SimpleCallableFuture(T arg) { - super(new SimpleCallableWithArg(), arg); - } - - public static class SimpleCallableWithArg implements CallableWithArg { - @Override - public T call(T arg) { - return arg; - } - } -} diff --git a/app/src/main/java/com/dataart/android/devicehive/network/DeviceHiveApiService.java b/app/src/main/java/com/dataart/android/devicehive/network/DeviceHiveApiService.java deleted file mode 100644 index bd09c70..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/network/DeviceHiveApiService.java +++ /dev/null @@ -1,148 +0,0 @@ -package com.dataart.android.devicehive.network; - -import java.util.LinkedList; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.Executor; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; - -import android.app.Service; -import android.content.Intent; -import android.os.IBinder; -import android.util.Log; - -import com.dataart.android.devicehive.DeviceHive; - -/** - * Android {@link android.app.Service} subclass which is used to concurrently execute - * commands sent via {@link android.content.Intent}. This service should be declared in - * AndroidManifest.xml file. Can execute commands either concurrently or in FIFO - * order. - * - * @see {@link com.dataart.android.devicehive.network.NetworkCommand#isSerial()} - */ -public class DeviceHiveApiService extends Service { - - private final static String NAMESPACE = DeviceHiveApiService.class - .getName(); - - /* package */final static String EXTRA_COMMAND = NAMESPACE - .concat(".EXTRA_COMMAND"); - - /* package */final static String EXTRA_COMMAND_CONFIG = NAMESPACE - .concat(".EXTRA_COMMAND_CONFIG"); - - /* package */final static String EXTRA_COMMAND_SERIAL = NAMESPACE - .concat(".EXTRA_COMMAND_SERIAL"); - - private final static ThreadFactory threadFactory = new ThreadFactory() { - - private final AtomicInteger threadSerialNumber = new AtomicInteger(0); - - @Override - public Thread newThread(Runnable r) { - final Thread thread = new Thread(r, "[DeviceHiveApiService #" - + threadSerialNumber.getAndIncrement() + "]"); - thread.setDaemon(true); - return thread; - } - }; - - private final ConcurrentLinkedQueue commandStartIdQueue = new ConcurrentLinkedQueue(); - - private final static ThreadPoolExecutor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor( - 4, 6, 1, TimeUnit.SECONDS, new LinkedBlockingQueue(10), - threadFactory); - - private final static SerialExecutor SERIAL_EXECUTOR = new SerialExecutor(); - - private static class SerialExecutor implements Executor { - private final LinkedList tasks = new LinkedList(); - private Runnable activeTask; - - public synchronized void execute(final Runnable r) { - tasks.offer(new Runnable() { - public void run() { - try { - r.run(); - } finally { - scheduleNext(); - } - } - }); - if (activeTask == null) { - scheduleNext(); - } - } - - protected synchronized void scheduleNext() { - activeTask = tasks.poll(); - if (activeTask != null) { - THREAD_POOL_EXECUTOR.execute(activeTask); - } - } - } - - @Override - public IBinder onBind(Intent intent) { - return null; - } - - @Override - public int onStartCommand(final Intent intent, final int flags, - final int startId) { - commandStartIdQueue.add(startId); - final Runnable runnable = new Runnable() { - @Override - public void run() { - try { - handleIntent(intent); - } finally { - stopSelf(commandStartIdQueue.remove()); - } - } - }; - if (intent.getBooleanExtra(EXTRA_COMMAND_SERIAL, false)) { - SERIAL_EXECUTOR.execute(runnable); - } else { - THREAD_POOL_EXECUTOR.execute(runnable); - } - return START_NOT_STICKY; - } - - protected void handleIntent(Intent intent) { - NetworkCommand command = null; - NetworkCommandConfig config = null; - final long startTime = System.currentTimeMillis(); - try { - command = intent.getParcelableExtra(EXTRA_COMMAND); - if (command != null) { - config = intent.getParcelableExtra(EXTRA_COMMAND_CONFIG); - if (config != null) { - if (config.isDebugLoggingEnabled) { - Log.d(DeviceHive.TAG, "Starting command " + command); - } - command.setConfig(config); - command.execute(this); - } else { - Log.w(DeviceHive.TAG, "Missing command config in " + intent); - } - } else { - Log.w(DeviceHive.TAG, "Missing command in " + intent); - } - } catch (Exception e) { - Log.e(DeviceHive.TAG, "Cannot process command " + command, e); - } finally { - if (command != null && config != null) { - if (config.isDebugLoggingEnabled) { - Log.d(DeviceHive.TAG, "Completed command " + command - + " in " + (System.currentTimeMillis() - startTime)); - } - } - } - } - -} diff --git a/app/src/main/java/com/dataart/android/devicehive/network/DeviceHiveResultReceiver.java b/app/src/main/java/com/dataart/android/devicehive/network/DeviceHiveResultReceiver.java deleted file mode 100644 index cf3f2e0..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/network/DeviceHiveResultReceiver.java +++ /dev/null @@ -1,163 +0,0 @@ -package com.dataart.android.devicehive.network; - -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.atomic.AtomicInteger; - -import android.os.Bundle; -import android.os.Handler; -import android.os.HandlerThread; -import android.os.ResultReceiver; -import android.util.Log; - -import com.dataart.android.devicehive.DeviceHive; - -/** - * Result receiver which is used to communicate(receive results) with service. - */ -public class DeviceHiveResultReceiver extends ResultReceiver { - - /** - * Message with this code is sent when request is started. - */ - public final static int MSG_EXECUTE_REQUEST = 0x00000010; - - /** - * Message with this code is sent to the result receiver when request is - * finished regardless of whether it succeeds or fails. - */ - public final static int MSG_COMPLETE_REQUEST = 0x00000011; - - /** - * Message with this code is sent to the result receiver when response of - * the request is handled(parsed). - */ - public final static int MSG_HANDLED_RESPONSE = 0x00000012; - - /** - * Message with this code is sent to the result receiver fails and returns - * corresponding Http status code. - */ - public final static int MSG_STATUS_FAILURE = 0x00000013; - - /** - * Message with this code is sent to the result receiver when request fails - * due to connectivity loss or IO error that usually lead to exception to be - * thrown. - */ - public final static int MSG_EXCEPTION = 0x0FFFFFFF; - - /** - * Result listener interface. - */ - public static interface ResultListener { - /** - * Called when result receiver receives results from the service. - * - * @param code - * Status code of the result. - * @param tag - * Tag value. - * @param data - * {@link android.os.Bundle} which contains command execution results. - */ - void onReceiveResult(int code, int tag, Bundle data); - } - - private final static Handler mainThreadHandler = new Handler(); - private final static Handler receiverHandler; - - static { - final HandlerThread thread = new HandlerThread( - DeviceHiveResultReceiver.class.getSimpleName() - + "[Handler Thread]"); - thread.start(); - receiverHandler = new Handler(thread.getLooper()); - } - - private static class ResultListenerConfig { - private final ResultListener listener; - private final boolean runOnMainThread; - - public ResultListenerConfig(ResultListener listener, - boolean runOnMainThread) { - this.listener = listener; - this.runOnMainThread = runOnMainThread; - } - } - - private ResultListenerConfig resultListenerConfig = null; - - public DeviceHiveResultReceiver() { - super(receiverHandler); - } - - /** - * Detach result listener from the result receiver. - */ - public void detachResultListener() { - this.resultListenerConfig = null; - } - - /** - * Set result listener. - * - * @param listener - * {@link com.dataart.android.devicehive.network.DeviceHiveResultReceiver.ResultListener} instance. - * @param runOnMainThread - * Whether - * {@link com.dataart.android.devicehive.network.DeviceHiveResultReceiver.ResultListener#onReceiveResult(int, int, android.os.Bundle)} - * should run on the main Thread. - */ - public void setResultListener(final ResultListener listener, - final boolean runOnMainThread) { - this.resultListenerConfig = new ResultListenerConfig(listener, - runOnMainThread); - } - - @Override - protected void onReceiveResult(final int resultCode, final Bundle resultData) { - if (resultListenerConfig != null) { - final int commandTagId = getIdForTag(NetworkCommand - .getCommandTag(resultData)); - if (resultListenerConfig.runOnMainThread) { - mainThreadHandler.post(new Runnable() { - @Override - public void run() { - if (resultListenerConfig != null) { - resultListenerConfig.listener.onReceiveResult( - resultCode, commandTagId, resultData); - } - } - }); - } else { - resultListenerConfig.listener.onReceiveResult(resultCode, - commandTagId, resultData); - } - } else { - Log.w(DeviceHive.TAG, String.format( - "Received result in detached listener: %s, %s", resultCode, - resultData)); - } - } - - /** - * Get tag id for given command tag. Returns the same value for equal tag - * strings. - * - * @param tag - * Command tag. - * @return Integer value corresponding to the tag. - */ - public static final int getIdForTag(final String tag) { - Integer id = existingTags.get(tag); - if (id == null) { - id = tagIdCounter.incrementAndGet(); - existingTags.put(tag, id); - } - return id.intValue(); - } - - private final static AtomicInteger tagIdCounter = new AtomicInteger(0); - private final static Map existingTags = new HashMap(); -} diff --git a/app/src/main/java/com/dataart/android/devicehive/network/JsonNetworkCommand.java b/app/src/main/java/com/dataart/android/devicehive/network/JsonNetworkCommand.java deleted file mode 100644 index 456e221..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/network/JsonNetworkCommand.java +++ /dev/null @@ -1,152 +0,0 @@ -package com.dataart.android.devicehive.network; - -import java.io.Serializable; -import java.io.UnsupportedEncodingException; -import java.lang.reflect.Type; -import java.net.URLEncoder; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -import org.apache.http.HttpEntity; -import org.apache.http.entity.StringEntity; - -import android.content.Context; -import android.os.Bundle; -import android.util.Log; - -import com.dataart.android.devicehive.DeviceHive; -import com.dataart.android.devicehive.ObjectWrapper; -import com.google.gson.FieldNamingPolicy; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.JsonPrimitive; -import com.google.gson.JsonSerializationContext; -import com.google.gson.JsonSerializer; - -/** - * Base command for JSON-related commands. - * - */ -public abstract class JsonNetworkCommand extends NetworkCommand { - - private final static Gson gson; - - static { - GsonBuilder builder = new GsonBuilder(); - builder.setFieldNamingPolicy(FieldNamingPolicy.IDENTITY); - builder.registerTypeAdapter(ObjectWrapper.class, - new ObjectWrapperAdapter()); - gson = builder.create(); - } - - private static class ObjectWrapperAdapter implements - JsonDeserializer>, - JsonSerializer> { - - public JsonElement serialize(ObjectWrapper src, - Type typeOfSrc, JsonSerializationContext context) { - return context.serialize(src.getObject()); - } - - @Override - public ObjectWrapper deserialize(JsonElement json, - Type typeOfT, JsonDeserializationContext context) - throws JsonParseException { - - return new ObjectWrapper( - (Serializable) parseElement(json)); - } - - private Object parseElement(JsonElement jsonElement) { - if (jsonElement.isJsonPrimitive()) { - return parsePrimitive(jsonElement.getAsJsonPrimitive()); - } else if (jsonElement.isJsonArray()) { - return parseArray(jsonElement.getAsJsonArray()); - } else { - return parseObject(jsonElement.getAsJsonObject()); - } - } - - private Object parsePrimitive(JsonPrimitive primitive) { - if (primitive.isBoolean()) { - return primitive.getAsBoolean(); - } else if (primitive.isNumber()) { - return primitive.getAsDouble(); - } else { - return primitive.getAsString(); - } - } - - private ArrayList parseArray(JsonArray jsonArray) { - final int size = jsonArray.size(); - ArrayList result = new ArrayList(size); - for (int i = 0; i < size; i++) { - result.add(parseElement(jsonArray.get(i))); - } - return result; - } - - private Object parseObject(JsonObject jsonObject) { - HashMap result = new HashMap(); - final Set> entrySet = jsonObject - .entrySet(); - for (Entry property : entrySet) { - result.put(property.getKey(), parseElement(property.getValue())); - } - return result; - } - } - - @Override - protected Map getHeaders() { - final Map headers = new HashMap(); - headers.put("Content-Type", "application/json; charset=utf-8"); - return headers; - } - - @Override - protected HttpEntity getRequestEntity() { - String data = toJson(gson); - HttpEntity entity = null; - try { - entity = new StringEntity(data, "utf-8"); - - - } catch (UnsupportedEncodingException e) { - Log.e(DeviceHive.TAG, "Failed to create entity", e); - } - return entity; - } - - protected abstract String toJson(final Gson gson); - - protected abstract int fromJson(final String response, final Gson gson, - final Bundle resultData); - - @Override - protected int handleResponse(final String response, - final Bundle resultData, final Context context) { - - return fromJson(response, gson, resultData); - } - - protected static String encodedString(String stringToEncode) { - String encodedString = null; - try { - encodedString = URLEncoder.encode(stringToEncode, "UTF-8"); - } catch (UnsupportedEncodingException e) { - throw new IllegalStateException("String to encode is illegal"); - } - return encodedString; - } - -} diff --git a/app/src/main/java/com/dataart/android/devicehive/network/NetworkCommand.java b/app/src/main/java/com/dataart/android/devicehive/network/NetworkCommand.java deleted file mode 100644 index 8137dff..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/network/NetworkCommand.java +++ /dev/null @@ -1,391 +0,0 @@ -package com.dataart.android.devicehive.network; - -import android.content.Context; -import android.content.Intent; -import android.os.Bundle; -import android.os.Parcelable; -import android.util.Log; - -import com.dataart.android.devicehive.DeviceHive; -import com.dataart.obd2.devicehive.DevicePreferences; - -import org.apache.http.Header; -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.HttpVersion; -import org.apache.http.auth.UsernamePasswordCredentials; -import org.apache.http.client.ClientProtocolException; -import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.HttpDelete; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpPut; -import org.apache.http.client.methods.HttpUriRequest; -import org.apache.http.conn.scheme.PlainSocketFactory; -import org.apache.http.conn.scheme.Scheme; -import org.apache.http.conn.scheme.SchemeRegistry; -import org.apache.http.conn.ssl.SSLSocketFactory; -import org.apache.http.impl.auth.BasicScheme; -import org.apache.http.impl.client.DefaultHttpClient; -import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; -import org.apache.http.params.BasicHttpParams; -import org.apache.http.params.HttpConnectionParams; -import org.apache.http.params.HttpParams; -import org.apache.http.params.HttpProtocolParams; -import org.apache.http.util.EntityUtils; - -import java.io.IOException; -import java.util.Map; - -/** - * Common base class for all service commands. - */ -public abstract class NetworkCommand implements Parcelable { - - protected final static ClassLoader CLASS_LOADER = NetworkCommand.class - .getClassLoader(); - - private final static String NAMESPACE = NetworkCommand.class.getName(); - - private final static String KEY_TAG = NAMESPACE.concat(".KEY_TAG"); - - private final static String KEY_STATUS_CODE = NAMESPACE - .concat(".KEY_STATUS_CODE"); - - private final static String KEY_EXCEPTION = NAMESPACE - .concat(".KEY_EXCEPTION"); - - private final static String KEY_COMMAND = NAMESPACE.concat(".KEY_COMMAND"); - - private NetworkCommandConfig config; - - private static final HttpClient client = getClient(); - - // timeouts - private static final int DEFAULT_CONNECTION_TIMEOUT_MILLIS = 40000; - private static final int DEFAULT_SOCKET_TIMEOUT_MILLIS = 40000; - - /** - * Http request type. - */ - protected static enum RequestType { - GET, POST, PUT, DELETE - } - - /** - * Start this command using given {@link android.content.Context} and {@link android.os.ResultReceiver} - * . - * - * @param context - * {@link android.content.Context} instance which is used to start command. - * @param config - * {@link NetworkCommandConfig} instance which contains configuration data for given command. - */ - public void start(final Context context, final NetworkCommandConfig config) { - final Intent intent = new Intent(context, DeviceHiveApiService.class); - intent.putExtra(DeviceHiveApiService.EXTRA_COMMAND, this); - intent.putExtra(DeviceHiveApiService.EXTRA_COMMAND_CONFIG, config); - intent.putExtra(DeviceHiveApiService.EXTRA_COMMAND_SERIAL, isSerial()); - context.startService(intent); - } - - /* package */ void setConfig(NetworkCommandConfig config) { - this.config = config; - } - - /** - * Override this method in order to force commands to be executed in a - * "serial" mode, i.e. in order they submitted (in single executor). Default - * implementation returns false. - * - * @return true, if command should be executed in "serial" mode, otherwise - * return false. - */ - protected boolean isSerial() { - return false; - } - - /** - * This convenient method is used to ensure the bundle has correct - * command-tag. - * - * @return Tagged {@link android.os.Bundle} instance. - */ - protected final Bundle getTaggedBundle() { - return getTaggedBundle(0); - } - - /** - * Create a {@link android.os.Bundle} instance and ensure the bundle has correct - * command-tag. - * - * @param capacity - * {@link android.os.Bundle} initial capacity. - * @return Tagged {@link android.os.Bundle} instance. - */ - protected final Bundle getTaggedBundle(final int capacity) { - final Bundle bundle = capacity > 0 ? new Bundle(capacity + 1) - : new Bundle(); - bundle.putString(KEY_TAG, getClass().getName()); - return bundle; - } - - /** - * Get Http request type. - * - * @returnm {@link com.dataart.android.devicehive.network.NetworkCommand.RequestType} - */ - protected abstract RequestType getRequestType(); - - /** - * Get request path component. - * - * @return Request path component. - */ - protected abstract String getRequestPath(); - - /** - * Get request headers. - * - * @return Request headers. - */ - protected abstract Map getHeaders(); - - /** - * Get {@link org.apache.http.HttpEntity} for the request. Override this method to return - * appropriate entity for POST and PUT requests. - * - * @return {@link org.apache.http.HttpEntity} implementer instance. - */ - protected HttpEntity getRequestEntity() { - return null; - } - - /** - * Check if given status code is considered as successful for this request. - * Can be overridden in descendants. - * - * @param statusCode - * Response status code. - */ - protected boolean isSuccessStatusCode(int statusCode) { - return statusCode == 200 || statusCode == 201; - } - - /** - * Handle response. - * @param response String representation of the response body. - * @param resultData {@link android.os.Bundle} which is used to put and pass the results of command execution to the sender. - * @param context Current {@link android.content.Context} object. - * @return Status code. - * @see {@link DeviceHiveResultReceiver}. - */ - protected int handleResponse(final String response, - final Bundle resultData, final Context context) { - return -1; - } - - /** - * Execute command. Called by the service on the dedicated thread. - * @param context Current {@link android.content.Context} object. - */ - protected void execute(Context context) { - logD("Request started"); - final long start = System.currentTimeMillis(); - final Bundle resultData = getTaggedBundle(); - resultData.putParcelable(KEY_COMMAND, this); - send(DeviceHiveResultReceiver.MSG_EXECUTE_REQUEST, resultData); - - HttpUriRequest httpRequest = toHttpRequest(); - addHeaders(httpRequest); -// final UsernamePasswordCredentials creds = config.getAuthorization(); -// if (creds != null) { -// //addBasicAuthenticationHeader(httpRequest, creds); -// } - - try { - HttpResponse responce = client.execute(httpRequest); - final int statusCode = responce.getStatusLine().getStatusCode(); - HttpEntity entity = responce.getEntity(); - - String responceString = ""; - if(entity != null) { - responceString = EntityUtils.toString(entity); - } else { - responceString = ""; - } - - - logD("Responce status code: " + statusCode); - logD("Responce body: " + responceString); - resultData.putInt(KEY_STATUS_CODE, statusCode); - if (!isSuccessStatusCode(statusCode)) { - logD("Responce code is not OK. Responce body: " - + responceString); - send(DeviceHiveResultReceiver.MSG_STATUS_FAILURE, resultData); - } else { - final int resultCode = handleResponse(responceString, - resultData, context); - if (resultCode > 0) { - send(resultCode, resultData); - } - } - } catch (ClientProtocolException e) { - Log.e(DeviceHive.TAG, "Failed to execute request: ", e); - resultData.putSerializable(KEY_EXCEPTION, e); - send(DeviceHiveResultReceiver.MSG_EXCEPTION, resultData); - } catch (IOException e) { - Log.e(DeviceHive.TAG, "Failed to execute request: ", e); - resultData.putSerializable(KEY_EXCEPTION, e); - send(DeviceHiveResultReceiver.MSG_EXCEPTION, resultData); - } finally { - send(DeviceHiveResultReceiver.MSG_COMPLETE_REQUEST, resultData); - long end = System.currentTimeMillis(); - logD(String.format("Request to %s completed: ", getTargetUrl()) - + (end - start) + "ms"); - } - } - - private HttpUriRequest addBasicAuthenticationHeader(HttpUriRequest request, - UsernamePasswordCredentials creds) { - Header hdr = BasicScheme.authenticate(creds, "utf-8", false); - request.addHeader(hdr); - return request; - } - - private void send(final int resultCode, Bundle resultData) { - if (config != null && config.resultReceiver != null) { - if (resultData == null) { - resultData = getTaggedBundle(); - } else if (!resultData.containsKey(KEY_TAG)) { - resultData.putString(KEY_TAG, getClass().getName()); - } - config.resultReceiver.send(resultCode, resultData); - } - } - - private String getTargetUrl() { - String url = config.baseUrl + "/" + getRequestPath(); - return url; - } - - private void addHeaders(HttpUriRequest request) { - Map headers = getHeaders(); - for (Map.Entry header : headers.entrySet()) { - request.addHeader(header.getKey(), header.getValue()); - } - - DevicePreferences pref = new DevicePreferences(); - String s = "Bearer " + pref.getAccessKey(); - - request.addHeader("Authorization", s); - } - - private HttpUriRequest toHttpRequest() { - String requestUrl = getTargetUrl(); - switch (getRequestType()) { - case POST: { - HttpPost request = new HttpPost(requestUrl); - HttpEntity entity = getRequestEntity(); - if (entity != null) { - request.setEntity(entity); - } - return request; - } - case GET: { - return new HttpGet(requestUrl); - } - case PUT: { - HttpPut request = new HttpPut(requestUrl); - HttpEntity entity = getRequestEntity(); - if (entity != null) { - request.setEntity(entity); - } - return request; - } - case DELETE: { - return new HttpDelete(requestUrl); - } - default: - logD("Unrecognized request type: " + getRequestType()); - return null; - } - } - - private static DefaultHttpClient getClient() { - HttpParams params = getDefaultHttpParams(); - SchemeRegistry registry = getDefaultSchemeRegistry(); - - ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager( - params, registry); - - return new DefaultHttpClient(manager, params); - } - - private static SchemeRegistry getDefaultSchemeRegistry() { - SchemeRegistry registry = new SchemeRegistry(); - registry.register(new Scheme("http", PlainSocketFactory - .getSocketFactory(), 80)); - final SSLSocketFactory sslSocketFactory = SSLSocketFactory - .getSocketFactory(); - sslSocketFactory - .setHostnameVerifier(SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); - registry.register(new Scheme("https", sslSocketFactory, 443)); - return registry; - } - - private static HttpParams getDefaultHttpParams() { - HttpParams params = new BasicHttpParams(); - HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); - HttpProtocolParams.setContentCharset(params, "utf-8"); - params.setBooleanParameter("http.protocol.expect-continue", false); - HttpConnectionParams.setConnectionTimeout(params, - DEFAULT_CONNECTION_TIMEOUT_MILLIS); - HttpConnectionParams - .setSoTimeout(params, DEFAULT_SOCKET_TIMEOUT_MILLIS); - return params; - } - - private void logD(final String message) { - if (config.isDebugLoggingEnabled) { - Log.d(DeviceHive.TAG, message); - } - } - - /** - * Get command tag from tagged {@link android.os.Bundle}. - * @param resultData Tagged {@link android.os.Bundle}. - * @return Command tag. - */ - public final static String getCommandTag(final Bundle resultData) { - return resultData.getString(KEY_TAG); - } - - /** - * Get {@link Throwable} from tagged {@link android.os.Bundle}. - * @param resultData Tagged {@link android.os.Bundle}. - * @return {@link Throwable} if any exceptions occur during command execution, otherwise return null. - */ - public final static Throwable getThrowable(final Bundle resultData) { - return (Throwable) resultData.getSerializable(KEY_EXCEPTION); - } - - /** - * Get {@link NetworkCommand} from tagged {@link android.os.Bundle}. - * @param resultData Tagged {@link android.os.Bundle}. - * @return Current {@link NetworkCommand} instance. - */ - public final static NetworkCommand getCommand(final Bundle resultData) { - return (NetworkCommand) resultData.getParcelable(KEY_COMMAND); - } - - /** - * Get status code from tagged {@link android.os.Bundle}. - * @param resultData Tagged {@link android.os.Bundle}. - * @return Status code. - */ - public final static int getStatusCode(final Bundle resultData) { - return resultData.getInt(KEY_STATUS_CODE); - } - -} diff --git a/app/src/main/java/com/dataart/android/devicehive/network/NetworkCommandConfig.java b/app/src/main/java/com/dataart/android/devicehive/network/NetworkCommandConfig.java deleted file mode 100644 index 4f5af41..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/network/NetworkCommandConfig.java +++ /dev/null @@ -1,137 +0,0 @@ -package com.dataart.android.devicehive.network; - -import android.os.Parcel; -import android.os.Parcelable; -import android.os.ResultReceiver; - -import com.dataart.obd2.devicehive.DevicePreferences; - -/** - * Network command execution configuration data. - */ -public class NetworkCommandConfig implements Parcelable { - - /** - * Server URL without path component. - */ - public final String baseUrl; - - /** - * Result receiver to receive messages from the service. - */ - public final ResultReceiver resultReceiver; - - /** - * Whether debug logging is enabled or not. - */ - public final boolean isDebugLoggingEnabled; - - private String accessKey; - - private static final ClassLoader CLASS_LOADER = NetworkCommandConfig.class - .getClassLoader(); - - /* package */NetworkCommandConfig(String baseUrl, - ResultReceiver resultReceiver, - boolean isDebugLoggingEnabled, String accessKey) { - this.baseUrl = baseUrl; - this.resultReceiver = resultReceiver; - this.isDebugLoggingEnabled = isDebugLoggingEnabled; - - DevicePreferences preferences = new DevicePreferences(); - this.accessKey = preferences.getAccessKey(); - - -// //TODO: check this -// this.username = "su"; -// this.password = "asdASDqwe123"; - } - - /** - * Construct {@link NetworkCommandConfig} instance and initialize it with - * given parameters. - * - * @param baseUrl - * Server URL excluding path component. - * @param resultReceiver - * {@link DeviceHiveResultReceiver} instance to receive messages - * from the service. - * @param isDebugLoggingEnabled - * Whether debug logging enabled. - */ - public NetworkCommandConfig(String baseUrl, - DeviceHiveResultReceiver resultReceiver, - boolean isDebugLoggingEnabled) { - this(baseUrl, resultReceiver, isDebugLoggingEnabled, null); - } - - /** - * Construct {@link NetworkCommandConfig} instance and initialize it with - * given parameters. - * - * @param baseUrl - * Server URL excluding path component. - * @param resultReceiver - * {@link DeviceHiveResultReceiver} instance to receive messages - * from the service. - */ - public NetworkCommandConfig(String baseUrl, - DeviceHiveResultReceiver resultReceiver) { - this(baseUrl, resultReceiver, false); - } - - /** - * Set Basic Authorization parameters. - * - * @param accessKey - * Access key - */ - public void setAuthorisation(String accessKey) { - this.accessKey=accessKey; - } - - /** - * Get Basic Authorization parameters. - * - * @return {@link org.apache.http.auth.UsernamePasswordCredentials} instance containing Basic - * Authorization data. - */ -// public UsernamePasswordCredentials getBasicAuthorisation() { -// if (username != null && password != null) { -// return new UsernamePasswordCredentials(username, password); -// } -// return null; -// } - - public String getAuthorization() { - return "Bearer "+accessKey; - } - - @Override - public int describeContents() { - return 0; - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - dest.writeString(baseUrl); - dest.writeParcelable(resultReceiver, 0); - dest.writeInt(isDebugLoggingEnabled ? 1 : 0); - dest.writeString(accessKey); - } - - public static final Creator CREATOR = new Creator() { - public NetworkCommandConfig createFromParcel(Parcel source) { - return new NetworkCommandConfig(source.readString(), - (ResultReceiver) source - .readParcelable(CLASS_LOADER), - source.readInt() > 0, - source.readString()); - } - - public NetworkCommandConfig[] newArray(int size) { - return new NetworkCommandConfig[size]; - } - }; - -} diff --git a/app/src/main/java/com/dataart/android/devicehive/network/ServiceConnection.java b/app/src/main/java/com/dataart/android/devicehive/network/ServiceConnection.java deleted file mode 100644 index f688b46..0000000 --- a/app/src/main/java/com/dataart/android/devicehive/network/ServiceConnection.java +++ /dev/null @@ -1,114 +0,0 @@ -package com.dataart.android.devicehive.network; - -import android.bluetooth.BluetoothClass.Device; -import android.content.Context; -import android.os.Bundle; -import android.os.Handler; -import android.os.HandlerThread; -import android.util.Log; - -import com.dataart.android.devicehive.DeviceHive; - -/** - * Abstract base class for service connections. Implements common functionality. - * Descendants are expected to implement specific communication logic. - */ -public abstract class ServiceConnection { - - protected final Context context; - private DeviceHiveResultReceiver resultReceiver; - - protected final static Handler mainThreadHandler = new Handler(); - - protected final static Handler asyncHandler; - - protected String apiEndpointUrl; - protected boolean isDebugLoggingEnabled = false; - - static { - final HandlerThread thread = new HandlerThread( - Device.class.getSimpleName() + "[Handler Thread]"); - thread.start(); - asyncHandler = new Handler(thread.getLooper()); - } - - private final DeviceHiveResultReceiver.ResultListener resultListener = new DeviceHiveResultReceiver.ResultListener() { - @Override - public void onReceiveResult(int code, int tag, Bundle data) { - ServiceConnection.this.onReceiveResult(code, tag, data); - } - }; - - public ServiceConnection(Context context) { - this.context = context; - } - - public void setApiEndpointUrl(String url) { - if (apiEndpointUrl != null && !apiEndpointUrl.equals(url)) { - // detach result listener to avoid receiving responses from old endpoint. - if (resultReceiver != null) { - resultReceiver.detachResultListener(); - resultReceiver = null; - } - } - this.apiEndpointUrl = url; - } - - public String getApiEndpointUrl() { - return apiEndpointUrl; - } - - public void setDebugLoggingEnabled(boolean enabled) { - this.isDebugLoggingEnabled = enabled; - } - - public Context getContext() { - return context; - } - - public void runOnMainThread(Runnable runnable) { - mainThreadHandler.post(runnable); - } - - protected void startNetworkCommand(NetworkCommand command) { - command.start(context, getCommandConfig()); - } - - protected NetworkCommandConfig getCommandConfig() { - final NetworkCommandConfig config = new NetworkCommandConfig( - apiEndpointUrl, getResultReceiver(), isDebugLoggingEnabled); - return config; - } - - protected DeviceHiveResultReceiver getResultReceiver() { - if (resultReceiver == null) { - resultReceiver = new DeviceHiveResultReceiver(); - resultReceiver.setResultListener(resultListener, true); - } - return resultReceiver; - } - - protected void detachResultReceiver() { - if (resultReceiver != null) { - resultReceiver.detachResultListener(); - resultReceiver = null; - } - } - - protected static final int getTagId(final Class tag) { - return getTagId(tag.getName()); - } - - protected static final int getTagId(final String tag) { - return DeviceHiveResultReceiver.getIdForTag(tag); - } - - protected void logD(final String message) { - if (isDebugLoggingEnabled) { - Log.d(DeviceHive.TAG, message); - } - } - - protected abstract void onReceiveResult(final int resultCode, - final int tagId, final Bundle resultData); -} diff --git a/app/src/main/java/com/dataart/obd2/MainActivity.java b/app/src/main/java/com/dataart/obd2/MainActivity.java index e61d08f..d6ae783 100644 --- a/app/src/main/java/com/dataart/obd2/MainActivity.java +++ b/app/src/main/java/com/dataart/obd2/MainActivity.java @@ -7,8 +7,6 @@ import android.bluetooth.BluetoothManager; import android.content.Context; import android.content.Intent; -import android.net.Uri; -import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; @@ -22,18 +20,12 @@ import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; -import android.widget.ListAdapter; -import android.widget.ListView; import android.widget.Spinner; import android.widget.TextView; +import android.widget.Toast; -import com.dataart.android.devicehive.Notification; -import com.dataart.obd2.obd2_gateway.OBD2Service; -import com.dataart.obd2.devicehive.DeviceHive; import com.dataart.obd2.devicehive.DevicePreferences; -import com.google.android.gms.appindexing.Action; -import com.google.android.gms.appindexing.AppIndex; -import com.google.android.gms.common.api.GoogleApiClient; +import com.dataart.obd2.obd2_gateway.OBD2Service; import java.util.Objects; import java.util.Set; @@ -41,12 +33,12 @@ import timber.log.Timber; -public class MainActivity extends AppCompatActivity implements DeviceHive.NotificationListener { +public class MainActivity extends AppCompatActivity { private BluetoothManager mBluetoothManager; private EditText serverUrlEditText; private EditText gatewayIdEditText; - private EditText accessKeyEditText; + private EditText jwtAccessTokenEditText; private TextView hintText; private Button serviceButton; private Button restartServiceButton; @@ -56,6 +48,13 @@ public class MainActivity extends AppCompatActivity implements DeviceHive.Notifi private final View.OnClickListener restartClickListener = new View.OnClickListener() { @Override public void onClick(View view) { + if (!validateValues()) { + return; + } + if (!isDevicesEnabled()) { + Toast.makeText(MainActivity.this, "There is no paired devices were found", Toast.LENGTH_SHORT).show(); + return; + } saveValues(); OBD2Service.stop(MainActivity.this); OBD2Service.start(MainActivity.this); @@ -63,6 +62,7 @@ public void onClick(View view) { serviceButton.setVisibility(View.VISIBLE); onServiceRunning(); hintText.setVisibility(View.GONE); + } }; private final TextView.OnEditorActionListener changeListener = (textView, actionId, keyEvent) -> { @@ -96,17 +96,12 @@ public void afterTextChanged(Editable editable) { onDataChanged(); } }; - /** - * ATTENTION: This was auto-generated to implement the App Indexing API. - * See https://g.co/AppIndexing/AndroidStudio for more information. - */ - private GoogleApiClient client; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); - Toolbar myToolbar = (Toolbar) findViewById(R.id.toolbar); + Toolbar myToolbar = findViewById(R.id.toolbar); setSupportActionBar(myToolbar); if (getSupportActionBar() != null) { getSupportActionBar().setTitle(R.string.app_name); @@ -114,20 +109,7 @@ protected void onCreate(Bundle savedInstanceState) { Timber.plant(new Timber.DebugTree()); -// Warn if developer tries to lower SDK version - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) { - alertSdkVersionMismatch(() -> { - finish(); - System.exit(0); - }); - - return; - } - init(); - // ATTENTION: This was auto-generated to implement the App Indexing API. - // See https://g.co/AppIndexing/AndroidStudio for more information. - client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build(); } private void fatalDialog(int message) { @@ -147,23 +129,18 @@ private void init() { prefs = new DevicePreferences(); - serverUrlEditText = (EditText) findViewById(R.id.server_url_edit); - gatewayIdEditText = (EditText) findViewById(R.id.settings_gateway_id); - accessKeyEditText = (EditText) findViewById(R.id.accesskey_edit); - hintText = (TextView) findViewById(R.id.hintText); - btDevicesSpinner = (Spinner) findViewById(R.id.bt_list); + serverUrlEditText = findViewById(R.id.server_url_edit); + gatewayIdEditText = findViewById(R.id.settings_gateway_id); + jwtAccessTokenEditText = findViewById(R.id.jwtRefreshToken_edit); + hintText = findViewById(R.id.hintText); + btDevicesSpinner = findViewById(R.id.bt_list); resetValues(); - serviceButton = (Button) findViewById(R.id.service_button); - serviceButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - startService(); - } - }); + serviceButton = findViewById(R.id.service_button); + serviceButton.setOnClickListener(view -> startService()); - restartServiceButton = (Button) findViewById(R.id.save_button); + restartServiceButton = findViewById(R.id.save_button); //noinspection ConstantConditions restartServiceButton.setOnClickListener(restartClickListener); @@ -173,8 +150,8 @@ public void onClick(View view) { gatewayIdEditText.setOnEditorActionListener(changeListener); gatewayIdEditText.addTextChangedListener(changeWatcher); - accessKeyEditText.setOnEditorActionListener(changeListener); - accessKeyEditText.addTextChangedListener(changeWatcher); + jwtAccessTokenEditText.setOnEditorActionListener(changeListener); + jwtAccessTokenEditText.addTextChangedListener(changeWatcher); btDevicesSpinner.setOnItemSelectedListener(btItemSelectedListener); @@ -218,7 +195,7 @@ public void onRequestPermissionsResult(int requestCode, @NonNull String[] permis private boolean isServiceRunning() { final ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { - if (OBD2Service.class.getName().equals(service.service.getClassName())) { + if (Objects.equals(OBD2Service.class.getName(), service.service.getClassName())) { return true; } } @@ -227,6 +204,17 @@ private boolean isServiceRunning() { private void startService() { if (!isServiceStarted) { + if (!validateValues()) { + return; + } + if (!isDevicesEnabled()) { + new AlertDialog.Builder(this) + .setTitle(R.string.unsupported) + .setMessage(R.string.error_message_bt_empty_list) + .setPositiveButton(android.R.string.ok, (dialog, which) -> dialog.dismiss()) + .create().show(); + return; + } saveValues(); onServiceRunning(); OBD2Service.start(MainActivity.this); @@ -249,11 +237,11 @@ private void onServiceStopped() { private boolean isRestartRequired() { final String newUrl = serverUrlEditText.getText().toString(); final String newGatewayId = gatewayIdEditText.getText().toString(); - final String newAccessKey = accessKeyEditText.getText().toString(); + final String newAccessKey = jwtAccessTokenEditText.getText().toString(); final Object newMac = btDevicesSpinner.getSelectedItem(); - return !(prefs.getServerUrl().equals(newUrl) && - prefs.getGatewayId().equals(newGatewayId) && - prefs.getAccessKey().equals(newAccessKey) && + return !(Objects.equals(prefs.getServerUrl(), newUrl) && + Objects.equals(prefs.getGatewayId(), newGatewayId) && + Objects.equals(prefs.getJwtRefreshToken(), newAccessKey) && (newMac != null && newMac.toString().endsWith(prefs.getOBD2Mac()))); } @@ -287,6 +275,10 @@ private void updateBondedDevices() { listAdapter.notifyDataSetChanged(); } + private boolean isDevicesEnabled() { + return BluetoothAdapter.getDefaultAdapter().getBondedDevices().size() > 0; + } + private void resetValues() { String serverUrl = prefs.getServerUrl(); serverUrlEditText.setText( @@ -302,8 +294,8 @@ private void resetValues() { : gatewayId ); - String accessKey = prefs.getAccessKey(); - accessKeyEditText.setText( + String accessKey = prefs.getJwtRefreshToken(); + jwtAccessTokenEditText.setText( TextUtils.isEmpty(accessKey) ? "" : accessKey @@ -315,15 +307,15 @@ private void resetValues() { private void resetErrors() { serverUrlEditText.setError(null); gatewayIdEditText.setError(null); - accessKeyEditText.setError(null); + jwtAccessTokenEditText.setError(null); } private boolean validateValues() { resetErrors(); - final String serverUrl = serverUrlEditText.getText().toString(); - final String gatewayId = gatewayIdEditText.getText().toString(); - final String accessKey = accessKeyEditText.getText().toString(); + String serverUrl = serverUrlEditText.getText().toString().trim(); + String gatewayId = gatewayIdEditText.getText().toString().trim(); + String jwtRefreshToken = jwtAccessTokenEditText.getText().toString().trim(); if (TextUtils.isEmpty(serverUrl)) { serverUrlEditText.setError(getString(R.string.error_message_empty_server_url)); @@ -331,9 +323,9 @@ private boolean validateValues() { } else if (TextUtils.isEmpty(gatewayId)) { gatewayIdEditText.setError(getString(R.string.error_message_empty_gateway_id)); gatewayIdEditText.requestFocus(); - } else if (TextUtils.isEmpty(accessKey)) { - accessKeyEditText.setError(getString(R.string.error_message_empty_accesskey)); - accessKeyEditText.requestFocus(); + } else if (TextUtils.isEmpty(jwtRefreshToken)) { + jwtAccessTokenEditText.setError(getString(R.string.error_message_empty_jwt_refresh_token)); + jwtAccessTokenEditText.requestFocus(); } else { return true; } @@ -342,70 +334,35 @@ private boolean validateValues() { } private void saveValues() { - final String serverUrl = serverUrlEditText.getText().toString(); - final String gatewayId = gatewayIdEditText.getText().toString(); - final String accessKey = accessKeyEditText.getText().toString(); + final String serverUrl = serverUrlEditText.getText().toString().trim(); + final String gatewayId = gatewayIdEditText.getText().toString().trim(); + final String accessKey = jwtAccessTokenEditText.getText().toString().trim(); final Object obd2mac = btDevicesSpinner.getSelectedItem(); - prefs.setAccessKeySync(accessKey); + prefs.setJwtRefreshTokenSync(accessKey); prefs.setServerUrlSync(serverUrl); prefs.setGatewayIdSync(gatewayId); if (obd2mac != null) { final String mac = obd2mac.toString(); - prefs.setOBD2MacSync(mac.substring(mac. lastIndexOf(" ") + 1)); + prefs.setOBD2MacSync(mac.substring(mac.lastIndexOf(" ") + 1)); } } - @Override - public void onDeviceSentNotification(Notification notification) { - - } - - @Override - public void onDeviceFailedToSendNotification(Notification notification) { - + private boolean isFieldsEmpty() { + String serverUrl = serverUrlEditText.getText().toString(); + String gatewayId = gatewayIdEditText.getText().toString(); + String accessKey = jwtAccessTokenEditText.getText().toString(); + return TextUtils.isEmpty(serverUrl) || TextUtils.isEmpty(gatewayId) || TextUtils.isEmpty(accessKey); } @Override protected void onStart() { super.onStart(); - // ATTENTION: This was auto-generated to implement the App Indexing API. - // See https://g.co/AppIndexing/AndroidStudio for more information. - client.connect(); - // ATTENTION: This was auto-generated to implement the App Indexing API. - // See https://g.co/AppIndexing/AndroidStudio for more information. - Action viewAction = Action.newAction( - Action.TYPE_VIEW, // TODO: choose an action type. - "Main Page", // TODO: Define a title for the content shown. - // TODO: If you have web page content that matches this app activity's content, - // make sure this auto-generated web page URL is correct. - // Otherwise, set the URL to null. - Uri.parse("http://host/path"), - // TODO: Make sure this auto-generated app URL is correct. - Uri.parse("android-app://com.dataart.obd2/http/host/path") - ); - AppIndex.AppIndexApi.start(client, viewAction); } @Override protected void onStop() { super.onStop(); - // ATTENTION: This was auto-generated to implement the App Indexing API. - // See https://g.co/AppIndexing/AndroidStudio for more information. - Action viewAction = Action.newAction( - Action.TYPE_VIEW, // TODO: choose an action type. - "Main Page", // TODO: Define a title for the content shown. - // TODO: If you have web page content that matches this app activity's content, - // make sure this auto-generated web page URL is correct. - // Otherwise, set the URL to null. - Uri.parse("http://host/path"), - // TODO: Make sure this auto-generated app URL is correct. - Uri.parse("android-app://com.dataart.obd2/http/host/path") - ); - AppIndex.AppIndexApi.end(client, viewAction); - // ATTENTION: This was auto-generated to implement the App Indexing API. - // See https://g.co/AppIndexing/AndroidStudio for more information. - client.disconnect(); } private void alertSdkVersionMismatch(final Runnable runnable) { diff --git a/app/src/main/java/com/dataart/obd2/OBD2Application.java b/app/src/main/java/com/dataart/obd2/OBD2Application.java index 03ad52e..aaf218e 100644 --- a/app/src/main/java/com/dataart/obd2/OBD2Application.java +++ b/app/src/main/java/com/dataart/obd2/OBD2Application.java @@ -1,5 +1,6 @@ package com.dataart.obd2; +import android.support.multidex.MultiDex; import android.support.multidex.MultiDexApplication; /** @@ -18,7 +19,7 @@ public static OBD2Application getApplication() { @Override public void onCreate() { super.onCreate(); - + MultiDex.install(this); application = this; } diff --git a/app/src/main/java/com/dataart/obd2/devicehive/DeviceEquipment.java b/app/src/main/java/com/dataart/obd2/devicehive/DeviceEquipment.java deleted file mode 100644 index df2aa57..0000000 --- a/app/src/main/java/com/dataart/obd2/devicehive/DeviceEquipment.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.dataart.obd2.devicehive; - -import android.util.Log; - -import com.dataart.android.devicehive.Command; -import com.dataart.android.devicehive.EquipmentData; -import com.dataart.android.devicehive.device.CommandResult; -import com.dataart.android.devicehive.device.Equipment; -import com.dataart.android.devicehive.device.future.SimpleCallableFuture; - -public class DeviceEquipment extends Equipment { - - private static final String TAG = "TestEquipment"; - - public DeviceEquipment() { - super(equipmentData()); - } - - private static EquipmentData equipmentData() { - return new EquipmentData("Test Android Equipment", - "Test Android Equipment code", "Test Android Equipment type"); - } - - @Override - public void onBeforeRunCommand(Command command) { - Log.d(TAG, "onBeforeRunCommand: " + command.getCommand()); - } - - @Override - public boolean shouldRunCommandAsynchronously(final Command command) { - return false; - } - - @Override - public SimpleCallableFuture runCommand(final Command command) { - Log.d(TAG, "runCommand: " + command.getCommand()); - - // run command - - return new SimpleCallableFuture(new CommandResult(CommandResult.STATUS_COMLETED, - "Executed on Android test equipment!")); - } - - @Override - protected boolean onRegisterEquipment() { - Log.d(TAG, "onRegisterEquipment"); - return true; - } - - @Override - protected boolean onUnregisterEquipment() { - Log.d(TAG, "onUnregisterEquipment"); - return true; - } - - @Override - protected void onStartProcessingCommands() { - Log.d(TAG, "onStartProcessingCommands"); - } - - @Override - protected void onStopProcessingCommands() { - Log.d(TAG, "onStopProcessingCommands"); - } - -} diff --git a/app/src/main/java/com/dataart/obd2/devicehive/DeviceHive.java b/app/src/main/java/com/dataart/obd2/devicehive/DeviceHive.java deleted file mode 100644 index 7b32fc0..0000000 --- a/app/src/main/java/com/dataart/obd2/devicehive/DeviceHive.java +++ /dev/null @@ -1,191 +0,0 @@ -package com.dataart.obd2.devicehive; - -import android.content.Context; -import android.os.Build; -import android.util.Log; - -import com.dataart.android.devicehive.Command; -import com.dataart.android.devicehive.DeviceClass; -import com.dataart.android.devicehive.DeviceData; -import com.dataart.android.devicehive.Network; -import com.dataart.android.devicehive.Notification; -import com.dataart.android.devicehive.device.CommandResult; -import com.dataart.android.devicehive.device.Device; -import com.dataart.android.devicehive.device.future.SimpleCallableFuture; -import com.dataart.obd2.BuildConfig; - -import java.util.LinkedList; -import java.util.List; - -public class DeviceHive extends Device { - - private static final String TAG = "AndroidOBD2"; - - private List registrationListeners = new LinkedList(); - private CommandListener commandListener; - private List notificationListeners = new LinkedList(); - - public interface RegistrationListener { - void onDeviceRegistered(); - - void onDeviceFailedToRegister(); - } - - public interface CommandListener { - SimpleCallableFuture onDeviceReceivedCommand(Command command); - } - - public interface NotificationListener { - void onDeviceSentNotification(Notification notification); - - void onDeviceFailedToSendNotification(Notification notification); - } - - public DeviceHive(Context context) { - super(context, getTestDeviceData()); - attachEquipment(new DeviceEquipment()); - - } - - private static DeviceData getTestDeviceData() { - final Network network = new Network("AndroidOBD", ""); - final DeviceClass deviceClass = new DeviceClass("Android OBD2 Device", BuildConfig.VERSION_NAME); - - return new DeviceData( - new DevicePreferences().getGatewayId(), - "582c2008-cbb6-4b1a-8cf1-7cec1388db9f", - getDeviceName(), - DeviceData.DEVICE_STATUS_ONLINE, - deviceClass); - } - - public static String getDeviceName() { - final String manufacturer = Build.MANUFACTURER; - final String model = Build.MODEL; - return model.startsWith(manufacturer) ? model : manufacturer + " " + model; - } - - @Override - public void onBeforeRunCommand(Command command) { - Log.d(TAG, "onBeforeRunCommand: " + command.getCommand()); - } - - @Override - public SimpleCallableFuture runCommand(final Command command) { - Log.d(TAG, "Executing command on test device: " + command.getCommand()); - return notifyListenersCommandReceived(command); - } - - @Override - public boolean shouldRunCommandAsynchronously(final Command command) { - return true; - } - - public void addDeviceListener(RegistrationListener listener) { - registrationListeners.add(listener); - } - - public void removeDeviceListener(RegistrationListener listener) { - registrationListeners.remove(listener); - } - - public void setCommandListener(CommandListener listener) { - this.commandListener = listener; - } - - public void removeCommandListener() { - commandListener = null; - } - - @Override - protected void onStartRegistration() { - Log.d(TAG, "onStartRegistration"); - } - - @Override - protected void onFinishRegistration() { - Log.d(TAG, "onFinishRegistration"); - isRegistered = true; - notifyListenersDeviceRegistered(); - } - - @Override - protected void onFailRegistration() { - Log.d(TAG, "onFailRegistration"); - notifyListenersDeviceFailedToRegister(); - } - - @Override - protected void onStartProcessingCommands() { - Log.d(TAG, "onStartProcessingCommands"); - } - - @Override - protected void onStopProcessingCommands() { - Log.d(TAG, "onStopProcessingCommands"); - } - - @Override - protected void onStartSendingNotification(Notification notification) { - Log.d(TAG, "onStartSendingNotification : " + notification.getName()); - } - - @Override - protected void onFinishSendingNotification(Notification notification) { - Log.d(TAG, "onFinishSendingNotification : " + notification.getName()); - notifyListenersDeviceSentNotification(notification); - } - - @Override - protected void onFailSendingNotification(Notification notification) { - Log.d(TAG, "onFailSendingNotification : " + notification.getName()); - notifyListenersDeviceFailedToSendNotification(notification); - } - - private SimpleCallableFuture notifyListenersCommandReceived(Command command) { - return commandListener.onDeviceReceivedCommand(command); - } - - private void notifyListenersDeviceRegistered() { - for (RegistrationListener listener : registrationListeners) { - listener.onDeviceRegistered(); - } - } - - private void notifyListenersDeviceFailedToRegister() { - for (RegistrationListener listener : registrationListeners) { - listener.onDeviceFailedToRegister(); - } - } - - private void notifyListenersDeviceSentNotification(Notification notification) { - for (NotificationListener listener : notificationListeners) { - listener.onDeviceSentNotification(notification); - } - } - - private void notifyListenersDeviceFailedToSendNotification( - Notification notification) { - for (NotificationListener listener : notificationListeners) { - listener.onDeviceFailedToSendNotification(notification); - } - } - - - public static DeviceHive newInstance(Context context) { - - final DeviceHive device = new DeviceHive(context); - device.setDebugLoggingEnabled(true); - - final DevicePreferences prefs = new DevicePreferences(); - String serverUrl = prefs.getServerUrl(); - - if (serverUrl == null) { - serverUrl = DeviceHiveConfig.API_ENDPOINT; - prefs.setServerUrlSync(serverUrl); - } - device.setApiEnpointUrl(serverUrl); - return device; - } - -} diff --git a/app/src/main/java/com/dataart/obd2/devicehive/DevicePreferences.java b/app/src/main/java/com/dataart/obd2/devicehive/DevicePreferences.java index 6896415..b225e91 100644 --- a/app/src/main/java/com/dataart/obd2/devicehive/DevicePreferences.java +++ b/app/src/main/java/com/dataart/obd2/devicehive/DevicePreferences.java @@ -1,8 +1,8 @@ package com.dataart.obd2.devicehive; +import android.annotation.SuppressLint; import android.content.Context; import android.content.SharedPreferences; -import android.os.AsyncTask; import com.dataart.obd2.OBD2Application; @@ -16,8 +16,8 @@ public class DevicePreferences { private final static String KEY_GATEWAY_ID = NAMESPACE .concat(".KEY_GATEWAY_ID"); - private final static String KEY_ACCESSKEY= NAMESPACE - .concat(".KEY_ACCESSKEY"); + private final static String JWT_REFRESH_TOKEN = NAMESPACE + .concat(".KEY_JWT_REFRESH_TOKEN"); private final static String KEY_OBD2MAC= NAMESPACE .concat(".OBD2_MAC"); @@ -45,44 +45,34 @@ public String getGatewayId() { public String getOBD2Mac() { return preferences.getString(KEY_OBD2MAC, null); } - + @SuppressLint("ApplySharedPref") public void setServerUrlSync(String serverUrl) { final SharedPreferences.Editor editor = preferences.edit(); editor.putString(KEY_SERVER_URL, serverUrl); editor.commit(); } - + @SuppressLint("ApplySharedPref") public void setGatewayIdSync(String gatewayId) { final SharedPreferences.Editor editor = preferences.edit(); editor.putString(KEY_GATEWAY_ID, gatewayId); editor.commit(); } - public String getAccessKey() { - return preferences.getString(KEY_ACCESSKEY, null); + public String getJwtRefreshToken() { + return preferences.getString(JWT_REFRESH_TOKEN, null); } - - public void setAccessKeySync(String accessKey) { + @SuppressLint("ApplySharedPref") + public void setJwtRefreshTokenSync(String jwtRefreshToken) { final SharedPreferences.Editor editor = preferences.edit(); - editor.putString(KEY_ACCESSKEY, accessKey); + editor.putString(JWT_REFRESH_TOKEN, jwtRefreshToken); editor.commit(); } - + @SuppressLint("ApplySharedPref") public void setOBD2MacSync(String mac) { final SharedPreferences.Editor editor = preferences.edit(); editor.putString(KEY_OBD2MAC, mac); editor.commit(); } - public void setCredentialsAsync(final String accessKey) { - new AsyncTask() { - @Override - protected Void doInBackground(Void... params) { - setAccessKeySync(accessKey); - return null; - } - - }.execute(); - } } diff --git a/app/src/main/java/com/dataart/obd2/obd2_gateway/OBD2Gateway.java b/app/src/main/java/com/dataart/obd2/obd2_gateway/OBD2Gateway.java index 297c5fe..73795e4 100644 --- a/app/src/main/java/com/dataart/obd2/obd2_gateway/OBD2Gateway.java +++ b/app/src/main/java/com/dataart/obd2/obd2_gateway/OBD2Gateway.java @@ -2,23 +2,34 @@ import android.content.Context; -import com.dataart.android.devicehive.Command; -import com.dataart.android.devicehive.Notification; -import com.dataart.android.devicehive.device.CommandResult; -import com.dataart.android.devicehive.device.future.SimpleCallableFuture; import com.dataart.obd2.R; -import com.dataart.obd2.devicehive.DeviceHive; import com.dataart.obd2.devicehive.DevicePreferences; +import com.github.devicehive.client.model.CommandFilter; +import com.github.devicehive.client.model.DHResponse; +import com.github.devicehive.client.model.DeviceCommandsCallback; +import com.github.devicehive.client.model.FailureData; +import com.github.devicehive.client.model.Parameter; +import com.github.devicehive.client.service.Device; +import com.github.devicehive.client.service.DeviceCommand; +import com.github.devicehive.client.service.DeviceHive; import com.github.pires.obd.commands.control.TroubleCodesCommand; import com.github.pires.obd.commands.protocol.ObdRawCommand; import com.github.pires.obd.exceptions.ResponseException; -import com.google.gson.Gson; +import com.google.gson.JsonObject; -import java.io.IOError; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Arrays; import java.util.HashMap; -import java.util.HashSet; +import java.util.List; + +import io.reactivex.Observable; +import io.reactivex.Observer; +import io.reactivex.disposables.Disposable; +import io.reactivex.schedulers.Schedulers; +import io.reactivex.subjects.PublishSubject; +import timber.log.Timber; /** * Created by Nikolay Khabarov on 8/8/16. @@ -26,13 +37,38 @@ public abstract class OBD2Gateway { private final static String TAG = OBD2Gateway.class.getSimpleName(); + + /** + * Command status "Completed" value. + */ + public static final String STATUS_COMLETED = "Completed"; + + /** + * Command status "Failed" value. + */ + public static final String STATUS_FAILED = "Failed"; + + /** + * Command status "Failed" value. + */ + public static final String STATUS_WAITING = "Waiting"; + public static final String GET_TROUBLE_CODES = "GetTroubleCodes"; + public static final String RUN_COMMAND = "RunCommand"; + public static final String MODE = "mode"; + public static final String PID = "pid"; + public static final String OBD_2 = "obd2"; + public static final String PARAMETERS = "parameters"; + public static final String GET = "get"; + public static final String RESULT = "result"; + + private Context mContext; private OBD2Reader mObd2Reader; - private DeviceHive mDeviceHive; + private DeviceHive deviceHive; + PublishSubject source; public OBD2Gateway(Context context) { mContext = context; - mDeviceHive = DeviceHive.newInstance(mContext); final DevicePreferences prefs = new DevicePreferences(); mObd2Reader = new OBD2Reader(prefs.getOBD2Mac()) { @Override @@ -54,102 +90,173 @@ protected void statusCallback(Status status) { } @Override - protected void dataCallback(OBD2Data data) { - Method[] methods = OBD2Data.class.getDeclaredMethods(); - HashMap map = new HashMap(); - for (Method method : methods) { - String name = method.getName(); - if (name.startsWith("get")) { - Object obj = null; - try { - obj = method.invoke(data); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } catch (InvocationTargetException e) { - e.printStackTrace(); - } - if (obj != null) { - map.put(name.substring(3), obj); + protected void dataCallback(OBD2Data d) { + Observable.just(d).observeOn(Schedulers.io()).subscribeOn(Schedulers.io()).subscribe(data -> { + DHResponse deviceDHResponse = deviceHive.getDevice(prefs.getGatewayId()); + Timber.d(deviceDHResponse.toString()); + + if (!deviceDHResponse.isSuccessful()) { + return; + } + Device device = deviceDHResponse.getData(); + Method[] methods = OBD2Data.class.getDeclaredMethods(); + + //Full info data from obd + HashMap map = new HashMap<>(); + + for (Method method : methods) { + String name = method.getName(); + if (name.startsWith(GET)) { + Object obj = null; + try { + obj = method.invoke(data); + } catch (IllegalAccessException | InvocationTargetException e) { + e.printStackTrace(); + } + if (obj != null) { + map.put(name.substring(3), obj); + } } } - } - mDeviceHive.sendNotification(new Notification("obd2", map)); + List parameters = new ArrayList<>(); + for (String s : map.keySet()) { + + parameters.add(new Parameter(s, map.get(s).toString())); + } + device.sendNotification(OBD_2, parameters); + }); } }; } public void start() { - final DevicePreferences prefs = new DevicePreferences(); - mDeviceHive.setApiEnpointUrl(prefs.getServerUrl()); - - mDeviceHive.setCommandListener(commandListener); - if (!mDeviceHive.isRegistered()) { - mDeviceHive.registerDevice(); - } - mDeviceHive.startProcessingCommands(); + DevicePreferences prefs = new DevicePreferences(); + Timber.d(prefs.getJwtRefreshToken()); + Timber.d(prefs.getGatewayId()); + deviceHive = DeviceHive.getInstance() + .init(prefs.getServerUrl(), prefs.getJwtRefreshToken()); mObd2Reader.start(); + subscribeOnCommands(); } public void stop() { + if (source != null) { + source.onComplete(); + } mObd2Reader.stop(); - mDeviceHive.removeCommandListener(); - mDeviceHive.stopProcessingCommands(); } - private final DeviceHive.CommandListener commandListener = new DeviceHive.CommandListener() { - @Override - public SimpleCallableFuture onDeviceReceivedCommand(Command command) { - String status = CommandResult.STATUS_FAILED; - String result = ""; - - final String name = command.getCommand(); - if (name.equalsIgnoreCase("GetTroubleCodes")) { - TroubleCodesCommand troubleCodesCommand = new TroubleCodesCommand(); - if (mObd2Reader.runCommand(troubleCodesCommand)) { - String codes = troubleCodesCommand.getFormattedResult(); - if (codes != null) { - final String codeArray[] = codes.split("\n"); - return new SimpleCallableFuture<>(new CommandResult( - CommandResult.STATUS_COMLETED, new Gson().toJson(codeArray))); - } else { - status = CommandResult.STATUS_FAILED; - result = "Failed to read codes"; + public void subscribeOnCommands() { + source = PublishSubject.create(); + source.subscribeOn(Schedulers.io()) + .subscribe(getCommandObservable()); + } + + + private Observer getCommandObservable() { + return new Observer() { + @Override + public void onSubscribe(Disposable d) { + new Thread(() -> { + DevicePreferences prefs = new DevicePreferences(); + DHResponse deviceDHResponse = deviceHive.getDevice(prefs.getGatewayId()); + Timber.d(deviceDHResponse.toString()); + if (!deviceDHResponse.isSuccessful()) { + return; } - } else { - status = CommandResult.STATUS_FAILED; - result = "Failed to run troubleCodesCommand"; - } - } else if (name.equalsIgnoreCase("RunCommand")) { - final HashMap params = (HashMap) command.getParameters(); - final String mode = (params != null) ? (String) params.get("mode") : null; - final String pid = (params != null) ? (String) params.get("pid") : null; - if (mode == null || pid == null) { - status = CommandResult.STATUS_FAILED; - result = "Please specify mode and pid parameters"; - } else { - ObdRawCommand obdCommand = new ObdRawCommand(mode + " " + pid); - boolean commandRes = true; - try { - commandRes = mObd2Reader.runCommand(obdCommand); - } catch (ResponseException e) { - // ignore response error and send it as is + Device device = deviceDHResponse.getData(); + CommandFilter commandFilter = new CommandFilter(); + commandFilter.setCommandNames(); + device.subscribeCommands(commandFilter, new DeviceCommandsCallback() { + @Override + public void onSuccess(List list) { + DeviceCommand command = list.get(0); + onNext(command); + } + + @Override + public void onFail(FailureData failureData) { + onError(new Throwable(failureData.getMessage())); + } + }); + }).start(); + } + + @Override + public void onNext(DeviceCommand command) { + String status; + String result; + String name = command.getCommandName(); + Timber.d(command.toString()); + if (name.equalsIgnoreCase(GET_TROUBLE_CODES)) { + TroubleCodesCommand troubleCodesCommand = new TroubleCodesCommand(); + if (mObd2Reader.runCommand(troubleCodesCommand)) { + String codes = troubleCodesCommand.getFormattedResult(); + if (codes != null) { + String codeArray[] = codes.split("\n"); + result = Arrays.toString(codeArray); + status = STATUS_COMLETED; + } else { + status = STATUS_FAILED; + result = "Failed to read codes"; + } + } else { + status = STATUS_FAILED; + result = "Failed to run troubleCodesCommand"; } - if (commandRes) { - status = CommandResult.STATUS_COMLETED; - result = obdCommand.getFormattedResult(); + } else if (name.equalsIgnoreCase(RUN_COMMAND)) { + JsonObject params = command.getParameters(); + + final String mode = (params != null) ? params.get(MODE).getAsString() : null; + final String pid = (params != null) ? params.get(PID).getAsString() : null; + + if (mode == null || pid == null) { + status = STATUS_FAILED; + result = "Please specify mode and pid parameters"; } else { - status = CommandResult.STATUS_FAILED; - result = "Failed to run command"; + ObdRawCommand obdCommand = new ObdRawCommand(mode + " " + pid); + boolean commandRes = true; + try { + commandRes = mObd2Reader.runCommand(obdCommand); + } catch (ResponseException e) { + // ignore response error and send it as is + } + if (commandRes) { + status = STATUS_COMLETED; + result = obdCommand.getFormattedResult(); + } else { + status = STATUS_FAILED; + result = "Failed to run command"; + } } + } else { + status = STATUS_FAILED; + result = mContext.getString(R.string.unknown_commnad); } - } else { - status = CommandResult.STATUS_FAILED; - result = mContext.getString(R.string.unknown_commnad); + command.setStatus(status); + + JsonObject resultJson = new JsonObject(); + resultJson.addProperty(RESULT, result); + + command.setResult(resultJson); + command.updateCommand(); + } - return new SimpleCallableFuture<>(new CommandResult(status, new Gson().toJson(result))); - } - }; + + @Override + public void onError(Throwable e) { + e.printStackTrace(); + } + + @Override + public void onComplete() { + } + }; + + + } + public abstract void updateState(String text); } diff --git a/app/src/main/java/com/dataart/obd2/obd2_gateway/OBD2Params.java b/app/src/main/java/com/dataart/obd2/obd2_gateway/OBD2Params.java new file mode 100644 index 0000000..6a06424 --- /dev/null +++ b/app/src/main/java/com/dataart/obd2/obd2_gateway/OBD2Params.java @@ -0,0 +1,15 @@ +package com.dataart.obd2.obd2_gateway; + +public class OBD2Params { + + private String pid; + private String mode; + + public String getPid() { + return pid; + } + + public String getMode() { + return mode; + } +} diff --git a/app/src/main/java/com/dataart/obd2/obd2_gateway/OBD2Reader.java b/app/src/main/java/com/dataart/obd2/obd2_gateway/OBD2Reader.java index 84997b6..2ba14d3 100644 --- a/app/src/main/java/com/dataart/obd2/obd2_gateway/OBD2Reader.java +++ b/app/src/main/java/com/dataart/obd2/obd2_gateway/OBD2Reader.java @@ -3,12 +3,9 @@ import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; -import android.os.Handler; import android.util.Log; import com.github.pires.obd.commands.ObdCommand; -import com.github.pires.obd.commands.control.TroubleCodesCommand; -import com.github.pires.obd.commands.engine.RPMCommand; import com.github.pires.obd.commands.protocol.EchoOffCommand; import com.github.pires.obd.commands.protocol.LineFeedOffCommand; import com.github.pires.obd.commands.protocol.ObdResetCommand; @@ -19,29 +16,41 @@ import java.io.InputStream; import java.io.OutputStream; import java.util.UUID; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; /** * Created by Nikolay Khabarov on 8/5/16. */ -public abstract class OBD2Reader implements Runnable{ +public abstract class OBD2Reader implements Runnable { + + //BT Device params private final static int READ_INTERVAL = 1000; private final static int READ_ERROR_INTERVAL = 5000; private static final UUID BT_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); private boolean isStarted = false; + private String mDeviceMac; + private BluetoothDevice mBluetoothDevice; private BluetoothSocket mSocket = null; + private boolean mObd2Init = false; + + //RW streams private InputStream mInputStream; private OutputStream mOutputStream; + + //Commands private ObdResetCommand mObdResetCommand = new ObdResetCommand(); private EchoOffCommand mEchoOffCommand = new EchoOffCommand(); private LineFeedOffCommand mLineFeedOffCommand = new LineFeedOffCommand(); private SelectProtocolCommand mSelectProtocolCommand = new SelectProtocolCommand(ObdProtocols.AUTO); - final Handler mHandler = new Handler(); + private ScheduledExecutorService service = Executors.newScheduledThreadPool(1); public enum Status { STATUS_DISCONNECTED, @@ -52,28 +61,31 @@ public enum Status { public OBD2Reader(String mac) { mDeviceMac = mac; - final BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter(); + BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter(); mBluetoothDevice = btAdapter.getRemoteDevice(mDeviceMac); } - public synchronized void start() { - if (isStarted == false) { + public void start() { + if (!isStarted) { isStarted = true; - mHandler.postDelayed(this, READ_INTERVAL); + service.shutdown(); + service = Executors.newScheduledThreadPool(1); + service.schedule(this, READ_INTERVAL, TimeUnit.MILLISECONDS); statusCallback(Status.STATUS_OBD2_CONNECTING); } } - public synchronized void stop() { + public void stop() { isStarted = false; - mHandler.removeCallbacks(this); + service.shutdownNow(); + service = Executors.newScheduledThreadPool(0); } private synchronized void nextIteration(boolean success) { if (!isStarted) { return; } - mHandler.postDelayed(this, success ? READ_INTERVAL : READ_ERROR_INTERVAL); + service.schedule(this, success ? READ_INTERVAL : READ_ERROR_INTERVAL, TimeUnit.MILLISECONDS); } private void closeSocket() { @@ -98,7 +110,7 @@ private boolean ensureConnected() { mOutputStream = mSocket.getOutputStream(); OBD2Data.cleanIgnoredCommands(); } catch (IOException e) { - if (!(e instanceof IOException)){ + if (!(e instanceof IOException)) { e.printStackTrace(); } closeSocket(); @@ -110,13 +122,13 @@ private boolean ensureConnected() { if (!mObd2Init) { try { - mObdResetCommand.run(mInputStream, mOutputStream); + mObdResetCommand.run(mInputStream, mOutputStream); Log.i("tag", "ObdResetCommand " + mObdResetCommand.getResult()); - mEchoOffCommand.run(mInputStream, mOutputStream); + mEchoOffCommand.run(mInputStream, mOutputStream); Log.i("tag", "EchoOffCommand " + mEchoOffCommand.getResult()); - mLineFeedOffCommand.run(mInputStream, mOutputStream); + mLineFeedOffCommand.run(mInputStream, mOutputStream); Log.i("tag", "LineFeedOffCommand " + mLineFeedOffCommand.getResult()); - mSelectProtocolCommand.run(mInputStream, mOutputStream); + mSelectProtocolCommand.run(mInputStream, mOutputStream); Log.i("tag", "SelectProtocolCommand " + mSelectProtocolCommand.getResult()); } catch (IOException e) { e.printStackTrace(); @@ -154,7 +166,7 @@ public void run() { nextIteration(iteration()); } - public synchronized boolean runCommand(ObdCommand command) { + public boolean runCommand(ObdCommand command) { if (!ensureConnected()) { return false; } @@ -173,5 +185,6 @@ public synchronized boolean runCommand(ObdCommand command) { protected abstract void statusCallback(Status status); + protected abstract void dataCallback(OBD2Data data); } diff --git a/app/src/main/java/com/dataart/obd2/obd2_gateway/OBD2Service.java b/app/src/main/java/com/dataart/obd2/obd2_gateway/OBD2Service.java index 27b5562..f0e93ac 100644 --- a/app/src/main/java/com/dataart/obd2/obd2_gateway/OBD2Service.java +++ b/app/src/main/java/com/dataart/obd2/obd2_gateway/OBD2Service.java @@ -1,9 +1,9 @@ package com.dataart.obd2.obd2_gateway; +import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; -import android.app.TaskStackBuilder; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothManager; import android.content.BroadcastReceiver; @@ -12,10 +12,10 @@ import android.content.IntentFilter; import android.os.IBinder; import android.support.v4.app.NotificationCompat; +import android.support.v4.app.TaskStackBuilder; import android.util.Log; import android.widget.Toast; -import com.dataart.android.devicehive.network.DeviceHiveApiService; import com.dataart.obd2.MainActivity; import com.dataart.obd2.R; @@ -54,12 +54,17 @@ public static void stop(final Context context) { @Override public void onCreate() { super.onCreate(); - final BluetoothManager mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); + BluetoothManager mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); mBluetoothAdapter = mBluetoothManager.getAdapter(); if (!mBluetoothAdapter.isEnabled()) { send(ACTION_BT_PERMISSION_REQUEST); } mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); + if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { + int importance = NotificationManager.IMPORTANCE_HIGH; + NotificationChannel mChannel = new NotificationChannel("1", "OBD2", importance); + mNotificationManager.createNotificationChannel(mChannel); + } registerReceiver(getBtStateReceiver(), new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED)); mObd2Gateway = new OBD2Gateway(this) { @Override @@ -85,10 +90,10 @@ public int onStartCommand(Intent intent, int flags, int startId) { public void onDestroy() { Timber.d("Service.onDestroy"); mObd2Gateway.stop(); - stopService(new Intent(this, DeviceHiveApiService.class)); if (mReceiver != null) { unregisterReceiver(mReceiver); } + mObd2Gateway = null; mNotificationManager.cancel(LE_NOTIFICATION_ID); super.onDestroy(); Log.d(TAG, "OBD2Service was destroyed"); @@ -107,7 +112,7 @@ public boolean onUnbind(Intent intent) { } private void notifyNewState(final String text) { - Timber.d("Service.onUnbind"); + Timber.d("notifyNewState"); mBuilder.setContentText(text); mNotificationManager.notify(LE_NOTIFICATION_ID, mBuilder.build()); } @@ -144,7 +149,7 @@ private void setNotification() { stackBuilder.addNextIntent(resultIntent); final PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); - mBuilder = new NotificationCompat.Builder(this) + mBuilder = new NotificationCompat.Builder(this, "1") .setContentText(getString(R.string.notification_disconnected)) .setContentTitle(getString(R.string.device_hive)) .setSmallIcon(R.drawable.ic_le_service) diff --git a/app/src/main/res/layout/activity_settings.xml b/app/src/main/res/layout/activity_settings.xml index 5221310..866a428 100644 --- a/app/src/main/res/layout/activity_settings.xml +++ b/app/src/main/res/layout/activity_settings.xml @@ -78,11 +78,11 @@ diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 4d92fbf..e314f5c 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -7,7 +7,7 @@ Gateway ID Username Password - Access Key + Jwt Refresh Token You have to restart the service in order to apply new parameters Choose your Bluetooth OBD2 adapter from list of paired devices @@ -16,15 +16,16 @@ Stop service http://playground.devicehive.com/api/rest - devicehive_obd2_andoid + devicehive-obd2-android 8Gff/CCqkLYkuYHwa2oXf2GCmpyaLsuOlVYkttL93LQ= Bluetooth not supported.\nApplication will close itself + There is no paired devices were found Server URL is required Gateway ID is required Username is required Password is required - Access key is required + Jwt Refresh Token is required Settings were saved diff --git a/build.gradle b/build.gradle index 77ab978..8917e1d 100644 --- a/build.gradle +++ b/build.gradle @@ -1,12 +1,13 @@ // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { + repositories { + google() jcenter() } dependencies { - classpath 'com.android.tools.build:gradle:2.1.2' - classpath 'me.tatarka:gradle-retrolambda:3.2.4' + classpath 'com.android.tools.build:gradle:3.0.1' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files @@ -15,6 +16,14 @@ buildscript { allprojects { repositories { + google() jcenter() + maven { + url 'https://jitpack.io' + } } } + +task clean(type: Delete) { + delete rootProject.buildDir +} diff --git a/gradle.properties b/gradle.properties index 1d3591c..081ee2c 100644 --- a/gradle.properties +++ b/gradle.properties @@ -10,9 +10,11 @@ # Specifies the JVM arguments used for the daemon process. # The setting is particularly useful for tweaking memory settings. # Default value: -Xmx10248m -XX:MaxPermSize=256m -# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 + org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 # When configured, Gradle will run in incubating parallel mode. # This option should only be used with decoupled projects. More details, visit # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects -# org.gradle.parallel=true \ No newline at end of file + org.gradle.parallel=true +#Fixes error default or static interface method used without --min-sdk-version >= 24 +android.enableD8=true \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index cfa5739..7018b6a 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ -#Wed Jun 01 11:00:23 EEST 2016 +#Fri Dec 15 12:47:30 EET 2017 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip