fork_mon_premier_robot/client/src/handlers.js

83 lines
2.1 KiB
JavaScript
Raw Normal View History

import { sendCommand, setEndpoint, testEndpoint } from './utils.js'
/**
* Handler for settings form.
*
* @param {Event} event Settings form submit event.
* @returns {Promise<void>}
*/
export async function settingsHandler(event) {
// Don't interrupt event if not form submitting
if (!(event instanceof SubmitEvent)) return true
if (event.target === null) return true
// Disable form sending
event.preventDefault()
const form = new FormData(event.target)
const ipAddress = form.get('ip-address')
if (ipAddress === null) return
const endpoint = `http://${ipAddress}`
await testEndpoint(endpoint)
setEndpoint(endpoint)
}
/**
* Attach command to touch controls buttons.
*
* @this HTMLButtonElement
* @returns {Promise<void>}
*/
export function controlButtonHandler() {
const { command, value } = this.dataset
// Check datas are set for button
if (command === undefined || value === undefined) {
alert(`Pas de command ou de valeur assigné au bouton "${this.title}"`)
throw new Error(`no command or value assigned to ${this.title}`)
}
// Check command is valid
if (!['forward', 'backward', 'left', 'right', 'stop'].includes(command)) {
alert(
`La command "${command}" n'est pas valide en tant que ('forward', 'backward', 'left', 'right', 'stop')`
)
throw new Error(
`specified command "${command}" is not in ['forward', 'backward', 'left', 'right', 'stop']`
)
}
// Check value is valid finite number
if (!Number.isFinite(Number(value))) {
alert(`La valeur "${value}" n'est convertible en entier fini`)
throw new Error(`value "${value}" cannot be casted to finite integer`)
}
sendCommand(command, Number(value))
}
/**
* Handler for keyboard events.
*
* @param {KeyboardEvent} event Keyboard event.
* @returns {Promise<void>}
*/
export function keyboardHandler({ code }) {
if (code === 'ArrowUp') {
return sendCommand('forward', 2)
}
if (code === 'ArrowDown') {
return sendCommand('backward', 2)
}
if (code === 'ArrowLeft') {
return sendCommand('left', 5)
}
if (code === 'ArrowRight') {
return sendCommand('right', 5)
}
if (code === 'Space') {
return sendCommand('stop', 0)
}
}