├── .gitmodules ├── LICENSE ├── README.md └── examples ├── Glass_PhillipsHue ├── glass_app │ ├── AndroidManifest.xml │ ├── lib │ │ ├── android-support-v4.jar │ │ └── gson-2.2.jar │ ├── res │ │ ├── drawable-hdpi │ │ │ ├── light_off.png │ │ │ ├── light_on.png │ │ │ ├── light_scene.1.png │ │ │ ├── light_scene2.png │ │ │ └── light_scene3.png │ │ ├── layout │ │ │ └── layout_stopwatch.xml │ │ └── values │ │ │ ├── colors.xml │ │ │ ├── strings.xml │ │ │ └── styles.xml │ └── src │ │ ├── com │ │ └── dataart │ │ │ └── android │ │ │ └── devicehive │ │ │ ├── ApiInfo.java │ │ │ ├── Command.java │ │ │ ├── DataContainer.java │ │ │ ├── DeviceClass.java │ │ │ ├── DeviceData.java │ │ │ ├── DeviceHive.java │ │ │ ├── EquipmentData.java │ │ │ ├── EquipmentState.java │ │ │ ├── Network.java │ │ │ ├── Notification.java │ │ │ ├── ObjectWrapper.java │ │ │ ├── client │ │ │ ├── ClientServiceConnection.java │ │ │ ├── DeviceClient.java │ │ │ ├── MultipleDeviceClient.java │ │ │ ├── SingleDeviceClient.java │ │ │ └── commands │ │ │ │ ├── DeviceClientCommand.java │ │ │ │ ├── GetCommandCommand.java │ │ │ │ ├── GetDeviceClassEquipmentCommand.java │ │ │ │ ├── GetDeviceCommand.java │ │ │ │ ├── GetDeviceEquipmentStateCommand.java │ │ │ │ ├── GetDeviceNotificationsCommand.java │ │ │ │ ├── GetDevicesCommand.java │ │ │ │ ├── GetNetworkDevicesCommand.java │ │ │ │ ├── GetNetworksCommand.java │ │ │ │ ├── NotificationsRetrivalCommand.java │ │ │ │ ├── PollDeviceNotificationsCommand.java │ │ │ │ ├── PollMultipleDeviceNotificationsCommand.java │ │ │ │ ├── PollNotificationsCommand.java │ │ │ │ └── SendDeviceCommandCommand.java │ │ │ ├── commands │ │ │ └── GetApiInfoCommand.java │ │ │ ├── device │ │ │ ├── CommandResult.java │ │ │ ├── CommandRunner.java │ │ │ ├── Device.java │ │ │ ├── DeviceServiceConnection.java │ │ │ ├── DeviceStatusNotification.java │ │ │ ├── Equipment.java │ │ │ ├── EquipmentNotification.java │ │ │ └── commands │ │ │ │ ├── DeviceCommand.java │ │ │ │ ├── DeviceCommandsRetrivalCommand.java │ │ │ │ ├── GetDeviceCommand.java │ │ │ │ ├── GetDeviceCommandsCommand.java │ │ │ │ ├── PollDeviceCommandsCommand.java │ │ │ │ ├── RegisterDeviceCommand.java │ │ │ │ ├── SendNotificationCommand.java │ │ │ │ └── UpdateCommandStatusCommand.java │ │ │ └── network │ │ │ ├── DeviceHiveApiService.java │ │ │ ├── DeviceHiveResultReceiver.java │ │ │ ├── JsonNetworkCommand.java │ │ │ ├── NetworkCommand.java │ │ │ ├── NetworkCommandConfig.java │ │ │ └── ServiceConnection.java │ │ └── org │ │ └── devicehive │ │ └── glass │ │ ├── NeuralyzerActivity.java │ │ └── PhillipsHueDevice.java └── python_gateway │ └── philips_hue_example.py ├── RainbowCube ├── firmware │ └── firmware.ino └── html │ ├── css │ └── spectrum.css │ ├── cube.html │ └── js │ ├── app.js │ └── lib │ ├── devicehive.js │ ├── jquery-1.8.3.min.js │ └── spectrum.js └── wifi_config ├── Makefile ├── exec.hpp ├── gpiopin.hpp ├── index.html ├── main.cpp ├── readme ├── server ├── server.hpp └── wireless.hpp /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "ios"] 2 | path = ios 3 | url = https://github.com/devicehive/devicehive-ios.git 4 | [submodule "cpp"] 5 | path = cpp 6 | url = https://github.com/devicehive/devicehive-cpp.git 7 | [submodule "android"] 8 | path = android 9 | url = https://github.com/devicehive/devicehive-android.git 10 | [submodule "admin-console"] 11 | path = admin-console 12 | url = https://github.com/devicehive/devicehive-admin-console.git 13 | [submodule "javascript"] 14 | path = javascript 15 | url = https://github.com/devicehive/devicehive-javascript.git 16 | [submodule "uc"] 17 | path = uc 18 | url = https://github.com/devicehive/devicehive-uc.git 19 | [submodule "python"] 20 | path = python 21 | url = https://github.com/devicehive/devicehive-python.git 22 | [submodule "arduino"] 23 | path = arduino 24 | url = https://github.com/devicehive/devicehive-arduino.git 25 | [submodule "j2me"] 26 | path = j2me 27 | url = https://github.com/devicehive/devicehive-j2me.git 28 | [submodule "net"] 29 | path = net 30 | url = https://github.com/devicehive/devicehive-.net.git 31 | [submodule "net-mf"] 32 | path = net-mf 33 | url = https://github.com/devicehive/devicehive-.net-mf.git 34 | [submodule "java"] 35 | path = java 36 | url = https://github.com/devicehive/devicehive-java.git 37 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | DeviceHive is developed by DataArt Apps and distributed under MIT license. 2 | 3 | Copyright (C) 2015 DataArt Apps 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of 6 | this software and associated documentation files (the "Software"), to deal in 7 | the Software without restriction, including without limitation the rights to 8 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 9 | of the Software, and to permit persons to whom the Software is furnished to do 10 | so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devicehive/framework/2a7dac8332209f3f2faed82c5184ef990f7fbc91/README.md -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 5 | 6 | 9 | 10 | 14 | 15 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/lib/android-support-v4.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devicehive/framework/2a7dac8332209f3f2faed82c5184ef990f7fbc91/examples/Glass_PhillipsHue/glass_app/lib/android-support-v4.jar -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/lib/gson-2.2.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devicehive/framework/2a7dac8332209f3f2faed82c5184ef990f7fbc91/examples/Glass_PhillipsHue/glass_app/lib/gson-2.2.jar -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/res/drawable-hdpi/light_off.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devicehive/framework/2a7dac8332209f3f2faed82c5184ef990f7fbc91/examples/Glass_PhillipsHue/glass_app/res/drawable-hdpi/light_off.png -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/res/drawable-hdpi/light_on.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devicehive/framework/2a7dac8332209f3f2faed82c5184ef990f7fbc91/examples/Glass_PhillipsHue/glass_app/res/drawable-hdpi/light_on.png -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/res/drawable-hdpi/light_scene.1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devicehive/framework/2a7dac8332209f3f2faed82c5184ef990f7fbc91/examples/Glass_PhillipsHue/glass_app/res/drawable-hdpi/light_scene.1.png -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/res/drawable-hdpi/light_scene2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devicehive/framework/2a7dac8332209f3f2faed82c5184ef990f7fbc91/examples/Glass_PhillipsHue/glass_app/res/drawable-hdpi/light_scene2.png -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/res/drawable-hdpi/light_scene3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devicehive/framework/2a7dac8332209f3f2faed82c5184ef990f7fbc91/examples/Glass_PhillipsHue/glass_app/res/drawable-hdpi/light_scene3.png -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/res/layout/layout_stopwatch.xml: -------------------------------------------------------------------------------- 1 | 8 | 15 | 16 | 17 | 22 | 23 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #ff000000 4 | 5 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | GlassMoodLamp 4 | GlassMoodLamp 5 | 6 | Tap to Light OffTap to Light On 7 | 8 | 9 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 7 | 14 | 15 | 16 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/src/com/dataart/android/devicehive/ApiInfo.java: -------------------------------------------------------------------------------- 1 | package com.dataart.android.devicehive; 2 | 3 | import android.os.Parcel; 4 | import android.os.Parcelable; 5 | 6 | /** 7 | * Represents meta-information about the current API. 8 | */ 9 | public class ApiInfo implements Parcelable { 10 | private String apiVersion; 11 | private String serverTimestamp; 12 | private String webSocketServerUrl; 13 | 14 | /** 15 | * Constructs API info object with given parameters. 16 | * 17 | * @param apiVersion 18 | * API version. 19 | * @param serverTimestamp 20 | * Current server timestamp. 21 | * @param webSocketServerUrl 22 | * WebSocket server URL. 23 | */ 24 | public ApiInfo(String apiVersion, String serverTimestamp, 25 | String webSocketServerUrl) { 26 | this.apiVersion = apiVersion; 27 | this.serverTimestamp = serverTimestamp; 28 | this.webSocketServerUrl = webSocketServerUrl; 29 | } 30 | 31 | /** 32 | * Get API version. 33 | * 34 | * @return API version string. 35 | */ 36 | public String getApiVersion() { 37 | return apiVersion; 38 | } 39 | 40 | /** 41 | * Get current server timestamp. 42 | * 43 | * @return Network key. 44 | */ 45 | public String getServerTimestamp() { 46 | return serverTimestamp; 47 | } 48 | 49 | /** 50 | * Get WebSocket server URL. 51 | * 52 | * @return WebSocket server URL. 53 | */ 54 | public String getWebSocketServerUrl() { 55 | return webSocketServerUrl; 56 | } 57 | 58 | @Override 59 | public int describeContents() { 60 | return 0; 61 | } 62 | 63 | @Override 64 | public void writeToParcel(Parcel dest, int flags) { 65 | dest.writeString(apiVersion); 66 | dest.writeString(serverTimestamp); 67 | dest.writeString(webSocketServerUrl); 68 | } 69 | 70 | public static Parcelable.Creator CREATOR = new Parcelable.Creator() { 71 | 72 | @Override 73 | public ApiInfo[] newArray(int size) { 74 | return new ApiInfo[size]; 75 | } 76 | 77 | @Override 78 | public ApiInfo createFromParcel(Parcel source) { 79 | return new ApiInfo(source.readString(), source.readString(), 80 | source.readString()); 81 | } 82 | }; 83 | 84 | @Override 85 | public String toString() { 86 | return "ApiInfo [apiVersion=" + apiVersion + ", serverTimestamp=" 87 | + serverTimestamp + ", webSocketServerUrl=" 88 | + webSocketServerUrl + "]"; 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/src/com/dataart/android/devicehive/Command.java: -------------------------------------------------------------------------------- 1 | package com.dataart.android.devicehive; 2 | 3 | import java.io.Serializable; 4 | 5 | import android.os.Parcel; 6 | import android.os.Parcelable; 7 | 8 | /** 9 | * Represents a device command, a unit of information sent to devices. 10 | */ 11 | public class Command implements Parcelable { 12 | private int id; 13 | private String timestamp; 14 | private String command; 15 | private ObjectWrapper parameters; 16 | private int lifetime; 17 | private int flags; 18 | private String status; 19 | private String result; 20 | 21 | /* package */Command(int id, String timestamp, String command, 22 | Serializable parameters, int lifetime, int flags, String status, 23 | String result) { 24 | this.id = id; 25 | this.timestamp = timestamp; 26 | this.command = command; 27 | this.parameters = new ObjectWrapper(parameters); 28 | this.lifetime = lifetime; 29 | this.flags = flags; 30 | this.status = status; 31 | this.result = result; 32 | } 33 | 34 | public Command(String command, Serializable parameters, int lifetime, 35 | int flags) { 36 | this(-1, null, command, parameters, lifetime, flags, null, null); 37 | } 38 | 39 | /** 40 | * Create command with given name and parameters. 41 | * 42 | * @param command 43 | * Command name. 44 | * @param parameters 45 | * Parameters dictionary. 46 | */ 47 | public Command(String command, Serializable parameters) { 48 | this(-1, null, command, parameters, 0, 0, null, null); 49 | } 50 | 51 | /** 52 | * Get command identifier. 53 | * 54 | * @return Command identifier set by the server. 55 | */ 56 | public int getId() { 57 | return id; 58 | } 59 | 60 | /** 61 | * Get command timestamp (UTC). 62 | * 63 | * @return Datetime timestamp associated with this command. 64 | */ 65 | public String getTimestamp() { 66 | return timestamp; 67 | } 68 | 69 | /** 70 | * Get command name. 71 | * 72 | * @return Command name. 73 | */ 74 | public String getCommand() { 75 | return command; 76 | } 77 | 78 | /** 79 | * Get command parameters dictionary. 80 | * 81 | * @return Command parameters dictionary. 82 | */ 83 | public Serializable getParameters() { 84 | return parameters != null ? parameters.getObject() : null; 85 | } 86 | 87 | /** 88 | * Get command lifetime. 89 | * 90 | * @return Number of seconds until this command expires. 91 | */ 92 | public int getLifetime() { 93 | return lifetime; 94 | } 95 | 96 | /** 97 | * Get command flags. It's optional. 98 | * 99 | * @return Value that could be supplied for device or related 100 | * infrastructure. 101 | */ 102 | public int getFlags() { 103 | return flags; 104 | } 105 | 106 | /** 107 | * Get command status, as reported by device or related infrastructure. 108 | * 109 | * @return Command status. 110 | */ 111 | public String getStatus() { 112 | return status; 113 | } 114 | 115 | /** 116 | * Get command execution result. It's optional value that could be provided 117 | * by device. 118 | * 119 | * @return Command execution result. 120 | */ 121 | public String getResult() { 122 | return result; 123 | } 124 | 125 | @Override 126 | public int describeContents() { 127 | return 0; 128 | } 129 | 130 | @Override 131 | public void writeToParcel(Parcel dest, int flags) { 132 | dest.writeInt(id); 133 | dest.writeString(timestamp); 134 | dest.writeString(command); 135 | dest.writeSerializable(parameters != null ? parameters.getObject() 136 | : parameters); 137 | dest.writeInt(lifetime); 138 | dest.writeInt(flags); 139 | dest.writeString(status); 140 | dest.writeString(result); 141 | } 142 | 143 | public static Parcelable.Creator CREATOR = new Parcelable.Creator() { 144 | 145 | @Override 146 | public Command[] newArray(int size) { 147 | return new Command[size]; 148 | } 149 | 150 | @Override 151 | public Command createFromParcel(Parcel source) { 152 | return new Command(source.readInt(), source.readString(), 153 | source.readString(), source.readSerializable(), 154 | source.readInt(), source.readInt(), source.readString(), 155 | source.readString()); 156 | } 157 | }; 158 | 159 | @Override 160 | public String toString() { 161 | return "Command [id=" + id + ", timestamp=" + timestamp + ", command=" 162 | + command + ", parameters=" + parameters + ", lifetime=" 163 | + lifetime + ", flags=" + flags + ", status=" + status 164 | + ", result=" + result + "]"; 165 | } 166 | 167 | } 168 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/src/com/dataart/android/devicehive/DataContainer.java: -------------------------------------------------------------------------------- 1 | package com.dataart.android.devicehive; 2 | 3 | import java.io.Serializable; 4 | 5 | import android.os.Parcel; 6 | import android.os.Parcelable; 7 | 8 | /* package */abstract class DataContainer implements Parcelable { 9 | 10 | protected ObjectWrapper data; 11 | 12 | protected DataContainer() { 13 | this(null); 14 | } 15 | 16 | protected DataContainer(Serializable data) { 17 | setData(data); 18 | } 19 | 20 | /** 21 | * Set equipment data, an object with an arbitrary structure that can be 22 | * serialized to JSON. Equipment data can only be set/changed before device 23 | * registration. 24 | * 25 | * @param data 26 | * An object that can be serialized to JSON. 27 | */ 28 | public void setData(Serializable data) { 29 | this.data = new ObjectWrapper(data); 30 | } 31 | 32 | /** 33 | * Get device data. 34 | * 35 | * @return An object with arbitrary structure. Typically, an object is 36 | * constructed using StringMaps, ArrayLists and primitives. 37 | */ 38 | public Object getData() { 39 | return data != null ? data.getObject() : data; 40 | } 41 | 42 | @Override 43 | public int describeContents() { 44 | return 0; 45 | } 46 | 47 | @Override 48 | public void writeToParcel(Parcel dest, int flags) { 49 | dest.writeSerializable(data != null ? data.getObject() : data); 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/src/com/dataart/android/devicehive/DeviceClass.java: -------------------------------------------------------------------------------- 1 | package com.dataart.android.devicehive; 2 | 3 | import java.io.Serializable; 4 | 5 | import android.os.Parcel; 6 | import android.os.Parcelable; 7 | 8 | /** 9 | * Represents a device class which holds meta-information about {@link Client}s. 10 | */ 11 | public class DeviceClass extends DataContainer { 12 | private int id; 13 | private String name; 14 | private String version; 15 | private boolean isPermanent; 16 | private Integer offlineTimeout; 17 | 18 | /** 19 | * Construct a new device class with given parameters. This method is 20 | * intended for internal use. 21 | * 22 | * @param id 23 | * Device class identifier. 24 | * @param name 25 | * Device class display name. 26 | * @param version 27 | * Device class version. 28 | * @param isPermanent 29 | * Whether this device class is permanent. 30 | * @param offlineTimeout 31 | * If set, specifies inactivity timeout in seconds before the 32 | * framework changes device status to "Offline". 33 | */ 34 | public DeviceClass(int id, String name, String version, 35 | boolean isPermanent, Integer offlineTimeout) { 36 | this(null, id, name, version, isPermanent, offlineTimeout); 37 | } 38 | 39 | /* package */DeviceClass(Serializable data, int id, String name, 40 | String version, boolean isPermanent, Integer offlineTimeout) { 41 | super(data); 42 | this.id = id; 43 | this.name = name; 44 | this.version = version; 45 | this.isPermanent = isPermanent; 46 | this.offlineTimeout = offlineTimeout; 47 | } 48 | 49 | /** 50 | * Construct a new device class with given parameters. 51 | * 52 | * @param name 53 | * Device class display name. 54 | * @param version 55 | * Device class version. 56 | * @param isPermanent 57 | * Whether this device class is permanent. 58 | * @param offlineTimeout 59 | * If set, specifies inactivity timeout in seconds before the 60 | * framework changes device status to "Offline". 61 | */ 62 | public DeviceClass(String name, String version, boolean isPermanent, 63 | Integer offlineTimeout) { 64 | this(-1, name, version, isPermanent, offlineTimeout); 65 | } 66 | 67 | /** 68 | * Constructs a new device class with given parameters. 69 | * 70 | * @param name 71 | * Device class display name. 72 | * @param version 73 | * Device class version. 74 | */ 75 | public DeviceClass(String name, String version) { 76 | this(-1, name, version, false, null); 77 | } 78 | 79 | /** 80 | * Get device class identifier. 81 | * 82 | * @return Device class identifier. 83 | */ 84 | public int getId() { 85 | return id; 86 | } 87 | 88 | /** 89 | * Get device class display name. 90 | * 91 | * @return Device class display name. 92 | */ 93 | public String getName() { 94 | return name; 95 | } 96 | 97 | /** 98 | * Get device class version. 99 | * 100 | * @return Device class version. 101 | */ 102 | public String getVersion() { 103 | return version; 104 | } 105 | 106 | /** 107 | * Check whether the device class is permanent. Permanent device classes 108 | * could not be modified by devices during registration. 109 | * 110 | * @return true if device class is permanent, otherwise returns false. 111 | */ 112 | public boolean isPermanent() { 113 | return isPermanent; 114 | } 115 | 116 | /** 117 | * Get offline timeout. If set, specifies inactivity timeout in seconds 118 | * before the framework changes device status to "Offline". 119 | * 120 | * @return Inactivity timeout value in seconds. 121 | */ 122 | public Integer getOfflineTimeout() { 123 | return offlineTimeout; 124 | } 125 | 126 | @Override 127 | public void writeToParcel(Parcel dest, int flags) { 128 | super.writeToParcel(dest, flags); 129 | dest.writeInt(id); 130 | dest.writeString(name); 131 | dest.writeString(version); 132 | dest.writeInt(isPermanent ? 1 : 0); 133 | dest.writeValue(offlineTimeout); 134 | } 135 | 136 | public static Parcelable.Creator CREATOR = new Parcelable.Creator() { 137 | 138 | @Override 139 | public DeviceClass[] newArray(int size) { 140 | return new DeviceClass[size]; 141 | } 142 | 143 | @Override 144 | public DeviceClass createFromParcel(Parcel source) { 145 | return new DeviceClass(source.readSerializable(), source.readInt(), 146 | source.readString(), source.readString(), 147 | source.readInt() > 0, (Integer) source.readValue(null)); 148 | } 149 | }; 150 | 151 | @Override 152 | public String toString() { 153 | return "DeviceClass [id=" + id + ", name=" + name + ", version=" 154 | + version + ", isPermanent=" + isPermanent 155 | + ", offlineTimeout=" + offlineTimeout + ", data=" + data + "]"; 156 | } 157 | 158 | } 159 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/src/com/dataart/android/devicehive/DeviceData.java: -------------------------------------------------------------------------------- 1 | package com.dataart.android.devicehive; 2 | 3 | import java.io.Serializable; 4 | import java.util.LinkedList; 5 | import java.util.List; 6 | 7 | import android.os.Parcel; 8 | import android.os.Parcelable; 9 | 10 | /** 11 | * Represents device data. 12 | */ 13 | public class DeviceData extends DataContainer { 14 | 15 | /** 16 | * "Online" device status. 17 | */ 18 | public static final String DEVICE_STATUS_ONLINE = "Online"; 19 | 20 | /** 21 | * "OK" device status. 22 | */ 23 | public static final String DEVICE_STATUS_OK = "OK"; 24 | 25 | private String id; 26 | private String key; 27 | private String name; 28 | private String status; 29 | private Network network; 30 | private DeviceClass deviceClass; 31 | private List equipment; 32 | 33 | private final static ClassLoader CLASS_LOADER = DeviceData.class 34 | .getClassLoader(); 35 | 36 | /** 37 | * Construct device data with given parameters. 38 | * 39 | * @param id 40 | * Device unique identifier. 41 | * @param key 42 | * Device authentication key. The key maximum length is 64 43 | * characters. 44 | * @param name 45 | * Device display name. 46 | * @param status 47 | * Device operation status. 48 | * @param network 49 | * Associated {@link Network}. 50 | * @param deviceClass 51 | * Associated {@link DeviceClass}. 52 | */ 53 | public DeviceData(String id, String key, String name, String status, 54 | Network network, DeviceClass deviceClass) { 55 | this(null, id, key, name, status, network, deviceClass, null); 56 | } 57 | 58 | /** 59 | * Construct device data with given parameters. 60 | * 61 | * @param id 62 | * Device unique identifier. 63 | * @param key 64 | * Device authentication key. The key maximum length is 64 65 | * characters. 66 | * @param name 67 | * Device display name. 68 | * @param status 69 | * Device operation status. 70 | * @param deviceClass 71 | * Associated {@link DeviceClass}. 72 | */ 73 | public DeviceData(String id, String key, String name, String status, 74 | DeviceClass deviceClass) { 75 | this(null, id, key, name, status, null, deviceClass, null); 76 | } 77 | 78 | /* package */DeviceData(Serializable data, String id, String key, 79 | String name, String status, Network network, 80 | DeviceClass deviceClass, List equipment) { 81 | super(data); 82 | this.id = id; 83 | this.key = key; 84 | this.name = name; 85 | this.status = status; 86 | this.network = network; 87 | this.deviceClass = deviceClass; 88 | this.equipment = equipment; 89 | } 90 | 91 | /** 92 | * Get device identifier. 93 | * 94 | * @return Device identifier. 95 | */ 96 | public String getId() { 97 | return id; 98 | } 99 | 100 | /** 101 | * Get device authentication key. 102 | * 103 | * @return Device authentication key. 104 | */ 105 | public String getKey() { 106 | return key; 107 | } 108 | 109 | /** 110 | * Get device display name. 111 | * 112 | * @return Device display name. 113 | */ 114 | public String getName() { 115 | return name; 116 | } 117 | 118 | /** 119 | * Get device status. 120 | * 121 | * @return Device status. 122 | */ 123 | public String getStatus() { 124 | return status; 125 | } 126 | 127 | /** 128 | * Get associated {@link Network}. 129 | * 130 | * @return Associated {@link Network} object. 131 | */ 132 | public Network getNetwork() { 133 | return network; 134 | } 135 | 136 | /** 137 | * Get device class. 138 | * 139 | * @return Associated {@link DeviceClass} object. 140 | */ 141 | public DeviceClass getDeviceClass() { 142 | return deviceClass; 143 | } 144 | 145 | /** 146 | * Get list of device equipment. 147 | * 148 | * @return Device equipment list. 149 | */ 150 | public List getEquipment() { 151 | return equipment; 152 | } 153 | 154 | /** 155 | * Add equipment to the device. 156 | * 157 | * @param equipmentData 158 | * Equipment to be added. 159 | */ 160 | public void addEquipment(EquipmentData equipmentData) { 161 | if (this.equipment == null) { 162 | this.equipment = new LinkedList(); 163 | } 164 | this.equipment.add(equipmentData); 165 | } 166 | 167 | @Override 168 | public int describeContents() { 169 | return 0; 170 | } 171 | 172 | @Override 173 | public void writeToParcel(Parcel dest, int flags) { 174 | super.writeToParcel(dest, flags); 175 | dest.writeString(id); 176 | dest.writeString(key); 177 | dest.writeString(name); 178 | dest.writeString(status); 179 | dest.writeParcelable(network, 0); 180 | dest.writeParcelable(deviceClass, 0); 181 | dest.writeTypedList(equipment); 182 | } 183 | 184 | public static Parcelable.Creator CREATOR = new Parcelable.Creator() { 185 | 186 | @Override 187 | public DeviceData[] newArray(int size) { 188 | return new DeviceData[size]; 189 | } 190 | 191 | @Override 192 | public DeviceData createFromParcel(Parcel source) { 193 | Serializable data = source.readSerializable(); 194 | String id = source.readString(); 195 | String key = source.readString(); 196 | String name = source.readString(); 197 | String status = source.readString(); 198 | Network network = source.readParcelable(CLASS_LOADER); 199 | DeviceClass deviceClass = source.readParcelable(CLASS_LOADER); 200 | List equipments = new LinkedList(); 201 | source.readTypedList(equipments, EquipmentData.CREATOR); 202 | return new DeviceData(data, id, key, name, status, network, 203 | deviceClass, equipments); 204 | } 205 | }; 206 | 207 | @Override 208 | public String toString() { 209 | return "DeviceData [id=" + id + ", key=" + key + ", name=" + name 210 | + ", status=" + status + ", network=" + network 211 | + ", deviceClass=" + deviceClass + ", equipment=" + equipment 212 | + ", data=" + data + "]"; 213 | } 214 | 215 | } 216 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/src/com/dataart/android/devicehive/DeviceHive.java: -------------------------------------------------------------------------------- 1 | package com.dataart.android.devicehive; 2 | 3 | /** 4 | * Some declarations which are intended for internal use. 5 | */ 6 | public class DeviceHive { 7 | /** 8 | * Logging TAG. 9 | */ 10 | public final static String TAG = "DeviceHive"; 11 | } 12 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/src/com/dataart/android/devicehive/EquipmentData.java: -------------------------------------------------------------------------------- 1 | package com.dataart.android.devicehive; 2 | 3 | import java.io.Serializable; 4 | 5 | import android.os.Parcel; 6 | import android.os.Parcelable; 7 | 8 | import com.dataart.android.devicehive.device.Equipment; 9 | 10 | /** 11 | * Represents equipment data. Used to initialize {@link Equipment} object. 12 | */ 13 | public class EquipmentData extends DataContainer { 14 | private int id; 15 | private String name; 16 | private String code; 17 | private String type; 18 | 19 | /** 20 | * Construct equipment data with given name, code and type. 21 | * 22 | * @param name 23 | * Equipment display name. 24 | * @param code 25 | * Equipment code. It's used to reference particular equipment 26 | * and it should be unique within a device class. 27 | * @param type 28 | * Equipment type. An arbitrary string representing equipment 29 | * capabilities. 30 | */ 31 | public EquipmentData(String name, String code, String type) { 32 | this(null, -1, name, code, type); 33 | } 34 | 35 | /* package */EquipmentData(Serializable data, int id, String name, 36 | String code, String type) { 37 | super(data); 38 | this.id = id; 39 | this.name = name; 40 | this.code = code; 41 | this.type = type; 42 | } 43 | 44 | /** 45 | * Get equipment identifier. 46 | * 47 | * @return Equipment identifier. 48 | */ 49 | public int getId() { 50 | return id; 51 | } 52 | 53 | /** 54 | * Get equipment display name. 55 | * 56 | * @return Equipment display name. 57 | */ 58 | public String getName() { 59 | return name; 60 | } 61 | 62 | /** 63 | * Get equipment code. It's used to reference particular equipment and it 64 | * should be unique within a {@link DeviceClass}. 65 | * 66 | * @return Equipment code. 67 | */ 68 | public String getCode() { 69 | return code; 70 | } 71 | 72 | /** 73 | * Get equipment type. It's an arbitrary string representing equipment 74 | * capabilities. 75 | * 76 | * @return Equipment type. 77 | */ 78 | public String getType() { 79 | return type; 80 | } 81 | 82 | @Override 83 | public void writeToParcel(Parcel dest, int flags) { 84 | super.writeToParcel(dest, flags); 85 | dest.writeInt(id); 86 | dest.writeString(name); 87 | dest.writeString(code); 88 | dest.writeString(type); 89 | } 90 | 91 | public static Parcelable.Creator CREATOR = new Parcelable.Creator() { 92 | 93 | @Override 94 | public EquipmentData[] newArray(int size) { 95 | return new EquipmentData[size]; 96 | } 97 | 98 | @Override 99 | public EquipmentData createFromParcel(Parcel source) { 100 | return new EquipmentData(source.readSerializable(), 101 | source.readInt(), source.readString(), source.readString(), 102 | source.readString()); 103 | } 104 | }; 105 | 106 | } 107 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/src/com/dataart/android/devicehive/EquipmentState.java: -------------------------------------------------------------------------------- 1 | package com.dataart.android.devicehive; 2 | 3 | import java.io.Serializable; 4 | 5 | import android.os.Parcel; 6 | import android.os.Parcelable; 7 | 8 | import com.google.gson.annotations.SerializedName; 9 | 10 | /** 11 | * Represents equipment state. 12 | */ 13 | public class EquipmentState implements Parcelable { 14 | @SerializedName("id") 15 | private String equipmentCode; 16 | private String timestamp; 17 | private ObjectWrapper parameters; 18 | 19 | /** 20 | * Construct equipment state with given parameters. 21 | * 22 | * @param code 23 | * Equipment code. 24 | * @param timestamp 25 | * @param parameters 26 | */ 27 | /* package */EquipmentState(String code, String timestamp, 28 | Serializable parameters) { 29 | this.equipmentCode = code; 30 | this.timestamp = timestamp; 31 | this.parameters = new ObjectWrapper(parameters); 32 | } 33 | 34 | /** 35 | * Get equipment code. 36 | * 37 | * @return Equipment code value. 38 | */ 39 | public String getEquipmentCode() { 40 | return equipmentCode; 41 | } 42 | 43 | /** 44 | * Get equipment state timestamp. 45 | * 46 | * @return Equipment state timestamp. 47 | */ 48 | public String getTimestamp() { 49 | return timestamp; 50 | } 51 | 52 | /** 53 | * Get current equipment state. 54 | * 55 | * @return Equipment state parameters. 56 | */ 57 | public Object getParameters() { 58 | return parameters != null ? parameters.getObject() : parameters; 59 | } 60 | 61 | @Override 62 | public void writeToParcel(Parcel dest, int flags) { 63 | dest.writeString(equipmentCode); 64 | dest.writeString(timestamp); 65 | dest.writeSerializable(parameters != null ? parameters.getObject() 66 | : parameters); 67 | } 68 | 69 | public static Parcelable.Creator CREATOR = new Parcelable.Creator() { 70 | 71 | @Override 72 | public EquipmentState[] newArray(int size) { 73 | return new EquipmentState[size]; 74 | } 75 | 76 | @Override 77 | public EquipmentState createFromParcel(Parcel source) { 78 | return new EquipmentState(source.readString(), source.readString(), 79 | source.readSerializable()); 80 | } 81 | }; 82 | 83 | @Override 84 | public int describeContents() { 85 | return 0; 86 | } 87 | 88 | @Override 89 | public String toString() { 90 | return String.format( 91 | "EquipmentState(code = %s, timestamp = %s, parameters = %s)", 92 | equipmentCode, timestamp, parameters); 93 | } 94 | 95 | } 96 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/src/com/dataart/android/devicehive/Network.java: -------------------------------------------------------------------------------- 1 | package com.dataart.android.devicehive; 2 | 3 | import android.os.Parcel; 4 | import android.os.Parcelable; 5 | 6 | /** 7 | * Represents a network, an isolated area where {@link Client}s reside. 8 | */ 9 | public class Network implements Parcelable { 10 | private int id; 11 | private String key; 12 | private String name; 13 | private String description; 14 | 15 | public Network(int id, String key, String name, String description) { 16 | this.id = id; 17 | this.key = key; 18 | this.name = name; 19 | this.description = description; 20 | } 21 | 22 | /** 23 | * Constructs network object with given name and description and key. 24 | * 25 | * @param key 26 | * Network key. 27 | * @param name 28 | * Network display name. 29 | * @param description 30 | * Network description. 31 | */ 32 | public Network(String key, String name, String description) { 33 | this(-1, key, name, description); 34 | } 35 | 36 | /** 37 | * Constructs network object with given name and description. 38 | * 39 | * @param name 40 | * Network display name. 41 | * @param description 42 | * Network description. 43 | */ 44 | public Network(String name, String description) { 45 | this(-1, null, name, description); 46 | } 47 | 48 | /** 49 | * Get network identifier. 50 | * 51 | * @return Network identifier. 52 | */ 53 | public int getId() { 54 | return id; 55 | } 56 | 57 | /** 58 | * Get network key. Optional key that is used to protect the network from 59 | * unauthorized device registrations. 60 | * 61 | * @return Network key. 62 | */ 63 | public String getKey() { 64 | return key; 65 | } 66 | 67 | /** 68 | * Get network display name. 69 | * 70 | * @return Network display name. 71 | */ 72 | public String getName() { 73 | return name; 74 | } 75 | 76 | /** 77 | * Get network description. 78 | * 79 | * @return Network description. 80 | */ 81 | public String getDescription() { 82 | return description; 83 | } 84 | 85 | @Override 86 | public int describeContents() { 87 | return 0; 88 | } 89 | 90 | @Override 91 | public void writeToParcel(Parcel dest, int flags) { 92 | dest.writeInt(id); 93 | dest.writeString(key); 94 | dest.writeString(name); 95 | dest.writeString(description); 96 | } 97 | 98 | public static Parcelable.Creator CREATOR = new Parcelable.Creator() { 99 | 100 | @Override 101 | public Network[] newArray(int size) { 102 | return new Network[size]; 103 | } 104 | 105 | @Override 106 | public Network createFromParcel(Parcel source) { 107 | return new Network(source.readInt(), source.readString(), 108 | source.readString(), source.readString()); 109 | } 110 | }; 111 | 112 | @Override 113 | public String toString() { 114 | return "Network [id=" + id + ", key=" + key + ", name=" + name 115 | + ", description=" + description + "]"; 116 | } 117 | 118 | } 119 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/src/com/dataart/android/devicehive/Notification.java: -------------------------------------------------------------------------------- 1 | package com.dataart.android.devicehive; 2 | 3 | import java.io.Serializable; 4 | 5 | import android.os.Parcel; 6 | import android.os.Parcelable; 7 | 8 | import com.google.gson.annotations.SerializedName; 9 | 10 | /** 11 | * Represents a device notification, a unit of information dispatched from 12 | * {@link Client}s. 13 | */ 14 | public class Notification implements Parcelable { 15 | private int id; 16 | @SerializedName("notification") 17 | private String name; 18 | private String timestamp; 19 | private ObjectWrapper parameters; 20 | 21 | protected Notification(int id, String name, String timestamp, 22 | Serializable parameters) { 23 | this.id = id; 24 | this.name = name; 25 | this.timestamp = timestamp; 26 | this.parameters = new ObjectWrapper(parameters); 27 | } 28 | 29 | /** 30 | * Construct a new notification with given name and parameters. 31 | * 32 | * @param name 33 | * Notification name. 34 | * @param parameters 35 | * Notification parameters. 36 | */ 37 | public Notification(String name, Serializable parameters) { 38 | this(-1, name, null, parameters); 39 | } 40 | 41 | /** 42 | * Get notification identifier. 43 | * 44 | * @return Notification identifier. 45 | */ 46 | public int getId() { 47 | return id; 48 | } 49 | 50 | /** 51 | * Get notification name. 52 | * 53 | * @return Notification name. 54 | */ 55 | public String getName() { 56 | return name; 57 | } 58 | 59 | /** 60 | * Get notification timestamp(UTC). 61 | * 62 | * @return Notification timestamp(UTC). 63 | */ 64 | public String getTimestamp() { 65 | return timestamp; 66 | } 67 | 68 | /** 69 | * Get notification parameters dictionary. 70 | * 71 | * @return Notification parameters dictionary. 72 | */ 73 | public Serializable getParameters() { 74 | return parameters != null ? parameters.getObject() : parameters; 75 | } 76 | 77 | @Override 78 | public int describeContents() { 79 | return 0; 80 | } 81 | 82 | @Override 83 | public void writeToParcel(Parcel dest, int flags) { 84 | dest.writeInt(id); 85 | dest.writeString(name); 86 | dest.writeSerializable(timestamp); 87 | dest.writeSerializable(parameters != null ? parameters.getObject() 88 | : parameters); 89 | } 90 | 91 | public static Parcelable.Creator CREATOR = new Parcelable.Creator() { 92 | 93 | @Override 94 | public Notification[] newArray(int size) { 95 | return new Notification[size]; 96 | } 97 | 98 | @Override 99 | public Notification createFromParcel(Parcel source) { 100 | return new Notification(source.readInt(), source.readString(), 101 | source.readString(), source.readSerializable()); 102 | } 103 | }; 104 | 105 | @Override 106 | public String toString() { 107 | return "Notification [id=" + id + ", name=" + name + ", timestamp=" 108 | + timestamp + ", parameters=" + parameters + "]"; 109 | } 110 | 111 | } 112 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/src/com/dataart/android/devicehive/ObjectWrapper.java: -------------------------------------------------------------------------------- 1 | package com.dataart.android.devicehive; 2 | 3 | import java.io.Serializable; 4 | 5 | public class ObjectWrapper implements Serializable { 6 | 7 | private static final long serialVersionUID = -7373759268902337088L; 8 | 9 | private final T object; 10 | 11 | public ObjectWrapper(T object) { 12 | this.object = object; 13 | } 14 | 15 | public T getObject() { 16 | return object; 17 | } 18 | 19 | @Override 20 | public String toString() { 21 | if (object == null) { 22 | return "" + object; 23 | } else { 24 | return object.toString(); 25 | } 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/src/com/dataart/android/devicehive/client/ClientServiceConnection.java: -------------------------------------------------------------------------------- 1 | package com.dataart.android.devicehive.client; 2 | 3 | import java.util.LinkedList; 4 | import java.util.List; 5 | import java.util.Queue; 6 | 7 | import android.content.Context; 8 | import android.os.Bundle; 9 | import android.util.Log; 10 | 11 | import com.dataart.android.devicehive.ApiInfo; 12 | import com.dataart.android.devicehive.Command; 13 | import com.dataart.android.devicehive.DeviceData; 14 | import com.dataart.android.devicehive.DeviceHive; 15 | import com.dataart.android.devicehive.Notification; 16 | import com.dataart.android.devicehive.client.commands.GetDeviceCommand; 17 | import com.dataart.android.devicehive.client.commands.NotificationsRetrivalCommand; 18 | import com.dataart.android.devicehive.client.commands.PollDeviceNotificationsCommand; 19 | import com.dataart.android.devicehive.client.commands.PollMultipleDeviceNotificationsCommand; 20 | import com.dataart.android.devicehive.client.commands.SendDeviceCommandCommand; 21 | import com.dataart.android.devicehive.commands.GetApiInfoCommand; 22 | import com.dataart.android.devicehive.network.DeviceHiveResultReceiver; 23 | import com.dataart.android.devicehive.network.NetworkCommand; 24 | import com.dataart.android.devicehive.network.NetworkCommandConfig; 25 | import com.dataart.android.devicehive.network.ServiceConnection; 26 | 27 | /* package */abstract class ClientServiceConnection extends ServiceConnection { 28 | 29 | private DeviceClient client; 30 | 31 | private final Queue notificationQueue = new LinkedList(); 32 | 33 | private boolean isReceivingNotifications = false; 34 | 35 | private String username; 36 | private String password; 37 | 38 | private boolean isPollRequestInProgress = false; 39 | 40 | private String lastNotificationPollTimestamp; 41 | private Integer notificationPollWaitTimeout; 42 | 43 | public ClientServiceConnection(Context context) { 44 | super(context); 45 | } 46 | 47 | /* package */void setAuthorisation(String username, String password) { 48 | this.username = username; 49 | this.password = password; 50 | } 51 | 52 | /* package */void setLastNotificationPollTimestamp(String timestamp) { 53 | this.lastNotificationPollTimestamp = timestamp; 54 | } 55 | 56 | /* package */String getLastNotificationPollTimestamp() { 57 | return lastNotificationPollTimestamp; 58 | } 59 | 60 | /* package */void setNotificationPollWaitTimeout(Integer timeout) { 61 | this.notificationPollWaitTimeout = timeout; 62 | } 63 | 64 | /* package */void sendCommand(DeviceData deviceData, Command command) { 65 | logD("Sending command: " + command.getCommand()); 66 | client.onStartSendingCommand(command); 67 | startNetworkCommand(new SendDeviceCommandCommand(deviceData.getId(), command)); 68 | } 69 | 70 | /* package */void reloadDeviceData(DeviceData deviceData) { 71 | startNetworkCommand(new GetDeviceCommand(deviceData.getId())); 72 | } 73 | 74 | /* package */void startReceivingNotifications() { 75 | if (isReceivingNotifications) { 76 | stopReceivingNotifications(); 77 | } 78 | isReceivingNotifications = true; 79 | handleNextNotification(); 80 | } 81 | 82 | /* package */void stopReceivingNotifications() { 83 | detachResultReceiver(); 84 | isReceivingNotifications = false; 85 | isPollRequestInProgress = false; 86 | } 87 | 88 | /* package */void setClient(DeviceClient client) { 89 | this.client = client; 90 | } 91 | 92 | /* package */boolean isReceivingNotifications() { 93 | return isReceivingNotifications; 94 | } 95 | 96 | private void handleNotification(final Notification notification) { 97 | if (client.shouldReceiveNotificationAsynchronously(notification)) { 98 | asyncHandler.post(new Runnable() { 99 | @Override 100 | public void run() { 101 | didReceiveNotification(notification); 102 | mainThreadHandler.post(new Runnable() { 103 | @Override 104 | public void run() { 105 | if (isReceivingNotifications) { 106 | handleNextNotification(); 107 | } 108 | } 109 | }); 110 | } 111 | }); 112 | } else { 113 | didReceiveNotification(notification); 114 | if (isReceivingNotifications) { 115 | handleNextNotification(); 116 | } 117 | } 118 | } 119 | 120 | private void handleNextNotification() { 121 | final Notification notification = notificationQueue.poll(); 122 | if (notification != null) { 123 | handleNotification(notification); 124 | } else { 125 | if (!isPollRequestInProgress) { 126 | isPollRequestInProgress = true; 127 | if (lastNotificationPollTimestamp == null) { 128 | // timestamp wasn't specified. Request and use server 129 | // timestamp instead. 130 | logD("Starting Get API info command"); 131 | startNetworkCommand(new GetApiInfoCommand()); 132 | } else { 133 | startPollNotificationsRequest(); 134 | } 135 | } 136 | } 137 | } 138 | 139 | protected abstract NotificationsRetrivalCommand getPollNotificationsCommand( 140 | String lastNotificationPollTimestamp, Integer waitTimeout); 141 | 142 | protected abstract void didReceiveNotification(Notification notification); 143 | 144 | private void startPollNotificationsRequest() { 145 | logD("Starting polling request with lastNotificationPollTimestamp = " 146 | + lastNotificationPollTimestamp); 147 | startNetworkCommand(getPollNotificationsCommand( 148 | lastNotificationPollTimestamp, notificationPollWaitTimeout)); 149 | } 150 | 151 | private int enqueueNotifications(List notifications) { 152 | if (notifications == null || notifications.isEmpty()) { 153 | return 0; 154 | } 155 | int enqueuedCount = 0; 156 | for (Notification notification : notifications) { 157 | boolean added = notificationQueue.offer(notification); 158 | if (!added) { 159 | Log.e(DeviceHive.TAG, "Failed to add notification to the queue"); 160 | } else { 161 | enqueuedCount++; 162 | } 163 | } 164 | return enqueuedCount; 165 | } 166 | 167 | @Override 168 | protected void onReceiveResult(final int resultCode, final int tagId, 169 | final Bundle resultData) { 170 | switch (resultCode) { 171 | case DeviceHiveResultReceiver.MSG_HANDLED_RESPONSE: 172 | logD("Handled response"); 173 | if (tagId == TAG_SEND_COMMAND) { 174 | Command command = SendDeviceCommandCommand 175 | .getSentCommand(resultData); 176 | logD("Command sent with response: " + command); 177 | client.onFinishSendingCommand(command); 178 | } else if (tagId == TAG_POLL_NOTIFICATIONS 179 | || tagId == TAG_POLL_MULTIPLE_NOTIFICATIONS) { 180 | logD("Poll request finished"); 181 | isPollRequestInProgress = false; 182 | List notifications = PollDeviceNotificationsCommand 183 | .getNotifications(resultData); 184 | logD("-------Received notifications: " + notifications); 185 | logD("Notifications count: " + notifications.size()); 186 | int enqueuedCount = enqueueNotifications(notifications); 187 | logD("Enqueued notifications count: " + enqueuedCount); 188 | if (!notifications.isEmpty()) { 189 | lastNotificationPollTimestamp = notifications.get( 190 | notifications.size() - 1).getTimestamp(); 191 | } 192 | if (isReceivingNotifications) { 193 | handleNextNotification(); 194 | } 195 | } else if (tagId == TAG_GET_DEVICE) { 196 | logD("Get device request finished"); 197 | final DeviceData deviceData = GetDeviceCommand 198 | .getDevice(resultData); 199 | client.onReloadDeviceDataFinishedInternal(deviceData); 200 | } else if (tagId == TAG_GET_API_INFO) { 201 | final ApiInfo apiInfo = GetApiInfoCommand 202 | .getApiInfo(resultData); 203 | logD("Get API info request finished: " + apiInfo); 204 | lastNotificationPollTimestamp = apiInfo.getServerTimestamp(); 205 | logD("Starting polling request with lastNotificationPollTimestamp = " 206 | + lastNotificationPollTimestamp); 207 | startPollNotificationsRequest(); 208 | } 209 | break; 210 | case DeviceHiveResultReceiver.MSG_EXCEPTION: 211 | final Throwable exception = NetworkCommand.getThrowable(resultData); 212 | Log.e(DeviceHive.TAG, "DeviceHiveResultReceiver.MSG_EXCEPTION", 213 | exception); 214 | case DeviceHiveResultReceiver.MSG_STATUS_FAILURE: 215 | if (tagId == TAG_SEND_COMMAND) { 216 | SendDeviceCommandCommand command = (SendDeviceCommandCommand) NetworkCommand 217 | .getCommand(resultData); 218 | client.onFailSendingCommand(command.getCommand()); 219 | } else if (tagId == TAG_POLL_NOTIFICATIONS 220 | || tagId == TAG_POLL_MULTIPLE_NOTIFICATIONS 221 | || tagId == TAG_GET_API_INFO) { 222 | Log.d(DeviceHive.TAG, "Failed to poll notifications"); 223 | isPollRequestInProgress = false; 224 | if (isReceivingNotifications) { 225 | handleNextNotification(); 226 | } 227 | } else if (tagId == TAG_GET_DEVICE) { 228 | client.onReloadDeviceDataFailedInternal(); 229 | } 230 | break; 231 | } 232 | 233 | } 234 | 235 | @Override 236 | protected NetworkCommandConfig getCommandConfig() { 237 | final NetworkCommandConfig config = super.getCommandConfig(); 238 | config.setBasicAuthorisation(username, password); 239 | return config; 240 | } 241 | 242 | private final static int TAG_SEND_COMMAND = getTagId(SendDeviceCommandCommand.class); 243 | private final static int TAG_POLL_NOTIFICATIONS = getTagId(PollDeviceNotificationsCommand.class); 244 | private final static int TAG_POLL_MULTIPLE_NOTIFICATIONS = getTagId(PollMultipleDeviceNotificationsCommand.class); 245 | private final static int TAG_GET_DEVICE = getTagId(GetDeviceCommand.class); 246 | private static final int TAG_GET_API_INFO = getTagId(GetApiInfoCommand.class); 247 | } 248 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/src/com/dataart/android/devicehive/client/DeviceClient.java: -------------------------------------------------------------------------------- 1 | package com.dataart.android.devicehive.client; 2 | 3 | import android.content.Context; 4 | 5 | import com.dataart.android.devicehive.Command; 6 | import com.dataart.android.devicehive.DeviceData; 7 | import com.dataart.android.devicehive.Notification; 8 | 9 | /** 10 | * An abstract device client which provides basic API for clients. This class is 11 | * abstract and designed to be subclassed. 12 | */ 13 | /* package */abstract class DeviceClient { 14 | 15 | protected final Context context; 16 | protected ClientServiceConnection serviceConnection; 17 | 18 | /** 19 | * Construct client with given {@link Context}. 20 | * 21 | * @param context 22 | * {@link Context} object. In most cases this should be 23 | * application context which stays alive during the entire life 24 | * of an application. 25 | */ 26 | protected DeviceClient(Context context) { 27 | this.context = context; 28 | } 29 | 30 | /** 31 | * Set Device Hive service URL. This method MUST be called before 32 | * performing registration and other subsequent network communications. 33 | * 34 | * @param url 35 | * URL of Device Hive service. 36 | */ 37 | public void setApiEnpointUrl(String url) { 38 | serviceConnection.setApiEndpointUrl(url); 39 | } 40 | 41 | /** 42 | * Get previously set Device Hive service URL. 43 | * 44 | * @return URL of Device Hive service. 45 | */ 46 | public String getApiEndpointUrl() { 47 | return serviceConnection.getApiEndpointUrl(); 48 | } 49 | 50 | /** 51 | * Set Basic Authorisation credentials. 52 | * 53 | * @param username 54 | * Username string. 55 | * @param password 56 | * Password strung. 57 | */ 58 | public void setAuthorisation(String username, String password) { 59 | serviceConnection.setAuthorisation(username, password); 60 | } 61 | 62 | /** 63 | * Enable or disable debug log messages. 64 | * 65 | * @param enabled 66 | * Whether debug log messages enabled or not. 67 | */ 68 | public void setDebugLoggingEnabled(boolean enabled) { 69 | serviceConnection.setDebugLoggingEnabled(enabled); 70 | } 71 | 72 | /** 73 | * Set timestamp of the last received notification. This value is used to 74 | * reduce amount of notifications received from the server as a result of 75 | * poll request to only those of them which were received by the server 76 | * later than the time defined by given timestamp. If not specified, the 77 | * server's timestamp is taken instead. 78 | * 79 | * @param timestamp 80 | * Timestamp of the last received notification. 81 | */ 82 | public void setLastNotificationPollTimestamp(String timestamp) { 83 | serviceConnection.setLastNotificationPollTimestamp(timestamp); 84 | } 85 | 86 | /** 87 | * Get the timestamp of the last received notification. 88 | * @return Timestamp of the last received notification. 89 | */ 90 | public String getLastNotificationPollTimestamp() { 91 | return serviceConnection.getLastNotificationPollTimestamp(); 92 | } 93 | 94 | /** 95 | * Set notification poll waiting timeout in seconds (default: 30 seconds, 96 | * maximum: 60 seconds). Specify 0 to disable waiting. 97 | * 98 | * @param timeout 99 | * Notification poll waiting timeout in seconds. 100 | */ 101 | public void setNotificationPollWaitTimeout(Integer timeout) { 102 | this.serviceConnection.setNotificationPollWaitTimeout(timeout); 103 | } 104 | 105 | /** 106 | * Check if this client is receiving notifications, i.e. performs 107 | * notification polling. 108 | * 109 | * @return true, if this client is performing notification polling, 110 | * otherwise returns false. 111 | */ 112 | public boolean isReceivingNotifications() { 113 | return serviceConnection.isReceivingNotifications(); 114 | } 115 | 116 | /** 117 | * Start receiving notifications. Client will start polling server for new 118 | * notifications. 119 | */ 120 | public void startReceivingNotifications() { 121 | onStartReceivingNotifications(); 122 | serviceConnection.startReceivingNotifications(); 123 | } 124 | 125 | /** 126 | * Stop receiving notifications. 127 | */ 128 | public void stopReceivingNotifications() { 129 | serviceConnection.stopReceivingNotifications(); 130 | onStopReceivingNotifications(); 131 | } 132 | 133 | /** 134 | * Get context which was used to create this client. 135 | * 136 | * @return {@link Context} was used to create this client. 137 | */ 138 | public Context getContext() { 139 | return serviceConnection.getContext(); 140 | } 141 | 142 | /** 143 | * Run given runnable on main thread. Helper method. 144 | * 145 | * @param runnable 146 | * Instance which implements {@link Runnable} interface. 147 | */ 148 | protected void runOnMainThread(Runnable runnable) { 149 | serviceConnection.runOnMainThread(runnable); 150 | } 151 | 152 | /** 153 | * Called right after {@link #startReceivingNotifications()} method is 154 | * called. Override this method to perform additional actions before the 155 | * client starts receiving notifications. 156 | */ 157 | protected void onStartReceivingNotifications() { 158 | // no op 159 | } 160 | 161 | /** 162 | * Called right after {@link #stopReceivingNotifications()} method is 163 | * called. Override this method to perform additional actions right after 164 | * the device stops receiving notifications. 165 | */ 166 | protected void onStopReceivingNotifications() { 167 | // no op 168 | } 169 | 170 | /** 171 | * Called when {@link Command} is about to be sent. Override this method to 172 | * perform additional actions before a command is sent. 173 | * 174 | * @param command 175 | * {@link Command} object. 176 | */ 177 | protected void onStartSendingCommand(Command command) { 178 | // no op 179 | } 180 | 181 | /** 182 | * Called when {@link Command} has been sent to the device. Override this 183 | * method to perform additional actions after a command is sent to the 184 | * device. 185 | * 186 | * @param command 187 | * {@link Command} object. 188 | */ 189 | protected void onFinishSendingCommand(Command command) { 190 | // no op 191 | } 192 | 193 | /** 194 | * Called when client failed to send command to the device. Override this 195 | * method to perform any extra actions. 196 | * 197 | * @param command 198 | * {@link Command} object. 199 | */ 200 | protected void onFailSendingCommand(Command command) { 201 | // no op 202 | } 203 | 204 | /** 205 | * Called when device client finishes reloading device data from the server. 206 | * 207 | * @param deviceData 208 | * {@link DeviceData} instance returned by the server. 209 | */ 210 | protected void onFinishReloadingDeviceData(DeviceData deviceData) { 211 | // no op 212 | } 213 | 214 | /** 215 | * Called when device client fails to reload device data from the server. 216 | */ 217 | protected void onFailReloadingDeviceData() { 218 | // no op 219 | } 220 | 221 | /** 222 | * Check whether given notification should be handled asynchronously. If so 223 | * {@link #onReceiveNotification(Notification)} method is called on some 224 | * other, not UI thread. 225 | * 226 | * @param notification 227 | * {@link Notification} instance. 228 | * @return true, if given notification should be handled asynchronously, 229 | * otherwise return false. 230 | */ 231 | protected abstract boolean shouldReceiveNotificationAsynchronously( 232 | final Notification notification); 233 | 234 | /* package */void onReloadDeviceDataFinishedInternal(DeviceData deviceData) { 235 | onFinishReloadingDeviceData(deviceData); 236 | } 237 | 238 | /* package */void onReloadDeviceDataFailedInternal() { 239 | onFailReloadingDeviceData(); 240 | } 241 | 242 | /* package */void setServiceConnection( 243 | ClientServiceConnection serviceConnection) { 244 | this.serviceConnection = serviceConnection; 245 | this.serviceConnection.setClient(this); 246 | } 247 | } 248 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/src/com/dataart/android/devicehive/client/MultipleDeviceClient.java: -------------------------------------------------------------------------------- 1 | package com.dataart.android.devicehive.client; 2 | 3 | import java.util.LinkedList; 4 | import java.util.List; 5 | 6 | import android.content.Context; 7 | 8 | import com.dataart.android.devicehive.Command; 9 | import com.dataart.android.devicehive.DeviceData; 10 | import com.dataart.android.devicehive.Notification; 11 | import com.dataart.android.devicehive.client.commands.NotificationsRetrivalCommand; 12 | import com.dataart.android.devicehive.client.commands.PollMultipleDeviceNotificationsCommand; 13 | import com.dataart.android.devicehive.client.commands.PollMultipleDeviceNotificationsCommand.DeviceNotification; 14 | 15 | /** 16 | * Represents a device client which provides high-level API for communication 17 | * and receive notifications from several devices. This class is abstract and 18 | * designed to be subclassed in order to handle incoming notifications. Also 19 | * this class provides a number of various callbacks: 20 | * {@link #onStartReceivingNotifications()}, 21 | * {@link #onStopReceivingNotifications()}, 22 | * {@link #onStartSendingCommand(Command)}, 23 | * {@link #onFinishSendingCommand(Command)}, 24 | * {@link #onFailSendingCommand(Command)}, etc. 25 | * 26 | */ 27 | public abstract class MultipleDeviceClient extends DeviceClient { 28 | 29 | private List devices; 30 | 31 | /** 32 | * Construct client with given {@link Context} and {@link DeviceData} 33 | * objects. 34 | * 35 | * @param context 36 | * {@link Context} object. In most cases this should be 37 | * application context which stays alive during the entire life 38 | * of an application. 39 | * @param deviceData 40 | * {@link DeviceData} object which describes device to 41 | * communicate with. 42 | */ 43 | public MultipleDeviceClient(Context context, final List devices) { 44 | super(context); 45 | this.devices = devices; 46 | setServiceConnection(new MultipleDeviceClientServiceConnection(context)); 47 | } 48 | 49 | private class MultipleDeviceClientServiceConnection extends 50 | ClientServiceConnection { 51 | 52 | public MultipleDeviceClientServiceConnection(Context context) { 53 | super(context); 54 | } 55 | 56 | @Override 57 | protected NotificationsRetrivalCommand getPollNotificationsCommand( 58 | String lastNotificationPollTimestamp, Integer waitTimeout) { 59 | return new PollMultipleDeviceNotificationsCommand(getDeviceGuids(), 60 | lastNotificationPollTimestamp, waitTimeout); 61 | } 62 | 63 | @Override 64 | protected void didReceiveNotification(Notification notification) { 65 | DeviceNotification deviceNotification = (DeviceNotification) notification; 66 | onReceiveNotification(deviceNotification.getDeviceGuid(), 67 | notification); 68 | } 69 | 70 | private List getDeviceGuids() { 71 | if (devices != null && !devices.isEmpty()) { 72 | final List guids = new LinkedList(); 73 | for (DeviceData device : devices) { 74 | guids.add(device.getId()); 75 | } 76 | return guids; 77 | } else { 78 | return null; 79 | } 80 | } 81 | } 82 | 83 | /** 84 | * Send command to the given device. 85 | * 86 | * @param device 87 | * Target device. 88 | * @param command 89 | * {@link Command} to be sent. 90 | */ 91 | public void sendCommand(DeviceData device, final Command command) { 92 | this.sendCommand(device, command); 93 | } 94 | 95 | /** 96 | * Reload device data. Current device data is updated with instance of 97 | * {@link DeviceData} retrieved from the server. 98 | * 99 | * @see #onFinishReloadingDeviceData(DeviceData) 100 | * @see #onFailReloadingDeviceData() 101 | */ 102 | public void reloadDeviceData(DeviceData device) { 103 | serviceConnection.reloadDeviceData(device); 104 | } 105 | 106 | /* package */void onReloadDeviceDataFinishedInternal(DeviceData deviceData) { 107 | final DeviceData device = getDeviceDataWithId(deviceData.getId()); 108 | devices.remove(device); 109 | devices.add(deviceData); 110 | onFinishReloadingDeviceData(deviceData); 111 | } 112 | 113 | private DeviceData getDeviceDataWithId(String deviceId) { 114 | for (DeviceData device : devices) { 115 | if (device.getId().equals(deviceId)) { 116 | return device; 117 | } 118 | } 119 | return null; 120 | } 121 | 122 | /** 123 | * Handle received notification. Can be called either on main (UI) thread or 124 | * some background thread depending on 125 | * {@link #shouldReceiveNotificationAsynchronously(Notification)} method 126 | * return value. 127 | * 128 | * @param notification 129 | * {@link Notification} instance to handle by the client. 130 | */ 131 | protected abstract void onReceiveNotification(String deviceId, 132 | final Notification notification); 133 | } 134 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/src/com/dataart/android/devicehive/client/SingleDeviceClient.java: -------------------------------------------------------------------------------- 1 | package com.dataart.android.devicehive.client; 2 | 3 | import android.content.Context; 4 | 5 | import com.dataart.android.devicehive.Command; 6 | import com.dataart.android.devicehive.DeviceData; 7 | import com.dataart.android.devicehive.Notification; 8 | import com.dataart.android.devicehive.client.commands.NotificationsRetrivalCommand; 9 | import com.dataart.android.devicehive.client.commands.PollDeviceNotificationsCommand; 10 | 11 | /** 12 | * Represents a single device client which provides high-level API for 13 | * communication with particular device. This class is abstract and designed to 14 | * be subclassed in order to handle incoming notifications. Also this class 15 | * provides a number of various callbacks: 16 | * {@link #onStartReceivingNotifications()}, 17 | * {@link #onStopReceivingNotifications()}, 18 | * {@link #onStartSendingCommand(Command)}, 19 | * {@link #onFinishSendingCommand(Command)}, 20 | * {@link #onFailSendingCommand(Command)}, etc. 21 | * 22 | */ 23 | public abstract class SingleDeviceClient extends DeviceClient { 24 | 25 | private DeviceData device; 26 | 27 | /** 28 | * Construct client with given {@link Context} and {@link DeviceData} 29 | * objects. 30 | * 31 | * @param context 32 | * {@link Context} object. In most cases this should be 33 | * application context which stays alive during the entire life 34 | * of an application. 35 | * @param deviceData 36 | * {@link DeviceData} object which describes device to 37 | * communicate with. 38 | */ 39 | public SingleDeviceClient(Context context, final DeviceData device) { 40 | super(context); 41 | this.device = device; 42 | setServiceConnection(new SingleDeviceClientServiceConnection(context)); 43 | } 44 | 45 | private class SingleDeviceClientServiceConnection extends 46 | ClientServiceConnection { 47 | 48 | public SingleDeviceClientServiceConnection(Context context) { 49 | super(context); 50 | } 51 | 52 | @Override 53 | protected NotificationsRetrivalCommand getPollNotificationsCommand( 54 | String lastNotificationPollTimestamp, Integer waitTimeout) { 55 | return new PollDeviceNotificationsCommand(device.getId(), 56 | lastNotificationPollTimestamp, waitTimeout); 57 | } 58 | 59 | @Override 60 | protected void didReceiveNotification(Notification notification) { 61 | onReceiveNotification(notification); 62 | } 63 | } 64 | 65 | /** 66 | * Get corresponding device. 67 | * 68 | * @return {@link DeviceData} object. 69 | */ 70 | public DeviceData getDevice() { 71 | return device; 72 | } 73 | 74 | /** 75 | * Send command to the device. 76 | * 77 | * @param command 78 | * {@link Command} to be sent. 79 | */ 80 | public void sendCommand(final Command command) { 81 | serviceConnection.sendCommand(device, command); 82 | } 83 | 84 | /** 85 | * Reload device data. Current device data is updated with instance of 86 | * {@link DeviceData} retrieved from the server. 87 | * 88 | * @see #onFinishReloadingDeviceData(DeviceData) 89 | * @see #onFailReloadingDeviceData() 90 | */ 91 | public void reloadDeviceData() { 92 | serviceConnection.reloadDeviceData(device); 93 | } 94 | 95 | /* package */void onReloadDeviceDataFinishedInternal(DeviceData deviceData) { 96 | this.device = deviceData; 97 | onFinishReloadingDeviceData(deviceData); 98 | } 99 | 100 | /** 101 | * Handle received notification. Can be called either on main (UI) thread or 102 | * some background thread depending on 103 | * {@link #shouldReceiveNotificationAsynchronously(Notification)} method 104 | * return value. 105 | * 106 | * @param notification 107 | * {@link Notification} instance to handle by the client. 108 | */ 109 | protected abstract void onReceiveNotification( 110 | final Notification notification); 111 | } 112 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/src/com/dataart/android/devicehive/client/commands/DeviceClientCommand.java: -------------------------------------------------------------------------------- 1 | package com.dataart.android.devicehive.client.commands; 2 | 3 | import android.os.Parcel; 4 | 5 | import com.dataart.android.devicehive.network.JsonNetworkCommand; 6 | 7 | /** 8 | * Base command for Device Hive device client commands. 9 | */ 10 | public abstract class DeviceClientCommand extends JsonNetworkCommand { 11 | 12 | @Override 13 | public int describeContents() { 14 | return 0; 15 | } 16 | 17 | @Override 18 | public void writeToParcel(Parcel dest, int flags) { 19 | 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/src/com/dataart/android/devicehive/client/commands/GetCommandCommand.java: -------------------------------------------------------------------------------- 1 | package com.dataart.android.devicehive.client.commands; 2 | 3 | import android.os.Bundle; 4 | import android.os.Parcel; 5 | import android.os.Parcelable; 6 | 7 | import com.dataart.android.devicehive.Command; 8 | import com.dataart.android.devicehive.network.DeviceHiveResultReceiver; 9 | import com.google.gson.Gson; 10 | 11 | /** 12 | * Get device command with given identifier. As a result returns {@link Command} 13 | * instance. 14 | */ 15 | public class GetCommandCommand extends DeviceClientCommand { 16 | 17 | private final static String NAMESPACE = GetCommandCommand.class.getName(); 18 | 19 | private static final String COMMAND_KEY = NAMESPACE.concat(".COMMAND_KEY"); 20 | 21 | private final String deviceId; 22 | private final int commandId; 23 | 24 | /** 25 | * Construct a new command. 26 | * 27 | * @param deviceId 28 | * Device unique identifier. 29 | * @param commandId 30 | * Command identifier. 31 | */ 32 | public GetCommandCommand(String deviceId, int commandId) { 33 | this.deviceId = deviceId; 34 | this.commandId = commandId; 35 | } 36 | 37 | @Override 38 | protected String toJson(Gson gson) { 39 | return null; 40 | } 41 | 42 | @Override 43 | protected RequestType getRequestType() { 44 | return RequestType.GET; 45 | } 46 | 47 | @Override 48 | protected String getRequestPath() { 49 | String requestPath = String.format("device/%s/command/%d", 50 | encodedString(deviceId), commandId); 51 | return requestPath; 52 | } 53 | 54 | public static Parcelable.Creator CREATOR = new Parcelable.Creator() { 55 | 56 | @Override 57 | public GetCommandCommand[] newArray(int size) { 58 | return new GetCommandCommand[size]; 59 | } 60 | 61 | @Override 62 | public GetCommandCommand createFromParcel(Parcel source) { 63 | return new GetCommandCommand(source.readString(), source.readInt()); 64 | } 65 | }; 66 | 67 | @Override 68 | public int describeContents() { 69 | return 0; 70 | } 71 | 72 | @Override 73 | public void writeToParcel(Parcel dest, int flags) { 74 | dest.writeString(deviceId); 75 | dest.writeInt(commandId); 76 | } 77 | 78 | @Override 79 | protected int fromJson(final String response, final Gson gson, 80 | final Bundle resultData) { 81 | 82 | final Command command = gson.fromJson(response, Command.class); 83 | resultData.putParcelable(COMMAND_KEY, command); 84 | return DeviceHiveResultReceiver.MSG_HANDLED_RESPONSE; 85 | } 86 | 87 | /** 88 | * Get {@link Command} object from response {@link Bundle} container. 89 | * 90 | * @param resultData 91 | * {@link Bundle} object containing required response data. 92 | * @return {@link Command} instance. 93 | */ 94 | public final static Command getDeviceCommand(Bundle resultData) { 95 | return resultData.getParcelable(COMMAND_KEY); 96 | } 97 | 98 | } 99 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/src/com/dataart/android/devicehive/client/commands/GetDeviceClassEquipmentCommand.java: -------------------------------------------------------------------------------- 1 | package com.dataart.android.devicehive.client.commands; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | import android.os.Bundle; 7 | import android.os.Parcel; 8 | import android.os.Parcelable; 9 | 10 | import com.dataart.android.devicehive.DeviceClass; 11 | import com.dataart.android.devicehive.EquipmentData; 12 | import com.dataart.android.devicehive.network.DeviceHiveResultReceiver; 13 | import com.google.gson.Gson; 14 | 15 | /** 16 | * Command which retrieves equipment for {@link DeviceClass}. As a result 17 | * returns list of {@link EquipmentData}. 18 | */ 19 | public class GetDeviceClassEquipmentCommand extends DeviceClientCommand { 20 | 21 | private final static String NAMESPACE = GetDeviceClassEquipmentCommand.class 22 | .getName(); 23 | 24 | private static final String DEVICE_CLASS_KEY = NAMESPACE 25 | .concat(".DEVICE_CLASS_KEY"); 26 | private static final String EQUIPMENT_KEY = NAMESPACE 27 | .concat(".EQUIPMENT_KEY"); 28 | 29 | private final int deviceClassId; 30 | 31 | /** 32 | * Construct a new command with given {@link DeviceClass}. 33 | * 34 | * @param deviceClassId 35 | * {@link DeviceClass} identifier. 36 | */ 37 | public GetDeviceClassEquipmentCommand(int deviceClassId) { 38 | this.deviceClassId = deviceClassId; 39 | } 40 | 41 | @Override 42 | protected RequestType getRequestType() { 43 | return RequestType.GET; 44 | } 45 | 46 | @Override 47 | protected String getRequestPath() { 48 | return String.format("device/class/%d", deviceClassId); 49 | } 50 | 51 | @Override 52 | protected String toJson(Gson gson) { 53 | return null; 54 | } 55 | 56 | private class DeviceClassEquipment extends DeviceClass { 57 | 58 | ArrayList equipment; 59 | 60 | DeviceClassEquipment(int id, String name, String version, 61 | boolean isPermanent, int offlineTimeout) { 62 | super(id, name, version, isPermanent, offlineTimeout); 63 | } 64 | 65 | } 66 | 67 | @Override 68 | public void writeToParcel(Parcel dest, int flags) { 69 | dest.writeInt(deviceClassId); 70 | } 71 | 72 | public static Parcelable.Creator CREATOR = new Parcelable.Creator() { 73 | 74 | @Override 75 | public GetDeviceClassEquipmentCommand[] newArray(int size) { 76 | return new GetDeviceClassEquipmentCommand[size]; 77 | } 78 | 79 | @Override 80 | public GetDeviceClassEquipmentCommand createFromParcel(Parcel source) { 81 | return new GetDeviceClassEquipmentCommand( 82 | source.readInt()); 83 | } 84 | }; 85 | 86 | @Override 87 | protected int fromJson(final String response, final Gson gson, 88 | final Bundle resultData) { 89 | 90 | final DeviceClassEquipment deviceClassEquipment = gson.fromJson( 91 | response, DeviceClassEquipment.class); 92 | resultData.putParcelable(DEVICE_CLASS_KEY, deviceClassEquipment); 93 | resultData.putParcelableArrayList(EQUIPMENT_KEY, 94 | deviceClassEquipment.equipment); 95 | return DeviceHiveResultReceiver.MSG_HANDLED_RESPONSE; 96 | } 97 | 98 | public final static DeviceClass getDeviceClass(Bundle resultData) { 99 | return resultData.getParcelable(DEVICE_CLASS_KEY); 100 | } 101 | 102 | /** 103 | * Get a list of {@link EquipmentData} which belong to target 104 | * {@link DeviceClass} object. 105 | * 106 | * @param resultData 107 | * {@link Bundle} object containing required response data. 108 | * @return A list of {@link EquipmentData} which belong to target 109 | * {@link DeviceClass} object. 110 | */ 111 | public final static List getEquipment(Bundle resultData) { 112 | return resultData.getParcelableArrayList(EQUIPMENT_KEY); 113 | } 114 | 115 | } 116 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/src/com/dataart/android/devicehive/client/commands/GetDeviceCommand.java: -------------------------------------------------------------------------------- 1 | package com.dataart.android.devicehive.client.commands; 2 | 3 | import android.os.Bundle; 4 | import android.os.Parcel; 5 | import android.os.Parcelable; 6 | 7 | import com.dataart.android.devicehive.DeviceData; 8 | import com.dataart.android.devicehive.network.DeviceHiveResultReceiver; 9 | import com.google.gson.Gson; 10 | 11 | /** 12 | * Get device object with given identifier. As a result returns 13 | * {@link DeviceData} instance. 14 | */ 15 | public class GetDeviceCommand extends DeviceClientCommand { 16 | 17 | private final static String NAMESPACE = GetDeviceCommand.class.getName(); 18 | 19 | private static final String DEVICE_KEY = NAMESPACE.concat(".DEVICE_KEY"); 20 | 21 | private final String deviceId; 22 | 23 | /** 24 | * Construct a new command. 25 | * 26 | * @param deviceId 27 | * Device unique identifier. 28 | */ 29 | public GetDeviceCommand(String deviceId) { 30 | this.deviceId = deviceId; 31 | } 32 | 33 | @Override 34 | protected String toJson(Gson gson) { 35 | return null; 36 | } 37 | 38 | @Override 39 | protected RequestType getRequestType() { 40 | return RequestType.GET; 41 | } 42 | 43 | @Override 44 | protected String getRequestPath() { 45 | String requestPath = String.format("/device/%s", 46 | encodedString(deviceId)); 47 | return requestPath; 48 | } 49 | 50 | public static Parcelable.Creator CREATOR = new Parcelable.Creator() { 51 | 52 | @Override 53 | public GetDeviceCommand[] newArray(int size) { 54 | return new GetDeviceCommand[size]; 55 | } 56 | 57 | @Override 58 | public GetDeviceCommand createFromParcel(Parcel source) { 59 | return new GetDeviceCommand(source.readString()); 60 | } 61 | }; 62 | 63 | @Override 64 | public int describeContents() { 65 | return 0; 66 | } 67 | 68 | @Override 69 | public void writeToParcel(Parcel dest, int flags) { 70 | dest.writeString(deviceId); 71 | } 72 | 73 | @Override 74 | protected int fromJson(final String response, final Gson gson, 75 | final Bundle resultData) { 76 | 77 | final DeviceData device = gson.fromJson(response, 78 | DeviceData.class); 79 | resultData.putParcelable(DEVICE_KEY, device); 80 | return DeviceHiveResultReceiver.MSG_HANDLED_RESPONSE; 81 | } 82 | 83 | /** 84 | * Get {@link DeviceData} object from response {@link Bundle} container. 85 | * 86 | * @param resultData 87 | * {@link Bundle} object containing required response data. 88 | * @return {@link DeviceData} instance. 89 | */ 90 | public final static DeviceData getDevice(Bundle resultData) { 91 | return resultData.getParcelable(DEVICE_KEY); 92 | } 93 | 94 | } 95 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/src/com/dataart/android/devicehive/client/commands/GetDeviceEquipmentStateCommand.java: -------------------------------------------------------------------------------- 1 | package com.dataart.android.devicehive.client.commands; 2 | 3 | import java.lang.reflect.Type; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | 7 | import android.os.Bundle; 8 | import android.os.Parcel; 9 | import android.os.Parcelable; 10 | 11 | import com.dataart.android.devicehive.DeviceData; 12 | import com.dataart.android.devicehive.EquipmentState; 13 | import com.dataart.android.devicehive.network.DeviceHiveResultReceiver; 14 | import com.google.gson.Gson; 15 | import com.google.gson.reflect.TypeToken; 16 | 17 | /** 18 | * Get state information for equipment of given {@link DeviceData}. As a result 19 | * returns list of {@link EquipmentState} objects. 20 | */ 21 | public class GetDeviceEquipmentStateCommand extends DeviceClientCommand { 22 | 23 | private final static String NAMESPACE = GetDeviceEquipmentStateCommand.class 24 | .getName(); 25 | 26 | private static final String DEVICE_KEY = NAMESPACE.concat(".DEVICE_KEY"); 27 | private static final String EQUIPMENT_STATE_KEY = NAMESPACE 28 | .concat(".EQUIPMENT_STATE_KEY"); 29 | 30 | private final String deviceId; 31 | 32 | /** 33 | * Construct a new command with given device identifier. 34 | * 35 | * @param deviceId 36 | * Device identifier. 37 | */ 38 | public GetDeviceEquipmentStateCommand(String deviceId) { 39 | this.deviceId = deviceId; 40 | } 41 | 42 | @Override 43 | protected RequestType getRequestType() { 44 | return RequestType.GET; 45 | } 46 | 47 | @Override 48 | protected String getRequestPath() { 49 | return String.format("device/%s/equipment", encodedString(deviceId)); 50 | } 51 | 52 | @Override 53 | protected String toJson(Gson gson) { 54 | return null; 55 | } 56 | 57 | @Override 58 | public void writeToParcel(Parcel dest, int flags) { 59 | dest.writeString(deviceId); 60 | } 61 | 62 | public static Parcelable.Creator CREATOR = new Parcelable.Creator() { 63 | 64 | @Override 65 | public GetDeviceEquipmentStateCommand[] newArray(int size) { 66 | return new GetDeviceEquipmentStateCommand[size]; 67 | } 68 | 69 | @Override 70 | public GetDeviceEquipmentStateCommand createFromParcel(Parcel source) { 71 | return new GetDeviceEquipmentStateCommand(source.readString()); 72 | } 73 | }; 74 | 75 | @Override 76 | protected int fromJson(final String response, final Gson gson, 77 | final Bundle resultData) { 78 | 79 | Type listType = new TypeToken>() { 80 | }.getType(); 81 | final ArrayList equipmentStates = gson.fromJson( 82 | response, listType); 83 | resultData.putString(DEVICE_KEY, deviceId); 84 | resultData.putParcelableArrayList(EQUIPMENT_STATE_KEY, equipmentStates); 85 | return DeviceHiveResultReceiver.MSG_HANDLED_RESPONSE; 86 | } 87 | 88 | /** 89 | * Get target device identifier. 90 | * 91 | * @param resultData 92 | * {@link Bundle} object containing required response data. 93 | * @return Device identifier. 94 | */ 95 | public final static String getDeviceId(Bundle resultData) { 96 | return resultData.getParcelable(DEVICE_KEY); 97 | } 98 | 99 | /** 100 | * Get a list of {@link EquipmentState} which determine current state of 101 | * device equipment. 102 | * 103 | * @param resultData 104 | * {@link Bundle} object containing required response data. 105 | * @return A list of {@link EquipmentState} which determine current state of 106 | * device equipment. 107 | */ 108 | public final static List getEquipmentState(Bundle resultData) { 109 | return resultData.getParcelableArrayList(EQUIPMENT_STATE_KEY); 110 | } 111 | 112 | } 113 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/src/com/dataart/android/devicehive/client/commands/GetDeviceNotificationsCommand.java: -------------------------------------------------------------------------------- 1 | package com.dataart.android.devicehive.client.commands; 2 | 3 | import android.os.Parcel; 4 | import android.os.Parcelable; 5 | 6 | import com.dataart.android.devicehive.Notification; 7 | 8 | /** 9 | * Get all device {@link Notification}s starting from given timestamp. This 10 | * request returns immediately regardless of whether there have been any 11 | * notifications since given timestamp or not. As a result returns list of 12 | * {@link Notification}. 13 | */ 14 | public class GetDeviceNotificationsCommand extends NotificationsRetrivalCommand { 15 | 16 | private final String deviceId; 17 | 18 | /** 19 | * Construct a new command. 20 | * 21 | * @param deviceId 22 | * Device identifier. 23 | * @param lastNotificationPollTimestamp 24 | * Timestamp which defines starting point in the past for 25 | * notifications. 26 | */ 27 | public GetDeviceNotificationsCommand(String deviceId, 28 | String lastNotificationPollTimestamp) { 29 | super(lastNotificationPollTimestamp); 30 | this.deviceId = deviceId; 31 | } 32 | 33 | @Override 34 | protected String getRequestPath() { 35 | String requestPath = String.format("device/%s/notification", 36 | encodedString(deviceId)); 37 | if (lastNotificationPollTimestamp != null) { 38 | requestPath += "?start=" 39 | + encodedString(lastNotificationPollTimestamp); 40 | } 41 | return requestPath; 42 | } 43 | 44 | @Override 45 | public void writeToParcel(Parcel dest, int flags) { 46 | dest.writeString(deviceId); 47 | super.writeToParcel(dest, flags); 48 | } 49 | 50 | public static Parcelable.Creator CREATOR = new Parcelable.Creator() { 51 | 52 | @Override 53 | public GetDeviceNotificationsCommand[] newArray(int size) { 54 | return new GetDeviceNotificationsCommand[size]; 55 | } 56 | 57 | @Override 58 | public GetDeviceNotificationsCommand createFromParcel(Parcel source) { 59 | return new GetDeviceNotificationsCommand(source.readString(), 60 | source.readString()); 61 | } 62 | }; 63 | } 64 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/src/com/dataart/android/devicehive/client/commands/GetDevicesCommand.java: -------------------------------------------------------------------------------- 1 | package com.dataart.android.devicehive.client.commands; 2 | 3 | import java.lang.reflect.Type; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | 7 | import android.os.Bundle; 8 | import android.os.Parcel; 9 | import android.os.Parcelable; 10 | 11 | import com.dataart.android.devicehive.DeviceData; 12 | import com.dataart.android.devicehive.network.DeviceHiveResultReceiver; 13 | import com.google.gson.Gson; 14 | import com.google.gson.reflect.TypeToken; 15 | 16 | /** 17 | * Get all existing devices. As a result returns a list of {@link DeviceData}. 18 | * Can be executed only by users with administrative privileges. 19 | * 20 | */ 21 | public class GetDevicesCommand extends DeviceClientCommand { 22 | 23 | private final static String NAMESPACE = GetDevicesCommand.class.getName(); 24 | 25 | private static final String DEVICES_KEY = NAMESPACE.concat(".DEVICES_KEY"); 26 | 27 | /** 28 | * Create a new command. 29 | */ 30 | public GetDevicesCommand() { 31 | super(); 32 | } 33 | 34 | @Override 35 | protected RequestType getRequestType() { 36 | return RequestType.GET; 37 | } 38 | 39 | @Override 40 | protected String getRequestPath() { 41 | return "device"; 42 | } 43 | 44 | public static Parcelable.Creator CREATOR = new Parcelable.Creator() { 45 | 46 | @Override 47 | public GetDevicesCommand[] newArray(int size) { 48 | return new GetDevicesCommand[size]; 49 | } 50 | 51 | @Override 52 | public GetDevicesCommand createFromParcel(Parcel source) { 53 | return new GetDevicesCommand(); 54 | } 55 | }; 56 | 57 | @Override 58 | protected int fromJson(final String response, final Gson gson, 59 | final Bundle resultData) { 60 | 61 | Type listType = new TypeToken>() { 62 | }.getType(); 63 | final ArrayList devices = gson.fromJson(response, 64 | listType); 65 | resultData.putParcelableArrayList(DEVICES_KEY, devices); 66 | return DeviceHiveResultReceiver.MSG_HANDLED_RESPONSE; 67 | } 68 | 69 | /** 70 | * Get a list of all existing devices from response {@link Bundle} 71 | * container. 72 | * 73 | * @param resultData 74 | * {@link Bundle} object containing required response data. 75 | * @return A list of {@link DeviceData}. 76 | */ 77 | public final static List getDevices(Bundle resultData) { 78 | return resultData.getParcelableArrayList(DEVICES_KEY); 79 | } 80 | 81 | @Override 82 | protected String toJson(Gson gson) { 83 | return null; 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/src/com/dataart/android/devicehive/client/commands/GetNetworkDevicesCommand.java: -------------------------------------------------------------------------------- 1 | package com.dataart.android.devicehive.client.commands; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | import android.os.Bundle; 7 | import android.os.Parcel; 8 | import android.os.Parcelable; 9 | 10 | import com.dataart.android.devicehive.DeviceData; 11 | import com.dataart.android.devicehive.Network; 12 | import com.dataart.android.devicehive.network.DeviceHiveResultReceiver; 13 | import com.google.gson.Gson; 14 | 15 | /** 16 | * Get all devices which belong to given network. As a result returns a list of 17 | * {@link DeviceData} objects. 18 | * 19 | */ 20 | public class GetNetworkDevicesCommand extends DeviceClientCommand { 21 | 22 | private final static String NAMESPACE = GetNetworkDevicesCommand.class 23 | .getName(); 24 | 25 | private static final String NETWORK_KEY = NAMESPACE.concat(".NETWORK_KEY"); 26 | private static final String DEVICES_KEY = NAMESPACE.concat(".DEVICES_KEY"); 27 | 28 | private final int networkId; 29 | 30 | /** 31 | * Construct a new command with given {@link Network} identifier. 32 | * 33 | * @param networkId 34 | * {@link Network} identifier. 35 | */ 36 | public GetNetworkDevicesCommand(int networkId) { 37 | this.networkId = networkId; 38 | } 39 | 40 | @Override 41 | protected RequestType getRequestType() { 42 | return RequestType.GET; 43 | } 44 | 45 | @Override 46 | protected String getRequestPath() { 47 | return String.format("network/%d", networkId); 48 | } 49 | 50 | @Override 51 | protected String toJson(Gson gson) { 52 | return null; 53 | } 54 | 55 | @Override 56 | public void writeToParcel(Parcel dest, int flags) { 57 | dest.writeInt(networkId); 58 | } 59 | 60 | public static Parcelable.Creator CREATOR = new Parcelable.Creator() { 61 | 62 | @Override 63 | public GetNetworkDevicesCommand[] newArray(int size) { 64 | return new GetNetworkDevicesCommand[size]; 65 | } 66 | 67 | @Override 68 | public GetNetworkDevicesCommand createFromParcel(Parcel source) { 69 | return new GetNetworkDevicesCommand(source.readInt()); 70 | } 71 | }; 72 | 73 | private class NetworkExtended extends Network { 74 | 75 | ArrayList devices; 76 | 77 | NetworkExtended(int id, String key, String name, String description) { 78 | super(id, key, name, description); 79 | } 80 | 81 | } 82 | 83 | @Override 84 | protected int fromJson(final String response, final Gson gson, 85 | final Bundle resultData) { 86 | 87 | final NetworkExtended networkExtended = gson.fromJson(response, 88 | NetworkExtended.class); 89 | resultData.putParcelable(NETWORK_KEY, networkExtended); 90 | resultData.putParcelableArrayList(DEVICES_KEY, networkExtended.devices); 91 | return DeviceHiveResultReceiver.MSG_HANDLED_RESPONSE; 92 | } 93 | 94 | /** 95 | * Get target {@link Network} object. 96 | * 97 | * @param resultData 98 | * {@link Bundle} object containing required response data. 99 | * @return {@link Network} instance. 100 | */ 101 | public final static Network getNetwork(Bundle resultData) { 102 | return resultData.getParcelable(NETWORK_KEY); 103 | } 104 | 105 | /** 106 | * Get a list of {@link DeviceData} which belong to target {@link Network} 107 | * object. 108 | * 109 | * @param resultData 110 | * {@link Bundle} object containing required response data. 111 | * @return A list of {@link DeviceData} which belong to target 112 | * {@link Network} object. 113 | */ 114 | public final static List getNetworkDevices(Bundle resultData) { 115 | return resultData.getParcelableArrayList(DEVICES_KEY); 116 | } 117 | 118 | } 119 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/src/com/dataart/android/devicehive/client/commands/GetNetworksCommand.java: -------------------------------------------------------------------------------- 1 | package com.dataart.android.devicehive.client.commands; 2 | 3 | import java.lang.reflect.Type; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | 7 | import android.os.Bundle; 8 | import android.os.Parcel; 9 | import android.os.Parcelable; 10 | 11 | import com.dataart.android.devicehive.Network; 12 | import com.dataart.android.devicehive.network.DeviceHiveResultReceiver; 13 | import com.google.gson.Gson; 14 | import com.google.gson.reflect.TypeToken; 15 | 16 | /** 17 | * Get a list of {@link Network} available for current user. 18 | * 19 | */ 20 | public class GetNetworksCommand extends DeviceClientCommand { 21 | 22 | private final static String NAMESPACE = GetNetworksCommand.class.getName(); 23 | 24 | private static final String NETWORKS_KEY = NAMESPACE 25 | .concat(".NETWORKS_KEY"); 26 | 27 | public GetNetworksCommand() { 28 | super(); 29 | } 30 | 31 | @Override 32 | protected RequestType getRequestType() { 33 | return RequestType.GET; 34 | } 35 | 36 | @Override 37 | protected String getRequestPath() { 38 | return "network"; 39 | } 40 | 41 | public static Parcelable.Creator CREATOR = new Parcelable.Creator() { 42 | 43 | @Override 44 | public GetNetworksCommand[] newArray(int size) { 45 | return new GetNetworksCommand[size]; 46 | } 47 | 48 | @Override 49 | public GetNetworksCommand createFromParcel(Parcel source) { 50 | return new GetNetworksCommand(); 51 | } 52 | }; 53 | 54 | @Override 55 | protected int fromJson(final String response, final Gson gson, 56 | final Bundle resultData) { 57 | Type listType = new TypeToken>() { 58 | }.getType(); 59 | final ArrayList networks = gson.fromJson(response, 60 | listType); 61 | resultData.putParcelableArrayList(NETWORKS_KEY, networks); 62 | return DeviceHiveResultReceiver.MSG_HANDLED_RESPONSE; 63 | } 64 | 65 | /** 66 | * Get a list of {@link Network} available for current user. 67 | * 68 | * @param resultData 69 | * {@link Bundle} object containing required response data. 70 | * @return A list of {@link Network} available for current user. 71 | */ 72 | public final static List getNetworks(Bundle resultData) { 73 | return resultData.getParcelableArrayList(NETWORKS_KEY); 74 | } 75 | 76 | @Override 77 | protected String toJson(Gson gson) { 78 | return null; 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/src/com/dataart/android/devicehive/client/commands/NotificationsRetrivalCommand.java: -------------------------------------------------------------------------------- 1 | package com.dataart.android.devicehive.client.commands; 2 | 3 | import java.lang.reflect.Type; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | 7 | import android.os.Bundle; 8 | import android.os.Parcel; 9 | 10 | import com.dataart.android.devicehive.DeviceData; 11 | import com.dataart.android.devicehive.Notification; 12 | import com.dataart.android.devicehive.network.DeviceHiveResultReceiver; 13 | import com.google.gson.Gson; 14 | import com.google.gson.reflect.TypeToken; 15 | 16 | /** 17 | * Abstract base class for commands which retrieve notifications for given 18 | * device. 19 | * 20 | */ 21 | public abstract class NotificationsRetrivalCommand extends DeviceClientCommand { 22 | 23 | private final static String NAMESPACE = NotificationsRetrivalCommand.class 24 | .getName(); 25 | 26 | protected static final String NOTIFICATIONS_KEY = NAMESPACE 27 | .concat(".NOTIFICATIONS_KEY"); 28 | 29 | protected final String lastNotificationPollTimestamp; 30 | 31 | /** 32 | * Construct command for given device and last received notification 33 | * timestamp. 34 | * 35 | * @param deviceData 36 | * {@link DeviceData} instance. 37 | * @param lastNotificationPollTimestamp 38 | * Last received notification timestamp. 39 | */ 40 | public NotificationsRetrivalCommand(String lastNotificationPollTimestamp) { 41 | this.lastNotificationPollTimestamp = lastNotificationPollTimestamp; 42 | } 43 | 44 | @Override 45 | protected RequestType getRequestType() { 46 | return RequestType.GET; 47 | } 48 | 49 | @Override 50 | public void writeToParcel(Parcel dest, int flags) { 51 | dest.writeString(lastNotificationPollTimestamp); 52 | } 53 | 54 | @Override 55 | protected String toJson(Gson gson) { 56 | return null; 57 | } 58 | 59 | @Override 60 | protected int fromJson(String response, Gson gson, Bundle resultData) { 61 | Type listType = new TypeToken>() { 62 | }.getType(); 63 | 64 | ArrayList notifications = gson.fromJson(response, 65 | listType); 66 | resultData.putParcelableArrayList(NOTIFICATIONS_KEY, notifications); 67 | return DeviceHiveResultReceiver.MSG_HANDLED_RESPONSE; 68 | } 69 | 70 | /** 71 | * Get a list of {@link Notification} sent from given {@link DeviceData} 72 | * object. 73 | * 74 | * @param resultData 75 | * {@link Bundle} object containing required response data. 76 | * @return A list of {@link Notification} sent from given {@link DeviceData} 77 | * . 78 | */ 79 | public final static List getNotifications(Bundle resultData) { 80 | return resultData.getParcelableArrayList(NOTIFICATIONS_KEY); 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/src/com/dataart/android/devicehive/client/commands/PollDeviceNotificationsCommand.java: -------------------------------------------------------------------------------- 1 | package com.dataart.android.devicehive.client.commands; 2 | 3 | import android.os.Parcel; 4 | import android.os.Parcelable; 5 | 6 | import com.dataart.android.devicehive.Notification; 7 | 8 | /** 9 | * Get all existing device {@link Notification}s starting from given timestamp. 10 | * This request returns immediately if there have been any notifications since 11 | * given timestamp. In the case when no notifications were found, the method 12 | * blocks until new notification is received. The blocking period is limited 13 | * (currently 30 seconds). As a result returns list of {@link Notification}. 14 | */ 15 | public class PollDeviceNotificationsCommand extends PollNotificationsCommand { 16 | 17 | private final String deviceId; 18 | 19 | /** 20 | * Construct a new command. 21 | * 22 | * @param deviceId 23 | * Device identifier. 24 | * @param lastNotificationPollTimestamp 25 | * Timestamp which defines starting point in the past for 26 | * notifications. 27 | */ 28 | public PollDeviceNotificationsCommand(String deviceId, 29 | String lastNotificationPollTimestamp) { 30 | this(deviceId, lastNotificationPollTimestamp, null); 31 | } 32 | 33 | /** 34 | * Construct a new command. 35 | * 36 | * @param deviceId 37 | * Device identifier. 38 | * @param lastNotificationPollTimestamp 39 | * Timestamp which defines starting point in the past for 40 | * notifications. 41 | * @param waitTimeout 42 | * Waiting timeout in seconds. 43 | */ 44 | public PollDeviceNotificationsCommand(String deviceId, 45 | String lastNotificationPollTimestamp, Integer waitTimeout) { 46 | super(lastNotificationPollTimestamp, waitTimeout); 47 | this.deviceId = deviceId; 48 | } 49 | 50 | @Override 51 | protected String getRequestPath() { 52 | String requestPath = String.format("device/%s/notification/poll", 53 | encodedString(deviceId)); 54 | if (lastNotificationPollTimestamp != null) { 55 | requestPath += "?timestamp=" 56 | + encodedString(lastNotificationPollTimestamp); 57 | } 58 | if (waitTimeout != null) { 59 | requestPath += lastNotificationPollTimestamp != null ? "&" : "?"; 60 | requestPath += "waitTimeout=" + waitTimeout; 61 | } 62 | return requestPath; 63 | } 64 | 65 | public static Parcelable.Creator CREATOR = new Parcelable.Creator() { 66 | 67 | @Override 68 | public PollDeviceNotificationsCommand[] newArray(int size) { 69 | return new PollDeviceNotificationsCommand[size]; 70 | } 71 | 72 | @Override 73 | public PollDeviceNotificationsCommand createFromParcel(Parcel source) { 74 | return new PollDeviceNotificationsCommand(source.readString(), 75 | source.readString(), 76 | (Integer) source.readValue(CLASS_LOADER)); 77 | } 78 | }; 79 | 80 | @Override 81 | public void writeToParcel(Parcel dest, int flags) { 82 | dest.writeString(deviceId); 83 | super.writeToParcel(dest, flags); 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/src/com/dataart/android/devicehive/client/commands/PollMultipleDeviceNotificationsCommand.java: -------------------------------------------------------------------------------- 1 | package com.dataart.android.devicehive.client.commands; 2 | 3 | import java.io.Serializable; 4 | import java.lang.reflect.Type; 5 | import java.util.ArrayList; 6 | import java.util.LinkedList; 7 | import java.util.List; 8 | 9 | import android.os.Bundle; 10 | import android.os.Parcel; 11 | import android.os.Parcelable; 12 | 13 | import com.dataart.android.devicehive.Notification; 14 | import com.dataart.android.devicehive.network.DeviceHiveResultReceiver; 15 | import com.google.gson.Gson; 16 | import com.google.gson.reflect.TypeToken; 17 | 18 | /** 19 | * Poll {@link Notification}s from given devices starting from given timestamp. 20 | * This request returns immediately if there have been any notifications since 21 | * given timestamp. In the case when no notifications were found, the method 22 | * blocks until new notification is received. The blocking period is limited 23 | * (currently 30 seconds). As a result returns list of {@link Notification}. 24 | */ 25 | public class PollMultipleDeviceNotificationsCommand extends 26 | PollNotificationsCommand { 27 | 28 | protected final List deviceIds; 29 | 30 | /** 31 | * Construct command for given device and last received notification 32 | * timestamp. 33 | * 34 | * @param deviceIds 35 | * List of device identifiers. 36 | * @param lastNotificationPollTimestamp 37 | * Last received notification timestamp. 38 | */ 39 | public PollMultipleDeviceNotificationsCommand(List deviceIds, 40 | String lastNotificationPollTimestamp) { 41 | this(deviceIds, lastNotificationPollTimestamp, null); 42 | } 43 | 44 | /** 45 | * Construct a new command. 46 | * 47 | * @param deviceIds 48 | * List of device identifiers. 49 | * @param lastNotificationPollTimestamp 50 | * Timestamp which defines starting point in the past for 51 | * notifications. 52 | * @param waitTimeout 53 | * Waiting timeout in seconds. 54 | */ 55 | public PollMultipleDeviceNotificationsCommand(List deviceIds, 56 | String lastNotificationPollTimestamp, Integer waitTimeout) { 57 | super(lastNotificationPollTimestamp, waitTimeout); 58 | this.deviceIds = deviceIds; 59 | } 60 | 61 | @Override 62 | public void writeToParcel(Parcel dest, int flags) { 63 | dest.writeStringList(deviceIds); 64 | super.writeToParcel(dest, flags); 65 | } 66 | 67 | public static Parcelable.Creator CREATOR = new Parcelable.Creator() { 68 | 69 | @Override 70 | public PollMultipleDeviceNotificationsCommand[] newArray(int size) { 71 | return new PollMultipleDeviceNotificationsCommand[size]; 72 | } 73 | 74 | @Override 75 | public PollMultipleDeviceNotificationsCommand createFromParcel( 76 | Parcel source) { 77 | List deviceIds = new LinkedList(); 78 | source.readStringList(deviceIds); 79 | return new PollMultipleDeviceNotificationsCommand(deviceIds, 80 | source.readString(), 81 | (Integer) source.readValue(CLASS_LOADER)); 82 | } 83 | }; 84 | 85 | @Override 86 | protected String getRequestPath() { 87 | String requestPath = "device/notification/poll"; 88 | if (isDeviceGuidsPresent()) { 89 | requestPath += String.format("?deviceGuids=%s", 90 | prepareGuidsString(deviceIds)); 91 | } 92 | if (lastNotificationPollTimestamp != null) { 93 | requestPath += isDeviceGuidsPresent() ? "&" : "?"; 94 | requestPath += "timestamp=" 95 | + encodedString(lastNotificationPollTimestamp); 96 | } 97 | if (waitTimeout != null) { 98 | requestPath += (isDeviceGuidsPresent() || lastNotificationPollTimestamp != null) ? "&" 99 | : "?"; 100 | requestPath += "waitTimeout=" + waitTimeout; 101 | } 102 | return requestPath; 103 | } 104 | 105 | private boolean isDeviceGuidsPresent() { 106 | return deviceIds != null && !deviceIds.isEmpty(); 107 | } 108 | 109 | private String prepareGuidsString(List guids) { 110 | if (deviceIds == null || deviceIds.isEmpty()) { 111 | return null; 112 | } else { 113 | final StringBuilder builder = new StringBuilder(""); 114 | String separator = ""; 115 | for (String guid : guids) { 116 | builder.append(separator).append(guid); 117 | separator = ","; 118 | } 119 | return builder.toString(); 120 | } 121 | } 122 | 123 | public static class DeviceNotification extends Notification { 124 | 125 | private String deviceGuid; 126 | 127 | public String getDeviceGuid() { 128 | return deviceGuid; 129 | } 130 | 131 | /* package */DeviceNotification(int id, String name, String timestamp, 132 | Serializable parameters) { 133 | super(id, name, timestamp, parameters); 134 | } 135 | 136 | /* package */DeviceNotification(String deviceGuid, 137 | Notification notification) { 138 | super(notification.getId(), notification.getName(), notification 139 | .getTimestamp(), notification.getParameters()); 140 | this.deviceGuid = deviceGuid; 141 | } 142 | } 143 | 144 | private static class DeviceGuidNotification { 145 | String deviceGuid; 146 | Notification notification; 147 | } 148 | 149 | @Override 150 | protected int fromJson(final String response, final Gson gson, 151 | final Bundle resultData) { 152 | 153 | Type listType = new TypeToken>() { 154 | }.getType(); 155 | 156 | ArrayList notifications = gson.fromJson( 157 | response, listType); 158 | resultData.putParcelableArrayList(NOTIFICATIONS_KEY, 159 | asDeviceNotificationList(notifications)); 160 | return DeviceHiveResultReceiver.MSG_HANDLED_RESPONSE; 161 | } 162 | 163 | private static ArrayList asDeviceNotificationList( 164 | List notifications) { 165 | ArrayList result = new ArrayList( 166 | notifications.size()); 167 | for (DeviceGuidNotification guidNotification : notifications) { 168 | result.add(new DeviceNotification(guidNotification.deviceGuid, 169 | guidNotification.notification)); 170 | } 171 | return result; 172 | } 173 | } 174 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/src/com/dataart/android/devicehive/client/commands/PollNotificationsCommand.java: -------------------------------------------------------------------------------- 1 | package com.dataart.android.devicehive.client.commands; 2 | 3 | import android.os.Parcel; 4 | 5 | import com.google.gson.Gson; 6 | 7 | /** 8 | * Abstract base class for commands which poll notifications for given device. 9 | * 10 | */ 11 | public abstract class PollNotificationsCommand extends 12 | NotificationsRetrivalCommand { 13 | 14 | protected final Integer waitTimeout; 15 | 16 | /** 17 | * Construct a new command with last received notification timestamp. 18 | * 19 | * @param lastNotificationPollTimestamp 20 | * Last received notification timestamp. 21 | */ 22 | public PollNotificationsCommand(String lastNotificationPollTimestamp) { 23 | this(lastNotificationPollTimestamp, null); 24 | } 25 | 26 | /** 27 | * Construct a new command with last received notification timestamp and 28 | * wait timeout. 29 | * 30 | * @param lastNotificationPollTimestamp 31 | * Last received notification timestamp. 32 | * @param waitTimeout 33 | * Waiting timeout in seconds. 34 | */ 35 | public PollNotificationsCommand(String lastNotificationPollTimestamp, 36 | Integer waitTimeout) { 37 | super(lastNotificationPollTimestamp); 38 | this.waitTimeout = waitTimeout; 39 | } 40 | 41 | @Override 42 | protected RequestType getRequestType() { 43 | return RequestType.GET; 44 | } 45 | 46 | @Override 47 | public void writeToParcel(Parcel dest, int flags) { 48 | super.writeToParcel(dest, flags); 49 | dest.writeValue(waitTimeout); 50 | } 51 | 52 | @Override 53 | protected String toJson(Gson gson) { 54 | return null; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/src/com/dataart/android/devicehive/client/commands/SendDeviceCommandCommand.java: -------------------------------------------------------------------------------- 1 | package com.dataart.android.devicehive.client.commands; 2 | 3 | import android.os.Bundle; 4 | import android.os.Parcel; 5 | import android.os.Parcelable; 6 | 7 | import com.dataart.android.devicehive.Command; 8 | import com.dataart.android.devicehive.Notification; 9 | import com.dataart.android.devicehive.network.DeviceHiveResultReceiver; 10 | import com.google.gson.Gson; 11 | 12 | /** 13 | * Send a new command to the given device. As a result returns {@link Command} 14 | * instance from the server response. 15 | * 16 | */ 17 | public class SendDeviceCommandCommand extends DeviceClientCommand { 18 | 19 | private final static String NAMESPACE = SendDeviceCommandCommand.class 20 | .getName(); 21 | 22 | private static final String COMMAND_KEY = NAMESPACE.concat(".COMMAND_KEY"); 23 | 24 | private final String deviceId; 25 | private final Command command; 26 | 27 | /** 28 | * Construct a new command with given device identifier and {@link Command} 29 | * instance. 30 | * 31 | * @param deviceId 32 | * Device unique identifier. 33 | * @param command 34 | * {@link Command} instance. 35 | * @param notification 36 | * {@link Notification} to be sent on behalf of given device. 37 | */ 38 | public SendDeviceCommandCommand(String deviceId, Command command) { 39 | this.deviceId = deviceId; 40 | this.command = command; 41 | } 42 | 43 | /** 44 | * Get {@link Command} to be sent. 45 | * 46 | * @return {@link Command} instance. 47 | */ 48 | public Command getCommand() { 49 | return command; 50 | } 51 | 52 | @Override 53 | protected RequestType getRequestType() { 54 | return RequestType.POST; 55 | } 56 | 57 | @Override 58 | protected String getRequestPath() { 59 | return String.format("device/%s/command", encodedString(deviceId)); 60 | } 61 | 62 | @Override 63 | public void writeToParcel(Parcel dest, int flags) { 64 | super.writeToParcel(dest, flags); 65 | dest.writeString(deviceId); 66 | dest.writeParcelable(command, 0); 67 | } 68 | 69 | public static Parcelable.Creator CREATOR = new Parcelable.Creator() { 70 | 71 | @Override 72 | public SendDeviceCommandCommand[] newArray(int size) { 73 | return new SendDeviceCommandCommand[size]; 74 | } 75 | 76 | @Override 77 | public SendDeviceCommandCommand createFromParcel(Parcel source) { 78 | return new SendDeviceCommandCommand(source.readString(), 79 | (Command) source.readParcelable(CLASS_LOADER)); 80 | } 81 | }; 82 | 83 | @Override 84 | protected String toJson(Gson gson) { 85 | return gson.toJson(command); 86 | } 87 | 88 | @Override 89 | protected int fromJson(final String response, final Gson gson, 90 | final Bundle resultData) { 91 | final Command command = gson.fromJson(response, Command.class); 92 | resultData.putParcelable(COMMAND_KEY, command); 93 | return DeviceHiveResultReceiver.MSG_HANDLED_RESPONSE; 94 | } 95 | 96 | /** 97 | * Get sent {@link Command} instance returned by the server. 98 | * 99 | * @param resultData 100 | * {@link Bundle} object containing required response data. 101 | * @return {@link Command} instance returned by the server. 102 | */ 103 | public final static Command getSentCommand(Bundle resultData) { 104 | return resultData.getParcelable(COMMAND_KEY); 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/src/com/dataart/android/devicehive/commands/GetApiInfoCommand.java: -------------------------------------------------------------------------------- 1 | package com.dataart.android.devicehive.commands; 2 | 3 | import android.os.Bundle; 4 | import android.os.Parcel; 5 | import android.os.Parcelable; 6 | 7 | import com.dataart.android.devicehive.ApiInfo; 8 | import com.dataart.android.devicehive.network.DeviceHiveResultReceiver; 9 | import com.dataart.android.devicehive.network.JsonNetworkCommand; 10 | import com.google.gson.Gson; 11 | 12 | /** 13 | * Gets meta-information of the current API. As a result returns {@link ApiInfo} 14 | * instance. 15 | */ 16 | public class GetApiInfoCommand extends JsonNetworkCommand { 17 | 18 | private final static String NAMESPACE = GetApiInfoCommand.class.getName(); 19 | 20 | private static final String API_INFO_KEY = NAMESPACE 21 | .concat(".API_INFO_KEY"); 22 | 23 | /** 24 | * Construct a new command. 25 | */ 26 | public GetApiInfoCommand() { 27 | 28 | } 29 | 30 | @Override 31 | protected String toJson(Gson gson) { 32 | return null; 33 | } 34 | 35 | @Override 36 | protected RequestType getRequestType() { 37 | return RequestType.GET; 38 | } 39 | 40 | @Override 41 | protected String getRequestPath() { 42 | return "info"; 43 | } 44 | 45 | public static Parcelable.Creator CREATOR = new Parcelable.Creator() { 46 | 47 | @Override 48 | public GetApiInfoCommand[] newArray(int size) { 49 | return new GetApiInfoCommand[size]; 50 | } 51 | 52 | @Override 53 | public GetApiInfoCommand createFromParcel(Parcel source) { 54 | return new GetApiInfoCommand(); 55 | } 56 | }; 57 | 58 | @Override 59 | public int describeContents() { 60 | return 0; 61 | } 62 | 63 | @Override 64 | public void writeToParcel(Parcel dest, int flags) { 65 | 66 | } 67 | 68 | @Override 69 | protected int fromJson(final String response, final Gson gson, 70 | final Bundle resultData) { 71 | 72 | final ApiInfo apiInfo = gson.fromJson(response, ApiInfo.class); 73 | resultData.putParcelable(API_INFO_KEY, apiInfo); 74 | return DeviceHiveResultReceiver.MSG_HANDLED_RESPONSE; 75 | } 76 | 77 | /** 78 | * Get {@link ApiInfo} object from response {@link Bundle} container. 79 | * 80 | * @param resultData 81 | * {@link Bundle} object containing required response data. 82 | * @return {@link ApiInfo} instance. 83 | */ 84 | public final static ApiInfo getApiInfo(Bundle resultData) { 85 | return resultData.getParcelable(API_INFO_KEY); 86 | } 87 | 88 | } 89 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/src/com/dataart/android/devicehive/device/CommandResult.java: -------------------------------------------------------------------------------- 1 | package com.dataart.android.devicehive.device; 2 | 3 | import java.io.Serializable; 4 | 5 | import com.dataart.android.devicehive.ObjectWrapper; 6 | 7 | import android.os.Parcel; 8 | import android.os.Parcelable; 9 | 10 | /** 11 | * Command execution result which is reported to the server. 12 | */ 13 | public class CommandResult implements Parcelable { 14 | 15 | /** 16 | * Command status "Completed" value. 17 | */ 18 | public static final String STATUS_COMLETED = "Completed"; 19 | 20 | /** 21 | * Command status "Failed" value. 22 | */ 23 | public static final String STATUS_FAILED = "Failed"; 24 | 25 | private final String status; 26 | private final ObjectWrapper result; 27 | 28 | /** 29 | * Constructs command result with given status and result. 30 | * 31 | * @param status 32 | * Command status. 33 | * @param result 34 | * Command execution result. 35 | */ 36 | public CommandResult(String status, Serializable result) { 37 | this.status = status; 38 | this.result = new ObjectWrapper(result); 39 | } 40 | 41 | /** 42 | * Get command status. 43 | * 44 | * @return Command status. 45 | */ 46 | public String getStatus() { 47 | return status; 48 | } 49 | 50 | /** 51 | * Get command execution result. 52 | * 53 | * @return Command execution result. 54 | */ 55 | public Serializable getResult() { 56 | return result; 57 | } 58 | 59 | @Override 60 | public int describeContents() { 61 | return 0; 62 | } 63 | 64 | @Override 65 | public void writeToParcel(Parcel dest, int flags) { 66 | dest.writeString(status); 67 | dest.writeSerializable(result.getObject()); 68 | } 69 | 70 | public static Parcelable.Creator CREATOR = new Parcelable.Creator() { 71 | 72 | @Override 73 | public CommandResult[] newArray(int size) { 74 | return new CommandResult[size]; 75 | } 76 | 77 | @Override 78 | public CommandResult createFromParcel(Parcel source) { 79 | return new CommandResult(source.readString(), 80 | source.readSerializable()); 81 | } 82 | }; 83 | } 84 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/src/com/dataart/android/devicehive/device/CommandRunner.java: -------------------------------------------------------------------------------- 1 | package com.dataart.android.devicehive.device; 2 | 3 | import com.dataart.android.devicehive.Command; 4 | 5 | /** 6 | * Common interface for objects able to execute commands. Usually these are 7 | * {@link Device} and {@link Equipment}. 8 | */ 9 | public interface CommandRunner { 10 | 11 | /** 12 | * Called right before command is executed either by the device itself or 13 | * one of its equipment. This method is called for the device before each 14 | * command execution (either by the device itself or one of its equipment). 15 | * 16 | * @param command 17 | * {@link Command} to be executed. 18 | */ 19 | void onBeforeRunCommand(Command command); 20 | 21 | /** 22 | * Check whether receiver of the command should execute command on some 23 | * other thread, not on the main (UI) thread. 24 | * 25 | * @param command 26 | * Command to be executed. 27 | * @return true if {@link #runCommand(Command)} should be called 28 | * asynchronously, otherwise returns false. 29 | */ 30 | boolean shouldRunCommandAsynchronously(final Command command); 31 | 32 | /** 33 | * Execute given command. Cab be called either on the main thread or some 34 | * other thread. It depends on the value that is returned by 35 | * {@link #shouldRunCommandAsynchronously(Command)} method. 36 | * 37 | * @param command 38 | * Command to be executed. 39 | * @return {@link CommandResult} object describing command execution result 40 | * and status. 41 | */ 42 | CommandResult runCommand(final Command command); 43 | } 44 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/src/com/dataart/android/devicehive/device/DeviceStatusNotification.java: -------------------------------------------------------------------------------- 1 | package com.dataart.android.devicehive.device; 2 | 3 | import java.util.HashMap; 4 | 5 | import com.dataart.android.devicehive.DeviceData; 6 | import com.dataart.android.devicehive.Notification; 7 | 8 | /** 9 | * Represents a device status notification which is sent by {@link Device} when 10 | * its status changes. 11 | */ 12 | public class DeviceStatusNotification extends Notification { 13 | 14 | /** 15 | * Predefined "Online" device status notification. 16 | */ 17 | public static final DeviceStatusNotification STATUS_ONLINE = new DeviceStatusNotification( 18 | DeviceData.DEVICE_STATUS_ONLINE); 19 | 20 | /** 21 | * Predefined "OK" device status notification. 22 | */ 23 | public static final DeviceStatusNotification STATUS_OK = new DeviceStatusNotification( 24 | DeviceData.DEVICE_STATUS_OK); 25 | 26 | /** 27 | * Construct device status notification with given device status. 28 | * 29 | * @param deviceStatus 30 | * Device status value. 31 | */ 32 | public DeviceStatusNotification(String deviceStatus) { 33 | super("DeviceStatus", parametersWithDeviceStatus(deviceStatus)); 34 | } 35 | 36 | private static HashMap parametersWithDeviceStatus( 37 | String deviceStatus) { 38 | HashMap parameters = new HashMap(); 39 | parameters.put("status", deviceStatus); 40 | return parameters; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/src/com/dataart/android/devicehive/device/Equipment.java: -------------------------------------------------------------------------------- 1 | package com.dataart.android.devicehive.device; 2 | 3 | import com.dataart.android.devicehive.DeviceHive; 4 | import com.dataart.android.devicehive.EquipmentData; 5 | 6 | import android.util.Log; 7 | 8 | /** 9 | * Represents an abstract equipment which is installed on devices. This class is 10 | * designed to be subclassed in order to represent specific equipment. 11 | * Descendants should implement abstract methods of {@link CommandRunner} 12 | * interface in order to execute commands. Also they may override various 13 | * callbacks: {@link #onRegisterEquipment()}, {@link #onUnregisterEquipment()}, 14 | * {@link #onStartProcessingCommands()}, {@link #onStopProcessingCommands()}, 15 | * etc. 16 | */ 17 | public abstract class Equipment implements CommandRunner { 18 | 19 | private final EquipmentData equipmentData; 20 | private Device device; 21 | 22 | /** 23 | * Construct equipment with given {@link EquipmentData}. 24 | * 25 | * @param equipmentData 26 | * {@link EquipmentData} object which describes equipment 27 | * parameters. 28 | */ 29 | public Equipment(EquipmentData equipmentData) { 30 | this.equipmentData = equipmentData; 31 | } 32 | 33 | /** 34 | * Get equipment data which describes equipment parameters. 35 | * 36 | * @return 37 | */ 38 | public EquipmentData getEquipmentData() { 39 | return equipmentData; 40 | } 41 | 42 | /** 43 | * Get device which this equipment attached to. 44 | * 45 | * @return Corresponding {@link Device} object or null, if 46 | * equipment isn't attached to any device. 47 | */ 48 | public Device getDevice() { 49 | return device; 50 | } 51 | 52 | /* package */void setDevice(Device device) { 53 | this.device = device; 54 | } 55 | 56 | /** 57 | * Send equipment notification. Equipment should be attached to a 58 | * {@link Device} and device should be registered in order for notification 59 | * to be successfully sent. 60 | * 61 | * @param notification 62 | * Notification to be sent. 63 | */ 64 | public void sendNotification(EquipmentNotification notification) { 65 | if (device == null) { 66 | Log.w(DeviceHive.TAG, "Equipment should be attached to a device in order to be able to send notifications"); 67 | } else { 68 | device.sendNotification(notification); 69 | } 70 | } 71 | 72 | /** 73 | * Called as a part of device registration process. Override this method to 74 | * perform any additional initialization. This method can be called either 75 | * on main thread or some other thread. It depends on 76 | * {@link Device#performsEquipmentRegistrationCallbacksAsynchronously()} 77 | * method's return value. 78 | * 79 | * @return true, if equipment is registered successfully, otherwise returns 80 | * false. 81 | */ 82 | protected boolean onRegisterEquipment() { 83 | return true; 84 | } 85 | 86 | /** 87 | * Called as a part of device deregistration process. Usually happens during 88 | * connection loss. Override this method to perform any additional 89 | * deinitialization. This method can be called either on main thread or some 90 | * other thread. It depends on 91 | * {@link Device#performsEquipmentRegistrationCallbacksAsynchronously()} 92 | * method's return value. 93 | * 94 | * @return true, if equipment is unregistered successfully, otherwise return 95 | * false. 96 | */ 97 | protected boolean onUnregisterEquipment() { 98 | return true; 99 | } 100 | 101 | /** 102 | * Called right after {@link Device#startProcessingCommands()} method is 103 | * called. Override this method to perform additional initialization or 104 | * other actions. 105 | */ 106 | protected void onStartProcessingCommands() { 107 | // no op 108 | } 109 | 110 | /** 111 | * Called right after {@link Device#stopProcessingCommands()} method is 112 | * called. Override this method to perform additional actions when device 113 | * stops processing commands. 114 | */ 115 | protected void onStopProcessingCommands() { 116 | // no op 117 | } 118 | 119 | } 120 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/src/com/dataart/android/devicehive/device/EquipmentNotification.java: -------------------------------------------------------------------------------- 1 | package com.dataart.android.devicehive.device; 2 | 3 | import java.util.HashMap; 4 | 5 | import com.dataart.android.devicehive.Notification; 6 | 7 | /** 8 | * Represents a {@link Notification} which is usually sent by an 9 | * {@link Equipment} to update its state. 10 | */ 11 | public class EquipmentNotification extends Notification { 12 | 13 | /** 14 | * Construct a notification with given equipment code and additional 15 | * equipment parameters dictionary. 16 | * 17 | * @param equipmentCode 18 | * Equipment code. 19 | * @param parameters 20 | * Equipment parameters dictionary. 21 | */ 22 | public EquipmentNotification(String equipmentCode, 23 | HashMap parameters) { 24 | super("equipment", equipmentParameters(equipmentCode, parameters)); 25 | } 26 | 27 | private static HashMap equipmentParameters( 28 | String equipmentCode, HashMap parameters) { 29 | final HashMap equipmentParameters = new HashMap( 30 | parameters); 31 | parameters.put("equipment", equipmentCode); 32 | return equipmentParameters; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/src/com/dataart/android/devicehive/device/commands/DeviceCommand.java: -------------------------------------------------------------------------------- 1 | package com.dataart.android.devicehive.device.commands; 2 | 3 | import java.util.Map; 4 | 5 | import android.os.Parcel; 6 | 7 | import com.dataart.android.devicehive.network.JsonNetworkCommand; 8 | 9 | /** 10 | * Base command for Device Hive device-related commands. 11 | */ 12 | public abstract class DeviceCommand extends JsonNetworkCommand { 13 | 14 | protected final String deviceId; 15 | protected final String deviceKey; 16 | 17 | /** 18 | * Construct new command with given device data. 19 | * 20 | * @param deviceId 21 | * Device identifier. 22 | * @param deviceKey 23 | * Device key. 24 | */ 25 | public DeviceCommand(String deviceId, String deviceKey) { 26 | this.deviceId = deviceId; 27 | this.deviceKey = deviceKey; 28 | } 29 | 30 | /** 31 | * Construct new command with given device data. 32 | * 33 | * @param deviceId 34 | * Device identifier. 35 | */ 36 | public DeviceCommand(String deviceId) { 37 | this(deviceId, null); 38 | } 39 | 40 | protected boolean deviceAuthenticationRequired() { 41 | return true; 42 | } 43 | 44 | @Override 45 | protected Map getHeaders() { 46 | final Map headers = super.getHeaders(); 47 | if (deviceAuthenticationRequired()) { 48 | addDeviceAuthentication(headers); 49 | } 50 | return headers; 51 | } 52 | 53 | protected String getEncodedDeviceId() { 54 | return encodedString(deviceId); 55 | } 56 | 57 | private void addDeviceAuthentication(Map headers) { 58 | headers.put("Auth-DeviceID", deviceId); 59 | headers.put("Auth-DeviceKey", deviceKey); 60 | } 61 | 62 | @Override 63 | public int describeContents() { 64 | return 0; 65 | } 66 | 67 | @Override 68 | public void writeToParcel(Parcel dest, int flags) { 69 | dest.writeString(deviceId); 70 | dest.writeString(deviceKey); 71 | } 72 | 73 | } 74 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/src/com/dataart/android/devicehive/device/commands/DeviceCommandsRetrivalCommand.java: -------------------------------------------------------------------------------- 1 | package com.dataart.android.devicehive.device.commands; 2 | 3 | import java.lang.reflect.Type; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | 7 | import android.os.Bundle; 8 | import android.os.Parcel; 9 | 10 | import com.dataart.android.devicehive.Command; 11 | import com.dataart.android.devicehive.DeviceData; 12 | import com.dataart.android.devicehive.network.DeviceHiveResultReceiver; 13 | import com.google.gson.Gson; 14 | import com.google.gson.reflect.TypeToken; 15 | 16 | /** 17 | * Abstract base class for command retrieval-related commands. 18 | */ 19 | public abstract class DeviceCommandsRetrivalCommand extends DeviceCommand { 20 | 21 | private final static String NAMESPACE = DeviceCommandsRetrivalCommand.class 22 | .getName(); 23 | 24 | private static final String COMMANDS_KEY = NAMESPACE 25 | .concat(".COMMANDS_KEY"); 26 | 27 | protected final String lastCommandPollTimestamp; 28 | 29 | /** 30 | * Construct a new command with given {@link DeviceData} and last received 31 | * command timestamp. 32 | * 33 | * @param deviceId 34 | * Device unique identifier. 35 | * @param deviceKey 36 | * Device key. 37 | * @param lastCommandPollTimestamp 38 | * Timestamp of the last received command. 39 | */ 40 | public DeviceCommandsRetrivalCommand(String deviceId, String deviceKey, 41 | String lastCommandPollTimestamp) { 42 | super(deviceId, deviceKey); 43 | this.lastCommandPollTimestamp = lastCommandPollTimestamp; 44 | } 45 | 46 | @Override 47 | protected RequestType getRequestType() { 48 | return RequestType.GET; 49 | } 50 | 51 | @Override 52 | protected String toJson(Gson gson) { 53 | return null; 54 | } 55 | 56 | @Override 57 | protected int fromJson(final String response, final Gson gson, 58 | final Bundle resultData) { 59 | 60 | Type listType = new TypeToken>() { 61 | }.getType(); 62 | 63 | ArrayList commands = gson.fromJson(response, listType); 64 | resultData.putParcelableArrayList(COMMANDS_KEY, commands); 65 | return DeviceHiveResultReceiver.MSG_HANDLED_RESPONSE; 66 | } 67 | 68 | public final static List getCommands(Bundle resultData) { 69 | return resultData.getParcelableArrayList(COMMANDS_KEY); 70 | } 71 | 72 | @Override 73 | public void writeToParcel(Parcel dest, int flags) { 74 | super.writeToParcel(dest, flags); 75 | dest.writeString(lastCommandPollTimestamp); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/src/com/dataart/android/devicehive/device/commands/GetDeviceCommand.java: -------------------------------------------------------------------------------- 1 | package com.dataart.android.devicehive.device.commands; 2 | 3 | import android.os.Bundle; 4 | import android.os.Parcel; 5 | import android.os.Parcelable; 6 | 7 | import com.dataart.android.devicehive.DeviceData; 8 | import com.dataart.android.devicehive.network.DeviceHiveResultReceiver; 9 | import com.google.gson.Gson; 10 | 11 | /** 12 | * Get device object with given identifier. As a result returns 13 | * {@link DeviceData} instance. 14 | */ 15 | public class GetDeviceCommand extends DeviceCommand { 16 | 17 | private final static String NAMESPACE = GetDeviceCommand.class.getName(); 18 | 19 | private static final String DEVICE_KEY = NAMESPACE.concat(".DEVICE_KEY"); 20 | 21 | /** 22 | * Construct a new command. 23 | * 24 | * @param deviceId 25 | * Device unique identifier. 26 | * @param deviceKey 27 | * Device key. 28 | */ 29 | public GetDeviceCommand(String deviceId, String deviceKey) { 30 | super(deviceId, deviceKey); 31 | } 32 | 33 | @Override 34 | protected String toJson(Gson gson) { 35 | return null; 36 | } 37 | 38 | @Override 39 | protected RequestType getRequestType() { 40 | return RequestType.GET; 41 | } 42 | 43 | @Override 44 | protected String getRequestPath() { 45 | String requestPath = String.format("/device/%s", getEncodedDeviceId()); 46 | return requestPath; 47 | } 48 | 49 | public static Parcelable.Creator CREATOR = new Parcelable.Creator() { 50 | 51 | @Override 52 | public GetDeviceCommand[] newArray(int size) { 53 | return new GetDeviceCommand[size]; 54 | } 55 | 56 | @Override 57 | public GetDeviceCommand createFromParcel(Parcel source) { 58 | return new GetDeviceCommand(source.readString(), 59 | source.readString()); 60 | } 61 | }; 62 | 63 | @Override 64 | public int describeContents() { 65 | return 0; 66 | } 67 | 68 | @Override 69 | public void writeToParcel(Parcel dest, int flags) { 70 | super.writeToParcel(dest, flags); 71 | } 72 | 73 | @Override 74 | protected int fromJson(final String response, final Gson gson, 75 | final Bundle resultData) { 76 | 77 | final DeviceData device = gson.fromJson(response, DeviceData.class); 78 | resultData.putParcelable(DEVICE_KEY, device); 79 | return DeviceHiveResultReceiver.MSG_HANDLED_RESPONSE; 80 | } 81 | 82 | /** 83 | * Get {@link DeviceData} object from response {@link Bundle} container. 84 | * 85 | * @param resultData 86 | * {@link Bundle} object containing required response data. 87 | * @return {@link DeviceData} instance. 88 | */ 89 | public final static DeviceData getDevice(Bundle resultData) { 90 | return resultData.getParcelable(DEVICE_KEY); 91 | } 92 | 93 | } 94 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/src/com/dataart/android/devicehive/device/commands/GetDeviceCommandsCommand.java: -------------------------------------------------------------------------------- 1 | package com.dataart.android.devicehive.device.commands; 2 | 3 | import android.os.Parcel; 4 | import android.os.Parcelable; 5 | 6 | import com.dataart.android.devicehive.DeviceData; 7 | 8 | /** 9 | * Get commands for given device starting from given date timestamp. Server 10 | * returns response immediately regardless of whether there are any commands for 11 | * given device. 12 | */ 13 | public class GetDeviceCommandsCommand extends DeviceCommandsRetrivalCommand { 14 | 15 | /** 16 | * Construct a new command with given {@link DeviceData} and last received 17 | * command timestamp. 18 | * 19 | * @param deviceId 20 | * Device unique identifier. 21 | * @param deviceKey 22 | * Device key. 23 | * @param lastCommandPollTimestamp 24 | * Timestamp of the last received command. If null value is 25 | * passed then server will return all command it's received so 26 | * far. 27 | */ 28 | public GetDeviceCommandsCommand(String deviceId, String deviceKey, 29 | String lastCommandPollTimestamp) { 30 | super(deviceId, deviceKey, lastCommandPollTimestamp); 31 | } 32 | 33 | @Override 34 | protected String getRequestPath() { 35 | String requestPath = String.format("device/%s/command", 36 | getEncodedDeviceId()); 37 | if (lastCommandPollTimestamp != null) { 38 | requestPath += "?start=" + encodedString(lastCommandPollTimestamp); 39 | } 40 | return requestPath; 41 | } 42 | 43 | public static Parcelable.Creator CREATOR = new Parcelable.Creator() { 44 | 45 | @Override 46 | public GetDeviceCommandsCommand[] newArray(int size) { 47 | return new GetDeviceCommandsCommand[size]; 48 | } 49 | 50 | @Override 51 | public GetDeviceCommandsCommand createFromParcel(Parcel source) { 52 | return new GetDeviceCommandsCommand(source.readString(), 53 | source.readString(), source.readString()); 54 | } 55 | }; 56 | 57 | } 58 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/src/com/dataart/android/devicehive/device/commands/PollDeviceCommandsCommand.java: -------------------------------------------------------------------------------- 1 | package com.dataart.android.devicehive.device.commands; 2 | 3 | import android.os.Parcel; 4 | import android.os.Parcelable; 5 | 6 | import com.dataart.android.devicehive.DeviceData; 7 | 8 | /** 9 | * Poll for commands for given device starting from given date timestamp. In the 10 | * case when no commands were found, the server doesn't return response until a 11 | * new command is received. The blocking period is limited. 12 | */ 13 | public class PollDeviceCommandsCommand extends DeviceCommandsRetrivalCommand { 14 | 15 | private final Integer waitTimeout; 16 | 17 | /** 18 | * Construct a new command with given {@link DeviceData} and last received 19 | * command timestamp. 20 | * 21 | * @param deviceId 22 | * Device unique identifier. 23 | * @param deviceKey 24 | * Device key. 25 | * @param lastCommandPollTimestamp 26 | * Timestamp of the last received command. If null value is 27 | * passed then server's timestamp will be used instead. 28 | */ 29 | public PollDeviceCommandsCommand(String deviceId, String deviceKey, 30 | String lastCommandPollTimestamp) { 31 | this(deviceId, deviceKey, lastCommandPollTimestamp, null); 32 | } 33 | 34 | /** 35 | * Construct a new command with given {@link DeviceData} and last received 36 | * command timestamp. 37 | * 38 | * @param deviceId 39 | * Device unique identifier. 40 | * @param deviceKey 41 | * Device key. 42 | * @param lastCommandPollTimestamp 43 | * Timestamp of the last received command. If null value is 44 | * passed then server's timestamp will be used instead. 45 | * @param waitTimeout 46 | * Waiting timeout in seconds. 47 | */ 48 | public PollDeviceCommandsCommand(String deviceId, String deviceKey, 49 | String lastCommandPollTimestamp, Integer waitTimeout) { 50 | super(deviceId, deviceKey, lastCommandPollTimestamp); 51 | this.waitTimeout = waitTimeout; 52 | } 53 | 54 | @Override 55 | protected String getRequestPath() { 56 | String requestPath = String.format("device/%s/command/poll", 57 | getEncodedDeviceId()); 58 | if (lastCommandPollTimestamp != null) { 59 | requestPath += "?timestamp=" 60 | + encodedString(lastCommandPollTimestamp); 61 | } 62 | if (waitTimeout != null) { 63 | requestPath += lastCommandPollTimestamp != null ? "&" : "?"; 64 | requestPath += "waitTimeout=" + waitTimeout; 65 | } 66 | return requestPath; 67 | } 68 | 69 | @Override 70 | public void writeToParcel(Parcel dest, int flags) { 71 | super.writeToParcel(dest, flags); 72 | dest.writeValue(waitTimeout); 73 | } 74 | 75 | public static Parcelable.Creator CREATOR = new Parcelable.Creator() { 76 | 77 | @Override 78 | public PollDeviceCommandsCommand[] newArray(int size) { 79 | return new PollDeviceCommandsCommand[size]; 80 | } 81 | 82 | @Override 83 | public PollDeviceCommandsCommand createFromParcel(Parcel source) { 84 | return new PollDeviceCommandsCommand(source.readString(), 85 | source.readString(), source.readString(), 86 | (Integer) source.readValue(CLASS_LOADER)); 87 | } 88 | }; 89 | 90 | } 91 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/src/com/dataart/android/devicehive/device/commands/RegisterDeviceCommand.java: -------------------------------------------------------------------------------- 1 | package com.dataart.android.devicehive.device.commands; 2 | 3 | import android.os.Bundle; 4 | import android.os.Parcel; 5 | import android.os.Parcelable; 6 | 7 | import com.dataart.android.devicehive.DeviceData; 8 | import com.dataart.android.devicehive.network.DeviceHiveResultReceiver; 9 | import com.google.gson.Gson; 10 | 11 | /** 12 | * Register a new device which parameters are described by given 13 | * {@link DeviceData} instance. 14 | * 15 | */ 16 | public class RegisterDeviceCommand extends DeviceCommand { 17 | 18 | private final static String NAMESPACE = RegisterDeviceCommand.class 19 | .getName(); 20 | 21 | private static final String DEVICE_DATA_KEY = NAMESPACE 22 | .concat(".DEVICE_DATA_KEY"); 23 | 24 | private final DeviceData deviceData; 25 | 26 | /** 27 | * Construct a new command with given {@link DeviceData}. 28 | * 29 | * @param deviceData 30 | * {@link DeviceData} instance. 31 | */ 32 | public RegisterDeviceCommand(DeviceData deviceData) { 33 | super(deviceData.getId(), deviceData.getKey()); 34 | this.deviceData = deviceData; 35 | } 36 | 37 | @Override 38 | protected RequestType getRequestType() { 39 | return RequestType.PUT; 40 | } 41 | 42 | @Override 43 | protected String getRequestPath() { 44 | return String.format("device/%s", getEncodedDeviceId()); 45 | } 46 | 47 | @Override 48 | public void writeToParcel(Parcel dest, int flags) { 49 | dest.writeParcelable(deviceData, 0); 50 | } 51 | 52 | public static Parcelable.Creator CREATOR = new Parcelable.Creator() { 53 | 54 | @Override 55 | public RegisterDeviceCommand[] newArray(int size) { 56 | return new RegisterDeviceCommand[size]; 57 | } 58 | 59 | @Override 60 | public RegisterDeviceCommand createFromParcel(Parcel source) { 61 | return new RegisterDeviceCommand( 62 | (DeviceData) source.readParcelable(CLASS_LOADER)); 63 | } 64 | }; 65 | 66 | @Override 67 | protected String toJson(Gson gson) { 68 | return gson.toJson(deviceData); 69 | } 70 | 71 | @Override 72 | protected int fromJson(final String response, final Gson gson, 73 | final Bundle resultData) { 74 | final DeviceData deviceData = gson.fromJson(response, DeviceData.class); 75 | resultData.putParcelable(DEVICE_DATA_KEY, deviceData); 76 | return DeviceHiveResultReceiver.MSG_HANDLED_RESPONSE; 77 | } 78 | 79 | public final static DeviceData getDeviceData(Bundle resultData) { 80 | return resultData.getParcelable(DEVICE_DATA_KEY); 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/src/com/dataart/android/devicehive/device/commands/SendNotificationCommand.java: -------------------------------------------------------------------------------- 1 | package com.dataart.android.devicehive.device.commands; 2 | 3 | import android.os.Bundle; 4 | import android.os.Parcel; 5 | import android.os.Parcelable; 6 | 7 | import com.dataart.android.devicehive.DeviceData; 8 | import com.dataart.android.devicehive.Notification; 9 | import com.dataart.android.devicehive.network.DeviceHiveResultReceiver; 10 | import com.google.gson.Gson; 11 | 12 | /** 13 | * Send a new notification from the given device. As a result returns 14 | * {@link Notification} instance from the server response. 15 | * 16 | */ 17 | public class SendNotificationCommand extends DeviceCommand { 18 | 19 | private final static String NAMESPACE = SendNotificationCommand.class 20 | .getName(); 21 | 22 | private static final String NOTIFICATION_DATA_KEY = NAMESPACE 23 | .concat(".NOTIFICATION_DATA_KEY"); 24 | 25 | private final Notification notification; 26 | 27 | /** 28 | * Construct a new command with given {@link DeviceData} and last received 29 | * command timestamp. 30 | * 31 | * @param deviceId 32 | * Device unique identifier. 33 | * @param deviceKey 34 | * Device key. 35 | * @param notification 36 | * {@link Notification} to be sent on behalf of given device. 37 | */ 38 | public SendNotificationCommand(String deviceId, String deviceKey, 39 | Notification notification) { 40 | super(deviceId, deviceKey); 41 | this.notification = notification; 42 | } 43 | 44 | /** 45 | * Get {@link Notification} to be sent. 46 | * @return {@link Notification} instance. 47 | */ 48 | public Notification getNotification() { 49 | return notification; 50 | } 51 | 52 | @Override 53 | protected RequestType getRequestType() { 54 | return RequestType.POST; 55 | } 56 | 57 | @Override 58 | protected String getRequestPath() { 59 | return String.format("device/%s/notification", getEncodedDeviceId()); 60 | } 61 | 62 | @Override 63 | public void writeToParcel(Parcel dest, int flags) { 64 | super.writeToParcel(dest, flags); 65 | dest.writeParcelable(notification, 0); 66 | } 67 | 68 | public static Parcelable.Creator CREATOR = new Parcelable.Creator() { 69 | 70 | @Override 71 | public SendNotificationCommand[] newArray(int size) { 72 | return new SendNotificationCommand[size]; 73 | } 74 | 75 | @Override 76 | public SendNotificationCommand createFromParcel(Parcel source) { 77 | return new SendNotificationCommand( 78 | source.readString(), 79 | source.readString(), 80 | (Notification) source.readParcelable(CLASS_LOADER)); 81 | } 82 | }; 83 | 84 | @Override 85 | protected String toJson(Gson gson) { 86 | return gson.toJson(notification); 87 | } 88 | 89 | @Override 90 | protected int fromJson(final String response, final Gson gson, 91 | final Bundle resultData) { 92 | final Notification notification = gson.fromJson(response, 93 | Notification.class); 94 | resultData.putParcelable(NOTIFICATION_DATA_KEY, notification); 95 | return DeviceHiveResultReceiver.MSG_HANDLED_RESPONSE; 96 | } 97 | 98 | public final static Notification getNotification(Bundle resultData) { 99 | return resultData.getParcelable(NOTIFICATION_DATA_KEY); 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/src/com/dataart/android/devicehive/device/commands/UpdateCommandStatusCommand.java: -------------------------------------------------------------------------------- 1 | package com.dataart.android.devicehive.device.commands; 2 | 3 | import android.os.Bundle; 4 | import android.os.Parcel; 5 | import android.os.Parcelable; 6 | 7 | import com.dataart.android.devicehive.Command; 8 | import com.dataart.android.devicehive.DeviceData; 9 | import com.dataart.android.devicehive.device.CommandResult; 10 | import com.dataart.android.devicehive.network.DeviceHiveResultReceiver; 11 | import com.google.gson.Gson; 12 | 13 | /** 14 | * Update status of given command with given {@link #commandResult}. As a result 15 | * returns updated {@link Command} instance returned by the server. 16 | * 17 | */ 18 | public class UpdateCommandStatusCommand extends DeviceCommand { 19 | 20 | private final static String NAMESPACE = UpdateCommandStatusCommand.class 21 | .getName(); 22 | 23 | private static final String COMMAND_KEY = NAMESPACE.concat(".COMMAND_KEY"); 24 | 25 | private final int commandId; 26 | private final CommandResult commandResult; 27 | 28 | /** 29 | * Construct a new update command with given {@link DeviceData} and 30 | * identifier of the command to update with {@link CommandResult}. 31 | * 32 | * @param deviceId 33 | * Device unique identifier. 34 | * @param deviceKey 35 | * Device key. 36 | * @param command 37 | * {@link Command} to be updated. 38 | * @param commandResult 39 | * {@link CommandResult} object describing command status. 40 | */ 41 | public UpdateCommandStatusCommand(String deviceId, String deviceKey, int commandId, 42 | CommandResult commandResult) { 43 | super(deviceId, deviceKey); 44 | this.commandId = commandId; 45 | this.commandResult = commandResult; 46 | } 47 | 48 | @Override 49 | protected RequestType getRequestType() { 50 | return RequestType.PUT; 51 | } 52 | 53 | @Override 54 | protected String getRequestPath() { 55 | return String.format("device/%s/command/%d", getEncodedDeviceId(), 56 | commandId); 57 | } 58 | 59 | @Override 60 | public void writeToParcel(Parcel dest, int flags) { 61 | super.writeToParcel(dest, flags); 62 | dest.writeInt(commandId); 63 | dest.writeParcelable(commandResult, 0); 64 | } 65 | 66 | public static Parcelable.Creator CREATOR = new Parcelable.Creator() { 67 | 68 | @Override 69 | public UpdateCommandStatusCommand[] newArray(int size) { 70 | return new UpdateCommandStatusCommand[size]; 71 | } 72 | 73 | @Override 74 | public UpdateCommandStatusCommand createFromParcel(Parcel source) { 75 | return new UpdateCommandStatusCommand( 76 | source.readString(), 77 | source.readString(), 78 | source.readInt(), 79 | (CommandResult) source.readParcelable(CLASS_LOADER)); 80 | } 81 | }; 82 | 83 | @Override 84 | protected String toJson(Gson gson) { 85 | return gson.toJson(commandResult); 86 | } 87 | 88 | @Override 89 | protected int fromJson(final String response, final Gson gson, 90 | final Bundle resultData) { 91 | final Command command = gson.fromJson(response, Command.class); 92 | resultData.putParcelable(COMMAND_KEY, command); 93 | return DeviceHiveResultReceiver.MSG_HANDLED_RESPONSE; 94 | } 95 | 96 | public final static Command getUpdatedCommand(Bundle resultData) { 97 | return resultData.getParcelable(COMMAND_KEY); 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/src/com/dataart/android/devicehive/network/DeviceHiveApiService.java: -------------------------------------------------------------------------------- 1 | package com.dataart.android.devicehive.network; 2 | 3 | import java.util.LinkedList; 4 | import java.util.concurrent.ConcurrentLinkedQueue; 5 | import java.util.concurrent.Executor; 6 | import java.util.concurrent.LinkedBlockingQueue; 7 | import java.util.concurrent.ThreadFactory; 8 | import java.util.concurrent.ThreadPoolExecutor; 9 | import java.util.concurrent.TimeUnit; 10 | import java.util.concurrent.atomic.AtomicInteger; 11 | 12 | import android.app.Service; 13 | import android.content.Intent; 14 | import android.os.IBinder; 15 | import android.util.Log; 16 | 17 | import com.dataart.android.devicehive.DeviceHive; 18 | 19 | /** 20 | * Android {@link Service} subclass which is used to concurrently execute 21 | * commands sent via {@link Intent}. This service should be declared in 22 | * AndroidManifest.xml file. Can execute commands either concurrently or in FIFO 23 | * order. 24 | * 25 | * @see {@link NetworkCommand#isSerial()} 26 | */ 27 | public class DeviceHiveApiService extends Service { 28 | 29 | private final static String NAMESPACE = DeviceHiveApiService.class 30 | .getName(); 31 | 32 | /* package */final static String EXTRA_COMMAND = NAMESPACE 33 | .concat(".EXTRA_COMMAND"); 34 | 35 | /* package */final static String EXTRA_COMMAND_CONFIG = NAMESPACE 36 | .concat(".EXTRA_COMMAND_CONFIG"); 37 | 38 | /* package */final static String EXTRA_COMMAND_SERIAL = NAMESPACE 39 | .concat(".EXTRA_COMMAND_SERIAL"); 40 | 41 | private final static ThreadFactory threadFactory = new ThreadFactory() { 42 | 43 | private final AtomicInteger threadSerialNumber = new AtomicInteger(0); 44 | 45 | @Override 46 | public Thread newThread(Runnable r) { 47 | final Thread thread = new Thread(r, "[DeviceHiveApiService #" 48 | + threadSerialNumber.getAndIncrement() + "]"); 49 | thread.setDaemon(true); 50 | return thread; 51 | } 52 | }; 53 | 54 | private final ConcurrentLinkedQueue commandStartIdQueue = new ConcurrentLinkedQueue(); 55 | 56 | private final static ThreadPoolExecutor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor( 57 | 4, 6, 1, TimeUnit.SECONDS, new LinkedBlockingQueue(10), 58 | threadFactory); 59 | 60 | private final static SerialExecutor SERIAL_EXECUTOR = new SerialExecutor(); 61 | 62 | private static class SerialExecutor implements Executor { 63 | private final LinkedList tasks = new LinkedList(); 64 | private Runnable activeTask; 65 | 66 | public synchronized void execute(final Runnable r) { 67 | tasks.offer(new Runnable() { 68 | public void run() { 69 | try { 70 | r.run(); 71 | } finally { 72 | scheduleNext(); 73 | } 74 | } 75 | }); 76 | if (activeTask == null) { 77 | scheduleNext(); 78 | } 79 | } 80 | 81 | protected synchronized void scheduleNext() { 82 | activeTask = tasks.poll(); 83 | if (activeTask != null) { 84 | THREAD_POOL_EXECUTOR.execute(activeTask); 85 | } 86 | } 87 | } 88 | 89 | @Override 90 | public IBinder onBind(Intent intent) { 91 | return null; 92 | } 93 | 94 | @Override 95 | public int onStartCommand(final Intent intent, final int flags, 96 | final int startId) { 97 | commandStartIdQueue.add(startId); 98 | final Runnable runnable = new Runnable() { 99 | @Override 100 | public void run() { 101 | try { 102 | handleIntent(intent); 103 | } finally { 104 | stopSelf(commandStartIdQueue.remove()); 105 | } 106 | } 107 | }; 108 | if (intent.getBooleanExtra(EXTRA_COMMAND_SERIAL, false)) { 109 | SERIAL_EXECUTOR.execute(runnable); 110 | } else { 111 | THREAD_POOL_EXECUTOR.execute(runnable); 112 | } 113 | return START_NOT_STICKY; 114 | } 115 | 116 | protected void handleIntent(Intent intent) { 117 | NetworkCommand command = null; 118 | NetworkCommandConfig config = null; 119 | final long startTime = System.currentTimeMillis(); 120 | try { 121 | command = intent.getParcelableExtra(EXTRA_COMMAND); 122 | if (command != null) { 123 | config = intent.getParcelableExtra(EXTRA_COMMAND_CONFIG); 124 | if (config != null) { 125 | if (config.isDebugLoggingEnabled) { 126 | Log.d(DeviceHive.TAG, "Starting command " + command); 127 | } 128 | command.setConfig(config); 129 | command.execute(this); 130 | } else { 131 | Log.w(DeviceHive.TAG, "Missing command config in " + intent); 132 | } 133 | } else { 134 | Log.w(DeviceHive.TAG, "Missing command in " + intent); 135 | } 136 | } catch (Exception e) { 137 | Log.e(DeviceHive.TAG, "Cannot process command " + command, e); 138 | } finally { 139 | if (command != null && config != null) { 140 | if (config.isDebugLoggingEnabled) { 141 | Log.d(DeviceHive.TAG, "Completed command " + command 142 | + " in " + (System.currentTimeMillis() - startTime)); 143 | } 144 | } 145 | } 146 | } 147 | 148 | } 149 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/src/com/dataart/android/devicehive/network/DeviceHiveResultReceiver.java: -------------------------------------------------------------------------------- 1 | package com.dataart.android.devicehive.network; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | import java.util.concurrent.atomic.AtomicInteger; 6 | 7 | import android.os.Bundle; 8 | import android.os.Handler; 9 | import android.os.HandlerThread; 10 | import android.os.ResultReceiver; 11 | import android.util.Log; 12 | 13 | import com.dataart.android.devicehive.DeviceHive; 14 | 15 | /** 16 | * Result receiver which is used to communicate(receive results) with service. 17 | */ 18 | public class DeviceHiveResultReceiver extends ResultReceiver { 19 | 20 | /** 21 | * Message with this code is sent when request is started. 22 | */ 23 | public final static int MSG_EXECUTE_REQUEST = 0x00000010; 24 | 25 | /** 26 | * Message with this code is sent to the result receiver when request is 27 | * finished regardless of whether it succeeds or fails. 28 | */ 29 | public final static int MSG_COMPLETE_REQUEST = 0x00000011; 30 | 31 | /** 32 | * Message with this code is sent to the result receiver when response of 33 | * the request is handled(parsed). 34 | */ 35 | public final static int MSG_HANDLED_RESPONSE = 0x00000012; 36 | 37 | /** 38 | * Message with this code is sent to the result receiver fails and returns 39 | * corresponding Http status code. 40 | */ 41 | public final static int MSG_STATUS_FAILURE = 0x00000013; 42 | 43 | /** 44 | * Message with this code is sent to the result receiver when request fails 45 | * due to connectivity loss or IO error that usually lead to exception to be 46 | * thrown. 47 | */ 48 | public final static int MSG_EXCEPTION = 0x0FFFFFFF; 49 | 50 | /** 51 | * Result listener interface. 52 | */ 53 | public static interface ResultListener { 54 | /** 55 | * Called when result receiver receives results from the service. 56 | * 57 | * @param code 58 | * Status code of the result. 59 | * @param tag 60 | * Tag value. 61 | * @param data 62 | * {@link Bundle} which contains command execution results. 63 | */ 64 | void onReceiveResult(int code, int tag, Bundle data); 65 | } 66 | 67 | private final static Handler mainThreadHandler = new Handler(); 68 | private final static Handler receiverHandler; 69 | 70 | static { 71 | final HandlerThread thread = new HandlerThread( 72 | DeviceHiveResultReceiver.class.getSimpleName() 73 | + "[Handler Thread]"); 74 | thread.start(); 75 | receiverHandler = new Handler(thread.getLooper()); 76 | } 77 | 78 | private static class ResultListenerConfig { 79 | private final ResultListener listener; 80 | private final boolean runOnMainThread; 81 | 82 | public ResultListenerConfig(ResultListener listener, 83 | boolean runOnMainThread) { 84 | this.listener = listener; 85 | this.runOnMainThread = runOnMainThread; 86 | } 87 | } 88 | 89 | private ResultListenerConfig resultListenerConfig = null; 90 | 91 | public DeviceHiveResultReceiver() { 92 | super(receiverHandler); 93 | } 94 | 95 | /** 96 | * Detach result listener from the result receiver. 97 | */ 98 | public void detachResultListener() { 99 | this.resultListenerConfig = null; 100 | } 101 | 102 | /** 103 | * Set result listener. 104 | * 105 | * @param listener 106 | * {@link ResultListener} instance. 107 | * @param runOnMainThread 108 | * Whether 109 | * {@link ResultListener#onReceiveResult(int, int, Bundle)} 110 | * should run on the main Thread. 111 | */ 112 | public void setResultListener(final ResultListener listener, 113 | final boolean runOnMainThread) { 114 | this.resultListenerConfig = new ResultListenerConfig(listener, 115 | runOnMainThread); 116 | } 117 | 118 | @Override 119 | protected void onReceiveResult(final int resultCode, final Bundle resultData) { 120 | if (resultListenerConfig != null) { 121 | final int commandTagId = getIdForTag(NetworkCommand 122 | .getCommandTag(resultData)); 123 | if (resultListenerConfig.runOnMainThread) { 124 | mainThreadHandler.post(new Runnable() { 125 | @Override 126 | public void run() { 127 | if (resultListenerConfig != null) { 128 | resultListenerConfig.listener.onReceiveResult( 129 | resultCode, commandTagId, resultData); 130 | } 131 | } 132 | }); 133 | } else { 134 | resultListenerConfig.listener.onReceiveResult(resultCode, 135 | commandTagId, resultData); 136 | } 137 | } else { 138 | Log.w(DeviceHive.TAG, String.format( 139 | "Received result in detached listener: %s, %s", resultCode, 140 | resultData)); 141 | } 142 | } 143 | 144 | /** 145 | * Get tag id for given command tag. Returns the same value for equal tag 146 | * strings. 147 | * 148 | * @param tag 149 | * Command tag. 150 | * @return Integer value corresponding to the tag. 151 | */ 152 | public static final int getIdForTag(final String tag) { 153 | Integer id = existingTags.get(tag); 154 | if (id == null) { 155 | id = tagIdCounter.incrementAndGet(); 156 | existingTags.put(tag, id); 157 | } 158 | return id.intValue(); 159 | } 160 | 161 | private final static AtomicInteger tagIdCounter = new AtomicInteger(0); 162 | private final static Map existingTags = new HashMap(); 163 | } 164 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/src/com/dataart/android/devicehive/network/JsonNetworkCommand.java: -------------------------------------------------------------------------------- 1 | package com.dataart.android.devicehive.network; 2 | 3 | import java.io.Serializable; 4 | import java.io.UnsupportedEncodingException; 5 | import java.lang.reflect.Type; 6 | import java.net.URLEncoder; 7 | import java.util.ArrayList; 8 | import java.util.HashMap; 9 | import java.util.Map; 10 | import java.util.Map.Entry; 11 | import java.util.Set; 12 | 13 | import org.apache.http.HttpEntity; 14 | import org.apache.http.entity.StringEntity; 15 | 16 | import android.content.Context; 17 | import android.os.Bundle; 18 | import android.util.Log; 19 | 20 | import com.dataart.android.devicehive.DeviceHive; 21 | import com.dataart.android.devicehive.ObjectWrapper; 22 | import com.google.gson.FieldNamingPolicy; 23 | import com.google.gson.Gson; 24 | import com.google.gson.GsonBuilder; 25 | import com.google.gson.JsonArray; 26 | import com.google.gson.JsonDeserializationContext; 27 | import com.google.gson.JsonDeserializer; 28 | import com.google.gson.JsonElement; 29 | import com.google.gson.JsonObject; 30 | import com.google.gson.JsonParseException; 31 | import com.google.gson.JsonPrimitive; 32 | import com.google.gson.JsonSerializationContext; 33 | import com.google.gson.JsonSerializer; 34 | 35 | /** 36 | * Base command for JSON-related commands. 37 | * 38 | */ 39 | public abstract class JsonNetworkCommand extends NetworkCommand { 40 | 41 | private final static Gson gson; 42 | 43 | static { 44 | GsonBuilder builder = new GsonBuilder(); 45 | builder.setFieldNamingPolicy(FieldNamingPolicy.IDENTITY); 46 | builder.registerTypeAdapter(ObjectWrapper.class, 47 | new ObjectWrapperAdapter()); 48 | gson = builder.create(); 49 | } 50 | 51 | private static class ObjectWrapperAdapter implements 52 | JsonDeserializer>, 53 | JsonSerializer> { 54 | 55 | public JsonElement serialize(ObjectWrapper src, 56 | Type typeOfSrc, JsonSerializationContext context) { 57 | return context.serialize(src.getObject()); 58 | } 59 | 60 | @Override 61 | public ObjectWrapper deserialize(JsonElement json, 62 | Type typeOfT, JsonDeserializationContext context) 63 | throws JsonParseException { 64 | 65 | return new ObjectWrapper( 66 | (Serializable) parseElement(json)); 67 | } 68 | 69 | private Object parseElement(JsonElement jsonElement) { 70 | if (jsonElement.isJsonPrimitive()) { 71 | return parsePrimitive(jsonElement.getAsJsonPrimitive()); 72 | } else if (jsonElement.isJsonArray()) { 73 | return parseArray(jsonElement.getAsJsonArray()); 74 | } else { 75 | return parseObject(jsonElement.getAsJsonObject()); 76 | } 77 | } 78 | 79 | private Object parsePrimitive(JsonPrimitive primitive) { 80 | if (primitive.isBoolean()) { 81 | return primitive.getAsBoolean(); 82 | } else if (primitive.isNumber()) { 83 | return primitive.getAsDouble(); 84 | } else { 85 | return primitive.getAsString(); 86 | } 87 | } 88 | 89 | private ArrayList parseArray(JsonArray jsonArray) { 90 | final int size = jsonArray.size(); 91 | ArrayList result = new ArrayList(size); 92 | for (int i = 0; i < size; i++) { 93 | result.add(parseElement(jsonArray.get(i))); 94 | } 95 | return result; 96 | } 97 | 98 | private Object parseObject(JsonObject jsonObject) { 99 | HashMap result = new HashMap(); 100 | final Set> entrySet = jsonObject 101 | .entrySet(); 102 | for (Entry property : entrySet) { 103 | result.put(property.getKey(), parseElement(property.getValue())); 104 | } 105 | return result; 106 | } 107 | } 108 | 109 | @Override 110 | protected Map getHeaders() { 111 | final Map headers = new HashMap(); 112 | headers.put("Content-Type", "application/json; charset=utf-8"); 113 | return headers; 114 | } 115 | 116 | @Override 117 | protected HttpEntity getRequestEntity() { 118 | String data = toJson(gson); 119 | HttpEntity entity = null; 120 | try { 121 | entity = new StringEntity(data, "utf-8"); 122 | } catch (UnsupportedEncodingException e) { 123 | Log.e(DeviceHive.TAG, "Failed to create entity", e); 124 | } 125 | return entity; 126 | } 127 | 128 | protected abstract String toJson(final Gson gson); 129 | 130 | protected abstract int fromJson(final String response, final Gson gson, 131 | final Bundle resultData); 132 | 133 | @Override 134 | protected int handleResponse(final String response, 135 | final Bundle resultData, final Context context) { 136 | 137 | return fromJson(response, gson, resultData); 138 | } 139 | 140 | protected static String encodedString(String stringToEncode) { 141 | String encodedString = null; 142 | try { 143 | encodedString = URLEncoder.encode(stringToEncode, "UTF-8"); 144 | } catch (UnsupportedEncodingException e) { 145 | throw new IllegalStateException("String to encode is illegal"); 146 | } 147 | return encodedString; 148 | } 149 | 150 | } 151 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/src/com/dataart/android/devicehive/network/NetworkCommandConfig.java: -------------------------------------------------------------------------------- 1 | package com.dataart.android.devicehive.network; 2 | 3 | import org.apache.http.auth.UsernamePasswordCredentials; 4 | 5 | import android.os.Parcel; 6 | import android.os.Parcelable; 7 | import android.os.ResultReceiver; 8 | 9 | /** 10 | * Network command execution configuration data. 11 | */ 12 | public class NetworkCommandConfig implements Parcelable { 13 | 14 | /** 15 | * Server URL without path component. 16 | */ 17 | public final String baseUrl; 18 | 19 | /** 20 | * Result receiver to receive messages from the service. 21 | */ 22 | public final ResultReceiver resultReceiver; 23 | 24 | /** 25 | * Whether debug logging is enabled or not. 26 | */ 27 | public final boolean isDebugLoggingEnabled; 28 | 29 | private String username; 30 | private String password; 31 | 32 | private static final ClassLoader CLASS_LOADER = NetworkCommandConfig.class 33 | .getClassLoader(); 34 | 35 | /* package */NetworkCommandConfig(String baseUrl, 36 | ResultReceiver resultReceiver, 37 | boolean isDebugLoggingEnabled, String username, String password) { 38 | this.baseUrl = baseUrl; 39 | this.resultReceiver = resultReceiver; 40 | this.isDebugLoggingEnabled = isDebugLoggingEnabled; 41 | this.username = username; 42 | this.password = password; 43 | } 44 | 45 | /** 46 | * Construct {@link NetworkCommandConfig} instance and initialize it with 47 | * given parameters. 48 | * 49 | * @param baseUrl 50 | * Server URL excluding path component. 51 | * @param resultReceiver 52 | * {@link DeviceHiveResultReceiver} instance to receive messages 53 | * from the service. 54 | * @param isDebugLoggingEnabled 55 | * Whether debug logging enabled. 56 | */ 57 | public NetworkCommandConfig(String baseUrl, 58 | DeviceHiveResultReceiver resultReceiver, 59 | boolean isDebugLoggingEnabled) { 60 | this(baseUrl, resultReceiver, isDebugLoggingEnabled, null, null); 61 | } 62 | 63 | /** 64 | * Construct {@link NetworkCommandConfig} instance and initialize it with 65 | * given parameters. 66 | * 67 | * @param baseUrl 68 | * Server URL excluding path component. 69 | * @param resultReceiver 70 | * {@link DeviceHiveResultReceiver} instance to receive messages 71 | * from the service. 72 | */ 73 | public NetworkCommandConfig(String baseUrl, 74 | DeviceHiveResultReceiver resultReceiver) { 75 | this(baseUrl, resultReceiver, false); 76 | } 77 | 78 | /** 79 | * Set Basic Authorization parameters. 80 | * 81 | * @param username 82 | * Username string. 83 | * @param password 84 | * Password string. 85 | */ 86 | public void setBasicAuthorisation(String username, String password) { 87 | this.username = username; 88 | this.password = password; 89 | } 90 | 91 | /** 92 | * Get Basic Authorization parameters. 93 | * 94 | * @return {@link UsernamePasswordCredentials} instance containing Basic 95 | * Authorization data. 96 | */ 97 | public UsernamePasswordCredentials getBasicAuthorisation() { 98 | if (username != null && password != null) { 99 | return new UsernamePasswordCredentials(username, password); 100 | } 101 | return null; 102 | } 103 | 104 | @Override 105 | public int describeContents() { 106 | return 0; 107 | } 108 | 109 | @Override 110 | public void writeToParcel(Parcel dest, int flags) { 111 | dest.writeString(baseUrl); 112 | dest.writeParcelable(resultReceiver, 0); 113 | dest.writeInt(isDebugLoggingEnabled ? 1 : 0); 114 | dest.writeString(username); 115 | dest.writeString(password); 116 | } 117 | 118 | public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { 119 | public NetworkCommandConfig createFromParcel(Parcel source) { 120 | return new NetworkCommandConfig(source.readString(), 121 | (ResultReceiver) source 122 | .readParcelable(CLASS_LOADER), 123 | source.readInt() > 0, source.readString(), 124 | source.readString()); 125 | } 126 | 127 | public NetworkCommandConfig[] newArray(int size) { 128 | return new NetworkCommandConfig[size]; 129 | } 130 | }; 131 | 132 | } 133 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/src/com/dataart/android/devicehive/network/ServiceConnection.java: -------------------------------------------------------------------------------- 1 | package com.dataart.android.devicehive.network; 2 | 3 | import android.bluetooth.BluetoothClass.Device; 4 | import android.content.Context; 5 | import android.os.Bundle; 6 | import android.os.Handler; 7 | import android.os.HandlerThread; 8 | import android.util.Log; 9 | 10 | import com.dataart.android.devicehive.DeviceHive; 11 | 12 | /** 13 | * Abstract base class for service connections. Implements common functionality. 14 | * Descendants are expected to implement specific communication logic. 15 | */ 16 | public abstract class ServiceConnection { 17 | 18 | protected final Context context; 19 | private DeviceHiveResultReceiver resultReceiver; 20 | 21 | protected final static Handler mainThreadHandler = new Handler(); 22 | 23 | protected final static Handler asyncHandler; 24 | 25 | protected String apiEndpointUrl; 26 | protected boolean isDebugLoggingEnabled = false; 27 | 28 | static { 29 | final HandlerThread thread = new HandlerThread( 30 | Device.class.getSimpleName() + "[Handler Thread]"); 31 | thread.start(); 32 | asyncHandler = new Handler(thread.getLooper()); 33 | } 34 | 35 | private final DeviceHiveResultReceiver.ResultListener resultListener = new DeviceHiveResultReceiver.ResultListener() { 36 | @Override 37 | public void onReceiveResult(int code, int tag, Bundle data) { 38 | ServiceConnection.this.onReceiveResult(code, tag, data); 39 | } 40 | }; 41 | 42 | public ServiceConnection(Context context) { 43 | this.context = context; 44 | } 45 | 46 | public void setApiEndpointUrl(String url) { 47 | if (apiEndpointUrl != null && !apiEndpointUrl.equals(url)) { 48 | // detach result listener to avoid receiving responses from old endpoint. 49 | if (resultReceiver != null) { 50 | resultReceiver.detachResultListener(); 51 | resultReceiver = null; 52 | } 53 | } 54 | this.apiEndpointUrl = url; 55 | } 56 | 57 | public String getApiEndpointUrl() { 58 | return apiEndpointUrl; 59 | } 60 | 61 | public void setDebugLoggingEnabled(boolean enabled) { 62 | this.isDebugLoggingEnabled = enabled; 63 | } 64 | 65 | public Context getContext() { 66 | return context; 67 | } 68 | 69 | public void runOnMainThread(Runnable runnable) { 70 | mainThreadHandler.post(runnable); 71 | } 72 | 73 | protected void startNetworkCommand(NetworkCommand command) { 74 | command.start(context, getCommandConfig()); 75 | } 76 | 77 | protected NetworkCommandConfig getCommandConfig() { 78 | final NetworkCommandConfig config = new NetworkCommandConfig( 79 | apiEndpointUrl, getResultReceiver(), isDebugLoggingEnabled); 80 | return config; 81 | } 82 | 83 | protected DeviceHiveResultReceiver getResultReceiver() { 84 | if (resultReceiver == null) { 85 | resultReceiver = new DeviceHiveResultReceiver(); 86 | resultReceiver.setResultListener(resultListener, true); 87 | } 88 | return resultReceiver; 89 | } 90 | 91 | protected void detachResultReceiver() { 92 | if (resultReceiver != null) { 93 | resultReceiver.detachResultListener(); 94 | resultReceiver = null; 95 | } 96 | } 97 | 98 | protected static final int getTagId(final Class tag) { 99 | return getTagId(tag.getName()); 100 | } 101 | 102 | protected static final int getTagId(final String tag) { 103 | return DeviceHiveResultReceiver.getIdForTag(tag); 104 | } 105 | 106 | protected void logD(final String message) { 107 | if (isDebugLoggingEnabled) { 108 | Log.d(DeviceHive.TAG, message); 109 | } 110 | } 111 | 112 | protected abstract void onReceiveResult(final int resultCode, 113 | final int tagId, final Bundle resultData); 114 | } 115 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/src/org/devicehive/glass/NeuralyzerActivity.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | package org.devicehive.glass; 4 | 5 | import java.util.Hashtable; 6 | 7 | import org.devicehive.glass.PhillipsHueDevice.NotificationsListener; 8 | 9 | import com.dataart.android.devicehive.Command; 10 | import com.dataart.android.devicehive.DeviceData; 11 | import com.dataart.android.devicehive.Notification; 12 | import com.dataart.android.devicehive.network.DeviceHiveResultReceiver; 13 | import com.dataart.android.devicehive.network.NetworkCommandConfig; 14 | import com.dataart.android.devicehive.network.DeviceHiveResultReceiver.ResultListener; 15 | //import com.example.devicehive.android.client.sample.BuildConfig; 16 | import com.dataart.devicehive.glass.BuildConfig; 17 | import com.dataart.devicehive.glass.R; 18 | import com.google.gson.Gson; 19 | 20 | import android.app.Activity; 21 | import android.os.Bundle; 22 | import android.os.SystemClock; 23 | import android.view.KeyEvent; 24 | import android.widget.Chronometer; 25 | import android.widget.ImageView; 26 | import android.widget.TextView; 27 | 28 | 29 | public class NeuralyzerActivity extends Activity implements NotificationsListener, ResultListener { 30 | 31 | 32 | private TextView mHint; 33 | private ImageView imageView; 34 | 35 | private long mBase = 0; 36 | private boolean mStarted = false; 37 | 38 | @Override 39 | protected void onCreate(Bundle savedInstanceState) { 40 | super.onCreate(savedInstanceState); 41 | setContentView(R.layout.layout_stopwatch); 42 | 43 | 44 | mHint = (TextView) findViewById(R.id.phrase_hint); 45 | 46 | imageView = (ImageView) findViewById(R.id.image); 47 | 48 | Light(false); 49 | 50 | } 51 | 52 | /** 53 | * Handle the tap event from the touchpad. 54 | */ 55 | 56 | boolean isOn = false; 57 | 58 | @Override 59 | public boolean onKeyDown(int keyCode, KeyEvent event) { 60 | 61 | switch (keyCode) { 62 | // Handle tap events. 63 | 64 | case KeyEvent.KEYCODE_DPAD_CENTER: 65 | case KeyEvent.KEYCODE_ENTER: 66 | 67 | 68 | Light(isOn); 69 | isOn = !isOn; 70 | 71 | 72 | return true; 73 | default: 74 | return super.onKeyDown(keyCode, event); 75 | } 76 | } 77 | 78 | @Override 79 | public void onResume() { 80 | super.onResume(); 81 | if (!mStarted) { 82 | 83 | 84 | } 85 | } 86 | 87 | @Override 88 | public void onPause() { 89 | super.onPause(); 90 | if (mStarted) { 91 | 92 | mStarted = false; 93 | } 94 | } 95 | 96 | @Override 97 | public void onDestroy() { 98 | if (mStarted) { 99 | 100 | mStarted = false; 101 | } 102 | super.onDestroy(); 103 | } 104 | 105 | 106 | 107 | PhillipsHueDevice client; 108 | Command command; 109 | 110 | DeviceHiveResultReceiver resultReceiver; 111 | 112 | public void Light(boolean isOn) { 113 | 114 | mHint.setText(isOn ? R.string.light_off : R.string.light_on); 115 | 116 | imageView.setImageResource(isOn ? R.drawable.light_on : R.drawable.light_off); 117 | 118 | 119 | if(resultReceiver == null) { 120 | resultReceiver = new DeviceHiveResultReceiver(); 121 | resultReceiver.setResultListener(this, true); 122 | 123 | final NetworkCommandConfig config = new NetworkCommandConfig("http://nn2015.pg.devicehive.com/api", 124 | resultReceiver, BuildConfig.DEBUG); 125 | 126 | 127 | } 128 | 129 | 130 | if(client == null) { 131 | client = new PhillipsHueDevice(getApplicationContext()); 132 | 133 | client.setApiEnpointUrl("http://nn2015.pg.devicehive.com/api"); 134 | 135 | client.setDebugLoggingEnabled(BuildConfig.DEBUG); 136 | 137 | client.addNotificationsListener(this); 138 | client.startReceivingNotifications(); 139 | } 140 | 141 | 142 | 143 | if (isOn) { 144 | client.lampOn(); 145 | } 146 | else { 147 | client.lampOff(); 148 | } 149 | 150 | 151 | } 152 | 153 | @Override 154 | public void onReceviceNotification(Notification notification) { 155 | // TODO Auto-generated method stub 156 | System.out.println( notification.toString()); 157 | } 158 | 159 | @Override 160 | public void onReceiveResult(int code, int tag, Bundle data) { 161 | // TODO Auto-generated method stub 162 | 163 | } 164 | } 165 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/glass_app/src/org/devicehive/glass/PhillipsHueDevice.java: -------------------------------------------------------------------------------- 1 | package org.devicehive.glass; 2 | 3 | import java.lang.reflect.Array; 4 | import java.util.ArrayList; 5 | import java.util.Hashtable; 6 | import java.util.LinkedList; 7 | import java.util.List; 8 | 9 | import android.content.Context; 10 | import android.util.Log; 11 | 12 | import com.dataart.android.devicehive.Command; 13 | import com.dataart.android.devicehive.DeviceData; 14 | import com.dataart.android.devicehive.Notification; 15 | import com.dataart.android.devicehive.client.SingleDeviceClient; 16 | 17 | public class PhillipsHueDevice extends SingleDeviceClient { 18 | 19 | private static final String TAG = "SampleDeviceClient"; 20 | 21 | private final List notificationListeners = new LinkedList(); 22 | 23 | private final List commandListeners = new LinkedList(); 24 | 25 | private final List deviceDataListeners = new LinkedList(); 26 | 27 | public PhillipsHueDevice(Context context, DeviceData deviceData) { 28 | super(context, deviceData); 29 | } 30 | 31 | public PhillipsHueDevice(Context context) { 32 | super(context, new DeviceData("8213426c-ecba-4644-9455-1d02be3c4dca", "", "philips hue DEV", null, null)); 33 | 34 | } 35 | 36 | public interface NotificationsListener { 37 | void onReceviceNotification(Notification notification); 38 | } 39 | 40 | public void addNotificationsListener(NotificationsListener listener) { 41 | notificationListeners.add(listener); 42 | } 43 | 44 | public void removeNotificationsListener(NotificationsListener listener) { 45 | notificationListeners.remove(listener); 46 | } 47 | 48 | public interface DeviceDataListener { 49 | void onReloadDeviceDataFinished(); 50 | void onReloadDeviceDataFailed(); 51 | } 52 | 53 | public void addDeviceDataListener(DeviceDataListener listener) { 54 | deviceDataListeners.add(listener); 55 | } 56 | 57 | public void removeDeviceDataListener(DeviceDataListener listener) { 58 | deviceDataListeners.remove(listener); 59 | } 60 | 61 | public interface CommandListener { 62 | void onStartSendindCommand(Command command); 63 | void onFinishSendindCommand(Command command); 64 | void onFailSendindCommand(Command command); 65 | } 66 | 67 | public void addCommandListener(CommandListener listener) { 68 | commandListeners.add(listener); 69 | } 70 | 71 | public void removeCommandListener(CommandListener listener) { 72 | commandListeners.remove(listener); 73 | } 74 | 75 | public void clearAllListeners() { 76 | notificationListeners.clear(); 77 | commandListeners.clear(); 78 | deviceDataListeners.clear(); 79 | } 80 | 81 | @Override 82 | protected void onReceiveNotification(final Notification notification) { 83 | Log.d(TAG, "onReceiveNotification: " + notification); 84 | notifyNotificationListeners(notification); 85 | } 86 | 87 | @Override 88 | protected boolean shouldReceiveNotificationAsynchronously( 89 | Notification notification) { 90 | return false; 91 | } 92 | 93 | @Override 94 | protected void onStartReceivingNotifications() { 95 | Log.d(TAG, "onStartReceivingNotifications"); 96 | } 97 | 98 | @Override 99 | protected void onStopReceivingNotifications() { 100 | Log.d(TAG, "onStopReceivingNotifications"); 101 | } 102 | 103 | @Override 104 | protected void onStartSendingCommand(Command command) { 105 | Log.d(TAG, "onStartSendingCommand: " + command); 106 | notifyCommandListenersStartSending(command); 107 | } 108 | 109 | @Override 110 | protected void onFinishSendingCommand(Command command) { 111 | Log.d(TAG, "onFinishSendingCommand: " + command); 112 | notifyCommandListenersFinishSending(command); 113 | } 114 | 115 | @Override 116 | protected void onFailSendingCommand(Command command) { 117 | Log.d(TAG, "onFailSendingCommand: " + command); 118 | notifyCommandListenersFailSending(command); 119 | } 120 | 121 | @Override 122 | protected void onFinishReloadingDeviceData(DeviceData deviceData) { 123 | notifyReloadDeviceDataFinished(); 124 | } 125 | 126 | @Override 127 | protected void onFailReloadingDeviceData() { 128 | notifyReloadDeviceDataFailed(); 129 | } 130 | 131 | private void notifyNotificationListeners(Notification notification) { 132 | for (NotificationsListener listener : notificationListeners) { 133 | listener.onReceviceNotification(notification); 134 | } 135 | } 136 | 137 | private void notifyCommandListenersStartSending(Command command) { 138 | for (CommandListener listener : commandListeners) { 139 | listener.onStartSendindCommand(command); 140 | } 141 | } 142 | 143 | private void notifyCommandListenersFinishSending(Command command) { 144 | for (CommandListener listener : commandListeners) { 145 | listener.onFinishSendindCommand(command); 146 | } 147 | } 148 | 149 | private void notifyCommandListenersFailSending(Command command) { 150 | for (CommandListener listener : commandListeners) { 151 | listener.onFailSendindCommand(command); 152 | } 153 | } 154 | 155 | private void notifyReloadDeviceDataFinished() { 156 | for (DeviceDataListener listener : deviceDataListeners) { 157 | listener.onReloadDeviceDataFinished(); 158 | } 159 | } 160 | 161 | private void notifyReloadDeviceDataFailed() { 162 | for (DeviceDataListener listener : deviceDataListeners) { 163 | listener.onReloadDeviceDataFailed(); 164 | } 165 | } 166 | 167 | public void getLamps() { 168 | Hashtable parameters = new Hashtable(); 169 | Command command = new Command("getLamps", parameters); 170 | this.sendCommand(command); 171 | } 172 | 173 | public void lightOff() { 174 | Hashtable parameters = new Hashtable(); 175 | 176 | 177 | parameters.put("R", new Integer(0)); 178 | parameters.put("G", new Integer(0)); 179 | parameters.put("B", new Integer(0)); 180 | 181 | parameters.put("DX", new Integer(4)); 182 | parameters.put("DY", new Integer(4)); 183 | parameters.put("DZ", new Integer(4)); 184 | 185 | Command command = new Command("setLamps", parameters); 186 | this.sendCommand(command); 187 | } 188 | 189 | Hashtable createLight(String id, int h, int s, int b, boolean isOn) { 190 | 191 | Hashtable parameters = new Hashtable(); 192 | 193 | 194 | parameters.put("id", id); 195 | parameters.put("hue", new Integer(h)); 196 | parameters.put("sat", new Integer(s)); 197 | parameters.put("bri", new Integer(b)); 198 | 199 | parameters.put("on", new Boolean(isOn)); 200 | 201 | return parameters; 202 | 203 | } 204 | 205 | public void lightRGB(String id, int h, int s, int b, boolean isOn) { 206 | 207 | ArrayList array = new ArrayList(); 208 | 209 | Hashtable parameters = new Hashtable(); 210 | 211 | 212 | parameters.put("id", id); 213 | parameters.put("hue", new Integer(h)); 214 | parameters.put("sat", new Integer(s)); 215 | parameters.put("bri", new Integer(b)); 216 | 217 | parameters.put("on", new Boolean(isOn)); 218 | 219 | 220 | 221 | Command command = new Command("setLamps", parameters); 222 | this.sendCommand(command); 223 | } 224 | 225 | public void lampOn() { 226 | ArrayList array = new ArrayList(); 227 | 228 | 229 | array.add(createLight("3", 55000, 155,125, true)); 230 | array.add(createLight("2", 55000, 155,125, true)); 231 | array.add(createLight("1", 55000, 155,125, true)); 232 | array.add(createLight("4", 55000, 155,125, true)); 233 | 234 | Command command = new Command("setLamps", array); 235 | this.sendCommand(command); 236 | } 237 | 238 | public void lampOff() { 239 | ArrayList array = new ArrayList(); 240 | 241 | 242 | array.add(createLight("3", 55000, 155,125, false)); 243 | array.add(createLight("2", 55000, 155,125, false)); 244 | array.add(createLight("1", 55000, 155,125, false)); 245 | array.add(createLight("4", 55000, 155,125, false)); 246 | 247 | Command command = new Command("setLamps", array); 248 | this.sendCommand(command); 249 | } 250 | 251 | 252 | } 253 | -------------------------------------------------------------------------------- /examples/Glass_PhillipsHue/python_gateway/philips_hue_example.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf8 -*- 3 | # vim:set et tabstop=4 shiftwidth=4 nu nowrap fileencoding=utf-8: 4 | 5 | import sys 6 | import os 7 | import argparse 8 | import urllib2 9 | import json 10 | 11 | from twisted.python import log 12 | from twisted.internet import reactor 13 | 14 | 15 | sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) 16 | 17 | import devicehive.client 18 | import devicehive.auto 19 | import devicehive.interfaces 20 | import devicehive.poll 21 | import devicehive.gateway 22 | import devicehive.gateway.binary 23 | from devicehive import DeviceInfo, Equipment, DeviceClass 24 | 25 | 26 | class BridgeConnector(object): 27 | def __init__(self, ip): 28 | self.ip = ip 29 | 30 | def register_developer(self): 31 | """ 32 | may be errors with this, philips hue documentation is not clear 33 | http://developers.meethue.com/gettingstarted.html 34 | """ 35 | opener = urllib2.build_opener(urllib2.HTTPHandler) 36 | data = { 37 | 'devicetype': 'devicehive_gateway user', 38 | 'username': 'devicehive_gateway' 39 | } 40 | request = urllib2.Request( 41 | url='{0}/api'.format(self.ip), 42 | data=json.dumps(data), 43 | ) 44 | request.add_header('Content-Type', 'application/json') 45 | request.get_method = lambda: 'POST' 46 | response = json.loads(opener.open(request).read()) 47 | success = response[0].get('success') 48 | if success: 49 | self.username = success.get('username') 50 | return True 51 | else: 52 | return False 53 | 54 | def get_lamps(self): 55 | lamps_state = [] 56 | for lamp_id in self.get_lamp_list(): 57 | lamps_state.append( 58 | self.get_lamp_state(lamp_id) 59 | ) 60 | if False in lamps_state: 61 | return False 62 | return lamps_state 63 | 64 | def get_lamp_list(self): 65 | opener = urllib2.build_opener(urllib2.HTTPHandler) 66 | request = urllib2.Request( 67 | url='{0}/api/{1}/lights'.format(self.ip, self.username) 68 | ) 69 | response = json.loads(opener.open(request).read()) 70 | return response.keys() 71 | 72 | def get_lamp_state(self, lamp_id): 73 | opener = urllib2.build_opener(urllib2.HTTPHandler) 74 | request = urllib2.Request( 75 | url='{0}/api/{1}/lights/{2}'.format(self.ip, self.username, lamp_id) 76 | ) 77 | response_raw = json.loads(opener.open(request).read()) 78 | if response_raw.get('error'): 79 | return False 80 | return { 81 | 'id': lamp_id, 82 | 'on': response_raw['state']['on'], 83 | 'hue': response_raw['state']['hue'], 84 | 'bri': response_raw['state']['bri'], 85 | 'sat': response_raw['state']['sat'], 86 | } 87 | 88 | def set_lamps_state(self, lamps_states): 89 | result = [] 90 | for lamp_state in lamps_states: 91 | lamp_id = lamp_state['id'] 92 | del lamp_state['id'] 93 | opener = urllib2.build_opener(urllib2.HTTPHandler) 94 | request = urllib2.Request( 95 | url='{0}/api/{1}/lights/{2}/state'.format(self.ip, self.username, lamp_id), 96 | data=json.dumps(lamp_state), 97 | ) 98 | request.add_header('Content-Type', 'application/json') 99 | request.get_method = lambda: 'PUT' 100 | response = json.loads(opener.open(request).read()) 101 | if type(response) == dict and response.get('error'): 102 | result.append(False) 103 | else: 104 | result.append(True) 105 | if False not in result: 106 | return {'success': True} 107 | else: 108 | return {'success': False} 109 | 110 | 111 | DEVICE_INFO = DeviceInfo( 112 | id='8213426c-ecba-4644-9455-1d02be3c4dca', 113 | key='6e419dd8-1fcd-45a5-9365-bc498ac81caa', 114 | name='philips hue DEV', 115 | equipment=[Equipment(name='philips HUE equip', code='555', type='lamp'), ], 116 | device_class=DeviceClass(name='PhilipsHue', version='0.1') 117 | ) 118 | 119 | 120 | class PhilipsHueGateway(devicehive.gateway.BaseGateway): 121 | devices = { 122 | 'main': DEVICE_INFO 123 | } 124 | 125 | def __init__(self, url, factory_cls, bridge_ip): 126 | self.bridge_connector = BridgeConnector(bridge_ip) 127 | super(PhilipsHueGateway, self).__init__(url, factory_cls) 128 | 129 | def registration_received(self, device_info): 130 | print 'Registration received from device.' 131 | transport = devicehive.client.ws.WebSocketFactory() 132 | transport.connect('http://nn2015.pg.devicehive.com/api') 133 | super(PhilipsHueGateway, self).registration_received(device_info) 134 | 135 | def notification_received(self, device_info, notification): 136 | super(PhilipsHueGateway, self).notification_received(device_info, notification) 137 | 138 | def do_command(self, sender, command, finish_deferred): 139 | if command.command == 'getLamps': 140 | result = self.bridge_connector.get_lamps() 141 | if result: 142 | finish_deferred.callback(devicehive.CommandResult('Completed', result)) 143 | else: 144 | self.factory.notify('errorNotification', {'errorId': 3, 'txt': "can't get lamp list"}) 145 | 146 | elif command.command == 'setLamps': 147 | result = self.bridge_connector.set_lamps_state(command.parameters) 148 | if result: 149 | finish_deferred.callback(devicehive.CommandResult('Completed', result)) 150 | else: 151 | self.factory.notify('errorNotification', {'errorId': 2, 'txt': "can't set params"}) 152 | 153 | def on_connected(self): 154 | self.connected = True 155 | for key in self.devices: 156 | self.connect_device(self.devices[key]) 157 | if self.bridge_connector.register_developer(): 158 | self.factory.notify('connectionInfo', {'success': True}) 159 | else: 160 | self.factory.notify('errorNotification', {'errorId': 1, 'txt': "can't connect to Phillips hue"},) 161 | 162 | def run(self, device_factory): 163 | self.device_factory = device_factory 164 | 165 | 166 | def main(bridge_ip): 167 | log.startLogging(sys.stdout) 168 | gateway = PhilipsHueGateway('http://nn2015.pg.devicehive.com/api', devicehive.auto.AutoFactory, bridge_ip) 169 | #factory to be used to organize communication channel to device 170 | bin_factory = devicehive.gateway.binary.BinaryFactory(gateway) 171 | # run gateway application 172 | gateway.run(bin_factory) 173 | reactor.run() 174 | 175 | 176 | if __name__ == '__main__': 177 | parser = argparse.ArgumentParser() 178 | #for 179 | parser.add_argument('-i', '--ip', type=str, default='http://127.0.0.1:5000', dest='bridge_id', required=False, help='bridge ip') 180 | r = parser.parse_args() 181 | main(r.bridge_id) 182 | 183 | 184 | -------------------------------------------------------------------------------- /examples/RainbowCube/firmware/firmware.ino: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define CMD_STATUS_SUCCESS "Success" 5 | #define CMD_STATUS_FAIL "Failed" 6 | 7 | #define ERR_OK "OK" 8 | #define ERR_UNKNOWN_CMD "Unknown command" 9 | #define ERR_INVALID_VALUE "Invalid data" 10 | #define ERR_TIMEOUT "Failed to retrieve command due to timeout" 11 | #define ERR_CHECKSUM "Invalid checksum" 12 | #define ERR_UNREG "Is not registered" 13 | 14 | static const char *REG_INFO = "{" 15 | "id:\"b125698d-61bd-40d7-b65e-e1f86852a166\"," 16 | "key:\"LED_cube\"," 17 | "name:\"LED Cube\"," 18 | "deviceClass:{" 19 | "name:\"LED_cube\"," 20 | "version:\"1.0\"}," 21 | "equipment:[{code:\"cube\",name:\"cube\",type:\"LED_Cube\"}]," 22 | "commands:[" 23 | "{intent:257,name:\"pixel\",params:{X:u8,Y:u8,Z:u8,R:u8,G:u8,B:u8}}," 24 | "{intent:258,name:\"pixels\",params:[{X:u8,Y:u8,Z:u8,R:u8,G:u8,B:u8}]}," 25 | "{intent:259,name:\"fill\",params:{R:u8,G:u8,B:u8}}" 26 | "]," 27 | "notifications:[]" 28 | "}"; 29 | 30 | 31 | /** 32 | * Write data into USART 33 | */ 34 | static int transmit_data(const uint8_t * buff, int len) 35 | { 36 | return Serial.write(buff, len); 37 | } 38 | 39 | /** 40 | * Read characters from USART module 41 | */ 42 | static int receive_data(uint8_t * buff, int len) 43 | { 44 | for (int i = 0; i < len; ++i) 45 | { 46 | do { /* nothing */ } 47 | while (!Serial.available()); 48 | 49 | buff[i] = Serial.read(); 50 | } 51 | return len; 52 | } 53 | 54 | 55 | /** 56 | * Handles registration request 57 | */ 58 | void do_reqreg_command(void) 59 | { 60 | if (RecvAndValidateChecksum()) 61 | { 62 | SendRegistration2Data(REG_INFO); 63 | } 64 | else 65 | SendNotificationData(0, CMD_STATUS_FAIL, ERR_CHECKSUM); 66 | } 67 | 68 | 69 | struct Pixel 70 | { 71 | BYTE X; 72 | BYTE Y; 73 | BYTE Z; 74 | BYTE R; 75 | BYTE G; 76 | BYTE B; 77 | }; 78 | 79 | //static int Pixel_size_check[(sizeof(Pixel)==6) ? 1 : -1]; 80 | 81 | /** 82 | * Handles PIXEL command 83 | */ 84 | void do_pixel_command(void) 85 | { 86 | DWORD code = 0; 87 | if (sizeof(code) == RecvBytes((BYTE*)&code, sizeof(code))) 88 | { 89 | Pixel body; 90 | if (sizeof(body) == RecvBytes((BYTE*)&body, sizeof(body))) 91 | { 92 | if (RecvAndValidateChecksum()) 93 | { 94 | Rb.setPixelZXY(body.Z, body.X, body.Y, 95 | body.R, body.G, body.B); 96 | 97 | SendNotificationData(code, CMD_STATUS_SUCCESS, ERR_OK); 98 | } 99 | else 100 | SendNotificationData(code, CMD_STATUS_FAIL, ERR_CHECKSUM); 101 | } 102 | else 103 | SendNotificationData(code, CMD_STATUS_FAIL, ERR_INVALID_VALUE); 104 | } 105 | else 106 | SendNotificationData(0, CMD_STATUS_FAIL, ERR_TIMEOUT); 107 | } 108 | 109 | 110 | /** 111 | * Handles PIXELS command 112 | */ 113 | void do_pixels_command(void) 114 | { 115 | DWORD code = 0; 116 | if (sizeof(code) == RecvBytes((BYTE*)&code, sizeof(code))) 117 | { 118 | // TODO: read body - array of pixels 119 | WORD i, count = 0; 120 | if (sizeof(count) == RecvBytes((BYTE*)&count, sizeof(count))) 121 | { 122 | for (i = 0; i < count; ++i) 123 | { 124 | Pixel body; 125 | if (sizeof(body) == RecvBytes((BYTE*)&body, sizeof(body))) 126 | { 127 | // execute before checksum verification??? 128 | Rb.setPixelZXY(body.Z, body.X, body.Y, 129 | body.R, body.G, body.B); 130 | } 131 | else 132 | SendNotificationData(code, CMD_STATUS_FAIL, ERR_INVALID_VALUE); 133 | } 134 | 135 | if (RecvAndValidateChecksum()) 136 | { 137 | SendNotificationData(code, CMD_STATUS_SUCCESS, ERR_OK); 138 | } 139 | else 140 | SendNotificationData(code, CMD_STATUS_FAIL, ERR_CHECKSUM); 141 | } 142 | else 143 | SendNotificationData(0, CMD_STATUS_FAIL, ERR_TIMEOUT); 144 | } else 145 | SendNotificationData(0, CMD_STATUS_FAIL, ERR_TIMEOUT); 146 | } 147 | 148 | 149 | /** 150 | * Handles FILL command 151 | */ 152 | void do_fill_command(void) 153 | { 154 | DWORD code = 0; 155 | if (sizeof(code) == RecvBytes((BYTE*)&code, sizeof(code))) 156 | { 157 | BYTE body[3]; 158 | if (sizeof(body) == RecvBytes(body, sizeof(body))) 159 | { 160 | if (RecvAndValidateChecksum()) 161 | { 162 | const BYTE R = body[0]; 163 | const BYTE G = body[1]; 164 | const BYTE B = body[2]; 165 | 166 | for (int x = 0; x < 4; ++x) 167 | for (int y = 0; y < 4; ++y) 168 | for (int z = 0; z < 4; ++z) 169 | { 170 | Rb.setPixelZXY(z, x, y, R, G, B); 171 | } 172 | 173 | SendNotificationData(code, CMD_STATUS_SUCCESS, ERR_OK); 174 | } 175 | else 176 | SendNotificationData(code, CMD_STATUS_FAIL, ERR_CHECKSUM); 177 | } 178 | else 179 | SendNotificationData(code, CMD_STATUS_FAIL, ERR_INVALID_VALUE); 180 | } 181 | else 182 | SendNotificationData(0, CMD_STATUS_FAIL, ERR_TIMEOUT); 183 | } 184 | 185 | 186 | /** 187 | Initializes the Arduino firmware. 188 | */ 189 | void setup(void) 190 | { 191 | Rb.init(); // initialize Rainbowduino driver 192 | Rb.blankDisplay(); 193 | 194 | Serial.begin(9600); 195 | InitializeDeviceHive(&transmit_data, &receive_data); 196 | 197 | SendRegistration2Data(REG_INFO); 198 | } 199 | 200 | 201 | /** 202 | Loop procedure is called continuously. 203 | */ 204 | void loop(void) 205 | { 206 | if (0 < Serial.available()) 207 | { 208 | MessageHeader msg_hdr; 209 | if (ReceiveMessageHeader(&msg_hdr)) 210 | { 211 | switch (msg_hdr.Intent) 212 | { 213 | case G2D_REQREG: 214 | do_reqreg_command(); 215 | break; 216 | 217 | case 257: 218 | do_pixel_command(); 219 | break; 220 | 221 | case 258: 222 | do_pixels_command(); 223 | break; 224 | 225 | case 259: 226 | do_fill_command(); 227 | break; 228 | 229 | default: // unknownw message, just skip it 230 | SkipMessage(msg_hdr.Length); 231 | SendNotificationData(0, CMD_STATUS_FAIL, ERR_UNKNOWN_CMD); 232 | break; 233 | } 234 | } 235 | } 236 | } 237 | -------------------------------------------------------------------------------- /examples/RainbowCube/html/cube.html: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | LED Cube DeviceHive 5 | 6 | 7 | 74 | 123 | 124 | 125 | 126 | 127 |

