Commit 9ad09bb5ac0536b8700890fd99526fa3929daaca

Authored by Artem Halushko
2 parents 48901254 e9553b62

Merge branch 'develop/3.0' of https://github.com/thingsboard/thingsboard into map/3.0

Showing 43 changed files with 453 additions and 430 deletions
... ... @@ -5,7 +5,7 @@
5 5 "94715984-ae74-76e4-20b7-2f956b01ed80": {
6 6 "isSystemType": true,
7 7 "bundleAlias": "entity_admin_widgets",
8   - "typeAlias": "device_admin_table2",
  8 + "typeAlias": "device_admin_table",
9 9 "type": "latest",
10 10 "title": "New widget",
11 11 "sizeX": 24,
... ... @@ -1264,4 +1264,4 @@
1264 1264 }
1265 1265 },
1266 1266 "name": "Gateways"
1267   -}
\ No newline at end of file
  1267 +}
... ...
... ... @@ -6,7 +6,7 @@
6 6 },
7 7 "widgetTypes": [
8 8 {
9   - "alias": "device_admin_table2",
  9 + "alias": "device_admin_table",
10 10 "name": "Device admin table",
11 11 "descriptor": {
12 12 "type": "latest",
... ... @@ -22,7 +22,7 @@
22 22 }
23 23 },
24 24 {
25   - "alias": "device_admin_table",
  25 + "alias": "asset_admin_table",
26 26 "name": "Asset admin table",
27 27 "descriptor": {
28 28 "type": "latest",
... ...
... ... @@ -14,7 +14,7 @@
14 14 "sizeY": 2,
15 15 "resources": [],
16 16 "templateHtml": "<fieldset class=\"gpio-panel\" style=\"height: 100%;\">\n <section class=\"gpio-row\" fxLayout=\"row\" *ngFor=\"let row of rows\" \n [ngStyle]=\"{'height': prefferedRowHeight+'px'}\">\n <section fxFlex fxLayout=\"row\" *ngFor=\"let cell of row; let $index = index\">\n <section fxLayout=\"row\" fxFlex *ngIf=\"cell\" fxLayoutAlign=\"{{$index===0 ? 'end center' : 'start center'}}\">\n <span class=\"gpio-left-label\" [fxShow]=\"$index===0\">{{ cell.label }}</span>\n <section fxLayout=\"row\" class=\"switch-panel\" fxLayoutAlign=\"start center\" [ngClass]=\"$index===0 ? 'col-0' : 'col-1'\"\n [ngStyle]=\"{'height': prefferedRowHeight+'px', 'backgroundColor': switchPanelBackgroundColor }\">\n <span class=\"pin\" [fxShow]=\"$index===0\">{{cell.pin}}</span>\n <span fxFlex [fxShow]=\"$index===1\"></span>\n <mat-slide-toggle\n [disabled]=\"!rpcEnabled || executingRpcRequest\"\n [checked]=\"cell.enabled\" \n (change)=\"gpioToggleChange($event, cell)\" \n (click)=\"gpioClick($event, cell)\">\n </mat-slide-toggle>\n <span fxFlex [fxShow]=\"$index===0\"></span>\n <span class=\"pin\" [fxShow]=\"$index===1\">{{cell.pin}}</span>\n </section>\n <span class=\"gpio-right-label\" [fxShow]=\"$index===1\">{{ cell.label }}</span>\n </section>\n <section fxLayout=\"row\" fxFlex *ngIf=\"!cell\">\n <span fxFlex [fxShow]=\"$index===0\"></span>\n <span class=\"switch-panel\"\n [ngStyle]=\"{'height': prefferedRowHeight+'px', 'backgroundColor': switchPanelBackgroundColor }\"></span>\n <span fxFlex [fxShow]=\"$index===1\"></span>\n </section>\n </section>\n </section> \n <span class=\"error\" style=\"position: absolute; bottom: 5px;\" [fxShow]=\"rpcErrorText\">{{rpcErrorText}}</span>\n <mat-progress-bar [fxShow]=\"executingRpcRequest\" style=\"position: absolute; bottom: 0;\" mode=\"indeterminate\"></mat-progress-bar>\n</fieldset>",
17   - "templateCss": ".error {\n font-size: 14px !important;\n color: maroon;/*rgb(250,250,250);*/\n background-color: transparent;\n padding: 6px;\n}\n\n.error span {\n margin: auto;\n}\n\n.gpio-panel {\n padding-top: 10px;\n white-space: nowrap;\n}\n\n.switch-panel {\n margin: 0;\n height: 32px;\n width: 66px;\n min-width: 66px;\n}\n\n.switch-panel mat-slide-toggle {\n margin: 0;\n width: 36px;\n min-width: 36px;\n}\n\n.switch-panel.col-0 mat-slide-toggle {\n margin-left: 8px;\n margin-right: 4px;\n}\n\n.switch-panel.col-1 mat-slide-toggle {\n margin-left: 4px;\n margin-right: 8px;\n}\n\n.gpio-row {\n height: 32px;\n}\n\n.pin {\n margin-top: auto;\n margin-bottom: auto;\n color: white;\n font-size: 12px;\n width: 16px;\n min-width: 16px;\n}\n\n.switch-panel.col-0 .pin {\n margin-left: auto;\n padding-left: 2px;\n text-align: right;\n}\n\n.switch-panel.col-1 .pin {\n margin-right: auto;\n \n text-align: left;\n}\n\n.gpio-left-label {\n margin-right: 8px;\n}\n\n.gpio-right-label {\n margin-left: 8px;\n}",
  17 + "templateCss": ".error {\n font-size: 14px !important;\n color: maroon;/*rgb(250,250,250);*/\n background-color: transparent;\n padding: 6px;\n}\n\n.error span {\n margin: auto;\n}\n\n.gpio-panel {\n padding-top: 10px;\n white-space: nowrap;\n}\n\n.gpio-panel section[fxflex] {\n min-width: 0px;\n}\n\n\n.switch-panel {\n margin: 0;\n height: 32px;\n width: 66px;\n min-width: 66px;\n}\n\n.switch-panel mat-slide-toggle {\n margin: 0;\n width: 36px;\n min-width: 36px;\n}\n\n.switch-panel.col-0 mat-slide-toggle {\n margin-left: 8px;\n margin-right: 4px;\n}\n\n.switch-panel.col-1 mat-slide-toggle {\n margin-left: 4px;\n margin-right: 8px;\n}\n\n.gpio-row {\n height: 32px;\n}\n\n.pin {\n margin-top: auto;\n margin-bottom: auto;\n color: white;\n font-size: 12px;\n width: 16px;\n min-width: 16px;\n}\n\n.switch-panel.col-0 .pin {\n margin-left: auto;\n padding-left: 2px;\n text-align: right;\n}\n\n.switch-panel.col-1 .pin {\n margin-right: auto;\n \n text-align: left;\n}\n\n.gpio-left-label {\n margin-right: 8px;\n}\n\n.gpio-right-label {\n margin-left: 8px;\n}",
18 18 "controllerScript": "var namespace;\nvar cssParser = new cssjs();\n\nself.onInit = function() {\n var utils = self.ctx.$injector.get(self.ctx.servicesMap.get('utils'));\n namespace = 'gpio-control-' + utils.guid();\n cssParser.testMode = false;\n cssParser.cssPreviewNamespace = namespace;\n self.ctx.$container.addClass(namespace);\n self.ctx.ngZone.run(function() {\n init(); \n });\n}\n\nfunction init() {\n \n var i, gpio;\n var scope = self.ctx.$scope;\n var settings = self.ctx.settings;\n scope.gpioList = [];\n for (var g = 0; g < settings.gpioList.length; g++) {\n gpio = settings.gpioList[g];\n scope.gpioList.push(\n {\n row: gpio.row,\n col: gpio.col,\n pin: gpio.pin,\n label: gpio.label,\n enabled: false\n }\n );\n }\n\n scope.requestTimeout = settings.requestTimeout || 1000;\n\n scope.switchPanelBackgroundColor = settings.switchPanelBackgroundColor || tinycolor('green').lighten(2).toRgbString();\n\n scope.gpioStatusRequest = {\n method: \"getGpioStatus\",\n paramsBody: \"{}\"\n };\n \n if (settings.gpioStatusRequest) {\n scope.gpioStatusRequest.method = settings.gpioStatusRequest.method || scope.gpioStatusRequest.method;\n scope.gpioStatusRequest.paramsBody = settings.gpioStatusRequest.paramsBody || scope.gpioStatusRequest.paramsBody;\n }\n \n scope.gpioStatusChangeRequest = {\n method: \"setGpioStatus\",\n paramsBody: \"{\\n \\\"pin\\\": \\\"{$pin}\\\",\\n \\\"enabled\\\": \\\"{$enabled}\\\"\\n}\"\n };\n \n if (settings.gpioStatusChangeRequest) {\n scope.gpioStatusChangeRequest.method = settings.gpioStatusChangeRequest.method || scope.gpioStatusChangeRequest.method;\n scope.gpioStatusChangeRequest.paramsBody = settings.gpioStatusChangeRequest.paramsBody || scope.gpioStatusChangeRequest.paramsBody;\n }\n \n scope.parseGpioStatusFunction = \"return body[pin] === true;\";\n \n if (settings.parseGpioStatusFunction && settings.parseGpioStatusFunction.length > 0) {\n scope.parseGpioStatusFunction = settings.parseGpioStatusFunction;\n }\n \n scope.parseGpioStatusFunction = new Function(\"body, pin\", scope.parseGpioStatusFunction);\n \n function requestGpioStatus() {\n self.ctx.controlApi.sendTwoWayCommand(scope.gpioStatusRequest.method, \n scope.gpioStatusRequest.paramsBody, \n scope.requestTimeout)\n .subscribe(\n function success(responseBody) {\n for (var g = 0; g < scope.gpioList.length; g++) {\n var gpio = scope.gpioList[g];\n var enabled = scope.parseGpioStatusFunction.apply(this, [responseBody, gpio.pin]);\n gpio.enabled = enabled; \n self.ctx.detectChanges();\n }\n }\n );\n }\n \n function changeGpioStatus(gpio) {\n var pin = gpio.pin + '';\n var enabled = !gpio.enabled;\n enabled = enabled === true ? 'true' : 'false';\n var paramsBody = scope.gpioStatusChangeRequest.paramsBody;\n var requestBody = JSON.parse(paramsBody.replace(\"\\\"{$pin}\\\"\", pin).replace(\"\\\"{$enabled}\\\"\", enabled));\n self.ctx.controlApi.sendTwoWayCommand(scope.gpioStatusChangeRequest.method, \n requestBody, scope.requestTimeout)\n .subscribe(\n function success(responseBody) {\n var enabled = scope.parseGpioStatusFunction.apply(this, [responseBody, gpio.pin]);\n gpio.enabled = enabled;\n self.ctx.detectChanges();\n }\n );\n }\n \n scope.gpioCells = {};\n var rowCount = 0;\n for (i = 0; i < scope.gpioList.length; i++) {\n gpio = scope.gpioList[i];\n scope.gpioCells[gpio.row+'_'+gpio.col] = gpio;\n rowCount = Math.max(rowCount, gpio.row+1);\n }\n \n scope.prefferedRowHeight = 32;\n scope.rows = [];\n for (i = 0; i < rowCount; i++) {\n var row = [];\n for (var c =0; c<2;c++) {\n if (scope.gpioCells[i+'_'+c]) {\n row[c] = scope.gpioCells[i+'_'+c];\n } else {\n row[c] = null;\n }\n }\n scope.rows.push(row);\n }\n\n scope.gpioClick = function($event, gpio) {\n if (scope.rpcEnabled && !scope.executingRpcRequest) {\n changeGpioStatus(gpio);\n }\n };\n \n scope.gpioToggleChange = function($event, gpio) {\n gpio.enabled = !$event.checked;\n $event.source.toggle();\n self.ctx.detectChanges();\n }\n \n if (scope.rpcEnabled) {\n requestGpioStatus(); \n }\n \n self.onResize();\n}\n\nself.onResize = function() {\n var scope = self.ctx.$scope;\n var rowCount = scope.rows.length;\n var prefferedRowHeight = (self.ctx.height - 35)/rowCount;\n prefferedRowHeight = Math.min(32, prefferedRowHeight);\n prefferedRowHeight = Math.max(12, prefferedRowHeight);\n scope.prefferedRowHeight = prefferedRowHeight;\n var ratio = prefferedRowHeight/32;\n \n var css = '.mat-slide-toggle .mat-slide-toggle-bar {\\n' +\n ' height: ' + 14*ratio+'px;\\n'+\n ' width: ' + 36*ratio+'px;\\n'+\n '}\\n';\n css += '.mat-slide-toggle .mat-slide-toggle-thumb-container {\\n' +\n ' height: ' + 20*ratio+'px;\\n'+\n ' width: ' + 20*ratio+'px;\\n'+\n '}\\n';\n css += '.mat-slide-toggle .mat-slide-toggle-thumb {\\n' +\n ' height: ' + 20*ratio+'px;\\n'+\n ' width: ' + 20*ratio+'px;\\n'+\n '}\\n';\n css += '.mat-slide-toggle .mat-slide-toggle-ripple {\\n' +\n ' height: ' + 40*ratio+'px;\\n'+\n ' width: ' + 40*ratio+'px;\\n'+\n ' top: calc(50% - '+20*ratio+'px);\\n'+\n ' left: calc(50% - '+20*ratio+'px);\\n'+\n '}\\n';\n css += '.gpio-left-label, .gpio-right-label {\\n' +\n ' font-size: ' + 16*ratio+'px;\\n'+\n '}\\n';\n var pinsFontSize = Math.max(9, 12*ratio);\n css += '.pin {\\n' +\n ' font-size: ' + pinsFontSize+'px;\\n'+\n '}\\n';\n\n cssParser.createStyleElement(namespace, css);\n \n self.ctx.detectChanges();\n}\n\nself.onDestroy = function() {\n}\n",
19 19 "settingsSchema": "{\n \"schema\": {\n \"type\": \"object\",\n \"title\": \"Settings\",\n \"properties\": {\n \"gpioList\": {\n \"title\": \"Gpio switches\",\n \"type\": \"array\",\n \"minItems\" : 1,\n \"items\": {\n \"title\": \"Gpio switch\",\n \"type\": \"object\",\n \"properties\": {\n \"pin\": {\n \"title\": \"Pin\",\n \"type\": \"number\"\n },\n \"label\": {\n \"title\": \"Label\",\n \"type\": \"string\"\n },\n \"row\": {\n \"title\": \"Row\",\n \"type\": \"number\"\n },\n \"col\": {\n \"title\": \"Column\",\n \"type\": \"number\"\n }\n },\n \"required\": [\"pin\", \"label\", \"row\", \"col\"]\n }\n },\n \"requestTimeout\": {\n \"title\": \"RPC request timeout\",\n \"type\": \"number\",\n \"default\": 500\n },\n \"switchPanelBackgroundColor\": {\n \"title\": \"Switches panel background color\",\n \"type\": \"string\",\n \"default\": \"#008a00\"\n },\n \"gpioStatusRequest\": {\n \"title\": \"GPIO status request\",\n \"type\": \"object\",\n \"properties\": {\n \"method\": {\n \"title\": \"Method name\",\n \"type\": \"string\",\n \"default\": \"getGpioStatus\"\n },\n \"paramsBody\": {\n \"title\": \"Method body\",\n \"type\": \"string\",\n \"default\": \"{}\"\n }\n },\n \"required\": [\"method\", \"paramsBody\"]\n },\n \"gpioStatusChangeRequest\": {\n \"title\": \"GPIO status change request\",\n \"type\": \"object\",\n \"properties\": {\n \"method\": {\n \"title\": \"Method name\",\n \"type\": \"string\",\n \"default\": \"setGpioStatus\"\n },\n \"paramsBody\": {\n \"title\": \"Method body\",\n \"type\": \"string\",\n \"default\": \"{\\n \\\"pin\\\": \\\"{$pin}\\\",\\n \\\"enabled\\\": \\\"{$enabled}\\\"\\n}\"\n }\n },\n \"required\": [\"method\", \"paramsBody\"]\n },\n \"parseGpioStatusFunction\": {\n \"title\": \"Parse gpio status function\",\n \"type\": \"string\",\n \"default\": \"return body[pin] === true;\"\n } \n },\n \"required\": [\"gpioList\", \n \"requestTimeout\",\n \"switchPanelBackgroundColor\",\n \"gpioStatusRequest\",\n \"gpioStatusChangeRequest\",\n \"parseGpioStatusFunction\"]\n },\n \"form\": [\n \"gpioList\",\n \"requestTimeout\",\n {\n \"key\": \"switchPanelBackgroundColor\",\n \"type\": \"color\"\n },\n {\n \"key\": \"gpioStatusRequest\",\n \"items\": [\n \"gpioStatusRequest.method\",\n {\n \"key\": \"gpioStatusRequest.paramsBody\",\n \"type\": \"json\"\n }\n ]\n },\n {\n \"key\": \"gpioStatusChangeRequest\",\n \"items\": [\n \"gpioStatusChangeRequest.method\",\n {\n \"key\": \"gpioStatusChangeRequest.paramsBody\",\n \"type\": \"json\"\n }\n ]\n },\n {\n \"key\": \"parseGpioStatusFunction\",\n \"type\": \"javascript\"\n }\n ]\n}",
20 20 "dataKeySettingsSchema": "{}\n",
... ... @@ -30,7 +30,7 @@
30 30 "sizeY": 2,
31 31 "resources": [],
32 32 "templateHtml": "<div class=\"gpio-panel\" style=\"height: 100%;\">\n <section fxLayout=\"row\" *ngFor=\"let row of rows\">\n <section fxFlex fxLayout=\"row\" *ngFor=\"let cell of row; let $index = index\">\n <section fxLayout=\"row\" fxFlex *ngIf=\"cell\" fxLayoutAlign=\"{{$index===0 ? 'end center' : 'start center'}}\">\n <span class=\"gpio-left-label\" [fxShow]=\"$index===0\">{{ cell.label }}</span>\n <section fxLayout=\"row\" class=\"led-panel\" [ngClass]=\"$index===0 ? 'col-0' : 'col-1'\"\n [ngStyle]=\"{backgroundColor: ledPanelBackgroundColor}\">\n <span class=\"pin\" [fxShow]=\"$index===0\">{{cell.pin}}</span>\n <span class=\"led-container\">\n <tb-led-light [size]=\"prefferedRowHeight\"\n [colorOn]=\"cell.colorOn\"\n [colorOff]=\"cell.colorOff\"\n [offOpacity]=\"'0.9'\"\n [enabled]=\"cell.enabled\">\n </tb-led-light>\n </span>\n <span class=\"pin\" [fxShow]=\"$index===1\">{{cell.pin}}</span>\n </section>\n <span class=\"gpio-right-label\" [fxShow]=\"$index===1\">{{ cell.label }}</span>\n </section>\n <section fxLayout=\"row\" fxFlex *ngIf=\"!cell\">\n <span fxFlex [fxShow]=\"$index===0\"></span>\n <span class=\"led-panel\"\n [ngStyle]=\"{backgroundColor: ledPanelBackgroundColor}\"></span>\n <span fxFlex [fxShow]=\"$index===1\"></span>\n </section>\n </section>\n </section> \n</div>",
33   - "templateCss": ".error {\n font-size: 14px !important;\n color: maroon;/*rgb(250,250,250);*/\n background-color: transparent;\n padding: 6px;\n}\n\n.error span {\n margin: auto;\n}\n\n.gpio-panel {\n padding-top: 10px;\n white-space: nowrap;\n}\n\n.gpio-panel tb-led-light > div {\n margin: auto;\n}\n\n.led-panel {\n margin: 0;\n width: 66px;\n min-width: 66px;\n}\n\n.led-container {\n width: 48px;\n min-width: 48px;\n}\n\n.pin {\n margin-top: auto;\n margin-bottom: auto;\n color: white;\n font-size: 12px;\n width: 16px;\n min-width: 16px;\n}\n\n.led-panel.col-0 .pin {\n margin-left: auto;\n padding-left: 2px;\n text-align: right;\n}\n\n.led-panel.col-1 .pin {\n margin-right: auto;\n \n text-align: left;\n}\n\n.gpio-left-label {\n margin-right: 8px;\n}\n\n.gpio-right-label {\n margin-left: 8px;\n}",
  33 + "templateCss": ".error {\n font-size: 14px !important;\n color: maroon;/*rgb(250,250,250);*/\n background-color: transparent;\n padding: 6px;\n}\n\n.error span {\n margin: auto;\n}\n\n.gpio-panel {\n padding-top: 10px;\n white-space: nowrap;\n}\n\n.gpio-panel section[fxflex] {\n min-width: 0px;\n}\n\n\n.gpio-panel tb-led-light > div {\n margin: auto;\n}\n\n.led-panel {\n margin: 0;\n width: 66px;\n min-width: 66px;\n}\n\n.led-container {\n width: 48px;\n min-width: 48px;\n}\n\n.pin {\n margin-top: auto;\n margin-bottom: auto;\n color: white;\n font-size: 12px;\n width: 16px;\n min-width: 16px;\n}\n\n.led-panel.col-0 .pin {\n margin-left: auto;\n padding-left: 2px;\n text-align: right;\n}\n\n.led-panel.col-1 .pin {\n margin-right: auto;\n \n text-align: left;\n}\n\n.gpio-left-label {\n margin-right: 8px;\n}\n\n.gpio-right-label {\n margin-left: 8px;\n}",
34 34 "controllerScript": "var namespace;\nvar cssParser = new cssjs();\n\nself.onInit = function() {\n var utils = self.ctx.$injector.get(self.ctx.servicesMap.get('utils'));\n namespace = 'gpio-panel-' + utils.guid();\n cssParser.testMode = false;\n cssParser.cssPreviewNamespace = namespace;\n self.ctx.$container.addClass(namespace);\n self.ctx.ngZone.run(function() {\n init(); \n });\n}\n\nfunction init() {\n var i, gpio;\n \n var scope = self.ctx.$scope;\n var settings = self.ctx.settings;\n \n scope.gpioList = [];\n scope.gpioByPin = {};\n for (var g = 0; g < settings.gpioList.length; g++) {\n gpio = settings.gpioList[g];\n scope.gpioList.push(\n {\n row: gpio.row,\n col: gpio.col,\n pin: gpio.pin,\n label: gpio.label,\n enabled: false,\n colorOn: tinycolor(gpio.color).lighten(20).toHexString(),\n colorOff: tinycolor(gpio.color).darken().toHexString()\n }\n );\n scope.gpioByPin[gpio.pin] = scope.gpioList[scope.gpioList.length-1];\n }\n\n scope.ledPanelBackgroundColor = settings.ledPanelBackgroundColor || tinycolor('green').lighten(2).toRgbString();\n\n scope.gpioCells = {};\n var rowCount = 0;\n for (i = 0; i < scope.gpioList.length; i++) {\n gpio = scope.gpioList[i];\n scope.gpioCells[gpio.row+'_'+gpio.col] = gpio;\n rowCount = Math.max(rowCount, gpio.row+1);\n }\n \n scope.prefferedRowHeight = 32;\n scope.rows = [];\n for (i = 0; i < rowCount; i++) {\n var row = [];\n for (var c =0; c<2;c++) {\n if (scope.gpioCells[i+'_'+c]) {\n row[c] = scope.gpioCells[i+'_'+c];\n } else {\n row[c] = null;\n }\n }\n scope.rows.push(row);\n } \n \n self.onResize();\n}\n\nself.onDataUpdated = function() {\n var changed = false;\n for (var d = 0; d < self.ctx.data.length; d++) {\n var cellData = self.ctx.data[d];\n var dataKey = cellData.dataKey;\n var gpio = self.ctx.$scope.gpioByPin[dataKey.label];\n if (gpio) {\n var enabled = false;\n if (cellData.data.length > 0) {\n var tvPair = cellData.data[cellData.data.length - 1];\n enabled = (tvPair[1] === true || tvPair[1] === 'true');\n }\n if (gpio.enabled != enabled) {\n changed = true;\n gpio.enabled = enabled;\n }\n }\n }\n if (changed) {\n self.ctx.detectChanges();\n } \n}\n\nself.onResize = function() {\n var rowCount = self.ctx.$scope.rows.length;\n var prefferedRowHeight = (self.ctx.height - 35)/rowCount;\n prefferedRowHeight = Math.min(32, prefferedRowHeight);\n prefferedRowHeight = Math.max(12, prefferedRowHeight);\n self.ctx.$scope.prefferedRowHeight = prefferedRowHeight;\n \n var ratio = prefferedRowHeight/32;\n \n var css = '.gpio-left-label, .gpio-right-label {\\n' +\n ' font-size: ' + 16*ratio+'px;\\n'+\n '}\\n';\n var pinsFontSize = Math.max(9, 12*ratio);\n css += '.pin {\\n' +\n ' font-size: ' + pinsFontSize+'px;\\n'+\n '}\\n';\n \n cssParser.createStyleElement(namespace, css); \n \n self.ctx.detectChanges();\n}\n\nself.onDestroy = function() {\n}\n",
35 35 "settingsSchema": "{\n \"schema\": {\n \"type\": \"object\",\n \"title\": \"Settings\",\n \"properties\": {\n \"gpioList\": {\n \"title\": \"Gpio leds\",\n \"type\": \"array\",\n \"minItems\" : 1,\n \"items\": {\n \"title\": \"Gpio led\",\n \"type\": \"object\",\n \"properties\": {\n \"pin\": {\n \"title\": \"Pin\",\n \"type\": \"number\"\n },\n \"label\": {\n \"title\": \"Label\",\n \"type\": \"string\"\n },\n \"row\": {\n \"title\": \"Row\",\n \"type\": \"number\"\n },\n \"col\": {\n \"title\": \"Column\",\n \"type\": \"number\"\n },\n \"color\": {\n \"title\": \"Color\",\n \"type\": \"string\",\n \"default\": \"red\"\n }\n },\n \"required\": [\"pin\", \"label\", \"row\", \"col\", \"color\"]\n }\n },\n \"ledPanelBackgroundColor\": {\n \"title\": \"LED panel background color\",\n \"type\": \"string\",\n \"default\": \"#008a00\"\n } \n },\n \"required\": [\"gpioList\", \n \"ledPanelBackgroundColor\"]\n },\n \"form\": [\n {\n \"key\": \"gpioList\",\n \"items\": [\n \"gpioList[].pin\",\n \"gpioList[].label\",\n \"gpioList[].row\",\n \"gpioList[].col\",\n {\n \"key\": \"gpioList[].color\",\n \"type\": \"color\"\n }\n ]\n },\n {\n \"key\": \"ledPanelBackgroundColor\",\n \"type\": \"color\"\n }\n ]\n}",
36 36 "dataKeySettingsSchema": "{}\n",
... ... @@ -38,22 +38,6 @@
38 38 }
39 39 },
40 40 {
41   - "alias": "raspberry_pi_gpio_control",
42   - "name": "Raspberry Pi GPIO Control",
43   - "descriptor": {
44   - "type": "rpc",
45   - "sizeX": 6,
46   - "sizeY": 10.5,
47   - "resources": [],
48   - "templateHtml": "<fieldset class=\"gpio-panel\" style=\"height: 100%;\">\n <section class=\"gpio-row\" fxLayout=\"row\" *ngFor=\"let row of rows\" \n [ngStyle]=\"{'height': prefferedRowHeight+'px'}\">\n <section fxFlex fxLayout=\"row\" *ngFor=\"let cell of row; let $index = index\">\n <section fxLayout=\"row\" fxFlex *ngIf=\"cell\" fxLayoutAlign=\"{{$index===0 ? 'end center' : 'start center'}}\">\n <span class=\"gpio-left-label\" [fxShow]=\"$index===0\">{{ cell.label }}</span>\n <section fxLayout=\"row\" class=\"switch-panel\" fxLayoutAlign=\"start center\" [ngClass]=\"$index===0 ? 'col-0' : 'col-1'\"\n [ngStyle]=\"{'height': prefferedRowHeight+'px', 'backgroundColor': switchPanelBackgroundColor }\">\n <span class=\"pin\" [fxShow]=\"$index===0\">{{cell.pin}}</span>\n <span fxFlex [fxShow]=\"$index===1\"></span>\n <mat-slide-toggle\n [disabled]=\"!rpcEnabled || executingRpcRequest\"\n [checked]=\"cell.enabled\" \n (change)=\"gpioToggleChange($event, cell)\" \n (click)=\"gpioClick($event, cell)\">\n </mat-slide-toggle>\n <span fxFlex [fxShow]=\"$index===0\"></span>\n <span class=\"pin\" [fxShow]=\"$index===1\">{{cell.pin}}</span>\n </section>\n <span class=\"gpio-right-label\" [fxShow]=\"$index===1\">{{ cell.label }}</span>\n </section>\n <section fxLayout=\"row\" fxFlex *ngIf=\"!cell\">\n <span fxFlex [fxShow]=\"$index===0\"></span>\n <span class=\"switch-panel\"\n [ngStyle]=\"{'height': prefferedRowHeight+'px', 'backgroundColor': switchPanelBackgroundColor }\"></span>\n <span fxFlex [fxShow]=\"$index===1\"></span>\n </section>\n </section>\n </section> \n <span class=\"error\" style=\"position: absolute; bottom: 5px;\" [fxShow]=\"rpcErrorText\">{{rpcErrorText}}</span>\n <mat-progress-bar [fxShow]=\"executingRpcRequest\" style=\"position: absolute; bottom: 0;\" mode=\"indeterminate\"></mat-progress-bar>\n</fieldset>",
49   - "templateCss": ".error {\n font-size: 14px !important;\n color: maroon;/*rgb(250,250,250);*/\n background-color: transparent;\n padding: 6px;\n}\n\n.error span {\n margin: auto;\n}\n\n.gpio-panel {\n padding-top: 10px;\n white-space: nowrap;\n}\n\n.switch-panel {\n margin: 0;\n height: 32px;\n width: 66px;\n min-width: 66px;\n}\n\n.switch-panel mat-slide-toggle {\n margin: 0;\n width: 36px;\n min-width: 36px;\n}\n\n.switch-panel.col-0 mat-slide-toggle {\n margin-left: 8px;\n margin-right: 4px;\n}\n\n.switch-panel.col-1 mat-slide-toggle {\n margin-left: 4px;\n margin-right: 8px;\n}\n\n.gpio-row {\n height: 32px;\n}\n\n.pin {\n margin-top: auto;\n margin-bottom: auto;\n color: white;\n font-size: 12px;\n width: 16px;\n min-width: 16px;\n}\n\n.switch-panel.col-0 .pin {\n margin-left: auto;\n padding-left: 2px;\n text-align: right;\n}\n\n.switch-panel.col-1 .pin {\n margin-right: auto;\n \n text-align: left;\n}\n\n.gpio-left-label {\n margin-right: 8px;\n}\n\n.gpio-right-label {\n margin-left: 8px;\n}",
50   - "controllerScript": "var namespace;\nvar cssParser = new cssjs();\n\nself.onInit = function() {\n var utils = self.ctx.$injector.get(self.ctx.servicesMap.get('utils'));\n namespace = 'gpio-control-' + utils.guid();\n cssParser.testMode = false;\n cssParser.cssPreviewNamespace = namespace;\n self.ctx.$container.addClass(namespace);\n self.ctx.ngZone.run(function() {\n init(); \n });\n}\n\nfunction init() {\n \n var i, gpio;\n var scope = self.ctx.$scope;\n var settings = self.ctx.settings;\n scope.gpioList = [];\n for (var g = 0; g < settings.gpioList.length; g++) {\n gpio = settings.gpioList[g];\n scope.gpioList.push(\n {\n row: gpio.row,\n col: gpio.col,\n pin: gpio.pin,\n label: gpio.label,\n enabled: false\n }\n );\n }\n\n scope.requestTimeout = settings.requestTimeout || 1000;\n\n scope.switchPanelBackgroundColor = settings.switchPanelBackgroundColor || tinycolor('green').lighten(2).toRgbString();\n\n scope.gpioStatusRequest = {\n method: \"getGpioStatus\",\n paramsBody: \"{}\"\n };\n \n if (settings.gpioStatusRequest) {\n scope.gpioStatusRequest.method = settings.gpioStatusRequest.method || scope.gpioStatusRequest.method;\n scope.gpioStatusRequest.paramsBody = settings.gpioStatusRequest.paramsBody || scope.gpioStatusRequest.paramsBody;\n }\n \n scope.gpioStatusChangeRequest = {\n method: \"setGpioStatus\",\n paramsBody: \"{\\n \\\"pin\\\": \\\"{$pin}\\\",\\n \\\"enabled\\\": \\\"{$enabled}\\\"\\n}\"\n };\n \n if (settings.gpioStatusChangeRequest) {\n scope.gpioStatusChangeRequest.method = settings.gpioStatusChangeRequest.method || scope.gpioStatusChangeRequest.method;\n scope.gpioStatusChangeRequest.paramsBody = settings.gpioStatusChangeRequest.paramsBody || scope.gpioStatusChangeRequest.paramsBody;\n }\n \n scope.parseGpioStatusFunction = \"return body[pin] === true;\";\n \n if (settings.parseGpioStatusFunction && settings.parseGpioStatusFunction.length > 0) {\n scope.parseGpioStatusFunction = settings.parseGpioStatusFunction;\n }\n \n scope.parseGpioStatusFunction = new Function(\"body, pin\", scope.parseGpioStatusFunction);\n \n function requestGpioStatus() {\n self.ctx.controlApi.sendTwoWayCommand(scope.gpioStatusRequest.method, \n scope.gpioStatusRequest.paramsBody, \n scope.requestTimeout)\n .subscribe(\n function success(responseBody) {\n for (var g = 0; g < scope.gpioList.length; g++) {\n var gpio = scope.gpioList[g];\n var enabled = scope.parseGpioStatusFunction.apply(this, [responseBody, gpio.pin]);\n gpio.enabled = enabled; \n self.ctx.detectChanges();\n }\n }\n );\n }\n \n function changeGpioStatus(gpio) {\n var pin = gpio.pin + '';\n var enabled = !gpio.enabled;\n enabled = enabled === true ? 'true' : 'false';\n var paramsBody = scope.gpioStatusChangeRequest.paramsBody;\n var requestBody = JSON.parse(paramsBody.replace(\"\\\"{$pin}\\\"\", pin).replace(\"\\\"{$enabled}\\\"\", enabled));\n self.ctx.controlApi.sendTwoWayCommand(scope.gpioStatusChangeRequest.method, \n requestBody, scope.requestTimeout)\n .subscribe(\n function success(responseBody) {\n var enabled = scope.parseGpioStatusFunction.apply(this, [responseBody, gpio.pin]);\n gpio.enabled = enabled;\n self.ctx.detectChanges();\n }\n );\n }\n \n scope.gpioCells = {};\n var rowCount = 0;\n for (i = 0; i < scope.gpioList.length; i++) {\n gpio = scope.gpioList[i];\n scope.gpioCells[gpio.row+'_'+gpio.col] = gpio;\n rowCount = Math.max(rowCount, gpio.row+1);\n }\n \n scope.prefferedRowHeight = 32;\n scope.rows = [];\n for (i = 0; i < rowCount; i++) {\n var row = [];\n for (var c =0; c<2;c++) {\n if (scope.gpioCells[i+'_'+c]) {\n row[c] = scope.gpioCells[i+'_'+c];\n } else {\n row[c] = null;\n }\n }\n scope.rows.push(row);\n }\n\n scope.gpioClick = function($event, gpio) {\n if (scope.rpcEnabled && !scope.executingRpcRequest) {\n changeGpioStatus(gpio);\n }\n };\n \n scope.gpioToggleChange = function($event, gpio) {\n gpio.enabled = !$event.checked;\n $event.source.toggle();\n self.ctx.detectChanges();\n }\n \n if (scope.rpcEnabled) {\n requestGpioStatus(); \n }\n \n self.onResize();\n}\n\nself.onResize = function() {\n var scope = self.ctx.$scope;\n var rowCount = scope.rows.length;\n var prefferedRowHeight = (self.ctx.height - 35)/rowCount;\n prefferedRowHeight = Math.min(32, prefferedRowHeight);\n prefferedRowHeight = Math.max(12, prefferedRowHeight);\n scope.prefferedRowHeight = prefferedRowHeight;\n var ratio = prefferedRowHeight/32;\n \n var css = '.mat-slide-toggle .mat-slide-toggle-bar {\\n' +\n ' height: ' + 14*ratio+'px;\\n'+\n ' width: ' + 36*ratio+'px;\\n'+\n '}\\n';\n css += '.mat-slide-toggle .mat-slide-toggle-thumb-container {\\n' +\n ' height: ' + 20*ratio+'px;\\n'+\n ' width: ' + 20*ratio+'px;\\n'+\n '}\\n';\n css += '.mat-slide-toggle .mat-slide-toggle-thumb {\\n' +\n ' height: ' + 20*ratio+'px;\\n'+\n ' width: ' + 20*ratio+'px;\\n'+\n '}\\n';\n css += '.mat-slide-toggle .mat-slide-toggle-ripple {\\n' +\n ' height: ' + 40*ratio+'px;\\n'+\n ' width: ' + 40*ratio+'px;\\n'+\n ' top: calc(50% - '+20*ratio+'px);\\n'+\n ' left: calc(50% - '+20*ratio+'px);\\n'+\n '}\\n';\n css += '.gpio-left-label, .gpio-right-label {\\n' +\n ' font-size: ' + 16*ratio+'px;\\n'+\n '}\\n';\n var pinsFontSize = Math.max(9, 12*ratio);\n css += '.pin {\\n' +\n ' font-size: ' + pinsFontSize+'px;\\n'+\n '}\\n';\n\n cssParser.createStyleElement(namespace, css);\n \n self.ctx.detectChanges();\n}\n\nself.onDestroy = function() {\n}\n",
51   - "settingsSchema": "{\n \"schema\": {\n \"type\": \"object\",\n \"title\": \"Settings\",\n \"properties\": {\n \"gpioList\": {\n \"title\": \"Gpio switches\",\n \"type\": \"array\",\n \"minItems\" : 1,\n \"items\": {\n \"title\": \"Gpio switch\",\n \"type\": \"object\",\n \"properties\": {\n \"pin\": {\n \"title\": \"Pin\",\n \"type\": \"number\"\n },\n \"label\": {\n \"title\": \"Label\",\n \"type\": \"string\"\n },\n \"row\": {\n \"title\": \"Row\",\n \"type\": \"number\"\n },\n \"col\": {\n \"title\": \"Column\",\n \"type\": \"number\"\n }\n },\n \"required\": [\"pin\", \"label\", \"row\", \"col\"]\n }\n },\n \"requestTimeout\": {\n \"title\": \"RPC request timeout\",\n \"type\": \"number\",\n \"default\": 500\n },\n \"switchPanelBackgroundColor\": {\n \"title\": \"Switches panel background color\",\n \"type\": \"string\",\n \"default\": \"#008a00\"\n },\n \"gpioStatusRequest\": {\n \"title\": \"GPIO status request\",\n \"type\": \"object\",\n \"properties\": {\n \"method\": {\n \"title\": \"Method name\",\n \"type\": \"string\",\n \"default\": \"getGpioStatus\"\n },\n \"paramsBody\": {\n \"title\": \"Method body\",\n \"type\": \"string\",\n \"default\": \"{}\"\n }\n },\n \"required\": [\"method\", \"paramsBody\"]\n },\n \"gpioStatusChangeRequest\": {\n \"title\": \"GPIO status change request\",\n \"type\": \"object\",\n \"properties\": {\n \"method\": {\n \"title\": \"Method name\",\n \"type\": \"string\",\n \"default\": \"setGpioStatus\"\n },\n \"paramsBody\": {\n \"title\": \"Method body\",\n \"type\": \"string\",\n \"default\": \"{\\n \\\"pin\\\": \\\"{$pin}\\\",\\n \\\"enabled\\\": \\\"{$enabled}\\\"\\n}\"\n }\n },\n \"required\": [\"method\", \"paramsBody\"]\n },\n \"parseGpioStatusFunction\": {\n \"title\": \"Parse gpio status function\",\n \"type\": \"string\",\n \"default\": \"return body[pin] === true;\"\n } \n },\n \"required\": [\"gpioList\", \n \"requestTimeout\",\n \"switchPanelBackgroundColor\",\n \"gpioStatusRequest\",\n \"gpioStatusChangeRequest\",\n \"parseGpioStatusFunction\"]\n },\n \"form\": [\n \"gpioList\",\n \"requestTimeout\",\n {\n \"key\": \"switchPanelBackgroundColor\",\n \"type\": \"color\"\n },\n {\n \"key\": \"gpioStatusRequest\",\n \"items\": [\n \"gpioStatusRequest.method\",\n {\n \"key\": \"gpioStatusRequest.paramsBody\",\n \"type\": \"json\"\n }\n ]\n },\n {\n \"key\": \"gpioStatusChangeRequest\",\n \"items\": [\n \"gpioStatusChangeRequest.method\",\n {\n \"key\": \"gpioStatusChangeRequest.paramsBody\",\n \"type\": \"json\"\n }\n ]\n },\n {\n \"key\": \"parseGpioStatusFunction\",\n \"type\": \"javascript\"\n }\n ]\n}",
52   - "dataKeySettingsSchema": "{}\n",
53   - "defaultConfig": "{\"targetDeviceAliases\":[],\"showTitle\":true,\"backgroundColor\":\"#fff\",\"color\":\"rgba(0, 0, 0, 0.87)\",\"padding\":\"0px\",\"settings\":{\"parseGpioStatusFunction\":\"return body[pin] === true;\",\"gpioStatusChangeRequest\":{\"method\":\"setGpioStatus\",\"paramsBody\":\"{\\n \\\"pin\\\": \\\"{$pin}\\\",\\n \\\"enabled\\\": \\\"{$enabled}\\\"\\n}\"},\"requestTimeout\":500,\"switchPanelBackgroundColor\":\"#008a00\",\"gpioStatusRequest\":{\"method\":\"getGpioStatus\",\"paramsBody\":\"{}\"},\"gpioList\":[{\"pin\":7,\"label\":\"GPIO 4 (GPCLK0)\",\"row\":3,\"col\":0,\"_uniqueKey\":0},{\"pin\":11,\"label\":\"GPIO 17\",\"row\":5,\"col\":0,\"_uniqueKey\":1},{\"pin\":12,\"label\":\"GPIO 18\",\"row\":5,\"col\":1,\"_uniqueKey\":2},{\"_uniqueKey\":3,\"pin\":13,\"label\":\"GPIO 27\",\"row\":6,\"col\":0},{\"_uniqueKey\":4,\"pin\":15,\"label\":\"GPIO 22\",\"row\":7,\"col\":0},{\"_uniqueKey\":5,\"pin\":16,\"label\":\"GPIO 23\",\"row\":7,\"col\":1},{\"_uniqueKey\":6,\"pin\":18,\"label\":\"GPIO 24\",\"row\":8,\"col\":1},{\"_uniqueKey\":7,\"pin\":22,\"label\":\"GPIO 25\",\"row\":10,\"col\":1},{\"_uniqueKey\":8,\"pin\":29,\"label\":\"GPIO 5\",\"row\":14,\"col\":0},{\"_uniqueKey\":9,\"pin\":31,\"label\":\"GPIO 6\",\"row\":15,\"col\":0},{\"_uniqueKey\":10,\"pin\":32,\"label\":\"GPIO 12\",\"row\":15,\"col\":1},{\"_uniqueKey\":11,\"pin\":33,\"label\":\"GPIO 13\",\"row\":16,\"col\":0},{\"_uniqueKey\":12,\"pin\":35,\"label\":\"GPIO 19\",\"row\":17,\"col\":0},{\"_uniqueKey\":13,\"pin\":36,\"label\":\"GPIO 16\",\"row\":17,\"col\":1},{\"_uniqueKey\":14,\"pin\":37,\"label\":\"GPIO 26\",\"row\":18,\"col\":0},{\"_uniqueKey\":15,\"pin\":38,\"label\":\"GPIO 20\",\"row\":18,\"col\":1},{\"_uniqueKey\":16,\"pin\":40,\"label\":\"GPIO 21\",\"row\":19,\"col\":1}]},\"title\":\"Raspberry Pi GPIO Control\"}"
54   - }
55   - },
56   - {
57 41 "alias": "raspberry_pi_gpio_panel",
58 42 "name": "Raspberry Pi GPIO Panel",
59 43 "descriptor": {
... ... @@ -62,12 +46,28 @@
62 46 "sizeY": 10.5,
63 47 "resources": [],
64 48 "templateHtml": "<div class=\"gpio-panel\" style=\"height: 100%;\">\n <section fxLayout=\"row\" *ngFor=\"let row of rows\">\n <section fxFlex fxLayout=\"row\" *ngFor=\"let cell of row; let $index = index\">\n <section fxLayout=\"row\" fxFlex *ngIf=\"cell\" fxLayoutAlign=\"{{$index===0 ? 'end center' : 'start center'}}\">\n <span class=\"gpio-left-label\" [fxShow]=\"$index===0\">{{ cell.label }}</span>\n <section fxLayout=\"row\" class=\"led-panel\" [ngClass]=\"$index===0 ? 'col-0' : 'col-1'\"\n [ngStyle]=\"{backgroundColor: ledPanelBackgroundColor}\">\n <span class=\"pin\" [fxShow]=\"$index===0\">{{cell.pin}}</span>\n <span class=\"led-container\">\n <tb-led-light [size]=\"prefferedRowHeight\"\n [colorOn]=\"cell.colorOn\"\n [colorOff]=\"cell.colorOff\"\n [offOpacity]=\"'0.9'\"\n [enabled]=\"cell.enabled\">\n </tb-led-light>\n </span>\n <span class=\"pin\" [fxShow]=\"$index===1\">{{cell.pin}}</span>\n </section>\n <span class=\"gpio-right-label\" [fxShow]=\"$index===1\">{{ cell.label }}</span>\n </section>\n <section fxLayout=\"row\" fxFlex *ngIf=\"!cell\">\n <span fxFlex [fxShow]=\"$index===0\"></span>\n <span class=\"led-panel\"\n [ngStyle]=\"{backgroundColor: ledPanelBackgroundColor}\"></span>\n <span fxFlex [fxShow]=\"$index===1\"></span>\n </section>\n </section>\n </section> \n</div>",
65   - "templateCss": ".error {\n font-size: 14px !important;\n color: maroon;/*rgb(250,250,250);*/\n background-color: transparent;\n padding: 6px;\n}\n\n.error span {\n margin: auto;\n}\n\n.gpio-panel {\n padding-top: 10px;\n white-space: nowrap;\n}\n\n.gpio-panel tb-led-light > div {\n margin: auto;\n}\n\n.led-panel {\n margin: 0;\n width: 66px;\n min-width: 66px;\n}\n\n.led-container {\n width: 48px;\n min-width: 48px;\n}\n\n.pin {\n margin-top: auto;\n margin-bottom: auto;\n color: white;\n font-size: 12px;\n width: 16px;\n min-width: 16px;\n}\n\n.led-panel.col-0 .pin {\n margin-left: auto;\n padding-left: 2px;\n text-align: right;\n}\n\n.led-panel.col-1 .pin {\n margin-right: auto;\n \n text-align: left;\n}\n\n.gpio-left-label {\n margin-right: 8px;\n}\n\n.gpio-right-label {\n margin-left: 8px;\n}",
  49 + "templateCss": ".error {\n font-size: 14px !important;\n color: maroon;/*rgb(250,250,250);*/\n background-color: transparent;\n padding: 6px;\n}\n\n.error span {\n margin: auto;\n}\n\n.gpio-panel {\n padding-top: 10px;\n white-space: nowrap;\n}\n\n.gpio-panel section[fxflex] {\n min-width: 0px;\n}\n\n.gpio-panel tb-led-light > div {\n margin: auto;\n}\n\n.led-panel {\n margin: 0;\n width: 66px;\n min-width: 66px;\n}\n\n.led-container {\n width: 48px;\n min-width: 48px;\n}\n\n.pin {\n margin-top: auto;\n margin-bottom: auto;\n color: white;\n font-size: 12px;\n width: 16px;\n min-width: 16px;\n}\n\n.led-panel.col-0 .pin {\n margin-left: auto;\n padding-left: 2px;\n text-align: right;\n}\n\n.led-panel.col-1 .pin {\n margin-right: auto;\n \n text-align: left;\n}\n\n.gpio-left-label {\n margin-right: 8px;\n}\n\n.gpio-right-label {\n margin-left: 8px;\n}",
66 50 "controllerScript": "var namespace;\nvar cssParser = new cssjs();\n\nself.onInit = function() {\n var utils = self.ctx.$injector.get(self.ctx.servicesMap.get('utils'));\n namespace = 'gpio-panel-' + utils.guid();\n cssParser.testMode = false;\n cssParser.cssPreviewNamespace = namespace;\n self.ctx.$container.addClass(namespace);\n self.ctx.ngZone.run(function() {\n init(); \n });\n}\n\nfunction init() {\n var i, gpio;\n \n var scope = self.ctx.$scope;\n var settings = self.ctx.settings;\n \n scope.gpioList = [];\n scope.gpioByPin = {};\n for (var g = 0; g < settings.gpioList.length; g++) {\n gpio = settings.gpioList[g];\n scope.gpioList.push(\n {\n row: gpio.row,\n col: gpio.col,\n pin: gpio.pin,\n label: gpio.label,\n enabled: false,\n colorOn: tinycolor(gpio.color).lighten(20).toHexString(),\n colorOff: tinycolor(gpio.color).darken().toHexString()\n }\n );\n scope.gpioByPin[gpio.pin] = scope.gpioList[scope.gpioList.length-1];\n }\n\n scope.ledPanelBackgroundColor = settings.ledPanelBackgroundColor || tinycolor('green').lighten(2).toRgbString();\n\n scope.gpioCells = {};\n var rowCount = 0;\n for (i = 0; i < scope.gpioList.length; i++) {\n gpio = scope.gpioList[i];\n scope.gpioCells[gpio.row+'_'+gpio.col] = gpio;\n rowCount = Math.max(rowCount, gpio.row+1);\n }\n \n scope.prefferedRowHeight = 32;\n scope.rows = [];\n for (i = 0; i < rowCount; i++) {\n var row = [];\n for (var c =0; c<2;c++) {\n if (scope.gpioCells[i+'_'+c]) {\n row[c] = scope.gpioCells[i+'_'+c];\n } else {\n row[c] = null;\n }\n }\n scope.rows.push(row);\n } \n \n self.onResize();\n}\n\nself.onDataUpdated = function() {\n var changed = false;\n for (var d = 0; d < self.ctx.data.length; d++) {\n var cellData = self.ctx.data[d];\n var dataKey = cellData.dataKey;\n var gpio = self.ctx.$scope.gpioByPin[dataKey.label];\n if (gpio) {\n var enabled = false;\n if (cellData.data.length > 0) {\n var tvPair = cellData.data[cellData.data.length - 1];\n enabled = (tvPair[1] === true || tvPair[1] === 'true');\n }\n if (gpio.enabled != enabled) {\n changed = true;\n gpio.enabled = enabled;\n }\n }\n }\n if (changed) {\n self.ctx.detectChanges();\n } \n}\n\nself.onResize = function() {\n var rowCount = self.ctx.$scope.rows.length;\n var prefferedRowHeight = (self.ctx.height - 35)/rowCount;\n prefferedRowHeight = Math.min(32, prefferedRowHeight);\n prefferedRowHeight = Math.max(12, prefferedRowHeight);\n self.ctx.$scope.prefferedRowHeight = prefferedRowHeight;\n \n var ratio = prefferedRowHeight/32;\n \n var css = '.gpio-left-label, .gpio-right-label {\\n' +\n ' font-size: ' + 16*ratio+'px;\\n'+\n '}\\n';\n var pinsFontSize = Math.max(9, 12*ratio);\n css += '.pin {\\n' +\n ' font-size: ' + pinsFontSize+'px;\\n'+\n '}\\n';\n \n cssParser.createStyleElement(namespace, css); \n \n self.ctx.detectChanges();\n}\n\nself.onDestroy = function() {\n}\n",
67 51 "settingsSchema": "{\n \"schema\": {\n \"type\": \"object\",\n \"title\": \"Settings\",\n \"properties\": {\n \"gpioList\": {\n \"title\": \"Gpio leds\",\n \"type\": \"array\",\n \"minItems\" : 1,\n \"items\": {\n \"title\": \"Gpio led\",\n \"type\": \"object\",\n \"properties\": {\n \"pin\": {\n \"title\": \"Pin\",\n \"type\": \"number\"\n },\n \"label\": {\n \"title\": \"Label\",\n \"type\": \"string\"\n },\n \"row\": {\n \"title\": \"Row\",\n \"type\": \"number\"\n },\n \"col\": {\n \"title\": \"Column\",\n \"type\": \"number\"\n },\n \"color\": {\n \"title\": \"Color\",\n \"type\": \"string\",\n \"default\": \"red\"\n }\n },\n \"required\": [\"pin\", \"label\", \"row\", \"col\", \"color\"]\n }\n },\n \"ledPanelBackgroundColor\": {\n \"title\": \"LED panel background color\",\n \"type\": \"string\",\n \"default\": \"#008a00\"\n } \n },\n \"required\": [\"gpioList\", \n \"ledPanelBackgroundColor\"]\n },\n \"form\": [\n {\n \"key\": \"gpioList\",\n \"items\": [\n \"gpioList[].pin\",\n \"gpioList[].label\",\n \"gpioList[].row\",\n \"gpioList[].col\",\n {\n \"key\": \"gpioList[].color\",\n \"type\": \"color\"\n }\n ]\n },\n {\n \"key\": \"ledPanelBackgroundColor\",\n \"type\": \"color\"\n }\n ]\n}",
68 52 "dataKeySettingsSchema": "{}\n",
69 53 "defaultConfig": "{\"showTitle\":true,\"backgroundColor\":\"#fff\",\"color\":\"rgba(0, 0, 0, 0.87)\",\"padding\":\"0px\",\"settings\":{\"gpioList\":[{\"pin\":1,\"label\":\"3.3V\",\"row\":0,\"col\":0,\"color\":\"#fc9700\",\"_uniqueKey\":0},{\"pin\":2,\"label\":\"5V\",\"row\":0,\"col\":1,\"color\":\"#fb0000\",\"_uniqueKey\":1},{\"pin\":3,\"label\":\"GPIO 2 (I2C1_SDA)\",\"row\":1,\"col\":0,\"color\":\"#02fefb\",\"_uniqueKey\":2},{\"color\":\"#fb0000\",\"pin\":4,\"label\":\"5V\",\"row\":1,\"col\":1},{\"color\":\"#02fefb\",\"pin\":5,\"label\":\"GPIO 3 (I2C1_SCL)\",\"row\":2,\"col\":0},{\"color\":\"#000000\",\"pin\":6,\"label\":\"GND\",\"row\":2,\"col\":1},{\"color\":\"#00fd00\",\"pin\":7,\"label\":\"GPIO 4 (GPCLK0)\",\"row\":3,\"col\":0},{\"color\":\"#fdfb00\",\"pin\":8,\"label\":\"GPIO 14 (UART_TXD)\",\"row\":3,\"col\":1},{\"color\":\"#000000\",\"pin\":9,\"label\":\"GND\",\"row\":4,\"col\":0},{\"color\":\"#fdfb00\",\"pin\":10,\"label\":\"GPIO 15 (UART_RXD)\",\"row\":4,\"col\":1},{\"color\":\"#00fd00\",\"pin\":11,\"label\":\"GPIO 17\",\"row\":5,\"col\":0},{\"color\":\"#00fd00\",\"pin\":12,\"label\":\"GPIO 18\",\"row\":5,\"col\":1},{\"color\":\"#00fd00\",\"pin\":13,\"label\":\"GPIO 27\",\"row\":6,\"col\":0},{\"color\":\"#000000\",\"pin\":14,\"label\":\"GND\",\"row\":6,\"col\":1},{\"color\":\"#00fd00\",\"pin\":15,\"label\":\"GPIO 22\",\"row\":7,\"col\":0},{\"color\":\"#00fd00\",\"pin\":16,\"label\":\"GPIO 23\",\"row\":7,\"col\":1},{\"color\":\"#fc9700\",\"pin\":17,\"label\":\"3.3V\",\"row\":8,\"col\":0},{\"color\":\"#00fd00\",\"pin\":18,\"label\":\"GPIO 24\",\"row\":8,\"col\":1},{\"color\":\"#fd01fd\",\"pin\":19,\"label\":\"GPIO 10 (SPI_MOSI)\",\"row\":9,\"col\":0},{\"color\":\"#000000\",\"pin\":20,\"label\":\"GND\",\"row\":9,\"col\":1},{\"color\":\"#fd01fd\",\"pin\":21,\"label\":\"GPIO 9 (SPI_MISO)\",\"row\":10,\"col\":0},{\"color\":\"#00fd00\",\"pin\":22,\"label\":\"GPIO 25\",\"row\":10,\"col\":1},{\"color\":\"#fd01fd\",\"pin\":23,\"label\":\"GPIO 11 (SPI_SCLK)\",\"row\":11,\"col\":0},{\"color\":\"#fd01fd\",\"pin\":24,\"label\":\"GPIO 8 (SPI_CE0)\",\"row\":11,\"col\":1},{\"color\":\"#000000\",\"pin\":25,\"label\":\"GND\",\"row\":12,\"col\":0},{\"color\":\"#fd01fd\",\"pin\":26,\"label\":\"GPIO 7 (SPI_CE1)\",\"row\":12,\"col\":1},{\"color\":\"#ffffff\",\"pin\":27,\"label\":\"ID_SD\",\"row\":13,\"col\":0},{\"color\":\"#ffffff\",\"pin\":28,\"label\":\"ID_SC\",\"row\":13,\"col\":1},{\"color\":\"#00fd00\",\"pin\":29,\"label\":\"GPIO 5\",\"row\":14,\"col\":0},{\"color\":\"#000000\",\"pin\":30,\"label\":\"GND\",\"row\":14,\"col\":1},{\"color\":\"#00fd00\",\"pin\":31,\"label\":\"GPIO 6\",\"row\":15,\"col\":0},{\"color\":\"#00fd00\",\"pin\":32,\"label\":\"GPIO 12\",\"row\":15,\"col\":1},{\"color\":\"#00fd00\",\"pin\":33,\"label\":\"GPIO 13\",\"row\":16,\"col\":0},{\"color\":\"#000000\",\"pin\":34,\"label\":\"GND\",\"row\":16,\"col\":1},{\"color\":\"#00fd00\",\"pin\":35,\"label\":\"GPIO 19\",\"row\":17,\"col\":0},{\"color\":\"#00fd00\",\"pin\":36,\"label\":\"GPIO 16\",\"row\":17,\"col\":1},{\"color\":\"#00fd00\",\"pin\":37,\"label\":\"GPIO 26\",\"row\":18,\"col\":0},{\"color\":\"#00fd00\",\"pin\":38,\"label\":\"GPIO 20\",\"row\":18,\"col\":1},{\"color\":\"#000000\",\"pin\":39,\"label\":\"GND\",\"row\":19,\"col\":0},{\"color\":\"#00fd00\",\"pin\":40,\"label\":\"GPIO 21\",\"row\":19,\"col\":1}],\"ledPanelBackgroundColor\":\"#008a00\"},\"title\":\"Raspberry Pi GPIO Panel\",\"datasources\":[{\"type\":\"function\",\"name\":\"function\",\"dataKeys\":[{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"7\",\"color\":\"#2196f3\",\"settings\":{},\"_hash\":0.22518255793320163,\"funcBody\":\"var period = time % 1500;\\nreturn period < 500;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"11\",\"color\":\"#4caf50\",\"settings\":{},\"_hash\":0.7008206860666621,\"funcBody\":\"var period = time % 1500;\\nreturn period >= 500 && period < 1000;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"12\",\"color\":\"#f44336\",\"settings\":{},\"_hash\":0.42600325102193426,\"funcBody\":\"var period = time % 1500;\\nreturn period >= 1000;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"13\",\"color\":\"#ffc107\",\"settings\":{},\"_hash\":0.48362241571415243,\"funcBody\":\"var period = time % 1500;\\nreturn period < 500;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"29\",\"color\":\"#607d8b\",\"settings\":{},\"_hash\":0.7217670147518815,\"funcBody\":\"var period = time % 1500;\\nreturn period >= 500 && period < 1000;\"}]}],\"timewindow\":{\"realtime\":{\"timewindowMs\":60000}}}"
70 54 }
  55 + },
  56 + {
  57 + "alias": "raspberry_pi_gpio_control",
  58 + "name": "Raspberry Pi GPIO Control",
  59 + "descriptor": {
  60 + "type": "rpc",
  61 + "sizeX": 6,
  62 + "sizeY": 10.5,
  63 + "resources": [],
  64 + "templateHtml": "<fieldset class=\"gpio-panel\" style=\"height: 100%;\">\n <section class=\"gpio-row\" fxLayout=\"row\" *ngFor=\"let row of rows\" \n [ngStyle]=\"{'height': prefferedRowHeight+'px'}\">\n <section fxFlex fxLayout=\"row\" *ngFor=\"let cell of row; let $index = index\">\n <section fxLayout=\"row\" fxFlex *ngIf=\"cell\" fxLayoutAlign=\"{{$index===0 ? 'end center' : 'start center'}}\">\n <span class=\"gpio-left-label\" [fxShow]=\"$index===0\">{{ cell.label }}</span>\n <section fxLayout=\"row\" class=\"switch-panel\" fxLayoutAlign=\"start center\" [ngClass]=\"$index===0 ? 'col-0' : 'col-1'\"\n [ngStyle]=\"{'height': prefferedRowHeight+'px', 'backgroundColor': switchPanelBackgroundColor }\">\n <span class=\"pin\" [fxShow]=\"$index===0\">{{cell.pin}}</span>\n <span fxFlex [fxShow]=\"$index===1\"></span>\n <mat-slide-toggle\n [disabled]=\"!rpcEnabled || executingRpcRequest\"\n [checked]=\"cell.enabled\" \n (change)=\"gpioToggleChange($event, cell)\" \n (click)=\"gpioClick($event, cell)\">\n </mat-slide-toggle>\n <span fxFlex [fxShow]=\"$index===0\"></span>\n <span class=\"pin\" [fxShow]=\"$index===1\">{{cell.pin}}</span>\n </section>\n <span class=\"gpio-right-label\" [fxShow]=\"$index===1\">{{ cell.label }}</span>\n </section>\n <section fxLayout=\"row\" fxFlex *ngIf=\"!cell\">\n <span fxFlex [fxShow]=\"$index===0\"></span>\n <span class=\"switch-panel\"\n [ngStyle]=\"{'height': prefferedRowHeight+'px', 'backgroundColor': switchPanelBackgroundColor }\"></span>\n <span fxFlex [fxShow]=\"$index===1\"></span>\n </section>\n </section>\n </section> \n <span class=\"error\" style=\"position: absolute; bottom: 5px;\" [fxShow]=\"rpcErrorText\">{{rpcErrorText}}</span>\n <mat-progress-bar [fxShow]=\"executingRpcRequest\" style=\"position: absolute; bottom: 0;\" mode=\"indeterminate\"></mat-progress-bar>\n</fieldset>",
  65 + "templateCss": ".error {\n font-size: 14px !important;\n color: maroon;/*rgb(250,250,250);*/\n background-color: transparent;\n padding: 6px;\n}\n\n.error span {\n margin: auto;\n}\n\n.gpio-panel {\n padding-top: 10px;\n white-space: nowrap;\n}\n\n.gpio-panel section[fxflex] {\n min-width: 0px;\n}\n\n.switch-panel {\n margin: 0;\n height: 32px;\n width: 66px;\n min-width: 66px;\n}\n\n.switch-panel mat-slide-toggle {\n margin: 0;\n width: 36px;\n min-width: 36px;\n}\n\n.switch-panel.col-0 mat-slide-toggle {\n margin-left: 8px;\n margin-right: 4px;\n}\n\n.switch-panel.col-1 mat-slide-toggle {\n margin-left: 4px;\n margin-right: 8px;\n}\n\n.gpio-row {\n height: 32px;\n}\n\n.pin {\n margin-top: auto;\n margin-bottom: auto;\n color: white;\n font-size: 12px;\n width: 16px;\n min-width: 16px;\n}\n\n.switch-panel.col-0 .pin {\n margin-left: auto;\n padding-left: 2px;\n text-align: right;\n}\n\n.switch-panel.col-1 .pin {\n margin-right: auto;\n \n text-align: left;\n}\n\n.gpio-left-label {\n margin-right: 8px;\n}\n\n.gpio-right-label {\n margin-left: 8px;\n}",
  66 + "controllerScript": "var namespace;\nvar cssParser = new cssjs();\n\nself.onInit = function() {\n var utils = self.ctx.$injector.get(self.ctx.servicesMap.get('utils'));\n namespace = 'gpio-control-' + utils.guid();\n cssParser.testMode = false;\n cssParser.cssPreviewNamespace = namespace;\n self.ctx.$container.addClass(namespace);\n self.ctx.ngZone.run(function() {\n init(); \n });\n}\n\nfunction init() {\n \n var i, gpio;\n var scope = self.ctx.$scope;\n var settings = self.ctx.settings;\n scope.gpioList = [];\n for (var g = 0; g < settings.gpioList.length; g++) {\n gpio = settings.gpioList[g];\n scope.gpioList.push(\n {\n row: gpio.row,\n col: gpio.col,\n pin: gpio.pin,\n label: gpio.label,\n enabled: false\n }\n );\n }\n\n scope.requestTimeout = settings.requestTimeout || 1000;\n\n scope.switchPanelBackgroundColor = settings.switchPanelBackgroundColor || tinycolor('green').lighten(2).toRgbString();\n\n scope.gpioStatusRequest = {\n method: \"getGpioStatus\",\n paramsBody: \"{}\"\n };\n \n if (settings.gpioStatusRequest) {\n scope.gpioStatusRequest.method = settings.gpioStatusRequest.method || scope.gpioStatusRequest.method;\n scope.gpioStatusRequest.paramsBody = settings.gpioStatusRequest.paramsBody || scope.gpioStatusRequest.paramsBody;\n }\n \n scope.gpioStatusChangeRequest = {\n method: \"setGpioStatus\",\n paramsBody: \"{\\n \\\"pin\\\": \\\"{$pin}\\\",\\n \\\"enabled\\\": \\\"{$enabled}\\\"\\n}\"\n };\n \n if (settings.gpioStatusChangeRequest) {\n scope.gpioStatusChangeRequest.method = settings.gpioStatusChangeRequest.method || scope.gpioStatusChangeRequest.method;\n scope.gpioStatusChangeRequest.paramsBody = settings.gpioStatusChangeRequest.paramsBody || scope.gpioStatusChangeRequest.paramsBody;\n }\n \n scope.parseGpioStatusFunction = \"return body[pin] === true;\";\n \n if (settings.parseGpioStatusFunction && settings.parseGpioStatusFunction.length > 0) {\n scope.parseGpioStatusFunction = settings.parseGpioStatusFunction;\n }\n \n scope.parseGpioStatusFunction = new Function(\"body, pin\", scope.parseGpioStatusFunction);\n \n function requestGpioStatus() {\n self.ctx.controlApi.sendTwoWayCommand(scope.gpioStatusRequest.method, \n scope.gpioStatusRequest.paramsBody, \n scope.requestTimeout)\n .subscribe(\n function success(responseBody) {\n for (var g = 0; g < scope.gpioList.length; g++) {\n var gpio = scope.gpioList[g];\n var enabled = scope.parseGpioStatusFunction.apply(this, [responseBody, gpio.pin]);\n gpio.enabled = enabled; \n self.ctx.detectChanges();\n }\n }\n );\n }\n \n function changeGpioStatus(gpio) {\n var pin = gpio.pin + '';\n var enabled = !gpio.enabled;\n enabled = enabled === true ? 'true' : 'false';\n var paramsBody = scope.gpioStatusChangeRequest.paramsBody;\n var requestBody = JSON.parse(paramsBody.replace(\"\\\"{$pin}\\\"\", pin).replace(\"\\\"{$enabled}\\\"\", enabled));\n self.ctx.controlApi.sendTwoWayCommand(scope.gpioStatusChangeRequest.method, \n requestBody, scope.requestTimeout)\n .subscribe(\n function success(responseBody) {\n var enabled = scope.parseGpioStatusFunction.apply(this, [responseBody, gpio.pin]);\n gpio.enabled = enabled;\n self.ctx.detectChanges();\n }\n );\n }\n \n scope.gpioCells = {};\n var rowCount = 0;\n for (i = 0; i < scope.gpioList.length; i++) {\n gpio = scope.gpioList[i];\n scope.gpioCells[gpio.row+'_'+gpio.col] = gpio;\n rowCount = Math.max(rowCount, gpio.row+1);\n }\n \n scope.prefferedRowHeight = 32;\n scope.rows = [];\n for (i = 0; i < rowCount; i++) {\n var row = [];\n for (var c =0; c<2;c++) {\n if (scope.gpioCells[i+'_'+c]) {\n row[c] = scope.gpioCells[i+'_'+c];\n } else {\n row[c] = null;\n }\n }\n scope.rows.push(row);\n }\n\n scope.gpioClick = function($event, gpio) {\n if (scope.rpcEnabled && !scope.executingRpcRequest) {\n changeGpioStatus(gpio);\n }\n };\n \n scope.gpioToggleChange = function($event, gpio) {\n gpio.enabled = !$event.checked;\n $event.source.toggle();\n self.ctx.detectChanges();\n }\n \n if (scope.rpcEnabled) {\n requestGpioStatus(); \n }\n \n self.onResize();\n}\n\nself.onResize = function() {\n var scope = self.ctx.$scope;\n var rowCount = scope.rows.length;\n var prefferedRowHeight = (self.ctx.height - 35)/rowCount;\n prefferedRowHeight = Math.min(32, prefferedRowHeight);\n prefferedRowHeight = Math.max(12, prefferedRowHeight);\n scope.prefferedRowHeight = prefferedRowHeight;\n var ratio = prefferedRowHeight/32;\n \n var css = '.mat-slide-toggle .mat-slide-toggle-bar {\\n' +\n ' height: ' + 14*ratio+'px;\\n'+\n ' width: ' + 36*ratio+'px;\\n'+\n '}\\n';\n css += '.mat-slide-toggle .mat-slide-toggle-thumb-container {\\n' +\n ' height: ' + 20*ratio+'px;\\n'+\n ' width: ' + 20*ratio+'px;\\n'+\n '}\\n';\n css += '.mat-slide-toggle .mat-slide-toggle-thumb {\\n' +\n ' height: ' + 20*ratio+'px;\\n'+\n ' width: ' + 20*ratio+'px;\\n'+\n '}\\n';\n css += '.mat-slide-toggle .mat-slide-toggle-ripple {\\n' +\n ' height: ' + 40*ratio+'px;\\n'+\n ' width: ' + 40*ratio+'px;\\n'+\n ' top: calc(50% - '+20*ratio+'px);\\n'+\n ' left: calc(50% - '+20*ratio+'px);\\n'+\n '}\\n';\n css += '.gpio-left-label, .gpio-right-label {\\n' +\n ' font-size: ' + 16*ratio+'px;\\n'+\n '}\\n';\n var pinsFontSize = Math.max(9, 12*ratio);\n css += '.pin {\\n' +\n ' font-size: ' + pinsFontSize+'px;\\n'+\n '}\\n';\n\n cssParser.createStyleElement(namespace, css);\n \n self.ctx.detectChanges();\n}\n\nself.onDestroy = function() {\n}\n",
  67 + "settingsSchema": "{\n \"schema\": {\n \"type\": \"object\",\n \"title\": \"Settings\",\n \"properties\": {\n \"gpioList\": {\n \"title\": \"Gpio switches\",\n \"type\": \"array\",\n \"minItems\" : 1,\n \"items\": {\n \"title\": \"Gpio switch\",\n \"type\": \"object\",\n \"properties\": {\n \"pin\": {\n \"title\": \"Pin\",\n \"type\": \"number\"\n },\n \"label\": {\n \"title\": \"Label\",\n \"type\": \"string\"\n },\n \"row\": {\n \"title\": \"Row\",\n \"type\": \"number\"\n },\n \"col\": {\n \"title\": \"Column\",\n \"type\": \"number\"\n }\n },\n \"required\": [\"pin\", \"label\", \"row\", \"col\"]\n }\n },\n \"requestTimeout\": {\n \"title\": \"RPC request timeout\",\n \"type\": \"number\",\n \"default\": 500\n },\n \"switchPanelBackgroundColor\": {\n \"title\": \"Switches panel background color\",\n \"type\": \"string\",\n \"default\": \"#008a00\"\n },\n \"gpioStatusRequest\": {\n \"title\": \"GPIO status request\",\n \"type\": \"object\",\n \"properties\": {\n \"method\": {\n \"title\": \"Method name\",\n \"type\": \"string\",\n \"default\": \"getGpioStatus\"\n },\n \"paramsBody\": {\n \"title\": \"Method body\",\n \"type\": \"string\",\n \"default\": \"{}\"\n }\n },\n \"required\": [\"method\", \"paramsBody\"]\n },\n \"gpioStatusChangeRequest\": {\n \"title\": \"GPIO status change request\",\n \"type\": \"object\",\n \"properties\": {\n \"method\": {\n \"title\": \"Method name\",\n \"type\": \"string\",\n \"default\": \"setGpioStatus\"\n },\n \"paramsBody\": {\n \"title\": \"Method body\",\n \"type\": \"string\",\n \"default\": \"{\\n \\\"pin\\\": \\\"{$pin}\\\",\\n \\\"enabled\\\": \\\"{$enabled}\\\"\\n}\"\n }\n },\n \"required\": [\"method\", \"paramsBody\"]\n },\n \"parseGpioStatusFunction\": {\n \"title\": \"Parse gpio status function\",\n \"type\": \"string\",\n \"default\": \"return body[pin] === true;\"\n } \n },\n \"required\": [\"gpioList\", \n \"requestTimeout\",\n \"switchPanelBackgroundColor\",\n \"gpioStatusRequest\",\n \"gpioStatusChangeRequest\",\n \"parseGpioStatusFunction\"]\n },\n \"form\": [\n \"gpioList\",\n \"requestTimeout\",\n {\n \"key\": \"switchPanelBackgroundColor\",\n \"type\": \"color\"\n },\n {\n \"key\": \"gpioStatusRequest\",\n \"items\": [\n \"gpioStatusRequest.method\",\n {\n \"key\": \"gpioStatusRequest.paramsBody\",\n \"type\": \"json\"\n }\n ]\n },\n {\n \"key\": \"gpioStatusChangeRequest\",\n \"items\": [\n \"gpioStatusChangeRequest.method\",\n {\n \"key\": \"gpioStatusChangeRequest.paramsBody\",\n \"type\": \"json\"\n }\n ]\n },\n {\n \"key\": \"parseGpioStatusFunction\",\n \"type\": \"javascript\"\n }\n ]\n}",
  68 + "dataKeySettingsSchema": "{}\n",
  69 + "defaultConfig": "{\"targetDeviceAliases\":[],\"showTitle\":true,\"backgroundColor\":\"#fff\",\"color\":\"rgba(0, 0, 0, 0.87)\",\"padding\":\"0px\",\"settings\":{\"parseGpioStatusFunction\":\"return body[pin] === true;\",\"gpioStatusChangeRequest\":{\"method\":\"setGpioStatus\",\"paramsBody\":\"{\\n \\\"pin\\\": \\\"{$pin}\\\",\\n \\\"enabled\\\": \\\"{$enabled}\\\"\\n}\"},\"requestTimeout\":500,\"switchPanelBackgroundColor\":\"#008a00\",\"gpioStatusRequest\":{\"method\":\"getGpioStatus\",\"paramsBody\":\"{}\"},\"gpioList\":[{\"pin\":7,\"label\":\"GPIO 4 (GPCLK0)\",\"row\":3,\"col\":0,\"_uniqueKey\":0},{\"pin\":11,\"label\":\"GPIO 17\",\"row\":5,\"col\":0,\"_uniqueKey\":1},{\"pin\":12,\"label\":\"GPIO 18\",\"row\":5,\"col\":1,\"_uniqueKey\":2},{\"_uniqueKey\":3,\"pin\":13,\"label\":\"GPIO 27\",\"row\":6,\"col\":0},{\"_uniqueKey\":4,\"pin\":15,\"label\":\"GPIO 22\",\"row\":7,\"col\":0},{\"_uniqueKey\":5,\"pin\":16,\"label\":\"GPIO 23\",\"row\":7,\"col\":1},{\"_uniqueKey\":6,\"pin\":18,\"label\":\"GPIO 24\",\"row\":8,\"col\":1},{\"_uniqueKey\":7,\"pin\":22,\"label\":\"GPIO 25\",\"row\":10,\"col\":1},{\"_uniqueKey\":8,\"pin\":29,\"label\":\"GPIO 5\",\"row\":14,\"col\":0},{\"_uniqueKey\":9,\"pin\":31,\"label\":\"GPIO 6\",\"row\":15,\"col\":0},{\"_uniqueKey\":10,\"pin\":32,\"label\":\"GPIO 12\",\"row\":15,\"col\":1},{\"_uniqueKey\":11,\"pin\":33,\"label\":\"GPIO 13\",\"row\":16,\"col\":0},{\"_uniqueKey\":12,\"pin\":35,\"label\":\"GPIO 19\",\"row\":17,\"col\":0},{\"_uniqueKey\":13,\"pin\":36,\"label\":\"GPIO 16\",\"row\":17,\"col\":1},{\"_uniqueKey\":14,\"pin\":37,\"label\":\"GPIO 26\",\"row\":18,\"col\":0},{\"_uniqueKey\":15,\"pin\":38,\"label\":\"GPIO 20\",\"row\":18,\"col\":1},{\"_uniqueKey\":16,\"pin\":40,\"label\":\"GPIO 21\",\"row\":19,\"col\":1}]},\"title\":\"Raspberry Pi GPIO Control\"}"
  70 + }
71 71 }
72 72 ]
73 73 }
\ No newline at end of file
... ...
... ... @@ -79,11 +79,18 @@ public class ThingsboardSecurityConfiguration extends WebSecurityConfigurerAdapt
79 79 @Qualifier("oauth2AuthenticationSuccessHandler")
80 80 private AuthenticationSuccessHandler oauth2AuthenticationSuccessHandler;
81 81
  82 + @Autowired(required = false)
  83 + @Qualifier("oauth2AuthenticationFailureHandler")
  84 + private AuthenticationFailureHandler oauth2AuthenticationFailureHandler;
  85 +
