89 lines
2 KiB
JavaScript
89 lines
2 KiB
JavaScript
/**
|
|
* A command string.
|
|
* @typedef {('forward' | 'backward' | 'left' | 'right' | 'stop')} Command
|
|
*/
|
|
|
|
/**
|
|
* Send command to the robot.
|
|
*
|
|
* @param {Command} command Command to send.
|
|
* @param {number} value Value of the command if needed.
|
|
*
|
|
* @returns {Promise<void>}
|
|
*/
|
|
export async function sendCommand(command, value) {
|
|
const endpoint = getEndpoint()
|
|
const url = new URL(`/get?command=${command}&value=${value}`, endpoint)
|
|
const response = await fetch(url)
|
|
const text = await response.text()
|
|
console.log(text)
|
|
}
|
|
|
|
/**
|
|
* Get robot endpoint address.
|
|
*
|
|
* @returns {string}
|
|
*/
|
|
export function getEndpoint() {
|
|
const endpoint = sessionStorage.getItem('robot-endpoint')
|
|
if (endpoint === null) {
|
|
alert("Aucune adresse IP n'a été renseignée !")
|
|
throw new Error('no given ip address')
|
|
}
|
|
return endpoint
|
|
}
|
|
|
|
/**
|
|
* Set robot endpoint address.
|
|
*
|
|
* @param {string} ip Robot ip.
|
|
*
|
|
* @returns {void}
|
|
*/
|
|
export function setEndpoint(ip) {
|
|
sessionStorage.setItem('robot-endpoint', ip)
|
|
}
|
|
|
|
/**
|
|
* Test connection to endpoint.
|
|
*
|
|
* @param {string} endpoint Endpoint to test for.
|
|
*
|
|
* @returns {void}
|
|
* @throws {Error} Endpoint unreachable.
|
|
*/
|
|
export async function testEndpoint(endpoint) {
|
|
try {
|
|
const response = await fetch(endpoint)
|
|
if (response.ok) return
|
|
} catch (cause) {
|
|
alert(`Impossible de joindre l'adresse "${endpoint}"`)
|
|
throw new Error(`unable to connect to robot at ${endpoint}`, {
|
|
cause,
|
|
})
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Assign a command to an input.
|
|
* Do negative command if value < 0 else do positive command.
|
|
*
|
|
* @param {Command} negativeCommand Command if value < 0.
|
|
* @param {Command} positiveCommand Command if value >= 0.
|
|
* @param {event} event Event of the input.
|
|
*
|
|
* @returns {Promise<void>}
|
|
*/
|
|
export function assignCommands(negativeCommand, positiveCommand, event) {
|
|
if (event.target === null) return
|
|
|
|
/** @type {HTMLInputElement} */
|
|
const target = event.target
|
|
const value = target.valueAsNumber
|
|
|
|
if (value < 0) {
|
|
return sendCommand(negativeCommand, Math.abs(value))
|
|
}
|
|
return sendCommand(positiveCommand, value)
|
|
}
|