Add mutex to web-shell

This commit is contained in:
blinry 2023-09-07 18:00:24 +02:00
parent 4b758e6bca
commit 2f115c99d4

View file

@ -1,4 +1,32 @@
//import {Mutex} from "./mutex.js" class Mutex {
constructor() {
this._queue = [] // Queue of pending tasks
this._locked = false // Mutex state
}
lock() {
if (this._locked) {
// If locked, return a promise that resolves when the mutex is unlocked
return new Promise((resolve) => this._queue.push(resolve))
} else {
// If not locked, set it to locked and return a resolved promise
this._locked = true
return Promise.resolve()
}
}
unlock() {
if (this._queue.length > 0) {
// If there are tasks waiting in the queue, pop the first task and resolve its promise
const nextTask = this._queue.shift()
nextTask()
} else {
// If no tasks in the queue, just unlock the mutex
this._locked = false
}
}
}
const mutex = new Mutex()
var emulator var emulator
@ -16,29 +44,35 @@ window["testy"] = testy
// Run a command via the serial port (/dev/ttyS0) and return the output. // Run a command via the serial port (/dev/ttyS0) and return the output.
function run(cmd) { function run(cmd) {
emulator.serial0_send(cmd + "\n")
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
var output = "" mutex.lock().then(() => {
var listener = (char) => { emulator.serial0_send(cmd + "\n")
if (char !== "\r") {
output += char
}
if (output.endsWith("# ")) { var output = ""
emulator.remove_listener("serial0-output-char", listener) var listener = (char) => {
let outputWithoutPrompt = output.slice(0, -4) if (char !== "\r") {
let outputWithoutFirstLine = outputWithoutPrompt.slice( output += char
outputWithoutPrompt.indexOf("\n") + 1 }
)
if (outputWithoutFirstLine.endsWith("\n")) { if (output.endsWith("# ")) {
outputWithoutFirstLine = outputWithoutFirstLine.slice(0, -1) emulator.remove_listener("serial0-output-char", listener)
let outputWithoutPrompt = output.slice(0, -4)
let outputWithoutFirstLine = outputWithoutPrompt.slice(
outputWithoutPrompt.indexOf("\n") + 1
)
if (outputWithoutFirstLine.endsWith("\n")) {
outputWithoutFirstLine = outputWithoutFirstLine.slice(
0,
-1
)
}
emulator.remove_listener("serial0-output-char", listener)
mutex.unlock()
resolve(outputWithoutFirstLine)
} }
emulator.remove_listener("serial0-output-char", listener)
resolve(outputWithoutFirstLine)
} }
} emulator.add_listener("serial0-output-char", listener)
emulator.add_listener("serial0-output-char", listener) })
}) })
} }
window["run"] = run window["run"] = run