@mindconnect/mindconnect-nodejs
Version:
MindConnect Library for NodeJS (community based)
123 lines • 7.75 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const console_1 = require("console");
const fs = require("fs");
const path = require("path");
const sdk_1 = require("../../api/sdk");
const utils_1 = require("../../api/utils");
const command_utils_1 = require("./command-utils");
const ora = require("ora");
const mime = require("mime-types");
const color = command_utils_1.getColor("blue");
exports.default = (program) => {
program
.command("spectrum-analysis")
.alias("sp")
.option("-f, --file <fileToUpload>", `wav file to upload or json to analyze (default for threshold detection: ${color("fft.spectrum.json")})`)
.option("-m, --mode [fft|threshold]", "Fast Fourier Transformation or threshold detection", "fft")
.option("-t, --thresholds <thresholdsFile>", "threshold json for threshold detection", "thresholds.spectrum.json")
.option("-t, --output <results>", `output file (fft: ${color("fft.spectrum.json")}, threshold: ${color("violations.spectrum.json")})`)
.option("-w, --windowtype [flattop|hamming|hanning|blackman]", "window type for the FFT", "flattop")
.option("-y, --retry <number>", "retry attempts before giving up", 3)
.option("-p, --passkey <passkey>", `passkey`)
.option("-v, --verbose", "verbose output")
.description(`${color("perform spectrum analysis on a sound file @")}`)
.action(options => {
(() => __awaiter(void 0, void 0, void 0, function* () {
try {
checkParameters(options);
command_utils_1.homeDirLog(options.verbose, color);
command_utils_1.proxyLog(options.verbose, color);
const spinner = ora("uploadingFile");
!options.verbose && spinner.start();
options.file = options.file || "fft.spectrum.json";
const uploadFile = path.resolve(options.file);
command_utils_1.verboseLog(`File to upload: ${color(uploadFile)}.`, options.verbose, spinner);
if (!fs.existsSync(uploadFile)) {
throw new Error(`Can't find file ${uploadFile}`);
}
const outputfilename = options.output || (options.mode === "fft" ? "fft.spectrum.json" : "violations.spectrum.json");
fs.existsSync(outputfilename) && utils_1.throwError(`The file ${outputfilename} already exists`);
command_utils_1.verboseLog(`Mode: ${options.mode}`, options.verbose, spinner);
command_utils_1.verboseLog(`OutputFileName: ${outputfilename}`, options.verbose, spinner);
const auth = utils_1.loadAuth();
const sdk = new sdk_1.MindSphereSdk({
tenant: auth.tenant,
gateway: auth.gateway,
basicAuth: utils_1.decrypt(auth, options.passkey)
});
const mimeType = mime.lookup(uploadFile);
options.mode === "fft" &&
mimeType !== "audio/wave" &&
utils_1.throwError("the file must be a audio/wave audio file");
options.mode === "threshold" &&
mimeType !== "application/json" &&
utils_1.throwError("the file must be a json file!");
const spectrumAnalysis = sdk.GetSpectrumAnalysisClient();
const buffer = fs.readFileSync(uploadFile);
if (options.windowtype !== undefined) {
options.windowtype = `${options.windowtype}`.toUpperCase();
}
if (options.mode === "fft") {
const result = (yield utils_1.retry(options.retry, () => spectrumAnalysis.CalculateFrequencies(buffer, `${options.windowtype}`, {
filename: path.basename(uploadFile),
mimetype: mimeType
})));
fs.writeFileSync(outputfilename, JSON.stringify(result));
if (!fs.existsSync("thresholds.spectrum.json")) {
fs.writeFileSync("thresholds.spectrum.json", JSON.stringify({
minFrequency: 100,
maxFrequency: 200,
lowerThreshold: -40.25,
upperThreshold: -30
}, null, 2));
command_utils_1.verboseLog("creating thresholds.spectrum.json", options.verbose, spinner);
}
}
else {
const fft = JSON.parse(buffer.toString("utf-8"));
const thresholds = fs.readFileSync(path.resolve(options.thresholds), "utf-8");
const result = (yield utils_1.retry(options.retry, () => spectrumAnalysis.DetectThresholdViolations({
data: fft.data,
spectrumFilter: JSON.parse(thresholds)
})));
fs.writeFileSync(outputfilename, JSON.stringify(result, null, 2));
}
spinner.succeed(`Done. See output in ${color(outputfilename)}`);
options.mode === "fft" &&
console.log(`\nPlease edit the thresholds in ${color("thresholds.spectum.json")} file before running the threshold violation detection\n`);
}
catch (err) {
command_utils_1.errorLog(err, options.verbose);
}
}))();
})
.on("--help", () => {
console_1.log("\n Examples:\n");
console_1.log(` mc spectrum-analysis -f machine.wav \t Decomposes the sound file into frequency components`);
console_1.log(` mc spectrum-analysis -f machine.wav --windowtype blackman \t use blackman window type for FFT preprocessing`);
console_1.log(` mc spectrum-analysis --mode threshold \t detect threshold violations for thresholds stored in ${color("thresholds.spectrum.json")}`);
command_utils_1.serviceCredentialLog(color);
});
};
function checkParameters(options) {
options.mode === "fft" &&
!options.file &&
command_utils_1.errorLog("Missing file name for spectrum-analytics command. Run mc sp --help for full syntax and examples.", true);
!options.passkey && command_utils_1.errorLog(" You have to provide the passkey for spectrum-analytics command", true);
options.mode !== "fft" && options.mode !== "threshold" && command_utils_1.errorLog(`Invalid mode: ${options.mode}`, true);
options.mode === "fft" &&
["flattop", "hamming", "hanning", "blackman"].indexOf(options.windowtype) < 0 &&
command_utils_1.errorLog(`invalid window type ${options.windowtype} for FFT`, true);
fs.existsSync(`${options.output}`) && command_utils_1.errorLog(`The file ${options.output} already exists!`, true);
}
//# sourceMappingURL=spectrum-analysis.js.map