@mindconnect/mindconnect-nodejs
Version:
NodeJS Library for Siemens Insights Hub Connectivity - TypeScript SDK for Insights Hub and Industrial IoT - Command Line Interface - Insights Hub Development Proxy (Siemens Insights Hub was formerly known as MindSphere)
218 lines • 12.1 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 performant_array_to_tree_1 = require("performant-array-to-tree");
const util = require("util");
const utils_1 = require("../../api/utils");
const command_utils_1 = require("./command-utils");
const ora = require("ora-classic");
const streamPipeline = util.promisify(require("stream").pipeline);
let color = (0, command_utils_1.getColor)("magenta");
exports.default = (program) => {
program
.command("asset-model")
.alias("asm")
.option("-m, --mode [export|import]", "export | import", "export")
.option("-d, --directory [directory]", "download to specified folder (default: <tenantname.mdsp.model>)")
.option("-i, --assetid [assetid]", "mindsphere asset id (default: root asset id)")
.option("-o, --overwrite", "overwrite directory with the model if it already exists")
.option("-k, --passkey <passkey>", "passkey")
.option("-y, --retry <number>", "retry attempts before giving up", "3")
.option("-v, --verbose", "verbose output")
.description(color("list, create or delete asset types *"))
.action((options) => {
(() => __awaiter(void 0, void 0, void 0, function* () {
try {
checkRequiredParamaters(options);
const sdk = (0, command_utils_1.getSdk)(options);
const tenantName = sdk.GetUserTenant() || sdk.GetTenant();
options.directory = options.directory || `${tenantName}.mdsp.model`;
options.assetid = options.assetid || (yield sdk.GetAssetManagementClient().GetRootAsset()).assetId;
color = (0, command_utils_1.adjustColor)(color, options);
(0, command_utils_1.homeDirLog)(options.verbose, color);
(0, command_utils_1.proxyLog)(options.verbose, color);
const model = {
assetTypes: [],
aspectTypes: [],
assets: [],
files: {},
};
const spinner = ora(`Downloading asset model of ${color(tenantName)} tenant`);
!options.verbose && spinner.start();
const directoryName = path.resolve(options.directory);
fs.existsSync(directoryName) &&
!options.overwrite &&
(0, utils_1.throwError)(`The folder ${directoryName} already exists. (use --overwrite to overwrite) `);
!fs.existsSync(directoryName) && fs.mkdirSync(directoryName);
yield addAssetTypes(sdk, options, model, spinner);
yield addAspectTypes(sdk, options, model, spinner);
yield addAssets(sdk, options, model, spinner);
fs.writeFileSync(path.resolve(`${directoryName}/${tenantName}}.model.mdsp.json`), JSON.stringify(model, null, 2));
spinner.succeed(`Done. The asset model is in ${color(directoryName)} folder.`);
switch (options.mode) {
default:
throw Error(`no such option: ${options.mode}`);
}
}
catch (err) {
(0, command_utils_1.errorLog)(err, options.verbose);
}
}))();
})
.on("--help", () => {
(0, console_1.log)("\n Examples:\n");
// log(` mc asset-types --mode list \t\t\t\t\t list all asset types`);
// log(` mc asset-types --mode list --assettype Pump\t\t list all asset types which are named Pump`);
// log(
// ` mc asset-types --mode template --assettype Pump \n\tcreate a template file (Enironment.assettype.mdsp.json) for assettype Pump`
// );
// log(
// ` mc asset-types --mode create --file Pump.assettype.mdsp.json \n\tcreate asset type Pump in MindSphere`
// );
(0, command_utils_1.serviceCredentialLog)();
});
};
function checkRequiredParamaters(options) {
// options.mode === "template" &&
// !options.assettype &&
// errorLog(
// "you have to provide asset type to create a template (see mc asset-types --help for more details)",
// true
// );
// options.mode === "create" &&
// !options.file &&
// errorLog(
// "you have to provide a file with asset type to create an asset type (see mc asset-types --help for more details)",
// true
// );
// options.mode === "delete" &&
// !options.assettype &&
// errorLog("you have to provide the asset type to delete (see mc asset-types --help for more details)", true);
// options.mode === "info" &&
// !options.assettype &&
// errorLog("you have to provide the asset type (see mc asset-types --help for more details)", true);
}
function addAspectTypes(sdk, options, model, spinner) {
return __awaiter(this, void 0, void 0, function* () {
var _a, _b;
const assetMgmt = sdk.GetAssetManagementClient();
let aspectTypes;
let page = 0;
do {
aspectTypes = yield assetMgmt.GetAspectTypes({ page: page, size: 2000 });
(_b = (_a = aspectTypes._embedded) === null || _a === void 0 ? void 0 : _a.aspectTypes) === null || _b === void 0 ? void 0 : _b.forEach((aspectType) => {
var _a;
// ignore types coming from core or from shared tenants
if ((_a = aspectType.id) === null || _a === void 0 ? void 0 : _a.startsWith(sdk.GetTenant())) {
const filename = `${aspectType.id}.aspect-type.mdsp.json`;
model.assetTypes.push(filename);
(0, command_utils_1.verboseLog)(`Downloading ${color(filename)}`, options.verbose, spinner);
fs.writeFileSync(path.resolve(`${options.directory}/${filename}`), JSON.stringify(aspectType, null, 2));
}
});
page++;
} while (page < aspectTypes.page.totalPages);
});
}
function addAssetTypes(sdk, options, model, spinner) {
return __awaiter(this, void 0, void 0, function* () {
var _a, _b;
const assetMgmt = sdk.GetAssetManagementClient();
let assetTypes;
let page = 0;
do {
assetTypes = yield assetMgmt.GetAssetTypes({ page: page, size: 2000 });
(_b = (_a = assetTypes._embedded) === null || _a === void 0 ? void 0 : _a.assetTypes) === null || _b === void 0 ? void 0 : _b.forEach((assetType) => {
var _a, _b;
// ignore types coming from core or from shared tenants
if ((_a = assetType.id) === null || _a === void 0 ? void 0 : _a.startsWith(sdk.GetTenant())) {
const filename = `${assetType.id}.asset-type.mdsp.json`;
model.assetTypes.push(filename);
(0, command_utils_1.verboseLog)(`Downloading ${color(filename)}`, options.verbose, spinner);
fs.writeFileSync(path.resolve(`${options.directory}/${filename}`), JSON.stringify(assetType, null, 2));
(_b = assetType.fileAssignments) === null || _b === void 0 ? void 0 : _b.forEach((file) => __awaiter(this, void 0, void 0, function* () {
if (!model.files[assetType.id]) {
model.files[assetType.id] = [];
}
const downloadFileName = `${file.fileId}.${assetType.id}.png`;
model.files[assetType.id].push(downloadFileName);
(0, command_utils_1.verboseLog)(`Downloading ${color(downloadFileName)}`, options.verbose, spinner);
const download = yield assetMgmt.DownloadFile(file.fileId);
!download.ok && (0, command_utils_1.errorLog)(`Unexpected response ${download.statusText}`, true);
const downloadPath = path.resolve(`${options.directory}/${downloadFileName}`);
const fileStream = fs.createWriteStream(downloadPath);
streamPipeline(download.body, fileStream);
}));
}
});
page++;
} while (page < assetTypes.page.totalPages);
});
}
function addAssets(sdk, options, model, spinner) {
return __awaiter(this, void 0, void 0, function* () {
var _a, _b;
const assetList = [];
const assetMgmt = sdk.GetAssetManagementClient();
let assets;
let page = 0;
do {
assets = yield assetMgmt.GetAssets({ page: page, size: 2000 });
(_b = (_a = assets._embedded) === null || _a === void 0 ? void 0 : _a.assets) === null || _b === void 0 ? void 0 : _b.forEach((asset) => {
var _a;
// ignore types coming from core or from shared tenants
assetList.push(asset);
const filename = `${asset.assetId}-${asset.typeId}.asset.mdsp.json`;
model.assets.push(filename);
(0, command_utils_1.verboseLog)(`Downloading ${color(filename)}`, options.verbose, spinner);
fs.writeFileSync(path.resolve(`${options.directory}/${filename}`), JSON.stringify(asset, null, 2));
(_a = asset.fileAssignments) === null || _a === void 0 ? void 0 : _a.forEach((file) => __awaiter(this, void 0, void 0, function* () {
if (!model.files[asset.assetId]) {
model.files[asset.assetId] = [];
}
const downloadFileName = `${file.fileId}.${asset.assetId}.png`;
model.files[asset.assetId].push(downloadFileName);
(0, command_utils_1.verboseLog)(`Downloading ${color(downloadFileName)}`, options.verbose, spinner);
const download = yield assetMgmt.DownloadFile(file.fileId);
!download.ok && (0, command_utils_1.errorLog)(`Unexpected response ${download.statusText}`, true);
const downloadPath = path.resolve(`${options.directory}/${downloadFileName}`);
const fileStream = fs.createWriteStream(downloadPath);
streamPipeline(download.body, fileStream);
}));
});
page++;
} while (page < assets.page.totalPages);
});
}
function getAssetTreeStructure(sdk, assetId) {
return __awaiter(this, void 0, void 0, function* () {
var _a, _b;
const assetList = [];
const assetMgmt = sdk.GetAssetManagementClient();
let assets;
let page = 0;
do {
assets = yield assetMgmt.GetAssets({ page: page, size: 2000 });
(_b = (_a = assets._embedded) === null || _a === void 0 ? void 0 : _a.assets) === null || _b === void 0 ? void 0 : _b.forEach((asset) => {
// ignore types coming from core or from shared tenants
assetList.push(asset);
});
page++;
} while (page < assets.page.totalPages);
const tree = (0, performant_array_to_tree_1.arrayToTree)(assetList, { id: "assetId" });
console.log(tree[0]);
(0, utils_1.printTree)(tree[0], 0, color);
});
}
//# sourceMappingURL=asset-model.js.map