<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="format-detection" content="telephone=no">
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
<meta name="renderer" content="webkit">
<!-- 移动设备 viewport -->
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
<jsp:include page="../../common.jsp" />
  <script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.js" type="text/javascript"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/crypto-js.js" type="text/javascript"></script>
</head>
<body>
    <a onclick="send()">发送MQTT消息</a>
</body>
<%--<script>
  var hostname = "mqtt-cn-oew1viggh03.mqtt.aliyuncs.com";      //主机IP  106.14.181.32    此域名已不是我在使用了(2019-6-16注)
  var port = 1883;
  var clientid = "GID_SHOUYINBEI@@@0101170001542";
  var timeout = 5;
  var keepAlive = 100;
  var cleanSession = false;
  var ssl = false;
  var client;
  var topic = "SYB_TOPIC_SHOUYINBEI/order/GID_SHOUYINBEI@@@0101170001542";

  function init (){
    client = new Paho.MQTT.Client(hostname, port, clientid);
    var options = {
      invocationContext: {
        host: hostname,
        port: port,
        path: client.path,
        clientId: clientid
      },
      timeout: timeout,
      keepAliveInterval: keepAlive,
      cleanSession: cleanSession,
      useSSL: ssl,
      // userName: userName,
      // password: password,
      onSuccess: onConnect,
      onFailure: function (e) {
        console.log(e);
        s = "{time:" + new Date().Format("yyyy-MM-dd hh:mm:ss") + ", onFailure()}";
        console.log(s);
      }
    };
    client.connect(options);

    client.onConnectionLost = onConnectionLost;

    //注册连接断开处理事件
    client.onMessageArrived = onMessageArrived;

  }

  init();

  function onConnectionLost(responseObject) {
    console.log(responseObject);
    s = "{time:" + new Date().Format("yyyy-MM-dd hh:mm:ss") + ", onConnectionLost()}";
    console.log(s);
    if (responseObject.errorCode !== 0) {
      console.log("onConnectionLost:" + responseObject.errorMessage);
      console.log("连接已断开");
    }
  }

  function onMessageArrived(message) {
    s = "{time:" + new Date().Format("yyyy-MM-dd hh:mm:ss") + ", onMessageArrived()}";
    console.log(s);
    console.log("收到消息:" + message.payloadString);
  }

  function send() {
    var msgText = {};
    msgText.type = "trans_cancel";
    msgText.orderId = "D00"+new Date().getTime();
    msgText.cancelTime = new Date().Format("yyyy-MM-dd HH:mm:ss");
    message = new Paho.MQTT.Message(JSON.stringify(msgText));
    message.destinationName = topic;
    client.send(message);
  }

  var count = 0;

  function start() {
    window.tester = window.setInterval(function () {
      if (client.isConnected) {
        var s = "{time:" + new Date().Format("yyyy-MM-dd hh:mm:ss") + ", content:" + (count++) +
                ", from: web console}";
        message = new Paho.MQTT.Message(s);
        message.destinationName = topic;
        client.send(message);
      }
    }, 1000);
  }

  function stop() {
    window.clearInterval(window.tester);
  }


  function onConnect() {
    console.log("onConnected");
    s = "{time:" + new Date().Format("yyyy-MM-dd hh:mm:ss") + ", onConnected()}";
    console.log(s);
    client.subscribe(topic);
  }

  Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
      "M+": this.getMonth() + 1, //月份
      "d+": this.getDate(), //日
      "h+": this.getHours(), //小时
      "m+": this.getMinutes(), //分
      "s+": this.getSeconds(), //秒
      "q+": Math.floor((this.getMonth() + 3) / 3), //季度
      "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
      if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[
              k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
  }
</script>--%>