82 86 @Autowired
83 87 @Qualifier("defaultAuthenticationSuccessHandler")
84 88 private AuthenticationSuccessHandler successHandler;
85 89
86   - @Autowired private AuthenticationFailureHandler failureHandler;
  90 + @Autowired
  91 + @Qualifier("defaultAuthenticationFailureHandler")
  92 + private AuthenticationFailureHandler failureHandler;
  93 +
87 94 @Autowired private RestAuthenticationProvider restAuthenticationProvider;
88 95 @Autowired private JwtAuthenticationProvider jwtAuthenticationProvider;
89 96 @Autowired private RefreshTokenAuthenticationProvider refreshTokenAuthenticationProvider;
... ... @@ -204,11 +211,11 @@ public class ThingsboardSecurityConfiguration extends WebSecurityConfigurerAdapt
204 211 http.oauth2Login()
205 212 .loginPage("/oauth2Login")
206 213 .loginProcessingUrl(oauth2Configuration.getLoginProcessingUrl())
207   - .successHandler(oauth2AuthenticationSuccessHandler);
  214 + .successHandler(oauth2AuthenticationSuccessHandler)
  215 + .failureHandler(oauth2AuthenticationFailureHandler);
208 216 }
209 217 }
210 218
211   -
212 219 @Bean
213 220 @ConditionalOnMissingBean(CorsFilter.class)
214 221 public CorsFilter corsFilter(@Autowired MvcCorsProperties mvcCorsProperties) {
... ...
... ... @@ -52,6 +52,7 @@ import org.thingsboard.server.service.security.model.UserPrincipal;
52 52 import org.thingsboard.server.service.security.model.token.JwtToken;
53 53 import org.thingsboard.server.service.security.model.token.JwtTokenFactory;
54 54 import org.thingsboard.server.service.security.system.SystemSecurityService;
  55 +import org.thingsboard.server.utils.MiscUtils;
55 56 import ua_parser.Client;
56 57
57 58 import javax.servlet.http.HttpServletRequest;
... ... @@ -170,7 +171,7 @@ public class AuthController extends BaseController {
170 171 try {
171 172 String email = resetPasswordByEmailRequest.get("email").asText();
172 173 UserCredentials userCredentials = userService.requestPasswordReset(TenantId.SYS_TENANT_ID, email);
173   - String baseUrl = constructBaseUrl(request);
  174 + String baseUrl = MiscUtils.constructBaseUrl(request);
174 175 String resetUrl = String.format("%s/api/noauth/resetPassword?resetToken=%s", baseUrl,
175 176 userCredentials.getResetToken());
176 177
... ... @@ -218,7 +219,7 @@ public class AuthController extends BaseController {
218 219 User user = userService.findUserById(TenantId.SYS_TENANT_ID, credentials.getUserId());
219 220 UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.USER_NAME, user.getEmail());
220 221 SecurityUser securityUser = new SecurityUser(user, credentials.isEnabled(), principal);
221   - String baseUrl = constructBaseUrl(request);
  222 + String baseUrl = MiscUtils.constructBaseUrl(request);
222 223 String loginUrl = String.format("%s/login", baseUrl);
223 224 String email = user.getEmail();
224 225
... ... @@ -265,7 +266,7 @@ public class AuthController extends BaseController {
265 266 User user = userService.findUserById(TenantId.SYS_TENANT_ID, userCredentials.getUserId());
266 267 UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.USER_NAME, user.getEmail());
267 268 SecurityUser securityUser = new SecurityUser(user, userCredentials.isEnabled(), principal);
268   - String baseUrl = constructBaseUrl(request);
  269 + String baseUrl = MiscUtils.constructBaseUrl(request);
269 270 String loginUrl = String.format("%s/login", baseUrl);
270 271 String email = user.getEmail();
271 272 mailService.sendPasswordWasResetEmail(loginUrl, email);
... ...
... ... @@ -567,39 +567,6 @@ public abstract class BaseController {
567 567 return ruleNode;
568 568 }
569 569
570   -
571   - protected String constructBaseUrl(HttpServletRequest request) {
572   - String scheme = request.getScheme();
573   -
574   - String forwardedProto = request.getHeader("x-forwarded-proto");
575   - if (forwardedProto != null) {
576   - scheme = forwardedProto;
577   - }
578   -
579   - int serverPort = request.getServerPort();
580   - if (request.getHeader("x-forwarded-port") != null) {
581   - try {
582   - serverPort = request.getIntHeader("x-forwarded-port");
583   - } catch (NumberFormatException e) {
584   - }
585   - } else if (forwardedProto != null) {
586   - switch (forwardedProto) {
587   - case "http":
588   - serverPort = 80;
589   - break;
590   - case "https":
591   - serverPort = 443;
592   - break;
593   - }
594   - }
595   -
596   - String baseUrl = String.format("%s://%s:%d",
597   - scheme,
598   - request.getServerName(),
599   - serverPort);
600   - return baseUrl;
601   - }
602   -
603 570 protected <I extends EntityId> I emptyId(EntityType entityType) {
604 571 return (I) EntityIdFactory.getByTypeAndUuid(entityType, ModelConstants.NULL_UUID);
605 572 }
... ...
... ... @@ -52,6 +52,7 @@ import org.thingsboard.server.service.security.model.token.JwtToken;
52 52 import org.thingsboard.server.service.security.model.token.JwtTokenFactory;
53 53 import org.thingsboard.server.service.security.permission.Operation;
54 54 import org.thingsboard.server.service.security.permission.Resource;
  55 +import org.thingsboard.server.utils.MiscUtils;
55 56
56 57 import javax.servlet.http.HttpServletRequest;
57 58
... ... @@ -148,7 +149,7 @@ public class UserController extends BaseController {
148 149 if (sendEmail) {
149 150 SecurityUser authUser = getCurrentUser();
150 151 UserCredentials userCredentials = userService.findUserCredentialsByUserId(authUser.getTenantId(), savedUser.getId());
151   - String baseUrl = constructBaseUrl(request);
  152 + String baseUrl = MiscUtils.constructBaseUrl(request);
152 153 String activateUrl = String.format(ACTIVATE_URL_PATTERN, baseUrl,
153 154 userCredentials.getActivateToken());
154 155 String email = savedUser.getEmail();
... ... @@ -188,7 +189,7 @@ public class UserController extends BaseController {
188 189
189 190 UserCredentials userCredentials = userService.findUserCredentialsByUserId(getCurrentUser().getTenantId(), user.getId());
190 191 if (!userCredentials.isEnabled()) {
191   - String baseUrl = constructBaseUrl(request);
  192 + String baseUrl = MiscUtils.constructBaseUrl(request);
192 193 String activateUrl = String.format(ACTIVATE_URL_PATTERN, baseUrl,
193 194 userCredentials.getActivateToken());
194 195 mailService.sendActivationEmail(activateUrl, email);
... ... @@ -213,7 +214,7 @@ public class UserController extends BaseController {
213 214 SecurityUser authUser = getCurrentUser();
214 215 UserCredentials userCredentials = userService.findUserCredentialsByUserId(authUser.getTenantId(), user.getId());
215 216 if (!userCredentials.isEnabled()) {
216   - String baseUrl = constructBaseUrl(request);
  217 + String baseUrl = MiscUtils.constructBaseUrl(request);
217 218 String activateUrl = String.format(ACTIVATE_URL_PATTERN, baseUrl,
218 219 userCredentials.getActivateToken());
219 220 return activateUrl;
... ...
... ... @@ -97,7 +97,11 @@ public class CassandraToSqlColumn {
97 97
98 98 public String getColumnValue(Row row) {
99 99 if (row.isNull(index)) {
100   - return null;
  100 + if (this.type == CassandraToSqlColumnType.BOOLEAN) {
  101 + return Boolean.toString(false);
  102 + } else {
  103 + return null;
  104 + }
101 105 } else {
102 106 switch (this.type) {
103 107 case ID:
... ...
... ... @@ -19,6 +19,7 @@ import lombok.extern.slf4j.Slf4j;
19 19 import org.springframework.beans.factory.annotation.Autowired;
20 20 import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
21 21 import org.springframework.security.core.userdetails.UsernameNotFoundException;
  22 +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
22 23 import org.springframework.util.StringUtils;
23 24 import org.thingsboard.server.common.data.Customer;
24 25 import org.thingsboard.server.common.data.Tenant;
... ... @@ -27,13 +28,16 @@ import org.thingsboard.server.common.data.id.CustomerId;
27 28 import org.thingsboard.server.common.data.id.TenantId;
28 29 import org.thingsboard.server.common.data.page.PageLink;
29 30 import org.thingsboard.server.common.data.security.Authority;
  31 +import org.thingsboard.server.common.data.security.UserCredentials;
30 32 import org.thingsboard.server.dao.customer.CustomerService;
31 33 import org.thingsboard.server.dao.oauth2.OAuth2User;
32 34 import org.thingsboard.server.dao.tenant.TenantService;
33 35 import org.thingsboard.server.dao.user.UserService;
  36 +import org.thingsboard.server.service.install.InstallScripts;
34 37 import org.thingsboard.server.service.security.model.SecurityUser;
35 38 import org.thingsboard.server.service.security.model.UserPrincipal;
36 39
  40 +import java.io.IOException;
37 41 import java.util.List;
38 42 import java.util.Optional;
39 43 import java.util.concurrent.locks.Lock;
... ... @@ -46,14 +50,20 @@ public abstract class AbstractOAuth2ClientMapper {
46 50 private UserService userService;
47 51
48 52 @Autowired
  53 + private BCryptPasswordEncoder passwordEncoder;
  54 +
  55 + @Autowired
49 56 private TenantService tenantService;
50 57
51 58 @Autowired
52 59 private CustomerService customerService;
53 60
  61 + @Autowired
  62 + private InstallScripts installScripts;
  63 +
54 64 private final Lock userCreationLock = new ReentrantLock();
55 65
56   - protected SecurityUser getOrCreateSecurityUserFromOAuth2User(OAuth2User oauth2User, boolean allowUserCreation) {
  66 + protected SecurityUser getOrCreateSecurityUserFromOAuth2User(OAuth2User oauth2User, boolean allowUserCreation, boolean activateUser) {
57 67 UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.USER_NAME, oauth2User.getEmail());
58 68
59 69 User user = userService.findUserByEmail(TenantId.SYS_TENANT_ID, oauth2User.getEmail());
... ... @@ -83,7 +93,14 @@ public abstract class AbstractOAuth2ClientMapper {
83 93 user.setFirstName(oauth2User.getFirstName());
84 94 user.setLastName(oauth2User.getLastName());
85 95 user = userService.saveUser(user);
  96 + if (activateUser) {
  97 + UserCredentials userCredentials = userService.findUserCredentialsByUserId(user.getTenantId(), user.getId());
  98 + userService.activateUserCredentials(user.getTenantId(), userCredentials.getActivateToken(), passwordEncoder.encode(""));
  99 + }
86 100 }
  101 + } catch (Exception e) {
  102 + log.error("Can't get or create security user from oauth2 user", e);
  103 + throw new RuntimeException("Can't get or create security user from oauth2 user", e);
87 104 } finally {
88 105 userCreationLock.unlock();
89 106 }
... ... @@ -98,13 +115,14 @@ public abstract class AbstractOAuth2ClientMapper {
98 115 }
99 116 }
100 117
101   - private TenantId getTenantId(String tenantName) {
  118 + private TenantId getTenantId(String tenantName) throws IOException {
102 119 List<Tenant> tenants = tenantService.findTenants(new PageLink(1, 0, tenantName)).getData();
103 120 Tenant tenant;
104 121 if (tenants == null || tenants.isEmpty()) {
105 122 tenant = new Tenant();
106 123 tenant.setTitle(tenantName);
107 124 tenant = tenantService.saveTenant(tenant);
  125 + installScripts.createDefaultRuleChains(tenant.getId());
108 126 } else {
109 127 tenant = tenants.get(0);
110 128 }
... ...
... ... @@ -56,7 +56,8 @@ public class BasicOAuth2ClientMapper extends AbstractOAuth2ClientMapper implemen
56 56 String customerName = sub.replace(config.getBasic().getCustomerNamePattern());
57 57 oauth2User.setCustomerName(customerName);
58 58 }
59   - return getOrCreateSecurityUserFromOAuth2User(oauth2User, config.getBasic().isAllowUserCreation());
  59 +
  60 + return getOrCreateSecurityUserFromOAuth2User(oauth2User, config.isAllowUserCreation(), config.isActivateUser());
60 61 }
61 62
62 63 private String getTenantName(Map<String, Object> attributes, OAuth2ClientMapperConfig config) {
... ...
... ... @@ -38,7 +38,7 @@ public class CustomOAuth2ClientMapper extends AbstractOAuth2ClientMapper impleme
38 38 @Override
39 39 public SecurityUser getOrCreateUserByClientPrincipal(OAuth2AuthenticationToken token, OAuth2ClientMapperConfig config) {
40 40 OAuth2User oauth2User = getOAuth2User(token, config.getCustom());
41   - return getOrCreateSecurityUserFromOAuth2User(oauth2User, config.getBasic().isAllowUserCreation());
  41 + return getOrCreateSecurityUserFromOAuth2User(oauth2User, config.isAllowUserCreation(), config.isActivateUser());
42 42 }
43 43
44 44 private synchronized OAuth2User getOAuth2User(OAuth2AuthenticationToken token, OAuth2ClientMapperConfig.CustomOAuth2ClientMapperConfig custom) {
... ...
  1 +/**
  2 + * Copyright © 2016-2020 The Thingsboard Authors
  3 + *
  4 + * Licensed under the Apache License, Version 2.0 (the "License");
  5 + * you may not use this file except in compliance with the License.
  6 + * You may obtain a copy of the License at
  7 + *
  8 + * http://www.apache.org/licenses/LICENSE-2.0
  9 + *
  10 + * Unless required by applicable law or agreed to in writing, software
  11 + * distributed under the License is distributed on an "AS IS" BASIS,
  12 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13 + * See the License for the specific language governing permissions and
  14 + * limitations under the License.
  15 + */
  16 +package org.thingsboard.server.service.security.auth.oauth2;
  17 +
  18 +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
  19 +import org.springframework.security.core.AuthenticationException;
  20 +import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
  21 +import org.springframework.stereotype.Component;
  22 +import org.thingsboard.server.utils.MiscUtils;
  23 +
  24 +import javax.servlet.ServletException;
  25 +import javax.servlet.http.HttpServletRequest;
  26 +import javax.servlet.http.HttpServletResponse;
  27 +import java.io.IOException;
  28 +import java.net.URLEncoder;
  29 +import java.nio.charset.StandardCharsets;
  30 +
  31 +@Component(value = "oauth2AuthenticationFailureHandler")
  32 +@ConditionalOnProperty(prefix = "security.oauth2", value = "enabled", havingValue = "true")
  33 +public class Oauth2AuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
  34 +
  35 + @Override
  36 + public void onAuthenticationFailure(HttpServletRequest request,
  37 + HttpServletResponse response, AuthenticationException exception)
  38 + throws IOException, ServletException {
  39 + String baseUrl = MiscUtils.constructBaseUrl(request);
  40 + getRedirectStrategy().sendRedirect(request, response, baseUrl + "/login?loginError=" +
  41 + URLEncoder.encode(exception.getMessage(), StandardCharsets.UTF_8.toString()));
  42 + }
  43 +}
... ...
... ... @@ -27,6 +27,7 @@ import org.thingsboard.server.service.security.auth.jwt.RefreshTokenRepository;
27 27 import org.thingsboard.server.service.security.model.SecurityUser;
28 28 import org.thingsboard.server.service.security.model.token.JwtToken;
29 29 import org.thingsboard.server.service.security.model.token.JwtTokenFactory;
  30 +import org.thingsboard.server.utils.MiscUtils;
30 31
31 32 import javax.servlet.http.HttpServletRequest;
32 33 import javax.servlet.http.HttpServletResponse;
... ... @@ -65,6 +66,7 @@ public class Oauth2AuthenticationSuccessHandler extends SimpleUrlAuthenticationS
65 66 JwtToken accessToken = tokenFactory.createAccessJwtToken(securityUser);
66 67 JwtToken refreshToken = refreshTokenRepository.requestRefreshToken(securityUser);
67 68
68   - getRedirectStrategy().sendRedirect(request, response, "/?accessToken=" + accessToken.getToken() + "&refreshToken=" + refreshToken.getToken());
  69 + String baseUrl = MiscUtils.constructBaseUrl(request);
  70 + getRedirectStrategy().sendRedirect(request, response, baseUrl + "/?accessToken=" + accessToken.getToken() + "&refreshToken=" + refreshToken.getToken());
69 71 }
70 72 }
\ No newline at end of file
... ...
... ... @@ -26,7 +26,7 @@ import javax.servlet.http.HttpServletRequest;
26 26 import javax.servlet.http.HttpServletResponse;
27 27 import java.io.IOException;
28 28
29   -@Component
  29 +@Component(value = "defaultAuthenticationFailureHandler")
30 30 public class RestAwareAuthenticationFailureHandler implements AuthenticationFailureHandler {
31 31
32 32 private final ThingsboardErrorResponseHandler errorResponseHandler;
... ...
... ... @@ -18,8 +18,8 @@ package org.thingsboard.server.utils;
18 18 import com.google.common.hash.HashFunction;
19 19 import com.google.common.hash.Hashing;
20 20
  21 +import javax.servlet.http.HttpServletRequest;
21 22 import java.nio.charset.Charset;
22   -import java.util.Random;
23 23
24 24
25 25 /**
... ... @@ -47,4 +47,36 @@ public class MiscUtils {
47 47 throw new IllegalArgumentException("Can't find hash function with name " + name);
48 48 }
49 49 }
  50 +
  51 + public static String constructBaseUrl(HttpServletRequest request) {
  52 + String scheme = request.getScheme();
  53 +
  54 + String forwardedProto = request.getHeader("x-forwarded-proto");
  55 + if (forwardedProto != null) {
  56 + scheme = forwardedProto;
  57 + }
  58 +
  59 + int serverPort = request.getServerPort();
  60 + if (request.getHeader("x-forwarded-port") != null) {
  61 + try {
  62 + serverPort = request.getIntHeader("x-forwarded-port");
  63 + } catch (NumberFormatException e) {
  64 + }
  65 + } else if (forwardedProto != null) {
  66 + switch (forwardedProto) {
  67 + case "http":
  68 + serverPort = 80;
  69 + break;
  70 + case "https":
  71 + serverPort = 443;
  72 + break;
  73 + }
  74 + }
  75 +
  76 + String baseUrl = String.format("%s://%s:%d",
  77 + scheme,
  78 + request.getServerName(),
  79 + serverPort);
  80 + return baseUrl;
  81 + }
50 82 }
... ...
... ... @@ -100,34 +100,54 @@ security:
100 100 basic:
101 101 enabled: "${SECURITY_BASIC_ENABLED:false}"
102 102 oauth2:
  103 + # Enable/disable OAuth 2 login functionality
  104 + # For details please refer to https://thingsboard.io/docs/user-guide/oauth-2-support/
103 105 enabled: "${SECURITY_OAUTH2_ENABLED:false}"
  106 + # Redirect URL where access code from external user management system will be processed
104 107 loginProcessingUrl: "${SECURITY_OAUTH2_LOGIN_PROCESSING_URL:/login/oauth2/code/}"
  108 + # List of SSO clients
105 109 clients:
106 110 default:
107   - loginButtonLabel: "${SECURITY_OAUTH2_DEFAULT_LOGIN_BUTTON_LABEL:Default}" # Label that going to be show on login screen
108   - loginButtonIcon: "${SECURITY_OAUTH2_DEFAULT_LOGIN_BUTTON_ICON:}" # Icon that going to be show on login screen. Material design icon ID (https://material.angularjs.org/latest/api/directive/mdIcon)
  111 + # Label that going to be show on login button - 'Login with {loginButtonLabel}'
  112 + loginButtonLabel: "${SECURITY_OAUTH2_DEFAULT_LOGIN_BUTTON_LABEL:Default}"
  113 + # Icon that going to be show on login button. Material design icon ID (https://material.angularjs.org/latest/api/directive/mdIcon)
  114 + loginButtonIcon: "${SECURITY_OAUTH2_DEFAULT_LOGIN_BUTTON_ICON:}"
109 115 clientName: "${SECURITY_OAUTH2_DEFAULT_CLIENT_NAME:ClientName}"
110 116 clientId: "${SECURITY_OAUTH2_DEFAULT_CLIENT_ID:}"
111 117 clientSecret: "${SECURITY_OAUTH2_DEFAULT_CLIENT_SECRET:}"
112 118 accessTokenUri: "${SECURITY_OAUTH2_DEFAULT_ACCESS_TOKEN_URI:}"
113 119 authorizationUri: "${SECURITY_OAUTH2_DEFAULT_AUTHORIZATION_URI:}"
114 120 scope: "${SECURITY_OAUTH2_DEFAULT_SCOPE:}"
115   - redirectUriTemplate: "${SECURITY_OAUTH2_DEFAULT_REDIRECT_URI_TEMPLATE:http://localhost:8080/login/oauth2/code/}" # Must be in sync with security.oauth2.loginProcessingUrl
  121 + # Redirect URL that must be in sync with 'security.oauth2.loginProcessingUrl', but domain name added
  122 + redirectUriTemplate: "${SECURITY_OAUTH2_DEFAULT_REDIRECT_URI_TEMPLATE:http://localhost:8080/login/oauth2/code/}"
116 123 jwkSetUri: "${SECURITY_OAUTH2_DEFAULT_JWK_SET_URI:}"
117   - authorizationGrantType: "${SECURITY_OAUTH2_DEFAULT_AUTHORIZATION_GRANT_TYPE:authorization_code}" # authorization_code, implicit, refresh_token or client_credentials
  124 + # 'authorization_code', 'implicit', 'refresh_token' or 'client_credentials'
  125 + authorizationGrantType: "${SECURITY_OAUTH2_DEFAULT_AUTHORIZATION_GRANT_TYPE:authorization_code}"
118 126 clientAuthenticationMethod: "${SECURITY_OAUTH2_DEFAULT_CLIENT_AUTHENTICATION_METHOD:post}" # basic or post
119 127 userInfoUri: "${SECURITY_OAUTH2_DEFAULT_USER_INFO_URI:}"
120 128 userNameAttributeName: "${SECURITY_OAUTH2_DEFAULT_USER_NAME_ATTRIBUTE_NAME:email}"
121 129 mapperConfig:
122   - type: "${SECURITY_OAUTH2_DEFAULT_MAPPER_TYPE:basic}" # basic or custom
  130 + # Allows to create user if it not exists
  131 + allowUserCreation: "${SECURITY_OAUTH2_DEFAULT_MAPPER_ALLOW_USER_CREATION:true}"
  132 + # Allows user to setup ThingsBoard internal password and login over default Login window
  133 + activateUser: "${SECURITY_OAUTH2_DEFAULT_MAPPER_ACTIVATE_USER:false}"
  134 + # Mapper type of converter from external user into internal - 'basic' or 'custom'
  135 + type: "${SECURITY_OAUTH2_DEFAULT_MAPPER_TYPE:basic}"
123 136 basic:
124   - allowUserCreation: "${SECURITY_OAUTH2_DEFAULT_MAPPER_BASIC_ALLOW_USER_CREATION:true}" # Allows to create user if it not exists
125   - emailAttributeKey: "${SECURITY_OAUTH2_DEFAULT_MAPPER_BASIC_EMAIL_ATTRIBUTE_KEY:email}" # Attribute key to use as email for the user
  137 + # Key from attributes of external user object to use as email
  138 + emailAttributeKey: "${SECURITY_OAUTH2_DEFAULT_MAPPER_BASIC_EMAIL_ATTRIBUTE_KEY:email}"
126 139 firstNameAttributeKey: "${SECURITY_OAUTH2_DEFAULT_MAPPER_BASIC_FIRST_NAME_ATTRIBUTE_KEY:}"
127 140 lastNameAttributeKey: "${SECURITY_OAUTH2_DEFAULT_MAPPER_BASIC_LAST_NAME_ATTRIBUTE_KEY:}"
128   - tenantNameStrategy: "${SECURITY_OAUTH2_DEFAULT_MAPPER_BASIC_TENANT_NAME_STRATEGY:domain}" # domain, email or custom
129   - tenantNamePattern: "${SECURITY_OAUTH2_DEFAULT_MAPPER_BASIC_TENANT_NAME_PATTERN:}" # %{attribute_key} as placeholder for attributes value by key
130   - customerNamePattern: "${SECURITY_OAUTH2_DEFAULT_MAPPER_BASIC_CUSTOMER_NAME_PATTERN:}" # %{attribute_key} as placeholder for attributes value by key
  141 + # Strategy for generating Tenant from external user object - 'domain', 'email' or 'custom'
  142 + # 'domain' - name of the Tenant will be extracted as domain from the email of the user
  143 + # 'email' - name of the Tenant will email of the user
  144 + # 'custom' - please configure 'tenantNamePattern' for custom mapping
  145 + tenantNameStrategy: "${SECURITY_OAUTH2_DEFAULT_MAPPER_BASIC_TENANT_NAME_STRATEGY:domain}"
  146 + # %{attribute_key} as placeholder for attribute value of attributes of external user object
  147 + tenantNamePattern: "${SECURITY_OAUTH2_DEFAULT_MAPPER_BASIC_TENANT_NAME_PATTERN:}"
  148 + # If this field is not empty, user will be created as a user under defined Customer
  149 + # %{attribute_key} as placeholder for attribute value of attributes of external user object
  150 + customerNamePattern: "${SECURITY_OAUTH2_DEFAULT_MAPPER_BASIC_CUSTOMER_NAME_PATTERN:}"
131 151 custom:
132 152 url: "${SECURITY_OAUTH2_DEFAULT_MAPPER_CUSTOM_URL:}"
133 153 username: "${SECURITY_OAUTH2_DEFAULT_MAPPER_CUSTOM_USERNAME:}"
... ... @@ -620,8 +640,7 @@ queue:
620 640 notifications: "${TB_QUEUE_RABBIT_MQ_NOTIFICATIONS_QUEUE_PROPERTIES:x-max-length-bytes:1048576000;x-message-ttl:604800000}"
621 641 js-executor: "${TB_QUEUE_RABBIT_MQ_JE_QUEUE_PROPERTIES:x-max-length-bytes:1048576000;x-message-ttl:604800000}"
622 642 partitions:
623   - hash_function_name: "${TB_QUEUE_PARTITIONS_HASH_FUNCTION_NAME:murmur3_128}"
624   - virtual_nodes_size: "${TB_QUEUE_PARTITIONS_VIRTUAL_NODES_SIZE:16}"
  643 + hash_function_name: "${TB_QUEUE_PARTITIONS_HASH_FUNCTION_NAME:murmur3_128}" # murmur3_32, murmur3_128 or sha256
625 644 transport_api:
626 645 requests_topic: "${TB_QUEUE_TRANSPORT_API_REQUEST_TOPIC:tb_transport.api.requests}"
627 646 responses_topic: "${TB_QUEUE_TRANSPORT_API_RESPONSE_TOPIC:tb_transport.api.responses}"
... ...
application/src/test/java/org/thingsboard/server/service/cluster/routing/HashPartitionServiceTest.java renamed from application/src/test/java/org/thingsboard/server/service/cluster/routing/ConsistentHashParitionServiceTest.java
... ... @@ -26,14 +26,14 @@ import org.springframework.context.ApplicationEventPublisher;
26 26 import org.springframework.test.util.ReflectionTestUtils;
27 27 import org.thingsboard.server.common.data.id.DeviceId;
28 28 import org.thingsboard.server.common.data.id.TenantId;
29   -import org.thingsboard.server.queue.discovery.ConsistentHashPartitionService;
  29 +import org.thingsboard.server.common.msg.queue.ServiceQueue;
  30 +import org.thingsboard.server.queue.discovery.HashPartitionService;
30 31 import org.thingsboard.server.common.msg.queue.ServiceType;
31 32 import org.thingsboard.server.queue.discovery.TbServiceInfoProvider;
32 33 import org.thingsboard.server.common.msg.queue.TopicPartitionInfo;
33 34 import org.thingsboard.server.gen.transport.TransportProtos;
34 35 import org.thingsboard.server.queue.discovery.TenantRoutingInfoService;
35 36 import org.thingsboard.server.queue.settings.TbQueueRuleEngineSettings;
36   -import org.thingsboard.server.queue.settings.TbRuleEngineQueueConfiguration;
37 37
38 38 import java.util.ArrayList;
39 39 import java.util.Collections;
... ... @@ -48,18 +48,18 @@ import static org.mockito.Mockito.when;
48 48
49 49 @Slf4j
50 50 @RunWith(MockitoJUnitRunner.class)
51   -public class ConsistentHashParitionServiceTest {
  51 +public class HashPartitionServiceTest {
52 52
53 53 public static final int ITERATIONS = 1000000;
54   - private ConsistentHashPartitionService clusterRoutingService;
  54 + public static final int SERVER_COUNT = 3;
  55 + private HashPartitionService clusterRoutingService;
55 56
56 57 private TbServiceInfoProvider discoveryService;
57 58 private TenantRoutingInfoService routingInfoService;
58 59 private ApplicationEventPublisher applicationEventPublisher;
59 60 private TbQueueRuleEngineSettings ruleEngineSettings;
60 61
61   - private String hashFunctionName = "murmur3_128";
62   - private Integer virtualNodesSize = 16;
  62 + private String hashFunctionName = "sha256";
63 63
64 64
65 65 @Before
... ... @@ -68,25 +68,28 @@ public class ConsistentHashParitionServiceTest {
68 68 applicationEventPublisher = mock(ApplicationEventPublisher.class);
69 69 routingInfoService = mock(TenantRoutingInfoService.class);
70 70 ruleEngineSettings = mock(TbQueueRuleEngineSettings.class);
71   - clusterRoutingService = new ConsistentHashPartitionService(discoveryService,
  71 + clusterRoutingService = new HashPartitionService(discoveryService,
72 72 routingInfoService,
73 73 applicationEventPublisher,
74 74 ruleEngineSettings
75 75 );
76 76 when(ruleEngineSettings.getQueues()).thenReturn(Collections.emptyList());
77 77 ReflectionTestUtils.setField(clusterRoutingService, "coreTopic", "tb.core");
78   - ReflectionTestUtils.setField(clusterRoutingService, "corePartitions", 3);
  78 + ReflectionTestUtils.setField(clusterRoutingService, "corePartitions", 10);
79 79 ReflectionTestUtils.setField(clusterRoutingService, "hashFunctionName", hashFunctionName);
80   - ReflectionTestUtils.setField(clusterRoutingService, "virtualNodesSize", virtualNodesSize);
81 80 TransportProtos.ServiceInfo currentServer = TransportProtos.ServiceInfo.newBuilder()
82   - .setServiceId("100.96.1.1")
  81 + .setServiceId("tb-core-0")
  82 + .setTenantIdMSB(TenantId.NULL_UUID.getMostSignificantBits())
  83 + .setTenantIdLSB(TenantId.NULL_UUID.getLeastSignificantBits())
83 84 .addAllServiceTypes(Collections.singletonList(ServiceType.TB_CORE.name()))
84 85 .build();
85 86 // when(discoveryService.getServiceInfo()).thenReturn(currentServer);
86 87 List<TransportProtos.ServiceInfo> otherServers = new ArrayList<>();
87   - for (int i = 1; i < 30; i++) {
  88 + for (int i = 1; i < SERVER_COUNT; i++) {
88 89 otherServers.add(TransportProtos.ServiceInfo.newBuilder()
89   - .setServiceId("100.96." + i * 2 + "." + i)
  90 + .setServiceId("tb-rule-" + i)
  91 + .setTenantIdMSB(TenantId.NULL_UUID.getMostSignificantBits())
  92 + .setTenantIdLSB(TenantId.NULL_UUID.getLeastSignificantBits())
90 93 .addAllServiceTypes(Collections.singletonList(ServiceType.TB_CORE.name()))
91 94 .build());
92 95 }
... ... @@ -116,12 +119,11 @@ public class ConsistentHashParitionServiceTest {
116 119 long end = System.currentTimeMillis();
117 120 double diff = (data.get(data.size() - 1).getValue() - data.get(0).getValue());
118 121 double diffPercent = (diff / ITERATIONS) * 100.0;
119   - System.out.println("Size: " + virtualNodesSize + " Time: " + (end - start) + " Diff: " + diff + "(" + String.format("%f", diffPercent) + "%)");
  122 + System.out.println("Time: " + (end - start) + " Diff: " + diff + "(" + String.format("%f", diffPercent) + "%)");
120 123 Assert.assertTrue(diffPercent < 0.5);
121 124 for (Map.Entry<Integer, Integer> entry : data) {
122 125 System.out.println(entry.getKey() + ": " + entry.getValue());
123 126 }
124   -
125 127 }
126 128
127 129 }
... ...
common/queue/src/main/java/org/thingsboard/server/queue/discovery/HashPartitionService.java renamed from common/queue/src/main/java/org/thingsboard/server/queue/discovery/ConsistentHashPartitionService.java
... ... @@ -18,6 +18,7 @@ package org.thingsboard.server.queue.discovery;
18 18 import com.google.common.hash.HashCode;
19 19 import com.google.common.hash.HashFunction;
20 20 import com.google.common.hash.Hashing;
  21 +import lombok.Getter;
21 22 import lombok.extern.slf4j.Slf4j;
22 23 import org.springframework.beans.factory.annotation.Value;
23 24 import org.springframework.context.ApplicationEventPublisher;
... ... @@ -35,6 +36,7 @@ import org.thingsboard.server.queue.settings.TbQueueRuleEngineSettings;
35 36 import javax.annotation.PostConstruct;
36 37 import java.nio.charset.StandardCharsets;
37 38 import java.util.ArrayList;
  39 +import java.util.Comparator;
38 40 import java.util.HashMap;
39 41 import java.util.HashSet;
40 42 import java.util.List;
... ... @@ -48,7 +50,7 @@ import java.util.stream.Collectors;
48 50
49 51 @Service
50 52 @Slf4j
51   -public class ConsistentHashPartitionService implements PartitionService {
  53 +public class HashPartitionService implements PartitionService {
52 54
53 55 @Value("${queue.core.topic}")
54 56 private String coreTopic;
... ... @@ -56,8 +58,6 @@ public class ConsistentHashPartitionService implements PartitionService {
56 58 private Integer corePartitions;
57 59 @Value("${queue.partitions.hash_function_name:murmur3_128}")
58 60 private String hashFunctionName;
59   - @Value("${queue.partitions.virtual_nodes_size:16}")
60   - private Integer virtualNodesSize;
61 61
62 62 private final ApplicationEventPublisher applicationEventPublisher;
63 63 private final TbServiceInfoProvider serviceInfoProvider;
... ... @@ -76,10 +76,10 @@ public class ConsistentHashPartitionService implements PartitionService {
76 76
77 77 private HashFunction hashFunction;
78 78
79   - public ConsistentHashPartitionService(TbServiceInfoProvider serviceInfoProvider,
80   - TenantRoutingInfoService tenantRoutingInfoService,
81   - ApplicationEventPublisher applicationEventPublisher,
82   - TbQueueRuleEngineSettings tbQueueRuleEngineSettings) {
  79 + public HashPartitionService(TbServiceInfoProvider serviceInfoProvider,
  80 + TenantRoutingInfoService tenantRoutingInfoService,
  81 + ApplicationEventPublisher applicationEventPublisher,
  82 + TbQueueRuleEngineSettings tbQueueRuleEngineSettings) {
83 83 this.serviceInfoProvider = serviceInfoProvider;
84 84 this.tenantRoutingInfoService = tenantRoutingInfoService;
85 85 this.applicationEventPublisher = applicationEventPublisher;
... ... @@ -128,20 +128,22 @@ public class ConsistentHashPartitionService implements PartitionService {
128 128 public void recalculatePartitions(ServiceInfo currentService, List<ServiceInfo> otherServices) {
129 129 logServiceInfo(currentService);
130 130 otherServices.forEach(this::logServiceInfo);
131   - Map<ServiceQueueKey, ConsistentHashCircle<ServiceInfo>> circles = new HashMap<>();
132   - addNode(circles, currentService);
  131 + Map<ServiceQueueKey, List<ServiceInfo>> queueServicesMap = new HashMap<>();
  132 + addNode(queueServicesMap, currentService);
133 133 for (ServiceInfo other : otherServices) {
134   - addNode(circles, other);
  134 + addNode(queueServicesMap, other);
135 135 }
  136 + queueServicesMap.values().forEach(list -> list.sort((a, b) -> a.getServiceId().compareTo(b.getServiceId())));
  137 +
136 138 ConcurrentMap<ServiceQueueKey, List<Integer>> oldPartitions = myPartitions;
137 139 TenantId myIsolatedOrSystemTenantId = getSystemOrIsolatedTenantId(currentService);
138 140 myPartitions = new ConcurrentHashMap<>();
139   - partitionSizes.forEach((type, size) -> {
140   - ServiceQueueKey myServiceQueueKey = new ServiceQueueKey(type, myIsolatedOrSystemTenantId);
  141 + partitionSizes.forEach((serviceQueue, size) -> {
  142 + ServiceQueueKey myServiceQueueKey = new ServiceQueueKey(serviceQueue, myIsolatedOrSystemTenantId);
141 143 for (int i = 0; i < size; i++) {
142   - ServiceInfo serviceInfo = resolveByPartitionIdx(circles.get(myServiceQueueKey), i);
  144 + ServiceInfo serviceInfo = resolveByPartitionIdx(queueServicesMap.get(myServiceQueueKey), i);
143 145 if (currentService.equals(serviceInfo)) {
144   - ServiceQueueKey serviceQueueKey = new ServiceQueueKey(type, getSystemOrIsolatedTenantId(serviceInfo));
  146 + ServiceQueueKey serviceQueueKey = new ServiceQueueKey(serviceQueue, getSystemOrIsolatedTenantId(serviceInfo));
145 147 myPartitions.computeIfAbsent(serviceQueueKey, key -> new ArrayList<>()).add(i);
146 148 }
147 149 }
... ... @@ -293,7 +295,7 @@ public class ConsistentHashPartitionService implements PartitionService {
293 295 return new TenantId(new UUID(serviceInfo.getTenantIdMSB(), serviceInfo.getTenantIdLSB()));
294 296 }
295 297
296   - private void addNode(Map<ServiceQueueKey, ConsistentHashCircle<ServiceInfo>> circles, ServiceInfo instance) {
  298 + private void addNode(Map<ServiceQueueKey, List<ServiceInfo>> queueServiceList, ServiceInfo instance) {
297 299 TenantId tenantId = getSystemOrIsolatedTenantId(instance);
298 300 for (String serviceTypeStr : instance.getServiceTypesList()) {
299 301 ServiceType serviceType = ServiceType.valueOf(serviceTypeStr.toUpperCase());
... ... @@ -302,34 +304,20 @@ public class ConsistentHashPartitionService implements PartitionService {
302 304 ServiceQueueKey serviceQueueKey = new ServiceQueueKey(new ServiceQueue(serviceType, queue.getName()), tenantId);
303 305 partitionSizes.put(new ServiceQueue(ServiceType.TB_RULE_ENGINE, queue.getName()), queue.getPartitions());
304 306 partitionTopics.put(new ServiceQueue(ServiceType.TB_RULE_ENGINE, queue.getName()), queue.getTopic());
305   - for (int i = 0; i < virtualNodesSize; i++) {
306   - circles.computeIfAbsent(serviceQueueKey, key -> new ConsistentHashCircle<>()).put(hash(instance, i).asLong(), instance);
307   - }
  307 + queueServiceList.computeIfAbsent(serviceQueueKey, key -> new ArrayList<>()).add(instance);
308 308 }
309 309 } else {
310 310 ServiceQueueKey serviceQueueKey = new ServiceQueueKey(new ServiceQueue(serviceType), tenantId);
311   - for (int i = 0; i < virtualNodesSize; i++) {
312   - circles.computeIfAbsent(serviceQueueKey, key -> new ConsistentHashCircle<>()).put(hash(instance, i).asLong(), instance);
313   - }
  311 + queueServiceList.computeIfAbsent(serviceQueueKey, key -> new ArrayList<>()).add(instance);
314 312 }
315 313 }
316 314 }
317 315
318   - private ServiceInfo resolveByPartitionIdx(ConsistentHashCircle<ServiceInfo> circle, Integer partitionIdx) {
319   - if (circle == null || circle.isEmpty()) {
  316 + private ServiceInfo resolveByPartitionIdx(List<ServiceInfo> servers, Integer partitionIdx) {
  317 + if (servers == null || servers.isEmpty()) {
320 318 return null;
321 319 }
322   - Long hash = hashFunction.newHasher().putInt(partitionIdx).hash().asLong();
323   - if (!circle.containsKey(hash)) {
324   - ConcurrentNavigableMap<Long, ServiceInfo> tailMap = circle.tailMap(hash);
325   - hash = tailMap.isEmpty() ?
326   - circle.firstKey() : tailMap.firstKey();
327   - }
328   - return circle.get(hash);
329   - }
330   -
331   - private HashCode hash(ServiceInfo instance, int i) {
332   - return hashFunction.newHasher().putString(instance.getServiceId(), StandardCharsets.UTF_8).putInt(i).hash();
  320 + return servers.get(partitionIdx % servers.size());
333 321 }
334 322
335 323 public static HashFunction forName(String name) {
... ... @@ -338,12 +326,11 @@ public class ConsistentHashPartitionService implements PartitionService {
338 326 return Hashing.murmur3_32();
339 327 case "murmur3_128":
340 328 return Hashing.murmur3_128();
341   - case "crc32":
342   - return Hashing.crc32();
343   - case "md5":
344   - return Hashing.md5();
  329 + case "sha256":
  330 + return Hashing.sha256();
345 331 default:
346 332 throw new IllegalArgumentException("Can't find hash function with name " + name);
347 333 }
348 334 }
  335 +
349 336 }
... ...
... ... @@ -20,13 +20,14 @@ import lombok.Data;
20 20 @Data
21 21 public class OAuth2ClientMapperConfig {
22 22
  23 + private boolean allowUserCreation;
  24 + private boolean activateUser;
23 25 private String type;
24 26 private BasicOAuth2ClientMapperConfig basic;
25 27 private CustomOAuth2ClientMapperConfig custom;
26 28
27 29 @Data
28 30 public static class BasicOAuth2ClientMapperConfig {
29   - private boolean allowUserCreation;
30 31 private String emailAttributeKey;
31 32 private String firstNameAttributeKey;
32 33 private String lastNameAttributeKey;
... ...
... ... @@ -58,7 +58,7 @@ frontend http-in
58 58
59 59 acl transport_http_acl path_beg /api/v1/
60 60 acl letsencrypt_http_acl path_beg /.well-known/acme-challenge/
61   - acl tb_api_acl path_beg /api/ /swagger /webjars /v2/ /static/rulenode/
  61 + acl tb_api_acl path_beg /api/ /swagger /webjars /v2/ /static/rulenode/ /oauth2/ /login/oauth2/
62 62
63 63 redirect scheme https if !letsencrypt_http_acl !transport_http_acl { env(FORCE_HTTPS_REDIRECT) -m str true }
64 64
... ... @@ -76,7 +76,7 @@ frontend https_in
76 76 reqadd X-Forwarded-Proto:\ https
77 77
78 78 acl transport_http_acl path_beg /api/v1/
79   - acl tb_api_acl path_beg /api/ /swagger /webjars /v2/ /static/rulenode/
  79 + acl tb_api_acl path_beg /api/ /swagger /webjars /v2/ /static/rulenode/ /oauth2/ /login/oauth2/
80 80
81 81 use_backend tb-http-backend if transport_http_acl
82 82 use_backend tb-api-backend if tb_api_acl
... ...
... ... @@ -1944,14 +1944,12 @@
1944 1944 "balanced-match": {
1945 1945 "version": "1.0.0",
1946 1946 "bundled": true,
1947   - "dev": true,
1948   - "optional": true
  1947 + "dev": true
1949 1948 },
1950 1949 "brace-expansion": {
1951 1950 "version": "1.1.11",
1952 1951 "bundled": true,
1953 1952 "dev": true,
1954   - "optional": true,
1955 1953 "requires": {
1956 1954 "balanced-match": "^1.0.0",
1957 1955 "concat-map": "0.0.1"
... ... @@ -1971,8 +1969,7 @@
1971 1969 "concat-map": {
1972 1970 "version": "0.0.1",
1973 1971 "bundled": true,
1974   - "dev": true,
1975   - "optional": true
  1972 + "dev": true
1976 1973 },
1977 1974 "console-control-strings": {
1978 1975 "version": "1.1.0",
... ... @@ -2120,7 +2117,6 @@
2120 2117 "version": "3.0.4",
2121 2118 "bundled": true,
2122 2119 "dev": true,
2123   - "optional": true,
2124 2120 "requires": {
2125 2121 "brace-expansion": "^1.1.7"
2126 2122 }
... ...
... ... @@ -472,11 +472,23 @@
472 472 <groupId>org.springframework.security</groupId>
473 473 <artifactId>spring-security-oauth2-client</artifactId>
474 474 <version>${spring-security.version}</version>
  475 + <exclusions>
  476 + <exclusion>
  477 + <groupId>org.springframework</groupId>
  478 + <artifactId>spring-core</artifactId>
  479 + </exclusion>
  480 + </exclusions>
475 481 </dependency>
476 482 <dependency>
477 483 <groupId>org.springframework.security</groupId>
478 484 <artifactId>spring-security-oauth2-jose</artifactId>
479 485 <version>${spring-security.version}</version>
  486 + <exclusions>
  487 + <exclusion>
  488 + <groupId>org.springframework</groupId>
  489 + <artifactId>spring-core</artifactId>
  490 + </exclusion>
  491 + </exclusions>
480 492 </dependency>
481 493 <dependency>
482 494 <groupId>org.springframework.boot</groupId>
... ...
... ... @@ -20,7 +20,6 @@ import com.google.common.cache.CacheLoader;
20 20 import com.google.common.cache.LoadingCache;
21 21 import com.google.common.util.concurrent.Futures;
22 22 import com.google.common.util.concurrent.ListenableFuture;
23   -import com.google.common.util.concurrent.MoreExecutors;
24 23 import lombok.AllArgsConstructor;
25 24 import lombok.Data;
26 25 import lombok.NoArgsConstructor;
... ... @@ -78,7 +77,8 @@ public abstract class TbAbstractRelationActionNode<C extends TbAbstractRelationA
78 77
79 78 @Override
80 79 public void onMsg(TbContext ctx, TbMsg msg) {
81   - withCallback(processEntityRelationAction(ctx, msg),
  80 + String relationType = processPattern(msg, config.getRelationType());
  81 + withCallback(processEntityRelationAction(ctx, msg, relationType),
82 82 filterResult -> ctx.tellNext(filterResult.getMsg(), filterResult.isResult() ? SUCCESS : FAILURE), t -> ctx.tellFailure(msg, t), ctx.getDbCallbackExecutor());
83 83 }
84 84
... ... @@ -86,13 +86,13 @@ public abstract class TbAbstractRelationActionNode<C extends TbAbstractRelationA
86 86 public void destroy() {
87 87 }
88 88
89   - protected ListenableFuture<RelationContainer> processEntityRelationAction(TbContext ctx, TbMsg msg) {
90   - return Futures.transformAsync(getEntity(ctx, msg), entityContainer -> doProcessEntityRelationAction(ctx, msg, entityContainer), MoreExecutors.directExecutor());
  89 + protected ListenableFuture<RelationContainer> processEntityRelationAction(TbContext ctx, TbMsg msg, String relationType) {
  90 + return Futures.transformAsync(getEntity(ctx, msg), entityContainer -> doProcessEntityRelationAction(ctx, msg, entityContainer, relationType), ctx.getDbCallbackExecutor());
91 91 }
92 92
93 93 protected abstract boolean createEntityIfNotExists();
94 94
95   - protected abstract ListenableFuture<RelationContainer> doProcessEntityRelationAction(TbContext ctx, TbMsg msg, EntityContainer entityContainer);
  95 + protected abstract ListenableFuture<RelationContainer> doProcessEntityRelationAction(TbContext ctx, TbMsg msg, EntityContainer entityContainer, String relationType);
96 96
97 97 protected abstract C loadEntityNodeActionConfig(TbNodeConfiguration configuration) throws TbNodeException;
98 98
... ... @@ -120,11 +120,11 @@ public abstract class TbAbstractRelationActionNode<C extends TbAbstractRelationA
120 120 if (EntitySearchDirection.FROM.name().equals(this.config.getDirection())) {
121 121 searchDirectionIds.setFromId(EntityIdFactory.getByTypeAndId(entityContainer.getEntityType().name(), entityContainer.getEntityId().toString()));
122 122 searchDirectionIds.setToId(msg.getOriginator());
123   - searchDirectionIds.setOrignatorDirectionFrom(false);
  123 + searchDirectionIds.setOriginatorDirectionFrom(false);
124 124 } else {
125 125 searchDirectionIds.setToId(EntityIdFactory.getByTypeAndId(entityContainer.getEntityType().name(), entityContainer.getEntityId().toString()));
126 126 searchDirectionIds.setFromId(msg.getOriginator());
127   - searchDirectionIds.setOrignatorDirectionFrom(true);
  127 + searchDirectionIds.setOriginatorDirectionFrom(true);
128 128 }
129 129 return searchDirectionIds;
130 130 }
... ... @@ -153,7 +153,7 @@ public abstract class TbAbstractRelationActionNode<C extends TbAbstractRelationA
153 153 protected static class SearchDirectionIds {
154 154 private EntityId fromId;
155 155 private EntityId toId;
156   - private boolean orignatorDirectionFrom;
  156 + private boolean originatorDirectionFrom;
157 157 }
158 158
159 159 private static class EntityCacheLoader extends CacheLoader<EntityKey, EntityContainer> {
... ...
... ... @@ -17,7 +17,6 @@ package org.thingsboard.rule.engine.action;
17 17
18 18 import com.google.common.util.concurrent.Futures;
19 19 import com.google.common.util.concurrent.ListenableFuture;
20   -import com.google.common.util.concurrent.MoreExecutors;
21 20 import lombok.extern.slf4j.Slf4j;
22 21 import org.thingsboard.rule.engine.api.RuleNode;
23 22 import org.thingsboard.rule.engine.api.TbContext;
... ... @@ -57,8 +56,6 @@ import java.util.List;
57 56 )
58 57 public class TbCreateRelationNode extends TbAbstractRelationActionNode<TbCreateRelationNodeConfiguration> {
59 58
60   - private String relationType;
61   -
62 59 @Override
63 60 protected TbCreateRelationNodeConfiguration loadEntityNodeActionConfig(TbNodeConfiguration configuration) throws TbNodeException {
64 61 return TbNodeUtils.convert(configuration, TbCreateRelationNodeConfiguration.class);
... ... @@ -70,8 +67,8 @@ public class TbCreateRelationNode extends TbAbstractRelationActionNode<TbCreateR
70 67 }
71 68
72 69 @Override
73   - protected ListenableFuture<RelationContainer> doProcessEntityRelationAction(TbContext ctx, TbMsg msg, EntityContainer entity) {
74   - ListenableFuture<Boolean> future = createIfAbsent(ctx, msg, entity);
  70 + protected ListenableFuture<RelationContainer> doProcessEntityRelationAction(TbContext ctx, TbMsg msg, EntityContainer entity, String relationType) {
  71 + ListenableFuture<Boolean> future = createIfAbsent(ctx, msg, entity, relationType);
75 72 return Futures.transform(future, result -> {
76 73 RelationContainer container = new RelationContainer();
77 74 if (result && config.isChangeOriginatorToRelatedEntity()) {
... ... @@ -82,16 +79,15 @@ public class TbCreateRelationNode extends TbAbstractRelationActionNode<TbCreateR
82 79 }
83 80 container.setResult(result);
84 81 return container;
85   - }, MoreExecutors.directExecutor());
  82 + }, ctx.getDbCallbackExecutor());
86 83 }
87 84
88   - private ListenableFuture<Boolean> createIfAbsent(TbContext ctx, TbMsg msg, EntityContainer entityContainer) {
89   - relationType = processPattern(msg, config.getRelationType());
  85 + private ListenableFuture<Boolean> createIfAbsent(TbContext ctx, TbMsg msg, EntityContainer entityContainer, String relationType) {
90 86 SearchDirectionIds sdId = processSingleSearchDirection(msg, entityContainer);
91 87 ListenableFuture<Boolean> checkRelationFuture = Futures.transformAsync(ctx.getRelationService().checkRelation(ctx.getTenantId(), sdId.getFromId(), sdId.getToId(), relationType, RelationTypeGroup.COMMON), result -> {
92 88 if (!result) {
93 89 if (config.isRemoveCurrentRelations()) {
94   - return processDeleteRelations(ctx, processFindRelations(ctx, msg, sdId));
  90 + return processDeleteRelations(ctx, processFindRelations(ctx, msg, sdId, relationType));
95 91 }
96 92 return Futures.immediateFuture(false);
97 93 }
... ... @@ -100,14 +96,14 @@ public class TbCreateRelationNode extends TbAbstractRelationActionNode<TbCreateR
100 96
101 97 return Futures.transformAsync(checkRelationFuture, result -> {
102 98 if (!result) {
103   - return processCreateRelation(ctx, entityContainer, sdId);
  99 + return processCreateRelation(ctx, entityContainer, sdId, relationType);
104 100 }
105 101 return Futures.immediateFuture(true);
106 102 }, ctx.getDbCallbackExecutor());
107 103 }
108 104
109   - private ListenableFuture<List<EntityRelation>> processFindRelations(TbContext ctx, TbMsg msg, SearchDirectionIds sdId) {
110   - if (sdId.isOrignatorDirectionFrom()) {
  105 + private ListenableFuture<List<EntityRelation>> processFindRelations(TbContext ctx, TbMsg msg, SearchDirectionIds sdId, String relationType) {
  106 + if (sdId.isOriginatorDirectionFrom()) {
111 107 return ctx.getRelationService().findByFromAndTypeAsync(ctx.getTenantId(), msg.getOriginator(), relationType, RelationTypeGroup.COMMON);
112 108 } else {
113 109 return ctx.getRelationService().findByToAndTypeAsync(ctx.getTenantId(), msg.getOriginator(), relationType, RelationTypeGroup.COMMON);
... ... @@ -121,91 +117,91 @@ public class TbCreateRelationNode extends TbAbstractRelationActionNode<TbCreateR
121 117 for (EntityRelation relation : entityRelations) {
122 118 list.add(ctx.getRelationService().deleteRelationAsync(ctx.getTenantId(), relation));
123 119 }
124   - return Futures.transform(Futures.allAsList(list), result -> false, MoreExecutors.directExecutor());
  120 + return Futures.transform(Futures.allAsList(list), result -> false, ctx.getDbCallbackExecutor());
125 121 }
126 122 return Futures.immediateFuture(false);
127 123 }, ctx.getDbCallbackExecutor());
128 124 }
129 125
130   - private ListenableFuture<Boolean> processCreateRelation(TbContext ctx, EntityContainer entityContainer, SearchDirectionIds sdId) {
  126 + private ListenableFuture<Boolean> processCreateRelation(TbContext ctx, EntityContainer entityContainer, SearchDirectionIds sdId, String relationType) {
131 127 switch (entityContainer.getEntityType()) {
132 128 case ASSET:
133   - return processAsset(ctx, entityContainer, sdId);
  129 + return processAsset(ctx, entityContainer, sdId, relationType);
134 130 case DEVICE:
135   - return processDevice(ctx, entityContainer, sdId);
  131 + return processDevice(ctx, entityContainer, sdId, relationType);
136 132 case CUSTOMER:
137   - return processCustomer(ctx, entityContainer, sdId);
  133 + return processCustomer(ctx, entityContainer, sdId, relationType);
138 134 case DASHBOARD:
139   - return processDashboard(ctx, entityContainer, sdId);
  135 + return processDashboard(ctx, entityContainer, sdId, relationType);
140 136 case ENTITY_VIEW:
141   - return processView(ctx, entityContainer, sdId);
  137 + return processView(ctx, entityContainer, sdId, relationType);
142 138 case TENANT:
143   - return processTenant(ctx, entityContainer, sdId);
  139 + return processTenant(ctx, entityContainer, sdId, relationType);
144 140 }
145 141 return Futures.immediateFuture(true);
146 142 }
147 143
148   - private ListenableFuture<Boolean> processView(TbContext ctx, EntityContainer entityContainer, SearchDirectionIds sdId) {
  144 + private ListenableFuture<Boolean> processView(TbContext ctx, EntityContainer entityContainer, SearchDirectionIds sdId, String relationType) {
149 145 return Futures.transformAsync(ctx.getEntityViewService().findEntityViewByIdAsync(ctx.getTenantId(), new EntityViewId(entityContainer.getEntityId().getId())), entityView -> {
150 146 if (entityView != null) {
151   - return processSave(ctx, sdId);
  147 + return processSave(ctx, sdId, relationType);
152 148 } else {
153 149 return Futures.immediateFuture(true);
154 150 }
155 151 }, ctx.getDbCallbackExecutor());
156 152 }
157 153
158   - private ListenableFuture<Boolean> processDevice(TbContext ctx, EntityContainer entityContainer, SearchDirectionIds sdId) {
  154 + private ListenableFuture<Boolean> processDevice(TbContext ctx, EntityContainer entityContainer, SearchDirectionIds sdId, String relationType) {
159 155 return Futures.transformAsync(ctx.getDeviceService().findDeviceByIdAsync(ctx.getTenantId(), new DeviceId(entityContainer.getEntityId().getId())), device -> {
160 156 if (device != null) {
161   - return processSave(ctx, sdId);
  157 + return processSave(ctx, sdId, relationType);
162 158 } else {
163 159 return Futures.immediateFuture(true);
164 160 }
165   - }, MoreExecutors.directExecutor());
  161 + }, ctx.getDbCallbackExecutor());
166 162 }
167 163
168   - private ListenableFuture<Boolean> processAsset(TbContext ctx, EntityContainer entityContainer, SearchDirectionIds sdId) {
  164 + private ListenableFuture<Boolean> processAsset(TbContext ctx, EntityContainer entityContainer, SearchDirectionIds sdId, String relationType) {
169 165 return Futures.transformAsync(ctx.getAssetService().findAssetByIdAsync(ctx.getTenantId(), new AssetId(entityContainer.getEntityId().getId())), asset -> {
170 166 if (asset != null) {
171   - return processSave(ctx, sdId);
  167 + return processSave(ctx, sdId, relationType);
172 168 } else {
173 169 return Futures.immediateFuture(true);
174 170 }
175 171 }, ctx.getDbCallbackExecutor());
176 172 }
177 173
178   - private ListenableFuture<Boolean> processCustomer(TbContext ctx, EntityContainer entityContainer, SearchDirectionIds sdId) {
  174 + private ListenableFuture<Boolean> processCustomer(TbContext ctx, EntityContainer entityContainer, SearchDirectionIds sdId, String relationType) {
179 175 return Futures.transformAsync(ctx.getCustomerService().findCustomerByIdAsync(ctx.getTenantId(), new CustomerId(entityContainer.getEntityId().getId())), customer -> {
180 176 if (customer != null) {
181   - return processSave(ctx, sdId);
  177 + return processSave(ctx, sdId, relationType);
182 178 } else {
183 179 return Futures.immediateFuture(true);
184 180 }
185 181 }, ctx.getDbCallbackExecutor());
186 182 }
187 183
188   - private ListenableFuture<Boolean> processDashboard(TbContext ctx, EntityContainer entityContainer, SearchDirectionIds sdId) {
  184 + private ListenableFuture<Boolean> processDashboard(TbContext ctx, EntityContainer entityContainer, SearchDirectionIds sdId, String relationType) {
189 185 return Futures.transformAsync(ctx.getDashboardService().findDashboardByIdAsync(ctx.getTenantId(), new DashboardId(entityContainer.getEntityId().getId())), dashboard -> {
190 186 if (dashboard != null) {
191   - return processSave(ctx, sdId);
  187 + return processSave(ctx, sdId, relationType);
192 188 } else {
193 189 return Futures.immediateFuture(true);
194 190 }
195 191 }, ctx.getDbCallbackExecutor());
196 192 }
197 193
198   - private ListenableFuture<Boolean> processTenant(TbContext ctx, EntityContainer entityContainer, SearchDirectionIds sdId) {
  194 + private ListenableFuture<Boolean> processTenant(TbContext ctx, EntityContainer entityContainer, SearchDirectionIds sdId, String relationType) {
199 195 return Futures.transformAsync(ctx.getTenantService().findTenantByIdAsync(ctx.getTenantId(), new TenantId(entityContainer.getEntityId().getId())), tenant -> {
200 196 if (tenant != null) {
201   - return processSave(ctx, sdId);
  197 + return processSave(ctx, sdId, relationType);
202 198 } else {
203 199 return Futures.immediateFuture(true);
204 200 }
205 201 }, ctx.getDbCallbackExecutor());
206 202 }
207 203
208   - private ListenableFuture<Boolean> processSave(TbContext ctx, SearchDirectionIds sdId) {
  204 + private ListenableFuture<Boolean> processSave(TbContext ctx, SearchDirectionIds sdId, String relationType) {
209 205 return ctx.getRelationService().saveRelationAsync(ctx.getTenantId(), new EntityRelation(sdId.getFromId(), sdId.getToId(), relationType, RelationTypeGroup.COMMON));
210 206 }
211 207
... ...
... ... @@ -17,7 +17,6 @@ package org.thingsboard.rule.engine.action;
17 17
18 18 import com.google.common.util.concurrent.Futures;
19 19 import com.google.common.util.concurrent.ListenableFuture;
20   -import com.google.common.util.concurrent.MoreExecutors;
21 20 import lombok.extern.slf4j.Slf4j;
22 21 import org.thingsboard.rule.engine.api.RuleNode;
23 22 import org.thingsboard.rule.engine.api.TbContext;
... ... @@ -48,8 +47,6 @@ import java.util.List;
48 47 )
49 48 public class TbDeleteRelationNode extends TbAbstractRelationActionNode<TbDeleteRelationNodeConfiguration> {
50 49
51   - private String relationType;
52   -
53 50 @Override
54 51 protected TbDeleteRelationNodeConfiguration loadEntityNodeActionConfig(TbNodeConfiguration configuration) throws TbNodeException {
55 52 return TbNodeUtils.convert(configuration, TbDeleteRelationNodeConfiguration.class);
... ... @@ -61,21 +58,20 @@ public class TbDeleteRelationNode extends TbAbstractRelationActionNode<TbDeleteR
61 58 }
62 59
63 60 @Override
64   - protected ListenableFuture<RelationContainer> processEntityRelationAction(TbContext ctx, TbMsg msg) {
65   - return getRelationContainerListenableFuture(ctx, msg);
  61 + protected ListenableFuture<RelationContainer> processEntityRelationAction(TbContext ctx, TbMsg msg, String relationType) {
  62 + return getRelationContainerListenableFuture(ctx, msg, relationType);
66 63 }
67 64
68 65 @Override
69   - protected ListenableFuture<RelationContainer> doProcessEntityRelationAction(TbContext ctx, TbMsg msg, EntityContainer entityContainer) {
70   - return Futures.transform(processSingle(ctx, msg, entityContainer), result -> new RelationContainer(msg, result), MoreExecutors.directExecutor());
  66 + protected ListenableFuture<RelationContainer> doProcessEntityRelationAction(TbContext ctx, TbMsg msg, EntityContainer entityContainer, String relationType) {
  67 + return Futures.transform(processSingle(ctx, msg, entityContainer, relationType), result -> new RelationContainer(msg, result), ctx.getDbCallbackExecutor());
71 68 }
72 69
73   - private ListenableFuture<RelationContainer> getRelationContainerListenableFuture(TbContext ctx, TbMsg msg) {
74   - relationType = processPattern(msg, config.getRelationType());
  70 + private ListenableFuture<RelationContainer> getRelationContainerListenableFuture(TbContext ctx, TbMsg msg, String relationType) {
75 71 if (config.isDeleteForSingleEntity()) {
76   - return Futures.transformAsync(getEntity(ctx, msg), entityContainer -> doProcessEntityRelationAction(ctx, msg, entityContainer), MoreExecutors.directExecutor());
  72 + return Futures.transformAsync(getEntity(ctx, msg), entityContainer -> doProcessEntityRelationAction(ctx, msg, entityContainer, relationType), ctx.getDbCallbackExecutor());
77 73 } else {
78   - return Futures.transform(processList(ctx, msg), result -> new RelationContainer(msg, result), MoreExecutors.directExecutor());
  74 + return Futures.transform(processList(ctx, msg), result -> new RelationContainer(msg, result), ctx.getDbCallbackExecutor());
79 75 }
80 76 }
81 77
... ... @@ -95,23 +91,23 @@ public class TbDeleteRelationNode extends TbAbstractRelationActionNode<TbDeleteR
95 91 }
96 92 }
97 93 return Futures.immediateFuture(true);
98   - }, MoreExecutors.directExecutor());
  94 + }, ctx.getDbCallbackExecutor());
99 95 }
100   - }, MoreExecutors.directExecutor());
  96 + }, ctx.getDbCallbackExecutor());
101 97 }
102 98
103   - private ListenableFuture<Boolean> processSingle(TbContext ctx, TbMsg msg, EntityContainer entityContainer) {
  99 + private ListenableFuture<Boolean> processSingle(TbContext ctx, TbMsg msg, EntityContainer entityContainer, String relationType) {
104 100 SearchDirectionIds sdId = processSingleSearchDirection(msg, entityContainer);
105 101 return Futures.transformAsync(ctx.getRelationService().checkRelation(ctx.getTenantId(), sdId.getFromId(), sdId.getToId(), relationType, RelationTypeGroup.COMMON),
106 102 result -> {
107 103 if (result) {
108   - return processSingleDeleteRelation(ctx, sdId);
  104 + return processSingleDeleteRelation(ctx, sdId, relationType);
109 105 }
110 106 return Futures.immediateFuture(true);
111   - }, MoreExecutors.directExecutor());
  107 + }, ctx.getDbCallbackExecutor());
112 108 }
113 109
114   - private ListenableFuture<Boolean> processSingleDeleteRelation(TbContext ctx, SearchDirectionIds sdId) {
  110 + private ListenableFuture<Boolean> processSingleDeleteRelation(TbContext ctx, SearchDirectionIds sdId, String relationType) {
115 111 return ctx.getRelationService().deleteRelationAsync(ctx.getTenantId(), sdId.getFromId(), sdId.getToId(), relationType, RelationTypeGroup.COMMON);
116 112 }
117 113
... ...
... ... @@ -43,6 +43,8 @@ import { DashboardInfo } from '@shared/models/dashboard.models';
43 43 import { PageData } from '@app/shared/models/page/page-data';
44 44 import { AdminService } from '@core/http/admin.service';
45 45 import { ActionNotificationShow } from '@core/notification/notification.actions';
  46 +import { MatDialog, MatDialogConfig } from '@angular/material/dialog';
  47 +import { AlertDialogComponent } from '@shared/components/dialog/alert-dialog.component';
46 48
47 49 @Injectable({
48 50 providedIn: 'root'
... ... @@ -60,7 +62,8 @@ export class AuthService {
60 62 private utils: UtilsService,
61 63 private dashboardService: DashboardService,
62 64 private adminService: AdminService,
63   - private translate: TranslateService
  65 + private translate: TranslateService,
  66 + private dialog: MatDialog
64 67 ) {
65 68 }
66 69
... ... @@ -273,6 +276,7 @@ export class AuthService {
273 276 const refreshToken = this.utils.getQueryParam('refreshToken');
274 277 const username = this.utils.getQueryParam('username');
275 278 const password = this.utils.getQueryParam('password');
  279 + const loginError = this.utils.getQueryParam('loginError');
276 280 if (publicId) {
277 281 return this.publicLogin(publicId).pipe(
278 282 mergeMap((response) => {
... ... @@ -317,6 +321,10 @@ export class AuthService {
317 321 }
318 322 )
319 323 );
  324 + } else if (loginError) {
  325 + this.showLoginErrorDialog(loginError);
  326 + this.utils.updateQueryParam('loginError', null);
  327 + return throwError(Error());
320 328 }
321 329 return this.procceedJwtTokenValidate(doTokenRefresh);
322 330 } else {
... ... @@ -324,6 +332,22 @@ export class AuthService {
324 332 }
325 333 }
326 334
  335 + private showLoginErrorDialog(loginError: string) {
  336 + this.translate.get(['login.error', 'action.close']).subscribe(
  337 + (translations) => {
  338 + const dialogConfig: MatDialogConfig = {
  339 + disableClose: true,
  340 + data: {
  341 + title: translations['login.error'],
  342 + message: loginError,
  343 + ok: translations['action.close']
  344 + }
  345 + };
  346 + this.dialog.open(AlertDialogComponent, dialogConfig);
  347 + }
  348 + );
  349 + }
  350 +
327 351 private procceedJwtTokenValidate(doTokenRefresh?: boolean): Observable<AuthPayload> {
328 352 const loadUserSubject = new ReplaySubject<AuthPayload>();
329 353 this.validateJwtToken(doTokenRefresh).subscribe(
... ...
... ... @@ -84,15 +84,15 @@ export class AuthGuard implements CanActivate, CanActivateChild {
84 84 // this.authService.gotoDefaultPlace(false);
85 85 return of(this.authService.defaultUrl(false));
86 86 } else {
87   - const tasks: Observable<any>[] = [];
88 87 if (path === 'login') {
89   - tasks.push(this.authService.loadOAuth2Clients());
  88 + return forkJoin([this.authService.loadOAuth2Clients()]).pipe(
  89 + map(() => {
  90 + return true;
  91 + })
  92 + );
  93 + } else {
  94 + return of(true);
90 95 }
91   - return forkJoin(tasks).pipe(
92   - map(() => {
93   - return true;
94   - })
95   - );
96 96 }
97 97 } else {
98 98 if (authState.authUser.isPublic) {
... ...
... ... @@ -345,6 +345,10 @@ export class UtilsService {
345 345 return additionalDataKey;
346 346 }
347 347
  348 + public createLabelFromDatasource(datasource: Datasource, pattern: string): string {
  349 + return createLabelFromDatasource(datasource, pattern);
  350 + }
  351 +
348 352 public generateColors(datasources: Array<Datasource>) {
349 353 let index = 0;
350 354 datasources.forEach((datasource) => {
... ...
... ... @@ -460,7 +460,7 @@ export function insertVariable(pattern: string, name: string, value: any): strin
460 460 return result;
461 461 }
462 462
463   -export function createLabelFromDatasource(datasource: Datasource, pattern: string) {
  463 +export function createLabelFromDatasource(datasource: Datasource, pattern: string): string {
464 464 let label = pattern;
465 465 if (!datasource) {
466 466 return label;
... ...
... ... @@ -100,6 +100,8 @@ export type MarkerSettings = {
100 100 tooltipFunction: GenericFunction;
101 101 labelFunction: GenericFunction;
102 102 markerImageFunction?: MarkerImageFunction;
  103 + markerOffsetX: number;
  104 + markerOffsetY: number;
103 105 }
104 106
105 107 export interface FormattedData {
... ...
... ... @@ -97,7 +97,7 @@ export class MapWidgetController implements MapWidgetInterface {
97 97 const schema = initSchema();
98 98 addToSchema(schema, this.getProvidersSchema(mapProvider));
99 99 addGroupInfo(schema, 'Map Provider Settings');
100   - addToSchema(schema, addCondition(commonMapSettingsSchema, 'model.provider !== "image-map"'));
  100 + addToSchema(schema, commonMapSettingsSchema);
101 101 addGroupInfo(schema, 'Common Map Settings');
102 102 addToSchema(schema, addCondition(mapPolygonSchema, 'model.showPolygon === true', ['showPolygon']));
103 103 addGroupInfo(schema, 'Polygon Settings');
... ...
... ... @@ -109,8 +109,10 @@ export function aspectCache(imageUrl: string): Observable<number> {
109 109 }
110 110 }
111 111
  112 +export type TranslateFunc = (key: string, defaultTranslation?: string) => string;
  113 +
112 114 function parseTemplate(template: string, data: { $datasource?: Datasource, [key: string]: any },
113   - translateFn?: (key: string) => string) {
  115 + translateFn?: TranslateFunc) {
114 116 let res = '';
115 117 try {
116 118 if (template.match(/<link-act/g)) {
... ... @@ -146,8 +148,6 @@ function parseTemplate(template: string, data: { $datasource?: Datasource, [key:
146 148 return res;
147 149 }
148 150
149   -type TranslateFunc = (key: string, defaultTranslation?: string) => string;
150   -
151 151 export const parseWithTranslation = {
152 152
153 153 translateFn: null,
... ...
... ... @@ -18,10 +18,12 @@ import L, { LeafletMouseEvent } from 'leaflet';
18 18 import { FormattedData, MarkerSettings } from './map-models';
19 19 import { aspectCache, createTooltip, parseWithTranslation, safeExecute } from './maps-utils';
20 20 import tinycolor from 'tinycolor2';
  21 +import { isDefined } from '@core/utils';
21 22
22 23 export class Marker {
23 24 leafletMarker: L.Marker;
24 25 tooltipOffset: [number, number];
  26 + markerOffset: [number, number];
25 27 tooltip: L.Popup;
26 28 location: L.LatLngExpression;
27 29 data: FormattedData;
... ... @@ -34,9 +36,14 @@ export class Marker {
34 36 draggable: settings.draggableMarker
35 37 });
36 38
  39 + this.markerOffset = [
  40 + isDefined(settings.markerOffsetX) ? settings.markerOffsetX : 0.5,
  41 + isDefined(settings.markerOffsetY) ? settings.markerOffsetY : 1,
  42 + ];
  43 +
37 44 this.createMarkerIcon((iconInfo) => {
38 45 this.leafletMarker.setIcon(iconInfo.icon);
39   - this.tooltipOffset = [0, -iconInfo.size[1] + 10];
  46 + this.tooltipOffset = [0, -iconInfo.size[1] * this.markerOffset[1] + 10];
40 47 this.updateMarkerLabel(settings);
41 48 });
42 49
... ... @@ -95,7 +102,7 @@ export class Marker {
95 102 updateMarkerIcon(settings: MarkerSettings) {
96 103 this.createMarkerIcon((iconInfo) => {
97 104 this.leafletMarker.setIcon(iconInfo.icon);
98   - this.tooltipOffset = [0, -iconInfo.size[1] + 10];
  105 + this.tooltipOffset = [0, -iconInfo.size[1] * this.markerOffset[1] + 10];
99 106 this.updateMarkerLabel(settings);
100 107 });
101 108 }
... ... @@ -129,7 +136,7 @@ export class Marker {
129 136 const icon = L.icon({
130 137 iconUrl: currentImage.url,
131 138 iconSize: [width, height],
132   - iconAnchor: [width / 2, height],
  139 + iconAnchor: [width * this.markerOffset[0], height * this.markerOffset[1]],
133 140 popupAnchor: [0, -height]
134 141 });
135 142 const iconInfo = {
... ... @@ -151,7 +158,7 @@ export class Marker {
151 158 const icon = L.icon({
152 159 iconUrl: 'https://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|' + color,
153 160 iconSize: [21, 34],
154   - iconAnchor: [10, 34],
  161 + iconAnchor: [21 * this.markerOffset[0], 34 * this.markerOffset[1]],
155 162 popupAnchor: [0, -34],
156 163 shadowUrl: 'https://chart.apis.google.com/chart?chst=d_map_pin_shadow',
157 164 shadowSize: [40, 37],
... ...
... ... @@ -30,10 +30,11 @@ export class ImageMap extends LeafletMap {
30 30 width = 0;
31 31 height = 0;
32 32 imageUrl;
  33 + posFunction;
33 34
34 35 constructor($container: HTMLElement, options: UnitedMapSettings) {
35 36 super($container, options);
36   - options.posFunction = parseFunction(options.posFunction, ['origXPos', 'origYPos']) as ((origXPos, origYPos) => { x, y });
  37 + this.posFunction = parseFunction(options.posFunction, ['origXPos', 'origYPos']) as ((origXPos, origYPos) => { x, y });
37 38 this.imageUrl = options.mapUrl;
38 39 aspectCache(this.imageUrl).subscribe(aspect => {
39 40 this.aspect = aspect;
... ... @@ -132,9 +133,10 @@ export class ImageMap extends LeafletMap {
132 133
133 134 convertPosition(expression): L.LatLng {
134 135 if (isNaN(expression[this.options.xPosKeyName]) || isNaN(expression[this.options.yPosKeyName])) return null;
  136 + Object.assign(expression, this.posFunction(expression[this.options.xPosKeyName], expression[this.options.yPosKeyName]))
135 137 return this.pointToLatLng(
136   - expression[this.options.xPosKeyName] * this.width,
137   - expression[this.options.yPosKeyName] * this.height);
  138 + expression.x * this.width,
  139 + expression.y * this.height);
138 140 }
139 141
140 142 pointToLatLng(x, y): L.LatLng {
... ...
... ... @@ -275,6 +275,16 @@ export const commonMapSettingsSchema =
275 275 type: 'string',
276 276 default: 'longitude'
277 277 },
  278 + xPosKeyName: {
  279 + title: 'X position key name',
  280 + type: 'string',
  281 + default: 'xPos'
  282 + },
  283 + yPosKeyName: {
  284 + title: 'Y position key name',
  285 + type: 'string',
  286 + default: 'yPos'
  287 + },
278 288 showLabel: {
279 289 title: 'Show label',
280 290 type: 'boolean',
... ... @@ -323,6 +333,21 @@ export const commonMapSettingsSchema =
323 333 title: 'Tooltip function: f(data, dsData, dsIndex)',
324 334 type: 'string'
325 335 },
  336 + posFunction: {
  337 + title: 'Position conversion function: f(origXPos, origYPos), should return x,y coordinates as double from 0 to 1 each',
  338 + type: 'string',
  339 + default: 'return {x: origXPos, y: origYPos};'
  340 + },
  341 + markerOffsetX: {
  342 + title: 'Marker X offset relative to position',
  343 + type: 'number',
  344 + default: 0.5
  345 + },
  346 + markerOffsetY: {
  347 + title: 'Marker Y offset relative to position',
  348 + type: 'number',
  349 + default: 1
  350 + },
326 351 color: {
327 352 title: 'Color',
328 353 type: 'string'
... ... @@ -366,14 +391,40 @@ export const commonMapSettingsSchema =
366 391 required: []
367 392 },
368 393 form: [
369   - 'defaultZoomLevel',
370   - 'useDefaultCenterPosition',
371   - 'defaultCenterPosition',
372   - 'fitMapBounds',
  394 + {
  395 + key: 'defaultZoomLevel',
  396 + condition: 'model.provider !== "image-map"'
  397 + },
  398 + {
  399 + key: 'useDefaultCenterPosition',
  400 + condition: 'model.provider !== "image-map"'
  401 + },
  402 + {
  403 + key: 'defaultCenterPosition',
  404 + condition: 'model.provider !== "image-map"'
  405 + },
  406 + {
  407 + key: 'fitMapBounds',
  408 + condition: 'model.provider !== "image-map"'
  409 + },
373 410 'draggableMarker',
374 411 'disableScrollZooming',
375   - 'latKeyName',
376   - 'lngKeyName',
  412 + {
  413 + key: 'latKeyName',
  414 + condition: 'model.provider !== "image-map"'
  415 + },
  416 + {
  417 + key: 'lngKeyName',
  418 + condition: 'model.provider !== "image-map"'
  419 + },
  420 + {
  421 + key: 'xPosKeyName',
  422 + condition: 'model.provider === "image-map"'
  423 + },
  424 + {
  425 + key: 'yPosKeyName',
  426 + condition: 'model.provider === "image-map"'
  427 + },
377 428 'showLabel',
378 429 'label',
379 430 'useLabelFunction',
... ... @@ -408,6 +459,19 @@ export const commonMapSettingsSchema =
408 459 type: 'javascript'
409 460 },
410 461 {
  462 + key: 'markerOffsetX',
  463 + condition: 'model.provider === "image-map"'
  464 + },
  465 + {
  466 + key: 'markerOffsetY',
  467 + condition: 'model.provider === "image-map"'
  468 + },
  469 + {
  470 + key: 'posFunction',
  471 + type: 'javascript',
  472 + condition: 'model.provider === "image-map"'
  473 + },
  474 + {
411 475 key: 'color',
412 476 type: 'color'
413 477 },
... ... @@ -654,123 +718,6 @@ export const imageMapSettingsSchema =
654 718 title: 'Image URL source entity attribute',
655 719 type: 'string',
656 720 default: ''
657   - },
658   - disableScrollZooming: {
659   - title: 'Disable scroll zooming',
660   - type: 'boolean',
661   - default: false
662   - },
663   - xPosKeyName: {
664   - title: 'X position key name',
665   - type: 'string',
666   - default: 'xPos'
667   - },
668   - yPosKeyName: {
669   - title: 'Y position key name',
670   - type: 'string',
671   - default: 'yPos'
672   - },
673   - showLabel: {
674   - title: 'Show label',
675   - type: 'boolean',
676   - default: true
677   - },
678   - label: {
679   - title: 'Label (pattern examples: \'${entityName}\', \'${entityName}: (Text ${keyName} units.)\' )',
680   - type: 'string',
681   - default: '${entityName}'
682   - },
683   - useLabelFunction: {
684   - title: 'Use label function',
685   - type: 'boolean',
686   - default: false
687   - },
688   - labelFunction: {
689   - title: 'Label function: f(data, dsData, dsIndex)',
690   - type: 'string'
691   - },
692   - showTooltip: {
693   - title: 'Show tooltip',
694   - type: 'boolean',
695   - default: true
696   - },
697   - showTooltipAction: {
698   - title: 'Action for displaying the tooltip',
699   - type: 'string',
700   - default: 'click'
701   - },
702   - autocloseTooltip: {
703   - title: 'Auto-close tooltips',
704   - type: 'boolean',
705   - default: true
706   - },
707   - tooltipPattern: {
708   - title: 'Tooltip (for ex. \'Text ${keyName} units.\' or <link-act name=\'my-action\'>Link text</link-act>\')',
709   - type: 'string',
710   - default: '<b>${entityName}</b><br/><br/><b>X Pos:</b> ${xPos:2}<br/><b>Y Pos:</b> ${yPos:2}'
711   - },
712   - useTooltipFunction: {
713   - title: 'Use tooltip function',
714   - type: 'boolean',
715   - default: false
716   - },
717   - tooltipFunction: {
718   - title: 'Tooltip function: f(data, dsData, dsIndex)',
719   - type: 'string'
720   - },
721   - color: {
722   - title: 'Color',
723   - type: 'string'
724   - },
725   - posFunction: {
726   - title: 'Position conversion function: f(origXPos, origYPos), should return x,y coordinates as double from 0 to 1 each',
727   - type: 'string',
728   - default: 'return {x: origXPos, y: origYPos};'
729   - },
730   - markerOffsetX: {
731   - title: 'Marker X offset relative to position',
732   - type: 'number',
733   - default: 0.5
734   - },
735   - markerOffsetY: {
736   - title: 'Marker Y offset relative to position',
737   - type: 'number',
738   - default: 1
739   - },
740   - useColorFunction: {
741   - title: 'Use color function',
742   - type: 'boolean',
743   - default: false
744   - },
745   - colorFunction: {
746   - title: 'Color function: f(data, dsData, dsIndex)',
747   - type: 'string'
748   - },
749   - markerImage: {
750   - title: 'Custom marker image',
751   - type: 'string'
752   - },
753   - markerImageSize: {
754   - title: 'Custom marker image size (px)',
755   - type: 'number',
756   - default: 34
757   - },
758   - useMarkerImageFunction: {
759   - title: 'Use marker image function',
760   - type: 'boolean',
761   - default: false
762   - },
763   - markerImageFunction: {
764   - title: 'Marker image function: f(data, images, dsData, dsIndex)',
765   - type: 'string'
766   - },
767   - markerImages: {
768   - title: 'Marker images',
769   - type: 'array',
770   - items: {
771   - title: 'Marker image',
772   - type: 'string'
773   - }
774 721 }
775 722 },
776 723 required: []
... ... @@ -781,77 +728,7 @@ export const imageMapSettingsSchema =
781 728 type: 'image'
782 729 },
783 730 'imageEntityAlias',
784   - 'imageUrlAttribute',
785   - 'disableScrollZooming',
786   - 'xPosKeyName',
787   - 'yPosKeyName',
788   - 'showLabel',
789   - 'label',
790   - 'useLabelFunction',
791   - {
792   - key: 'labelFunction',
793   - type: 'javascript'
794   - },
795   - 'showTooltip',
796   - {
797   - key: 'showTooltipAction',
798   - type: 'rc-select',
799   - multiple: false,
800   - items: [
801   - {
802   - value: 'click',
803   - label: 'Show tooltip on click (Default)'
804   - },
805   - {
806   - value: 'hover',
807   - label: 'Show tooltip on hover'
808   - }
809   - ]
810   - },
811   - 'autocloseTooltip',
812   - {
813   - key: 'tooltipPattern',
814   - type: 'textarea'
815   - },
816   - 'useTooltipFunction',
817   - {
818   - key: 'tooltipFunction',
819   - type: 'javascript'
820   - },
821   - {
822   - key: 'color',
823   - type: 'color'
824   - },
825   - {
826   - key: 'posFunction',
827   - type: 'javascript'
828   - },
829   - 'markerOffsetX',
830   - 'markerOffsetY',
831   - 'useColorFunction',
832   - {
833   - key: 'colorFunction',
834   - type: 'javascript'
835   - },
836   - {
837   - key: 'markerImage',
838   - type: 'image'
839   - },
840   - 'markerImageSize',
841   - 'useMarkerImageFunction',
842   - {
843   - key: 'markerImageFunction',
844   - type: 'javascript'
845   - },
846   - {
847   - key: 'markerImages',
848   - items: [
849   - {
850   - key: 'markerImages[]',
851   - type: 'image'
852   - }
853   - ]
854   - }
  731 + 'imageUrlAttribute'
855 732 ]
856 733 };
857 734
... ...
... ... @@ -199,9 +199,8 @@ export class EntityStateControllerComponent extends StateControllerComponent imp
199 199 let stateName = dashboardState.name;
200 200 stateName = this.utils.customTranslation(stateName, stateName);
201 201 const params = this.stateObject[index].params;
202   - const targetParams = params && params.targetEntityParamName ? params[params.targetEntityParamName] : params;
203   - const entityName = targetParams && targetParams.entityName ? targetParams.entityName : '';
204   - const entityLabel = targetParams && targetParams.entityLabel ? targetParams.entityLabel : '';
  202 + const entityName = params && params.entityName ? params.entityName : '';
  203 + const entityLabel = params && params.entityLabel ? params.entityLabel : '';
205 204 result = insertVariable(stateName, 'entityName', entityName);
206 205 result = insertVariable(result, 'entityLabel', entityLabel);
207 206 for (const prop of Object.keys(params)) {
... ...
... ... @@ -56,10 +56,10 @@
56 56 <div class="line"><mat-divider></mat-divider></div>
57 57 </div>
58 58 <ng-container *ngFor="let oauth2Client of oauth2Clients">
59   - <button mat-raised-button color="primary" class="centered" routerLink="{{ oauth2Client.url }}">
60   - <mat-icon class="material-icons md-18" svgIcon="{{ oauth2Client.icon }}"></mat-icon>
  59 + <a mat-raised-button color="warn" class="centered" href="{{ oauth2Client.url }}">
  60 + <mat-icon svgIcon="{{ oauth2Client.icon }}"></mat-icon>
61 61 {{ 'login.login-with' | translate: {name: oauth2Client.name} }}
62   - </button>
  62 + </a>
63 63 </ng-container>
64 64 </div>
65 65 </div>
... ...
... ... @@ -65,11 +65,17 @@
65 65 min-width: 20px;
66 66 }
67 67
  68 + a.centered {
  69 + &:hover {
  70 + border-bottom: 0px;
  71 + }
  72 + }
68 73
69 74 .centered ::ng-deep .mat-button-wrapper {
70 75 display: flex;
71 76 justify-content: center;
72 77 align-items: center;
  78 + text-transform: uppercase;
73 79 }
74 80 }
75 81 }
... ...
... ... @@ -1355,7 +1355,8 @@
1355 1355 "password-link-sent-message": "Password reset link was successfully sent!",
1356 1356 "email": "Email",
1357 1357 "login-with": "Login with {{name}}",
1358   - "or": "or"
  1358 + "or": "or",
  1359 + "error": "Login error"
1359 1360 },
1360 1361 "position": {
1361 1362 "top": "Top",
... ...
... ... @@ -22,7 +22,7 @@ export default angular.module('thingsboard.api.user', [thingsboardApiLogin,
22 22 .name;
23 23
24 24 /*@ngInject*/
25   -function UserService($http, $q, $rootScope, adminService, dashboardService, timeService, loginService, toast, store, jwtHelper, $translate, $state, $location) {
  25 +function UserService($http, $q, $rootScope, adminService, dashboardService, timeService, loginService, toast, store, jwtHelper, $translate, $state, $location, $mdDialog) {
26 26 var currentUser = null,
27 27 currentUserDetails = null,
28 28 lastPublicDashboardId = null,
... ... @@ -406,6 +406,10 @@ function UserService($http, $q, $rootScope, adminService, dashboardService, time
406 406 }, function fail() {
407 407 deferred.reject();
408 408 });
  409 + } else if (locationSearch.loginError) {
  410 + showLoginErrorDialog(locationSearch.loginError);
  411 + $location.search('loginError', null);
  412 + deferred.reject();
409 413 } else {
410 414 procceedJwtTokenValidate();
411 415 }
... ... @@ -415,6 +419,17 @@ function UserService($http, $q, $rootScope, adminService, dashboardService, time
415 419 return deferred.promise;
416 420 }
417 421
  422 + function showLoginErrorDialog(loginError) {
  423 + $translate(['login.error',
  424 + 'action.close']).then(function (translations) {
  425 + var alert = $mdDialog.alert()
  426 + .title(translations['login.error'])
  427 + .htmlContent(loginError)
  428 + .ok(translations['action.close']);
  429 + $mdDialog.show(alert);
  430 + });
  431 + }
  432 +
418 433 function loadIsUserTokenAccessEnabled() {
419 434 var deferred = $q.defer();
420 435 if (currentUser.authority === 'SYS_ADMIN' || currentUser.authority === 'TENANT_ADMIN') {
... ...
... ... @@ -1334,7 +1334,8 @@
1334 1334 "password-link-sent-message": "Password reset link was successfully sent!",
1335 1335 "email": "Email",
1336 1336 "login-with": "Login with {{name}}",
1337   - "or": "or"
  1337 + "or": "or",
  1338 + "error": "Login error"
1338 1339 },
1339 1340 "position": {
1340 1341 "top": "Top",
... ...
... ... @@ -51,7 +51,7 @@
51 51 <div class="text mat-typography">{{ "login.or" | translate | uppercase }}</div>
52 52 <div class="line"><md-divider></md-divider></div>
53 53 </div>
54   - <md-button ng-repeat="oauth2Client in oauth2Clients" class="md-raised"
  54 + <md-button ng-repeat="oauth2Client in oauth2Clients" class="md-raised md-accent md-hue-2"
55 55 layout="row" layout-align="center center" ng-href="{{ oauth2Client.url }}" target="_self">
56 56 <md-icon class="material-icons md-18" md-svg-icon="{{ oauth2Client.icon }}"></md-icon>
57 57 {{ 'login.login-with' | translate: {name: oauth2Client.name} }}
... ...
... ... @@ -94,7 +94,7 @@ export default class TbGoogleMap {
94 94 window[this.initMapFunctionName] = function() { // eslint-disable-line no-undef, angular/window-service
95 95 lazyLoad.load([ // eslint-disable-line no-undef
96 96 { type: 'js', path: 'https://unpkg.com/@google/markerwithlabel@1.2.3/src/markerwithlabel.js' },
97   - { type: 'js', path: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js' }
  97 + { type: 'js', path: 'https://unpkg.com/@google/markerclustererplus@4.0.1/dist/markerclustererplus.min.js' }
98 98 ]).then(
99 99 function success() {
100 100 gmGlobals.gmApiKeys[tbMap.apiKey].loaded = true;
... ...