import static org.fusesource.hawtbuf.Buffer.utf8;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.fusesource.mqtt.client.BlockingConnection;
import org.fusesource.mqtt.client.MQTT;
import org.fusesource.mqtt.client.Message;
import org.fusesource.mqtt.client.QoS;
import org.fusesource.mqtt.client.Topic;
public class MqttUtil {
public static void test(String topic) throws Exception {
Map<String, Object> jsonMap = new HashMap<String, Object>();
MQTT mqtt = new MQTT();
//mqtt连接地址
mqtt.setHost(server_addr, port);
// mqtt.setClientId(clientId);
mqtt.setCleanSession(true);
//mqtt 用户名
mqtt.setUserName(username);
//mqtt 密码
mqtt.setPassword(password);
//16进制字符串转换为Byte型数组
byte[] payload = HexStringToByte("48454C4C4F");
//byte[] payload = {(byte) 0xF0, (byte) 0x9F, (byte) 0x98, (byte) 0x81};
//获取mqtt的连接对象BlockingConnection
BlockingConnection connection = mqtt.blockingConnection();
//连接mqtt
connection.connect();
//mq主题
Topic[] topics = { new Topic(utf8(topic), QoS.AT_LEAST_ONCE) };
//订阅主题
byte[] qoses = connection.subscribe(topics);
//发送消息
connection.publish(topic, payload, QoS.EXACTLY_ONCE, false);
//接收主题消息
Message message;
while (true) {
try {
message = connection.receive(1000, TimeUnit.MILLISECONDS);
System.out.println("1--"+new String(message.getPayload()));
//接收消息
String msg = String.valueOf(message.getPayloadBuffer());
System.out.println("2--"+msg);
String jsonStr = "";
//判断是消息体是ASCII还是HEX
if (msg.substring(0, 3).equals("hex")) {
msg = msg.substring(5);
byte[] bytes = HexStringToByte(msg);
jsonStr = new String(bytes, "utf-8");
System.out.println("3--"+jsonStr);
} else {
jsonStr = msg.substring(7);
System.out.println(jsonStr);
}
} catch (Exception e) {
connection.disconnect();
break;
}
}
}
/**
* 16进制字符串转换为Byte型数组16进制源字符串
*
* @param 16进制字符串
* @return Byte类型数组
*/
public static byte[] HexStringToByte(String hexString) {
hexString = hexString.replace(" ", "");
int len = hexString.length();
if (len % 2 != 0)
return null;
byte[] bufD = new byte[len / 2];
byte[] tmpBuf = hexString.getBytes();
int i = 0, j = 0;
for (i = 0; i < len; i++) {
if (tmpBuf[i] >= 0x30 && tmpBuf[i] <= 0x39)
tmpBuf[i] -= 0x30;
else if (tmpBuf[i] >= 0x41 && tmpBuf[i] <= 0x46)
tmpBuf[i] -= 0x37;
else if (tmpBuf[i] >= 0x61 && tmpBuf[i] <= 0x66)
tmpBuf[i] -= 0x57;
else
tmpBuf[i] = 0xF;
}
for (i = 0, j = 0; i < len; i += 2, j++) {
bufD[j] = (byte) ((tmpBuf[i] << 4) | tmpBuf[i + 1]);
}
return bufD;
}
public static void main(String[] args) throws Exception {
test("myTopic");
}
}
MQTT发送和接收HEX数据
猜你喜欢
转载自blog.csdn.net/qq_34200979/article/details/129044920
今日推荐
周排行