Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import * as _ from 'lodash';
- import { createConnection } from 'mysql';
- import { Utils } from 'tyx';
- import fs = require('fs');
- const DBS = 'dbadmin:gUYZ6anpLEF3gksC@dev.db.n5-nederman.com:3306/iot_test';
- // const DBS = 'dbadmin:gUYZ6anpLEF3gksC@localhost:30306/iot_dev';
- const sensors: any[] = [];
- main().then(() => console.log('done'));
- const TO_CONVERT: any[] = []; // ["label", "onoff"];
- async function main() {
- const tokens = DBS.split(/:|@|\/|;/);
- const db = createConnection({
- user: tokens[0],
- password: tokens[1],
- host: tokens[2],
- port: parseInt(tokens[3], 10),
- database: tokens[4]
- });
- const dashboardFilter = [] ||
- [
- '52519425-c793-4405-87a1-0dfbbc507e0d'
- ];
- const data = await new Promise<any>((resolve, reject) => {
- db.query(
- `SELECT * FROM dashboard`
- + (dashboardFilter.length ? ` WHERE dashboardId IN ('${dashboardFilter.join('\',\'')}')` : ''),
- (err, res) => {
- if (err) reject(err); else resolve(res);
- });
- });
- const res: any = { layout: {}, widget: {} };
- for (const dash of data) {
- try { JSON.parse(dash.definition); }
- catch (err) { console.error(dash.dashboardId); }
- let json: any;
- try {
- json = JSON.parse(dash.definition);
- } catch (err) {
- console.error(err);
- continue;
- }
- // if (json.version) throw new TypeError("New dashboard format");
- fs.writeFileSync(`src/tools/dashboard/org/old_${dash.dashboardId}.json`, JSON.stringify(json, null, 2));
- /* set the new structure of the dashboard */
- // const allSensors = {};
- // visit(0, json, res, allSensors);
- // json = convertLayout(json);
- /* set the sensors attached in the widgets in binding properties */
- // sensors = [];
- // getSensors(json);
- // json['binding'] = sensors;
- /* update the old widgets */
- // json = updateOldWidgets(json);
- json = newMetadataStructure(json);
- json.type = 'dashboard';
- json.version = 2;
- fs.writeFileSync(`src/tools/dashboard/data/new_${dash.dashboardId}.json`, JSON.stringify(json, null, 2));
- try {
- await new Promise<any>((resolve, reject) => {
- db.query(`UPDATE dashboard SET definition = ? WHERE dashboardId = ?`, [JSON.stringify(json), dash.dashboardId], (err, data) => {
- if (err) reject(err); else resolve(res);
- });
- });
- console.log(`Updated: [${dash.dashboardId}]`);
- } catch (err) {
- console.error(err);
- }
- }
- // res.layoutKeys = summ(res.layout);
- // res.widgetKeys = summ(res.widget);
- // console.log(res);
- fs.writeFileSync('src/tools/dashboards.json', JSON.stringify(res, null, 2));
- db.destroy();
- }
- function updateLayout(definition: any) {
- if (!definition) { return null; }
- for (let i = 0; i < _.get(definition, 'children', definition).length; i++) {
- /* if there are children in the element, check them */
- if (definition.children) {
- /* if element has other children */
- if (!_.isEmpty(definition.children[i].children)) {
- updateLayout(definition.children[i]);
- }
- }
- if (definition.children[i]['config']) {
- if (definition.children[i]['component'] !== 'multiLineChart') {
- definition.children[i]['layout'].label = sensors.find(sensor => sensor.sensorId === definition.children[i]['binding'].sensorId).label;
- delete definition.children[i]['layout'].name;
- }
- }
- }
- return definition;
- }
- function newMetadataStructure(definition: any) {
- if (!definition) { return null; }
- for (let i = 0; i < _.get(definition, 'children', definition).length; i++) {
- /* if there are children in the element, check them */
- if (definition.children) {
- /* if element has other children */
- if (!_.isEmpty(definition.children[i].children)) {
- newMetadataStructure(definition.children[i]);
- }
- }
- if (definition.children[i].config && definition.children[i].config.ranges) {
- definition.children[i].config.ranges = updateRanges(definition.children[i].config.ranges, definition.children[i].component, definition.children[i].config.max);
- definition.children[i].modified.ranges = updateRanges(definition.children[i].modified.ranges, definition.children[i].component, definition.children[i].modified.max);
- }
- }
- return definition;
- }
- function updateRanges(rangesArray: { [key: string]: any }[], component: string, max?: any) {
- rangesArray.forEach((range: any, rangeIndex: any) => {
- rangesArray[rangeIndex].label = rangesArray[rangeIndex].indicator;
- delete rangesArray[rangeIndex].indicator;
- if (component === 'onoff') {
- rangesArray[rangeIndex].from = rangeIndex - 1;
- if (rangeIndex !== rangesArray.length - 1) {
- rangesArray[rangeIndex].to = rangeIndex;
- } else {
- rangesArray[rangeIndex].to = rangeIndex - 1;
- }
- } else {
- rangesArray[rangeIndex].label = 'Range ' + (rangeIndex + 1);
- }
- });
- if (component !== 'onoff') {
- rangesArray.push({
- from: max,
- to: max,
- label: null,
- color: null
- });
- }
- return rangesArray;
- }
- function updateOldWidgets(definition: any) {
- if (!definition) { return null; }
- for (let i = 0; i < _.get(definition, 'children', definition).length; i++) {
- /* if there are children in the element, check them */
- if (definition.children) {
- /* if element has other children */
- if (!_.isEmpty(definition.children[i].children)) {
- updateOldWidgets(definition.children[i]);
- }
- }
- /* if widget is old one, set the default metadata to false and set modified = config */
- if (definition.children[i]['type'] === 'widget' && !definition.children[i]['layout']['defaultMetadata']) {
- definition.children[i]['layout']['defaultMetadata'] = 'false';
- definition.children[i]['modified'] = definition.children[i]['config'];
- }
- /* if widget is old one, set the name and description in config and set modified = config */
- if (definition.children[i]['config'] && !definition.children[i]['config']['name']) {
- definition.children[i]['config']['name'] = definition.children[i]['layout']['name'];
- definition.children[i]['config']['description'] = definition.children[i]['layout']['description'];
- definition.children[i]['modified'] = definition.children[i]['config'];
- }
- /* if element line-chart, set the type to mean(Average) and set modified = config */
- if (definition.children[i]['config'] &&
- (definition.children[i]['component'] === 'simpleLineChart' ||
- definition.children[i]['component'] === 'highstock' ||
- definition.children[i]['component'] === 'zoomableSpline' ||
- definition.children[i]['component'] === 'areaRange' ||
- definition.children[i]['component'] === 'barChart')
- && !definition.children[i]['config']['type']) {
- definition.children[i]['config']['type'] = 'mean';
- definition.children[i]['modified'] = definition.children[i]['config'];
- }
- }
- return definition;
- }
- function getSensors(definition: any): any {
- if (!definition) { return null; }
- for (let i = 0; i < _.get(definition, 'children', definition).length; i++) {
- /* if there are children in the element, check them */
- if (definition.children) {
- /* if element is multiLine and there are sensors attached on it */
- if (definition.children[i]['component'] === 'multiLineChart' && definition.children[i]['config']) {
- getSensors(definition.children[i]['config']['sensors']);
- } else if (!_.isEmpty(definition.children[i].children)) {
- /* if element has other children */
- getSensors(definition.children[i]);
- }
- }
- /* if element is list of the sensors attached on multiLine, sensors always have { binding: { sensorId: '' }} */
- if (!definition.children) {
- if (definition[i].binding) sensors.push(definition[i].binding.sensorId);
- else sensors.push(definition[i].sensorId);
- } else if (definition.children[i]['component'] !== 'multiLineChart') {
- /* if element not multiLine, check if it has attached */
- if (_.get(definition, 'children[' + i + '].binding', false)) {
- sensors.push(definition.children[i].binding.sensorId);
- }
- }
- }
- }
- function visit(level: number, node: any, res: any, allSensors: any) {
- if (!node) return;
- const name = node.component;
- let group = res.layout;
- if (node.tenantId || node.plantId || node.systemId || node.sensorId || res.widget[name]
- || name === 'mediaUpload'
- || name === 'textEditor'
- || name === 'sensorsTable'
- || name === 'alarmsTable'
- || name === 'section?'
- || name === 'label'
- ) {
- if (res.layout[name]) {
- res.widget[name] = res.layout[name];
- res.layout[name] = null;
- }
- group = res.widget;
- }
- const cp = group[name] = group[name] || { component: name, count: 0, keys: {} };
- cp.count++;
- const ks = Object.keys(node);
- ks.forEach((k) => { cp.keys[k] = cp.keys[k] || 0; cp.keys[k]++; });
- for (let i = 0; i < node.children.length; i++) {
- const n = node.children[i];
- const g = visit(level + 1, n, res, allSensors);
- const cv = (g === res.layout) ? convertLayout(n) : convertWidget(n, allSensors);
- node.children[i] = cv;
- }
- return group;
- }
- function convertLayout(node: any) {
- const res: any = {
- type: 'layout',
- version: undefined as any,
- component: node.component,
- id: Utils.uuid(),
- binding: undefined as any,
- layout: {},
- // temp: {},
- children: node.children
- };
- for (const key in node) {
- if (res[key]) continue;
- if (['animation', 'isTemplate'].indexOf(key) > -1) {
- // res.temp[key] = node[key];
- continue;
- } else {
- res.layout[key] = node[key];
- }
- }
- return res;
- }
- function color(val: string) {
- if (!val || !val.startsWith || !val.startsWith('rgb(')) return val;
- const rgb = '#' + val.replace('rgb(', '')
- .replace(')', '')
- .split(',')
- .map(v => +v)
- .map(v => v.toString(16))
- .map(v => v.length === 1 ? '0' + v : v)
- .join('').toUpperCase();
- return rgb;
- }
- function convertWidget(node: any, allSensors: any) {
- if (TO_CONVERT.length && TO_CONVERT.indexOf(node.component) === -1) {
- return node;
- }
- const res: any = {
- type: 'widget',
- component: node.component,
- id: Utils.uuid(),
- binding: undefined as any,
- layout: {},
- config: {} as any,
- children: node.children
- };
- if (node.component === 'onoff') {
- res.config.ranges = [];
- if (node.errorRange) {
- res.config.ranges.push({
- indicator: node.errorRange.errorValueIndicator,
- color: color(node.errorRange.color)
- });
- }
- if (node.firstRange) {
- res.config.ranges.push({
- indicator: node.firstRange.zeroValueIndicator,
- color: color(node.firstRange.color)
- });
- }
- if (node.secondRange) {
- res.config.ranges.push({
- indicator: node.secondRange.firstValueIndicator,
- color: color(node.secondRange.color)
- });
- }
- if (node.thirdRange) {
- res.config.ranges.push({
- indicator: node.thirdRange.secondValueIndicator,
- color: color(node.thirdRange.color)
- });
- }
- if (node.fourthRange) {
- res.config.ranges.push({
- indicator: node.fourthRange.thirdValueIndicator,
- color: color(node.fourthRange.color)
- });
- }
- if (node.fifthRange) {
- res.config.ranges.push({
- indicator: node.fifthRange.fourthValueIndicator,
- color: color(node.fifthRange.color)
- });
- }
- if (res.config.ranges.length) delete node.ranges;
- if (res.config.ranges.length < 6) {
- res.config.ranges = [
- {
- indicator: 'Error',
- color: '#BF0000'
- },
- {
- indicator: 'OFF',
- color: '#F4D502'
- },
- {
- indicator: 'Running 2',
- color: '#36CA38'
- },
- {
- indicator: '/',
- color: '#FF0000'
- },
- {
- indicator: 'Fault',
- color: '#7F7F7F'
- },
- {
- indicator: 'Alarm',
- color: '#FF4347'
- }
- ];
- }
- } else if (node.firstRange) {
- res.config.ranges = [];
- if (node.firstRange) {
- res.config.ranges.push({
- from: node.firstRange.from,
- to: node.firstRange.to,
- color: color(node.firstRange.color)
- });
- }
- if (node.secondRange) {
- res.config.ranges.push({
- from: node.secondRange.from,
- to: node.secondRange.to,
- color: color(node.secondRange.color)
- });
- }
- if (node.thirdRange) {
- res.config.ranges.push({
- from: node.thirdRange.from,
- to: node.thirdRange.to,
- color: color(node.thirdRange.color)
- });
- }
- }
- delete node.errorRange;
- delete node.firstRange;
- delete node.secondRange;
- delete node.thirdRange;
- delete node.fourthRange;
- delete node.fifthRange;
- if (Array.isArray(node.ranges)) {
- for (const item of node.ranges) {
- for (const key in item) {
- item[key] = color(item[key]);
- }
- }
- }
- for (const key in node) {
- if (res[key]) continue;
- if (['tenantId', 'plantId', 'systemId', 'sensorId'].indexOf(key) > -1) {
- res.binding = res.binding || {};
- res.binding[key] = node[key];
- if (key === 'sensorId') {
- allSensors[node[key]] = true;
- }
- } else if (['animation', 'isTemplate', 'textDisplay'].indexOf(key) > -1) {
- // res.temp[key] = node[key];
- continue;
- } else if (['chartHeight', 'img', 'size', 'name', 'description', 'fontSize'].indexOf(key) > -1) {
- res.layout[key] = color(node[key]);
- } else if (['years', 'months', 'days', 'hours', 'minutes'].indexOf(key) > -1 && res['component'] === 'time') {
- // res.temp[key] = node[key];
- continue;
- } else if (['years', 'months', 'days', 'hours', 'minutes'].indexOf(key) > -1 && res['component'] === 'onoff') {
- // res.remove[key] = node[key];
- } else if (['scale'].indexOf(key) > -1) {
- // res.remove[key] = node[key];
- continue;
- } else if (['sensors'].indexOf(key) > -1) {
- res.config[key] = color(node[key]);
- res.binding['sensorIds'] = res.binding['sensorIds'] || [];
- res.binding['sensorId'] = undefined;
- for (const t of res.config[key]) {
- res.binding['sensorIds'].push(t['sensorId']);
- allSensors[t['sensorId']] = true;
- }
- } else {
- let ren = key;
- const map: any = {
- timestamp: 'span'
- };
- ren = map[ren] || ren;
- res.config[ren] = color(node[key]);
- }
- }
- if (_.isEmpty(res.config)) delete res.config;
- return res;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement