Search code examples
javaazureiotazure-iot-hubazure-iot-edge

Environment variable IOTEDGE_WORKLOADURI is required in Java azure IoT SDK using ModuleClient Class


enter image description here

   public class AzureIoTExample {
    
    private static AzureIoTExample.MessageCallbackMqtt msgCallback = new AzureIoTExample.MessageCallbackMqtt();
      protected static class MessageCallbackMqtt implements MessageCallback {

            @Override
            public IotHubMessageResult execute(Message msg, Object context) {
                return IotHubMessageResult.COMPLETE;
            }

        }
    private static ModuleClient client = null;
    public static void main(String[] args) throws IOException, ModuleClientException {
        IotHubClientProtocol protocol = IotHubClientProtocol.MQTT;
         client = ModuleClient.createFromEnvironment (protocol);
         client.setMessageCallback("Input", msgCallback, client);
         client.registerConnectionStatusChangeCallback(new ConnectionStatusChangeCallback(), null);
         client.open();
       System.out.print(System.getenv("IothubConnectionstringVariableName"));
    }
}

Trying to connect with IoTEdge using Azure Java SDK via ModuleClient Class of azure.sdk.iot.device Package. when I'm running the code. was getting an error i.e., Environment IoTEdge_WorkLoadURI is required.

To Achieve the connection what exactly needs to done and How to Achieve this ??


Solution

    • The code below connects and sends messages to Azure IoT Edge using the Azure IoT Java SDK, generating random temperature and humidity values, and sending them as JSON messages to an IoT Edge device.
    
    
    package org.example;// Import necessary libraries
    import com.microsoft.azure.sdk.iot.device.*;
    import com.microsoft.azure.sdk.iot.device.exceptions.IotHubClientException;
    import com.microsoft.azure.sdk.iot.device.transport.IotHubConnectionStatus;
    
    import java.io.IOException;
    import java.net.URISyntaxException;
    import java.nio.charset.StandardCharsets;
    import java.util.Scanner;
    
    public class SendToIoTEdgeSample {
        private static final int D2C_MESSAGE_TIMEOUT_MILLISECONDS = 10000;
    
        public static void main(String[] args) throws IOException, URISyntaxException, IotHubClientException, InterruptedException {
            // Your IoT Hub connection string and other configurations
            String connString = "IOT_edge_CONNECTION_STRING";
          //  System.getenv("IOT_edge_CONNECTION_STRING");
            int numRequests = 5; // Specify the number of messages to send
    
            // Using MQTT protocol
            IotHubClientProtocol protocol = IotHubClientProtocol.MQTT;
    
           
            System.setProperty("logback.configurationFile", "path/to/logback.xml");
    
            System.out.println("Successfully read input parameters.");
            System.out.format("Using communication protocol %s.\n", protocol.name());
    
            // Create an IoT Hub client
            DeviceClient client = new DeviceClient(connString, protocol);
    
            System.out.println("Successfully created an IoT Hub client.");
    
            // Open connection to IoT Hub (Edge)
            client.open(true);
    
            System.out.println("Opened connection to IoT Hub (Edge).");
    
            System.out.println("Beginning to send messages...");
    
            // Message sending loop
            for (int i = 0; i < numRequests; ++i) {
                double temperature = 20 + Math.random() * 10;
                double humidity = 30 + Math.random() * 20;
    
                String msgStr = "{\"temperature\":" + temperature + ",\"humidity\":" + humidity + "}";
    
                try {
                    Message msg = new Message(msgStr);
                    msg.setContentType("application/json");
                    msg.setProperty("temperatureAlert", temperature > 28 ? "true" : "false");
                    msg.setMessageId(java.util.UUID.randomUUID().toString());
                    msg.setExpiryTime(D2C_MESSAGE_TIMEOUT_MILLISECONDS);
    
                    System.out.println(msgStr);
    
                    // Send the message to the default module on Azure IoT Edge
                    client.sendEvent(msg);
    
                    System.out.println("Successfully sent the message");
                } catch (IotHubClientException e) {
                    System.out.println("Failed to send the message. Status code: " + e.getStatusCode());
                }
            }
    
            // Close the connection
            System.out.println("Closing the client...");
            client.close();
        }
    }
    
    
    • To retrieve the IoT Edge connection string from an environment variable, use the code below:

    String connString = System.getenv("IOTEDGECONNECTIONSTRING");

    pom.xml:

    <dependencies>
        <!-- Azure IoT Device SDK -->
        <dependency>
            <groupId>com.microsoft.azure.sdk.iot</groupId>
            <artifactId>iot-device-client</artifactId>
            <version>2.1.5</version>
        </dependency>
    
        <!-- Azure IoT Service SDK -->
        <dependency>
            <groupId>com.microsoft.azure.sdk.iot</groupId>
            <artifactId>iot-service-client</artifactId>
            <version>2.1.6</version>
        </dependency>
    
        <!-- Logback Classic for Logging -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.6</version>
        </dependency>
    </dependencies>
    
    
    
    

    Output: enter image description here

    enter image description here