zwave-js
Version:
Z-Wave driver written entirely in JavaScript/TypeScript
49 lines • 1.92 kB
JavaScript
import { ZWaveError, ZWaveErrorCodes } from "@zwave-js/core";
import { Bytes } from "@zwave-js/shared";
/** Encapsulates information about the currently active bootloader */
export class EndDeviceCLI {
constructor(writeSerial, expectMessage) {
this.writeSerial = writeSerial;
this.expectMessage = expectMessage;
this._commands = new Map();
}
writeSerial;
expectMessage;
_commands;
get commands() {
return this._commands;
}
async executeCommand(command) {
if (!this.commands.has(command)) {
throw new ZWaveError(`Unknown CLI command ${command}`, ZWaveErrorCodes.Driver_NotSupported);
}
const response = this.expectMessage();
await this.writeSerial(Bytes.from(command.trim() + "\r\n", "ascii"));
let ret = await response;
if (!ret)
return;
// Successful commands echo the command itself, followed by a line break
if (ret.startsWith(command.trim() + "\r\n")) {
ret = ret.slice(command.length + 2);
}
ret = ret.trim();
// Most commands prefix their response with the log level, usually "[I] "
ret = ret.replace(/^\[[A-Z]\] /, "");
return ret;
}
async detectCommands() {
const response = this.expectMessage();
await this.writeSerial(Bytes.from("help\r\n", "ascii"));
const commandList = await response;
if (!commandList) {
throw new ZWaveError("Failed to detect CLI commands", ZWaveErrorCodes.Driver_NotSupported);
}
const commands = commandList.trim()
.split("\n")
.map((line) => line.trim())
.map((line) => line.split(/\s+/, 2).map((part) => part.trim()))
.filter((parts) => parts.every((part) => !!part));
this._commands = new Map(commands);
}
}
//# sourceMappingURL=EndDeviceCLI.js.map