<script type="text/javascript">
  var instanceId = 'mqtt-cn-oew1viggh03';//实例 ID，购买后从控制台获取
  var host = 'mqtt-cn-oew1viggh03.mqtt.aliyuncs.com';// 设置当前用户的接入点域名，接入点获取方法请参考接入准备章节文档，先在控制台创建实例
  var port = 80;//WebSocket 协议服务端口，如果是走 HTTPS，设置443端口
  var topic = 'SYB_TOPIC_SHOUYINBEI';//需要操作的 Topic,第一级父级 topic 需要在控制台申请
  var useTLS = false;//是否走加密 HTTPS，如果走 HTTPS，设置为 true
  var accessKey = 'LTAI4G25PY4Tebxq4gCrhtF5';//账号的 AccessKey，在阿里云控制台查看
  var secretKey = 'dUc1KMRqfvJI2AzOPKXYrWe3Hnmict';//账号的的 SecretKey，在阿里云控制台查看
  var cleansession = true;
  var groupId = 'GID_SHOUYINBEI';//MQTT GroupID,创建实例后从 MQTT 控制台创建
  var clientId = groupId + '@@@0101170001542';//GroupId@@@DeviceId，由控制台创建的 Group ID 和自己指定的 Device ID 组合构成
  var mqtt;
  var reconnectTimeout = 2000;
  var username = 'Signature|' + accessKey + '|' + instanceId;//username和 Password 签名模式下的设置方法，参考文档 https://help.aliyun.com/document_detail/48271.html?spm=a2c4g.11186623.6.553.217831c3BSFry7
  var password = CryptoJS.HmacSHA1(clientId, secretKey).toString(CryptoJS.enc.Base64);

  function MQTTconnect() {
    mqtt = new Paho.MQTT.Client(
            host,//MQTT 域名
            port,//WebSocket 端口，如果使用 HTTPS 加密则配置为443,否则配置80
            clientId//客户端 ClientId
    );
    var options = {
      timeout: 3,
      onSuccess: onConnect,
      mqttVersion: 4,
      cleanSession: cleansession,
      onFailure: function (message) {
        setTimeout(MQTTconnect, reconnectTimeout);
      }
    };
    mqtt.onConnectionLost = onConnectionLost;
    mqtt.onMessageArrived = onMessageArrived;
    if (username != null) {
      options.userName = username;
      options.password = password;
      options.useSSL = useTLS;//如果使用 HTTPS 加密则配置为 true
    }
    mqtt.connect(options);
  }

  function onConnect() {
      console.log("连接成功！")
    /*var msgText = {};
    msgText.type = "trans_cancel";
    msgText.orderId = "D00"+new Date().getTime();
    msgText.cancelTime = dateFormat("YYYY-mm-dd HH:MM:SS",new Date());
    console.log(msgText);
    // Connection succeeded; subscribe to our topic
    //发送 P2P 消息，topic 设置方式参考https://help.aliyun.com/document_detail/96176.html?spm=a2c4g.11186623.6.586.694f7cb4oookL7
    message = new Paho.MQTT.Message(JSON.stringify(msgText));//set body
    message.destinationName = topic + "/order/" + clientId;// set topic
    mqtt.send(message);*/
  }

  function onConnectionLost(response) {
    setTimeout(MQTTconnect, reconnectTimeout);
  };

  function onMessageArrived(message) {
    var topic = message.destinationName;
    var payload = message.payloadString;
    console.log("recv msg : " + topic + "   " + payload);
  };
  MQTTconnect();

  function dateFormat(fmt, date) {
    let ret;
    const opt = {
      "Y+": date.getFullYear().toString(),        // 年
      "m+": (date.getMonth() + 1).toString(),     // 月
      "d+": date.getDate().toString(),            // 日
      "H+": date.getHours().toString(),           // 时
      "M+": date.getMinutes().toString(),         // 分
      "S+": date.getSeconds().toString()          // 秒
      // 有其他格式化字符需求可以继续添加，必须转化成字符串
    };
    for (let k in opt) {
      ret = new RegExp("(" + k + ")").exec(fmt);
      if (ret) {
        fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
      };
    };
    return fmt;
  }

  function send() {
      var msgText = {};
      msgText.type = "trans_cancel";
      msgText.orderId = "D00"+new Date().getTime();
      msgText.cancelTime = dateFormat("YYYY-mm-dd HH:MM:SS",new Date());
      console.log(msgText);
      message = new Paho.MQTT.Message(JSON.stringify(msgText));
      var sendTopic  = topic + "/order/"+ clientId;
      message.destinationName = sendTopic;
      mqtt.send(message);
  }
</script>

</html>