LOADING... 128 |

129 | 130 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 161 | 162 | 163 | 164 | -------------------------------------------------------------------------------- /examples/RainbowCube/html/js/app.js: -------------------------------------------------------------------------------- 1 | (function () { 2 | window.config = { 3 | serverUrl: '[DeviceHive_api_url]', 4 | login: '[DeviceHive_login]', 5 | password: '[DeviceHive_Password]', 6 | deviceId: '[Device_Id]', 7 | cmdTimeout: 1000 * 60 * 2, //2 minutes 8 | ledCmdName: 'pixels', 9 | cubeSize: 4 10 | }; 11 | 12 | 13 | var deviceHive = new DeviceHive(config.serverUrl, config.login, config.password), 14 | currentTimeout; 15 | 16 | var deviceIdElem = $('.deviceId'), 17 | deviceNameElem = $('.device-name'), 18 | deviceStatusElem = $('.device-status'), 19 | cmdInfoElem = $('.cmdInfo'), 20 | colorPickerElem = $('#colorpicker'), 21 | actionsElem = $('.actions'); 22 | 23 | var fillQube = function (leftX, leftY, leftZ, width, height, depth, r, g, b) { 24 | if (!width || !height || !depth || leftX + width > config.cubeSize || leftY + depth > config.cubeSize || leftZ + height > config.cubeSize) { 25 | throw "Cannot fill the Cube."; 26 | } 27 | 28 | var result = []; 29 | 30 | for (var i = 0; i < leftX + width; i++) { 31 | for (var j = 0; j < leftY + depth; j++) { 32 | for (var k = 0; k < leftZ + height; k++) { 33 | result.push({ 34 | X: '' + i, 35 | Y: '' + j, 36 | Z: '' + k, 37 | R: '' + r, 38 | G: '' + g, 39 | B: '' + b 40 | }); 41 | } 42 | } 43 | } 44 | 45 | return result; 46 | }; 47 | 48 | var handleError = function (xhr, textStatus, error) { 49 | cmdInfoElem.hide(); 50 | if ($.type(xhr) === 'string') { 51 | $('.loading').text('Device is unplugged or not registered. Please register and plug-in your device and then reload this page.'); 52 | return; 53 | } 54 | alert('An error occured: ' + textStatus + '. Error info: ' + JSON.stringify(error)); 55 | }; 56 | 57 | var sendCommand = function (deviceId, commandName, params, timeout) { 58 | var dfdResult = $.Deferred(); 59 | 60 | deviceHive.sendCommand(deviceId, commandName, params).result(function (commandData) { 61 | var command = commandData; 62 | command.status === 'Failed' 63 | ? dfdResult.reject(null, command.status, command) 64 | : dfdResult.resolve(command); 65 | }); 66 | 67 | if (currentTimeout) { 68 | clearTimeout(currentTimeout); 69 | } 70 | 71 | currentTimeout = setTimeout(function () { 72 | dfdResult.rejectWith(null, [null, 'Timeout expired', 'timeout']); 73 | }, timeout || config.deviceHive.defaultNotificationTimeout); 74 | 75 | return dfdResult; 76 | }; 77 | 78 | var buttonClickHandler = function (pos) { 79 | return function () { 80 | cmdInfoElem.fadeOut(function () { 81 | cmdInfoElem.text('Pending...'); 82 | cmdInfoElem.fadeIn(); 83 | 84 | var rgb = colorPickerElem.spectrum("get").toRgb(); 85 | 86 | var cubeParams = fillQube(0, 0, 0, pos + 1, pos + 1, pos + 1, rgb.r, rgb.g, rgb.b); 87 | sendCommand(config.deviceId, config.ledCmdName, cubeParams, config.cmdTimeout).done(function (command) { 88 | cmdInfoElem.text(JSON.stringify(command.command.result)); 89 | }).fail(handleError); 90 | 91 | }); 92 | }; 93 | }; 94 | 95 | var createActions = function () { 96 | for (var i = 0; i < 4; i++) { 97 | var button = $('').attr('id', 'actionButton' + i).attr('type', 'button').val(i + 1); 98 | button.click(buttonClickHandler(i)); 99 | 100 | actionsElem.append(button); 101 | } 102 | }; 103 | 104 | window.app = { 105 | init: function () { 106 | deviceIdElem.text('Device Id: ' + config.deviceId); 107 | return deviceHive.openChannel().then(function () { 108 | return deviceHive.getDevice(config.deviceId); 109 | }).then(function (device) { 110 | deviceNameElem.text(device.name); 111 | deviceStatusElem.text(device.status); 112 | 113 | colorPickerElem.spectrum({ 114 | color: "#ECC", 115 | showInput: true, 116 | className: "colorpicker", 117 | preferredFormat: "hex", 118 | flat: true 119 | }); 120 | 121 | createActions(); 122 | 123 | return $('.loading').fadeOut().promise(); 124 | 125 | }).then(function () { 126 | return $('.main').fadeIn().promise(); 127 | }).fail(handleError); 128 | } 129 | }; 130 | })() -------------------------------------------------------------------------------- /examples/wifi_config/Makefile: -------------------------------------------------------------------------------- 1 | # use CROSS_COMPILE variable to set toolchain (empty by default): 2 | # >make CROSS_COMPILE=arm-linux-gnueabi- 3 | 4 | # build variant: 'debug' or 'release' (by default) 5 | # to change use VARIANT variable: 6 | # >make VARIANT=debug 7 | # >make VARIANT=release 8 | variant:=release 9 | ifdef VARIANT 10 | ifeq '${VARIANT}' 'release' 11 | variant:=release 12 | else ifeq '${VARIANT}' 'debug' 13 | variant:=debug 14 | else 15 | $(error '${VARIANT}' is unknown variant, expected: release or debug) 16 | endif 17 | endif 18 | 19 | # platform helper 20 | ifdef PLATFORM 21 | platform=${PLATFORM} 22 | else 23 | platform:=$(shell uname -m) 24 | endif 25 | 26 | 27 | ifeq '${variant}' 'debug' 28 | defines+=-D_DEBUG 29 | defines+=-g 30 | else # default 31 | defines+=-DNDEBUG 32 | defines+=-Os 33 | endif 34 | 35 | 36 | CXXFLAGS+=-Wall ${include_dirs} ${defines} -std=gnu++0x 37 | #CXXFLAGS+=-fdata-sections -ffunction-sections 38 | #LDFLAGS+=-Wl,--gc-sections -pthread -L${ex_libs} 39 | 40 | 41 | server: main.cpp exec.hpp gpiopin.hpp server.hpp wireless.hpp 42 | g++ -o server main.cpp ${CXXFLAGS} ${LDFLAGS} \ 43 | -liw -lmongoose -lmongocpp 44 | 45 | 46 | ######################################################### 47 | # clean all the object files and applications 48 | clean: 49 | @rm -rf *.o 50 | @rm -f server 51 | 52 | 53 | .PHONY: clean 54 | -------------------------------------------------------------------------------- /examples/wifi_config/exec.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | 6 | 7 | std::string exec(const std::string& cmd) 8 | { 9 | std::string result; 10 | 11 | FILE* pipe = popen(cmd.c_str(), "r"); 12 | if (!pipe) return "ERROR"; 13 | 14 | char buffer[128]; 15 | while(!feof(pipe)) { 16 | if(fgets(buffer, 128, pipe) != NULL) 17 | result += buffer; 18 | } 19 | pclose(pipe); 20 | 21 | return result; 22 | } 23 | -------------------------------------------------------------------------------- /examples/wifi_config/gpiopin.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | #ifdef __linux__ 8 | #include 9 | #endif // __linux__ 10 | 11 | class GPIOPin 12 | { 13 | public: 14 | enum DIRECTION 15 | { 16 | IN, 17 | OUT, 18 | NOT_SET 19 | }; 20 | 21 | GPIOPin(int pin):m_pin(pin), m_dir(NOT_SET), m_exported(false) 22 | { 23 | m_exported = exportPin(); 24 | std::stringstream str; 25 | str << "/sys/class/gpio/gpio" << pin << "/value"; 26 | str >> val_path; 27 | str << "/sys/class/gpio/gpio" << pin << "/direction"; 28 | str >> dir_path; 29 | } 30 | 31 | ~GPIOPin() 32 | { 33 | if (m_exported) 34 | { 35 | unexportPin(); 36 | } 37 | } 38 | 39 | void set(DIRECTION dir) 40 | { 41 | if (m_dir != dir) 42 | { 43 | m_dir = dir; 44 | std::ofstream diros(dir_path); 45 | switch (m_dir) 46 | { 47 | case IN: 48 | diros << "in"; 49 | break; 50 | case OUT: 51 | diros << "out"; 52 | break; 53 | default: 54 | break; 55 | } 56 | 57 | diros.close(); 58 | } 59 | } 60 | 61 | inline int read() 62 | { 63 | int res =-1; 64 | if (!m_exported) 65 | return res; 66 | 67 | if (m_dir != IN) 68 | set(IN); 69 | 70 | FILE* file = fopen(val_path.c_str(), "r"); 71 | if (file == NULL) 72 | return res; 73 | 74 | char buf; 75 | if (fread(&buf, 1, 1, file)) 76 | res = int(buf)-48;//"0" 77 | fclose(file); 78 | return res; 79 | } 80 | 81 | bool write(int val) 82 | { 83 | bool res = false; 84 | if (!m_exported) 85 | return res; 86 | 87 | if (m_dir != OUT) 88 | set(OUT); 89 | 90 | std::ofstream valfs(val_path); 91 | if (valfs.good()) 92 | { 93 | valfs << val; 94 | res = true; 95 | } 96 | 97 | valfs.close(); 98 | return res; 99 | } 100 | 101 | bool exportPin() 102 | { 103 | std::ofstream exportfs("/sys/class/gpio/export"); 104 | if (!exportfs.good()) 105 | return false; 106 | 107 | exportfs << m_pin; 108 | exportfs.close(); 109 | return true; 110 | } 111 | 112 | bool unexportPin() 113 | { 114 | std::ofstream unexportfs("/sys/class/gpio/unexport"); 115 | if (!unexportfs.good()) 116 | return false; 117 | 118 | unexportfs << m_pin; 119 | unexportfs.close(); 120 | return true; 121 | } 122 | 123 | private: 124 | 125 | int m_pin; 126 | DIRECTION m_dir; 127 | std::string val_path, dir_path; 128 | bool m_exported; 129 | }; 130 | -------------------------------------------------------------------------------- /examples/wifi_config/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | SetUp WiFi 4 | 41 | 42 | 43 |
44 |
45 | Setup WiFi 46 | 47 | 50 | 51 | 56 | 57 | 58 | 59 | 60 |
61 |
62 | 63 | 101 | 102 | 103 | -------------------------------------------------------------------------------- /examples/wifi_config/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | 17 | #include "gpiopin.hpp" 18 | #include "wireless.hpp" 19 | #include "server.hpp" 20 | 21 | bool sigusr1 = false; 22 | 23 | void sig_handler(int sig) 24 | { 25 | sigusr1 = true; 26 | }; 27 | 28 | 29 | int main() 30 | { 31 | pid_t pid, sid; 32 | 33 | pid = fork(); 34 | if (pid < 0) { 35 | exit(EXIT_FAILURE); 36 | } 37 | 38 | if (pid > 0) { 39 | exit(EXIT_SUCCESS); 40 | } 41 | 42 | umask(0); 43 | 44 | sid = setsid(); 45 | if (sid < 0) { 46 | return 1; 47 | } 48 | 49 | if ((chdir("/")) < 0) { 50 | return 1; 51 | } 52 | 53 | close(STDIN_FILENO); 54 | close(STDOUT_FILENO); 55 | close(STDERR_FILENO); 56 | 57 | struct sigaction sig_struct; 58 | memset (&sig_struct, '\0', sizeof(sig_struct)); 59 | sig_struct.sa_handler = sig_handler; 60 | sig_struct.sa_flags = 0; 61 | sigset_t set; 62 | sigemptyset(&set); 63 | sigaddset(&set, SIGUSR1); 64 | sig_struct.sa_mask = set; 65 | if (sigaction(SIGUSR1, &sig_struct, NULL) == -1){ 66 | return 1; 67 | } 68 | 69 | GPIOServer server; 70 | server.setOption("document_root", "html"); 71 | server.setOption("listening_ports", "8080"); 72 | server.setOption("num_threads", "5"); 73 | server.start(); 74 | 75 | GPIOPin gpio3(3); 76 | int oldv = -1; 77 | while (true) 78 | { 79 | if (sigusr1) 80 | break; 81 | 82 | int newv = gpio3.read(); 83 | if (newv != oldv) 84 | { 85 | oldv = newv; 86 | switch (newv) 87 | { 88 | case 0: 89 | setAP(); 90 | break; 91 | case 1: 92 | setCli(); 93 | break; 94 | default: 95 | break; 96 | } 97 | } 98 | 99 | sleep(2); 100 | } 101 | 102 | server.stop(); 103 | return 0; 104 | } 105 | -------------------------------------------------------------------------------- /examples/wifi_config/readme: -------------------------------------------------------------------------------- 1 | server binary is pre-built for RPi 2 | 3 | Build dependencies: 4 | 5 | 1. wireless tools (http://www.hpl.hp.com/personal/Jean_Tourrilhes/Linux/Tools.html) 6 | 2. mongoose server (https://code.google.com/p/mongoose/) 7 | 3. mongocpp (http://code.google.com/r/vpiotr-mongoose-cpp/) -------------------------------------------------------------------------------- /examples/wifi_config/server: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devicehive/framework/2a7dac8332209f3f2faed82c5184ef990f7fbc91/examples/wifi_config/server -------------------------------------------------------------------------------- /examples/wifi_config/server.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | #include "exec.hpp" 9 | 10 | class GPIOServer: public mongoose::MongooseServer { 11 | public: 12 | GPIOServer(): mongoose::MongooseServer() {} 13 | virtual ~GPIOServer() {} 14 | protected: 15 | virtual bool handleEvent(mongoose::ServerHandlingEvent eventCode, 16 | mongoose::MongooseConnection &connection, 17 | const mongoose::MongooseRequest &request, 18 | mongoose::MongooseResponse &response) 19 | { 20 | bool res = false; 21 | if (eventCode == MG_NEW_REQUEST) { 22 | res = true; 23 | handleInfo(request,response ); 24 | } 25 | 26 | return res; 27 | } 28 | 29 | void handleInfo(const mongoose::MongooseRequest &request, 30 | mongoose::MongooseResponse &response) 31 | { 32 | auto s = request.getQueryString(); 33 | auto m = parseQueryString(s); 34 | 35 | if (m.find("networkName") != m.end() && m.find("encryptionType") != m.end()) 36 | { 37 | setWPA(m["networkName"], m["key"], encType(m["encryptionType"])); 38 | } 39 | 40 | response.setStatus(200); 41 | response.setConnectionAlive(false); 42 | response.setCacheDisabled(); 43 | response.setContentType("text/html"); 44 | response.addContent(generateInfoContent(request, m["networkName"])); 45 | response.write(); 46 | } 47 | 48 | const std::string generateInfoContent(const mongoose::MongooseRequest &request, const std::string &cur = std::string()) 49 | { 50 | std::string result; 51 | auto essidlist = iwlist(); 52 | std::string networks; 53 | 54 | std::string curNetwork; 55 | if (cur.empty()) 56 | { 57 | curNetwork = exec("/sbin/iwconfig wlan0"); 58 | std::string::size_type pos = curNetwork.find("ESSID:\""); 59 | if (pos != std::string::npos) 60 | { 61 | pos += strlen("ESSID:\""); 62 | curNetwork=curNetwork.substr(pos,curNetwork.find('\"', pos+1)-pos); 63 | } 64 | } 65 | else 66 | curNetwork = cur; 67 | 68 | for(auto it = essidlist.begin(); it != essidlist.end(); ++it) 69 | { 70 | networks += "" +*it+""); 74 | } 75 | 76 | std::ifstream t("/home/pi/test/index.html"); 77 | std::stringstream buffer; 78 | buffer << t.rdbuf(); 79 | result = buffer.str(); 80 | result.replace(result.find(""),strlen(""), networks); 81 | 82 | return result; 83 | } 84 | private: 85 | static void tokenize(const std::string& str, std::vector& tokens, 86 | const std::string& delimiters = " ", bool trimEmpty = false) 87 | { 88 | std::string::size_type pos, lastPos = 0; 89 | while(true) 90 | { 91 | pos = str.find_first_of(delimiters, lastPos); 92 | if(pos == std::string::npos) 93 | { 94 | pos = str.length(); 95 | 96 | if(pos != lastPos || !trimEmpty) 97 | tokens.push_back(urldecode(std::string(str.data()+lastPos,pos-lastPos))); 98 | 99 | break; 100 | } 101 | else 102 | { 103 | if(pos != lastPos || !trimEmpty) 104 | tokens.push_back(urldecode(std::string(str.data()+lastPos,pos-lastPos))); 105 | } 106 | 107 | lastPos = pos + 1; 108 | } 109 | }; 110 | 111 | static std::map parseQueryString(const std::string &query) 112 | { 113 | std::vector vec; 114 | std::map res; 115 | 116 | tokenize(query, vec, "&"); 117 | std::for_each(vec.begin(), vec.end(), [&](const std::string& s) 118 | { 119 | std::vector vec; 120 | tokenize(s, vec, "="); 121 | if (vec.size()==2) 122 | res[vec[0]] = vec[1]; 123 | }); 124 | 125 | return res; 126 | } 127 | 128 | static std::string urldecode(const std::string &src) 129 | { 130 | std::string dst; 131 | dst.reserve(src.length()); 132 | char a, b; 133 | for(size_t i = 0, n = src.length(); i < n; ++i) 134 | { 135 | a = src[i]; 136 | switch (a) 137 | { 138 | case '%': 139 | a = src[i++]; 140 | b = src[i++]; 141 | if (a && b && isxdigit(a) && isxdigit(b)) 142 | { 143 | if (a >= 'a') 144 | a -= 'A'-'a'; 145 | if (a >= 'A') 146 | a -= ('A' - 10); 147 | else 148 | a -= '0'; 149 | if (b >= 'a') 150 | b -= 'A'-'a'; 151 | if (b >= 'A') 152 | b -= ('A' - 10); 153 | else 154 | b -= '0'; 155 | dst.push_back(16*a+b); 156 | } 157 | case '+': 158 | dst.push_back(' '); 159 | break; 160 | default: 161 | dst.push_back(a); 162 | break; 163 | } 164 | } 165 | return dst; 166 | } 167 | }; 168 | -------------------------------------------------------------------------------- /examples/wifi_config/wireless.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | #include "exec.hpp" 8 | 9 | std::set iwlist(void) 10 | { 11 | std::set res; 12 | 13 | wireless_scan_head head; 14 | wireless_scan *result; 15 | iwrange range; 16 | int sock; 17 | 18 | 19 | /* Open socket to kernel */ 20 | sock = iw_sockets_open(); 21 | 22 | /* Get some metadata to use for scanning */ 23 | if (iw_get_range_info(sock, "wlan0", &range) < 0) { 24 | printf("Error during iw_get_range_info. Aborting.\n"); 25 | return res; 26 | } 27 | 28 | /* Perform the scan */ 29 | if (iw_scan(sock, "wlan0", range.we_version_compiled, &head) < 0) { 30 | printf("Error during iw_scan. Aborting.\n"); 31 | return res; 32 | } 33 | 34 | /* Traverse the results */ 35 | result = head.result; 36 | while (NULL != result) { 37 | std::stringstream ss; 38 | ss << result->b.essid; 39 | //if ((result->b.key_flags & IW_ENCODE_DISABLED) == IW_ENCODE_DISABLED) 40 | if (result->b.has_key) 41 | ss << " enc"; 42 | res.insert(ss.str()); 43 | 44 | result = result->next; 45 | } 46 | 47 | return res; 48 | } 49 | 50 | enum ENC 51 | { 52 | NONE, 53 | WEP, 54 | WPA 55 | }; 56 | 57 | ENC encType(const std::string& enctype) 58 | { 59 | ENC res = NONE; 60 | if (enctype == "WPA") 61 | res = WPA; 62 | else if (enctype == "WEP") 63 | res = WEP; 64 | 65 | return res; 66 | } 67 | 68 | void setWPA(const std::string& essid, const std::string& key, ENC enc) 69 | { 70 | if (essid.empty() || (enc != NONE && key.empty())) 71 | return; 72 | 73 | std::ofstream wpa_conf_os("/etc/wpa_supplicant/wpa_supplicant.conf"); 74 | wpa_conf_os << "network={\n"; 75 | wpa_conf_os << "\tssid=\"" << essid << "\"\n"; 76 | switch (enc) 77 | { 78 | case WPA: 79 | wpa_conf_os << "\tpsk=\"" << key << "\"\n"; 80 | break; 81 | case WEP: 82 | wpa_conf_os << "\twep_key0=\"" << key << "\"\n"; 83 | wpa_conf_os << "\twep_tx_keyidx=0\n"; 84 | //continue 85 | case NONE: 86 | wpa_conf_os << "\tkey_mgmt=NONE\n"; 87 | break; 88 | default: 89 | break; 90 | } 91 | wpa_conf_os << "}\n"; 92 | wpa_conf_os.close(); 93 | } 94 | 95 | void setAP() 96 | { 97 | exec("/sbin/ifdown wlan0"); 98 | exec("/usr/sbin/service hostapd stop"); 99 | exec("/usr/sbin/service udhcpd stop"); 100 | 101 | std::ofstream interfaces("/etc/network/interfaces"); 102 | interfaces << "auto lo\n\n"; 103 | interfaces << "iface lo inet loopback\n"; 104 | interfaces << "iface eth0 inet dhcp\n\n"; 105 | interfaces << "auto wlan0\n"; 106 | interfaces << "iface wlan0 inet static\n"; 107 | interfaces << "address 10.0.0.1\n"; 108 | interfaces << "netmask 255.255.255.0\n\n"; 109 | interfaces << "up iptables-restore < /etc/iptables.ipv4.nat\n"; 110 | 111 | interfaces.close(); 112 | 113 | exec("/sbin/ifup wlan0"); 114 | exec("/usr/sbin/service hostapd start"); 115 | exec("/usr/sbin/service udhcpd start"); 116 | } 117 | 118 | void setCli() 119 | { 120 | exec("/sbin/ifdown wlan0"); 121 | exec("/usr/sbin/service hostapd stop"); 122 | exec("/usr/sbin/service udhcpd stop"); 123 | 124 | std::ofstream interfaces("/etc/network/interfaces"); 125 | interfaces << "auto lo\n\n"; 126 | interfaces << "iface lo inet loopback\n"; 127 | interfaces << "iface eth0 inet dhcp\n\n"; 128 | interfaces << "auto wlan0\n"; 129 | interfaces << "iface wlan0 inet dhcp\n"; 130 | interfaces << "wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf\n"; 131 | interfaces << "iface default inet dhcp\n"; 132 | 133 | interfaces.close(); 134 | 135 | exec("/sbin/ifup wlan0"); 136 | } --------------------------------------------------------------------------------