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,9 +44,10 @@ 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) {
return new Promise((resolve, reject) => {
mutex.lock().then(() => {
emulator.serial0_send(cmd + "\n") emulator.serial0_send(cmd + "\n")
return new Promise((resolve, reject) => {
var output = "" var output = ""
var listener = (char) => { var listener = (char) => {
if (char !== "\r") { if (char !== "\r") {
@ -32,14 +61,19 @@ function run(cmd) {
outputWithoutPrompt.indexOf("\n") + 1 outputWithoutPrompt.indexOf("\n") + 1
) )
if (outputWithoutFirstLine.endsWith("\n")) { if (outputWithoutFirstLine.endsWith("\n")) {
outputWithoutFirstLine = outputWithoutFirstLine.slice(0, -1) outputWithoutFirstLine = outputWithoutFirstLine.slice(
0,
-1
)
} }
emulator.remove_listener("serial0-output-char", listener) emulator.remove_listener("serial0-output-char", listener)
mutex.unlock()
resolve(outputWithoutFirstLine) resolve(outputWithoutFirstLine)
} }
} }
emulator.add_listener("serial0-output-char", listener) emulator.add_listener("serial0-output-char", listener)
}) })
})
} }
window["run"] = run window["run"] = run
window["web_shell"] = {run, testy} window["web_shell"] = {run, testy}