Browse Source

Improvement/lwm2m/refactoring 1 (#3956)

UI: Refactoring lwm2m
pull/3980/head
Vladyslav 6 years ago
committed by GitHub
parent
commit
cd6a76de86
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 21
      ui-ngx/src/app/core/http/device-profile.service.ts
  2. 3
      ui-ngx/src/app/modules/home/components/device/device-credentials.component.html
  3. 37
      ui-ngx/src/app/modules/home/components/device/device-credentials.component.ts
  4. 2
      ui-ngx/src/app/modules/home/components/home-components.module.ts
  5. 57
      ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-device-config-server.component.html
  6. 45
      ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-device-config-server.component.ts
  7. 9
      ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-device-profile-transport-configuration.component.html
  8. 269
      ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-device-profile-transport-configuration.component.ts
  9. 1
      ui-ngx/src/app/modules/home/pages/device/lwm2m/security-config.models.ts

21
ui-ngx/src/app/core/http/device-profile.service.ts

@ -22,9 +22,7 @@ import { Observable } from 'rxjs';
import { PageData } from '@shared/models/page/page-data'; import { PageData } from '@shared/models/page/page-data';
import { DeviceProfile, DeviceProfileInfo, DeviceTransportType } from '@shared/models/device.models'; import { DeviceProfile, DeviceProfileInfo, DeviceTransportType } from '@shared/models/device.models';
import { isDefinedAndNotNull } from '@core/utils'; import { isDefinedAndNotNull } from '@core/utils';
import { import { ObjectLwM2M, ServerSecurityConfig } from '@home/components/profile/device/lwm2m/profile-config.models';
ObjectLwM2M, ServerSecurityConfig
} from "../../modules/home/components/profile/device/lwm2m/profile-config.models";
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root'
@ -43,16 +41,23 @@ export class DeviceProfileService {
return this.http.get<DeviceProfile>(`/api/deviceProfile/${deviceProfileId}`, defaultHttpOptionsFromConfig(config)); return this.http.get<DeviceProfile>(`/api/deviceProfile/${deviceProfileId}`, defaultHttpOptionsFromConfig(config));
} }
public getLwm2mObjects(objectIds: number [], config?: RequestConfig): Observable<ObjectLwM2M[]> { public getLwm2mObjects(objectIds: number[], config?: RequestConfig): Observable<Array<ObjectLwM2M>> {
return this.http.get<ObjectLwM2M[]>(`/api/lwm2m/deviceProfile/${objectIds}`, defaultHttpOptionsFromConfig(config)); return this.http.get<Array<ObjectLwM2M>>(`/api/lwm2m/deviceProfile/${objectIds}`, defaultHttpOptionsFromConfig(config));
} }
public getLwm2mBootstrapSecurityInfo(securityMode: string, bootstrapServerIs: boolean, config?: RequestConfig): Observable<ServerSecurityConfig> { public getLwm2mBootstrapSecurityInfo(securityMode: string, bootstrapServerIs: boolean,
return this.http.get<ServerSecurityConfig>(`/api/lwm2m/deviceProfile/bootstrap/${securityMode}/${bootstrapServerIs}`, defaultHttpOptionsFromConfig(config)); config?: RequestConfig): Observable<ServerSecurityConfig> {
return this.http.get<ServerSecurityConfig>(
`/api/lwm2m/deviceProfile/bootstrap/${securityMode}/${bootstrapServerIs}`,
defaultHttpOptionsFromConfig(config)
);
} }
public getLwm2mObjectsPage(pageLink: PageLink, config?: RequestConfig): Observable<PageData<ObjectLwM2M>> { public getLwm2mObjectsPage(pageLink: PageLink, config?: RequestConfig): Observable<PageData<ObjectLwM2M>> {
return this.http.get<PageData<ObjectLwM2M>>(`/api/lwm2m/deviceProfile/objects${pageLink.toQuery()}`, defaultHttpOptionsFromConfig(config)); return this.http.get<PageData<ObjectLwM2M>>(
`/api/lwm2m/deviceProfile/objects${pageLink.toQuery()}`,
defaultHttpOptionsFromConfig(config)
);
} }
public saveDeviceProfile(deviceProfile: DeviceProfile, config?: RequestConfig): Observable<DeviceProfile> { public saveDeviceProfile(deviceProfile: DeviceProfile, config?: RequestConfig): Observable<DeviceProfile> {

3
ui-ngx/src/app/modules/home/components/device/device-credentials.component.html

@ -90,9 +90,8 @@
</mat-error> </mat-error>
<div mat-dialog-actions fxLayoutAlign="center center"> <div mat-dialog-actions fxLayoutAlign="center center">
<button mat-raised-button color="primary" <button mat-raised-button color="primary"
[disabled]="false"
matTooltip="{{'device.lwm2m-value-edit-tip' | translate }}" matTooltip="{{'device.lwm2m-value-edit-tip' | translate }}"
(click)="openSecurityInfoLwM2mDialog($event, deviceCredentialsFormGroup.get('credentialsValue').value, deviceCredentialsFormGroup.get('credentialsId').value )" (click)="openSecurityInfoLwM2mDialog($event)"
> >
{{'device.lwm2m-value-edit' | translate }} {{'device.lwm2m-value-edit' | translate }}
</button> </button>

37
ui-ngx/src/app/modules/home/components/device/device-credentials.component.ts

@ -14,7 +14,7 @@
/// limitations under the License. /// limitations under the License.
/// ///
import { Component, forwardRef, Inject, Input, OnDestroy, OnInit } from '@angular/core'; import { Component, forwardRef, Input, OnDestroy, OnInit } from '@angular/core';
import { import {
ControlValueAccessor, ControlValueAccessor,
FormBuilder, FormBuilder,
@ -41,8 +41,7 @@ import {
DeviceCredentialsDialogLwm2mData, DeviceCredentialsDialogLwm2mData,
END_POINT, END_POINT,
getDefaultSecurityConfig, getDefaultSecurityConfig,
JSON_ALL_CONFIG, JSON_ALL_CONFIG
SecurityConfigModels
} from '@home/pages/device/lwm2m/security-config.models'; } from '@home/pages/device/lwm2m/security-config.models';
import { TranslateService } from '@ngx-translate/core'; import { TranslateService } from '@ngx-translate/core';
import { MatDialog } from '@angular/material/dialog'; import { MatDialog } from '@angular/material/dialog';
@ -197,6 +196,7 @@ export class DeviceCredentialsComponent implements ControlValueAccessor, OnInit,
this.deviceCredentialsFormGroup.get('credentialsBasic').disable({emitEvent: false}); this.deviceCredentialsFormGroup.get('credentialsBasic').disable({emitEvent: false});
break; break;
case DeviceCredentialsType.X509_CERTIFICATE: case DeviceCredentialsType.X509_CERTIFICATE:
case DeviceCredentialsType.LWM2M_CREDENTIALS:
this.deviceCredentialsFormGroup.get('credentialsValue').setValidators([Validators.required]); this.deviceCredentialsFormGroup.get('credentialsValue').setValidators([Validators.required]);
this.deviceCredentialsFormGroup.get('credentialsValue').updateValueAndValidity({emitEvent: false}); this.deviceCredentialsFormGroup.get('credentialsValue').updateValueAndValidity({emitEvent: false});
this.deviceCredentialsFormGroup.get('credentialsId').setValidators([]); this.deviceCredentialsFormGroup.get('credentialsId').setValidators([]);
@ -211,13 +211,6 @@ export class DeviceCredentialsComponent implements ControlValueAccessor, OnInit,
this.deviceCredentialsFormGroup.get('credentialsValue').setValidators([]); this.deviceCredentialsFormGroup.get('credentialsValue').setValidators([]);
this.deviceCredentialsFormGroup.get('credentialsValue').updateValueAndValidity({emitEvent: false}); this.deviceCredentialsFormGroup.get('credentialsValue').updateValueAndValidity({emitEvent: false});
break; break;
case DeviceCredentialsType.LWM2M_CREDENTIALS:
this.deviceCredentialsFormGroup.get('credentialsValue').setValidators([Validators.required]);
this.deviceCredentialsFormGroup.get('credentialsValue').updateValueAndValidity({emitEvent: false});
this.deviceCredentialsFormGroup.get('credentialsId').setValidators([]);
this.deviceCredentialsFormGroup.get('credentialsId').updateValueAndValidity({emitEvent: false});
this.deviceCredentialsFormGroup.get('credentialsBasic').disable({emitEvent: false});
break;
} }
} }
@ -245,27 +238,39 @@ export class DeviceCredentialsComponent implements ControlValueAccessor, OnInit,
}); });
} }
openSecurityInfoLwM2mDialog($event: Event, value: string, id: string): void { openSecurityInfoLwM2mDialog($event: Event): void {
if ($event) { if ($event) {
$event.stopPropagation(); $event.stopPropagation();
$event.preventDefault(); $event.preventDefault();
} }
let credentialsValue = this.deviceCredentialsFormGroup.get('credentialsValue').value;
if (credentialsValue === null || credentialsValue.length === 0) {
credentialsValue = getDefaultSecurityConfig();
} else {
credentialsValue = JSON.parse(credentialsValue);
}
const credentialsId = this.deviceCredentialsFormGroup.get('credentialsId').value || DEFAULT_END_POINT;
this.dialog.open<SecurityConfigComponent, DeviceCredentialsDialogLwm2mData, object>(SecurityConfigComponent, { this.dialog.open<SecurityConfigComponent, DeviceCredentialsDialogLwm2mData, object>(SecurityConfigComponent, {
disableClose: true, disableClose: true,
panelClass: ['tb-dialog', 'tb-fullscreen-dialog'], panelClass: ['tb-dialog', 'tb-fullscreen-dialog'],
data: { data: {
jsonAllConfig: (value === null || value.length === 0) ? getDefaultSecurityConfig() as SecurityConfigModels : JSON.parse(value) as SecurityConfigModels, jsonAllConfig: credentialsValue,
endPoint: (id === null) ? DEFAULT_END_POINT : id, endPoint: credentialsId
isNew: (id === null || value === null || value.length === 0)
} }
}).afterClosed().subscribe( }).afterClosed().subscribe(
(res) => { (res) => {
if (res) { if (res) {
this.deviceCredentialsFormGroup.get('credentialsValue').patchValue((Object.keys(res[JSON_ALL_CONFIG]).length === 0 || JSON.stringify(res[JSON_ALL_CONFIG]) === "[{}]") ? null : JSON.stringify(res[JSON_ALL_CONFIG])); this.deviceCredentialsFormGroup.patchValue({
this.deviceCredentialsFormGroup.get('credentialsId').patchValue((Object.keys(res[END_POINT]).length === 0 || JSON.stringify(res[END_POINT]) === "[{}]") ? null : JSON.stringify(res[END_POINT]).split('\"').join('')); credentialsValue: this.isDefautLw2mResponse(res[JSON_ALL_CONFIG]) ? null : JSON.stringify(res[JSON_ALL_CONFIG]),
credentialsId: this.isDefautLw2mResponse(res[END_POINT]) ? null : JSON.stringify(res[END_POINT]).split('\"').join('')
});
this.deviceCredentialsFormGroup.get('credentialsValue').markAsDirty(); this.deviceCredentialsFormGroup.get('credentialsValue').markAsDirty();
} }
} }
); );
} }
private isDefautLw2mResponse(response: object): boolean {
return Object.keys(response).length === 0 || JSON.stringify(response) === '[{}]';
}
} }

