ws.html 8.42 KB
Newer Older
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 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>设备消息监控</title>
    <style>
        html, body {
            height: 100%;
            margin: 0;
            background-color: #3C3F41;
        }

        table {
            width: 100%;
            table-layout: fixed;
            border-collapse: collapse;
        }

        td {
            height: inherit;
            border: 1px solid #555;
        }

        select {
            width: 210px;
            height: 30px;
            margin: 0 auto 5px auto;
            color: #BABABA;
            font-size: 16px;
            padding: 2px;
            border: 1px solid #646464;
            background-color: #414141;
        }

        input {
            width: 100px;
            height: 23px;
            color: #BABABA;
            padding: 2px;
            border: 1px solid #646464;
            background-color: #414141;
        }

        button {
            width: 90px;
            color: #BABABA;
            font-size: 18px;
            border: 1px solid #4C708C;
            background-color: #365880;
        }

        button:active {
            color: #EEE;
            border: 1px solid #6B96B4;
        }

        p {
            color: #BABABA;
            text-align: left;
            white-space: pre-wrap;
            word-wrap: break-word;
            word-break: break-all;
        }

        a {
            color: #FFF;
        }

        .cell {
            height: inherit;
            text-align: center;
            display: flex;
            flex-direction: column;
        }

        .textarea {
            height: inherit;
            overflow: auto;
            background-color: #2B2B2B;
        }

        .tool {
            padding: 10px 0 10px 0;
        }

        ::-webkit-scrollbar {
            width: 10px;
        }

        ::-webkit-scrollbar-thumb {
            background-color: #666;
        }

        ::-webkit-scrollbar-thumb:hover {
            background-color: #777;
        }
    </style>
</head>

<body>
<table id="dev_box">
    <tr>
        <td>
            <div class="cell">
                <div class="textarea" id="dev_text_[idx]"></div>
                <div class="tool">
                    <select id="dev_sel_[idx]">[option]</select>
                    <input type="text" onkeyup="onSearch(this)">
                    <button type="button" onclick="onSub([idx])">订阅</button>
                    <button type="button" onclick="onUnsub([idx])">取消</button>
                    <button type="button" onclick="$('dev_text_[idx]').innerHTML=''">清空</button>
                    <button type="button" onclick="onExport([idx])">导出</button>
                </div>
            </div>
        </td>
    </tr>
</table>
<a href="?s=1,2" target="_blank">1*2</a>
<a href="?s=1,4" target="_blank">1*4</a>
<a href="?s=2,6" target="_blank">2*6</a>

<script type="text/javascript">
    const reg = new RegExp("\\[([^\\[\\]]*?)]", 'igm'); //igm是指分别用于指定区分大小写的匹配、全局匹配和多行匹配。

    const host = window.location.host;
    const domain = '//' + host;

    let eventSource = null;
    const subscriptions = {};

    const $ = function (id) {
        return document.getElementById(id);
    };

    function getQueryVariable(key) {
        const query = window.location.search.substring(1);
        const paramsArr = query.split("&");
        for (let i = 0; i < paramsArr.length; i++) {
            const pair = paramsArr[i].split("=");
            if (pair[0] === key) {
                return pair[1];
            }
        }
        return null;
    }

    const renderForm = function (data) {
        let options = '<option value="">没有可订阅的设备</option>\n';
        if (data && data.length) {
            options = '<option value="">---请选择订阅设备---</option>\n';
            options += data.map(function (device) {
                return `<option value="${device.mobileNo}">${device.mobileNo} - ${device.plateNo}</option>`
            }).join('\n');
        }

        let size = [1, 1];
        const s = getQueryVariable('s');
        if (s)
            size = s.split(',');
        const row = size[0] > 3 ? 3 : size[0];
        const column = size[1] > 6 ? 6 : size[1];

        const height = Math.floor((document.documentElement.clientHeight) / row) - 1;

        const table = $('dev_box');
        const td = table.children[0].children[0].innerHTML;
        let html = '';
        let idx = 0;

        for (let i = 0; i < row; i++) {
            html += `<tr style="height: ${height}px">`;
            for (let j = 0; j < column; j++) {
                html += td.replace(reg, function (node, key) {
                    return ({idx: idx, option: options})[key]
                });
                ++idx;
            }
            html += '</tr>';
        }
        table.innerHTML = html;
    };

    function onSearch(e) {
        let value = e.value;
        let select = e.previousElementSibling;
        if (!select.disabled) {
            const options = select.querySelectorAll('option');
            options[0].selected = true;
            if (value) {
                options.forEach(option => {
                    if (option.innerHTML.search(value) >= 0) {
                        option.selected = true;
                    }
                });
            }
        }
    }

    function onExport(idx) {
        const data = $('dev_text_' + idx).innerText;
        if (data) {
            const a = document.createElement('a');
            a.download = $('dev_sel_' + idx).value + '_' + new Date().toLocaleString().replaceAll(/[^0-9]/g, '_') + '.txt';
            a.href = 'data:text/plain;base64,' + btoa(unescape(encodeURIComponent(data)));
            a.click();
        }
    }

    function onSub(idx) {
        const select = $('dev_sel_' + idx);
        if (select.disabled) {
            return;
        }
        const clientId = select.value;
        if (!clientId) {
            return;
        }
        if (subscriptions[clientId]) {
            alert(`同一设备[${clientId}]不能重复订阅`);
            return;
        }

        select.disabled = true;
        const text = $('dev_text_' + idx);
        text.println = function (data) {
            const c = this.scrollTop + this.offsetHeight + 4;
            const h = this.scrollHeight;

            const p = document.createElement('p');
            p.append(new Date().toLocaleString().replaceAll('/', '-') + ' ');
            p.append(data);
            this.append(p);

            if (c >= h)
                this.scrollTop = this.scrollHeight;
        }

        eventSource.addEventListener(clientId, subscriptions[clientId] = function (event) {
            text.println(event.data);
        });

        fetch(`${domain}/device/sse?sub=1&clientId=${clientId}`, {method: 'post'})
            .then(res => res.json())
            .then(function (res) {
                if (res) {
                    text.println('开始订阅');
                } else {
                    text.println('订阅失败,请刷新页面');
                }
            }).catch(err => text.println('连接服务器失败'));
    }

    function onUnsub(idx) {
        const select = $('dev_sel_' + idx);
        const clientId = select.value;
        if (!clientId) {
            return;
        }

        fetch(`${domain}/device/sse?sub=0&clientId=${clientId}`, {method: 'post'})
            .then(res => res.json())
            .then(function (res) {
                if (res) {
                    console.log(`取消订阅设备[${clientId}]....`);
                    eventSource.removeEventListener(clientId, subscriptions[clientId]);
                    delete subscriptions[clientId];
                    select.disabled = false;
                    $('dev_text_' + idx).println('结束订阅');
                }
            }).catch(err => console.error(err));
    }

    window.onload = function () {
        fetch(`${domain}/device/option`)
            .then(res => res.json())
            .then(function (res) {
                renderForm(res.data);
                eventSource = new EventSource(`${domain}/device/sse`);

                eventSource.addEventListener('open', function (e) {
                    console.log(`建立连接`);
                });

                eventSource.addEventListener('error', function (e) {
                    console.log(`断开连接`);
                });
            }).catch(err => console.error(err));
    }
</script>
</body>
</html>