Paho Java Client 连接阿里云物联网平台
进入阿里云物联网平台->点击产品->新建
点击设备->添加设备
查看设备证书,复制记录,后面使用
阿里云TCP通信
一机一密、一型一密预注册认证方式:使用设备证书(ProductKey、DeviceName和DeviceSecret)连接。
mqttClientId: clientId+"|securemode=3,signmethod=hmacsha1,timestamp=132323232|"mqttUsername: deviceName+"&"+productKeymqttPassword: sign_hmac(deviceSecret,content)
mqttClientId:格式中| |内为扩展参数。clientId:表示客户端ID,可自定义,长度不可超过64个字符。建议使用设备的MAC地址或SN码,方便您识别区分不同的客户端。securemode:表示目前安全模式,可选值有2(TLS直连模式)和3(TCP直连模式)。signmethod:表示签名算法类型。支持hmacmd5,hmacsha1和hmacsha256,默认为hmacmd5。timestamp:表示当前时间毫秒值,可以不传递。mqttPassword:sign签名需把提交给服务器的参数按字典排序后,根据signmethod加签。签名计算示例,请参见MQTT连接签名示例。content的值为提交给服务器的参数(ProductKey、DeviceName、timestamp和clientId),按照字母顺序排序, 然后将参数值依次拼接。
示例:
假设clientId = 12345,deviceName = device, productKey = pk, timestamp = 789,signmethod=hmacsha1,deviceSecret=secret,那么使用TCP方式提交给MQTT的参数如下
mqttclientId=12345|securemode=3,signmethod=hmacsha1,timestamp=789|mqttUsername=device&pkmqttPassword=hmacsha1("secret","clientId12345deviceNamedeviceproductKeypktimestamp789").toHexString();
加密后的Password为二进制转16制字符串,示例结果为:
FAFD82A3D602B37FB0FA8B7892F24A477F85****
signmethod在线转换工具
Paho Java Client 代码:
参数按照要求填入替换
import org.eclipse.paho.client.mqttv3.MqttClient;import org.eclipse.paho.client.mqttv3.MqttConnectOptions;import org.eclipse.paho.client.mqttv3.MqttException;import org.eclipse.paho.client.mqttv3.MqttMessage;import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;public class AppAliyun {public static void main(String[] args) {String subTopic = "/xxxxx/EG46-01/user/get";String pubTopic = "/xxxxx/EG46-01/user/update";String content = "Hello World";int qos = 2;String broker = "tcp://xxxxx.iot-as--:1883";String clientId = "EG46-01|securemode=3,signmethod=hmacsha1|";MemoryPersistence persistence = new MemoryPersistence();try {MqttClient client = new MqttClient(broker, clientId, persistence);// MQTT 连接选项MqttConnectOptions connOpts = new MqttConnectOptions();connOpts.setUserName("用户名");connOpts.setPassword("密码".toCharArray());// 保留会话connOpts.setCleanSession(true);// 设置回调client.setCallback(new OnMessageCallback());// 建立连接System.out.println("Connecting to broker: " + broker);client.connect(connOpts);System.out.println("Connected");System.out.println("Publishing message: " + content);// 订阅client.subscribe(subTopic);// 消息发布所需参数MqttMessage message = new MqttMessage(content.getBytes());message.setQos(qos);client.publish(pubTopic, message);System.out.println("Message published");/*client.disconnect();System.out.println("Disconnected");client.close();System.exit(0);*/} catch (MqttException me) {System.out.println("reason " + me.getReasonCode());System.out.println("msg " + me.getMessage());System.out.println("loc " + me.getLocalizedMessage());System.out.println("cause " + me.getCause());System.out.println("excep " + me);me.printStackTrace();}}}
数据透传运行效果图: