use of com.microsoft.azure.sdk.iot.device.exceptions.ModuleClientException in project azure-iot-sdk-java by Azure.
the class ModuleInvokeMethodSample method main.
/**
* Receives requests from an IoT Hub. Default protocol is to use
* MQTT transport.
*
* @param args
* args[0] = IoT Hub connection string
* args[1] = protocol (one of 'mqtt' or 'amqps' or 'mqtt_ws' or 'amqps_ws')
* args[2] = the method name
* args[3] = the string payload to send alongside the method invocation
* args[4] = the device id of the device to invoke the method on
* args[5] = (optional) the module id to invoke the method on
*/
public static void main(String[] args) throws IOException, URISyntaxException, ModuleClientException {
System.out.println("Starting...");
System.out.println("Beginning setup.");
if (args.length != 4 && args.length != 5) {
System.out.format("Expected 4 or 5 arguments but received: %d.\n" + "The program should be called with the following args: \n" + "1. (mqtt | https | amqps | amqps_ws | mqtt_ws)\n" + "2. The name of the method to invoke\n" + "3. The string payload to send alongside the method invocation\n" + "4. The id of the device to invoke the method on\n" + "5. (optional) The id of the module to invoke the method on\n", args.length);
return;
}
IotHubClientProtocol protocol;
String protocolStr = args[0];
if (protocolStr.equalsIgnoreCase("https")) {
throw new UnsupportedOperationException("Module Client does not support HTTPS communication");
} else if (protocolStr.equalsIgnoreCase("amqps")) {
protocol = IotHubClientProtocol.AMQPS;
} else if (protocolStr.equalsIgnoreCase("mqtt")) {
protocol = IotHubClientProtocol.MQTT;
} else if (protocolStr.equalsIgnoreCase("amqps_ws")) {
protocol = IotHubClientProtocol.AMQPS_WS;
} else if (protocolStr.equalsIgnoreCase("mqtt_ws")) {
protocol = IotHubClientProtocol.MQTT_WS;
} else {
System.out.format("Expected argument 2 to be one of 'mqtt', 'mqtt_ws', 'amqps' or 'amqps_ws' but received %s\n", protocolStr);
return;
}
String methodName = args[1];
String methodPayload = args[2];
String deviceIdToInvokeOn = args[3];
String moduleIdToInvokeOn = args.length > 4 ? args[4] : null;
ModuleClient client = ModuleClient.createFromEnvironment(protocol);
client.open();
MethodRequest methodRequest = new MethodRequest(methodName, methodPayload);
MethodResult result;
try {
if (moduleIdToInvokeOn == null || moduleIdToInvokeOn.isEmpty()) {
result = invokeMethodOnDevice(methodName, deviceIdToInvokeOn, client, methodRequest);
} else {
result = invokeMethodOnModule(methodName, deviceIdToInvokeOn, moduleIdToInvokeOn, client, methodRequest);
}
System.out.println("Received response status: " + result.getStatus());
System.out.println("Received response payload: " + result.getPayloadObject());
} catch (ModuleClientException e) {
System.out.println("Encountered an exception while invoking method");
e.printStackTrace();
} finally {
client.closeNow();
}
}
use of com.microsoft.azure.sdk.iot.device.exceptions.ModuleClientException in project azure-iot-sdk-java by Azure.
the class ModuleGlue method invokeDeviceMethod.
public void invokeDeviceMethod(String connectionId, String deviceId, Object methodInvokeParameters, Handler<AsyncResult<Object>> handler) {
ModuleClient client = getClient(connectionId);
if (client == null) {
handler.handle(Future.failedFuture(new MainApiException(500, "invalid connection id")));
} else {
JsonObject params = (JsonObject) methodInvokeParameters;
String methodName = params.getString("methodName");
String payload = params.getString("payload");
int responseTimeout = params.getInteger("responseTimeoutInSeconds", 0);
int connectionTimeout = params.getInteger("connectTimeoutInSeconds", 0);
MethodRequest request = new MethodRequest(methodName, payload, responseTimeout, connectionTimeout);
try {
MethodResult result = client.invokeMethod(deviceId, request);
handler.handle(Future.succeededFuture(makeMethodResultThatEncodesCorrectly(result)));
} catch (ModuleClientException e) {
handler.handle(Future.failedFuture(e));
}
}
}
use of com.microsoft.azure.sdk.iot.device.exceptions.ModuleClientException in project azure-iot-sdk-java by Azure.
the class ModuleGlue method invokeModuleMethod.
public void invokeModuleMethod(String connectionId, String deviceId, String moduleId, Object methodInvokeParameters, Handler<AsyncResult<Object>> handler) {
ModuleClient client = getClient(connectionId);
if (client == null) {
handler.handle(Future.failedFuture(new MainApiException(500, "invalid connection id")));
} else {
JsonObject params = (JsonObject) methodInvokeParameters;
String methodName = params.getString("methodName");
String payload = params.getString("payload");
int responseTimeout = params.getInteger("responseTimeoutInSeconds", 0);
int connectionTimeout = params.getInteger("connectTimeoutInSeconds", 0);
MethodRequest request = new MethodRequest(methodName, payload, responseTimeout, connectionTimeout);
try {
MethodResult result = client.invokeMethod(deviceId, moduleId, request);
handler.handle(Future.succeededFuture(makeMethodResultThatEncodesCorrectly(result)));
} catch (ModuleClientException e) {
handler.handle(Future.failedFuture(e));
}
}
}
use of com.microsoft.azure.sdk.iot.device.exceptions.ModuleClientException in project azure-iot-sdk-java by Azure.
the class ModuleClient method invokeMethod.
/**
* Invoke a method on a device
* @param deviceId the device to invoke a method on
* @param methodRequest the request containing the method to invoke on the device
* @return the result of the method call
* @throws ModuleClientException if the method cannot be invoked
* @throws IllegalArgumentException if deviceid is null or empty
*/
public MethodResult invokeMethod(String deviceId, MethodRequest methodRequest) throws ModuleClientException, IllegalArgumentException {
if (deviceId == null || deviceId.isEmpty()) {
// Codes_SRS_MODULECLIENT_34_039: [If the provided deviceId is null or empty, this function shall throw an IllegalArgumentException.]
throw new IllegalArgumentException("DeviceId cannot be null or empty");
}
try {
// Codes_SRS_MODULECLIENT_34_033: [This function shall create an HttpsTransportManager and use it to invoke the method on the device.]
HttpsTransportManager httpsTransportManager = new HttpsTransportManager(this.config);
httpsTransportManager.open();
return httpsTransportManager.invokeMethod(methodRequest, deviceId, "");
} catch (URISyntaxException | IOException | TransportException e) {
// Codes_SRS_MODULECLIENT_34_034: [If this function encounters an exception, it shall throw a moduleClientException with that exception nested.]
throw new ModuleClientException("Could not invoke method", e);
}
}
use of com.microsoft.azure.sdk.iot.device.exceptions.ModuleClientException in project azure-iot-sdk-java by Azure.
the class ModuleClient method createFromEnvironment.
/**
* Create a module client instance from your environment variables
* @param protocol the protocol the module client instance will use
* @param clientOptions The options that allow configuration of the module client instance during initialization
* @return the created module client instance
* @throws ModuleClientException if the module client cannot be created
*/
public static ModuleClient createFromEnvironment(IotHubClientProtocol protocol, ClientOptions clientOptions) throws ModuleClientException {
log.info("Creating module client from environment with protocol {}...", protocol);
Map<String, String> envVariables = System.getenv();
// Codes_SRS_MODULECLIENT_34_013: [This function shall check for a saved edgehub connection string.]
log.debug("Checking for an edgehub connection string...");
String connectionString = envVariables.get(EdgehubConnectionstringVariableName);
if (connectionString == null) {
log.debug("No edgehub connection string was configured, checking for an IoThub connection string...");
// Codes_SRS_MODULECLIENT_34_019: [If no edgehub connection string is present, this function shall check for a saved iothub connection string.]
connectionString = envVariables.get(IothubConnectionstringVariableName);
}
// First try to create from connection string and if env variable for connection string is not found try to create from edgedUri
if (connectionString != null) {
log.debug("Creating module client with the provided connection string");
// Codes_SRS_MODULECLIENT_34_020: [If an edgehub or iothub connection string is present, this function shall create a module client instance using that connection string and the provided protocol.]
ModuleClient moduleClient;
try {
moduleClient = new ModuleClient(connectionString, protocol, clientOptions);
} catch (URISyntaxException e) {
throw new ModuleClientException("Could not create module client", e);
}
// Check for a different default cert to be used
String alternativeDefaultTrustedCert = envVariables.get(EdgeCaCertificateFileVariableName);
if (alternativeDefaultTrustedCert != null && !alternativeDefaultTrustedCert.isEmpty()) {
log.debug("Configuring module client to use the configured alternative trusted certificate");
// Codes_SRS_MODULECLIENT_34_031: [If an alternative default trusted cert is saved in the environment
// variables, this function shall set that trusted cert in the created module client.]
moduleClient.setOption_SetCertificatePath(alternativeDefaultTrustedCert);
}
return moduleClient;
} else {
log.info("No connection string was configured for this module, so it will get its credentials from the edgelet");
// Codes_SRS_MODULECLIENT_34_014: [This function shall check for environment variables for edgedUri, deviceId, moduleId,
// hostname, authScheme, gatewayHostname, and generationId. If any of these other than gatewayHostname is missing,
// this function shall throw a ModuleClientException.]
String edgedUri = envVariables.get(IotEdgedUriVariableName);
String deviceId = envVariables.get(DeviceIdVariableName);
String moduleId = envVariables.get(ModuleIdVariableName);
String hostname = envVariables.get(IotHubHostnameVariableName);
String authScheme = envVariables.get(AuthSchemeVariableName);
String gatewayHostname = envVariables.get(GatewayHostnameVariableName);
String generationId = envVariables.get(ModuleGenerationIdVariableName);
if (edgedUri == null) {
throw new ModuleClientException("Environment variable " + IotEdgedUriVariableName + " is required.");
}
if (deviceId == null) {
throw new ModuleClientException("Environment variable " + DeviceIdVariableName + " is required.");
}
if (moduleId == null) {
throw new ModuleClientException("Environment variable " + ModuleIdVariableName + " is required.");
}
if (hostname == null) {
throw new ModuleClientException("Environment variable " + IotHubHostnameVariableName + " is required.");
}
if (authScheme == null) {
throw new ModuleClientException("Environment variable " + AuthSchemeVariableName + " is required.");
}
if (generationId == null) {
throw new ModuleClientException("Environment variable " + ModuleGenerationIdVariableName + " is required");
}
if (!authScheme.equalsIgnoreCase(SasTokenAuthScheme)) {
// Codes_SRS_MODULECLIENT_34_030: [If the auth scheme environment variable is not "SasToken", this function shall throw a moduleClientException.]
throw new ModuleClientException("Unsupported authentication scheme. Supported scheme is " + SasTokenAuthScheme + ".");
}
SignatureProvider signatureProvider;
try {
signatureProvider = new HttpHsmSignatureProvider(edgedUri, DEFAULT_API_VERSION);
} catch (NoSuchAlgorithmException | URISyntaxException e) {
throw new ModuleClientException("Could not use Hsm Signature Provider", e);
}
try {
// Codes_SRS_MODULECLIENT_34_017: [This function shall create an authentication provider using the created
// signature provider, and the environment variables for deviceid, moduleid, hostname, gatewayhostname,
// and the default time for tokens to live and the default sas token buffer time.]
IotHubAuthenticationProvider iotHubAuthenticationProvider = IotHubSasTokenHsmAuthenticationProvider.create(signatureProvider, deviceId, moduleId, hostname, gatewayHostname, generationId, DEFAULT_SAS_TOKEN_TIME_TO_LIVE_SECONDS, DEFAULT_SAS_TOKEN_BUFFER_PERCENTAGE);
// Codes_SRS_MODULECLIENT_34_018: [This function shall return a new ModuleClient instance built from the created authentication provider and the provided protocol.]
ModuleClient moduleClient = new ModuleClient(iotHubAuthenticationProvider, protocol, SEND_PERIOD_MILLIS, getReceivePeriod(protocol));
if (gatewayHostname != null && !gatewayHostname.isEmpty()) {
// Codes_SRS_MODULECLIENT_34_032: [This function shall retrieve the trust bundle from the hsm and set them in the module client.]
TrustBundleProvider trustBundleProvider = new HttpsHsmTrustBundleProvider();
String trustCertificates = trustBundleProvider.getTrustBundleCerts(edgedUri, DEFAULT_API_VERSION);
moduleClient.setTrustedCertificates(trustCertificates);
}
return moduleClient;
} catch (IOException | TransportException | HsmException | URISyntaxException e) {
throw new ModuleClientException(e);
}
}
}
Aggregations