Javascript MQTT 웹소켓 통신

- 자바스크립트를 이용하여 MQTT 통신

1. js 다운로드 : 

 

mqttws31-min.js
0.03MB
mqttws31.js
0.08MB

 

2. javascript

- 예제 함수 

  • stratConnect() : 랜덤으로 client ID를 생성하여 MQTT Broker에 연결
  • onConnect() : 연결성공 후 topic 설정하여 subscribe 준비
  • onConnectionLost(responseObject) : 연결이 끊길경우 error message 출력
  • onMessageArrived(message) : subscribe message 출력
  • publish(element) : publish message 전송 / element는 HTML 버튼 선택자 (버튼 클릭시 ON/OFF 메시지 전송)
  • startDisconnect() : 연결 종료
// Called after form input is processed
function startConnect() {
    // random client ID 생성
    clientID = "clientID-" + parseInt(Math.random() * 100);

    // broker IP , broker websocket port
    host = "브로커아이피";
    port = "브로커웹소켓포트";

    console.log("Connecting to: "+host+"  on port: "+port+" / clinet value: "+clientID);

    // connection
    client = new Paho.MQTT.Client(host, Number(port), clientID);

    // callback
    client.onConnectionLost = onConnectionLost;

    // Connect the client, if successful, call onConnect function
    client.connect({ 
        onSuccess: onConnect
    });
}

function onConnect() {
    
    topic = "#"; //MQTT 토픽명 (#은 모든 토픽 허용)

    // Print output
    console.log("Subscriving to: "+topic);

    // Subscribe to the requested topic
    client.subscribe(topic);
    client.onMessageArrived = onMessageArrived;

}

// connection error
function onConnectionLost(responseObject) {
    document.getElementById("messages").innerHTML += '<span>ERROR: Connection lost</span><br/>';
    if (responseObject.errorCode !== 0) {
        document.getElementById("messages").innerHTML += '<span>ERROR: ' + + responseObject.errorMessage + '</span><br/>';
    }
}

// subsribe output
function onMessageArrived(message) {
    console.log("onMessageArrived: " + message.payloadString);
}

// send a message (publish)
function publish (element) {
	
	var topic = $(element).attr("id"); //버튼의 id를 topic으로 설정
	
	if(element.checked == true){
		var message = "ON";
	} else {
		var message = "OFF";
	}
	
    message = new Paho.MQTT.Message(message);
    message.destinationName = topic;
    message.qos = 2;

    client.send(message);
}


// disconnection
function startDisconnect() {
    client.disconnect();
    document.getElementById("messages").innerHTML += '<span>Disconnected</span><br/>';
}

 

 

 

+ Recent posts