@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)
232 lines • 11.8 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 });
exports.deleteAsset = exports.getTree = exports.listAssets = void 0;
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 sdk_1 = require("../../api/sdk");
const utils_1 = require("../../api/utils");
const command_utils_1 = require("./command-utils");
let color = (0, command_utils_1.getColor)("magenta");
exports.default = (program) => {
program
.command("assets")
.alias("ast")
.option("-m, --mode [list|create|delete|template|tree]", "mode [list | create | delete | template | tree]", "list")
.option("-f, --file <file>", ".mdsp.json file with asset definition")
.option("-n, --assetname <assetname>", "assetname")
.option("-p, --parentid <parentid>", "parentid")
.option("-e, --externalid <externalid>", "externalid")
.option("-i, --assetid <assetid>", "mindsphere asset id ")
.option("-t, --typeid <typeid>", "typeid")
.option("-d, --desc <desc>", "description", "created with mindsphere CLI")
.option("-w, --twintype <twintype>", "digital twin type [performance|simulation]")
.option("-c, --includeshared", "include shared aspect types")
.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 assets *`))
.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);
(0, command_utils_1.homeDirLog)(options.verbose, color);
(0, command_utils_1.proxyLog)(options.verbose, color);
const assetMgmt = sdk.GetAssetManagementClient();
const rootAssetId = (yield assetMgmt.GetRootAsset()).assetId;
switch (options.mode) {
case "create":
yield createAsset(options, rootAssetId, sdk);
break;
case "list":
yield listAssets(options, sdk);
break;
case "tree":
yield getTree(sdk);
break;
case "delete":
yield deleteAsset(options, sdk);
break;
case "template":
createTemplate(options, rootAssetId, sdk.GetTenant());
break;
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");
(0, console_1.log)(` mdsp assets --mode create --typeid core.basicarea --assetname MyArea \t creates an asset in mindsphere of type basicarea`);
(0, console_1.log)(` mdsp assets --mode create --file MyPump.asset.mdsp.json \t\t creates an asset from specified file template`);
(0, console_1.log)(` mdsp assets --mode list \t\t\t\t\t\t lists all assets in mindsphere`);
(0, console_1.log)(` mdsp assets --mode list --typeid mclib\t\t\t\t lists all assets in mindsphere of type core.mclib`);
(0, console_1.log)(` mdsp assets --mode delete --assetid 1234567..ef \t\t\t deletes asset with specified id from mindsphere`);
(0, console_1.log)(` mdsp assets --mode template --typeid <mytenant>.Pump --assetname MyPump \n\t\tcreates a file template MyPump.asset.mdsp.json which can be use in create command`);
(0, command_utils_1.serviceCredentialLog)();
});
};
function listAssets(options, sdk) {
return __awaiter(this, void 0, void 0, function* () {
var _a;
const includeShared = options.includeshared;
const assetMgmt = sdk.GetAssetManagementClient();
color = (0, command_utils_1.adjustColor)(color, options);
let page = 0;
let assets;
const filter = buildFilter(options);
(0, command_utils_1.verboseLog)(JSON.stringify(filter, null, 2), options.verbose);
console.log(`assetid etag twintype [typeid] name sharing`);
let assetCount = 0;
do {
assets = (yield (0, utils_1.retry)(options.retry, () => assetMgmt.GetAssets({
page: page,
size: 100,
filter: Object.keys(filter).length === 0 ? undefined : JSON.stringify(filter),
sort: "name,asc",
includeShared: includeShared,
})));
assets._embedded = assets._embedded || { assets: [] };
assets.page = assets.page || { totalPages: 0 };
for (const asset of assets._embedded.assets || []) {
assetCount++;
console.log(`${asset.assetId} ${asset.etag}\t${asset.twinType}\t[${asset.typeId}]\t${color(asset.name)} ${(_a = asset.sharing) === null || _a === void 0 ? void 0 : _a.modes}`);
(0, command_utils_1.verboseLog)(JSON.stringify(asset, null, 2), options.verbose);
}
} while (page++ < (assets.page.totalPages || 0));
console.log(`${color(assetCount)} assets listed.\n`);
});
}
exports.listAssets = listAssets;
function getTree(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);
});
}
exports.getTree = getTree;
function createTemplate(options, rootid, tenant) {
const fileName = options.file || `${options.assetname || "unnamed"}.asset.mdsp.json`;
const type = `${options.typeid}`.includes(".") ? options.typeid : `${tenant}.${options.typeid}`;
const asset = {
name: options.assetname || "unnamed",
externalId: options.externalid,
description: options.desc || "created with mindsphere CLI",
location: {
country: "Germany",
region: "Bayern",
locality: "Erlangen",
streetAddress: "Schuhstr. 60",
postalCode: "91052",
longitude: 49.5894843,
latitude: 11.0061579,
},
variables: [],
aspects: [],
fileAssignments: [],
typeId: type || "please enter typeid",
parentId: options.parentid || rootid,
timezone: "Europe/Berlin",
twinType: options.twintype || "performance",
};
fs.writeFileSync(fileName, JSON.stringify(asset, null, 2));
console.log(`The data was written into ${color(fileName)} run \n\n\t mdsp aspects --mode create --file ${fileName} \n\nto create the aspect`);
}
function createAsset(options, rootAssetId, sdk) {
return __awaiter(this, void 0, void 0, function* () {
const assetMgmt = sdk.GetAssetManagementClient();
let data = {
name: options.assetname,
parentId: options.parentid || rootAssetId,
externalId: options.externalid,
typeId: options.typeid,
description: options.desc,
twinType: options.twintype || sdk_1.AssetManagementModels.TwinType.Performance,
};
if (options.file) {
const filePath = path.resolve(options.file);
const filecontent = fs.readFileSync(filePath);
data = JSON.parse(filecontent.toString());
data.name = options.assetname || data.name;
data.parentId = options.parentid || data.parentId;
data.externalId = options.externalid || data.externalId;
data.typeId = options.typeid || data.typeId;
data.description = options.desc || data.description;
data.twinType = options.twinType || data.twinType;
}
const result = (yield (0, utils_1.retry)(options.retry, () => __awaiter(this, void 0, void 0, function* () { return assetMgmt.PostAsset(data); })));
console.log(`Asset with assetid ${color(result.assetId)} was created.`);
console.log("\nAsset Manager:");
console.log("\t" +
color(`${sdk.GetGateway().replace("gateway", sdk.GetTenant() + "-assetmanager")}/entity/${result.assetId}`));
});
}
function buildFilter(options) {
const filter = (options.filter && JSON.parse(options.filter)) || {};
let pointer = filter;
if (options.assetname !== undefined && options.typeid !== undefined) {
filter.and = {};
pointer = filter.and;
}
if (options.assetname) {
pointer.name = { contains: `${options.assetname}` };
}
if (options.typeid) {
pointer.typeId = { contains: `${options.typeid}` };
}
return filter;
}
function deleteAsset(options, sdk) {
return __awaiter(this, void 0, void 0, function* () {
const includeShared = options.includeshared;
const assetMgmt = sdk.GetAssetManagementClient();
const asset = yield (0, utils_1.retry)(options.retry, () => assetMgmt.GetAsset(options.assetid));
(0, command_utils_1.verboseLog)(JSON.stringify(asset, null, 2), options.verbose);
yield (0, utils_1.retry)(options.retry, () => assetMgmt.DeleteAsset(options.assetid, {
ifMatch: (asset === null || asset === void 0 ? void 0 : asset.etag) || "0",
includeShared: includeShared,
}));
console.log(`Asset with assetid ${color(asset.assetId)} (${color(asset.name)}) was deleted.`);
});
}
exports.deleteAsset = deleteAsset;
function checkRequiredParameters(options) {
options.mode === "create" &&
!options.file &&
(!options.assetname || !options.typeid) &&
(0, command_utils_1.errorLog)("you have to specify at least the asset name and typeid if you are not using file template", true);
options.twintype &&
!["performance", "simulation"].includes(options.twintype) &&
(0, command_utils_1.errorLog)("the twin type must be either performance or simulation", true);
}
//# sourceMappingURL=assets.js.map