-
-
Save ngraziano/24e10a745c30b8c45a1bfe3e7111ae49 to your computer and use it in GitHub Desktop.
Test to get events in browser in js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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