@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)
171 lines • 8.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 });
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 path = require("path");
let color = (0, command_utils_1.getColor)("magenta");
exports.default = (program) => {
program
.command("oe-devices")
.alias("oed")
.option("-m, --mode [list|create|delete|template|info]", "list | create | delete | template | info", "list")
.option("-f, --file <file>", ".mdsp.json file with device definition")
.option("-n, --devicename <devicename>", "device name")
.option("-a, --assetid <assetid>", "the id of the asset linked to the device")
.option("-t, --typeid <typeid>", "the device type id")
.option("-d, --desc <desc>", "description", "created with mindsphere CLI")
.option("-s, --serialnumber <serialnumber>", "the id of the asset linked to the device")
.option("-i, --id <id>", "the device id")
.option("-o, --overwrite", "overwrite template file 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 (open edge) devices *"))
.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);
switch (options.mode) {
case "list":
yield listDevices(sdk, options);
break;
case "template":
yield createTemplate(options, sdk);
console.log("Edit the file before submitting it to MindSphere.");
break;
case "delete":
yield deleteDevice(options, sdk);
break;
case "create":
yield createDevice(options, sdk);
break;
case "info":
yield deviceInfo(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 oe-devices --mode list --assetid <assetid>\tlist all devices linked to the asset`);
(0, console_1.log)(` mdsp oe-devices --mode info --id <deviceid>\t\tget device details`);
(0, console_1.log)(` mdsp oe-devices --mode template \t\t\tcreate a template file for a new device`);
(0, console_1.log)(` mdsp oe-devices --mode delete --id <devieceid>\tdelete the device with the specified id`);
(0, console_1.log)(` mdsp oe-devices --mode create --file openedge.device.mdsp.json \n \
create new device using the file openedge.device.mdsp.json`);
(0, command_utils_1.serviceCredentialLog)();
});
};
function createDevice(options, sdk) {
return __awaiter(this, void 0, void 0, function* () {
const filePath = path.resolve(options.file);
const file = fs.readFileSync(filePath);
const deviceType = JSON.parse(file.toString());
const name = deviceType.name.includes(".") ? deviceType.name : `${sdk.GetTenant()}.${deviceType.name}`;
const device = yield sdk.GetDeviceManagementClient().PostDevice(deviceType);
(0, command_utils_1.printObjectInfo)("Device:", device, options, ["id"], color);
console.log(`created device ${color(name)}`);
});
}
function createTemplate(options, sdk) {
return __awaiter(this, void 0, void 0, function* () {
const tenant = sdk.GetTenant();
const template = {
name: `${tenant}.${options.devicename || "<devicename>"}`,
description: options.desc,
deviceTypeId: options.typeid || `12345...`,
serialNumber: options.serialnumber || `7d018c...`,
assetId: options.assetid || `7d018c...`,
agents: [],
properties: {
key1: "value1",
key2: "value2",
},
};
(0, command_utils_1.verboseLog)(template, options.verbose);
writeDeviceTypeToFile(options, template);
});
}
function writeDeviceTypeToFile(options, templateType) {
const fileName = options.file || `openedge.device.mdsp.json`;
const filePath = path.resolve(fileName);
fs.existsSync(filePath) &&
!options.overwrite &&
(0, utils_1.throwError)(`The ${filePath} already exists. (use --overwrite to overwrite) `);
fs.writeFileSync(filePath, JSON.stringify(templateType, null, 2));
console.log(`The data was written into ${color(filePath)} run \n\n\tmdsp oe-devices --mode create --file ${fileName} \n\nto create the device`);
}
function deleteDevice(options, sdk) {
return __awaiter(this, void 0, void 0, function* () {
const id = options.id ? options.id : `${options.id}`;
yield sdk.GetDeviceManagementClient().DeleteDevice(id);
console.log(`Device with id ${color(id)} deleted.`);
});
}
function listDevices(sdk, options) {
return __awaiter(this, void 0, void 0, function* () {
var _a;
const deviceMgmt = sdk.GetDeviceManagementClient();
let page = 0;
console.log(`id \ttype \tserialNumber \tassetId \tagent(s) \tcreatedAt`);
let deviceCount = 0;
let devices;
do {
const filter = {
page: page,
size: 100,
sort: "id,asc",
};
devices = (yield (0, __1.retry)(options.retry, () => deviceMgmt.GetDevices(filter)));
devices.content = devices.content || [];
devices.page = devices.page || { totalPages: 0 };
for (const device of devices.content || []) {
deviceCount++;
console.log(`${color(device.id)}\t${device.deviceTypeId}\t${device.serialNumber}\t${device.assetId}\t${(_a = device.agents) === null || _a === void 0 ? void 0 : _a.length}\t${device.createdAt}`);
(0, command_utils_1.verboseLog)(JSON.stringify(device, null, 2), options.verbose);
}
} while (page++ < (devices.page.totalPages || 0));
console.log(`${color(deviceCount)} device(s) listed.\n`);
});
}
function deviceInfo(options, sdk) {
return __awaiter(this, void 0, void 0, function* () {
const id = options.id.includes(".") ? options.id : `${options.id}`;
const device = yield sdk.GetDeviceManagementClient().GetDevice(id);
(0, command_utils_1.printObjectInfo)("Device:", device, options, ["id"], color);
});
}
function checkRequiredParameters(options) {
options.mode === "create" &&
!options.file &&
(0, command_utils_1.errorLog)("you have to provide a file with device type to create device type (see mdsp oe-devices --help for more details)", true);
options.mode === "delete" &&
!options.id &&
(0, command_utils_1.errorLog)("you have to provide the id of the device type to delete (see mdsp oe-devices --help for more details)", true);
options.mode === "info" &&
!options.id &&
(0, command_utils_1.errorLog)("you have to provide the id of the device type (see mdsp oe-devices --help for more details)", true);
}
//# sourceMappingURL=oe-devices.js.map