DJCtrlEmu/drivers/linux-rawmidi.js
2023-10-03 06:53:25 -04:00

53 lines
1.1 KiB
JavaScript

const path = require("node:path");
const fs = require("node:fs");
const midiDeviceRegExp = new RegExp("^midi[0-9]+$");
let openDevice;
let callback;
module.exports = {
"list": function () {
var deviceNodeList = fs.readdirSync("/dev").filter(d => d.match(midiDeviceRegExp));
return deviceNodeList.map(d => path.join("/dev", d));
},
"open": function (device, eventCB) {
if (openDevice) {
openDevice["read"].close();
openDevice["write"].close();
}
var deviceName = path.basename(device);
var devicePath = path.join("/dev", deviceName);
openDevice = {
"read": fs.createReadStream(devicePath),
"write": fs.createWriteStream(devicePath)
};
if (eventCB) {
callback = eventCB;
openDevice.read.on("data", function (chunk) {
callback(chunk);
});
}
},
"send": function (message) {
if (!openDevice) return;
var data = Buffer.from(new Uint8Array(message));
openDevice["write"].write(data);
},
"close": function () {
if (!openDevice) return;
openDevice["read"].close();
openDevice["write"].close();
delete openDevice;
delete callback;
}
};