2
ui-ngx/src/app/modules/home/components/home-components.module.ts

@ -307,7 +307,7 @@ import { Lwm2mProfileComponentsModule } from '@home/components/profile/device/lw
EditAlarmDetailsDialogComponent, EditAlarmDetailsDialogComponent,
DeviceProfileProvisionConfigurationComponent, DeviceProfileProvisionConfigurationComponent,
AlarmScheduleComponent, AlarmScheduleComponent,
Lwm2mProfileComponentsModule, // Lwm2mProfileComponentsModule,
SmsProviderConfigurationComponent, SmsProviderConfigurationComponent,
AwsSnsProviderConfigurationComponent, AwsSnsProviderConfigurationComponent,
TwilioSmsProviderConfigurationComponent TwilioSmsProviderConfigurationComponent

57
ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-device-config-server.component.html

@ -21,10 +21,9 @@
<div fxLayout="row" fxLayoutGap="8px"> <div fxLayout="row" fxLayoutGap="8px">
<mat-form-field class="mat-block"> <mat-form-field class="mat-block">
<mat-label>{{ 'device-profile.lwm2m.mode' | translate }}</mat-label> <mat-label>{{ 'device-profile.lwm2m.mode' | translate }}</mat-label>
<mat-select formControlName="securityMode" <mat-select formControlName="securityMode">
[ngSwitch]="securityConfigLwM2MTypes">
<mat-option *ngFor="let securityMode of securityConfigLwM2MTypes" <mat-option *ngFor="let securityMode of securityConfigLwM2MTypes"
[value]="securityMode" > [value]="securityMode">
{{ credentialTypeLwM2MNamesMap.get(securityConfigLwM2MType[securityMode]) }} {{ credentialTypeLwM2MNamesMap.get(securityConfigLwM2MType[securityMode]) }}
</mat-option> </mat-option>
</mat-select> </mat-select>
@ -87,33 +86,31 @@
{{ 'device-profile.lwm2m.bootstrap-server' | translate }} {{ 'device-profile.lwm2m.bootstrap-server' | translate }}
</mat-checkbox> </mat-checkbox>
</div> </div>
<div [fxShow]="serverFormGroup.get('securityMode').value !== securityConfigLwM2MType.NO_SEC"> <div *ngIf="serverFormGroup.get('securityMode').value === securityConfigLwM2MType.RPK ||
<div serverFormGroup.get('securityMode').value === securityConfigLwM2MType.X509">
[fxShow]="serverFormGroup.get('securityMode').value === securityConfigLwM2MType.RPK || <mat-form-field class="mat-block">
serverFormGroup.get('securityMode').value === securityConfigLwM2MType.X509"> <mat-label>{{ 'device-profile.lwm2m.server-public-key' | translate }}</mat-label>
<mat-form-field class="mat-block"> <textarea matInput type="text" rows="3" cols="1" required
<mat-label>{{ 'device-profile.lwm2m.server-public-key' | translate }}</mat-label> formControlName="serverPublicKey" #serverPublicKey
<textarea matInput type="text" rows="3" cols="1" formControlName="serverPublicKey" #serverPublicKey maxlength={{lenMaxServerPublicKey}} maxlength="{{lenMaxServerPublicKey}}"
matTooltip="{{'device-profile.lwm2m.server-public-key-tip' | translate}}" matTooltip="{{'device-profile.lwm2m.server-public-key-tip' | translate}}"
[required]="serverFormGroup.get('securityMode').value === securityConfigLwM2MType.RPK || ></textarea>
serverFormGroup.get('securityMode').value === securityConfigLwM2MType.X509"></textarea> <mat-hint align="end">{{serverPublicKey.value?.length || 0}}/{{lenMaxServerPublicKey}}</mat-hint>
<mat-hint align="end">{{serverPublicKey.value?.length || 0}}/{{lenMaxServerPublicKey}}</mat-hint> <mat-error *ngIf="serverFormGroup.get('serverPublicKey').hasError('required')">
<mat-error *ngIf="serverFormGroup.get('serverPublicKey').hasError('required')"> {{ 'device-profile.lwm2m.server-public-key' | translate }}
{{ 'device-profile.lwm2m.server-public-key' | translate }} <strong>{{ 'device-profile.lwm2m.required' | translate }}</strong>
<strong>{{ 'device-profile.lwm2m.required' | translate }}</strong> </mat-error>
</mat-error> <mat-error *ngIf="serverFormGroup.get('serverPublicKey').hasError('pattern') &&
<mat-error *ngIf="serverFormGroup.get('serverPublicKey').hasError('pattern') && serverFormGroup.get('securityMode').value === securityConfigLwM2MType.RPK">
serverFormGroup.get('securityMode').value === securityConfigLwM2MType.RPK"> {{ 'device-profile.lwm2m.client-key' | translate }}
{{ 'device-profile.lwm2m.client-key' | translate }} <strong>{{ 'device-profile.lwm2m.pattern_hex_dec_182' | translate }}</strong>
<strong>{{ 'device-profile.lwm2m.pattern_hex_dec_182' | translate }}</strong> </mat-error>
</mat-error> <mat-error *ngIf="serverFormGroup.get('serverPublicKey').hasError('pattern') &&
<mat-error *ngIf="serverFormGroup.get('serverPublicKey').hasError('pattern') && serverFormGroup.get('securityMode').value === securityConfigLwM2MType.X509">
serverFormGroup.get('securityMode').value === securityConfigLwM2MType.X509"> {{ 'device-profile.lwm2m.client-key' | translate }}
{{ 'device-profile.lwm2m.client-key' | translate }} <strong>{{ 'device-profile.lwm2m.pattern_hex_dec' | translate }}</strong>
<strong>{{ 'device-profile.lwm2m.pattern_hex_dec' | translate }}</strong> </mat-error>
</mat-error> </mat-form-field>
</mat-form-field>
</div>
</div> </div>
</div> </div>
</div> </div>

