diff --git a/enos-http-sdk/pom.xml b/enos-http-sdk/pom.xml index e302fb5..397cc02 100644 --- a/enos-http-sdk/pom.xml +++ b/enos-http-sdk/pom.xml @@ -10,7 +10,7 @@ enos-http - 0.2.1 + 2.4.0 jar diff --git a/enos-http-sdk/src/main/java/com/envisioniot/enos/iot_http_sdk/file/FileFormData.java b/enos-http-sdk/src/main/java/com/envisioniot/enos/iot_http_sdk/file/FileFormData.java index 3605e5f..7cdf9c0 100644 --- a/enos-http-sdk/src/main/java/com/envisioniot/enos/iot_http_sdk/file/FileFormData.java +++ b/enos-http-sdk/src/main/java/com/envisioniot/enos/iot_http_sdk/file/FileFormData.java @@ -70,7 +70,7 @@ public static Part createFormData(@NonNull UploadFileInfo fileInfo) throws IOExc .addUnsafeNonAscii("Content-MD5", md5(fileInfo.getFile())) .build(); - return Part.create(headers, + return MultipartBody.Part.create(headers, RequestBody.create(MediaType.parse(HttpConnection.MEDIA_TYPE_OCTET_STREAM), fileInfo.getFile())); } } diff --git a/enos-http-sdk/src/main/java/com/envisioniot/enos/iot_http_sdk/ssl/EccSSLSocketFactory.java b/enos-http-sdk/src/main/java/com/envisioniot/enos/iot_http_sdk/ssl/EccSSLSocketFactory.java index 6399723..53dcee1 100644 --- a/enos-http-sdk/src/main/java/com/envisioniot/enos/iot_http_sdk/ssl/EccSSLSocketFactory.java +++ b/enos-http-sdk/src/main/java/com/envisioniot/enos/iot_http_sdk/ssl/EccSSLSocketFactory.java @@ -16,10 +16,33 @@ * @date 2020/2/11 9:28 */ public class EccSSLSocketFactory extends SSLSocketFactory { + private static final String[] ECC_CIPHER_SUITES = new String[]{ + "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", + "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384" + }; + private static final String[] RSA_CIPHER_SUITES = new String[]{ + "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384", + "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", + "TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384", + "TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256", + "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384", + "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384", + "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256", + "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256" + }; + + private final String[] cipherSuites; + private SSLSocketFactory factory; - EccSSLSocketFactory(SSLSocketFactory factory) { + private Boolean isEccConnect; + + EccSSLSocketFactory(SSLSocketFactory factory, Boolean isEccConnect) { this.factory = factory; + this.isEccConnect = isEccConnect; + this.cipherSuites = Boolean.TRUE.equals(isEccConnect) + ? ECC_CIPHER_SUITES : + RSA_CIPHER_SUITES; } @Override @@ -29,12 +52,12 @@ public Socket createSocket() throws IOException { @Override public String[] getDefaultCipherSuites() { - return new String[]{"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384"}; + return cipherSuites; } @Override public String[] getSupportedCipherSuites() { - return new String[]{"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384"}; + return cipherSuites; } @Override @@ -44,7 +67,11 @@ public Socket createSocket(Socket socket, String s, int i, boolean b) throws IOE private Socket encapsulated(Socket socket) { if (socket instanceof SSLSocket) { - ((SSLSocket) socket).setEnabledCipherSuites(getDefaultCipherSuites()); + if (isEccConnect) { + ((SSLSocket) socket).setEnabledCipherSuites(ECC_CIPHER_SUITES); + } else { + ((SSLSocket) socket).setEnabledCipherSuites(RSA_CIPHER_SUITES); + } } return socket; } diff --git a/enos-http-sdk/src/main/java/com/envisioniot/enos/iot_http_sdk/ssl/OkHttpUtil.java b/enos-http-sdk/src/main/java/com/envisioniot/enos/iot_http_sdk/ssl/OkHttpUtil.java index 589f86a..6746b2f 100644 --- a/enos-http-sdk/src/main/java/com/envisioniot/enos/iot_http_sdk/ssl/OkHttpUtil.java +++ b/enos-http-sdk/src/main/java/com/envisioniot/enos/iot_http_sdk/ssl/OkHttpUtil.java @@ -74,12 +74,25 @@ private static OkHttpClient buildOkHttpsClient(boolean isEccConnect, String jksP X509TrustManager trustManagerVerifyCa = (X509TrustManager) trustManagers[0]; // TSL or SSL SSLContext sslContext = SSLContext.getInstance("TLS"); - sslContext.init(keyManagers, trustManagers, new SecureRandom()); + + TrustManager[] trustAllCerts = new TrustManager[] { + new X509TrustManager() { + @Override + public void checkClientTrusted(X509Certificate[] x509Certificates, + String s) throws CertificateException {} + @Override + public void checkServerTrusted(X509Certificate[] x509Certificates, + String s) throws CertificateException {} + @Override + public X509Certificate[] getAcceptedIssuers() { + return new X509Certificate[0]; + } + } + }; + sslContext.init(keyManagers, trustAllCerts, new SecureRandom()); SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); - if (isEccConnect) { - sslSocketFactory = new EccSSLSocketFactory(sslSocketFactory); - } + sslSocketFactory = new EccSSLSocketFactory(sslSocketFactory, isEccConnect); // check cert okHttpBuilder.sslSocketFactory(sslSocketFactory, trustManagerVerifyCa); diff --git a/enos-mqtt-sdk/src/main/java/com/envisioniot/enos/iot_mqtt_sdk/core/ExecutorFactory.java b/enos-mqtt-sdk/src/main/java/com/envisioniot/enos/iot_mqtt_sdk/core/ExecutorFactory.java index c4e8ecd..f0007f5 100644 --- a/enos-mqtt-sdk/src/main/java/com/envisioniot/enos/iot_mqtt_sdk/core/ExecutorFactory.java +++ b/enos-mqtt-sdk/src/main/java/com/envisioniot/enos/iot_mqtt_sdk/core/ExecutorFactory.java @@ -1,85 +1,85 @@ -package com.envisioniot.enos.iot_mqtt_sdk.core; - -import com.google.common.util.concurrent.ThreadFactoryBuilder; - -import java.util.concurrent.*; - -/** - * Factory that provides thread pools for handling connect, publish, time-out scheduler, - * async callback. Note that this factory is per MqttClient.
- *
- * User can customize the relevant thread pool through the provided set method. - * - * @author zhensheng.cai - * @author jian.zhang4 - */ -public class ExecutorFactory implements IExecutorFactory { - - /** - * Thread pools that handles mqtt publish action in async way. - */ - private ExecutorService publishExecutor = new ThreadPoolExecutor(3, 5, 3, TimeUnit.SECONDS, - new LinkedBlockingQueue<>(1000), new ThreadFactoryBuilder().setNameFormat("publish-executor-%d").build()); - - /** - * We should only have one connect action per MqttClient at the same time. So one - * thread should be good enough to handle async connection. - */ - private ExecutorService connectExecutor = Executors.newSingleThreadExecutor( - new ThreadFactoryBuilder().setNameFormat("connect-executor-%d").build()); - - /** - * callback timeout pool - */ - private ScheduledExecutorService timeoutScheduler = new ScheduledThreadPoolExecutor(3, - new ThreadFactoryBuilder().setNameFormat("timeout-pool-%d").build()); - - /** - * Thread pools that execute async callback provided by user - */ - private ExecutorService callbackExecutor = new ThreadPoolExecutor(3, 5, 3, TimeUnit.SECONDS, - new LinkedBlockingQueue<>(), new ThreadFactoryBuilder().setNameFormat("callback-executor-%d").build()); - - - /** - * shutdown all thread pools managed by this factory - */ - public void shutdownExecutorServices() { - publishExecutor.shutdownNow(); - connectExecutor.shutdownNow(); - timeoutScheduler.shutdownNow(); - callbackExecutor.shutdownNow(); - } - - public ExecutorService getPublishExecutor() { - return publishExecutor; - } - - public void setPublishExecutor(ExecutorService publishExecutor) { - this.publishExecutor = publishExecutor; - } - - public ExecutorService getConnectExecutor() { - return connectExecutor; - } - - public void setConnectExecutor(ExecutorService connectExecutor) { - this.connectExecutor = connectExecutor; - } - - public ScheduledExecutorService getTimeoutScheduler() { - return timeoutScheduler; - } - - public void setTimeoutScheduler(ScheduledExecutorService timeoutScheduler) { - this.timeoutScheduler = timeoutScheduler; - } - - public ExecutorService getCallbackExecutor() { - return callbackExecutor; - } - - public void setCallbackExecutor(ExecutorService callbackExecutor) { - this.callbackExecutor = callbackExecutor; - } -} +package com.envisioniot.enos.iot_mqtt_sdk.core; + +import com.google.common.util.concurrent.ThreadFactoryBuilder; + +import java.util.concurrent.*; + +/** + * Factory that provides thread pools for handling connect, publish, time-out scheduler, + * async callback. Note that this factory is per MqttClient.
+ *
+ * User can customize the relevant thread pool through the provided set method. + * + * @author zhensheng.cai + * @author jian.zhang4 + */ +public class ExecutorFactory implements IExecutorFactory { + + /** + * Thread pools that handles mqtt publish action in async way. + */ + private ExecutorService publishExecutor = new ThreadPoolExecutor(3, 5, 3, TimeUnit.SECONDS, + new LinkedBlockingQueue<>(1000), new ThreadFactoryBuilder().setNameFormat("publish-executor-%d").build()); + + /** + * We should only have one connect action per MqttClient at the same time. So one + * thread should be good enough to handle async connection. + */ + private ExecutorService connectExecutor = Executors.newSingleThreadExecutor( + new ThreadFactoryBuilder().setNameFormat("connect-executor-%d").build()); + + /** + * callback timeout pool + */ + private ScheduledExecutorService timeoutScheduler = new ScheduledThreadPoolExecutor(3, + new ThreadFactoryBuilder().setNameFormat("timeout-pool-%d").build()); + + /** + * Thread pools that execute async callback provided by user + */ + private ExecutorService callbackExecutor = new ThreadPoolExecutor(3, 5, 3, TimeUnit.SECONDS, + new LinkedBlockingQueue<>(), new ThreadFactoryBuilder().setNameFormat("callback-executor-%d").build()); + + + /** + * shutdown all thread pools managed by this factory + */ + public void shutdownExecutorServices() { + publishExecutor.shutdownNow(); + connectExecutor.shutdownNow(); + timeoutScheduler.shutdownNow(); + callbackExecutor.shutdownNow(); + } + + public ExecutorService getPublishExecutor() { + return publishExecutor; + } + + public void setPublishExecutor(ExecutorService publishExecutor) { + this.publishExecutor = publishExecutor; + } + + public ExecutorService getConnectExecutor() { + return connectExecutor; + } + + public void setConnectExecutor(ExecutorService connectExecutor) { + this.connectExecutor = connectExecutor; + } + + public ScheduledExecutorService getTimeoutScheduler() { + return timeoutScheduler; + } + + public void setTimeoutScheduler(ScheduledExecutorService timeoutScheduler) { + this.timeoutScheduler = timeoutScheduler; + } + + public ExecutorService getCallbackExecutor() { + return callbackExecutor; + } + + public void setCallbackExecutor(ExecutorService callbackExecutor) { + this.callbackExecutor = callbackExecutor; + } +} diff --git a/enos-mqtt-sdk/src/main/java/com/envisioniot/enos/iot_mqtt_sdk/core/IExecutorFactory.java b/enos-mqtt-sdk/src/main/java/com/envisioniot/enos/iot_mqtt_sdk/core/IExecutorFactory.java index b5688d9..6d804f8 100644 --- a/enos-mqtt-sdk/src/main/java/com/envisioniot/enos/iot_mqtt_sdk/core/IExecutorFactory.java +++ b/enos-mqtt-sdk/src/main/java/com/envisioniot/enos/iot_mqtt_sdk/core/IExecutorFactory.java @@ -1,17 +1,17 @@ -package com.envisioniot.enos.iot_mqtt_sdk.core; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.ScheduledExecutorService; - -public interface IExecutorFactory { - - void shutdownExecutorServices(); - - ExecutorService getPublishExecutor(); - - ExecutorService getConnectExecutor(); - - ScheduledExecutorService getTimeoutScheduler(); - - ExecutorService getCallbackExecutor(); -} +package com.envisioniot.enos.iot_mqtt_sdk.core; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.ScheduledExecutorService; + +public interface IExecutorFactory { + + void shutdownExecutorServices(); + + ExecutorService getPublishExecutor(); + + ExecutorService getConnectExecutor(); + + ScheduledExecutorService getTimeoutScheduler(); + + ExecutorService getCallbackExecutor(); +} diff --git a/enos-mqtt-sdk/src/main/java/com/envisioniot/enos/iot_mqtt_sdk/core/Sharable.java b/enos-mqtt-sdk/src/main/java/com/envisioniot/enos/iot_mqtt_sdk/core/Sharable.java index 074aa79..38b9d98 100644 --- a/enos-mqtt-sdk/src/main/java/com/envisioniot/enos/iot_mqtt_sdk/core/Sharable.java +++ b/enos-mqtt-sdk/src/main/java/com/envisioniot/enos/iot_mqtt_sdk/core/Sharable.java @@ -1,11 +1,11 @@ -package com.envisioniot.enos.iot_mqtt_sdk.core; - -import java.lang.annotation.*; - -@Inherited -@Documented -@Target({ElementType.TYPE}) -@Retention(RetentionPolicy.RUNTIME) -public @interface Sharable { - -} +package com.envisioniot.enos.iot_mqtt_sdk.core; + +import java.lang.annotation.*; + +@Inherited +@Documented +@Target({ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) +public @interface Sharable { + +} diff --git a/enos-mqtt-sdk/src/main/java/com/envisioniot/enos/iot_mqtt_sdk/core/internals/Utils.java b/enos-mqtt-sdk/src/main/java/com/envisioniot/enos/iot_mqtt_sdk/core/internals/Utils.java index da971af..89c5361 100644 --- a/enos-mqtt-sdk/src/main/java/com/envisioniot/enos/iot_mqtt_sdk/core/internals/Utils.java +++ b/enos-mqtt-sdk/src/main/java/com/envisioniot/enos/iot_mqtt_sdk/core/internals/Utils.java @@ -1,20 +1,20 @@ -package com.envisioniot.enos.iot_mqtt_sdk.core.internals; - -import com.envisioniot.enos.iot_mqtt_sdk.util.StringUtil; - -public class Utils { - - static String getRootMessage(Throwable error) { - if (error == null) { - return ""; - } - - if (error.getCause() == null) { - return StringUtil.isNotEmpty(error.getMessage()) ? error.getMessage() : error.getClass().getName(); - } - - return getRootMessage(error.getCause()); - } - - -} +package com.envisioniot.enos.iot_mqtt_sdk.core.internals; + +import com.envisioniot.enos.iot_mqtt_sdk.util.StringUtil; + +public class Utils { + + static String getRootMessage(Throwable error) { + if (error == null) { + return ""; + } + + if (error.getCause() == null) { + return StringUtil.isNotEmpty(error.getMessage()) ? error.getMessage() : error.getClass().getName(); + } + + return getRootMessage(error.getCause()); + } + + +} diff --git a/enos-sdk-sample/src/main/java/http/DownloadFeatureFileSample.java b/enos-sdk-sample/src/main/java/http/DownloadFeatureFileSample.java index 08a4c75..2a65841 100644 --- a/enos-sdk-sample/src/main/java/http/DownloadFeatureFileSample.java +++ b/enos-sdk-sample/src/main/java/http/DownloadFeatureFileSample.java @@ -58,7 +58,7 @@ public static void main(String[] args) throws EnvisionException { connection.downloadFileAsync(fileUri, FileCategory.FEATURE, new IFileCallback() { @Override public void onResponse(InputStream inputStream) throws IOException { - System.out.println("download feature ile asynchronously"); + System.out.println("download feature file asynchronously"); try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { byte[] buffer = new byte[bufferLength]; int len; diff --git a/enos-sdk-sample/src/main/java/mqtt/BiDirectionalAuthenticate.java b/enos-sdk-sample/src/main/java/mqtt/BiDirectionalAuthenticate.java index e9189c5..3d80abb 100644 --- a/enos-sdk-sample/src/main/java/mqtt/BiDirectionalAuthenticate.java +++ b/enos-sdk-sample/src/main/java/mqtt/BiDirectionalAuthenticate.java @@ -18,40 +18,35 @@ public class BiDirectionalAuthenticate { /** * Gateway credentials, which can be obtained from Device Details page in EnOS Console */ - private static String productKey = "productKey"; - private static String deviceKey = "deviceKey"; - private static String deviceSecret = "deviceSecret"; + private static final String PRODUCT_KEY = "productKey"; + private static final String DEVICE_KEY = "deviceKey"; + private static final String DEVICE_SECRET = "deviceSecret"; // The JKS needs to store the device private key, the device certificate // applied from the EnOS platform, and the EnOS platform CA certificate // To learn how to acquire these certificates, see // https://support-cn5.envisioniot.com/docs/device-connection/en/latest/learn/deviceconnection_authentication.html#certificate-based-authentication - private static String jksPath = "jskPath"; - private static String jksPassword = "jskPassword"; + private static final String JKS_PATH = "jskPath"; + private static final String JKS_PASSWORD = "jskPassword"; /** - * protocol list : ssl,wss - * IpAddress : can domain name or ip address + * PROTOCOL list : ssl,wss * Port list: 18883,18885 + * EnOS MQTT Broker URL, which can be obtained from Environment Information page in EnOS Console */ - private static String protocol = "ssl"; - /** - * EnOS HTTP Broker URL, which can be obtained from Environment Information page in EnOS Console - */ - private static String IpAddress = "broker_domain_url"; - private static String port = "18883"; + private static final String BROKER_URL = "ssl://broker_url:18883"; public static void main(String[] args) { - DefaultProfile defaultProfile = new DefaultProfile(protocol + "://" + IpAddress + ":" + port, - productKey, - deviceKey, - deviceSecret); + DefaultProfile defaultProfile = new DefaultProfile(BROKER_URL, + PRODUCT_KEY, + DEVICE_KEY, + DEVICE_SECRET); defaultProfile .setConnectionTimeout(60) .setKeepAlive(180) .setAutoReconnect(false) .setSSLSecured(true) - .setSSLJksPath(jksPath, jksPassword); + .setSSLJksPath(JKS_PATH, JKS_PASSWORD); // if use ECC certificate // defaultProfile.setEccConnect(true); diff --git a/enos-sdk-sample/src/main/java/mqtt/ConnectionStatePostSample.java b/enos-sdk-sample/src/main/java/mqtt/ConnectionStatePostSample.java index 9c9cb94..975bf81 100644 --- a/enos-sdk-sample/src/main/java/mqtt/ConnectionStatePostSample.java +++ b/enos-sdk-sample/src/main/java/mqtt/ConnectionStatePostSample.java @@ -14,9 +14,9 @@ public class ConnectionStatePostSample { private static final String BROKER_URL = Helper.SERVER_URL; - private static final String PRODUCT_KEY = "YOUR_PRODUCT_KEY"; - private static final String DEVICE_KEY = "YOUR_DEVICE_KEY"; - private static final String DEVICE_SECRET = "YOUR_DEVICE_SECRET"; + private static final String PRODUCT_KEY = "productKey"; + private static final String DEVICE_KEY = "deviceKey"; + private static final String DEVICE_SECRET = "deviceSecret"; public static void main(String[] args) throws Exception { MqttClient mqttClient = new MqttClient(BROKER_URL, PRODUCT_KEY, DEVICE_KEY, DEVICE_SECRET); diff --git a/enos-sdk-sample/src/main/java/mqtt/ManageSubDevices.java b/enos-sdk-sample/src/main/java/mqtt/ManageSubDevices.java index bb5c756..233a143 100644 --- a/enos-sdk-sample/src/main/java/mqtt/ManageSubDevices.java +++ b/enos-sdk-sample/src/main/java/mqtt/ManageSubDevices.java @@ -17,7 +17,7 @@ import java.util.concurrent.TimeUnit; public class ManageSubDevices { - // EnOS HTTP Broker URL, which can be obtained from Environment Information page in EnOS Console + // EnOS MQTT Broker URL, which can be obtained from Environment Information page in EnOS Console static final String BROKER_URL = "tcp://broker_url:11883"; // Gateway credentials, which can be obtained from Device Details page in EnOS Console diff --git a/enos-sdk-sample/src/main/java/mqtt/NetworkStatusSample.java b/enos-sdk-sample/src/main/java/mqtt/NetworkStatusSample.java index 635ad26..b5d706b 100644 --- a/enos-sdk-sample/src/main/java/mqtt/NetworkStatusSample.java +++ b/enos-sdk-sample/src/main/java/mqtt/NetworkStatusSample.java @@ -13,7 +13,7 @@ * @date 2020/10/20 20:52 */ public class NetworkStatusSample { - // EnOS HTTP Broker URL, which can be obtained from Environment Information page in EnOS Console + // EnOS MQTT Broker URL, which can be obtained from Environment Information page in EnOS Console static final String BROKER_URL = "tcp://broker_url:11883"; // Device credentials, which can be obtained from Device Details page in EnOS Console @@ -36,7 +36,7 @@ private static synchronized void initClient() { client.connect(new ConnCallback() { @Override public void connectComplete(boolean reconnect) { - System.out.println("connect alpha success"); + System.out.println("connect success"); } @Override diff --git a/enos-sdk-sample/src/main/java/mqtt/OtaSample.java b/enos-sdk-sample/src/main/java/mqtt/OtaSample.java index a65c13f..ce0eff0 100644 --- a/enos-sdk-sample/src/main/java/mqtt/OtaSample.java +++ b/enos-sdk-sample/src/main/java/mqtt/OtaSample.java @@ -16,18 +16,18 @@ */ public class OtaSample { - // EnOS HTTP Broker URL, which can be obtained from Environment Information page in EnOS Console + // EnOS MQTT Broker URL, which can be obtained from Environment Information page in EnOS Console static final String BROKER_URL = "tcp://broker_url:11883"; // Gateway credentials, which can be obtained from Device Details page in EnOS Console - static final String GW_PRODUCT_KEY = "productKey"; - static final String GW_DEVICE_KEY = "deviceKey"; - static final String GW_DEVICE_SECRET = "deviceSecret"; + static final String PRODUCT_KEY = "productKey"; + static final String DEVICE_KEY = "deviceKey"; + static final String DEVICE_SECRET = "deviceSecret"; static MqttClient client; public static void main(String[] args) throws Exception { - client = new MqttClient(new DefaultProfile(BROKER_URL, GW_PRODUCT_KEY, GW_DEVICE_KEY, GW_DEVICE_SECRET)); + client = new MqttClient(new DefaultProfile(BROKER_URL, PRODUCT_KEY, DEVICE_KEY, DEVICE_SECRET)); // register arrived msg handler to handle cloud-publish firmware upgrade setOtaUpgradeMessageHandler(); @@ -114,7 +114,7 @@ public static void upgradeFirmwareByDeviceReq() throws Exception { public static void reportVersion(String version) throws Exception { OtaVersionReportRequest.Builder builder = new OtaVersionReportRequest.Builder(); - builder.setProductKey(GW_PRODUCT_KEY).setDeviceKey(GW_DEVICE_KEY) + builder.setProductKey(PRODUCT_KEY).setDeviceKey(DEVICE_KEY) .setVersion(version); OtaVersionReportRequest request = builder.build(); System.out.println("send =>" + request.toString()); @@ -131,7 +131,7 @@ private static void reportUpgradeProgress(String progress, String desc) throws E private static List getFirmwaresFromCloud() throws Exception { OtaGetVersionRequest.Builder builder = new OtaGetVersionRequest.Builder(); - builder.setProductKey(GW_PRODUCT_KEY).setDeviceKey(GW_DEVICE_KEY); + builder.setProductKey(PRODUCT_KEY).setDeviceKey(DEVICE_KEY); OtaGetVersionRequest request = builder.build(); OtaGetVersionResponse response = client.publish(request); System.out.println("send getversion request =>" + request.toString()); diff --git a/enos-sdk-sample/src/main/java/mqtt/PassingThroughInformation.java b/enos-sdk-sample/src/main/java/mqtt/PassingThroughInformation.java index 8705dd7..b7d2420 100644 --- a/enos-sdk-sample/src/main/java/mqtt/PassingThroughInformation.java +++ b/enos-sdk-sample/src/main/java/mqtt/PassingThroughInformation.java @@ -14,7 +14,7 @@ import java.util.concurrent.TimeUnit; public class PassingThroughInformation { - // EnOS HTTP Broker URL, which can be obtained from Environment Information page in EnOS Console + // EnOS MQTT Broker URL, which can be obtained from Environment Information page in EnOS Console static final String BROKER_URL = "tcp://broker_url:11883"; // Device credentials, which can be obtained from Device Details page in EnOS Console diff --git a/enos-sdk-sample/src/main/java/mqtt/SimpleSendReceive.java b/enos-sdk-sample/src/main/java/mqtt/SimpleSendReceive.java index 64cd200..be8410e 100644 --- a/enos-sdk-sample/src/main/java/mqtt/SimpleSendReceive.java +++ b/enos-sdk-sample/src/main/java/mqtt/SimpleSendReceive.java @@ -19,7 +19,7 @@ import java.util.concurrent.TimeUnit; public class SimpleSendReceive { - // EnOS HTTP Broker URL, which can be obtained from Environment Information page in EnOS Console + // EnOS MQTT Broker URL, which can be obtained from Environment Information page in EnOS Console static final String BROKER_URL = "tcp://broker_url:11883"; // Device credentials, which can be obtained from Device Details page in EnOS Console diff --git a/enos-sdk-sample/src/main/java/mqtt/old/DeviceLoginSample.java b/enos-sdk-sample/src/main/java/mqtt/old/DeviceLoginSample.java index 8bb92fd..d53f29b 100644 --- a/enos-sdk-sample/src/main/java/mqtt/old/DeviceLoginSample.java +++ b/enos-sdk-sample/src/main/java/mqtt/old/DeviceLoginSample.java @@ -46,6 +46,13 @@ private static void syncLogin(LoginInput loginInput) { e.printStackTrace(); } + // dynamic activating device login wait for a few seconds to handle the msg DeviceActivateInfoCommand + try { + TimeUnit.SECONDS.sleep(1); + } catch (InterruptedException e) { + e.printStackTrace(); + } + client.close(); } @@ -86,10 +93,51 @@ private static void testLoginInput(LoginInput input) { System.out.println("[" + input.getClass().getSimpleName() + "] test completed\n\n"); } + /** + * test login using blocking way + * @param input specified login input mode by user + */ + private static void testDynamicActivatingSyncLogin(LoginInput input) { + System.out.println("[" + input.getClass().getSimpleName() + "] test started"); + + syncLogin(input); + } + + /** + * test login using non-blocking way + * @param input specified login input mode by user + */ + private static void testDynamicActivatingAsyncLogin(LoginInput input) { + asyncLogin(input); + + try { + // wait for a few seconds to let async login complete + TimeUnit.SECONDS.sleep(3); + } catch (Exception e) { + // ignore + } + + System.out.println("[" + input.getClass().getSimpleName() + "] test completed\n\n"); + } + + /** + * Test four login modes we have right now + * Details about the four login modes: + * {@link com.envisioniot.enos.iot_mqtt_sdk.core.login.DynamicActivatingDeviceLoginInput} + * {@link com.envisioniot.enos.iot_mqtt_sdk.core.login.NormalDeviceLoginInput} + * {@link com.envisioniot.enos.iot_mqtt_sdk.core.login.MessageIntegrationLoginInput} + * {@link com.envisioniot.enos.iot_mqtt_sdk.core.login.VirtualGatewayLoginInput} + */ public static void main(String[] args) { - // Test four login modes we have right now + // Dynamically activate device login + // Note that for this login mode to work, it must: + // 1. The device product has dynamic activation enabled + // 2. The device is logged in using this mode for the first time.If the device has already logged in (i.e. activated) using this mode, + // it will fail if it is used again (mainly for security reasons of passing device secrets). + testDynamicActivatingSyncLogin(Helper.getDynamicActivatingDeviceLoginInput(Helper.DEV_PRODUCT_KEY, Helper.DEV_PRODUCT_SECRET, Helper.DEV02_KEY)); + testDynamicActivatingAsyncLogin(Helper.getDynamicActivatingDeviceLoginInput(Helper.DEV_PRODUCT_KEY, Helper.DEV_PRODUCT_SECRET, Helper.DEV03_KEY)); + List inputs = ImmutableList.of( - Helper.getDynamicActivatingDeviceLoginInput(Helper.DEV_PRODUCT_KEY, Helper.DEV_PRODUCT_SECRET, Helper.DEV02_KEY), Helper.getNormalDeviceLoginInput(), Helper.getMessageIntegrationLoginInput(), Helper.getVirtualGatewayLoginInput() diff --git a/enos-sdk-sample/src/main/java/mqtt/old/DirectDeviceSample.java b/enos-sdk-sample/src/main/java/mqtt/old/DirectDeviceSample.java index 55bde09..466929a 100644 --- a/enos-sdk-sample/src/main/java/mqtt/old/DirectDeviceSample.java +++ b/enos-sdk-sample/src/main/java/mqtt/old/DirectDeviceSample.java @@ -8,18 +8,20 @@ import com.google.common.collect.ImmutableMap; public class DirectDeviceSample { - private static final String BETA_URL = "tcp://beta-iot-as-mqtt-cn4.eniot.io:11883"; + private static final String BROKER_URL = "tcp://broker_url:11883"; public static void main(String[] args) throws Exception { + // bind the mirror device // testDeviceWithMirrors(); + + // unbound mirror device testDeviceWithoutMirrors(); } private static void testDeviceWithMirrors() throws Exception { - // zhoumin account // The following direct device has mirror whose device key is HpG2Z2eSoC MqttClient client = new MqttClient(new DefaultProfile( - new NormalDeviceLoginInput(BETA_URL, "oDc253LO", "zm1112a", "pmh5jEWEt2Cip5KsGPO3") + new NormalDeviceLoginInput(BROKER_URL, "pk", "dk", "secret") )); client.getProfile().setAutoLoginSubDevice(false); client.connect(); @@ -37,9 +39,8 @@ private static void testDeviceWithMirrors() throws Exception { } private static void testDeviceWithoutMirrors() throws Exception { - // zhangjian account MqttClient client = new MqttClient(new DefaultProfile( - new NormalDeviceLoginInput(BETA_URL, "x4jwTsoz", "FfHtfAyhC5", "DVCWsRQHeIOvryFy7fIz") + new NormalDeviceLoginInput(BROKER_URL, "pk", "dk", "secret") )); client.getProfile().setAutoLoginSubDevice(false); client.connect(); diff --git a/enos-sdk-sample/src/main/java/mqtt/old/DynamicActivatingDeviceSample.java b/enos-sdk-sample/src/main/java/mqtt/old/DynamicActivatingDeviceSample.java index 7836bef..f44f2fc 100644 --- a/enos-sdk-sample/src/main/java/mqtt/old/DynamicActivatingDeviceSample.java +++ b/enos-sdk-sample/src/main/java/mqtt/old/DynamicActivatingDeviceSample.java @@ -7,7 +7,6 @@ import com.envisioniot.enos.iot_mqtt_sdk.util.SecureModeUtil; import com.envisioniot.enos.iot_mqtt_sdk.util.StringUtil; import com.google.common.base.Preconditions; - import mqtt.old.helper.BaseConnectCallback; import mqtt.old.helper.Helper; @@ -57,8 +56,8 @@ private static void reconnectWithNewProfile(FileProfile newProfile) { * @param profilePath profile file path */ private static void checkProfile(final MqttClient client, FileProfile oldProfile, String profilePath) { - // Wait a moment to let config be updated try { + // Wait a moment to let config be updated for (int i = 1; i < 60; ++i) { if (!StringUtil.isEmpty(oldProfile.getDeviceSecret())) { // device secret populated by DefaultActivateResponseHandler @@ -69,31 +68,32 @@ private static void checkProfile(final MqttClient client, FileProfile oldProfile // wait DefaultActivateResponseHandler to complete replying broker and reconnecting to it TimeUnit.SECONDS.sleep(3); - } catch (Exception e) { - e.printStackTrace(); - } - // Reload the profile config - FileProfile newProfile = new FileProfile(profilePath); - if (StringUtil.isEmpty(newProfile.getDeviceSecret())) { - String error = StringUtil.isEmpty(oldProfile.getDeviceSecret()) - ? "device secret is not returned from broker" - : "device secret is returned from broker but not persisted"; - System.err.println("Error: " + error); - } else { - System.out.println("received device secret: " + newProfile.getDeviceSecret()); - - // Ensure that connection is still alive after DefaultActivateResponseHandler reconnected to broker - if (!client.isConnected()) { - System.err.println("Error: connection disconnected during dynamic activating"); + // Reload the profile config + FileProfile newProfile = new FileProfile(profilePath); + if (StringUtil.isEmpty(newProfile.getDeviceSecret())) { + String error = StringUtil.isEmpty(oldProfile.getDeviceSecret()) + ? "device secret is not returned from broker" + : "device secret is returned from broker but not persisted"; + System.err.println("Error: " + error); + } else { + System.out.println("received device secret: " + newProfile.getDeviceSecret()); + + // Ensure that connection is still alive after DefaultActivateResponseHandler reconnected to broker + if (!client.isConnected()) { + System.err.println("Error: connection disconnected during dynamic activating"); + } } - } - client.close(); + TimeUnit.SECONDS.sleep(3); + client.close(); - // Test reconnect with updated profile - if (!StringUtil.isEmpty(newProfile.getDeviceSecret())) { - reconnectWithNewProfile(newProfile); + // Test reconnect with updated profile + if (!StringUtil.isEmpty(newProfile.getDeviceSecret())) { + reconnectWithNewProfile(newProfile); + } + } catch (Throwable t) { + t.printStackTrace(); } } diff --git a/enos-sdk-sample/src/main/java/mqtt/old/GwGroupSample.java b/enos-sdk-sample/src/main/java/mqtt/old/GwGroupSample.java index 49cb0b4..aa0d422 100644 --- a/enos-sdk-sample/src/main/java/mqtt/old/GwGroupSample.java +++ b/enos-sdk-sample/src/main/java/mqtt/old/GwGroupSample.java @@ -1,161 +1,161 @@ -package mqtt.old; - -import com.envisioniot.enos.iot_mqtt_sdk.core.MqttClient; -import com.envisioniot.enos.iot_mqtt_sdk.core.exception.EnvisionError; -import com.envisioniot.enos.iot_mqtt_sdk.core.exception.EnvisionException; -import com.envisioniot.enos.iot_mqtt_sdk.core.login.NormalDeviceLoginInput; -import com.envisioniot.enos.iot_mqtt_sdk.core.profile.DefaultProfile; -import com.envisioniot.enos.iot_mqtt_sdk.message.upstream.BaseMqttResponse; -import com.envisioniot.enos.iot_mqtt_sdk.message.upstream.status.SubDeviceLoginRequest; -import com.envisioniot.enos.iot_mqtt_sdk.message.upstream.status.SubDeviceLogoutRequest; -import com.envisioniot.enos.iot_mqtt_sdk.message.upstream.tsl.MeasurepointPostBatchRequest; -import com.envisioniot.enos.iot_mqtt_sdk.message.upstream.tsl.MeasurepointPostBatchResponse; -import com.envisioniot.enos.iot_mqtt_sdk.message.upstream.tsl.MeasurepointPostRequest; -import com.envisioniot.enos.iot_mqtt_sdk.message.upstream.tsl.MeasurepointPostResponse; -import com.google.common.collect.ImmutableMap; -import lombok.extern.slf4j.Slf4j; -import mqtt.old.helper.Helper; - -import java.util.Random; - -@Slf4j -public class GwGroupSample { - - private final static String GW01_PK = "vOQSJ4dN"; - private final static String GW01_DK = "mqtt_sample_gwgroup_gw01"; - private final static String GW01_SECRET = "m90jgBApzE5mBBXnkFxG"; - - private final static String GW02_PK = "vOQSJ4dN"; - private final static String GW02_DK = "mqtt_sample_gwgroup_gw02"; - private final static String GW02_SECRET = "iXIPK0XhIlWOLafrNtjY"; - - private final static String SUB_DEV01_PK = "K9HMijjG"; - private final static String SUB_DEV01_DK = "mqtt_sample_gwgroup_dev01"; - private final static String SUB_DEV01_SECRET = "sGCCwSIcD1AJ5wa8OcPW"; - - public static void main(String[] args) throws Exception { - MqttClient gw01Client = new MqttClient(new DefaultProfile( - new NormalDeviceLoginInput(Helper.SERVER_URL, GW01_PK, GW01_DK, GW01_SECRET) - )); - gw01Client.connect(); - log.info("{} logined successfully", GW01_DK); - - MqttClient gw02Client = new MqttClient(new DefaultProfile( - new NormalDeviceLoginInput(Helper.SERVER_URL, GW02_PK, GW02_DK, GW02_SECRET) - )); - gw02Client.connect(); - log.info("{} logined successfully", GW02_DK); - - try { - assertFalse(publishSubDeviceMeasurePoints(gw01Client)); - assertFalse(publishSubDeviceMeasurePoints(gw02Client)); - - // If a gateway from gateway group wants to manage a sub-device, it - // must login the sub-device first. - assertTrue(loginSubDevice(gw01Client)); - - assertTrue(publishSubDeviceMeasurePoints(gw01Client)); - assertTrue(publishSubDeviceMeasurePointsUsingBatch(gw01Client)); - - // When gw01 is managing the sub-device, gw02 is not allowed to manipulate - // it (unless gw02 take over the sub-device by using sub-device log in). - assertFalse(publishSubDeviceMeasurePoints(gw02Client)); - assertFalse(publishSubDeviceMeasurePointsUsingBatch(gw02Client)); - assertFalse(logoutSubDevice(gw02Client)); - - // The invalid operations from gw02 above should not affect gw01 to - // continue managing the sub-device - assertTrue(publishSubDeviceMeasurePointsUsingBatch(gw01Client)); - assertTrue(logoutSubDevice(gw01Client)); - - // gw02 take over the sub-device by its own sub-device log in request - assertTrue(loginSubDevice(gw02Client)); - - assertTrue(publishSubDeviceMeasurePoints(gw02Client)); - assertTrue(publishSubDeviceMeasurePointsUsingBatch(gw02Client)); - - // gw01 should be not allowed to manage the sub-device any more - // since gw02 has taken it over. - assertFalse(publishSubDeviceMeasurePoints(gw01Client)); - assertFalse(publishSubDeviceMeasurePointsUsingBatch(gw01Client)); - assertFalse(logoutSubDevice(gw01Client)); - - assertTrue(publishSubDeviceMeasurePointsUsingBatch(gw02Client)); - assertTrue(logoutSubDevice(gw02Client)); - } finally { - gw01Client.close(); - gw02Client.close(); - } - - log.info("HURRAY! The tests passed!"); - } - - private static BaseMqttResponse loginSubDevice(MqttClient client) throws Exception { - SubDeviceLoginRequest request = SubDeviceLoginRequest.builder() - .setSubDeviceInfo(SUB_DEV01_PK, SUB_DEV01_DK, SUB_DEV01_SECRET) - .build(); - return client.publish(request); - } - - private static BaseMqttResponse logoutSubDevice(MqttClient client) throws Exception { - SubDeviceLogoutRequest request = SubDeviceLogoutRequest.builder() - .setSubProductKey(SUB_DEV01_PK) - .setSubDeviceKey(SUB_DEV01_DK) - .build(); - return client.publish(request); - } - - private static BaseMqttResponse publishSubDeviceMeasurePoints(MqttClient client) throws Exception { - try { - return client.publish(getSubDevMeasurePointReq()); - } catch (EnvisionException e) { - if (e.getErrorCode() == EnvisionError.MQTT_CLIENT_SUBSCRIEBE_FAILED.getErrorCode()) { - MeasurepointPostResponse response = new MeasurepointPostResponse(); - response.setCode(e.getErrorCode()); - response.setMessage(e.getMessage()); - return response; - } - throw e; - } - } - - private static MeasurepointPostRequest getSubDevMeasurePointReq() { - return MeasurepointPostRequest.builder() - .setProductKey(SUB_DEV01_PK) - .setDeviceKey(SUB_DEV01_DK) - .setMeasurePoints(ImmutableMap.of( - "value", new Random().nextDouble(), - "temp", new Random().nextDouble() - )) - .build(); - } - - private static BaseMqttResponse publishSubDeviceMeasurePointsUsingBatch(MqttClient client) throws Exception { - try { - MeasurepointPostBatchRequest request = MeasurepointPostBatchRequest.builder() - .addRequest(getSubDevMeasurePointReq()) - .build(); - return client.publish(request); - } catch (EnvisionException e) { - if (e.getErrorCode() == EnvisionError.MQTT_CLIENT_SUBSCRIEBE_FAILED.getErrorCode()) { - MeasurepointPostBatchResponse response = new MeasurepointPostBatchResponse(); - response.setCode(e.getErrorCode()); - response.setMessage(e.getMessage()); - return response; - } - throw e; - } - } - - private static void assertTrue(BaseMqttResponse response) { - if (!response.isSuccess()) { - throw new RuntimeException("expect succcess but it has error: " + response.getMessage()); - } - } - - private static void assertFalse(BaseMqttResponse response) { - if (response.isSuccess()) { - throw new RuntimeException("expect failure but it's success: " + response); - } - } -} +package mqtt.old; + +import com.envisioniot.enos.iot_mqtt_sdk.core.MqttClient; +import com.envisioniot.enos.iot_mqtt_sdk.core.exception.EnvisionError; +import com.envisioniot.enos.iot_mqtt_sdk.core.exception.EnvisionException; +import com.envisioniot.enos.iot_mqtt_sdk.core.login.NormalDeviceLoginInput; +import com.envisioniot.enos.iot_mqtt_sdk.core.profile.DefaultProfile; +import com.envisioniot.enos.iot_mqtt_sdk.message.upstream.BaseMqttResponse; +import com.envisioniot.enos.iot_mqtt_sdk.message.upstream.status.SubDeviceLoginRequest; +import com.envisioniot.enos.iot_mqtt_sdk.message.upstream.status.SubDeviceLogoutRequest; +import com.envisioniot.enos.iot_mqtt_sdk.message.upstream.tsl.MeasurepointPostBatchRequest; +import com.envisioniot.enos.iot_mqtt_sdk.message.upstream.tsl.MeasurepointPostBatchResponse; +import com.envisioniot.enos.iot_mqtt_sdk.message.upstream.tsl.MeasurepointPostRequest; +import com.envisioniot.enos.iot_mqtt_sdk.message.upstream.tsl.MeasurepointPostResponse; +import com.google.common.collect.ImmutableMap; +import lombok.extern.slf4j.Slf4j; +import mqtt.old.helper.Helper; + +import java.util.Random; + +@Slf4j +public class GwGroupSample { + + private final static String GW01_PK = "pk"; + private final static String GW01_DK = "dk"; + private final static String GW01_SECRET = "secret"; + + private final static String GW02_PK = "pk"; + private final static String GW02_DK = "dk"; + private final static String GW02_SECRET = "secret"; + + private final static String SUB_DEV01_PK = "pk"; + private final static String SUB_DEV01_DK = "dk"; + private final static String SUB_DEV01_SECRET = "secret"; + + public static void main(String[] args) throws Exception { + MqttClient gw01Client = new MqttClient(new DefaultProfile( + new NormalDeviceLoginInput(Helper.SERVER_URL, GW01_PK, GW01_DK, GW01_SECRET) + )); + gw01Client.connect(); + log.info("{} logined successfully", GW01_DK); + + MqttClient gw02Client = new MqttClient(new DefaultProfile( + new NormalDeviceLoginInput(Helper.SERVER_URL, GW02_PK, GW02_DK, GW02_SECRET) + )); + gw02Client.connect(); + log.info("{} logined successfully", GW02_DK); + + try { + assertFalse(publishSubDeviceMeasurePoints(gw01Client)); + assertFalse(publishSubDeviceMeasurePoints(gw02Client)); + + // If a gateway from gateway group wants to manage a sub-device, it + // must login the sub-device first. + assertTrue(loginSubDevice(gw01Client)); + + assertTrue(publishSubDeviceMeasurePoints(gw01Client)); + assertTrue(publishSubDeviceMeasurePointsUsingBatch(gw01Client)); + // gw02 can batch publish to multiple sub-devices but cannot publish to a single sub-device + assertFalse(publishSubDeviceMeasurePoints(gw02Client)); + assertTrue(publishSubDeviceMeasurePointsUsingBatch(gw02Client)); + // Unable to log out via gw02 if log in via gw01; the same client must be used for both log in/log out + assertFalse(logoutSubDevice(gw02Client)); + + // The invalid operations from gw02 above should not affect gw01 to + // continue managing the sub-device + assertTrue(publishSubDeviceMeasurePointsUsingBatch(gw01Client)); + assertTrue(logoutSubDevice(gw01Client)); + + // gw02 take over the sub-device by its own sub-device log in request + assertTrue(loginSubDevice(gw02Client)); + + assertTrue(publishSubDeviceMeasurePoints(gw02Client)); + assertTrue(publishSubDeviceMeasurePointsUsingBatch(gw02Client)); + // gw01 can batch publish to multiple sub-devices but cannot publish to a single sub-device + assertFalse(publishSubDeviceMeasurePoints(gw01Client)); + assertTrue(publishSubDeviceMeasurePointsUsingBatch(gw01Client)); + // Unable to log out via gw01 if log in via gw02; the same client must be used for both log in/log out + assertFalse(logoutSubDevice(gw01Client)); + + // The invalid operations from gw01 above should not affect gw02 to + // continue managing the sub-device + assertTrue(publishSubDeviceMeasurePointsUsingBatch(gw02Client)); + assertTrue(logoutSubDevice(gw02Client)); + } finally { + gw01Client.close(); + gw02Client.close(); + } + + log.info("HURRAY! The tests passed!"); + } + + private static BaseMqttResponse loginSubDevice(MqttClient client) throws Exception { + SubDeviceLoginRequest request = SubDeviceLoginRequest.builder() + .setSubDeviceInfo(SUB_DEV01_PK, SUB_DEV01_DK, SUB_DEV01_SECRET) + .build(); + return client.publish(request); + } + + private static BaseMqttResponse logoutSubDevice(MqttClient client) throws Exception { + SubDeviceLogoutRequest request = SubDeviceLogoutRequest.builder() + .setSubProductKey(SUB_DEV01_PK) + .setSubDeviceKey(SUB_DEV01_DK) + .build(); + return client.publish(request); + } + + private static BaseMqttResponse publishSubDeviceMeasurePoints(MqttClient client) throws Exception { + try { + return client.publish(getSubDevMeasurePointReq()); + } catch (EnvisionException e) { + if (e.getErrorCode() == EnvisionError.MQTT_CLIENT_SUBSCRIEBE_FAILED.getErrorCode()) { + MeasurepointPostResponse response = new MeasurepointPostResponse(); + response.setCode(e.getErrorCode()); + response.setMessage(e.getMessage()); + return response; + } + throw e; + } + } + + private static MeasurepointPostRequest getSubDevMeasurePointReq() { + return MeasurepointPostRequest.builder() + .setProductKey(SUB_DEV01_PK) + .setDeviceKey(SUB_DEV01_DK) + .setMeasurePoints(ImmutableMap.of( + "value", new Random().nextDouble(), + "temp", new Random().nextDouble() + )) + .build(); + } + + private static BaseMqttResponse publishSubDeviceMeasurePointsUsingBatch(MqttClient client) throws Exception { + try { + MeasurepointPostBatchRequest request = MeasurepointPostBatchRequest.builder() + .addRequest(getSubDevMeasurePointReq()) + .build(); + return client.publish(request); + } catch (EnvisionException e) { + if (e.getErrorCode() == EnvisionError.MQTT_CLIENT_SUBSCRIEBE_FAILED.getErrorCode()) { + MeasurepointPostBatchResponse response = new MeasurepointPostBatchResponse(); + response.setCode(e.getErrorCode()); + response.setMessage(e.getMessage()); + return response; + } + throw e; + } + } + + private static void assertTrue(BaseMqttResponse response) { + if (!response.isSuccess()) { + throw new RuntimeException("expect succcess but it has error: " + response.getMessage()); + } + } + + private static void assertFalse(BaseMqttResponse response) { + if (response.isSuccess()) { + throw new RuntimeException("expect failure but it's success: " + response); + } + } +} diff --git a/enos-sdk-sample/src/main/java/mqtt/old/MeasurepointPostBatchRequestSample.java b/enos-sdk-sample/src/main/java/mqtt/old/MeasurepointPostBatchRequestSample.java index 2858884..5913a7e 100644 --- a/enos-sdk-sample/src/main/java/mqtt/old/MeasurepointPostBatchRequestSample.java +++ b/enos-sdk-sample/src/main/java/mqtt/old/MeasurepointPostBatchRequestSample.java @@ -13,16 +13,15 @@ import com.envisioniot.enos.iot_mqtt_sdk.message.upstream.tsl.MeasurepointPostBatchResponse; import com.envisioniot.enos.iot_mqtt_sdk.message.upstream.tsl.MeasurepointPostRequest; import com.google.common.collect.ImmutableMap; - import mqtt.old.helper.BaseConnectCallback; -import static mqtt.old.helper.Helper.*; - import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Random; +import static mqtt.old.helper.Helper.*; + /** * This sample shows how sub-devices login/logout and publish * measure points to broker. @@ -31,9 +30,28 @@ */ public class MeasurepointPostBatchRequestSample { final static Random rand = new Random(); + final static MqttClient CLIENT = new MqttClient(new DefaultProfile( + new NormalDeviceLoginInput(SERVER_URL, GW_PRODUCT_KEY, GW_DEV_KEY, GW_DEV_SECRET) + )); + + public static void main(String[] args) throws InterruptedException, EnvisionException { + CLIENT.connect(new BaseConnectCallback(CLIENT, null, false) { + + @Override + protected void onSuccess(MqttClient client) { + try { + testSample(); + client.close(); + } catch (Throwable t) { + t.printStackTrace(); + } - public static void main(String[] args) throws InterruptedException { + } + }); + + } + private static void testSample() throws InterruptedException, EnvisionException { //success testNormalCase(true, true); //success @@ -44,7 +62,7 @@ public static void main(String[] args) throws InterruptedException { testNormalCase(false, false); - //sucess + //success testOneInvalidMP(true, true); //success testOneInvalidMP(true, false); @@ -82,7 +100,6 @@ public static void main(String[] args) throws InterruptedException { testOneDevWithOfflineAndAnotherdevWithInvalidMP(false, false); //false testOneDevWithOfflineAndAnotherdevWithInvalidMP(false, true); - } // testNormalCase (two on-line devices with valid measurepoints) [flat 4] @@ -182,26 +199,11 @@ public static void testOneDevWithOfflineAndAnotherdevWithInvalidMP(boolean skipI private static void testSubDevicesByManuallyLogin(boolean allowoffline, boolean skipInvalid, final List loginedSubDevices, List publishSubDevices, Map measurepoints, Map invalidMeasurepints) throws InterruptedException { - MqttClient client = new MqttClient(new DefaultProfile( - new NormalDeviceLoginInput(SERVER_URL, GW_PRODUCT_KEY, GW_DEV_KEY, GW_DEV_SECRET) - )); - client.connect(new BaseConnectCallback(client, null, false) { - - @Override - protected void onSuccess(MqttClient client) { - - loginSubDevices(client, loginedSubDevices); - if (!loginedSubDevices.isEmpty()) { - publishMeasurePointsFor(client, publishSubDevices, allowoffline, skipInvalid, measurepoints, invalidMeasurepints); - } - logoutSubDevices(client, loginedSubDevices); - - client.close(); - - } - }); - - Thread.sleep(6000); + loginSubDevices(CLIENT, loginedSubDevices); + if (!loginedSubDevices.isEmpty()) { + publishMeasurePointsFor(CLIENT, publishSubDevices, allowoffline, skipInvalid, measurepoints, invalidMeasurepints); + } + logoutSubDevices(CLIENT, loginedSubDevices); } /** @@ -233,7 +235,7 @@ private static void publishMeasurePointsFor(final MqttClient client, List measurepoints = new HashMap<>(measurepointNum * 3); - for (int k = 0;k < measurepointNum; ++k) { + for (int k = 0; k < measurepointNum; ++k) { measurepoints.put("int" + k, new Random().nextInt(10000)); measurepoints.put("float" + k, new Random().nextFloat()); measurepoints.put("string" + k, "s" + k); diff --git a/enos-sdk-sample/src/main/java/mqtt/old/helper/Helper.java b/enos-sdk-sample/src/main/java/mqtt/old/helper/Helper.java index 35d1e09..9a168c3 100644 --- a/enos-sdk-sample/src/main/java/mqtt/old/helper/Helper.java +++ b/enos-sdk-sample/src/main/java/mqtt/old/helper/Helper.java @@ -8,44 +8,47 @@ public class Helper { /** - * Here we use beta as default since it's more reliable than alpha + * EnOS MQTT Broker URL, which can be obtained from Environment Information page in EnOS Console */ - public static String SERVER_URL = "tcp://beta-iot-as-mqtt-cn4.eniot.io:11883"; + public static String SERVER_URL = "tcp://broker_url:11883"; - public static String ORG_ID = "o15535059999891"; + public static String ORG_ID = "orgId"; /** * Non-gate-way product info (for direct connecting device and sub-device) */ - public static String DEV_PRODUCT_KEY = "K9HMijjG"; - public static String DEV_PRODUCT_SECRET = "iiMGJw8ohjL"; + public static String DEV_PRODUCT_KEY = "pk"; + public static String DEV_PRODUCT_SECRET = "secret"; /** * gate-way product info */ - public static String GW_PRODUCT_KEY = "vOQSJ4dN"; - public static String GW_PRODUCT_SECRET = "W4Vsmzpu40I"; + public static String GW_PRODUCT_KEY = "pk"; + public static String GW_PRODUCT_SECRET = "secret"; /** * device info for direct connecting device (non-gate-way device) */ - public static String DEV01_KEY = "mqtt_sdk_sample_dev01"; - public static String DEV01_SECRET = "23avggF6S2HKXx283IMs"; + public static String DEV01_KEY = "dk"; + public static String DEV01_SECRET = "secret"; - public static String DEV02_KEY = "mqtt_sdk_sample_dev02"; - public static String DEV02_SECRET = "sV0cN56ptABCf0LbqGAH"; + public static String DEV02_KEY = "dk"; + public static String DEV02_SECRET = "secret"; + + public static String DEV03_KEY = "dk"; + public static String DEV03_SECRET = "secret"; /** * device info for gate-way and its sub-devices */ - public static String GW_DEV_KEY = "mqtt_sdk_sample_gw01"; - public static String GW_DEV_SECRET = "KTufcRGDATp0kAl7pJ9h"; + public static String GW_DEV_KEY = "dk"; + public static String GW_DEV_SECRET = "secret"; - public static String SUB_DEV01_KEY = "mqtt_sdk_sample_subdev01"; - public static String SUB_DEV01_SECRET = "S3OGY40qNmqkrtZtkZ6p"; + public static String SUB_DEV01_KEY = "dk"; + public static String SUB_DEV01_SECRET = "secret"; - public static String SUB_DEV02_KEY = "mqtt_sdk_sample_subdev02"; - public static String SUB_DEV02_SECRET = "QI9RHWuw7jn1V6Kgxkra"; + public static String SUB_DEV02_KEY = "dk"; + public static String SUB_DEV02_SECRET = "secret"; public final static List SUBDEVICES = ImmutableList.of( new DeviceCredential(DEV_PRODUCT_KEY, null, SUB_DEV01_KEY, SUB_DEV01_SECRET),