@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)
221 lines • 11.7 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 __1 = require("../..");
const utils_1 = require("../../api/utils");
const command_utils_1 = require("./command-utils");
const download_events_1 = require("./download-events");
const path = require("path");
let color = (0, command_utils_1.getColor)("magenta");
const red = (0, command_utils_1.getColor)("red");
const yellow = (0, command_utils_1.getColor)("yellow");
const blue = (0, command_utils_1.getColor)("blue");
exports.default = (program) => {
program
.command("events")
.alias("ev")
.option("-m, --mode [list|create|delete|template|filtertemplate|info]", "list | create | delete | template | filtertemplate | info", "list")
.option("-f, --file <file>", ".mdsp.json file with event definition")
.option("-i, --assetid <assetid>", "mindsphere asset id ")
.option("-e, --eventid <eventid>", "event id ")
.option("-f, --filter [filter]", `JSON file with filter (see: ${color("https://developer.mindsphere.io/apis/advanced-eventmanagement/api-eventmanagement-best-practices.html")}) `)
.option("-n, --eventtype <eventtype>", "the event type name")
.option("-s, --size <size>", "max. number of events to list", "100")
.option("-c, --includeshared", "include shared event types")
.option("-g, --includeglobal", "include global event 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 events *"))
.action((options) => {
(() => __awaiter(void 0, void 0, void 0, function* () {
try {
checkRequiredParamaters(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);
switch (options.mode) {
case "list":
yield listEvents(sdk, options);
break;
case "template":
yield createEventTemplate(options, sdk);
console.log("Edit the file before submitting it to MindSphere.");
break;
case "filtertemplate":
(0, download_events_1.createFilter)(options);
console.log("Edit the file before submitting it to MindSphere.");
break;
case "delete":
yield deleteEvent(options, sdk);
break;
case "create":
yield createEvent(options, sdk);
break;
case "info":
yield eventInfo(options, sdk);
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 events --mode list \t\t\t\t list last <size> events (default:100)`);
(0, console_1.log)(` mdsp events --mode list --eventtype PumpEvent\t\t list last <size> PumpEvents (default: 100)`);
(0, console_1.log)(` mdsp events --mode info --eventid <eventid>\t\t get info about event with specified id`);
(0, console_1.log)(` mdsp events --mode delete --eventid <eventid>\t\t delete event with specified id`);
(0, console_1.log)(` mdsp events --mode filtertemplate \t\t\t create filter template for --mode list command`);
(0, console_1.log)(` mdsp events --mode template --eventtype PumpEvent \t create a template file for event `);
(0, console_1.log)(` mdsp events --mode create --file PumpEvent.eventtype.mdsp.json \t create event`);
(0, command_utils_1.serviceCredentialLog)();
});
};
function createEvent(options, sdk) {
return __awaiter(this, void 0, void 0, function* () {
const includeShared = options.includeshared;
const filePath = path.resolve(options.file);
const file = fs.readFileSync(filePath);
const event = JSON.parse(file.toString());
const result = yield sdk.GetEventManagementClient().PostEvent(event, { includeShared: includeShared });
console.log(`creted event ${result.id}`);
});
}
function createEventTemplate(options, sdk) {
return __awaiter(this, void 0, void 0, function* () {
const eventType = extractEventType(options, sdk.GetTenant());
const templateType = yield sdk
.GetEventManagementClient()
.GetEventType(eventType, { includeShared: options.includeshared });
(0, command_utils_1.verboseLog)(JSON.stringify(templateType, null, 2), options.verbose);
writeEventToFile(options, templateType);
});
}
function extractEventType(options, tenant) {
let eventType = options.eventtype || "com.siemens.mindsphere.eventmgmt.event.type.MindSphereStandardEvent";
eventType = (0, utils_1.isGuid)(eventType) || eventType.includes(".") ? eventType : `${tenant}.${eventType}`;
return eventType;
}
function writeEventToFile(options, templateType) {
const fileName = options.file || `${templateType.name}.event.mdsp.json`;
const template = {};
template.entityId = options.assetid || "AssetID";
template.timestamp = new Date().toISOString();
template.typeId = templateType.id;
templateType.fields.forEach((element) => {
template[element.name] = `${element.type}${element.required ? " ,required" : ""}`;
});
fs.writeFileSync(fileName, JSON.stringify(template, null, 2));
console.log(`The data was written into ${color(fileName)} run \n\n\tmdsp events --mode create --file ${fileName} \n\nto create the event.`);
}
function deleteEvent(options, sdk) {
return __awaiter(this, void 0, void 0, function* () {
const includeShared = options.includeshared;
const id = options.eventid;
const event = yield (0, __1.retry)(options.retry, () => sdk.GetEventManagementClient().GetEvent(id, { includeShared: includeShared }));
const result = yield (0, __1.retry)(options.retry, () => sdk.GetEventManagementClient().PostDeleteEventsJob({
filter: {
id: `${event.id}`,
typeId: `${event.typeId}`,
},
}));
console.log(`Deletion job with id ${color(result.id)} is in state ${color(result.state)}.`);
result.details && console.log(`Details: ${JSON.stringify(result.details)}.`);
console.log(`Run\n\n\tmdsp events-bulk --mode check --jobid ${result.id}\n\nto check the state of the job.\n `);
});
}
function listEvents(sdk, options) {
return __awaiter(this, void 0, void 0, function* () {
const assetNames = {};
const includeShared = options.includeshared;
const eventMgmt = sdk.GetEventManagementClient();
let page = 0;
let events;
const filter = buildFilter(options, sdk.GetTenant());
// // verboseLog(JSON.stringify(filter, null, 2), options.verbose);
// !options.idonly && console.log(`id etag aspects name owner scope sharing`);
console.log(`eventid ${color("asset")} (assetid) severity type description`);
let eventCount = 0;
do {
events = (yield (0, __1.retry)(options.retry, () => eventMgmt.GetEvents({
page: page,
size: 100,
filter: Object.keys(filter).length === 0 ? undefined : JSON.stringify(filter),
sort: "timestamp,desc",
includeShared: includeShared,
})));
events._embedded = events._embedded || { events: [] };
events.page = events.page || { totalPages: 0 };
for (const event of events._embedded.events || []) {
if (!assetNames[event.entityId]) {
assetNames[event.entityId] = (yield sdk.GetAssetManagementClient().GetAsset(event.entityId)).name;
}
eventCount++;
!options.idonly &&
console.log(`${event.id} ${color(assetNames[event.entityId])} (${event.entityId}) ${toSeverityString(event.severity)} ${shortEvent(event.typeId)} ${event.timestamp} ${event.description || "<no description>"}`);
options.idonly && console.log(`${event.id}`);
(0, command_utils_1.verboseLog)(JSON.stringify(event, null, 2), options.verbose);
}
} while (page++ < (events.page.totalPages || 0) && eventCount < options.size);
console.log(`${color(eventCount)} events listed.\n`);
});
}
function toSeverityString(severity) {
let result = severity;
result = severity === 20 ? red("Error") : result;
result = severity === 30 ? yellow("Warning") : result;
result = severity === 40 ? blue("Info") : result;
return result || "<no severity>";
}
function shortEvent(eventType) {
const ev = eventType.split(".");
const short = ev[ev.length - 1];
return short === "MindSphereStandardEvent" ? "MSE" : short;
}
function buildFilter(options, tenant) {
const filter = (options.filter && JSON.parse(options.filter)) || {};
if (options.assetid) {
filter.entityId = `${options.assetid}`;
}
if (options.eventtype) {
const eventType = extractEventType(options, tenant);
filter.typeId = `${eventType}`;
}
return filter;
}
function eventInfo(options, sdk) {
return __awaiter(this, void 0, void 0, function* () {
const includeShared = options.includeshared;
const id = options.eventid;
const event = yield sdk.GetEventManagementClient().GetEvent(id, { includeShared: includeShared });
console.log(JSON.stringify(event, null, 2));
});
}
function checkRequiredParamaters(options) {
options.mode === "create" &&
!options.file &&
(0, command_utils_1.errorLog)("you have to provide a file with event type to create an event type (see mdsp events --help for more details)", true);
options.mode === "delete" &&
!options.eventid &&
(0, command_utils_1.errorLog)("you have to provide the eventid to delete (see mdsp events --help for more details)", true);
options.mode === "info" &&
!options.eventid &&
(0, command_utils_1.errorLog)("you have to provide the eventid (see mdsp events --help for more details)", true);
}
//# sourceMappingURL=events.js.map