Skip to content

Instantly share code, notes, and snippets.

@ngraziano
Created May 1, 2021 18:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ngraziano/24e10a745c30b8c45a1bfe3e7111ae49 to your computer and use it in GitHub Desktop.
Save ngraziano/24e10a745c30b8c45a1bfe3e7111ae49 to your computer and use it in GitHub Desktop.
Test to get events in browser in js
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Quick and dirty event console</title>
<script>
const abortController = new AbortController();
const utf8decoder = new TextDecoder();
// based on https://github.com/TheThingsNetwork/lorawan-stack/blob/c0e437afc7fccb9d506e05f73b4a2d2c3db54d13/sdk/js/src/api/stream/stream.js
window.onload = async function () {
const token =
"NNSXS.XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
const appId = "my-nice-application";
const response = await fetch(
"https://eu1.cloud.thethings.network/api/v3/events",
{
body: JSON.stringify({
identifiers: [
{
application_ids: { application_id: appId },
},
],
}),
method: "POST",
signal: abortController.signal,
headers: {
Authorization: "Bearer " + token,
Accept: "text/event-stream",
},
}
);
let buffer = "";
const reader = response.body.getReader();
const onChunk = ({ done, value }) => {
if (done) {
return;
}
const parsed = utf8decoder.decode(value);
buffer += parsed;
const lines = buffer.split(/\n\n/);
buffer = lines.pop();
for (const line of lines) {
newMessage(JSON.parse(line).result);
}
return reader.read().then(onChunk);
};
reader
.read()
.then(onChunk)
.catch((error) => {
console.log("BOOOO ERROR",error)
});
};
setTimeout(() => abortController.abort(), 5 *60 *1000)
function newMessage(message) {
console.log(message);
if(message.name=="as.up.data.forward") {
var main = document.getElementById("main");
const messElem = document.createElement('p');
messElem.innerText = JSON.stringify(message.data.uplink_message.decoded_payload);
main.appendChild(messElem);
}
}
</script>
</head>
<body id="main">
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment