Repository navigation
Expand file tree
/
Copy pathazure_connect.java
More file actions
63 lines (59 loc) · 2.27 KB
/
Copy pathazure_connect.java
File metadata and controls
63 lines (59 loc) · 2.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package azure;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttAsyncClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
public class azure_connect {
public void connect(String deviceId,String key,String hub) {
String uri = hub+"/devices/"+deviceId;
String sasToken = sastoken.GetSASToken(uri," ",key);
System.out.println("-----------Sastoken: " + sasToken);
String brokerUri = "ssl://"+hub+":8883";
String clientId = deviceId;
String Username = hub+"/"+deviceId+"/?api-version=2021-04-12";
System.out.println("-----------Username: " + Username);
System.out.println( "Connecting to " + brokerUri +" as "+clientId);
MqttAsyncClient client = null;
try {
client = new MqttAsyncClient( brokerUri, clientId );
String topic = "devices/"+deviceId+"/messages/events/";
String content = "{device:123}";
MqttMessage message = new MqttMessage(content.getBytes());
if (client != null) {
MqttConnectOptions options = new MqttConnectOptions();
options.setUserName(Username);
options.setPassword(sasToken.toCharArray());
options.setCleanSession(true);
options.setConnectionTimeout(30);
options.setKeepAliveInterval(0);
IMqttToken token = client.connect(options);
//System.out.println("Connecting to " + brokerUri + " as " + clientId);
token.waitForCompletion(6000);
//System.out.println("Connecting to " + brokerUri + " as " + clientId);
if (client.isConnected()) {
System.out.println("Success!");
client.publish(topic, message);
System.out.println("Message published");
System.out.println("topic: " + topic);
System.out.println("message content: " + content);
// disconnect
client.disconnect();
// close client
client.close();
} else {
System.out.println("Could not connect to Azure IoT hub, timed-out");
}
}
} catch ( MqttException e ) {
client.getDebug().dumpBaseDebug();
e.printStackTrace();
} finally {
if ( client != null ) {
try {
client.disconnect();
} catch ( MqttException ignore ) {}
}
}
}
}