45
ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-device-config-server.component.ts

@ -43,7 +43,6 @@ import { DeviceProfileService } from '@core/http/device-profile.service';
@Component({ @Component({
selector: 'tb-profile-lwm2m-device-config-server', selector: 'tb-profile-lwm2m-device-config-server',
templateUrl: './lwm2m-device-config-server.component.html', templateUrl: './lwm2m-device-config-server.component.html',
styleUrls: [],
providers: [ providers: [
{ {
provide: NG_VALUE_ACCESSOR, provide: NG_VALUE_ACCESSOR,
@ -55,8 +54,8 @@ import { DeviceProfileService } from '@core/http/device-profile.service';
export class Lwm2mDeviceConfigServerComponent implements OnInit, ControlValueAccessor, Validators { export class Lwm2mDeviceConfigServerComponent implements OnInit, ControlValueAccessor, Validators {
valuePrev = null as any;
private requiredValue: boolean; private requiredValue: boolean;
valuePrev = null;
serverFormGroup: FormGroup; serverFormGroup: FormGroup;
securityConfigLwM2MType = SECURITY_CONFIG_MODE; securityConfigLwM2MType = SECURITY_CONFIG_MODE;
securityConfigLwM2MTypes = Object.keys(SECURITY_CONFIG_MODE); securityConfigLwM2MTypes = Object.keys(SECURITY_CONFIG_MODE);
@ -69,7 +68,7 @@ export class Lwm2mDeviceConfigServerComponent implements OnInit, ControlValueAcc
disabled: boolean; disabled: boolean;
@Input() @Input()
bootstrapServerIs: boolean bootstrapServerIs: boolean;
get required(): boolean { get required(): boolean {
return this.requiredValue; return this.requiredValue;
@ -107,7 +106,7 @@ export class Lwm2mDeviceConfigServerComponent implements OnInit, ControlValueAcc
} }
updateValueFields(serverData: ServerSecurityConfig): void { updateValueFields(serverData: ServerSecurityConfig): void {
serverData['bootstrapServerIs'] = this.bootstrapServerIs; serverData.bootstrapServerIs = this.bootstrapServerIs;
this.serverFormGroup.patchValue(serverData, {emitEvent: false}); this.serverFormGroup.patchValue(serverData, {emitEvent: false});
this.serverFormGroup.get('bootstrapServerIs').disable(); this.serverFormGroup.get('bootstrapServerIs').disable();
const securityMode = this.serverFormGroup.get('securityMode').value as SECURITY_CONFIG_MODE; const securityMode = this.serverFormGroup.get('securityMode').value as SECURITY_CONFIG_MODE;
@ -132,21 +131,22 @@ export class Lwm2mDeviceConfigServerComponent implements OnInit, ControlValueAcc
this.serverFormGroup.get('serverPublicKey').setValidators([Validators.required, Validators.pattern(KEY_PUBLIC_REGEXP_X509)]); this.serverFormGroup.get('serverPublicKey').setValidators([Validators.required, Validators.pattern(KEY_PUBLIC_REGEXP_X509)]);
break; break;
} }
this.checkValueWithNewValidate(); this.serverFormGroup.updateValueAndValidity();
// this.checkValueWithNewValidate();
} }
checkValueWithNewValidate(): void { // checkValueWithNewValidate(): void {
this.serverFormGroup.patchValue({ // this.serverFormGroup.patchValue({
host: this.serverFormGroup.get('host').value, // host: this.serverFormGroup.get('host').value,
port: this.serverFormGroup.get('port').value, // port: this.serverFormGroup.get('port').value,
bootstrapServerIs: this.serverFormGroup.get('bootstrapServerIs').value, // bootstrapServerIs: this.serverFormGroup.get('bootstrapServerIs').value,
serverPublicKey: this.serverFormGroup.get('serverPublicKey').value, // serverPublicKey: this.serverFormGroup.get('serverPublicKey').value,
clientHoldOffTime: this.serverFormGroup.get('clientHoldOffTime').value, // clientHoldOffTime: this.serverFormGroup.get('clientHoldOffTime').value,
serverId: this.serverFormGroup.get('serverId').value, // serverId: this.serverFormGroup.get('serverId').value,
bootstrapServerAccountTimeout: this.serverFormGroup.get('bootstrapServerAccountTimeout').value, // bootstrapServerAccountTimeout: this.serverFormGroup.get('bootstrapServerAccountTimeout').value,
}, // },
{emitEvent: true}); // {emitEvent: true});
} // }
writeValue(value: any): void { writeValue(value: any): void {
if (value) { if (value) {
@ -154,8 +154,7 @@ export class Lwm2mDeviceConfigServerComponent implements OnInit, ControlValueAcc
} }
} }
private propagateChange = (v: any) => { private propagateChange = (v: any) => {};
};
registerOnChange(fn: any): void { registerOnChange(fn: any): void {
this.propagateChange = fn; this.propagateChange = fn;
@ -164,8 +163,8 @@ export class Lwm2mDeviceConfigServerComponent implements OnInit, ControlValueAcc
private propagateChangeState(value: any): void { private propagateChangeState(value: any): void {
if (value !== undefined) { if (value !== undefined) {
if (this.valuePrev === null) { if (this.valuePrev === null) {
this.valuePrev = "init"; this.valuePrev = 'init';
} else if (this.valuePrev === "init") { } else if (this.valuePrev === 'init') {
this.valuePrev = value; this.valuePrev = value;
} else if (JSON.stringify(value) !== JSON.stringify(this.valuePrev)) { } else if (JSON.stringify(value) !== JSON.stringify(this.valuePrev)) {
this.valuePrev = value; this.valuePrev = value;
@ -192,7 +191,7 @@ export class Lwm2mDeviceConfigServerComponent implements OnInit, ControlValueAcc
} }
getServerGroup(): FormGroup { getServerGroup(): FormGroup {
const port = (this.bootstrapServerIs) ? DEFAULT_PORT_BOOTSTRAP_NO_SEC : DEFAULT_PORT_SERVER_NO_SEC; const port = this.bootstrapServerIs ? DEFAULT_PORT_BOOTSTRAP_NO_SEC : DEFAULT_PORT_SERVER_NO_SEC;
return this.fb.group({ return this.fb.group({
host: [this.window.location.hostname, this.required ? [Validators.required] : []], host: [this.window.location.hostname, this.required ? [Validators.required] : []],
port: [port, this.required ? [Validators.required] : []], port: [port, this.required ? [Validators.required] : []],
@ -202,7 +201,7 @@ export class Lwm2mDeviceConfigServerComponent implements OnInit, ControlValueAcc
clientHoldOffTime: [DEFAULT_CLIENT_HOLD_OFF_TIME, this.required ? [Validators.required] : []], clientHoldOffTime: [DEFAULT_CLIENT_HOLD_OFF_TIME, this.required ? [Validators.required] : []],
serverId: [DEFAULT_ID_SERVER, this.required ? [Validators.required] : []], serverId: [DEFAULT_ID_SERVER, this.required ? [Validators.required] : []],
bootstrapServerAccountTimeout: ['', this.required ? [Validators.required] : []], bootstrapServerAccountTimeout: ['', this.required ? [Validators.required] : []],
}) });
} }
getLwm2mBootstrapSecurityInfo(mode: string) { getLwm2mBootstrapSecurityInfo(mode: string) {

9
ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-device-profile-transport-configuration.component.html

@ -40,8 +40,7 @@
<mat-expansion-panel> <mat-expansion-panel>
<mat-expansion-panel-header> <mat-expansion-panel-header>
<mat-panel-title> <mat-panel-title>
<div <div class="tb-panel-title">{{ 'device-profile.lwm2m.servers' | translate | uppercase }}</div>
class="tb-panel-title">{{ 'device-profile.lwm2m.servers' | translate | uppercase }}</div>
</mat-panel-title> </mat-panel-title>
</mat-expansion-panel-header> </mat-expansion-panel-header>
<div fxLayout="column"> <div fxLayout="column">
@ -93,8 +92,7 @@
<mat-expansion-panel> <mat-expansion-panel>
<mat-expansion-panel-header> <mat-expansion-panel-header>
<mat-panel-title> <mat-panel-title>
<div <div class="tb-panel-title">{{ 'device-profile.lwm2m.bootstrap-server' | translate | uppercase }}</div>
class="tb-panel-title">{{ 'device-profile.lwm2m.bootstrap-server' | translate | uppercase }}</div>
</mat-panel-title> </mat-panel-title>
</mat-expansion-panel-header> </mat-expansion-panel-header>
<div class="mat-padding"> <div class="mat-padding">
@ -110,8 +108,7 @@
<mat-expansion-panel> <mat-expansion-panel>
<mat-expansion-panel-header> <mat-expansion-panel-header>
<mat-panel-title> <mat-panel-title>
<div <div class="tb-panel-title">{{ 'device-profile.lwm2m.lwm2m-server' | translate | uppercase }}</div>
class="tb-panel-title">{{ 'device-profile.lwm2m.lwm2m-server' | translate | uppercase }}</div>
</mat-panel-title> </mat-panel-title>
</mat-expansion-panel-header> </mat-expansion-panel-header>
<div class="mat-padding"> <div class="mat-padding">

269
ui-ngx/src/app/modules/home/components/profile/device/lwm2m/lwm2m-device-profile-transport-configuration.component.ts

@ -33,7 +33,7 @@ import {
OBSERVE, OBSERVE,
OBSERVE_ATTR, OBSERVE_ATTR,
TELEMETRY, TELEMETRY,
ObjectLwM2M, getDefaultProfileConfig, KEY_NAME, Instance ObjectLwM2M, getDefaultProfileConfig, KEY_NAME, Instance, ProfileConfigModels, ResourceLwM2M
} from "./profile-config.models"; } from "./profile-config.models";
import { DeviceProfileService } from "@core/http/device-profile.service"; import { DeviceProfileService } from "@core/http/device-profile.service";
import { deepClone, isUndefined } from "@core/utils"; import { deepClone, isUndefined } from "@core/utils";
@ -44,7 +44,6 @@ import { isNotNullOrUndefined } from 'codelyzer/util/isNotNullOrUndefined';
@Component({ @Component({
selector: 'tb-profile-lwm2m-device-transport-configuration', selector: 'tb-profile-lwm2m-device-transport-configuration',
templateUrl: './lwm2m-device-profile-transport-configuration.component.html', templateUrl: './lwm2m-device-profile-transport-configuration.component.html',
styleUrls: [],
providers: [{ providers: [{
provide: NG_VALUE_ACCESSOR, provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => Lwm2mDeviceProfileTransportConfigurationComponent), useExisting: forwardRef(() => Lwm2mDeviceProfileTransportConfigurationComponent),
@ -53,6 +52,10 @@ import { isNotNullOrUndefined } from 'codelyzer/util/isNotNullOrUndefined';
}) })
export class Lwm2mDeviceProfileTransportConfigurationComponent implements ControlValueAccessor, OnInit, Validators { export class Lwm2mDeviceProfileTransportConfigurationComponent implements ControlValueAccessor, OnInit, Validators {
private configurationValue: ProfileConfigModels;
private requiredValue: boolean;
private disabled = false;
lwm2mDeviceProfileTransportConfFormGroup: FormGroup; lwm2mDeviceProfileTransportConfFormGroup: FormGroup;
observeAttr = OBSERVE_ATTR as string; observeAttr = OBSERVE_ATTR as string;
observe = OBSERVE as string; observe = OBSERVE as string;
@ -62,9 +65,6 @@ export class Lwm2mDeviceProfileTransportConfigurationComponent implements Contro
bootstrapServers: string; bootstrapServers: string;
bootstrapServer: string; bootstrapServer: string;
lwm2mServer: string; lwm2mServer: string;
private configurationValue: {};
private requiredValue: boolean;
private disabled = false as boolean;
sortFunction = this.sortObjectKeyPathJson; sortFunction = this.sortObjectKeyPathJson;
get required(): boolean { get required(): boolean {
@ -76,8 +76,7 @@ export class Lwm2mDeviceProfileTransportConfigurationComponent implements Contro
this.requiredValue = coerceBooleanProperty(value); this.requiredValue = coerceBooleanProperty(value);
} }
private propagateChange = (v: any) => { private propagateChange = (v: any) => { };
};
constructor(private store: Store<AppState>, constructor(private store: Store<AppState>,
private fb: FormBuilder, private fb: FormBuilder,
@ -85,17 +84,17 @@ export class Lwm2mDeviceProfileTransportConfigurationComponent implements Contro
@Inject(WINDOW) private window: Window) { @Inject(WINDOW) private window: Window) {
this.lwm2mDeviceProfileTransportConfFormGroup = this.fb.group({ this.lwm2mDeviceProfileTransportConfFormGroup = this.fb.group({
objectIds: [{}, Validators.required], objectIds: [{}, Validators.required],
observeAttrTelemetry: [{'clientLwM2M': [] as ObjectLwM2M []}, Validators.required], observeAttrTelemetry: [{clientLwM2M: [] as ObjectLwM2M[]}, Validators.required],
shortId: [null, Validators.required], shortId: [null, Validators.required],
lifetime: [null, Validators.required], lifetime: [null, Validators.required],
defaultMinPeriod: [null, Validators.required], defaultMinPeriod: [null, Validators.required],
notifIfDisabled: [true, []], notifIfDisabled: [true, []],
binding: ["U", Validators.required], binding: ['U', Validators.required],
bootstrapServer: [null, Validators.required], bootstrapServer: [null, Validators.required],
lwm2mServer: [null, Validators.required], lwm2mServer: [null, Validators.required],
configurationJson: [null, Validators.required], configurationJson: [null, Validators.required],
}); });
this.lwm2mDeviceProfileTransportConfFormGroup.valueChanges.subscribe(value => { this.lwm2mDeviceProfileTransportConfFormGroup.valueChanges.subscribe(() => {
if (!this.disabled) { if (!this.disabled) {
this.updateModel(); this.updateModel();
} }
@ -122,7 +121,7 @@ export class Lwm2mDeviceProfileTransportConfigurationComponent implements Contro
} }
writeValue(value: any | null): void { writeValue(value: any | null): void {
value = (Object.keys(value).length == 0) ? getDefaultProfileConfig() : value; value = (Object.keys(value).length === 0) ? getDefaultProfileConfig() : value;
this.lwm2mDeviceProfileTransportConfFormGroup.patchValue({ this.lwm2mDeviceProfileTransportConfFormGroup.patchValue({
configurationJson: value configurationJson: value
}, },
@ -132,14 +131,14 @@ export class Lwm2mDeviceProfileTransportConfigurationComponent implements Contro
} }
private initWriteValue(): void { private initWriteValue(): void {
let modelValue = {"objectIds": null, "objectsList": []}; const modelValue = {objectIds: null, objectsList: []};
modelValue.objectIds = this.getObjectsFromJsonAllConfig(); modelValue.objectIds = this.getObjectsFromJsonAllConfig();
if (modelValue.objectIds !== null) { if (modelValue.objectIds !== null) {
this.deviceProfileService.getLwm2mObjects(modelValue.objectIds).subscribe( this.deviceProfileService.getLwm2mObjects(modelValue.objectIds).subscribe(
(objectsList) => { (objectsList) => {
modelValue.objectsList = objectsList; modelValue.objectsList = objectsList;
this.updateWriteValue(modelValue); this.updateWriteValue(modelValue);
} }
); );
} else { } else {
this.updateWriteValue(modelValue); this.updateWriteValue(modelValue);
@ -147,17 +146,17 @@ export class Lwm2mDeviceProfileTransportConfigurationComponent implements Contro
} }
private updateWriteValue(value: any): void { private updateWriteValue(value: any): void {
let objectsList = deepClone(value.objectsList); const objectsList = deepClone(value.objectsList);
this.lwm2mDeviceProfileTransportConfFormGroup.patchValue({ this.lwm2mDeviceProfileTransportConfFormGroup.patchValue({
objectIds: value, objectIds: value,
observeAttrTelemetry: {clientLwM2M: this.getObserveAttrTelemetryObjects(objectsList)}, observeAttrTelemetry: {clientLwM2M: this.getObserveAttrTelemetryObjects(objectsList)},
shortId: this.configurationValue['bootstrap'].servers.shortId, shortId: this.configurationValue.bootstrap.servers.shortId,
lifetime: this.configurationValue['bootstrap'].servers.lifetime, lifetime: this.configurationValue.bootstrap.servers.lifetime,
defaultMinPeriod: this.configurationValue['bootstrap'].servers.defaultMinPeriod, defaultMinPeriod: this.configurationValue.bootstrap.servers.defaultMinPeriod,
notifIfDisabled: this.configurationValue['bootstrap'].servers.notifIfDisabled, notifIfDisabled: this.configurationValue.bootstrap.servers.notifIfDisabled,
binding: this.configurationValue['bootstrap'].servers.binding, binding: this.configurationValue.bootstrap.servers.binding,
bootstrapServer: this.configurationValue['bootstrap'].bootstrapServer, bootstrapServer: this.configurationValue.bootstrap.bootstrapServer,
lwm2mServer: this.configurationValue['bootstrap'].lwm2mServer lwm2mServer: this.configurationValue.bootstrap.lwm2mServer
}, },
{emitEvent: false}); {emitEvent: false});
} }
@ -174,10 +173,10 @@ export class Lwm2mDeviceProfileTransportConfigurationComponent implements Contro
private updateObserveAttrTelemetryObjectFormGroup(objectsList: ObjectLwM2M[]) { private updateObserveAttrTelemetryObjectFormGroup(objectsList: ObjectLwM2M[]) {
this.lwm2mDeviceProfileTransportConfFormGroup.patchValue({ this.lwm2mDeviceProfileTransportConfFormGroup.patchValue({
observeAttrTelemetry: {clientLwM2M: this.getObserveAttrTelemetryObjects(objectsList)} observeAttrTelemetry: {clientLwM2M: this.getObserveAttrTelemetryObjects(objectsList)}
}, },
{emitEvent: false}); {emitEvent: false});
this.lwm2mDeviceProfileTransportConfFormGroup.get("observeAttrTelemetry").markAsPristine({ this.lwm2mDeviceProfileTransportConfFormGroup.get('observeAttrTelemetry').markAsPristine({
onlySelf: true onlySelf: true
}); });
} }
@ -188,9 +187,11 @@ export class Lwm2mDeviceProfileTransportConfigurationComponent implements Contro
} }
upDateValueToJsonTab_0(): void { upDateValueToJsonTab_0(): void {
if (!this.lwm2mDeviceProfileTransportConfFormGroup.get("observeAttrTelemetry").pristine) { if (!this.lwm2mDeviceProfileTransportConfFormGroup.get('observeAttrTelemetry').pristine) {
this.upDateObserveAttrTelemetryFromGroupToJson(this.lwm2mDeviceProfileTransportConfFormGroup.get("observeAttrTelemetry").value['clientLwM2M']); this.upDateObserveAttrTelemetryFromGroupToJson(
this.lwm2mDeviceProfileTransportConfFormGroup.get("observeAttrTelemetry").markAsPristine({ this.lwm2mDeviceProfileTransportConfFormGroup.get('observeAttrTelemetry').value.clientLwM2M
);
this.lwm2mDeviceProfileTransportConfFormGroup.get('observeAttrTelemetry').markAsPristine({
onlySelf: true onlySelf: true
}); });
this.upDateJsonAllConfig(); this.upDateJsonAllConfig();
@ -200,14 +201,14 @@ export class Lwm2mDeviceProfileTransportConfigurationComponent implements Contro
upDateValueToJsonTab_1(): void { upDateValueToJsonTab_1(): void {
this.upDateValueServersToJson(); this.upDateValueServersToJson();
if (!this.lwm2mDeviceProfileTransportConfFormGroup.get('bootstrapServer').pristine) { if (!this.lwm2mDeviceProfileTransportConfFormGroup.get('bootstrapServer').pristine) {
this.configurationValue['bootstrap'].bootstrapServer = this.lwm2mDeviceProfileTransportConfFormGroup.get('bootstrapServer').value; this.configurationValue.bootstrap.bootstrapServer = this.lwm2mDeviceProfileTransportConfFormGroup.get('bootstrapServer').value;
this.lwm2mDeviceProfileTransportConfFormGroup.get('bootstrapServer').markAsPristine({ this.lwm2mDeviceProfileTransportConfFormGroup.get('bootstrapServer').markAsPristine({
onlySelf: true onlySelf: true
}); });
this.upDateJsonAllConfig(); this.upDateJsonAllConfig();
} }
if (!this.lwm2mDeviceProfileTransportConfFormGroup.get('lwm2mServer').pristine) { if (!this.lwm2mDeviceProfileTransportConfFormGroup.get('lwm2mServer').pristine) {
this.configurationValue['bootstrap'].lwm2mServer = this.lwm2mDeviceProfileTransportConfFormGroup.get('lwm2mServer').value; this.configurationValue.bootstrap.lwm2mServer = this.lwm2mDeviceProfileTransportConfFormGroup.get('lwm2mServer').value;
this.lwm2mDeviceProfileTransportConfFormGroup.get('lwm2mServer').markAsPristine({ this.lwm2mDeviceProfileTransportConfFormGroup.get('lwm2mServer').markAsPristine({
onlySelf: true onlySelf: true
}); });
@ -216,36 +217,37 @@ export class Lwm2mDeviceProfileTransportConfigurationComponent implements Contro
} }
upDateValueServersToJson(): void { upDateValueServersToJson(): void {
const bootstrapServers = this.configurationValue.bootstrap.servers;
if (!this.lwm2mDeviceProfileTransportConfFormGroup.get('shortId').pristine) { if (!this.lwm2mDeviceProfileTransportConfFormGroup.get('shortId').pristine) {
this.configurationValue['bootstrap'].servers.shortId = this.lwm2mDeviceProfileTransportConfFormGroup.get('shortId').value; bootstrapServers.shortId = this.lwm2mDeviceProfileTransportConfFormGroup.get('shortId').value;
this.lwm2mDeviceProfileTransportConfFormGroup.get('shortId').markAsPristine({ this.lwm2mDeviceProfileTransportConfFormGroup.get('shortId').markAsPristine({
onlySelf: true onlySelf: true
}); });
this.upDateJsonAllConfig(); this.upDateJsonAllConfig();
} }
if (!this.lwm2mDeviceProfileTransportConfFormGroup.get('lifetime').pristine) { if (!this.lwm2mDeviceProfileTransportConfFormGroup.get('lifetime').pristine) {
this.configurationValue['bootstrap'].servers.lifetime = this.lwm2mDeviceProfileTransportConfFormGroup.get('lifetime').value; bootstrapServers.lifetime = this.lwm2mDeviceProfileTransportConfFormGroup.get('lifetime').value;
this.lwm2mDeviceProfileTransportConfFormGroup.get('lifetime').markAsPristine({ this.lwm2mDeviceProfileTransportConfFormGroup.get('lifetime').markAsPristine({
onlySelf: true onlySelf: true
}); });
this.upDateJsonAllConfig(); this.upDateJsonAllConfig();
} }
if (!this.lwm2mDeviceProfileTransportConfFormGroup.get('defaultMinPeriod').pristine) { if (!this.lwm2mDeviceProfileTransportConfFormGroup.get('defaultMinPeriod').pristine) {
this.configurationValue['bootstrap'].servers.defaultMinPeriod = this.lwm2mDeviceProfileTransportConfFormGroup.get('defaultMinPeriod').value; bootstrapServers.defaultMinPeriod = this.lwm2mDeviceProfileTransportConfFormGroup.get('defaultMinPeriod').value;
this.lwm2mDeviceProfileTransportConfFormGroup.get('defaultMinPeriod').markAsPristine({ this.lwm2mDeviceProfileTransportConfFormGroup.get('defaultMinPeriod').markAsPristine({
onlySelf: true onlySelf: true
}); });
this.upDateJsonAllConfig(); this.upDateJsonAllConfig();
} }
if (!this.lwm2mDeviceProfileTransportConfFormGroup.get('notifIfDisabled').pristine) { if (!this.lwm2mDeviceProfileTransportConfFormGroup.get('notifIfDisabled').pristine) {
this.configurationValue['bootstrap'].servers.notifIfDisabled = this.lwm2mDeviceProfileTransportConfFormGroup.get('notifIfDisabled').value; bootstrapServers.notifIfDisabled = this.lwm2mDeviceProfileTransportConfFormGroup.get('notifIfDisabled').value;
this.lwm2mDeviceProfileTransportConfFormGroup.get('notifIfDisabled').markAsPristine({ this.lwm2mDeviceProfileTransportConfFormGroup.get('notifIfDisabled').markAsPristine({
onlySelf: true onlySelf: true
}); });
this.upDateJsonAllConfig(); this.upDateJsonAllConfig();
} }
if (!this.lwm2mDeviceProfileTransportConfFormGroup.get('binding').pristine) { if (!this.lwm2mDeviceProfileTransportConfFormGroup.get('binding').pristine) {
this.configurationValue['bootstrap'].servers.binding = this.lwm2mDeviceProfileTransportConfFormGroup.get('binding').value; bootstrapServers.binding = this.lwm2mDeviceProfileTransportConfFormGroup.get('binding').value;
this.lwm2mDeviceProfileTransportConfFormGroup.get('binding').markAsPristine({ this.lwm2mDeviceProfileTransportConfFormGroup.get('binding').markAsPristine({
onlySelf: true onlySelf: true
}); });
@ -254,122 +256,130 @@ export class Lwm2mDeviceProfileTransportConfigurationComponent implements Contro
} }
getObserveAttrTelemetryObjects(listObject: ObjectLwM2M[]): ObjectLwM2M [] { getObserveAttrTelemetryObjects(listObject: ObjectLwM2M[]): ObjectLwM2M [] {
let clientObserveAttr = deepClone(listObject) as ObjectLwM2M[]; const clientObserveAttr = deepClone(listObject);
if (this.configurationValue[this.observeAttr]) { if (this.configurationValue[this.observeAttr]) {
let observeArray = this.configurationValue[this.observeAttr][this.observe] as Array<string>; const observeArray = this.configurationValue[this.observeAttr][this.observe] as Array<string>;
let attributeArray = this.configurationValue[this.observeAttr][this.attribute] as Array<string>; const attributeArray = this.configurationValue[this.observeAttr][this.attribute] as Array<string>;
let telemetryArray = this.configurationValue[this.observeAttr][this.telemetry] as Array<string>; const telemetryArray = this.configurationValue[this.observeAttr][this.telemetry] as Array<string>;
let keyNameJson = this.configurationValue[this.observeAttr][this.keyName] as JsonObject; const keyNameJson = this.configurationValue[this.observeAttr][this.keyName] as JsonObject;
if (this.includesInstancesNo(attributeArray, telemetryArray, clientObserveAttr)) { if (this.includesInstancesNo(attributeArray, telemetryArray)) {
this.addInstances(attributeArray, telemetryArray, clientObserveAttr); this.addInstances(attributeArray, telemetryArray, clientObserveAttr);
} }
if (observeArray) this.updateObserveAttrTelemetryObjects(observeArray, clientObserveAttr, "observe"); if (observeArray) {
if (attributeArray) this.updateObserveAttrTelemetryObjects(attributeArray, clientObserveAttr, "attribute"); this.updateObserveAttrTelemetryObjects(observeArray, clientObserveAttr, 'observe');
if (telemetryArray) this.updateObserveAttrTelemetryObjects(telemetryArray, clientObserveAttr, "telemetry"); }
if (keyNameJson) this.updateKeyNameObjects(deepClone(keyNameJson), clientObserveAttr); if (attributeArray) {
this.updateObserveAttrTelemetryObjects(attributeArray, clientObserveAttr, 'attribute');
}
if (telemetryArray) {
this.updateObserveAttrTelemetryObjects(telemetryArray, clientObserveAttr, 'telemetry');
}
if (keyNameJson) {
this.updateKeyNameObjects(deepClone(keyNameJson), clientObserveAttr);
}
} }
clientObserveAttr.forEach(obj => { clientObserveAttr.forEach(obj => {
obj.instances.sort((a,b) => a.id - b.id);; obj.instances.sort((a, b) => a.id - b.id);
}) });
return clientObserveAttr; return clientObserveAttr;
} }
includesInstancesNo(attributeArray: Array<string>, telemetryArray: Array<string>, clientObserveAttr: ObjectLwM2M[]): boolean { includesInstancesNo(attributeArray: Array<string>, telemetryArray: Array<string>): boolean {
let isIdIndex = (element) => !element.includes("/0/"); const isIdIndex = (element) => !element.includes('/0/');
return attributeArray.findIndex(isIdIndex) >= 0 || telemetryArray.findIndex(isIdIndex) >= 0 return attributeArray.findIndex(isIdIndex) >= 0 || telemetryArray.findIndex(isIdIndex) >= 0;
} }
addInstances(attributeArray: Array<string>, telemetryArray: Array<string>, clientObserveAttr: ObjectLwM2M[]): void { addInstances(attributeArray: Array<string>, telemetryArray: Array<string>, clientObserveAttr: ObjectLwM2M[]): void {
let attr = [] as Array<string>; const attr = [] as Array<string>;
[...attributeArray].filter(x => (!x.includes("/0/"))).forEach(x => { [...attributeArray].filter(x => (!x.includes('/0/'))).forEach(x => {
attr.push(this.convertPathToInstance(x)); attr.push(this.convertPathToInstance(x));
}); });
let telemetry = [] as Array<string>; const telemetry = [] as Array<string>;
[...telemetryArray].filter(x => (!x.includes("/0/"))).forEach(x => { [...telemetryArray].filter(x => (!x.includes('/0/'))).forEach(x => {
telemetry.push(this.convertPathToInstance(x)); telemetry.push(this.convertPathToInstance(x));
}); });
let instancesNoZero = new Set(attr.concat(telemetry).sort()); const instancesNoZero = new Set(attr.concat(telemetry).sort());
instancesNoZero.forEach(path => { instancesNoZero.forEach(path => {
let pathParameter = Array.from(path.split('/'), Number); const pathParameter = Array.from(path.split('/'), Number);
let objectLwM2M = clientObserveAttr.find(x => (x.id === pathParameter[0])); const objectLwM2M = clientObserveAttr.find(x => (x.id === pathParameter[0]));
if (objectLwM2M) { if (objectLwM2M) {
let instance = deepClone(objectLwM2M.instances[0]) as Instance; const instance = deepClone(objectLwM2M.instances[0]) as Instance;
instance.id = pathParameter[1]; instance.id = pathParameter[1];
objectLwM2M.instances.push(instance); objectLwM2M.instances.push(instance);
} }
}) });
} }
convertPathToInstance(path: string): string { convertPathToInstance(path: string): string {
let newX = Array.from(path.substring(1).split('/'), Number); const newX = Array.from(path.substring(1).split('/'), Number);
return [newX[0], newX[1]].join("/"); return [newX[0], newX[1]].join('/');
} }
updateObserveAttrTelemetryObjects(isParameter: Array<string>, clientObserveAttr: ObjectLwM2M[], nameParameter: string): void { updateObserveAttrTelemetryObjects(isParameter: Array<string>, clientObserveAttr: ObjectLwM2M[], nameParameter: string): void {
isParameter.forEach(attr => { isParameter.forEach(attr => {
let idKeys = Array.from(attr.substring(1).split('/'), Number); const idKeys = Array.from(attr.substring(1).split('/'), Number);
clientObserveAttr clientObserveAttr
.forEach(e => { .forEach(e => {
if (e.id == idKeys[0]) { if (e.id === idKeys[0]) {
let instance = e.instances.find(e => e.id == idKeys[1]); const instance = e.instances.find(itrInstance => itrInstance.id === idKeys[1]);
if (isNotNullOrUndefined(instance)) { if (isNotNullOrUndefined(instance)) {
instance.resources.find(e => e.id == idKeys[2])[nameParameter] = true; instance.resources.find(resource => resource.id === idKeys[2])[nameParameter] = true;
}
} }
} });
});
}); });
} }
updateKeyNameObjects(nameJson: JsonObject, clientObserveAttr: ObjectLwM2M[]): void { updateKeyNameObjects(nameJson: JsonObject, clientObserveAttr: ObjectLwM2M[]): void {
let keyName = JSON.parse(JSON.stringify(nameJson)); const keyName = JSON.parse(JSON.stringify(nameJson));
Object.keys(keyName).forEach(function (key) { Object.keys(keyName).forEach(key => {
let idKeys = Array.from(key.substring(1).split('/'), Number); const idKeys = Array.from(key.substring(1).split('/'), Number);
clientObserveAttr clientObserveAttr
.forEach(e => { .forEach(e => {
if (e.id == idKeys[0]) { if (e.id === idKeys[0]) {
e.instances.find(e => e.id == idKeys[1]).resources e.instances
.find(e => e.id == idKeys[2]).keyName = keyName[key]; .find(instance => instance.id === idKeys[1]).resources
} .find(resource => resource.id === idKeys[2]).keyName = keyName[key];
}); }
});
}); });
} }
upDateObserveAttrTelemetryFromGroupToJson(val: ObjectLwM2M []): void { upDateObserveAttrTelemetryFromGroupToJson(val: ObjectLwM2M[]): void {
let observeArray = [] as Array<string>; const observeArray: Array<string> = [];
let attributeArray = [] as Array<string>; const attributeArray: Array<string> = [];
let telemetryArray = [] as Array<string>; const telemetryArray: Array<string> = [];
let observeJson = JSON.parse(JSON.stringify(val)); const observeJson: ObjectLwM2M[] = JSON.parse(JSON.stringify(val));
let pathObj; let pathObj;
let pathInst; let pathInst;
let pathRes let pathRes;
observeJson.forEach(obj => { observeJson.forEach(obj => {
Object.entries(obj).forEach(([key, value]) => { Object.entries(obj).forEach(([key, value]) => {
if (key === 'id') { if (key === 'id') {
pathObj = value; pathObj = value;
} }
if (key === 'instances') { if (key === 'instances') {
let instancesJson = JSON.parse(JSON.stringify(value)) as []; const instancesJson = JSON.parse(JSON.stringify(value)) as Instance[];
if (instancesJson.length > 0) { if (instancesJson.length > 0) {
instancesJson.forEach(instance => { instancesJson.forEach(instance => {
Object.entries(instance).forEach(([key, value]) => { Object.entries(instance).forEach(([instanceKey, instanceValue]) => {
if (key === 'id') { if (instanceKey === 'id') {
pathInst = value; pathInst = instanceValue;
} }
if (key === 'resources') { if (instanceKey === 'resources') {
let resourcesJson = JSON.parse(JSON.stringify(value)) as []; const resourcesJson = JSON.parse(JSON.stringify(instanceValue)) as ResourceLwM2M[];
if (resourcesJson.length > 0) { if (resourcesJson.length > 0) {
resourcesJson.forEach(res => { resourcesJson.forEach(res => {
Object.entries(res).forEach(([key, value]) => { Object.entries(res).forEach(([resourceKey, resourceValue]) => {
if (key === 'id') { if (resourceKey === 'id') {
// pathRes = value // pathRes = resourceValue
pathRes = '/' + pathObj + '/' + pathInst + '/' + value; pathRes = '/' + pathObj + '/' + pathInst + '/' + resourceValue;
} else if (key === 'observe' && value) { } else if (resourceKey === 'observe' && resourceValue) {
observeArray.push(pathRes) observeArray.push(pathRes);
} else if (key === 'attribute' && value) { } else if (resourceKey === 'attribute' && resourceValue) {
attributeArray.push(pathRes) attributeArray.push(pathRes);
} else if (key === 'telemetry' && value) { } else if (resourceKey === 'telemetry' && resourceValue) {
telemetryArray.push(pathRes) telemetryArray.push(pathRes);
} }
}); });
}); });
@ -396,19 +406,19 @@ export class Lwm2mDeviceProfileTransportConfigurationComponent implements Contro
} }
sortObjectKeyPathJson(key, value) { sortObjectKeyPathJson(key, value) {
if (key == "keyName") { if (key === 'keyName') {
return Object.keys(value).sort((a, b) => { return Object.keys(value).sort((a, b) => {
let aLC = Array.from(a.substring(1).split('/'), Number); const aLC = Array.from(a.substring(1).split('/'), Number);
let bLC = Array.from(b.substring(1).split('/'), Number); const bLC = Array.from(b.substring(1).split('/'), Number);
return aLC[0] == bLC[0] ? aLC[1] - bLC[1] : aLC[0] - bLC[0]; return aLC[0] === bLC[0] ? aLC[1] - bLC[1] : aLC[0] - bLC[0];
}).reduce((r, k) => (r[k] = value[k], r), {}); }).reduce((r, k) => r[k] = value[k], {});
} else { } else {
return value return value;
} }
} }
updateKeyName(): void { updateKeyName(): void {
let paths = new Set<string>(); const paths = new Set<string>();
if (this.configurationValue[this.observeAttr][this.attribute]) { if (this.configurationValue[this.observeAttr][this.attribute]) {
this.configurationValue[this.observeAttr][this.attribute].forEach(path => { this.configurationValue[this.observeAttr][this.attribute].forEach(path => {
paths.add(path); paths.add(path);
@ -419,31 +429,32 @@ export class Lwm2mDeviceProfileTransportConfigurationComponent implements Contro
paths.add(path); paths.add(path);
}); });
} }
let keyNameNew = {}; const keyNameNew = {};
paths.forEach(path => { paths.forEach(path => {
let pathParameter = this.findIndexsForIds(path); const pathParameter = this.findIndexsForIds(path);
if (pathParameter.length === 3) { if (pathParameter.length === 3) {
let value = this.lwm2mDeviceProfileTransportConfFormGroup.get("observeAttrTelemetry").value['clientLwM2M'][pathParameter[0]].instances[pathParameter[1]].resources[pathParameter[2]][this.keyName]; keyNameNew[path] = this.lwm2mDeviceProfileTransportConfFormGroup.get('observeAttrTelemetry').value
keyNameNew[path] = value; .clientLwM2M[pathParameter[0]].instances[pathParameter[1]].resources[pathParameter[2]][this.keyName];
} }
}); });
this.configurationValue[this.observeAttr][this.keyName] = this.sortObjectKeyPathJson("keyName", keyNameNew); this.configurationValue[this.observeAttr][this.keyName] = this.sortObjectKeyPathJson('keyName', keyNameNew);
} }
findIndexsForIds(path: string): number[] { findIndexsForIds(path: string): number[] {
let pathParameter = Array.from(path.substring(1).split('/'), Number); const pathParameter = Array.from(path.substring(1).split('/'), Number);
let pathParameterIndexes = [] as number[]; const pathParameterIndexes: number[] = [];
let objectsOld = deepClone(this.lwm2mDeviceProfileTransportConfFormGroup.get("observeAttrTelemetry").value.clientLwM2M) as ObjectLwM2M[]; const objectsOld = deepClone(
this.lwm2mDeviceProfileTransportConfFormGroup.get('observeAttrTelemetry').value.clientLwM2M) as ObjectLwM2M[];
let isIdIndex = (element) => element.id === pathParameter[0]; let isIdIndex = (element) => element.id === pathParameter[0];
let objIndex = objectsOld.findIndex(isIdIndex); const objIndex = objectsOld.findIndex(isIdIndex);
if (objIndex >= 0) { if (objIndex >= 0) {
pathParameterIndexes.push(objIndex); pathParameterIndexes.push(objIndex);
isIdIndex = (element) => element.id === pathParameter[1]; isIdIndex = (element) => element.id === pathParameter[1];
let instIndex = objectsOld[objIndex].instances.findIndex(isIdIndex); const instIndex = objectsOld[objIndex].instances.findIndex(isIdIndex);
if (instIndex >= 0) { if (instIndex >= 0) {
pathParameterIndexes.push(instIndex); pathParameterIndexes.push(instIndex);
isIdIndex = (element) => element.id === pathParameter[2]; isIdIndex = (element) => element.id === pathParameter[2];
let resIndex = objectsOld[objIndex].instances[instIndex].resources.findIndex(isIdIndex); const resIndex = objectsOld[objIndex].instances[instIndex].resources.findIndex(isIdIndex);
if (resIndex >= 0) { if (resIndex >= 0) {
pathParameterIndexes.push(resIndex); pathParameterIndexes.push(resIndex);
} }
@ -453,7 +464,7 @@ export class Lwm2mDeviceProfileTransportConfigurationComponent implements Contro
} }
getObjectsFromJsonAllConfig(): number [] { getObjectsFromJsonAllConfig(): number [] {
let objectsIds = new Set<number>(); const objectsIds = new Set<number>();
if (this.configurationValue[this.observeAttr]) { if (this.configurationValue[this.observeAttr]) {
if (this.configurationValue[this.observeAttr][this.observe]) { if (this.configurationValue[this.observeAttr][this.observe]) {
this.configurationValue[this.observeAttr][this.observe].forEach(obj => { this.configurationValue[this.observeAttr][this.observe].forEach(obj => {
@ -488,9 +499,9 @@ export class Lwm2mDeviceProfileTransportConfigurationComponent implements Contro
} }
removeObjectsList(value: ObjectLwM2M): void { removeObjectsList(value: ObjectLwM2M): void {
let objectsOld = deepClone(this.lwm2mDeviceProfileTransportConfFormGroup.get("observeAttrTelemetry").value.clientLwM2M); const objectsOld = deepClone(this.lwm2mDeviceProfileTransportConfFormGroup.get('observeAttrTelemetry').value.clientLwM2M);
const isIdIndex = (element) => element.id === value.id; const isIdIndex = (element) => element.id === value.id;
let index = objectsOld.findIndex(isIdIndex); const index = objectsOld.findIndex(isIdIndex);
if (index >= 0) { if (index >= 0) {
objectsOld.splice(index, 1); objectsOld.splice(index, 1);
} }
@ -504,7 +515,7 @@ export class Lwm2mDeviceProfileTransportConfigurationComponent implements Contro
} }
removeObserveAttrTelemetryFromJson(observeAttrTel: string, id: number): void { removeObserveAttrTelemetryFromJson(observeAttrTel: string, id: number): void {
let isIdIndex = (element) => Array.from(element.substring(1).split('/'), Number)[0] === id; const isIdIndex = (element) => Array.from(element.substring(1).split('/'), Number)[0] === id;
let index = this.configurationValue[this.observeAttr][observeAttrTel].findIndex(isIdIndex); let index = this.configurationValue[this.observeAttr][observeAttrTel].findIndex(isIdIndex);
while (index >= 0) { while (index >= 0) {
this.configurationValue[this.observeAttr][observeAttrTel].splice(index, 1); this.configurationValue[this.observeAttr][observeAttrTel].splice(index, 1);
@ -513,9 +524,9 @@ export class Lwm2mDeviceProfileTransportConfigurationComponent implements Contro
} }
removeKeyNameFromJson(id: number): void { removeKeyNameFromJson(id: number): void {
let keyNmaeJson = this.configurationValue[this.observeAttr][this.keyName]; const keyNmaeJson = this.configurationValue[this.observeAttr][this.keyName];
Object.keys(keyNmaeJson).forEach(function (key) { Object.keys(keyNmaeJson).forEach(key => {
let idKey = Array.from(key.substring(1).split('/'), Number)[0]; const idKey = Array.from(key.substring(1).split('/'), Number)[0];
if (idKey === id) { if (idKey === id) {
delete keyNmaeJson[key]; delete keyNmaeJson[key];
} }

1
ui-ngx/src/app/modules/home/pages/device/lwm2m/security-config.models.ts

@ -33,7 +33,6 @@ export const KEY_PUBLIC_REGEXP_X509 = /^[0-9a-fA-F]{0,3000}$/;
export interface DeviceCredentialsDialogLwm2mData { export interface DeviceCredentialsDialogLwm2mData {
jsonAllConfig?: SecurityConfigModels; jsonAllConfig?: SecurityConfigModels;
endPoint?: string; endPoint?: string;
isNew?: boolean;
} }
export enum SECURITY_CONFIG_MODE { export enum SECURITY_CONFIG_MODE {

Loading…
Cancel
Save