refactor(client): ♻️ remove deprecated xhr API and rewrite hard coded and redundant parts

This commit is contained in:
Julien Oculi 2024-06-25 12:27:16 +02:00
parent 63b92d00a8
commit 8d561f14c3

View file

@ -63,18 +63,31 @@
directionnelles pour le diriger et la barre espace pour le stopper. directionnelles pour le diriger et la barre espace pour le stopper.
</p> </p>
</body> </body>
<script> <script type="module">
/**
* A command string.
* @typedef {('forward' | 'backward' | 'left' | 'right' | 'stop')} Command
*/
/**
* Send command to the robot.
*
* @param {string} endpoint Address IP of the robot
* @param {Command} command Command to send.
* @param {number} value Value of the command if needed.
*/
async function sendCommand(endpoint, command, value) {
const response = await fetch(
`http://${endpoint}/get?command=${command}&value=${value}`
)
const text = await response.text()
console.log(text)
}
document.addEventListener('keydown', (event) => { document.addEventListener('keydown', (event) => {
const key = event.keyCode const key = event.keyCode
const url = keyMap[key] const { command, value } = keyMap[key]
console.log(url) sendCommand(endpoint, command, value)
const xhr = new XMLHttpRequest()
xhr.open('GET', url)
xhr.onload = () => {
const response = xhr.responseText
console.log(response)
}
xhr.send()
}) })
function storeInput() { function storeInput() {
@ -82,23 +95,11 @@
valueRot = document.getElementById('valueRot').value valueRot = document.getElementById('valueRot').value
valueLength = document.getElementById('valueLength').value valueLength = document.getElementById('valueLength').value
keyMap = { keyMap = {
38: 38: { command: 'forward', value: valueLength },
'http://' + 40: { command: 'backward', value: valueLength },
ipInput + 37: { command: 'left', value: valueRot },
'/get?command=forward&value=' + 39: { command: 'right', value: valueRot },
valueLength, 32: { command: 'stop', value: 0 },
40:
'http://' +
ipInput +
'/get?command=backward&value=' +
valueLength,
37: 'http://' + ipInput + '/get?command=left&value=' + valueRot,
39:
'http://' +
ipInput +
'/get?command=right&value=' +
valueRot,
32: 'http://' + ipInput + '/get?command=stop',
} }
} }
</script> </script>