web采用MQTT协议远程控制LED灯

测试环境

mqtt_client (Publish) firefox win10

mqtt_client (Subscribe) ubuntu 12.04

mqtt_broker mosquitto ubuntu 12.04

web端需要用到JavaScript Client 下载地址

mqtt_client (Publish)代码

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>

你可能感兴趣的:(MQTT)