웹에서 MQTT 프로토콜을 사용한 원격 제어 LED 램프

7968 단어 MQTT

테스트 환경


mqtt_client (Publish) firefox win10


mqtt_client (Subscribe) ubuntu 12.04


mqtt_broker mosquitto ubuntu 12.04


웹에서 JavaScript Client 다운로드 주소가 필요합니다.


mqtt_client 코드


publish.html



<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <script src="js/mqttws31.js" type="text/javascript">script>
    <title>test_buttontitle>
    <script type="text/javascript">
        var client = new Messaging.Client("127.0.0.1",8000,"myclientid_" + parseInt(Math.random() * 100,10));
        client.onConnectionLost = function(responseObject)
        {
            alert("connection lost:"+responseObject.errorMessage);
        }
        var options = 
        {
            timeout: 3,
            keepAliveInterval:60,
            onSuccess:function()
            {
                //document.getElementById("status").innerHTML = "connected to server";
                alert("connected to server");
            },
            onFailure:function(message)
            {
                //document.getElementById("status").innerHTML = "connect failed";
                alert("connection failed to server");
            }
        }

        function connect()
        {
            //document.getElementById("status").innerHTML = "connecting";
                alert("connecting");
            client.connect(options);
        }

        function disconnect()
        {
            client.disconnect();
                alert("disconnect");
            //document.getElementById("status").innerHTML = "disconnect from server";

        }
        function lamp_on()
        {
            var str = '{"cmd":1}';
            var message = new Messaging.Message(str);
            message.destinationName = "cmd";
            client.send(message);
        }
        function lamp_off()
        {
            var str = '{"cmd":0}';
            var message = new Messaging.Message(str);
            message.destinationName = "cmd";
            client.send(message);
        }
    script>
  head>
  <body>
  <div align="center">
      <input type="button" name="switch_on" value="switch_on" onClick="lamp_on()">
      <input type="button" name="switch_off" value="switch_off" onClick="lamp_off()">
      <input type="button" name="connect" value="connect" onClick="connect()" >
      <input type="button" name="disconnect" value="disconnect" onClick="disconnect()" >
  div>
  <div id="status" align="center">
  div>
  body>
html>

좋은 웹페이지 즐겨찾기