const hideClass = "hide"; let isSending = false; let workers = []; const textInput = document.getElementById("textInput"); const startSendingButton = document.getElementById("start-sending-button"); const stopSendingButton = document.getElementById("stop-sending-button"); const startCalibrationButton = document.getElementById("start-calibration-button"); const stopCalibrationButton = document.getElementById("stop-calibration-button"); startCalibrationButton.addEventListener("click", startCalibration); stopCalibrationButton.addEventListener("click", stopCalibration); startSendingButton.addEventListener("click", startSending); stopSendingButton.addEventListener("click", stopSending); function getWebWorker() { return new Worker("./scripts/Worker.js"); } function startWorkers() { for (let i = 0; i < 8; i++) { workers.push(getWebWorker()); } } function stopWorkers() { for (const worker of workers) { worker.terminate(); } workers = []; } function startCalibration() { console.log("Starting calibration"); startCalibrationButton.classList.add(hideClass); stopCalibrationButton.classList.remove(hideClass); Utility.setMessage("Calibration currently ongoing."); startWorkers(); } function stopCalibration() { console.log("Stopping calibration"); stopCalibrationButton.classList.add(hideClass); startCalibrationButton.classList.remove(hideClass); Utility.setMessage(""); stopWorkers(); } function startSending() { startSendingButton.classList.add(hideClass); stopSendingButton.classList.remove(hideClass); Utility.setMessage(`Sending message: ${textInput.value}`); console.log(`Start sending message: ${textInput.value}`); const packet = new Packet(textInput.value); const signal = Utility.manchesterEncode(packet.getData()); isSending = true; transmitSignal(signal); } function stopSending() { console.log("Stop Sending"); Utility.setMessage(""); stopSendingButton.classList.add(hideClass); startSendingButton.classList.remove(hideClass); isSending = false; } /** * Transmit the given bit array until the sending is stopped. * * @param {Number[]} signal */ async function transmitSignal(signal) { while (isSending) { // Send the preamble for (const bit of PREAMBLE) { if (!isSending) { stopWorkers(); return; } console.log(`Sending preamble: ${bit}`); await transmitBit(bit); } for (let i = 0; i < signal.length; i++) { if (!isSending) { stopWorkers(); return; } console.log(`Sending bit ${i + 1} of ${signal.length} of packet: ${signal[i]}`); await transmitBit(signal[i]); } } } /** * This either starts or stops the web workers depending on the bit value * and then waits for a duration of CLOCK_TIME. * * @param {Number} bit */ function transmitBit(bit) { if (bit === 1) { startWorkers(); return new Promise((resolve) => setTimeout(resolve, CLOCK_TIME)); } stopWorkers(); return new Promise((resolve) => setTimeout(resolve, CLOCK_TIME)); }