我是Java新手,我正在尝试创建一个可以向Azure IoT Hub发送信息的OPC UA客户端。
每次OPC UA客户端从OPC UA服务器读取值时,必须将该值和节点名称发送到Azure IoT Hub。
我遵循了本教程https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-java-java-getstarted#comments-container,并成功创建了一个能够连接到Hub并向其发送消息的模拟设备。
另一方面,我有一个OPC UA客户端,它可以连接OPC UA服务器并从中读取值。
我使用上面链接的示例中的代码来修改我的OPC UA客户端,以便在读取操作中向Hub发送消息。我正在使用与教程中使用的相同的连接字符串和设备ID。
我能够构建并运行修改后的OPC UA客户端,但消息不会到达Hub。
我注意到执行卡在语句“client_azure.open()”中大约10分钟,然后继续执行,所以我相信它无法打开与Hub的连接,但我不知道不知道为什么。
我的代码是这样的:
public class OPCUAclient { //main class of the OPC UA client
private static String connString = "HostName=XXXXX;DeviceId=YYYYYY;SharedAccessKey=ZZZZZZZ";
private static IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
private static String deviceId = "YYYYYYY";
private static DeviceClient client_azure;
public static void main(String[] args) throws Exception, IOException, URISyntaxException {
client_azure = new DeviceClient(connString, protocol);
client_azure.open(); //Here is where the application takes like 10 minutes to react
.
.
.
azure_client.close()
}
//OPC UA code
.
.
.
//inside a method of the OPC UA code, I execute the following
MessageSender sender = new MessageSender();
ExecutorService executor = Executors.newFixedThreadPool(1);
executor.execute(sender);
//System.out.println("Press ENTER to exit.");
//System.in.read();
executor.shutdownNow();
.
.
.
//At the end of the OPCUAclient class, the following methods are defined
private static class TelemetryDataPoint {
public String deviceId;
public String node;
public int value;
TelemetryDataPoint(int value_t, String node_t){
value = value_t;
node=node_t;
}
public String serialize() {
Gson gson = new Gson();
return gson.toJson(this);
}
}
private static class EventCallback implements IotHubEventCallback
{
public void execute(IotHubStatusCode status, Object context) {
System.out.println("IoT Hub responded to message with status: " + status.name());
if (context != null) {
synchronized (context) {
context.notify();
}
}
}
}
private static class MessageSender implements Runnable {
public int value;
public String node; //NodeId
MessageSender(){
value = 1; //value_azure;
node = "Blue"; //node_azure;
}
public void run() {
try{
TelemetryDataPoint telemetryDataPoint = new TelemetryDataPoint(value, node);
telemetryDataPoint.deviceId = deviceId;
String msgStr = telemetryDataPoint.serialize();
Message msg = new Message(msgStr);
System.out.println("Sending: " + msgStr);
Object lockobj = new Object();
EventCallback callback = new EventCallback();
client_azure.sendEventAsync(msg, callback, lockobj);
synchronized (lockobj) {
lockobj.wait();
}
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Finished.");
}
}
}
}
我的代码有什么问题吗?
提前致谢