본문 바로가기

IT, 개발/웹개발

자바스크립트 MQTT 통신 예제 (mqttws31.js / mqttws31-min.js)

728x90
반응형

mosquitto

 

MQTT client 연결하여 메시지 받는 방법과 메시지 보내는 방법에 대해 알아보도록 하겠습니다.
저는 웹 개발하면서 모든 화면에서 include 하는 header 파일에 MQTT 클라이언트 코드를 작성하고 각 화면에서 사용하였습니다.

 


우선 MQTT 통신을 위한 js 파일을 준비해야합니다.

아래 두 파일을 미리 준비하시면 좋을 것 같습니다.

 

1. mqttws31.js
2. mqttws31-min.js

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

 

head 태그에 다운로드한 js 파일(경로 포함)을 넣어줍니다.

 

<head>
    <script src="/yourpath/mqttws31.js"></script>
    <script src="/yourpath/mqttws31-min.js"></script>
</head>

 

 

다음은 스크립트 예제입니다.

 

 

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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<script>
 
$(document).ready(function(){
    
    // function 실행
    fncStartMqtt();
    
});
 
 
// MQTT client
var mqttClient= null;
 
//MQTT info
// 각자 상황에 맞는 host, port, topic 을 사용합니다.
var mqtt_host = "192.168.0.1";
var mqtt_port = "1883";
var mqtt_clientId = "clientID-" + parseInt(Math.random() * 100);        // 랜덤 클라이언트 ID 
var mqtt_topic = "testTopic";
 
// MQTT 클라이언트 연결
function fncStartMqtt() 
{
    mqttClient = new Paho.MQTT.Client(mqtt_host, Number(mqtt_port), mqtt_clientId);
 
    mqttClient.onConnectionLost = onConnectionLost;
    mqttClient.onMessageArrived = onMessageArrived;
 
    mqttClient.connect({
        onSuccess : onConnect
        , onFailure : onFailure
    });
}
 
// 연결 성공 시 실행되는 function
function onConnect() 
{
    console.log("connet : onConnect..");
 
    mqttClient.subscribe(mqtt_topic);
}
 
// 연결 실패 시 실행되는 function
function onFailure() 
{
    console.log("connet : onFailure..");
 
}
 
 
 
function onConnectionLost(responseObject) 
{
    if (responseObject.errorCode !== 0
    {
        console.log("onConnectionLost : " + responseObject.errorMessage);
 
        // 연결 재시도
        fncConnMqtt();
    }
}
 
// 메시지 받는 부분
function onMessageArrived(message) 
{
    console.log("onMessageArrived : " + message.payloadString);
 
    // mqtt 받은 메시지 
    // 받은 메시지를 각 화면에서 사용하려면 각 화면에서 아래 function 선언하여 사용
    fncMqttAction(message.payloadString);
}
 
 
 
// 메시지 보내기
// 각 화면에서 메시지를 보내려면 각 화면에서 아래 function 선언하여 사용
function fncMqttDoSend(sendMsg) 
{
    mqttClient.send(mqtt_topic, sendMsg);
}
 
</script>
cs

 

 


※ 받은 메시지를 각 화면에서 선언 시 

function fncMqttAction(mqttMsg)
{

}

 

※ 각 화면에서 메시지 보내기 사용하려면 

fncMqttDoSend("보낼메시지");

 

 

 

 

 

728x90
반응형