-
Notifications
You must be signed in to change notification settings - Fork 1
/
example.html
90 lines (81 loc) · 2.59 KB
/
example.html
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
<html>
<!-- To try locally, run: `yarn build` and then `npx http-server -o` -->
<body>
<table>
<tbody></tbody>
</table>
<script type="module">
import {
getAuth,
getUser,
callService,
createConnection,
subscribeEntities,
ERR_OPP_HOST_REQUIRED,
} from "./dist/index.js";
(async () => {
let auth;
try {
auth = await getAuth();
} catch (err) {
if (err === ERR_OPP_HOST_REQUIRED) {
const oppUrl = prompt(
"What host to connect to?",
"http://localhost:8123"
);
if (!oppUrl) return;
auth = await getAuth({ oppUrl });
} else {
alert(`Unknown error: ${err}`);
return;
}
}
const connection = await createConnection({ auth });
subscribeEntities(connection, (entities) =>
renderEntities(connection, entities)
);
// Clear url if we have been able to establish a connection
if (location.search.includes("auth_callback=1")) {
history.replaceState(null, "", location.pathname);
}
// To play from the console
window.auth = auth;
window.connection = connection;
getUser(connection).then((user) => {
console.log("Logged in as", user);
window.user = user;
});
})();
function renderEntities(connection, entities) {
const root = document.querySelector("tbody");
while (root.lastChild) root.removeChild(root.lastChild);
Object.keys(entities)
.sort()
.forEach((entId) => {
const tr = document.createElement("tr");
const tdName = document.createElement("td");
tdName.innerHTML = entId;
tr.appendChild(tdName);
const tdState = document.createElement("td");
const text = document.createTextNode(entities[entId].state);
tdState.appendChild(text);
if (
["switch", "light", "input_boolean"].includes(
entId.split(".", 1)[0]
)
) {
const button = document.createElement("button");
button.innerHTML = "toggle";
button.onclick = () =>
callService(connection, "openpeerpower", "toggle", {
entity_id: entId,
});
tdState.appendChild(button);
}
tr.appendChild(tdState);
root.appendChild(tr);
});
}
</script>
</body>
</html>