Files

85 lines
2.7 KiB
JavaScript

async function GET(path) {
return new Promise(function (onSuccess, onError) {
let xhr = new XMLHttpRequest();
xhr.open('GET', path);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
onSuccess(JSON.parse(xhr.responseText));
} else {
onError(xhr);
}
}
}
xhr.onerror = () => onError(xhr);
xhr.send(null);
});
}
async function POST(path, data={}) {
return new Promise(function (onSuccess, onError) {
var xhr = new XMLHttpRequest();
xhr.open('POST', path, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
onSuccess(xhr);
} else {
onError(xhr);
}
}
};
xhr.onerror = () => onError(xhr);
xhr.send(JSON.stringify(data));
});
}
function assert(condition, message) {
if (!condition) {
throw message || "Assertion failed";
}
}
async function transmit(transmitterID, channel, action, shockerPin, intensity=0, lucalEncoded=false) {
assert(typeof transmitterID === 'number');
assert(typeof channel === 'number');
assert(['shock', 'vibrate', 'beep'].includes(action));
assert(typeof shockerPin === 'number');
assert(typeof intensity === 'number');
assert(typeof lucalEncoded === 'boolean');
POST('/transmit', {transmitterID: transmitterID, channel: channel, action: action, shockerPin: shockerPin, intensity: intensity, lucalEncoded: lucalEncoded});
}
async function txFromUI(action, intensity=0) {
let transmitterID = Number(document.getElementById('transmitterIDInput').value);
let channel = Number(document.getElementById('channelIDInput').value);
let lucalEncoded = document.getElementById('lucalEncodedInput').checked;
let shockerPin = Number(document.getElementById('shockerPinInput').value);
transmit(transmitterID, channel, action, shockerPin, intensity, lucalEncoded);
}
async function shock() {
let intensity = Number(document.getElementById('shockIntensity').value);
txFromUI('shock', intensity);
}
async function vibrate() {
let intensity = Number(document.getElementById('vibrateIntensity').value);
txFromUI('vibrate', intensity);
}
async function beep() {
txFromUI('beep');
}
window.addEventListener('load', () => {
GET('/limit').then((data) => {
document.getElementById('shockIntensity').max = data.limit;
document.getElementById('vibrateIntensity').max = data.limit;
});
});