Advertisement
Guest User

Untitled

a guest
Oct 19th, 2018
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.79 KB | None | 0 0
  1. import * as _ from 'lodash';
  2. import { createConnection } from 'mysql';
  3. import { Utils } from 'tyx';
  4. import fs = require('fs');
  5.  
  6. const DBS = 'dbadmin:gUYZ6anpLEF3gksC@dev.db.n5-nederman.com:3306/iot_test';
  7. // const DBS = 'dbadmin:gUYZ6anpLEF3gksC@localhost:30306/iot_dev';
  8. const sensors: any[] = [];
  9.  
  10. main().then(() => console.log('done'));
  11.  
  12. const TO_CONVERT: any[] = []; // ["label", "onoff"];
  13.  
  14. async function main() {
  15. const tokens = DBS.split(/:|@|\/|;/);
  16. const db = createConnection({
  17. user: tokens[0],
  18. password: tokens[1],
  19. host: tokens[2],
  20. port: parseInt(tokens[3], 10),
  21. database: tokens[4]
  22. });
  23.  
  24. const dashboardFilter = [] ||
  25. [
  26. '52519425-c793-4405-87a1-0dfbbc507e0d'
  27. ];
  28.  
  29. const data = await new Promise<any>((resolve, reject) => {
  30. db.query(
  31. `SELECT * FROM dashboard`
  32. + (dashboardFilter.length ? ` WHERE dashboardId IN ('${dashboardFilter.join('\',\'')}')` : ''),
  33. (err, res) => {
  34. if (err) reject(err); else resolve(res);
  35. });
  36. });
  37.  
  38. const res: any = { layout: {}, widget: {} };
  39. for (const dash of data) {
  40.  
  41. try { JSON.parse(dash.definition); }
  42. catch (err) { console.error(dash.dashboardId); }
  43.  
  44. let json: any;
  45. try {
  46. json = JSON.parse(dash.definition);
  47. } catch (err) {
  48. console.error(err);
  49. continue;
  50. }
  51.  
  52. // if (json.version) throw new TypeError("New dashboard format");
  53. fs.writeFileSync(`src/tools/dashboard/org/old_${dash.dashboardId}.json`, JSON.stringify(json, null, 2));
  54.  
  55. /* set the new structure of the dashboard */
  56. // const allSensors = {};
  57. // visit(0, json, res, allSensors);
  58. // json = convertLayout(json);
  59.  
  60. /* set the sensors attached in the widgets in binding properties */
  61. // sensors = [];
  62. // getSensors(json);
  63. // json['binding'] = sensors;
  64.  
  65. /* update the old widgets */
  66. // json = updateOldWidgets(json);
  67.  
  68. json = newMetadataStructure(json);
  69.  
  70. json.type = 'dashboard';
  71. json.version = 2;
  72. fs.writeFileSync(`src/tools/dashboard/data/new_${dash.dashboardId}.json`, JSON.stringify(json, null, 2));
  73.  
  74. try {
  75. await new Promise<any>((resolve, reject) => {
  76. db.query(`UPDATE dashboard SET definition = ? WHERE dashboardId = ?`, [JSON.stringify(json), dash.dashboardId], (err, data) => {
  77. if (err) reject(err); else resolve(res);
  78. });
  79. });
  80. console.log(`Updated: [${dash.dashboardId}]`);
  81. } catch (err) {
  82. console.error(err);
  83. }
  84. }
  85. // res.layoutKeys = summ(res.layout);
  86. // res.widgetKeys = summ(res.widget);
  87. // console.log(res);
  88.  
  89. fs.writeFileSync('src/tools/dashboards.json', JSON.stringify(res, null, 2));
  90. db.destroy();
  91. }
  92.  
  93. function updateLayout(definition: any) {
  94.  
  95. if (!definition) { return null; }
  96. for (let i = 0; i < _.get(definition, 'children', definition).length; i++) {
  97.  
  98. /* if there are children in the element, check them */
  99. if (definition.children) {
  100.  
  101. /* if element has other children */
  102. if (!_.isEmpty(definition.children[i].children)) {
  103. updateLayout(definition.children[i]);
  104. }
  105. }
  106.  
  107. if (definition.children[i]['config']) {
  108. if (definition.children[i]['component'] !== 'multiLineChart') {
  109. definition.children[i]['layout'].label = sensors.find(sensor => sensor.sensorId === definition.children[i]['binding'].sensorId).label;
  110. delete definition.children[i]['layout'].name;
  111. }
  112. }
  113. }
  114. return definition;
  115. }
  116.  
  117. function newMetadataStructure(definition: any) {
  118. if (!definition) { return null; }
  119. for (let i = 0; i < _.get(definition, 'children', definition).length; i++) {
  120.  
  121. /* if there are children in the element, check them */
  122. if (definition.children) {
  123.  
  124. /* if element has other children */
  125. if (!_.isEmpty(definition.children[i].children)) {
  126. newMetadataStructure(definition.children[i]);
  127. }
  128. }
  129.  
  130. if (definition.children[i].config && definition.children[i].config.ranges) {
  131. definition.children[i].config.ranges = updateRanges(definition.children[i].config.ranges, definition.children[i].component, definition.children[i].config.max);
  132. definition.children[i].modified.ranges = updateRanges(definition.children[i].modified.ranges, definition.children[i].component, definition.children[i].modified.max);
  133. }
  134. }
  135. return definition;
  136. }
  137.  
  138. function updateRanges(rangesArray: { [key: string]: any }[], component: string, max?: any) {
  139. rangesArray.forEach((range: any, rangeIndex: any) => {
  140. rangesArray[rangeIndex].label = rangesArray[rangeIndex].indicator;
  141. delete rangesArray[rangeIndex].indicator;
  142.  
  143. if (component === 'onoff') {
  144.  
  145. rangesArray[rangeIndex].from = rangeIndex - 1;
  146.  
  147. if (rangeIndex !== rangesArray.length - 1) {
  148. rangesArray[rangeIndex].to = rangeIndex;
  149. } else {
  150. rangesArray[rangeIndex].to = rangeIndex - 1;
  151. }
  152. } else {
  153. rangesArray[rangeIndex].label = 'Range ' + (rangeIndex + 1);
  154. }
  155. });
  156.  
  157. if (component !== 'onoff') {
  158. rangesArray.push({
  159. from: max,
  160. to: max,
  161. label: null,
  162. color: null
  163. });
  164. }
  165.  
  166. return rangesArray;
  167. }
  168.  
  169. function updateOldWidgets(definition: any) {
  170. if (!definition) { return null; }
  171. for (let i = 0; i < _.get(definition, 'children', definition).length; i++) {
  172.  
  173. /* if there are children in the element, check them */
  174. if (definition.children) {
  175.  
  176. /* if element has other children */
  177. if (!_.isEmpty(definition.children[i].children)) {
  178. updateOldWidgets(definition.children[i]);
  179. }
  180. }
  181.  
  182. /* if widget is old one, set the default metadata to false and set modified = config */
  183. if (definition.children[i]['type'] === 'widget' && !definition.children[i]['layout']['defaultMetadata']) {
  184. definition.children[i]['layout']['defaultMetadata'] = 'false';
  185. definition.children[i]['modified'] = definition.children[i]['config'];
  186. }
  187.  
  188. /* if widget is old one, set the name and description in config and set modified = config */
  189. if (definition.children[i]['config'] && !definition.children[i]['config']['name']) {
  190. definition.children[i]['config']['name'] = definition.children[i]['layout']['name'];
  191. definition.children[i]['config']['description'] = definition.children[i]['layout']['description'];
  192. definition.children[i]['modified'] = definition.children[i]['config'];
  193. }
  194.  
  195. /* if element line-chart, set the type to mean(Average) and set modified = config */
  196. if (definition.children[i]['config'] &&
  197. (definition.children[i]['component'] === 'simpleLineChart' ||
  198. definition.children[i]['component'] === 'highstock' ||
  199. definition.children[i]['component'] === 'zoomableSpline' ||
  200. definition.children[i]['component'] === 'areaRange' ||
  201. definition.children[i]['component'] === 'barChart')
  202. && !definition.children[i]['config']['type']) {
  203. definition.children[i]['config']['type'] = 'mean';
  204. definition.children[i]['modified'] = definition.children[i]['config'];
  205. }
  206. }
  207. return definition;
  208. }
  209.  
  210. function getSensors(definition: any): any {
  211. if (!definition) { return null; }
  212. for (let i = 0; i < _.get(definition, 'children', definition).length; i++) {
  213.  
  214. /* if there are children in the element, check them */
  215. if (definition.children) {
  216.  
  217. /* if element is multiLine and there are sensors attached on it */
  218. if (definition.children[i]['component'] === 'multiLineChart' && definition.children[i]['config']) {
  219. getSensors(definition.children[i]['config']['sensors']);
  220. } else if (!_.isEmpty(definition.children[i].children)) {
  221. /* if element has other children */
  222. getSensors(definition.children[i]);
  223. }
  224. }
  225.  
  226. /* if element is list of the sensors attached on multiLine, sensors always have { binding: { sensorId: '' }} */
  227. if (!definition.children) {
  228. if (definition[i].binding) sensors.push(definition[i].binding.sensorId);
  229. else sensors.push(definition[i].sensorId);
  230. } else if (definition.children[i]['component'] !== 'multiLineChart') {
  231. /* if element not multiLine, check if it has attached */
  232. if (_.get(definition, 'children[' + i + '].binding', false)) {
  233. sensors.push(definition.children[i].binding.sensorId);
  234. }
  235. }
  236. }
  237. }
  238.  
  239. function visit(level: number, node: any, res: any, allSensors: any) {
  240. if (!node) return;
  241. const name = node.component;
  242. let group = res.layout;
  243.  
  244. if (node.tenantId || node.plantId || node.systemId || node.sensorId || res.widget[name]
  245. || name === 'mediaUpload'
  246. || name === 'textEditor'
  247. || name === 'sensorsTable'
  248. || name === 'alarmsTable'
  249. || name === 'section?'
  250. || name === 'label'
  251. ) {
  252. if (res.layout[name]) {
  253. res.widget[name] = res.layout[name];
  254. res.layout[name] = null;
  255. }
  256. group = res.widget;
  257. }
  258.  
  259. const cp = group[name] = group[name] || { component: name, count: 0, keys: {} };
  260. cp.count++;
  261. const ks = Object.keys(node);
  262. ks.forEach((k) => { cp.keys[k] = cp.keys[k] || 0; cp.keys[k]++; });
  263.  
  264. for (let i = 0; i < node.children.length; i++) {
  265. const n = node.children[i];
  266. const g = visit(level + 1, n, res, allSensors);
  267. const cv = (g === res.layout) ? convertLayout(n) : convertWidget(n, allSensors);
  268. node.children[i] = cv;
  269. }
  270. return group;
  271. }
  272.  
  273. function convertLayout(node: any) {
  274. const res: any = {
  275. type: 'layout',
  276. version: undefined as any,
  277. component: node.component,
  278. id: Utils.uuid(),
  279. binding: undefined as any,
  280. layout: {},
  281. // temp: {},
  282. children: node.children
  283. };
  284. for (const key in node) {
  285. if (res[key]) continue;
  286. if (['animation', 'isTemplate'].indexOf(key) > -1) {
  287. // res.temp[key] = node[key];
  288. continue;
  289. } else {
  290. res.layout[key] = node[key];
  291. }
  292. }
  293. return res;
  294. }
  295.  
  296. function color(val: string) {
  297. if (!val || !val.startsWith || !val.startsWith('rgb(')) return val;
  298. const rgb = '#' + val.replace('rgb(', '')
  299. .replace(')', '')
  300. .split(',')
  301. .map(v => +v)
  302. .map(v => v.toString(16))
  303. .map(v => v.length === 1 ? '0' + v : v)
  304. .join('').toUpperCase();
  305. return rgb;
  306. }
  307.  
  308. function convertWidget(node: any, allSensors: any) {
  309. if (TO_CONVERT.length && TO_CONVERT.indexOf(node.component) === -1) {
  310. return node;
  311. }
  312.  
  313. const res: any = {
  314. type: 'widget',
  315. component: node.component,
  316. id: Utils.uuid(),
  317. binding: undefined as any,
  318. layout: {},
  319. config: {} as any,
  320. children: node.children
  321. };
  322.  
  323. if (node.component === 'onoff') {
  324. res.config.ranges = [];
  325. if (node.errorRange) {
  326. res.config.ranges.push({
  327. indicator: node.errorRange.errorValueIndicator,
  328. color: color(node.errorRange.color)
  329. });
  330. }
  331. if (node.firstRange) {
  332. res.config.ranges.push({
  333. indicator: node.firstRange.zeroValueIndicator,
  334. color: color(node.firstRange.color)
  335. });
  336. }
  337. if (node.secondRange) {
  338. res.config.ranges.push({
  339. indicator: node.secondRange.firstValueIndicator,
  340. color: color(node.secondRange.color)
  341. });
  342. }
  343. if (node.thirdRange) {
  344. res.config.ranges.push({
  345. indicator: node.thirdRange.secondValueIndicator,
  346. color: color(node.thirdRange.color)
  347. });
  348. }
  349. if (node.fourthRange) {
  350. res.config.ranges.push({
  351. indicator: node.fourthRange.thirdValueIndicator,
  352. color: color(node.fourthRange.color)
  353. });
  354. }
  355. if (node.fifthRange) {
  356. res.config.ranges.push({
  357. indicator: node.fifthRange.fourthValueIndicator,
  358. color: color(node.fifthRange.color)
  359. });
  360. }
  361. if (res.config.ranges.length) delete node.ranges;
  362.  
  363. if (res.config.ranges.length < 6) {
  364. res.config.ranges = [
  365. {
  366. indicator: 'Error',
  367. color: '#BF0000'
  368. },
  369. {
  370. indicator: 'OFF',
  371. color: '#F4D502'
  372. },
  373. {
  374. indicator: 'Running 2',
  375. color: '#36CA38'
  376. },
  377. {
  378. indicator: '/',
  379. color: '#FF0000'
  380. },
  381. {
  382. indicator: 'Fault',
  383. color: '#7F7F7F'
  384. },
  385. {
  386. indicator: 'Alarm',
  387. color: '#FF4347'
  388. }
  389. ];
  390. }
  391. } else if (node.firstRange) {
  392. res.config.ranges = [];
  393. if (node.firstRange) {
  394. res.config.ranges.push({
  395. from: node.firstRange.from,
  396. to: node.firstRange.to,
  397. color: color(node.firstRange.color)
  398. });
  399. }
  400. if (node.secondRange) {
  401. res.config.ranges.push({
  402. from: node.secondRange.from,
  403. to: node.secondRange.to,
  404. color: color(node.secondRange.color)
  405. });
  406. }
  407. if (node.thirdRange) {
  408. res.config.ranges.push({
  409. from: node.thirdRange.from,
  410. to: node.thirdRange.to,
  411. color: color(node.thirdRange.color)
  412. });
  413. }
  414. }
  415.  
  416. delete node.errorRange;
  417. delete node.firstRange;
  418. delete node.secondRange;
  419. delete node.thirdRange;
  420. delete node.fourthRange;
  421. delete node.fifthRange;
  422.  
  423. if (Array.isArray(node.ranges)) {
  424. for (const item of node.ranges) {
  425. for (const key in item) {
  426. item[key] = color(item[key]);
  427. }
  428. }
  429. }
  430.  
  431. for (const key in node) {
  432. if (res[key]) continue;
  433. if (['tenantId', 'plantId', 'systemId', 'sensorId'].indexOf(key) > -1) {
  434. res.binding = res.binding || {};
  435. res.binding[key] = node[key];
  436.  
  437. if (key === 'sensorId') {
  438. allSensors[node[key]] = true;
  439. }
  440.  
  441. } else if (['animation', 'isTemplate', 'textDisplay'].indexOf(key) > -1) {
  442. // res.temp[key] = node[key];
  443. continue;
  444. } else if (['chartHeight', 'img', 'size', 'name', 'description', 'fontSize'].indexOf(key) > -1) {
  445. res.layout[key] = color(node[key]);
  446. } else if (['years', 'months', 'days', 'hours', 'minutes'].indexOf(key) > -1 && res['component'] === 'time') {
  447. // res.temp[key] = node[key];
  448. continue;
  449. } else if (['years', 'months', 'days', 'hours', 'minutes'].indexOf(key) > -1 && res['component'] === 'onoff') {
  450. // res.remove[key] = node[key];
  451. } else if (['scale'].indexOf(key) > -1) {
  452. // res.remove[key] = node[key];
  453. continue;
  454. } else if (['sensors'].indexOf(key) > -1) {
  455.  
  456. res.config[key] = color(node[key]);
  457.  
  458. res.binding['sensorIds'] = res.binding['sensorIds'] || [];
  459. res.binding['sensorId'] = undefined;
  460.  
  461. for (const t of res.config[key]) {
  462. res.binding['sensorIds'].push(t['sensorId']);
  463.  
  464. allSensors[t['sensorId']] = true;
  465.  
  466. }
  467. } else {
  468. let ren = key;
  469. const map: any = {
  470. timestamp: 'span'
  471. };
  472. ren = map[ren] || ren;
  473. res.config[ren] = color(node[key]);
  474. }
  475. }
  476. if (_.isEmpty(res.config)) delete res.config;
  477.  
  478. return res;
  479. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement