cyp/app/js/mpd.js

62 lines
1.3 KiB
JavaScript
Raw Normal View History

2019-03-20 03:45:23 +08:00
import * as parser from "./parser.js";
let ws;
let commandQueue = [];
let pendingResolve;
function onMessage(e) {
if (pendingResolve) {
pendingResolve(JSON.parse(e.data)); // FIXME tady test na ACK
pendingResolve = null;
}
processQueue();
}
function onError(e) {
console.error(e);
ws = null; // fixme
}
function onClose(e) {
console.warn(e);
ws = null; // fixme
}
function processQueue() {
if (pendingResolve || commandQueue.length == 0) { return; }
2019-03-20 05:56:39 +08:00
let {cmd, resolve} = commandQueue.shift();
pendingResolve = resolve;
2019-03-20 03:45:23 +08:00
if (cmd instanceof Array) { cmd = ["command_list_begin", ...cmd, "command_list_end"].join("\n"); }
ws.send(cmd);
}
2019-03-20 05:56:39 +08:00
export function escape(str) {
return str.replace(/(['"\\])/g, "\\$1");
}
2019-03-20 03:45:23 +08:00
2019-03-20 05:56:39 +08:00
export async function command(cmd) {
return new Promise(resolve => {
commandQueue.push({cmd, resolve});
processQueue();
});
2019-03-20 03:45:23 +08:00
}
export async function getStatus() {
let lines = await command(["status", "currentsong"]);
2019-03-20 05:56:39 +08:00
lines.pop(); // "OK"
2019-03-20 03:45:23 +08:00
return parser.linesToStruct(lines);
}
export async function init() {
return new Promise((resolve, reject) => {
try {
2019-03-20 05:56:39 +08:00
ws = new WebSocket("ws://localhost:8080?server=raspberrypi.local");
2019-03-20 03:45:23 +08:00
} catch (e) { reject(e); }
pendingResolve = resolve;
ws.addEventListener("error", onError);
ws.addEventListener("message", onMessage);
ws.addEventListener("close", onClose);
});
}