@iotize/cli
Version:
IoTize command line interface
321 lines • 13.3 kB
JavaScript
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
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 cli_core_1 = require("@iotize/cli-core");
const device_client_js_1 = require("@iotize/device-client.js");
const impl_1 = require("@iotize/device-client.js/client/impl");
const impl_2 = require("@iotize/device-client.js/client/impl");
const impl_3 = require("@iotize/device-client.js/client/impl");
const clime_1 = require("clime");
const inquirer_1 = require("inquirer");
const ui_1 = require("../../ui");
const device_1 = require("../options/device");
class MyOptions extends device_1.DeviceOptions {
}
__decorate([
clime_1.option({
required: false,
default: 500
}),
__metadata("design:type", Number)
], MyOptions.prototype, "pollingPeriod", void 0);
__decorate([
clime_1.option({
required: false,
default: false,
toggle: true
}),
__metadata("design:type", Boolean)
], MyOptions.prototype, "cr", void 0);
__decorate([
clime_1.option({
required: false,
default: false,
toggle: true
}),
__metadata("design:type", Boolean)
], MyOptions.prototype, "lf", void 0);
exports.MyOptions = MyOptions;
const NUMBER_VALIDATOR = (value) => {
try {
parseInt(value);
return true;
}
catch (err) {
return false;
}
};
let default_1 = class default_1 extends clime_1.Command {
constructor() {
super(...arguments);
this.displayConverter = MyStringConverter.instance();
this.displayModeMenu = new cli_core_1.MenuBuilder()
.action('acsii', (action) => {
this.displayConverter = MyStringConverter.instance();
this.displayType = action;
})
.action('hex', (action) => {
this.displayConverter = impl_3.HexStringConverter.instance();
this.displayType = action;
});
this.displayType = 'ascii';
}
execute(options) {
return __awaiter(this, void 0, void 0, function* () {
this.options = options;
this.device = yield options.getDevice(true);
// device.service.target.transparentSendRead(data);
let menu = new cli_core_1.MenuBuilder();
menu.action('info', (action) => __awaiter(this, void 0, void 0, function* () {
yield this.showDeviceInfo(this.device.service.device.getSerialNumber(), 'Serial Number');
yield this.showDeviceInfo(this.device.service.target.getProtocol(), 'Target Protocol');
ui_1.display.infonl('Serial Configuration: ');
let serialSettings = (yield this.device.service.target.getUARTSettings()).body();
ui_1.display.pretty(serialSettings);
}))
.action('configure', () => __awaiter(this, void 0, void 0, function* () {
let newSerialConfig = yield this.askUserConfig();
let uartSettings = newSerialConfig;
yield this.configureSerial(uartSettings);
}))
.action('transeive', () => __awaiter(this, void 0, void 0, function* () {
yield this.transeive();
}))
.action('login', () => __awaiter(this, void 0, void 0, function* () {
yield this.login();
}))
.action('display', () => __awaiter(this, void 0, void 0, function* () {
yield this.displayModeMenu.show('Select display input type ?');
}))
.action('quit', () => __awaiter(this, void 0, void 0, function* () {
yield this.quit();
}))
.default((action) => {
ui_1.display.error(`Unknown action ${action}`);
});
while (true) {
try {
yield menu.show('TapNLink Terminal - what do you want to do ?>');
}
catch (err) {
console.log('Error occured: ', err);
ui_1.display.error(err.message);
}
}
});
}
login() {
return __awaiter(this, void 0, void 0, function* () {
let result = yield inquirer_1.prompt([
{
name: 'username',
message: 'Username ?',
type: 'input'
},
{
name: 'password',
message: 'Password ?',
type: 'input'
}
]);
yield this.device.login(result['username'], result['password']);
return result;
});
}
showIfResponseError(writeResponse, successMessage) {
if (!writeResponse.isSuccessful()) {
ui_1.display.error(new impl_1.ResponseError(writeResponse).toString());
}
else {
if (successMessage) {
ui_1.display.success(successMessage);
}
}
}
// async showDeviceInfo(fct: () => Promise<Response<any>>) {
// let response = await fct();
// display.info(`${fct.name}: ${response.body()}`)
// }
showDeviceInfo(responsePromise, alias) {
return __awaiter(this, void 0, void 0, function* () {
let response = yield responsePromise;
ui_1.display.infonl(`${alias}: ${response.body()}`);
});
}
quit() {
return __awaiter(this, void 0, void 0, function* () {
this.device.disconnect();
process.exit(0);
});
}
transeive() {
return __awaiter(this, void 0, void 0, function* () {
yield this.connectToTarget();
this.dataPolling();
while (true) {
try {
let action = yield inquirer_1.prompt({
message: `${this.displayType}${this.options.cr ? '+CR' : ''} ${this.options.lf ? '+LF' : ''}>`,
name: 'command'
});
if (action['command'] === 'quit') {
this.stopDataPolling();
return Promise.resolve();
}
let input = action['command'];
if (this.displayType === 'ascii') {
input +=
(this.options.cr ? '\r' : '') +
(this.options.lf ? '\n' : '');
}
let data = this.displayConverter.encode(input);
let response = yield this.device.service.target.send(data);
this.appendReadResult(response);
}
catch (err) {
ui_1.display.error(err.toString());
}
}
});
}
stopDataPolling() {
if (this.pollingHandler) {
clearTimeout(this.pollingHandler);
}
}
dataPolling() {
if (this.options.pollingPeriod > 0) {
this.pollingHandler = setTimeout(() => __awaiter(this, void 0, void 0, function* () {
let result = yield this.device.service.target.readBytes();
this.appendReadResult(result);
this.dataPolling();
}), this.options.pollingPeriod);
}
}
appendReadResult(result) {
if (result.isSuccessful()) {
let data = result.rawBody();
if (data && data.length > 0) {
ui_1.display.info(this.displayConverter.decode(data));
}
}
else {
this.showIfResponseError(result);
}
}
configureSerial(config) {
return __awaiter(this, void 0, void 0, function* () {
let response = yield this.device.service.target.setUARTSettings(config);
this.showIfResponseError(response, 'Successfully configured serial');
if (response.isSuccessful()) {
this.connectToTarget();
}
});
}
connectToTarget() {
return __awaiter(this, void 0, void 0, function* () {
let disconnectResponse = yield this.device.service.target.disconnect();
this.showIfResponseError(disconnectResponse);
let connectResponse = yield this.device.service.target.connect();
this.showIfResponseError(connectResponse, 'Successfully connected to target');
});
}
askUserConfig() {
return __awaiter(this, void 0, void 0, function* () {
let choices = [];
let currentConfig = (yield this.device.service.target.getUARTSettings()).body();
choices.push(this.buildQuestionFromEnum(device_client_js_1.UartSettings.PhysicalPort, 'physicalPort', currentConfig.physicalPort));
choices.push(this.buildQuestionFromEnum(device_client_js_1.UartSettings.StopBit, 'stopBit', currentConfig.stopBit));
choices.push(this.buildQuestionFromEnum(device_client_js_1.UartSettings.Handshake, 'handshake', currentConfig.handshakeValue));
choices.push(this.buildQuestionFromEnum(device_client_js_1.UartSettings.HandshakeDelimiter, 'handshakeDelimiter', currentConfig.handshakeDelimiter));
choices.push(this.buildQuestionFromEnum(device_client_js_1.UartSettings.BitParity, 'bitParity', currentConfig.bitParity));
choices.push({
name: 'baudRate',
message: 'Baud rate ?',
type: 'input',
default: currentConfig.baudRate,
validate: NUMBER_VALIDATOR
});
choices.push({
name: 'slv',
message: 'Slave ?',
type: 'input',
default: currentConfig.slv,
validate: NUMBER_VALIDATOR
});
choices.push({
name: 'ofs',
message: 'Offset ?',
type: 'input',
default: currentConfig.ofs,
validate: NUMBER_VALIDATOR
});
let result = yield inquirer_1.prompt(choices);
return result;
});
}
getEnumInfos(type) {
let keys = Object.keys(type);
let values = keys.map(k => type[k]).map(v => v);
return {
keys: keys,
values: values
};
}
buildQuestionFromEnum(type, name, defaultValue) {
// let type: any = (global as any)[typename];
let values = this.getEnumInfos(type).values;
return {
message: `${name} ?`,
name: name,
choices: values,
type: 'list',
default: defaultValue
};
}
};
__decorate([
clime_1.metadata,
__metadata("design:type", Function),
__metadata("design:paramtypes", [MyOptions]),
__metadata("design:returntype", Promise)
], default_1.prototype, "execute", null);
default_1 = __decorate([
clime_1.command({
description: 'Terminal'
})
], default_1);
exports.default = default_1;
class MyStringConverter extends impl_2.StringConverter {
// decode(body: Uint8Array): string{
// let last = body[body.length-1];
// if (last === 0x7F){
// body = body.subarray(0, body.length-2);
// }
// return super.decode(body);
// }
// encode(value: string): Uint8Array{
// return super.encode(value);
// }
static istance() {
return new MyStringConverter();
}
}
//# sourceMappingURL=terminal.js.map