iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 3
0
IoT

簡簡單單的MQTT入門系列 第 3

Java 的 mqtt client

  • 分享至 

  • xImage
  •  

各種主流的程式語言都有MQTT Client libraries,包含C、C++、Go、Java、Javascript / Node.js
、Objective-C、dotNET、PHP、Python、Swift等,請看官網上的介紹
Arduino從程式庫管理員亦可查到多個MQTT Client libraries。

筆者使常用的程式語言是Java,選擇的mqtt client是fusesource mqtt client

訂閱

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 Sub {

	final static String TOPIC_NAME = "temperature/Wuling";
	final static String IP = "127.0.0.1";
	final static int PORT = 1883;

	public static void main(String[] args) throws Exception {
		MQTT mqtt = new MQTT();
		mqtt.setHost(IP, PORT); // 設定ip和port
		BlockingConnection connection = mqtt.blockingConnection();
		connection.connect(); // 連接Broker
		System.out.println("Connected to Broker!");
		//設置Topic,傳送品質為EXACTLY_ONCE
		Topic[] topics = { new Topic(TOPIC_NAME, QoS.EXACTLY_ONCE) };
		connection.subscribe(topics);

		while (true) {
			//取得訊息
			Message message = connection.receive(10, TimeUnit.SECONDS);
			if (message != null) {
				System.out.println("Received messages. " + new String(message.getPayload()));
				message.ack(); // 返回ack,告知Broker收到訊息
			}
		}

	}

}

發佈

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.fusesource.mqtt.client.BlockingConnection;
import org.fusesource.mqtt.client.MQTT;
import org.fusesource.mqtt.client.QoS;

public class Pub {

	final static String TOPIC_NAME = "temperature/Wuling";
	final static String IP = "127.0.0.1";
	final static int PORT = 1883;
	final static SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");

	public static void main(String[] args) throws Exception {
		MQTT mqtt = new MQTT();
		mqtt.setHost(IP, PORT); // 設定ip和port
		BlockingConnection connection = mqtt.blockingConnection();
		connection.connect(); // 連接Broker
		System.out.println("Connected to Broker!");
		while (true) {
			String value = createRandom();
			//發佈訊息,TOPIC為"temperature/Wuling",設置傳送品質為AT_LEAST_ONCE,不保留訊息
			connection.publish(TOPIC_NAME, value.getBytes(), QoS.AT_LEAST_ONCE, false);
			System.out.println("Sent messages with temperature=" + value);
			Thread.sleep(1000);
		}
	}

	public static String createRandom() {
		return  
			sdf.format(new Date()) + ":" +
			new BigDecimal(Math.random() * -10 + 30).setScale(1, RoundingMode.FLOOR).toPlainString();
	}
}

上一篇
安裝Broker-VerneMQ
下一篇
很棒的教學資料
系列文
簡簡單單的MQTT入門23
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言