-
Notifications
You must be signed in to change notification settings - Fork 4
/
js_fragments.cpp
80 lines (79 loc) · 2.4 KB
/
js_fragments.cpp
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
#include <Arduino.h>
const String js_log_script =
"var ws\n"
"var log\n"
"var input\n"
"var button\n"
"var indicator\n"
"var attempt = 0\n"
"var reconnect_delay = 1000\n"
"function start(){\n"
"console.log(\"connecting\")\n"
"setConnected(false)\n"
"ws = new WebSocket(\"ws://\" + window.location.host + ':' + log.dataset['port'])\n"
"ws.onmessage = onMessage\n"
"ws.onopen = onOpen\n"
"ws.onerror = onError\n"
"ws.onclose = onClose\n"
"}\n"
"function getStartDelay(){\n"
"if (attempt == 0){\n"
"return 0\n"
"} else{\n"
"return reconnect_delay\n"
"}\n"
"}\n"
"function onOpen(){\n"
"console.log(\"open\")\n"
"attempt = 0\n"
"setConnected(true)\n"
"}\n"
"function onError(){\n"
"console.log(\"error\",attempt)\n"
"attempt += 1\n"
"setTimeout(start,getStartDelay())\n"
"}\n"
"function onClose(){\n"
"console.log(\"close\")\n"
"setTimeout(start,getStartDelay())\n"
"}\n"
"function onMessage(event){\n"
"console.log(\"data\",event.data)\n"
"var z = document.getElementById('empty')\n"
"if (z){z.remove()}\n"
"var data = JSON.parse(event.data)\n"
"var e = document.createElement('div')\n"
"e.textContent = data.sentence\n"
"e.className = 'from-' + data.source\n"
"var scrolledAtBottom = log.clientHeight + log.scrollTop == log.scrollHeight\n"
"log.appendChild(e)\n"
"if (scrolledAtBottom){\n"
"log.scrollTop = log.scrollHeight\n"
"}\n"
"}\n"
"function onSend(){\n"
"if (ws && ws.readyState == WebSocket.OPEN){\n"
"console.log(\"send\",input.value)\n"
"ws.send(input.value + '\\r\\n')\n"
"input.value = ''\n"
"}\n"
"return false\n"
"}\n"
"function setConnected(state){\n"
"if (state){\n"
"indicator.classList.add('on')\n"
"} else{\n"
"indicator.classList.remove('on')\n"
"}\n"
"indicator.textContent = state ? 'connected' : 'disconnected'\n"
"button.disabled = ! state\n"
"}\n"
"window.addEventListener('load',function(){\n"
"log = document.getElementById('log')\n"
"input = document.getElementById('in')\n"
"button = document.getElementById('send')\n"
"indicator = document.getElementById('indicator')\n"
"document.forms[0].onsubmit = onSend\n"
"start()\n"
"});\n"
;