使用 ModuleClient 类的 Java azure IoT SDK 中需要环境变量 IOTEDGE_WORKLOADURI

问题描述 投票:0回答:1

   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"));
    }
}

尝试通过 azure.sdk.iot.device 包的 ModuleClient 类使用 Azure Java SDK 连接 IoTEdge。 当我运行代码时。收到错误,即需要环境 IoTEdge_WorkLoadURI。

要实现连接到底需要做什么以及如何实现这一点??

java azure iot azure-iot-hub azure-iot-edge
1个回答
0
投票
  • 下面的代码使用 Azure IoT Java SDK 连接并向 Azure IoT Edge 发送消息,生成随机温度和湿度值,并将它们作为 JSON 消息发送到 IoT Edge 设备。


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();
    }
}

  • 要从环境变量中检索 IoT Edge 连接字符串,请使用以下代码:

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>



输出: enter image description here

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.