UNPKG

@mindconnect/mindconnect-nodejs

Version:

NodeJS Library for MindSphere Connectivity - TypeScript SDK for MindSphere - MindSphere Command Line Interface - MindSphere Development Proxy

117 lines 7.47 kB
"use strict"; 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 utils_1 = require("../../api/utils"); const command_utils_1 = require("./command-utils"); const ora = require("ora"); const mime = require("mime-types"); let color = (0, 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 { checkRequiredParameters(options); const sdk = (0, command_utils_1.getSdk)(options); color = (0, command_utils_1.adjustColor)(color, options, true); (0, command_utils_1.homeDirLog)(options.verbose, color); (0, 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); (0, 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) && (0, utils_1.throwError)(`The file ${outputfilename} already exists`); (0, command_utils_1.verboseLog)(`Mode: ${options.mode}`, options.verbose, spinner); (0, command_utils_1.verboseLog)(`OutputFileName: ${outputfilename}`, options.verbose, spinner); const mimeType = mime.lookup(uploadFile); options.mode === "fft" && mimeType !== "audio/wave" && (0, utils_1.throwError)("the file must be a audio/wave audio file"); options.mode === "threshold" && mimeType !== "application/json" && (0, 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 (0, 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)); (0, 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 (0, 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.spectrum.json")} file before running the threshold violation detection\n`); } catch (err) { (0, command_utils_1.errorLog)(err, options.verbose); } }))(); }) .on("--help", () => { (0, console_1.log)("\n Examples:\n"); (0, console_1.log)(` mc spectrum-analysis -f machine.wav \t Decomposes the sound file into frequency components`); (0, console_1.log)(` mc spectrum-analysis -f machine.wav --windowtype blackman \t use blackman window type for FFT preprocessing`); (0, console_1.log)(` mc spectrum-analysis --mode threshold \t detect threshold violations for thresholds stored in ${color("thresholds.spectrum.json")}`); (0, command_utils_1.serviceCredentialLog)(color); }); }; function checkRequiredParameters(options) { options.mode === "fft" && !options.file && (0, command_utils_1.errorLog)("Missing file name for spectrum-analytics command. Run mc sp --help for full syntax and examples.", true); options.mode !== "fft" && options.mode !== "threshold" && (0, command_utils_1.errorLog)(`Invalid mode: ${options.mode}`, true); options.mode === "fft" && ["flattop", "hamming", "hanning", "blackman"].indexOf(options.windowtype) < 0 && (0, command_utils_1.errorLog)(`invalid window type ${options.windowtype} for FFT`, true); fs.existsSync(`${options.output}`) && (0, command_utils_1.errorLog)(`The file ${options.output} already exists!`, true); } //# sourceMappingURL=spectrum-analysis.js.map