use of software.amazon.awssdk.crt.mqtt.MqttClientConnection in project aws-greengrass-nucleus by aws-greengrass.
the class ShadowDeploymentListener method unsubscribeToShadowTopics.
/*
UnSubscribe to "$aws/things/{thingName}/shadow/update/accepted" topic to get notified when shadow is updated
UnSubscribe to "$aws/things/{thingName}/shadow/update/rejected" topic to get notified when an update is rejected
UnSubscribe to "$aws/things/{thingName}/shadow/get/accepted" topic to retrieve shadow by publishing to get topic
*/
@SuppressWarnings("PMD.CloseResource")
private void unsubscribeToShadowTopics() {
MqttClientConnection connection = getMqttClientConnection();
// This is best effort. Do not want to block on it.
connection.unsubscribe(SHADOW_UPDATE_ACCEPTED_TOPIC.replace("{thingName}", thingName).replace("{shadowName}", DEPLOYMENT_SHADOW_NAME));
connection.unsubscribe(SHADOW_UPDATE_REJECTED_TOPIC.replace("{thingName}", thingName).replace("{shadowName}", DEPLOYMENT_SHADOW_NAME));
connection.unsubscribe(SHADOW_GET_TOPIC.replace("{thingName}", thingName).replace("{shadowName}", DEPLOYMENT_SHADOW_NAME));
}
use of software.amazon.awssdk.crt.mqtt.MqttClientConnection in project aws-crt-java by awslabs.
the class ProxyTest method buildDirectMqttConnection.
private MqttClientConnection buildDirectMqttConnection(ProxyTestType testType, ProxyAuthType authType) {
try (EventLoopGroup eventLoopGroup = new EventLoopGroup(1);
HostResolver resolver = new HostResolver(eventLoopGroup);
ClientBootstrap bootstrap = new ClientBootstrap(eventLoopGroup, resolver);
TlsContext tlsContext = createX509TlsContext(null);
MqttClient mqttClient = new MqttClient(bootstrap, tlsContext);
MqttConnectionConfig connectionConfig = new MqttConnectionConfig();
TlsContext proxyTlsContext = createProxyTlsContext(testType)) {
HttpProxyOptions proxyOptions = buildProxyOptions(testType, authType, proxyTlsContext);
String clientId = PROXY_TEST_CLIENTID + (UUID.randomUUID()).toString();
connectionConfig.setMqttClient(mqttClient);
connectionConfig.setEndpoint(MQTT_ENDPOINT);
connectionConfig.setHttpProxyOptions(proxyOptions);
connectionConfig.setCleanSession(true);
connectionConfig.setClientId(clientId);
connectionConfig.setPort(MQTT_DIRECT_PORT);
connectionConfig.setProtocolOperationTimeoutMs(60000);
return new MqttClientConnection(connectionConfig);
}
}
use of software.amazon.awssdk.crt.mqtt.MqttClientConnection in project aws-crt-java by awslabs.
the class ProxyTest method testMqttDirect_TunnelingProxy_NoAuth.
@Test
public void testMqttDirect_TunnelingProxy_NoAuth() {
skipIfNetworkUnavailable();
Assume.assumeTrue(isEnvironmentSetUpForProxyTests());
try (MqttClientConnection connection = buildDirectMqttConnection(ProxyTestType.TUNNELING_HTTPS, ProxyAuthType.None)) {
doMqttConnectTest(connection);
}
}
use of software.amazon.awssdk.crt.mqtt.MqttClientConnection in project aws-iot-device-sdk-java-v2 by aws.
the class PubSubStress method initConnections.
static void initConnections() {
List<ConnectionState> connectionsInProgress = new ArrayList<>();
for (int i = 0; i < connectionCount; ++i) {
MqttClientConnectionEvents callbacks = new MqttClientConnectionEvents() {
@Override
public void onConnectionInterrupted(int errorCode) {
if (errorCode != 0) {
System.out.println("Connection interrupted: " + errorCode + ": " + CRT.awsErrorString(errorCode));
}
}
@Override
public void onConnectionResumed(boolean sessionPresent) {
System.out.println("Connection resumed: " + (sessionPresent ? "existing session" : "clean session"));
}
};
String newClientId = String.format("%s%d", clientId, i);
MqttClientConnection connection = cmdUtils.buildMQTTConnection(callbacks);
try {
ConnectionState connectionState = new ConnectionState();
connectionState.clientId = newClientId;
connectionState.connectFuture = connection.connect();
connectionState.connection = connection;
connectionsInProgress.add(connectionState);
if ((i + 1) % PROGRESS_OP_COUNT == 0) {
System.out.println(String.format("(Main Thread) Connect start count: %d", i + 1));
}
// Simple throttle to avoid Iot Connect/Second limit
Thread.sleep(5);
} catch (Exception ignored) {
connection.disconnect();
connection.close();
}
}
System.out.println(String.format("(Main Thread) Started %d connections", connectionsInProgress.size()));
for (int i = 0; i < connectionsInProgress.size(); ++i) {
ConnectionState connectionState = connectionsInProgress.get(i);
CompletableFuture<Boolean> connectFuture = connectionState.connectFuture;
if (connectFuture == null) {
continue;
}
try {
connectFuture.get(5, TimeUnit.SECONDS);
String clientTopic = String.format("%s%d", topic, i);
connectionState.topic = clientTopic;
connectionState.subscribeFuture = connectionState.connection.subscribe(clientTopic, QualityOfService.AT_LEAST_ONCE, (message) -> {
try {
String payload = new String(message.getPayload(), "UTF-8");
} catch (UnsupportedEncodingException ex) {
System.out.println(String.format("(Topic %s): Unable to decode payload: %s", clientTopic, ex.getMessage()));
}
});
if ((i + 1) % PROGRESS_OP_COUNT == 0) {
System.out.println(String.format("(Main Thread) Subscribe start count: %d", i + 1));
}
// Simple throttle to avoid Iot Subscribe/Second limit
Thread.sleep(5);
} catch (Exception e) {
connectionState.connection.disconnect();
connectionState.connection.close();
connectionState.connection = null;
}
}
System.out.println(String.format("(Main Thread) Started subscriptions for %d connections", connectionsInProgress.size()));
for (int i = 0; i < connectionsInProgress.size(); ++i) {
ConnectionState connectionState = connectionsInProgress.get(i);
CompletableFuture<Integer> subscribeFuture = connectionState.subscribeFuture;
if (subscribeFuture == null) {
continue;
}
try {
subscribeFuture.get(5, TimeUnit.SECONDS);
connections.put(connectionState.clientId, connectionState.connection);
validClientIds.add(connectionState.clientId);
validTopics.add(connectionState.topic);
} catch (Exception e) {
connectionState.connection.disconnect();
connectionState.connection.close();
connectionState.connection = null;
}
}
System.out.println(String.format("(Main Thread) Successfully established %d connections", connections.size()));
}
use of software.amazon.awssdk.crt.mqtt.MqttClientConnection in project aws-iot-device-sdk-java-v2 by aws.
the class ShadowSample method main.
public static void main(String[] args) {
cmdUtils = new CommandLineUtils();
cmdUtils.registerProgramName("ShadowSample");
cmdUtils.addCommonMQTTCommands();
cmdUtils.registerCommand("key", "<path>", "Path to your key in PEM format.");
cmdUtils.registerCommand("cert", "<path>", "Path to your client certificate in PEM format.");
cmdUtils.registerCommand("port", "<int>", "Port to use (optional, default='8883').");
cmdUtils.registerCommand("thing_name", "<str>", "The name of the IoT thing.");
cmdUtils.registerCommand("client_id", "<int>", "Client id to use (optional, default='test-*')");
cmdUtils.sendArguments(args);
thingName = cmdUtils.getCommandRequired("thing_name", "");
MqttClientConnectionEvents callbacks = new MqttClientConnectionEvents() {
@Override
public void onConnectionInterrupted(int errorCode) {
if (errorCode != 0) {
System.out.println("Connection interrupted: " + errorCode + ": " + CRT.awsErrorString(errorCode));
}
}
@Override
public void onConnectionResumed(boolean sessionPresent) {
System.out.println("Connection resumed: " + (sessionPresent ? "existing session" : "clean session"));
}
};
try {
MqttClientConnection connection = cmdUtils.buildMQTTConnection(callbacks);
shadow = new IotShadowClient(connection);
CompletableFuture<Boolean> connected = connection.connect();
try {
boolean sessionPresent = connected.get();
System.out.println("Connected to " + (!sessionPresent ? "clean" : "existing") + " session!");
} catch (Exception ex) {
throw new RuntimeException("Exception occurred during connect", ex);
}
System.out.println("Subscribing to shadow delta events...");
ShadowDeltaUpdatedSubscriptionRequest requestShadowDeltaUpdated = new ShadowDeltaUpdatedSubscriptionRequest();
requestShadowDeltaUpdated.thingName = thingName;
CompletableFuture<Integer> subscribedToDeltas = shadow.SubscribeToShadowDeltaUpdatedEvents(requestShadowDeltaUpdated, QualityOfService.AT_LEAST_ONCE, ShadowSample::onShadowDeltaUpdated);
subscribedToDeltas.get();
System.out.println("Subscribing to update respones...");
UpdateShadowSubscriptionRequest requestUpdateShadow = new UpdateShadowSubscriptionRequest();
requestUpdateShadow.thingName = thingName;
CompletableFuture<Integer> subscribedToUpdateAccepted = shadow.SubscribeToUpdateShadowAccepted(requestUpdateShadow, QualityOfService.AT_LEAST_ONCE, ShadowSample::onUpdateShadowAccepted);
CompletableFuture<Integer> subscribedToUpdateRejected = shadow.SubscribeToUpdateShadowRejected(requestUpdateShadow, QualityOfService.AT_LEAST_ONCE, ShadowSample::onUpdateShadowRejected);
subscribedToUpdateAccepted.get();
subscribedToUpdateRejected.get();
System.out.println("Subscribing to get responses...");
GetShadowSubscriptionRequest requestGetShadow = new GetShadowSubscriptionRequest();
requestGetShadow.thingName = thingName;
CompletableFuture<Integer> subscribedToGetShadowAccepted = shadow.SubscribeToGetShadowAccepted(requestGetShadow, QualityOfService.AT_LEAST_ONCE, ShadowSample::onGetShadowAccepted);
CompletableFuture<Integer> subscribedToGetShadowRejected = shadow.SubscribeToGetShadowRejected(requestGetShadow, QualityOfService.AT_LEAST_ONCE, ShadowSample::onGetShadowRejected);
subscribedToGetShadowAccepted.get();
subscribedToGetShadowRejected.get();
gotResponse = new CompletableFuture<>();
System.out.println("Requesting current shadow state...");
GetShadowRequest getShadowRequest = new GetShadowRequest();
getShadowRequest.thingName = thingName;
CompletableFuture<Integer> publishedGetShadow = shadow.PublishGetShadow(getShadowRequest, QualityOfService.AT_LEAST_ONCE);
publishedGetShadow.get();
gotResponse.get();
String newValue = "";
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print(SHADOW_PROPERTY + "> ");
System.out.flush();
newValue = scanner.next();
if (newValue.compareToIgnoreCase("quit") == 0) {
break;
}
gotResponse = new CompletableFuture<>();
changeShadowValue(newValue).get();
gotResponse.get();
}
scanner.close();
CompletableFuture<Void> disconnected = connection.disconnect();
disconnected.get();
} catch (CrtRuntimeException | InterruptedException | ExecutionException ex) {
System.out.println("Exception encountered: " + ex.toString());
}
System.out.println("Complete!");
CrtResource.waitForNoResources();
}
Aggregations